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.

GPU particles the same on every run: bevy_hanabi vendored with two raea: changes (closes #52)

shinyobjectz65a687182f6b
diff --git a/Cargo.lock b/Cargo.lock
index cadb47f3..b2df9b6e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2593,7 +2593,6 @@ dependencies = [
[[package]]
name = "bevy_hanabi"
version = "0.20.0-dev"
-source = "git+https://github.com/djeedai/bevy_hanabi?rev=77630ff1eed8b104f34e91d23e9440428dc5ab01#77630ff1eed8b104f34e91d23e9440428dc5ab01"
dependencies = [
"anyhow",
"bevy",
diff --git a/Cargo.toml b/Cargo.toml
index 6866a4c8..dec6988a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -317,3 +317,9 @@ firewheel-nodes = { path = "vendor/firewheel-nodes" }
# with Rune and Blitz in one build (raea-rune-slots) doesn't compile without it (changes marked "raea:"). Back to
# upstream once Rune has it.
rune-taffy = { path = "vendor/rune-taffy" }
+
+[patch."https://github.com/djeedai/bevy_hanabi"]
+# bevy_hanabi at engine/bevy-plugins' rev with frame-pure particles: a new particle seeded by its spawn index, not the
+# slot it recycles, and blended effects drawn back to front (changes marked "raea:", raea #52). Only the plugin build
+# compiles it. Back to upstream once hanabi has a deterministic mode.
+bevy_hanabi = { path = "vendor/bevy_hanabi" }
diff --git a/NOTICE b/NOTICE
index 7f1276fb..04ef688e 100644
--- a/NOTICE
+++ b/NOTICE
@@ -92,7 +92,6 @@ LICENSES/<crate>-<version>/.
bevy_flipbook 0.1.0: MIT
bevy_ghx_grid 0.10.0: MIT OR Apache-2.0
bevy_ghx_proc_gen 0.10.0: MIT OR Apache-2.0
- bevy_hanabi 0.20.0-dev: MIT OR Apache-2.0
bevy_heavy 0.6.0: MIT OR Apache-2.0
bevy_http_client 0.12.0: MIT OR Apache-2.0
bevy_hui 0.8.0: MIT OR Apache-2.0
diff --git a/bench/hanabi-repeat/check.sh b/bench/hanabi-repeat/check.sh
new file mode 100755
index 00000000..ed1c961e
--- /dev/null
+++ b/bench/hanabi-repeat/check.sh
@@ -0,0 +1,23 @@
+#!/bin/bash
+# #52: GPU particles rendered again give the same frames. sdk/raea/bench/bevy-plugins/hanabi.tsx (two seeded fountains,
+# one opaque and one alpha-blended) is rendered RUNS times (4), all 120 frames to hashes, and every run must match the
+# first. Before vendor/bevy_hanabi, its draw list and its recycled slots were taken with GPU atomics, in an order that
+# changed from run to run: the blended fountain differed from frame 7 or so (draw order), and once particles died both
+# could (a new particle was seeded by the slot it took). Needs the plugin build.
+# bench/hanabi-repeat/check.sh (RAEA_PLUGIN_BIN: the plugin build, default sdk/raea/bench/bevy-plugins/motion.sh;
+# RUNS: how many runs)
+cd "$(dirname "$0")/../.." || exit 2
+BIN=${RAEA_PLUGIN_BIN:-$PWD/sdk/raea/bench/bevy-plugins/motion.sh}
+RUNS=${RUNS:-4}
+export RAEA_SIGN=0 RAEA_MARK=0 RAEA_EXPORT_CACHE=0 RAEA_3D=program
+OUT=$(mktemp -d "${TMPDIR:-/tmp}/raea-hanabi-repeat.XXXXXX")
+trap 'rm -rf "$OUT"' EXIT
+status=0
+for i in $(seq 1 "$RUNS"); do
+ "$BIN" render sdk/raea/bench/bevy-plugins/hanabi.tsx -o "$OUT/$i.txt" > "$OUT/$i.log" 2>&1 || { echo "FAIL: run $i failed"; tail -5 "$OUT/$i.log"; exit 1; }
+ [ "$i" = 1 ] && continue
+ d=$(diff "$OUT/1.txt" "$OUT/$i.txt" | grep '^<' | cut -d' ' -f2 | head -5 | tr '\n' ' ')
+ [ -z "$d" ] || { echo "FAIL: run $i differs from run 1 at frames ${d}($(diff "$OUT/1.txt" "$OUT/$i.txt" | grep -c '^<') of $(wc -l < "$OUT/1.txt"))"; status=1; }
+done
+[ $status = 0 ] && echo "PASS: $RUNS runs of hanabi, every frame the same"
+exit $status
diff --git a/engine/bevy-plugins/src/hanabi.rs b/engine/bevy-plugins/src/hanabi.rs
index 9b8265a0..a00a9914 100644
--- a/engine/bevy-plugins/src/hanabi.rs
+++ b/engine/bevy-plugins/src/hanabi.rs
@@ -1,8 +1,9 @@
//! bevy_hanabi (GPU particles). What had to be written by hand: an effect is an EffectAsset (a graph of modifiers and
//! expressions held behind a Handle), which a row can't carry, so `Particles` is a reflected component of ours that
//! builds a fountain effect from plain numbers when it's added; hanabi's CPU random source is seeded (it seeds itself
-//! from the OS); its per-update re-seed is held to the frame steps; and WinitPlugin, which hanabi's `x11` feature
-//! switches on, is turned off.
+//! from the OS); its per-update re-seed is held to the frame steps; the first 3D camera is hanabi's main camera, which
+//! vendor/bevy_hanabi sorts blended particles by (far first, so a frame is the same on every run: raea #52); and
+//! WinitPlugin, which hanabi's `x11` feature switches on, is turned off.
use bevy::app::PluginGroupBuilder;
use bevy::prelude::*;
@@ -50,7 +51,17 @@ pub(crate) fn install(app: &mut App) {
// hanabi seeds its CPU random source from the OS at build: a fixed one instead
app.insert_resource(bevy_hanabi::Random(rand_pcg::Pcg32::new(0xcafe_f00d_d15e_a5e5, 0xa02b_dbf7_bb3c_0a7)));
app.register_type::<Particles>();
- app.add_systems(Update, build_particles);
+ app.add_systems(Update, (build_particles, main_camera));
+}
+
+/// hanabi's camera features (vendor/bevy_hanabi's blended sort among them) read the one camera with HanabiMainCamera:
+/// the first 3D camera, unless the scene tagged one.
+fn main_camera(mut commands: Commands, cams: Query<Entity, With<Camera3d>>, main: Query<(), With<HanabiMainCamera>>) {
+ if main.is_empty()
+ && let Some(cam) = cams.iter().min()
+ {
+ commands.entity(cam).insert(HanabiMainCamera);
+ }
}
/// hanabi's `x11` feature switches bevy_winit on; raea-render drives its own updates and has no window.
diff --git a/vendor/bevy_hanabi/Cargo.toml b/vendor/bevy_hanabi/Cargo.toml
new file mode 100644
index 00000000..73bc6fc6
--- /dev/null
+++ b/vendor/bevy_hanabi/Cargo.toml
@@ -0,0 +1,91 @@
+# raea: bevy_hanabi from git (djeedai/bevy_hanabi@77630ff1eed8b104f34e91d23e9440428dc5ab01), its src/ byte for byte but for
+# the changes marked "raea:" (frame-pure particles, raea #52). Cargo.toml.orig is upstream's manifest; this one drops its
+# examples, GPU tests, dev-dependencies and [workspace], whose files aren't carried.
+[package]
+name = "bevy_hanabi"
+version = "0.20.0-dev"
+authors = ["Jerome Humbert <[email protected]>"]
+edition = "2021"
+rust-version = "1.97.1"
+description = "Hanabi GPU particle system for the Bevy game engine"
+repository = "https://github.com/djeedai/bevy_hanabi"
+homepage = "https://github.com/djeedai/bevy_hanabi"
+documentation = "https://docs.rs/bevy_hanabi"
+keywords = ["bevy", "particle-system", "particles", "vfx"]
+license = "MIT OR Apache-2.0"
+readme = "README.md"
+exclude = [
+ "docs/*.svg",
+ "docs/*.png",
+ "examples/*.gif",
+ "examples/*.png",
+ "examples/wasm/*",
+ ".github",
+ "release.md",
+ "build_examples_wasm.bat",
+ "build_examples_wasm.sh",
+ "run_examples.bat",
+ "run_examples.sh",
+ "deny.toml",
+ "rustfmt.toml.nightly",
+]
+autoexamples = false
+
+[features]
+default = ["2d", "3d", "gpu_tests"]
+
+# Enable support for rendering through a 2D camera (Camera2d).
+# You need to activate either the 2d or 3d feature at least (or both).
+2d = []
+
+# Enable support for rendering through a 3D camera (Camera3d).
+# You need to activate either the 2d or 3d feature at least (or both).
+3d = []
+
+# Enable tracing annotations. This is disabled by default for performance.
+trace = []
+
+# Special feature to enable GPU-based tests, which otherwise fail
+# on a CI machine without a graphic adapter or without proper drivers.
+# This is a testing-only feature, which has no effect on the build.
+gpu_tests = []
+
+[dependencies]
+bytemuck = { version = "1.5", features = ["derive", "must_cast"] }
+fixedbitset = "0.5"
+rand = "0.10"
+rand_pcg = "0.10"
+serde = { version = "1.0", features = ["derive"] }
+anyhow = "1.0"
+ron = "0.12"
+bitflags = "2.3"
+thiserror = "2"
+# Same versions as Bevy 0.20 (bevy_render)
+wgpu = { version = "30", default-features = false, features = [
+ "wgsl",
+ "dx12",
+ "metal",
+ "vulkan",
+ "fragile-send-sync-non-atomic-wasm",
+] }
+
+# getrandom requires both 'wasm_js' as a feature AND as a RUSTFLAGS to work on wasm
+[target.'cfg(target_arch = "wasm32")'.dependencies]
+getrandom = { version = "0.4", default-features = false, features = [
+ "wasm_js",
+] }
+
+[dependencies.bevy]
+version = "0.20"
+default-features = false
+features = [
+ "bevy_core_pipeline",
+ "bevy_render",
+ "bevy_asset",
+ "bevy_log",
+ "x11",
+]
+
+[package.metadata.docs.rs]
+all-features = true
+
diff --git a/vendor/bevy_hanabi/Cargo.toml.orig b/vendor/bevy_hanabi/Cargo.toml.orig
new file mode 100644
index 00000000..dd9102f1
--- /dev/null
+++ b/vendor/bevy_hanabi/Cargo.toml.orig
@@ -0,0 +1,196 @@
+[package]
+name = "bevy_hanabi"
+version = "0.20.0-dev"
+authors = ["Jerome Humbert <[email protected]>"]
+edition = "2021"
+rust-version = "1.97.1"
+description = "Hanabi GPU particle system for the Bevy game engine"
+repository = "https://github.com/djeedai/bevy_hanabi"
+homepage = "https://github.com/djeedai/bevy_hanabi"
+documentation = "https://docs.rs/bevy_hanabi"
+keywords = ["bevy", "particle-system", "particles", "vfx"]
+license = "MIT OR Apache-2.0"
+readme = "README.md"
+exclude = [
+ "docs/*.svg",
+ "docs/*.png",
+ "examples/*.gif",
+ "examples/*.png",
+ "examples/wasm/*",
+ ".github",
+ "release.md",
+ "build_examples_wasm.bat",
+ "build_examples_wasm.sh",
+ "run_examples.bat",
+ "run_examples.sh",
+ "deny.toml",
+ "rustfmt.toml.nightly",
+]
+autoexamples = false
+
+[features]
+default = ["2d", "3d", "gpu_tests"]
+
+# Enable support for rendering through a 2D camera (Camera2d).
+# You need to activate either the 2d or 3d feature at least (or both).
+2d = []
+
+# Enable support for rendering through a 3D camera (Camera3d).
+# You need to activate either the 2d or 3d feature at least (or both).
+3d = []
+
+# Enable tracing annotations. This is disabled by default for performance.
+trace = []
+
+# Special feature to enable GPU-based tests, which otherwise fail
+# on a CI machine without a graphic adapter or without proper drivers.
+# This is a testing-only feature, which has no effect on the build.
+gpu_tests = []
+
+[dependencies]
+bytemuck = { version = "1.5", features = ["derive", "must_cast"] }
+fixedbitset = "0.5"
+rand = "0.10"
+rand_pcg = "0.10"
+serde = { version = "1.0", features = ["derive"] }
+anyhow = "1.0"
+ron = "0.12"
+bitflags = "2.3"
+thiserror = "2"
+# Same versions as Bevy 0.20 (bevy_render)
+wgpu = { version = "30", default-features = false, features = [
+ "wgsl",
+ "dx12",
+ "metal",
+ "vulkan",
+ "fragile-send-sync-non-atomic-wasm",
+] }
+
+# getrandom requires both 'wasm_js' as a feature AND as a RUSTFLAGS to work on wasm
+[target.'cfg(target_arch = "wasm32")'.dependencies]
+getrandom = { version = "0.4", default-features = false, features = [
+ "wasm_js",
+] }
+
+[dependencies.bevy]
+version = "0.20"
+default-features = false
+features = [
+ "bevy_core_pipeline",
+ "bevy_render",
+ "bevy_asset",
+ "bevy_log",
+ "x11",
+]
+
+[package.metadata.docs.rs]
+all-features = true
+
+[dev-dependencies]
+naga = { version = "30", features = ["wgsl-in"] }
+wesl = { version = "0.6", features = ["naga-ext"] }
+# Enable all features by default in examples to make it easier to run them and to use
+# extra features like text rendering or gizmos, which are example-specific.
+bevy = { version = "0.20", default-features = true }
+
+# For procedural texture generation in examples
+noise = "0.9"
+
+futures = "0.3"
+
+[[example]]
+name = "firework"
+
+[[example]]
+name = "portal"
+
+[[example]]
+name = "expr"
+
+[[example]]
+name = "spawn"
+
+[[example]]
+name = "multicam"
+
+[[example]]
+name = "visibility"
+
+[[example]]
+name = "random"
+
+[[example]]
+name = "spawn_on_command"
+
+[[example]]
+name = "activate"
+
+[[example]]
+name = "force_field"
+
+[[example]]
+name = "lifetime"
+
+[[example]]
+name = "init"
+
+[[example]]
+name = "instancing"
+
+[[example]]
+name = "gradient"
+
+[[example]]
+name = "circle"
+
+[[example]]
+name = "billboard"
+
+[[example]]
+name = "2d"
+
+[[example]]
+name = "worms"
+
+[[example]]
+name = "ribbon"
+
+[[example]]
+name = "ordering"
+
+[[example]]
+name = "puffs"
+
+[[example]]
+name = "lightning"
+
+[[example]]
+name = "lut"
+
+[[test]]
+name = "empty_effect"
+path = "gpu_tests/empty_effect.rs"
+harness = false
+required-features = ["bevy/bevy_winit", "bevy/bevy_window"]
+
+[[test]]
+name = "single_particle"
+path = "gpu_tests/single_particle.rs"
+harness = false
+required-features = ["bevy/bevy_winit", "bevy/bevy_window"]
+
+[[test]]
+name = "properties"
+path = "gpu_tests/properties.rs"
+harness = false
+required-features = ["bevy/bevy_winit", "bevy/bevy_window"]
+
+[[test]]
+name = "batching_instancing"
+path = "gpu_tests/batching_instancing.rs"
+harness = false
+required-features = ["bevy/bevy_winit", "bevy/bevy_window"]
+
+[workspace]
+resolver = "2"
+members = ["."]
diff --git a/LICENSES/bevy_hanabi-0.20.0-dev/LICENSE-APACHE2 b/vendor/bevy_hanabi/LICENSE-APACHE2
similarity index 100%
rename from LICENSES/bevy_hanabi-0.20.0-dev/LICENSE-APACHE2
rename to vendor/bevy_hanabi/LICENSE-APACHE2
diff --git a/LICENSES/bevy_hanabi-0.20.0-dev/LICENSE-MIT b/vendor/bevy_hanabi/LICENSE-MIT
similarity index 100%
rename from LICENSES/bevy_hanabi-0.20.0-dev/LICENSE-MIT
rename to vendor/bevy_hanabi/LICENSE-MIT
diff --git a/vendor/bevy_hanabi/README.md b/vendor/bevy_hanabi/README.md
new file mode 100644
index 00000000..9afcf584
--- /dev/null
+++ b/vendor/bevy_hanabi/README.md
@@ -0,0 +1,256 @@
+# πŸŽ† Bevy Hanabi
+
+[![License: MIT or Apache 2.0](https://img.shields.io/badge/License-MIT%20or%20Apache2-blue.svg)](./LICENSE)
+[![Doc](https://docs.rs/bevy_hanabi/badge.svg)](https://docs.rs/bevy_hanabi)
+[![Crate](https://img.shields.io/crates/v/bevy_hanabi.svg)](https://crates.io/crates/bevy_hanabi)
+[![Build Status](https://github.com/djeedai/bevy_hanabi/actions/workflows/ci.yaml/badge.svg)](https://github.com/djeedai/bevy_hanabi/actions/workflows/ci.yaml)
+[![Coverage Status](https://coveralls.io/repos/github/djeedai/bevy_hanabi/badge.svg?branch=main)](https://coveralls.io/github/djeedai/bevy_hanabi?branch=main)
+[![Bevy tracking](https://img.shields.io/badge/Bevy%20tracking-v0.20-lightblue)](https://github.com/bevyengine/bevy/blob/main/docs/plugins_guidelines.md#main-branch-tracking)
+
+πŸŽ† Hanabi β€” a GPU particle system for the Bevy game engine.
+
+![firework](https://raw.githubusercontent.com/djeedai/bevy_hanabi/ea57ad23be55a098b9d9446425f1909a8e88f6fc/examples/firework.gif)
+
+## Overview
+
+The Hanabi particle system is a modern GPU-based particle system for the Bevy game engine. It focuses on scale to produce stunning visual effects (VFX) in real time, offloading most of the work to the GPU, with minimal CPU intervention. The design is inspired by modern particle systems found in other industry-leading game engines.
+
+🚧 _This project is under heavy development, and is currently lacking both features and performance / usability polish. However, for moderate-size effects, it can already be used in your project. Feedback and contributions on both design and features are very much welcome._
+
+πŸŽ† Hanabi makes heavy use of compute shaders to offload work to the GPU in a performant way. Support for compute shaders on the `wasm` target (WebAssembly) is available as of v0.13 (Bevy 0.14), and only through WebGPU. See the [WebAssembly support](https://github.com/djeedai/bevy_hanabi/blob/ea57ad23be55a098b9d9446425f1909a8e88f6fc/docs/wasm.md) documentation for details.
+
+## Usage
+
+The πŸŽ† Bevy Hanabi plugin is compatible with Bevy versions >= 0.6; see [Compatible Bevy versions](#compatible-bevy-versions).
+
+### Add the dependency
+
+Add the `bevy_hanabi` dependency to `Cargo.toml`:
+
+```toml
+[dependencies]
+bevy_hanabi = "0.19"
+```
+
+See also [Features](#features) below for the list of supported features.
+
+### System setup
+
+Add the `HanabiPlugin` to your app:
+
+```rust
+use bevy_hanabi::prelude::*;
+
+App::default()
+ .add_plugins(DefaultPlugins)
+ .add_plugins(HanabiPlugin)
+ .run();
+```
+
+### Create an effect asset
+
+Create an `EffectAsset` describing a visual effect:
+
+```rust
+fn setup(mut effects: ResMut<Assets<EffectAsset>>) {
+ // Define a color gradient from red to transparent black
+ let mut gradient = Gradient::new();
+ gradient.add_key(0.0, Vec4::new(1., 0., 0., 1.));
+ gradient.add_key(1.0, Vec4::splat(0.));
+
+ // Create a new expression module
+ let mut module = Module::default();
+
+ // On spawn, randomly initialize the position of the particle
+ // to be over the surface of a sphere of radius 2 units.
+ let init_pos = SetPositionSphereModifier {
+ center: module.lit(Vec3::ZERO),
+ radius: module.lit(2.),
+ dimension: ShapeDimension::Surface,
+ };
+
+ // Also initialize a radial initial velocity to 6 units/sec
+ // away from the (same) sphere center.
+ let init_vel = SetVelocitySphereModifier {
+ center: module.lit(Vec3::ZERO),
+ speed: module.lit(6.),
+ };
+
+ // Initialize the total lifetime of the particle, that is
+ // the time for which it's simulated and rendered. This modifier
+ // is almost always required, otherwise the particles won't show.
+ let lifetime = module.lit(10.); // literal value "10.0"
+ let init_lifetime = SetAttributeModifier::new(
+ Attribute::LIFETIME, lifetime);
+
+ // Every frame, add a gravity-like acceleration downward
+ let accel = module.lit(Vec3::new(0., -3., 0.));
+ let update_accel = AccelModifier::new(accel);
+
+ // Create the effect asset
+ let effect = EffectAsset::new(
+ // Maximum number of particles alive at a time
+ 1024,
+ // Spawn at a rate of 5 particles per second
+ SpawnerSettings::rate(5.0.into()),
+ // Move the expression module into the asset
+ module
+ )
+ .with_name("MyEffect")
+ .init(init_pos)
+ .init(init_vel)
+ .init(init_lifetime)
+ .update(update_accel)
+ // Render the particles with a color gradient over their
+ // lifetime. This maps the gradient key 0 to the particle spawn
+ // time, and the gradient key 1 to the particle death (10s).
+ .render(ColorOverLifetimeModifier { gradient, ..default() });
+
+ // Insert into the asset system
+ let effect_handle = effects.add(effect);
+}
+```
+
+### Spawn a particle effect
+
+Use a `ParticleEffect` to create an effect instance from an existing asset.
+
+```rust
+commands.spawn((
+ ParticleEffect::new(effect_handle),
+ Transform::from_translation(Vec3::Y),
+));
+```
+
+## Examples
+
+See the [`examples/`](https://github.com/djeedai/bevy_hanabi/tree/ea57ad23be55a098b9d9446425f1909a8e88f6fc/examples) folder.
+
+A web demo (using the WebAssembly target) showing all examples is availabe in the [`examples/wasm/`](https://github.com/djeedai/bevy_hanabi/tree/ea57ad23be55a098b9d9446425f1909a8e88f6fc/examples/wasm) folder. You can open `index.html` in any browser to see a GIF of all the examples. Running the actual WebAssembly example however requires serving the files with an HTTP server. If you have NodeJS installed, you can do that for example by running `npx http-server examples/wasm`.
+
+Note for Linux users: The examples build with the `bevy/x11` feature by default to enable support for the X11 display server. If you want to use the Wayland display server instead, add the `bevy/wayland` feature.
+
+## Feature List
+
+This list contains the major fixed features provided by πŸŽ† Hanabi. Beyond that, with the power of the [Expressions API](https://docs.rs/bevy_hanabi/0.19.0/bevy_hanabi/graph/expr/index.html), visual effect authors can further customize their effects by assigning individual particle attributes (position, color, _etc._).
+
+- Spawn
+ - [x] Constant rate
+ - [x] One-time burst
+ - [x] Repeated burst
+ - [x] Spawner resetting
+ - [x] Spawner activation/deactivation
+ - [x] Randomized spawning parameters
+- Initialize
+ - [x] Constant position
+ - [x] Position over shape
+ - [ ] cube
+ - [x] circle
+ - [x] sphere
+ - [x] cone / truncated cone (3D)
+ - [ ] plane
+ - [ ] generic mesh / point cloud (?)
+ - [x] Random position offset
+ - [x] Velocity over shape (with random speed)
+ - [x] circle
+ - [x] sphere
+ - [x] tangent
+ - [x] Constant/random per-particle color
+ - [x] Constant/random per-particle size
+ - [x] Constant/random par-particle age and lifetime
+- Update
+ - [x] Simulation condition
+ - [x] Always, even when hidden
+ - [x] Only when visible
+ - [x] Motion integration (Euler)
+ - [x] Apply forces and accelerations
+ - [x] Constant acceleration (gravity)
+ - [x] Radial acceleration
+ - [x] Tangent acceleration
+ - [x] Force field
+ - [x] Linear drag
+ - [ ] Collision
+ - [ ] Shape
+ - [ ] plane
+ - [ ] cube
+ - [ ] sphere
+ - [ ] Depth buffer
+ - [x] Allow/deny despawn box
+ - [x] Lifetime
+ - [x] Size change over lifetime
+ - [x] Color change over lifetime
+- Render
+ - [x] Quad
+ - [x] Textured
+ - [x] Generic 3D mesh
+ - [x] Deformation
+ - [x] Stretch alongside velocity
+ - [x] Trails / Ribbons
+ - [x] Camera support
+ - [x] Render layers
+ - [x] 2D cameras ([`Camera2d`](https://docs.rs/bevy/0.19/bevy/core_pipeline/core_2d/struct.Camera2d.html)) only
+ - [x] 3D cameras ([`Camera3d`](https://docs.rs/bevy/0.19/bevy/core_pipeline/core_3d/struct.Camera3d.html)) only
+ - [x] Simultaneous dual 2D/3D cameras
+ - [x] Multiple viewports (split screen)
+ - [x] HDR camera and bloom
+ - [x] Size and orient particles
+ - [x] Face camera (Billboard)
+ - [x] Face constant direction
+ - [x] Orient alongside velocity
+ - [x] Screen-space size (projection independent)
+- Debug
+ - [x] GPU debug labels / groups
+ - [ ] Debug visualization
+ - [ ] Position magnitude
+ - [ ] Velocity magnitude
+ - [ ] Age / lifetime
+
+## Features
+
+πŸŽ† Bevy Hanabi supports the following cargo features:
+
+| Feature | Default | Description |
+|---|:-:|---|
+| `2d` | βœ” | Enable rendering through 2D cameras ([`Camera2d`](https://docs.rs/bevy/0.19/bevy/core_pipeline/core_2d/struct.Camera2d.html)) |
+| `3d` | βœ” | Enable rendering through 3D cameras ([`Camera3d`](https://docs.rs/bevy/0.19/bevy/core_pipeline/core_3d/struct.Camera3d.html)) |
+
+For optimization purpose, users of a single type of camera can disable the other type by skipping default features in their `Cargo.toml`. For example to use only the 3D mode:
+
+```toml
+bevy_hanabi = { version = "0.19", default-features = false, features = [ "3d" ] }
+```
+
+## Compatible Bevy versions
+
+The `main` branch is compatible with the latest Bevy release.
+
+Compatibility of `bevy_hanabi` versions:
+
+| `bevy_hanabi` | `bevy` |
+| :-- | :-- |
+| `main` | `0.20` |
+| `0.19` | `0.19` |
+| `0.18` | `0.18` |
+| `0.17` | `0.17` |
+| `0.16` | `0.16` |
+| `0.14`-`0.15` | `0.15` |
+| `0.12`-`0.13` | `0.14` |
+| `0.10`-`0.11` | `0.13` |
+| `0.8`-`0.9` | `0.12` |
+| `0.7` | `0.11` |
+| `0.6` | `0.10` |
+| `0.5` | `0.9` |
+| `0.3`-`0.4` | `0.8` |
+| `0.2` | `0.7` |
+| `0.1` | `0.6` |
+
+## License
+
+πŸŽ† Hanabi is dual-licensed under either:
+
+- MIT License ([`LICENSE-MIT`](./LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
+- Apache License, Version 2.0 ([`LICENSE-APACHE2`](./LICENSE-APACHE2) or <http://www.apache.org/licenses/LICENSE-2.0>)
+
+at your option.
+
+`SPDX-License-Identifier: MIT OR Apache-2.0`
diff --git a/vendor/bevy_hanabi/src/asset.rs b/vendor/bevy_hanabi/src/asset.rs
new file mode 100644
index 00000000..44a85b7f
--- /dev/null
+++ b/vendor/bevy_hanabi/src/asset.rs
@@ -0,0 +1,1498 @@
+use bevy::asset::AssetPath;
+use bevy::asset::{io::Reader, AssetLoader, LoadContext};
+use bevy::reflect::TypeRegistry;
+use bevy::reflect::{TypePath, TypeRegistryArc};
+use bevy::{
+ asset::{Asset, Assets, Handle},
+ log::trace,
+ math::{Vec2, Vec3},
+ platform::collections::HashSet,
+ prelude::{Component, Entity, FromWorld, Mesh, Plane3d, Resource, World},
+ reflect::Reflect,
+ utils::default,
+};
+use bevy::{ecs::reflect::AppTypeRegistry, reflect::serde::TypedReflectSerializer};
+use serde::de::DeserializeSeed as _;
+use serde::{Deserialize, Serialize};
+use thiserror::Error;
+use wgpu::{BlendComponent, BlendFactor, BlendOperation, BlendState};
+
+use crate::Modifiers;
+use crate::{
+ modifier::{Modifier, RenderModifier},
+ ExprHandle, ModifierContext, Module, ParticleLayout, Property, PropertyLayout, SimulationSpace,
+ SpawnerSettings, TextureLayout,
+};
+
+/// Type of motion integration applied to the particles of a system.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub enum MotionIntegration {
+ /// No motion integration. The [`Attribute::POSITION`] of the particles
+ /// needs to be explicitly assigned by a modifier for the particles to move.
+ ///
+ /// [`Attribute::POSITION`]: crate::Attribute::POSITION
+ None,
+
+ /// Apply Euler motion integration each simulation update before all
+ /// modifiers are applied.
+ ///
+ /// Not to be confused with Bevy's `PreUpdate` phase. Here "update" refers
+ /// to the particle update on the GPU via a compute shader.
+ PreUpdate,
+
+ /// Apply Euler motion integration each simulation update after all
+ /// modifiers are applied. This is the default.
+ ///
+ /// Not to be confused with Bevy's `PostUpdate` phase. Here "update" refers
+ /// to the particle update on the GPU via a compute shader.
+ #[default]
+ PostUpdate,
+}
+
+/// Simulation condition for an effect.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub enum SimulationCondition {
+ /// Simulate the effect only when visible.
+ ///
+ /// The visibility is determined by the [`InheritedVisibility`] and the
+ /// [`ViewVisibility`] components, if present. The effect is assumed to be
+ /// visible if those components are absent.
+ ///
+ /// This is the default for all assets, and is the most performant option,
+ /// allowing to have many effects in the scene without the need to simulate
+ /// all of them if they're not visible.
+ ///
+ /// Note that any [`ParticleEffect`] spawned is always compiled into a
+ /// [`CompiledParticleEffect`], even when it's not visible and even when
+ /// that variant is selected. That means it consumes GPU resources (memory,
+ /// in particular).
+ ///
+ /// Note also that AABB culling is not currently available. Only boolean
+ /// ON/OFF visibility is used.
+ ///
+ /// [`Visibility`]: bevy::camera::visibility::Visibility
+ /// [`InheritedVisibility`]: bevy::camera::visibility::InheritedVisibility
+ /// [`ViewVisibility`]: bevy::camera::visibility::ViewVisibility
+ /// [`ParticleEffect`]: crate::ParticleEffect
+ /// [`CompiledParticleEffect`]: crate::CompiledParticleEffect
+ #[default]
+ WhenVisible,
+
+ /// Always simulate the effect, whether visible or not.
+ ///
+ /// For performance reasons, it's recommended to only simulate visible
+ /// particle effects (that is, use [`SimulationCondition::WhenVisible`]).
+ /// However occasionally it may be needed to continue the simulation
+ /// when the effect is not visible, to ensure some temporal continuity when
+ /// the effect is made visible again. This is an uncommon case, and you
+ /// should be aware of the performance implications of using this
+ /// condition, and only use it when strictly necessary.
+ ///
+ /// Any [`InheritedVisibility`] or [`ViewVisibility`] component is ignored.
+ ///
+ /// [`Visibility`]: bevy::camera::visibility::Visibility
+ /// [`InheritedVisibility`]: bevy::camera::visibility::InheritedVisibility
+ /// [`ViewVisibility`]: bevy::camera::visibility::ViewVisibility
+ Always,
+}
+
+/// Alpha mode for rendering an effect.
+///
+/// The alpha mode determines how the alpha value of a particle is used to
+/// render it. In general effects use semi-transparent particles. However, there
+/// are multiple alpha blending techniques available, producing different
+/// results.
+///
+/// This is very similar to the `bevy::prelude::AlphaMode` of the `bevy_pbr`
+/// crate, except that a different set of values is supported which reflects
+/// what this library currently supports.
+///
+/// The alpha mode only affects the render phase that particles are rendered
+/// into when rendering 3D views. For 2D views, all particle effects are
+/// rendered during the [`Transparent2d`] render phase.
+///
+/// [`Transparent2d`]: bevy::core_pipeline::core_2d::Transparent2d
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+#[non_exhaustive]
+pub enum AlphaMode {
+ /// Render the effect with alpha blending.
+ ///
+ /// This is the most common mode for handling transparency. It uses the
+ /// "blend" or "over" formula, where the color of each particle fragment is
+ /// accumulated into the destination render target after being modulated by
+ /// its alpha value.
+ ///
+ /// ```txt
+ /// dst_color = src_color * (1 - particle_alpha) + particle_color * particle_alpha;
+ /// dst_alpha = src_alpha * (1 - particle_alpha) + particle_alpha
+ /// ```
+ ///
+ /// This is the default blending mode.
+ ///
+ /// For 3D views, effects with this mode are rendered during the
+ /// [`Transparent3d`] render phase.
+ ///
+ /// [`Transparent3d`]: bevy::core_pipeline::core_3d::Transparent3d
+ #[default]
+ Blend,
+
+ /// Similar to [`AlphaMode::Blend`], however assumes RGB channel values are
+ /// [premultiplied](https://en.wikipedia.org/wiki/Alpha_compositing#Straight_versus_premultiplied).
+ ///
+ /// For otherwise constant RGB values, behaves more like
+ /// [`AlphaMode::Blend`] for alpha values closer to 1.0, and more like
+ /// [`AlphaMode::Add`] for alpha values closer to 0.0.
+ ///
+ /// Can be used to avoid β€œborder” or β€œoutline” artifacts that can occur
+ /// when using plain alpha-blended textures.
+ Premultiply,
+
+ /// Combines the color of the fragments with the colors behind them in an
+ /// additive process, (i.e. like light) producing lighter results.
+ ///
+ /// Black produces no effect. Alpha values can be used to modulate the
+ /// result.
+ ///
+ /// Useful for effects like holograms, ghosts, lasers and other energy
+ /// beams.
+ Add,
+
+ /// Combines the color of the fragments with the colors behind them in a
+ /// multiplicative process, (i.e. like pigments) producing darker results.
+ ///
+ /// White produces no effect. Alpha values can be used to modulate the
+ /// result.
+ ///
+ /// Useful for effects like stained glass, window tint film and some colored
+ /// liquids.
+ Multiply,
+
+ /// Render the effect with alpha masking.
+ ///
+ /// With this mode, the final alpha value computed per particle fragment is
+ /// compared against the cutoff value stored in this enum. Any fragment
+ /// with a value under the cutoff is discarded, while any fragment with
+ /// a value equal or over the cutoff becomes fully opaque. The end result is
+ /// an opaque particle with a cutout shape.
+ ///
+ /// ```txt
+ /// if src_alpha >= cutoff {
+ /// dst_color = particle_color;
+ /// dst_alpha = 1;
+ /// } else {
+ /// discard;
+ /// }
+ /// ```
+ ///
+ /// The assigned expression must yield a scalar floating-point value,
+ /// typically in the \[0:1\] range. This expression is assigned at the
+ /// beginning of the fragment shader to the special built-in `alpha_cutoff`
+ /// variable, which can be further accessed and modified by render
+ /// modifiers.
+ ///
+ /// The cutoff threshold comparison of the fragment's alpha value against
+ /// `alpha_cutoff` is performed as the last operation in the fragment
+ /// shader. This allows modifiers to affect the alpha value of the
+ /// particle before it's tested against the cutoff value stored in
+ /// `alpha_cutoff`.
+ ///
+ /// For 3D views, effects with this mode are rendered during the
+ /// [`AlphaMask3d`] render phase.
+ ///
+ /// [`AlphaMask3d`]: bevy::core_pipeline::core_3d::AlphaMask3d
+ Mask(ExprHandle),
+
+ /// Render the effect with no alpha, and update the depth buffer.
+ ///
+ /// Use this mode when every pixel covered by the particle's mesh is fully
+ /// opaque.
+ Opaque,
+}
+
+impl From<AlphaMode> for BlendState {
+ fn from(value: AlphaMode) -> Self {
+ match value {
+ AlphaMode::Blend => BlendState::ALPHA_BLENDING,
+ AlphaMode::Premultiply => BlendState::PREMULTIPLIED_ALPHA_BLENDING,
+ AlphaMode::Add => BlendState {
+ color: BlendComponent {
+ src_factor: BlendFactor::SrcAlpha,
+ dst_factor: BlendFactor::One,
+ operation: BlendOperation::Add,
+ },
+ alpha: BlendComponent {
+ src_factor: BlendFactor::Zero,
+ dst_factor: BlendFactor::One,
+ operation: BlendOperation::Add,
+ },
+ },
+ AlphaMode::Multiply => BlendState {
+ color: BlendComponent {
+ src_factor: BlendFactor::Dst,
+ dst_factor: BlendFactor::OneMinusSrcAlpha,
+ operation: BlendOperation::Add,
+ },
+ alpha: BlendComponent::OVER,
+ },
+ _ => BlendState::ALPHA_BLENDING,
+ }
+ }
+}
+
+/// Default particle mesh, if not otherwise specified in [`EffectAsset::mesh`].
+///
+/// This defaults to a unit quad facing the Z axis.
+///
+/// [`EffectAsset`]: crate::EffectAsset
+#[derive(Debug, Clone, Resource)]
+pub struct DefaultMesh(pub Handle<Mesh>);
+
+impl FromWorld for DefaultMesh {
+ fn from_world(world: &mut World) -> Self {
+ let mut meshes = world.resource_mut::<Assets<Mesh>>();
+ let handle = meshes.add(Plane3d::new(Vec3::Z, Vec2::splat(0.5)));
+ trace!("Created DefaultMesh(Plane3d/Z): handle={handle:?}");
+ Self(handle)
+ }
+}
+
+/// Asset describing a visual effect.
+///
+/// An effect asset represents the description of an effect, intended to be
+/// authored during development and instantiated once or more during the
+/// application execution.
+///
+/// An actual effect instance can be spanwed with a [`ParticleEffect`]
+/// component which references the [`EffectAsset`].
+///
+/// [`ParticleEffect`]: crate::ParticleEffect
+/// [`EffectAsset`]: crate::EffectAsset
+#[derive(Asset, Default, Clone, Reflect)]
+#[reflect(from_reflect = false)]
+pub struct EffectAsset {
+ /// Display name of the effect.
+ ///
+ /// This has no internal use, and is mostly for the user to identify an
+ /// effect or for display in some tool UI. It's however used in serializing
+ /// the asset.
+ pub name: String,
+ /// Maximum number of concurrent particles.
+ ///
+ /// The capacity is the maximum number of particles that can be alive at the
+ /// same time. It determines the size of various GPU resources, most notably
+ /// the particle buffer itself. To prevent wasting GPU resources, users
+ /// should keep this quantity as close as possible to the maximum number of
+ /// particles they expect to render.
+ capacity: u32,
+ /// The CPU spawner for this effect.
+ pub spawner: SpawnerSettings,
+ /// For 2D rendering, the Z coordinate used as the sort key.
+ ///
+ /// This value is passed to the render pipeline and used when sorting
+ /// transparent items to render, to order them. As a result, effects
+ /// with different Z values cannot be batched together, which may
+ /// negatively affect performance.
+ ///
+ /// Ignored for 3D rendering.
+ pub z_layer_2d: f32,
+ /// Particle simulation space.
+ pub simulation_space: SimulationSpace,
+ /// Condition under which the effect is simulated.
+ pub simulation_condition: SimulationCondition,
+ /// Seed for the pseudo-random number generator.
+ ///
+ /// This value is used as the default value for all [`ParticleEffect`]
+ /// instances based on this asset. You can override this on a per-instance
+ /// basis by setting [`ParticleEffect::prng_seed`]. The resulting value
+ /// is uploaded to GPU and used for the various random expressions and
+ /// quantities computed in shaders.
+ ///
+ /// [`ParticleEffect`]: crate::ParticleEffect
+ /// [`ParticleEffect::prng_seed`]: crate::ParticleEffect::prng_seed
+ pub prng_seed: u32,
+ /// Init modifier defining the effect.
+ init_modifiers: Modifiers,
+ /// Update modifiers defining the effect.
+ update_modifiers: Modifiers,
+ /// Render modifiers defining the effect.
+ render_modifiers: Modifiers,
+ /// Type of motion integration applied to the particles of a system.
+ pub motion_integration: MotionIntegration,
+ /// Expression module for this effect.
+ module: Module,
+ /// Alpha mode.
+ pub alpha_mode: AlphaMode,
+ /// The mesh that each particle renders.
+ ///
+ /// The asset path must reference a [`Mesh`] asset. If `None`, the effect
+ /// uses the [`DefaultMesh`].
+ ///
+ /// Unlike previous versions of Hanabi, you cannot anymore assign a runtime
+ /// [`Handle<Mesh>`] to an [`EffectAsset`]; although this might be
+ /// convenient, this prevents serializing the asset, because not all assets
+ /// in the [`Assets<Mesh>`] resource correspond to an actual asset with a
+ /// path.
+ pub mesh: Option<AssetPath<'static>>,
+}
+
+impl EffectAsset {
+ /// Create a new effect asset.
+ ///
+ /// The effect assets requires 2 essential pieces:
+ /// - The capacity of the effect, which represents the maximum number of
+ /// particles which can be stored and simulated at the same time for each
+ /// group. Each group has its own capacity, in number of particles. All
+ /// capacities must be non-zero and should be the smallest possible values
+ /// which allow you to author the effect. These values directly impact the
+ /// GPU memory consumption of the effect, which will allocate some buffers
+ /// to store that many particles for as long as the effect exists. The
+ /// capacities of an effect are immutable. See also [`capacity()`] for
+ /// more details.
+ /// - The [`SpawnerSettings`], which defines when particles are emitted.
+ ///
+ /// Additionally, if any modifier added to this effect uses some [`Expr`] to
+ /// customize its behavior, then those [`Expr`] are stored into a [`Module`]
+ /// which should be passed to this method. If expressions are not used, just
+ /// pass an empty module [`Module::default()`].
+ ///
+ /// # Examples
+ ///
+ /// Create a new effect asset without any modifier. This effect doesn't
+ /// really do anything because _e.g._ the particles have a zero lifetime.
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let spawner = SpawnerSettings::rate(5_f32.into()); // 5 particles per second
+ /// let module = Module::default();
+ /// let capacity = 1024; // max 1024 particles alive at any time
+ /// let effect = EffectAsset::new(capacity, spawner, module);
+ /// ```
+ ///
+ /// Create a new effect asset with a modifier holding an expression. The
+ /// expression is stored inside the [`Module`] transfered to the
+ /// [`EffectAsset`], which owns the module once created.
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let spawner = SpawnerSettings::rate(5_f32.into()); // 5 particles per second
+ ///
+ /// let mut module = Module::default();
+ ///
+ /// // Create a modifier that initialized the particle lifetime to 10 seconds.
+ /// let lifetime = module.lit(10.); // literal value "10.0"
+ /// let init_lifetime = SetAttributeModifier::new(Attribute::LIFETIME, lifetime);
+ ///
+ /// let capacity = 1024; // max 1024 particles alive at any time
+ /// let effect = EffectAsset::new(capacity, spawner, module);
+ /// ```
+ ///
+ /// [`capacity()`]: self::EffectAsset::capacity
+ /// [`Expr`]: crate::graph::expr::Expr
+ pub fn new(capacity: u32, spawner: SpawnerSettings, module: Module) -> Self {
+ Self {
+ capacity,
+ spawner,
+ module,
+ ..default()
+ }
+ }
+
+ /// Get the capacity of the effect, in number of particles.
+ ///
+ /// This value represents the number of particles stored in GPU memory at
+ /// all times, even if unused, so you should try to minimize it.
+ /// However, the library cannot emit more particles than the effect
+ /// capacity. Whatever the spawner settings, if the number of particles
+ /// reaches the capacity, no new particle can be emitted. Choosing an
+ /// appropriate capacity for an effect is therefore a compromise between
+ /// more particles available for visuals and more GPU memory usage.
+ ///
+ /// Common values range from 256 or less for smaller effects, to several
+ /// hundreds of thousands for unique effects consuming a large portion of
+ /// the GPU memory budget. Hanabi has been tested with over a million
+ /// particles, however the performance will largely depend on the actual GPU
+ /// hardware and available memory, so authors are encouraged not to go too
+ /// crazy with the capacity.
+ ///
+ /// [`EffectSpawner`]: crate::EffectSpawner
+ pub fn capacity(&self) -> u32 {
+ self.capacity
+ }
+
+ /// Get the expression module storing all expressions in use by modifiers of
+ /// this effect.
+ pub fn module(&self) -> &Module {
+ &self.module
+ }
+
+ /// Set the effect name.
+ ///
+ /// The effect name is used when serializing the effect.
+ pub fn with_name(mut self, name: impl Into<String>) -> Self {
+ self.name = name.into();
+ self
+ }
+
+ /// Set the effect's simulation condition.
+ pub fn with_simulation_condition(mut self, simulation_condition: SimulationCondition) -> Self {
+ self.simulation_condition = simulation_condition;
+ self
+ }
+
+ /// Set the effect's simulation space.
+ pub fn with_simulation_space(mut self, simulation_space: SimulationSpace) -> Self {
+ self.simulation_space = simulation_space;
+ self
+ }
+
+ /// Set the alpha mode.
+ pub fn with_alpha_mode(mut self, alpha_mode: AlphaMode) -> Self {
+ self.alpha_mode = alpha_mode;
+ self
+ }
+
+ /// Set the effect's motion integration.
+ pub fn with_motion_integration(mut self, motion_integration: MotionIntegration) -> Self {
+ self.motion_integration = motion_integration;
+ self
+ }
+
+ /// Get the list of existing properties.
+ ///
+ /// This is a shortcut for `self.module().properties()`.
+ pub fn properties(&self) -> &[Property] {
+ self.module.properties()
+ }
+
+ /// Add an initialization modifier to the effect.
+ ///
+ /// Initialization modifiers apply to all particles that are spawned or
+ /// cloned.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the modifier doesn't support the init context (that is,
+ /// `modifier.context()` returns a flag which doesn't include
+ /// [`ModifierContext::Init`]).
+ #[inline]
+ pub fn init<M>(mut self, modifier: M) -> Self
+ where
+ M: Modifier + Send + Sync,
+ {
+ assert!(modifier.context().contains(ModifierContext::Init));
+ self.init_modifiers.push(Box::new(modifier));
+ self
+ }
+
+ /// Add an update modifier to the effect.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the modifier doesn't support the update context (that is,
+ /// `modifier.context()` returns a flag which doesn't include
+ /// [`ModifierContext::Update`]).
+ #[inline]
+ pub fn update<M>(mut self, modifier: M) -> Self
+ where
+ M: Modifier + Send + Sync,
+ {
+ assert!(modifier.context().contains(ModifierContext::Update));
+ self.update_modifiers.push(Box::new(modifier));
+ self
+ }
+
+ /// Add a [`BoxedModifier`] to the specific context.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the context is [`ModifierContext::Render`]; use
+ /// [`add_render_modifier()`] instead.
+ ///
+ /// Panics if the input `context` contains more than one context (the
+ /// bitfield contains more than 1 bit set) or no context at all (zero bit
+ /// set).
+ ///
+ /// Panics if the modifier doesn't support the context specified (that is,
+ /// `modifier.context()` returns a flag which doesn't include `context`).
+ ///
+ /// [`BoxedModifier`]: crate::BoxedModifier
+ /// [`add_render_modifier()`]: crate::EffectAsset::add_render_modifier
+ pub fn add_modifier(mut self, context: ModifierContext, modifier: Box<dyn Modifier>) -> Self {
+ assert!(context == ModifierContext::Init || context == ModifierContext::Update);
+ assert!(modifier.context().contains(context));
+ if context == ModifierContext::Init {
+ self.init_modifiers.push(modifier);
+ } else {
+ self.update_modifiers.push(modifier);
+ }
+ self
+ }
+
+ /// Add a render modifier to the effect.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the modifier doesn't support the render context (that is,
+ /// `modifier.context()` returns a flag which doesn't include
+ /// [`ModifierContext::Render`]).
+ #[inline]
+ pub fn render<M>(mut self, modifier: M) -> Self
+ where
+ M: RenderModifier + Send + Sync,
+ {
+ assert!(modifier.context().contains(ModifierContext::Render));
+ self.render_modifiers.push(Box::new(modifier));
+ self
+ }
+
+ /// Add a [`RenderModifier`] to the render context.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the modifier doesn't support the render context (that is,
+ /// `modifier.context()` returns a flag which doesn't include
+ /// [`ModifierContext::Render`]).
+ pub fn add_render_modifier(mut self, modifier: Box<dyn RenderModifier>) -> Self {
+ assert!(modifier.context().contains(ModifierContext::Render));
+ self.render_modifiers.push(modifier.boxed_clone());
+ self
+ }
+
+ /// Get a list of all the modifiers of this effect.
+ pub fn modifiers(&self) -> impl Iterator<Item = &dyn Modifier> {
+ self.init_modifiers
+ .iter()
+ .map(|bm| &**bm)
+ .chain(self.update_modifiers.iter().map(|bm| &**bm))
+ .chain(self.render_modifiers.iter().map(|bm| &**bm))
+ }
+
+ /// Get a list of all the init modifiers of this effect.
+ ///
+ /// This is a filtered list of all modifiers, retaining only modifiers
+ /// executing in the [`ModifierContext::Init`] context.
+ ///
+ /// [`ModifierContext::Init`]: crate::ModifierContext::Init
+ pub fn init_modifiers(&self) -> impl Iterator<Item = &dyn Modifier> {
+ self.init_modifiers.iter().map(|bm| &**bm)
+ }
+
+ /// Get a list of all the update modifiers of this effect.
+ ///
+ /// This is a filtered list of all modifiers, retaining only modifiers
+ /// executing in the [`ModifierContext::Update`] context.
+ ///
+ /// [`ModifierContext::Update`]: crate::ModifierContext::Update
+ pub fn update_modifiers(&self) -> impl Iterator<Item = &dyn Modifier> {
+ self.update_modifiers.iter().map(|bm| &**bm)
+ }
+
+ /// Get a list of all the render modifiers of this effect.
+ ///
+ /// This is a filtered list of all modifiers, retaining only modifiers
+ /// executing in the [`ModifierContext::Render`] context.
+ ///
+ /// [`ModifierContext::Render`]: crate::ModifierContext::Render
+ pub fn render_modifiers(&self) -> impl Iterator<Item = &dyn RenderModifier> {
+ self.render_modifiers.iter().filter_map(|m| m.as_render())
+ }
+
+ /// Build the particle layout of the asset based on its modifiers.
+ ///
+ /// This method calculates the particle layout of the effect based on the
+ /// currently existing modifiers, and return it as a newly allocated
+ /// [`ParticleLayout`] object.
+ pub fn particle_layout(&self) -> ParticleLayout {
+ // Build the set of unique attributes required for all modifiers
+ let mut set = HashSet::new();
+ for modifier in self.modifiers() {
+ for &attr in modifier.attributes() {
+ set.insert(attr);
+ }
+ }
+
+ // Add all attributes used by expressions. Those are indirectly used by
+ // modifiers, but may not have been added directly yet.
+ self.module.gather_attributes(&mut set);
+
+ // Build the layout
+ let mut layout = ParticleLayout::new();
+ for attr in set {
+ layout = layout.append(attr);
+ }
+ layout.build()
+ }
+
+ /// Build the property layout of the asset based on its properties.
+ ///
+ /// This method calculates the property layout of the effect based on the
+ /// currently existing properties, and return it as a newly allocated
+ /// [`PropertyLayout`] object.
+ pub fn property_layout(&self) -> PropertyLayout {
+ PropertyLayout::new(self.properties().iter())
+ }
+
+ /// Get the texture layout of the module of this effect.
+ pub fn texture_layout(&self) -> TextureLayout {
+ self.module.texture_layout()
+ }
+
+ /// Sets the mesh that each particle will render.
+ ///
+ /// Note: this asset path must reference a [`Mesh`] asset.
+ pub fn mesh(mut self, mesh: AssetPath<'static>) -> Self {
+ self.mesh = Some(mesh);
+ self
+ }
+
+ /// Serialize this effect asset.
+ ///
+ /// This uses the canonical Hanabi serialization format, which is internally
+ /// based on RON (implementation detail). The type registry must contain all
+ /// types this [`EffectAsset`] references, including all concrete types of
+ /// [`Modifier`] objects. In general, you should pass the app's own
+ /// [`TypeRegistry`] found in the [`AppTypeRegistry`] resource.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy::prelude::*;
+ /// # use bevy_hanabi::*;
+ /// fn serialize_effect(type_registry: Res<AppTypeRegistry>) {
+ /// let asset = EffectAsset::default();
+ /// // [...]
+ /// let type_registry = type_registry.read();
+ /// let s = asset.serialize(&type_registry).unwrap();
+ /// // [...]
+ /// }
+ /// ```
+ ///
+ /// # Advanced
+ ///
+ /// For more advanced serialization, for example to another format, see also
+ /// the [`EffectAssetSerializer`] which implements [`serde::Serialize`].
+ pub fn serialize(&self, type_registry: &TypeRegistry) -> Result<String, ron::Error> {
+ let serializer = EffectAssetSerializer::new(self, type_registry);
+ let pretty_config = ron::ser::PrettyConfig::default()
+ .indentor(" ".to_string())
+ .new_line("\n".to_string());
+ ron::ser::to_string_pretty(&serializer, pretty_config)
+ }
+
+ /// Deserialize an effect asset from string.
+ ///
+ /// This uses the canonical Hanabi serialization format, which is internally
+ /// based on RON (implementation detail). The type registry must contain all
+ /// types the serialized [`EffectAsset`] references, including all concrete
+ /// types of [`Modifier`] objects. In general, you should pass the app's
+ /// own [`TypeRegistry`] found in the [`AppTypeRegistry`] resource.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy::prelude::*;
+ /// # use bevy_hanabi::*;
+ /// # fn get_asset_string() -> String { unimplemented!() }
+ /// fn deserialize_effect(type_registry: Res<AppTypeRegistry>) {
+ /// // [...]
+ /// let s: String = get_asset_string();
+ /// let type_registry = type_registry.read();
+ /// let asset = EffectAsset::deserialize(&s[..], &type_registry).unwrap();
+ /// // [...]
+ /// }
+ /// ```
+ ///
+ /// # Advanced
+ ///
+ /// For more advanced deserialization, for example to another format, see
+ /// also the [`EffectAssetDeserializer`] which implements
+ /// [`serde::de::DeserializeSeed`].
+ pub fn deserialize(s: &str, type_registry: &TypeRegistry) -> Result<Self, ron::Error> {
+ let mut deserializer = ron::de::Deserializer::from_str(s)?;
+ let deserialize = EffectAssetDeserializer::new(type_registry);
+ let asset = deserialize.deserialize(&mut deserializer)?;
+ Ok(asset)
+ }
+}
+
+impl bevy::reflect::serde::SerializeWithRegistry for EffectAsset {
+ fn serialize<S>(&self, serializer: S, registry: &TypeRegistry) -> Result<S::Ok, S::Error>
+ where
+ S: serde::Serializer,
+ {
+ use serde::ser::SerializeStruct as _;
+
+ let mut s = serializer.serialize_struct("EffectAsset", 14)?;
+ s.serialize_field("name", &self.name)?;
+ s.serialize_field("capacity", &self.capacity)?;
+ s.serialize_field("spawner", &self.spawner)?;
+ s.serialize_field("z_layer_2d", &self.z_layer_2d)?;
+ s.serialize_field("simulation_space", &self.simulation_space)?;
+ s.serialize_field("simulation_condition", &self.simulation_condition)?;
+ s.serialize_field("prng_seed", &self.prng_seed)?;
+ s.serialize_field(
+ "init_modifiers",
+ &TypedReflectSerializer::new(&self.init_modifiers, registry),
+ )?;
+ s.serialize_field(
+ "update_modifiers",
+ &TypedReflectSerializer::new(&self.update_modifiers, registry),
+ )?;
+ s.serialize_field(
+ "render_modifiers",
+ &TypedReflectSerializer::new(&self.render_modifiers, registry),
+ )?;
+ s.serialize_field("motion_integration", &self.motion_integration)?;
+ s.serialize_field("module", &self.module)?;
+ s.serialize_field("alpha_mode", &self.alpha_mode)?;
+ s.serialize_field("mesh", &self.mesh)?;
+ s.end()
+ }
+}
+
+impl<'de> bevy::reflect::serde::DeserializeWithRegistry<'de> for EffectAsset {
+ fn deserialize<D>(deserializer: D, registry: &TypeRegistry) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ #[derive(Deserialize)]
+ #[serde(field_identifier, rename_all = "snake_case")]
+ enum Field {
+ Name,
+ Capacity,
+ Spawner,
+ #[serde(rename = "z_layer_2d")]
+ ZLayer2d,
+ SimulationSpace,
+ SimulationCondition,
+ PrngSeed,
+ InitModifiers,
+ UpdateModifiers,
+ RenderModifiers,
+ MotionIntegration,
+ Module,
+ AlphaMode,
+ Mesh,
+ }
+
+ struct SerializedEffectAssetVisitor<'a> {
+ pub registry: &'a TypeRegistry,
+ }
+
+ impl<'a, 'de> serde::de::Visitor<'de> for SerializedEffectAssetVisitor<'a> {
+ type Value = EffectAsset;
+
+ fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
+ formatter.write_str("struct EffectAsset")
+ }
+
+ fn visit_map<V>(self, mut map: V) -> Result<EffectAsset, V::Error>
+ where
+ V: serde::de::MapAccess<'de>,
+ {
+ let modifiers = self
+ .registry
+ .get(std::any::TypeId::of::<Modifiers>())
+ .ok_or_else(|| {
+ serde::de::Error::custom("Failed to find type registration for Modifiers.")
+ })?;
+
+ let mut name = None;
+ let mut capacity = None;
+ let mut spawner = None;
+ let mut z_layer_2d = None;
+ let mut simulation_space = None;
+ let mut simulation_condition = None;
+ let mut prng_seed = None;
+ let mut init_modifiers = None;
+ let mut update_modifiers = None;
+ let mut render_modifiers = None;
+ let mut motion_integration = None;
+ let mut module = None;
+ let mut alpha_mode = None;
+ let mut mesh = None;
+ while let Some(key) = map.next_key()? {
+ match key {
+ Field::Name => {
+ if name.is_some() {
+ return Err(serde::de::Error::duplicate_field("name"));
+ }
+ name = Some(map.next_value()?);
+ }
+ Field::Capacity => {
+ if capacity.is_some() {
+ return Err(serde::de::Error::duplicate_field("capacity"));
+ }
+ capacity = Some(map.next_value()?);
+ }
+ Field::Spawner => {
+ if spawner.is_some() {
+ return Err(serde::de::Error::duplicate_field("spawner"));
+ }
+ spawner = Some(map.next_value()?);
+ }
+ Field::ZLayer2d => {
+ if z_layer_2d.is_some() {
+ return Err(serde::de::Error::duplicate_field("z_layer_2d"));
+ }
+ z_layer_2d = Some(map.next_value()?);
+ }
+ Field::SimulationSpace => {
+ if simulation_space.is_some() {
+ return Err(serde::de::Error::duplicate_field("simulation_space"));
+ }
+ simulation_space = Some(map.next_value()?);
+ }
+ Field::SimulationCondition => {
+ if simulation_condition.is_some() {
+ return Err(serde::de::Error::duplicate_field(
+ "simulation_condition",
+ ));
+ }
+ simulation_condition = Some(map.next_value()?);
+ }
+ Field::PrngSeed => {
+ if prng_seed.is_some() {
+ return Err(serde::de::Error::duplicate_field("prng_seed"));
+ }
+ prng_seed = Some(map.next_value()?);
+ }
+ Field::InitModifiers => {
+ if init_modifiers.is_some() {
+ return Err(serde::de::Error::duplicate_field("init_modifiers"));
+ }
+ init_modifiers = Some(map.next_value_seed(
+ bevy::reflect::serde::TypedReflectDeserializer::new(
+ modifiers,
+ self.registry,
+ ),
+ )?);
+ }
+ Field::UpdateModifiers => {
+ if update_modifiers.is_some() {
+ return Err(serde::de::Error::duplicate_field("update_modifiers"));
+ }
+ update_modifiers = Some(map.next_value_seed(
+ bevy::reflect::serde::TypedReflectDeserializer::new(
+ modifiers,
+ self.registry,
+ ),
+ )?);
+ }
+ Field::RenderModifiers => {
+ if render_modifiers.is_some() {
+ return Err(serde::de::Error::duplicate_field("render_modifiers"));
+ }
+ render_modifiers = Some(map.next_value_seed(
+ bevy::reflect::serde::TypedReflectDeserializer::new(
+ modifiers,
+ self.registry,
+ ),
+ )?);
+ }
+ Field::MotionIntegration => {
+ if motion_integration.is_some() {
+ return Err(serde::de::Error::duplicate_field(
+ "motion_integration",
+ ));
+ }
+ motion_integration = Some(map.next_value()?);
+ }
+ Field::Module => {
+ if module.is_some() {
+ return Err(serde::de::Error::duplicate_field("module"));
+ }
+ module = Some(map.next_value()?);
+ }
+ Field::AlphaMode => {
+ if alpha_mode.is_some() {
+ return Err(serde::de::Error::duplicate_field("alpha_mode"));
+ }
+ alpha_mode = Some(map.next_value()?);
+ }
+ Field::Mesh => {
+ if mesh.is_some() {
+ return Err(serde::de::Error::duplicate_field("mesh"));
+ }
+ mesh = Some(map.next_value()?);
+ }
+ }
+ }
+
+ // Recover the concrete field objects
+ let name = name.ok_or_else(|| serde::de::Error::missing_field("name"))?;
+ let capacity =
+ capacity.ok_or_else(|| serde::de::Error::missing_field("capacity"))?;
+ let spawner = spawner.ok_or_else(|| serde::de::Error::missing_field("spawner"))?;
+ let z_layer_2d =
+ z_layer_2d.ok_or_else(|| serde::de::Error::missing_field("z_layer_2d"))?;
+ let simulation_space = simulation_space
+ .ok_or_else(|| serde::de::Error::missing_field("simulation_space"))?;
+ let simulation_condition = simulation_condition
+ .ok_or_else(|| serde::de::Error::missing_field("simulation_condition"))?;
+ let prng_seed =
+ prng_seed.ok_or_else(|| serde::de::Error::missing_field("prng_seed"))?;
+ let motion_integration = motion_integration
+ .ok_or_else(|| serde::de::Error::missing_field("motion_integration"))?;
+ let module = module.ok_or_else(|| serde::de::Error::missing_field("module"))?;
+ let alpha_mode =
+ alpha_mode.ok_or_else(|| serde::de::Error::missing_field("alpha_mode"))?;
+ let mesh = mesh.ok_or_else(|| serde::de::Error::missing_field("mesh"))?;
+ // Modifiers uses ReflectModifier type data to construct a concrete type. So we
+ // can directly try_take() here from the PartialReflect to recover that concrete
+ // object. This should always succeed.
+ let init_modifiers = init_modifiers
+ .map(|m| m.try_take::<Modifiers>())
+ .transpose()
+ .map_err(|_| serde::de::Error::custom("Failed to get Modifiers"))?
+ .unwrap_or_default();
+ let update_modifiers = update_modifiers
+ .map(|m| m.try_take::<Modifiers>())
+ .transpose()
+ .map_err(|_| serde::de::Error::custom("Failed to get Modifiers"))?
+ .unwrap_or_default();
+ let render_modifiers = render_modifiers
+ .map(|m| m.try_take::<Modifiers>())
+ .transpose()
+ .map_err(|_| serde::de::Error::custom("Failed to get Modifiers"))?
+ .unwrap_or_default();
+
+ // Rebuild the concrete EffectAsset object
+ Ok(EffectAsset {
+ name,
+ capacity,
+ spawner,
+ z_layer_2d,
+ simulation_space,
+ simulation_condition,
+ prng_seed,
+ init_modifiers,
+ update_modifiers,
+ render_modifiers,
+ motion_integration,
+ module,
+ alpha_mode,
+ mesh,
+ })
+ }
+ }
+
+ const FIELDS: &[&str] = &[
+ "name",
+ "capacity",
+ "spawner",
+ "z_layer_2d",
+ "simulation_space",
+ "simulation_condition",
+ "prng_seed",
+ "init_modifiers",
+ "update_modifiers",
+ "render_modifiers",
+ "motion_integration",
+ "module",
+ "alpha_mode",
+ "mesh",
+ ];
+ deserializer.deserialize_struct(
+ "EffectAsset",
+ FIELDS,
+ SerializedEffectAssetVisitor { registry },
+ )
+ }
+}
+
+/// Serializer for an [`EffectAsset`].
+pub struct EffectAssetSerializer<'a> {
+ asset: &'a EffectAsset,
+ type_registry: &'a TypeRegistry,
+}
+
+impl<'a> EffectAssetSerializer<'a> {
+ /// Create a new serializer for a given [`EffectAsset`].
+ ///
+ /// The `type_registry` must contain all types referenced by the
+ /// [`EffectAsset`], and in particular all concrete [`Modifier`] types.
+ pub fn new(asset: &'a EffectAsset, type_registry: &'a TypeRegistry) -> Self {
+ Self {
+ asset,
+ type_registry,
+ }
+ }
+}
+
+impl<'a> serde::Serialize for EffectAssetSerializer<'a> {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: serde::Serializer,
+ {
+ use bevy::reflect::serde::SerializeWithRegistry;
+
+ <EffectAsset as SerializeWithRegistry>::serialize(
+ self.asset,
+ serializer,
+ self.type_registry,
+ )
+ }
+}
+
+/// Deserializer for an [`EffectAsset`].
+pub struct EffectAssetDeserializer<'a> {
+ type_registry: &'a TypeRegistry,
+}
+
+impl<'a> EffectAssetDeserializer<'a> {
+ /// Create a new deserializer for [`EffectAsset`].
+ ///
+ /// The `type_registry` must contain all types that could be referenced by
+ /// the [`EffectAsset`] to deserialize, and in particular all concrete
+ /// [`Modifier`] types.
+ pub fn new(type_registry: &'a TypeRegistry) -> Self {
+ Self { type_registry }
+ }
+}
+
+impl<'a, 'de> serde::de::DeserializeSeed<'de> for EffectAssetDeserializer<'a> {
+ type Value = EffectAsset;
+
+ fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ <EffectAsset as bevy::reflect::serde::DeserializeWithRegistry>::deserialize(
+ deserializer,
+ self.type_registry,
+ )
+ }
+}
+
+/// Asset loader for [`EffectAsset`].
+///
+/// Effet assets take the `.effect` extension.
+#[derive(Debug, TypePath)]
+pub struct EffectAssetLoader {
+ /// The type registry passed to [`EffectAsset::deserialize()`].
+ pub type_registry: TypeRegistryArc,
+}
+
+impl FromWorld for EffectAssetLoader {
+ fn from_world(world: &mut World) -> Self {
+ let type_registry = world.resource::<AppTypeRegistry>();
+ EffectAssetLoader {
+ type_registry: type_registry.0.clone(),
+ }
+ }
+}
+
+/// Error for the [`EffectAssetLoader`] loading an [`EffectAsset`].
+#[derive(Error, Debug)]
+#[non_exhaustive]
+pub enum EffectAssetLoaderError {
+ /// I/O error reading the asset source.
+ #[error("An IO error occurred during loading of a particle effect")]
+ Io(#[from] std::io::Error),
+
+ /// UTF-8 error converting the asset serialized content.
+ #[error("An encoding error occurred during loading of a particle effect")]
+ Encoding(#[from] std::string::FromUtf8Error),
+
+ /// Error during RON format parsing.
+ #[error("A RON format error occurred during loading of a particle effect")]
+ RonSpan(#[from] ron::error::SpannedError),
+
+ /// Error during RON format parsing.
+ #[error("A RON error occurred during loading of a particle effect")]
+ Ron(#[from] ron::error::Error),
+}
+
+impl AssetLoader for EffectAssetLoader {
+ type Asset = EffectAsset;
+
+ type Settings = ();
+
+ type Error = EffectAssetLoaderError;
+
+ async fn load(
+ &self,
+ reader: &mut dyn Reader,
+ _settings: &Self::Settings,
+ _load_context: &mut LoadContext<'_>,
+ ) -> Result<Self::Asset, Self::Error> {
+ let mut bytes = Vec::new();
+ reader.read_to_end(&mut bytes).await?;
+ let s = String::from_utf8(bytes)?;
+ let type_registry = self.type_registry.read();
+ let asset = EffectAsset::deserialize(&s, &type_registry)?;
+ Ok(asset)
+ }
+
+ fn extensions(&self) -> &[&str] {
+ &["effect"]
+ }
+}
+
+/// Component defining the parent effect of the current effect.
+///
+/// This component is optional. When present, on the same entity as the
+/// [`ParticleEffect`], it defines the "parent effect" of that effect. The
+/// particles of the parent effect are accessible from the init pass of this
+/// effect, to allow the particles from the current effect to inherit some
+/// attributes (position, velocity, ...) from the parent particle which
+/// triggered its spawning via GPU spawn events.
+///
+/// Adding this component automatically makes the current particle effect
+/// instance use GPU spawn events emitted by its parent, and automatically makes
+/// the parent effect instance emits such events.
+///
+/// An effect has at most one parent, defined by this component, but a parent
+/// effect can have multiple children. For example, a parent effect can emit GPU
+/// spawn events continuously ([`EventEmitCondition::Always`]) to generate some
+/// kind of trail, and also emit GPU spawn events when its particles die
+/// ([`EventEmitCondition::OnDie`]) for any explosion-like effect.
+///
+/// [`ParticleEffect`]: crate::ParticleEffect
+/// [`EventEmitCondition::Always`]: crate::EventEmitCondition::Always
+/// [`EventEmitCondition::OnDie`]: crate::EventEmitCondition::OnDie
+#[derive(Debug, Clone, Copy, Component, Reflect)]
+pub struct EffectParent {
+ /// Entity of the parent effect.
+ pub entity: Entity,
+}
+
+impl EffectParent {
+ /// Create a new component with the given entity as parent.
+ pub fn new(parent: Entity) -> Self {
+ Self { entity: parent }
+ }
+}
+
+#[derive(Debug, Default, Clone, Copy, PartialEq, Reflect, Serialize, Deserialize)]
+pub struct ParticleTrails {
+ pub spawn_period: f32,
+}
+
+#[cfg(test)]
+mod tests {
+ use std::path::Path;
+
+ use bevy::{
+ asset::{
+ io::{
+ memory::{Dir, MemoryAssetReader, MemoryAssetWriter},
+ AssetSourceBuilder, AssetSourceId,
+ },
+ LoadState,
+ },
+ diagnostic::DiagnosticsPlugin,
+ };
+
+ use super::*;
+ use crate::*;
+
+ #[test]
+ fn add_modifiers() {
+ let mut m = Module::default();
+ let expr = m.lit(3.);
+
+ for modifier_context in [ModifierContext::Init, ModifierContext::Update] {
+ let effect = EffectAsset::default().add_modifier(
+ modifier_context,
+ Box::new(SetAttributeModifier::new(Attribute::POSITION, expr)),
+ );
+ assert_eq!(effect.modifiers().count(), 1);
+ let m = effect.modifiers().next().unwrap();
+ assert!(m.context().contains(modifier_context));
+ }
+
+ {
+ let effect = EffectAsset::default().add_render_modifier(Box::new(SetColorModifier {
+ color: CpuValue::Single(Vec4::ONE),
+ blend: ColorBlendMode::Overwrite,
+ mask: ColorBlendMask::RGBA,
+ }));
+ assert_eq!(effect.modifiers().count(), 1);
+ let m = effect.modifiers().next().unwrap();
+ assert!(m.context().contains(ModifierContext::Render));
+ }
+ }
+
+ #[test]
+ fn test_apply_modifiers() {
+ let mut module = Module::default();
+ let origin = module.lit(Vec3::ZERO);
+ let one = module.lit(1.);
+ let init_age = SetAttributeModifier::new(Attribute::AGE, one);
+ let init_lifetime = SetAttributeModifier::new(Attribute::LIFETIME, one);
+ let init_pos_sphere = SetPositionSphereModifier {
+ center: module.lit(Vec3::ZERO),
+ radius: module.lit(1.),
+ dimension: ShapeDimension::Volume,
+ };
+ let init_vel_sphere = SetVelocitySphereModifier {
+ center: module.lit(Vec3::ZERO),
+ speed: module.lit(1.),
+ };
+
+ let mut effect = EffectAsset::new(4096, SpawnerSettings::rate(30.0.into()), module)
+ .init(init_pos_sphere)
+ .init(init_vel_sphere)
+ //.update(AccelModifier::default())
+ .update(LinearDragModifier::new(one))
+ .update(ConformToSphereModifier::new(origin, one, one, one, one))
+ .render(ParticleTextureModifier::new(0))
+ .render(ColorOverLifetimeModifier::default())
+ .render(SizeOverLifetimeModifier::default())
+ .render(OrientModifier::new(OrientMode::ParallelCameraDepthPlane))
+ .render(OrientModifier::new(OrientMode::FaceCameraPosition))
+ .render(OrientModifier::new(OrientMode::AlongVelocity));
+
+ assert_eq!(effect.capacity, 4096);
+
+ let module = &mut effect.module;
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut init_context = ShaderWriter::new(
+ ModifierContext::Init,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ assert!(init_pos_sphere.apply(module, &mut init_context).is_ok());
+ assert!(init_vel_sphere.apply(module, &mut init_context).is_ok());
+ assert!(init_age.apply(module, &mut init_context).is_ok());
+ assert!(init_lifetime.apply(module, &mut init_context).is_ok());
+ // assert_eq!(effect., init_context.init_code);
+
+ let accel_mod = AccelModifier::constant(module, Vec3::ONE);
+ let drag_mod = LinearDragModifier::constant(module, 3.5);
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut update_context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ assert!(accel_mod.apply(module, &mut update_context).is_ok());
+ assert!(drag_mod.apply(module, &mut update_context).is_ok());
+ assert!(ConformToSphereModifier::new(origin, one, one, one, one)
+ .apply(module, &mut update_context)
+ .is_ok());
+ // assert_eq!(effect.update_layout, update_layout);
+
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut render_context =
+ RenderContext::new(&property_layout, &particle_layout, &texture_layout);
+ ParticleTextureModifier::new(0)
+ .apply_render(module, &mut render_context)
+ .unwrap();
+ ColorOverLifetimeModifier::default()
+ .apply_render(module, &mut render_context)
+ .unwrap();
+ SizeOverLifetimeModifier::default()
+ .apply_render(module, &mut render_context)
+ .unwrap();
+ OrientModifier::new(OrientMode::ParallelCameraDepthPlane)
+ .apply_render(module, &mut render_context)
+ .unwrap();
+ OrientModifier::new(OrientMode::FaceCameraPosition)
+ .apply_render(module, &mut render_context)
+ .unwrap();
+ OrientModifier::new(OrientMode::AlongVelocity)
+ .apply_render(module, &mut render_context)
+ .unwrap();
+ // assert_eq!(effect.render_layout, render_layout);
+ }
+
+ /// Round-trip EffectAsset through its own functions serialize() and
+ /// deserialize().
+ #[test]
+ fn serde_asset() {
+ let w = ExprWriter::new();
+
+ let pos = w.lit(Vec3::new(1.2, -3.45, 87.54485));
+ let x = w.lit(BVec2::new(false, true));
+ let _ = x + pos.clone();
+ let mod_pos = SetAttributeModifier::new(Attribute::POSITION, pos.expr());
+
+ let mut module = w.finish();
+ let prop = module.add_property("my_prop", Vec3::new(1.2, -2.3, 55.32).into());
+ let prop = module.prop(prop);
+ let _ = module.abs(prop);
+
+ let effect = EffectAsset {
+ name: "Effect".into(),
+ capacity: 4096,
+ spawner: SpawnerSettings::rate(30.0.into()),
+ module,
+ z_layer_2d: 1.5,
+ simulation_space: SimulationSpace::Local,
+ simulation_condition: SimulationCondition::Always,
+ prng_seed: 4284,
+ motion_integration: MotionIntegration::PreUpdate,
+ alpha_mode: AlphaMode::Multiply,
+ ..Default::default()
+ }
+ .init(mod_pos);
+
+ let type_registry = AppTypeRegistry::new_with_derived_types();
+ register_modifiers(&type_registry);
+ let registry = type_registry.read();
+
+ // Round-trip
+ let s = effect.serialize(&registry).unwrap();
+ eprintln!("{}", s);
+ let effect_serde = EffectAsset::deserialize(&s, &registry).unwrap();
+
+ assert_eq!(effect.name, effect_serde.name);
+ assert_eq!(effect.capacity, effect_serde.capacity);
+ assert_eq!(effect.spawner, effect_serde.spawner);
+ assert_eq!(effect.z_layer_2d, effect_serde.z_layer_2d);
+ assert_eq!(effect.simulation_space, effect_serde.simulation_space);
+ assert_eq!(
+ effect.simulation_condition,
+ effect_serde.simulation_condition
+ );
+ assert_eq!(effect.motion_integration, effect_serde.motion_integration);
+ assert_eq!(effect.module, effect_serde.module);
+ assert_eq!(effect.alpha_mode, effect_serde.alpha_mode);
+ assert_eq!(
+ effect.init_modifiers().count(),
+ effect_serde.init_modifiers().count()
+ );
+ assert_eq!(
+ effect.update_modifiers().count(),
+ effect_serde.update_modifiers().count()
+ );
+ assert_eq!(
+ effect.render_modifiers().count(),
+ effect_serde.render_modifiers().count()
+ );
+ }
+
+ #[test]
+ fn alpha_mode_blend_state() {
+ assert_eq!(BlendState::ALPHA_BLENDING, AlphaMode::Blend.into());
+ assert_eq!(
+ BlendState::PREMULTIPLIED_ALPHA_BLENDING,
+ AlphaMode::Premultiply.into()
+ );
+
+ let blend_state = BlendState {
+ color: BlendComponent {
+ src_factor: BlendFactor::SrcAlpha,
+ dst_factor: BlendFactor::One,
+ operation: BlendOperation::Add,
+ },
+ alpha: BlendComponent {
+ src_factor: BlendFactor::Zero,
+ dst_factor: BlendFactor::One,
+ operation: BlendOperation::Add,
+ },
+ };
+ assert_eq!(blend_state, AlphaMode::Add.into());
+
+ let blend_state = BlendState {
+ color: BlendComponent {
+ src_factor: BlendFactor::Dst,
+ dst_factor: BlendFactor::OneMinusSrcAlpha,
+ operation: BlendOperation::Add,
+ },
+ alpha: BlendComponent::OVER,
+ };
+ assert_eq!(blend_state, AlphaMode::Multiply.into());
+
+ let expr = Module::default().lit(0.5);
+ assert_eq!(BlendState::ALPHA_BLENDING, AlphaMode::Mask(expr).into());
+ }
+
+ // Regression test for #440
+ #[test]
+ fn transitive_attr() {
+ let mut m = Module::default();
+ let age = m.attr(Attribute::F32_0);
+ let modifier = SetAttributeModifier::new(Attribute::AGE, age);
+ let asset = EffectAsset::new(32, SpawnerSettings::once(3.0.into()), m).init(modifier);
+ let particle_layout = asset.particle_layout();
+ assert!(particle_layout.contains(Attribute::AGE)); // direct
+ assert!(particle_layout.contains(Attribute::F32_0)); // transitive
+ }
+
+ /// Creates a basic asset app and an in-memory file system.
+ fn create_app() -> (App, Dir) {
+ let mut app = App::new();
+ let dir = Dir::default();
+ let dir1 = dir.clone();
+ let dir2 = dir.clone();
+ app.register_asset_source(
+ AssetSourceId::Default,
+ AssetSourceBuilder::new(move || Box::new(MemoryAssetReader { root: dir1.clone() }))
+ .with_writer(move |_| Some(Box::new(MemoryAssetWriter { root: dir2.clone() }))),
+ )
+ .add_plugins((
+ TaskPoolPlugin::default(),
+ AssetPlugin {
+ watch_for_changes_override: Some(false),
+ use_asset_processor_override: Some(false),
+ ..Default::default()
+ },
+ DiagnosticsPlugin,
+ ));
+ (app, dir)
+ }
+
+ fn run_app_until(app: &mut App, mut predicate: impl FnMut(&mut World) -> Option<()>) {
+ for _ in 0..10_000 {
+ app.update();
+ if predicate(app.world_mut()).is_some() {
+ return;
+ }
+ }
+ panic!("Ran out of loops to return `Some` from `predicate`");
+ }
+
+ /// Check that the [`EffectAssetLoader`] can load an asset.
+ #[test]
+ fn loader() {
+ let (mut app, dir) = create_app();
+ app.init_asset::<EffectAsset>()
+ .init_asset_loader::<EffectAssetLoader>();
+
+ // Create an effect, serialize it, and write it to the in-memory file system
+ let asset_ref = {
+ let type_registry = app.world().resource::<AppTypeRegistry>().clone();
+ let type_registry = type_registry.read();
+ let spawner = SpawnerSettings::rate(3.0.into());
+ let module = Module::default();
+ let effect = EffectAsset::new(256, spawner, module);
+ let s = effect.serialize(&type_registry).unwrap();
+ dir.insert_asset_text(Path::new("test.effect"), &s[..]);
+ effect
+ };
+
+ // Load the asset through the AssetServer
+ let asset_server = app.world().resource::<AssetServer>().clone();
+ let handle = asset_server.load::<EffectAsset>("test.effect");
+ run_app_until(&mut app, |world| {
+ let asset_server = world.resource::<AssetServer>();
+ match asset_server.get_load_state(&handle).unwrap() {
+ LoadState::NotLoaded | LoadState::Loading => None,
+ LoadState::Loaded => Some(()),
+ LoadState::Failed(err) => panic!("Failed to load asset: {err:?}"),
+ }
+ });
+
+ // Compare the loaded asset deserialized from (in-memory) "disk", to the
+ // original reference asset.
+ let asset = app
+ .world()
+ .resource::<Assets<EffectAsset>>()
+ .get(&handle)
+ .unwrap();
+ assert_eq!(asset.capacity(), asset_ref.capacity());
+ assert_eq!(asset.spawner, asset_ref.spawner);
+ }
+}
diff --git a/vendor/bevy_hanabi/src/attributes.rs b/vendor/bevy_hanabi/src/attributes.rs
new file mode 100644
index 00000000..da74d4e1
--- /dev/null
+++ b/vendor/bevy_hanabi/src/attributes.rs
@@ -0,0 +1,2678 @@
+//! Effect attributes, like the position or velocity of a particle.
+//!
+//! An _effect attribute_ is a quantity stored per particle for all particles.
+//! Unlike [properties](crate::properties), each particle can have a different
+//! value for each attribute. Examples of particle attributes include the
+//! particle's own position and its velocity. Attributes are represented by the
+//! [`Attribute`] type.
+//!
+//! Attributes are indirectly added to an effect by adding [modifiers] requiring
+//! them. Each modifier documents its required attributes. You can force a
+//! single attribute by adding the [`SetAttributeModifier`].
+//!
+//! Note that πŸŽ† Hanabi provides a number of associated [`Attribute`] constants,
+//! like [`Attribute::POSITION`]. You cannot build your own [`Attribute`]
+//! instance. See [Built-in attributes](#built-in-attributes) and [Custom
+//! attributes](#custom-attributes) for all available attributes.
+//!
+//! # Definition
+//!
+//! [`Attribute`] defines the attribute's unique name, the type of its value,
+//! and a default value used to initialize the attribute if not otherwise
+//! explicitly initialized.
+//!
+//! The attribute name is a string used to identify the attribute, and also as
+//! the associated variable name in any WGSL shader code using that attribute.
+//! Because it's unique, attributes can be compared by their name alone.
+//!
+//! The attribute type encodes the type of data stored in the attribute,
+//! including the number of components for a vector or matrix type. It's stored
+//! together with the default value for the attribute into a [`Value`] field.
+//!
+//! # Layout
+//!
+//! Each particle effect contains one or more attributes. The set of all
+//! attributes makes a particle. Attributes are organized in memory into a
+//! _layout_, which optimizes GPU RAM usage and access by packing types
+//! together, and avoid any padding gaps. However this layout needs to follow
+//! the rules of WGSL structs, therefore might introduce some gaps (wasted
+//! space) nonetheless, depending on each attribute's required type alignment.
+//!
+//! Here's an example for the default particle attribute set, containing the
+//! particle's position and velocity vectors (`vec3<f32>`), and its age and
+//! lifetime (`f32`), packed into a 32 bytes struct:
+//!
+//! | Bytes | 0..4 | 4..8 | 8..12 | 12..16 |
+//! |--------|---|---|---|---|
+//! | 0..16 | [`POSITION`](Attribute::POSITION).X | [`POSITION`](Attribute::POSITION).Y | [`POSITION`](Attribute::POSITION).Z | [`AGE`](Attribute::AGE) |
+//! | 16..32 | [`VELOCITY`](Attribute::VELOCITY).X | [`VELOCITY`](Attribute::VELOCITY).Y | [`VELOCITY`](Attribute::VELOCITY).Z | [`LIFETIME`](Attribute::LIFETIME) |
+//!
+//! In WGSL code, this is represented by:
+//!
+//! ```wgsl
+//! struct Particle {
+//! position: vec3<f32>,
+//! age: f32,
+//! velocity: vec3<f32>,
+//! lifetime: f32,
+//! }
+//! ```
+//!
+//! The layout of a particle effect is represented by the [`ParticleLayout`]
+//! type, and built from a set of attributes via the [`ParticleLayoutBuilder`]
+//! helper. This is done internally by πŸŽ† Hanabi for each effect, so in general
+//! you don't have to use those types directly.
+//!
+//! # Built-in attributes
+//!
+//! πŸŽ† Hanabi provides a number of built-in attributes with a specified meaning.
+//! Those attributes are interpreted by some built-in library systems in a way
+//! specific to the attribute. For example, the [`Attribute::POSITION`]
+//! represents the particle's own position, and will be used as the position
+//! where to render the particle.
+//!
+//! In general those attributes can be read and written by the user, for example
+//! via the [`SetAttributeModifier`], but are also read and/or modified by πŸŽ†
+//! Hanabi itself.
+//!
+//! | Attribute | Meaning |
+//! |---|---|
+//! | [`Attribute::POSITION`] | The particle's position in [simulation space](crate::SimulationSpace). |
+//! | [`Attribute::VELOCITY`] | The particle's velocity in [simulation space](crate::SimulationSpace). |
+//! | [`Attribute::AGE`] | The particle's age, in seconds. |
+//! | [`Attribute::LIFETIME`] | The particle's total lifetime, in seconds. |
+//! | [`Attribute::COLOR`] | The particle's LDR color as `u32`. |
+//! | [`Attribute::HDR_COLOR`] | The particle's HDR color as `vec4<f32>`. |
+//! | [`Attribute::ALPHA`] | The particle's opacity. |
+//! | [`Attribute::SIZE`] | The particle's uniform size. |
+//! | [`Attribute::SIZE2`] | The particle's non-uniform 2D size. |
+//! | [`Attribute::SIZE3`] | The particle's non-uniform 3D size. |
+//! | [`Attribute::AXIS_X`] | X axis of the particle frame. |
+//! | [`Attribute::AXIS_Y`] | Y axis of the particle frame. |
+//! | [`Attribute::AXIS_Z`] | Z axis of the particle frame. |
+//! | [`Attribute::SPRITE_INDEX`] | Index of the current sprite for flipbook animation. |
+//!
+//! # Custom attributes
+//!
+//! In additon of the built-in attributes, πŸŽ† Hanabi provides a number of
+//! _custom attributes_, which are attributes with a specified type but no
+//! particular internal meaning. Users are free to use those attributes to store
+//! any quantity they like, noting that each new attribute increases the
+//! per-particle size and therefor the total RAM usage of the particle effect.
+//!
+//! | Attribute | Meaning |
+//! |---|---|
+//! | [`Attribute::F32_0`] | A custom `f32` attribute. |
+//! | [`Attribute::F32_1`] | A custom `f32` attribute. |
+//! | [`Attribute::F32_2`] | A custom `f32` attribute. |
+//! | [`Attribute::F32_3`] | A custom `f32` attribute. |
+//! | [`Attribute::F32_4`] | A custom `f32` attribute. |
+//! | [`Attribute::F32_5`] | A custom `f32` attribute. |
+//! | [`Attribute::F32_6`] | A custom `f32` attribute. |
+//! | [`Attribute::F32_7`] | A custom `f32` attribute. |
+//! | [`Attribute::F32X2_0`] | A custom `vec2<f32>` attribute. |
+//! | [`Attribute::F32X2_1`] | A custom `vec2<f32>` attribute. |
+//! | [`Attribute::F32X2_2`] | A custom `vec2<f32>` attribute. |
+//! | [`Attribute::F32X2_3`] | A custom `vec2<f32>` attribute. |
+//! | [`Attribute::F32X2_4`] | A custom `vec2<f32>` attribute. |
+//! | [`Attribute::F32X2_5`] | A custom `vec2<f32>` attribute. |
+//! | [`Attribute::F32X2_6`] | A custom `vec2<f32>` attribute. |
+//! | [`Attribute::F32X2_7`] | A custom `vec2<f32>` attribute. |
+//! | [`Attribute::F32X3_0`] | A custom `vec3<f32>` attribute. |
+//! | [`Attribute::F32X3_1`] | A custom `vec3<f32>` attribute. |
+//! | [`Attribute::F32X3_2`] | A custom `vec3<f32>` attribute. |
+//! | [`Attribute::F32X3_3`] | A custom `vec3<f32>` attribute. |
+//! | [`Attribute::F32X3_4`] | A custom `vec3<f32>` attribute. |
+//! | [`Attribute::F32X3_5`] | A custom `vec3<f32>` attribute. |
+//! | [`Attribute::F32X3_6`] | A custom `vec3<f32>` attribute. |
+//! | [`Attribute::F32X3_7`] | A custom `vec3<f32>` attribute. |
+//! | [`Attribute::F32X4_0`] | A custom `vec4<f32>` attribute. |
+//! | [`Attribute::F32X4_1`] | A custom `vec4<f32>` attribute. |
+//! | [`Attribute::F32X4_2`] | A custom `vec4<f32>` attribute. |
+//! | [`Attribute::F32X4_3`] | A custom `vec4<f32>` attribute. |
+//! | [`Attribute::F32X4_4`] | A custom `vec4<f32>` attribute. |
+//! | [`Attribute::F32X4_5`] | A custom `vec4<f32>` attribute. |
+//! | [`Attribute::F32X4_6`] | A custom `vec4<f32>` attribute. |
+//! | [`Attribute::F32X4_7`] | A custom `vec4<f32>` attribute. |
+//! | [`Attribute::U32_0`] | A custom `u32` attribute. |
+//! | [`Attribute::U32_1`] | A custom `u32` attribute. |
+//! | [`Attribute::U32_2`] | A custom `u32` attribute. |
+//! | [`Attribute::U32_3`] | A custom `u32` attribute. |
+//! | [`Attribute::U32_4`] | A custom `u32` attribute. |
+//! | [`Attribute::U32_5`] | A custom `u32` attribute. |
+//! | [`Attribute::U32_6`] | A custom `u32` attribute. |
+//! | [`Attribute::U32_7`] | A custom `u32` attribute. |
+//!
+//! [modifiers]: crate::modifier
+//! [`SetAttributeModifier`]: crate::modifier::SetAttributeModifier
+
+use std::{
+ any::Any,
+ borrow::Cow,
+ fmt::Display,
+ num::{NonZeroU32, NonZeroU64},
+};
+
+use bevy::{
+ math::{Vec2, Vec3, Vec4},
+ reflect::{
+ structs::{FieldIter, Struct, StructInfo},
+ utility::{GenericTypePathCell, NonGenericTypeInfoCell},
+ ApplyError, CreateTypeData, FromReflect, GetTypeRegistration, NamedField, PartialReflect,
+ Reflect, ReflectDeserialize, ReflectFromReflect, ReflectMut, ReflectOwned, ReflectRef,
+ ReflectSerialize, TypeInfo, TypePath, TypeRegistration, Typed,
+ },
+};
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ graph::{ScalarValue, Value, VectorValue},
+ ToWgslString,
+};
+
+/// Scalar types.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+#[non_exhaustive]
+pub enum ScalarType {
+ /// Boolean value (`bool`).
+ ///
+ /// The size of a `bool` is undefined in the WGSL specification, but fixed
+ /// at 4 bytes here.
+ Bool,
+ /// Floating point value (`f32`).
+ Float,
+ /// Signed 32-bit integer value (`i32`).
+ Int,
+ /// Unsigned 32-bit integer value (`u32`).
+ Uint,
+}
+
+impl Display for ScalarType {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Bool => write!(f, "bool"),
+ Self::Float => write!(f, "f32"),
+ Self::Int => write!(f, "i32"),
+ Self::Uint => write!(f, "u32"),
+ }
+ }
+}
+
+impl ScalarType {
+ /// Check if this type is a numeric type.
+ ///
+ /// A numeric type can be used in various math operators etc. All scalar
+ /// types are numeric, except `ScalarType::Bool`.
+ pub fn is_numeric(&self) -> bool {
+ !(matches!(self, ScalarType::Bool))
+ }
+
+ /// Size of a value of this type, in bytes.
+ ///
+ /// This corresponds to the size of a variable of that type when part of a
+ /// struct in WGSL. For `bool`, this is always 4 bytes (undefined in WGSL
+ /// spec).
+ pub const fn size(&self) -> usize {
+ 4
+ }
+
+ /// Alignment of a value of this type, in bytes.
+ ///
+ /// This corresponds to the alignment of a variable of that type when part
+ /// of a struct in WGSL. For `bool`, this is always 4 bytes (undefined in
+ /// WGSL spec).
+ pub const fn align(&self) -> usize {
+ 4
+ }
+}
+
+impl ToWgslString for ScalarType {
+ fn to_wgsl_string(&self) -> String {
+ match self {
+ ScalarType::Bool => "bool",
+ ScalarType::Float => "f32",
+ ScalarType::Int => "i32",
+ ScalarType::Uint => "u32",
+ }
+ .to_string()
+ }
+}
+
+/// Vector type (`vecN<T>`).
+///
+/// Describes the type of a vector, which is composed of 2 to 4 components of a
+/// same scalar type. This type corresponds to one of the valid vector types in
+/// the WGSL specification.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct VectorType {
+ /// Type of all elements (components) of the vector.
+ elem_type: ScalarType,
+ /// Number of components. Always 2/3/4.
+ count: u8,
+}
+
+impl Display for VectorType {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "vec{}<{}>", self.count, self.elem_type)
+ }
+}
+
+impl VectorType {
+ /// Boolean vector with 2 components (`vec2<bool>`).
+ pub const VEC2B: VectorType = VectorType::new(ScalarType::Bool, 2);
+ /// Boolean vector with 3 components (`vec3<bool>`).
+ pub const VEC3B: VectorType = VectorType::new(ScalarType::Bool, 3);
+ /// Boolean vector with 4 components (`vec4<bool>`).
+ pub const VEC4B: VectorType = VectorType::new(ScalarType::Bool, 4);
+ /// Floating-point vector with 2 components (`vec2<f32>`).
+ pub const VEC2F: VectorType = VectorType::new(ScalarType::Float, 2);
+ /// Floating-point vector with 3 components (`vec3<f32>`).
+ pub const VEC3F: VectorType = VectorType::new(ScalarType::Float, 3);
+ /// Floating-point vector with 4 components (`vec4<f32>`).
+ pub const VEC4F: VectorType = VectorType::new(ScalarType::Float, 4);
+ /// Vector with 2 signed integer components (`vec2<i32>`).
+ pub const VEC2I: VectorType = VectorType::new(ScalarType::Int, 2);
+ /// Vector with 3 signed integer components (`vec3<i32>`).
+ pub const VEC3I: VectorType = VectorType::new(ScalarType::Int, 3);
+ /// Vector with 4 signed integer components (`vec4<i32>`).
+ pub const VEC4I: VectorType = VectorType::new(ScalarType::Int, 4);
+ /// Vector with 2 unsigned integer components (`vec2<u32>`).
+ pub const VEC2U: VectorType = VectorType::new(ScalarType::Uint, 2);
+ /// Vector with 3 unsigned integer components (`vec3<u32>`).
+ pub const VEC3U: VectorType = VectorType::new(ScalarType::Uint, 3);
+ /// Vector with 4 unsigned integer components (`vec4<u32>`).
+ pub const VEC4U: VectorType = VectorType::new(ScalarType::Uint, 4);
+
+ /// Create a new vector type.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the component `count` is not 2/3/4.
+ pub const fn new(elem_type: ScalarType, count: u8) -> Self {
+ assert!(count >= 2 && count <= 4);
+ Self { elem_type, count }
+ }
+
+ /// Scalar type of the individual vector elements (components).
+ pub const fn elem_type(&self) -> ScalarType {
+ self.elem_type
+ }
+
+ /// Number of components.
+ pub const fn count(&self) -> usize {
+ self.count as usize
+ }
+
+ /// Is the type a numeric type?
+ ///
+ /// See [`ScalarType::is_numeric()`] for a definition of a numeric type.
+ ///
+ /// [`ScalarType::is_numeric()`]: crate::ScalarType::is_numeric
+ pub fn is_numeric(&self) -> bool {
+ self.elem_type.is_numeric()
+ }
+
+ /// Size of a value of this type, in bytes.
+ ///
+ /// This corresponds to the size of a variable of that type when part of a
+ /// struct in WGSL.
+ pub const fn size(&self) -> usize {
+ // https://gpuweb.github.io/gpuweb/wgsl/#alignment-and-size
+ self.count() * self.elem_type.size()
+ }
+
+ /// Alignment of a value of this type, in bytes.
+ ///
+ /// This corresponds to the alignment of a variable of that type when part
+ /// of a struct in WGSL.
+ pub const fn align(&self) -> usize {
+ // https://gpuweb.github.io/gpuweb/wgsl/#alignment-and-size
+ if self.count >= 3 {
+ 4 * self.elem_type.align()
+ } else {
+ 2 * self.elem_type.align()
+ }
+ }
+}
+
+impl ToWgslString for VectorType {
+ fn to_wgsl_string(&self) -> String {
+ format!("vec{}<{}>", self.count, self.elem_type.to_wgsl_string())
+ }
+}
+
+/// Floating-point matrix type (`matCxR<f32>`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct MatrixType {
+ rows: u8,
+ cols: u8,
+}
+
+impl Display for MatrixType {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "mat{}x{}<f32>", self.cols, self.rows)
+ }
+}
+
+impl MatrixType {
+ /// Floating-point matrix of size 2x2 (`mat2x2<f32>`).
+ pub const MAT2X2F: MatrixType = MatrixType::new(2, 2);
+ /// Floating-point matrix of size 3x2 (`mat3x2<f32>`).
+ pub const MAT3X2F: MatrixType = MatrixType::new(3, 2);
+ /// Floating-point matrix of size 4x2 (`mat4x2<f32>`).
+ pub const MAT4X2F: MatrixType = MatrixType::new(4, 2);
+ /// Floating-point matrix of size 2x3 (`mat2x3<f32>`).
+ pub const MAT2X3F: MatrixType = MatrixType::new(2, 3);
+ /// Floating-point matrix of size 3x3 (`mat3x3<f32>`).
+ pub const MAT3X3F: MatrixType = MatrixType::new(3, 3);
+ /// Floating-point matrix of size 4x3 (`mat4x3<f32>`).
+ pub const MAT4X3F: MatrixType = MatrixType::new(4, 3);
+ /// Floating-point matrix of size 2x4 (`mat2x4<f32>`).
+ pub const MAT2X4F: MatrixType = MatrixType::new(2, 4);
+ /// Floating-point matrix of size 3x4 (`mat3x4<f32>`).
+ pub const MAT3X4F: MatrixType = MatrixType::new(3, 4);
+ /// Floating-point matrix of size 4x4 (`mat4x4<f32>`).
+ pub const MAT4X4F: MatrixType = MatrixType::new(4, 4);
+
+ /// Create a new matrix type.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the number of columns or rows is not 2, 3, or 4.
+ pub const fn new(cols: u8, rows: u8) -> Self {
+ assert!(cols >= 2 && cols <= 4);
+ assert!(rows >= 2 && rows <= 4);
+ Self { cols, rows }
+ }
+
+ /// Number of columns in the matrix.
+ pub const fn cols(&self) -> usize {
+ self.cols as usize
+ }
+
+ /// Number of rows in the matrix.
+ pub const fn rows(&self) -> usize {
+ self.rows as usize
+ }
+
+ /// Size of a value of this type, in bytes.
+ ///
+ /// This corresponds to the size of a variable of that type when part of a
+ /// struct in WGSL.
+ pub const fn size(&self) -> usize {
+ // SizeOf(array<vecR, C>), which means matCx3 and matCx4 have same size
+ // https://gpuweb.github.io/gpuweb/wgsl/#alignment-and-size
+ if self.rows >= 3 {
+ self.cols() * VectorType::VEC4F.size()
+ } else {
+ self.cols() * VectorType::VEC2F.size()
+ }
+ }
+
+ /// Alignment of a value of this type, in bytes.
+ ///
+ /// This corresponds to the alignment of a variable of that type when part
+ /// of a struct in WGSL.
+ pub const fn align(&self) -> usize {
+ // AlignOf(vecR), which means matCx3 and matCx4 have same align
+ // https://gpuweb.github.io/gpuweb/wgsl/#alignment-and-size
+ VectorType::new(ScalarType::Float, self.rows).align()
+ }
+}
+
+impl ToWgslString for MatrixType {
+ fn to_wgsl_string(&self) -> String {
+ format!(
+ "mat{}x{}<{}>",
+ self.cols,
+ self.rows,
+ ScalarType::Float.to_wgsl_string()
+ )
+ }
+}
+
+/// Type of an [`Attribute`]'s value.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+#[non_exhaustive]
+pub enum ValueType {
+ /// A scalar type (single value).
+ Scalar(ScalarType),
+ /// A vector type with 2 to 4 components.
+ Vector(VectorType),
+ /// A floating-point matrix type of size between 2x2 and 4x4.
+ Matrix(MatrixType),
+}
+
+impl Display for ValueType {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ // The enum variants are different enough we don't need to discriminate at this
+ // level
+ match self {
+ ValueType::Scalar(s) => s.fmt(f),
+ ValueType::Vector(v) => v.fmt(f),
+ ValueType::Matrix(m) => m.fmt(f),
+ }
+ }
+}
+
+impl ValueType {
+ /// Is the type a numeric type?
+ pub fn is_numeric(&self) -> bool {
+ match self {
+ ValueType::Scalar(s) => s.is_numeric(),
+ ValueType::Vector(v) => v.is_numeric(),
+ ValueType::Matrix(_) => true,
+ }
+ }
+
+ /// Is the type a scalar type?
+ pub fn is_scalar(&self) -> bool {
+ matches!(self, ValueType::Scalar(_))
+ }
+
+ /// Is the type a vector type?
+ pub fn is_vector(&self) -> bool {
+ matches!(self, ValueType::Vector(_))
+ }
+
+ /// Is the type a matrix type?
+ pub fn is_matrix(&self) -> bool {
+ matches!(self, ValueType::Matrix(_))
+ }
+
+ /// Size of a value of this type, in bytes.
+ pub fn size(&self) -> usize {
+ match self {
+ ValueType::Scalar(s) => s.size(),
+ ValueType::Vector(v) => v.size(),
+ ValueType::Matrix(m) => m.size(),
+ }
+ }
+
+ /// Alignment of a value of this type, in bytes.
+ ///
+ /// This corresponds to the alignment of a variable of that type when part
+ /// of a struct in WGSL.
+ pub fn align(&self) -> usize {
+ match self {
+ ValueType::Scalar(s) => s.align(),
+ ValueType::Vector(v) => v.align(),
+ ValueType::Matrix(m) => m.align(),
+ }
+ }
+}
+
+impl From<ScalarType> for ValueType {
+ fn from(value: ScalarType) -> Self {
+ ValueType::Scalar(value)
+ }
+}
+
+impl From<VectorType> for ValueType {
+ fn from(value: VectorType) -> Self {
+ ValueType::Vector(value)
+ }
+}
+
+impl From<MatrixType> for ValueType {
+ fn from(value: MatrixType) -> Self {
+ ValueType::Matrix(value)
+ }
+}
+
+impl ToWgslString for ValueType {
+ fn to_wgsl_string(&self) -> String {
+ match self {
+ ValueType::Scalar(s) => s.to_wgsl_string(),
+ ValueType::Vector(v) => v.to_wgsl_string(),
+ ValueType::Matrix(m) => m.to_wgsl_string(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, Reflect)]
+pub(crate) struct AttributeInner {
+ name: Cow<'static, str>,
+ default_value: Value,
+}
+
+impl PartialEq for AttributeInner {
+ fn eq(&self, other: &Self) -> bool {
+ // Compare attributes by name since it's unique.
+ self.name == other.name
+ }
+}
+
+impl Eq for AttributeInner {}
+
+impl std::hash::Hash for AttributeInner {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ // Keep consistent with PartialEq and Eq
+ self.name.hash(state);
+ }
+}
+
+macro_rules! declare_custom_attr_inner {
+ ($t:ident, $T:ty, $name:literal, $new_fn:ident) => {
+ pub const $t: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed($name),
+ Value::Vector(VectorValue::$new_fn(<$T>::ZERO)),
+ );
+ };
+}
+
+macro_rules! declare_custom_attr_u32_inner {
+ ($t:ident, $name:literal, $scalar_type:ident) => {
+ pub const $t: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed($name),
+ Value::Scalar(ScalarValue::$scalar_type(0)),
+ );
+ };
+}
+
+impl AttributeInner {
+ pub const ID: &'static AttributeInner =
+ &AttributeInner::new(Cow::Borrowed("id"), Value::Scalar(ScalarValue::Uint(0)));
+
+ pub const PARTICLE_COUNTER: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("particle_counter"),
+ Value::Scalar(ScalarValue::Uint(0)),
+ );
+
+ pub const POSITION: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("position"),
+ Value::Vector(VectorValue::new_vec3(Vec3::ZERO)),
+ );
+
+ pub const VELOCITY: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("velocity"),
+ Value::Vector(VectorValue::new_vec3(Vec3::ZERO)),
+ );
+
+ pub const AGE: &'static AttributeInner =
+ &AttributeInner::new(Cow::Borrowed("age"), Value::Scalar(ScalarValue::Float(0.)));
+
+ pub const LIFETIME: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("lifetime"),
+ Value::Scalar(ScalarValue::Float(1.)),
+ );
+
+ pub const COLOR: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("color"),
+ Value::Scalar(ScalarValue::Uint(0xFFFFFFFFu32)),
+ );
+
+ pub const HDR_COLOR: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("hdr_color"),
+ Value::Vector(VectorValue::new_vec4(Vec4::ONE)),
+ );
+
+ pub const ALPHA: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("alpha"),
+ Value::Scalar(ScalarValue::Float(1.)),
+ );
+
+ pub const SIZE: &'static AttributeInner =
+ &AttributeInner::new(Cow::Borrowed("size"), Value::Scalar(ScalarValue::Float(1.)));
+
+ pub const SIZE2: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("size2"),
+ Value::Vector(VectorValue::new_vec2(Vec2::ONE)),
+ );
+
+ pub const SIZE3: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("size3"),
+ Value::Vector(VectorValue::new_vec3(Vec3::ONE)),
+ );
+
+ pub const PREV: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("prev"),
+ Value::Scalar(ScalarValue::Uint(!0u32)),
+ );
+
+ pub const NEXT: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("next"),
+ Value::Scalar(ScalarValue::Uint(!0u32)),
+ );
+
+ pub const AXIS_X: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("axis_x"),
+ Value::Vector(VectorValue::new_vec3(Vec3::X)),
+ );
+
+ pub const AXIS_Y: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("axis_y"),
+ Value::Vector(VectorValue::new_vec3(Vec3::Y)),
+ );
+
+ pub const AXIS_Z: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("axis_z"),
+ Value::Vector(VectorValue::new_vec3(Vec3::Z)),
+ );
+
+ pub const SPRITE_INDEX: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("sprite_index"),
+ Value::Scalar(ScalarValue::Int(0)),
+ );
+
+ pub const F32_0: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("f32_0"),
+ Value::Scalar(ScalarValue::Float(0.)),
+ );
+
+ pub const F32_1: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("f32_1"),
+ Value::Scalar(ScalarValue::Float(0.)),
+ );
+
+ pub const F32_2: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("f32_2"),
+ Value::Scalar(ScalarValue::Float(0.)),
+ );
+
+ pub const F32_3: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("f32_3"),
+ Value::Scalar(ScalarValue::Float(0.)),
+ );
+
+ pub const F32_4: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("f32_4"),
+ Value::Scalar(ScalarValue::Float(0.)),
+ );
+
+ pub const F32_5: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("f32_5"),
+ Value::Scalar(ScalarValue::Float(0.)),
+ );
+
+ pub const F32_6: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("f32_6"),
+ Value::Scalar(ScalarValue::Float(0.)),
+ );
+
+ pub const F32_7: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("f32_7"),
+ Value::Scalar(ScalarValue::Float(0.)),
+ );
+
+ declare_custom_attr_inner!(F32X2_0, Vec2, "f32x2_0", new_vec2);
+ declare_custom_attr_inner!(F32X2_1, Vec2, "f32x2_1", new_vec2);
+ declare_custom_attr_inner!(F32X2_2, Vec2, "f32x2_2", new_vec2);
+ declare_custom_attr_inner!(F32X2_3, Vec2, "f32x2_3", new_vec2);
+ declare_custom_attr_inner!(F32X2_4, Vec2, "f32x2_4", new_vec2);
+ declare_custom_attr_inner!(F32X2_5, Vec2, "f32x2_5", new_vec2);
+ declare_custom_attr_inner!(F32X2_6, Vec2, "f32x2_6", new_vec2);
+ declare_custom_attr_inner!(F32X2_7, Vec2, "f32x2_7", new_vec2);
+ declare_custom_attr_inner!(F32X3_0, Vec3, "f32x3_0", new_vec3);
+ declare_custom_attr_inner!(F32X3_1, Vec3, "f32x3_1", new_vec3);
+ declare_custom_attr_inner!(F32X3_2, Vec3, "f32x3_2", new_vec3);
+ declare_custom_attr_inner!(F32X3_3, Vec3, "f32x3_3", new_vec3);
+ declare_custom_attr_inner!(F32X3_4, Vec3, "f32x3_4", new_vec3);
+ declare_custom_attr_inner!(F32X3_5, Vec3, "f32x3_5", new_vec3);
+ declare_custom_attr_inner!(F32X3_6, Vec3, "f32x3_6", new_vec3);
+ declare_custom_attr_inner!(F32X3_7, Vec3, "f32x3_7", new_vec3);
+ declare_custom_attr_inner!(F32X4_0, Vec4, "f32x4_0", new_vec4);
+ declare_custom_attr_inner!(F32X4_1, Vec4, "f32x4_1", new_vec4);
+ declare_custom_attr_inner!(F32X4_2, Vec4, "f32x4_2", new_vec4);
+ declare_custom_attr_inner!(F32X4_3, Vec4, "f32x4_3", new_vec4);
+ declare_custom_attr_inner!(F32X4_4, Vec4, "f32x4_4", new_vec4);
+ declare_custom_attr_inner!(F32X4_5, Vec4, "f32x4_5", new_vec4);
+ declare_custom_attr_inner!(F32X4_6, Vec4, "f32x4_6", new_vec4);
+ declare_custom_attr_inner!(F32X4_7, Vec4, "f32x4_7", new_vec4);
+
+ declare_custom_attr_u32_inner!(U32_0, "u32_0", Uint);
+ declare_custom_attr_u32_inner!(U32_1, "u32_1", Uint);
+ declare_custom_attr_u32_inner!(U32_2, "u32_2", Uint);
+ declare_custom_attr_u32_inner!(U32_3, "u32_3", Uint);
+ declare_custom_attr_u32_inner!(U32_4, "u32_4", Uint);
+ declare_custom_attr_u32_inner!(U32_5, "u32_5", Uint);
+ declare_custom_attr_u32_inner!(U32_6, "u32_6", Uint);
+ declare_custom_attr_u32_inner!(U32_7, "u32_7", Uint);
+
+ pub const RIBBON_ID: &'static AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("ribbon_id"),
+ Value::Scalar(ScalarValue::Uint(0u32)),
+ );
+
+ pub(crate) const PAD0: &'static AttributeInner =
+ &AttributeInner::new(Cow::Borrowed("pad0"), Value::Scalar(ScalarValue::Uint(0)));
+ pub(crate) const PAD1: &'static AttributeInner =
+ &AttributeInner::new(Cow::Borrowed("pad1"), Value::Scalar(ScalarValue::Uint(0)));
+ pub(crate) const PAD2: &'static AttributeInner =
+ &AttributeInner::new(Cow::Borrowed("pad2"), Value::Scalar(ScalarValue::Uint(0)));
+ pub(crate) const PAD3: &'static AttributeInner =
+ &AttributeInner::new(Cow::Borrowed("pad3"), Value::Scalar(ScalarValue::Uint(0)));
+ pub(crate) const PAD4: &'static AttributeInner =
+ &AttributeInner::new(Cow::Borrowed("pad4"), Value::Scalar(ScalarValue::Uint(0)));
+
+ #[inline]
+ pub(crate) const fn new(name: Cow<'static, str>, default_value: Value) -> Self {
+ Self {
+ name,
+ default_value,
+ }
+ }
+}
+
+/// An attribute of a particle simulated for an effect.
+///
+/// Effects are composed of many simulated particles. Each particle is in turn
+/// composed of a set of attributes, which are used to simulate and render it.
+/// Common attributes include the particle's position, its age, or its color.
+/// See [`Attribute::all()`] for a list of supported attributes. User-created
+/// attributes are not supported.
+///
+/// See also the [`attributes` module](crate::attributes) documentation for more
+/// details about particle attributes.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(try_from = "&str", into = "&'static str")]
+pub struct Attribute(pub(crate) &'static AttributeInner);
+
+impl TryFrom<&str> for Attribute {
+ type Error = &'static str;
+
+ fn try_from(value: &str) -> Result<Self, Self::Error> {
+ Attribute::from_name(value).ok_or("Unknown attribute name.")
+ }
+}
+
+impl From<Attribute> for &'static str {
+ fn from(value: Attribute) -> Self {
+ value.name()
+ }
+}
+
+impl TypePath for Attribute {
+ fn type_path() -> &'static str {
+ static CELL: GenericTypePathCell = GenericTypePathCell::new();
+ CELL.get_or_insert::<Self, _>(|| "bevy_hanabi::attribute::Attribute".to_owned())
+ }
+
+ fn short_type_path() -> &'static str {
+ static CELL: GenericTypePathCell = GenericTypePathCell::new();
+ CELL.get_or_insert::<Self, _>(|| "Attribute".to_owned())
+ }
+
+ fn type_ident() -> Option<&'static str> {
+ Some("Attribute")
+ }
+
+ fn crate_name() -> Option<&'static str> {
+ Some("bevy_hanabi")
+ }
+
+ fn module_path() -> Option<&'static str> {
+ Some("bevy_hanabi::attribute")
+ }
+}
+
+impl Typed for Attribute {
+ fn type_info() -> &'static TypeInfo {
+ static CELL: NonGenericTypeInfoCell = NonGenericTypeInfoCell::new();
+ CELL.get_or_set(|| {
+ let fields = [
+ NamedField::new::<Cow<str>>("name"),
+ NamedField::new::<Value>("default_value"),
+ ];
+ let info = StructInfo::new::<Self>(&fields);
+ TypeInfo::Struct(info)
+ })
+ }
+}
+
+impl Struct for Attribute {
+ fn field(&self, name: &str) -> Option<&dyn PartialReflect> {
+ match name {
+ "name" => Some(&self.0.name),
+ "default_value" => Some(&self.0.default_value),
+ _ => None,
+ }
+ }
+
+ fn field_mut(&mut self, _name: &str) -> Option<&mut dyn PartialReflect> {
+ // Attributes are immutable
+ None
+ }
+
+ fn field_at(&self, index: usize) -> Option<&dyn PartialReflect> {
+ match index {
+ 0 => Some(&self.0.name),
+ 1 => Some(&self.0.default_value),
+ _ => None,
+ }
+ }
+
+ fn field_at_mut(&mut self, _index: usize) -> Option<&mut dyn PartialReflect> {
+ // Attributes are immutable
+ None
+ }
+
+ fn name_at(&self, index: usize) -> Option<&str> {
+ match index {
+ 0 => Some("name"),
+ 1 => Some("default_value"),
+ _ => None,
+ }
+ }
+
+ fn index_of_name(&self, name: &str) -> Option<usize> {
+ match name {
+ "name" => Some(0),
+ "default_value" => Some(1),
+ _ => None,
+ }
+ }
+
+ fn field_len(&self) -> usize {
+ 2
+ }
+
+ fn iter_fields(&self) -> FieldIter<'_> {
+ FieldIter::new(self)
+ }
+}
+
+impl GetTypeRegistration for Attribute {
+ fn get_type_registration() -> TypeRegistration {
+ let mut registration = TypeRegistration::of::<Self>();
+ registration.insert::<ReflectDeserialize>(CreateTypeData::<Self>::create_type_data(()));
+ registration.insert::<ReflectSerialize>(CreateTypeData::<Self>::create_type_data(()));
+ registration.insert::<ReflectFromReflect>(CreateTypeData::<Self>::create_type_data(()));
+ registration
+ }
+}
+
+impl PartialReflect for Attribute {
+ fn get_represented_type_info(&self) -> Option<&'static TypeInfo> {
+ Some(<Self as Typed>::type_info())
+ }
+
+ #[inline]
+ fn into_partial_reflect(self: Box<Self>) -> Box<dyn PartialReflect> {
+ self
+ }
+
+ #[inline]
+ fn as_partial_reflect(&self) -> &dyn PartialReflect {
+ self
+ }
+
+ #[inline]
+ fn as_partial_reflect_mut(&mut self) -> &mut dyn PartialReflect {
+ self
+ }
+
+ #[inline]
+ fn try_into_reflect(self: Box<Self>) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>> {
+ Ok(self)
+ }
+
+ #[inline]
+ fn try_as_reflect(&self) -> Option<&dyn Reflect> {
+ Some(self)
+ }
+
+ #[inline]
+ fn try_as_reflect_mut(&mut self) -> Option<&mut dyn Reflect> {
+ Some(self)
+ }
+
+ fn try_apply(&mut self, value: &dyn PartialReflect) -> Result<(), ApplyError> {
+ if let Some(value) = value.try_downcast_ref::<Self>() {
+ *self = *value;
+ Ok(())
+ } else {
+ Err(ApplyError::MismatchedTypes {
+ from_type: value.reflect_type_path().into(),
+ to_type: Self::type_path().into(),
+ })
+ }
+ }
+
+ #[inline]
+ fn reflect_ref(&self) -> ReflectRef<'_> {
+ ReflectRef::Struct(self)
+ }
+
+ #[inline]
+ fn reflect_mut(&mut self) -> ReflectMut<'_> {
+ ReflectMut::Struct(self)
+ }
+
+ #[inline]
+ fn reflect_owned(self: Box<Self>) -> ReflectOwned {
+ ReflectOwned::Struct(self)
+ }
+}
+
+impl Reflect for Attribute {
+ #[inline]
+ fn into_any(self: Box<Self>) -> Box<dyn Any> {
+ self
+ }
+
+ #[inline]
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ #[inline]
+ fn as_any_mut(&mut self) -> &mut dyn Any {
+ self
+ }
+
+ #[inline]
+ fn into_reflect(self: Box<Self>) -> Box<dyn Reflect> {
+ self
+ }
+
+ #[inline]
+ fn as_reflect(&self) -> &dyn Reflect {
+ self
+ }
+
+ #[inline]
+ fn as_reflect_mut(&mut self) -> &mut dyn Reflect {
+ self
+ }
+
+ #[inline]
+ fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>> {
+ *self = value.take()?;
+ Ok(())
+ }
+}
+
+impl FromReflect for Attribute {
+ fn from_reflect(reflect: &dyn PartialReflect) -> Option<Self> {
+ Attribute::from_name(
+ reflect
+ .try_as_reflect()?
+ .as_any()
+ .downcast_ref::<String>()?,
+ )
+ }
+}
+
+macro_rules! declare_custom_attr_pub {
+ ($t: ident, $name: literal, $count: literal, $vector_type: ident) => {
+ #[doc = concat!("A generic vector float attribute with ", $count, " components.\n\n This attribute can be used for anything. It has no specific meaning. You can store whatever per-particle value you want in it (for example, at spawn time) and read it back later.\n\n# Name\n\n`", $name, "`\n\n# Type\n\n[`VectorType::", stringify!($vector_type), "`]")]
+ pub const $t: Attribute = Attribute(AttributeInner::$t);
+ };
+}
+
+macro_rules! declare_custom_attr_u32_pub {
+ ($t: ident, $name: literal, $scalar_type: ident) => {
+ #[doc = concat!("A generic scalar uint attribute.\n\n This attribute can be used for anything. It has no specific meaning. You can store whatever per-particle value you want in it (for example, at spawn time) and read it back later.\n\n# Name\n\n`", $name, "`\n\n# Type\n\n[`ScalarType::", stringify!($scalar_type), "`]")]
+ pub const $t: Attribute = Attribute(AttributeInner::$t);
+ };
+}
+
+impl Attribute {
+ /// The particle unique ID.
+ ///
+ /// This is a pseudo-attribute, which doesn't require any storage in the
+ /// particle layout, and is always available. It can be read but cannot be
+ /// set. The particle ID is guaranteed to be unique within a single
+ /// effect instance only; particles from different instances may have
+ /// the same ID.
+ ///
+ /// # Name
+ ///
+ /// `id`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Uint`]
+ pub const ID: Attribute = Attribute(AttributeInner::ID);
+
+ /// A monotonically increasing counter.
+ ///
+ /// This is a pseudo-attribute, which doesn't require any storage in the
+ /// particle layout, and is always available. It can be read but cannot be
+ /// set. The counter is guaranteed to be unique each time a new particle
+ /// spawns. It may loop after 2^32 values, but unless you store that value
+ /// for a very long time you can consider the value unique.
+ ///
+ /// # Name
+ ///
+ /// `particle_counter`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Uint`]
+ pub const PARTICLE_COUNTER: Attribute = Attribute(AttributeInner::PARTICLE_COUNTER);
+
+ /// The particle position in [simulation space].
+ ///
+ /// # Name
+ ///
+ /// `position`
+ ///
+ /// # Type
+ ///
+ /// [`VectorType::VEC3F`] representing the XYZ coordinates of the position.
+ ///
+ /// [simulation space]: crate::SimulationSpace
+ pub const POSITION: Attribute = Attribute(AttributeInner::POSITION);
+
+ /// The particle velocity in [simulation space].
+ ///
+ /// # Name
+ ///
+ /// `velocity`
+ ///
+ /// # Type
+ ///
+ /// [`VectorType::VEC3F`] representing the XYZ coordinates of the velocity.
+ ///
+ /// [simulation space]: crate::SimulationSpace
+ pub const VELOCITY: Attribute = Attribute(AttributeInner::VELOCITY);
+
+ /// The age of the particle.
+ ///
+ /// Each time the particle is updated, the current simulation delta time is
+ /// added to the particle's age. The age can be used to animate some other
+ /// quantities; see the [`ColorOverLifetimeModifier`] for example.
+ ///
+ /// If the particle also has a lifetime (either a per-effect
+ /// constant value, or a per-particle value stored in the
+ /// [`Attribute::LIFETIME`] attribute), then when the age of the particle
+ /// exceeds its lifetime, the particle dies and is not simulated nor
+ /// rendered anymore.
+ ///
+ /// # Name
+ ///
+ /// `age`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Float`]
+ ///
+ /// [`ColorOverLifetimeModifier`]: crate::modifier::output::ColorOverLifetimeModifier
+ pub const AGE: Attribute = Attribute(AttributeInner::AGE);
+
+ /// The lifetime of the particle.
+ ///
+ /// This attribute stores a per-particle lifetime, which compared to the
+ /// particle's age allows determining if the particle needs to be
+ /// simulated and rendered. This requires the [`Attribute::AGE`]
+ /// attribute to be used too.
+ ///
+ /// # Name
+ ///
+ /// `lifetime`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Float`]
+ pub const LIFETIME: Attribute = Attribute(AttributeInner::LIFETIME);
+
+ /// The particle's base color.
+ ///
+ /// This attribute stores a per-particle color, which can be used for
+ /// various purposes, generally as the base color for rendering the
+ /// particle.
+ ///
+ /// # Name
+ ///
+ /// `color`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Uint`] representing the RGBA components of the color
+ /// encoded as `0xAABBGGRR`, with a single byte per component, where the
+ /// alpha value is stored in the most significant byte and the red value in
+ /// the least significant byte. Note that this representation is the
+ /// same as the one returned by [`LinearRgba::as_u32()`].
+ ///
+ /// [`LinearRgba::as_u32()`]: bevy::color::LinearRgba::as_u32
+ pub const COLOR: Attribute = Attribute(AttributeInner::COLOR);
+
+ /// The particle's base color (HDR).
+ ///
+ /// This attribute stores a per-particle HDR color, which can be used for
+ /// various purposes, generally as the base color for rendering the
+ /// particle.
+ ///
+ /// # Name
+ ///
+ /// `hdr_color`
+ ///
+ /// # Type
+ ///
+ /// [`VectorType::VEC4F`] representing the RGBA components of the color.
+ /// Values are not clamped, and can be outside the \[0:1\] range to
+ /// represent HDR values.
+ pub const HDR_COLOR: Attribute = Attribute(AttributeInner::HDR_COLOR);
+
+ /// The particle's opacity (alpha).
+ ///
+ /// This is a value in \[0:1\], where `0` corresponds to a fully transparent
+ /// particle, and `1` to a fully opaque one.
+ ///
+ /// # Name
+ ///
+ /// `alpha`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Float`]
+ pub const ALPHA: Attribute = Attribute(AttributeInner::ALPHA);
+
+ /// The particle's uniform size.
+ ///
+ /// The particle is uniformly scaled by this size.
+ ///
+ /// # Name
+ ///
+ /// `size`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Float`]
+ pub const SIZE: Attribute = Attribute(AttributeInner::SIZE);
+
+ /// The particle's 2D size.
+ ///
+ /// The particle is scaled along its local X and Y axes by these values. The
+ /// Z axis is unaffected.
+ ///
+ /// # Name
+ ///
+ /// `size2`
+ ///
+ /// # Type
+ ///
+ /// [`VectorType::VEC2F`] representing the XY sizes of the particle.
+ pub const SIZE2: Attribute = Attribute(AttributeInner::SIZE2);
+
+ /// The particle's 3D size.
+ ///
+ /// The particle is scaled along its local X, Y, and Z axes by these values.
+ ///
+ /// # Name
+ ///
+ /// `size3`
+ ///
+ /// # Type
+ ///
+ /// [`VectorType::VEC3F`] representing the XYZ sizes of the particle.
+ pub const SIZE3: Attribute = Attribute(AttributeInner::SIZE3);
+
+ /// The previous particle in the ribbon chain.
+ ///
+ /// This is only present if there's a ribbon. Since there's only one linked
+ /// list, we support at most one ribbon per effect.
+ ///
+ /// # Name
+ ///
+ /// `prev`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Uint`] representing the index of the previous particle in
+ /// the chain.
+ pub const PREV: Attribute = Attribute(AttributeInner::PREV);
+
+ /// The next particle in the ribbon chain.
+ ///
+ /// This is only present if there's a ribbon. Since there's only one linked
+ /// list, we support at most one ribbon per effect.
+ ///
+ /// # Name
+ ///
+ /// `next`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Uint`] representing the index of the next particle in the
+ /// chain.
+ pub const NEXT: Attribute = Attribute(AttributeInner::NEXT);
+
+ /// The local X axis of the particle.
+ ///
+ /// This attribute stores a per-particle X axis, which defines the
+ /// horizontal direction of a quad particle. This is generally used to
+ /// re-orient the particle during rendering, for example to face the camera
+ /// or another point of interest. For example, the [`OrientModifier`]
+ /// modifies this attribute to make the particle face a specific item.
+ ///
+ /// # Name
+ ///
+ /// `axis_x`
+ ///
+ /// # Type
+ ///
+ /// [`VectorType::VEC3F`]
+ ///
+ /// [`OrientModifier`]: crate::modifier::output::OrientModifier
+ pub const AXIS_X: Attribute = Attribute(AttributeInner::AXIS_X);
+
+ /// The local Y axis of the particle.
+ ///
+ /// This attribute stores a per-particle Y axis, which defines the vertical
+ /// direction of a quad particle. This is generally used to re-orient the
+ /// particle during rendering, for example to face the camera or another
+ /// point of interest. For example, the [`OrientModifier`] modifies this
+ /// attribute to make the particle face a specific item.
+ ///
+ /// # Name
+ ///
+ /// `axis_y`
+ ///
+ /// # Type
+ ///
+ /// [`VectorType::VEC3F`]
+ ///
+ /// [`OrientModifier`]: crate::modifier::output::OrientModifier
+ pub const AXIS_Y: Attribute = Attribute(AttributeInner::AXIS_Y);
+
+ /// The local Z axis of the particle.
+ ///
+ /// This attribute stores a per-particle Z axis, which defines the normal to
+ /// a quad particle's plane. This is generally used to re-orient the
+ /// particle during rendering, for example to face the camera or another
+ /// point of interest. For example, the [`OrientModifier`] modifies this
+ /// attribute to make the particle face a specific item.
+ ///
+ /// # Name
+ ///
+ /// `axis_z`
+ ///
+ /// # Type
+ ///
+ /// [`VectorType::VEC3F`]
+ ///
+ /// [`OrientModifier`]: crate::modifier::output::OrientModifier
+ pub const AXIS_Z: Attribute = Attribute(AttributeInner::AXIS_Z);
+
+ /// The sprite index in a flipbook animation.
+ ///
+ /// This attribute stores the index of the sprite of a flipbook animation.
+ /// This is used with the [`FlipbookModifier`].
+ ///
+ /// # Name
+ ///
+ /// `sprite_index`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Int`]
+ ///
+ /// [`FlipbookModifier`]: crate::modifier::output::FlipbookModifier
+ pub const SPRITE_INDEX: Attribute = Attribute(AttributeInner::SPRITE_INDEX);
+
+ /// A generic scalar float attribute.
+ ///
+ /// This attribute can be used for anything. It has no specific meaning. You
+ /// can store whatever per-particle value you want in it (for example, at
+ /// spawn time) and read it back later.
+ ///
+ /// # Name
+ ///
+ /// `f32_0`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Float`]
+ pub const F32_0: Attribute = Attribute(AttributeInner::F32_0);
+
+ /// A generic scalar float attribute.
+ ///
+ /// This attribute can be used for anything. It has no specific meaning. You
+ /// can store whatever per-particle value you want in it (for example, at
+ /// spawn time) and read it back later.
+ ///
+ /// # Name
+ ///
+ /// `f32_1`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Float`]
+ pub const F32_1: Attribute = Attribute(AttributeInner::F32_1);
+
+ /// A generic scalar float attribute.
+ ///
+ /// This attribute can be used for anything. It has no specific meaning. You
+ /// can store whatever per-particle value you want in it (for example, at
+ /// spawn time) and read it back later.
+ ///
+ /// # Name
+ ///
+ /// `f32_2`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Float`]
+ pub const F32_2: Attribute = Attribute(AttributeInner::F32_2);
+
+ /// A generic scalar float attribute.
+ ///
+ /// This attribute can be used for anything. It has no specific meaning. You
+ /// can store whatever per-particle value you want in it (for example, at
+ /// spawn time) and read it back later.
+ ///
+ /// # Name
+ ///
+ /// `f32_3`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Float`]
+ pub const F32_3: Attribute = Attribute(AttributeInner::F32_3);
+
+ /// A generic scalar float attribute.
+ ///
+ /// This attribute can be used for anything. It has no specific meaning. You
+ /// can store whatever per-particle value you want in it (for example, at
+ /// spawn time) and read it back later.
+ ///
+ /// # Name
+ ///
+ /// `f32_4`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Float`]
+ pub const F32_4: Attribute = Attribute(AttributeInner::F32_4);
+
+ /// A generic scalar float attribute.
+ ///
+ /// This attribute can be used for anything. It has no specific meaning. You
+ /// can store whatever per-particle value you want in it (for example, at
+ /// spawn time) and read it back later.
+ ///
+ /// # Name
+ ///
+ /// `f32_5`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Float`]
+ pub const F32_5: Attribute = Attribute(AttributeInner::F32_5);
+
+ /// A generic scalar float attribute.
+ ///
+ /// This attribute can be used for anything. It has no specific meaning. You
+ /// can store whatever per-particle value you want in it (for example, at
+ /// spawn time) and read it back later.
+ ///
+ /// # Name
+ ///
+ /// `f32_6`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Float`]
+ pub const F32_6: Attribute = Attribute(AttributeInner::F32_6);
+
+ /// A generic scalar float attribute.
+ ///
+ /// This attribute can be used for anything. It has no specific meaning. You
+ /// can store whatever per-particle value you want in it (for example, at
+ /// spawn time) and read it back later.
+ ///
+ /// # Name
+ ///
+ /// `f32_7`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Float`]
+ pub const F32_7: Attribute = Attribute(AttributeInner::F32_7);
+
+ declare_custom_attr_pub!(F32X2_0, "f32x2_0", 2, VEC2F);
+ declare_custom_attr_pub!(F32X2_1, "f32x2_1", 2, VEC2F);
+ declare_custom_attr_pub!(F32X2_2, "f32x2_2", 2, VEC2F);
+ declare_custom_attr_pub!(F32X2_3, "f32x2_3", 2, VEC2F);
+ declare_custom_attr_pub!(F32X2_4, "f32x2_4", 2, VEC2F);
+ declare_custom_attr_pub!(F32X2_5, "f32x2_5", 2, VEC2F);
+ declare_custom_attr_pub!(F32X2_6, "f32x2_6", 2, VEC2F);
+ declare_custom_attr_pub!(F32X2_7, "f32x2_7", 2, VEC2F);
+ declare_custom_attr_pub!(F32X3_0, "f32x3_0", 3, VEC3F);
+ declare_custom_attr_pub!(F32X3_1, "f32x3_1", 3, VEC3F);
+ declare_custom_attr_pub!(F32X3_2, "f32x3_2", 3, VEC3F);
+ declare_custom_attr_pub!(F32X3_3, "f32x3_3", 3, VEC3F);
+ declare_custom_attr_pub!(F32X3_4, "f32x3_4", 3, VEC3F);
+ declare_custom_attr_pub!(F32X3_5, "f32x3_5", 3, VEC3F);
+ declare_custom_attr_pub!(F32X3_6, "f32x3_6", 3, VEC3F);
+ declare_custom_attr_pub!(F32X3_7, "f32x3_7", 3, VEC3F);
+ declare_custom_attr_pub!(F32X4_0, "f32x4_0", 4, VEC4F);
+ declare_custom_attr_pub!(F32X4_1, "f32x4_1", 4, VEC4F);
+ declare_custom_attr_pub!(F32X4_2, "f32x4_2", 4, VEC4F);
+ declare_custom_attr_pub!(F32X4_3, "f32x4_3", 4, VEC4F);
+ declare_custom_attr_pub!(F32X4_4, "f32x4_4", 4, VEC4F);
+ declare_custom_attr_pub!(F32X4_5, "f32x4_5", 4, VEC4F);
+ declare_custom_attr_pub!(F32X4_6, "f32x4_6", 4, VEC4F);
+ declare_custom_attr_pub!(F32X4_7, "f32x4_7", 4, VEC4F);
+
+ declare_custom_attr_u32_pub!(U32_0, "u32_0", Uint);
+ declare_custom_attr_u32_pub!(U32_1, "u32_1", Uint);
+ declare_custom_attr_u32_pub!(U32_2, "u32_2", Uint);
+ declare_custom_attr_u32_pub!(U32_3, "u32_3", Uint);
+ declare_custom_attr_u32_pub!(U32_4, "u32_4", Uint);
+ declare_custom_attr_u32_pub!(U32_5, "u32_5", Uint);
+ declare_custom_attr_u32_pub!(U32_6, "u32_6", Uint);
+ declare_custom_attr_u32_pub!(U32_7, "u32_7", Uint);
+
+ /// ID of the ribbon a particle is part of.
+ ///
+ /// This attribute is used to group particles together by ribbon.
+ ///
+ /// # Name
+ ///
+ /// `ribbon_id`
+ ///
+ /// # Type
+ ///
+ /// [`ScalarType::Uint`]
+ pub const RIBBON_ID: Attribute = Attribute(AttributeInner::RIBBON_ID);
+
+ /// Collection of all the existing particle attributes.
+ const ALL: [Attribute; 59] = [
+ Attribute::ID,
+ Attribute::PARTICLE_COUNTER,
+ Attribute::POSITION,
+ Attribute::VELOCITY,
+ Attribute::AGE,
+ Attribute::LIFETIME,
+ Attribute::COLOR,
+ Attribute::HDR_COLOR,
+ Attribute::ALPHA,
+ Attribute::SIZE,
+ Attribute::SIZE2,
+ Attribute::SIZE3,
+ Attribute::PREV,
+ Attribute::NEXT,
+ Attribute::AXIS_X,
+ Attribute::AXIS_Y,
+ Attribute::AXIS_Z,
+ Attribute::SPRITE_INDEX,
+ Attribute::F32_0,
+ Attribute::F32_1,
+ Attribute::F32_2,
+ Attribute::F32_3,
+ Attribute::F32_4,
+ Attribute::F32_5,
+ Attribute::F32_6,
+ Attribute::F32_7,
+ Attribute::F32X2_0,
+ Attribute::F32X2_1,
+ Attribute::F32X2_2,
+ Attribute::F32X2_3,
+ Attribute::F32X2_4,
+ Attribute::F32X2_5,
+ Attribute::F32X2_6,
+ Attribute::F32X2_7,
+ Attribute::F32X3_0,
+ Attribute::F32X3_1,
+ Attribute::F32X3_2,
+ Attribute::F32X3_3,
+ Attribute::F32X3_4,
+ Attribute::F32X3_5,
+ Attribute::F32X3_6,
+ Attribute::F32X3_7,
+ Attribute::F32X4_0,
+ Attribute::F32X4_1,
+ Attribute::F32X4_2,
+ Attribute::F32X4_3,
+ Attribute::F32X4_4,
+ Attribute::F32X4_5,
+ Attribute::F32X4_6,
+ Attribute::F32X4_7,
+ Attribute::U32_0,
+ Attribute::U32_1,
+ Attribute::U32_2,
+ Attribute::U32_3,
+ Attribute::U32_4,
+ Attribute::U32_5,
+ Attribute::U32_6,
+ Attribute::U32_7,
+ Attribute::RIBBON_ID,
+ ];
+
+ // Internal fake attributes used for padding structs.
+ pub(crate) const PAD0: Attribute = Attribute(AttributeInner::PAD0);
+ pub(crate) const PAD1: Attribute = Attribute(AttributeInner::PAD1);
+ pub(crate) const PAD2: Attribute = Attribute(AttributeInner::PAD2);
+ pub(crate) const PAD3: Attribute = Attribute(AttributeInner::PAD3);
+ pub(crate) const PAD4: Attribute = Attribute(AttributeInner::PAD4);
+
+ /// Retrieve an attribute by its name.
+ ///
+ /// See [`Attribute::all()`] for the list of attributes, and the
+ /// [`Attribute::name()`] method of each attribute for their name.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let attr = Attribute::from_name("position").unwrap();
+ /// assert_eq!(attr, Attribute::POSITION);
+ /// ```
+ pub fn from_name(name: &str) -> Option<Attribute> {
+ Attribute::ALL
+ .iter()
+ .find(|&attr| attr.name() == name)
+ .copied()
+ }
+
+ /// Get the list of all existing attributes.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// for attr in Attribute::all() {
+ /// println!("{}", attr.name());
+ /// }
+ /// ```
+ pub fn all() -> &'static [Attribute] {
+ &Self::ALL
+ }
+
+ /// The attribute's name.
+ ///
+ /// The name of an attribute is unique, and corresponds to the name of the
+ /// variable in the generated WGSL code.
+ #[inline]
+ pub fn name(&self) -> &'static str {
+ self.0.name.as_ref()
+ }
+
+ /// The attribute's default value.
+ #[inline]
+ pub fn default_value(&self) -> Value {
+ self.0.default_value
+ }
+
+ /// The attribute's type.
+ ///
+ /// This is a shortcut for `default_value().value_type()`.
+ #[inline]
+ pub fn value_type(&self) -> ValueType {
+ self.0.default_value.value_type()
+ }
+
+ /// Size of this attribute, in bytes.
+ ///
+ /// This is a shortcut for `value_type().size()`.
+ #[inline]
+ pub fn size(&self) -> usize {
+ self.value_type().size()
+ }
+
+ /// Alignment of this attribute, in bytes.
+ ///
+ /// This is a shortcut for `value_type().align()`.
+ #[inline]
+ pub fn align(&self) -> usize {
+ self.value_type().align()
+ }
+}
+
+/// Layout for a single [`Attribute`] inside a [`ParticleLayout`].
+#[derive(Clone, Copy, PartialEq, Eq, Hash)]
+pub struct AttributeLayout {
+ /// The particle attribute.
+ pub attribute: Attribute,
+ /// Offset, in bytes, from the start of the particle.
+ pub offset: u32,
+}
+
+impl std::fmt::Debug for AttributeLayout {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ // "(+offset) name: type"
+ f.write_fmt(format_args!(
+ "(+{}) {}: {}",
+ self.offset,
+ self.attribute.name(),
+ self.attribute.value_type().to_wgsl_string(),
+ ))
+ }
+}
+
+/// Builder helper to create a new [`ParticleLayout`].
+///
+/// Use [`ParticleLayout::new()`] to create a new empty builder.
+#[derive(Debug, Default, Clone)]
+pub struct ParticleLayoutBuilder {
+ layout: Vec<AttributeLayout>,
+}
+
+impl ParticleLayoutBuilder {
+ /// Add a new attribute to the layout builder.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let mut builder = ParticleLayout::new();
+ /// builder.append(Attribute::POSITION);
+ /// ```
+ pub fn append(mut self, attribute: Attribute) -> Self {
+ self.layout.push(AttributeLayout {
+ attribute,
+ offset: 0, // fixed up by build()
+ });
+ self
+ }
+
+ /// Finalize the builder pattern and build the layout from the existing
+ /// attributes.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let layout = ParticleLayout::new().append(Attribute::POSITION).build();
+ /// ```
+ pub fn build(mut self) -> ParticleLayout {
+ let pads = [
+ Attribute::PAD0,
+ Attribute::PAD1,
+ Attribute::PAD2,
+ Attribute::PAD3,
+ Attribute::PAD4,
+ ];
+ let mut next_pad = 0;
+
+ // Remove duplicates
+ self.layout.sort_unstable_by_key(|la| la.attribute.name());
+ self.layout.dedup_by_key(|la| la.attribute.name());
+
+ // Sort by size
+ self.layout.sort_unstable_by_key(|la| la.attribute.size());
+
+ let unpadded_len = self.layout.len() as u32;
+
+ let mut layout = vec![];
+ let mut offset = 0;
+ let mut align = 4; // min valid align
+
+ // Enqueue all Float4, which are already aligned
+ let index4 = self
+ .layout
+ .partition_point(|attr| attr.attribute.size() < 16);
+ for i in index4..self.layout.len() {
+ let mut attr = self.layout[i];
+ attr.offset = offset;
+ offset += 16;
+ layout.push(attr);
+ }
+ let num4 = self.layout.len() - index4;
+ if num4 > 0 {
+ align = 16;
+ }
+
+ let index2 = self
+ .layout
+ .partition_point(|attr| attr.attribute.size() < 8);
+ let num1 = index2;
+ let index3 = self
+ .layout
+ .partition_point(|attr| attr.attribute.size() < 12);
+ let num2 = (index2..index3).len();
+ let num3 = (index3..index4).len();
+ if num3 > 0 {
+ align = 16;
+ } else if num2 > 0 {
+ align = align.max(8);
+ }
+
+ // Enqueue paired { Float3 + Float1 }
+ let num_pairs = num1.min(num3);
+ for i in 0..num_pairs {
+ // Float3
+ let mut attr = self.layout[index3 + i];
+ attr.offset = offset;
+ offset += 12;
+ layout.push(attr);
+
+ // Float
+ let mut attr = self.layout[i];
+ attr.offset = offset;
+ offset += 4;
+ layout.push(attr);
+ }
+ let index1 = num_pairs;
+ let index3 = index3 + num_pairs;
+ let num1 = num1 - num_pairs;
+ let num3 = num3 - num_pairs;
+
+ // Enqueue paired { Float2 + Float2 }
+ for i in 0..(num2 / 2) {
+ for j in 0..2 {
+ let mut attr = self.layout[index2 + i * 2 + j];
+ attr.offset = offset;
+ offset += 8;
+ layout.push(attr);
+ }
+ }
+ let index2 = index2 + (num2 / 2) * 2;
+ let num2 = num2 % 2;
+
+ // Here we're aligned at 16 byte boundary. We have no more Float4, at most one
+ // Float2, and either some Float3 or some Float1 left (but never both).
+
+ // Enqueue all the Float3 if any, since it requires the largest align.
+ if num3 > 0 {
+ debug_assert_eq!(num1, 0);
+
+ for i in 0..num3 {
+ // The attribute itself
+ let mut attr = self.layout[index3 + i];
+ attr.offset = offset;
+ layout.push(attr);
+
+ // The 32-bit padding after it. We know we don't have any Float1 to pad so we
+ // need a dummy padding field.
+ let pad = AttributeLayout {
+ attribute: pads[next_pad],
+ offset: offset + 12,
+ };
+ next_pad += 1;
+ layout.push(pad);
+
+ offset += 16;
+ }
+ }
+
+ // Here we're aligned at 16 byte boundary. We have no more Float4, at most one
+ // Float2, and possibly some Float1 left.
+
+ // Enqueue the Float2 if any
+ if num2 > 0 {
+ debug_assert_eq!(num2, 1);
+
+ let mut attr = self.layout[index2];
+ attr.offset = offset;
+ offset += 8;
+ layout.push(attr);
+ }
+
+ // Enqueue all remaining Float1
+ for i in 0..num1 {
+ let mut attr = self.layout[index1 + i];
+ attr.offset = offset;
+ layout.push(attr);
+ offset += 4;
+ }
+
+ // Pad the struct to its align. This is mandatory to work around https://github.com/gfx-rs/wgpu/issues/5262.
+ let rem = offset.next_multiple_of(align) - offset;
+ if rem > 0 {
+ debug_assert_eq!(rem % 4, 0);
+ let num = rem / 4;
+ for _ in 0..num {
+ debug_assert!(next_pad < 3);
+ let pad = AttributeLayout {
+ attribute: pads[next_pad],
+ offset,
+ };
+ layout.push(pad);
+ next_pad += 1;
+ offset += 4;
+ }
+ }
+
+ ParticleLayout {
+ layout,
+ align,
+ unpadded_len,
+ }
+ }
+}
+
+impl From<&ParticleLayout> for ParticleLayoutBuilder {
+ fn from(layout: &ParticleLayout) -> Self {
+ Self {
+ layout: layout.layout.clone(),
+ }
+ }
+}
+
+/// Particle layout of an effect.
+///
+/// The particle layout describes the set of attributes used by the particles of
+/// an effect, and the relative positioning of those attributes inside the
+/// particle GPU buffer.
+///
+/// Effects with a compatible particle layout can be simulated or rendered
+/// together in a single call, therefore it is recommended to minimize the
+/// layout variations across effects and attempt to reuse the same layout for
+/// multiple effects, which can be benefical for performance.
+///
+/// # Construction
+///
+/// To create a particle layout you can either:
+/// - Use [`ParticleLayout::default()`] to create the default layout, which
+/// contains some default attributes commonly used for effects
+/// ([`Attribute::POSITION`], [`Attribute::VELOCITY`], [`Attribute::AGE`],
+/// [`Attribute::LIFETIME`]).
+/// - Use [`ParticleLayout::empty()`] to create an empty layout without any
+/// attribute.
+/// - Use [`ParticleLayout::new()`] to create a [`ParticleLayoutBuilder`] and
+/// append the necessary attributes manually then call [`build()`] to complete
+/// the layout.
+///
+/// [`build()`]: crate::ParticleLayoutBuilder::build
+#[derive(Clone, PartialEq, Eq, Hash)]
+pub struct ParticleLayout {
+ layout: Vec<AttributeLayout>,
+ align: u32,
+ unpadded_len: u32,
+}
+
+impl std::fmt::Debug for ParticleLayout {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ // Output a compact list of all layout entries
+ f.debug_list().entries(self.layout.iter()).finish()
+ }
+}
+
+impl Default for ParticleLayout {
+ fn default() -> Self {
+ // Default layout: { position, age, velocity, lifetime }
+ ParticleLayout::new()
+ .append(Attribute::POSITION)
+ .append(Attribute::AGE)
+ .append(Attribute::VELOCITY)
+ .append(Attribute::LIFETIME)
+ .build()
+ }
+}
+
+impl ParticleLayout {
+ /// Create an empty finalized layout.
+ ///
+ /// The layout is immutable. This is mostly used as a placeholder while a
+ /// valid layout is not available yet. To create a new non-finalized layout
+ /// which can be mutated, use [`ParticleLayout::new()`] instead.
+ pub const fn empty() -> ParticleLayout {
+ Self {
+ layout: vec![],
+ align: 4,
+ unpadded_len: 0,
+ }
+ }
+
+ /// Create a new empty layout.
+ ///
+ /// This returns a builder for the particle layout. Use
+ /// [`ParticleLayoutBuilder::build()`] to finalize the builder and create
+ /// the actual (immutable) [`ParticleLayout`].
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let layout = ParticleLayout::new()
+ /// .append(Attribute::POSITION)
+ /// .append(Attribute::AGE)
+ /// .append(Attribute::LIFETIME)
+ /// .build();
+ /// ```
+ #[allow(clippy::new_ret_no_self)]
+ pub fn new() -> ParticleLayoutBuilder {
+ ParticleLayoutBuilder::default()
+ }
+
+ /// Build a new particle layout from the current one merged with a new set
+ /// of attributes.
+ pub fn merged_with(
+ &self,
+ // attributes: impl IntoIterator<Item = Attribute>,
+ attributes: &[Attribute],
+ ) -> ParticleLayout {
+ let mut builder = ParticleLayoutBuilder::from(self);
+ // for attr in attributes.into_iter() {
+ for attr in attributes {
+ builder = builder.append(*attr);
+ }
+ builder.build()
+ }
+
+ /// Check if this layout is empty.
+ pub fn is_empty(&self) -> bool {
+ self.unpadded_len == 0
+ }
+
+ /// Get the number of fields in the layout.
+ ///
+ /// Note: if internal padding field need to be added to the final WGSL
+ /// struct, they're not counted here. This returns the number of unique
+ /// attributes added to the layout.
+ pub fn len(&self) -> u32 {
+ self.unpadded_len
+ }
+
+ /// Get the size of the layout in bytes.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let layout = ParticleLayout::new()
+ /// .append(Attribute::POSITION) // vec3<f32>
+ /// .build();
+ /// assert_eq!(layout.size(), 16);
+ /// ```
+ pub fn size(&self) -> u32 {
+ if self.layout.is_empty() {
+ 0
+ } else {
+ let last_attr = self.layout.last().unwrap();
+ last_attr.offset + last_attr.attribute.size() as u32
+ }
+ }
+
+ /// Get the alignment of the layout in bytes.
+ ///
+ /// The alignment follows the rules of WGSL.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let layout = ParticleLayout::new()
+ /// .append(Attribute::POSITION) // vec3<f32>
+ /// .build();
+ /// assert_eq!(layout.align(), 16);
+ /// ```
+ pub fn align(&self) -> u32 {
+ self.align
+ }
+
+ /// Minimum binding size in bytes.
+ ///
+ /// This corresponds to the stride of the attribute struct in WGSL when
+ /// contained inside an array.
+ pub fn min_binding_size(&self) -> NonZeroU64 {
+ let size = self.size();
+ NonZeroU64::new(size.next_multiple_of(self.align) as u64).unwrap()
+ }
+
+ /// Minimum binding size in bytes.
+ ///
+ /// This corresponds to the stride of the attribute struct in WGSL when
+ /// contained inside an array.
+ pub fn min_binding_size32(&self) -> NonZeroU32 {
+ let size = self.size();
+ NonZeroU32::new(size.next_multiple_of(self.align)).unwrap()
+ }
+
+ /// Get the list of attributes forming this layout.
+ pub fn attributes(&self) -> impl ExactSizeIterator<Item = &AttributeLayout> {
+ self.layout.iter()
+ }
+
+ /// Check if the layout contains the specified [`Attribute`].
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let layout = ParticleLayout::new().append(Attribute::SIZE).build();
+ /// let has_size = layout.contains(Attribute::SIZE);
+ /// assert!(has_size);
+ /// ```
+ pub fn contains(&self, attribute: Attribute) -> bool {
+ self.layout
+ .iter()
+ .any(|&entry| entry.attribute.name() == attribute.name())
+ }
+
+ /// Get the offset in bytes of the specified [`Attribute`], if it exists.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let layout = ParticleLayout::new()
+ /// .append(Attribute::POSITION)
+ /// .append(Attribute::SIZE)
+ /// .build();
+ /// let size_offset = layout.byte_offset(Attribute::SIZE);
+ /// assert_eq!(size_offset, Some(12));
+ /// ```
+ pub fn byte_offset(&self, attribute: Attribute) -> Option<u32> {
+ self.layout.iter().find_map(|&entry| {
+ if entry.attribute.name() == attribute.name() {
+ Some(entry.offset)
+ } else {
+ None
+ }
+ })
+ }
+
+ /// Generate the WGSL attribute code corresponding to the layout.
+ pub fn generate_code(&self) -> String {
+ // assert!(self.layout.is_sorted_by_key(|entry| entry.offset));
+ self.layout
+ .iter()
+ .map(|entry| {
+ format!(
+ " {}: {},",
+ entry.attribute.name(),
+ entry.attribute.value_type().to_wgsl_string()
+ )
+ })
+ .fold(String::new(), |mut a, b| {
+ a.reserve(b.len() + 1);
+ a.push_str(&b);
+ a.push('\n');
+ a
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use bevy::reflect::TypeRegistration;
+ use naga::{front::wgsl::Frontend, proc::Layouter};
+
+ use super::*;
+
+ // Ensure the size and alignment of all types conforms to the WGSL spec by
+ // querying naga as a reference.
+ #[test]
+ fn value_type_align() {
+ let mut frontend = Frontend::new();
+ for (value_type, value) in &[
+ (
+ ValueType::Scalar(ScalarType::Float),
+ Value::Scalar(ScalarValue::Float(0.)),
+ ),
+ // FIXME - We use a constant below, which has a size of 1 byte. For a field
+ // inside a struct, the size of bool is undefined in WGSL/naga, and 4 bytes
+ // in Hanabi. We probably can't test bool with naga here anyway.
+ // (
+ // ValueType::Scalar(ScalarType::Bool),
+ // Value::Scalar(ScalarValue::Bool(true)),
+ // ),
+ (
+ ValueType::Scalar(ScalarType::Int),
+ Value::Scalar(ScalarValue::Int(-42)),
+ ),
+ (
+ ValueType::Scalar(ScalarType::Uint),
+ Value::Scalar(ScalarValue::Uint(999)),
+ ),
+ (
+ ValueType::Vector(VectorType {
+ elem_type: ScalarType::Float,
+ count: 2,
+ }),
+ Value::Vector(VectorValue::new_vec2(Vec2::new(-0.5, 3.458))),
+ ),
+ (
+ ValueType::Vector(VectorType {
+ elem_type: ScalarType::Float,
+ count: 3,
+ }),
+ Value::Vector(VectorValue::new_vec3(Vec3::new(-0.5, 3.458, -53.))),
+ ),
+ (
+ ValueType::Vector(VectorType {
+ elem_type: ScalarType::Float,
+ count: 4,
+ }),
+ Value::Vector(VectorValue::new_vec4(Vec4::new(-0.5, 3.458, 0., -53.))),
+ ),
+ ] {
+ //assert_eq!(value.value_type(), *value_type);
+
+ // Create a tiny WGSL snippet with the Value(Type) and parse it
+ let src = format!("fn main() {{\nlet x = {};\n}}", value.to_wgsl_string());
+ let res = frontend.parse(&src);
+ if let Err(err) = &res {
+ println!("Error: {:?}", err);
+ }
+ assert!(res.is_ok());
+ let m = res.unwrap();
+ //println!("Module: {:?}", m);
+
+ // Retrieve the "x" constant and the size/align of its type
+ let (_main_handle, main) = m
+ .functions
+ .iter()
+ .find(|c| c.1.name == Some("main".to_string()))
+ .unwrap();
+ let (expr_handle, _expr_name) =
+ main.named_expressions.iter().find(|c| c.1 == "x").unwrap();
+ let expr = main.expressions.try_get(*expr_handle).unwrap();
+
+ match expr {
+ naga::ir::Expression::Literal(lit) => {
+ // For the literals we support, this is true.
+ assert_eq!(lit.width(), value_type.size() as u8);
+ assert_eq!(lit.width(), value_type.align() as u8);
+ }
+ naga::ir::Expression::Compose { ty, .. } => {
+ let (size, align) = {
+ // Calculate the type layout according to WGSL
+ let mut layouter = Layouter::default();
+ assert!(layouter.update(m.to_ctx()).is_ok());
+ let layout = layouter[*ty];
+ (layout.size, layout.alignment)
+ };
+
+ // Compare WGSL layout with the one of Value(Type)
+ assert_eq!(size, value_type.size() as u32);
+ assert_eq!(
+ align,
+ naga::proc::Alignment::new(value_type.align() as u32).unwrap()
+ );
+ }
+ _ => panic!(),
+ };
+ }
+ }
+
+ #[test]
+ fn value_type_is_numeric() {
+ assert!(!ScalarType::Bool.is_numeric());
+ assert!(ScalarType::Float.is_numeric());
+ assert!(ScalarType::Int.is_numeric());
+ assert!(ScalarType::Uint.is_numeric());
+
+ assert!(!VectorType::VEC2B.is_numeric());
+ assert!(!VectorType::VEC3B.is_numeric());
+ assert!(!VectorType::VEC4B.is_numeric());
+ assert!(VectorType::VEC2F.is_numeric());
+ assert!(VectorType::VEC3F.is_numeric());
+ assert!(VectorType::VEC4F.is_numeric());
+ assert!(VectorType::VEC2I.is_numeric());
+ assert!(VectorType::VEC3I.is_numeric());
+ assert!(VectorType::VEC4I.is_numeric());
+ assert!(VectorType::VEC2U.is_numeric());
+ assert!(VectorType::VEC3U.is_numeric());
+ assert!(VectorType::VEC4U.is_numeric());
+
+ assert!(!ValueType::Scalar(ScalarType::Bool).is_numeric());
+ assert!(ValueType::Scalar(ScalarType::Float).is_numeric());
+ assert!(ValueType::Scalar(ScalarType::Int).is_numeric());
+ assert!(ValueType::Scalar(ScalarType::Uint).is_numeric());
+
+ assert!(!ValueType::Vector(VectorType::VEC2B).is_numeric());
+ assert!(!ValueType::Vector(VectorType::VEC3B).is_numeric());
+ assert!(!ValueType::Vector(VectorType::VEC4B).is_numeric());
+ assert!(ValueType::Vector(VectorType::VEC2F).is_numeric());
+ assert!(ValueType::Vector(VectorType::VEC3F).is_numeric());
+ assert!(ValueType::Vector(VectorType::VEC4F).is_numeric());
+ assert!(ValueType::Vector(VectorType::VEC2I).is_numeric());
+ assert!(ValueType::Vector(VectorType::VEC3I).is_numeric());
+ assert!(ValueType::Vector(VectorType::VEC4I).is_numeric());
+ assert!(ValueType::Vector(VectorType::VEC2U).is_numeric());
+ assert!(ValueType::Vector(VectorType::VEC3U).is_numeric());
+ assert!(ValueType::Vector(VectorType::VEC4U).is_numeric());
+
+ assert!(ValueType::Matrix(MatrixType::MAT2X2F).is_numeric());
+ assert!(ValueType::Matrix(MatrixType::MAT3X2F).is_numeric());
+ assert!(ValueType::Matrix(MatrixType::MAT4X2F).is_numeric());
+ assert!(ValueType::Matrix(MatrixType::MAT2X3F).is_numeric());
+ assert!(ValueType::Matrix(MatrixType::MAT3X3F).is_numeric());
+ assert!(ValueType::Matrix(MatrixType::MAT4X3F).is_numeric());
+ assert!(ValueType::Matrix(MatrixType::MAT2X4F).is_numeric());
+ assert!(ValueType::Matrix(MatrixType::MAT3X4F).is_numeric());
+ assert!(ValueType::Matrix(MatrixType::MAT4X4F).is_numeric());
+ }
+
+ #[test]
+ #[should_panic]
+ fn vector_type_invalid_rank_1() {
+ let _ = VectorType::new(ScalarType::Float, 1);
+ }
+
+ #[test]
+ #[should_panic]
+ fn vector_type_invalid_rank_5() {
+ let _ = VectorType::new(ScalarType::Float, 5);
+ }
+
+ #[test]
+ #[should_panic]
+ fn matrix_type_invalid_cols_1() {
+ let _ = MatrixType::new(1, 3);
+ }
+
+ #[test]
+ #[should_panic]
+ fn matrix_type_invalid_cols_5() {
+ let _ = MatrixType::new(5, 3);
+ }
+
+ #[test]
+ #[should_panic]
+ fn matrix_type_invalid_rows_1() {
+ let _ = MatrixType::new(3, 1);
+ }
+
+ #[test]
+ #[should_panic]
+ fn matrix_type_invalid_rows_5() {
+ let _ = MatrixType::new(3, 5);
+ }
+
+ #[test]
+ fn matrix_type_size() {
+ assert_eq!(MatrixType::MAT2X2F.size(), 16);
+ assert_eq!(MatrixType::MAT3X2F.size(), 24);
+ assert_eq!(MatrixType::MAT4X2F.size(), 32);
+
+ // vec3 rows are aligned on 16 bytes
+ assert_eq!(MatrixType::MAT2X3F.size(), 32);
+ assert_eq!(MatrixType::MAT3X3F.size(), 48);
+ assert_eq!(MatrixType::MAT4X3F.size(), 64);
+
+ assert_eq!(MatrixType::MAT2X4F.size(), 32);
+ assert_eq!(MatrixType::MAT3X4F.size(), 48);
+ assert_eq!(MatrixType::MAT4X4F.size(), 64);
+ }
+
+ #[test]
+ fn matrix_type_align() {
+ assert_eq!(MatrixType::MAT2X2F.align(), 8);
+ assert_eq!(MatrixType::MAT3X2F.align(), 8);
+ assert_eq!(MatrixType::MAT4X2F.align(), 8);
+
+ // vec3 rows are aligned on 16 bytes
+ assert_eq!(MatrixType::MAT2X3F.align(), 16);
+ assert_eq!(MatrixType::MAT3X3F.align(), 16);
+ assert_eq!(MatrixType::MAT4X3F.align(), 16);
+
+ assert_eq!(MatrixType::MAT2X4F.align(), 16);
+ assert_eq!(MatrixType::MAT3X4F.align(), 16);
+ assert_eq!(MatrixType::MAT4X4F.align(), 16);
+ }
+
+ #[test]
+ fn value_type_is_type() {
+ for t in [
+ ScalarType::Bool,
+ ScalarType::Float,
+ ScalarType::Int,
+ ScalarType::Uint,
+ ] {
+ assert!(ValueType::Scalar(t).is_scalar());
+ assert!(!ValueType::Scalar(t).is_vector());
+ assert!(!ValueType::Scalar(t).is_matrix());
+ assert_eq!(ValueType::Scalar(t).size(), t.size());
+ assert_eq!(ValueType::Scalar(t).align(), t.align());
+ }
+
+ for t in [
+ VectorType::VEC2B,
+ VectorType::VEC3B,
+ VectorType::VEC4B,
+ VectorType::VEC2F,
+ VectorType::VEC3F,
+ VectorType::VEC4F,
+ VectorType::VEC2I,
+ VectorType::VEC3I,
+ VectorType::VEC4I,
+ VectorType::VEC2U,
+ VectorType::VEC3U,
+ VectorType::VEC4U,
+ ] {
+ assert!(!ValueType::Vector(t).is_scalar());
+ assert!(ValueType::Vector(t).is_vector());
+ assert!(!ValueType::Vector(t).is_matrix());
+ assert_eq!(ValueType::Vector(t).size(), t.size());
+ assert_eq!(ValueType::Vector(t).align(), t.align());
+ }
+
+ for t in [
+ MatrixType::MAT2X2F,
+ MatrixType::MAT3X2F,
+ MatrixType::MAT4X2F,
+ MatrixType::MAT2X3F,
+ MatrixType::MAT3X3F,
+ MatrixType::MAT4X3F,
+ MatrixType::MAT2X4F,
+ MatrixType::MAT3X4F,
+ MatrixType::MAT4X4F,
+ ] {
+ assert!(!ValueType::Matrix(t).is_scalar());
+ assert!(!ValueType::Matrix(t).is_vector());
+ assert!(ValueType::Matrix(t).is_matrix());
+ assert_eq!(ValueType::Matrix(t).size(), t.size());
+ assert_eq!(ValueType::Matrix(t).align(), t.align());
+ }
+ }
+
+ const TEST_ATTR_NAME: &str = "test_attr";
+ const TEST_ATTR_INNER: &AttributeInner = &AttributeInner::new(
+ Cow::Borrowed(TEST_ATTR_NAME),
+ Value::Vector(VectorValue::new_vec3(Vec3::ONE)),
+ );
+
+ #[test]
+ fn attr_new() {
+ let attr = Attribute(TEST_ATTR_INNER);
+ assert_eq!(attr.name(), TEST_ATTR_NAME);
+ assert_eq!(attr.size(), 12);
+ assert_eq!(attr.align(), 16);
+ assert_eq!(
+ attr.value_type(),
+ ValueType::Vector(VectorType {
+ elem_type: ScalarType::Float,
+ count: 3
+ })
+ );
+ assert_eq!(
+ attr.default_value(),
+ Value::Vector(VectorValue::new_vec3(Vec3::ONE))
+ );
+ }
+
+ #[test]
+ fn attr_from_name() {
+ for attr in Attribute::all() {
+ assert_eq!(Attribute::from_name(attr.name()), Some(*attr));
+ }
+ }
+
+ #[test]
+ fn attr_reflect() {
+ let mut attr = Attribute(TEST_ATTR_INNER);
+
+ let r = attr.as_reflect();
+ assert_eq!(TypeRegistration::of::<Attribute>().type_id(), r.type_id());
+ match r.reflect_ref() {
+ ReflectRef::Struct(s) => {
+ assert_eq!(2, s.field_len());
+
+ assert_eq!(Some("name"), s.name_at(0));
+ assert_eq!(Some("default_value"), s.name_at(1));
+ assert_eq!(None, s.name_at(2));
+ assert_eq!(None, s.name_at(9999));
+
+ assert_eq!(
+ Some("alloc::borrow::Cow<str>"),
+ s.field("name")
+ .map(|f| f.get_represented_type_info().unwrap().type_path())
+ );
+ assert_eq!(
+ Some("bevy_hanabi::graph::Value"),
+ s.field("default_value")
+ .map(|f| f.get_represented_type_info().unwrap().type_path())
+ );
+ assert!(s.field("DUMMY").is_none());
+ assert!(s.field("").is_none());
+
+ for (_, f) in s.iter_fields() {
+ let tp = f.get_represented_type_info().unwrap().type_path();
+ assert!(
+ tp.contains("alloc::borrow::Cow<str>")
+ || tp.contains("bevy_hanabi::graph::Value")
+ );
+ }
+
+ let d = s.to_dynamic_struct().unwrap();
+ assert_eq!(
+ TypeRegistration::of::<Attribute>().type_id(),
+ d.get_represented_type_info().unwrap().type_id()
+ );
+ assert_eq!(Some(0), d.index_of_name("name"));
+ assert_eq!(Some(1), d.index_of_name("default_value"));
+ }
+ _ => panic!("Attribute should be reflected as a Struct"),
+ }
+
+ // Mutating operators are not implemented by design; only hard-coded built-in
+ // attributes are supported. In any case that won't matter because you
+ // cannot call `as_reflect_mut()` since you cannot obtain a mutable reference to
+ // an attribute.
+ let r = attr.as_reflect_mut();
+ match r.reflect_mut() {
+ ReflectMut::Struct(s) => {
+ assert!(s.field_mut("name").is_none());
+ assert!(s.field_mut("default_value").is_none());
+ assert!(s.field_at_mut(0).is_none());
+ assert!(s.field_at_mut(1).is_none());
+ }
+ _ => panic!("Attribute should be reflected as a Struct"),
+ }
+ }
+
+ #[test]
+ fn attr_from_reflect() {
+ for attr in Attribute::ALL {
+ let s: String = attr.name().into();
+ let r = s.as_partial_reflect();
+ let r_attr = Attribute::from_reflect(r).expect(
+ "Cannot find
+ attribute by name",
+ );
+ assert_eq!(r_attr, attr);
+ }
+
+ assert_eq!(
+ None,
+ Attribute::from_reflect("test".to_string().as_partial_reflect())
+ );
+ }
+
+ #[test]
+ fn attr_serde() {
+ // All existing attributes can round-trip via serialization
+ for attr in Attribute::ALL {
+ // Serialize; this produces just the name of the attribute, which uniquely
+ // identifies it. The default value is never serialized.
+ let ron = ron::to_string(&attr).unwrap();
+ assert_eq!(ron, format!("\"{}\"", attr.name()));
+
+ // Deserialize; this recovers the Attribute from its name using
+ // Attribute::from_name().
+ let s: Attribute = ron::from_str(&ron).unwrap();
+ assert_eq!(s, attr);
+ }
+
+ // Any other attribute name cannot deserialize
+ assert!(ron::from_str::<Attribute>("\"\"").is_err());
+ assert!(ron::from_str::<Attribute>("\"UNKNOWN\"").is_err());
+ }
+
+ const F1_INNER: &AttributeInner =
+ &AttributeInner::new(Cow::Borrowed("F1"), Value::Scalar(ScalarValue::Float(3.)));
+ const F1B_INNER: &AttributeInner =
+ &AttributeInner::new(Cow::Borrowed("F1B"), Value::Scalar(ScalarValue::Float(5.)));
+ const F2_INNER: &AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("F2"),
+ Value::Vector(VectorValue::new_vec2(Vec2::ZERO)),
+ );
+ const F2B_INNER: &AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("F2B"),
+ Value::Vector(VectorValue::new_vec2(Vec2::ONE)),
+ );
+ const F3_INNER: &AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("F3"),
+ Value::Vector(VectorValue::new_vec3(Vec3::ZERO)),
+ );
+ const F3B_INNER: &AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("F3B"),
+ Value::Vector(VectorValue::new_vec3(Vec3::ONE)),
+ );
+ const F4_INNER: &AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("F4"),
+ Value::Vector(VectorValue::new_vec4(Vec4::ZERO)),
+ );
+ const F4B_INNER: &AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("F4B"),
+ Value::Vector(VectorValue::new_vec4(Vec4::ONE)),
+ );
+
+ const F1: Attribute = Attribute(F1_INNER);
+ const F1B: Attribute = Attribute(F1B_INNER);
+ const F2: Attribute = Attribute(F2_INNER);
+ const F2B: Attribute = Attribute(F2B_INNER);
+ const F3: Attribute = Attribute(F3_INNER);
+ const F3B: Attribute = Attribute(F3B_INNER);
+ const F4: Attribute = Attribute(F4_INNER);
+ const F4B: Attribute = Attribute(F4B_INNER);
+
+ /// Calculate the raw alignment based on the actual attributes in the layout
+ /// vec, ignoring the value the layout stored. This is for fact-checking
+ /// purpose.
+ fn calc_raw_align(layout: &ParticleLayout) -> u32 {
+ if layout.layout.is_empty() {
+ 0
+ } else {
+ layout
+ .layout
+ .iter()
+ .map(|attr| attr.attribute.value_type().align())
+ .max()
+ .unwrap() as u32
+ }
+ }
+
+ #[test]
+ fn test_layout_build() {
+ // empty
+ let layout = ParticleLayout::new().build();
+ assert_eq!(layout.layout.len(), 0);
+ assert_eq!(layout.generate_code(), String::new());
+
+ // single
+ for attr in Attribute::ALL {
+ let layout = ParticleLayout::new().append(attr).build();
+
+ // This is the un-padded length, so exactly equal
+ assert_eq!(layout.len(), 1);
+
+ // There may be padding field(s)...
+ assert!(!layout.layout.is_empty());
+ let size = layout.size();
+ let aligned_size = size.next_multiple_of(layout.align());
+ assert_eq!(aligned_size % attr.align() as u32, 0);
+ let attr_size = attr.size() as u32;
+ if aligned_size != attr_size {
+ // Padding
+ assert!(aligned_size > attr_size);
+ let pad_size = aligned_size - attr_size;
+ assert_eq!(pad_size % 4, 0);
+ let num_pad = pad_size / 4;
+ assert_eq!(layout.layout.len() as u32, 1 + num_pad);
+ } else {
+ // No padding
+ assert_eq!(layout.layout.len(), 1);
+ }
+
+ let attr0 = &layout.layout[0];
+ assert_eq!(attr0.offset, 0);
+ assert!(layout.generate_code().starts_with(&format!(
+ " {}: {},\n",
+ attr0.attribute.name(),
+ attr0.attribute.value_type().to_wgsl_string()
+ )));
+
+ // Align
+ assert_eq!(layout.align(), calc_raw_align(&layout));
+ }
+
+ // dedup
+ for attr in [F1, F2, F3, F4] {
+ let mut layout = ParticleLayout::new();
+ for _ in 0..3 {
+ layout = layout.append(attr);
+ }
+ let layout = layout.build();
+ assert_eq!(layout.len(), 1); // unique
+ let attr = &layout.layout[0];
+ assert_eq!(attr.offset, 0);
+ }
+
+ // homogenous
+ for attrs in [[F1, F1B], [F2, F2B], [F3, F3B], [F4, F4B]] {
+ let mut layout = ParticleLayout::new();
+ for &attr in &attrs {
+ layout = layout.append(attr);
+ }
+ let layout = layout.build();
+ assert_eq!(layout.len(), 2);
+ let attr_0 = &layout.layout[0];
+ let size = attr_0.attribute.size();
+ assert_eq!(attr_0.offset as usize, 0);
+ if attr_0.attribute.size() != attr_0.attribute.align() {
+ // Padding
+ let attr_1 = &layout.layout[2]; // skip padding attr
+ assert_eq!(
+ attr_1.offset as usize,
+ size.next_multiple_of(attr_0.attribute.align())
+ );
+ assert_eq!(attr_1.attribute.size(), size);
+ } else {
+ // No padding
+ let attr_1 = &layout.layout[1];
+ assert_eq!(
+ attr_1.offset as usize,
+ size.next_multiple_of(attr_0.attribute.align())
+ );
+ assert_eq!(attr_1.attribute.size(), size);
+ }
+ }
+
+ // [3, 1, 3, 2] -> [3 1 3 - 2 - -]
+ {
+ let mut layout = ParticleLayout::new();
+ for &attr in &[F1, F3, F2, F3B] {
+ layout = layout.append(attr);
+ }
+ let layout = layout.build();
+ assert_eq!(layout.len(), 4);
+ assert_eq!(layout.layout.len(), 7);
+ assert_eq!(layout.size(), 48);
+ assert_eq!(layout.align(), 16);
+ for (i, (off, a)) in [
+ (0, F3),
+ (12, F1),
+ (16, F3B),
+ (28, Attribute::PAD0),
+ (32, F2),
+ (40, Attribute::PAD1),
+ (44, Attribute::PAD2),
+ ]
+ .iter()
+ .enumerate()
+ {
+ let attr_i = layout.layout[i];
+ assert_eq!(attr_i.offset, *off);
+ assert_eq!(attr_i.attribute, *a);
+ }
+ }
+
+ // [1, 4, 3, 2, 2, 3] -> [4 3 1 2 2 3 -]
+ {
+ let mut layout = ParticleLayout::new();
+ for &attr in &[F1, F4, F3, F2, F2B, F3B] {
+ layout = layout.append(attr);
+ }
+ let layout = layout.build();
+ assert_eq!(layout.len(), 6);
+ assert_eq!(layout.layout.len(), 7);
+ assert_eq!(layout.size(), 64);
+ assert_eq!(layout.align(), 16);
+ for (i, (off, a)) in [
+ (0, F4),
+ (16, F3),
+ (28, F1),
+ (32, F2),
+ (40, F2B),
+ (48, F3B),
+ (60, Attribute::PAD0),
+ ]
+ .iter()
+ .enumerate()
+ {
+ let attr_i = layout.layout[i];
+ assert_eq!(attr_i.offset, *off);
+ assert_eq!(attr_i.attribute, *a);
+ }
+ }
+ }
+}
diff --git a/vendor/bevy_hanabi/src/gradient.rs b/vendor/bevy_hanabi/src/gradient.rs
new file mode 100644
index 00000000..3d9a0b78
--- /dev/null
+++ b/vendor/bevy_hanabi/src/gradient.rs
@@ -0,0 +1,779 @@
+use std::hash::{Hash, Hasher};
+
+use bevy::{
+ math::{FloatOrd, Quat, Vec2, Vec3, Vec3A, Vec4},
+ reflect::{FromReflect, Reflect},
+};
+use serde::{Deserialize, Serialize};
+
+/// Describes a type that can be linearly interpolated between two keys.
+///
+/// This trait is used for values in a gradient, which are primitive types and
+/// are therefore copyable.
+pub trait Lerp: Copy {
+ fn lerp(self, other: Self, ratio: f32) -> Self;
+}
+
+impl Lerp for f32 {
+ #[inline]
+ fn lerp(self, other: Self, ratio: f32) -> Self {
+ self.mul_add(1. - ratio, other * ratio)
+ }
+}
+
+impl Lerp for f64 {
+ #[inline]
+ fn lerp(self, other: Self, ratio: f32) -> Self {
+ self.mul_add((1. - ratio) as f64, other * ratio as f64)
+ }
+}
+
+macro_rules! impl_lerp_vecn {
+ ($t:ty) => {
+ impl Lerp for $t {
+ #[inline]
+ fn lerp(self, other: Self, ratio: f32) -> Self {
+ // Force use of type's own lerp() to disambiguate and prevent infinite recursion
+ <$t>::lerp(self, other, ratio)
+ }
+ }
+ };
+}
+
+impl_lerp_vecn!(Vec2);
+impl_lerp_vecn!(Vec3);
+impl_lerp_vecn!(Vec3A);
+impl_lerp_vecn!(Vec4);
+
+impl Lerp for Quat {
+ fn lerp(self, other: Self, ratio: f32) -> Self {
+ // We use slerp() instead of lerp() as conceptually we want a smooth
+ // interpolation and we expect Quat to be used to represent a rotation.
+ // lerp() would produce an interpolation with varying speed, which feels
+ // non-natural.
+ self.slerp(other, ratio)
+ }
+}
+
+/// A single key point for a [`Gradient`].
+#[derive(Debug, Default, Clone, Copy, PartialEq, Reflect, Serialize, Deserialize)]
+pub struct GradientKey<T: Lerp + FromReflect> {
+ /// Ratio in \[0:1\] where the key is located.
+ ratio: f32,
+
+ /// Value associated with the key.
+ ///
+ /// The value is uploaded as is to the render shader. For colors, this means
+ /// the value does not imply any particular color space by itself.
+ pub value: T,
+}
+
+impl<T: Lerp + FromReflect> GradientKey<T> {
+ /// Get the ratio where the key point is located, in \[0:1\].
+ pub fn ratio(&self) -> f32 {
+ self.ratio
+ }
+}
+
+impl Hash for GradientKey<f32> {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ FloatOrd(self.ratio).hash(state);
+ FloatOrd(self.value).hash(state);
+ }
+}
+
+impl Hash for GradientKey<Vec2> {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ FloatOrd(self.ratio).hash(state);
+ FloatOrd(self.value.x).hash(state);
+ FloatOrd(self.value.y).hash(state);
+ }
+}
+
+impl Hash for GradientKey<Vec3> {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ FloatOrd(self.ratio).hash(state);
+ FloatOrd(self.value.x).hash(state);
+ FloatOrd(self.value.y).hash(state);
+ FloatOrd(self.value.z).hash(state);
+ }
+}
+
+impl Hash for GradientKey<Vec4> {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ FloatOrd(self.ratio).hash(state);
+ FloatOrd(self.value.x).hash(state);
+ FloatOrd(self.value.y).hash(state);
+ FloatOrd(self.value.z).hash(state);
+ FloatOrd(self.value.w).hash(state);
+ }
+}
+
+/// A gradient curve made of keypoints and associated values.
+///
+/// The gradient can be sampled anywhere, and will return a linear interpolation
+/// of the values of its closest keys. Sampling before 0 or after 1 returns a
+/// constant value equal to the one of the closest bound.
+///
+/// # Construction
+///
+/// The most efficient constructors take the entirety of the key points upfront.
+/// This prevents costly linear searches to insert key points one by one:
+/// - [`constant()`] creates a gradient with a single key point;
+/// - [`linear()`] creates a linear gradient between two key points;
+/// - [`from_keys()`] creates a more general gradient with any number of key
+/// points.
+///
+/// [`constant()`]: crate::Gradient::constant
+/// [`linear()`]: crate::Gradient::linear
+/// [`from_keys()`]: crate::Gradient::from_keys
+#[derive(Debug, Default, Clone, PartialEq, Reflect, Serialize, Deserialize)]
+pub struct Gradient<T: Lerp + FromReflect> {
+ keys: Vec<GradientKey<T>>,
+}
+
+// SAFETY: This is consistent with the derive, but we can't derive due to trait
+// bounds.
+#[allow(clippy::derived_hash_with_manual_eq)]
+impl<T> Hash for Gradient<T>
+where
+ T: Default + Lerp + FromReflect,
+ GradientKey<T>: Hash,
+{
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.keys.hash(state);
+ }
+}
+
+impl<T: Lerp + FromReflect> Gradient<T> {
+ /// Create a new empty gradient.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::Gradient;
+ /// let g: Gradient<f32> = Gradient::new();
+ /// assert!(g.is_empty());
+ /// ```
+ pub const fn new() -> Self {
+ Self { keys: vec![] }
+ }
+
+ /// Create a constant gradient.
+ ///
+ /// The gradient contains `value` at key 0.0 and nothing else. Any sampling
+ /// evaluates to that single value.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::Gradient;
+ /// # use bevy::math::Vec2;
+ /// let g = Gradient::constant(Vec2::X);
+ /// assert_eq!(g.sample(0.3), Vec2::X);
+ /// ```
+ pub fn constant(value: T) -> Self {
+ Self {
+ keys: vec![GradientKey::<T> { ratio: 0., value }],
+ }
+ }
+
+ /// Create a linear gradient between two values.
+ ///
+ /// The gradient contains the `start` value at key 0.0 and the `end` value
+ /// at key 1.0.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::Gradient;
+ /// # use bevy::math::Vec3;
+ /// let g = Gradient::linear(Vec3::ZERO, Vec3::Y);
+ /// assert_eq!(g.sample(0.3), Vec3::new(0., 0.3, 0.));
+ /// ```
+ pub fn linear(start: T, end: T) -> Self {
+ Self {
+ keys: vec![
+ GradientKey::<T> {
+ ratio: 0.,
+ value: start,
+ },
+ GradientKey::<T> {
+ ratio: 1.,
+ value: end,
+ },
+ ],
+ }
+ }
+
+ /// Create a new gradient from a series of key points.
+ ///
+ /// If one or more duplicate ratios already exist, append each new key after
+ /// all the existing keys with same ratio. The keys are inserted in order,
+ /// but do not need to be sorted by ratio.
+ ///
+ /// The ratio must be a finite floating point value.
+ ///
+ /// This variant is slightly more performant than [`with_keys()`] because it
+ /// can sort all keys before inserting them in batch.
+ ///
+ /// If you have only one or two keys, consider using [`constant()`] or
+ /// [`linear()`], respectively, instead of this.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::Gradient;
+ /// let g = Gradient::from_keys([(0., 3.2), (1., 13.89), (0.3, 9.33)]);
+ /// assert_eq!(g.len(), 3);
+ /// assert_eq!(g.sample(0.3), 9.33);
+ /// ```
+ ///
+ /// # Panics
+ ///
+ /// This method panics if any `ratio` is not in the \[0:1\] range.
+ ///
+ /// [`with_keys()`]: crate::Gradient::with_keys
+ /// [`constant()`]: crate::Gradient::constant
+ /// [`linear()`]: crate::Gradient::linear
+ pub fn from_keys(keys: impl IntoIterator<Item = (f32, T)>) -> Self {
+ // Note that all operations below are stable, including the sort. This ensures
+ // the keys are kept in the correct order.
+ let mut keys = keys
+ .into_iter()
+ .map(|(ratio, value)| GradientKey { ratio, value })
+ .collect::<Vec<_>>();
+ keys.sort_by_key(|a| FloatOrd(a.ratio));
+ Self { keys }
+ }
+
+ /// Returns `true` if the gradient contains no key points.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use bevy_hanabi::Gradient;
+ /// let mut g = Gradient::new();
+ /// assert!(g.is_empty());
+ ///
+ /// g.add_key(0.3, 3.42);
+ /// assert!(!g.is_empty());
+ /// ```
+ pub fn is_empty(&self) -> bool {
+ self.keys.is_empty()
+ }
+
+ /// Returns the number of key points in the gradient, also referred to as
+ /// its 'length'.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use bevy_hanabi::Gradient;
+ /// let g = Gradient::linear(3.5, 7.8);
+ /// assert_eq!(g.len(), 2);
+ /// ```
+ pub fn len(&self) -> usize {
+ self.keys.len()
+ }
+
+ /// Add a key point to the gradient.
+ ///
+ /// If one or more duplicate ratios already exist, append the new key after
+ /// all the existing keys with same ratio.
+ ///
+ /// The ratio must be a finite floating point value.
+ ///
+ /// Note that this function needs to perform a linear search into the
+ /// gradient's key points to find an insertion point. If you already know
+ /// all key points in advance, it's more efficient to use [`constant()`],
+ /// [`linear()`], or [`with_keys()`].
+ ///
+ /// # Panics
+ ///
+ /// This method panics if `ratio` is not in the \[0:1\] range.
+ ///
+ /// [`constant()`]: crate::Gradient::constant
+ /// [`linear()`]: crate::Gradient::linear
+ /// [`with_keys()`]: crate::Gradient::with_keys
+ pub fn with_key(mut self, ratio: f32, value: T) -> Self {
+ self.add_key(ratio, value);
+ self
+ }
+
+ /// Add a series of key points to the gradient.
+ ///
+ /// If one or more duplicate ratios already exist, append each new key after
+ /// all the existing keys with same ratio. The keys are inserted in order.
+ ///
+ /// The ratio must be a finite floating point value.
+ ///
+ /// This variant is slightly more performant than [`add_key()`] because it
+ /// can reserve storage for all key points upfront, which requires an exact
+ /// size iterator.
+ ///
+ /// Note that if all key points are known upfront, [`from_keys()`] is a lot
+ /// more performant.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::Gradient;
+ /// fn add_some_keys(mut g: Gradient<f32>) -> Gradient<f32> {
+ /// g.with_keys([(0.7, 12.9), (0.32, 9.31)].into_iter())
+ /// }
+ /// ```
+ ///
+ /// # Panics
+ ///
+ /// This method panics if any `ratio` is not in the \[0:1\] range.
+ ///
+ /// [`add_key()`]: crate::Gradient::add_key
+ /// [`from_keys()`]: crate::Gradient::from_keys
+ pub fn with_keys(mut self, keys: impl ExactSizeIterator<Item = (f32, T)>) -> Self {
+ self.keys.reserve(keys.len());
+ for (ratio, value) in keys {
+ self.add_key(ratio, value);
+ }
+ self
+ }
+
+ /// Add a key point to the gradient.
+ ///
+ /// If one or more duplicate ratios already exist, append the new key after
+ /// all the existing keys with same ratio.
+ ///
+ /// The ratio must be a finite floating point value.
+ ///
+ /// # Panics
+ ///
+ /// This method panics if `ratio` is not in the \[0:1\] range.
+ pub fn add_key(&mut self, ratio: f32, value: T) {
+ assert!(ratio >= 0.0);
+ assert!(ratio <= 1.0);
+ let index = match self
+ .keys
+ .binary_search_by(|key| FloatOrd(key.ratio).cmp(&FloatOrd(ratio)))
+ {
+ Ok(mut index) => {
+ // When there are duplicate keys, binary_search_by() returns the index of an
+ // unspecified one. Make sure we insert always as the last
+ // duplicate one, for determinism.
+ let len = self.keys.len();
+ while index + 1 < len && self.keys[index].ratio == self.keys[index + 1].ratio {
+ index += 1;
+ }
+ index + 1 // insert after last duplicate
+ }
+ Err(upper_index) => upper_index,
+ };
+ self.keys.insert(index, GradientKey { ratio, value });
+ }
+
+ /// Get the gradient keys.
+ pub fn keys(&self) -> &[GradientKey<T>] {
+ &self.keys[..]
+ }
+
+ /// Get mutable access to the gradient keys.
+ pub fn keys_mut(&mut self) -> &mut [GradientKey<T>] {
+ &mut self.keys[..]
+ }
+
+ /// Sample the gradient at the given ratio.
+ ///
+ /// If the ratio is exactly equal to those of one or more keys, sample the
+ /// first key in the collection. If the ratio falls between two keys,
+ /// return a linear interpolation of their values. If the ratio is
+ /// before the first key or after the last one, return the first and
+ /// last value, respectively.
+ ///
+ /// # Panics
+ ///
+ /// This method panics if the gradient is empty (has no key point).
+ pub fn sample(&self, ratio: f32) -> T {
+ assert!(!self.keys.is_empty());
+ match self
+ .keys
+ .binary_search_by(|key| FloatOrd(key.ratio).cmp(&FloatOrd(ratio)))
+ {
+ Ok(mut index) => {
+ // When there are duplicate keys, binary_search_by() returns the index of an
+ // unspecified one. Make sure we sample the first duplicate, for determinism.
+ while index > 0 && self.keys[index - 1].ratio == self.keys[index].ratio {
+ index -= 1;
+ }
+ self.keys[index].value
+ }
+ Err(upper_index) => {
+ if upper_index > 0 {
+ if upper_index < self.keys.len() {
+ let key0 = &self.keys[upper_index - 1];
+ let key1 = &self.keys[upper_index];
+ let t = (ratio - key0.ratio) / (key1.ratio - key0.ratio);
+ key0.value.lerp(key1.value, t)
+ } else {
+ // post: sampling point located after the last key
+ self.keys[upper_index - 1].value
+ }
+ } else {
+ // pre: sampling point located before the first key
+ self.keys[upper_index].value
+ }
+ }
+ }
+ }
+
+ /// Sample the gradient at regular intervals.
+ ///
+ /// Create a list of sample points starting at ratio `start` and spaced with
+ /// `inc` delta ratio. The number of samples is equal to the length of
+ /// the `dst` slice. Sample the gradient at all those points, and fill
+ /// the `dst` slice with the resulting values.
+ ///
+ /// This is equivalent to calling [`sample()`] in a loop, but is more
+ /// efficient.
+ ///
+ /// [`sample()`]: Gradient::sample
+ pub fn sample_by(&self, start: f32, inc: f32, dst: &mut [T]) {
+ let count = dst.len();
+ assert!(!self.keys.is_empty());
+ let mut ratio = start;
+ // pre: sampling points located before the first key
+ let first_ratio = self.keys[0].ratio;
+ let first_col = self.keys[0].value;
+ let mut idst = 0;
+ while idst < count && ratio <= first_ratio {
+ dst[idst] = first_col;
+ idst += 1;
+ ratio += inc;
+ }
+ // main: sampling points located on or after the first key
+ let mut ikey = 1;
+ let len = self.keys.len();
+ for i in idst..count {
+ // Find the first key after the ratio
+ while ikey < len && ratio > self.keys[ikey].ratio {
+ ikey += 1;
+ }
+ if ikey >= len {
+ // post: sampling points located after the last key
+ let last_col = self.keys[len - 1].value;
+ for d in &mut dst[i..] {
+ *d = last_col;
+ }
+ return;
+ }
+ if self.keys[ikey].ratio == ratio {
+ dst[i] = self.keys[ikey].value;
+ } else {
+ let k0 = &self.keys[ikey - 1];
+ let k1 = &self.keys[ikey];
+ let t = (ratio - k0.ratio) / (k1.ratio - k0.ratio);
+ dst[i] = k0.value.lerp(k1.value, t);
+ }
+ ratio += inc;
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::hash_map::DefaultHasher;
+
+ use bevy::reflect::{structs::Struct, PartialReflect, ReflectRef};
+ use rand::{distr::StandardUniform, prelude::Distribution, rng, rngs::ThreadRng, Rng, RngExt};
+
+ use super::*;
+ use crate::test_utils::*;
+
+ const RED: Vec4 = Vec4::new(1., 0., 0., 1.);
+ const BLUE: Vec4 = Vec4::new(0., 0., 1., 1.);
+ const GREEN: Vec4 = Vec4::new(0., 1., 0., 1.);
+
+ fn make_test_gradient() -> Gradient<Vec4> {
+ let mut g = Gradient::new();
+ g.add_key(0.5, RED);
+ g.add_key(0.8, BLUE);
+ g.add_key(0.8, GREEN);
+ g
+ }
+
+ fn color_approx_eq(c0: Vec4, c1: Vec4, tol: f32) -> bool {
+ ((c0.x - c1.x).abs() < tol)
+ && ((c0.y - c1.y).abs() < tol)
+ && ((c0.z - c1.z).abs() < tol)
+ && ((c0.w - c1.w).abs() < tol)
+ }
+
+ #[test]
+ fn lerp_test() {
+ assert_approx_eq!(Lerp::lerp(3_f32, 5_f32, 0.1), 3.2_f32);
+ assert_approx_eq!(Lerp::lerp(3_f32, 5_f32, 0.5), 4.0_f32);
+ assert_approx_eq!(Lerp::lerp(3_f32, 5_f32, 0.9), 4.8_f32);
+ assert_approx_eq!(Lerp::lerp(5_f32, 3_f32, 0.1), 4.8_f32);
+ assert_approx_eq!(Lerp::lerp(5_f32, 3_f32, 0.5), 4.0_f32);
+ assert_approx_eq!(Lerp::lerp(5_f32, 3_f32, 0.9), 3.2_f32);
+
+ assert_approx_eq!(Lerp::lerp(3_f64, 5_f64, 0.1), 3.2_f64);
+ assert_approx_eq!(Lerp::lerp(3_f64, 5_f64, 0.5), 4.0_f64);
+ assert_approx_eq!(Lerp::lerp(3_f64, 5_f64, 0.9), 4.8_f64);
+ assert_approx_eq!(Lerp::lerp(5_f64, 3_f64, 0.1), 4.8_f64);
+ assert_approx_eq!(Lerp::lerp(5_f64, 3_f64, 0.5), 4.0_f64);
+ assert_approx_eq!(Lerp::lerp(5_f64, 3_f64, 0.9), 3.2_f64);
+
+ let s = Quat::IDENTITY;
+ let e = Quat::from_rotation_x(90_f32.to_radians());
+ assert_approx_eq!(Lerp::lerp(s, e, 0.1), s.slerp(e, 0.1));
+ assert_approx_eq!(Lerp::lerp(s, e, 0.5), s.slerp(e, 0.5));
+ assert_approx_eq!(Lerp::lerp(s, e, 0.9), s.slerp(e, 0.9));
+ assert_approx_eq!(Lerp::lerp(e, s, 0.1), s.slerp(e, 0.9));
+ assert_approx_eq!(Lerp::lerp(e, s, 0.5), s.slerp(e, 0.5));
+ assert_approx_eq!(Lerp::lerp(e, s, 0.9), s.slerp(e, 0.1));
+ }
+
+ #[test]
+ fn constant() {
+ let grad = Gradient::constant(3.0);
+ assert!(!grad.is_empty());
+ assert_eq!(grad.len(), 1);
+ for r in [
+ -1e5, -0.5, -0.0001, 0., 0.0001, 0.3, 0.5, 0.9, 0.9999, 1., 1.0001, 100., 1e5,
+ ] {
+ assert_approx_eq!(grad.sample(r), 3.0);
+ }
+ }
+
+ #[test]
+ fn with_keys() {
+ let g = Gradient::new().with_keys([(0.5, RED), (0.8, BLUE)].into_iter());
+ assert_eq!(g.len(), 2);
+ // Keys are inserted in order and after existing ones -> (R, B, B, R)
+ let g2 = g.with_keys([(0.5, BLUE), (0.8, RED)].into_iter());
+ assert_eq!(g2.len(), 4);
+ assert_eq!(g2.sample(0.499), RED);
+ assert_eq!(g2.sample(0.501), BLUE);
+ assert_eq!(g2.sample(0.799), BLUE);
+ assert_eq!(g2.sample(0.801), RED);
+ }
+
+ #[test]
+ fn add_key() {
+ let mut g = Gradient::new();
+ assert!(g.is_empty());
+ assert_eq!(g.len(), 0);
+ g.add_key(0.3, RED);
+ assert!(!g.is_empty());
+ assert_eq!(g.len(), 1);
+ // duplicate keys allowed
+ let mut g = g.with_key(0.3, RED);
+ assert_eq!(g.len(), 2);
+ // duplicate ratios stored in order they're inserted
+ g.add_key(0.7, BLUE);
+ g.add_key(0.7, GREEN);
+ assert_eq!(g.len(), 4);
+ let keys = g.keys();
+ assert_eq!(keys.len(), 4);
+ assert!(color_approx_eq(RED, keys[0].value, 1e-5));
+ assert!(color_approx_eq(RED, keys[1].value, 1e-5));
+ assert!(color_approx_eq(BLUE, keys[2].value, 1e-5));
+ assert!(color_approx_eq(GREEN, keys[3].value, 1e-5));
+ }
+
+ #[test]
+ fn sample() {
+ let mut g = Gradient::new();
+ g.add_key(0.5, RED);
+ assert_eq!(RED, g.sample(0.0));
+ assert_eq!(RED, g.sample(0.5));
+ assert_eq!(RED, g.sample(1.0));
+ g.add_key(0.8, BLUE);
+ g.add_key(0.8, GREEN);
+ assert_eq!(RED, g.sample(0.0));
+ assert_eq!(RED, g.sample(0.499));
+ assert_eq!(RED, g.sample(0.5));
+ let expected = RED.lerp(BLUE, 1. / 3.);
+ let actual = g.sample(0.6);
+ assert!(color_approx_eq(actual, expected, 1e-5));
+ assert_eq!(BLUE, g.sample(0.8));
+ assert_eq!(GREEN, g.sample(0.801));
+ assert_eq!(GREEN, g.sample(1.0));
+ }
+
+ #[test]
+ fn sample_by() {
+ let g = Gradient::from_keys([(0.5, RED), (0.8, BLUE)]);
+ const COUNT: usize = 256;
+ let mut data: [Vec4; COUNT] = [Vec4::ZERO; COUNT];
+ let start = 0.;
+ let inc = 1. / COUNT as f32;
+ g.sample_by(start, inc, &mut data[..]);
+ for (i, &d) in data.iter().enumerate() {
+ let ratio = inc.mul_add(i as f32, start);
+ let expected = g.sample(ratio);
+ assert!(color_approx_eq(expected, d, 1e-5));
+ }
+ }
+
+ #[test]
+ fn reflect() {
+ let g = make_test_gradient();
+
+ // Reflect
+ let reflect: &dyn PartialReflect = &g;
+ assert!(reflect
+ .get_represented_type_info()
+ .unwrap()
+ .is::<Gradient<Vec4>>());
+ let g_reflect = reflect.try_downcast_ref::<Gradient<Vec4>>();
+ assert!(g_reflect.is_some());
+ let g_reflect = g_reflect.unwrap();
+ assert_eq!(*g_reflect, g);
+
+ // FromReflect
+ let g_from = Gradient::<Vec4>::from_reflect(reflect).unwrap();
+ assert_eq!(g_from, g);
+
+ // Struct
+ assert!(g
+ .get_represented_type_info()
+ .unwrap()
+ .type_path()
+ .starts_with("bevy_hanabi::gradient::Gradient<")); // the Vec4 type name depends on platform
+ let keys = g.field("keys").unwrap();
+ let ReflectRef::List(keys) = keys.reflect_ref() else {
+ panic!("Invalid type");
+ };
+ assert_eq!(keys.len(), 3);
+ for (i, (r, v)) in [(0.5, RED), (0.8, BLUE), (0.8, GREEN)].iter().enumerate() {
+ let k = keys.get(i).unwrap();
+ let gk = k.try_downcast_ref::<GradientKey<Vec4>>().unwrap();
+ assert_approx_eq!(gk.ratio(), r);
+ assert_approx_eq!(gk.value, v);
+
+ let ReflectRef::Struct(k) = k.reflect_ref() else {
+ panic!("Invalid type");
+ };
+ assert!(k
+ .get_represented_type_info()
+ .unwrap()
+ .type_path()
+ .contains("GradientKey"));
+ }
+ }
+
+ #[test]
+ fn serde() {
+ let g = make_test_gradient();
+
+ let s = ron::to_string(&g).unwrap();
+ // println!("gradient: {:?}", s);
+ let g_serde: Gradient<Vec4> = ron::from_str(&s).unwrap();
+ assert_eq!(g, g_serde);
+ }
+
+ /// Hash the given gradient.
+ fn hash_gradient<T>(g: &Gradient<T>) -> u64
+ where
+ T: Default + Lerp + FromReflect,
+ GradientKey<T>: Hash,
+ {
+ let mut hasher = DefaultHasher::default();
+ g.hash(&mut hasher);
+ hasher.finish()
+ }
+
+ /// Make a collection of random keys, for testing.
+ fn make_keys<R, T, S>(rng: &mut R, count: usize) -> Vec<(f32, T)>
+ where
+ R: Rng + ?Sized,
+ T: Lerp + FromReflect + From<S>,
+ StandardUniform: Distribution<S>,
+ {
+ if count == 0 {
+ return vec![];
+ }
+ if count == 1 {
+ return vec![(0., rng.random().into())];
+ }
+ let mut ret = Vec::with_capacity(count);
+ for i in 0..count {
+ ret.push((i as f32 / (count - 1) as f32, rng.random().into()));
+ }
+ ret
+ }
+
+ #[test]
+ fn hash() {
+ let mut thread_rng = rng();
+ for count in 0..10 {
+ let keys: Vec<(f32, f32)> = make_keys::<ThreadRng, f32, f32>(&mut thread_rng, count);
+ let mut g1 = Gradient::new().with_keys(keys.into_iter());
+ let g2 = g1.clone();
+ assert_eq!(g1, g2);
+ assert_eq!(hash_gradient(&g1), hash_gradient(&g2));
+ if count > 0 {
+ g1.keys_mut()[0].value += 1.;
+ assert_ne!(g1, g2);
+ assert_ne!(hash_gradient(&g1), hash_gradient(&g2));
+ g1.keys_mut()[0].value = g2.keys()[0].value;
+ assert_eq!(g1, g2);
+ assert_eq!(hash_gradient(&g1), hash_gradient(&g2));
+ }
+ }
+
+ let mut thread_rng = rng();
+ for count in 0..10 {
+ let keys: Vec<(f32, Vec2)> =
+ make_keys::<ThreadRng, Vec2, (f32, f32)>(&mut thread_rng, count);
+ let mut g1 = Gradient::new().with_keys(keys.into_iter());
+ let g2 = g1.clone();
+ assert_eq!(g1, g2);
+ assert_eq!(hash_gradient(&g1), hash_gradient(&g2));
+ if count > 0 {
+ g1.keys_mut()[0].value += 1.;
+ assert_ne!(g1, g2);
+ assert_ne!(hash_gradient(&g1), hash_gradient(&g2));
+ g1.keys_mut()[0].value = g2.keys()[0].value;
+ assert_eq!(g1, g2);
+ assert_eq!(hash_gradient(&g1), hash_gradient(&g2));
+ }
+ }
+
+ let mut thread_rng = rng();
+ for count in 0..10 {
+ let keys: Vec<(f32, Vec3)> =
+ make_keys::<ThreadRng, Vec3, (f32, f32, f32)>(&mut thread_rng, count);
+ let mut g1 = Gradient::new().with_keys(keys.into_iter());
+ let g2 = g1.clone();
+ assert_eq!(g1, g2);
+ assert_eq!(hash_gradient(&g1), hash_gradient(&g2));
+ if count > 0 {
+ g1.keys_mut()[0].value += 1.;
+ assert_ne!(g1, g2);
+ assert_ne!(hash_gradient(&g1), hash_gradient(&g2));
+ g1.keys_mut()[0].value = g2.keys()[0].value;
+ assert_eq!(g1, g2);
+ assert_eq!(hash_gradient(&g1), hash_gradient(&g2));
+ }
+ }
+
+ let mut thread_rng = rng();
+ for count in 0..10 {
+ let keys: Vec<(f32, Vec4)> =
+ make_keys::<ThreadRng, Vec4, (f32, f32, f32, f32)>(&mut thread_rng, count);
+ let mut g1 = Gradient::new().with_keys(keys.into_iter());
+ let g2 = g1.clone();
+ assert_eq!(g1, g2);
+ assert_eq!(hash_gradient(&g1), hash_gradient(&g2));
+ if count > 0 {
+ g1.keys_mut()[0].value += 1.;
+ assert_ne!(g1, g2);
+ assert_ne!(hash_gradient(&g1), hash_gradient(&g2));
+ g1.keys_mut()[0].value = g2.keys()[0].value;
+ assert_eq!(g1, g2);
+ assert_eq!(hash_gradient(&g1), hash_gradient(&g2));
+ }
+ }
+ }
+}
diff --git a/vendor/bevy_hanabi/src/graph/expr.rs b/vendor/bevy_hanabi/src/graph/expr.rs
new file mode 100644
index 00000000..0749c1d6
--- /dev/null
+++ b/vendor/bevy_hanabi/src/graph/expr.rs
@@ -0,0 +1,5350 @@
+//! Expression API
+//!
+//! This module contains the low-level _Expression API_, designed to produce
+//! highly customizable modifier behaviors through a code-first API focused on
+//! runtime and serialization. For asset editing, the higher-level [Node API]
+//! offers an easier-to-use abstraction built on top of the Expression API.
+//!
+//! # Modules and expressions
+//!
+//! A particle effect is composed of a series [`Modifier`]s decribing how to
+//! initialize and update (simulate) the particles of the effect. Choosing which
+//! modifier to add to an effect provides the user some limited level of
+//! customizing. However modifiers alone cannot provide enough customizing to
+//! build visual effects. For this reason, modifier inputs can be further
+//! customized with _expressions_. An expression produces a value which is
+//! assigned to the input. That value can be constant, in which case it will be
+//! hard-coded into the generated WGSL shader, for performance reasons.
+//! Alternatively, that value can vary based on other quantities, like an effect
+//! property, a particle attribute, or some built-in simulation variable like
+//! the simulation time.
+//!
+//! An expression is represented by the [`Expr`] enum. Expressions can be
+//! combined together to form more complex expression; for example, the Add
+//! expression computes the sum between two other expressions. [`Expr`]
+//! represents a form of abstraction over the actual WGSL shader code, and is
+//! generally closely related to the actual expressions of the WGSL language
+//! itself.
+//!
+//! An expression often refers to other expressions. However, [`Expr`] as an
+//! enum cannot directly contain other [`Expr`], otherwise the type would become
+//! infinitely recursive. Instead, each expression is stored into a [`Module`]
+//! and indexed by an [`ExprHandle`], a non-zero index referencing the
+//! expression inside the module. This indirection avoids the recursion issue.
+//! This means all expressions are implicitly associated with a unique module,
+//! and care must be taken to not mix exressions from different modules.
+//!
+//! Each [`EffectAsset`] contains a single [`Module`] storing all the [`Expr`]
+//! used in all its modifiers.
+//!
+//! # Kinds of expressions
+//!
+//! Expressions can be grouped into various kinds, for the sake of
+//! comprehension:
+//! - Literal expressions represent a constant, which will be hard-coded into
+//! the final WGSL shader code. Expressions like `1.42` or `vec3<f32>(0.)` are
+//! literal expressions in WGSL, and are represented by a [`LiteralExpr`].
+//! - Built-in expressions represent specific built-in values provided by the
+//! simulation context. For example, the current simulation time is a built-in
+//! expression accessible from the shader code of any visual effect to animate
+//! it. A built-in expression is represented by a [`BuiltInExpr`].
+//! - Attribute expressions represent the value of an attribute of a particle. A
+//! typical example is the particle position, represented by
+//! [`Attribute::POSITION`], which can be obtained as an expression through an
+//! [`AttributeExpr`].
+//! - Property expressions represent the value of a visual effect property, a
+//! quantity assigned by the user on the CPU side and uploaded each frame into
+//! the GPU for precise per-frame control over an effect. It's represented by
+//! a [`PropertyExpr`].
+//! - Unary and binary operations are expressions taking one or two operand
+//! expressions and transforming them. A typical example is the Add operator,
+//! which takes two operand expressions and produces their sum.
+//!
+//! # Building expressions
+//!
+//! The fundamental way to build expressions is to directly write them into a
+//! [`Module`] itself. The [`Module`] type contains various methods to create
+//! new expressions and immediately write them.
+//!
+//! ```
+//! # use bevy_hanabi::*;
+//! let mut module = Module::default();
+//!
+//! // Build and write a literal expression into the module.
+//! let expr = module.lit(3.42);
+//! ```
+//!
+//! Due to the code-first nature of the Expression API however, that approach
+//! can be very verbose. Instead, users are encouraged to use an [`ExprWriter`],
+//! a simple utility to build expressions with a shortened syntax. Once an
+//! expression is built, it can be written into the underlying [`Module`]. This
+//! approach generally makes the code more readable, and is therefore highly
+//! encouraged, but is not mandatory.
+//!
+//! ```
+//! # use bevy_hanabi::*;
+//! // Create a writer owning a new Module
+//! let mut w = ExprWriter::new();
+//!
+//! // Build a complex expression: max(3.42, properties.my_prop)
+//! let prop = w.add_property("my_property", 3.0.into());
+//! let expr = w.lit(3.42).max(w.prop(prop));
+//!
+//! // Finalize the expression and write it into the Module. The returned handle can
+//! // be assign to a modifier input.
+//! let handle = expr.expr();
+//!
+//! // Finish using the writer and recover the Module with all written expressions
+//! let module = w.finish();
+//! ```
+//!
+//! [Node API]: crate::graph::node
+//! [`Modifier`]: crate::Modifier
+//! [`EffectAsset`]: crate::EffectAsset
+
+use std::{cell::RefCell, num::NonZeroU32, rc::Rc};
+
+use bevy::{
+ platform::collections::HashSet,
+ prelude::default,
+ reflect::{Reflect, ReflectDeserialize, ReflectSerialize},
+};
+use serde::{Deserialize, Serialize};
+use thiserror::Error;
+
+use super::Value;
+use crate::{
+ Attribute, ModifierContext, ParticleLayout, Property, PropertyLayout, ScalarType,
+ SlotDimension, TextureLayout, TextureSlot, ToWgslString, ValueType, VectorType,
+};
+
+/// A one-based ID into a collection of a [`Module`].
+type Id = NonZeroU32;
+
+/// Handle of an expression inside a given [`Module`].
+///
+/// A handle uniquely references an [`Expr`] stored inside a [`Module`]. It's a
+/// lightweight representation, similar to a simple array index. For this
+/// reason, it's easily copyable. However it's also lacking any kind of error
+/// checking, and mixing handles to different modules produces undefined
+/// behaviors (like an index does when indexing the wrong array).
+///
+/// # Serialization
+///
+/// [`ExprHandle`] is serialized as a string `#<id>`, where `<id>` is the
+/// 1-based integer index of the expression in the implicitly associated
+/// [`Module`]'s expression array. Valid `<id>` values are in the range
+/// `1..=u32::MAX`.
+///
+/// Note that during deserialization, there is no validation that the index
+/// actually refers to a valid entry in the expression array.
+///
+/// Examples of valid values:
+/// - `"#1"`
+/// - `"#42"`
+/// - `"#4000"` -- deserializes OK, but unlikely there are 4000 expressions in
+/// the Module
+///
+/// Examples of **invalid** values:
+/// - `"#0"` -- 0 is a reserved value
+/// - `"#-1"` -- must be positive
+/// - `"#4294967296"` -- out of bounds (> u32::MAX)
+/// - `33` -- not a string
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect)]
+#[reflect(Serialize, Deserialize)]
+#[repr(transparent)]
+pub struct ExprHandle {
+ id: Id,
+}
+
+impl serde::Serialize for ExprHandle {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: serde::Serializer,
+ {
+ serializer.serialize_str(&format!("#{}", self.id.get()))
+ }
+}
+
+impl<'de> serde::Deserialize<'de> for ExprHandle {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ struct IdVisitor;
+
+ impl<'de2> serde::de::Visitor<'de2> for IdVisitor {
+ type Value = ExprHandle;
+
+ fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
+ formatter.write_str(
+ "a string of the form \"#<N>\" where <N> is a non-zero expression index",
+ )
+ }
+
+ fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
+ where
+ E: serde::de::Error,
+ {
+ if v.len() > 1 && v.chars().nth(0) == Some('#') {
+ let id = v[1..]
+ .parse::<u32>()
+ .map_err(|_| serde::de::Error::custom("Failed to parse ID value"))?;
+ NonZeroU32::try_from(id)
+ .map(|id| ExprHandle { id })
+ .map_err(|_| serde::de::Error::custom("Invalid ID value"))
+ } else {
+ Err(serde::de::Error::custom(
+ "Invalid ID format (expected '#N')",
+ ))
+ }
+ }
+
+ fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
+ where
+ E: serde::de::Error,
+ {
+ self.visit_str(&v[..])
+ }
+ }
+
+ deserializer.deserialize_any(IdVisitor)
+ }
+}
+
+impl ExprHandle {
+ /// Create a new handle from a 1-based [`Id`].
+ #[allow(dead_code)]
+ fn new(id: Id) -> Self {
+ Self { id }
+ }
+
+ /// Create a new handle from a 1-based [`Id`] as a `usize`, for cases where
+ /// the index is known to be non-zero already.
+ #[allow(unsafe_code)]
+ unsafe fn new_unchecked(id: usize) -> Self {
+ debug_assert!(id != 0);
+ Self {
+ id: NonZeroU32::new_unchecked(id as u32),
+ }
+ }
+
+ /// Get the zero-based index into the array of the module.
+ pub fn index(&self) -> usize {
+ (self.id.get() - 1) as usize
+ }
+}
+
+/// Handle of a property inside a given [`Module`].
+///
+/// A handle uniquely references a [`Property`] stored inside a [`Module`]. It's
+/// a lightweight representation, similar to a simple array index. For this
+/// reason, it's easily copyable. However it's also lacking any kind of error
+/// checking, and mixing handles to different modules produces undefined
+/// behaviors (like an index does when indexing the wrong array).
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect, Serialize, Deserialize,
+)]
+#[repr(transparent)]
+#[serde(transparent)]
+pub struct PropertyHandle {
+ id: Id,
+}
+
+impl PropertyHandle {
+ /// Create a new handle from a 1-based [`Id`].
+ #[allow(dead_code)]
+ fn new(id: Id) -> Self {
+ Self { id }
+ }
+
+ /// Create a new handle from a 1-based [`Id`] as a `usize`, for cases where
+ /// the index is known to be non-zero already.
+ #[allow(unsafe_code)]
+ unsafe fn new_unchecked(id: usize) -> Self {
+ debug_assert!(id != 0);
+ Self {
+ id: NonZeroU32::new_unchecked(id as u32),
+ }
+ }
+
+ /// Get the zero-based index into the array of the module.
+ pub fn index(&self) -> usize {
+ (self.id.get() - 1) as usize
+ }
+}
+
+/// Handle of a texture inside a given [`Module`].
+///
+/// A handle uniquely references a [`TextureSlot`] stored inside a [`Module`].
+/// It's a lightweight representation, similar to a simple array index. For this
+/// reason, it's easily copyable. However it's also lacking any kind of error
+/// checking, and mixing handles to different modules produces undefined
+/// behaviors (like an index does when indexing the wrong array).
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect, Serialize, Deserialize,
+)]
+#[repr(transparent)]
+#[serde(transparent)]
+pub struct TextureHandle {
+ id: Id,
+}
+
+impl TextureHandle {
+ /// Create a new handle from a 1-based [`Id`].
+ #[allow(dead_code)]
+ fn new(id: Id) -> Self {
+ Self { id }
+ }
+
+ /// Create a new handle from a 1-based [`Id`] as a `usize`, for cases where
+ /// the index is known to be non-zero already.
+ #[allow(unsafe_code)]
+ unsafe fn new_unchecked(id: usize) -> Self {
+ debug_assert!(id != 0);
+ Self {
+ id: NonZeroU32::new_unchecked(id as u32),
+ }
+ }
+
+ /// Get the zero-based index into the array of the module.
+ #[allow(dead_code)]
+ fn index(&self) -> usize {
+ (self.id.get() - 1) as usize
+ }
+}
+
+/// Container for expressions.
+///
+/// A module represents a storage for a set of expressions used in a single
+/// [`EffectAsset`]. Modules are not reusable accross effect assets; each effect
+/// asset owns a single module, containing all the expressions used in all the
+/// modifiers attached to that asset. However, for convenience, a module can be
+/// cloned into an unrelated module, and the clone can be assigned to another
+/// effect asset.
+///
+/// Modules are built incrementally. Expressions are written into the module
+/// through convenience helpers like [`lit()`] or [`attr()`]. Alternatively, an
+/// [`ExprWriter`] can be used to populate a new or existing module. Either way,
+/// once an expression is written into a module, it cannot be modified or
+/// deleted. Modules are not designed to be used as editing structures, but as
+/// storage and serialization ones.
+///
+/// [`EffectAsset`]: crate::EffectAsset
+/// [`lit()`]: Module::lit
+/// [`attr()`]: Module::attr
+#[derive(Debug, Default, Clone, PartialEq, Hash, Reflect, Serialize, Deserialize)]
+pub struct Module {
+ /// Expressions defined in the module.
+ expressions: Vec<Expr>,
+ /// Properties used as part of a [`PropertyExpr`].
+ properties: Vec<Property>,
+ /// Texture layout.
+ texture_layout: TextureLayout,
+}
+
+macro_rules! impl_module_unary {
+ ($t: ident, $T: ident) => {
+ #[doc = concat!("Build a [`UnaryOperator::", stringify!($T), "`](crate::graph::expr::UnaryOperator::", stringify!($T),") unary expression and append it to the module.\n\nThis is a shortcut for [`unary(UnaryOperator::", stringify!($T), ", inner)`](crate::graph::expr::Module::unary).")]
+ #[inline]
+ pub fn $t(&mut self, inner: ExprHandle) -> ExprHandle {
+ self.unary(UnaryOperator::$T, inner)
+ }
+ };
+}
+
+macro_rules! impl_module_binary {
+ ($t: ident, $T: ident) => {
+ #[doc = concat!("Build a [`BinaryOperator::", stringify!($T), "`](crate::graph::expr::BinaryOperator::", stringify!($T),") binary expression and append it to the module.\n\nThis is a shortcut for [`binary(BinaryOperator::", stringify!($T), ", left, right)`](crate::graph::expr::Module::binary).")]
+ #[inline]
+ pub fn $t(&mut self, left: ExprHandle, right: ExprHandle) -> ExprHandle {
+ self.binary(BinaryOperator::$T, left, right)
+ }
+ };
+}
+
+macro_rules! impl_module_ternary {
+ ($t: ident, $T: ident) => {
+ #[doc = concat!("Build a [`TernaryOperator::", stringify!($T), "`](crate::graph::expr::TernaryOperator::", stringify!($T),") ternary expression and append it to the module.\n\nThis is a shortcut for [`ternary(TernaryOperator::", stringify!($T), ", first, second, third)`](crate::graph::expr::Module::ternary).")]
+ #[inline]
+ pub fn $t(&mut self, first: ExprHandle, second: ExprHandle, third: ExprHandle) -> ExprHandle {
+ self.ternary(TernaryOperator::$T, first, second, third)
+ }
+ };
+}
+
+impl Module {
+ /// Create a new module from an existing collection of expressions.
+ pub fn from_raw(expr: Vec<Expr>) -> Self {
+ Self {
+ expressions: expr,
+ properties: vec![],
+ texture_layout: default(),
+ }
+ }
+
+ /// Get all the expressions in this module.
+ pub fn expressions(&self) -> impl Iterator<Item = (ExprHandle, &Expr)> {
+ self.expressions.iter().enumerate().map(|(index, expr)| {
+ (
+ // SAFETY - We directly iterate over the array with enumerate() so all indices are
+ // valid by design.
+ #[allow(unsafe_code)]
+ unsafe {
+ ExprHandle::new_unchecked(index + 1)
+ },
+ expr,
+ )
+ })
+ }
+
+ /// Append a new expression to the module.
+ pub fn add_expr(&mut self, expr: impl Into<Expr>) -> ExprHandle {
+ self.expressions.push(expr.into());
+ #[allow(unsafe_code)]
+ unsafe {
+ ExprHandle::new_unchecked(self.expressions.len())
+ }
+ }
+
+ /// Add a new property to the module.
+ ///
+ /// See [`Property`] for more details on what effect properties are.
+ ///
+ /// # Panics
+ ///
+ /// Panics if a property with the same name already exists.
+ pub fn add_property(
+ &mut self,
+ name: impl Into<String>,
+ default_value: Value,
+ ) -> PropertyHandle {
+ let name = name.into();
+ assert!(!self.properties.iter().any(|p| p.name() == name));
+ self.properties.push(Property::new(name, default_value));
+ // SAFETY - We just pushed a new property into the array, so its length is
+ // non-zero.
+ #[allow(unsafe_code)]
+ unsafe {
+ PropertyHandle::new_unchecked(self.properties.len())
+ }
+ }
+
+ /// Get an existing property by handle.
+ ///
+ /// Existing properties are properties previously created with
+ /// [`add_property()`].
+ ///
+ /// [`add_property()`]: crate::Module::add_property
+ pub fn get_property(&self, property: PropertyHandle) -> Option<&Property> {
+ self.properties.get(property.index())
+ }
+
+ /// Get an existing property by name.
+ ///
+ /// Existing properties are properties previously created with
+ /// [`add_property()`].
+ ///
+ /// [`add_property()`]: crate::Module::add_property
+ pub fn get_property_by_name(&self, name: &str) -> Option<PropertyHandle> {
+ self.properties
+ .iter()
+ .enumerate()
+ .find(|(_, prop)| prop.name() == name)
+ .map(|(index, _)| PropertyHandle::new(NonZeroU32::new(index as u32 + 1).unwrap()))
+ }
+
+ /// Get the list of existing properties.
+ pub fn properties(&self) -> &[Property] {
+ &self.properties
+ }
+
+ /// Add a new texture slot to the module.
+ ///
+ /// The `name` parameter defines a new [`TextureSlot`] associated with this
+ /// module, and must be unique inside this module. A unique index is also
+ /// associated with the slot, corresponding to the value returned by
+ /// [`TextureLayout::get_slot_by_name()`].
+ ///
+ /// Once a slot is added, an actual texture resource, defined by its
+ /// `Handle<Image>`, is bound to that slot through the
+ /// [`EffectMaterial`] component. Expressions like [`TextureSampleExpr`] can
+ /// be used to sample the texture using the returned [`TextureHandle`].
+ ///
+ /// # Returns
+ ///
+ /// The handle of the texture inside this module. This handle is used in
+ /// expressions like [`TextureSampleExpr`] or [`TextureLoadExpr`] to
+ /// reference this texture slot.
+ ///
+ /// # Panics
+ ///
+ /// Panics if a texture slot with the same name already exists inside this
+ /// module. Different effect asset (different modules) can have the same
+ /// slot name.
+ ///
+ /// [`EffectMaterial`]: crate::EffectMaterial
+ pub fn add_texture_slot(
+ &mut self,
+ name: impl Into<String>,
+ slot_dimension: SlotDimension,
+ ) -> TextureHandle {
+ let name = name.into();
+ assert!(!self.texture_layout.layout.iter().any(|t| t.name == name));
+ self.texture_layout.layout.push(TextureSlot {
+ name,
+ dimension: slot_dimension,
+ });
+ // SAFETY - We just pushed a new slot into the array, so its length is non-zero.
+ #[allow(unsafe_code)]
+ unsafe {
+ TextureHandle::new_unchecked(self.texture_layout.layout.len())
+ }
+ }
+
+ /// Insert into the given set all attributes referenced by any
+ /// [`AttributeExpr`] present in the module.
+ ///
+ /// Note that this **excludes** the attributes from an
+ /// [`Expr::ParentAttribute`] expression.
+ pub fn gather_attributes(&self, set: &mut HashSet<Attribute>) {
+ for expr in &self.expressions {
+ if let Expr::Attribute(attr) = expr {
+ set.insert(attr.attr);
+ }
+ }
+ }
+
+ /// Build a literal expression and append it to the module.
+ #[inline]
+ pub fn lit<V>(&mut self, value: V) -> ExprHandle
+ where
+ Value: From<V>,
+ {
+ self.add_expr(Expr::Literal(LiteralExpr::new(value)))
+ }
+
+ /// Build an attribute expression and append it to the module.
+ #[inline]
+ pub fn attr(&mut self, attr: Attribute) -> ExprHandle {
+ self.add_expr(Expr::Attribute(AttributeExpr::new(attr)))
+ }
+
+ /// Build a parent attribute expression and append it to the module.
+ #[inline]
+ pub fn parent_attr(&mut self, attr: Attribute) -> ExprHandle {
+ self.add_expr(Expr::ParentAttribute(AttributeExpr::new(attr)))
+ }
+
+ /// Build a property expression and append it to the module.
+ ///
+ /// A property expression retrieves the value of the given property.
+ #[inline]
+ pub fn prop(&mut self, property: PropertyHandle) -> ExprHandle {
+ self.add_expr(Expr::Property(PropertyExpr::new(property)))
+ }
+
+ /// Build a built-in expression and append it to the module.
+ #[inline]
+ pub fn builtin(&mut self, op: BuiltInOperator) -> ExprHandle {
+ self.add_expr(Expr::BuiltIn(BuiltInExpr::new(op)))
+ }
+
+ /// Build a unary expression and append it to the module.
+ ///
+ /// The handle to the expression representing the operand of the unary
+ /// operation must be valid, that is reference an expression
+ /// contained in the current [`Module`].
+ ///
+ /// # Panics
+ ///
+ /// Panics in some cases if the operand handle do not reference an existing
+ /// expression in the current module. Note however that this check can
+ /// miss some invalid handles (false negative), so only represents an
+ /// extra safety net that users shouldn't rely exclusively on
+ /// to ensure the operand handles are valid. Instead, it's the
+ /// responsibility of the user to ensure the operand handle references an
+ /// existing expression in the current [`Module`].
+ #[inline]
+ pub fn unary(&mut self, op: UnaryOperator, inner: ExprHandle) -> ExprHandle {
+ assert!(inner.index() < self.expressions.len());
+ self.add_expr(Expr::Unary { op, expr: inner })
+ }
+
+ impl_module_unary!(abs, Abs);
+ impl_module_unary!(acos, Acos);
+ impl_module_unary!(asin, Asin);
+ impl_module_unary!(atan, Atan);
+ impl_module_unary!(all, All);
+ impl_module_unary!(any, Any);
+ impl_module_unary!(ceil, Ceil);
+ impl_module_unary!(cos, Cos);
+ impl_module_unary!(exp, Exp);
+ impl_module_unary!(exp2, Exp2);
+ impl_module_unary!(floor, Floor);
+ impl_module_unary!(fract, Fract);
+ impl_module_unary!(inverse_sqrt, InvSqrt);
+ impl_module_unary!(length, Length);
+ impl_module_unary!(log, Log);
+ impl_module_unary!(log2, Log2);
+ impl_module_unary!(normalize, Normalize);
+ impl_module_unary!(pack4x8snorm, Pack4x8snorm);
+ impl_module_unary!(pack4x8unorm, Pack4x8unorm);
+ impl_module_unary!(round, Round);
+ impl_module_unary!(saturate, Saturate);
+ impl_module_unary!(sign, Sign);
+ impl_module_unary!(sin, Sin);
+ impl_module_unary!(sqrt, Sqrt);
+ impl_module_unary!(tan, Tan);
+ impl_module_unary!(unpack4x8snorm, Unpack4x8snorm);
+ impl_module_unary!(unpack4x8unorm, Unpack4x8unorm);
+ impl_module_unary!(w, W);
+ impl_module_unary!(x, X);
+ impl_module_unary!(y, Y);
+ impl_module_unary!(z, Z);
+
+ /// Build a binary expression and append it to the module.
+ ///
+ /// The handles to the expressions representing the left and right operands
+ /// of the binary operation must be valid, that is reference expressions
+ /// contained in the current [`Module`].
+ ///
+ /// # Panics
+ ///
+ /// Panics in some cases if either of the left or right operand handles do
+ /// not reference existing expressions in the current module. Note however
+ /// that this check can miss some invalid handles (false negative), so only
+ /// represents an extra safety net that users shouldn't rely exclusively on
+ /// to ensure the operand handles are valid. Instead, it's the
+ /// responsibility of the user to ensure handles reference existing
+ /// expressions in the current [`Module`].
+ #[inline]
+ pub fn binary(
+ &mut self,
+ op: BinaryOperator,
+ left: ExprHandle,
+ right: ExprHandle,
+ ) -> ExprHandle {
+ assert!(left.index() < self.expressions.len());
+ assert!(right.index() < self.expressions.len());
+ self.add_expr(Expr::Binary { op, left, right })
+ }
+
+ impl_module_binary!(add, Add);
+ impl_module_binary!(atan2, Atan2);
+ impl_module_binary!(cross, Cross);
+ impl_module_binary!(distance, Distance);
+ impl_module_binary!(div, Div);
+ impl_module_binary!(dot, Dot);
+ impl_module_binary!(ge, GreaterThanOrEqual);
+ impl_module_binary!(gt, GreaterThan);
+ impl_module_binary!(le, LessThanOrEqual);
+ impl_module_binary!(lt, LessThan);
+ impl_module_binary!(max, Max);
+ impl_module_binary!(min, Min);
+ impl_module_binary!(mul, Mul);
+ impl_module_binary!(rem, Remainder);
+ impl_module_binary!(step, Step);
+ impl_module_binary!(sub, Sub);
+ impl_module_binary!(uniform, UniformRand);
+ impl_module_binary!(normal, NormalRand);
+ impl_module_binary!(vec2, Vec2);
+ impl_module_binary!(vec4_xyz_w, Vec4XyzW);
+
+ /// Build a ternary expression and append it to the module.
+ ///
+ /// The handles to the expressions representing the three operands of the
+ /// ternary operation must be valid, that is reference expressions
+ /// contained in the current [`Module`].
+ ///
+ /// # Panics
+ ///
+ /// Panics in some cases if any of the operand handles do not reference
+ /// existing expressions in the current module. Note however
+ /// that this check can miss some invalid handles (false negative), so only
+ /// represents an extra safety net that users shouldn't rely exclusively on
+ /// to ensure the operand handles are valid. Instead, it's the
+ /// responsibility of the user to ensure handles reference existing
+ /// expressions in the current [`Module`].
+ #[inline]
+ pub fn ternary(
+ &mut self,
+ op: TernaryOperator,
+ first: ExprHandle,
+ second: ExprHandle,
+ third: ExprHandle,
+ ) -> ExprHandle {
+ assert!(first.index() < self.expressions.len());
+ assert!(second.index() < self.expressions.len());
+ assert!(third.index() < self.expressions.len());
+ self.add_expr(Expr::Ternary {
+ op,
+ first,
+ second,
+ third,
+ })
+ }
+
+ impl_module_ternary!(mix, Mix);
+ impl_module_ternary!(clamp, Clamp);
+ impl_module_ternary!(smoothstep, SmoothStep);
+ impl_module_ternary!(vec3, Vec3);
+
+ /// Build a cast expression and append it to the module.
+ ///
+ /// The handle to the expressions representing the operand of the cast
+ /// operation must be valid, that is reference expressions contained in
+ /// the current [`Module`].
+ ///
+ /// # Panics
+ ///
+ /// Panics in some cases if the operand handle does not reference existing
+ /// expressions in the current module. Note however that this check can
+ /// miss some invalid handles (false negative), so only represents an
+ /// extra safety net that users shouldn't rely exclusively on
+ /// to ensure the operand handles are valid. Instead, it's the
+ /// responsibility of the user to ensure handles reference existing
+ /// expressions in the current [`Module`].
+ ///
+ /// Panics if the resulting cast expression is not valid. See
+ /// [`CastExpr::is_valid()`] for the exact meaning.
+ pub fn cast(&mut self, expr: ExprHandle, target: impl Into<ValueType>) -> ExprHandle {
+ assert!(expr.index() < self.expressions.len());
+ let target = target.into();
+ let expr = CastExpr::new(expr, target);
+ if let Some(valid) = expr.is_valid(self) {
+ assert!(valid);
+ }
+ self.add_expr(Expr::Cast(expr))
+ }
+
+ /// Get an existing expression from its handle.
+ #[inline]
+ pub fn get(&self, expr: ExprHandle) -> Option<&Expr> {
+ let index = expr.index();
+ self.expressions.get(index)
+ }
+
+ /// Get an existing expression from its handle.
+ #[inline]
+ pub fn get_mut(&mut self, expr: ExprHandle) -> Option<&mut Expr> {
+ let index = expr.index();
+ self.expressions.get_mut(index)
+ }
+
+ /// Get an existing expression from its handle.
+ #[inline]
+ pub fn try_get(&self, expr: ExprHandle) -> Result<&Expr, ExprError> {
+ let index = expr.index();
+ self.expressions
+ .get(index)
+ .ok_or(ExprError::InvalidExprHandleError(format!(
+ "Cannot find expression with handle {:?} in the current module. Check that the Module used to build the expression was the same used in the EvalContext or the original EffectAsset.", expr)))
+ }
+
+ /// Get an existing expression from its handle.
+ #[inline]
+ pub fn try_get_mut(&mut self, expr: ExprHandle) -> Result<&mut Expr, ExprError> {
+ let index = expr.index();
+ self.expressions
+ .get_mut(index)
+ .ok_or(ExprError::InvalidExprHandleError(format!(
+ "Cannot find expression with handle {:?} in the current module. Check that the Module used to build the expression was the same used in the EvalContext or the original EffectAsset.", expr)))
+ }
+
+ /// Is the expression resulting in a compile-time constant which can be
+ /// hard-coded into a shader's code?
+ ///
+ /// # Panics
+ ///
+ /// Panics if `expr` doesn't refer to an expression of this module.
+ #[inline]
+ pub fn is_const(&self, expr: ExprHandle) -> bool {
+ let expr = self.get(expr).unwrap();
+ expr.is_const(self)
+ }
+
+ /// Has the expression any side-effect?
+ ///
+ /// Expressions with side-effect need to be stored into temporary variables
+ /// when the shader code is emitted, so that the side effect is only applied
+ /// once when the expression is reused in multiple locations.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `expr` doesn't refer to an expression of this module.
+ pub fn has_side_effect(&self, expr: ExprHandle) -> bool {
+ let expr = self.get(expr).unwrap();
+ expr.has_side_effect(self)
+ }
+
+ /// Get the texture layout of this module.
+ pub fn texture_layout(&self) -> TextureLayout {
+ self.texture_layout.clone()
+ }
+}
+
+/// Errors raised when manipulating expressions [`Expr`] and node graphs
+/// [`Graph`].
+///
+/// [`Graph`]: crate::graph::Graph
+#[derive(Debug, Clone, PartialEq, Eq, Error)]
+#[non_exhaustive]
+pub enum ExprError {
+ /// Expression type error.
+ ///
+ /// Generally used for invalid type conversion (casting).
+ #[error("Type error: {0}")]
+ TypeError(String),
+
+ /// Expression syntax error.
+ #[error("Syntax error: {0}")]
+ SyntaxError(String),
+
+ /// Generic graph evaluation error.
+ #[error("Graph evaluation error: {0}")]
+ GraphEvalError(String),
+
+ /// Error resolving a property.
+ ///
+ /// An unknown property was not defined in the evaluation context, which
+ /// usually means that the property was not defined with
+ /// [`Module::add_property()`].
+ #[error("Property error: {0}")]
+ PropertyError(String),
+
+ /// Invalid expression handle not referencing any existing [`Expr`] in the
+ /// evaluation [`Module`].
+ ///
+ /// This error is commonly raised when using an [`ExprWriter`] and
+ /// forgetting to transfer the underlying [`Module`] where the expressions
+ /// are written to the [`EffectAsset`]. See [`ExprWriter`] for details.
+ ///
+ /// [`EffectAsset`]: crate::EffectAsset
+ #[error("Invalid expression handle: {0}")]
+ InvalidExprHandleError(String),
+
+ /// Invalid modifier context.
+ ///
+ /// The operation was expecting a given [`ModifierContext`], but instead
+ /// another [`ModifierContext`] was available.
+ #[error("Invalid modifier context {0}, expected {1} instead.{2}")]
+ InvalidModifierContext(ModifierContext, ModifierContext, &'static str),
+
+ /// Texture slot index out of bounds.
+ ///
+ /// Some expression attempted to index a texture slot out of bounds.
+ #[error("Texture slot #{0} out of bounds; effect has only {1} slots.")]
+ SlotBoundsError(u32, u32),
+
+ /// Texture slot dimension mismatch.
+ ///
+ /// Some expression expected a slot dimension, but the actual dimension of
+ /// the slot declared in the [`Module`] was different.
+ #[error("Texture slot #{0} has dimension {1:?}, but an expression expected a dimension of {2:?} instead.")]
+ SlotDimensionError(u32, SlotDimension, SlotDimension),
+}
+
+/// Evaluation context for transforming expressions into WGSL code.
+///
+/// The evaluation context references a [`Module`] storing all [`Expr`] in use,
+/// as well as a [`ParticleLayout`] defining the existing attributes of each
+/// particle and their layout in memory, and a [`PropertyLayout`] defining
+/// existing properties and their layout in memory. These together define the
+/// context within which expressions are evaluated.
+///
+/// A same expression can be valid in one context and invalid in another. The
+/// most obvious example is a [`PropertyExpr`] which is only valid if the
+/// property is actually defined in the property layout of the evaluation
+/// context.
+pub trait EvalContext {
+ /// Get the modifier context of the evaluation.
+ fn modifier_context(&self) -> ModifierContext;
+
+ /// Get the particle layout of the effect.
+ fn particle_layout(&self) -> &ParticleLayout;
+
+ /// Get the property layout of the effect.
+ fn property_layout(&self) -> &PropertyLayout;
+
+ /// Get the texture layout of the effect.
+ fn texture_layout(&self) -> &TextureLayout;
+
+ /// Evaluate an expression, returning its WGSL shader code.
+ ///
+ /// The evaluation is guaranteed to be unique. Calling `eval()` multiple
+ /// times with the same handle will return the same result. If the
+ /// expression referenced by `handle` has side effects, it's evaluated only
+ /// once on first call, stored in a local variable, and the variable cached
+ /// and returned on subsequent calls.
+ fn eval(&mut self, module: &Module, handle: ExprHandle) -> Result<String, ExprError>;
+
+ /// Generate a unique local variable name.
+ ///
+ /// Each time this function is called, a new unique name is generated. The
+ /// name is guaranteed to be unique within the current evaluation context
+ /// only. Do not use for global top-level identifiers.
+ ///
+ /// The variable name is not registered automatically in the [`Module`]. If
+ /// you call `make_local_var()` but doesn't use the returned name, it won't
+ /// appear in the shader.
+ fn make_local_var(&mut self) -> String;
+
+ /// Push an intermediate statement during an evaluation.
+ ///
+ /// Intermediate statements are inserted before the expression evaluation
+ /// which produced them. They're generally used to define temporary local
+ /// variables, for example to store the result of expressions with side
+ /// effects.
+ fn push_stmt(&mut self, stmt: &str);
+
+ /// Create a function.
+ ///
+ /// Create a new function with the given `func_name` inside the given
+ /// [`Module`]. The function takes a list of arguments `args`, which are
+ /// copied verbatim into the shader code without any validation. The body of
+ /// the function is generated by invoking the given closure once with the
+ /// input `module` and a temporary [`EvalContext`] local to the function.
+ /// The closure must return the generated shader code of the function
+ /// body. Any statement pushed to the temporary function context with
+ /// [`EvalContext::push_stmt()`] is emitted inside the function body before
+ /// the returned code. The function can subsequently be called from the
+ /// parent context by generating code to call `func_name`, with the correct
+ /// arguments.
+ fn make_fn(
+ &mut self,
+ func_name: &str,
+ args: &str,
+ ret: Option<&str>,
+ module: &mut Module,
+ f: &mut dyn FnMut(&mut Module, &mut dyn EvalContext) -> Result<String, ExprError>,
+ ) -> Result<(), ExprError>;
+
+ /// Check if the particle attribute struct is a pointer?
+ ///
+ /// In some context the attribute struct (named 'particle' in WGSL code) is
+ /// a pointer instead of being a struct instance. This happens in particular
+ /// when defining a function for a modifier, and passing the attribute
+ /// struct to be modified. In that case the generated code needs to emit
+ /// a pointer indirection code to access the fields of the struct.
+ fn is_attribute_pointer(&self) -> bool;
+}
+
+/// Language expression producing a value.
+#[derive(Debug, Clone, Copy, PartialEq, Hash, Reflect, Serialize, Deserialize)]
+pub enum Expr {
+ /// Built-in expression ([`BuiltInExpr`]).
+ ///
+ /// A built-in expression provides access to some internal
+ /// quantities like the simulation time.
+ BuiltIn(BuiltInExpr),
+
+ /// Literal expression ([`LiteralExpr`]).
+ ///
+ /// A literal expression represents a shader constants.
+ Literal(LiteralExpr),
+
+ /// Property expression ([`PropertyExpr`]).
+ ///
+ /// A property expression represents the value of an [`EffectAsset`]'s
+ /// property.
+ ///
+ /// [`EffectAsset`]: crate::EffectAsset
+ Property(PropertyExpr),
+
+ /// Attribute expression ([`AttributeExpr`]).
+ ///
+ /// An attribute expression represents the value of an attribute for a
+ /// particle, like its position or velocity.
+ Attribute(AttributeExpr),
+
+ /// Attribute expression ([`AttributeExpr`]) from a parent effect.
+ ///
+ /// An attribute expression represents the value of an attribute for a
+ /// particle, like its position or velocity. This attribute however refers
+ /// to the parent particle which spawned this one, via GPU events.
+ ///
+ /// This attribute is only valid when used in init modifiers, from an effect
+ /// with a parent effect (an effect which has an [`EffectParent`]
+ /// component).
+ ///
+ /// [`EffectParent`]: crate::EffectParent
+ ParentAttribute(AttributeExpr),
+
+ /// Unary operation expression.
+ ///
+ /// A unary operation transforms an expression into another expression.
+ Unary {
+ /// Unary operator.
+ op: UnaryOperator,
+ /// Operand the unary operation applies to.
+ expr: ExprHandle,
+ },
+
+ /// Binary operation expression.
+ ///
+ /// A binary operation composes two expressions into a third one.
+ Binary {
+ /// Binary operator.
+ op: BinaryOperator,
+ /// Left-hand side operand the binary operation applies to.
+ left: ExprHandle,
+ /// Right-hand side operand the binary operation applies to.
+ right: ExprHandle,
+ },
+
+ /// Ternary operation expression.
+ ///
+ /// A ternary operation composes three expressions into a fourth one.
+ Ternary {
+ /// Ternary operator.
+ op: TernaryOperator,
+ /// First operand the ternary operation applies to.
+ first: ExprHandle,
+ /// Second operand the ternary operation applies to.
+ second: ExprHandle,
+ /// Third operand the ternary operation applies to.
+ third: ExprHandle,
+ },
+
+ /// Cast expression.
+ ///
+ /// An expression to cast an expression to another type.
+ Cast(CastExpr),
+
+ /// Access to textures (filtered).
+ ///
+ /// An expression to sample a texture from the effect's material, with
+ /// filering (including mip-mapping). This is only valid in the fragment
+ /// shader, during the [`ModifierContext::Render`] pass.
+ TextureSample(TextureSampleExpr),
+
+ /// Access to textures (unfiltered).
+ ///
+ /// An expression to load from a texture of the effect's material. All
+ /// textures supported by [`SlotDimension`] are valid.
+ TextureLoad(TextureLoadExpr),
+}
+
+impl Expr {
+ /// Is the expression resulting in a compile-time constant which can be
+ /// hard-coded into a shader's code?
+ ///
+ /// The [`Module`] passed as argument is the owning module of the
+ /// expression, which is used to recursively evaluate the const-ness of the
+ /// entire expression. For some expressions like literals or attributes or
+ /// properties their const-ness is intrinsic to the expression type, but for
+ /// other expressions like binary operations (addition, ...) their
+ /// const-ness depends in turn on the const-ness of their sub-expressions
+ /// (left and right operands), which requires a [`Module`] to be retrieved
+ /// and evaluated.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # let mut module = Module::default();
+ /// // Literals are always constant by definition.
+ /// assert!(Expr::Literal(LiteralExpr::new(1.)).is_const(&module));
+ ///
+ /// // Properties and attributes are never constant, since they're by definition used
+ /// // to provide runtime customization.
+ /// let prop = module.add_property("my_property", 3.0.into());
+ /// assert!(!Expr::Property(PropertyExpr::new(prop)).is_const(&module));
+ /// assert!(!Expr::Attribute(AttributeExpr::new(Attribute::POSITION)).is_const(&module));
+ /// ```
+ pub fn is_const(&self, module: &Module) -> bool {
+ match self {
+ Expr::BuiltIn(expr) => expr.is_const(),
+ Expr::Literal(expr) => expr.is_const(),
+ Expr::Property(expr) => expr.is_const(),
+ Expr::Attribute(expr) => expr.is_const(),
+ Expr::ParentAttribute(expr) => expr.is_const(),
+ Expr::Unary { expr, .. } => module.is_const(*expr),
+ Expr::Binary { left, right, .. } => module.is_const(*left) && module.is_const(*right),
+ Expr::Ternary {
+ first,
+ second,
+ third,
+ ..
+ } => module.is_const(*first) && module.is_const(*second) && module.is_const(*third),
+ Expr::Cast(expr) => module.is_const(expr.inner),
+ Expr::TextureSample(_) | Expr::TextureLoad(_) => false,
+ }
+ }
+
+ /// Has the expression any side-effect?
+ ///
+ /// Expressions with side-effect need to be stored into temporary variables
+ /// when the shader code is emitted, so that the side effect is only applied
+ /// once when the expression is reused in multiple locations.
+ pub fn has_side_effect(&self, _: &Module) -> bool {
+ match self {
+ Expr::BuiltIn(expr) => expr.has_side_effect(),
+ Expr::Literal(_) => false,
+ Expr::Property(_) => false,
+ Expr::Attribute(_) => false,
+ Expr::ParentAttribute(_) => false,
+ Expr::Unary { .. } => false,
+ Expr::Binary { op, .. } => {
+ *op == BinaryOperator::UniformRand || *op == BinaryOperator::NormalRand
+ }
+ Expr::Ternary { .. } => false,
+ Expr::Cast(_) => false,
+ Expr::TextureSample(_) | Expr::TextureLoad(_) => false,
+ }
+ }
+
+ /// The type of the value produced by the expression.
+ ///
+ /// If the type is variable and depends on the runtime evaluation context,
+ /// this returns `None`. In that case the type needs to be obtained by
+ /// evaluating the expression with [`eval()`].
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// // Literal expressions always have a constant, build-time value type.
+ /// let expr = Expr::Literal(LiteralExpr::new(1.));
+ /// assert_eq!(
+ /// expr.value_type(),
+ /// Some(ValueType::Scalar(ScalarType::Float))
+ /// );
+ /// ```
+ ///
+ /// [`eval()`]: crate::graph::Expr::eval
+ pub fn value_type(&self) -> Option<ValueType> {
+ match self {
+ Expr::BuiltIn(expr) => Some(expr.value_type()),
+ Expr::Literal(expr) => Some(expr.value_type()),
+ Expr::Property(_) => None,
+ Expr::Attribute(expr) => Some(expr.value_type()),
+ Expr::ParentAttribute(expr) => Some(expr.value_type()),
+ Expr::Unary { .. } => None,
+ Expr::Binary { .. } => None,
+ Expr::Ternary { .. } => None,
+ Expr::Cast(expr) => Some(expr.value_type()),
+ Expr::TextureSample(expr) => Some(expr.value_type()),
+ Expr::TextureLoad(expr) => Some(expr.value_type()),
+ }
+ }
+
+ /// Evaluate the expression in the given context.
+ ///
+ /// Evaluate the full expression as part of the given evaluation context,
+ /// returning the WGSL string representation of the expression on success.
+ ///
+ /// The evaluation context is used to resolve some quantities related to the
+ /// effect asset, like its properties. It also holds the [`Module`] that the
+ /// expression is part of, to allow resolving sub-expressions of operators.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let mut module = Module::default();
+ /// # let pl = PropertyLayout::empty();
+ /// # let pal = ParticleLayout::default();
+ /// # let tl = TextureLayout::default();
+ /// # let mut context = ShaderWriter::new(ModifierContext::Update, &pl, &pal, &tl);
+ /// let handle = module.lit(1.);
+ /// let expr = module.get(handle).unwrap();
+ /// assert_eq!(Ok("1.".to_string()), expr.eval(&module, &mut context));
+ /// ```
+ pub fn eval(
+ &self,
+ module: &Module,
+ context: &mut dyn EvalContext,
+ ) -> Result<String, ExprError> {
+ match self {
+ Expr::BuiltIn(expr) => expr.eval(context),
+ Expr::Literal(expr) => expr.eval(context),
+ Expr::Property(expr) => expr.eval(module, context),
+ Expr::Attribute(expr) => expr.eval(context, false),
+ Expr::ParentAttribute(expr) => expr.eval(context, true),
+ Expr::Unary { op, expr } => {
+ // Recursively evaluate child expressions throught the context to ensure caching
+ let expr = context.eval(module, *expr)?;
+
+ // if expr.value_type() != self.value_type() {
+ // return Err(ExprError::TypeError(format!(
+ // "Cannot apply normalize() function to non-vector expression: {}",
+ // expr.unwrap_or("(error evaluating expression)".to_string())
+ // )));
+ // }
+
+ Ok(if op.is_functional() {
+ format!("{}({})", op.to_wgsl_string(), expr)
+ } else {
+ format!("{}.{}", expr, op.to_wgsl_string())
+ })
+ }
+ Expr::Binary { op, left, right } => {
+ // Recursively evaluate child expressions throught the context to ensure caching
+ let compiled_left = context.eval(module, *left)?;
+ let compiled_right = context.eval(module, *right)?;
+
+ // if !self.input.value_type().is_vector() {
+ // return Err(ExprError::TypeError(format!(
+ // "Cannot apply normalize() function to non-vector expression: {}",
+ // expr.unwrap_or("(error evaluating expression)".to_string())
+ // )));
+ // }
+
+ let body = if op.is_functional() {
+ if op.needs_type_suffix() {
+ let lhs_type = module.get(*left).and_then(|arg| arg.value_type());
+ let rhs_type = module.get(*right).and_then(|arg| arg.value_type());
+ if lhs_type.is_none() || rhs_type.is_none() {
+ return Err(ExprError::TypeError(
+ "Can't determine the type of the operand".to_string(),
+ ));
+ }
+ if lhs_type != rhs_type {
+ return Err(ExprError::TypeError("Mismatched types".to_string()));
+ }
+ let value_type = lhs_type.unwrap();
+ let suffix = match value_type {
+ ValueType::Scalar(ScalarType::Float) => "f",
+ ValueType::Vector(vector_type)
+ if vector_type.elem_type() == ScalarType::Float =>
+ {
+ match vector_type.count() {
+ 2 => "vec2",
+ 3 => "vec3",
+ 4 => "vec4",
+ _ => unreachable!(),
+ }
+ }
+ _ => {
+ // Add more types here as needed.
+ return Err(ExprError::TypeError("Unsupported type".to_string()));
+ }
+ };
+
+ Ok(format!(
+ "{}_{}({}, {})",
+ op.to_wgsl_string(),
+ suffix,
+ compiled_left,
+ compiled_right
+ ))
+ } else {
+ Ok(format!(
+ "{}({}, {})",
+ op.to_wgsl_string(),
+ compiled_left,
+ compiled_right
+ ))
+ }
+ } else {
+ Ok(format!(
+ "({}) {} ({})",
+ compiled_left,
+ op.to_wgsl_string(),
+ compiled_right
+ ))
+ };
+
+ body.map(|body| {
+ check_side_effects_and_create_local_if_needed(
+ context,
+ body,
+ self.has_side_effect(module),
+ )
+ })
+ }
+ Expr::Ternary {
+ op,
+ first,
+ second,
+ third,
+ } => {
+ // Recursively evaluate child expressions throught the context to ensure caching
+ let first = context.eval(module, *first)?;
+ let second = context.eval(module, *second)?;
+ let third = context.eval(module, *third)?;
+
+ // if !self.input.value_type().is_vector() {
+ // return Err(ExprError::TypeError(format!(
+ // "Cannot apply normalize() function to non-vector expression: {}",
+ // expr.unwrap_or("(error evaluating expression)".to_string())
+ // )));
+ // }
+
+ Ok(format!(
+ "{}({}, {}, {})",
+ op.to_wgsl_string(),
+ first,
+ second,
+ third
+ ))
+ }
+ Expr::Cast(expr) => {
+ // Recursively evaluate child expressions throught the context to ensure caching
+ let inner = context.eval(module, expr.inner)?;
+
+ Ok(format!("{}({})", expr.target.to_wgsl_string(), inner))
+ }
+ Expr::TextureSample(expr) => expr.eval(module, context),
+ Expr::TextureLoad(expr) => expr.eval(module, context),
+ }
+ }
+}
+
+/// A literal constant expression like `3.0` or `vec3<f32>(1.0, 2.0, 3.0)`.
+///
+/// Literal expression are compile-time constants. They are always constant
+/// ([`is_const()`] is `true`) and have a value type equal to the type of the
+/// constant itself.
+///
+/// [`is_const()`]: LiteralExpr::is_const
+#[derive(Debug, Clone, Copy, PartialEq, Hash, Reflect, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct LiteralExpr {
+ /// The literal value of this expression.
+ pub value: Value,
+}
+
+impl LiteralExpr {
+ /// Create a new literal expression from a [`Value`].
+ pub fn new<V>(value: V) -> Self
+ where
+ Value: From<V>,
+ {
+ Self {
+ value: value.into(),
+ }
+ }
+
+ /// Is the expression resulting in a compile-time constant which can be
+ /// hard-coded into a shader's code?
+ pub fn is_const(&self) -> bool {
+ true
+ }
+
+ /// Get the value type of the expression.
+ pub fn value_type(&self) -> ValueType {
+ self.value.value_type()
+ }
+
+ /// Evaluate the expression in the given context.
+ pub fn eval(&self, _context: &dyn EvalContext) -> Result<String, ExprError> {
+ Ok(self.value.to_wgsl_string())
+ }
+}
+
+impl ToWgslString for LiteralExpr {
+ fn to_wgsl_string(&self) -> String {
+ self.value.to_wgsl_string()
+ }
+}
+
+impl From<&Value> for LiteralExpr {
+ fn from(value: &Value) -> Self {
+ Self { value: *value }
+ }
+}
+
+impl<T: Into<Value>> From<T> for LiteralExpr {
+ fn from(value: T) -> Self {
+ Self {
+ value: value.into(),
+ }
+ }
+}
+
+/// Expression representing the value of an attribute of a particle.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct AttributeExpr {
+ /// The attribute this expression represents.
+ ///
+ /// The expression evaluates to the value of this attribute at the time of
+ /// evaluation.
+ pub attr: Attribute,
+}
+
+impl AttributeExpr {
+ /// Create a new attribute expression.
+ #[inline]
+ pub fn new(attr: Attribute) -> Self {
+ Self { attr }
+ }
+
+ /// Is the expression resulting in a compile-time constant which can be
+ /// hard-coded into a shader's code?
+ pub fn is_const(&self) -> bool {
+ false
+ }
+
+ /// Get the value type of the expression.
+ pub fn value_type(&self) -> ValueType {
+ self.attr.value_type()
+ }
+
+ /// Evaluate the expression in the given context.
+ pub fn eval(&self, context: &dyn EvalContext, parent: bool) -> Result<String, ExprError> {
+ if self.attr == Attribute::ID {
+ // Pseudo-attribute, not stored in the particle buffer
+ Ok(if parent {
+ "parent_particle_index"
+ } else {
+ "particle_index"
+ }
+ .to_string())
+ } else if self.attr == Attribute::PARTICLE_COUNTER {
+ // Pseudo-attribute, not stored in the particle buffer
+ Ok("particle_counter".to_string())
+ } else {
+ let owner = if parent {
+ "parent_particle"
+ } else {
+ "particle"
+ };
+ if context.is_attribute_pointer() {
+ Ok(format!("(*{}).{}", owner, self.attr.name()))
+ } else {
+ Ok(format!("{}.{}", owner, self.attr.name()))
+ }
+ }
+ }
+}
+
+impl ToWgslString for AttributeExpr {
+ fn to_wgsl_string(&self) -> String {
+ format!("particle.{}", self.attr.name())
+ }
+}
+
+impl From<Attribute> for AttributeExpr {
+ fn from(value: Attribute) -> Self {
+ AttributeExpr::new(value)
+ }
+}
+
+/// Expression representing the value of a property of an effect.
+///
+/// A property expression represents the value of the property at the time the
+/// expression appears. In shader, the expression yields a read from the
+/// property memory location.
+///
+/// To create a property to reference with an expression, use
+/// [`Module::add_property()`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+#[repr(transparent)]
+#[serde(transparent)]
+pub struct PropertyExpr {
+ /// The property this expression represents.
+ ///
+ /// The expression evaluates to the value of this property at the time of
+ /// evaluation.
+ pub property: PropertyHandle,
+}
+
+impl PropertyExpr {
+ /// Create a new property expression.
+ #[inline]
+ pub fn new(property: PropertyHandle) -> Self {
+ Self { property }
+ }
+
+ /// Is the expression resulting in a compile-time constant which can be
+ /// hard-coded into a shader's code?
+ pub fn is_const(&self) -> bool {
+ false
+ }
+
+ /// Evaluate the expression in the given context.
+ pub fn eval(&self, module: &Module, context: &dyn EvalContext) -> Result<String, ExprError> {
+ let prop = module
+ .get_property(self.property)
+ .ok_or(ExprError::PropertyError(format!(
+ "Unknown property handle {:?} in evaluation module.",
+ self.property
+ )))?;
+ if !context.property_layout().contains(prop.name()) {
+ return Err(ExprError::PropertyError(format!(
+ "Unknown property '{}' in evaluation layout.",
+ prop.name()
+ )));
+ }
+
+ Ok(prop.to_wgsl_string())
+ }
+}
+
+/// Expression to cast an expression to another type.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct CastExpr {
+ /// The operand expression to cast.
+ pub inner: ExprHandle,
+ /// The target type to cast to.
+ pub target: ValueType,
+}
+
+impl CastExpr {
+ /// Create a new cast expression.
+ #[inline]
+ pub fn new(inner: ExprHandle, target: impl Into<ValueType>) -> Self {
+ Self {
+ inner,
+ target: target.into(),
+ }
+ }
+
+ /// Get the value type of the expression.
+ ///
+ /// This is the target type the cast converts to.
+ pub fn value_type(&self) -> ValueType {
+ self.target
+ }
+
+ /// Try to evaluate if the cast expression is valid.
+ ///
+ /// The evaluation fails if the value type of the operand cannot be
+ /// determined. In that case, the function returns `None`. This doesn't mean
+ /// the cast expression is invalid, but rather that we cannot currently
+ /// evaluate it, as it likely depends on the runtime context in which it's
+ /// used.
+ ///
+ /// Valid cast expressions are:
+ /// - scalar to scalar
+ /// - scalar to vector
+ /// - vector to vector
+ /// - matrix to matrix
+ ///
+ /// # Returns
+ ///
+ /// - `Some(is_valid)` if the evaluation was successful in determining
+ /// whether the expression is valid or not.
+ /// - `None` if the expression couldn't be evaluated, and so couldn't be
+ /// validated. This generally happens when the inner expression has a
+ /// value type unknown statically (depends on runtime context), which
+ /// prevents evaluating whether the cast expression is valid.
+ pub fn is_valid(&self, module: &Module) -> Option<bool> {
+ let Some(inner) = module.get(self.inner) else {
+ return Some(false);
+ };
+ if let Some(inner_type) = inner.value_type() {
+ match self.target {
+ ValueType::Scalar(_) => {
+ // scalar -> scalar only
+ Some(matches!(inner_type, ValueType::Scalar(_)))
+ }
+ ValueType::Vector(_) => {
+ // {scalar, vector} -> vector
+ Some(!matches!(inner_type, ValueType::Matrix(_)))
+ }
+ ValueType::Matrix(_) => {
+ // matrix -> matrix only
+ Some(matches!(inner_type, ValueType::Matrix(_)))
+ }
+ }
+ } else {
+ None
+ }
+ }
+}
+
+/// Expression to sample a texture from the effect's material with filtering.
+///
+/// This supports all texture types supported by [`SlotDimension`]. The texture
+/// is sampled with [the WGSL `textureSample()` function], and returns a
+/// `vec4<f32>` if the texture is a non-depth texture, or a `f32` if it it; see
+/// [`SlotDimension::is_depth()`]. Note that this read is filtered in all
+/// dimensions, including mip-mapping.
+///
+/// Note that WGSL restricts the use of `textureSample()` to the fragment
+/// shader. Hanabi will emit an error if this expression is used in the
+/// [`ModifierContext::Init`] or [`ModifierContext::Update`]. For
+/// [`ModifierContext::Render`], there's no distinction currently between the
+/// vertex and fragment shader, so Hanabi cannot proactively emit an error if
+/// the expression ends up used in the vertex shader. If you need to read a
+/// texture from any of those forbidden contexts, use [`TextureLoadExpr`]
+/// instead.
+///
+/// [the WGSL `textureSample()` function]: https://www.w3.org/TR/WGSL/#texturesample
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct TextureSampleExpr {
+ /// The index of the texture slot to sample.
+ ///
+ /// A texture slot is defined in the [`Module`] by calling
+ /// [`Module::add_texture_slot()`]. The texture bound to each slot is
+ /// defined in the [`EffectMaterial`] component.
+ ///
+ /// [`EffectMaterial`]: crate::EffectMaterial
+ pub slot_index: u32,
+ /// The type of texture to sample. This must match the dimension of the
+ /// slot at index `slot_index`.
+ pub slot_dimension: SlotDimension,
+ /// The coordinates to sample at. This is a floating-point scalar or vector,
+ /// depending on the image dimension (1D/2D/3D).
+ pub coordinates: ExprHandle,
+ /// Optional array index to load (u32 or i32). Mandatory for loading from
+ /// array textures, and must be `None` for non-array textures. See
+ /// [`SlotDimension::is_array()`].
+ pub array_index: Option<ExprHandle>,
+}
+
+impl TextureSampleExpr {
+ /// Create a new texture sample expression.
+ ///
+ /// Not all combinations of slot dimension and array index are supported.
+ /// The `array_index` must be `Some` if [`SlotDimension::is_array`] is
+ /// `true`, and `None` otherwise. This function returns an error if the
+ /// specified combination is invalid. Check the [WGSL specification] of
+ /// the `textureSample()` function for more details.
+ ///
+ /// [WGSL specification]: https://www.w3.org/TR/WGSL/#texturesample
+ #[inline]
+ pub fn new(
+ slot_index: u32,
+ slot_dimension: SlotDimension,
+ coordinates: ExprHandle,
+ array_index: Option<ExprHandle>,
+ ) -> Result<Self, ExprError> {
+ if slot_dimension.is_array() {
+ if array_index.is_none() {
+ return Err(ExprError::TypeError(
+ "TextureSampleExpr with array texture requires an array index".to_string(),
+ ));
+ }
+ } else {
+ if array_index.is_some() {
+ return Err(ExprError::TypeError(
+ "TextureSampleExpr with non-array texture doesn't support array index"
+ .to_string(),
+ ));
+ }
+ }
+ Ok(Self {
+ slot_index,
+ slot_dimension,
+ coordinates,
+ array_index,
+ })
+ }
+
+ /// Get the value type of the expression.
+ pub fn value_type(&self) -> ValueType {
+ if self.slot_dimension.is_depth() {
+ ValueType::Scalar(ScalarType::Float)
+ } else {
+ ValueType::Vector(VectorType::VEC4F)
+ }
+ }
+
+ /// Try to evaluate if the texture load expression is valid.
+ ///
+ /// This checks that the fields are consistent with the slot dimension, and
+ /// the expressions exist in the module.
+ pub fn is_valid(&self, module: &Module) -> Option<bool> {
+ if self.slot_dimension.is_array() != self.array_index.is_some() {
+ return Some(false);
+ }
+ if module.get(self.coordinates).is_none() {
+ return Some(false);
+ };
+ if let Some(array_index) = self.array_index {
+ if module.get(array_index).is_none() {
+ return Some(false);
+ };
+ }
+ Some(true)
+ }
+
+ /// Evaluate the expression in the given context.
+ pub fn eval(
+ &self,
+ module: &Module,
+ context: &mut dyn EvalContext,
+ ) -> Result<String, ExprError> {
+ // Sampling type texture access can only be used in a fragment shader, so only
+ // in the Render context. This is a WGSL restriction.
+ if context.modifier_context() != ModifierContext::Render {
+ return Err(ExprError::InvalidModifierContext(
+ context.modifier_context(),
+ ModifierContext::Render,
+ " TextureSampleExpr can only be used in a fragment shader. Use TextureLoadExpr instead.",
+ ));
+ }
+
+ let coordinates = module.try_get(self.coordinates)?;
+ let coordinates = coordinates.eval(module, context)?;
+
+ let array_index = if let Some(array_index) = self.array_index {
+ let array_index = module.try_get(array_index)?;
+ array_index.eval(module, context)?
+ } else {
+ // WGSL spec says i32 or u32; both are fine
+ "0".to_string()
+ };
+
+ // Bound-check the slot index
+ let slot_count = context.texture_layout().layout.len() as u32;
+ if self.slot_index >= slot_count {
+ return Err(ExprError::SlotBoundsError(self.slot_index, slot_count));
+ }
+
+ // Validate the expected slot dimension
+ let layout_dimension = context.texture_layout().layout[self.slot_index as usize].dimension;
+ if layout_dimension != self.slot_dimension {
+ return Err(ExprError::SlotDimensionError(
+ self.slot_index,
+ layout_dimension,
+ self.slot_dimension,
+ ));
+ }
+
+ // Note: do not use to_wgsl_string(), we want an index suffix and not a WGSL
+ // literal value.
+ let slot_index = self.slot_index;
+ if self.slot_dimension.is_array() {
+ Ok(format!(
+ "textureSample(material_texture_{slot_index}, material_sampler_{slot_index}, {coordinates}, {array_index})",
+ ))
+ } else {
+ Ok(format!(
+ "textureSample(material_texture_{slot_index}, material_sampler_{slot_index}, {coordinates})",
+ ))
+ }
+ }
+}
+
+/// Expression to load a value from a texture of the effect's material, without
+/// filtering.
+///
+/// This supports all texture types supported by [`SlotDimension`]. The texture
+/// is read with [the WGSL `textureLoad()` function], and returns a
+/// `vec4<f32>` if the texture is a non-depth texture, or a `f32` if it it; see
+/// [`SlotDimension::is_depth()`]. Note that this read is unfiltered; this is
+/// the reason why the expression takes an explicit `mip_level`. To use
+/// filering, including mip-mapping, use [`TextureSampleExpr`] instead, but note
+/// that filtered read can only occur in the fragment shader during the
+/// [`ModifierContext::Render`] pass.
+///
+/// Hanabi currently doesn't support "gather"-type loads (loading 4 values at
+/// once with `textureGather()`).
+///
+/// [the WGSL `textureLoad()` function]: https://www.w3.org/TR/WGSL/#textureload
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct TextureLoadExpr {
+ /// The index of the texture slot to load from.
+ ///
+ /// A texture slot is defined in the [`Module`] by calling
+ /// [`Module::add_texture_slot()`]. The texture bound to each slot is
+ /// defined in the [`EffectMaterial`] component.
+ ///
+ /// [`EffectMaterial`]: crate::EffectMaterial
+ pub slot_index: u32,
+ /// The type of texture to load from. This must match the dimension of the
+ /// slot at index `slot_index`.
+ pub slot_dimension: SlotDimension,
+ /// The coordinates to load at. This is an integral (i32 or u32) scalar or
+ /// vector, depending on the image dimension (1D/2D/3D). Array index and
+ /// mip-map level are specified separately.
+ pub coordinates: ExprHandle,
+ /// Optional array index to load (u32 or i32). Mandatory for loading from
+ /// array textures, and must be `None` for non-array textures.
+ pub array_index: Option<ExprHandle>,
+ /// Optional mip level to load (u32 or i32). Defaults to 0 (full
+ /// resolution).
+ pub mip_level: Option<ExprHandle>,
+}
+
+impl TextureLoadExpr {
+ /// Create a new texture load expression.
+ ///
+ /// Not all combinations of slot dimension and array index / mip-map level
+ /// are supported. Direct loading from cube textures is also not supported
+ /// (only sampled loading, through [`TextureSampleExpr`]). This function
+ /// returns an error if the specified combination is invalid. Check the
+ /// [WGSL specification] of the `textureLoad()` function for more details.
+ ///
+ /// [WGSL specification]: https://www.w3.org/TR/WGSL/#textureload
+ #[inline]
+ pub fn new(
+ slot_index: u32,
+ slot_dimension: SlotDimension,
+ coordinates: ExprHandle,
+ array_index: Option<ExprHandle>,
+ mip_level: Option<ExprHandle>,
+ ) -> Result<Self, ExprError> {
+ if slot_dimension.is_cube() {
+ return Err(ExprError::TypeError(format!(
+ "TextureLoadExpr doesn't support slot dimension {:?}.",
+ slot_dimension
+ )));
+ }
+ if slot_dimension.is_array() {
+ if array_index.is_none() {
+ return Err(ExprError::TypeError(
+ "TextureLoadExpr with array texture requires an array index".to_string(),
+ ));
+ }
+ } else {
+ if array_index.is_some() {
+ return Err(ExprError::TypeError(
+ "TextureLoadExpr with non-array texture doesn't support array index"
+ .to_string(),
+ ));
+ }
+ }
+ Ok(Self {
+ slot_index,
+ slot_dimension,
+ coordinates,
+ array_index,
+ mip_level,
+ })
+ }
+
+ /// Get the value type of the expression.
+ ///
+ /// # Panics
+ ///
+ /// This panics if [`slot_dimension`] is unsupported.
+ ///
+ /// [`slot_dimension`]: Self::slot_dimension
+ pub fn value_type(&self) -> ValueType {
+ assert!(!self.slot_dimension.is_cube());
+ if self.slot_dimension.is_depth() {
+ ValueType::Scalar(ScalarType::Float)
+ } else {
+ ValueType::Vector(VectorType::VEC4F)
+ }
+ }
+
+ /// Try to evaluate if the texture load expression is valid.
+ ///
+ /// This checks that the fields are consistent with the slot dimension, and
+ /// the expressions exist in the module.
+ pub fn is_valid(&self, module: &Module) -> Option<bool> {
+ if !match self.slot_dimension {
+ SlotDimension::D1 | SlotDimension::D2 | SlotDimension::D3 | SlotDimension::DepthD2 => {
+ self.mip_level.is_some() && self.array_index.is_none()
+ }
+ SlotDimension::D2Array | SlotDimension::DepthD2Array => {
+ self.mip_level.is_some() && self.array_index.is_some()
+ }
+ _ => false,
+ } {
+ return Some(false);
+ }
+ if module.get(self.coordinates).is_none() {
+ return Some(false);
+ };
+ if let Some(mip_level) = self.mip_level {
+ if module.get(mip_level).is_none() {
+ return Some(false);
+ };
+ }
+ if let Some(array_index) = self.array_index {
+ if module.get(array_index).is_none() {
+ return Some(false);
+ };
+ }
+ Some(true)
+ }
+
+ /// Evaluate the expression in the given context.
+ pub fn eval(
+ &self,
+ module: &Module,
+ context: &mut dyn EvalContext,
+ ) -> Result<String, ExprError> {
+ let coordinates = module.try_get(self.coordinates)?;
+ let coordinates = coordinates.eval(module, context)?;
+
+ let array_index = if let Some(array_index) = self.array_index {
+ let array_index = module.try_get(array_index)?;
+ array_index.eval(module, context)?
+ } else {
+ // WGSL spec says i32 or u32; both are fine
+ "0".to_string()
+ };
+
+ let mip_level = if let Some(mip_level) = self.mip_level {
+ let mip_level = module.try_get(mip_level)?;
+ mip_level.eval(module, context)?
+ } else {
+ // WGSL spec says i32 or u32; both are fine
+ "0".to_string()
+ };
+
+ // Bound-check the slot index
+ let slot_count = context.texture_layout().layout.len() as u32;
+ if self.slot_index >= slot_count {
+ return Err(ExprError::SlotBoundsError(self.slot_index, slot_count));
+ }
+
+ // Validate the expected slot dimension
+ let layout_dimension = context.texture_layout().layout[self.slot_index as usize].dimension;
+ if layout_dimension != self.slot_dimension {
+ return Err(ExprError::SlotDimensionError(
+ self.slot_index,
+ layout_dimension,
+ self.slot_dimension,
+ ));
+ }
+
+ // Note: do not use to_wgsl_string(), we want an index suffix and not a WGSL
+ // literal value.
+ let slot_index = self.slot_index;
+ match self.slot_dimension {
+ SlotDimension::D1 | SlotDimension::D2 | SlotDimension::D3 | SlotDimension::DepthD2 => {
+ Ok(format!(
+ "textureLoad(material_texture_{slot_index}, {coordinates}, {mip_level})",
+ ))
+ }
+ SlotDimension::D2Array | SlotDimension::DepthD2Array => {
+ Ok(format!(
+ "textureLoad(material_texture_{slot_index}, {coordinates}, {array_index}, {mip_level})",
+ ))
+ }
+ _ => Err(ExprError::TypeError(format!(
+ "TextureLoadExpr doesn't support slot dimension {:?}",
+ self.slot_dimension))),
+ }
+ }
+}
+
+/// Built-in operators.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub enum BuiltInOperator {
+ /// Current effect system simulation time since startup, in seconds.
+ ///
+ /// This is based on the
+ /// [`Time<EffectSimulation>`](crate::time::EffectSimulation) clock.
+ ///
+ /// Type: `f32`
+ Time,
+ /// Delta time, in seconds, since last effect system update.
+ ///
+ /// Type: `f32`
+ DeltaTime,
+ /// Current virtual time since startup, in seconds.
+ ///
+ /// This is based on the [`Time<Virtual>`](bevy::time::Virtual) clock.
+ ///
+ /// Type: `f32`
+ VirtualTime,
+ /// Virtual delta time, in seconds, since last effect system update.
+ ///
+ /// Type: `f32`
+ VirtualDeltaTime,
+ /// Current real time since startup, in seconds.
+ ///
+ /// This is based on the [`Time<Time>`](bevy::time::Real) clock.
+ ///
+ /// Type: `f32`
+ RealTime,
+ /// Real delta time, in seconds, since last effect system update.
+ ///
+ /// Type: `f32`
+ RealDeltaTime,
+ /// Random unit value of the given type.
+ ///
+ /// The type can be any scalar or vector type. Matrix types are not
+ /// supported. The random values generated are uniformly distributed in
+ /// `[0:1]`. For vectors, each component is sampled separately.
+ ///
+ /// The random number generator is from [the PCG family] of PRNGs, and is
+ /// implemented directly inside the shader, and running on the GPU
+ /// exclusively. It's seeded by the [`SpawnerSettings`].
+ ///
+ /// Type: Same as its [`ValueType`].
+ ///
+ /// [the PCG family]: https://www.pcg-random.org/
+ /// [`SpawnerSettings`]: crate::SpawnerSettings
+ Rand(ValueType),
+ /// Value of the alpha cutoff for alpha masking.
+ ///
+ /// This value is only available in the render context. It represents the
+ /// current threshold, generally in \[0:1\], which the particle's fragment
+ /// alpha value will be compared against to determine alpha masking.
+ ///
+ /// The value is initalized at the beginning of the fragment shader to the
+ /// expression stored in [`AlphaMode::Mask`].
+ ///
+ /// Type: `f32`
+ ///
+ /// [`AlphaMode::Mask`]: crate::AlphaMode::Mask
+ AlphaCutoff,
+ /// Alive flag for the particle.
+ ///
+ /// The alive flag is initialized at the beginning of the update pass:
+ /// - If the particle has both the [`Attribute::AGE`] and
+ /// [`Attribute::LIFETIME`], then the initial value at the beginning of
+ /// the update pass is `age < lifetime`.
+ /// - Otherwise, the initial value is `true`.
+ ///
+ /// At the end of the update pass, if the particle has both the
+ /// [`Attribute::AGE`] and [`Attribute::LIFETIME`], then the flag is
+ /// re-evaluated as:
+ ///
+ /// ```wgsl
+ /// is_alive = is_alive && (particle.age < particle.lifetime);
+ /// ```
+ ///
+ /// If the flag is `false` after that, the particle is considered dead and
+ /// it's deallocated.
+ ///
+ /// This flag is only available in the update pass. Attempting to use it
+ /// inside either the init or render passes will generate an invalid shader.
+ ///
+ /// Type: `bool`
+ IsAlive,
+}
+
+impl BuiltInOperator {
+ /// Get the operator name.
+ pub fn name(&self) -> &str {
+ match self {
+ BuiltInOperator::Time => "time",
+ BuiltInOperator::DeltaTime => "delta_time",
+ BuiltInOperator::VirtualTime => "virtual_time",
+ BuiltInOperator::VirtualDeltaTime => "virtual_delta_time",
+ BuiltInOperator::RealTime => "real_time",
+ BuiltInOperator::RealDeltaTime => "real_delta_time",
+ BuiltInOperator::Rand(value_type) => match value_type {
+ ValueType::Scalar(s) => match s {
+ ScalarType::Bool => "brand",
+ ScalarType::Float => "frand",
+ ScalarType::Int => "irand",
+ ScalarType::Uint => "urand",
+ },
+ ValueType::Vector(vector_type) => {
+ match (vector_type.elem_type(), vector_type.count()) {
+ (ScalarType::Bool, 2) => "brand2",
+ (ScalarType::Bool, 3) => "brand3",
+ (ScalarType::Bool, 4) => "brand4",
+ (ScalarType::Float, 2) => "frand2",
+ (ScalarType::Float, 3) => "frand3",
+ (ScalarType::Float, 4) => "frand4",
+ (ScalarType::Int, 2) => "irand2",
+ (ScalarType::Int, 3) => "irand3",
+ (ScalarType::Int, 4) => "irand4",
+ (ScalarType::Uint, 2) => "urand2",
+ (ScalarType::Uint, 3) => "urand3",
+ (ScalarType::Uint, 4) => "urand4",
+ _ => panic!("Invalid vector type {:?}", vector_type),
+ }
+ }
+ ValueType::Matrix(_) => panic!("Invalid BuiltInOperator::Rand(ValueType::Matrix)."),
+ },
+ BuiltInOperator::AlphaCutoff => "alpha_cutoff",
+ BuiltInOperator::IsAlive => "is_alive",
+ }
+ }
+
+ /// Get the type of the value of a built-in operator.
+ pub fn value_type(&self) -> ValueType {
+ match self {
+ BuiltInOperator::Time => ValueType::Scalar(ScalarType::Float),
+ BuiltInOperator::DeltaTime => ValueType::Scalar(ScalarType::Float),
+ BuiltInOperator::VirtualTime => ValueType::Scalar(ScalarType::Float),
+ BuiltInOperator::VirtualDeltaTime => ValueType::Scalar(ScalarType::Float),
+ BuiltInOperator::RealTime => ValueType::Scalar(ScalarType::Float),
+ BuiltInOperator::RealDeltaTime => ValueType::Scalar(ScalarType::Float),
+ BuiltInOperator::Rand(value_type) => *value_type,
+ BuiltInOperator::AlphaCutoff => ValueType::Scalar(ScalarType::Float),
+ BuiltInOperator::IsAlive => ValueType::Scalar(ScalarType::Bool),
+ }
+ }
+
+ // /// Evaluate the result of the operator as an expression.
+ // pub fn eval(&self, _context: &dyn EvalContext) -> Result<String, ExprError> {
+ // match self {
+ // BuiltInOperator::Time => Value::Scalar(Scal)
+ // }
+ // }
+}
+
+impl ToWgslString for BuiltInOperator {
+ fn to_wgsl_string(&self) -> String {
+ match self {
+ BuiltInOperator::Rand(_) => format!("{}()", self.name()),
+ BuiltInOperator::IsAlive => "is_alive".to_string(),
+ _ => format!("sim_params.{}", self.name()),
+ }
+ }
+}
+
+/// Expression for getting built-in quantities related to the effect system.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct BuiltInExpr {
+ /// The built-in operator this expression represents.
+ ///
+ /// The expression evaluates to the value of this built-in operator at the
+ /// time of evaluation.
+ pub operator: BuiltInOperator,
+}
+
+impl BuiltInExpr {
+ /// Create a new built-in operator expression.
+ ///
+ /// # Panics
+ ///
+ /// Panics on invalid [`BuiltInOperator`], like `Rand(MatrixType)`. See
+ /// each [`BuiltInOperator`] variant for more details.
+ #[inline]
+ pub fn new(operator: BuiltInOperator) -> Self {
+ if let BuiltInOperator::Rand(value_type) = operator {
+ assert!(!matches!(value_type, ValueType::Matrix(_)));
+ }
+ Self { operator }
+ }
+
+ /// Is the expression resulting in a compile-time constant?
+ ///
+ /// Constant expressions can be hard-coded into a shader's code, making them
+ /// more efficient and open to shader compiler optimizing.
+ pub fn is_const(&self) -> bool {
+ false
+ }
+
+ /// Has the expression any side-effect?
+ ///
+ /// Expressions with side-effect need to be stored into temporary variables
+ /// when the shader code is emitted, so that the side effect is only applied
+ /// once when the expression is reused in multiple locations.
+ pub fn has_side_effect(&self) -> bool {
+ matches!(self.operator, BuiltInOperator::Rand(_))
+ }
+
+ /// Get the value type of the expression.
+ ///
+ /// The value type of the expression is the type of the value(s) that an
+ /// expression produces.
+ pub fn value_type(&self) -> ValueType {
+ self.operator.value_type()
+ }
+
+ /// Evaluate the expression in the given context.
+ pub fn eval(&self, context: &mut dyn EvalContext) -> Result<String, ExprError> {
+ Ok(check_side_effects_and_create_local_if_needed(
+ context,
+ self.to_wgsl_string(),
+ self.has_side_effect(),
+ ))
+ }
+}
+
+impl ToWgslString for BuiltInExpr {
+ fn to_wgsl_string(&self) -> String {
+ self.operator.to_wgsl_string()
+ }
+}
+
+/// Creates a local variable if necessary to avoid evaluating side-effecting
+/// expressions multiple times.
+///
+/// If `has_side_effect` is true, this function creates a local variable within
+/// the [`EvalContext`] and stores the `compiled_code` there. Otherwise, it
+/// simply returns `compiled_code` unchanged.
+fn check_side_effects_and_create_local_if_needed(
+ context: &mut dyn EvalContext,
+ compiled_code: String,
+ has_side_effect: bool,
+) -> String {
+ if has_side_effect {
+ let var_name = context.make_local_var();
+ context.push_stmt(&format!("let {} = {};", var_name, compiled_code));
+ var_name
+ } else {
+ compiled_code
+ }
+}
+
+/// Unary operator.
+///
+/// Operator applied to a single operand to produce another value. The type of
+/// the operand and the result are not necessarily the same. Valid operand types
+/// depend on the operator itself.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub enum UnaryOperator {
+ /// Absolute value operator.
+ ///
+ /// Return the absolute value of the operand, component-wise for vectors.
+ /// Only valid for numeric operands.
+ Abs,
+
+ /// Inverse cosine operator.
+ ///
+ /// Return the inverse cosine of the operand, component-wise for vectors.
+ /// Only valid for floating-point operands.
+ Acos,
+
+ /// Inverse sine operator.
+ ///
+ /// Return the inverse sine of the operand, component-wise for vectors.
+ /// Only valid for floating-point operands.
+ Asin,
+
+ /// Inverse tangent operator.
+ ///
+ /// Return the inverse tangent of the operand, component-wise for vectors.
+ /// Only valid for floating-point operands.
+ Atan,
+
+ /// Logical ALL operator for bool vectors.
+ ///
+ /// Return `true` if all the components of the bool vector operand are
+ /// `true`. Invalid for any other type of operand.
+ All,
+
+ /// Logical ANY operator for bool vectors.
+ ///
+ /// Return `true` if any component of the bool vector operand is `true`.
+ /// Invalid for any other type of operand.
+ Any,
+
+ /// Ceiling operator.
+ ///
+ /// Return the unique integral number `k` such that `k-1 < x <= k`, where
+ /// `x` is the operand which the operator applies to.
+ Ceil,
+
+ /// Cosine operator.
+ Cos,
+
+ /// Natural exponent operator.
+ ///
+ /// Return the natural exponentiation of the operand (`e^x`), component-wise
+ /// for vectors.
+ Exp,
+
+ /// Base-2 exponent operator.
+ ///
+ /// Return two raised to the power of the operand (`2^x`), component-wise
+ /// for vectors.
+ Exp2,
+
+ /// Floor operator.
+ ///
+ /// Return the unique integral number `k` such that `k <= x < k+1`, where
+ /// `x` is the operand which the operator applies to.
+ Floor,
+
+ /// Fractional part operator.
+ ///
+ /// Return the fractional part of the operand, which is equal to `x -
+ /// floor(x)`, component-wise for vectors.
+ Fract,
+
+ /// Inverse square root operator.
+ ///
+ /// Return the inverse square root of the floating-point operand (`1.0 /
+ /// sqrt(x)`), component-wise for vectors.
+ InvSqrt,
+
+ /// Length operator.
+ ///
+ /// Return the length of a floating point scalar or vector. The "length" of
+ /// a scalar is taken as its absolute value. The length of a vector is the
+ /// Euclidian distance `sqrt(x^2 + ...)` (square root of the sum of the
+ /// squared components).
+ ///
+ /// The output is always a floating point scalar.
+ Length,
+
+ /// Natural logarithm operator.
+ ///
+ /// Return the natural logarithm of the operand (`log(x)`), component-wise
+ /// for vectors.
+ Log,
+
+ /// Base-2 logarithm operator.
+ ///
+ /// Return the base-2 logarithm of the operand (`log2(x)`), component-wise
+ /// for vectors.
+ Log2,
+
+ /// Vector normalizing operator.
+ ///
+ /// Normalize the given numeric vector. Only valid for numeric vector
+ /// operands.
+ Normalize,
+
+ /// Packing operator from `vec4<f32>` to `u32` (signed normalized).
+ ///
+ /// Convert the four components of a signed normalized floating point vector
+ /// into a signed integral `i8` value in `[-128:127]`, then pack those
+ /// four values into a single `u32`. Each vector component should be in
+ /// `[-1:1]` before packing; values outside this range are clamped.
+ Pack4x8snorm,
+
+ /// Packing operator from `vec4<f32>` to `u32` (unsigned normalized).
+ ///
+ /// Convert the four components of an unsigned normalized floating point
+ /// vector into an unsigned integral `u8` value in `[0:255]`, then pack
+ /// those four values into a single `u32`. Each vector component should
+ /// be in `[0:1]` before packing; values outside this range are clamped.
+ Pack4x8unorm,
+
+ /// Rounding operator.
+ ///
+ /// Round the given scalar of vector float to the nearest integer, returned
+ /// as a float value.
+ Round,
+
+ /// Saturate operator.
+ ///
+ /// Clamp the value of the operand to the \[0:1\] range, component-wise for
+ /// vectors.
+ Saturate,
+
+ /// Sign operator.
+ ///
+ /// Return a value representing the sign of a floating point scalar or
+ /// vector input:
+ /// - `1.` if the operand is > 0
+ /// - `0.` if the operand is = 0
+ /// - `-1.` if the operand is < 0
+ ///
+ /// Applies component-wise for vectors.
+ Sign,
+
+ /// Sine operator.
+ Sin,
+
+ /// Square root operator.
+ ///
+ /// Return the square root of the floating-point operand, component-wise for
+ /// vectors.
+ Sqrt,
+
+ /// Tangent operator.
+ Tan,
+
+ /// Unpacking operator from `u32` to `vec4<f32>` (signed normalized).
+ ///
+ /// Unpack the `u32` into four signed integral `i8` value in `[-128:127]`,
+ /// then convert each value to a signed normalized `f32` value in `[-1:1]`.
+ Unpack4x8snorm,
+
+ /// Unpacking operator from `u32` to `vec4<f32>` (unsigned normalized).
+ ///
+ /// Unpack the `u32` into four unsigned integral `u8` value in `[0:255]`,
+ /// then convert each value to an unsigned normalized `f32` value in
+ /// `[0:1]`.
+ Unpack4x8unorm,
+
+ /// Get the fourth component of a vector.
+ ///
+ /// This is only valid for vectors of rank 4.
+ W,
+
+ /// Get the first component of a scalar or vector.
+ ///
+ /// For scalar, return the value itself. For vectors, return the first
+ /// component.
+ X,
+
+ /// Get the second component of a vector.
+ Y,
+
+ /// Get the third component of a vector.
+ ///
+ /// This is only valid for vectors of rank 3 or more.
+ Z,
+}
+
+impl UnaryOperator {
+ /// Check if a unary operator is called via a functional-style call.
+ ///
+ /// Functional-style calls are in the form `op(inner)`, like `abs(x)` for
+ /// example, while non-functional ones are in the form `inner.op`,
+ /// like `v.x` for example. This check is used for formatting the WGSL
+ /// code emitted during evaluation of a binary operation expression.
+ pub fn is_functional(&self) -> bool {
+ !matches!(
+ *self,
+ UnaryOperator::X | UnaryOperator::Y | UnaryOperator::Z | UnaryOperator::W
+ )
+ }
+}
+
+impl ToWgslString for UnaryOperator {
+ fn to_wgsl_string(&self) -> String {
+ match *self {
+ UnaryOperator::Abs => "abs".to_string(),
+ UnaryOperator::Acos => "acos".to_string(),
+ UnaryOperator::Asin => "asin".to_string(),
+ UnaryOperator::Atan => "atan".to_string(),
+ UnaryOperator::All => "all".to_string(),
+ UnaryOperator::Any => "any".to_string(),
+ UnaryOperator::Ceil => "ceil".to_string(),
+ UnaryOperator::Cos => "cos".to_string(),
+ UnaryOperator::Exp => "exp".to_string(),
+ UnaryOperator::Exp2 => "exp2".to_string(),
+ UnaryOperator::Floor => "floor".to_string(),
+ UnaryOperator::Fract => "fract".to_string(),
+ UnaryOperator::InvSqrt => "inverseSqrt".to_string(),
+ UnaryOperator::Length => "length".to_string(),
+ UnaryOperator::Log => "log".to_string(),
+ UnaryOperator::Log2 => "log2".to_string(),
+ UnaryOperator::Normalize => "normalize".to_string(),
+ UnaryOperator::Pack4x8snorm => "pack4x8snorm".to_string(),
+ UnaryOperator::Pack4x8unorm => "pack4x8unorm".to_string(),
+ UnaryOperator::Round => "round".to_string(),
+ UnaryOperator::Saturate => "saturate".to_string(),
+ UnaryOperator::Sign => "sign".to_string(),
+ UnaryOperator::Sin => "sin".to_string(),
+ UnaryOperator::Sqrt => "sqrt".to_string(),
+ UnaryOperator::Tan => "tan".to_string(),
+ UnaryOperator::Unpack4x8snorm => "unpack4x8snorm".to_string(),
+ UnaryOperator::Unpack4x8unorm => "unpack4x8unorm".to_string(),
+ UnaryOperator::W => "w".to_string(),
+ UnaryOperator::X => "x".to_string(),
+ UnaryOperator::Y => "y".to_string(),
+ UnaryOperator::Z => "z".to_string(),
+ }
+ }
+}
+
+/// Binary operator.
+///
+/// Operator applied between two operands, generally denoted "left" and "right".
+/// The type of the operands and the result are not necessarily the same. Valid
+/// operand types depend on the operator itself.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub enum BinaryOperator {
+ /// Addition operator.
+ ///
+ /// Returns the sum of its operands. Only valid for numeric operands.
+ Add,
+
+ /// Inverse tangent operator with 2 arguments.
+ ///
+ /// Returns the arctangent (inverse tangent) of the ratio of the first
+ /// argument divided by the second argument.
+ Atan2,
+
+ /// Cross product operator.
+ ///
+ /// Returns the cross product of the left and right operands. Only valid for
+ /// vector type operands of size 3. Always produce a vector result of the
+ /// same size.
+ Cross,
+
+ /// Distance operator.
+ ///
+ /// Returns the distance between two floating point scalar or vectors, that
+ /// is `length(right - left)`.
+ Distance,
+
+ /// Division operator.
+ ///
+ /// Returns the left operand divided by the right operand. Only valid for
+ /// numeric operands.
+ Div,
+
+ /// Dot product operator.
+ ///
+ /// Returns the dot product of the left and right operands. Only valid for
+ /// vector type operands. Always produce a scalar floating-point result.
+ Dot,
+
+ /// Greater-than operator.
+ ///
+ /// Returns `true` if the left operand is strictly greater than the right
+ /// operand. Only valid for numeric types. If the operands are vectors,
+ /// they must be of the same rank, and the result is a bool vector of
+ /// that rank.
+ GreaterThan,
+
+ /// Greater-than-or-equal operator.
+ ///
+ /// Returns `true` if the left operand is greater than or equal to the right
+ /// operand. Only valid for numeric types. If the operands are vectors,
+ /// they must be of the same rank, and the result is a bool vector of
+ /// that rank.
+ GreaterThanOrEqual,
+
+ /// Less-than operator.
+ ///
+ /// Returns `true` if the left operand is strictly less than the right
+ /// operand. Only valid for numeric types. If the operands are vectors,
+ /// they must be of the same rank, and the result is a bool vector of
+ /// that rank.
+ LessThan,
+
+ /// Less-than-or-equal operator.
+ ///
+ /// Returns `true` if the left operand is less than or equal to the right
+ /// operand. Only valid for numeric types. If the operands are vectors,
+ /// they must be of the same rank, and the result is a bool vector of
+ /// that rank.
+ LessThanOrEqual,
+
+ /// Maximum operator.
+ ///
+ /// Returns the maximum value of its left and right operands. Only valid for
+ /// numeric types. If the operands are vectors, they must be of the same
+ /// rank, and the result is a vector of that rank and same element
+ /// scalar type.
+ Max,
+
+ /// Minimum operator.
+ ///
+ /// Returns the minimum value of its left and right operands. Only valid for
+ /// numeric types. If the operands are vectors, they must be of the same
+ /// rank, and the result is a vector of that rank and same element
+ /// scalar type.
+ Min,
+
+ /// Multiply operator.
+ ///
+ /// Returns the product of its operands. Only valid for numeric operands.
+ Mul,
+
+ /// Remainder operator.
+ ///
+ /// Returns the remainder of the division of the first operand by the
+ /// second. Only valid for numeric types. If the operands are vectors,
+ /// they must be of the same rank, and the result is a vector of that
+ /// rank and same element scalar type.
+ Remainder,
+
+ /// Stepping operator.
+ ///
+ /// Returns `1.0` if the left operand is less than or equal to the right
+ /// operand, or `0.0` otherwise. Only valid for floating scalar or vectors
+ /// of the same rank, and applied component-wise for vectors.
+ Step,
+
+ /// Subtraction operator.
+ ///
+ /// Returns the difference between its left and right operands. Only valid
+ /// for numeric operands.
+ Sub,
+
+ /// Uniform random number operator.
+ ///
+ /// Returns a value generated by a fast non-cryptographically-secure
+ /// pseudo-random number generator (PRNG) whose statistical characteristics
+ /// are undefined and generally focused around speed. The random value is
+ /// uniformly distributed between the left and right operands, which must be
+ /// numeric types. If the operands are vectors, they must be of the same
+ /// rank, and the result is a vector of that rank and same element
+ /// scalar type.
+ UniformRand,
+
+ /// Normal distribution random number operator.
+ ///
+ /// Returns a value generated by a fast non-cryptographically-secure
+ /// pseudo-random number generator (PRNG) whose statistical characteristics
+ /// are undefined and generally focused around speed. The random value is
+ /// normally distributed with mean given by the first operand and standard
+ /// deviation by the second, which must be numeric types. If the operands
+ /// are vectors, they must be of the same rank, and the result is a vector
+ /// of that rank and same element scalar type.
+ NormalRand,
+
+ /// Constructor for 2-element vectors.
+ ///
+ /// Given two scalar elements `x` and `y`, returns the vector consisting of
+ /// those two elements `(x, y)`.
+ Vec2,
+
+ /// Constructor for a 4-element vector.
+ ///
+ /// Given a 3-element vector `xyz` and a scalar value `w`, returns the
+ /// vector `vec4(xyz, w)`.
+ Vec4XyzW,
+}
+
+impl BinaryOperator {
+ /// Check if a binary operator is called via a functional-style call.
+ ///
+ /// Functional-style calls are in the form `op(lhs, rhs)`, like `min(a,
+ /// b)` for example, while non-functional ones are in the form `lhs op rhs`,
+ /// like `a + b` for example. This check is used for formatting the WGSL
+ /// code emitted during evaluation of a binary operation expression.
+ pub fn is_functional(&self) -> bool {
+ match *self {
+ BinaryOperator::Add
+ | BinaryOperator::Div
+ | BinaryOperator::GreaterThan
+ | BinaryOperator::GreaterThanOrEqual
+ | BinaryOperator::LessThan
+ | BinaryOperator::LessThanOrEqual
+ | BinaryOperator::Mul
+ | BinaryOperator::Remainder
+ | BinaryOperator::Sub => false,
+ BinaryOperator::Atan2
+ | BinaryOperator::Cross
+ | BinaryOperator::Distance
+ | BinaryOperator::Dot
+ | BinaryOperator::Max
+ | BinaryOperator::Min
+ | BinaryOperator::Step
+ | BinaryOperator::UniformRand
+ | BinaryOperator::NormalRand
+ | BinaryOperator::Vec2
+ | BinaryOperator::Vec4XyzW => true,
+ }
+ }
+
+ /// Check if a binary operator needs a type suffix.
+ ///
+ /// This is currently just for `rand_uniform`
+ /// (`BinaryOperator::UniformRand`) and `rand_normal`
+ /// (`BinaryOperator::NormalRand`), which are functions we define ourselves.
+ /// WGSL doesn't support user-defined function overloading, so we need a
+ /// suffix to disambiguate the types.
+ pub fn needs_type_suffix(&self) -> bool {
+ matches!(
+ *self,
+ BinaryOperator::UniformRand | BinaryOperator::NormalRand
+ )
+ }
+}
+
+impl ToWgslString for BinaryOperator {
+ fn to_wgsl_string(&self) -> String {
+ match *self {
+ BinaryOperator::Add => "+".to_string(),
+ BinaryOperator::Atan2 => "atan2".to_string(),
+ BinaryOperator::Cross => "cross".to_string(),
+ BinaryOperator::Distance => "distance".to_string(),
+ BinaryOperator::Div => "/".to_string(),
+ BinaryOperator::Dot => "dot".to_string(),
+ BinaryOperator::GreaterThan => ">".to_string(),
+ BinaryOperator::GreaterThanOrEqual => ">=".to_string(),
+ BinaryOperator::LessThan => "<".to_string(),
+ BinaryOperator::LessThanOrEqual => "<=".to_string(),
+ BinaryOperator::Max => "max".to_string(),
+ BinaryOperator::Min => "min".to_string(),
+ BinaryOperator::Mul => "*".to_string(),
+ BinaryOperator::Remainder => "%".to_string(),
+ BinaryOperator::Step => "step".to_string(),
+ BinaryOperator::Sub => "-".to_string(),
+ BinaryOperator::UniformRand => "rand_uniform".to_string(),
+ BinaryOperator::NormalRand => "rand_normal".to_string(),
+ BinaryOperator::Vec2 => "vec2".to_string(),
+ BinaryOperator::Vec4XyzW => "vec4".to_string(),
+ }
+ }
+}
+
+/// Ternary operator.
+///
+/// Operator applied between three operands. The type of the operands and the
+/// result are not necessarily the same. Valid operand types depend on the
+/// operator itself.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub enum TernaryOperator {
+ /// Linear blend ("mix") operator.
+ ///
+ /// Returns the linear blend between the first and second argument, based on
+ /// the fraction of the third argument. If the operands are vectors, they
+ /// must be of the same rank, and the result is a vector of that rank
+ /// and same element scalar type.
+ ///
+ /// The linear blend of `x` and `y` with fraction `t` is equivalent to `x *
+ /// (1 - t) + y * t`.
+ Mix,
+
+ /// Clamp operator.
+ ///
+ /// Returns the first argument clamped to the range defined by the second
+ /// and third arguments. If the operands are vectors, they must be of
+ /// the same rank, and the result is a vector of that rank
+ /// and same element scalar type.
+ ///
+ /// The expression `clamp(x, low, high)` is equivalent to `min(max(x, low),
+ /// high)`.
+ Clamp,
+
+ /// Smooth stepping operator.
+ ///
+ /// Returns the smooth Hermitian interpolation between the first and second
+ /// argument, calculated at the third argument. If the operands are vectors,
+ /// they must be of the same rank, and the result is a vector of that
+ /// rank and same element scalar type.
+ ///
+ /// The smooth stepping of `low` and `high` at position `x` is equivalent to
+ /// `t * t * (3. - 2. * t)` where `t = clamp((x - low) / (high - low))`
+ /// represents the fractional position of `x` between `low` and `high`.
+ ///
+ /// The result is always a floating point scalar in \[0:1\].
+ SmoothStep,
+
+ /// Constructor for 3-element vectors.
+ ///
+ /// Given three scalar elements `x`, `y`, and `z`, returns the vector
+ /// consisting of those three elements `(x, y, z)`.
+ Vec3,
+}
+
+impl ToWgslString for TernaryOperator {
+ fn to_wgsl_string(&self) -> String {
+ match *self {
+ TernaryOperator::Mix => "mix".to_string(),
+ TernaryOperator::Clamp => "clamp".to_string(),
+ TernaryOperator::SmoothStep => "smoothstep".to_string(),
+ TernaryOperator::Vec3 => "vec3".to_string(),
+ }
+ }
+}
+
+/// Expression writer.
+///
+/// Utility to write expressions with a simple functional syntax. Expressions
+/// created with the writer are gatherned into a [`Module`] which can be
+/// transfered once [`finish()`]ed to initialize an [`EffectAsset`].
+///
+/// Because an [`EffectAsset`] contains a single [`Module`], you generally want
+/// to keep using the same [`ExprWriter`] to write all the expressions used by
+/// all the [`Modifer`]s assigned to a given [`EffectAsset`], and only then once
+/// done call [`finish()`] to recover the [`ExprWriter`]'s underlying [`Module`]
+/// to assign it to the [`EffectAsset`].
+///
+/// # Example
+///
+/// ```
+/// # use bevy_hanabi::*;
+/// # use bevy::prelude::*;
+/// // Create a writer
+/// let w = ExprWriter::new();
+///
+/// // Create a new expression: max(5. + particle.position, properties.my_prop)
+/// let prop = w.add_property("my_property", Vec3::ONE.into());
+/// let expr = (w.lit(5.) + w.attr(Attribute::POSITION)).max(w.prop(prop));
+///
+/// // Finalize the expression and write it down into the `Module` as an `Expr`
+/// let expr: ExprHandle = expr.expr();
+///
+/// // Create a modifier and assign the expression to one of its input(s)
+/// let init_modifier = SetAttributeModifier::new(Attribute::LIFETIME, expr);
+///
+/// // Create an EffectAsset with the modifier and the Module from the writer
+/// let effect = EffectAsset::new(1024, SpawnerSettings::rate(32_f32.into()), w.finish())
+/// .init(init_modifier);
+/// ```
+///
+/// [`finish()`]: ExprWriter::finish
+/// [`EffectAsset`]: crate::EffectAsset
+/// [`Modifer`]: crate::Modifier
+#[derive(Debug, Default, Clone)]
+pub struct ExprWriter {
+ module: Rc<RefCell<Module>>,
+}
+
+#[allow(dead_code)]
+impl ExprWriter {
+ /// Create a new writer.
+ ///
+ /// The writer owns a new [`Module`] internally, and write all expressions
+ /// to it. The module can be released to the user with [`finish()`] once
+ /// done using the writer.
+ ///
+ /// [`finish()`]: ExprWriter::finish
+ pub fn new() -> Self {
+ Self {
+ module: Rc::new(RefCell::new(Module::default())),
+ }
+ }
+
+ /// Create a new writer from an existing module.
+ ///
+ /// This is an advanced use entry point to write expressions into an
+ /// existing [`Module`]. In general, users should prefer using
+ /// [`ExprWriter::new()`] to create a new [`Module`], and keep using the
+ /// same [`ExprWriter`] to write all expressions of the same
+ /// [`EffectAsset`].
+ ///
+ /// [`EffectAsset`]: crate::EffectAsset
+ pub fn from_module(module: Rc<RefCell<Module>>) -> Self {
+ Self { module }
+ }
+
+ /// Add a new property.
+ ///
+ /// See [`Property`] for more details on what effect properties are.
+ ///
+ /// # Panics
+ ///
+ /// Panics if a property with the same name already exists.
+ pub fn add_property(&self, name: impl Into<String>, default_value: Value) -> PropertyHandle {
+ self.module.borrow_mut().add_property(name, default_value)
+ }
+
+ /// Push a new expression into the writer.
+ pub fn push(&self, expr: impl Into<Expr>) -> WriterExpr {
+ let expr = {
+ let mut m = self.module.borrow_mut();
+ m.add_expr(expr.into())
+ };
+ WriterExpr {
+ expr,
+ module: Rc::clone(&self.module),
+ }
+ }
+
+ /// Create a new writer expression from a literal constant.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let mut w = ExprWriter::new();
+ /// let x = w.lit(-3.5); // x = -3.5;
+ /// ```
+ pub fn lit(&self, value: impl Into<Value>) -> WriterExpr {
+ self.push(Expr::Literal(LiteralExpr {
+ value: value.into(),
+ }))
+ }
+
+ /// Create a new writer expression from an attribute.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let mut w = ExprWriter::new();
+ /// let x = w.attr(Attribute::POSITION); // x = particle.position;
+ /// ```
+ pub fn attr(&self, attr: Attribute) -> WriterExpr {
+ self.push(Expr::Attribute(AttributeExpr::new(attr)))
+ }
+
+ /// Create a new writer expression from an attribute on a parent effect.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let mut w = ExprWriter::new();
+ /// let x = w.parent_attr(Attribute::POSITION); // x = parent_particle.position;
+ /// ```
+ pub fn parent_attr(&self, attr: Attribute) -> WriterExpr {
+ self.push(Expr::ParentAttribute(AttributeExpr::new(attr)))
+ }
+
+ /// Create a new writer expression from a property.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let mut w = ExprWriter::new();
+ /// let prop = w.add_property("my_prop", 3.0.into());
+ /// let x = w.prop(prop); // x = properties.my_prop;
+ /// ```
+ pub fn prop(&self, handle: PropertyHandle) -> WriterExpr {
+ self.push(Expr::Property(PropertyExpr::new(handle)))
+ }
+
+ /// Create a new writer expression representing the current simulation time.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let mut w = ExprWriter::new();
+ /// let x = w.time(); // x = sim_params.time;
+ /// ```
+ pub fn time(&self) -> WriterExpr {
+ self.push(Expr::BuiltIn(BuiltInExpr::new(BuiltInOperator::Time)))
+ }
+
+ /// Create a new writer expression representing the simulation delta time
+ /// since last frame.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let mut w = ExprWriter::new();
+ /// let x = w.delta_time(); // x = sim_params.delta_time;
+ /// ```
+ pub fn delta_time(&self) -> WriterExpr {
+ self.push(Expr::BuiltIn(BuiltInExpr::new(BuiltInOperator::DeltaTime)))
+ }
+
+ /// Create a new writer expression representing a random value of the given
+ /// type.
+ ///
+ /// The type can be any scalar or vector type. Matrix types are not
+ /// supported. The random values generated are uniformly distributed in
+ /// `[0:1]`. For vectors, each component is sampled separately.
+ ///
+ /// # Panics
+ ///
+ /// Panics in the same cases as [`BuiltInExpr::new()`] does.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let mut w = ExprWriter::new();
+ /// let x = w.rand(VectorType::VEC3F); // x = frand3();
+ /// ```
+ pub fn rand(&self, value_type: impl Into<ValueType>) -> WriterExpr {
+ self.push(Expr::BuiltIn(BuiltInExpr::new(BuiltInOperator::Rand(
+ value_type.into(),
+ ))))
+ }
+
+ /// Create a new writer expression representing the alpha cutoff value used
+ /// for alpha masking.
+ ///
+ /// This expression is only valid when used in the context of the fragment
+ /// shader, in the render context.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let mut w = ExprWriter::new();
+ /// let x = w.alpha_cutoff(); // x = alpha_cutoff;
+ /// ```
+ pub fn alpha_cutoff(&self) -> WriterExpr {
+ self.push(Expr::BuiltIn(BuiltInExpr::new(
+ BuiltInOperator::AlphaCutoff,
+ )))
+ }
+
+ /// Finish using the writer, and recover the [`Module`] where all [`Expr`]
+ /// were written by the writer.
+ ///
+ /// This module is typically passed to [`EffectAsset::new()`] before adding
+ /// to that effect the modifiers which use the expressions created by this
+ /// writer.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # let spawner = SpawnerSettings::default();
+ /// let mut w = ExprWriter::new();
+ /// // [...]
+ /// let module = w.finish();
+ /// let asset = EffectAsset::new(256, spawner, module);
+ /// ```
+ ///
+ /// [`EffectAsset::new()`]: crate::EffectAsset::new()
+ pub fn finish(self) -> Module {
+ self.module.take()
+ }
+}
+
+/// Intermediate expression from an [`ExprWriter`].
+///
+/// A writer expression [`WriterExpr`] is equivalent to an [`ExprHandle`], but
+/// retains a reference to the underlying [`Module`] and therefore can easily be
+/// chained with other [`WriterExpr`] via a concise syntax, at the expense of
+/// being more heavyweight and locking the underlying [`Module`] under a
+/// ref-counted interior mutability (`Rc<RefCell<Module>>`). [`ExprHandle`] by
+/// opposition is a very lightweight type, similar to a simple index. And like
+/// an array index, [`ExprHandle`] doesn't explicitly reference its associated
+/// storage ([`Module`]) which needs to be remembered by the user explicitly.
+///
+/// In addition, [`WriterExpr`] implements several numerical operators like the
+/// [`std::ops::Add`] trait, making it simpler to combine it with another
+/// [`WriterExpr`].
+///
+/// ```
+/// # use bevy_hanabi::*;
+/// let mut w = ExprWriter::new();
+/// let x = w.lit(-3.5);
+/// let y = w.lit(78.);
+/// let z = x + y; // == 74.5
+/// ```
+///
+/// In general the [`WriterExpr`] type is not used directly, but inferred from
+/// calling [`ExprWriter`] methods and combining [`WriterExpr`] together.
+///
+/// ```
+/// # use bevy_hanabi::*;
+/// let mut w = ExprWriter::new();
+/// let my_prop = w.add_property("my_prop", 3.0.into());
+///
+/// // x = max(-3.5 + 1., properties.my_prop) * 0.5 - particle.position;
+/// let x = (w.lit(-3.5) + w.lit(1.))
+/// .max(w.prop(my_prop))
+/// .mul(w.lit(0.5))
+/// .sub(w.attr(Attribute::POSITION));
+///
+/// let handle: ExprHandle = x.expr();
+/// ```
+#[derive(Debug, Clone)]
+pub struct WriterExpr {
+ expr: ExprHandle,
+ module: Rc<RefCell<Module>>,
+}
+
+impl WriterExpr {
+ fn unary_op(self, op: UnaryOperator) -> Self {
+ let expr = self.module.borrow_mut().add_expr(Expr::Unary {
+ op,
+ expr: self.expr,
+ });
+ WriterExpr {
+ expr,
+ module: self.module,
+ }
+ }
+
+ /// Take the absolute value of the current expression.
+ ///
+ /// This is a unary operator, which applies component-wise to vector and
+ /// matrix operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = -3.5;`.
+ /// let x = w.lit(-3.5);
+ ///
+ /// // The absolute value `y = abs(x);`.
+ /// let y = x.abs(); // == 3.5
+ /// ```
+ #[inline]
+ pub fn abs(self) -> Self {
+ self.unary_op(UnaryOperator::Abs)
+ }
+
+ /// Apply the logical operator "all" to the current bool vector expression.
+ ///
+ /// This is a unary operator, which applies to vector operand expressions to
+ /// produce a scalar boolean.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::BVec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<bool>(true, false, true);`.
+ /// let x = w.lit(BVec3::new(true, false, true));
+ ///
+ /// // Check if all components are true `y = all(x);`.
+ /// let y = x.all(); // == false
+ /// ```
+ #[inline]
+ pub fn all(self) -> Self {
+ self.unary_op(UnaryOperator::All)
+ }
+
+ /// Apply the logical operator "any" to the current bool vector expression.
+ ///
+ /// This is a unary operator, which applies to vector operand expressions to
+ /// produce a scalar boolean.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::BVec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<bool>(true, false, true);`.
+ /// let x = w.lit(BVec3::new(true, false, true));
+ ///
+ /// // Check if any components is true `y = any(x);`.
+ /// let y = x.any(); // == true
+ /// ```
+ #[inline]
+ pub fn any(self) -> Self {
+ self.unary_op(UnaryOperator::Any)
+ }
+
+ /// Apply the "acos" (inverse cosine) operator to the current float scalar
+ /// or vector expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions. The return value lies in
+ /// the 0 ≀ x ≀ Ο€ range.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Acos: `y = acos(x);`
+ /// let y = x.acos();
+ /// ```
+ #[inline]
+ pub fn acos(self) -> Self {
+ self.unary_op(UnaryOperator::Acos)
+ }
+
+ /// Apply the "asin" (inverse sine) operator to the current float scalar or
+ /// vector expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions. The return value lies in
+ /// the -Ο€/2 ≀ x ≀ Ο€/2 range.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Asin: `y = asin(x);`
+ /// let y = x.asin();
+ /// ```
+ #[inline]
+ pub fn asin(self) -> Self {
+ self.unary_op(UnaryOperator::Asin)
+ }
+
+ /// Apply the "atan" (inverse tangent) operator to the current float scalar
+ /// or vector expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions. The return value lies in
+ /// the -Ο€/2 ≀ x ≀ Ο€/2 range.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Atan: `y = atan(x);`
+ /// let y = x.atan();
+ /// ```
+ #[inline]
+ pub fn atan(self) -> Self {
+ self.unary_op(UnaryOperator::Atan)
+ }
+
+ /// Apply the "ceil" operator to the current float scalar or vector
+ /// expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Ceil: `y = ceil(x);`
+ /// let y = x.ceil();
+ /// ```
+ #[inline]
+ pub fn ceil(self) -> Self {
+ self.unary_op(UnaryOperator::Ceil)
+ }
+
+ /// Apply the "cos" operator to the current float scalar or vector
+ /// expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Cos: `y = cos(x);`
+ /// let y = x.cos();
+ /// ```
+ #[inline]
+ pub fn cos(self) -> Self {
+ self.unary_op(UnaryOperator::Cos)
+ }
+
+ /// Apply the "exp" operator to the current float scalar or vector
+ /// expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Exp: `y = exp(x);`
+ /// let y = x.exp();
+ /// ```
+ #[inline]
+ pub fn exp(self) -> Self {
+ self.unary_op(UnaryOperator::Exp)
+ }
+
+ /// Apply the "exp2" operator to the current float scalar or vector
+ /// expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Exp2: `y = exp2(x);`
+ /// let y = x.exp2();
+ /// ```
+ #[inline]
+ pub fn exp2(self) -> Self {
+ self.unary_op(UnaryOperator::Exp2)
+ }
+
+ /// Apply the "floor" operator to the current float scalar or vector
+ /// expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Floor: `y = floor(x);`
+ /// let y = x.floor();
+ /// ```
+ #[inline]
+ pub fn floor(self) -> Self {
+ self.unary_op(UnaryOperator::Floor)
+ }
+
+ /// Apply the "fract" operator to the current float scalar or vector
+ /// expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Fract: `y = fract(x);`
+ /// let y = x.fract();
+ /// ```
+ #[inline]
+ pub fn fract(self) -> Self {
+ self.unary_op(UnaryOperator::Fract)
+ }
+
+ /// Apply the "inverseSqrt" (inverse square root) operator to the current
+ /// float scalar or vector expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Inverse square root: `y = inverseSqrt(x) = 1.0 / sqrt(x);`
+ /// let y = x.inverse_sqrt();
+ /// ```
+ #[inline]
+ pub fn inverse_sqrt(self) -> Self {
+ self.unary_op(UnaryOperator::InvSqrt)
+ }
+
+ /// Apply the "length" operator to the current float scalar or vector
+ /// expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Length: `y = length(x);`
+ /// let y = x.length();
+ /// ```
+ #[inline]
+ pub fn length(self) -> Self {
+ self.unary_op(UnaryOperator::Length)
+ }
+
+ /// Apply the "log" operator to the current float scalar or vector
+ /// expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Log: `y = log(x);`
+ /// let y = x.log();
+ /// ```
+ #[inline]
+ pub fn log(self) -> Self {
+ self.unary_op(UnaryOperator::Log)
+ }
+
+ /// Apply the "log2" operator to the current float scalar or vector
+ /// expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Log2: `y = log2(x);`
+ /// let y = x.log2();
+ /// ```
+ #[inline]
+ pub fn log2(self) -> Self {
+ self.unary_op(UnaryOperator::Log2)
+ }
+
+ /// Apply the "normalize" operator to the current float vector expression.
+ ///
+ /// This is a unary operator, which applies to float vector operand
+ /// expressions to produce another float vector with unit length
+ /// (normalized).
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Normalize: `y = normalize(x);`
+ /// let y = x.normalized();
+ /// ```
+ #[inline]
+ pub fn normalized(self) -> Self {
+ self.unary_op(UnaryOperator::Normalize)
+ }
+
+ /// Apply the "pack4x8snorm" operator to the current 4-component float
+ /// vector expression.
+ ///
+ /// This is a unary operator, which applies to 4-component float vector
+ /// operand expressions to produce a single `u32` scalar expression.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec4;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec4<f32>(-1., 1., 0., 7.2);`.
+ /// let x = w.lit(Vec4::new(-1., 1., 0., 7.2));
+ ///
+ /// // Pack: `y = pack4x8snorm(x);`
+ /// let y = x.pack4x8snorm(); // 0x7F007FFFu32
+ /// ```
+ #[inline]
+ pub fn pack4x8snorm(self) -> Self {
+ self.unary_op(UnaryOperator::Pack4x8snorm)
+ }
+
+ /// Apply the "pack4x8unorm" operator to the current 4-component float
+ /// vector expression.
+ ///
+ /// This is a unary operator, which applies to 4-component float vector
+ /// operand expressions to produce a single `u32` scalar expression.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec4;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec4<f32>(-1., 1., 0., 7.2);`.
+ /// let x = w.lit(Vec4::new(-1., 1., 0., 7.2));
+ ///
+ /// // Pack: `y = pack4x8unorm(x);`
+ /// let y = x.pack4x8unorm(); // 0xFF00FF00u32
+ /// ```
+ #[inline]
+ pub fn pack4x8unorm(self) -> Self {
+ self.unary_op(UnaryOperator::Pack4x8unorm)
+ }
+
+ /// Apply the "round" operator to the current float scalar or vector
+ /// expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1.5, -3.2, 0.75);`.
+ /// let x = w.lit(Vec3::new(1.5, -3.2, 0.75));
+ ///
+ /// // Sign: `y = round(x);`
+ /// let y = x.round();
+ /// ```
+ #[inline]
+ pub fn round(self) -> Self {
+ self.unary_op(UnaryOperator::Round)
+ }
+
+ /// Apply the "sign" operator to the current float scalar or vector
+ /// expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Sign: `y = sign(x);`
+ /// let y = x.sign();
+ /// ```
+ #[inline]
+ pub fn sign(self) -> Self {
+ self.unary_op(UnaryOperator::Sign)
+ }
+
+ /// Apply the "sin" operator to the current float scalar or vector
+ /// expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Sin: `y = sin(x);`
+ /// let y = x.sin();
+ /// ```
+ #[inline]
+ pub fn sin(self) -> Self {
+ self.unary_op(UnaryOperator::Sin)
+ }
+
+ /// Apply the "sqrt" (square root) operator to the current float scalar or
+ /// vector expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Square root: `y = sqrt(x);`
+ /// let y = x.sqrt();
+ /// ```
+ #[inline]
+ pub fn sqrt(self) -> Self {
+ self.unary_op(UnaryOperator::Sqrt)
+ }
+
+ /// Apply the "tan" operator to the current float scalar or vector
+ /// expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Tan: `y = tan(x);`
+ /// let y = x.tan();
+ /// ```
+ #[inline]
+ pub fn tan(self) -> Self {
+ self.unary_op(UnaryOperator::Tan)
+ }
+
+ /// Apply the "unpack4x8snorm" operator to the current `u32` scalar
+ /// expression.
+ ///
+ /// This is a unary operator, which applies to `u32` scalar operand
+ /// expressions to produce a 4-component floating point vector of signed
+ /// normalized components in `[-1:1]`.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `y = 0x7F007FFFu32;`.
+ /// let y = w.lit(0x7F007FFFu32);
+ ///
+ /// // Unpack: `x = unpack4x8snorm(y);`
+ /// let x = y.unpack4x8snorm(); // vec4<f32>(-1., 1., 0., 7.2)
+ /// ```
+ #[inline]
+ pub fn unpack4x8snorm(self) -> Self {
+ self.unary_op(UnaryOperator::Unpack4x8snorm)
+ }
+
+ /// Apply the "unpack4x8unorm" operator to the current `u32` scalar
+ /// expression.
+ ///
+ /// This is a unary operator, which applies to `u32` scalar operand
+ /// expressions to produce a 4-component floating point vector of unsigned
+ /// normalized components in `[0:1]`.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `y = 0xFF00FF00u32;`.
+ /// let y = w.lit(0xFF00FF00u32);
+ ///
+ /// // Unpack: `x = unpack4x8unorm(y);`
+ /// let x = y.unpack4x8unorm(); // vec4<f32>(-1., 1., 0., 7.2)
+ /// ```
+ #[inline]
+ pub fn unpack4x8unorm(self) -> Self {
+ self.unary_op(UnaryOperator::Unpack4x8unorm)
+ }
+
+ /// Apply the "saturate" operator to the current float scalar or vector
+ /// expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
+ /// let x = w.lit(Vec3::ONE);
+ ///
+ /// // Saturate: `y = saturate(x);`
+ /// let y = x.saturate();
+ /// ```
+ #[inline]
+ pub fn saturate(self) -> Self {
+ self.unary_op(UnaryOperator::Saturate)
+ }
+
+ /// Get the first component of a scalar or vector.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `v = vec3<f32>(1., 1., 1.);`.
+ /// let v = w.lit(Vec3::ONE);
+ ///
+ /// // f = v.x;`
+ /// let f = v.x();
+ /// ```
+ #[inline]
+ pub fn x(self) -> Self {
+ self.unary_op(UnaryOperator::X)
+ }
+
+ /// Get the second component of a vector.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `v = vec3<f32>(1., 1., 1.);`.
+ /// let v = w.lit(Vec3::ONE);
+ ///
+ /// // f = v.y;`
+ /// let f = v.y();
+ /// ```
+ #[inline]
+ pub fn y(self) -> Self {
+ self.unary_op(UnaryOperator::Y)
+ }
+
+ /// Get the third component of a vector.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `v = vec3<f32>(1., 1., 1.);`.
+ /// let v = w.lit(Vec3::ONE);
+ ///
+ /// // f = v.z;`
+ /// let f = v.z();
+ /// ```
+ #[inline]
+ pub fn z(self) -> Self {
+ self.unary_op(UnaryOperator::Z)
+ }
+
+ /// Get the fourth component of a vector.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `v = vec3<f32>(1., 1., 1.);`.
+ /// let v = w.lit(Vec3::ONE);
+ ///
+ /// // f = v.w;`
+ /// let f = v.w();
+ /// ```
+ #[inline]
+ pub fn w(self) -> Self {
+ self.unary_op(UnaryOperator::W)
+ }
+
+ fn binary_op(self, other: Self, op: BinaryOperator) -> Self {
+ assert_eq!(self.module, other.module);
+ let left = self.expr;
+ let right = other.expr;
+ let expr = self
+ .module
+ .borrow_mut()
+ .add_expr(Expr::Binary { op, left, right });
+ WriterExpr {
+ expr,
+ module: self.module,
+ }
+ }
+
+ /// Add the current expression with another expression.
+ ///
+ /// This is a binary operator, which applies component-wise to vector
+ /// operand expressions.
+ ///
+ /// You can also use the [`std::ops::Add`] trait directly, via the `+`
+ /// symbol, as an alternative to calling this method directly.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec2;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec2<f32>(3., -2.);`.
+ /// let x = w.lit(Vec2::new(3., -2.));
+ ///
+ /// // Another literal expression `y = vec2<f32>(1., 5.);`.
+ /// let y = w.lit(Vec2::new(1., 5.));
+ ///
+ /// // The sum of both vectors `z = x + y;`.
+ /// let z = x.add(y); // == vec2<f32>(4., 3.)
+ /// // -OR-
+ /// // let z = x + y;
+ /// ```
+ #[allow(clippy::should_implement_trait)]
+ #[inline]
+ pub fn add(self, other: Self) -> Self {
+ self.binary_op(other, BinaryOperator::Add)
+ }
+
+ /// Apply the "atan2" (inverse tangent with 2 arguments) operator to the
+ /// current float scalar or vector expression.
+ ///
+ /// This is a unary operator, which applies to float scalar or vector
+ /// operand expressions to produce a float scalar or vector. It applies
+ /// component-wise to vector operand expressions. The return value lies in
+ /// the -Ο€ ≀ x ≀ Ο€ range, and represents a value whose tangent is equal to
+ /// y over x (`z = atan2(y, x)` <=> `tan(z) = y / x`).
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // Two literal expressions `x` and `y`.
+ /// let x = w.lit(Vec3::new(1., 0., -1.));
+ /// let y = w.lit(Vec3::ONE);
+ ///
+ /// // Atan: `z = atan2(y, x);`
+ /// let z = y.atan2(x);
+ /// ```
+ #[inline]
+ pub fn atan2(self, other: Self) -> Self {
+ self.binary_op(other, BinaryOperator::Atan2)
+ }
+
+ /// Calculate the cross product of the current expression by another
+ /// expression.
+ ///
+ /// This is a binary operator, which applies to vector operands of size 3
+ /// only, and always produces a vector of the same size.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(3., -2., 1.);`.
+ /// let x = w.lit(Vec3::new(3., -2., 1.));
+ ///
+ /// // Another literal expression `y = vec3<f32>(1., 5., 0.);`.
+ /// let y = w.lit(Vec3::new(1., 5., 0.));
+ ///
+ /// // The cross product of both vectors `z = cross(x, y);`.
+ /// let z = x.cross(y);
+ /// ```
+ #[inline]
+ pub fn cross(self, other: Self) -> Self {
+ self.binary_op(other, BinaryOperator::Cross)
+ }
+
+ /// Calculate the dot product of the current expression by another
+ /// expression.
+ ///
+ /// This is a binary operator, which applies to vector operands of same size
+ /// only, and always produces a floating point scalar.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec2;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec2<f32>(3., -2.);`.
+ /// let x = w.lit(Vec2::new(3., -2.));
+ ///
+ /// // Another literal expression `y = vec2<f32>(1., 5.);`.
+ /// let y = w.lit(Vec2::new(1., 5.));
+ ///
+ /// // The dot product of both vectors `z = dot(x, y);`.
+ /// let z = x.dot(y);
+ /// ```
+ #[inline]
+ pub fn dot(self, other: Self) -> Self {
+ self.binary_op(other, BinaryOperator::Dot)
+ }
+
+ /// Calculate the distance between the current expression and another
+ /// expression.
+ ///
+ /// This is a binary operator.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(3., -2., 1.);`.
+ /// let x = w.lit(Vec3::new(3., -2., 1.));
+ ///
+ /// // Another literal expression `y = vec3<f32>(1., 5., 0.);`.
+ /// let y = w.lit(Vec3::new(1., 5., 0.));
+ ///
+ /// // The distance between the vectors `z = distance(x, y);`.
+ /// let z = x.distance(y);
+ /// ```
+ #[inline]
+ pub fn distance(self, other: Self) -> Self {
+ self.binary_op(other, BinaryOperator::Distance)
+ }
+
+ /// Divide the current expression by another expression.
+ ///
+ /// This is a binary operator, which applies component-wise to vector
+ /// operand expressions.
+ ///
+ /// You can also use the [`std::ops::Div`] trait directly, via the `/`
+ /// symbol, as an alternative to calling this method directly.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec2;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec2<f32>(3., -2.);`.
+ /// let x = w.lit(Vec2::new(3., -2.));
+ ///
+ /// // Another literal expression `y = vec2<f32>(1., 5.);`.
+ /// let y = w.lit(Vec2::new(1., 5.));
+ ///
+ /// // The quotient of both vectors `z = x / y;`.
+ /// let z = x.div(y); // == vec2<f32>(3., -0.4)
+ /// // -OR-
+ /// // let z = x / y;
+ /// ```
+ #[allow(clippy::should_implement_trait)]
+ #[inline]
+ pub fn div(self, other: Self) -> Self {
+ self.binary_op(other, BinaryOperator::Div)
+ }
+
+ /// Apply the logical operator "greater than or equal" to this expression
+ /// and another expression.
+ ///
+ /// This is a binary operator, which applies component-wise to vector
+ /// operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(3., -2., 7.);`.
+ /// let x = w.lit(Vec3::new(3., -2., 7.));
+ ///
+ /// // Another literal expression `y = vec3<f32>(1., 5., 7.);`.
+ /// let y = w.lit(Vec3::new(1., 5., 7.));
+ ///
+ /// // The boolean result of the greater than or equal operation `z = (x >= y);`.
+ /// let z = x.ge(y); // == vec3<bool>(true, false, true)
+ /// ```
+ #[inline]
+ pub fn ge(self, other: Self) -> Self {
+ self.binary_op(other, BinaryOperator::GreaterThanOrEqual)
+ }
+
+ /// Apply the logical operator "greater than" to this expression and another
+ /// expression.
+ ///
+ /// This is a binary operator, which applies component-wise to vector
+ /// operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(3., -2., 7.);`.
+ /// let x = w.lit(Vec3::new(3., -2., 7.));
+ ///
+ /// // Another literal expression `y = vec3<f32>(1., 5., 7.);`.
+ /// let y = w.lit(Vec3::new(1., 5., 7.));
+ ///
+ /// // The boolean result of the greater than operation `z = (x > y);`.
+ /// let z = x.gt(y); // == vec3<bool>(true, false, false)
+ /// ```
+ #[inline]
+ pub fn gt(self, other: Self) -> Self {
+ self.binary_op(other, BinaryOperator::GreaterThan)
+ }
+
+ /// Apply the logical operator "less than or equal" to this expression and
+ /// another expression.
+ ///
+ /// This is a binary operator, which applies component-wise to vector
+ /// operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(3., -2., 7.);`.
+ /// let x = w.lit(Vec3::new(3., -2., 7.));
+ ///
+ /// // Another literal expression `y = vec3<f32>(1., 5., 7.);`.
+ /// let y = w.lit(Vec3::new(1., 5., 7.));
+ ///
+ /// // The boolean result of the less than or equal operation `z = (x <= y);`.
+ /// let z = x.le(y); // == vec3<bool>(false, true, true)
+ /// ```
+ #[inline]
+ pub fn le(self, other: Self) -> Self {
+ self.binary_op(other, BinaryOperator::LessThanOrEqual)
+ }
+
+ /// Apply the logical operator "less than" to this expression and another
+ /// expression.
+ ///
+ /// This is a binary operator, which applies component-wise to vector
+ /// operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(3., -2., 7.);`.
+ /// let x = w.lit(Vec3::new(3., -2., 7.));
+ ///
+ /// // Another literal expression `y = vec3<f32>(1., 5., 7.);`.
+ /// let y = w.lit(Vec3::new(1., 5., 7.));
+ ///
+ /// // The boolean result of the less than operation `z = (x < y);`.
+ /// let z = x.lt(y); // == vec3<bool>(false, true, false)
+ /// ```
+ #[inline]
+ pub fn lt(self, other: Self) -> Self {
+ self.binary_op(other, BinaryOperator::LessThan)
+ }
+
+ /// Take the maximum value of the current expression and another expression.
+ ///
+ /// This is a binary operator, which applies component-wise to vector
+ /// operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec2;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec2<f32>(3., -2.);`.
+ /// let x = w.lit(Vec2::new(3., -2.));
+ ///
+ /// // Another literal expression `y = vec2<f32>(1., 5.);`.
+ /// let y = w.lit(Vec2::new(1., 5.));
+ ///
+ /// // The maximum of both vectors `z = max(x, y);`.
+ /// let z = x.max(y); // == vec2<f32>(3., 5.)
+ /// ```
+ #[inline]
+ pub fn max(self, other: Self) -> Self {
+ self.binary_op(other, BinaryOperator::Max)
+ }
+
+ /// Take the minimum value of the current expression and another expression.
+ ///
+ /// This is a binary operator, which applies component-wise to vector
+ /// operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec2;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec2<f32>(3., -2.);`.
+ /// let x = w.lit(Vec2::new(3., -2.));
+ ///
+ /// // Another literal expression `y = vec2<f32>(1., 5.);`.
+ /// let y = w.lit(Vec2::new(1., 5.));
+ ///
+ /// // The minimum of both vectors `z = min(x, y);`.
+ /// let z = x.min(y); // == vec2<f32>(1., -2.)
+ /// ```
+ #[inline]
+ pub fn min(self, other: Self) -> Self {
+ self.binary_op(other, BinaryOperator::Min)
+ }
+
+ /// Multiply the current expression with another expression.
+ ///
+ /// This is a binary operator, which applies component-wise to vector
+ /// operand expressions.
+ ///
+ /// You can also use the [`std::ops::Mul`] trait directly, via the `*`
+ /// symbol, as an alternative to calling this method directly.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec2;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec2<f32>(3., -2.);`.
+ /// let x = w.lit(Vec2::new(3., -2.));
+ ///
+ /// // Another literal expression `y = vec2<f32>(1., 5.);`.
+ /// let y = w.lit(Vec2::new(1., 5.));
+ ///
+ /// // The product of both vectors `z = x * y;`.
+ /// let z = x.mul(y); // == vec2<f32>(3., -10.)
+ /// // -OR-
+ /// // let z = x * y;
+ /// ```
+ #[allow(clippy::should_implement_trait)]
+ #[inline]
+ pub fn mul(self, other: Self) -> Self {
+ self.binary_op(other, BinaryOperator::Mul)
+ }
+
+ /// Apply the logical operator "normal" to this expression and another
+ /// expression.
+ ///
+ /// This is a binary operator, which applies component-wise to vector
+ /// operand expressions. That is, for vectors, this produces a vector of
+ /// random values where each component is normally distributed with a mean
+ /// of the corresponding component of the first operand and a standard
+ /// deviation of the corresponding component of the second operand.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(3., -2., 7.);`.
+ /// let x = w.lit(Vec3::new(3., -2., 7.));
+ ///
+ /// // Another literal expression `y = vec3<f32>(1., 5., 7.);`.
+ /// let y = w.lit(Vec3::new(1., 5., 7.));
+ ///
+ /// // A random variable normally distributed in [1:3]x[-2:5]x[7:7].
+ /// let z = x.normal(y);
+ /// ```
+ #[inline]
+ pub fn normal(self, other: Self) -> Self {
+ self.binary_op(other, BinaryOperator::NormalRand)
+ }
+
+ /// Calculate the remainder of the division of the current expression by
+ /// another expression.
+ ///
+ /// This is a binary operator.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(3., -2., 1.);`.
+ /// let x = w.lit(Vec3::new(3., -2., 1.));
+ ///
+ /// // Another literal expression `y = vec3<f32>(1., 5., 0.);`.
+ /// let y = w.lit(Vec3::new(1., 5., 0.));
+ ///
+ /// // The remainder of the division `z = x % y;`.
+ /// let z = x.rem(y);
+ /// ```
+ #[allow(clippy::should_implement_trait)]
+ #[inline]
+ pub fn rem(self, other: Self) -> Self {
+ self.binary_op(other, BinaryOperator::Remainder)
+ }
+
+ /// Calculate the step of a value with respect to a reference.
+ ///
+ /// This is a binary operator, which applies component-wise to vector
+ /// operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(3., -2.);`.
+ /// let x = w.lit(Vec3::new(3., -2., 8.));
+ ///
+ /// // An edge reference `e = vec3<f32>(1., 5.);`.
+ /// let e = w.lit(Vec3::new(1., 5., 8.));
+ ///
+ /// // The step value
+ /// let s = x.step(e); // == vec3<f32>(1., 0., 1.)
+ /// ```
+ #[allow(clippy::should_implement_trait)]
+ #[inline]
+ pub fn step(self, edge: Self) -> Self {
+ // Note: order is step(edge, x) but x.step(edge)
+ edge.binary_op(self, BinaryOperator::Step)
+ }
+
+ /// Subtract another expression from the current expression.
+ ///
+ /// This is a binary operator, which applies component-wise to vector
+ /// operand expressions.
+ ///
+ /// You can also use the [`std::ops::Sub`] trait directly, via the `-`
+ /// symbol, as an alternative to calling this method directly.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec2;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec2<f32>(3., -2.);`.
+ /// let x = w.lit(Vec2::new(3., -2.));
+ ///
+ /// // Another literal expression `y = vec2<f32>(1., 5.);`.
+ /// let y = w.lit(Vec2::new(1., 5.));
+ ///
+ /// // The difference of both vectors `z = x - y;`.
+ /// let z = x.sub(y); // == vec2<f32>(2., -7.)
+ /// // -OR-
+ /// // let z = x - y;
+ /// ```
+ #[allow(clippy::should_implement_trait)]
+ #[inline]
+ pub fn sub(self, other: Self) -> Self {
+ self.binary_op(other, BinaryOperator::Sub)
+ }
+
+ /// Apply the logical operator "uniform" to this expression and another
+ /// expression.
+ ///
+ /// This is a binary operator, which applies component-wise to vector
+ /// operand expressions. That is, for vectors, this produces a vector of
+ /// random values where each component is uniformly distributed within the
+ /// bounds of the related component of both operands.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec3;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec3<f32>(3., -2., 7.);`.
+ /// let x = w.lit(Vec3::new(3., -2., 7.));
+ ///
+ /// // Another literal expression `y = vec3<f32>(1., 5., 7.);`.
+ /// let y = w.lit(Vec3::new(1., 5., 7.));
+ ///
+ /// // A random variable uniformly distributed in [1:3]x[-2:5]x[7:7].
+ /// let z = x.uniform(y);
+ /// ```
+ #[inline]
+ pub fn uniform(self, other: Self) -> Self {
+ self.binary_op(other, BinaryOperator::UniformRand)
+ }
+
+ fn ternary_op(self, second: Self, third: Self, op: TernaryOperator) -> Self {
+ assert_eq!(self.module, second.module);
+ assert_eq!(self.module, third.module);
+ let first = self.expr;
+ let second = second.expr;
+ let third = third.expr;
+ let expr = self.module.borrow_mut().add_expr(Expr::Ternary {
+ op,
+ first,
+ second,
+ third,
+ });
+ WriterExpr {
+ expr,
+ module: self.module,
+ }
+ }
+
+ /// Blending linearly ("mix") two expressions with the fraction provided by
+ /// a third expression.
+ ///
+ /// This is a ternary operator, which applies component-wise to vector
+ /// operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec2;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec2<f32>(3., -2.);`.
+ /// let x = w.lit(Vec2::new(3., -2.));
+ ///
+ /// // Another literal expression `y = vec2<f32>(1., 4.);`.
+ /// let y = w.lit(Vec2::new(1., 4.));
+ ///
+ /// // A fraction `t = 0.5;`.
+ /// let t = w.lit(0.25);
+ ///
+ /// // The linear blend of x and y via t: z = (1 - t) * x + y * t
+ /// let z = x.mix(y, t); // == vec2<f32>(2.5, -0.5)
+ /// ```
+ #[inline]
+ pub fn mix(self, other: Self, fraction: Self) -> Self {
+ self.ternary_op(other, fraction, TernaryOperator::Mix)
+ }
+
+ /// Clamp an expression between the bounds defined by two other expressions.
+ ///
+ /// This is a ternary operator, which applies component-wise to vector
+ /// operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec2;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = vec2<f32>(1., -2.);`.
+ /// let x = w.lit(Vec2::new(1., -2.));
+ ///
+ /// // A literal expression `lo = vec2<f32>(3., -3.);`.
+ /// let lo = w.lit(Vec2::new(3., -3.));
+ ///
+ /// // A literal expression `hi = vec2<f32>(5., 1.);`.
+ /// let hi = w.lit(Vec2::new(5., 1.));
+ ///
+ /// // Clamp x in [lo:hi]
+ /// let z = x.clamp(lo, hi); // == vec2<f32>(3., -2.)
+ /// ```
+ #[inline]
+ pub fn clamp(self, lo: Self, hi: Self) -> Self {
+ self.ternary_op(lo, hi, TernaryOperator::Clamp)
+ }
+
+ /// Calculate the smooth Hermite interpolation in \[0:1\] of the current
+ /// value taken between the given bounds.
+ ///
+ /// This is a ternary operator, which applies component-wise to vector
+ /// operand expressions.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec2;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `low = vec2<f32>(3., -2.);`.
+ /// let low = w.lit(Vec2::new(3., -2.));
+ ///
+ /// // Another literal expression `high = vec2<f32>(1., 4.);`.
+ /// let high = w.lit(Vec2::new(1., 4.));
+ ///
+ /// // A point `x = vec2<f32>(2., 1.);` between `low` and `high`.
+ /// let x = w.lit(Vec2::new(2., 1.));
+ ///
+ /// // The smooth Hermite interpolation: `t = smoothstep(low, high, x)`
+ /// let t = x.smoothstep(low, high); // == 0.5
+ /// ```
+ #[inline]
+ pub fn smoothstep(self, low: Self, high: Self) -> Self {
+ // Note: order is smoothstep(low, high, x) but x.smoothstep(low, high)
+ low.ternary_op(high, self, TernaryOperator::SmoothStep)
+ }
+
+ /// Construct a `Vec2` from two scalars.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # let mut w = ExprWriter::new();
+ /// let theta = w.add_property("theta", 0.0.into());
+ /// // Convert the angular property `theta` to a 2D vector.
+ /// let (cos_theta, sin_theta) = (w.prop(theta).cos(), w.prop(theta).sin());
+ /// let circle_pos = cos_theta.vec2(sin_theta);
+ /// ```
+ #[inline]
+ pub fn vec2(self, y: Self) -> Self {
+ self.binary_op(y, BinaryOperator::Vec2)
+ }
+
+ /// Construct a `Vec3` from two scalars.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # let mut w = ExprWriter::new();
+ /// let theta = w.add_property("theta", 0.0.into());
+ /// // Convert the angular property `theta` to a 3D vector in a flat plane.
+ /// let (cos_theta, sin_theta) = (w.prop(theta).cos(), w.prop(theta).sin());
+ /// let circle_pos = cos_theta.vec3(w.lit(0.0), sin_theta);
+ /// ```
+ #[inline]
+ pub fn vec3(self, y: Self, z: Self) -> Self {
+ self.ternary_op(y, z, TernaryOperator::Vec3)
+ }
+
+ /// Construct a `Vec4` from a vector XYZ and a scalar W.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # let mut w = ExprWriter::new();
+ /// let rgb = w.rand(VectorType::VEC3F);
+ /// let a = w.lit(1.);
+ /// // Build vec4<f32>(R, G, B, A) and convert to 0xAABBGGRR
+ /// let col = rgb.vec4_xyz_w(a).pack4x8unorm();
+ /// ```
+ #[inline]
+ pub fn vec4_xyz_w(self, w: Self) -> Self {
+ self.binary_op(w, BinaryOperator::Vec4XyzW)
+ }
+
+ /// Cast an expression to a different type.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # use bevy::math::Vec2;
+ /// # let mut w = ExprWriter::new();
+ /// let x = w.lit(Vec2::new(3., -2.));
+ /// let y = x.cast(VectorType::VEC3I); // x = vec3<i32>(particle.position);
+ /// ```
+ pub fn cast(self, target: impl Into<ValueType>) -> Self {
+ let target = target.into();
+ let expr = self
+ .module
+ .borrow_mut()
+ .add_expr(Expr::Cast(CastExpr::new(self.expr, target)));
+ WriterExpr {
+ expr,
+ module: self.module,
+ }
+ }
+
+ /// Finalize an expression chain and return the accumulated expression.
+ ///
+ /// The returned handle indexes the [`Module`] owned by the [`ExprWriter`]
+ /// this intermediate expression was built from.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// # let mut w = ExprWriter::new();
+ /// // A literal expression `x = -3.5;`.
+ /// let x = w.lit(-3.5);
+ ///
+ /// // Retrieve the ExprHandle for that expression.
+ /// let handle = x.expr();
+ /// ```
+ #[inline]
+ pub fn expr(self) -> ExprHandle {
+ self.expr
+ }
+}
+
+impl std::ops::Add<WriterExpr> for WriterExpr {
+ type Output = WriterExpr;
+
+ #[inline]
+ fn add(self, rhs: WriterExpr) -> Self::Output {
+ self.add(rhs)
+ }
+}
+
+impl std::ops::Sub<WriterExpr> for WriterExpr {
+ type Output = WriterExpr;
+
+ #[inline]
+ fn sub(self, rhs: WriterExpr) -> Self::Output {
+ self.sub(rhs)
+ }
+}
+
+impl std::ops::Mul<WriterExpr> for WriterExpr {
+ type Output = WriterExpr;
+
+ #[inline]
+ fn mul(self, rhs: WriterExpr) -> Self::Output {
+ self.mul(rhs)
+ }
+}
+
+impl std::ops::Div<WriterExpr> for WriterExpr {
+ type Output = WriterExpr;
+
+ #[inline]
+ fn div(self, rhs: WriterExpr) -> Self::Output {
+ self.div(rhs)
+ }
+}
+
+impl std::ops::Rem<WriterExpr> for WriterExpr {
+ type Output = WriterExpr;
+
+ #[inline]
+ fn rem(self, rhs: WriterExpr) -> Self::Output {
+ self.rem(rhs)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use bevy::{platform::collections::HashSet, prelude::*};
+ use ron::ser::PrettyConfig;
+
+ use super::*;
+ use crate::{MatrixType, ScalarValue, ShaderWriter, VectorType};
+
+ #[test]
+ fn module() {
+ let mut m = Module::default();
+
+ #[allow(unsafe_code)]
+ let unknown = unsafe { ExprHandle::new_unchecked(1) };
+ assert!(m.get(unknown).is_none());
+ assert!(m.get_mut(unknown).is_none());
+ assert!(matches!(
+ m.try_get(unknown),
+ Err(ExprError::InvalidExprHandleError(_))
+ ));
+ assert!(matches!(
+ m.try_get_mut(unknown),
+ Err(ExprError::InvalidExprHandleError(_))
+ ));
+
+ let x = m.lit(5.);
+ let mut expected = Expr::Literal(LiteralExpr::new(5.));
+ assert_eq!(m.get(x), Some(&expected));
+ assert_eq!(m.get_mut(x), Some(&mut expected));
+ assert_eq!(m.try_get(x), Ok(&expected));
+ assert_eq!(m.try_get_mut(x), Ok(&mut expected));
+ }
+
+ #[test]
+ fn local_var() {
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ let mut h = HashSet::new();
+ for _ in 0..100 {
+ let v = ctx.make_local_var();
+ assert!(h.insert(v));
+ }
+ }
+
+ #[test]
+ fn make_fn() {
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ let mut module = Module::default();
+
+ // Make a function
+ let func_name = "my_func";
+ let args = "arg0: i32, arg1: f32";
+ assert!(ctx
+ .make_fn(func_name, args, None, &mut module, &mut |m, ctx| {
+ m.lit(3.);
+ let v = ctx.make_local_var();
+ assert_eq!(v, "var0");
+ let code = String::new();
+ Ok(code)
+ })
+ .is_ok());
+
+ // The local function context doesn't influence the outer caller context
+ let v = ctx.make_local_var();
+ assert_eq!(v, "var0");
+
+ // However the module is common to the outer caller and the function
+ assert!(!module.expressions.is_empty());
+ }
+
+ #[test]
+ fn property() {
+ let mut m = Module::default();
+
+ let _my_prop = m.add_property("my_prop", Value::Scalar(345_u32.into()));
+ let _other_prop = m.add_property(
+ "other_prop",
+ Value::Vector(Vec3::new(3., -7.5, 42.42).into()),
+ );
+
+ assert!(m.properties().iter().any(|p| p.name() == "my_prop"));
+ assert!(m.properties().iter().any(|p| p.name() == "other_prop"));
+ assert!(!m.properties().iter().any(|p| p.name() == "do_not_exist"));
+ }
+
+ #[test]
+ fn writer() {
+ // Get a module and its writer
+ let w = ExprWriter::new();
+ let my_prop = w.add_property("my_prop", 3.0.into());
+
+ // Build some expression
+ let x = w.lit(3.).abs().max(w.attr(Attribute::POSITION) * w.lit(2.))
+ + w.lit(-4.).min(w.prop(my_prop));
+ let x = x.expr();
+
+ // Create an evaluation context
+ let property_layout =
+ PropertyLayout::new(&[Property::new("my_prop", ScalarValue::Float(3.))]);
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let m = w.finish();
+ let mut context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+
+ // Evaluate the expression
+ let x = m.try_get(x).unwrap();
+ let s = x.eval(&m, &mut context).unwrap();
+ assert_eq!(
+ "(max(abs(3.), (particle.position) * (2.))) + (min(-4., properties[properties_array_index].my_prop))"
+ .to_string(),
+ s
+ );
+ }
+
+ #[test]
+ fn type_error() {
+ let l = Value::Scalar(3.5_f32.into());
+ let r: Result<Vec2, ExprError> = l.try_into();
+ assert!(r.is_err());
+ assert!(matches!(r, Err(ExprError::TypeError(_))));
+ }
+
+ #[test]
+ fn math_expr() {
+ let mut m = Module::default();
+
+ let x = m.attr(Attribute::POSITION);
+ let y = m.lit(Vec3::ONE);
+
+ let add = m.add(x, y);
+ let sub = m.sub(x, y);
+ let mul = m.mul(x, y);
+ let div = m.div(x, y);
+ let rem = m.rem(x, y);
+ let lt = m.lt(x, y);
+ let le = m.le(x, y);
+ let gt = m.gt(x, y);
+ let ge = m.ge(x, y);
+
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+
+ for (expr, op) in [
+ (add, "+"),
+ (sub, "-"),
+ (mul, "*"),
+ (div, "/"),
+ (rem, "%"),
+ (lt, "<"),
+ (le, "<="),
+ (gt, ">"),
+ (ge, ">="),
+ ] {
+ let expr = ctx.eval(&m, expr);
+ assert!(expr.is_ok());
+ let expr = expr.unwrap();
+ assert_eq!(
+ expr,
+ format!(
+ "(particle.{}) {} (vec3<f32>(1.,1.,1.))",
+ Attribute::POSITION.name(),
+ op,
+ )
+ );
+ }
+ }
+
+ #[test]
+ fn builtin_expr() {
+ let mut m = Module::default();
+
+ // Simulation parameters
+ let builtin_ops = [
+ BuiltInOperator::Time,
+ BuiltInOperator::DeltaTime,
+ BuiltInOperator::VirtualTime,
+ BuiltInOperator::VirtualDeltaTime,
+ BuiltInOperator::RealTime,
+ BuiltInOperator::RealDeltaTime,
+ ];
+ for op in builtin_ops {
+ let handle = m.builtin(op);
+
+ {
+ let expr = m.get(handle);
+ assert!(expr.is_some());
+ let expr = expr.unwrap();
+ assert!(matches!(*expr, Expr::BuiltIn(_)));
+ if let Expr::BuiltIn(op) = expr {
+ assert!(builtin_ops.contains(&op.operator));
+ }
+ }
+
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+
+ let expr = ctx.eval(&m, handle);
+ assert!(expr.is_ok());
+ let expr = expr.unwrap();
+ assert_eq!(expr, format!("sim_params.{}", op.name()));
+ }
+
+ // Exercise the expression introspection
+ for (handle, expr) in m.expressions() {
+ assert!(handle.index() < m.expressions.len());
+ assert!(matches!(*expr, Expr::BuiltIn(_)));
+ if let Expr::BuiltIn(op) = expr {
+ assert!(builtin_ops.contains(&op.operator));
+ }
+ }
+
+ // is_alive
+ {
+ let value = m.builtin(BuiltInOperator::IsAlive);
+
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+
+ let expr = ctx.eval(&m, value);
+ assert!(expr.is_ok());
+ let expr = expr.unwrap();
+ assert_eq!(expr, "is_alive");
+ }
+
+ // BuiltInOperator::Rand (which has side effect)
+ for (scalar_type, prefix) in [
+ (ScalarType::Bool, "b"),
+ (ScalarType::Float, "f"),
+ (ScalarType::Int, "i"),
+ (ScalarType::Uint, "u"),
+ ] {
+ let value = m.builtin(BuiltInOperator::Rand(scalar_type.into()));
+
+ // Scalar form
+ {
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+
+ let expr = ctx.eval(&m, value);
+ assert!(expr.is_ok());
+ let expr = expr.unwrap();
+ assert_eq!(expr, "var0");
+ assert_eq!(ctx.main_code, format!("let var0 = {}rand();\n", prefix));
+ }
+
+ // Vector form
+ for count in 2..=4 {
+ let vec = m.builtin(BuiltInOperator::Rand(
+ VectorType::new(scalar_type, count).into(),
+ ));
+
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+
+ let expr = ctx.eval(&m, vec);
+ assert!(expr.is_ok());
+ let expr = expr.unwrap();
+ assert_eq!(expr, "var0");
+ assert_eq!(
+ ctx.main_code,
+ format!("let var0 = {}rand{}();\n", prefix, count)
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn unary_expr() {
+ let mut m = Module::default();
+
+ let x = m.attr(Attribute::POSITION);
+ let y = m.lit(Vec3::new(1., -3.1, 6.99));
+ let z = m.lit(BVec3::new(false, true, false));
+ let w = m.lit(Vec4::W);
+ let v = m.lit(Vec4::new(-1., 1., 0., 7.2));
+ let us = m.lit(0x0u32);
+ let uu = m.lit(0x0u32);
+
+ let abs = m.abs(x);
+ let acos = m.acos(w);
+ let all = m.all(z);
+ let any = m.any(z);
+ let asin = m.asin(w);
+ let atan = m.atan(w);
+ let ceil = m.ceil(y);
+ let cos = m.cos(y);
+ let exp = m.exp(y);
+ let exp2 = m.exp2(y);
+ let floor = m.floor(y);
+ let fract = m.fract(y);
+ let inv_sqrt = m.inverse_sqrt(y);
+ let length = m.length(y);
+ let log = m.log(y);
+ let log2 = m.log2(y);
+ let norm = m.normalize(y);
+ let pack4x8snorm = m.pack4x8snorm(v);
+ let pack4x8unorm = m.pack4x8unorm(v);
+ let round = m.round(y);
+ let saturate = m.saturate(y);
+ let sign = m.sign(y);
+ let sin = m.sin(y);
+ let sqrt = m.sqrt(y);
+ let tan = m.tan(y);
+ let unpack4x8snorm = m.unpack4x8snorm(us);
+ let unpack4x8unorm = m.unpack4x8unorm(uu);
+ let comp_x = m.x(w);
+ let comp_y = m.y(w);
+ let comp_z = m.z(w);
+ let comp_w = m.w(w);
+
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+
+ for (expr, op, inner) in [
+ (
+ abs,
+ "abs",
+ &format!("particle.{}", Attribute::POSITION.name())[..],
+ ),
+ (acos, "acos", "vec4<f32>(0.,0.,0.,1.)"),
+ (all, "all", "vec3<bool>(false,true,false)"),
+ (any, "any", "vec3<bool>(false,true,false)"),
+ (asin, "asin", "vec4<f32>(0.,0.,0.,1.)"),
+ (atan, "atan", "vec4<f32>(0.,0.,0.,1.)"),
+ (ceil, "ceil", "vec3<f32>(1.,-3.1,6.99)"),
+ (cos, "cos", "vec3<f32>(1.,-3.1,6.99)"),
+ (exp, "exp", "vec3<f32>(1.,-3.1,6.99)"),
+ (exp2, "exp2", "vec3<f32>(1.,-3.1,6.99)"),
+ (floor, "floor", "vec3<f32>(1.,-3.1,6.99)"),
+ (fract, "fract", "vec3<f32>(1.,-3.1,6.99)"),
+ (inv_sqrt, "inverseSqrt", "vec3<f32>(1.,-3.1,6.99)"),
+ (length, "length", "vec3<f32>(1.,-3.1,6.99)"),
+ (log, "log", "vec3<f32>(1.,-3.1,6.99)"),
+ (log2, "log2", "vec3<f32>(1.,-3.1,6.99)"),
+ (norm, "normalize", "vec3<f32>(1.,-3.1,6.99)"),
+ (pack4x8snorm, "pack4x8snorm", "vec4<f32>(-1.,1.,0.,7.2)"),
+ (pack4x8unorm, "pack4x8unorm", "vec4<f32>(-1.,1.,0.,7.2)"),
+ (round, "round", "vec3<f32>(1.,-3.1,6.99)"),
+ (saturate, "saturate", "vec3<f32>(1.,-3.1,6.99)"),
+ (sign, "sign", "vec3<f32>(1.,-3.1,6.99)"),
+ (sin, "sin", "vec3<f32>(1.,-3.1,6.99)"),
+ (sqrt, "sqrt", "vec3<f32>(1.,-3.1,6.99)"),
+ (tan, "tan", "vec3<f32>(1.,-3.1,6.99)"),
+ (unpack4x8snorm, "unpack4x8snorm", "0u"),
+ (unpack4x8unorm, "unpack4x8unorm", "0u"),
+ ] {
+ let expr = ctx.eval(&m, expr);
+ assert!(expr.is_ok());
+ let expr = expr.unwrap();
+ assert_eq!(expr, format!("{}({})", op, inner));
+ }
+
+ for (expr, op, inner) in [
+ (comp_x, "x", "vec4<f32>(0.,0.,0.,1.)"),
+ (comp_y, "y", "vec4<f32>(0.,0.,0.,1.)"),
+ (comp_z, "z", "vec4<f32>(0.,0.,0.,1.)"),
+ (comp_w, "w", "vec4<f32>(0.,0.,0.,1.)"),
+ ] {
+ let expr = ctx.eval(&m, expr);
+ assert!(expr.is_ok());
+ let expr = expr.unwrap();
+ assert_eq!(expr, format!("{}.{}", inner, op));
+ }
+ }
+
+ #[test]
+ fn binary_expr() {
+ let mut m = Module::default();
+
+ let x = m.attr(Attribute::POSITION);
+ let y = m.lit(Vec3::ONE);
+ let z = m.lit(1.45);
+
+ let atan2 = m.atan2(x, y);
+ let cross = m.cross(x, y);
+ let dist = m.distance(x, y);
+ let dot = m.dot(x, y);
+ let min = m.min(x, y);
+ let max = m.max(x, y);
+ let step = m.step(x, y);
+ let vec4_xyz_w = m.vec4_xyz_w(x, z);
+
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+
+ for (expr, op) in [
+ (atan2, "atan2"),
+ (cross, "cross"),
+ (dist, "distance"),
+ (dot, "dot"),
+ (min, "min"),
+ (max, "max"),
+ (step, "step"),
+ ] {
+ let expr = ctx.eval(&m, expr);
+ assert!(expr.is_ok());
+ let expr = expr.unwrap();
+ assert_eq!(
+ expr,
+ format!(
+ "{}(particle.{}, vec3<f32>(1.,1.,1.))",
+ op,
+ Attribute::POSITION.name(),
+ )
+ );
+ }
+
+ {
+ let expr = ctx.eval(&m, vec4_xyz_w);
+ assert!(expr.is_ok());
+ let expr = expr.unwrap();
+ let z = ctx.eval(&m, z).unwrap();
+ assert_eq!(
+ expr,
+ format!("vec4(particle.{}, {})", Attribute::POSITION.name(), z)
+ );
+ }
+ }
+
+ #[test]
+ fn ternary_expr() {
+ let mut m = Module::default();
+
+ let x = m.attr(Attribute::POSITION);
+ let y = m.lit(Vec3::ONE);
+ let z = m.lit(Vec3::splat(2.));
+ let t = m.lit(0.3);
+ let a = m.lit(-4.2);
+ let b = m.lit(53.09);
+
+ let mix = m.mix(x, y, t);
+ let clamp = m.clamp(x, y, z);
+ let smoothstep = m.smoothstep(x, y, x);
+ let vecthree = m.vec3(a, b, t);
+
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+
+ for (expr, op, third) in [
+ (mix, "mix", t),
+ (clamp, "clamp", z),
+ (smoothstep, "smoothstep", x),
+ ] {
+ let expr = ctx.eval(&m, expr);
+ assert!(expr.is_ok());
+ let expr = expr.unwrap();
+ let third = ctx.eval(&m, third).unwrap();
+ assert_eq!(
+ expr,
+ format!(
+ "{}(particle.{}, vec3<f32>(1.,1.,1.), {})",
+ op,
+ Attribute::POSITION.name(),
+ third
+ )
+ );
+ }
+
+ {
+ let expr = ctx.eval(&m, vecthree);
+ assert!(expr.is_ok());
+ let expr = expr.unwrap();
+ let a = ctx.eval(&m, a).unwrap();
+ let b = ctx.eval(&m, b).unwrap();
+ let t = ctx.eval(&m, t).unwrap();
+ assert_eq!(expr, format!("vec3({}, {}, {})", a, b, t));
+ }
+ }
+
+ #[test]
+ fn cast_expr() {
+ let mut m = Module::default();
+
+ let x = m.attr(Attribute::POSITION);
+ let y = m.lit(IVec2::ONE);
+ let z = m.lit(0.3);
+ let w = m.lit(false);
+
+ let cx = m.cast(x, VectorType::VEC3I);
+ let cy = m.cast(y, VectorType::VEC2U);
+ let cz = m.cast(z, ScalarType::Int);
+ let cw = m.cast(w, ScalarType::Uint);
+
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+
+ for (expr, cast, target) in [
+ (x, cx, ValueType::Vector(VectorType::VEC3I)),
+ (y, cy, VectorType::VEC2U.into()),
+ (z, cz, ScalarType::Int.into()),
+ (w, cw, ScalarType::Uint.into()),
+ ] {
+ let expr = ctx.eval(&m, expr);
+ assert!(expr.is_ok());
+ let expr = expr.unwrap();
+ let cast = ctx.eval(&m, cast);
+ assert!(cast.is_ok());
+ let cast = cast.unwrap();
+ assert_eq!(cast, format!("{}({})", target.to_wgsl_string(), expr));
+ }
+ }
+
+ #[test]
+ fn attribute_pointer() {
+ let mut m = Module::default();
+ let x = m.attr(Attribute::POSITION);
+
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+
+ let res = ctx.eval(&m, x);
+ assert!(res.is_ok());
+ let xx = res.ok().unwrap();
+ assert_eq!(xx, format!("particle.{}", Attribute::POSITION.name()));
+
+ // Use a different context; it's invalid to reuse a mutated context, as the
+ // expression cache will have been generated with the wrong context.
+ let mut ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ )
+ .with_attribute_pointer();
+
+ let res = ctx.eval(&m, x);
+ assert!(res.is_ok());
+ let xx = res.ok().unwrap();
+ assert_eq!(xx, format!("(*particle).{}", Attribute::POSITION.name()));
+ }
+
+ #[test]
+ #[should_panic]
+ fn invalid_cast_vector_to_scalar() {
+ let mut m = Module::default();
+ let x = m.lit(Vec2::ONE);
+ let _ = m.cast(x, ScalarType::Float);
+ }
+
+ #[test]
+ #[should_panic]
+ fn invalid_cast_matrix_to_scalar() {
+ let mut m = Module::default();
+ let x = m.lit(Value::Matrix(Mat4::ZERO.into()));
+ let _ = m.cast(x, ScalarType::Float);
+ }
+
+ #[test]
+ #[should_panic]
+ fn invalid_cast_matrix_to_vector() {
+ let mut m = Module::default();
+ let x = m.lit(Value::Matrix(Mat4::ZERO.into()));
+ let _ = m.cast(x, VectorType::VEC4F);
+ }
+
+ #[test]
+ #[should_panic]
+ fn invalid_cast_scalar_to_matrix() {
+ let mut m = Module::default();
+ let x = m.lit(3.);
+ let _ = m.cast(x, MatrixType::MAT3X3F);
+ }
+
+ #[test]
+ #[should_panic]
+ fn invalid_cast_vector_to_matrix() {
+ let mut m = Module::default();
+ let x = m.lit(Vec3::ZERO);
+ let _ = m.cast(x, MatrixType::MAT2X4F);
+ }
+
+ #[test]
+ fn cast_expr_new() {
+ let mut m = Module::default();
+
+ let x = m.attr(Attribute::POSITION);
+ let c = CastExpr::new(x, VectorType::VEC3F);
+ assert_eq!(c.value_type(), ValueType::Vector(VectorType::VEC3F));
+ assert_eq!(c.is_valid(&m), Some(true));
+
+ let x = m.attr(Attribute::POSITION);
+ let c = CastExpr::new(x, ScalarType::Bool);
+ assert_eq!(c.value_type(), ValueType::Scalar(ScalarType::Bool));
+ assert_eq!(c.is_valid(&m), Some(false)); // invalid cast vector -> scalar
+
+ let p = m.add_property("my_prop", 3.0.into());
+ let y = m.prop(p);
+ let c = CastExpr::new(y, MatrixType::MAT2X3F);
+ assert_eq!(c.value_type(), ValueType::Matrix(MatrixType::MAT2X3F));
+ assert_eq!(c.is_valid(&m), None); // properties' value_type() is unknown
+ }
+
+ #[test]
+ fn side_effect() {
+ let mut m = Module::default();
+
+ // Adding the same cloned expression with side effect to itself should yield
+ // twice the value, and not two separate evaluations of the expression.
+ // CORRECT:
+ // let r = frand();
+ // r + r
+ // INCORRECT:
+ // frand() + frand()
+
+ let r = m.builtin(BuiltInOperator::Rand(ScalarType::Float.into()));
+ let r2 = r;
+ let r3 = r2;
+ let a = m.add(r, r2);
+ let b = m.mix(r, r2, r3);
+ let c = m.abs(a);
+
+ {
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ let value = ctx.eval(&m, a).unwrap();
+ assert_eq!(value, "(var0) + (var0)");
+ assert_eq!(ctx.main_code, "let var0 = frand();\n");
+ }
+
+ {
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ let value = ctx.eval(&m, b).unwrap();
+ assert_eq!(value, "mix(var0, var0, var0)");
+ assert_eq!(ctx.main_code, "let var0 = frand();\n");
+ }
+
+ {
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ let value = ctx.eval(&m, c).unwrap();
+ assert_eq!(value, "abs((var0) + (var0))");
+ assert_eq!(ctx.main_code, "let var0 = frand();\n");
+ }
+ }
+
+ // #[test]
+ // fn serde() {
+ // let v = Value::Scalar(3.0_f32.into());
+ // let l: LiteralExpr = v.into();
+ // assert_eq!(Ok(v), l.eval());
+ // let s = ron::to_string(&l).unwrap();
+ // println!("literal: {:?}", s);
+ // let l_serde: LiteralExpr = ron::from_str(&s).unwrap();
+ // assert_eq!(l_serde, l);
+
+ // let b: ExprHandle = Box::new(l);
+ // let s = ron::to_string(&b).unwrap();
+ // println!("boxed literal: {:?}", s);
+ // let b_serde: ExprHandle = ron::from_str(&s).unwrap();
+ // assert!(b_serde.is_const());
+ // assert_eq!(b_serde.to_wgsl_string(), b.to_wgsl_string());
+
+ // let v0 = Value::Scalar(3.0_f32.into());
+ // let v1 = Value::Scalar(2.5_f32.into());
+ // let l0: LiteralExpr = v0.into();
+ // let l1: LiteralExpr = v1.into();
+ // let a = l0 + l1;
+ // assert!(a.is_const());
+ // assert_eq!(Ok(Value::Scalar(5.5_f32.into())), a.eval());
+ // let s = ron::to_string(&a).unwrap();
+ // println!("add: {:?}", s);
+ // let a_serde: AddExpr = ron::from_str(&s).unwrap();
+ // println!("a_serde: {:?}", a_serde);
+ // assert_eq!(a_serde.left.to_wgsl_string(), l0.to_wgsl_string());
+ // assert_eq!(a_serde.right.to_wgsl_string(), l1.to_wgsl_string());
+ // }
+
+ #[test]
+ fn expr_handle_serde() {
+ let handle = ExprHandle {
+ id: NonZeroU32::new(42).unwrap(),
+ };
+
+ // ser
+ let s = ron::ser::to_string_pretty(&handle, PrettyConfig::default()).unwrap();
+ eprintln!("{}", s);
+
+ // de
+ {
+ let mut de = ron::de::Deserializer::from_str(&s).unwrap();
+ let serde_handle = ExprHandle::deserialize(&mut de).unwrap();
+ assert_eq!(handle, serde_handle);
+ }
+
+ // de -- literal string
+ {
+ let mut de = ron::de::Deserializer::from_str("\"#42\"").unwrap();
+ let serde_handle = ExprHandle::deserialize(&mut de).unwrap();
+ assert_eq!(handle, serde_handle);
+ }
+
+ // de -- invalid string
+ {
+ let mut de = ron::de::Deserializer::from_str("\"invalid\"").unwrap();
+ let ret = ExprHandle::deserialize(&mut de);
+ assert!(ret.is_err());
+ }
+
+ // de -- literal (not supported)
+ {
+ let mut de = ron::de::Deserializer::from_str("33").unwrap();
+ let ret = ExprHandle::deserialize(&mut de);
+ assert!(ret.is_err());
+ }
+
+ // de -- invalid ID (zero)
+ {
+ let mut de = ron::de::Deserializer::from_str("\"#0\"").unwrap();
+ let ret = ExprHandle::deserialize(&mut de);
+ assert!(ret.is_err());
+ }
+
+ // de -- invalid ID (negative)
+ {
+ let mut de = ron::de::Deserializer::from_str("\"#-5\"").unwrap();
+ let ret = ExprHandle::deserialize(&mut de);
+ assert!(ret.is_err());
+ }
+
+ // de -- valid ID (u32::MAX)
+ {
+ let mut de = ron::de::Deserializer::from_str("\"#4294967295\"").unwrap();
+ let serde_handle = ExprHandle::deserialize(&mut de).unwrap();
+ assert_eq!(serde_handle.id.get(), u32::MAX);
+ }
+
+ // de -- invalid ID (u32::MAX + 1; out of bounds)
+ {
+ let mut de = ron::de::Deserializer::from_str("\"#4294967296\"").unwrap();
+ let ret = ExprHandle::deserialize(&mut de);
+ assert!(ret.is_err());
+ }
+ }
+
+ #[test]
+ fn texture_load_expr() {
+ let mut module = Module::default();
+ let coordinates = module.lit(Vec2::ZERO);
+ let array_index = module.lit(0_u32);
+ let mip_level = module.lit(0_u32);
+
+ let dims = [
+ SlotDimension::D1,
+ SlotDimension::D2,
+ SlotDimension::D2Array,
+ SlotDimension::Cube,
+ SlotDimension::CubeArray,
+ SlotDimension::D3,
+ SlotDimension::DepthD2,
+ SlotDimension::DepthD2Array,
+ SlotDimension::DepthCube,
+ SlotDimension::DepthCubeArray,
+ ];
+ let mips = [None, Some(mip_level)];
+ for dim in &dims {
+ for mip in &mips {
+ let mip = *mip;
+
+ let res = TextureLoadExpr::new(4, *dim, coordinates, None, mip);
+ assert_eq!(
+ res.is_ok(),
+ !dim.is_array() && !dim.is_cube(),
+ "array=false dim={dim:?} res={res:?} mip={mip:?}"
+ );
+
+ let res = TextureLoadExpr::new(4, *dim, coordinates, Some(array_index), mip);
+ assert_eq!(
+ res.is_ok(),
+ dim.is_array() && !dim.is_cube(),
+ "array=true dim={dim:?} res={res:?} mip={mip:?}"
+ );
+ }
+ }
+ }
+}
diff --git a/vendor/bevy_hanabi/src/graph/mod.rs b/vendor/bevy_hanabi/src/graph/mod.rs
new file mode 100644
index 00000000..85970f34
--- /dev/null
+++ b/vendor/bevy_hanabi/src/graph/mod.rs
@@ -0,0 +1,2394 @@
+//! Effect graph and language definition, including *expressions*.
+//!
+//! This module contains the elements used to build an _effect graph_, a fully
+//! customizable description of a visual effect.
+//!
+//! The effect graph API is composed of two layers:
+//! - The [**Expression API**] provides a micro-language to build shader
+//! expressions ([`Expr`]) via code. Those expressions are composed together
+//! into complex behaviors assigned to the input values of some modifiers.
+//! This enables complete customizing of the modifiers. This API is focused on
+//! runtime execution and asset serialization. It provides the user with a way
+//! to _indirectly_ write effect shaders without any knowledge about shaders,
+//! and with a framework which guarantees the shader code generated is
+//! correct.
+//! - The [**Node API**] provides a higher-level API built on top of the
+//! Expression API. Its use is entirely optional. It defines a node graph
+//! ([`Graph`]), where each node ([`Node`]) represents an expression or a
+//! modifier. Nodes are linked together to implicitly build expressions. This
+//! API focuses on asset editing, with the explicit intent to be used to build
+//! a (visual) effect editor.
+//!
+//! # API status
+//!
+//! Currently effect graphs are not fully available yet; only some preview
+//! elements exist.
+//!
+//! The Expression API already contains a good set of expressions, and some
+//! modifiers have already been converted to accept expressions for their input
+//! fields. Its generally in a reasonable shape for early adoption.
+//!
+//! The Node API contains a basic node and graph definition, which is entirely
+//! experimental at this stage.
+//!
+//! We recommend starting to familiarize yourself with effect graphs, and
+//! starting to port your code to use expressions ([`Expr`]), as the entire
+//! library is moving in the direction of adopting effect graphs across the
+//! board.
+//!
+//! [**Expression API**]: crate::graph::expr
+//! [**Node API**]: crate::graph::node
+
+use std::fmt::Debug;
+
+use bevy::{
+ math::{
+ BVec2, BVec3, BVec4, FloatOrd, IVec2, IVec3, IVec4, Mat2, Mat3, Mat4, UVec2, UVec3, UVec4,
+ Vec2, Vec3, Vec3A, Vec4,
+ },
+ reflect::Reflect,
+};
+use serde::{Deserialize, Serialize};
+
+use crate::{MatrixType, ScalarType, ToWgslString, ValueType, VectorType};
+
+pub mod expr;
+pub mod node;
+
+pub use expr::{
+ AttributeExpr, BinaryOperator, BuiltInExpr, BuiltInOperator, EvalContext, Expr, ExprError,
+ ExprHandle, ExprWriter, LiteralExpr, Module, PropertyExpr, UnaryOperator, WriterExpr,
+};
+pub use node::{
+ AddNode, AttributeNode, DivNode, Graph, MulNode, Node, NormalizeNode, Slot, SlotDir, SlotId,
+ SubNode, TimeNode,
+};
+
+/// Variant storage for a scalar value.
+#[derive(Debug)]
+#[non_exhaustive]
+pub enum ScalarValueMut<'a> {
+ /// Single `bool` value.
+ Bool(&'a mut bool),
+ /// Single `f32` value.
+ Float(&'a mut f32),
+ /// Single `i32` value.
+ Int(&'a mut i32),
+ /// Single `u32` value.
+ Uint(&'a mut u32),
+}
+
+/// Variant storage for a single (scalar) value.
+///
+/// The value implements total equality and hashing. For [`ScalarValue::Float`],
+/// the total equality is based on [`FloatOrd`]. Values of different types
+/// compare inequally to each other, even if the values would be equal after
+/// casting, and hash differently. To compare two [`ScalarValue`] taking into
+/// account casting, use [`cast_eq()`].
+///
+/// [`cast_eq()`]: crate::graph::ScalarValue::cast_eq
+#[derive(Debug, Clone, Copy, Reflect, Serialize, Deserialize)]
+#[non_exhaustive] // f16 not supported yet
+pub enum ScalarValue {
+ /// Single `bool` value.
+ Bool(bool),
+ /// Single `f32` value.
+ Float(f32),
+ /// Single `i32` value.
+ Int(i32),
+ /// Single `u32` value.
+ Uint(u32),
+}
+
+impl ScalarValue {
+ /// The value `false` when a boolean value is stored internally.
+ pub(crate) const BOOL_FALSE_STORAGE: u32 = 0u32;
+
+ /// The value `true` when a boolean value is stored internally.
+ pub(crate) const BOOL_TRUE_STORAGE: u32 = 0xFF_FF_FF_FFu32;
+
+ /// The value `false` and `true` when a boolean value is stored internally.
+ pub(crate) const BOOL_STORAGE: [u32; 2] = [Self::BOOL_FALSE_STORAGE, Self::BOOL_TRUE_STORAGE];
+
+ /// Convert this value to a `bool` value.
+ ///
+ /// Any non-zero value converts to `true`, while a zero value converts to
+ /// `false`.
+ pub fn as_bool(&self) -> bool {
+ match *self {
+ ScalarValue::Bool(b) => b,
+ ScalarValue::Float(f) => f != 0f32,
+ ScalarValue::Int(i) => i != 0,
+ ScalarValue::Uint(u) => u != 0,
+ }
+ }
+
+ /// Convert this value to a floating-point value.
+ ///
+ /// Boolean values convert to 0 or 1. Numeric values are cast to `f32`.
+ pub fn as_f32(&self) -> f32 {
+ match *self {
+ ScalarValue::Bool(b) => {
+ if b {
+ 1f32
+ } else {
+ 0f32
+ }
+ }
+ ScalarValue::Float(f) => f,
+ ScalarValue::Int(i) => i as f32,
+ ScalarValue::Uint(u) => u as f32,
+ }
+ }
+
+ /// Convert this value to an `i32` value.
+ ///
+ /// Boolean values convert to 0 or 1. Numeric values are cast to `i32`.
+ pub fn as_i32(&self) -> i32 {
+ match *self {
+ ScalarValue::Bool(b) => {
+ if b {
+ 1i32
+ } else {
+ 0i32
+ }
+ }
+ ScalarValue::Float(f) => f as i32,
+ ScalarValue::Int(i) => i,
+ ScalarValue::Uint(u) => u as i32,
+ }
+ }
+
+ /// Convert this value to an `u32` value.
+ ///
+ /// Boolean values convert to 0 or 1. Numeric values are cast to `u32`.
+ pub fn as_u32(&self) -> u32 {
+ match *self {
+ ScalarValue::Bool(b) => {
+ if b {
+ 1u32
+ } else {
+ 0u32
+ }
+ }
+ ScalarValue::Float(f) => f as u32,
+ ScalarValue::Int(i) => i as u32,
+ ScalarValue::Uint(u) => u,
+ }
+ }
+
+ /// Get the value as a binary blob ready for GPU upload.
+ pub fn as_bytes(&self) -> &[u8] {
+ match self {
+ ScalarValue::Bool(_) => panic!("Cannot convert scalar bool to byte slice."),
+ ScalarValue::Float(f) => bytemuck::cast_slice::<f32, u8>(std::slice::from_ref(f)),
+ ScalarValue::Int(i) => bytemuck::cast_slice::<i32, u8>(std::slice::from_ref(i)),
+ ScalarValue::Uint(u) => bytemuck::cast_slice::<u32, u8>(std::slice::from_ref(u)),
+ }
+ }
+
+ /// Get the raw internal storage value representing this scalar value.
+ ///
+ /// Used internally for some conversion operations. The representation is
+ /// not guaranteed to be stable.
+ fn as_storage(&self) -> u32 {
+ match self {
+ ScalarValue::Bool(b) => Self::BOOL_STORAGE[*b as usize],
+ ScalarValue::Float(f) => bytemuck::cast::<f32, u32>(*f),
+ ScalarValue::Int(i) => bytemuck::cast::<i32, u32>(*i),
+ ScalarValue::Uint(u) => *u,
+ }
+ }
+
+ /// Get the scalar type of this value.
+ pub fn scalar_type(&self) -> ScalarType {
+ match self {
+ ScalarValue::Bool(_) => ScalarType::Bool,
+ ScalarValue::Float(_) => ScalarType::Float,
+ ScalarValue::Int(_) => ScalarType::Int,
+ ScalarValue::Uint(_) => ScalarType::Uint,
+ }
+ }
+
+ /// Check equality with another value by casting the other value to this
+ /// value's type.
+ ///
+ /// Floating point values ([`ScalarValue::Float`]) use [`FloatOrd`] for
+ /// total equality.
+ pub fn cast_eq(&self, other: &Self) -> bool {
+ match *self {
+ ScalarValue::Bool(b) => b == other.as_bool(),
+ ScalarValue::Float(f) => FloatOrd(f) == FloatOrd(other.as_f32()),
+ ScalarValue::Int(i) => i == other.as_i32(),
+ ScalarValue::Uint(u) => u == other.as_u32(),
+ }
+ }
+
+ // fn binary_op(&self, other: &Self, op: BinaryOperator) -> Self {
+ // match *self {
+ // ScalarValue::Bool(_) => panic!("Cannot apply binary operation to
+ // boolean value."), ScalarValue::Float(f) =>
+ // ScalarValue::Float(op.apply_f32(f, other.as_f32())),
+ // ScalarValue::Int(i) => ScalarValue::Int(op.apply_i32(i,
+ // other.as_i32())), ScalarValue::Uint(u) =>
+ // ScalarValue::Uint(op.apply_u32(u, other.as_u32())), }
+ // }
+}
+
+impl PartialEq for ScalarValue {
+ fn eq(&self, other: &Self) -> bool {
+ match *self {
+ ScalarValue::Bool(b) => match *other {
+ ScalarValue::Bool(b2) => b == b2,
+ _ => false,
+ },
+ ScalarValue::Float(f) => match *other {
+ ScalarValue::Float(f2) => FloatOrd(f) == FloatOrd(f2),
+ _ => false,
+ },
+ ScalarValue::Int(i) => match *other {
+ ScalarValue::Int(i2) => i == i2,
+ _ => false,
+ },
+ ScalarValue::Uint(u) => match *other {
+ ScalarValue::Uint(u2) => u == u2,
+ _ => false,
+ },
+ }
+ }
+}
+
+impl Eq for ScalarValue {}
+
+impl std::hash::Hash for ScalarValue {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ // Hash some u8 to encode the enum variant, then the actual value
+ match *self {
+ ScalarValue::Bool(b) => {
+ 1_u8.hash(state);
+ b.hash(state)
+ }
+ ScalarValue::Float(f) => {
+ 2_u8.hash(state);
+ FloatOrd(f).hash(state);
+ }
+ ScalarValue::Int(i) => {
+ 3_u8.hash(state);
+ i.hash(state);
+ }
+ ScalarValue::Uint(u) => {
+ 4_u8.hash(state);
+ u.hash(state);
+ }
+ }
+ }
+}
+
+impl ToWgslString for ScalarValue {
+ fn to_wgsl_string(&self) -> String {
+ match *self {
+ ScalarValue::Bool(b) => b.to_wgsl_string(),
+ ScalarValue::Float(f) => f.to_wgsl_string(),
+ ScalarValue::Int(i) => i.to_wgsl_string(),
+ ScalarValue::Uint(u) => u.to_wgsl_string(),
+ }
+ }
+}
+
+// impl BinaryOperation for ScalarValue {
+// fn apply(&self, other: &Self, op: BinaryOperator) -> Self {
+// match *self {
+// ScalarValue::Bool(_) => panic!("Cannot apply binary operation to
+// boolean value."), ScalarValue::Float(f) =>
+// ScalarValue::Float(op.apply_f32(f, other.as_f32())),
+// ScalarValue::Int(i) => ScalarValue::Int(op.apply_i32(i, other.as_i32())),
+// ScalarValue::Uint(u) => ScalarValue::Uint(op.apply_u32(u,
+// other.as_u32())), }
+// }
+// }
+
+impl From<bool> for ScalarValue {
+ fn from(value: bool) -> Self {
+ Self::Bool(value)
+ }
+}
+
+impl From<f32> for ScalarValue {
+ fn from(value: f32) -> Self {
+ Self::Float(value)
+ }
+}
+
+impl From<i32> for ScalarValue {
+ fn from(value: i32) -> Self {
+ Self::Int(value)
+ }
+}
+
+impl From<u32> for ScalarValue {
+ fn from(value: u32) -> Self {
+ Self::Uint(value)
+ }
+}
+
+/// Trait to convert the elements of a vector.
+pub trait ElemType {
+ /// The zero element of the type.
+ const ZERO: Self;
+
+ /// Get the N-th component of the vector given its raw storage.
+ fn get_n<const N: usize>(storage: &[u32; 4]) -> Self;
+
+ /// Get the given component of the vector given its raw storage.
+ fn get(index: usize, storage: &[u32; 4]) -> Self;
+
+ /// Get a slice of all the components of the vector given its raw storage.
+ ///
+ /// This is only valid for numeric types, and will panic for a boolean type.
+ fn get_all(storage: &[u32; 4], count: usize) -> &[Self]
+ where
+ Self: Sized;
+
+ /// Get a mutable reference to the given component of the vector from within
+ /// its raw storage.
+ fn get_mut(index: usize, storage: &mut [u32; 4]) -> &mut Self;
+}
+
+impl ElemType for bool {
+ const ZERO: Self = false;
+
+ fn get_n<const N: usize>(storage: &[u32; 4]) -> Self {
+ storage[N] != 0
+ }
+
+ fn get(index: usize, storage: &[u32; 4]) -> Self {
+ storage[index] != 0
+ }
+
+ fn get_all(_storage: &[u32; 4], _count: usize) -> &[Self] {
+ panic!("Cannot get bool element type as slice.");
+ }
+
+ fn get_mut(_index: usize, _storage: &mut [u32; 4]) -> &mut Self {
+ panic!("Cannot get bool element type as mutable reference.");
+ }
+}
+
+impl ElemType for f32 {
+ const ZERO: Self = 0f32;
+
+ fn get_n<const N: usize>(storage: &[u32; 4]) -> Self {
+ bytemuck::cast_slice::<u32, f32>(storage)[N]
+ }
+
+ fn get(index: usize, storage: &[u32; 4]) -> Self {
+ bytemuck::cast_slice::<u32, f32>(storage)[index]
+ }
+
+ fn get_all(storage: &[u32; 4], count: usize) -> &[Self] {
+ &bytemuck::cast_slice::<u32, f32>(storage)[..count]
+ }
+
+ fn get_mut(index: usize, storage: &mut [u32; 4]) -> &mut Self {
+ bytemuck::cast_mut::<u32, f32>(&mut storage[index])
+ }
+}
+
+impl ElemType for i32 {
+ const ZERO: Self = 0i32;
+
+ fn get_n<const N: usize>(storage: &[u32; 4]) -> Self {
+ bytemuck::cast_slice::<u32, i32>(storage)[N]
+ }
+
+ fn get(index: usize, storage: &[u32; 4]) -> Self {
+ bytemuck::cast_slice::<u32, i32>(storage)[index]
+ }
+
+ fn get_all(storage: &[u32; 4], count: usize) -> &[Self] {
+ &bytemuck::cast_slice::<u32, i32>(storage)[..count]
+ }
+
+ fn get_mut(index: usize, storage: &mut [u32; 4]) -> &mut Self {
+ bytemuck::cast_mut::<u32, i32>(&mut storage[index])
+ }
+}
+
+impl ElemType for u32 {
+ const ZERO: Self = 0u32;
+
+ fn get_n<const N: usize>(storage: &[u32; 4]) -> Self {
+ storage[N]
+ }
+
+ fn get(index: usize, storage: &[u32; 4]) -> Self {
+ storage[index]
+ }
+
+ fn get_all(storage: &[u32; 4], count: usize) -> &[Self] {
+ &storage[..count]
+ }
+
+ fn get_mut(index: usize, storage: &mut [u32; 4]) -> &mut Self {
+ &mut storage[index]
+ }
+}
+
+/// Variant storage for a vector value.
+#[derive(Debug, Clone, Copy, Reflect, Serialize, Deserialize)]
+#[serde(from = "VectorValueEnum", into = "VectorValueEnum")]
+pub struct VectorValue {
+ vector_type: VectorType,
+ storage: [u32; 4],
+}
+
+impl VectorValue {
+ /// Workaround for `impl const From<BVec2>`.
+ #[allow(unsafe_code)]
+ pub const fn new_bvec2(value: BVec2) -> Self {
+ Self {
+ vector_type: VectorType::VEC2B,
+ storage: [
+ ScalarValue::BOOL_STORAGE[value.x as usize],
+ ScalarValue::BOOL_STORAGE[value.y as usize],
+ 0u32,
+ 0u32,
+ ],
+ }
+ }
+
+ /// Workaround for `impl const From<BVec3>`.
+ #[allow(unsafe_code)]
+ pub const fn new_bvec3(value: BVec3) -> Self {
+ Self {
+ vector_type: VectorType::VEC3B,
+ storage: [
+ ScalarValue::BOOL_STORAGE[value.x as usize],
+ ScalarValue::BOOL_STORAGE[value.y as usize],
+ ScalarValue::BOOL_STORAGE[value.z as usize],
+ 0u32,
+ ],
+ }
+ }
+
+ /// Workaround for `impl const From<BVec4>`.
+ #[allow(unsafe_code)]
+ pub const fn new_bvec4(value: BVec4) -> Self {
+ Self {
+ vector_type: VectorType::VEC4B,
+ storage: [
+ ScalarValue::BOOL_STORAGE[value.x as usize],
+ ScalarValue::BOOL_STORAGE[value.y as usize],
+ ScalarValue::BOOL_STORAGE[value.z as usize],
+ ScalarValue::BOOL_STORAGE[value.w as usize],
+ ],
+ }
+ }
+
+ /// Workaround for `impl const From<Vec2>`.
+ pub const fn new_vec2(value: Vec2) -> Self {
+ Self {
+ vector_type: VectorType::VEC2F,
+ storage: [f32::to_bits(value.x), f32::to_bits(value.y), 0u32, 0u32],
+ }
+ }
+
+ /// Workaround for `impl const From<Vec3>`.
+ pub const fn new_vec3(value: Vec3) -> Self {
+ Self {
+ vector_type: VectorType::VEC3F,
+ storage: [
+ f32::to_bits(value.x),
+ f32::to_bits(value.y),
+ f32::to_bits(value.z),
+ 0u32,
+ ],
+ }
+ }
+
+ /// Workaround for `impl const From<Vec4>`.
+ #[allow(unsafe_code)]
+ pub const fn new_vec4(value: Vec4) -> Self {
+ Self {
+ vector_type: VectorType::VEC4F,
+ storage: unsafe { std::mem::transmute::<[f32; 4], [u32; 4]>(value.to_array()) },
+ }
+ }
+
+ /// Workaround for `impl const From<IVec2>`.
+ pub const fn new_ivec2(value: IVec2) -> Self {
+ Self {
+ vector_type: VectorType::VEC2I,
+ storage: [value.x as u32, value.y as u32, 0u32, 0u32],
+ }
+ }
+
+ /// Workaround for `impl const From<IVec3>`.
+ pub const fn new_ivec3(value: IVec3) -> Self {
+ Self {
+ vector_type: VectorType::VEC3I,
+ storage: [value.x as u32, value.y as u32, value.z as u32, 0u32],
+ }
+ }
+
+ /// Workaround for `impl const From<IVec4>`.
+ #[allow(unsafe_code)]
+ pub const fn new_ivec4(value: IVec4) -> Self {
+ Self {
+ vector_type: VectorType::VEC4I,
+ storage: unsafe { std::mem::transmute::<[i32; 4], [u32; 4]>(value.to_array()) },
+ }
+ }
+
+ /// Workaround for `impl const From<UVec2>`.
+ pub const fn new_uvec2(v: UVec2) -> Self {
+ Self {
+ vector_type: VectorType::VEC2U,
+ storage: [v.x, v.y, 0, 0],
+ }
+ }
+
+ /// Workaround for `impl const From<UVec3>`.
+ pub const fn new_uvec3(v: UVec3) -> Self {
+ Self {
+ vector_type: VectorType::VEC3U,
+ storage: [v.x, v.y, v.z, 0],
+ }
+ }
+
+ /// Workaround for `impl const From<UVec4>`.
+ pub const fn new_uvec4(v: UVec4) -> Self {
+ Self {
+ vector_type: VectorType::VEC4U,
+ storage: v.to_array(),
+ }
+ }
+
+ /// Create a new vector by "splatting" a scalar value into all components.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the component `count` is not 2/3/4.
+ pub fn splat(value: &ScalarValue, count: u8) -> Self {
+ let raw_value = value.as_storage();
+ Self {
+ vector_type: VectorType::new(value.scalar_type(), count),
+ storage: [raw_value; 4],
+ }
+ }
+
+ /// Get the type of the vector elements.
+ ///
+ /// This is a convenience shortcut for `self.vector_type().elem_type()`.
+ pub fn elem_type(&self) -> ScalarType {
+ self.vector_type.elem_type()
+ }
+
+ /// Get the vector type itself.
+ pub fn vector_type(&self) -> VectorType {
+ self.vector_type
+ }
+
+ /// Get the scalar value of the N-th element of the vector.
+ pub fn value_n<const N: usize>(&self) -> ScalarValue {
+ match self.elem_type() {
+ ScalarType::Bool => ScalarValue::Bool(self.get_n::<bool, N>()),
+ ScalarType::Float => ScalarValue::Float(self.get_n::<f32, N>()),
+ ScalarType::Int => ScalarValue::Int(self.get_n::<i32, N>()),
+ ScalarType::Uint => ScalarValue::Uint(self.get_n::<u32, N>()),
+ }
+ }
+
+ /// Get the scalar value of an element of the vector.
+ pub fn value(&self, index: usize) -> ScalarValue {
+ match self.elem_type() {
+ ScalarType::Bool => ScalarValue::Bool(self.get::<bool>(index)),
+ ScalarType::Float => ScalarValue::Float(self.get::<f32>(index)),
+ ScalarType::Int => ScalarValue::Int(self.get::<i32>(index)),
+ ScalarType::Uint => ScalarValue::Uint(self.get::<u32>(index)),
+ }
+ }
+
+ /// Get the scalar value of an element of the vector.
+ pub fn value_mut(&mut self, index: usize) -> ScalarValueMut<'_> {
+ match self.elem_type() {
+ ScalarType::Bool => ScalarValueMut::Bool(self.get_mut::<bool>(index)),
+ ScalarType::Float => ScalarValueMut::Float(self.get_mut::<f32>(index)),
+ ScalarType::Int => ScalarValueMut::Int(self.get_mut::<i32>(index)),
+ ScalarType::Uint => ScalarValueMut::Uint(self.get_mut::<u32>(index)),
+ }
+ }
+
+ /// Get the value of the N-th element of the vector.
+ pub fn get_n<T: ElemType, const N: usize>(&self) -> T {
+ if self.vector_type.count() > N {
+ T::get_n::<N>(&self.storage)
+ } else {
+ T::ZERO
+ }
+ }
+
+ /// Get the value of an element of the vector.
+ pub fn get<T: ElemType>(&self, index: usize) -> T {
+ if index < self.vector_type.count() {
+ T::get(index, &self.storage)
+ } else {
+ T::ZERO
+ }
+ }
+
+ /// Get the value of an element of the vector.
+ fn get_mut<T: ElemType>(&mut self, index: usize) -> &mut T {
+ assert!(index < self.vector_type.count());
+ T::get_mut(index, &mut self.storage)
+ }
+
+ /// Get a slice of all the values of the vector.
+ ///
+ /// This is only valid for numeric types, and will panic for a boolean type.
+ pub fn get_all<T: ElemType>(&self) -> &[T] {
+ T::get_all(&self.storage, self.vector_type.count())
+ }
+
+ /// Cast this vector value to a [`BVec2`].
+ ///
+ /// # Panics
+ ///
+ /// Panics if the current vector type is not [`VectorType::VEC2B`].
+ pub fn as_bvec2(&self) -> BVec2 {
+ assert_eq!(self.vector_type, VectorType::VEC2B);
+ BVec2::new(self.storage[0] != 0, self.storage[1] != 0)
+ }
+
+ /// Cast this vector value to a [`BVec3`].
+ ///
+ /// # Panics
+ ///
+ /// Panics if the current vector type is not [`VectorType::VEC3B`].
+ pub fn as_bvec3(&self) -> BVec3 {
+ assert_eq!(self.vector_type, VectorType::VEC3B);
+ BVec3::new(
+ self.storage[0] != 0,
+ self.storage[1] != 0,
+ self.storage[2] != 0,
+ )
+ }
+
+ /// Cast this vector value to a [`BVec4`].
+ ///
+ /// # Panics
+ ///
+ /// Panics if the current vector type is not [`VectorType::VEC4B`].
+ pub fn as_bvec4(&self) -> BVec4 {
+ assert_eq!(self.vector_type, VectorType::VEC4B);
+ BVec4::new(
+ self.storage[0] != 0,
+ self.storage[1] != 0,
+ self.storage[2] != 0,
+ self.storage[3] != 0,
+ )
+ }
+
+ /// Cast this vector value to a [`Vec2`].
+ ///
+ /// # Panics
+ ///
+ /// Panics if the current vector type is not [`VectorType::VEC2F`].
+ pub fn as_vec2(&self) -> Vec2 {
+ assert_eq!(self.vector_type, VectorType::VEC2F);
+ Vec2::from_slice(bytemuck::cast_slice::<u32, f32>(&self.storage))
+ }
+
+ /// Cast this vector value to a [`Vec3`].
+ ///
+ /// # Panics
+ ///
+ /// Panics if the current vector type is not [`VectorType::VEC3F`].
+ pub fn as_vec3(&self) -> Vec3 {
+ assert_eq!(self.vector_type, VectorType::VEC3F);
+ Vec3::from_slice(bytemuck::cast_slice::<u32, f32>(&self.storage))
+ }
+
+ /// Cast this vector value to a [`Vec3A`].
+ ///
+ /// # Panics
+ ///
+ /// Panics if the current vector type is not [`VectorType::VEC3F`].
+ pub fn as_vec3a(&self) -> Vec3A {
+ assert_eq!(self.vector_type, VectorType::VEC3F);
+ Vec3A::from_slice(bytemuck::cast_slice::<u32, f32>(&self.storage))
+ }
+
+ /// Cast this vector value to a [`Vec4`].
+ ///
+ /// # Panics
+ ///
+ /// Panics if the current vector type is not [`VectorType::VEC4F`].
+ pub fn as_vec4(&self) -> Vec4 {
+ assert_eq!(self.vector_type, VectorType::VEC4F);
+ Vec4::from_slice(bytemuck::cast_slice::<u32, f32>(&self.storage))
+ }
+
+ /// Cast this vector value to a [`IVec2`].
+ ///
+ /// # Panics
+ ///
+ /// Panics if the current vector type is not [`VectorType::VEC2I`].
+ pub fn as_ivec2(&self) -> IVec2 {
+ assert_eq!(self.vector_type, VectorType::VEC2I);
+ IVec2::from_slice(bytemuck::cast_slice::<u32, i32>(&self.storage))
+ }
+
+ /// Cast this vector value to a [`IVec3`].
+ ///
+ /// # Panics
+ ///
+ /// Panics if the current vector type is not [`VectorType::VEC3I`].
+ pub fn as_ivec3(&self) -> IVec3 {
+ assert_eq!(self.vector_type, VectorType::VEC3I);
+ IVec3::from_slice(bytemuck::cast_slice::<u32, i32>(&self.storage))
+ }
+
+ /// Cast this vector value to a [`IVec4`].
+ ///
+ /// # Panics
+ ///
+ /// Panics if the current vector type is not [`VectorType::VEC4I`].
+ pub fn as_ivec4(&self) -> IVec4 {
+ assert_eq!(self.vector_type, VectorType::VEC4I);
+ IVec4::from_slice(bytemuck::cast_slice::<u32, i32>(&self.storage))
+ }
+
+ /// Cast this vector value to a [`UVec2`].
+ ///
+ /// # Panics
+ ///
+ /// Panics if the current vector type is not [`VectorType::VEC2U`].
+ pub fn as_uvec2(&self) -> UVec2 {
+ assert_eq!(self.vector_type, VectorType::VEC2U);
+ UVec2::from_slice(&self.storage)
+ }
+
+ /// Cast this vector value to a [`UVec3`].
+ ///
+ /// # Panics
+ ///
+ /// Panics if the current vector type is not [`VectorType::VEC3U`].
+ pub fn as_uvec3(&self) -> UVec3 {
+ assert_eq!(self.vector_type, VectorType::VEC3U);
+ UVec3::from_slice(&self.storage)
+ }
+
+ /// Cast this vector value to a [`UVec4`].
+ ///
+ /// # Panics
+ ///
+ /// Panics if the current vector type is not [`VectorType::VEC4U`].
+ pub fn as_uvec4(&self) -> UVec4 {
+ assert_eq!(self.vector_type, VectorType::VEC4U);
+ UVec4::from_slice(&self.storage)
+ }
+
+ /// Get the value as a binary blob ready for GPU upload.
+ pub fn as_bytes(&self) -> &[u8] {
+ let count = self.vector_type.count();
+ bytemuck::cast_slice::<u32, u8>(&self.storage[..count])
+ }
+
+ /// Check equality with another value by casting the other value to this
+ /// value's type.
+ ///
+ /// Floating point values ([`ScalarValue::Float`]) use [`FloatOrd`] for
+ /// total equality.
+ ///
+ /// Vectors of different size always compare inequal (returns `false`).
+ pub fn cast_eq(&self, other: &Self) -> bool {
+ let count = self.vector_type().count();
+ if count != other.vector_type().count() {
+ return false;
+ }
+ match self.elem_type() {
+ ScalarType::Bool => {
+ let s = self.cast_bool();
+ let o = other.cast_bool();
+ s[..count] == o[..count]
+ }
+ ScalarType::Float => {
+ let s = self.cast_f32();
+ let o = other.cast_f32();
+ s[..count] == o[..count]
+ }
+ ScalarType::Int => {
+ let s = self.cast_i32();
+ let o = other.cast_i32();
+ s[..count] == o[..count]
+ }
+ ScalarType::Uint => {
+ let s = self.cast_u32();
+ let o = other.cast_u32();
+ s[..count] == o[..count]
+ }
+ }
+ }
+
+ fn cast_bool(&self) -> [u32; 4] {
+ match self.elem_type() {
+ ScalarType::Bool => self.storage,
+ ScalarType::Float => [
+ ScalarValue::BOOL_STORAGE
+ [(bytemuck::cast::<u32, f32>(self.storage[0]) != 0.) as usize],
+ ScalarValue::BOOL_STORAGE
+ [(bytemuck::cast::<u32, f32>(self.storage[1]) != 0.) as usize],
+ ScalarValue::BOOL_STORAGE
+ [(bytemuck::cast::<u32, f32>(self.storage[2]) != 0.) as usize],
+ ScalarValue::BOOL_STORAGE
+ [(bytemuck::cast::<u32, f32>(self.storage[3]) != 0.) as usize],
+ ],
+ ScalarType::Int => [
+ ScalarValue::BOOL_STORAGE
+ [(bytemuck::cast::<u32, i32>(self.storage[0]) != 0) as usize],
+ ScalarValue::BOOL_STORAGE
+ [(bytemuck::cast::<u32, i32>(self.storage[1]) != 0) as usize],
+ ScalarValue::BOOL_STORAGE
+ [(bytemuck::cast::<u32, i32>(self.storage[2]) != 0) as usize],
+ ScalarValue::BOOL_STORAGE
+ [(bytemuck::cast::<u32, i32>(self.storage[3]) != 0) as usize],
+ ],
+ ScalarType::Uint => [
+ ScalarValue::BOOL_STORAGE[(self.storage[0] != 0) as usize],
+ ScalarValue::BOOL_STORAGE[(self.storage[1] != 0) as usize],
+ ScalarValue::BOOL_STORAGE[(self.storage[2] != 0) as usize],
+ ScalarValue::BOOL_STORAGE[(self.storage[3] != 0) as usize],
+ ],
+ }
+ }
+
+ fn cast_f32(&self) -> [FloatOrd; 4] {
+ match self.elem_type() {
+ ScalarType::Bool => {
+ let ft = [FloatOrd(0.), FloatOrd(1.)];
+ [
+ ft[(self.storage[0] != 0) as usize],
+ ft[(self.storage[1] != 0) as usize],
+ ft[(self.storage[2] != 0) as usize],
+ ft[(self.storage[3] != 0) as usize],
+ ]
+ }
+ ScalarType::Float => [
+ FloatOrd(bytemuck::cast::<u32, f32>(self.storage[0])),
+ FloatOrd(bytemuck::cast::<u32, f32>(self.storage[1])),
+ FloatOrd(bytemuck::cast::<u32, f32>(self.storage[2])),
+ FloatOrd(bytemuck::cast::<u32, f32>(self.storage[3])),
+ ],
+ ScalarType::Int => [
+ FloatOrd(bytemuck::cast::<u32, i32>(self.storage[0]) as f32),
+ FloatOrd(bytemuck::cast::<u32, i32>(self.storage[1]) as f32),
+ FloatOrd(bytemuck::cast::<u32, i32>(self.storage[2]) as f32),
+ FloatOrd(bytemuck::cast::<u32, i32>(self.storage[3]) as f32),
+ ],
+ ScalarType::Uint => [
+ FloatOrd(self.storage[0] as f32),
+ FloatOrd(self.storage[1] as f32),
+ FloatOrd(self.storage[2] as f32),
+ FloatOrd(self.storage[3] as f32),
+ ],
+ }
+ }
+
+ fn cast_i32(&self) -> [i32; 4] {
+ match self.elem_type() {
+ ScalarType::Bool => {
+ let ft = [0, 1];
+ [
+ ft[(self.storage[0] != 0) as usize],
+ ft[(self.storage[1] != 0) as usize],
+ ft[(self.storage[2] != 0) as usize],
+ ft[(self.storage[3] != 0) as usize],
+ ]
+ }
+ ScalarType::Float => [
+ bytemuck::cast::<u32, f32>(self.storage[0]) as i32,
+ bytemuck::cast::<u32, f32>(self.storage[1]) as i32,
+ bytemuck::cast::<u32, f32>(self.storage[2]) as i32,
+ bytemuck::cast::<u32, f32>(self.storage[3]) as i32,
+ ],
+ ScalarType::Int => [
+ bytemuck::cast::<u32, i32>(self.storage[0]),
+ bytemuck::cast::<u32, i32>(self.storage[1]),
+ bytemuck::cast::<u32, i32>(self.storage[2]),
+ bytemuck::cast::<u32, i32>(self.storage[3]),
+ ],
+ ScalarType::Uint => [
+ self.storage[0] as i32,
+ self.storage[1] as i32,
+ self.storage[2] as i32,
+ self.storage[3] as i32,
+ ],
+ }
+ }
+
+ fn cast_u32(&self) -> [u32; 4] {
+ match self.elem_type() {
+ ScalarType::Bool => {
+ let ft = [0, 1];
+ [
+ ft[(self.storage[0] != 0) as usize],
+ ft[(self.storage[1] != 0) as usize],
+ ft[(self.storage[2] != 0) as usize],
+ ft[(self.storage[3] != 0) as usize],
+ ]
+ }
+ ScalarType::Float => [
+ bytemuck::cast::<u32, f32>(self.storage[0]) as u32,
+ bytemuck::cast::<u32, f32>(self.storage[1]) as u32,
+ bytemuck::cast::<u32, f32>(self.storage[2]) as u32,
+ bytemuck::cast::<u32, f32>(self.storage[3]) as u32,
+ ],
+ ScalarType::Int => [
+ bytemuck::cast::<u32, i32>(self.storage[0]) as u32,
+ bytemuck::cast::<u32, i32>(self.storage[1]) as u32,
+ bytemuck::cast::<u32, i32>(self.storage[2]) as u32,
+ bytemuck::cast::<u32, i32>(self.storage[3]) as u32,
+ ],
+ ScalarType::Uint => self.storage,
+ }
+ }
+
+ // fn binary_op(&self, other: &Self, op: BinaryOperator) -> Self {
+ // let count = self.vector_type.count();
+ // let mut v = *self;
+ // // component-wise op
+ // for i in 0..count {
+ // v.value_mut(i).binary_op(&other.value(i), op);
+ // }
+ // v
+ // }
+}
+
+impl PartialEq for VectorValue {
+ fn eq(&self, other: &Self) -> bool {
+ if self.vector_type() != other.vector_type() {
+ return false;
+ }
+ let count = self.vector_type().count();
+ match self.elem_type() {
+ ScalarType::Float => {
+ let s = self.cast_f32();
+ let o = other.cast_f32();
+ s[..count] == o[..count]
+ }
+ _ => self.storage[..count] == other.storage[..count],
+ }
+ }
+}
+
+impl Eq for VectorValue {}
+
+impl std::hash::Hash for VectorValue {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.vector_type.hash(state);
+ // Only compare the subset of storage actually in use
+ let count = self.vector_type.count();
+ let elem_type = self.elem_type();
+ if elem_type == ScalarType::Float {
+ for i in 0..count {
+ FloatOrd(self.get::<f32>(i)).hash(state);
+ }
+ } else {
+ self.storage[..count].hash(state);
+ }
+ }
+}
+
+impl ToWgslString for VectorValue {
+ fn to_wgsl_string(&self) -> String {
+ let mut vals = format!(
+ "{}({},{}",
+ self.vector_type().to_wgsl_string(),
+ self.value_n::<0>().to_wgsl_string(),
+ self.value_n::<1>().to_wgsl_string()
+ );
+ let count = self.vector_type.count();
+ if count > 2 {
+ vals.push(',');
+ vals.push_str(&self.value_n::<2>().to_wgsl_string());
+ if count > 3 {
+ vals.push(',');
+ vals.push_str(&self.value_n::<3>().to_wgsl_string());
+ }
+ }
+ vals.push(')');
+ vals
+ }
+}
+
+impl From<BVec2> for VectorValue {
+ fn from(value: BVec2) -> Self {
+ Self {
+ vector_type: VectorType::new(ScalarType::Bool, 2),
+ storage: [
+ ScalarValue::BOOL_STORAGE[value.x as usize],
+ ScalarValue::BOOL_STORAGE[value.y as usize],
+ 0,
+ 0,
+ ],
+ }
+ }
+}
+
+impl From<BVec3> for VectorValue {
+ fn from(value: BVec3) -> Self {
+ Self {
+ vector_type: VectorType::new(ScalarType::Bool, 3),
+ storage: [
+ ScalarValue::BOOL_STORAGE[value.x as usize],
+ ScalarValue::BOOL_STORAGE[value.y as usize],
+ ScalarValue::BOOL_STORAGE[value.z as usize],
+ 0,
+ ],
+ }
+ }
+}
+
+impl From<BVec4> for VectorValue {
+ fn from(value: BVec4) -> Self {
+ Self {
+ vector_type: VectorType::new(ScalarType::Bool, 4),
+ storage: [
+ ScalarValue::BOOL_STORAGE[value.x as usize],
+ ScalarValue::BOOL_STORAGE[value.y as usize],
+ ScalarValue::BOOL_STORAGE[value.z as usize],
+ ScalarValue::BOOL_STORAGE[value.w as usize],
+ ],
+ }
+ }
+}
+
+impl From<IVec2> for VectorValue {
+ fn from(value: IVec2) -> Self {
+ let mut s = Self {
+ vector_type: VectorType::VEC2I,
+ storage: [0u32; 4],
+ };
+ let v = bytemuck::cast_slice_mut::<u32, i32>(&mut s.storage);
+ value.write_to_slice(v);
+ s
+ }
+}
+
+impl From<IVec3> for VectorValue {
+ fn from(value: IVec3) -> Self {
+ let mut s = Self {
+ vector_type: VectorType::VEC3I,
+ storage: [0u32; 4],
+ };
+ let v = bytemuck::cast_slice_mut::<u32, i32>(&mut s.storage);
+ value.write_to_slice(v);
+ s
+ }
+}
+
+impl From<IVec4> for VectorValue {
+ fn from(value: IVec4) -> Self {
+ let mut s = Self {
+ vector_type: VectorType::VEC4I,
+ storage: [0u32; 4],
+ };
+ let v = bytemuck::cast_slice_mut::<u32, i32>(&mut s.storage);
+ value.write_to_slice(v);
+ s
+ }
+}
+
+impl From<UVec2> for VectorValue {
+ fn from(value: UVec2) -> Self {
+ let mut s = Self {
+ vector_type: VectorType::VEC2U,
+ storage: [0u32; 4],
+ };
+ let v = &mut s.storage;
+ value.write_to_slice(v);
+ s
+ }
+}
+
+impl From<UVec3> for VectorValue {
+ fn from(value: UVec3) -> Self {
+ let mut s = Self {
+ vector_type: VectorType::VEC3U,
+ storage: [0u32; 4],
+ };
+ let v = &mut s.storage;
+ value.write_to_slice(v);
+ s
+ }
+}
+
+impl From<UVec4> for VectorValue {
+ fn from(value: UVec4) -> Self {
+ let mut s = Self {
+ vector_type: VectorType::VEC4U,
+ storage: [0u32; 4],
+ };
+ let v = &mut s.storage;
+ value.write_to_slice(v);
+ s
+ }
+}
+
+impl From<Vec2> for VectorValue {
+ fn from(value: Vec2) -> Self {
+ let mut s = Self {
+ vector_type: VectorType::VEC2F,
+ storage: [0u32; 4],
+ };
+ let v = bytemuck::cast_slice_mut::<u32, f32>(&mut s.storage);
+ value.write_to_slice(v);
+ s
+ }
+}
+
+impl From<Vec3> for VectorValue {
+ fn from(value: Vec3) -> Self {
+ let mut s = Self {
+ vector_type: VectorType::VEC3F,
+ storage: [0u32; 4],
+ };
+ let v = bytemuck::cast_slice_mut::<u32, f32>(&mut s.storage);
+ value.write_to_slice(v);
+ s
+ }
+}
+
+impl From<Vec3A> for VectorValue {
+ fn from(value: Vec3A) -> Self {
+ let mut s = Self {
+ vector_type: VectorType::VEC3F,
+ storage: [0u32; 4],
+ };
+ let v = bytemuck::cast_slice_mut::<u32, f32>(&mut s.storage);
+ value.write_to_slice(v);
+ s
+ }
+}
+
+impl From<Vec4> for VectorValue {
+ fn from(value: Vec4) -> Self {
+ let mut s = Self {
+ vector_type: VectorType::VEC4F,
+ storage: [0u32; 4],
+ };
+ let v = bytemuck::cast_slice_mut::<u32, f32>(&mut s.storage);
+ value.write_to_slice(v);
+ s
+ }
+}
+
+/// Helper used as placeholder instead of [`VectorValue`] for serialization.
+///
+/// This enables serializing [`VectorValue`] as a glam type enum, instead of the
+/// compressed binary runtime representation actually stored inside
+/// [`VectorValue`].
+#[derive(Serialize, Deserialize)]
+enum VectorValueEnum {
+ BVec2(BVec2),
+ BVec3(BVec3),
+ BVec4(BVec4),
+ IVec2(IVec2),
+ IVec3(IVec3),
+ IVec4(IVec4),
+ UVec2(UVec2),
+ UVec3(UVec3),
+ UVec4(UVec4),
+ Vec2(Vec2),
+ Vec3(Vec3),
+ Vec4(Vec4),
+}
+
+impl From<VectorValueEnum> for VectorValue {
+ fn from(value: VectorValueEnum) -> Self {
+ match value {
+ VectorValueEnum::BVec2(v) => VectorValue::new_bvec2(v),
+ VectorValueEnum::BVec3(v) => VectorValue::new_bvec3(v),
+ VectorValueEnum::BVec4(v) => VectorValue::new_bvec4(v),
+ VectorValueEnum::IVec2(v) => VectorValue::new_ivec2(v),
+ VectorValueEnum::IVec3(v) => VectorValue::new_ivec3(v),
+ VectorValueEnum::IVec4(v) => VectorValue::new_ivec4(v),
+ VectorValueEnum::UVec2(v) => VectorValue::new_uvec2(v),
+ VectorValueEnum::UVec3(v) => VectorValue::new_uvec3(v),
+ VectorValueEnum::UVec4(v) => VectorValue::new_uvec4(v),
+ VectorValueEnum::Vec2(v) => VectorValue::new_vec2(v),
+ VectorValueEnum::Vec3(v) => VectorValue::new_vec3(v),
+ VectorValueEnum::Vec4(v) => VectorValue::new_vec4(v),
+ }
+ }
+}
+
+impl From<VectorValue> for VectorValueEnum {
+ fn from(value: VectorValue) -> Self {
+ let count = value.vector_type.count();
+ match value.elem_type() {
+ ScalarType::Bool => {
+ if count == 2 {
+ VectorValueEnum::BVec2(value.as_bvec2())
+ } else if count == 3 {
+ VectorValueEnum::BVec3(value.as_bvec3())
+ } else {
+ VectorValueEnum::BVec4(value.as_bvec4())
+ }
+ }
+ ScalarType::Int => {
+ if count == 2 {
+ VectorValueEnum::IVec2(value.as_ivec2())
+ } else if count == 3 {
+ VectorValueEnum::IVec3(value.as_ivec3())
+ } else {
+ VectorValueEnum::IVec4(value.as_ivec4())
+ }
+ }
+ ScalarType::Uint => {
+ if count == 2 {
+ VectorValueEnum::UVec2(value.as_uvec2())
+ } else if count == 3 {
+ VectorValueEnum::UVec3(value.as_uvec3())
+ } else {
+ VectorValueEnum::UVec4(value.as_uvec4())
+ }
+ }
+ ScalarType::Float => {
+ if count == 2 {
+ VectorValueEnum::Vec2(value.as_vec2())
+ } else if count == 3 {
+ VectorValueEnum::Vec3(value.as_vec3())
+ } else {
+ VectorValueEnum::Vec4(value.as_vec4())
+ }
+ }
+ }
+ }
+}
+
+/// Floating-point matrix value.
+#[derive(Debug, Clone, Copy, Reflect, Serialize, Deserialize)]
+pub struct MatrixValue {
+ /// Matrix type.
+ matrix_type: MatrixType,
+ /// Raw storage for up to 16 values. Actual usage depends on matrix size.
+ /// Note that data is stored pre-aligned according to WGSL rules, so that we
+ /// can directly return a slice to it.
+ storage: [f32; 16],
+}
+
+impl MatrixValue {
+ /// Create a new CxR matrix value from raw data.
+ ///
+ /// The matrix can be of any dimension `2..=4`, with data. The `data` slice
+ /// needs to be of length `cols * rows` exactly.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let m = MatrixValue::new(3, 2, &[0., 1., 2., 1., 2., 3.]);
+ /// assert_eq!(m.matrix_type().cols(), 3);
+ /// assert_eq!(m.matrix_type().rows(), 2);
+ /// ```
+ ///
+ /// # Panics
+ ///
+ /// Panics if either `cols` or `rows` is not 2/3/4.
+ ///
+ /// Panics if `data.len() != cols * rows`.
+ pub fn new(cols: usize, rows: usize, data: &[f32]) -> Self {
+ assert!((2..=4).contains(&cols));
+ assert!((2..=4).contains(&rows));
+ assert_eq!(data.len(), cols * rows);
+ let mut s = Self {
+ matrix_type: MatrixType::new(cols as u8, rows as u8),
+ storage: [0.0; 16],
+ };
+ if rows != 3 {
+ // Easy; just copy, there's no padding
+ let num = cols * rows;
+ let dst = &mut s.storage[0..num];
+ dst.copy_from_slice(&data[0..num]);
+ } else {
+ // Need to pad each row vec3 -> vec4
+ for col in 0..cols {
+ let dst_offset = col * 4;
+ let dst = &mut s.storage[dst_offset..dst_offset + rows];
+ let src_offset = col * 3;
+ dst.copy_from_slice(&data[src_offset..src_offset + rows]);
+ }
+ }
+ s
+ }
+
+ /// Scalar type of the elements of the matrix.
+ ///
+ /// This always returns [`ScalarType::Float`]. This method is provided for
+ /// consistency.
+ pub const fn elem_type(&self) -> ScalarType {
+ ScalarType::Float
+ }
+
+ /// Matrix type.
+ pub fn matrix_type(&self) -> MatrixType {
+ self.matrix_type
+ }
+
+ /// Get the scalar value of the matrix element in the R-th row and C-th
+ /// column.
+ pub fn value_n<const R: usize, const C: usize>(&self) -> ScalarValue {
+ ScalarValue::Float(self.get_n::<R, C>())
+ }
+
+ /// Get the scalar value of a matrix element.
+ pub fn value(&self, row: usize, col: usize) -> ScalarValue {
+ ScalarValue::Float(self.get(row, col))
+ }
+
+ /// Get the scalar value of an element of the matrix.
+ pub fn value_mut(&mut self, row: usize, col: usize) -> &mut f32 {
+ self.get_mut(row, col)
+ }
+
+ /// Get the floating-point value of the matrix element in the R-th row and
+ /// C-th column.
+ pub fn get_n<const R: usize, const C: usize>(&self) -> f32 {
+ if R < self.matrix_type.rows() && C < self.matrix_type.cols() {
+ self.storage[self.matrix_type.rows() * C + R]
+ } else {
+ 0f32
+ }
+ }
+
+ /// Get the floating-point value of a matrix element.
+ pub fn get(&self, row: usize, col: usize) -> f32 {
+ if row < self.matrix_type.rows() && col < self.matrix_type.cols() {
+ self.storage[self.matrix_type.rows() * col + row]
+ } else {
+ 0f32
+ }
+ }
+
+ /// Get the value of an element of the matrix.
+ fn get_mut(&mut self, row: usize, col: usize) -> &mut f32 {
+ assert!(row < self.matrix_type.rows());
+ assert!(col < self.matrix_type.cols());
+ &mut self.storage[self.matrix_type.rows() * col + row]
+ }
+
+ /// Get the value as a binary blob ready for GPU upload.
+ ///
+ /// The slice has a size aligned with the requirements of WGSL, and can
+ /// contain gaps where no actual matrix data is stored. See
+ /// <https://gpuweb.github.io/gpuweb/wgsl/#alignment-and-size> for details.
+ pub fn as_bytes(&self) -> &[u8] {
+ // https://gpuweb.github.io/gpuweb/wgsl/#alignment-and-size
+ let count = self.matrix_type.cols() * self.matrix_type.align() / 4;
+ bytemuck::cast_slice::<f32, u8>(&self.storage[..count])
+ }
+
+ // fn binary_op(&self, other: &Self, op: BinaryOperator) -> Self {
+ // let mut m = *self;
+ // // component-wise op
+ // for j in 0..self.matrix_type.cols() {
+ // for i in 0..self.matrix_type.rows() {
+ // let dst = m.value_mut(i, j);
+ // let a = *dst;
+ // let b = other.get(i, j);
+ // *dst = op.apply_f32(a, b);
+ // }
+ // }
+ // m
+ // }
+}
+
+impl PartialEq for MatrixValue {
+ fn eq(&self, other: &Self) -> bool {
+ if self.matrix_type != other.matrix_type {
+ return false;
+ }
+ let count = self.matrix_type.rows() * self.matrix_type.cols();
+ self.storage[..count] == other.storage[..count]
+ }
+}
+
+impl std::hash::Hash for MatrixValue {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.matrix_type.hash(state);
+ let count = self.matrix_type.rows() * self.matrix_type.cols();
+ for i in 0..count {
+ FloatOrd(self.storage[i]).hash(state);
+ }
+ }
+}
+
+impl ToWgslString for MatrixValue {
+ fn to_wgsl_string(&self) -> String {
+ let mut vals = format!("{}(", self.matrix_type().to_wgsl_string(),);
+ for j in 0..self.matrix_type.cols() {
+ for i in 0..self.matrix_type.rows() {
+ vals.push_str(&self.value(i, j).to_wgsl_string());
+ vals.push(',');
+ }
+ }
+ vals.pop(); // Remove the last comma
+ vals.push(')');
+ vals
+ }
+}
+
+impl From<Mat2> for MatrixValue {
+ fn from(value: Mat2) -> Self {
+ let mut s = Self {
+ matrix_type: MatrixType::MAT2X2F,
+ storage: [0.; 16],
+ };
+ value.write_cols_to_slice(&mut s.storage);
+ s
+ }
+}
+
+impl From<Mat3> for MatrixValue {
+ fn from(value: Mat3) -> Self {
+ let mut s = Self {
+ matrix_type: MatrixType::MAT3X3F,
+ storage: [0.; 16],
+ };
+ value.write_cols_to_slice(&mut s.storage);
+ s
+ }
+}
+
+impl From<Mat4> for MatrixValue {
+ fn from(value: Mat4) -> Self {
+ let mut s = Self {
+ matrix_type: MatrixType::MAT4X4F,
+ storage: [0.; 16],
+ };
+ value.write_cols_to_slice(&mut s.storage);
+ s
+ }
+}
+
+/// Variant storage for a simple value.
+///
+/// The variant can store a scalar, vector, or matrix value.
+#[derive(Debug, Clone, Copy, PartialEq, Hash, Reflect, Serialize, Deserialize)]
+#[non_exhaustive]
+pub enum Value {
+ /// Scalar value.
+ Scalar(ScalarValue),
+ /// Vector value with 2 to 4 components.
+ ///
+ /// Note that 1-component vectors are invalid; [`Value::Scalar`] must be
+ /// used instead. Similarly, vectors with more than 4 components are
+ /// invalid.
+ Vector(VectorValue),
+ /// Floating-point matrix value of size 2x2 to 4x4.
+ ///
+ /// Note that single-row or single-column matrices are invalid;
+ /// [`Value::Vector`] must be used instead, or [`Value::Scalar`] for a
+ /// 1x1 "matrix". Similarly, matrices with more than 4 rows or columns are
+ /// invalid.
+ Matrix(MatrixValue),
+}
+
+impl Value {
+ /// Get the value as a binary blob ready for GPU upload.
+ pub fn as_bytes(&self) -> &[u8] {
+ match self {
+ Value::Scalar(s) => s.as_bytes(),
+ Value::Vector(v) => v.as_bytes(),
+ Value::Matrix(m) => m.as_bytes(),
+ }
+ }
+
+ /// Get the type of the value.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let value = graph::Value::Scalar(3_f32.into());
+ /// assert_eq!(ValueType::Scalar(ScalarType::Float), value.value_type());
+ /// ```
+ pub fn value_type(&self) -> ValueType {
+ match self {
+ Value::Scalar(s) => ValueType::Scalar(s.scalar_type()),
+ Value::Vector(v) => ValueType::Vector(v.vector_type()),
+ Value::Matrix(m) => ValueType::Matrix(m.matrix_type()),
+ }
+ }
+
+ /// Cast this value to a [`ScalarValue`].
+ ///
+ /// # Panics
+ ///
+ /// Panics if this value is not a [`ScalarValue`].
+ pub fn as_scalar(&self) -> &ScalarValue {
+ match self {
+ Value::Scalar(s) => s,
+ _ => panic!("Cannot cast from {:?} to ScalarType.", self.value_type()),
+ }
+ }
+
+ /// Cast this value to a [`VectorValue`].
+ ///
+ /// # Panics
+ ///
+ /// Panics if this value is not a [`VectorValue`].
+ pub fn as_vector(&self) -> &VectorValue {
+ match self {
+ Value::Vector(v) => v,
+ _ => panic!("Cannot cast from {:?} to VectorType.", self.value_type()),
+ }
+ }
+
+ /// Cast this value to a [`MatrixValue`].
+ ///
+ /// # Panics
+ ///
+ /// Panics if this value is not a [`MatrixValue`].
+ pub fn as_matrix(&self) -> &MatrixValue {
+ match self {
+ Value::Matrix(m) => m,
+ _ => panic!("Cannot cast from {:?} to MatrixType.", self.value_type()),
+ }
+ }
+
+ // /// Apply a binary arithmetic operator between self and another operand.
+ // pub fn binary_op(&self, other: &Value, op: BinaryOperator) -> Value {
+ // match self {
+ // Value::Scalar(s) => Value::Scalar(s.binary_op(other.as_scalar(),
+ // op)), Value::Vector(v) =>
+ // Value::Vector(v.binary_op(other.as_vector(), op)),
+ // Value::Matrix(m) => Value::Matrix(m.binary_op(other.as_matrix(),
+ // op)), }
+ // }
+}
+
+impl ToWgslString for Value {
+ fn to_wgsl_string(&self) -> String {
+ match self {
+ Value::Scalar(s) => s.to_wgsl_string(),
+ Value::Vector(v) => v.to_wgsl_string(),
+ Value::Matrix(m) => m.to_wgsl_string(),
+ }
+ }
+}
+
+impl From<ScalarValue> for Value {
+ fn from(value: ScalarValue) -> Self {
+ Self::Scalar(value)
+ }
+}
+
+impl From<VectorValue> for Value {
+ fn from(value: VectorValue) -> Self {
+ Self::Vector(value)
+ }
+}
+
+impl From<MatrixValue> for Value {
+ fn from(value: MatrixValue) -> Self {
+ Self::Matrix(value)
+ }
+}
+
+macro_rules! impl_scalar_value {
+ ($t:ty, $sv:ident) => {
+ impl From<$t> for Value {
+ fn from(value: $t) -> Self {
+ Self::Scalar(value.into())
+ }
+ }
+
+ impl TryInto<$t> for ScalarValue {
+ type Error = ExprError;
+
+ fn try_into(self) -> Result<$t, Self::Error> {
+ match self {
+ ScalarValue::$sv(b) => Ok(b),
+ _ => Err(ExprError::TypeError(format!(
+ "Expected {:?} type, found {:?} instead.",
+ ScalarType::$sv,
+ self.scalar_type()
+ ))),
+ }
+ }
+ }
+
+ impl TryInto<$t> for Value {
+ type Error = ExprError;
+
+ fn try_into(self) -> Result<$t, Self::Error> {
+ match self {
+ Value::Scalar(s) => s.try_into(),
+ _ => Err(ExprError::TypeError(format!(
+ "Expected ValueType::Scalar type, found {:?} instead.",
+ self.value_type()
+ ))),
+ }
+ }
+ }
+ };
+}
+
+impl_scalar_value!(bool, Bool);
+impl_scalar_value!(f32, Float);
+impl_scalar_value!(i32, Int);
+impl_scalar_value!(u32, Uint);
+
+macro_rules! impl_vec_value {
+ ($t:ty, $vt:ident, $cast:tt) => {
+ impl From<$t> for Value {
+ fn from(value: $t) -> Self {
+ Self::Vector(value.into())
+ }
+ }
+
+ impl TryInto<$t> for VectorValue {
+ type Error = ExprError;
+
+ fn try_into(self) -> Result<$t, Self::Error> {
+ if self.vector_type() == VectorType::$vt {
+ Ok(self.$cast())
+ } else {
+ Err(ExprError::TypeError(format!(
+ "Expected {:?} type, found {:?} instead.",
+ VectorType::$vt,
+ self.vector_type()
+ )))
+ }
+ }
+ }
+
+ impl TryInto<$t> for Value {
+ type Error = ExprError;
+
+ fn try_into(self) -> Result<$t, Self::Error> {
+ match self {
+ Value::Vector(v) => v.try_into(),
+ _ => Err(ExprError::TypeError(format!(
+ "Expected ValueType::Scalar type, found {:?} instead.",
+ self.value_type()
+ ))),
+ }
+ }
+ }
+ };
+}
+
+impl_vec_value!(BVec2, VEC2B, as_bvec2);
+impl_vec_value!(BVec3, VEC3B, as_bvec3);
+impl_vec_value!(BVec4, VEC4B, as_bvec4);
+impl_vec_value!(Vec2, VEC2F, as_vec2);
+impl_vec_value!(Vec3, VEC3F, as_vec3);
+impl_vec_value!(Vec3A, VEC3F, as_vec3a);
+impl_vec_value!(Vec4, VEC4F, as_vec4);
+impl_vec_value!(IVec2, VEC2I, as_ivec2);
+impl_vec_value!(IVec3, VEC3I, as_ivec3);
+impl_vec_value!(IVec4, VEC4I, as_ivec4);
+impl_vec_value!(UVec2, VEC2U, as_uvec2);
+impl_vec_value!(UVec3, VEC3U, as_uvec3);
+impl_vec_value!(UVec4, VEC4U, as_uvec4);
+
+#[cfg(test)]
+mod tests {
+ use std::{
+ collections::hash_map::DefaultHasher,
+ hash::{Hash, Hasher},
+ };
+
+ use super::*;
+
+ #[test]
+ fn as_bytes() {
+ // let v = Value::Scalar(true.into());
+ // let b = v.as_bytes();
+ // assert_eq!(b, &[0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8]);
+
+ let v = Value::Scalar(3f32.into());
+ let b = v.as_bytes();
+ assert_eq!(b, &[0u8, 0u8, 0x40u8, 0x40u8]); // 0x40400000
+
+ let v = Value::Scalar(0x12FF89ACu32.into());
+ let b = v.as_bytes();
+ assert_eq!(b, &[0xACu8, 0x89u8, 0xFFu8, 0x12u8]);
+
+ let v = Value::Scalar(0x12FF89ACi32.into());
+ let b = v.as_bytes();
+ assert_eq!(b, &[0xACu8, 0x89u8, 0xFFu8, 0x12u8]);
+
+ let v = Value::Vector(Vec2::new(-2., 3.).into());
+ let b = v.as_bytes();
+ assert_eq!(b, &[0u8, 0u8, 0u8, 0xC0u8, 0u8, 0u8, 0x40u8, 0x40u8]); // 0xc0000000 0x40400000
+
+ let v = Value::Vector(Vec3::new(-2., 3., 4.).into());
+ let b = v.as_bytes();
+ assert_eq!(
+ b,
+ &[0u8, 0u8, 0u8, 0xC0u8, 0u8, 0u8, 0x40u8, 0x40u8, 0u8, 0u8, 0x80u8, 0x40u8]
+ ); // 0xc0000000 0x40400000 0x40800000
+
+ let v = Value::Vector(Vec4::new(-2., 3., 4., -5.).into());
+ let b = v.as_bytes();
+ assert_eq!(
+ b,
+ &[
+ 0u8, 0u8, 0u8, 0xC0u8, 0u8, 0u8, 0x40u8, 0x40u8, 0u8, 0u8, 0x80u8, 0x40u8, 0u8,
+ 0u8, 0xa0u8, 0xc0u8
+ ]
+ ); // 0xc0000000 0x40400000 0x40800000 0xc0a00000
+
+ let v = Value::Matrix(Mat2::IDENTITY.into());
+ let b = v.as_bytes();
+ assert_eq!(b.len(), v.value_type().align() * 2);
+ assert_eq!(b.len(), 16);
+ let v = Value::Matrix(Mat3::IDENTITY.into());
+ let b = v.as_bytes();
+ assert_eq!(b.len(), v.value_type().align() * 3);
+ assert_eq!(b.len(), 48); // sizeof(vec4) * 3
+ let v = Value::Matrix(Mat4::IDENTITY.into());
+ let b = v.as_bytes();
+ assert_eq!(b.len(), v.value_type().align() * 4);
+ assert_eq!(b.len(), 64);
+
+ // https://gpuweb.github.io/gpuweb/wgsl/#alignment-and-size
+ assert_eq!(ScalarValue::Float(0.0).as_bytes().len(), 4);
+ assert_eq!(ScalarValue::Float(0.0).scalar_type().size(), 4);
+ assert_eq!(ScalarValue::Float(0.0).scalar_type().align(), 4);
+ assert_eq!(ScalarValue::Int(0).as_bytes().len(), 4);
+ assert_eq!(ScalarValue::Int(0).scalar_type().size(), 4);
+ assert_eq!(ScalarValue::Int(0).scalar_type().align(), 4);
+ assert_eq!(ScalarValue::Uint(0).as_bytes().len(), 4);
+ assert_eq!(ScalarValue::Uint(0).scalar_type().size(), 4);
+ assert_eq!(ScalarValue::Uint(0).scalar_type().align(), 4);
+ assert_eq!(VectorValue::new_vec2(Vec2::ZERO).as_bytes().len(), 8);
+ assert_eq!(VectorValue::new_vec2(Vec2::ZERO).vector_type().size(), 8);
+ assert_eq!(VectorValue::new_vec2(Vec2::ZERO).vector_type().align(), 8);
+ assert_eq!(VectorValue::new_vec3(Vec3::ZERO).as_bytes().len(), 12);
+ assert_eq!(VectorValue::new_vec3(Vec3::ZERO).vector_type().size(), 12);
+ assert_eq!(VectorValue::new_vec3(Vec3::ZERO).vector_type().align(), 16); // padding!
+ assert_eq!(VectorValue::new_vec4(Vec4::ZERO).as_bytes().len(), 16);
+ assert_eq!(VectorValue::new_vec4(Vec4::ZERO).vector_type().size(), 16);
+ assert_eq!(VectorValue::new_vec4(Vec4::ZERO).vector_type().align(), 16);
+ assert_eq!(VectorValue::new_ivec2(IVec2::ZERO).as_bytes().len(), 8);
+ assert_eq!(VectorValue::new_ivec2(IVec2::ZERO).vector_type().size(), 8);
+ assert_eq!(VectorValue::new_ivec2(IVec2::ZERO).vector_type().align(), 8);
+ assert_eq!(VectorValue::new_ivec3(IVec3::ZERO).as_bytes().len(), 12);
+ assert_eq!(VectorValue::new_ivec3(IVec3::ZERO).vector_type().size(), 12);
+ assert_eq!(
+ VectorValue::new_ivec3(IVec3::ZERO).vector_type().align(),
+ 16
+ ); // padding!
+ assert_eq!(VectorValue::new_ivec4(IVec4::ZERO).as_bytes().len(), 16);
+ assert_eq!(VectorValue::new_ivec4(IVec4::ZERO).vector_type().size(), 16);
+ assert_eq!(
+ VectorValue::new_ivec4(IVec4::ZERO).vector_type().align(),
+ 16
+ );
+ assert_eq!(VectorValue::new_uvec2(UVec2::ZERO).as_bytes().len(), 8);
+ assert_eq!(VectorValue::new_uvec2(UVec2::ZERO).vector_type().size(), 8);
+ assert_eq!(VectorValue::new_uvec2(UVec2::ZERO).vector_type().align(), 8);
+ assert_eq!(VectorValue::new_uvec3(UVec3::ZERO).as_bytes().len(), 12);
+ assert_eq!(VectorValue::new_uvec3(UVec3::ZERO).vector_type().size(), 12);
+ assert_eq!(
+ VectorValue::new_uvec3(UVec3::ZERO).vector_type().align(),
+ 16
+ ); // padding!
+ assert_eq!(VectorValue::new_uvec4(UVec4::ZERO).as_bytes().len(), 16);
+ assert_eq!(VectorValue::new_uvec4(UVec4::ZERO).vector_type().size(), 16);
+ assert_eq!(
+ VectorValue::new_uvec4(UVec4::ZERO).vector_type().align(),
+ 16
+ );
+ assert_eq!(ScalarValue::Int(0).as_bytes().len(), 4);
+ assert_eq!(ScalarValue::Uint(0).as_bytes().len(), 4);
+ assert_eq!(MatrixValue::new(2, 2, &[0.0; 4]).as_bytes().len(), 16);
+ assert_eq!(MatrixValue::new(3, 2, &[0.0; 6]).as_bytes().len(), 24);
+ assert_eq!(MatrixValue::new(4, 2, &[0.0; 8]).as_bytes().len(), 32);
+ assert_eq!(MatrixValue::new(2, 3, &[0.0; 6]).as_bytes().len(), 32); // padding!
+ assert_eq!(MatrixValue::new(3, 3, &[0.0; 9]).as_bytes().len(), 48); // padding!
+ assert_eq!(MatrixValue::new(4, 3, &[0.0; 12]).as_bytes().len(), 64); // padding!
+ assert_eq!(MatrixValue::new(2, 4, &[0.0; 8]).as_bytes().len(), 32);
+ assert_eq!(MatrixValue::new(3, 4, &[0.0; 12]).as_bytes().len(), 48);
+ assert_eq!(MatrixValue::new(4, 4, &[0.0; 16]).as_bytes().len(), 64);
+
+ // MatrixValue
+ let f: [f32; 16] = [
+ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15.,
+ ];
+ let expected24: &[u8] = bytemuck::cast_slice(&f[..]);
+ // R=3 requires extra padding to AlignOf(vec4) = 16
+ let expected3: &[f32] = &[
+ 0., 1., 2., 0., 3., 4., 5., 0., 6., 7., 8., 0., 9., 10., 11., 0.,
+ ];
+ let expected3: &[u8] = bytemuck::cast_slice(expected3);
+ for j in 2..=4 {
+ for i in 2..=4 {
+ let v = MatrixValue::new(i, j, &f[..i * j]);
+ assert_eq!(v.matrix_type().cols(), i);
+ assert_eq!(v.matrix_type().rows(), j);
+
+ let b = v.as_bytes();
+ assert_eq!(b.len(), v.matrix_type().align() * i);
+ if j != 3 {
+ assert_eq!(b, &expected24[..b.len()], "(i={},j={})", i, j);
+ } else {
+ assert_eq!(b, &expected3[..b.len()], "(i={},j={})", i, j);
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn value_type() {
+ assert_eq!(
+ Value::Scalar(true.into()).value_type(),
+ ValueType::Scalar(ScalarType::Bool)
+ );
+ assert_eq!(
+ Value::Scalar(0f32.into()).value_type(),
+ ValueType::Scalar(ScalarType::Float)
+ );
+ assert_eq!(
+ Value::Scalar(0i32.into()).value_type(),
+ ValueType::Scalar(ScalarType::Int)
+ );
+ assert_eq!(
+ Value::Scalar(0u32.into()).value_type(),
+ ValueType::Scalar(ScalarType::Uint)
+ );
+ assert_eq!(
+ Value::Vector(Vec2::ZERO.into()).value_type(),
+ ValueType::Vector(VectorType::VEC2F)
+ );
+ assert_eq!(
+ Value::Vector(Vec3::ZERO.into()).value_type(),
+ ValueType::Vector(VectorType::VEC3F)
+ );
+ assert_eq!(
+ Value::Vector(Vec4::ZERO.into()).value_type(),
+ ValueType::Vector(VectorType::VEC4F)
+ );
+ assert_eq!(
+ Value::Vector(BVec2::TRUE.into()).value_type(),
+ ValueType::Vector(VectorType::VEC2B)
+ );
+ assert_eq!(
+ Value::Vector(BVec3::TRUE.into()).value_type(),
+ ValueType::Vector(VectorType::VEC3B)
+ );
+ assert_eq!(
+ Value::Vector(BVec4::TRUE.into()).value_type(),
+ ValueType::Vector(VectorType::VEC4B)
+ );
+ assert_eq!(
+ Value::Matrix(Mat2::IDENTITY.into()).value_type(),
+ ValueType::Matrix(MatrixType::MAT2X2F)
+ );
+ assert_eq!(
+ Value::Matrix(Mat3::IDENTITY.into()).value_type(),
+ ValueType::Matrix(MatrixType::MAT3X3F)
+ );
+ assert_eq!(
+ Value::Matrix(Mat4::IDENTITY.into()).value_type(),
+ ValueType::Matrix(MatrixType::MAT4X4F)
+ );
+ }
+
+ #[test]
+ fn to_wgsl_string() {
+ for b in [true, false] {
+ assert_eq!(Value::Scalar(b.into()).to_wgsl_string(), b.to_wgsl_string());
+ }
+ for f in [0_f32, -1., 1., 1e-5] {
+ assert_eq!(Value::Scalar(f.into()).to_wgsl_string(), f.to_wgsl_string());
+ }
+ for u in [0_u32, 1, 42, 999999] {
+ assert_eq!(Value::Scalar(u.into()).to_wgsl_string(), u.to_wgsl_string());
+ }
+ for i in [0_i32, -1, 1, -42, 42, -100000, 100000] {
+ assert_eq!(Value::Scalar(i.into()).to_wgsl_string(), i.to_wgsl_string());
+ }
+ for v in [
+ Vec2::ZERO,
+ Vec2::ONE,
+ Vec2::NEG_ONE,
+ Vec2::X,
+ Vec2::Y,
+ Vec2::NEG_X,
+ Vec2::NEG_Y,
+ Vec2::new(-42.578, 663.449),
+ ] {
+ assert_eq!(Value::Vector(v.into()).to_wgsl_string(), v.to_wgsl_string());
+ }
+ for v in [
+ Vec3::ZERO,
+ Vec3::ONE,
+ Vec3::NEG_ONE,
+ Vec3::X,
+ Vec3::Y,
+ Vec3::Z,
+ Vec3::NEG_X,
+ Vec3::NEG_Y,
+ Vec3::NEG_Z,
+ Vec3::new(-42.578, 663.449, -42558.35),
+ ] {
+ assert_eq!(Value::Vector(v.into()).to_wgsl_string(), v.to_wgsl_string());
+ }
+ for v in [
+ Vec4::ZERO,
+ Vec4::ONE,
+ Vec4::NEG_ONE,
+ Vec4::X,
+ Vec4::Y,
+ Vec4::Z,
+ Vec4::NEG_X,
+ Vec4::NEG_Y,
+ Vec4::NEG_Z,
+ Vec4::new(-42.578, 663.449, -42558.35, -4.2),
+ ] {
+ assert_eq!(Value::Vector(v.into()).to_wgsl_string(), v.to_wgsl_string());
+ }
+
+ for (m, expected) in [
+ (Mat3::IDENTITY, "mat3x3<f32>(1.,0.,0.,0.,1.,0.,0.,0.,1.)"),
+ (Mat3::ZERO, "mat3x3<f32>(0.,0.,0.,0.,0.,0.,0.,0.,0.)"),
+ (
+ Mat3::from_cols(
+ Vec3::new(1., 2., 3.),
+ Vec3::new(4., 5., 6.),
+ Vec3::new(7., 8., 9.),
+ ),
+ "mat3x3<f32>(1.,2.,3.,4.,5.,6.,7.,8.,9.)",
+ ),
+ ] {
+ assert_eq!(
+ Value::Matrix(m.into()).to_wgsl_string(),
+ expected.to_string()
+ );
+ }
+ }
+
+ #[test]
+ fn vector_value() {
+ let v = BVec2::new(false, true);
+ let vv = VectorValue::new_bvec2(v);
+ assert_eq!(ScalarValue::BOOL_FALSE_STORAGE, vv.storage[0]);
+ assert_eq!(ScalarValue::BOOL_TRUE_STORAGE, vv.storage[1]);
+ assert_eq!(0u32, vv.storage[2]);
+ assert_eq!(0u32, vv.storage[3]);
+
+ let v = BVec3::new(false, true, false);
+ let vv = VectorValue::new_bvec3(v);
+ assert_eq!(ScalarValue::BOOL_FALSE_STORAGE, vv.storage[0]);
+ assert_eq!(ScalarValue::BOOL_TRUE_STORAGE, vv.storage[1]);
+ assert_eq!(ScalarValue::BOOL_FALSE_STORAGE, vv.storage[2]);
+ assert_eq!(0u32, vv.storage[3]);
+
+ let v = BVec4::new(false, true, false, true);
+ let vv = VectorValue::new_bvec4(v);
+ assert_eq!(ScalarValue::BOOL_FALSE_STORAGE, vv.storage[0]);
+ assert_eq!(ScalarValue::BOOL_TRUE_STORAGE, vv.storage[1]);
+ assert_eq!(ScalarValue::BOOL_FALSE_STORAGE, vv.storage[2]);
+ assert_eq!(ScalarValue::BOOL_TRUE_STORAGE, vv.storage[3]);
+
+ let v = Vec2::new(-3.2, 5.);
+ let vv = VectorValue::new_vec2(v);
+ assert_eq!(v.x.to_bits(), vv.storage[0]);
+ assert_eq!(v.y.to_bits(), vv.storage[1]);
+ assert_eq!(0u32, vv.storage[2]);
+ assert_eq!(0u32, vv.storage[3]);
+
+ let v = Vec3::new(-3.2, 5., 64.5);
+ let vv = VectorValue::new_vec3(v);
+ assert_eq!(v.x.to_bits(), vv.storage[0]);
+ assert_eq!(v.y.to_bits(), vv.storage[1]);
+ assert_eq!(v.z.to_bits(), vv.storage[2]);
+ assert_eq!(0u32, vv.storage[3]);
+
+ let v = Vec4::new(-3.2, 5., 64.5, -42.);
+ let vv = VectorValue::new_vec4(v);
+ assert_eq!(v.x.to_bits(), vv.storage[0]);
+ assert_eq!(v.y.to_bits(), vv.storage[1]);
+ assert_eq!(v.z.to_bits(), vv.storage[2]);
+ assert_eq!(v.w.to_bits(), vv.storage[3]);
+
+ #[allow(unsafe_code)]
+ {
+ let v = IVec2::new(-3, 5);
+ let vv = VectorValue::new_ivec2(v);
+ assert_eq!(v.x as u32, vv.storage[0]);
+ assert_eq!(v.y as u32, vv.storage[1]);
+ assert_eq!(0u32, vv.storage[2]);
+ assert_eq!(0u32, vv.storage[3]);
+
+ let v = IVec3::new(-3, 5, 64);
+ let vv = VectorValue::new_ivec3(v);
+ assert_eq!(v.x as u32, vv.storage[0]);
+ assert_eq!(v.y as u32, vv.storage[1]);
+ assert_eq!(v.z as u32, vv.storage[2]);
+ assert_eq!(0u32, vv.storage[3]);
+
+ let v = IVec4::new(-3, 5, 64, -42);
+ let vv = VectorValue::new_ivec4(v);
+ assert_eq!(v.x as u32, vv.storage[0]);
+ assert_eq!(v.y as u32, vv.storage[1]);
+ assert_eq!(v.z as u32, vv.storage[2]);
+ assert_eq!(v.w as u32, vv.storage[3]);
+ }
+
+ let v = UVec2::new(3, 5);
+ let vv = VectorValue::new_uvec2(v);
+ assert_eq!(v.x, vv.storage[0]);
+ assert_eq!(v.y, vv.storage[1]);
+ assert_eq!(0u32, vv.storage[2]);
+ assert_eq!(0u32, vv.storage[3]);
+
+ let v = UVec3::new(3, 5, 64);
+ let vv = VectorValue::new_uvec3(v);
+ assert_eq!(v.x, vv.storage[0]);
+ assert_eq!(v.y, vv.storage[1]);
+ assert_eq!(v.z, vv.storage[2]);
+ assert_eq!(0u32, vv.storage[3]);
+
+ let v = UVec4::new(3, 5, 64, 42);
+ let vv = VectorValue::new_uvec4(v);
+ assert_eq!(v.x, vv.storage[0]);
+ assert_eq!(v.y, vv.storage[1]);
+ assert_eq!(v.z, vv.storage[2]);
+ assert_eq!(v.w, vv.storage[3]);
+ }
+
+ #[test]
+ fn from() {
+ assert_eq!(Value::Scalar(ScalarValue::Bool(true)), true.into());
+ assert_eq!(Value::Scalar(ScalarValue::Float(0.)), 0_f32.into());
+ assert_eq!(Value::Scalar(ScalarValue::Int(-42)), (-42_i32).into());
+ assert_eq!(Value::Scalar(ScalarValue::Uint(0)), 0_u32.into());
+
+ let v = BVec2::new(false, true);
+ let vv: VectorValue = v.into();
+ assert_eq!(vv, VectorValue::new_bvec2(v));
+ assert_eq!(ScalarValue::BOOL_FALSE_STORAGE, vv.storage[0]);
+ assert_eq!(ScalarValue::BOOL_TRUE_STORAGE, vv.storage[1]);
+ assert_eq!(0, vv.storage[2]);
+ assert_eq!(0, vv.storage[3]);
+
+ let v = BVec3::new(false, true, false);
+ let vv: VectorValue = v.into();
+ assert_eq!(vv, VectorValue::new_bvec3(v));
+ assert_eq!(ScalarValue::BOOL_FALSE_STORAGE, vv.storage[0]);
+ assert_eq!(ScalarValue::BOOL_TRUE_STORAGE, vv.storage[1]);
+ assert_eq!(ScalarValue::BOOL_FALSE_STORAGE, vv.storage[2]);
+ assert_eq!(0, vv.storage[3]);
+
+ let v = BVec4::new(false, true, false, true);
+ let vv: VectorValue = v.into();
+ assert_eq!(vv, VectorValue::new_bvec4(v));
+ assert_eq!(ScalarValue::BOOL_FALSE_STORAGE, vv.storage[0]);
+ assert_eq!(ScalarValue::BOOL_TRUE_STORAGE, vv.storage[1]);
+ assert_eq!(ScalarValue::BOOL_FALSE_STORAGE, vv.storage[2]);
+ assert_eq!(ScalarValue::BOOL_TRUE_STORAGE, vv.storage[3]);
+
+ assert_eq!(
+ Value::Vector(VectorValue::new_vec2(Vec2::Y)),
+ Vec2::Y.into()
+ );
+ assert_eq!(
+ Value::Vector(VectorValue::new_vec3(Vec3::Z)),
+ Vec3::Z.into()
+ );
+ assert_eq!(
+ Value::Vector(VectorValue::new_vec4(Vec4::W)),
+ Vec4::W.into()
+ );
+
+ assert_eq!(
+ Value::Vector(VectorValue::new_ivec2(IVec2::Y)),
+ IVec2::Y.into()
+ );
+ assert_eq!(
+ Value::Vector(VectorValue::new_ivec3(IVec3::Z)),
+ IVec3::Z.into()
+ );
+ assert_eq!(
+ Value::Vector(VectorValue::new_ivec4(IVec4::W)),
+ IVec4::W.into()
+ );
+
+ assert_eq!(
+ Value::Vector(VectorValue::new_uvec2(UVec2::Y)),
+ UVec2::Y.into()
+ );
+ assert_eq!(
+ Value::Vector(VectorValue::new_uvec3(UVec3::Z)),
+ UVec3::Z.into()
+ );
+ assert_eq!(
+ Value::Vector(VectorValue::new_uvec4(UVec4::W)),
+ UVec4::W.into()
+ );
+ }
+
+ fn calc_hash<H: Hash>(value: &H) -> u64 {
+ let mut hasher = DefaultHasher::default();
+ value.hash(&mut hasher);
+ hasher.finish()
+ }
+
+ fn calc_f32_vector_hash(vector_type: VectorType, values: &[f32]) -> u64 {
+ let mut hasher = DefaultHasher::default();
+ vector_type.hash(&mut hasher);
+ for f in values {
+ FloatOrd(*f).hash(&mut hasher);
+ }
+ hasher.finish()
+ }
+
+ fn calc_i32_vector_hash(vector_type: VectorType, values: &[i32]) -> u64 {
+ let mut hasher = DefaultHasher::default();
+ vector_type.hash(&mut hasher);
+ let v = bytemuck::cast_slice::<i32, u32>(values);
+ let c = vector_type.count();
+ v[..c].hash(&mut hasher);
+ hasher.finish()
+ }
+
+ fn calc_u32_vector_hash(vector_type: VectorType, values: &[u32]) -> u64 {
+ let mut hasher = DefaultHasher::default();
+ vector_type.hash(&mut hasher);
+ let c = vector_type.count();
+ values[..c].hash(&mut hasher);
+ hasher.finish()
+ }
+
+ #[test]
+ fn hash() {
+ // Different types must not be equal
+ let zeros = [
+ Into::<ScalarValue>::into(false),
+ Into::<ScalarValue>::into(0_f32),
+ Into::<ScalarValue>::into(0_u32),
+ Into::<ScalarValue>::into(0_i32),
+ ];
+ let ones = [
+ Into::<ScalarValue>::into(true),
+ Into::<ScalarValue>::into(1_f32),
+ Into::<ScalarValue>::into(1_u32),
+ Into::<ScalarValue>::into(1_i32),
+ ];
+ for arr in [zeros, ones] {
+ for i in 0..=3 {
+ for j in 0..=3 {
+ if i == j {
+ // Equal to self
+ assert_eq!(arr[i], arr[j]);
+ assert_eq!(calc_hash(&arr[i]), calc_hash(&arr[j]));
+ } else {
+ // Different types must be different and hash to different values
+ assert_ne!(arr[i], arr[j]);
+ assert_ne!(calc_hash(&arr[i]), calc_hash(&arr[j]));
+ }
+ // With casting however, values can be equal
+ assert!(arr[i].cast_eq(&arr[j]));
+ }
+ }
+ }
+
+ // Different types must not be equal
+ let vecs = [
+ VectorValue::new_vec2(Vec2::new(1., 0.)),
+ VectorValue::new_ivec2(IVec2::new(1, 0)),
+ VectorValue::new_uvec2(UVec2::new(1, 0)),
+ VectorValue::new_bvec2(BVec2::new(true, false)),
+ ];
+ for i in 0..=3 {
+ for j in 0..=3 {
+ if i == j {
+ // Equal to self
+ assert_eq!(vecs[i], vecs[j]);
+ assert_eq!(calc_hash(&vecs[i]), calc_hash(&vecs[j]));
+ } else {
+ // Different types must be different and hash to different values
+ assert_ne!(vecs[i], vecs[j]);
+ assert_ne!(calc_hash(&vecs[i]), calc_hash(&vecs[j]));
+ }
+ // With casting however, values can be equal
+ assert!(vecs[i].cast_eq(&vecs[j]));
+ }
+ }
+
+ // Vectors with different sizes are always inequal
+ assert_ne!(
+ VectorValue::new_vec2(Vec2::ZERO),
+ VectorValue::new_vec3(Vec3::ZERO)
+ );
+ assert_ne!(
+ VectorValue::new_vec2(Vec2::ZERO),
+ VectorValue::new_vec4(Vec4::ZERO)
+ );
+ assert_ne!(
+ VectorValue::new_vec3(Vec3::ZERO),
+ VectorValue::new_vec4(Vec4::ZERO)
+ );
+
+ assert_eq!(
+ calc_hash(&Into::<VectorValue>::into(Vec2::new(3.5, -42.))),
+ calc_f32_vector_hash(VectorType::VEC2F, &[3.5, -42.])
+ );
+ assert_eq!(
+ calc_hash(&Into::<VectorValue>::into(Vec3::new(3.5, -42., 999.99))),
+ calc_f32_vector_hash(VectorType::VEC3F, &[3.5, -42., 999.99])
+ );
+ assert_eq!(
+ calc_hash(&Into::<VectorValue>::into(Vec4::new(
+ 3.5, -42., 999.99, -0.01,
+ ))),
+ calc_f32_vector_hash(VectorType::VEC4F, &[3.5, -42., 999.99, -0.01])
+ );
+
+ assert_eq!(
+ calc_hash(&Into::<VectorValue>::into(IVec2::new(3, -42))),
+ calc_i32_vector_hash(VectorType::VEC2I, &[3, -42])
+ );
+ assert_eq!(
+ calc_hash(&Into::<VectorValue>::into(IVec3::new(3, -42, 999))),
+ calc_i32_vector_hash(VectorType::VEC3I, &[3, -42, 999])
+ );
+ assert_eq!(
+ calc_hash(&Into::<VectorValue>::into(IVec4::new(3, -42, 999, -1))),
+ calc_i32_vector_hash(VectorType::VEC4I, &[3, -42, 999, -1])
+ );
+
+ assert_eq!(
+ calc_hash(&VectorValue::new_uvec2(UVec2::new(3, 42))),
+ calc_u32_vector_hash(VectorType::VEC2U, &[3, 42])
+ );
+ assert_eq!(
+ calc_hash(&VectorValue::new_uvec3(UVec3::new(3, 42, 999))),
+ calc_u32_vector_hash(VectorType::VEC3U, &[3, 42, 999])
+ );
+ assert_eq!(
+ calc_hash(&VectorValue::new_uvec4(UVec4::new(3, 42, 999, 1))),
+ calc_u32_vector_hash(VectorType::VEC4U, &[3, 42, 999, 1])
+ );
+ }
+
+ #[test]
+ fn try_into() {
+ let b: Value = true.into();
+ let ret: Result<bool, _> = b.try_into();
+ assert_eq!(ret, Ok(true));
+ assert!(matches!(
+ TryInto::<f32>::try_into(b),
+ Err(ExprError::TypeError(_))
+ ));
+ assert!(matches!(
+ TryInto::<i32>::try_into(b),
+ Err(ExprError::TypeError(_))
+ ));
+ assert!(matches!(
+ TryInto::<Vec3>::try_into(b),
+ Err(ExprError::TypeError(_))
+ ));
+
+ let f: Value = 3.4_f32.into();
+ let ret: Result<f32, _> = f.try_into();
+ assert_eq!(ret, Ok(3.4_f32));
+ assert!(matches!(
+ TryInto::<bool>::try_into(f),
+ Err(ExprError::TypeError(_))
+ ));
+ assert!(matches!(
+ TryInto::<u32>::try_into(f),
+ Err(ExprError::TypeError(_))
+ ));
+ assert!(matches!(
+ TryInto::<Vec2>::try_into(f),
+ Err(ExprError::TypeError(_))
+ ));
+
+ let u: Value = 42_u32.into();
+ let ret: Result<u32, _> = u.try_into();
+ assert_eq!(ret, Ok(42_u32));
+ assert!(matches!(
+ TryInto::<bool>::try_into(u),
+ Err(ExprError::TypeError(_))
+ ));
+ assert!(matches!(
+ TryInto::<f32>::try_into(u),
+ Err(ExprError::TypeError(_))
+ ));
+ assert!(matches!(
+ TryInto::<Vec4>::try_into(u),
+ Err(ExprError::TypeError(_))
+ ));
+
+ let i: Value = 42_i32.into();
+ let ret: Result<i32, _> = i.try_into();
+ assert_eq!(ret, Ok(42_i32));
+ assert!(matches!(
+ TryInto::<bool>::try_into(i),
+ Err(ExprError::TypeError(_))
+ ));
+ assert!(matches!(
+ TryInto::<f32>::try_into(i),
+ Err(ExprError::TypeError(_))
+ ));
+ assert!(matches!(
+ TryInto::<Vec4>::try_into(i),
+ Err(ExprError::TypeError(_))
+ ));
+ }
+
+ #[test]
+ fn splat() {
+ let b = true;
+ for c in 2..=4 {
+ let x = VectorValue::splat(&b.into(), c);
+ assert_eq!(x.elem_type(), ScalarType::Bool);
+ assert_eq!(x.vector_type().count(), c as usize);
+ if c == 2 {
+ assert_eq!(TryInto::<BVec2>::try_into(x), Ok(BVec2::splat(b)));
+ } else if c == 3 {
+ assert_eq!(TryInto::<BVec3>::try_into(x), Ok(BVec3::splat(b)));
+ } else {
+ assert_eq!(TryInto::<BVec4>::try_into(x), Ok(BVec4::splat(b)));
+ }
+ }
+
+ let f = 3.4_f32;
+ for c in 2..=4 {
+ let x = VectorValue::splat(&f.into(), c);
+ assert_eq!(x.elem_type(), ScalarType::Float);
+ assert_eq!(x.vector_type().count(), c as usize);
+ if c == 2 {
+ assert_eq!(TryInto::<Vec2>::try_into(x), Ok(Vec2::splat(f)));
+ } else if c == 3 {
+ assert_eq!(TryInto::<Vec3>::try_into(x), Ok(Vec3::splat(f)));
+ } else {
+ assert_eq!(TryInto::<Vec4>::try_into(x), Ok(Vec4::splat(f)));
+ }
+ }
+
+ let i = -46458_i32;
+ for c in 2..=4 {
+ let x = VectorValue::splat(&i.into(), c);
+ assert_eq!(x.elem_type(), ScalarType::Int);
+ assert_eq!(x.vector_type().count(), c as usize);
+ if c == 2 {
+ assert_eq!(TryInto::<IVec2>::try_into(x), Ok(IVec2::splat(i)));
+ } else if c == 3 {
+ assert_eq!(TryInto::<IVec3>::try_into(x), Ok(IVec3::splat(i)));
+ } else {
+ assert_eq!(TryInto::<IVec4>::try_into(x), Ok(IVec4::splat(i)));
+ }
+ }
+ }
+}
diff --git a/vendor/bevy_hanabi/src/graph/node.rs b/vendor/bevy_hanabi/src/graph/node.rs
new file mode 100644
index 00000000..1fe1f335
--- /dev/null
+++ b/vendor/bevy_hanabi/src/graph/node.rs
@@ -0,0 +1,1005 @@
+//! Node API.
+//!
+//! ⚠️ This API is under construction and is missing some features. ⚠️
+//!
+//! The Node API is designed for effect editing, and the creation of UI tools.
+//! It builds on top of the [Expression API] and is entirely optional. It
+//! defines a [`Graph`] composed of [`Node`]s. Each node represent either a
+//! [`Modifier`] or an [`Expr`]. A node has some [`Slot`]s associated with it,
+//! representing its inputs and outputs, if any. An _output_ slot of a node can
+//! be linked to an _input_ slot of another node to express that the value
+//! produced by the upstream node must flow through to the input of the
+//! downstream node.
+//!
+//! An effect [`Graph`] can be serialized as is, to retain its editing
+//! capabilities. Alternatively, once the user has finished building an effect,
+//! it can be converted to a runtime [`EffectAsset`] for use as a
+//! [`ParticleEffect`].
+//!
+//! [Expression API]: crate::graph::expr
+//! [`Modifier`]: crate::Modifier
+//! [`Expr`]: crate::graph::expr::Expr
+//! [`EffectAsset`]: crate::EffectAsset
+//! [`ParticleEffect`]: crate::ParticleEffect
+
+use std::num::NonZeroU32;
+
+use crate::{Attribute, BuiltInOperator, ExprError, ExprHandle, Module, ValueType};
+
+/// Identifier of a node in a graph.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct NodeId(NonZeroU32);
+
+impl NodeId {
+ /// Create a new node identifier.
+ pub fn new(id: NonZeroU32) -> Self {
+ Self(id)
+ }
+
+ /// Get the one-based node index.
+ pub fn id(&self) -> NonZeroU32 {
+ self.0
+ }
+
+ /// Get the zero-based index of the node in the underlying graph node array.
+ pub fn index(&self) -> usize {
+ (self.0.get() - 1) as usize
+ }
+}
+
+/// Identifier of a slot in a graph.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct SlotId(NonZeroU32);
+
+impl SlotId {
+ /// Create a new slot identifier.
+ pub fn new(id: NonZeroU32) -> Self {
+ Self(id)
+ }
+
+ /// Get the one-based slot index.
+ pub fn id(&self) -> NonZeroU32 {
+ self.0
+ }
+
+ /// Get the zero-based index of the slot in the underlying graph slot array.
+ pub fn index(&self) -> usize {
+ (self.0.get() - 1) as usize
+ }
+}
+
+/// Node slot direction.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum SlotDir {
+ /// Input slot receiving data from outside the node.
+ Input,
+ /// Output slot providing data generated by the node.
+ Output,
+}
+
+/// Definition of a slot of a node.
+#[derive(Debug, Clone)]
+pub struct SlotDef {
+ /// Slot name.
+ name: String,
+ /// Slot direaction.
+ dir: SlotDir,
+ /// Type of values accepted by the slot. This may be `None` for variant
+ /// slots, if the type depends on the inputs of the node during evaluation.
+ value_type: Option<ValueType>,
+}
+
+impl SlotDef {
+ /// Create a new input slot.
+ pub fn input(name: impl Into<String>, value_type: Option<ValueType>) -> Self {
+ Self {
+ name: name.into(),
+ dir: SlotDir::Input,
+ value_type,
+ }
+ }
+
+ /// Create a new output slot.
+ pub fn output(name: impl Into<String>, value_type: Option<ValueType>) -> Self {
+ Self {
+ name: name.into(),
+ dir: SlotDir::Output,
+ value_type,
+ }
+ }
+
+ /// Get the slot name.
+ #[inline]
+ pub fn name(&self) -> &str {
+ &self.name
+ }
+
+ /// Get the slot direction.
+ #[inline]
+ pub fn dir(&self) -> SlotDir {
+ self.dir
+ }
+
+ /// Is the slot an input slot?
+ #[inline]
+ pub fn is_input(&self) -> bool {
+ self.dir == SlotDir::Input
+ }
+
+ /// Is the slot an input slot?
+ #[inline]
+ pub fn is_output(&self) -> bool {
+ self.dir == SlotDir::Output
+ }
+
+ /// Get the slot value type.
+ #[inline]
+ pub fn value_type(&self) -> Option<ValueType> {
+ self.value_type
+ }
+}
+
+/// Single slot of a node.
+#[derive(Debug, Clone)]
+pub struct Slot {
+ /// Owner node identifier.
+ node_id: NodeId,
+ /// Identifier.
+ id: SlotId,
+ /// Slot definition.
+ def: SlotDef,
+ /// Linked slots.
+ linked_slots: Vec<SlotId>,
+}
+
+impl Slot {
+ /// Create a new slot.
+ pub fn new(node_id: NodeId, slot_id: SlotId, slot_def: SlotDef) -> Self {
+ Slot {
+ node_id,
+ id: slot_id,
+ def: slot_def,
+ linked_slots: vec![],
+ }
+ }
+
+ /// Get the node identifier of the node this slot is from.
+ pub fn node_id(&self) -> NodeId {
+ self.node_id
+ }
+
+ /// Get the slot identifier.
+ pub fn id(&self) -> SlotId {
+ self.id
+ }
+
+ /// Get the slot definition.
+ pub fn def(&self) -> &SlotDef {
+ &self.def
+ }
+
+ /// Get the slot direction.
+ pub fn dir(&self) -> SlotDir {
+ self.def.dir()
+ }
+
+ /// Check if this slot is an input slot.
+ ///
+ /// This is a convenience helper for `self.dir() == SlotDir::Input`.
+ pub fn is_input(&self) -> bool {
+ self.dir() == SlotDir::Input
+ }
+
+ /// Check if this slot is an output slot.
+ ///
+ /// This is a convenience helper for `self.dir() == SlotDir::Output`.
+ pub fn is_output(&self) -> bool {
+ self.dir() == SlotDir::Output
+ }
+
+ /// Link this output slot to an input slot.
+ ///
+ /// # Panics
+ ///
+ /// Panics if this slot's direction is `SlotDir::Input`.
+ fn link_to(&mut self, input: SlotId) {
+ assert!(self.is_output());
+ if !self.linked_slots.contains(&input) {
+ self.linked_slots.push(input);
+ }
+ }
+
+ fn unlink_from(&mut self, input: SlotId) -> bool {
+ assert!(self.is_output());
+ if let Some(index) = self.linked_slots.iter().position(|&s| s == input) {
+ self.linked_slots.remove(index);
+ true
+ } else {
+ false
+ }
+ }
+
+ fn link_input(&mut self, output: SlotId) {
+ assert!(self.is_input());
+ if self.linked_slots.is_empty() {
+ self.linked_slots.push(output);
+ } else {
+ self.linked_slots[0] = output;
+ }
+ }
+
+ fn unlink_input(&mut self) {
+ assert!(self.is_input());
+ self.linked_slots.clear();
+ }
+}
+
+/// Effect graph.
+///
+/// An effect graph represents an editable version of an [`EffectAsset`]. The
+/// graph is composed of [`Node`]s, which represent either a [`Modifier`] or an
+/// expression [`Expr`]. Expression nodes are linked together to form more
+/// complex expressions which are then assigned to the modifier inputs. Once the
+/// graph is ready, it can be converted into an [`EffectAsset`].
+///
+/// [`EffectAsset`]: crate::EffectAsset
+/// [`Modifier`]: crate::Modifier
+/// [`Expr`]: crate::graph::Expr
+#[derive(Default)]
+pub struct Graph {
+ nodes: Vec<Box<dyn Node>>,
+ slots: Vec<Slot>,
+}
+
+impl std::fmt::Debug for Graph {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Graph").field("slots", &self.slots).finish()
+ }
+}
+
+impl Graph {
+ /// Create a new empty graph.
+ ///
+ /// An empty graph doesn't represent a valid [`EffectAsset`]. You must add
+ /// some [`Node`]s with [`add_node()`] and [`link()`] them together to form
+ /// a valid graph.
+ ///
+ /// [`EffectAsset`]: crate::EffectAsset
+ /// [`add_node()`]: crate::graph::Graph::add_node
+ /// [`link()`]: crate::graph::Graph::link
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Add a node to the graph, without any link.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::*;
+ /// let mut graph = Graph::new();
+ /// let time_node = graph.add_node(TimeNode::default());
+ /// ```
+ #[inline]
+ pub fn add_node<N>(&mut self, node: N) -> NodeId
+ where
+ N: Node + 'static,
+ {
+ self.add_node_impl(Box::new(node))
+ }
+
+ fn add_node_impl(&mut self, node: Box<dyn Node>) -> NodeId {
+ let index = self.nodes.len() as u32;
+ let node_id = NodeId::new(NonZeroU32::new(index + 1).unwrap());
+
+ for slot_def in node.slots() {
+ let slot_id = SlotId::new(NonZeroU32::new(self.slots.len() as u32 + 1).unwrap());
+ let slot = Slot::new(node_id, slot_id, slot_def.clone());
+ self.slots.push(slot);
+ }
+
+ self.nodes.push(node);
+
+ node_id
+ }
+
+ /// Link an output slot of a node to an input slot of another node.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the `output` argument doesn't reference an output slot of an
+ /// existing node, or the `input` argument doesn't reference an input slot
+ /// of an existing node.
+ pub fn link(&mut self, output: SlotId, input: SlotId) {
+ let out_slot = self.get_slot_mut(output);
+ assert!(out_slot.is_output());
+ out_slot.link_to(input);
+
+ let in_slot = self.get_slot_mut(input);
+ assert!(in_slot.is_input());
+ in_slot.link_input(output);
+ }
+
+ /// Unlink an output slot of a node from an input slot of another node.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the `output` argument doesn't reference an output slot of an
+ /// existing node, or the `input` argument doesn't reference an input slot
+ /// of an existing node.
+ pub fn unlink(&mut self, output: SlotId, input: SlotId) {
+ let out_slot = self.get_slot_mut(output);
+ assert!(out_slot.is_output());
+ if out_slot.unlink_from(input) {
+ let in_slot = self.get_slot_mut(input);
+ assert!(in_slot.is_input());
+ in_slot.unlink_input();
+ }
+ }
+
+ /// Unlink all remote slots from a given slot.
+ pub fn unlink_all(&mut self, slot_id: SlotId) {
+ let slot = self.get_slot_mut(slot_id);
+ let linked_slots = std::mem::take(&mut slot.linked_slots);
+ for remote_id in &linked_slots {
+ let remote_slot = self.get_slot_mut(*remote_id);
+ if remote_slot.is_input() {
+ remote_slot.unlink_input();
+ } else {
+ remote_slot.unlink_from(slot_id);
+ }
+ }
+ }
+
+ /// Get all slots of a node.
+ pub fn slots(&self, node_id: NodeId) -> Vec<SlotId> {
+ self.slots
+ .iter()
+ .filter_map(|s| {
+ if s.node_id() == node_id {
+ Some(s.id())
+ } else {
+ None
+ }
+ })
+ .collect()
+ }
+
+ /// Get a given input slot of a node by name.
+ pub fn input_slot<'a, 'b: 'a, S: Into<&'b str>>(
+ &'a self,
+ node_id: NodeId,
+ name: S,
+ ) -> Option<SlotId> {
+ let name = name.into();
+ self.slots
+ .iter()
+ .find(|s| s.node_id() == node_id && s.is_input() && s.def().name() == name)
+ .map(|s| s.id)
+ }
+
+ /// Get all input slots of a node.
+ pub fn input_slots(&self, node_id: NodeId) -> Vec<SlotId> {
+ self.slots
+ .iter()
+ .filter_map(|s| {
+ if s.node_id() == node_id && s.is_input() {
+ Some(s.id())
+ } else {
+ None
+ }
+ })
+ .collect()
+ }
+
+ /// Get a given output slot of a node by name.
+ pub fn output_slot<'a, 'b: 'a, S: Into<&'b str>>(
+ &'a self,
+ node_id: NodeId,
+ name: S,
+ ) -> Option<SlotId> {
+ let name = name.into();
+ self.slots
+ .iter()
+ .find(|s| s.node_id() == node_id && s.is_output() && s.def().name() == name)
+ .map(|s| s.id)
+ }
+
+ /// Get all output slots of a node.
+ pub fn output_slots(&self, node_id: NodeId) -> Vec<SlotId> {
+ self.slots
+ .iter()
+ .filter_map(|s| {
+ if s.node_id() == node_id && s.is_output() {
+ Some(s.id())
+ } else {
+ None
+ }
+ })
+ .collect()
+ }
+
+ /// Find a slot ID by slot name.
+ pub fn get_slot_id<'a, 'b: 'a, S: Into<&'b str>>(&'a self, name: S) -> Option<SlotId> {
+ let name = name.into();
+ self.slots
+ .iter()
+ .find(|&s| s.def().name() == name)
+ .map(|s| s.id)
+ }
+
+ #[allow(dead_code)] // TEMP
+ fn get_slot(&self, id: SlotId) -> &Slot {
+ let index = id.index();
+ assert!(index < self.slots.len());
+ &self.slots[index]
+ }
+
+ fn get_slot_mut(&mut self, id: SlotId) -> &mut Slot {
+ let index = id.index();
+ assert!(index < self.slots.len());
+ &mut self.slots[index]
+ }
+}
+
+/// Generic graph node.
+pub trait Node {
+ /// Get the list of slots of this node.
+ ///
+ /// The list contains both input and output slots, without any guaranteed
+ /// order.
+ fn slots(&self) -> &[SlotDef];
+
+ /// Evaluate the node from the given input expressions, and optionally
+ /// produce output expression(s).
+ ///
+ /// The expressions themselves are not evaluated (that is, _e.g._ "3 + 2" is
+ /// _not_ reduced to "5").
+ fn eval(
+ &self,
+ module: &mut Module,
+ inputs: Vec<ExprHandle>,
+ ) -> Result<Vec<ExprHandle>, ExprError>;
+}
+
+/// Graph node to add two values.
+#[derive(Debug, Clone)]
+pub struct AddNode {
+ slots: [SlotDef; 3],
+}
+
+impl Default for AddNode {
+ fn default() -> Self {
+ Self {
+ slots: [
+ SlotDef::input("lhs", None),
+ SlotDef::input("rhs", None),
+ SlotDef::output("result", None),
+ ],
+ }
+ }
+}
+
+impl Node for AddNode {
+ fn slots(&self) -> &[SlotDef] {
+ &self.slots
+ }
+
+ fn eval(
+ &self,
+ module: &mut Module,
+ inputs: Vec<ExprHandle>,
+ ) -> Result<Vec<ExprHandle>, ExprError> {
+ if inputs.len() != 2 {
+ return Err(ExprError::GraphEvalError(format!(
+ "Unexpected input count to AddNode::eval(): expected 2, got {}",
+ inputs.len()
+ )));
+ }
+ let mut inputs = inputs.into_iter();
+ let left = inputs.next().unwrap();
+ let right = inputs.next().unwrap();
+ let add = module.add(left, right);
+ Ok(vec![add])
+ }
+}
+
+/// Graph node to subtract two values.
+#[derive(Debug, Clone)]
+pub struct SubNode {
+ slots: [SlotDef; 3],
+}
+
+impl Default for SubNode {
+ fn default() -> Self {
+ Self {
+ slots: [
+ SlotDef::input("lhs", None),
+ SlotDef::input("rhs", None),
+ SlotDef::output("result", None),
+ ],
+ }
+ }
+}
+
+impl Node for SubNode {
+ fn slots(&self) -> &[SlotDef] {
+ &self.slots
+ }
+
+ fn eval(
+ &self,
+ module: &mut Module,
+ inputs: Vec<ExprHandle>,
+ ) -> Result<Vec<ExprHandle>, ExprError> {
+ if inputs.len() != 2 {
+ return Err(ExprError::GraphEvalError(format!(
+ "Unexpected input count to SubNode::eval(): expected 2, got
+{}",
+ inputs.len()
+ )));
+ }
+ let mut inputs = inputs.into_iter();
+ let left = inputs.next().unwrap();
+ let right = inputs.next().unwrap();
+ let sub = module.sub(left, right);
+ Ok(vec![sub])
+ }
+}
+
+/// Graph node to multiply two values.
+#[derive(Debug, Clone)]
+pub struct MulNode {
+ slots: [SlotDef; 3],
+}
+
+impl Default for MulNode {
+ fn default() -> Self {
+ Self {
+ slots: [
+ SlotDef::input("lhs", None),
+ SlotDef::input("rhs", None),
+ SlotDef::output("result", None),
+ ],
+ }
+ }
+}
+
+impl Node for MulNode {
+ fn slots(&self) -> &[SlotDef] {
+ &self.slots
+ }
+
+ fn eval(
+ &self,
+ module: &mut Module,
+ inputs: Vec<ExprHandle>,
+ ) -> Result<Vec<ExprHandle>, ExprError> {
+ if inputs.len() != 2 {
+ return Err(ExprError::GraphEvalError(format!(
+ "Unexpected input count to MulNode::eval(): expected 2, got
+{}",
+ inputs.len()
+ )));
+ }
+ let mut inputs = inputs.into_iter();
+ let left = inputs.next().unwrap();
+ let right = inputs.next().unwrap();
+ let mul = module.mul(left, right);
+ Ok(vec![mul])
+ }
+}
+
+/// Graph node to divide two values.
+#[derive(Debug, Clone)]
+pub struct DivNode {
+ slots: [SlotDef; 3],
+}
+
+impl Default for DivNode {
+ fn default() -> Self {
+ Self {
+ slots: [
+ SlotDef::input("lhs", None),
+ SlotDef::input("rhs", None),
+ SlotDef::output("result", None),
+ ],
+ }
+ }
+}
+
+impl Node for DivNode {
+ fn slots(&self) -> &[SlotDef] {
+ &self.slots
+ }
+
+ fn eval(
+ &self,
+ module: &mut Module,
+ inputs: Vec<ExprHandle>,
+ ) -> Result<Vec<ExprHandle>, ExprError> {
+ if inputs.len() != 2 {
+ return Err(ExprError::GraphEvalError(format!(
+ "Unexpected input count to DivNode::eval(): expected 2, got
+{}",
+ inputs.len()
+ )));
+ }
+ let mut inputs = inputs.into_iter();
+ let left = inputs.next().unwrap();
+ let right = inputs.next().unwrap();
+ let div = module.div(left, right);
+ Ok(vec![div])
+ }
+}
+
+/// Graph node to get any single particle attribute.
+#[derive(Debug, Clone)]
+pub struct AttributeNode {
+ /// The attribute to get.
+ attr: Attribute,
+ /// The output slot corresponding to the get value.
+ slots: [SlotDef; 1],
+}
+
+impl Default for AttributeNode {
+ fn default() -> Self {
+ Self::new(Attribute::POSITION)
+ }
+}
+
+impl AttributeNode {
+ /// Create a new attribute node for the given [`Attribute`].
+ pub fn new(attr: Attribute) -> Self {
+ Self {
+ attr,
+ slots: [SlotDef::output(attr.name(), Some(attr.value_type()))],
+ }
+ }
+}
+
+impl AttributeNode {
+ /// Get the attribute this node reads.
+ pub fn attr(&self) -> Attribute {
+ self.attr
+ }
+
+ /// Set the attribute this node reads.
+ pub fn set_attr(&mut self, attr: Attribute) {
+ self.attr = attr;
+ }
+}
+
+impl Node for AttributeNode {
+ fn slots(&self) -> &[SlotDef] {
+ &self.slots
+ }
+
+ fn eval(
+ &self,
+ module: &mut Module,
+ inputs: Vec<ExprHandle>,
+ ) -> Result<Vec<ExprHandle>, ExprError> {
+ if !inputs.is_empty() {
+ return Err(ExprError::GraphEvalError(
+ "Unexpected non-empty input to
+AttributeNode::eval()."
+ .to_string(),
+ ));
+ }
+ let attr = module.attr(self.attr);
+ Ok(vec![attr])
+ }
+}
+
+/// Graph node to get various time values related to the effect system.
+#[derive(Debug, Clone)]
+pub struct TimeNode {
+ /// Output slots corresponding to the various time-related quantities.
+ slots: [SlotDef; 2],
+}
+
+impl Default for TimeNode {
+ fn default() -> Self {
+ Self {
+ slots: [BuiltInOperator::Time, BuiltInOperator::DeltaTime]
+ .map(|op| SlotDef::output(op.name(), Some(op.value_type()))),
+ }
+ }
+}
+
+impl Node for TimeNode {
+ fn slots(&self) -> &[SlotDef] {
+ &self.slots
+ }
+
+ fn eval(
+ &self,
+ module: &mut Module,
+ inputs: Vec<ExprHandle>,
+ ) -> Result<Vec<ExprHandle>, ExprError> {
+ if !inputs.is_empty() {
+ return Err(ExprError::GraphEvalError(
+ "Unexpected non-empty input to
+TimeNode::eval()."
+ .to_string(),
+ ));
+ }
+ Ok([BuiltInOperator::Time, BuiltInOperator::DeltaTime]
+ .map(|op| module.builtin(op))
+ .to_vec())
+ }
+}
+
+/// Graph node to normalize a vector value.
+#[derive(Debug, Clone)]
+pub struct NormalizeNode {
+ /// Input and output vectors.
+ slots: [SlotDef; 2],
+}
+
+impl Default for NormalizeNode {
+ fn default() -> Self {
+ Self {
+ slots: [SlotDef::output("in", None), SlotDef::output("out", None)],
+ }
+ }
+}
+
+impl Node for NormalizeNode {
+ fn slots(&self) -> &[SlotDef] {
+ &self.slots
+ }
+
+ fn eval(
+ &self,
+ module: &mut Module,
+ inputs: Vec<ExprHandle>,
+ ) -> Result<Vec<ExprHandle>, ExprError> {
+ if inputs.len() != 1 {
+ return Err(ExprError::GraphEvalError(
+ "Unexpected input slot count to NormalizeNode::eval() not
+equal to one."
+ .to_string(),
+ ));
+ }
+ let input = inputs.into_iter().next().unwrap();
+ let norm = module.normalize(input);
+ Ok(vec![norm])
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use bevy::prelude::*;
+
+ use super::{Node, *};
+ use crate::{
+ EvalContext, ModifierContext, ParticleLayout, PropertyLayout, ShaderWriter, TextureLayout,
+ };
+
+ #[test]
+ fn add() {
+ let node = AddNode::default();
+
+ let mut module = Module::default();
+
+ let ret = node.eval(&mut module, vec![]);
+ assert!(matches!(ret, Err(ExprError::GraphEvalError(_))));
+ let three = module.lit(3.);
+ let ret = node.eval(&mut module, vec![three]);
+ assert!(matches!(ret, Err(ExprError::GraphEvalError(_))));
+
+ let two = module.lit(2.);
+ let outputs = node.eval(&mut module, vec![three, two]).unwrap();
+ assert_eq!(outputs.len(), 1);
+ let out = outputs[0];
+
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ let str = context.eval(&module, out).unwrap();
+ assert_eq!(str, "(3.) + (2.)".to_string());
+ }
+
+ #[test]
+ fn sub() {
+ let node = SubNode::default();
+
+ let mut module = Module::default();
+
+ let ret = node.eval(&mut module, vec![]);
+ assert!(matches!(ret, Err(ExprError::GraphEvalError(_))));
+ let three = module.lit(3.);
+ let ret = node.eval(&mut module, vec![three]);
+ assert!(matches!(ret, Err(ExprError::GraphEvalError(_))));
+
+ let two = module.lit(2.);
+ let outputs = node.eval(&mut module, vec![three, two]).unwrap();
+ assert_eq!(outputs.len(), 1);
+ let out = outputs[0];
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ let str = context.eval(&module, out).unwrap();
+ assert_eq!(str, "(3.) - (2.)".to_string());
+ }
+
+ #[test]
+ fn mul() {
+ let node = MulNode::default();
+
+ let mut module = Module::default();
+
+ let ret = node.eval(&mut module, vec![]);
+ assert!(matches!(ret, Err(ExprError::GraphEvalError(_))));
+ let three = module.lit(3.);
+ let ret = node.eval(&mut module, vec![three]);
+ assert!(matches!(ret, Err(ExprError::GraphEvalError(_))));
+
+ let two = module.lit(2.);
+ let outputs = node.eval(&mut module, vec![three, two]).unwrap();
+ assert_eq!(outputs.len(), 1);
+ let out = outputs[0];
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ let str = context.eval(&module, out).unwrap();
+ assert_eq!(str, "(3.) * (2.)".to_string());
+ }
+
+ #[test]
+ fn div() {
+ let node = DivNode::default();
+
+ let mut module = Module::default();
+
+ let ret = node.eval(&mut module, vec![]);
+ assert!(matches!(ret, Err(ExprError::GraphEvalError(_))));
+ let three = module.lit(3.);
+ let ret = node.eval(&mut module, vec![three]);
+ assert!(matches!(ret, Err(ExprError::GraphEvalError(_))));
+
+ let two = module.lit(2.);
+ let outputs = node.eval(&mut module, vec![three, two]).unwrap();
+ assert_eq!(outputs.len(), 1);
+ let out = outputs[0];
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ let str = context.eval(&module, out).unwrap();
+ assert_eq!(str, "(3.) / (2.)".to_string());
+ }
+
+ #[test]
+ fn attr() {
+ let node = AttributeNode::new(Attribute::POSITION);
+
+ let mut module = Module::default();
+
+ let three = module.lit(3.);
+ let ret = node.eval(&mut module, vec![three]);
+ assert!(matches!(ret, Err(ExprError::GraphEvalError(_))));
+
+ let outputs = node.eval(&mut module, vec![]).unwrap();
+ assert_eq!(outputs.len(), 1);
+ let out = outputs[0];
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ let str = context.eval(&module, out).unwrap();
+ assert_eq!(str, format!("particle.{}", Attribute::POSITION.name()));
+ }
+
+ #[test]
+ fn time() {
+ let node = TimeNode::default();
+
+ let mut module = Module::default();
+
+ let three = module.lit(3.);
+ let ret = node.eval(&mut module, vec![three]);
+ assert!(matches!(ret, Err(ExprError::GraphEvalError(_))));
+
+ let outputs = node.eval(&mut module, vec![]).unwrap();
+ assert_eq!(outputs.len(), 2);
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ let str0 = context.eval(&module, outputs[0]).unwrap();
+ let str1 = context.eval(&module, outputs[1]).unwrap();
+ assert_eq!(str0, format!("sim_params.{}", BuiltInOperator::Time.name()));
+ assert_eq!(
+ str1,
+ format!("sim_params.{}", BuiltInOperator::DeltaTime.name())
+ );
+ }
+
+ #[test]
+ fn normalize() {
+ let node = NormalizeNode::default();
+
+ let mut module = Module::default();
+
+ let ret = node.eval(&mut module, vec![]);
+ assert!(matches!(ret, Err(ExprError::GraphEvalError(_))));
+
+ let ones = module.lit(Vec3::ONE);
+ let outputs = node.eval(&mut module, vec![ones]).unwrap();
+ assert_eq!(outputs.len(), 1);
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ let str = context.eval(&module, outputs[0]).unwrap();
+ assert_eq!(str, "normalize(vec3<f32>(1.,1.,1.))".to_string());
+ }
+
+ #[test]
+ fn graph() {
+ let mut g = Graph::new();
+
+ let nid_pos = g.add_node(AttributeNode::new(Attribute::POSITION));
+ let nid_add = g.add_node(AddNode::default());
+ let sid_pos = g.output_slots(nid_pos)[0];
+ let sid_add_lhs = g.input_slots(nid_add)[0];
+ let sid_add_rhs = g.input_slots(nid_add)[1];
+ g.link(sid_pos, sid_add_lhs);
+
+ let nid_vel = g.add_node(AttributeNode::new(Attribute::VELOCITY));
+ let nid_mul = g.add_node(MulNode::default());
+ let nid_dt = g.add_node(TimeNode::default());
+ let sid_vel = g.output_slots(nid_vel)[0];
+ let sid_dt = g
+ .output_slot(nid_dt, BuiltInOperator::DeltaTime.name())
+ .unwrap();
+ let sid_mul_lhs = g.input_slots(nid_mul)[0];
+ let sid_mul_rhs = g.input_slots(nid_mul)[1];
+ g.link(sid_vel, sid_mul_lhs);
+ g.link(sid_dt, sid_mul_rhs);
+
+ let sid_mul_out = g.output_slots(nid_mul)[0];
+ g.link(sid_mul_out, sid_add_rhs);
+ }
+}
diff --git a/vendor/bevy_hanabi/src/lib.rs b/vendor/bevy_hanabi/src/lib.rs
new file mode 100644
index 00000000..2be09aa9
--- /dev/null
+++ b/vendor/bevy_hanabi/src/lib.rs
@@ -0,0 +1,3132 @@
+#![deny(
+ warnings,
+ missing_copy_implementations,
+ trivial_casts,
+ trivial_numeric_casts,
+ missing_docs,
+ unsafe_code,
+ unstable_features,
+ unused_import_braces,
+ clippy::suboptimal_flops,
+ clippy::imprecise_flops,
+ clippy::branches_sharing_code,
+ clippy::suspicious_operation_groupings,
+ clippy::useless_let_if_seq
+)]
+#![allow(clippy::too_many_arguments, clippy::type_complexity)]
+
+//! πŸŽ† Hanabi -- a GPU particle system plugin for the Bevy game engine.
+//!
+//! The πŸŽ† Hanabi particle system is a GPU-based particle system integrated with
+//! the built-in Bevy renderer. It allows creating complex visual effects with
+//! millions of particles simulated in real time, by leveraging the power of
+//! compute shaders and offloading most of the work of particle simulating to
+//! the GPU.
+//!
+//! The library supports the `wasm` target (WebAssembly) via the WebGPU renderer
+//! only. Compute shaders are not available via the legacy WebGL2 renderer.
+//! See Bevy's own [WebGL2 and WebGPU](https://github.com/bevyengine/bevy/tree/latest/examples#webgl2-and-webgpu)
+//! section of the examples README for more information on how to run Wasm
+//! builds with WebGPU.
+//!
+//! # 2D vs. 3D
+//!
+//! πŸŽ† Hanabi integrates both with the 2D and the 3D core pipelines of Bevy. The
+//! 2D pipeline integration is controlled by the `2d` cargo feature, while the
+//! 3D pipeline integration is controlled by the `3d` cargo feature. Both
+//! features are enabled by default for convenience. As an optimization, users
+//! can disable default features and re-enable only one of the two modes. At
+//! least one of the `2d` or `3d` features must be enabled.
+//!
+//! ```toml
+//! # Example: enable only 3D integration
+//! bevy_hanabi = { version = "0.19", default-features = false, features = ["3d"] }
+//! ```
+//!
+//! # Example
+//!
+//! Add the πŸŽ† Hanabi plugin to your app:
+//!
+//! ```no_run
+//! # use bevy::prelude::*;
+//! use bevy_hanabi::prelude::*;
+//!
+//! App::default()
+//! .add_plugins(DefaultPlugins)
+//! .add_plugins(HanabiPlugin)
+//! .run();
+//! ```
+//!
+//! Create an [`EffectAsset`] describing a visual effect:
+//!
+//! ```
+//! # use bevy::prelude::*;
+//! # use bevy_hanabi::prelude::*;
+//! fn setup(mut effects: ResMut<Assets<EffectAsset>>) {
+//! // Define a color gradient from red to transparent black
+//! let mut gradient = bevy_hanabi::Gradient::new();
+//! gradient.add_key(0.0, Vec4::new(1., 0., 0., 1.));
+//! gradient.add_key(1.0, Vec4::ZERO);
+//!
+//! // Create a new expression module
+//! let mut module = Module::default();
+//!
+//! // On spawn, randomly initialize the position of the particle
+//! // to be over the surface of a sphere of radius 2 units.
+//! let init_pos = SetPositionSphereModifier {
+//! center: module.lit(Vec3::ZERO),
+//! radius: module.lit(2.),
+//! dimension: ShapeDimension::Surface,
+//! };
+//!
+//! // Also initialize a radial initial velocity to 6 units/sec
+//! // away from the (same) sphere center.
+//! let init_vel = SetVelocitySphereModifier {
+//! center: module.lit(Vec3::ZERO),
+//! speed: module.lit(6.),
+//! };
+//!
+//! // Initialize the total lifetime of the particle, that is
+//! // the time for which it's simulated and rendered. This modifier
+//! // is almost always required, otherwise the particles will stay
+//! // alive forever, and new particles can't be spawned instead.
+//! let lifetime = module.lit(10.); // literal value "10.0"
+//! let init_lifetime = SetAttributeModifier::new(Attribute::LIFETIME, lifetime);
+//!
+//! // Every frame, add a gravity-like acceleration downward
+//! let accel = module.lit(Vec3::new(0., -3., 0.));
+//! let update_accel = AccelModifier::new(accel);
+//!
+//! // Create the effect asset
+//! let effect = EffectAsset::new(
+//! // Maximum number of particles alive at a time
+//! 1024,
+//! // Spawn at a rate of 5 particles per second
+//! SpawnerSettings::rate(5.0.into()),
+//! // Move the expression module into the asset
+//! module,
+//! )
+//! .with_name("MyEffect")
+//! .init(init_pos)
+//! .init(init_vel)
+//! .init(init_lifetime)
+//! .update(update_accel)
+//! // Render the particles with a color gradient over their
+//! // lifetime. This maps the gradient key 0 to the particle spawn
+//! // time, and the gradient key 1 to the particle death (10s).
+//! .render(ColorOverLifetimeModifier {
+//! gradient,
+//! blend: ColorBlendMode::Overwrite,
+//! mask: ColorBlendMask::RGBA,
+//! });
+//!
+//! // Insert into the asset system
+//! let effect_asset = effects.add(effect);
+//! }
+//! ```
+//!
+//! Then add an instance of that effect to an entity by spawning a
+//! [`ParticleEffect`] component referencing the asset.
+//!
+//! ```
+//! # use bevy::prelude::*;
+//! # use bevy_hanabi::prelude::*;
+//! # fn spawn_effect(mut commands: Commands) {
+//! # let effect_asset = Handle::<EffectAsset>::default();
+//! commands.spawn((
+//! ParticleEffect::new(effect_asset),
+//! Transform::from_translation(Vec3::Y),
+//! ));
+//! # }
+//! ```
+//!
+//! # Workflow
+//!
+//! Authoring and using a particle effect follows this workflow:
+//!
+//! 1. Create an [`EffectAsset`] representing the definition of the particle
+//! effect. This asset is a proper Bevy [`Asset`], expected to be authored in
+//! advance, serialized, and shipped with your application. Creating an
+//! [`EffectAsset`] at runtime while the application is running is also
+//! supported, though. In any case however, the asset doesn't do anything by
+//! itself.
+//! 2. At runtime, when the application is running, create an actual particle
+//! effect instance by spawning a [`ParticleEffect`] component. The component
+//! references the [`EffectAsset`] via its `handle` field. Multiple instances
+//! can reference the same asset at the same time, and some changes to the
+//! asset are reflected to its instances, although not all changes are
+//! supported. In general, avoid changing an [`EffectAsset`] while it's in
+//! use by one or more [`ParticleEffect`].
+//! 3. If using properties, spawn an [`EffectProperties`] component on the same
+//! entity. Then update properties through that component at any time while
+//! the effect is active. This allows some moderate CPU-side control over the
+//! simulation and rendering of the effect, without having to destroy the
+//! effect and re-create a new one.
+//! 4. If using textures, spawn an [`EffectMaterial`] component to define which
+//! texture is bound to which slot in the effect. An [`EffectAsset`] only
+//! defines "slots" of textures, not the actual assets bound to those slots.
+//! This way, you can reuse the same effect asset multiple times with
+//! different textures, like you'd do with a regular rendering mesh.
+//! 5. For advanced VFX composed of multiple hierarchical effects, where two or
+//! more effects are connected to each other in a parent-child relationship,
+//! spawn an [`EffectParent`] on any child effect instance to specify its
+//! parent instance. See also the [`EmitSpawnEventModifier`].
+//!
+//! The [`EffectAsset`] is intended to be the serialized effect format, which
+//! authors can save to disk and ship with their application. At this time
+//! however serialization and deserialization is still a work in progress. In
+//! particular, serialization and deserialization of all
+//! [modifiers](crate::modifier) is currently not supported on `wasm` target.
+
+use std::fmt::Write as _;
+
+use bevy::{
+ asset::AsAssetId,
+ camera::visibility::VisibilityClass,
+ platform::collections::{HashMap, HashSet},
+ prelude::*,
+ render::{
+ extract_component::ExtractComponent, render_resource::IntoBindGroupLayoutEntryBuilder as _,
+ sync_world::SyncToRenderWorld,
+ },
+};
+use rand::{RngExt as _, SeedableRng as _};
+use serde::{Deserialize, Serialize};
+use thiserror::Error;
+
+mod asset;
+pub mod attributes;
+mod gradient;
+pub mod graph;
+pub mod modifier;
+mod plugin;
+pub mod properties;
+mod render;
+mod spawn;
+mod time;
+
+#[cfg(test)]
+mod test_utils;
+
+pub use asset::{
+ AlphaMode, DefaultMesh, EffectAsset, EffectAssetDeserializer, EffectAssetLoader,
+ EffectAssetSerializer, EffectParent, MotionIntegration, SimulationCondition,
+};
+pub use attributes::*;
+pub use gradient::{Gradient, GradientKey};
+pub use graph::*;
+pub use modifier::*;
+pub use plugin::{EffectSystems, HanabiPlugin};
+pub use properties::*;
+pub use render::{DebugSettings, LayoutFlags, ShaderCache};
+pub use spawn::{tick_spawners, CpuValue, EffectSpawner, Random, SpawnerSettings};
+pub use time::{EffectSimulation, EffectSimulationTime};
+use wgpu::{
+ BindGroupLayoutEntry, BindingType, SamplerBindingType, ShaderStages, TextureDescriptor,
+ TextureDimension, TextureSampleType, TextureViewDimension,
+};
+
+#[allow(missing_docs)]
+pub mod prelude {
+ #[doc(hidden)]
+ pub use crate::*;
+}
+
+#[cfg(not(any(feature = "2d", feature = "3d")))]
+compile_error!(
+ "You need to enable at least one of the '2d' or '3d' features for anything to happen."
+);
+
+/// Extension trait to convert an object to WGSL code.
+///
+/// This is mainly used for floating-point constants. This is required because
+/// WGSL doesn't support a floating point constant without a decimal separator
+/// (_e.g._ `0.` instead of `0`), which would be what a regular string
+/// formatting function like [`format!()`] would produce, but which is
+/// interpreted as an integral type by WGSL instead.
+///
+/// # Example
+///
+/// ```
+/// # use bevy_hanabi::ToWgslString;
+/// let x = 2.0_f32;
+/// assert_eq!("let x = 2.;", format!("let x = {};", x.to_wgsl_string()));
+/// ```
+///
+/// # Remark
+///
+/// This trait is soft-deprecated. It serves the same purpose as
+/// [`EvalContext::eval()`], however it lacks any context for the evaluation of
+/// an expression producing WGSL code, so its use is limited. It's still useful
+/// for constant (literal) expressions, which do not require any context to
+/// evaluate.
+///
+/// [`format!()`]: std::format
+/// [`EvalContext::eval()`]: crate::graph::expr::EvalContext::eval
+pub trait ToWgslString {
+ /// Convert an object to a string representing its WGSL code.
+ fn to_wgsl_string(&self) -> String;
+}
+
+impl ToWgslString for f32 {
+ fn to_wgsl_string(&self) -> String {
+ let s = format!("{self:.6}");
+ s.trim_end_matches('0').to_string()
+ }
+}
+
+impl ToWgslString for f64 {
+ fn to_wgsl_string(&self) -> String {
+ let s = format!("{self:.15}");
+ s.trim_end_matches('0').to_string()
+ }
+}
+
+impl ToWgslString for Vec2 {
+ fn to_wgsl_string(&self) -> String {
+ format!(
+ "vec2<f32>({0},{1})",
+ self.x.to_wgsl_string(),
+ self.y.to_wgsl_string()
+ )
+ }
+}
+
+impl ToWgslString for Vec3 {
+ fn to_wgsl_string(&self) -> String {
+ format!(
+ "vec3<f32>({0},{1},{2})",
+ self.x.to_wgsl_string(),
+ self.y.to_wgsl_string(),
+ self.z.to_wgsl_string()
+ )
+ }
+}
+
+impl ToWgslString for Vec4 {
+ fn to_wgsl_string(&self) -> String {
+ format!(
+ "vec4<f32>({0},{1},{2},{3})",
+ self.x.to_wgsl_string(),
+ self.y.to_wgsl_string(),
+ self.z.to_wgsl_string(),
+ self.w.to_wgsl_string()
+ )
+ }
+}
+
+impl ToWgslString for bool {
+ fn to_wgsl_string(&self) -> String {
+ if *self {
+ "true".to_string()
+ } else {
+ "false".to_string()
+ }
+ }
+}
+
+impl ToWgslString for BVec2 {
+ fn to_wgsl_string(&self) -> String {
+ format!(
+ "vec2<bool>({0},{1})",
+ self.x.to_wgsl_string(),
+ self.y.to_wgsl_string()
+ )
+ }
+}
+
+impl ToWgslString for BVec3 {
+ fn to_wgsl_string(&self) -> String {
+ format!(
+ "vec3<bool>({0},{1},{2})",
+ self.x.to_wgsl_string(),
+ self.y.to_wgsl_string(),
+ self.z.to_wgsl_string()
+ )
+ }
+}
+
+impl ToWgslString for BVec4 {
+ fn to_wgsl_string(&self) -> String {
+ format!(
+ "vec4<bool>({0},{1},{2},{3})",
+ self.x.to_wgsl_string(),
+ self.y.to_wgsl_string(),
+ self.z.to_wgsl_string(),
+ self.w.to_wgsl_string()
+ )
+ }
+}
+
+impl ToWgslString for i32 {
+ fn to_wgsl_string(&self) -> String {
+ format!("{}", self)
+ }
+}
+
+impl ToWgslString for IVec2 {
+ fn to_wgsl_string(&self) -> String {
+ format!(
+ "vec2<i32>({0},{1})",
+ self.x.to_wgsl_string(),
+ self.y.to_wgsl_string()
+ )
+ }
+}
+
+impl ToWgslString for IVec3 {
+ fn to_wgsl_string(&self) -> String {
+ format!(
+ "vec3<i32>({0},{1},{2})",
+ self.x.to_wgsl_string(),
+ self.y.to_wgsl_string(),
+ self.z.to_wgsl_string()
+ )
+ }
+}
+
+impl ToWgslString for IVec4 {
+ fn to_wgsl_string(&self) -> String {
+ format!(
+ "vec4<i32>({0},{1},{2},{3})",
+ self.x.to_wgsl_string(),
+ self.y.to_wgsl_string(),
+ self.z.to_wgsl_string(),
+ self.w.to_wgsl_string()
+ )
+ }
+}
+
+impl ToWgslString for u32 {
+ fn to_wgsl_string(&self) -> String {
+ format!("{}u", self)
+ }
+}
+
+impl ToWgslString for UVec2 {
+ fn to_wgsl_string(&self) -> String {
+ format!(
+ "vec2<u32>({0},{1})",
+ self.x.to_wgsl_string(),
+ self.y.to_wgsl_string()
+ )
+ }
+}
+
+impl ToWgslString for UVec3 {
+ fn to_wgsl_string(&self) -> String {
+ format!(
+ "vec3<u32>({0},{1},{2})",
+ self.x.to_wgsl_string(),
+ self.y.to_wgsl_string(),
+ self.z.to_wgsl_string()
+ )
+ }
+}
+
+impl ToWgslString for UVec4 {
+ fn to_wgsl_string(&self) -> String {
+ format!(
+ "vec4<u32>({0},{1},{2},{3})",
+ self.x.to_wgsl_string(),
+ self.y.to_wgsl_string(),
+ self.z.to_wgsl_string(),
+ self.w.to_wgsl_string()
+ )
+ }
+}
+
+impl ToWgslString for CpuValue<f32> {
+ fn to_wgsl_string(&self) -> String {
+ match self {
+ Self::Single(x) => x.to_wgsl_string(),
+ Self::Uniform((a, b)) => format!(
+ "(frand() * ({1} - {0}) + {0})",
+ a.to_wgsl_string(),
+ b.to_wgsl_string(),
+ ),
+ }
+ }
+}
+
+impl ToWgslString for CpuValue<Vec2> {
+ fn to_wgsl_string(&self) -> String {
+ match self {
+ Self::Single(v) => v.to_wgsl_string(),
+ Self::Uniform((a, b)) => format!(
+ "(frand2() * ({1} - {0}) + {0})",
+ a.to_wgsl_string(),
+ b.to_wgsl_string(),
+ ),
+ }
+ }
+}
+
+impl ToWgslString for CpuValue<Vec3> {
+ fn to_wgsl_string(&self) -> String {
+ match self {
+ Self::Single(v) => v.to_wgsl_string(),
+ Self::Uniform((a, b)) => format!(
+ "(frand3() * ({1} - {0}) + {0})",
+ a.to_wgsl_string(),
+ b.to_wgsl_string(),
+ ),
+ }
+ }
+}
+
+impl ToWgslString for CpuValue<Vec4> {
+ fn to_wgsl_string(&self) -> String {
+ match self {
+ Self::Single(v) => v.to_wgsl_string(),
+ Self::Uniform((a, b)) => format!(
+ "(frand4() * ({1} - {0}) + {0})",
+ a.to_wgsl_string(),
+ b.to_wgsl_string(),
+ ),
+ }
+ }
+}
+
+/// Simulation space for the particles of an effect.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Reflect, Serialize, Deserialize)]
+#[non_exhaustive]
+pub enum SimulationSpace {
+ /// Particles are simulated in global space.
+ ///
+ /// The global space is the Bevy world space. Particles simulated in global
+ /// space are "detached" from the emitter when they spawn, and not
+ /// influenced anymore by the emitter's [`GlobalTransform`] after spawning.
+ /// The particle's [`Attribute::POSITION`] is the world space position
+ /// of the particle.
+ ///
+ /// This is the default.
+ #[default]
+ Global,
+
+ /// Particles are simulated in local effect space.
+ ///
+ /// The local space is the space associated with the [`GlobalTransform`] of
+ /// the [`ParticleEffect`] component being simulated. Particles
+ /// simulated in local effect space are "attached" to the effect, and
+ /// will be affected by its [`GlobalTransform`]. The particle's
+ /// [`Attribute::POSITION`] is the position of the particle relative to
+ /// the effect's [`GlobalTransform`].
+ Local,
+}
+
+impl SimulationSpace {
+ /// Evaluate the simulation space expression.
+ ///
+ /// - Init: [`SimulationSpace::Global`] converts emitter space to simulation
+ /// space; [`SimulationSpace::Local`] is a no-op.
+ /// - Update: no-op. Particles are already in simulation space.
+ /// - In the render context, this expression transforms the particle's
+ /// position from simulation space to view space.
+ pub fn eval(&self, context: &dyn EvalContext) -> Result<String, ExprError> {
+ match context.modifier_context() {
+ ModifierContext::Init => match *self {
+ SimulationSpace::Global => {
+ if !context.particle_layout().contains(Attribute::POSITION) {
+ return Err(ExprError::GraphEvalError(format!("Global-space simulation requires that the particles have a {} attribute.", Attribute::POSITION.name())));
+ }
+ let pos = Attribute::POSITION.name();
+ let mut code = format!(
+ "particle.{0} = (transform * vec4<f32>(particle.{0}, 1.0)).xyz;\n",
+ pos
+ );
+ if context.particle_layout().contains(Attribute::VELOCITY) {
+ let vel = Attribute::VELOCITY.name();
+ code.push_str(&format!(
+ "particle.{0} = (transform * vec4<f32>(particle.{0}, 0.0)).xyz;\n",
+ vel
+ ));
+ }
+ Ok(code)
+ }
+ SimulationSpace::Local => Ok("".to_string()),
+ },
+ ModifierContext::Update => Ok(String::new()),
+ ModifierContext::Render => Ok(match *self {
+ // TODO: cast vec3 -> vec4 auomatically
+ SimulationSpace::Global => "vec4<f32>(local_position, 1.0)",
+ // TODO: transform_world_to_view(...)
+ SimulationSpace::Local => "transform * vec4<f32>(local_position, 1.0)",
+ }
+ .to_string()),
+ _ => Err(ExprError::GraphEvalError(
+ "Invalid modifier context value.".to_string(),
+ )),
+ }
+ }
+}
+
+/// Value a user wants to assign to a property with
+/// [`EffectProperties::set()`] before the instance had a chance
+/// to inspect its underlying asset and check the asset's defined properties.
+///
+/// A property with this name might not exist, in which case the value will be
+/// discarded silently when the instance is initialized from its asset.
+#[derive(Debug, Clone, PartialEq, Reflect)]
+pub struct PropertyValue {
+ /// Name of the property the value should be assigned to.
+ name: String,
+
+ /// The property value to assign, instead of the default value of the
+ /// property.
+ value: Value,
+}
+
+impl From<PropertyInstance> for PropertyValue {
+ fn from(prop: PropertyInstance) -> Self {
+ Self {
+ name: prop.def.name().to_string(),
+ value: prop.value,
+ }
+ }
+}
+
+impl From<&PropertyInstance> for PropertyValue {
+ fn from(prop: &PropertyInstance) -> Self {
+ Self {
+ name: prop.def.name().to_string(),
+ value: prop.value,
+ }
+ }
+}
+
+/// Marker component to tag the "main" camera.
+///
+/// Various features in Hanabi need a single camera to work with. However, Bevy
+/// doesn't have a concept of a "main" camera. This component solves this and
+/// marks a camera as the "main" one that Hanabi effects will use for camera
+/// related features, like sorting by camera distance (for semi-transparent
+/// particles), reading the depth buffer (_e.g._ for collision), or checking the
+/// camera frustum bounds (_e.g._ for frustum culling).
+///
+/// The component must be added to at most one entity
+/// having a [`Camera`] component. If absent, camera-related features will not
+/// work (but all other features continue to work). If no camera-related feature
+/// is used, adding this component is not required. Generally you want to add it
+/// to the camera that renders the "main view" of your game or application, the
+/// one that defines the final rendered view.
+///
+/// Dynamically switching camera is supported, but note that only one camera per
+/// frame can be tagged (the unique camera tagged at the time of the render
+/// world extraction phase is the camera taken into account). Tagging multiple
+/// camera will result in a system error and break Hanabi rendering.
+#[derive(Default, Clone, Copy, Component)]
+pub struct HanabiMainCamera;
+
+/// The [`VisibilityClass`] used for all particle effects.
+#[derive(Default, Clone, Copy, Component, ExtractComponent)]
+#[extract_app(bevy::render::RenderApp)]
+pub struct EffectVisibilityClass;
+
+/// Particle-based visual effect instance.
+///
+/// The particle effect component represents a single instance of a visual
+/// effect. The visual effect itself is described by a handle to an
+/// [`EffectAsset`].
+///
+/// This instance is associated to an [`Entity`], inheriting
+/// its [`GlobalTransform`] as the origin frame for its particle spawning.
+///
+/// # Content
+///
+/// The values in this component, with the exception of the handle to the
+/// underlying asset itself ([`ParticleEffect::handle`]), are optional
+/// per-instance overrides taking precedence over the fallback value set in the
+/// [`EffectAsset`].
+///
+/// Note that the effect graph itself including all its modifiers cannot be
+/// overridden per instance. For minor variations use different assets. If you
+/// need too many variants try to use a property instead.
+///
+/// # Component dependencies
+///
+/// ## Mandatory components
+///
+/// The [`ParticleEffect`] component requires, in the sense of ECS, some other
+/// components for the particle effect to work. Those mandatory components are
+/// automatically added by Bevy if not otherwise provided during spawning.
+///
+/// - A [`CompiledParticleEffect`] component, which contains some precomputed
+/// data and allocated resources, in particular GPU resources.
+/// - A [`Visibility`] component (and the components it requires in turn) to
+/// make use of the Bevy visibility system and optimize rendering of the
+/// effects. This influences simulation when using
+/// [`SimulationCondition::WhenVisible`].
+/// - A [`Transform`] component to define the position of the particle emitter.
+///
+/// ## Optional components
+///
+/// - The [`EffectMaterial`] defines the "material" of the particle effect,
+/// which contains for example the textures used by the particle system. This
+/// component is optional, because not all effects make use of a material.
+/// - The [`EffectParent`] defines the parent effect of this effect. This is
+/// used for hierarchical effect construction, and to use GPU spawn events to
+/// make the parent effect trigger spawning particles in this effect.
+/// - The [`EffectProperties`] defines the runtime values of the properties of
+/// the effect. If the effect doesn't use properties, this component is not
+/// used.
+///
+/// # Change detection
+///
+/// The [`CompiledParticleEffect`] component located on the same [`Entity`] as
+/// the current [`ParticleEffect`] component is automatically updated when a
+/// change occurs to this component. This separation is designed to leverage the
+/// change detection system of Bevy, in order to ensure that any manual change
+/// by the user is performed on this component and any automated change is
+/// performed on the [`CompiledParticleEffect`] component. This allows
+/// efficiently detecting when a user change requires an update to the compiled
+/// particle effect, while ensuring conversely that internal mutations do not
+/// invalidate the compiled effect and do not trigger a costly shader rebuild
+/// for example.
+#[derive(Debug, Default, Clone, Component, Reflect)]
+#[reflect(Component)]
+#[require(
+ CompiledParticleEffect,
+ Transform,
+ Visibility,
+ VisibilityClass,
+ SyncToRenderWorld
+)]
+#[component(on_add = bevy::camera::visibility::add_visibility_class::<EffectVisibilityClass>)]
+pub struct ParticleEffect {
+ /// Handle of the effect to instantiate.
+ pub handle: Handle<EffectAsset>,
+ /// Optional per-instance PRNG seed.
+ ///
+ /// Set this value to `Some(seed)` to override the default value set in
+ /// [`EffectAsset::prng_seed`] for this effect instance. By default this is
+ /// `None`, and the instance uses the same PRNG seed as its [`EffectAsset`].
+ pub prng_seed: Option<u32>,
+}
+
+impl ParticleEffect {
+ /// Create a new particle effect instance from an existing asset.
+ pub fn new(handle: Handle<EffectAsset>) -> Self {
+ Self {
+ handle,
+ prng_seed: None,
+ }
+ }
+}
+
+impl AsAssetId for ParticleEffect {
+ type Asset = EffectAsset;
+
+ fn as_asset_id(&self) -> AssetId<Self::Asset> {
+ self.handle.id()
+ }
+}
+
+/// Material for an effect instance.
+///
+/// A material component contains the render resources (textures) for a single
+/// effect instance. Those textures are automatically bound during rendering to
+/// the slots defined with [`Module::add_texture_slot()`]. Using this, multiple
+/// effect instances sharing a same source [`EffectAsset`] can be instantiated
+/// and rendered with different sets of textures, without changing the asset.
+///
+/// The [`EffectMaterial`] component needs to be spawned on the same entity as
+/// the [`ParticleEffect`] component representing the effect instance.
+#[derive(Debug, Default, Clone, Component)]
+pub struct EffectMaterial {
+ /// List of texture images to use to render the effect instance.
+ ///
+ /// The images are ordered by [slot index] into the corresponding
+ /// [`TextureLayout`].
+ ///
+ /// [slot index]: crate::TextureLayout::get_slot_by_name
+ pub images: Vec<Handle<Image>>,
+}
+
+/// Dimension of a texture for a material slot.
+///
+/// This defines the type of WGSL texture read or sampler used, and what format
+/// is expected for the [`Image`] bound to that slot. Image binding is done via
+/// the [`EffectMaterial`] component.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+#[reflect(Default)]
+pub enum SlotDimension {
+ /// A one dimensional texture. `texture_1d` in WGSL.
+ #[serde(rename = "1d")]
+ D1,
+
+ /// A two dimensional texture. `texture_2d` in WGSL.
+ #[serde(rename = "2d")]
+ #[default]
+ D2,
+
+ /// A two dimensional array texture. `texture_2d_array` in WGSL.
+ #[serde(rename = "2d-array")]
+ D2Array,
+
+ /// A cubemap texture. `texture_cube` in WGSL.
+ #[serde(rename = "cube")]
+ Cube,
+
+ /// A cubemap array texture. `texture_cube_array` in WGSL.
+ #[serde(rename = "cube-array")]
+ CubeArray,
+
+ /// A three dimensional texture. `texture_3d` in WGSL.
+ #[serde(rename = "3d")]
+ D3,
+
+ /// A two dimensional depth texture. `texture_depth_2d`.
+ #[serde(rename = "depth-2d")]
+ DepthD2,
+
+ /// A two dimensional array texture. `texture_depth_2d_array` in WGSL.
+ #[serde(rename = "depth-2d-array")]
+ DepthD2Array,
+
+ /// A cubemap texture. `texture_depth_cube` in WGSL.
+ #[serde(rename = "depth-cube")]
+ DepthCube,
+
+ /// A cubemap array texture. `texture_depth_cube_array` in WGSL.
+ #[serde(rename = "depth-cube-array")]
+ DepthCubeArray,
+}
+
+impl SlotDimension {
+ /// Check if this slot dimension uses an array texture.
+ ///
+ /// Array textures require an addition `array_index` when loading a value or
+ /// sampling the texture. See [`TextureSampleExpr`] and [`TextureLoadExpr`].
+ pub fn is_array(&self) -> bool {
+ matches!(
+ *self,
+ SlotDimension::D2Array
+ | SlotDimension::CubeArray
+ | SlotDimension::DepthD2Array
+ | SlotDimension::DepthCubeArray
+ )
+ }
+
+ /// Check if this slot dimension uses a depth texture.
+ ///
+ /// Depth textures use a comparison sampler, and always return a scalar
+ /// `f32` value. Non-depth textures conversely return a `vec4<f32>`, and use
+ /// an interpolating sampler (and optional mip-map).
+ pub fn is_depth(&self) -> bool {
+ matches!(
+ *self,
+ SlotDimension::DepthD2
+ | SlotDimension::DepthD2Array
+ | SlotDimension::DepthCube
+ | SlotDimension::DepthCubeArray
+ )
+ }
+
+ /// Check if this slot dimension uses a cube texture.
+ ///
+ /// Cube textures have some usage restrictions. In particular, you cannot
+ /// use them with a [`TextureLoadExpr`]. They always need a multiple of 6
+ /// layers (and exactly 6 if not an array).
+ pub fn is_cube(&self) -> bool {
+ matches!(
+ *self,
+ SlotDimension::Cube
+ | SlotDimension::CubeArray
+ | SlotDimension::DepthCube
+ | SlotDimension::DepthCubeArray
+ )
+ }
+
+ /// Convert this slot dimension to a WGSL texture type name.
+ pub fn to_wgsl_texture_type(&self) -> String {
+ match *self {
+ SlotDimension::D1 => "texture_1d<f32>",
+ SlotDimension::D2 => "texture_2d<f32>",
+ SlotDimension::D2Array => "texture_2d_array<f32>",
+ SlotDimension::D3 => "texture_3d<f32>",
+ SlotDimension::Cube => "texture_cube<f32>",
+ SlotDimension::CubeArray => "texture_cube_array<f32>",
+ SlotDimension::DepthD2 => "texture_depth_2d<f32>",
+ SlotDimension::DepthD2Array => "texture_depth_2d_array<f32>",
+ SlotDimension::DepthCube => "texture_depth_cube<f32>",
+ SlotDimension::DepthCubeArray => "texture_depth_cube_array<f32>",
+ }
+ .to_string()
+ }
+
+ /// Convert this slot dimension to a WGSL sampler type.
+ ///
+ /// This returns `sampler_comparison` if [`is_depth()`] is `true`, or
+ /// `sampler` otherwise.
+ ///
+ /// [`is_depth()`]: Self::is_depth
+ pub fn to_wgsl_sampler_type(&self) -> String {
+ if self.is_depth() {
+ "sampler_comparison"
+ } else {
+ "sampler"
+ }
+ .to_string()
+ }
+}
+
+/// Texture slot of a [`Module`].
+///
+/// A texture slot defines a named bind point where a texture can be attached
+/// and read/sampled by an effect during rendering. A slot also has an implicit
+/// unique index corresponding to its position in the [`TextureLayout::layout`]
+/// array of the effect.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct TextureSlot {
+ /// Unique slot name.
+ pub name: String,
+ /// Texture dimension the slot uses. This determines the sampler of the slot
+ /// in the WGSL shader.
+ pub dimension: SlotDimension,
+}
+
+impl TextureSlot {
+ /// Check if this slot accepts the given texture type.
+ ///
+ /// - `texture_dimension` determines the cardinality 1D/2D/3D of the texture
+ /// access.
+ /// - `array_layer_count` is the number of layers of an array texture. It
+ /// can only be > 1 for a [`SlotDimension`] corresponding to an array
+ /// texture.
+ /// - `is_depth` determines if the texture is accessed via a comparison
+ /// sampler as a depth texture. Note that this doesn't mean that the
+ /// texture must contain values that semantically represent a depth value;
+ /// the semantic of a texture value is irrelevant for the shader compiler,
+ /// and only matters for the author.
+ pub fn accepts(
+ &self,
+ texture_dimension: TextureDimension,
+ array_layer_count: u32,
+ is_depth: bool,
+ ) -> bool {
+ let expected_dimension = match self.dimension {
+ SlotDimension::D1 => TextureDimension::D1,
+ SlotDimension::D3 => TextureDimension::D3,
+ _ => TextureDimension::D2,
+ };
+ if texture_dimension != expected_dimension {
+ return false;
+ }
+
+ // Depth slots need a texture with a depth format
+ if self.dimension.is_depth() != is_depth {
+ return false;
+ }
+
+ // Cube textures need a number of layer multiple of 6. And non-array ones need
+ // exactly 6.
+ if self.dimension.is_cube()
+ && ((!self.dimension.is_array() && (array_layer_count != 6))
+ || !array_layer_count.is_multiple_of(6))
+ {
+ return false;
+ }
+
+ // A layer count > 1 requires an array textures or a cube texture
+ if array_layer_count > 1 {
+ self.dimension.is_array() || self.dimension.is_cube()
+ } else {
+ true
+ }
+ }
+
+ /// Get the WGPU binding type [`BindingType`] for a texture bound to this
+ /// slot.
+ ///
+ /// This returns a [`BindingType::Texture`].
+ pub fn to_texture_binding_type(&self) -> BindingType {
+ let (sample_type, view_dimension) = match self.dimension {
+ SlotDimension::D1 => (
+ TextureSampleType::Float { filterable: true },
+ TextureViewDimension::D1,
+ ),
+ SlotDimension::D2 => (
+ TextureSampleType::Float { filterable: true },
+ TextureViewDimension::D2,
+ ),
+ SlotDimension::D2Array => (
+ TextureSampleType::Float { filterable: true },
+ TextureViewDimension::D2Array,
+ ),
+ SlotDimension::D3 => (
+ TextureSampleType::Float { filterable: true },
+ TextureViewDimension::D3,
+ ),
+ SlotDimension::Cube => (
+ TextureSampleType::Float { filterable: true },
+ TextureViewDimension::Cube,
+ ),
+ SlotDimension::CubeArray => (
+ TextureSampleType::Float { filterable: true },
+ TextureViewDimension::CubeArray,
+ ),
+ SlotDimension::DepthD2 => (TextureSampleType::Depth, TextureViewDimension::D2),
+ SlotDimension::DepthD2Array => {
+ (TextureSampleType::Depth, TextureViewDimension::D2Array)
+ }
+ SlotDimension::DepthCube => (TextureSampleType::Depth, TextureViewDimension::Cube),
+ SlotDimension::DepthCubeArray => {
+ (TextureSampleType::Depth, TextureViewDimension::CubeArray)
+ }
+ };
+ BindingType::Texture {
+ sample_type,
+ view_dimension,
+ multisampled: false,
+ }
+ }
+
+ /// Get the WGPU binding type [`BindingType`] for a sampler bound to this
+ /// slot.
+ ///
+ /// This returns a [`BindingType::Sampler`] which is either a
+ /// [`SamplerBindingType::Comparison`] if [`SlotDimension::is_depth()`] is
+ /// `true`, or [`SamplerBindingType::Filtering`] otherwise.
+ pub fn to_sampler_binding_type(&self) -> BindingType {
+ let sampler_binding_type = if self.dimension.is_depth() {
+ SamplerBindingType::Comparison
+ } else {
+ SamplerBindingType::Filtering
+ };
+ BindingType::Sampler(sampler_binding_type)
+ }
+}
+
+/// Texture layout.
+///
+/// Defines the list of texture slots for an effect.
+#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct TextureLayout {
+ /// The list of slots.
+ ///
+ /// The slots index corresponds to the index inside this array. Each image
+ /// in [`EffectMaterial::images`] maps by index to a unique slot in this
+ /// array.
+ pub layout: Vec<TextureSlot>,
+}
+
+impl TextureLayout {
+ /// Find a texture slot by name, and return its index.
+ ///
+ /// The index uniquely identify the slot (like its name), and indexes into
+ /// the [`EffectMaterial::images`] array to determine which texture is bound
+ /// to it.
+ pub fn get_slot_by_name(&self, name: &str) -> Option<usize> {
+ self.layout.iter().position(|slot| slot.name == name)
+ }
+
+ /// Check if the given texture is compatible with the given slot.
+ ///
+ /// This checks that the slot index is valid, and that
+ /// [`TextureSlot::accepts()`] is `true` for that slot.
+ pub fn is_compatible(&self, slot_index: u32, texture_descriptor: &TextureDescriptor) -> bool {
+ if slot_index >= self.layout.len() as u32 {
+ return false;
+ }
+ if texture_descriptor.sample_count > 1 {
+ // Multisampled textures not currently supported by Hanabi
+ return false;
+ }
+ let slot = &self.layout[slot_index as usize];
+ slot.accepts(
+ texture_descriptor.dimension,
+ texture_descriptor.array_layer_count(),
+ texture_descriptor.format.is_depth_stencil_format(),
+ )
+ }
+
+ /// Append the bindings for the textures described by this layout.
+ pub fn append_layout_bindings(
+ &self,
+ start_binding: u32,
+ entries: &mut Vec<BindGroupLayoutEntry>,
+ ) {
+ let mut bind_index = start_binding;
+ for slot in &self.layout {
+ let tex_index = bind_index;
+ let sampler_index = bind_index + 1;
+ entries.push(
+ slot.to_texture_binding_type()
+ .into_bind_group_layout_entry_builder()
+ .build(
+ tex_index,
+ ShaderStages::COMPUTE | ShaderStages::VERTEX | ShaderStages::FRAGMENT,
+ ),
+ );
+ entries.push(
+ slot.to_sampler_binding_type()
+ .into_bind_group_layout_entry_builder()
+ .build(
+ sampler_index,
+ ShaderStages::COMPUTE | ShaderStages::VERTEX | ShaderStages::FRAGMENT,
+ ),
+ );
+ bind_index += 2;
+ }
+ }
+
+ /// Generate the WGSL code for the material bindings of this layout.
+ pub fn to_wgsl_binding(&self, group_index: u32, start_index: u32) -> String {
+ if self.layout.is_empty() {
+ return String::new();
+ }
+ let mut code = String::with_capacity(160 * self.layout.len());
+ let mut bind_index = start_index;
+ for (slot_index, slot) in self.layout.iter().enumerate() {
+ let tex_index = bind_index;
+ let sampler_index = bind_index + 1;
+ let texture_type = slot.dimension.to_wgsl_texture_type();
+ let sampler_type = slot.dimension.to_wgsl_sampler_type();
+ code.push_str(&format!(
+ "@group({group_index}) @binding({tex_index}) var material_texture_{slot_index}: {texture_type};
+@group({group_index}) @binding({sampler_index}) var material_sampler_{slot_index}: {sampler_type};
+"
+ ));
+ bind_index += 2;
+ }
+ code
+ }
+}
+
+/// Optional mesh override for a particle effect.
+///
+/// Add this component to the same entity as a [`ParticleEffect`] to override
+/// the [`Mesh`] used to render the particles.
+#[derive(Debug, Default, Clone, PartialEq, Hash, Component)]
+pub struct EffectMesh(pub Handle<Mesh>);
+
+/// Effect shaders.
+///
+/// Contains the final shaders for the init, update, and render passes of a
+/// single effect type.
+#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct EffectShaders {
+ /// The init compute shader, which runs on each newly spawned particle to
+ /// initialize its data once.
+ pub init: Handle<Shader>,
+ /// The update compute shader, which runs every frame to simulate all alive
+ /// particles.
+ pub update: Handle<Shader>,
+ /// The render graphics shader, which actually renders alive particles.
+ pub render: Handle<Shader>,
+}
+
+/// Source code (WESL) of an effect.
+///
+/// The source code is generated from an [`EffectAsset`] by applying all
+/// modifiers. The resulting source code is _configured_ (the Hanabi variables
+/// `{{VARIABLE}}` are replaced with the relevant WGSL code) but is not
+/// _specialized_ (the conditional attributes like `@if` are still present).
+///
+/// This is mainly used internally by Hanabi as an intermediate step toward
+/// generating the final [`EffectShaders`], and is exposed mainly for debugging
+/// and inspection (editor). In general, you don't need to use this type
+/// directly.
+#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct EffectShaderSources {
+ /// WESL source code for the init compute shader.
+ pub init_shader_source: String,
+ /// WESL source code for the update compute shader.
+ pub update_shader_source: String,
+ /// WESL source code for the render graphics shader (both vertex and
+ /// fragment).
+ pub render_shader_source: String,
+ /// Effect flags the source codes were generated with.
+ pub layout_flags: LayoutFlags,
+}
+
+/// Error resulting from the generating of the WGSL shader code of an
+/// [`EffectAsset`].
+#[derive(Debug, Error)]
+pub enum ShaderGenerateError {
+ /// Error related to an [`Expr`].
+ #[error("Expression error: {0}")]
+ Expr(ExprError),
+
+ /// Shader validation error.
+ #[error("Validation error: {0}")]
+ Validate(String),
+}
+
+impl EffectShaderSources {
+ /// Generate the effect shader WGSL source code.
+ ///
+ /// This takes a base asset effect and generate the WGSL code for the
+ /// various shaders (init/update/render).
+ pub fn generate(
+ asset: &EffectAsset,
+ // Note: ideally the below fields are folded into the asset, but currently the parent
+ // relationship and GPU event one are not encoded in assets.
+ parent_layout: Option<&ParticleLayout>,
+ num_event_bindings: u32,
+ ) -> Result<EffectShaderSources, ShaderGenerateError> {
+ trace!(
+ "Generating shader sources for asset '{}' with {} event bindings",
+ asset.name,
+ num_event_bindings
+ );
+
+ let particle_layout = asset.particle_layout();
+
+ // The particle layout cannot be empty currently because we always emit some
+ // Particle{} struct and it needs at least one field. There's probably no use
+ // case for an empty layout anyway.
+ if particle_layout.size() == 0 {
+ return Err(ShaderGenerateError::Validate(format!(
+ "Asset {} has invalid empty particle layout.",
+ asset.name
+ )));
+ }
+ if let Some(parent_layout) = parent_layout {
+ if parent_layout.size() == 0 {
+ return Err(ShaderGenerateError::Validate(format!(
+ "Effect using asset {} has invalid empty parent particle layout.",
+ asset.name
+ )));
+ }
+ }
+
+ // Currently the POSITION attribute is mandatory, as it's always used by the
+ // render shader.
+ if !particle_layout.contains(Attribute::POSITION) {
+ return Err(ShaderGenerateError::Validate(format!(
+ "The particle layout of asset '{}' is missing the '{}' attribute. Add a modifier using that attribute, for example the SetAttributeModifier.",
+ asset.name, Attribute::POSITION.name().to_ascii_uppercase()
+ )));
+ }
+
+ // Currently ribbon rendering requires AGE, so warn if it's missing because
+ // everything will break with some weird error aboud bind groups or whatnot.
+ if particle_layout.contains(Attribute::RIBBON_ID)
+ && !particle_layout.contains(Attribute::AGE)
+ {
+ return Err(ShaderGenerateError::Validate(format!(
+ "The particle layout of asset '{}' uses ribbons (has the '{}' attribute), but is missing the '{}' attribute, which is mandatory for ribbons. Add a modifier using that attribute, for example the SetAttributeModifier.",
+ asset.name, Attribute::RIBBON_ID.name().to_ascii_uppercase(), Attribute::AGE.name().to_ascii_uppercase()
+ )));
+ }
+
+ // Generate the WGSL code declaring all the attributes inside the Particle
+ // struct.
+ let attributes_code = particle_layout.generate_code();
+ let parent_particle_code = parent_layout
+ .map(|layout| {
+ format!(
+ "@if(READ_PARENT_PARTICLE)\nstruct ParentParticle {{\n{}\n}}",
+ layout.generate_code()
+ )
+ })
+ .unwrap_or_default();
+
+ // For the renderer, assign all its inputs to the values of the attributes
+ // present, or a default value.
+ let mut inputs_code = String::new();
+ // All required attributes, except the size/color which are variadic
+ let required_attributes =
+ HashSet::from_iter([Attribute::AXIS_X, Attribute::AXIS_Y, Attribute::AXIS_Z]);
+ let mut present_attributes = HashSet::new();
+ let mut has_size = false;
+ let mut has_color = false;
+ for attr_layout in particle_layout.attributes() {
+ let attr = attr_layout.attribute;
+ if attr == Attribute::SIZE {
+ if !has_size {
+ inputs_code += &format!(
+ "var size = vec3<f32>(particle.{0}, particle.{0}, particle.{0});\n",
+ Attribute::SIZE.name()
+ );
+ has_size = true;
+ present_attributes.insert(attr);
+ } else {
+ warn!("Attribute SIZE conflicts with another size attribute; ignored.");
+ }
+ } else if attr == Attribute::SIZE2 {
+ if !has_size {
+ inputs_code += &format!(
+ "var size = vec3<f32>(particle.{0}, 1.0);\n",
+ Attribute::SIZE2.name()
+ );
+ has_size = true;
+ present_attributes.insert(attr);
+ } else {
+ warn!("Attribute SIZE2 conflicts with another size attribute; ignored.");
+ }
+ } else if attr == Attribute::SIZE3 {
+ if !has_size {
+ inputs_code += &format!("var size = particle.{0};\n", Attribute::SIZE3.name());
+ has_size = true;
+ present_attributes.insert(attr);
+ } else {
+ warn!("Attribute SIZE3 conflicts with another size attribute; ignored.");
+ }
+ } else if attr == Attribute::HDR_COLOR {
+ if !has_color {
+ inputs_code +=
+ &format!("var color = particle.{};\n", Attribute::HDR_COLOR.name());
+ has_color = true;
+ present_attributes.insert(attr);
+ } else {
+ warn!("Attribute HDR_COLOR conflicts with another color attribute; ignored.");
+ }
+ } else if attr == Attribute::COLOR {
+ if !has_color {
+ inputs_code += &format!(
+ "var color = unpack4x8unorm(particle.{0});\n",
+ Attribute::COLOR.name()
+ );
+ has_color = true;
+ present_attributes.insert(attr);
+ } else {
+ warn!("Attribute COLOR conflicts with another color attribute; ignored.");
+ }
+ } else {
+ inputs_code += &format!("var {0} = particle.{0};\n", attr.name());
+ present_attributes.insert(attr);
+ }
+ }
+ // For all attributes required by the render shader, if they're not explicitly
+ // stored in the particle layout, define a variable with their default value.
+ if !has_size {
+ inputs_code += &format!(
+ "var size = {0};\n",
+ Attribute::SIZE3.default_value().to_wgsl_string() // TODO - or SIZE?
+ );
+ }
+ if !has_color {
+ inputs_code += &format!(
+ "var color = {};\n",
+ Attribute::HDR_COLOR.default_value().to_wgsl_string() // TODO - or COLOR?
+ );
+ }
+ for &attr in required_attributes.difference(&present_attributes) {
+ inputs_code += &format!(
+ "var {} = {};\n",
+ attr.name(),
+ attr.default_value().to_wgsl_string()
+ );
+ }
+
+ // Generate the shader code defining the per-effect properties, if any
+ let property_layout = asset.property_layout();
+ let properties_code = property_layout
+ .generate_property_struct_code()
+ .unwrap_or_default();
+ let properties_binding_code = if property_layout.is_empty() {
+ "// (no properties)".to_string()
+ } else {
+ "@group(2) @binding(3) var<storage, read> properties : array<Properties>;".to_string()
+ };
+
+ // Generate the shader code defining the material bindings. These occupy the
+ // @group(2) @binding(4..) range.
+ let texture_layout = asset.texture_layout();
+ let material_bindings_code = texture_layout.to_wgsl_binding(2, 4);
+
+ // Event buffer bindings for the update pass, if the effect emits GPU events to
+ // one or more other effects.
+ let mut emit_event_buffer_bindings_code = String::with_capacity(256);
+ emit_event_buffer_bindings_code.push_str(
+ "@if(EMITS_GPU_SPAWN_EVENTS)\n@group(3) @binding(1) var<storage, read_write> child_info_buffer : ChildInfoBuffer;\n",
+ );
+ let mut emit_event_buffer_append_funcs_code = String::with_capacity(1024);
+ let base_binding_index = 2;
+ for i in 0..num_event_bindings {
+ let binding_index = base_binding_index + i;
+ emit_event_buffer_bindings_code.push_str(&format!(
+ "@if(EMITS_GPU_SPAWN_EVENTS)\n@group(3) @binding({binding_index}) var<storage, read_write> event_buffer_{i} : EventBuffer;\n"));
+ emit_event_buffer_append_funcs_code.push_str(&format!(
+ r##"/// Append one or more spawn events to the event buffer.
+@if(EMITS_GPU_SPAWN_EVENTS)
+fn append_spawn_events_{0}(base_child_index: u32, particle_index: u32, count: u32) {{
+ // Optimize this case.
+ if (count == 0u) {{
+ return;
+ }}
+
+ let capacity = arrayLength(&event_buffer_{0}.spawn_events);
+ let base = min(u32(atomicAdd(&child_info_buffer.rows[base_child_index + {0}].event_count, i32(count))), capacity);
+ let capped_count = min(count, capacity - base);
+ for (var i = 0u; i < capped_count; i += 1u) {{
+ event_buffer_{0}.spawn_events[base + i].particle_index = particle_index;
+ }}
+}}
+"##,
+ i,
+ ));
+ }
+ emit_event_buffer_bindings_code.pop();
+ if emit_event_buffer_bindings_code.is_empty() {
+ emit_event_buffer_bindings_code = "// (not emitting GPU events)".into();
+ }
+ emit_event_buffer_append_funcs_code.pop();
+ if emit_event_buffer_append_funcs_code.is_empty() {
+ emit_event_buffer_append_funcs_code = "// (not emitting GPU events)".into();
+ }
+
+ // Start from the base module containing the expressions actually serialized in
+ // the asset. We will add the ones created on-the-fly by applying the
+ // modifiers to the contexts.
+ let mut module = asset.module().clone();
+
+ let mut layout_flags = LayoutFlags::NONE;
+ if asset.simulation_space == SimulationSpace::Local {
+ layout_flags |= LayoutFlags::LOCAL_SPACE_SIMULATION;
+ }
+ match &asset.alpha_mode {
+ AlphaMode::Mask(_) => layout_flags.insert(LayoutFlags::USE_ALPHA_MASK),
+ AlphaMode::Opaque => layout_flags.insert(LayoutFlags::OPAQUE),
+ _ => layout_flags.remove(LayoutFlags::USE_ALPHA_MASK | LayoutFlags::OPAQUE),
+ }
+ if particle_layout.contains(Attribute::RIBBON_ID) {
+ layout_flags |= LayoutFlags::RIBBONS;
+ }
+ if parent_layout.is_some() {
+ layout_flags |= LayoutFlags::READ_PARENT_PARTICLE;
+ }
+
+ // Generate the shader code for the initializing shader
+ let (init_code, init_extra, init_sim_space_transform_code, consume_gpu_spawn_events) = {
+ // Apply all the init modifiers
+ let mut init_context = ShaderWriter::new(
+ ModifierContext::Init,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ for m in asset.init_modifiers() {
+ if let Err(err) = m.apply(&mut module, &mut init_context) {
+ error!(
+ "Failed to compile effect '{}', error in init context: {}",
+ asset.name, err
+ );
+ return Err(ShaderGenerateError::Expr(err));
+ }
+ }
+
+ let sim_space_transform_code =
+ asset.simulation_space.eval(&init_context).map_err(|err| {
+ error!("Failed to compile effect's simulation space: {}", err);
+ ShaderGenerateError::Expr(err)
+ })?;
+
+ // Effect uses GPU spawn events if it produces them, or if it has a parent and
+ // consumes them from that parent.
+ let consume_gpu_spawn_events =
+ init_context.emits_gpu_spawn_events().unwrap_or(false) || parent_layout.is_some();
+
+ (
+ init_context.main_code,
+ init_context.extra_code,
+ sim_space_transform_code,
+ consume_gpu_spawn_events,
+ )
+ };
+
+ let init_shader_source = PARTICLES_INIT_SHADER_TEMPLATE
+ .replace("{{ATTRIBUTES}}", &attributes_code)
+ .replace("{{PARENT_PARTICLE}}", &parent_particle_code)
+ .replace("{{INIT_CODE}}", &init_code)
+ .replace("{{INIT_EXTRA}}", &init_extra)
+ .replace("{{PROPERTIES}}", &properties_code)
+ .replace("{{PROPERTIES_BINDING}}", &properties_binding_code)
+ .replace("{{MATERIAL_BINDINGS}}", &material_bindings_code)
+ .replace(
+ "{{SIMULATION_SPACE_TRANSFORM_PARTICLE}}",
+ &init_sim_space_transform_code,
+ );
+ trace!(
+ "Configured init shader for '{}':\n{}",
+ asset.name,
+ init_shader_source
+ );
+
+ // Generate the shader code for the update shader
+ let (mut update_code, update_extra, emit_gpu_spawn_events) = {
+ let mut update_context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ for m in asset.update_modifiers() {
+ if let Err(err) = m.apply(&mut module, &mut update_context) {
+ error!(
+ "Failed to compile effect '{}', error in update context: {}",
+ asset.name, err
+ );
+ return Err(ShaderGenerateError::Expr(err));
+ }
+ }
+
+ let emit_gpu_spawn_events = update_context.emits_gpu_spawn_events().unwrap_or(false);
+
+ (
+ update_context.main_code,
+ update_context.extra_code,
+ emit_gpu_spawn_events,
+ )
+ };
+
+ if consume_gpu_spawn_events {
+ layout_flags |= LayoutFlags::CONSUME_GPU_SPAWN_EVENTS;
+ }
+ if emit_gpu_spawn_events {
+ layout_flags |= LayoutFlags::EMIT_GPU_SPAWN_EVENTS;
+ }
+
+ // Insert Euler motion integration if needed.
+ let has_position = present_attributes.contains(&Attribute::POSITION);
+ let has_velocity = present_attributes.contains(&Attribute::VELOCITY);
+ if asset.motion_integration != MotionIntegration::None {
+ if has_position && has_velocity {
+ // Note the prepended "\n" to prevent appending to a comment line.
+ let code = format!(
+ "\nparticle.{0} += particle.{1} * sim_params.delta_time;\n",
+ Attribute::POSITION.name(),
+ Attribute::VELOCITY.name()
+ );
+ if asset.motion_integration == MotionIntegration::PreUpdate {
+ update_code.insert_str(0, &code);
+ } else {
+ update_code += &code;
+ }
+ } else {
+ warn!(
+ "Asset '{}' specifies motion integration but is missing {}. Particles won't move unless the POSITION attribute is explicitly assigned. Set MotionIntegration::None to remove this warning.",
+ asset.name,
+ if has_position {
+ "Attribute::VELOCITY"
+ } else {
+ "Attribute::POSITION"
+ }
+ )
+ }
+ }
+
+ // Generate the shader code for the render shader
+ let (
+ vertex_code,
+ fragment_code,
+ render_extra,
+ alpha_cutoff_code,
+ flipbook_scale_code,
+ flipbook_row_count_code,
+ ) = {
+ let texture_layout = module.texture_layout();
+ let mut render_context =
+ RenderContext::new(&property_layout, &particle_layout, &texture_layout);
+ for m in asset.render_modifiers() {
+ m.apply_render(&mut module, &mut render_context)
+ .map_err(ShaderGenerateError::Expr)?;
+ }
+
+ if render_context.needs_uv {
+ layout_flags |= LayoutFlags::NEEDS_UV;
+ }
+ if render_context.needs_normal {
+ layout_flags |= LayoutFlags::NEEDS_NORMAL;
+ }
+ if render_context.needs_particle_fragment {
+ layout_flags |= LayoutFlags::NEEDS_PARTICLE_FRAGMENT;
+ }
+
+ let alpha_cutoff_code = if let AlphaMode::Mask(cutoff) = &asset.alpha_mode {
+ render_context.eval(&module, *cutoff).unwrap_or_else(|err| {
+ error!(
+ "Failed to evaluate the expression for AlphaMode::Mask, error: {}",
+ err
+ );
+
+ // In Debug, show everything to help diagnosing
+ #[cfg(debug_assertions)]
+ return 1_f32.to_wgsl_string();
+
+ // In Release, hide everything with an error
+ #[cfg(not(debug_assertions))]
+ return 0_f32.to_wgsl_string();
+ })
+ } else {
+ // WESL parses disabled branches before conditional translation.
+ // Keep the unused initializer syntactically valid.
+ "0.0".to_string()
+ };
+
+ let (flipbook_scale_code, flipbook_row_count_code) = if let Some(grid_size) =
+ render_context.sprite_grid_size
+ {
+ layout_flags |= LayoutFlags::FLIPBOOK;
+ // Note: row_count needs to be i32, not u32, because of sprite_index
+ let flipbook_row_count_code = (grid_size.x as i32).to_wgsl_string();
+ let flipbook_scale_code =
+ Vec2::new(1.0 / grid_size.x as f32, 1.0 / grid_size.y as f32).to_wgsl_string();
+ (flipbook_scale_code, flipbook_row_count_code)
+ } else {
+ ("vec2<f32>(1.0)".to_string(), "1i".to_string())
+ };
+
+ (
+ render_context.vertex_code,
+ render_context.fragment_code,
+ render_context.render_extra,
+ alpha_cutoff_code,
+ flipbook_scale_code,
+ flipbook_row_count_code,
+ )
+ };
+
+ // Configure aging code
+ let has_age = present_attributes.contains(&Attribute::AGE);
+ let has_lifetime = present_attributes.contains(&Attribute::LIFETIME);
+ let mut age_code = String::new();
+ if has_age {
+ if has_lifetime {
+ age_code += &format!(
+ "\n let was_alive = particle.{0} < particle.{1};",
+ Attribute::AGE.name(),
+ Attribute::LIFETIME.name()
+ );
+ }
+
+ age_code += &format!(
+ "\n particle.{0} = particle.{0} + sim_params.delta_time;",
+ Attribute::AGE.name()
+ );
+
+ if has_lifetime {
+ age_code += &format!(
+ "\n var is_alive = particle.{0} < particle.{1};",
+ Attribute::AGE.name(),
+ Attribute::LIFETIME.name()
+ );
+ }
+ } else {
+ // Since we're using a dead index buffer, all particles that make it to the
+ // update compute shader are guaranteed to be alive (we never
+ // simulate dead particles).
+ age_code = "\n let was_alive = true;\n var is_alive = true;".to_string();
+ }
+
+ // Configure reaping code
+ let reap_code = if has_age && has_lifetime {
+ format!(
+ "is_alive = is_alive && (particle.{0} < particle.{1});",
+ Attribute::AGE.name(),
+ Attribute::LIFETIME.name()
+ )
+ } else {
+ "".to_string()
+ };
+
+ // Assign attributes individually instead of using struct
+ // assignment. Otherwise we might race on `PREV` and `NEXT`
+ // attributes, which might be updated behind our back when adjacent
+ // particles die.
+ let mut writeback_code = "".to_owned();
+ for attribute in present_attributes
+ .iter()
+ .filter(|attribute| **attribute != Attribute::PREV && **attribute != Attribute::NEXT)
+ {
+ writeln!(
+ &mut writeback_code,
+ " particle_buffer.particles[base_particle + particle_index].{0} = particle.{0};",
+ attribute.name()
+ )
+ .unwrap();
+ }
+
+ // Configure the update shader template, and make sure a corresponding shader
+ // asset exists
+ let update_shader_source = PARTICLES_UPDATE_SHADER_TEMPLATE
+ .replace("{{ATTRIBUTES}}", &attributes_code)
+ .replace("{{PARENT_PARTICLE}}", &parent_particle_code)
+ .replace("{{AGE_CODE}}", &age_code)
+ .replace("{{REAP_CODE}}", &reap_code)
+ .replace("{{UPDATE_CODE}}", &update_code)
+ .replace("{{WRITEBACK_CODE}}", &writeback_code)
+ .replace("{{UPDATE_EXTRA}}", &update_extra)
+ .replace("{{PROPERTIES}}", &properties_code)
+ .replace("{{PROPERTIES_BINDING}}", &properties_binding_code)
+ .replace("{{MATERIAL_BINDINGS}}", &material_bindings_code)
+ .replace(
+ "{{EMIT_EVENT_BUFFER_BINDINGS}}",
+ &emit_event_buffer_bindings_code,
+ )
+ .replace(
+ "{{EMIT_EVENT_BUFFER_APPEND_FUNCS}}",
+ &emit_event_buffer_append_funcs_code,
+ );
+ trace!(
+ "Configured update shader for '{}':\n{}",
+ asset.name,
+ update_shader_source
+ );
+
+ // Configure the render shader template, and make sure a corresponding shader
+ // asset exists
+ let render_shader_source = PARTICLES_RENDER_SHADER_TEMPLATE
+ .replace("{{ATTRIBUTES}}", &attributes_code)
+ .replace("{{INPUTS}}", &inputs_code)
+ .replace("{{PROPERTIES}}", &properties_code)
+ .replace("{{PROPERTIES_BINDING}}", &properties_binding_code)
+ .replace("{{MATERIAL_BINDINGS}}", &material_bindings_code)
+ .replace("{{VERTEX_MODIFIERS}}", &vertex_code)
+ .replace("{{FRAGMENT_MODIFIERS}}", &fragment_code)
+ .replace("{{RENDER_EXTRA}}", &render_extra)
+ .replace("{{ALPHA_CUTOFF}}", &alpha_cutoff_code)
+ .replace("{{FLIPBOOK_SCALE}}", &flipbook_scale_code)
+ .replace("{{FLIPBOOK_ROW_COUNT}}", &flipbook_row_count_code);
+ trace!(
+ "Configured render shader for '{}':\n{}",
+ asset.name,
+ render_shader_source
+ );
+
+ Ok(EffectShaderSources {
+ init_shader_source,
+ update_shader_source,
+ render_shader_source,
+ layout_flags,
+ })
+ }
+}
+
+/// Compiled data for a [`ParticleEffect`].
+///
+/// This component is managed automatically, and should not be accessed
+/// manually. It contains data generated from the associated [`ParticleEffect`]
+/// component located on the same [`Entity`]. The data is split into this
+/// component for change detection reasons, and any change to the associated
+/// [`ParticleEffect`] will cause the values of this component to be
+/// recalculated. Otherwise the data is cached frame-to-frame for performance.
+///
+/// All [`ParticleEffect`]s are compiled by the system running in the
+/// [`EffectSystems::CompileEffects`] set every frame when they're spawned or
+/// when they change, irrelevant of whether the entity if visible
+/// ([`Visibility::Visible`]).
+#[derive(Debug, Clone, Component)]
+pub struct CompiledParticleEffect {
+ /// Handle to the underlying asset.
+ asset: Handle<EffectAsset>,
+ /// Parent effect, if any.
+ parent: Option<Entity>,
+ /// Child effects.
+ children: Vec<Entity>,
+ /// Cached simulation condition, to avoid having to query the asset each
+ /// time we need it.
+ simulation_condition: SimulationCondition,
+ /// A custom mesh for this effect, if specified.
+ mesh: Option<Handle<Mesh>>,
+ /// Handle to the effect shaders for his effect instance, if configured.
+ effect_shader: Option<EffectShaders>,
+ /// Textures used by the effect, if any.
+ textures: Vec<Handle<Image>>,
+ /// Layout flags.
+ layout_flags: LayoutFlags,
+ /// Alpha mode.
+ alpha_mode: AlphaMode,
+ /// Particle layout of the parent effect, if any.
+ parent_particle_layout: Option<ParticleLayout>,
+ /// PRNG seed.
+ prng_seed: u32,
+ /// Ready state reported by the render world.
+ is_ready: bool,
+}
+
+impl Default for CompiledParticleEffect {
+ fn default() -> Self {
+ Self {
+ asset: default(),
+ parent: None,
+ children: vec![],
+ simulation_condition: SimulationCondition::default(),
+ mesh: None,
+ effect_shader: None,
+ textures: vec![],
+ layout_flags: LayoutFlags::NONE,
+ alpha_mode: default(),
+ parent_particle_layout: None,
+ prng_seed: 0,
+ is_ready: false,
+ }
+ }
+}
+
+impl CompiledParticleEffect {
+ /// Check if the effect is ready.
+ #[inline(always)]
+ pub fn is_ready(&self) -> bool {
+ self.is_ready
+ }
+
+ #[cfg(test)]
+ pub(crate) fn with_ready_for_tests(mut self) -> Self {
+ self.is_ready = true;
+ self
+ }
+
+ /// Clear the compiled data from this component.
+ pub(crate) fn clear(&mut self) {
+ self.asset = Handle::default();
+ self.effect_shader = None;
+ self.textures.clear();
+ }
+
+ /// Update the compiled effect from its asset and instance.
+ pub(crate) fn update(
+ &mut self,
+ rebuild: bool,
+ instance: &ParticleEffect,
+ material: Option<&EffectMaterial>,
+ mesh: Option<&EffectMesh>,
+ asset: &EffectAsset,
+ parent_entity: Option<Entity>,
+ child_entities: Vec<Entity>,
+ parent_layout: Option<ParticleLayout>,
+ asset_server: &AssetServer,
+ shaders: &mut ResMut<Assets<Shader>>,
+ shader_cache: &mut ResMut<ShaderCache>,
+ ) {
+ trace!(
+ "Updating (rebuild:{}) compiled particle effect '{}' ({:?})",
+ rebuild,
+ asset.name,
+ instance.handle,
+ );
+
+ // #289 - Panic in fn extract_effects
+ // We now keep a strong handle. Since CompiledParticleEffect is kept in sync
+ // with the source ParticleEffect, this shouldn't produce any strong cyclic
+ // dependency.
+ debug_assert!(instance.handle.is_strong());
+
+ // Note: if something marked the ParticleEffect as changed (via Mut for example)
+ // but didn't actually change anything, or at least didn't change the asset,
+ // then we may end up here with the same asset handle. Don't try to be
+ // too smart, and rebuild everything anyway, it's easier than trying to
+ // diff what may or may not have changed.
+ self.asset = instance.handle.clone();
+ self.simulation_condition = asset.simulation_condition;
+ self.prng_seed = instance.prng_seed.unwrap_or(asset.prng_seed);
+
+ // Check if the instance changed. If so, rebuild some data from this compiled
+ // effect based on the new data of the effect instance.
+ if rebuild {
+ // Clear the compiled effect if the effect instance changed. We could try to get
+ // smarter here, only invalidate what changed, but for now just wipe everything
+ // and rebuild from scratch all three shaders together.
+ self.effect_shader = None;
+ }
+
+ // If the shaders are already compiled, there's nothing more to do
+ if self.effect_shader.is_some() {
+ return;
+ }
+
+ self.parent = parent_entity;
+ self.children = child_entities;
+
+ let num_event_bindings = self.children.len() as u32;
+ let shader_source = match EffectShaderSources::generate(
+ asset,
+ parent_layout.as_ref(),
+ num_event_bindings,
+ ) {
+ Ok(shader_source) => shader_source,
+ Err(err) => {
+ error!(
+ "Failed to generate shaders for effect asset '{}': {}",
+ asset.name, err
+ );
+ return;
+ }
+ };
+
+ self.layout_flags = shader_source.layout_flags;
+ self.alpha_mode = asset.alpha_mode;
+ self.parent_particle_layout = parent_layout;
+ trace!(
+ "Compiled effect sources: layout_flags={:?} alpha_mode={:?}",
+ self.layout_flags,
+ self.alpha_mode
+ );
+
+ // TODO - Replace with Option<EffectShader { handle: Handle<Shader>, hash:
+ // u64 }> where the hash takes into account the code and extra code
+ // for each pass (and any other varying item). We don't need to keep
+ // around the entire shader code, only a hash of it for compare (or, maybe safer
+ // to avoid hash collisions, an index into a shader cache). The only
+ // use is to be able to compare 2 instances and see if they can be
+ // batched together.
+ self.effect_shader = Some(EffectShaders {
+ init: shader_cache.get_or_insert(
+ &asset.name,
+ "init",
+ &shader_source.init_shader_source,
+ shaders,
+ ),
+ update: shader_cache.get_or_insert(
+ &asset.name,
+ "update",
+ &shader_source.update_shader_source,
+ shaders,
+ ),
+ render: shader_cache.get_or_insert(
+ &asset.name,
+ "render",
+ &shader_source.render_shader_source,
+ shaders,
+ ),
+ });
+
+ trace!(
+ "CompiledParticleEffect::update(): shaders={:?} texture_count={} layout_flags={:?}",
+ self.effect_shader.as_ref().unwrap(),
+ material.map(|mat| mat.images.len()).unwrap_or(0),
+ self.layout_flags,
+ );
+
+ if let Some(mesh) = mesh {
+ self.mesh = Some(mesh.0.clone());
+ } else {
+ self.mesh = asset
+ .mesh
+ .as_ref()
+ .map(|path: &bevy::asset::AssetPath<'_>| asset_server.load::<Mesh>(path));
+ }
+
+ self.textures = material.map(|mat| &mat.images).cloned().unwrap_or_default();
+ }
+
+ /// Get the effect shader if configured, or `None` otherwise.
+ ///
+ /// The returned assets are the shaders actually compiled and used. You
+ /// should never mutate those shader assets directly; changing them without
+ /// updating the rest of the effect will cause discrepancies in the render
+ /// pipeline and most likely panics and crashes. This getter is provided
+ /// mainly for debugging and inspection (editor).
+ pub fn get_configured_shaders(&self) -> Option<&EffectShaders> {
+ self.effect_shader.as_ref()
+ }
+}
+
+const PARTICLES_INIT_SHADER_TEMPLATE: &str = include_str!("render/vfx_init.wesl");
+const PARTICLES_UPDATE_SHADER_TEMPLATE: &str = include_str!("render/vfx_update.wesl");
+const PARTICLES_RENDER_SHADER_TEMPLATE: &str = include_str!("render/vfx_render.wesl");
+
+/// Trait to convert any data structure to its equivalent shader code.
+trait ShaderCode {
+ /// Generate the shader code for the current state of the object.
+ fn to_shader_code(&self, input: &str) -> String;
+}
+
+impl ShaderCode for Gradient<Vec2> {
+ fn to_shader_code(&self, input: &str) -> String {
+ if self.keys().is_empty() {
+ return String::new();
+ }
+ let mut s: String = self
+ .keys()
+ .iter()
+ .enumerate()
+ .map(|(index, key)| {
+ format!(
+ "let t{0} = {1};\nlet v{0} = {2};",
+ index,
+ key.ratio().to_wgsl_string(),
+ key.value.to_wgsl_string()
+ )
+ })
+ .fold("// Gradient\n".into(), |s, key| s + &key + "\n");
+ if self.keys().len() == 1 {
+ s + "return v0;\n"
+ } else {
+ s += &format!("if ({input} <= t0) {{ return v0; }}\n");
+ let mut s = self
+ .keys()
+ .iter()
+ .skip(1)
+ .enumerate()
+ .map(|(index, _key)| {
+ format!(
+ "else if ({input} <= t{1}) {{ return mix(v{0}, v{1}, ({input} - t{0}) / (t{1} - t{0})); }}\n",
+ index,
+ index + 1
+ )
+ })
+ .fold(s, |s, key| s + &key);
+ let _ = writeln!(s, "else {{ return v{}; }}", self.keys().len() - 1);
+ s
+ }
+ }
+}
+
+impl ShaderCode for Gradient<Vec3> {
+ fn to_shader_code(&self, input: &str) -> String {
+ if self.keys().is_empty() {
+ return String::new();
+ }
+ let mut s: String = self
+ .keys()
+ .iter()
+ .enumerate()
+ .map(|(index, key)| {
+ format!(
+ "let t{0} = {1};\nlet v{0} = {2};",
+ index,
+ key.ratio().to_wgsl_string(),
+ key.value.to_wgsl_string()
+ )
+ })
+ .fold("// Gradient\n".into(), |s, key| s + &key + "\n");
+ if self.keys().len() == 1 {
+ s + "return v0;\n"
+ } else {
+ s += &format!("if ({input} <= t0) {{ return v0; }}\n");
+ let mut s = self
+ .keys()
+ .iter()
+ .skip(1)
+ .enumerate()
+ .map(|(index, _key)| {
+ format!(
+ "else if ({input} <= t{1}) {{ return mix(v{0}, v{1}, ({input} - t{0}) / (t{1} - t{0})); }}\n",
+ index,
+ index + 1
+ )
+ })
+ .fold(s, |s, key| s + &key);
+ let _ = writeln!(s, "else {{ return v{}; }}", self.keys().len() - 1);
+ s
+ }
+ }
+}
+
+impl ShaderCode for Gradient<Vec4> {
+ fn to_shader_code(&self, input: &str) -> String {
+ if self.keys().is_empty() {
+ return String::new();
+ }
+ let mut s: String = self
+ .keys()
+ .iter()
+ .enumerate()
+ .map(|(index, key)| {
+ format!(
+ "let t{0} = {1};\nlet c{0} = {2};",
+ index,
+ key.ratio().to_wgsl_string(),
+ key.value.to_wgsl_string()
+ )
+ })
+ .fold("// Gradient\n".into(), |s, key| s + &key + "\n");
+ if self.keys().len() == 1 {
+ s + "return c0;\n"
+ } else {
+ s += &format!("if ({input} <= t0) {{ return c0; }}\n");
+ let mut s = self
+ .keys()
+ .iter()
+ .skip(1)
+ .enumerate()
+ .map(|(index, _key)| {
+ format!(
+ "else if ({input} <= t{1}) {{ return mix(c{0}, c{1}, ({input} - t{0}) / (t{1} - t{0})); }}\n",
+ index,
+ index + 1
+ )
+ })
+ .fold(s, |s, key| s + &key);
+ let _ = writeln!(s, "else {{ return c{}; }}", self.keys().len() - 1);
+ s
+ }
+ }
+}
+
+/// Compile all the [`ParticleEffect`] components into a
+/// [`CompiledParticleEffect`].
+///
+/// This system runs in the [`EffectSystems::CompileEffects`] set of the
+/// [`PostUpdate`] schedule. It gathers all new instances of [`ParticleEffect`],
+/// as well as instances which changed, and (re)compile them into an optimized
+/// form saved into the [`CompiledParticleEffect`] component.
+///
+/// Hidden instances are compiled like visible ones, both to allow users to
+/// compile "in the background" by spawning a hidden effect, and also to prevent
+/// having mixed state where only some effects are compiled, and effects
+/// becoming visible later need to be special casing. If you want to avoid
+/// compiling an effect, don't spawn it.
+fn compile_effects(
+ asset_server: Res<AssetServer>,
+ effects: Res<Assets<EffectAsset>>,
+ mut shaders: ResMut<Assets<Shader>>,
+ mut shader_cache: ResMut<ShaderCache>,
+ mut q_effects: Query<(
+ Entity,
+ Ref<ParticleEffect>,
+ Option<Ref<EffectMaterial>>,
+ Option<Ref<EffectMesh>>,
+ Option<Ref<EffectParent>>,
+ &mut CompiledParticleEffect,
+ )>,
+) {
+ trace!("compile_effects: {} effect(s)", q_effects.iter().len());
+
+ // Loop over all existing effects and collect the valid ones. We do a separate
+ // pass because we can't borrow mutably while doing a double lookup on the
+ // query. This map is used to lookup valid parents, and filter out effects with
+ // a declared parent but unresolved parent asset.
+ let particle_layouts_and_parents: HashMap<Entity, (ParticleLayout, Option<Entity>)> = q_effects
+ .iter()
+ .filter_map(|(entity, effect, _, _, parent, _)| {
+ effects
+ .get(&effect.handle)
+ .map(|asset| (entity, (asset.particle_layout(), parent.map(|p| p.entity))))
+ })
+ .collect();
+
+ // Count children
+ let mut children: HashMap<Entity, Vec<Entity>> =
+ HashMap::with_capacity_and_hasher(particle_layouts_and_parents.len(), Default::default());
+ for (child, (_, parent)) in particle_layouts_and_parents.iter() {
+ if let Some(parent) = parent.as_ref() {
+ children.entry(*parent).or_default().push(*child);
+ }
+ }
+
+ // Loop over all existing effects to update them, including invisible ones
+ for (
+ asset,
+ entity,
+ effect,
+ material,
+ mesh,
+ parent_entity,
+ parent_layout,
+ mut compiled_effect,
+ ) in q_effects.iter_mut().filter_map(
+ |(entity, effect, material, mesh, parent, compiled_effect)| {
+ // Check if asset is available, otherwise silently ignore as we can't check for
+ // changes, and conceptually it makes no sense to render a particle effect whose
+ // asset was unloaded.
+ let asset = effects.get(&effect.handle)?;
+
+ // Same for the parent asset, if any.
+ let (parent_entity, parent_layout) = if let Some(parent) = &parent {
+ let Some((parent_layout, _)) = particle_layouts_and_parents.get(&parent.entity)
+ else {
+ // There's a parent declared, but not found. Skip the current asset.
+ return None;
+ };
+ // Declared parent with found parent asset, child asset is valid.
+ (Some(parent.entity), Some(parent_layout.clone()))
+ } else {
+ // No declared parent, asset is valid.
+ (None, None)
+ };
+
+ Some((
+ asset,
+ entity,
+ effect,
+ material,
+ mesh,
+ parent_entity,
+ parent_layout,
+ compiled_effect,
+ ))
+ },
+ ) {
+ let child_entities = children
+ .get_mut(&entity)
+ .map(std::mem::take)
+ .unwrap_or_default();
+
+ // If the ParticleEffect didn't change, and the compiled one is for the correct
+ // asset, then there's nothing to do.
+ let material_changed = material.as_ref().is_some_and(|r| r.is_changed());
+ let need_rebuild =
+ effect.is_changed() || material_changed || compiled_effect.children != child_entities;
+ if need_rebuild || (compiled_effect.asset != effect.handle) {
+ if need_rebuild {
+ debug!("Invalidating the compiled cache for effect on entity {:?} due to changes in the ParticleEffect component. If you see this message too much, then performance might be affected. Find why the change detection of the ParticleEffect is triggered.", entity);
+ }
+
+ compiled_effect.update(
+ need_rebuild,
+ &effect,
+ material.map(|r| r.into_inner()),
+ mesh.map(|r| r.into_inner()),
+ asset,
+ parent_entity,
+ child_entities,
+ parent_layout,
+ &asset_server,
+ &mut shaders,
+ &mut shader_cache,
+ );
+ } else {
+ // Update the PRNG seed. Unfortunately at the minute the "seed" (which
+ // really is the internal PRNG state rather) is not cached on GPU, and
+ // is re-uploaded each frame, so if it's not changed every frame then
+ // there's no randomness anymore, because the uses of the previous frame
+ // are "forgotten".
+ let mut rng = rand::rngs::StdRng::seed_from_u64(compiled_effect.prng_seed as u64);
+ compiled_effect.prng_seed = rng.random();
+ }
+ }
+
+ // Clear removed effects, to allow them to be released by the asset server
+ for (_, effect, _, _, parent, mut compiled_effect) in q_effects.iter_mut() {
+ // If the effect has no asset, clear its compilation
+ if effects.get(&effect.handle).is_none() {
+ compiled_effect.clear();
+ }
+
+ // If the effect has a parent, and that parent has no asset, also clear the
+ // child's compilation.
+ if let Some(parent) = parent {
+ if particle_layouts_and_parents.get(&parent.entity).is_none() {
+ compiled_effect.clear();
+ }
+ }
+ }
+}
+
+/// Update all properties of a [`ParticleEffect`] into its associated
+/// [`EffectProperties`].
+///
+/// This system runs in the [`EffectSystems::UpdatePropertiesFromAsset`] set of
+/// the [`PostUpdate`] schedule. It gathers all new instances of
+/// [`ParticleEffect`], as well as instances which changed, and update their
+/// associated [`EffectProperties`] component.
+///
+/// Hidden instances are processed like visible ones, both to allow users to
+/// compile "in the background" by spawning a hidden effect, and also to prevent
+/// having mixed state where only some effects are compiled, and effects
+/// becoming visible later need to be special casing. If you want to avoid
+/// compiling an effect, don't spawn it.
+fn update_properties_from_asset(
+ assets: Res<Assets<EffectAsset>>,
+ mut q_effects: Query<(Ref<ParticleEffect>, &mut EffectProperties), Changed<ParticleEffect>>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("update_properties_from_asset").entered();
+ trace!("update_properties_from_asset()");
+
+ // Loop over all existing effects, including invisible ones
+ for (effect, properties) in q_effects.iter_mut() {
+ // Check if the asset is available, otherwise silently ignore as we can't check
+ // for changes, and conceptually it makes no sense to render a particle
+ // effect whose asset was unloaded.
+ let Some(asset) = assets.get(&effect.handle) else {
+ continue;
+ };
+
+ EffectProperties::update(properties, asset.properties(), effect.is_added());
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::ops::DerefMut;
+
+ use bevy::{
+ asset::{
+ io::{
+ memory::{Dir, MemoryAssetReader},
+ AssetSourceBuilder, AssetSourceBuilders, AssetSourceId,
+ },
+ AssetServerMode, LoadState, UnapprovedPathMode,
+ },
+ camera::visibility::{VisibilityPlugin, VisibilitySystems},
+ tasks::{IoTaskPool, TaskPoolBuilder},
+ };
+
+ use super::*;
+ use crate::spawn::new_rng;
+
+ const INTS: &[usize] = &[1, 2, 4, 8, 9, 15, 16, 17, 23, 24, 31, 32, 33];
+ const INTS_POW2: &[usize] = &[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024];
+
+ /// Same as `INTS`, rounded up to 16
+ const INTS16: &[usize] = &[16, 16, 16, 16, 16, 16, 16, 32, 32, 32, 32, 32, 48];
+
+ #[test]
+ fn next_multiple() {
+ // align-1 is no-op
+ for &size in INTS {
+ assert_eq!(size, size.next_multiple_of(1));
+ }
+
+ // zero-sized is always aligned
+ for &align in INTS_POW2 {
+ assert_eq!(0, 0usize.next_multiple_of(align));
+ }
+
+ // size < align : rounds up to align
+ for &size in INTS {
+ assert_eq!(256, size.next_multiple_of(256));
+ }
+
+ // size > align : actually aligns
+ for (&size, &aligned_size) in INTS.iter().zip(INTS16) {
+ assert_eq!(aligned_size, size.next_multiple_of(16));
+ }
+ }
+
+ #[test]
+ fn to_wgsl_f32() {
+ let s = 1.0_f32.to_wgsl_string();
+ assert_eq!(s, "1.");
+ let s = (-1.0_f32).to_wgsl_string();
+ assert_eq!(s, "-1.");
+ let s = 1.5_f32.to_wgsl_string();
+ assert_eq!(s, "1.5");
+ let s = 0.5_f32.to_wgsl_string();
+ assert_eq!(s, "0.5");
+ let s = 0.123_456_78_f32.to_wgsl_string();
+ assert_eq!(s, "0.123457"); // 6 digits
+ }
+
+ #[test]
+ fn to_wgsl_f64() {
+ let s = 1.0_f64.to_wgsl_string();
+ assert_eq!(s, "1.");
+ let s = (-1.0_f64).to_wgsl_string();
+ assert_eq!(s, "-1.");
+ let s = 1.5_f64.to_wgsl_string();
+ assert_eq!(s, "1.5");
+ let s = 0.5_f64.to_wgsl_string();
+ assert_eq!(s, "0.5");
+ let s = 0.123_456_789_012_345_67_f64.to_wgsl_string();
+ assert_eq!(s, "0.123456789012346"); // 15 digits
+ }
+
+ #[test]
+ fn to_wgsl_vec() {
+ let s = Vec2::new(1., 2.).to_wgsl_string();
+ assert_eq!(s, "vec2<f32>(1.,2.)");
+ let s = Vec3::new(1., 2., -1.).to_wgsl_string();
+ assert_eq!(s, "vec3<f32>(1.,2.,-1.)");
+ let s = Vec4::new(1., 2., -1., 2.).to_wgsl_string();
+ assert_eq!(s, "vec4<f32>(1.,2.,-1.,2.)");
+ }
+
+ #[test]
+ fn to_wgsl_ivec() {
+ let s = IVec2::new(1, 2).to_wgsl_string();
+ assert_eq!(s, "vec2<i32>(1,2)");
+ let s = IVec3::new(1, 2, -1).to_wgsl_string();
+ assert_eq!(s, "vec3<i32>(1,2,-1)");
+ let s = IVec4::new(1, 2, -1, 2).to_wgsl_string();
+ assert_eq!(s, "vec4<i32>(1,2,-1,2)");
+ }
+
+ #[test]
+ fn to_wgsl_uvec() {
+ let s = UVec2::new(1, 2).to_wgsl_string();
+ assert_eq!(s, "vec2<u32>(1u,2u)");
+ let s = UVec3::new(1, 2, 42).to_wgsl_string();
+ assert_eq!(s, "vec3<u32>(1u,2u,42u)");
+ let s = UVec4::new(1, 2, 42, 5).to_wgsl_string();
+ assert_eq!(s, "vec4<u32>(1u,2u,42u,5u)");
+ }
+
+ #[test]
+ fn to_wgsl_bvec() {
+ let s = BVec2::new(false, true).to_wgsl_string();
+ assert_eq!(s, "vec2<bool>(false,true)");
+ let s = BVec3::new(false, true, true).to_wgsl_string();
+ assert_eq!(s, "vec3<bool>(false,true,true)");
+ let s = BVec4::new(false, true, true, false).to_wgsl_string();
+ assert_eq!(s, "vec4<bool>(false,true,true,false)");
+ }
+
+ #[test]
+ fn to_wgsl_value_f32() {
+ let s = CpuValue::Single(1.0_f32).to_wgsl_string();
+ assert_eq!(s, "1.");
+ let s = CpuValue::Uniform((1.0_f32, 2.0_f32)).to_wgsl_string();
+ assert_eq!(s, "(frand() * (2. - 1.) + 1.)");
+ }
+
+ #[test]
+ fn to_wgsl_value_vec2() {
+ let s = CpuValue::Single(Vec2::ONE).to_wgsl_string();
+ assert_eq!(s, "vec2<f32>(1.,1.)");
+ let s = CpuValue::Uniform((Vec2::ZERO, Vec2::ONE)).to_wgsl_string();
+ assert_eq!(
+ s,
+ "(frand2() * (vec2<f32>(1.,1.) - vec2<f32>(0.,0.)) + vec2<f32>(0.,0.))"
+ );
+ }
+
+ #[test]
+ fn to_wgsl_value_vec3() {
+ let s = CpuValue::Single(Vec3::ONE).to_wgsl_string();
+ assert_eq!(s, "vec3<f32>(1.,1.,1.)");
+ let s = CpuValue::Uniform((Vec3::ZERO, Vec3::ONE)).to_wgsl_string();
+ assert_eq!(
+ s,
+ "(frand3() * (vec3<f32>(1.,1.,1.) - vec3<f32>(0.,0.,0.)) + vec3<f32>(0.,0.,0.))"
+ );
+ }
+
+ #[test]
+ fn to_wgsl_value_vec4() {
+ let s = CpuValue::Single(Vec4::ONE).to_wgsl_string();
+ assert_eq!(s, "vec4<f32>(1.,1.,1.,1.)");
+ let s = CpuValue::Uniform((Vec4::ZERO, Vec4::ONE)).to_wgsl_string();
+ assert_eq!(s, "(frand4() * (vec4<f32>(1.,1.,1.,1.) - vec4<f32>(0.,0.,0.,0.)) + vec4<f32>(0.,0.,0.,0.))");
+ }
+
+ #[test]
+ fn to_shader_code() {
+ let mut grad = Gradient::new();
+ assert_eq!("", grad.to_shader_code("key"));
+
+ grad.add_key(0.0, Vec4::splat(0.0));
+ assert_eq!(
+ "// Gradient\nlet t0 = 0.;\nlet c0 = vec4<f32>(0.,0.,0.,0.);\nreturn c0;\n",
+ grad.to_shader_code("key")
+ );
+
+ grad.add_key(1.0, Vec4::new(1.0, 0.0, 0.0, 1.0));
+ assert_eq!(
+ r#"// Gradient
+let t0 = 0.;
+let c0 = vec4<f32>(0.,0.,0.,0.);
+let t1 = 1.;
+let c1 = vec4<f32>(1.,0.,0.,1.);
+if (key <= t0) { return c0; }
+else if (key <= t1) { return mix(c0, c1, (key - t0) / (t1 - t0)); }
+else { return c1; }
+"#,
+ grad.to_shader_code("key")
+ );
+ }
+
+ #[test]
+ fn test_simulation_space_eval() {
+ let particle_layout = ParticleLayout::empty();
+ let property_layout = PropertyLayout::default();
+ let texture_layout = TextureLayout::default();
+ {
+ // Global init requires storing the particle's position
+ let ctx = ShaderWriter::new(
+ ModifierContext::Init,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ assert!(SimulationSpace::Local.eval(&ctx).is_ok());
+ assert!(SimulationSpace::Global.eval(&ctx).is_err());
+
+ let particle_layout = ParticleLayout::new().append(Attribute::POSITION).build();
+ let ctx = ShaderWriter::new(
+ ModifierContext::Init,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ assert!(SimulationSpace::Local.eval(&ctx).is_ok());
+ assert!(SimulationSpace::Global.eval(&ctx).is_ok());
+ }
+ {
+ let ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ assert_eq!(SimulationSpace::Local.eval(&ctx).unwrap(), "");
+ assert_eq!(SimulationSpace::Global.eval(&ctx).unwrap(), "");
+
+ let particle_layout = ParticleLayout::new().append(Attribute::POSITION).build();
+ let ctx = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ assert_eq!(SimulationSpace::Local.eval(&ctx).unwrap(), "");
+ assert_eq!(SimulationSpace::Global.eval(&ctx).unwrap(), "");
+ }
+ {
+ // In the render context, the particle position is always available (either
+ // stored or not), so the simulation space can always be evaluated.
+ let texture_layout = TextureLayout::default();
+ let ctx = RenderContext::new(&property_layout, &particle_layout, &texture_layout);
+ assert!(SimulationSpace::Local.eval(&ctx).is_ok());
+ assert!(SimulationSpace::Global.eval(&ctx).is_ok());
+ }
+ }
+
+ #[test]
+ fn test_simulation_space_init_spawn_to_sim() {
+ let property_layout = PropertyLayout::default();
+ let texture_layout = TextureLayout::default();
+ let particle_layout = ParticleLayout::new()
+ .append(Attribute::POSITION)
+ .append(Attribute::VELOCITY)
+ .build();
+ let ctx = ShaderWriter::new(
+ ModifierContext::Init,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+
+ let global = SimulationSpace::Global.eval(&ctx).unwrap();
+ assert!(global.contains("vec4<f32>(particle.position, 1.0)"));
+ assert!(global.contains("vec4<f32>(particle.velocity, 0.0)"));
+ assert!(!global.contains("transform[3]"));
+
+ let local = SimulationSpace::Local.eval(&ctx).unwrap();
+ assert!(local.is_empty());
+ }
+
+ fn make_test_app() -> App {
+ IoTaskPool::get_or_init(|| {
+ TaskPoolBuilder::default()
+ .num_threads(1)
+ .thread_name("Hanabi test IO Task Pool".to_string())
+ .build()
+ });
+
+ let mut app = App::new();
+
+ let watch_for_changes = false;
+ let mut builders = app
+ .world_mut()
+ .get_resource_or_insert_with::<AssetSourceBuilders>(Default::default);
+ let dir = Dir::default();
+ let dummy_builder =
+ AssetSourceBuilder::new(move || Box::new(MemoryAssetReader { root: dir.clone() }));
+ builders.insert(AssetSourceId::Default, dummy_builder);
+ let sources = builders.build_sources(watch_for_changes, false);
+ let asset_server = AssetServer::new(
+ sources.into(),
+ AssetServerMode::Unprocessed,
+ watch_for_changes,
+ UnapprovedPathMode::Forbid,
+ );
+
+ app.insert_resource(asset_server);
+ // app.add_plugins(DefaultPlugins);
+ app.init_asset::<Mesh>();
+ app.init_asset::<bevy::mesh::skinning::SkinnedMeshInverseBindposes>();
+ app.init_asset::<Shader>();
+ app.add_plugins(VisibilityPlugin);
+ app.init_resource::<ShaderCache>();
+ app.insert_resource(Random(new_rng()));
+ app.init_asset::<EffectAsset>();
+ app.add_systems(
+ PostUpdate,
+ compile_effects.after(VisibilitySystems::CheckVisibility),
+ );
+
+ app
+ }
+
+ /// Test case for `tick_spawners()`.
+ struct TestCase {
+ /// Initial entity visibility on spawn. If `None`, do not add a
+ /// [`Visibility`] component.
+ visibility: Option<Visibility>,
+ }
+
+ impl TestCase {
+ fn new(visibility: Option<Visibility>) -> Self {
+ Self { visibility }
+ }
+ }
+
+ #[test]
+ fn test_effect_shader_source() {
+ // Empty particle layout
+ let module = Module::default();
+ let asset = EffectAsset::new(256, SpawnerSettings::rate(32.0.into()), module)
+ .with_simulation_space(SimulationSpace::Local);
+ assert_eq!(asset.simulation_space, SimulationSpace::Local);
+ let res = EffectShaderSources::generate(&asset, None, 0);
+ assert!(res.is_err());
+ let err = res.err().unwrap();
+ assert!(matches!(err, ShaderGenerateError::Validate(_)));
+
+ // Missing Attribute::POSITION, currently mandatory for all effects
+ let mut module = Module::default();
+ let zero = module.lit(Vec3::ZERO);
+ let asset = EffectAsset::new(256, SpawnerSettings::rate(32.0.into()), module)
+ .init(SetAttributeModifier::new(Attribute::VELOCITY, zero));
+ assert!(asset.particle_layout().size() > 0);
+ let res = EffectShaderSources::generate(&asset, None, 0);
+ assert!(res.is_err());
+ let err = res.err().unwrap();
+ assert!(matches!(err, ShaderGenerateError::Validate(_)));
+
+ // Valid
+ let mut module = Module::default();
+ let zero = module.lit(Vec3::ZERO);
+ let asset = EffectAsset::new(256, SpawnerSettings::rate(32.0.into()), module)
+ .with_simulation_space(SimulationSpace::Local)
+ .init(SetAttributeModifier::new(Attribute::POSITION, zero));
+ assert_eq!(asset.simulation_space, SimulationSpace::Local);
+ let res = EffectShaderSources::generate(&asset, None, 0);
+ assert!(res.is_ok());
+ let shader_source = res.unwrap();
+ for (name, code) in [
+ ("Init", shader_source.init_shader_source),
+ ("Update", shader_source.update_shader_source),
+ ("Render", shader_source.render_shader_source),
+ ] {
+ println!("{} shader:\n\n{}", name, code);
+
+ let mut modules = Vec::<(String, String)>::new();
+
+ // Import bevy_render::view for the render shader
+ {
+ // Load Bevy's actual view shader for the WESL resolver without
+ // creating a GPU device.
+ IoTaskPool::get_or_init(|| {
+ TaskPoolBuilder::default()
+ .num_threads(1)
+ .thread_name("Hanabi test IO Task Pool".to_string())
+ .build()
+ });
+ let mut dummy_app = App::new();
+ dummy_app.add_plugins(bevy::asset::AssetPlugin::default());
+ dummy_app.add_plugins(bevy::render::RenderPlugin {
+ render_creation: bevy::render::settings::WgpuSettings {
+ backends: None,
+ ..default()
+ }
+ .into(),
+ ..default()
+ });
+ let asset_server = dummy_app.world().resource::<AssetServer>();
+ let view_shader_handle =
+ asset_server.load::<Shader>("embedded://bevy_render/view.wesl");
+
+ // Need at least one frame tick for the loaded asset to send a message to the
+ // asset server to get registered
+ let mut max_frames = 10000; // it takes a decent amount of time to load async the asset, even if embedded
+ while max_frames > 0 {
+ dummy_app.world_mut().run_schedule(PreUpdate);
+
+ let asset_server = dummy_app.world().resource::<AssetServer>();
+ let load_state = asset_server.get_load_state(&view_shader_handle).unwrap();
+ if let LoadState::Failed(err) = load_state {
+ panic!("Load failed: {:?}", err);
+ }
+ if matches!(load_state, LoadState::Loaded) {
+ break;
+ }
+
+ max_frames -= 1;
+ }
+ assert!(max_frames > 0);
+
+ let shaders = dummy_app.world().get_resource::<Assets<Shader>>().unwrap();
+ let view_shader = shaders.get(&view_shader_handle).unwrap();
+
+ modules.push((
+ "bevy_render::view".into(),
+ view_shader.source.as_str().into(),
+ ));
+ }
+
+ // Import bevy_hanabi::vfx_common
+ {
+ let min_storage_buffer_offset_alignment = 256;
+ let common_shader =
+ HanabiPlugin::make_common_shader(min_storage_buffer_offset_alignment);
+ modules.push((
+ "bevy_hanabi::render::vfx_common".into(),
+ common_shader.source.as_str().into(),
+ ));
+ }
+
+ let wgsl = crate::test_utils::compile_wesl(
+ &code,
+ &[
+ "LOCAL_SPACE_SIMULATION",
+ "NEEDS_UV",
+ "PARTICLE_SCREEN_SPACE_SIZE",
+ ],
+ &modules
+ .iter()
+ .map(|(path, source)| (path.as_str(), source.as_str()))
+ .collect::<Vec<_>>(),
+ )
+ .unwrap_or_else(|error| panic!("{}", error.diagnostic().render_plain()));
+ let module = naga::front::wgsl::parse_str(&wgsl).unwrap();
+ naga::valid::Validator::new(
+ naga::valid::ValidationFlags::all(),
+ naga::valid::Capabilities::default(),
+ )
+ .validate(&module)
+ .unwrap();
+ }
+ }
+
+ // Regression test for #343
+ #[test]
+ fn test_compile_effect_invalid_handle() {
+ let mut app = make_test_app();
+
+ let effect_entity = {
+ let world = app.world_mut();
+
+ // Spawn particle effect
+ let entity = world.spawn(ParticleEffect::default()).id();
+
+ // Spawn a camera, otherwise ComputedVisibility stays at HIDDEN
+ world.spawn(Camera3d::default());
+
+ entity
+ };
+
+ // Tick once
+ app.update();
+
+ // Check
+ {
+ let world = app.world_mut();
+
+ let (entity, particle_effect, compiled_particle_effect) = world
+ .query::<(Entity, &ParticleEffect, &CompiledParticleEffect)>()
+ .iter(world)
+ .next()
+ .unwrap();
+ assert_eq!(entity, effect_entity);
+ assert_eq!(particle_effect.handle, Handle::<EffectAsset>::default());
+
+ // `compile_effects()` cannot update the CompiledParticleEffect because the
+ // asset is invalid
+ assert_eq!(
+ compiled_particle_effect.asset,
+ Handle::<EffectAsset>::default()
+ );
+ assert!(compiled_particle_effect.effect_shader.is_none());
+ }
+ }
+
+ // Regression test for #228
+ #[test]
+ fn test_compile_effect_changed() {
+ let spawner = SpawnerSettings::once(32.0.into());
+
+ let mut app = make_test_app();
+
+ let (effect_entity, handle) = {
+ let world = app.world_mut();
+
+ // Add effect asset
+ let mut assets = world.resource_mut::<Assets<EffectAsset>>();
+ let mut module = Module::default();
+ let init_pos = module.lit(Vec3::ZERO);
+ let mut asset = EffectAsset::new(64, spawner, module)
+ .init(SetAttributeModifier::new(Attribute::POSITION, init_pos));
+ asset.simulation_condition = SimulationCondition::Always;
+ let handle = assets.add(asset);
+
+ // Spawn particle effect
+ let entity = world
+ .spawn((
+ ParticleEffect::new(handle.clone()),
+ CompiledParticleEffect::default(),
+ ))
+ .id();
+
+ // Spawn a camera, otherwise ComputedVisibility stays at HIDDEN
+ world.spawn(Camera3d::default());
+
+ (entity, handle)
+ };
+
+ // Tick once
+ app.update();
+
+ // Check
+ {
+ let world = app.world_mut();
+
+ let (entity, particle_effect, compiled_particle_effect) = world
+ .query::<(Entity, &ParticleEffect, &CompiledParticleEffect)>()
+ .iter(world)
+ .next()
+ .unwrap();
+ assert_eq!(entity, effect_entity);
+ assert_eq!(particle_effect.handle, handle);
+
+ // `compile_effects()` always updates the CompiledParticleEffect
+ assert_eq!(compiled_particle_effect.asset, handle);
+ assert!(compiled_particle_effect.asset.is_strong());
+ assert!(compiled_particle_effect.effect_shader.is_some());
+ }
+
+ // Mark as changed without actually changing anything
+ {
+ let world = app.world_mut();
+
+ let mut particle_effect = world
+ .query::<&mut ParticleEffect>()
+ .iter_mut(world)
+ .next()
+ .unwrap();
+
+ // Force via Mut to mark the component as changed
+ particle_effect.deref_mut();
+ }
+
+ // Tick once - Regression test for #228, this should not panic
+ app.update();
+
+ // Check again, nothing changed
+ {
+ let world = app.world_mut();
+
+ let (entity, particle_effect, compiled_particle_effect) = world
+ .query::<(Entity, &ParticleEffect, &CompiledParticleEffect)>()
+ .iter(world)
+ .next()
+ .unwrap();
+ assert_eq!(entity, effect_entity);
+ assert_eq!(particle_effect.handle, handle);
+
+ // `compile_effects()` always updates the CompiledParticleEffect
+ assert_eq!(compiled_particle_effect.asset, handle);
+ assert!(compiled_particle_effect.asset.is_strong());
+ assert!(compiled_particle_effect.effect_shader.is_some());
+ }
+ }
+
+ #[test]
+ fn test_compile_effect_visibility() {
+ let spawner = SpawnerSettings::once(32.0.into());
+
+ for test_case in &[
+ TestCase::new(None),
+ TestCase::new(Some(Visibility::Hidden)),
+ TestCase::new(Some(Visibility::Visible)),
+ ] {
+ let mut app = make_test_app();
+
+ let (effect_entity, handle) = {
+ let world = app.world_mut();
+
+ // Add effect asset
+ let mut assets = world.resource_mut::<Assets<EffectAsset>>();
+ let mut module = Module::default();
+ let init_pos = module.lit(Vec3::ZERO);
+ let mut asset = EffectAsset::new(64, spawner, module)
+ .init(SetAttributeModifier::new(Attribute::POSITION, init_pos));
+ asset.simulation_condition = if test_case.visibility.is_some() {
+ SimulationCondition::WhenVisible
+ } else {
+ SimulationCondition::Always
+ };
+ // Use local simulation space so we don't need to store Attribute::POSITION for
+ // particles
+ asset.simulation_space = SimulationSpace::Local;
+ let handle = assets.add(asset);
+
+ // Spawn particle effect
+ let entity = if let Some(visibility) = test_case.visibility {
+ world
+ .spawn((
+ visibility,
+ InheritedVisibility::default(),
+ ParticleEffect::new(handle.clone()),
+ CompiledParticleEffect::default(),
+ ))
+ .id()
+ } else {
+ world
+ .spawn((
+ ParticleEffect::new(handle.clone()),
+ CompiledParticleEffect::default(),
+ ))
+ .id()
+ };
+
+ // Spawn a camera, otherwise ComputedVisibility stays at HIDDEN
+ world.spawn(Camera3d::default());
+
+ (entity, handle)
+ };
+
+ // Tick once
+ app.update();
+
+ let world = app.world_mut();
+
+ // Check the state of the components after `tick_spawners()` ran
+ if let Some(test_visibility) = test_case.visibility {
+ // Simulated-when-visible effect (SimulationCondition::WhenVisible)
+
+ let (
+ entity,
+ visibility,
+ inherited_visibility,
+ particle_effect,
+ compiled_particle_effect,
+ ) = world
+ .query::<(
+ Entity,
+ &Visibility,
+ &InheritedVisibility,
+ &ParticleEffect,
+ &CompiledParticleEffect,
+ )>()
+ .iter(world)
+ .next()
+ .unwrap();
+ assert_eq!(entity, effect_entity);
+ assert_eq!(visibility, test_visibility);
+ assert_eq!(
+ inherited_visibility.get(),
+ test_visibility == Visibility::Visible
+ );
+ assert_eq!(particle_effect.handle, handle);
+
+ // `compile_effects()` always updates the CompiledParticleEffect of new effects,
+ // even if hidden
+ assert_eq!(compiled_particle_effect.asset, handle);
+ assert!(compiled_particle_effect.asset.is_strong());
+ assert!(compiled_particle_effect.effect_shader.is_some());
+
+ // Toggle visibility and tick once more; this shouldn't panic (regression; #182)
+ let (mut visibility, _) = world
+ .query::<(&mut Visibility, &ParticleEffect)>()
+ .iter_mut(world)
+ .next()
+ .unwrap();
+ if *visibility == Visibility::Visible {
+ *visibility = Visibility::Hidden;
+ } else {
+ *visibility = Visibility::Visible;
+ }
+ app.update();
+ } else {
+ // Always-simulated effect (SimulationCondition::Always)
+
+ let (entity, particle_effect, compiled_particle_effect) = world
+ .query::<(Entity, &ParticleEffect, &CompiledParticleEffect)>()
+ .iter(world)
+ .next()
+ .unwrap();
+ assert_eq!(entity, effect_entity);
+ assert_eq!(particle_effect.handle, handle);
+
+ // `compile_effects()` always updates the CompiledParticleEffect
+ assert_eq!(compiled_particle_effect.asset, handle);
+ assert!(compiled_particle_effect.asset.is_strong());
+ assert!(compiled_particle_effect.effect_shader.is_some());
+ }
+ }
+ }
+
+ bitflags::bitflags! {
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ pub struct LayerMatchFlags: u8 {
+ const EXACTLY_ONE = (1u8 << 0);
+ const ONE_OR_MORE = (1u8 << 1);
+ const EXACTLY_SIX = (1u8 << 2);
+ const MULTIPLE_OF_SIX = (1u8 << 3);
+ }
+ }
+
+ impl LayerMatchFlags {
+ pub fn accepts(&self, layer: u32) -> bool {
+ match *self {
+ Self::EXACTLY_ONE => layer == 1,
+ Self::ONE_OR_MORE => layer >= 1,
+ Self::EXACTLY_SIX => layer == 6,
+ Self::MULTIPLE_OF_SIX => layer.is_multiple_of(6),
+ _ => panic!(),
+ }
+ }
+ }
+
+ fn check_texslot(slot: &TextureSlot, accepts: (TextureDimension, LayerMatchFlags, bool)) {
+ for dim in [
+ TextureDimension::D1,
+ TextureDimension::D2,
+ TextureDimension::D3,
+ ] {
+ for layer in [1, 2, 6, 14, 18] {
+ for is_depth in [true, false] {
+ let is_matching =
+ (dim == accepts.0) && (is_depth == accepts.2) && accepts.1.accepts(layer);
+ assert_eq!(
+ slot.accepts(dim, layer, is_depth),
+ is_matching,
+ "Expected slot {slot:?} to accept={is_matching} for dim={dim:?}, layer={layer}, is_depth={is_depth}");
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn texslot_accepts() {
+ let slot_1d = TextureSlot {
+ name: "D1".to_string(),
+ dimension: SlotDimension::D1,
+ };
+ let accepts = (TextureDimension::D1, LayerMatchFlags::EXACTLY_ONE, false);
+ check_texslot(&slot_1d, accepts);
+
+ let slot_2d = TextureSlot {
+ name: "D2".to_string(),
+ dimension: SlotDimension::D2,
+ };
+ let accepts = (TextureDimension::D2, LayerMatchFlags::EXACTLY_ONE, false);
+ check_texslot(&slot_2d, accepts);
+
+ let slot_2d_array = TextureSlot {
+ name: "D2Array".to_string(),
+ dimension: SlotDimension::D2Array,
+ };
+ let accepts = (TextureDimension::D2, LayerMatchFlags::ONE_OR_MORE, false);
+ check_texslot(&slot_2d_array, accepts);
+
+ let slot_cube = TextureSlot {
+ name: "Cube".to_string(),
+ dimension: SlotDimension::Cube,
+ };
+ let accepts = (TextureDimension::D2, LayerMatchFlags::EXACTLY_SIX, false);
+ check_texslot(&slot_cube, accepts);
+
+ let slot_cube_array = TextureSlot {
+ name: "CubeArray".to_string(),
+ dimension: SlotDimension::CubeArray,
+ };
+ let accepts = (
+ TextureDimension::D2,
+ LayerMatchFlags::MULTIPLE_OF_SIX,
+ false,
+ );
+ check_texslot(&slot_cube_array, accepts);
+
+ let slot_3d = TextureSlot {
+ name: "D3".to_string(),
+ dimension: SlotDimension::D3,
+ };
+ let accepts = (TextureDimension::D3, LayerMatchFlags::EXACTLY_ONE, false);
+ check_texslot(&slot_3d, accepts);
+
+ let slot_depth_2d = TextureSlot {
+ name: "DepthD2".to_string(),
+ dimension: SlotDimension::DepthD2,
+ };
+ let accepts = (TextureDimension::D2, LayerMatchFlags::EXACTLY_ONE, true);
+ check_texslot(&slot_depth_2d, accepts);
+
+ let slot_depth_2d_array = TextureSlot {
+ name: "DepthD2Array".to_string(),
+ dimension: SlotDimension::DepthD2Array,
+ };
+ let accepts = (TextureDimension::D2, LayerMatchFlags::ONE_OR_MORE, true);
+ check_texslot(&slot_depth_2d_array, accepts);
+
+ let slot_depth_cube = TextureSlot {
+ name: "DepthCube".to_string(),
+ dimension: SlotDimension::DepthCube,
+ };
+ let accepts = (TextureDimension::D2, LayerMatchFlags::EXACTLY_SIX, true);
+ check_texslot(&slot_depth_cube, accepts);
+
+ let slot_depth_cube_array = TextureSlot {
+ name: "DepthCubeArray".to_string(),
+ dimension: SlotDimension::DepthCubeArray,
+ };
+ let accepts = (TextureDimension::D2, LayerMatchFlags::MULTIPLE_OF_SIX, true);
+ check_texslot(&slot_depth_cube_array, accepts);
+ }
+
+ #[test]
+ fn slotdim_is() {
+ for dim in [
+ SlotDimension::D1,
+ SlotDimension::D2,
+ SlotDimension::D2Array,
+ SlotDimension::Cube,
+ SlotDimension::CubeArray,
+ SlotDimension::D3,
+ SlotDimension::DepthD2,
+ SlotDimension::DepthD2Array,
+ SlotDimension::DepthCube,
+ SlotDimension::DepthCubeArray,
+ ] {
+ // The canonical WGSL name, which is what the SlotDimentions debug-format to,
+ // happens to always contain "array" if the texture is an array texture, "depth"
+ // if it's used for comparison, and "cube" if it's a cube texture. We use this
+ // as validation.
+ let name = format!("{:?}", dim).to_ascii_lowercase();
+
+ let is_array = name.contains("array");
+ assert_eq!(is_array, dim.is_array());
+
+ let is_depth = name.contains("depth");
+ assert_eq!(is_depth, dim.is_depth());
+
+ let is_cube = name.contains("cube");
+ assert_eq!(is_cube, dim.is_cube());
+ }
+ }
+
+ #[test]
+ fn slotdim_texture_type() {
+ for dim in [
+ SlotDimension::D1,
+ SlotDimension::D2,
+ SlotDimension::D2Array,
+ SlotDimension::Cube,
+ SlotDimension::CubeArray,
+ SlotDimension::D3,
+ SlotDimension::DepthD2,
+ SlotDimension::DepthD2Array,
+ SlotDimension::DepthCube,
+ SlotDimension::DepthCubeArray,
+ ] {
+ let tex = dim.to_wgsl_texture_type();
+
+ let slot_type = format!("{dim:?}")
+ .to_ascii_lowercase()
+ .replace("array", "_array")
+ .replace("depth", "depth_")
+ .replace("d1", "1d")
+ .replace("d2", "2d")
+ .replace("d3", "3d");
+
+ assert_eq!(tex, format!("texture_{slot_type}<f32>"));
+ }
+ }
+
+ #[test]
+ fn slotdim_sampler_type() {
+ for dim in [
+ SlotDimension::D1,
+ SlotDimension::D2,
+ SlotDimension::D2Array,
+ SlotDimension::Cube,
+ SlotDimension::CubeArray,
+ SlotDimension::D3,
+ SlotDimension::DepthD2,
+ SlotDimension::DepthD2Array,
+ SlotDimension::DepthCube,
+ SlotDimension::DepthCubeArray,
+ ] {
+ let sampler = dim.to_wgsl_sampler_type();
+ assert_eq!(sampler.contains("comparison"), dim.is_depth());
+ }
+ }
+}
diff --git a/vendor/bevy_hanabi/src/modifier/accel.rs b/vendor/bevy_hanabi/src/modifier/accel.rs
new file mode 100644
index 00000000..aeb7078a
--- /dev/null
+++ b/vendor/bevy_hanabi/src/modifier/accel.rs
@@ -0,0 +1,394 @@
+//! Modifiers influencing the acceleration of particles, including gravity.
+//!
+//! The particle acceleration directly drives their velocity. It's applied each
+//! frame during simulation update.
+/// ```txt
+/// particle.velocity += acceleration * simulation.delta_time;
+/// ```
+use std::hash::Hash;
+
+use bevy::prelude::*;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ calc_func_id,
+ expr::PropertyHandle,
+ graph::{BuiltInExpr, EvalContext, ExprError},
+ Attribute, BoxedModifier, ExprHandle, Modifier, ModifierContext, Module, ShaderWriter,
+};
+
+/// A modifier to apply a uniform acceleration to all particles each frame, to
+/// simulate gravity or any other global force.
+///
+/// The acceleration is the same for all particles of the effect, and is applied
+/// each frame to modify the particle's velocity based on the simulation
+/// timestep.
+///
+/// ```txt
+/// particle.velocity += acceleration * simulation.delta_time;
+/// ```
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::VELOCITY`]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct AccelModifier {
+ /// The acceleration to apply to all particles in the effect each frame.
+ ///
+ /// Expression type: `Vec3`
+ accel: ExprHandle,
+}
+
+impl AccelModifier {
+ /// Create a new modifier from an acceleration expression.
+ pub fn new(accel: ExprHandle) -> Self {
+ Self { accel }
+ }
+
+ /// Create a new modifier with an acceleration derived from a property.
+ ///
+ /// To create a new property, use [`Module::add_property()`].
+ pub fn via_property(module: &mut Module, property: PropertyHandle) -> Self {
+ Self {
+ accel: module.prop(property),
+ }
+ }
+
+ /// Create a new modifier with a constant acceleration.
+ pub fn constant(module: &mut Module, acceleration: Vec3) -> Self {
+ Self {
+ accel: module.lit(acceleration),
+ }
+ }
+}
+
+impl Modifier for AccelModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Update
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ &[Attribute::VELOCITY]
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let attr = module.attr(Attribute::VELOCITY);
+ let attr = context.eval(module, attr)?;
+ let expr = context.eval(module, self.accel)?;
+ let dt = BuiltInExpr::new(crate::graph::BuiltInOperator::DeltaTime).eval(context)?;
+ context.main_code += &format!("{} += ({}) * {};", attr, expr, dt);
+ Ok(())
+ }
+}
+
+/// A modifier to apply a radial acceleration to all particles each frame.
+///
+/// The acceleration is the same for all particles of the effect, and is applied
+/// each frame to modify the particle's velocity based on the simulation
+/// timestep.
+///
+/// ```txt
+/// particle.velocity += acceleration * simulation.delta_time;
+/// ```
+///
+/// In the absence of other modifiers, the radial acceleration alone, if
+/// oriented toward the center point, makes particles move toward that center
+/// point. The radial direction is calculated as the direction from the modifier
+/// origin to the particle position.
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::POSITION`]
+/// - [`Attribute::VELOCITY`]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct RadialAccelModifier {
+ /// The center point the radial direction is calculated from.
+ ///
+ /// Expression type: `Vec3`
+ origin: ExprHandle,
+ /// The acceleration to apply to all particles in the effect each frame.
+ ///
+ /// Expression type: `f32`
+ accel: ExprHandle,
+}
+
+impl RadialAccelModifier {
+ /// Create a new modifier from an origin expression and an acceleration
+ /// expression.
+ pub fn new(origin: ExprHandle, accel: ExprHandle) -> Self {
+ Self { origin, accel }
+ }
+
+ /// Create a new modifier with an acceleration derived from a property.
+ ///
+ /// The origin of the sphere defining the radial direction is constant.
+ ///
+ /// To create a new property, use [`Module::add_property()`].
+ pub fn via_property(module: &mut Module, origin: Vec3, property: PropertyHandle) -> Self {
+ Self {
+ origin: module.lit(origin),
+ accel: module.prop(property),
+ }
+ }
+
+ /// Create a new modifier with a constant radial origin and acceleration.
+ pub fn constant(module: &mut Module, origin: Vec3, acceleration: f32) -> Self {
+ Self {
+ origin: module.lit(origin),
+ accel: module.lit(acceleration),
+ }
+ }
+}
+
+impl Modifier for RadialAccelModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Update
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ &[Attribute::POSITION, Attribute::VELOCITY]
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let func_id = calc_func_id(self);
+ let func_name = format!("radial_accel_{0:016X}", func_id);
+
+ context.make_fn(
+ &func_name,
+ "particle: ptr<function, Particle>",
+ None,
+ module,
+ &mut |m: &mut Module, ctx: &mut dyn EvalContext| -> Result<String, ExprError> {
+ let origin = ctx.eval(m, self.origin)?;
+ let accel = ctx.eval(m, self.accel)?;
+
+ Ok(format!(
+ r##"let radial = normalize((*particle).{} - {});
+ (*particle).{} += radial * (({}) * sim_params.delta_time);
+ "##,
+ Attribute::POSITION.name(),
+ origin,
+ Attribute::VELOCITY.name(),
+ accel,
+ ))
+ },
+ )?;
+
+ context.main_code += &format!("{}(&particle);\n", func_name);
+
+ Ok(())
+ }
+}
+
+/// A modifier to apply a tangential acceleration to all particles each frame.
+///
+/// The acceleration is the same for all particles of the effect, and is applied
+/// each frame to modify the particle's velocity based on the simulation
+/// timestep.
+///
+/// ```txt
+/// particle.velocity += acceleration * simulation.delta_time;
+/// ```
+///
+/// In the absence of other modifiers, the tangential acceleration alone makes
+/// particles rotate around the center point. The tangent direction is
+/// calculated as the cross product of the rotation plane axis and the direction
+/// from the modifier origin to the particle position. The effect is undefined
+/// if those two directions align.
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::POSITION`]
+/// - [`Attribute::VELOCITY`]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct TangentAccelModifier {
+ /// The center point the tangent direction is calculated from.
+ ///
+ /// Expression type: `Vec3`
+ origin: ExprHandle,
+ /// The axis defining the rotation plane and orientation.
+ ///
+ /// Expression type: `Vec3`
+ axis: ExprHandle,
+ /// The acceleration to apply to all particles in the effect each frame.
+ ///
+ /// Expression type: `f32`
+ accel: ExprHandle,
+}
+
+impl TangentAccelModifier {
+ /// Create a new modifier from origin and axis expressions, and an
+ /// acceleration expression.
+ pub fn new(origin: ExprHandle, axis: ExprHandle, accel: ExprHandle) -> Self {
+ Self {
+ origin,
+ axis,
+ accel,
+ }
+ }
+
+ /// Create a new modifier with an acceleration derived from a property.
+ ///
+ /// The origin and axis are constant.
+ ///
+ /// To create a new property, use [`Module::add_property()`].
+ pub fn via_property(
+ module: &mut Module,
+ origin: Vec3,
+ axis: Vec3,
+ property: PropertyHandle,
+ ) -> Self {
+ Self {
+ origin: module.lit(origin),
+ axis: module.lit(axis),
+ accel: module.prop(property),
+ }
+ }
+
+ /// Create a new modifier with constant values.
+ pub fn constant(module: &mut Module, origin: Vec3, axis: Vec3, acceleration: f32) -> Self {
+ Self {
+ origin: module.lit(origin),
+ axis: module.lit(axis),
+ accel: module.lit(acceleration),
+ }
+ }
+}
+
+impl Modifier for TangentAccelModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Update
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ &[Attribute::POSITION, Attribute::VELOCITY]
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let func_id = calc_func_id(self);
+ let func_name = format!("tangent_accel_{0:016X}", func_id);
+
+ let origin = context.eval(module, self.origin)?;
+ let axis = context.eval(module, self.axis)?;
+ let accel = context.eval(module, self.accel)?;
+
+ context.extra_code += &format!(
+ r##"fn {}(particle: ptr<function, Particle>) {{
+ let radial = normalize((*particle).{} - {});
+ let tangent = normalize(cross({}, radial));
+ (*particle).{} += tangent * (({}) * sim_params.delta_time);
+}}
+"##,
+ func_name,
+ Attribute::POSITION.name(),
+ origin,
+ axis,
+ Attribute::VELOCITY.name(),
+ accel,
+ );
+
+ context.main_code += &format!("{}(&particle);\n", func_name);
+
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{ParticleLayout, Property, PropertyLayout, TextureLayout, ToWgslString};
+
+ #[test]
+ fn mod_accel() {
+ let mut module = Module::default();
+ let accel = Vec3::new(1., 2., 3.);
+ let modifier = AccelModifier::constant(&mut module, accel);
+
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ assert!(modifier.apply(&mut module, &mut context).is_ok());
+
+ assert!(context.main_code.contains(&accel.to_wgsl_string()));
+ }
+
+ #[test]
+ fn mod_radial_accel() {
+ let mut module = Module::default();
+ let property_layout = PropertyLayout::new(&[Property::new("my_prop", 3.)]);
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+
+ let origin = Vec3::new(-1.2, 5.3, -8.5);
+ let accel = 6.;
+ let modifier = RadialAccelModifier::constant(&mut module, origin, accel);
+ let mut context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ assert!(modifier.apply(&mut module, &mut context).is_ok());
+ // TODO: less weak check...
+ assert!(context.extra_code.contains(&accel.to_wgsl_string()));
+
+ let origin = module.attr(Attribute::POSITION);
+ let my_prop = module.add_property("my_prop", 3.0.into());
+ let accel = module.prop(my_prop);
+ let modifier = RadialAccelModifier::new(origin, accel);
+ let mut context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ assert!(modifier.apply(&mut module, &mut context).is_ok());
+ // TODO: less weak check...
+ assert!(context.extra_code.contains(Attribute::POSITION.name()));
+ assert!(context.extra_code.contains("my_prop"));
+ }
+
+ #[test]
+ fn mod_tangent_accel() {
+ let mut module = Module::default();
+ let origin = Vec3::new(-1.2, 5.3, -8.5);
+ let axis = Vec3::Y;
+ let accel = 6.;
+ let modifier = TangentAccelModifier::constant(&mut module, origin, axis, accel);
+
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ assert!(modifier.apply(&mut module, &mut context).is_ok());
+
+ // TODO: less weak check...
+ assert!(context.extra_code.contains(&accel.to_wgsl_string()));
+ }
+}
diff --git a/vendor/bevy_hanabi/src/modifier/attr.rs b/vendor/bevy_hanabi/src/modifier/attr.rs
new file mode 100644
index 00000000..fe85d67b
--- /dev/null
+++ b/vendor/bevy_hanabi/src/modifier/attr.rs
@@ -0,0 +1,236 @@
+//! Modifiers to manipulate a particle's attributes.
+//!
+//! Attribute modifiers initialize or update during simulation the attributes of
+//! all particles of an effect. The provide the core functionality for
+//! per-particle diversity / randomness, as attributes are the only quantities
+//! stored per particle.
+
+use bevy::prelude::*;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ graph::{EvalContext, ExprError},
+ Attribute, BoxedModifier, ExprHandle, Modifier, ModifierContext, Module, ShaderWriter,
+};
+
+/// A modifier to assign a value to a particle attribute.
+///
+/// This modifier sets the value of an [`Attribute`] of the particle of a system
+/// to a given graph expression, either when the particle spawns (if used as an
+/// init modifier) or each frame when the particle is simulated (if used as an
+/// update modifier).
+///
+/// This is a basic building block to create any complex effect. Most other init
+/// modifiers are convenience helpers to achieve a behavior which can otherwise
+/// be produced, more verbosely, by setting the individual attributes of a
+/// particle with instances of this modifier.
+///
+/// # Example
+///
+/// ```
+/// # use bevy::math::Vec3;
+/// # use bevy_hanabi::*;
+/// let mut module = Module::default();
+///
+/// // Set the position of the particle to (0,0,0) on spawn.
+/// let pos = module.lit(Vec3::ZERO);
+/// let init_pos = SetAttributeModifier::new(Attribute::POSITION, pos);
+///
+/// // Each frame, assign the value of the "my_velocity" property to the velocity
+/// // of the particle. The property is assigned from CPU, and uploaded to GPU
+/// // automatically when its value changed.
+/// let my_velocity = module.add_property("my_velocity", Vec3::ZERO.into());
+/// let vel = module.prop(my_velocity);
+/// let update_vel = SetAttributeModifier::new(Attribute::VELOCITY, vel);
+/// ```
+///
+/// # Warning
+///
+/// At the minute there is no validation that the type of the value is the same
+/// as the type of the attribute. Users are advised to be careful, until more
+/// safeguards are added.
+///
+/// # Attributes
+///
+/// This modifier requires the attribute specified in the `attribute` field.
+#[derive(Debug, Clone, Copy, PartialEq, Reflect, Serialize, Deserialize)]
+pub struct SetAttributeModifier {
+ /// The attribute to initialize.
+ ///
+ /// See [`Attribute`] for the list of available attributes.
+ pub attribute: Attribute,
+ /// The initial value of the attribute.
+ ///
+ /// Expression type: same as the attribute.
+ pub value: ExprHandle,
+}
+
+impl SetAttributeModifier {
+ /// Create a new instance of a [`SetAttributeModifier`].
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy::math::Vec3;
+ /// # use bevy_hanabi::*;
+ /// let mut module = Module::default();
+ /// let pos = module.lit(Vec3::ZERO);
+ /// let init_pos = SetAttributeModifier::new(Attribute::POSITION, pos);
+ /// ```
+ pub fn new(attribute: Attribute, value: ExprHandle) -> Self {
+ assert!(
+ attribute != Attribute::ID,
+ "The particle's ID is a read-only pseudo-attribute, cannot be assigned."
+ );
+ assert!(
+ attribute != Attribute::PARTICLE_COUNTER,
+ "The PARTICLE_COUNTER attribute is a read-only pseudo-attribute, cannot be assigned."
+ );
+ Self { attribute, value }
+ }
+
+ fn eval(
+ &self,
+ module: &mut Module,
+ context: &mut dyn EvalContext,
+ ) -> Result<String, ExprError> {
+ // Validate if possible that the expression produces the same type expected by
+ // the attribute. This makes it much easier to diagnose issues.
+ let expr = module.try_get(self.value)?;
+ if let Some(value_type) = expr.value_type() {
+ let attr_value_type = self.attribute.value_type();
+ if value_type != attr_value_type {
+ return Err(ExprError::TypeError(format!(
+ "Mismatching expression type in SetAttributeModifer: attribute '{}' requires an expression producing a value of type {}, but a value of type {} was produced instead",
+ self.attribute.name().to_uppercase(), attr_value_type, value_type)));
+ }
+ }
+
+ // Generate the code
+ let attr = module.attr(self.attribute);
+ let attr = context.eval(module, attr)?;
+ let expr = context.eval(module, self.value)?;
+ Ok(format!("{} = {};\n", attr, expr))
+ }
+}
+
+impl Modifier for SetAttributeModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Init | ModifierContext::Update
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ std::slice::from_ref(&self.attribute)
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let code = self.eval(module, context)?;
+ context.main_code += &code;
+ Ok(())
+ }
+}
+
+/// Inherit the value of the given attribute when spawning a new particle.
+///
+/// This init modifier is used when spawning particles from other particles. The
+/// attribute is inherited from the source particle by reading its value from
+/// the previous frame's update pass and using that value to initialize the
+/// particle being spawned. The source particle is the particle of the parent
+/// effect which emitted the GPU spawn event this particle is spawned from. The
+/// effect instance must have an [`EffectParent`] to declare its parent effect.
+///
+/// [`EffectParent`]: crate::EffectParent
+#[derive(Debug, Clone, Copy, PartialEq, Reflect, Serialize, Deserialize)]
+pub struct InheritAttributeModifier {
+ /// The attribute to inherit.
+ ///
+ /// See [`Attribute`] for the list of available attributes. The attribute
+ /// must be present on the parent particle, and is added to the particles of
+ /// the current effect too. During the init pass, the parent value is copied
+ /// into the attribute of the newly spawned particle.
+ pub attribute: Attribute,
+}
+
+impl InheritAttributeModifier {
+ /// Create a new instance of a [`InheritAttributeModifier`].
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy::math::Vec3;
+ /// # use bevy_hanabi::*;
+ /// // Inherit the position of the parent particle which spawned this particle
+ /// let inherit_pos = InheritAttributeModifier::new(Attribute::POSITION);
+ /// ```
+ pub fn new(attribute: Attribute) -> Self {
+ Self { attribute }
+ }
+
+ fn eval(
+ &self,
+ module: &mut Module,
+ context: &mut dyn EvalContext,
+ ) -> Result<String, ExprError> {
+ let attr = module.attr(self.attribute);
+ let attr = context.eval(module, attr)?;
+ Ok(format!(
+ "{} = parent_particle.{};\n",
+ attr,
+ self.attribute.name()
+ ))
+ }
+}
+
+impl Modifier for InheritAttributeModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Init
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ std::slice::from_ref(&self.attribute)
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let code = self.eval(module, context)?;
+ context.main_code += &code;
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::SetAttributeModifier;
+ use crate::{
+ Attribute, ExprError, ModifierContext, Module, ParticleLayout, PropertyLayout,
+ ShaderWriter, TextureLayout,
+ };
+
+ #[test]
+ fn eval_validate() {
+ let mut module = Module::default();
+ let attr = Attribute::POSITION; // vec3<f32>
+ let expr = module.lit(3.); // f32
+ let attr = SetAttributeModifier::new(attr, expr);
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ assert!(matches!(
+ attr.eval(&mut module, &mut context),
+ Err(ExprError::TypeError(_))
+ ));
+ }
+}
diff --git a/vendor/bevy_hanabi/src/modifier/force.rs b/vendor/bevy_hanabi/src/modifier/force.rs
new file mode 100644
index 00000000..25a0b347
--- /dev/null
+++ b/vendor/bevy_hanabi/src/modifier/force.rs
@@ -0,0 +1,324 @@
+//! Modifiers to apply forces to the particles.
+//!
+//! The forces are applied as accelerations times unit mass, as particles
+//! currently do not have a mass.
+
+use std::hash::Hash;
+
+use bevy::prelude::*;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ calc_func_id,
+ graph::{BuiltInOperator, EvalContext, ExprError},
+ Attribute, BoxedModifier, ExprHandle, Modifier, ModifierContext, Module, ShaderWriter,
+};
+
+/// A modifier to apply a force to the particle which makes it conform ("stick")
+/// to the surface of a sphere.
+///
+/// This modifies the [`Attribute::VELOCITY`] of the particle to make it
+/// converge to the surface of the sphere, while keeping its tangent velocity
+/// component unchanged. This modifier gives best results when it's the last
+/// modifier affecting the particle velocity; otherwise subsequent modifiers
+/// might interfere and break the correction factor calculated by this modifier.
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::POSITION`]
+/// - [`Attribute::VELOCITY`]
+///
+/// # Functioning
+///
+/// The modifier applies a correction to the radial component of the particle's
+/// velocity, either to draw it toward the surface if it's within the zone of
+/// influence of the modifier but too far from the surface, or to make it stick
+/// to the surface if it's already in its vicinity.
+///
+/// ![Conform to sphere](https://raw.githubusercontent.com/djeedai/bevy_hanabi/fa23246e8430e0f29ed0a180d8ea6916b3534789/docs/conform-to-sphere.png)
+///
+/// When inside the area of influence defined by [`influence_dist`], particles
+/// are accelerated by the [`attraction_accel`] alongside the radial direction
+/// toward the sphere center. This effectively makes the particle move closer to
+/// the sphere surface. The particle's velocity is clamped by
+/// [`max_attraction_speed`] to prevent it from accelerating infinitely.
+///
+/// Once the particle arrives in the vicinity of the sphere, an more precisely
+/// inside a "shell" area around the sphere surface, the behavior is tweaked a
+/// bit. That shell area is defined as the area at a distance of
+/// [`shell_half_thickness`] from the sphere surface. The attraction
+/// acceleration in the shell area is increased by a [`sticky_factor`], which
+/// prevents fast moving particles from overshooting their target and passing
+/// through the sphere surface to the other side, oscillating around the surface
+/// with each new correction. The shell area effectively acts as a tolerance
+/// area, where particles inside it are considered to be "around" the sphere
+/// surface. This prevents numerical instabilities trying to conform exactly to
+/// the (infinitely thin) surface while also moving tangentially to it. For this
+/// reason, particles inside the shell area are on average located on the
+/// surface of the sphere, but may wobble around this average. For this reason,
+/// it's best to keep the shell thickness tiny, so this wobbling is not visible.
+///
+/// Particles outside of the area of influence are entirely unaffected.
+///
+/// [`influence_dist`]: crate::ConformToSphereModifier::influence_dist
+/// [`attraction_accel`]: crate::ConformToSphereModifier::attraction_accel
+/// [`max_attraction_speed`]: crate::ConformToSphereModifier::max_attraction_speed
+/// [`shell_half_thickness`]: crate::ConformToSphereModifier::shell_half_thickness
+/// [`sticky_factor`]: crate::ConformToSphereModifier::sticky_factor
+#[derive(Debug, Clone, Copy, PartialEq, Hash, Reflect, Serialize, Deserialize)]
+pub struct ConformToSphereModifier {
+ /// The sphere origin (`Vec3`), in [simulation
+ /// space](crate::SimulationSpace).
+ ///
+ /// This is the point toward which particles are attracted.
+ pub origin: ExprHandle,
+ /// The sphere radius (`f32`).
+ ///
+ /// This is the distance from the sphere origin, and defines the surface to
+ /// which particles conform ("stick").
+ pub radius: ExprHandle,
+ /// The influence distance of this attractor (`f32`).
+ ///
+ /// Particles located at a distance greater than this from the sphere
+ /// surface are not affected by this modifier. This effectively limits
+ /// the effect to a sphere of influence with a radius equal to the
+ /// sphere radius plus this influence distance.
+ ///
+ /// Note that particles located inside the sphere are always influenced.
+ ///
+ /// [`radius`]: ConformToSphereModifier::radius
+ pub influence_dist: ExprHandle,
+ /// Acceleration applied to particles to attract them (`f32`).
+ ///
+ /// Particles in the area of influence of the effect are accelerated by this
+ /// value toward the sphere surface.
+ ///
+ /// Note that because this is an acceleration, all particles are accelerated
+ /// identically. If you want the per-particle mass to have an effect on the
+ /// attraction effect, assign to this acceleration a constant force divided
+ /// by the per-particle mass. That way heavier particles will accelerate
+ /// more slowly, having more inertia.
+ pub attraction_accel: ExprHandle,
+ /// Maximum speed of attraction toward the sphere surface (`f32`).
+ ///
+ /// This value clamps the radial speed of particles being attracted toward
+ /// the sphere surface. Any particle with a radial velocity larger than this
+ /// gets immediately slowed down to this value. This prevents particles from
+ /// accelerating infinitely. This effectively simulates some kind of drag
+ /// effect.
+ pub max_attraction_speed: ExprHandle,
+ /// Optional shell half-thickness defining the conforming tolerance (`f32`).
+ ///
+ /// This is an advanced use parameter. Most users can ignore it. If not
+ /// specified (`None`), a default value is assigned which works in most
+ /// cases.
+ ///
+ /// Particles located close to the sphere surface tend to oscillate around
+ /// it, due to the nature of the linear correction applied to the particle
+ /// velocity, and numerical errors. This can cause numerical instabilities
+ /// and visual jitter. To prevent this, the correction factor is smoothed
+ /// out toward zero in a shell around the sphere surface. Inside that shell,
+ /// the velocity correction factor is reduced, which allows particle to not
+ /// strictly conform to the sphere as long as they remain inside this area.
+ pub shell_half_thickness: Option<ExprHandle>,
+ /// Optional "stickiness" acceleration factor (`f32`).
+ ///
+ /// This is an advanced use parameter. Most users can ignore it. If not
+ /// specified (`None`), a default value is assigned which works in most
+ /// cases.
+ ///
+ /// When particles enter the tolerance shell area, the attraction
+ /// acceleration is amplified by this factor to improve the "stickiness" to
+ /// the ideal sphere surface. The default value if not specified is `2.0`.
+ /// Increasing this value makes the particles instantly "stick" to the
+ /// sphere surface, which may be desirable to avoid an "overshoot" effect
+ /// when particles approach the conforming sphere surface too fast, but
+ /// may also look un-natural depending on the effect.
+ pub sticky_factor: Option<ExprHandle>,
+}
+
+impl ConformToSphereModifier {
+ /// Create a new modifier.
+ pub fn new(
+ origin: ExprHandle,
+ radius: ExprHandle,
+ influence_dist: ExprHandle,
+ attraction_accel: ExprHandle,
+ max_attraction_speed: ExprHandle,
+ ) -> Self {
+ Self {
+ origin,
+ radius,
+ influence_dist,
+ attraction_accel,
+ max_attraction_speed,
+ shell_half_thickness: None,
+ sticky_factor: None,
+ }
+ }
+}
+
+impl Modifier for ConformToSphereModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Update
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ &[Attribute::POSITION, Attribute::VELOCITY]
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let func_id = calc_func_id(self);
+ let func_name = format!("force_field_{0:016X}", func_id);
+
+ context.make_fn(
+ &func_name,
+ "particle: ptr<function, Particle>",
+ None,
+ module,
+ &mut |m: &mut Module, ctx: &mut dyn EvalContext| -> Result<String, ExprError> {
+ let origin = ctx.eval(m, self.origin)?;
+ let radius = ctx.eval(m, self.radius)?;
+ let influence_dist = ctx.eval(m, self.influence_dist)?;
+ let shell_half_thickness = if let Some(shell_half_thickness) = self.shell_half_thickness { ctx.eval(m, shell_half_thickness)? } else { "0.1".to_string() };
+ let max_attraction_speed = ctx.eval(m, self.max_attraction_speed)?;
+ let attraction_accel = ctx.eval(m, self.attraction_accel)?;
+ let sticky_factor = if let Some(sticky_factor) = self.sticky_factor { ctx.eval(m, sticky_factor)? } else { "2.0".to_string() };
+
+ let attr_pos = format!("(*particle).{}", Attribute::POSITION.name());
+ let attr_vel = format!("(*particle).{}", Attribute::VELOCITY.name());
+
+ Ok(format!(
+ r##" // Sphere center
+ let c = {origin};
+ // Sphere radius
+ let r = {radius};
+ // Distance and direction to origin (sphere center)
+ let rel_pos = c - {attr_pos};
+ let origin_dist = length(rel_pos);
+ let origin_dir = normalize(rel_pos);
+ // Signed distance to sphere surface, negative if inside sphere
+ let surface_dist = origin_dist - r;
+ // Influence distance
+ let influence_dist = {influence_dist};
+ if (surface_dist > influence_dist) {{
+ return;
+ }}
+ // Current signed radial speed (normal to sphere surface) toward the sphere center, which needs to be
+ // corrected to conform to the sphere.
+ let cur_radial_speed = dot({attr_vel}, origin_dir);
+ // Signed radial speed (toward the sphere center) at which we'd like to move to stick to the surface.
+ // This is smoothed out to zero as the distance to the surface gets close to zero, to prevent numerical
+ // oscillations around the surface.
+ let shell_half_thickness = {shell_half_thickness};
+ let shell_factor = smoothstep(0., shell_half_thickness, abs(surface_dist));
+ let max_attraction_speed = {max_attraction_speed};
+ let max_radial_speed = sign(surface_dist) * shell_factor * max_attraction_speed;
+ // Delta radial speed to reach the ideal value
+ let delta_speed = max_radial_speed - cur_radial_speed;
+ // Conforming delta speed from attraction acceleration
+ let attraction_accel = {attraction_accel};
+ let sticky_accel = attraction_accel * {sticky_factor};
+ let conforming_accel = mix(sticky_accel, attraction_accel, shell_factor);
+ let conforming_delta_speed = sim_params.delta_time * conforming_accel;
+ // Final impulse clamped by the maximum acceleration speed
+ {attr_vel} += sign(delta_speed) * min(abs(delta_speed), conforming_delta_speed) * origin_dir;
+"##
+ ))
+ },
+ )?;
+
+ context.main_code += &format!("{}(&particle);\n", func_name);
+
+ Ok(())
+ }
+}
+
+/// A modifier to apply a linear drag force to all particles each frame. The
+/// force slows down the particles without changing their direction.
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::VELOCITY`]
+#[derive(Debug, Clone, Copy, Reflect, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub struct LinearDragModifier {
+ /// Drag coefficient. Higher values increase the drag force, and
+ /// consequently decrease the particle's speed faster.
+ ///
+ /// Expression type: `f32`
+ pub drag: ExprHandle,
+}
+
+impl LinearDragModifier {
+ /// Create a new modifier from a drag expression.
+ pub fn new(drag: ExprHandle) -> Self {
+ Self { drag }
+ }
+
+ /// Instantiate a [`LinearDragModifier`] with a constant drag value.
+ pub fn constant(module: &mut Module, drag: f32) -> Self {
+ Self {
+ drag: module.lit(drag),
+ }
+ }
+}
+
+impl Modifier for LinearDragModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Update
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ &[Attribute::VELOCITY]
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let m = module;
+ let attr = m.attr(Attribute::VELOCITY);
+ let dt = m.builtin(BuiltInOperator::DeltaTime);
+ let drag_dt = m.mul(self.drag, dt);
+ let one = m.lit(1.);
+ let one_minus_drag_dt = m.sub(one, drag_dt);
+ let zero = m.lit(0.);
+ let expr = m.max(zero, one_minus_drag_dt);
+ let attr = context.eval(m, attr)?;
+ let expr = context.eval(m, expr)?;
+ context.main_code += &format!("{} *= {};", attr, expr);
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{ParticleLayout, PropertyLayout, TextureLayout};
+
+ #[test]
+ fn mod_drag() {
+ let mut module = Module::default();
+ let modifier = LinearDragModifier::constant(&mut module, 3.5);
+
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ assert!(modifier.apply(&mut module, &mut context).is_ok());
+
+ assert!(context.main_code.contains("3.5")); // TODO - less weak check
+ }
+}
diff --git a/vendor/bevy_hanabi/src/modifier/kill.rs b/vendor/bevy_hanabi/src/modifier/kill.rs
new file mode 100644
index 00000000..4d074ede
--- /dev/null
+++ b/vendor/bevy_hanabi/src/modifier/kill.rs
@@ -0,0 +1,303 @@
+//! Modifiers to kill particles under specific conditions.
+//!
+//! These modifiers control the despawning (killing) of particles meeting
+//! specific conditions, like entering or leaving an area in space.
+
+use bevy::prelude::*;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ calc_func_id,
+ graph::{EvalContext, ExprError},
+ Attribute, BoxedModifier, ExprHandle, Modifier, ModifierContext, Module, ShaderWriter,
+};
+
+/// A modifier killing all particles that enter or exit a sphere.
+///
+/// This enables confining particles to a region in space, or preventing
+/// particles to enter that region.
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::POSITION`]
+#[derive(Debug, Clone, Copy, Reflect, Serialize, Deserialize)]
+pub struct KillSphereModifier {
+ /// Center of the sphere.
+ ///
+ /// Expression type: `Vec3`
+ pub center: ExprHandle,
+ /// Squared radius of the sphere.
+ ///
+ /// This is the sphere radius multiplied with itself. Storing the squared
+ /// radius makes it more performant for simulation.
+ ///
+ /// Expression type: `f32`
+ pub sqr_radius: ExprHandle,
+ /// If `true`, invert the kill condition and kill all particles inside the
+ /// AABB. If `false` (default), kill all particles outside the AABB.
+ pub kill_inside: bool,
+}
+
+impl KillSphereModifier {
+ /// Create a new instance of an [`KillSphereModifier`] from a sphere center
+ /// and squared radius.
+ ///
+ /// The e
+ ///
+ /// The created instance has a default `kill_inside = false` value.
+ pub fn new(center: ExprHandle, sqr_radius: ExprHandle) -> Self {
+ Self {
+ center,
+ sqr_radius,
+ kill_inside: false,
+ }
+ }
+
+ /// Set whether particles are killed when inside the AABB or not.
+ pub fn with_kill_inside(mut self, kill_inside: bool) -> Self {
+ self.kill_inside = kill_inside;
+ self
+ }
+}
+
+impl Modifier for KillSphereModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Update
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ &[Attribute::POSITION]
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let pos = module.attr(Attribute::POSITION);
+ let diff = module.sub(pos, self.center);
+ let sqr_dist = module.dot(diff, diff);
+ let cmp = if self.kill_inside {
+ module.lt(sqr_dist, self.sqr_radius)
+ } else {
+ module.gt(sqr_dist, self.sqr_radius)
+ };
+ let expr = context.eval(module, cmp)?;
+
+ context.main_code += &format!(
+ r#"if ({}) {{
+ is_alive = false;
+}}
+"#,
+ expr
+ );
+
+ Ok(())
+ }
+}
+
+/// A modifier killing all particles that enter or exit an AABB.
+///
+/// This enables confining particles to a region in space, or preventing
+/// particles to enter that region.
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::POSITION`]
+#[derive(Debug, Clone, Copy, Reflect, Serialize, Deserialize)]
+pub struct KillAabbModifier {
+ /// Center of the AABB.
+ ///
+ /// Expression type: `Vec3`
+ pub center: ExprHandle,
+ /// Half-size of the AABB.
+ ///
+ /// Expression type: `Vec3`
+ pub half_size: ExprHandle,
+ /// If `true`, invert the kill condition and kill all particles inside the
+ /// AABB. If `false` (default), kill all particles outside the AABB.
+ pub kill_inside: bool,
+}
+
+impl KillAabbModifier {
+ /// Create a new instance of an [`KillAabbModifier`] from an AABB center and
+ /// half extents.
+ ///
+ /// The created instance has a default `kill_inside = false` value.
+ pub fn new(center: impl Into<ExprHandle>, half_size: impl Into<ExprHandle>) -> Self {
+ Self {
+ center: center.into(),
+ half_size: half_size.into(),
+ kill_inside: false,
+ }
+ }
+
+ /// Set whether particles are killed when inside the AABB or not.
+ pub fn with_kill_inside(mut self, kill_inside: bool) -> Self {
+ self.kill_inside = kill_inside;
+ self
+ }
+}
+
+impl Modifier for KillAabbModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Update
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ &[Attribute::POSITION]
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let pos = module.attr(Attribute::POSITION);
+ let diff = module.sub(pos, self.center);
+ let dist = module.abs(diff);
+ let cmp = if self.kill_inside {
+ module.lt(dist, self.half_size)
+ } else {
+ module.gt(dist, self.half_size)
+ };
+ let reduce = if self.kill_inside {
+ module.all(cmp)
+ } else {
+ module.any(cmp)
+ };
+ let expr = context.eval(module, reduce)?;
+
+ context.main_code += &format!(
+ r#"if ({}) {{
+ is_alive = false;
+}}
+"#,
+ expr
+ );
+
+ Ok(())
+ }
+}
+
+/// A modifier killing all particles that exit the camera's frustum.
+///
+/// This ensures camera moving off-screen (not visible) are immediately killed,
+/// to avoid simulating them for nothing. The camera frustum is read from the
+/// (unique) camera tagged with the [`HanabiMainCamera`] component; if this
+/// component is missing, this modifier does nothing.
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::POSITION`]
+#[derive(Debug, Default, Clone, Copy, Hash, Reflect, Serialize, Deserialize)]
+pub struct KillFrustumModifier {
+ /// Optional distance threshold (defaults to 0) the particle is allowed to
+ /// be at outside the frustum planes before being killed. This ensures that
+ /// _e.g._ a shaking camera won't kill particles at the edge of the screen,
+ /// before moving back to the area where the particle was, which could
+ /// effectively make the user "see" that they disappeared. The value can be
+ /// negative, but this will shrink the frustum inside the view, and will
+ /// kill particles still visible on screen, so is strongly discouraged.
+ pub threshold: Option<ExprHandle>,
+}
+
+impl KillFrustumModifier {
+ /// Create a new instance of an [`KillFrustumModifier`].
+ ///
+ /// The created instance has a default `threshold = 0.0` value.
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Set the distance threshold from the camera frustum plances, that is the
+ /// distance outside of the screen that particles are allowed to be before
+ /// they're killed.
+ pub fn with_threshold(mut self, threshold: impl Into<ExprHandle>) -> Self {
+ self.threshold = Some(threshold.into());
+ self
+ }
+}
+
+impl Modifier for KillFrustumModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Update
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ &[Attribute::POSITION]
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let func_id = calc_func_id(self);
+ let func_name = format!("kill_frustum_{0:016X}", func_id);
+
+ context.make_fn(
+ &func_name,
+ "particle: ptr<function, Particle>",
+ Some("bool"),
+ module,
+ &mut |m: &mut Module, ctx: &mut dyn EvalContext| -> Result<String, ExprError> {
+ let threshold = if let Some(threshold) = self.threshold {
+ ctx.eval(m, threshold)?
+ } else {
+ "0.0".to_string()
+ };
+
+ Ok(format!(
+ r##" let p = transform_position_simulation_to_world((*particle).{0}).xyz;
+ let threshold = {1};
+ for (var i = 0; i < 6; i += 1) {{
+ if (dot(sim_params.frustum[i].xyz, p) + sim_params.frustum[i].w + threshold <= 0) {{
+ return true;
+ }}
+ }}
+ return false;
+"##,
+ Attribute::POSITION.name(),
+ threshold
+ ))
+ },
+ )?;
+
+ context.main_code +=
+ &format!("if ({func_name}(&particle)) {{\n is_alive = false;\n}}\n");
+
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{ParticleLayout, PropertyLayout, TextureLayout};
+
+ #[test]
+ fn mod_kill_aabb() {
+ let mut module = Module::default();
+ let center = module.lit(Vec3::ZERO);
+ let half_size = module.lit(Vec3::ONE);
+ let modifier = KillAabbModifier::new(center, half_size);
+
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ assert!(modifier.apply(&mut module, &mut context).is_ok());
+
+ assert!(context.main_code.contains("is_alive = false")); // TODO - less
+ // weak check
+ }
+}
diff --git a/vendor/bevy_hanabi/src/modifier/mod.rs b/vendor/bevy_hanabi/src/modifier/mod.rs
new file mode 100644
index 00000000..d6c7b8ee
--- /dev/null
+++ b/vendor/bevy_hanabi/src/modifier/mod.rs
@@ -0,0 +1,1479 @@
+//! Building blocks to create a visual effect.
+//!
+//! A **modifier** is a building block used to define the behavior of an effect.
+//! Particles effects are composed of multiple modifiers, which put together and
+//! configured produce the desired visual effect. Each modifier changes a
+//! specific part of the behavior of an effect. Modifiers are grouped in three
+//! categories:
+//!
+//! - **Init modifiers** influence the initializing of particles when they
+//! spawn. They typically configure the initial position and/or velocity of
+//! particles. Init modifiers implement the [`Modifier`] trait, and act on the
+//! [`ModifierContext::Init`] modifier context.
+//! - **Update modifiers** influence the particle update loop each frame. For
+//! example, an update modifier can apply a gravity force to all particles.
+//! Update modifiers implement the [`Modifier`] trait, and act on the
+//! [`ModifierContext::Update`] modifier context.
+//! - **Render modifiers** influence the rendering of each particle. They can
+//! change the particle's color, or orient it to face the camera. Render
+//! modifiers implement the [`RenderModifier`] trait, and act on the
+//! [`ModifierContext::Render`] modifier context.
+//!
+//! A single modifier can be part of multiple categories. For example, the
+//! [`SetAttributeModifier`] can be used either to initialize a particle's
+//! attribute on spawning, or to assign a value to that attribute each frame
+//! during simulation (update).
+//!
+//! # Modifiers and expressions
+//!
+//! Modifiers are configured by assigning values to their field(s). Some values
+//! are compile-time constants, like which attribute a [`SetAttributeModifier`]
+//! mutates. Others however can take the form of
+//! [expressions](crate::graph::expr), which form a mini language designed to
+//! emit shader code and provide extended customization. For example, a 3D
+//! vector position can be assigned to a [property](crate::properties) and
+//! mutated each frame, giving CPU-side control over the behavior of the GPU
+//! particle effect. See [expressions](crate::graph::expr) for more details.
+//!
+//! # Limitations
+//!
+//! At this time, serialization and deserialization of modifiers is not
+//! supported on Wasm. This means assets authored and saved on a non-Wasm target
+//! cannot be read back into an application running on Wasm.
+
+use std::{
+ collections::hash_map::DefaultHasher,
+ hash::{Hash, Hasher},
+};
+
+use bevy::{
+ asset::Handle,
+ ecs::reflect::AppTypeRegistry,
+ image::Image,
+ math::{UVec2, Vec3, Vec4},
+ platform::collections::HashMap,
+ reflect::Reflect,
+};
+use bitflags::bitflags;
+use serde::{Deserialize, Serialize};
+
+pub mod accel;
+pub mod attr;
+pub mod force;
+pub mod kill;
+pub mod output;
+pub mod position;
+pub mod registry;
+pub mod velocity;
+
+pub use accel::*;
+pub use attr::*;
+pub use force::*;
+pub use kill::*;
+pub use output::*;
+pub use position::*;
+pub use registry::*;
+pub use velocity::*;
+
+use crate::{
+ Attribute, EvalContext, ExprError, ExprHandle, Gradient, Module, ParticleLayout,
+ PropertyLayout, TextureLayout,
+};
+
+/// The dimension of a shape to consider.
+///
+/// The exact meaning depends on the context where this enum is used.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub enum ShapeDimension {
+ /// Consider the surface of the shape only.
+ #[default]
+ Surface,
+ /// Consider the entire shape volume.
+ Volume,
+}
+
+/// Calculate a function ID by hashing the given value representative of the
+/// function.
+pub(crate) fn calc_func_id<T: Hash>(value: &T) -> u64 {
+ let mut hasher = DefaultHasher::new();
+ value.hash(&mut hasher);
+ hasher.finish()
+}
+
+bitflags! {
+ /// Context a modifier applies to.
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ pub struct ModifierContext : u8 {
+ /// Particle initializing on spawning.
+ ///
+ /// Modifiers in the init context are executed for each newly spawned
+ /// particle, to initialize that particle.
+ const Init = 0b001;
+ /// Particle simulation (update).
+ ///
+ /// Modifiers in the update context are executed each frame to simulate
+ /// the particle behavior.
+ const Update = 0b010;
+ /// Particle rendering.
+ ///
+ /// Modifiers in the render context are executed for each view (camera)
+ /// where a particle is visible, each frame.
+ const Render = 0b100;
+ }
+}
+
+impl std::fmt::Display for ModifierContext {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut s = if self.contains(ModifierContext::Init) {
+ "Init".to_string()
+ } else {
+ String::new()
+ };
+ if self.contains(ModifierContext::Update) {
+ if s.is_empty() {
+ s = "Update".to_string();
+ } else {
+ s += " | Update";
+ }
+ }
+ if self.contains(ModifierContext::Render) {
+ if s.is_empty() {
+ s = "Render".to_string();
+ } else {
+ s += " | Render";
+ }
+ }
+ if s.is_empty() {
+ s = "None".to_string();
+ }
+ write!(f, "{}", s)
+ }
+}
+
+/// Trait describing a modifier customizing an effect pipeline.
+pub trait Modifier: Reflect + Send + Sync + 'static {
+ /// Get the context this modifier applies to.
+ fn context(&self) -> ModifierContext;
+
+ /// Try to cast this modifier to a [`RenderModifier`].
+ fn as_render(&self) -> Option<&dyn RenderModifier> {
+ None
+ }
+
+ /// Try to cast this modifier to a [`RenderModifier`].
+ fn as_render_mut(&mut self) -> Option<&mut dyn RenderModifier> {
+ None
+ }
+
+ /// Try to convert this modifier to a [`RenderModifier`].
+ fn into_boxed_render(self: Box<Self>) -> Option<Box<dyn RenderModifier>> {
+ None
+ }
+
+ /// Get the list of attributes required for this modifier to be used.
+ fn attributes(&self) -> &[Attribute];
+
+ /// Clone self.
+ fn boxed_clone(&self) -> BoxedModifier;
+
+ /// Apply the modifier to generate code.
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError>;
+}
+
+/// Boxed version of [`Modifier`].
+pub type BoxedModifier = Box<dyn Modifier>;
+
+impl Clone for BoxedModifier {
+ fn clone(&self) -> Self {
+ self.boxed_clone()
+ }
+}
+
+/// Shader code writer.
+///
+/// Writer utility to generate shader code. The writer works in a defined
+/// context, for a given [`ModifierContext`] and a particular effect setup
+/// ([`ParticleLayout`] and [`PropertyLayout`]).
+#[derive(Debug, PartialEq)]
+pub struct ShaderWriter<'a> {
+ /// Main shader compute code emitted.
+ ///
+ /// This is the WGSL code emitted into the target [`ModifierContext`]. The
+ /// context dictates what variables are available (this is currently
+ /// implicit and requires knownledge of the target context; there's little
+ /// validation that the emitted code is valid).
+ pub main_code: String,
+ /// Extra functions emitted at shader top level.
+ ///
+ /// This contains optional WGSL code emitted at shader top level. This
+ /// generally contains functions called from `main_code`.
+ pub extra_code: String,
+ /// Layout of properties for the current effect.
+ pub property_layout: &'a PropertyLayout,
+ /// Layout of attributes of a particle for the current effect.
+ pub particle_layout: &'a ParticleLayout,
+ /// Layout of textures for the current effect.
+ pub texture_layout: &'a TextureLayout,
+ /// Modifier context the writer is being used from.
+ modifier_context: ModifierContext,
+ /// Counter for unique variable names.
+ var_counter: u32,
+ /// Cache of evaluated expressions.
+ expr_cache: HashMap<ExprHandle, String>,
+ /// Is the attribute struct a pointer?
+ is_attribute_pointer: bool,
+ /// Is the shader using GPU spawn events?
+ emits_gpu_spawn_events: Option<bool>,
+}
+
+impl<'a> ShaderWriter<'a> {
+ /// Create a new init context.
+ pub fn new(
+ modifier_context: ModifierContext,
+ property_layout: &'a PropertyLayout,
+ particle_layout: &'a ParticleLayout,
+ texture_layout: &'a TextureLayout,
+ ) -> Self {
+ Self {
+ main_code: String::new(),
+ extra_code: String::new(),
+ property_layout,
+ particle_layout,
+ texture_layout,
+ modifier_context,
+ var_counter: 0,
+ expr_cache: Default::default(),
+ is_attribute_pointer: false,
+ emits_gpu_spawn_events: None,
+ }
+ }
+
+ /// Mark the attribute struct as being available through a pointer.
+ pub fn with_attribute_pointer(mut self) -> Self {
+ self.is_attribute_pointer = true;
+ self
+ }
+
+ /// Mark the shader as emitting GPU spawn events.
+ ///
+ /// This is used by the [`EmitSpawnEventModifier`] to declare that the
+ /// current effect emits GPU spawn events, and therefore needs an event
+ /// buffer to be allocated and the appropriate compute work to be executed
+ /// to fill that buffer with events.
+ ///
+ /// # Returns
+ ///
+ /// Returns an error if another modifier previously called this function
+ /// with a different value of `use_events`. Calling this function with the
+ /// same value is a no-op, and doesn't generate any error.
+ pub fn set_emits_gpu_spawn_events(&mut self, use_events: bool) -> Result<(), ExprError> {
+ if let Some(was_using_events) = self.emits_gpu_spawn_events {
+ if was_using_events == use_events {
+ Ok(())
+ } else {
+ Err(ExprError::GraphEvalError(
+ "Conflicting use of GPU spawn events.".to_string(),
+ ))
+ // FIXME - Should probably be a validation error instead...
+ // Err(ShaderGenerateError::Validate(
+ // "Conflicting use of GPU spawn events.".to_string(),
+ // ))
+ }
+ } else {
+ self.emits_gpu_spawn_events = Some(use_events);
+ Ok(())
+ }
+ }
+
+ /// Check whether this shader emits GPU spawn events.
+ ///
+ /// If no modifier called [`set_emits_gpu_spawn_events()`], this returns
+ /// `None`. Otherwise this returns `Some(value)` where `value` was the value
+ /// passed to [`set_emits_gpu_spawn_events()`].
+ ///
+ /// [`set_emits_gpu_spawn_events()`]: crate::ShaderWriter::set_emits_gpu_spawn_events
+ pub fn emits_gpu_spawn_events(&self) -> Option<bool> {
+ self.emits_gpu_spawn_events
+ }
+}
+
+impl EvalContext for ShaderWriter<'_> {
+ fn modifier_context(&self) -> ModifierContext {
+ self.modifier_context
+ }
+
+ fn property_layout(&self) -> &PropertyLayout {
+ self.property_layout
+ }
+
+ fn particle_layout(&self) -> &ParticleLayout {
+ self.particle_layout
+ }
+
+ fn texture_layout(&self) -> &TextureLayout {
+ self.texture_layout
+ }
+
+ fn eval(&mut self, module: &Module, handle: ExprHandle) -> Result<String, ExprError> {
+ // On cache hit, don't re-evaluate the expression to prevent any duplicate
+ // side-effect.
+ if let Some(s) = self.expr_cache.get(&handle) {
+ Ok(s.clone())
+ } else {
+ module.try_get(handle)?.eval(module, self).inspect(|s| {
+ self.expr_cache.insert(handle, s.clone());
+ })
+ }
+ }
+
+ fn make_local_var(&mut self) -> String {
+ let index = self.var_counter;
+ self.var_counter += 1;
+ format!("var{}", index)
+ }
+
+ fn push_stmt(&mut self, stmt: &str) {
+ self.main_code += stmt;
+ self.main_code += "\n";
+ }
+
+ fn make_fn(
+ &mut self,
+ func_name: &str,
+ args: &str,
+ ret: Option<&str>,
+ module: &mut Module,
+ f: &mut dyn FnMut(&mut Module, &mut dyn EvalContext) -> Result<String, ExprError>,
+ ) -> Result<(), ExprError> {
+ // Generate a temporary context for the function content itself
+ // FIXME - Dynamic with_attribute_pointer()!
+ let mut ctx = ShaderWriter::new(
+ self.modifier_context,
+ self.property_layout,
+ self.particle_layout,
+ self.texture_layout,
+ )
+ .with_attribute_pointer();
+
+ // Evaluate the function content
+ let body = f(module, &mut ctx)?;
+
+ // Append any extra
+ self.extra_code += &ctx.extra_code;
+
+ // Append the function itself
+ let ret = ret.map(|x| format!("-> {x} ")).unwrap_or_default();
+ self.extra_code += &format!(
+ r##"fn {0}({1}) {ret}{{
+{2}{3}}}"##,
+ func_name, args, ctx.main_code, body
+ );
+
+ Ok(())
+ }
+
+ fn is_attribute_pointer(&self) -> bool {
+ self.is_attribute_pointer
+ }
+}
+
+/// Particle rendering shader code generation context.
+#[derive(Debug, PartialEq)]
+pub struct RenderContext<'a> {
+ /// Layout of properties for the current effect.
+ pub property_layout: &'a PropertyLayout,
+ /// Layout of attributes of a particle for the current effect.
+ pub particle_layout: &'a ParticleLayout,
+ /// Main particle rendering code for the vertex shader.
+ pub vertex_code: String,
+ /// Main particle rendering code for the fragment shader.
+ pub fragment_code: String,
+ /// Extra functions emitted at top level, which `vertex_code` and
+ /// `fragment_code` can call.
+ pub render_extra: String,
+ /// Texture layout.
+ pub texture_layout: &'a TextureLayout,
+ /// Effect textures.
+ pub textures: Vec<Handle<Image>>,
+ /// Flipbook sprite sheet grid size, if any.
+ pub sprite_grid_size: Option<UVec2>,
+ /// Color gradients.
+ pub gradients: HashMap<u64, Gradient<Vec4>>,
+ /// Size gradients.
+ pub size_gradients: HashMap<u64, Gradient<Vec3>>,
+ /// The particle needs UV coordinates to sample one or more texture(s).
+ pub needs_uv: bool,
+ /// The particle needs normals for lighting effects.
+ pub needs_normal: bool,
+ /// The particle needs access to its data in the fragment shader.
+ pub needs_particle_fragment: bool,
+ /// Counter for unique variable names.
+ var_counter: u32,
+ /// Cache of evaluated expressions.
+ expr_cache: HashMap<ExprHandle, String>,
+ /// Is the attriubute struct a pointer?
+ is_attribute_pointer: bool,
+}
+
+impl<'a> RenderContext<'a> {
+ /// Create a new update context.
+ pub fn new(
+ property_layout: &'a PropertyLayout,
+ particle_layout: &'a ParticleLayout,
+ texture_layout: &'a TextureLayout,
+ ) -> Self {
+ Self {
+ property_layout,
+ particle_layout,
+ vertex_code: String::new(),
+ fragment_code: String::new(),
+ render_extra: String::new(),
+ texture_layout,
+ textures: vec![],
+ sprite_grid_size: None,
+ gradients: HashMap::default(),
+ size_gradients: HashMap::default(),
+ needs_uv: false,
+ needs_normal: false,
+ needs_particle_fragment: false,
+ var_counter: 0,
+ expr_cache: Default::default(),
+ is_attribute_pointer: false,
+ }
+ }
+
+ /// Mark the rendering shader as needing UVs.
+ pub fn set_needs_uv(&mut self) {
+ self.needs_uv = true;
+ }
+
+ /// Mark the rendering shader as needing normals.
+ pub fn set_needs_normal(&mut self) {
+ self.needs_normal = true;
+ }
+
+ /// Mark the rendering shader as needing particle data in the fragment
+ /// shader.
+ pub fn set_needs_particle_fragment(&mut self) {
+ self.needs_particle_fragment = true;
+ }
+
+ /// Add a color gradient.
+ ///
+ /// # Returns
+ ///
+ /// Returns the unique name of the gradient, to be used as function name in
+ /// the shader code.
+ fn add_color_gradient(&mut self, gradient: Gradient<Vec4>) -> String {
+ let func_id = calc_func_id(&gradient);
+ self.gradients.insert(func_id, gradient);
+ let func_name = format!("color_gradient_{0:016X}", func_id);
+ func_name
+ }
+
+ /// Add a size gradient.
+ ///
+ /// # Returns
+ ///
+ /// Returns the unique name of the gradient, to be used as function name in
+ /// the shader code.
+ fn add_size_gradient(&mut self, gradient: Gradient<Vec3>) -> String {
+ let func_id = calc_func_id(&gradient);
+ self.size_gradients.insert(func_id, gradient);
+ let func_name = format!("size_gradient_{0:016X}", func_id);
+ func_name
+ }
+
+ /// Mark the attribute struct as being available through a pointer.
+ pub fn with_attribute_pointer(mut self) -> Self {
+ self.is_attribute_pointer = true;
+ self
+ }
+}
+
+impl EvalContext for RenderContext<'_> {
+ fn modifier_context(&self) -> ModifierContext {
+ ModifierContext::Render
+ }
+
+ fn property_layout(&self) -> &PropertyLayout {
+ self.property_layout
+ }
+
+ fn particle_layout(&self) -> &ParticleLayout {
+ self.particle_layout
+ }
+
+ fn texture_layout(&self) -> &TextureLayout {
+ self.texture_layout
+ }
+
+ fn eval(&mut self, module: &Module, handle: ExprHandle) -> Result<String, ExprError> {
+ // On cache hit, don't re-evaluate the expression to prevent any duplicate
+ // side-effect.
+ if let Some(s) = self.expr_cache.get(&handle) {
+ Ok(s.clone())
+ } else {
+ module.try_get(handle)?.eval(module, self).inspect(|s| {
+ self.expr_cache.insert(handle, s.clone());
+ })
+ }
+ }
+
+ fn make_local_var(&mut self) -> String {
+ let index = self.var_counter;
+ self.var_counter += 1;
+ format!("var{}", index)
+ }
+
+ fn push_stmt(&mut self, stmt: &str) {
+ // FIXME - vertex vs. fragment code, can't differentiate here currently
+ self.vertex_code += stmt;
+ self.vertex_code += "\n";
+ }
+
+ fn make_fn(
+ &mut self,
+ func_name: &str,
+ args: &str,
+ ret: Option<&str>,
+ module: &mut Module,
+ f: &mut dyn FnMut(&mut Module, &mut dyn EvalContext) -> Result<String, ExprError>,
+ ) -> Result<(), ExprError> {
+ // Generate a temporary context for the function content itself
+ // FIXME - Dynamic with_attribute_pointer()!
+ let texture_layout = module.texture_layout();
+ let mut ctx =
+ RenderContext::new(self.property_layout, self.particle_layout, &texture_layout)
+ .with_attribute_pointer();
+
+ // Evaluate the function content
+ let body = f(module, &mut ctx)?;
+
+ // Append any extra
+ self.render_extra += &ctx.render_extra;
+
+ // Append the function itself
+ let ret = ret.map(|x| format!("-> {x} ")).unwrap_or_default();
+ self.render_extra += &format!(
+ r##"fn {0}({1}) {ret}{{
+ {2};
+ }}
+ "##,
+ func_name, args, body
+ );
+
+ Ok(())
+ }
+
+ fn is_attribute_pointer(&self) -> bool {
+ self.is_attribute_pointer
+ }
+}
+
+/// Trait to customize the rendering of alive particles each frame.
+pub trait RenderModifier: Modifier {
+ /// Apply the rendering code.
+ fn apply_render(
+ &self,
+ module: &mut Module,
+ context: &mut RenderContext,
+ ) -> Result<(), ExprError>;
+
+ /// Clone into boxed self.
+ fn boxed_render_clone(&self) -> Box<dyn RenderModifier>;
+
+ /// Upcast to [`Modifier`] trait.
+ fn as_modifier(&self) -> &dyn Modifier;
+}
+
+impl Clone for Box<dyn RenderModifier> {
+ fn clone(&self) -> Self {
+ self.boxed_render_clone()
+ }
+}
+
+/// Macro to implement the [`Modifier`] trait for a render modifier.
+macro_rules! impl_mod_render {
+ ($t:ty, $attrs:expr) => {
+ impl $crate::Modifier for $t {
+ fn context(&self) -> $crate::ModifierContext {
+ $crate::ModifierContext::Render
+ }
+
+ fn as_render(&self) -> Option<&dyn $crate::RenderModifier> {
+ Some(self)
+ }
+
+ fn as_render_mut(&mut self) -> Option<&mut dyn $crate::RenderModifier> {
+ Some(self)
+ }
+
+ fn into_boxed_render(self: Box<Self>) -> Option<Box<dyn RenderModifier>> {
+ Some(self)
+ }
+
+ fn attributes(&self) -> &[$crate::Attribute] {
+ $attrs
+ }
+
+ fn boxed_clone(&self) -> $crate::BoxedModifier {
+ Box::new(self.clone())
+ }
+
+ fn apply(
+ &self,
+ _module: &mut Module,
+ context: &mut ShaderWriter,
+ ) -> Result<(), ExprError> {
+ Err(ExprError::InvalidModifierContext(
+ context.modifier_context(),
+ ModifierContext::Render,
+ "",
+ ))
+ }
+ }
+ };
+}
+
+pub(crate) use impl_mod_render;
+
+/// Condition to emit a GPU spawn event.
+///
+/// Determines when a GPU spawn event is emitted by a parent effect. See
+/// the [`EffectParent`] component for details about the parent-child effect
+/// relationship and its use.
+///
+/// [`EffectParent`]: crate::EffectParent
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub enum EventEmitCondition {
+ /// Always emit events each time the particle is updated, each simulation
+ /// frame.
+ Always,
+ /// Only emit events if the particle died during this frame update.
+ OnDie,
+}
+
+/// Emit GPU spawn events to spawn new particle(s) in a child effect.
+///
+/// This update modifier is used to spawn new particles into a child effect
+/// instance based on a condition applied to particles of the current effect
+/// instance. The most common use case is to spawn one or more child particles
+/// into a child effect when a particle in this effect dies; this is achieved
+/// with [`EventEmitCondition::OnDie`].
+///
+/// An effect instance with this modifier will emit GPU spawn events. Those
+/// events are read by all child effects (those effects with an [`EffectParent`]
+/// component pointing at the current effect instance). GPU spawn events are
+/// stored internally in a GPU buffer; they're **unrelated** to Bevy ECS events.
+///
+/// [`EffectParent`]: crate::EffectParent
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct EmitSpawnEventModifier {
+ /// Emit condition for the GPU spawn events.
+ pub condition: EventEmitCondition,
+ /// The number of particles to spawn if the emit condition is met.
+ ///
+ /// Expression type: `Uint`
+ pub count: ExprHandle,
+ /// Index of the event channel / child the events are emitted into.
+ ///
+ /// GPU spawn events emitted by this parent event are associated with a
+ /// single event channel. When the N-th child effect of a parent effect
+ /// consumes those event, it implicitly reads events from channel #N. In
+ /// general if a parent has a single child, use `0` here.
+ pub child_index: u32,
+}
+
+impl EmitSpawnEventModifier {
+ fn eval(
+ &self,
+ module: &mut Module,
+ context: &mut dyn EvalContext,
+ ) -> Result<String, ExprError> {
+ // FIXME - mixing (ex-)channel and event buffer index; this should be automated
+ let channel_index = self.child_index;
+ // TODO - validate GPU spawn events are in use in the eval context...
+
+ let count_val = context.eval(module, self.count)?;
+ let count_var = context.make_local_var();
+ context.push_stmt(&format!("let {} = {};", count_var, count_val));
+
+ let cond = match self.condition {
+ EventEmitCondition::Always => format!(
+ "if (is_alive) {{ append_spawn_events_{channel_index}((*effect_metadata).base_child_index, particle_index, {}); }}",
+ count_var
+ ),
+ EventEmitCondition::OnDie => format!(
+ "if (was_alive && !is_alive) {{ append_spawn_events_{channel_index}((*effect_metadata).base_child_index, particle_index, {}); }}",
+ count_var
+ ),
+ };
+ Ok(cond)
+ }
+}
+
+impl Modifier for EmitSpawnEventModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Update
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ &[]
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let code = self.eval(module, context)?;
+ context.main_code += &code;
+ context.set_emits_gpu_spawn_events(true)?;
+ Ok(())
+ }
+}
+
+/// Register all built-in modifiers.
+///
+/// This registers all built-in modifiers with the given [`AppTypeRegistry`], by
+/// both calling [`TypeRegistry::register::<T>()`] and inserting a
+/// [`ReflectModifier`] type data for the modifier type `T`.
+///
+/// This is automatically called by the [`HanabiPlugin`]. In general you don't
+/// need to call this.
+///
+/// # Example
+///
+/// ```
+/// # use bevy::prelude::*;
+/// # use bevy_hanabi::*;
+/// fn register(type_registry: Res<AppTypeRegistry>) {
+/// register_modifiers(&type_registry);
+/// }
+/// ```
+///
+/// [`TypeRegistry::register::<T>()`]: bevy::reflect::TypeRegistry::register
+/// [`HanabiPlugin`]: crate::HanabiPlugin
+pub fn register_modifiers(type_registry: &AppTypeRegistry) {
+ {
+ let mut type_registry = type_registry.write();
+
+ // mod.rs
+ type_registry.register::<EmitSpawnEventModifier>();
+ // accel.rs
+ type_registry.register::<AccelModifier>();
+ type_registry.register::<RadialAccelModifier>();
+ type_registry.register::<TangentAccelModifier>();
+ // attr.rs
+ type_registry.register::<SetAttributeModifier>();
+ type_registry.register::<InheritAttributeModifier>();
+ // force.rs
+ type_registry.register::<ConformToSphereModifier>();
+ type_registry.register::<LinearDragModifier>();
+ // kill.rs
+ type_registry.register::<KillSphereModifier>();
+ type_registry.register::<KillAabbModifier>();
+ type_registry.register::<KillFrustumModifier>();
+ // output.rs
+ type_registry.register::<ParticleTextureModifier>();
+ type_registry.register::<SetColorModifier>();
+ type_registry.register::<ColorOverLifetimeModifier>();
+ type_registry.register::<SetSizeModifier>();
+ type_registry.register::<SizeOverLifetimeModifier>();
+ type_registry.register::<OrientModifier>();
+ type_registry.register::<FlipbookModifier>();
+ type_registry.register::<ScreenSpaceSizeModifier>();
+ type_registry.register::<RoundModifier>();
+ // position.rs
+ type_registry.register::<SetPositionCircleModifier>();
+ type_registry.register::<SetPositionSphereModifier>();
+ type_registry.register::<SetPositionCone3dModifier>();
+ type_registry.register::<SetPositionBoxModifier>();
+ // velocity.rs
+ type_registry.register::<SetVelocityCircleModifier>();
+ type_registry.register::<SetVelocitySphereModifier>();
+ type_registry.register::<SetVelocityTangentModifier>();
+
+ // Register Modifiers wrapper for serde-aware boxed modifiers
+ type_registry.register::<crate::modifier::registry::Modifiers>();
+ }
+
+ // accel.rs
+ register_reflect_modifier::<AccelModifier>(type_registry, |module| {
+ let accel = module.lit(Vec3::X);
+ Box::new(AccelModifier::new(accel))
+ });
+ register_reflect_modifier::<RadialAccelModifier>(type_registry, |module| {
+ let origin = module.lit(Vec3::ZERO);
+ let accel = module.lit(1.0);
+ Box::new(RadialAccelModifier::new(origin, accel))
+ });
+ register_reflect_modifier::<TangentAccelModifier>(type_registry, |module| {
+ let origin = module.lit(Vec3::ZERO);
+ let axis = module.lit(Vec3::X);
+ let accel = module.lit(1.0);
+ Box::new(TangentAccelModifier::new(origin, axis, accel))
+ });
+
+ // attr.rs
+ register_reflect_modifier::<SetAttributeModifier>(type_registry, |module| {
+ let value = module.lit(1.0);
+ Box::new(SetAttributeModifier::new(Attribute::LIFETIME, value))
+ });
+ register_reflect_modifier::<InheritAttributeModifier>(type_registry, |_| {
+ Box::new(InheritAttributeModifier::new(Attribute::LIFETIME))
+ });
+
+ // force.rs
+ register_reflect_modifier::<ConformToSphereModifier>(type_registry, |module| {
+ let origin = module.lit(Vec3::ZERO);
+ let radius = module.lit(1.0);
+ let influence_dist = module.lit(10.0);
+ let attraction_accel = module.lit(1.0);
+ let max_attraction_speed = module.lit(1.0);
+ Box::new(ConformToSphereModifier::new(
+ origin,
+ radius,
+ influence_dist,
+ attraction_accel,
+ max_attraction_speed,
+ ))
+ });
+ register_reflect_modifier::<LinearDragModifier>(type_registry, |module| {
+ let drag = module.lit(1.0);
+ Box::new(LinearDragModifier::new(drag))
+ });
+
+ // kill.rs
+ register_reflect_modifier::<KillSphereModifier>(type_registry, |module| {
+ let center = module.lit(Vec3::ZERO);
+ let sqr_radius = module.lit(1.0);
+ Box::new(KillSphereModifier::new(center, sqr_radius))
+ });
+ register_reflect_modifier::<KillAabbModifier>(type_registry, |module| {
+ let center = module.lit(Vec3::ZERO);
+ let sqr_radius = module.lit(1.0);
+ Box::new(KillAabbModifier::new(center, sqr_radius))
+ });
+
+ // output.rs
+ register_reflect_modifier::<ParticleTextureModifier>(type_registry, |_| {
+ Box::new(ParticleTextureModifier::new(0))
+ });
+ register_reflect_modifier::<SetColorModifier>(type_registry, |_| {
+ Box::new(SetColorModifier::new(Vec4::ONE))
+ });
+ register_reflect_modifier::<ColorOverLifetimeModifier>(type_registry, |_| {
+ Box::new(ColorOverLifetimeModifier::new(Gradient::constant(
+ Vec4::ONE,
+ )))
+ });
+ register_reflect_modifier::<SetSizeModifier>(type_registry, |_| {
+ Box::new(SetSizeModifier {
+ size: Vec3::ONE.into(),
+ })
+ });
+ register_reflect_modifier::<SizeOverLifetimeModifier>(type_registry, |_| {
+ Box::new(SizeOverLifetimeModifier {
+ gradient: Gradient::constant(Vec3::ONE),
+ screen_space_size: false,
+ })
+ });
+ register_reflect_modifier::<OrientModifier>(type_registry, |_| {
+ Box::new(OrientModifier::new(OrientMode::default()))
+ });
+ register_reflect_modifier::<FlipbookModifier>(type_registry, |_| {
+ Box::new(FlipbookModifier::default())
+ });
+ register_reflect_modifier::<ScreenSpaceSizeModifier>(type_registry, |_| {
+ Box::new(ScreenSpaceSizeModifier)
+ });
+ register_reflect_modifier::<RoundModifier>(type_registry, |module| {
+ Box::new(RoundModifier::constant(module, 1.0))
+ });
+
+ // position.rs
+ register_reflect_modifier::<SetPositionCircleModifier>(type_registry, |module| {
+ Box::new(SetPositionCircleModifier {
+ center: module.lit(Vec3::ZERO),
+ axis: module.lit(Vec3::Z),
+ radius: module.lit(1.0),
+ dimension: ShapeDimension::Surface,
+ })
+ });
+ register_reflect_modifier::<SetPositionSphereModifier>(type_registry, |module| {
+ Box::new(SetPositionSphereModifier {
+ center: module.lit(Vec3::ZERO),
+ radius: module.lit(1.0),
+ dimension: ShapeDimension::Surface,
+ })
+ });
+ register_reflect_modifier::<SetPositionCone3dModifier>(type_registry, |module| {
+ Box::new(SetPositionCone3dModifier {
+ height: module.lit(1.0),
+ base_radius: module.lit(1.0),
+ top_radius: module.lit(0.0),
+ dimension: ShapeDimension::Surface,
+ })
+ });
+ register_reflect_modifier::<SetPositionBoxModifier>(type_registry, |module| {
+ Box::new(SetPositionBoxModifier {
+ center: module.lit(Vec3::ZERO),
+ extent: module.lit(Vec3::ONE),
+ dimension: ShapeDimension::Surface,
+ })
+ });
+
+ // velocity.rs
+ register_reflect_modifier::<SetVelocityCircleModifier>(type_registry, |module| {
+ Box::new(SetVelocityCircleModifier {
+ center: module.lit(Vec3::ZERO),
+ axis: module.lit(Vec3::Z),
+ speed: module.lit(1.0),
+ })
+ });
+ register_reflect_modifier::<SetVelocitySphereModifier>(type_registry, |module| {
+ Box::new(SetVelocitySphereModifier {
+ center: module.lit(Vec3::ZERO),
+ speed: module.lit(1.0),
+ })
+ });
+ register_reflect_modifier::<SetVelocityTangentModifier>(type_registry, |module| {
+ Box::new(SetVelocityTangentModifier {
+ origin: module.lit(Vec3::ZERO),
+ axis: module.lit(Vec3::X),
+ speed: module.lit(1.0),
+ })
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use bevy::prelude::*;
+ use naga::front::wgsl::Frontend;
+
+ use super::*;
+ use crate::{BuiltInOperator, ExprWriter, ScalarType};
+
+ fn make_test_modifier() -> SetPositionSphereModifier {
+ // We use a dummy module here because we don't care about the values and won't
+ // evaluate the modifier.
+ let mut m = Module::default();
+ SetPositionSphereModifier {
+ center: m.lit(Vec3::ZERO),
+ radius: m.lit(1.),
+ dimension: ShapeDimension::Surface,
+ }
+ }
+
+ #[test]
+ fn modifier_into_render() {
+ let original = SetSizeModifier {
+ size: Vec3::ONE.into(),
+ };
+ let original = Box::new(original);
+ let before: *const dyn RenderModifier = &*original;
+ let modifier: Box<dyn Modifier> = original;
+
+ // into_boxed_render() casts the same object
+ let modifier = modifier.into_boxed_render();
+ assert!(modifier.is_some());
+ let modifier = modifier.unwrap();
+ let after: *const dyn RenderModifier = &*modifier;
+ assert_eq!(before.addr(), after.addr());
+
+ // boxed_render_clone() creates a different object
+ let modifier = modifier.boxed_render_clone();
+ let after: *const dyn RenderModifier = &*modifier;
+ assert_ne!(before.addr(), after.addr());
+ }
+
+ #[test]
+ fn modifier_context_display() {
+ assert_eq!("None", format!("{}", ModifierContext::empty()));
+ assert_eq!("Init", format!("{}", ModifierContext::Init));
+ assert_eq!("Update", format!("{}", ModifierContext::Update));
+ assert_eq!("Render", format!("{}", ModifierContext::Render));
+ assert_eq!(
+ "Init | Update",
+ format!("{}", ModifierContext::Init | ModifierContext::Update)
+ );
+ assert_eq!(
+ "Update | Render",
+ format!("{}", ModifierContext::Update | ModifierContext::Render)
+ );
+ assert_eq!(
+ "Init | Render",
+ format!("{}", ModifierContext::Init | ModifierContext::Render)
+ );
+ assert_eq!(
+ "Init | Update | Render",
+ format!("{}", ModifierContext::all())
+ );
+ }
+
+ #[test]
+ fn reflect() {
+ let m = make_test_modifier();
+
+ // Reflect
+ let reflect: &dyn Reflect = m.as_reflect();
+ assert!(reflect.is::<SetPositionSphereModifier>());
+ let m_reflect = reflect.downcast_ref::<SetPositionSphereModifier>().unwrap();
+ assert_eq!(*m_reflect, m);
+ }
+
+ #[test]
+ fn serde() {
+ use serde::de::DeserializeSeed as _;
+
+ let m = make_test_modifier();
+ let bm: BoxedModifier = Box::new(m);
+
+ // Use reflect-based serialization with a TypeRegistry so the boxed trait
+ // object can be serialized via the registered ReflectModifier factories.
+ let type_registry = AppTypeRegistry::new_with_derived_types();
+ register_modifiers(&type_registry);
+ let registry = type_registry.read();
+
+ // Serialize via ReflectSerializer
+ let serializer = bevy::reflect::serde::ReflectSerializer::new(bm.as_reflect(), &registry);
+ let s = ron::to_string(&serializer).unwrap();
+ println!("modifier: {:?}", s);
+
+ // Deserialize via ReflectDeserializer and construct a concrete instance using
+ // the ReflectModifier factory (same approach as in registry serde_impl).
+ let mut de = ron::de::Deserializer::from_str(&s).unwrap();
+ let reflect_deser = bevy::reflect::serde::ReflectDeserializer::new(&registry);
+ let boxed_partial = reflect_deser.deserialize(&mut de).unwrap();
+
+ let type_info = boxed_partial
+ .get_represented_type_info()
+ .expect("reflected value has no represented type info");
+ let type_id = type_info.type_id();
+
+ // Lookup ReflectModifier type data to build default instance
+ let reflect_modifier = registry
+ .get_type_data::<crate::modifier::registry::ReflectModifier>(type_id)
+ .expect("no ReflectModifier type data for type");
+
+ // Convert PartialReflect -> concrete Reflect
+ let rfr = registry
+ .get_type_data::<bevy::reflect::ReflectFromReflect>(type_id)
+ .expect("no ReflectFromReflect data for type");
+ let concrete_reflect = rfr
+ .from_reflect(boxed_partial.as_partial_reflect())
+ .expect("from_reflect failed");
+
+ // Build default instance and assign the deserialized data
+ let mut module = Module::default();
+ let mut modifier: BoxedModifier = (reflect_modifier.factory)(&mut module);
+ let reflect_mut: &mut dyn Reflect = Reflect::as_reflect_mut(&mut *modifier);
+ reflect_mut
+ .set(concrete_reflect)
+ .expect("failed to assign reflect value to modifier instance");
+
+ let m_serde = modifier;
+
+ let rm: &dyn Reflect = m.as_reflect();
+ let rm_serde: &dyn Reflect = m_serde.as_reflect();
+ assert_eq!(
+ rm.get_represented_type_info().unwrap().type_id(),
+ rm_serde.get_represented_type_info().unwrap().type_id()
+ );
+
+ assert!(rm_serde.is::<SetPositionSphereModifier>());
+ let rm_reflect = rm_serde
+ .downcast_ref::<SetPositionSphereModifier>()
+ .unwrap();
+ assert_eq!(*rm_reflect, m);
+ }
+
+ #[test]
+ fn validate_init() {
+ let mut module = Module::default();
+ let center = module.lit(Vec3::ZERO);
+ let axis = module.lit(Vec3::Y);
+ let radius = module.lit(1.);
+ let modifiers: &[&dyn Modifier] = &[
+ &SetPositionCircleModifier {
+ center,
+ axis,
+ radius,
+ dimension: ShapeDimension::Volume,
+ },
+ &SetPositionSphereModifier {
+ center,
+ radius,
+ dimension: ShapeDimension::Volume,
+ },
+ &SetPositionCone3dModifier {
+ base_radius: radius,
+ top_radius: radius,
+ height: radius,
+ dimension: ShapeDimension::Volume,
+ },
+ &SetVelocityCircleModifier {
+ center,
+ axis,
+ speed: radius,
+ },
+ &SetVelocitySphereModifier {
+ center,
+ speed: radius,
+ },
+ &SetVelocityTangentModifier {
+ origin: center,
+ axis,
+ speed: radius,
+ },
+ ];
+ for &modifier in modifiers.iter() {
+ assert!(modifier.context().contains(ModifierContext::Init));
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut context = ShaderWriter::new(
+ ModifierContext::Init,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ assert!(modifier.apply(&mut module, &mut context).is_ok());
+ let main_code = context.main_code;
+ let extra_code = context.extra_code;
+
+ let mut particle_layout = ParticleLayout::new();
+ for &attr in modifier.attributes() {
+ particle_layout = particle_layout.append(attr);
+ }
+ let particle_layout = particle_layout.build();
+ let attributes_code = particle_layout.generate_code();
+
+ let code = format!(
+ r##"fn frand() -> f32 {{
+ return 0.0;
+}}
+
+const tau: f32 = 6.283185307179586476925286766559;
+
+struct Particle {{
+ {attributes_code}
+}};
+
+{extra_code}
+
+@compute @workgroup_size(64)
+fn main() {{
+ var particle = Particle();
+{main_code}
+}}"##
+ );
+ // println!("code: {:?}", code);
+
+ let mut frontend = Frontend::new();
+ let res = frontend.parse(&code);
+ if let Err(err) = &res {
+ println!(
+ "Modifier: {:?}",
+ modifier.get_represented_type_info().unwrap().type_path()
+ );
+ println!("Code: {:?}", code);
+ println!("Err: {:?}", err);
+ }
+ assert!(res.is_ok());
+ }
+ }
+
+ #[test]
+ fn validate_update() {
+ let writer = ExprWriter::new();
+ let origin = writer.lit(Vec3::ZERO).expr();
+ let center = origin;
+ let axis = origin;
+ let y_axis = writer.lit(Vec3::Y).expr();
+ let one = writer.lit(1.).expr();
+ let radius = one;
+ let modifiers: &[&dyn Modifier] = &[
+ &AccelModifier::new(origin),
+ &RadialAccelModifier::new(origin, one),
+ &TangentAccelModifier::new(origin, y_axis, one),
+ &ConformToSphereModifier::new(origin, one, one, one, one),
+ &LinearDragModifier::new(writer.lit(3.5).expr()),
+ &KillAabbModifier::new(writer.lit(Vec3::ZERO).expr(), writer.lit(Vec3::ONE).expr()),
+ &SetPositionCircleModifier {
+ center,
+ axis,
+ radius,
+ dimension: ShapeDimension::Volume,
+ },
+ &SetPositionSphereModifier {
+ center,
+ radius,
+ dimension: ShapeDimension::Volume,
+ },
+ &SetPositionCone3dModifier {
+ base_radius: radius,
+ top_radius: radius,
+ height: radius,
+ dimension: ShapeDimension::Volume,
+ },
+ &SetVelocityCircleModifier {
+ center,
+ axis,
+ speed: radius,
+ },
+ &SetVelocitySphereModifier {
+ center,
+ speed: radius,
+ },
+ &SetVelocityTangentModifier {
+ origin: center,
+ axis,
+ speed: radius,
+ },
+ ];
+ let mut module = writer.finish();
+ for &modifier in modifiers.iter() {
+ assert!(modifier.context().contains(ModifierContext::Update));
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let mut context = ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ assert!(modifier.apply(&mut module, &mut context).is_ok());
+ let update_code = context.main_code;
+ let update_extra = context.extra_code;
+
+ let mut particle_layout = ParticleLayout::new();
+ for &attr in modifier.attributes() {
+ particle_layout = particle_layout.append(attr);
+ }
+ let particle_layout = particle_layout.build();
+ let attributes_code = particle_layout.generate_code();
+
+ let code = format!(
+ r##"fn frand() -> f32 {{
+ return 0.0;
+}}
+
+const tau: f32 = 6.283185307179586476925286766559;
+
+struct Particle {{
+ {attributes_code}
+}};
+
+struct ParticleBuffer {{
+ particles: array<Particle>,
+}};
+
+struct SimParams {{
+ delta_time: f32,
+ time: f32,
+ virtual_delta_time: f32,
+ virtual_time: f32,
+ real_delta_time: f32,
+ real_time: f32,
+}};
+
+struct Spawner {{
+ transform: mat3x4<f32>, // transposed (row-major)
+ spawn: atomic<i32>,
+ seed: u32,
+ count_unused: u32,
+ effect_index: u32,
+}};
+
+fn proj(u: vec3<f32>, v: vec3<f32>) -> vec3<f32> {{
+ return dot(v, u) / dot(u,u) * u;
+}}
+
+{update_extra}
+
+@group(0) @binding(0) var<uniform> sim_params : SimParams;
+@group(1) @binding(0) var<storage, read_write> particle_buffer : ParticleBuffer;
+@group(2) @binding(0) var<storage, read_write> spawner : Spawner; // NOTE - same group as init
+
+@compute @workgroup_size(64)
+fn main() {{
+ var particle: Particle = particle_buffer.particles[0];
+ var is_alive = true;
+{update_code}
+}}"##
+ );
+
+ let mut frontend = Frontend::new();
+ let res = frontend.parse(&code);
+ if let Err(err) = &res {
+ println!(
+ "Modifier: {:?}",
+ modifier.get_represented_type_info().unwrap().type_path()
+ );
+ println!("Code: {:?}", code);
+ println!("Err: {:?}", err);
+ }
+ assert!(res.is_ok());
+ }
+ }
+
+ #[test]
+ fn validate_render() {
+ let base_module = Module::default();
+ let modifiers: &[&dyn RenderModifier] = &[
+ &ParticleTextureModifier::new(0),
+ &ColorOverLifetimeModifier::default(),
+ &SizeOverLifetimeModifier::default(),
+ &OrientModifier::new(OrientMode::ParallelCameraDepthPlane),
+ &OrientModifier::new(OrientMode::FaceCameraPosition),
+ &OrientModifier::new(OrientMode::AlongVelocity),
+ ];
+ for &modifier in modifiers.iter() {
+ let mut module = base_module.clone();
+ module.add_texture_slot("tex", crate::SlotDimension::D2);
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = module.texture_layout();
+ assert_eq!(texture_layout.layout.len(), 1);
+ let texture_bindinds = texture_layout.to_wgsl_binding(2, 4);
+ let mut context =
+ RenderContext::new(&property_layout, &particle_layout, &texture_layout);
+ modifier
+ .apply_render(&mut module, &mut context)
+ .expect("Failed to apply modifier to render context.");
+ let vertex_code = context.vertex_code;
+ let fragment_code = context.fragment_code;
+ let render_extra = context.render_extra;
+
+ let mut particle_layout = ParticleLayout::new();
+ for &attr in modifier.attributes() {
+ particle_layout = particle_layout.append(attr);
+ }
+ let particle_layout = particle_layout.build();
+ let attributes_code = particle_layout.generate_code();
+
+ let code = format!(
+ r##"
+struct ColorGrading {{
+ balance: mat3x3<f32>,
+ saturation: vec3<f32>,
+ contrast: vec3<f32>,
+ gamma: vec3<f32>,
+ gain: vec3<f32>,
+ lift: vec3<f32>,
+ midtone_range: vec2<f32>,
+ exposure: f32,
+ hue: f32,
+ post_saturation: f32,
+}}
+
+struct View {{
+ clip_from_world: mat4x4<f32>,
+ unjittered_clip_from_world: mat4x4<f32>,
+ world_from_clip: mat4x4<f32>,
+ world_from_view: mat4x4<f32>,
+ view_from_world: mat4x4<f32>,
+ clip_from_view: mat4x4<f32>,
+ view_from_clip: mat4x4<f32>,
+ world_position: vec3<f32>,
+ exposure: f32,
+ // viewport(x_origin, y_origin, width, height)
+ viewport: vec4<f32>,
+ frustum: array<vec4<f32>, 6>,
+ color_grading: ColorGrading,
+ mip_bias: f32,
+}}
+
+fn frand() -> f32 {{ return 0.0; }}
+fn get_camera_position_effect_space() -> vec3<f32> {{ return vec3<f32>(); }}
+fn get_camera_rotation_effect_space() -> mat3x3<f32> {{ return mat3x3<f32>(); }}
+
+const tau: f32 = 6.283185307179586476925286766559;
+
+struct Particle {{
+ {attributes_code}
+}};
+
+struct VertexOutput {{
+ @builtin(position) position: vec4<f32>,
+ @location(0) color: vec4<f32>,
+}};
+
+@group(0) @binding(0) var<uniform> view: View;
+{texture_bindinds}
+
+{render_extra}
+
+@compute @workgroup_size(64)
+fn main() {{
+ var particle = Particle();
+ var position = vec3<f32>(0.0, 0.0, 0.0);
+ var velocity = vec3<f32>(0.0, 0.0, 0.0);
+ var size = vec3<f32>(1.0, 1.0, 1.0);
+ var axis_x = vec3<f32>(1.0, 0.0, 0.0);
+ var axis_y = vec3<f32>(0.0, 1.0, 0.0);
+ var axis_z = vec3<f32>(0.0, 0.0, 1.0);
+ var color = vec4<f32>(1.0, 1.0, 1.0, 1.0);
+{vertex_code}
+ var out: VertexOutput;
+ return out;
+}}
+
+
+@fragment
+fn fragment(in: VertexOutput) -> @location(0) vec4<f32> {{
+ var color = vec4<f32>(0.0);
+ var uv = vec2<f32>(0.0);
+{fragment_code}
+ return vec4<f32>(1.0);
+}}"##
+ );
+
+ let mut frontend = Frontend::new();
+ let res = frontend.parse(&code);
+ if let Err(err) = &res {
+ println!(
+ "Modifier: {:?}\n",
+ modifier.get_represented_type_info().unwrap().type_path()
+ );
+ println!("Code: {code:?}\n\nError: {err:?}");
+ }
+ assert!(res.is_ok());
+ }
+ }
+
+ #[test]
+ fn eval_cached() {
+ let mut module = Module::default();
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = TextureLayout::default();
+ let x = module.builtin(BuiltInOperator::Rand(ScalarType::Float.into()));
+ let init: &mut dyn EvalContext = &mut ShaderWriter::new(
+ ModifierContext::Init,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ let update: &mut dyn EvalContext = &mut ShaderWriter::new(
+ ModifierContext::Update,
+ &property_layout,
+ &particle_layout,
+ &texture_layout,
+ );
+ let render: &mut dyn EvalContext =
+ &mut RenderContext::new(&property_layout, &particle_layout, &texture_layout);
+ for ctx in [init, update, render] {
+ // First evaluation is cached inside a local variable 'var0'
+ let s = ctx.eval(&module, x).unwrap();
+ assert_eq!(s, "var0");
+ // Second evaluation return the same variable
+ let s2 = ctx.eval(&module, x).unwrap();
+ assert_eq!(s2, s);
+ }
+ }
+}
diff --git a/vendor/bevy_hanabi/src/modifier/output.rs b/vendor/bevy_hanabi/src/modifier/output.rs
new file mode 100644
index 00000000..98f917ea
--- /dev/null
+++ b/vendor/bevy_hanabi/src/modifier/output.rs
@@ -0,0 +1,1144 @@
+//! Modifiers to influence the output (rendering) of each particle.
+
+use std::hash::Hash;
+
+use bevy::prelude::*;
+use bitflags::bitflags;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ impl_mod_render, Attribute, BoxedModifier, CpuValue, EvalContext, ExprError, ExprHandle,
+ Gradient, Modifier, ModifierContext, Module, RenderContext, RenderModifier, ShaderCode,
+ ShaderWriter, ToWgslString,
+};
+
+/// Mapping of the sample read from a texture image to the base particle color.
+///
+/// This defines the way the texture image of [`ParticleTextureModifier`] blends
+/// with the base particle color to define the final render color of the
+/// particle.
+#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub enum ImageSampleMapping {
+ /// Modulate the particle's base color with the full RGBA sample of the
+ /// texture image.
+ ///
+ /// ```wgsl
+ /// color = baseColor * texColor;
+ /// ```
+ #[default]
+ Modulate,
+
+ /// Modulate the particle's base color with the RGB sample of the texture
+ /// image, leaving the alpha component unmodified.
+ ///
+ /// ```wgsl
+ /// color.rgb = baseColor.rgb * texColor.rgb;
+ /// ```
+ ModulateRGB,
+
+ /// Modulate the alpha component (opacity) of the particle's base color with
+ /// the red component of the sample of the texture image.
+ ///
+ /// ```wgsl
+ /// color.a = baseColor.a * texColor.r;
+ /// ```
+ ModulateOpacityFromR,
+}
+
+impl ImageSampleMapping {
+ /// Convert this mapping to shader code for the given texture slot.
+ pub fn to_shader_code(&self, texture_slot: &str) -> String {
+ match *self {
+ ImageSampleMapping::Modulate => format!("color = color * texColor{texture_slot};"),
+ ImageSampleMapping::ModulateRGB => {
+ format!("color = vec4<f32>(color.rgb * texColor{texture_slot}.rgb, color.a);")
+ }
+ ImageSampleMapping::ModulateOpacityFromR => {
+ format!("color.a = color.a * texColor{texture_slot}.r;")
+ }
+ }
+ }
+}
+
+/// A modifier modulating each particle's color by sampling a texture.
+///
+/// # Attributes
+///
+/// This modifier does not require any specific particle attribute.
+#[derive(Debug, Clone, Copy, PartialEq, Reflect, Serialize, Deserialize)]
+pub struct ParticleTextureModifier {
+ /// Index of the texture slot containing the texture to use. The slot is
+ /// defined in the [`Module`], and the actual texture is bound via the
+ /// [`EffectMaterial`] component.
+ ///
+ /// [`EffectMaterial`]: crate::EffectMaterial
+ pub texture_slot: u32,
+
+ /// The mapping of the texture image samples to the base particle color.
+ pub sample_mapping: ImageSampleMapping,
+}
+
+impl ParticleTextureModifier {
+ /// Create a new modifier with the default [`ImageSampleMapping`].
+ pub fn new(texture_slot: u32) -> Self {
+ Self {
+ texture_slot,
+ sample_mapping: default(),
+ }
+ }
+}
+
+impl_mod_render!(ParticleTextureModifier, &[]); // TODO - should require some UV maybe?
+
+impl RenderModifier for ParticleTextureModifier {
+ fn apply_render(
+ &self,
+ module: &mut Module,
+ context: &mut RenderContext,
+ ) -> Result<(), ExprError> {
+ context.set_needs_uv();
+ let code = self.eval(module, context)?;
+ context.fragment_code += &code;
+ Ok(())
+ }
+
+ fn boxed_render_clone(&self) -> Box<dyn RenderModifier> {
+ Box::new(*self)
+ }
+
+ fn as_modifier(&self) -> &dyn Modifier {
+ self
+ }
+}
+
+impl ParticleTextureModifier {
+ /// Evaluate the modifier to generate the shader code.
+ pub fn eval(
+ &self,
+ _module: &Module,
+ _context: &mut dyn EvalContext,
+ ) -> Result<String, ExprError> {
+ let texture_slot = self.texture_slot.to_string();
+ let sample_mapping = self.sample_mapping.to_shader_code(&texture_slot);
+ let sample_mapping_name = format!("{:?}", self.sample_mapping);
+
+ // Build a switch statement to select the texture/sampler.
+ // FIXME - Ideally with bindless (texture/sampler arrays with dynamic indices)
+ // we don't need this. But bindless is not available on Web anyway, so this is a
+ // safe fallback.
+ let mut code = String::with_capacity(1024);
+ code += &format!(
+ " // ParticleTextureModifier
+ var texColor{texture_slot} = textureSample(material_texture_{texture_slot}, material_sampler_{texture_slot}, uv);
+ // Sample mapping: {sample_mapping_name}
+ {sample_mapping}"
+ );
+ Ok(code)
+ }
+}
+
+/// Color blending modes.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub enum ColorBlendMode {
+ /// Overwrite the destination color with the source one.
+ #[default]
+ Overwrite,
+ /// Add the source color to the destination one.
+ Add,
+ /// Multiply the source color by the destination one.
+ Modulate,
+}
+
+impl ColorBlendMode {
+ /// Convert the blend mode to the string representation of its operator.
+ pub fn to_assign_operator(&self) -> String {
+ match *self {
+ ColorBlendMode::Overwrite => "=",
+ ColorBlendMode::Add => "+=",
+ ColorBlendMode::Modulate => "*=",
+ }
+ .to_string()
+ }
+}
+
+/// Color component write mask for blending colors.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct ColorBlendMask(u8);
+
+bitflags! {
+ impl ColorBlendMask: u8 {
+ /// First component (red).
+ const R = 0b0001;
+ /// Second component (green).
+ const G = 0b0010;
+ /// Third component (blue).
+ const B = 0b0100;
+ /// Last component (alpha).
+ const A = 0b1000;
+
+ /// RGB mask (skip alpha).
+ const RGB = 0b0111;
+
+ /// RGBA mask (all components).
+ const RGBA = 0b1111;
+ }
+}
+
+impl Default for ColorBlendMask {
+ fn default() -> Self {
+ Self::RGBA
+ }
+}
+
+impl ColorBlendMask {
+ /// Convert the mask to a string of components, e.g. "rgb" or "ra".
+ pub fn to_components(&self) -> String {
+ let cmp = ['r', 'g', 'b', 'a'];
+ (0..=3).fold(String::with_capacity(4), |mut acc, i| {
+ let mask = ColorBlendMask::from_bits_truncate(1u8 << i);
+ if self.contains(mask) {
+ acc.push(cmp[i]);
+ }
+ acc
+ })
+ }
+}
+
+/// A modifier to set the rendering color of all particles.
+///
+/// This modifier assigns a _single_ color to all particles. That color can be
+/// determined by the user with [`CpuValue::Single`], or left randomized with
+/// [`CpuValue::Uniform`], but will be the same color for all particles.
+///
+/// # Attributes
+///
+/// This modifier does not require any specific particle attribute.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct SetColorModifier {
+ /// The particle color.
+ pub color: CpuValue<Vec4>,
+ /// The color blend mode.
+ pub blend: ColorBlendMode,
+ /// The blend mask.
+ pub mask: ColorBlendMask,
+}
+
+impl SetColorModifier {
+ /// Create a new modifier with the default color blend and mask.
+ pub fn new<C>(color: C) -> Self
+ where
+ C: Into<CpuValue<Vec4>>,
+ {
+ Self {
+ color: color.into(),
+ blend: default(),
+ mask: default(),
+ }
+ }
+}
+
+impl_mod_render!(SetColorModifier, &[]);
+
+impl RenderModifier for SetColorModifier {
+ fn apply_render(
+ &self,
+ _module: &mut Module,
+ context: &mut RenderContext,
+ ) -> Result<(), ExprError> {
+ let op = self.blend.to_assign_operator();
+ let col = self.color.to_wgsl_string();
+ let s = if self.mask == ColorBlendMask::RGBA {
+ format!("color {op} {col};\n")
+ } else {
+ let mask = self.mask.to_components();
+ format!("color.{mask} {op} ({col}).{mask};\n")
+ };
+ context.vertex_code += &s;
+ Ok(())
+ }
+
+ fn boxed_render_clone(&self) -> Box<dyn RenderModifier> {
+ Box::new(*self)
+ }
+
+ fn as_modifier(&self) -> &dyn Modifier {
+ self
+ }
+}
+
+/// A modifier modulating each particle's color over its lifetime with a
+/// gradient curve.
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::AGE`]
+/// - [`Attribute::LIFETIME`]
+#[derive(Debug, Default, Clone, PartialEq, Hash, Reflect, Serialize, Deserialize)]
+pub struct ColorOverLifetimeModifier {
+ /// The color gradient defining the particle color based on its lifetime.
+ pub gradient: Gradient<Vec4>,
+ /// The color blend mode.
+ pub blend: ColorBlendMode,
+ /// The blend mask.
+ pub mask: ColorBlendMask,
+}
+
+impl ColorOverLifetimeModifier {
+ /// Create a new modifier from a given gradient.
+ pub fn new(gradient: Gradient<Vec4>) -> Self {
+ Self {
+ gradient,
+ blend: default(),
+ mask: default(),
+ }
+ }
+}
+
+impl_mod_render!(
+ ColorOverLifetimeModifier,
+ &[Attribute::AGE, Attribute::LIFETIME]
+);
+
+impl RenderModifier for ColorOverLifetimeModifier {
+ fn apply_render(
+ &self,
+ _module: &mut Module,
+ context: &mut RenderContext,
+ ) -> Result<(), ExprError> {
+ let func_name = context.add_color_gradient(self.gradient.clone());
+ context.render_extra += &format!(
+ r#"fn {0}(key: f32) -> vec4<f32> {{
+ {1}
+}}
+
+"#,
+ func_name,
+ self.gradient.to_shader_code("key")
+ );
+
+ let op = self.blend.to_assign_operator();
+ let col = format!(
+ "{0}(particle.{1} / particle.{2})",
+ func_name,
+ Attribute::AGE.name(),
+ Attribute::LIFETIME.name()
+ );
+ let s = if self.mask == ColorBlendMask::RGBA {
+ format!("color {op} {col};\n")
+ } else {
+ let mask = self.mask.to_components();
+ let non_mask = match self.blend {
+ ColorBlendMode::Overwrite => {
+ format!("color.{}", self.mask.complement().to_components())
+ }
+ ColorBlendMode::Add => "0".to_string(),
+ ColorBlendMode::Modulate => "1".to_string(),
+ };
+ format!("color {op} vec4<f32>(({col}).{mask}, {non_mask});\n")
+ };
+
+ context.vertex_code += &s;
+ Ok(())
+ }
+
+ fn boxed_render_clone(&self) -> Box<dyn RenderModifier> {
+ Box::new(self.clone())
+ }
+
+ fn as_modifier(&self) -> &dyn Modifier {
+ self
+ }
+}
+
+/// A modifier to set the size of all particles.
+///
+/// This modifier assigns a _single_ size to all particles. That size can be
+/// determined by the user with [`CpuValue::Single`], or left randomized with
+/// [`CpuValue::Uniform`], but will be the same size for all particles.
+///
+/// # Attributes
+///
+/// This modifier does not require any specific particle attribute. The size of
+/// the particle is extracted from the [`Attribute::SIZE`],
+/// [`Attribute::SIZE2`], or [`Attribute::SIZE3`] if any, but even if they're
+/// absent this modifier acts on the default particle size.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct SetSizeModifier {
+ /// The 3D particle size.
+ pub size: CpuValue<Vec3>,
+}
+
+impl_mod_render!(SetSizeModifier, &[]);
+
+impl RenderModifier for SetSizeModifier {
+ fn apply_render(
+ &self,
+ _module: &mut Module,
+ context: &mut RenderContext,
+ ) -> Result<(), ExprError> {
+ context.vertex_code += &format!("size = {0};\n", self.size.to_wgsl_string());
+ Ok(())
+ }
+
+ fn boxed_render_clone(&self) -> Box<dyn RenderModifier> {
+ Box::new(*self)
+ }
+
+ fn as_modifier(&self) -> &dyn Modifier {
+ self
+ }
+}
+
+/// A modifier modulating each particle's size over its lifetime with a gradient
+/// curve.
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::AGE`]
+/// - [`Attribute::LIFETIME`]
+#[derive(Debug, Default, Clone, PartialEq, Hash, Reflect, Serialize, Deserialize)]
+pub struct SizeOverLifetimeModifier {
+ /// The size gradient defining the particle size based on its lifetime.
+ pub gradient: Gradient<Vec3>,
+ /// Is the particle size in screen-space logical pixel? If `true`, the size
+ /// is in screen-space logical pixels, and not affected by the camera
+ /// projection. If `false`, the particle size is in world units.
+ pub screen_space_size: bool,
+}
+
+impl_mod_render!(
+ SizeOverLifetimeModifier,
+ &[Attribute::AGE, Attribute::LIFETIME]
+);
+
+impl RenderModifier for SizeOverLifetimeModifier {
+ fn apply_render(
+ &self,
+ _module: &mut Module,
+ context: &mut RenderContext,
+ ) -> Result<(), ExprError> {
+ let func_name = context.add_size_gradient(self.gradient.clone());
+ context.render_extra += &format!(
+ r#"fn {0}(key: f32) -> vec3<f32> {{
+ {1}
+}}
+
+"#,
+ func_name,
+ self.gradient.to_shader_code("key")
+ );
+
+ context.vertex_code += &format!(
+ "size = {0}(particle.{1} / particle.{2});\n",
+ func_name,
+ Attribute::AGE.name(),
+ Attribute::LIFETIME.name()
+ );
+
+ Ok(())
+ }
+
+ fn boxed_render_clone(&self) -> Box<dyn RenderModifier> {
+ Box::new(self.clone())
+ }
+
+ fn as_modifier(&self) -> &dyn Modifier {
+ self
+ }
+}
+
+/// Mode of orientation of a particle's local frame.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub enum OrientMode {
+ /// Orient a particle such that its local XY plane is parallel to the
+ /// camera's near and far planes (depth planes).
+ ///
+ /// By default the local X axis is (1,0,0) in camera space, and the local Y
+ /// axis is (0,1,0). The local Z axis is (0,0,1), perpendicular to the
+ /// camera depth planes, pointing toward the camera. If an
+ /// [`OrientModifier::rotation`] is provided, it defines a rotation in the
+ /// local X-Y plane, relative to that default.
+ ///
+ /// This mode is a bit cheaper to calculate than [`FaceCameraPosition`], and
+ /// should be preferred to it unless the particle absolutely needs to have
+ /// its Z axis pointing to the camera position.
+ ///
+ /// This is the default variant.
+ ///
+ /// [`FaceCameraPosition`]: crate::modifier::output::OrientMode::FaceCameraPosition
+ #[default]
+ ParallelCameraDepthPlane,
+
+ /// Orient a particle to face the camera's position.
+ ///
+ /// The local Z axis of the particle points directly at the camera position.
+ /// The X and Y axes form an orthonormal frame with it, where Y is roughly
+ /// upward. If an [`OrientModifier::rotation`] is provided, it defines a
+ /// rotation in the local X-Y plane, relative to that default.
+ ///
+ /// This mode is a bit more costly to calculate than
+ /// [`ParallelCameraDepthPlane`], and should be used only when the
+ /// particle absolutely needs to have its Z axis pointing to the camera
+ /// position.
+ ///
+ /// [`ParallelCameraDepthPlane`]: crate::modifier::output::OrientMode::ParallelCameraDepthPlane
+ FaceCameraPosition,
+
+ /// Orient a particle alongside its velocity.
+ ///
+ /// The local X axis points alongside the velocity. The local Y axis is
+ /// derived as the cross product of the camera direction with that local X
+ /// axis. The Z axis completes the orthonormal basis. This allows flat
+ /// particles (quads) to roughly face the camera position (as long as
+ /// velocity is not perpendicular to the camera depth plane), while having
+ /// their X axis always pointing alongside the velocity.
+ ///
+ /// With this mode, any provided [`OrientModifier::rotation`] is ignored.
+ AlongVelocity,
+}
+
+/// Orients the particle's local frame.
+///
+/// The orientation is calculated during the rendering of each particle.
+///
+/// An additional in-plane rotation can be optionally specified; its meaning
+/// depends on the [`OrientMode`] in use. Note that the in-plane rotation
+/// expression should be saved as an attribute (such as [`Attribute::F32_0`])
+/// if you want it to have different values per instance.
+///
+/// # Example
+///
+/// ```
+/// # use bevy::prelude::*;
+/// # use bevy_hanabi::*;
+/// let writer = ExprWriter::new();
+///
+/// let init_rotation = (writer.rand(ScalarType::Float) * writer.lit(std::f32::consts::TAU)).expr();
+/// let init_rotation = SetAttributeModifier::new(Attribute::F32_0, init_rotation);
+///
+/// let rotation = writer.attr(Attribute::F32_0).expr();
+///
+/// let lifetime = writer.lit(1.).expr();
+/// let init_lifetime = SetAttributeModifier::new(Attribute::LIFETIME, lifetime);
+///
+/// let age = writer.lit(0.).expr();
+/// let init_age = SetAttributeModifier::new(Attribute::AGE, age);
+///
+/// let asset = EffectAsset::new(256, SpawnerSettings::default(), writer.finish())
+/// .with_name("orient")
+/// .init(init_age)
+/// .init(init_lifetime)
+/// .init(init_rotation)
+/// .render(OrientModifier::new(OrientMode::ParallelCameraDepthPlane).with_rotation(rotation));
+/// ```
+///
+/// # Attributes
+///
+/// The required attribute(s) depend on the orientation [`mode`]:
+/// - [`OrientMode::ParallelCameraDepthPlane`]: This modifier does not require
+/// any specific particle attribute.
+/// - [`OrientMode::FaceCameraPosition`]: This modifier requires the
+/// [`Attribute::POSITION`] attribute.
+/// - [`OrientMode::AlongVelocity`]: This modifier requires the
+/// [`Attribute::POSITION`] and [`Attribute::VELOCITY`] attributes.
+///
+/// [`mode`]: crate::modifier::output::OrientModifier::mode
+/// [`Attribute::POSITION`]: crate::attributes::Attribute::POSITION
+#[derive(Debug, Default, Clone, Copy, PartialEq, Hash, Reflect, Serialize, Deserialize)]
+pub struct OrientModifier {
+ /// Orientation mode for the particles.
+ pub mode: OrientMode,
+ /// Optional in-plane rotation expression, as a single `f32` angle in
+ /// radians.
+ ///
+ /// The actual meaning depends on [`OrientMode`], and the rotation may be
+ /// ignored for some mode(s).
+ pub rotation: Option<ExprHandle>,
+}
+
+impl OrientModifier {
+ /// Create a new instance of this modifier with the given orient mode.
+ pub fn new(mode: OrientMode) -> Self {
+ Self {
+ mode,
+ ..Default::default()
+ }
+ }
+
+ /// Set the rotation expression for the particles.
+ pub fn with_rotation(mut self, rotation: ExprHandle) -> Self {
+ self.rotation = Some(rotation);
+ self
+ }
+}
+
+impl Modifier for OrientModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Render
+ }
+
+ fn as_render(&self) -> Option<&dyn RenderModifier> {
+ Some(self)
+ }
+
+ fn as_render_mut(&mut self) -> Option<&mut dyn RenderModifier> {
+ Some(self)
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ // Note: don't required AXIS_X/Y/Z, they're written at the last minute in the
+ // render shader alone, so don't need to be stored as part of the particle's
+ // layout for simulation.
+ match self.mode {
+ OrientMode::ParallelCameraDepthPlane => &[],
+ OrientMode::FaceCameraPosition => &[Attribute::POSITION],
+ OrientMode::AlongVelocity => &[Attribute::POSITION, Attribute::VELOCITY],
+ }
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, _module: &mut Module, _context: &mut ShaderWriter) -> Result<(), ExprError> {
+ Err(ExprError::TypeError("Wrong modifier context".to_string()))
+ }
+}
+
+impl RenderModifier for OrientModifier {
+ fn apply_render(
+ &self,
+ module: &mut Module,
+ context: &mut RenderContext,
+ ) -> Result<(), ExprError> {
+ match self.mode {
+ OrientMode::ParallelCameraDepthPlane => {
+ if let Some(rotation) = self.rotation {
+ let rotation = context.eval(module, rotation)?;
+ context.vertex_code += &format!(
+ r#"let cam_rot = get_camera_rotation_effect_space();
+let particle_rot_in_cam_space = {};
+let particle_rot_in_cam_space_cos = cos(particle_rot_in_cam_space);
+let particle_rot_in_cam_space_sin = sin(particle_rot_in_cam_space);
+axis_x = cam_rot[0].xyz * particle_rot_in_cam_space_cos + cam_rot[1].xyz * particle_rot_in_cam_space_sin;
+axis_y = cam_rot[0].xyz * particle_rot_in_cam_space_sin - cam_rot[1].xyz * particle_rot_in_cam_space_cos;
+axis_z = cam_rot[2].xyz;
+"#,
+ rotation
+ );
+ } else {
+ context.vertex_code += r#"let cam_rot = get_camera_rotation_effect_space();
+axis_x = cam_rot[0].xyz;
+axis_y = cam_rot[1].xyz;
+axis_z = cam_rot[2].xyz;
+"#;
+ }
+ }
+ OrientMode::FaceCameraPosition => {
+ if let Some(rotation) = self.rotation {
+ let rotation = context.eval(module, rotation)?;
+ context.vertex_code += &format!(
+ r#"axis_z = normalize(get_camera_position_effect_space() - position);
+let particle_rot_in_cam_space = {};
+let particle_rot_in_cam_space_cos = cos(particle_rot_in_cam_space);
+let particle_rot_in_cam_space_sin = sin(particle_rot_in_cam_space);
+let cam_up = get_camera_rotation_effect_space()[1];
+let axis_x0 = normalize(cross(cam_up, axis_z));
+let axis_y0 = cross(axis_z, axis_x0);
+axis_x = axis_x0 * particle_rot_in_cam_space_cos + axis_y0 * particle_rot_in_cam_space_sin;
+axis_y = axis_x0 * particle_rot_in_cam_space_sin - axis_y0 * particle_rot_in_cam_space_cos;
+"#,
+ rotation
+ );
+ } else {
+ context.vertex_code += r#"axis_z = normalize(get_camera_position_effect_space() - position);
+let cam_up = get_camera_rotation_effect_space()[1];
+axis_x = normalize(cross(cam_up, axis_z));
+axis_y = cross(axis_z, axis_x);
+"#;
+ }
+ }
+ OrientMode::AlongVelocity => {
+ context.vertex_code += r#"let dir = normalize(position - get_camera_position_effect_space());
+axis_x = normalize(particle.velocity);
+axis_y = cross(dir, axis_x);
+axis_z = cross(axis_x, axis_y);
+"#;
+ }
+ }
+
+ Ok(())
+ }
+
+ fn boxed_render_clone(&self) -> Box<dyn RenderModifier> {
+ Box::new(*self)
+ }
+
+ fn as_modifier(&self) -> &dyn Modifier {
+ self
+ }
+}
+
+/// A modifier to render particles using flipbook animation.
+///
+/// Flipbook animation renders multiple still images at interactive framerate
+/// (generally 10+ FPS) to give the illusion of animation. The still images are
+/// sprites, taken from a single texture acting as a sprite sheet. This requires
+/// using the [`ParticleTextureModifier`] to specify the source texture
+/// containing the sprite sheet image. The [`FlipbookModifier`] itself only
+/// activates flipbook rendering, specifying how to slice the texture into a
+/// sprite sheet (list of sprites).
+///
+/// The flipbook renderer reads the [`Attribute::SPRITE_INDEX`] of the particle
+/// and selects a region of the particle texture specified via
+/// [`ParticleTextureModifier`]. Note that [`FlipbookModifier`] by itself
+/// doesn't animate anything; instead, the animation comes from a varying value
+/// of [`Attribute::SPRITE_INDEX`].
+///
+/// There's no built-in modifier to update the [`Attribute::SPRITE_INDEX`];
+/// instead you should use a [`SetAttributeModifier`] with a suitable
+/// expression. A common example is to base the sprite index on the particle
+/// age, accessed from [`Attribute::AGE`]. Note that in that case the
+/// [`Attribute::AGE`] being a floating point value must be cast to an integer
+/// to be assigned to [`Attribute::SPRITE_INDEX`].
+///
+/// # Example
+///
+/// ```
+/// # use bevy::prelude::*;
+/// # use bevy_hanabi::*;
+/// # let texture = Handle::<Image>::default();
+/// let writer = ExprWriter::new();
+///
+/// let lifetime = writer.lit(5.).expr();
+/// let init_lifetime = SetAttributeModifier::new(Attribute::LIFETIME, lifetime);
+///
+/// // Age goes from 0 to LIFETIME=5s
+/// let age = writer.lit(0.).expr();
+/// let init_age = SetAttributeModifier::new(Attribute::AGE, age);
+///
+/// // sprite_index = i32(particle.age) % 4;
+/// let sprite_index = writer
+/// .attr(Attribute::AGE)
+/// .cast(ScalarType::Int)
+/// .rem(writer.lit(4i32))
+/// .expr();
+/// let update_sprite_index = SetAttributeModifier::new(Attribute::SPRITE_INDEX, sprite_index);
+///
+/// let asset = EffectAsset::new(32768, SpawnerSettings::once(32.0.into()), writer.finish())
+/// .with_name("flipbook")
+/// .init(init_age)
+/// .init(init_lifetime)
+/// .update(update_sprite_index)
+/// .render(ParticleTextureModifier {
+/// texture_slot: 0,
+/// sample_mapping: ImageSampleMapping::ModulateOpacityFromR,
+/// })
+/// .render(FlipbookModifier {
+/// sprite_grid_size: UVec2::new(2, 2), // 4 frames
+/// });
+/// ```
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::SPRITE_INDEX`]
+///
+/// [`SetAttributeModifier`]: crate::modifier::attr::SetAttributeModifier
+#[derive(Debug, Clone, Copy, PartialEq, Reflect, Serialize, Deserialize)]
+pub struct FlipbookModifier {
+ /// Flipbook sprite sheet grid size.
+ ///
+ /// The grid size defines the number of sprites in the texture, and
+ /// implicitly their size as the total texture size divided by the grid
+ /// size.
+ ///
+ /// To animate the rendered sprite index, modify the
+ /// [`Attribute::SPRITE_INDEX`] property. The value of that attribute should
+ /// ideally be in the `[0:N-1]` range where `N = grid.x * grid.y` is the
+ /// total number of sprites. However values outside that range will not
+ /// produce any error, but will yield texture UV coordinates outside the
+ /// `[0:1]` range.
+ pub sprite_grid_size: UVec2,
+}
+
+impl Default for FlipbookModifier {
+ fn default() -> Self {
+ // Default to something which animates, to help debug mistakes.
+ Self {
+ sprite_grid_size: UVec2::ONE * 2,
+ }
+ }
+}
+
+impl_mod_render!(FlipbookModifier, &[Attribute::SPRITE_INDEX]);
+
+impl RenderModifier for FlipbookModifier {
+ fn apply_render(
+ &self,
+ _module: &mut Module,
+ context: &mut RenderContext,
+ ) -> Result<(), ExprError> {
+ context.sprite_grid_size = Some(self.sprite_grid_size);
+ Ok(())
+ }
+
+ fn boxed_render_clone(&self) -> Box<dyn RenderModifier> {
+ Box::new(*self)
+ }
+
+ fn as_modifier(&self) -> &dyn Modifier {
+ self
+ }
+}
+
+/// A modifier to interpret the size of all particles in screen-space pixels.
+///
+/// This modifier assigns a pixel size to particles in screen space, ignoring
+/// the distance to the camera and perspective. It effectively scales the
+/// existing [`Attribute::SIZE`] of each particle to negate the perspective
+/// correction usually applied to rendered objects based on their distance to
+/// the camera.
+///
+/// Note that this modifier should generally be placed last in the stack, or at
+/// least after any modifier which might modify the particle position or its
+/// size. Otherwise the scaling will be incorrect.
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::POSITION`]
+///
+/// If the [`Attribute::SIZE`], [`Attribute::SIZE2`], or [`Attribute::SIZE3`]
+/// are present, they're used to initialize the particle's size. Otherwise the
+/// default size is used. So this modifier doesn't require any size attribute.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct ScreenSpaceSizeModifier;
+
+impl_mod_render!(
+ ScreenSpaceSizeModifier,
+ &[Attribute::POSITION, Attribute::SIZE]
+);
+
+impl RenderModifier for ScreenSpaceSizeModifier {
+ fn apply_render(
+ &self,
+ _module: &mut Module,
+ context: &mut RenderContext,
+ ) -> Result<(), ExprError> {
+ // Get perspective divide factor from clip space position. This is the "average"
+ // factor for the entire particle, taken at its position (mesh origin),
+ // and applied uniformly for all vertices. Scale size by w_cs to negate
+ // the perspective divide which will happen later after the vertex shader.
+ // The 2.0 factor is because clip space is in [-1:1] so we need to divide by the
+ // half screen size only.
+ // Note: here "size" is the built-in render size, which is always defined and
+ // called "size", and which may or may not be the Attribute::SIZE/2
+ // attribute(s).
+ context.vertex_code += &format!(
+ "let w_cs = transform_position_simulation_to_clip(particle.{0}).w;\n
+ let screen_size_pixels = view.viewport.zw;\n
+ let projection_scale = vec2<f32>(view.clip_from_view[0][0], view.clip_from_view[1][1]);\n
+ size = (size * w_cs * 2.0) / min(screen_size_pixels.x * projection_scale.x, screen_size_pixels.y * projection_scale.y);\n",
+ Attribute::POSITION.name());
+ Ok(())
+ }
+
+ fn boxed_render_clone(&self) -> Box<dyn RenderModifier> {
+ Box::new(*self)
+ }
+
+ fn as_modifier(&self) -> &dyn Modifier {
+ self
+ }
+}
+
+/// Makes particles round.
+///
+/// The shape of each particle is a [squircle] (like a rounded rectangle, but
+/// faster to evaluate). The `roundness` parameter specifies how round the shape
+/// is. At 0.0, the particle is a rectangle; at 1.0, the particle is an
+/// ellipse.
+///
+/// Given x and y from (-1, 1), the equation of the shape of the particle is
+/// |x|ⁿ + |y|ⁿ = 1, where n = 2 / `roundness``.
+///
+/// Note that this modifier is presently incompatible with the
+/// [`FlipbookModifier`]. Attempts to use them together will produce unexpected
+/// results.
+///
+/// [squircle]: https://en.wikipedia.org/wiki/Squircle
+#[derive(Debug, Clone, Copy, PartialEq, Reflect, Serialize, Deserialize)]
+pub struct RoundModifier {
+ /// How round the particle is.
+ ///
+ /// This ranges from 0.0 for a perfect rectangle to 1.0 for a perfect
+ /// ellipse. 1/3 produces a nice rounded rectangle shape.
+ ///
+ /// n in the squircle formula is calculated as (2 / roundness).
+ pub roundness: ExprHandle,
+}
+
+impl_mod_render!(RoundModifier, &[]);
+
+impl RenderModifier for RoundModifier {
+ fn apply_render(
+ &self,
+ module: &mut Module,
+ context: &mut RenderContext,
+ ) -> Result<(), ExprError> {
+ context.set_needs_uv();
+
+ let roundness = context.eval(module, self.roundness)?;
+ context.fragment_code += &format!(
+ "let roundness = {};
+ if (roundness > 0.0f) {{
+ let n = 2.0f / roundness;
+ if (pow(abs(1.0f - 2.0f * in.uv.x), n) +
+ pow(abs(1.0f - 2.0f * in.uv.y), n) > 1.0f) {{
+ discard;
+ }}
+ }}",
+ roundness
+ );
+
+ Ok(())
+ }
+
+ fn boxed_render_clone(&self) -> Box<dyn RenderModifier> {
+ Box::new(*self)
+ }
+
+ fn as_modifier(&self) -> &dyn Modifier {
+ self
+ }
+}
+
+impl RoundModifier {
+ /// Creates a new [`RoundModifier`] with the given roundness.
+ ///
+ /// The `roundness` parameter varies from 0.0 to 1.0.
+ pub fn constant(module: &mut Module, roundness: f32) -> RoundModifier {
+ RoundModifier {
+ roundness: module.lit(roundness),
+ }
+ }
+
+ /// Creates a new [`RoundModifier`] that describes an ellipse.
+ #[doc(alias = "circle")]
+ pub fn ellipse(module: &mut Module) -> RoundModifier {
+ RoundModifier::constant(module, 1.0)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::*;
+
+ #[test]
+ fn color_blend_mask() {
+ assert_eq!(ColorBlendMask::RGB.to_components(), "rgb");
+ assert_eq!(ColorBlendMask::RGBA.to_components(), "rgba");
+
+ let m = ColorBlendMask::R | ColorBlendMask::B;
+ assert_eq!(m.to_components(), "rb");
+ assert_eq!(m.complement(), ColorBlendMask::G | ColorBlendMask::A);
+ assert_eq!(m.complement().to_components(), "ga");
+ }
+
+ #[test]
+ fn mod_particle_texture() {
+ let mut module = Module::default();
+ let modifier = ParticleTextureModifier::new(42);
+
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = module.texture_layout();
+ let mut context = RenderContext::new(&property_layout, &particle_layout, &texture_layout);
+ modifier.apply_render(&mut module, &mut context).unwrap();
+
+ // TODO - no validation at the minute
+ assert_eq!(context.texture_layout.layout.len(), 0); // we "forgot" to add the slot to Module
+ assert_eq!(context.textures.len(), 0); // we "forgot" the EffectMaterial
+ }
+
+ #[test]
+ fn mod_flipbook() {
+ let modifier = FlipbookModifier {
+ sprite_grid_size: UVec2::new(3, 4),
+ };
+
+ let mut module = Module::default();
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = module.texture_layout();
+ let mut context = RenderContext::new(&property_layout, &particle_layout, &texture_layout);
+ modifier.apply_render(&mut module, &mut context).unwrap();
+
+ assert!(context.sprite_grid_size.is_some());
+ assert_eq!(context.sprite_grid_size.unwrap(), UVec2::new(3, 4));
+ }
+
+ #[test]
+ fn mod_color_over_lifetime() {
+ let red: Vec4 = Vec4::new(1., 0., 0., 1.);
+ let blue: Vec4 = Vec4::new(0., 0., 1., 1.);
+ let mut gradient = Gradient::new();
+ gradient.add_key(0.5, red);
+ gradient.add_key(0.8, blue);
+ let modifier = ColorOverLifetimeModifier {
+ gradient: gradient.clone(),
+ blend: ColorBlendMode::Overwrite,
+ mask: ColorBlendMask::RGBA,
+ };
+
+ let mut module = Module::default();
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = module.texture_layout();
+ let mut context = RenderContext::new(&property_layout, &particle_layout, &texture_layout);
+ modifier.apply_render(&mut module, &mut context).unwrap();
+
+ assert!(context
+ .render_extra
+ .contains(&gradient.to_shader_code("key")));
+ }
+
+ #[test]
+ fn mod_size_over_lifetime() {
+ let x = Vec3::new(1., 0., 1.);
+ let y = Vec3::new(0., 1., 1.);
+ let mut gradient = Gradient::new();
+ gradient.add_key(0.5, x);
+ gradient.add_key(0.8, y);
+ let modifier = SizeOverLifetimeModifier {
+ gradient: gradient.clone(),
+ screen_space_size: false,
+ };
+
+ let mut module = Module::default();
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = module.texture_layout();
+ let mut context = RenderContext::new(&property_layout, &particle_layout, &texture_layout);
+ modifier.apply_render(&mut module, &mut context).unwrap();
+
+ assert!(context
+ .render_extra
+ .contains(&gradient.to_shader_code("key")));
+ }
+
+ #[test]
+ fn mod_set_color() {
+ let mut modifier = SetColorModifier::default();
+ assert_eq!(modifier.context(), ModifierContext::Render);
+ assert!(modifier.as_render().is_some());
+ assert!(modifier.as_render_mut().is_some());
+ assert_eq!(modifier.boxed_clone().context(), ModifierContext::Render);
+
+ let mut module = Module::default();
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = module.texture_layout();
+ let mut context = RenderContext::new(&property_layout, &particle_layout, &texture_layout);
+ modifier.apply_render(&mut module, &mut context).unwrap();
+
+ assert_eq!(modifier.color, CpuValue::from(Vec4::ZERO));
+ assert_eq!(context.vertex_code, "color = vec4<f32>(0.,0.,0.,0.);\n");
+ }
+
+ #[test]
+ fn mod_set_size() {
+ let mut modifier = SetSizeModifier::default();
+ assert_eq!(modifier.context(), ModifierContext::Render);
+ assert!(modifier.as_render().is_some());
+ assert!(modifier.as_render_mut().is_some());
+ assert_eq!(modifier.boxed_clone().context(), ModifierContext::Render);
+
+ let mut module = Module::default();
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = module.texture_layout();
+ let mut context = RenderContext::new(&property_layout, &particle_layout, &texture_layout);
+ modifier.apply_render(&mut module, &mut context).unwrap();
+
+ assert_eq!(modifier.size, CpuValue::from(Vec3::ZERO));
+ assert_eq!(context.vertex_code, "size = vec3<f32>(0.,0.,0.);\n");
+ }
+
+ #[test]
+ fn mod_orient() {
+ let mut modifier = OrientModifier::default();
+ assert_eq!(modifier.context(), ModifierContext::Render);
+ assert!(modifier.as_render().is_some());
+ assert!(modifier.as_render_mut().is_some());
+ assert_eq!(modifier.boxed_clone().context(), ModifierContext::Render);
+ }
+
+ #[test]
+ fn mod_orient_default() {
+ let mut module = Module::default();
+ let modifier = OrientModifier::default();
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = module.texture_layout();
+ let mut context = RenderContext::new(&property_layout, &particle_layout, &texture_layout);
+ modifier.apply_render(&mut module, &mut context).unwrap();
+
+ // TODO - less weak test...
+ assert!(context
+ .vertex_code
+ .contains("get_camera_rotation_effect_space"));
+ assert!(!context
+ .vertex_code
+ .contains("cos(particle_rot_in_cam_space)"));
+ assert!(!context.vertex_code.contains("let axis_x0 ="));
+ }
+
+ #[test]
+ fn mod_orient_rotation() {
+ let mut module = Module::default();
+ let modifier = OrientModifier::default().with_rotation(module.lit(1.));
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = module.texture_layout();
+ let mut context = RenderContext::new(&property_layout, &particle_layout, &texture_layout);
+ modifier.apply_render(&mut module, &mut context).unwrap();
+
+ // TODO - less weak test...
+ assert!(context
+ .vertex_code
+ .contains("get_camera_rotation_effect_space"));
+ assert!(context
+ .vertex_code
+ .contains("cos(particle_rot_in_cam_space)"));
+ assert!(!context.vertex_code.contains("let axis_x0 ="));
+ }
+
+ #[test]
+ fn mod_orient_rotation_face_camera() {
+ let mut module = Module::default();
+ let modifier =
+ OrientModifier::new(OrientMode::FaceCameraPosition).with_rotation(module.lit(1.));
+ let property_layout = PropertyLayout::default();
+ let particle_layout = ParticleLayout::default();
+ let texture_layout = module.texture_layout();
+ let mut context = RenderContext::new(&property_layout, &particle_layout, &texture_layout);
+ modifier.apply_render(&mut module, &mut context).unwrap();
+
+ // TODO - less weak test...
+ assert!(context
+ .vertex_code
+ .contains("get_camera_position_effect_space"));
+ assert!(context
+ .vertex_code
+ .contains("get_camera_rotation_effect_space"));
+ assert!(context
+ .vertex_code
+ .contains("cos(particle_rot_in_cam_space)"));
+ assert!(context.vertex_code.contains("let axis_x0 ="));
+ }
+}
diff --git a/vendor/bevy_hanabi/src/modifier/position.rs b/vendor/bevy_hanabi/src/modifier/position.rs
new file mode 100644
index 00000000..8445f18e
--- /dev/null
+++ b/vendor/bevy_hanabi/src/modifier/position.rs
@@ -0,0 +1,478 @@
+//! Modifiers to set the position of particles.
+//!
+//! These modifiers directly manipulate a particle's position. They're generally
+//! useful to initialize the position at spawn time, but can occasionally be
+//! used during simulation update to enforce a particular position.
+
+use bevy::prelude::*;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ calc_func_id, graph::ExprError, modifier::ShapeDimension, Attribute, BoxedModifier,
+ EvalContext, ExprHandle, Modifier, ModifierContext, Module, ShaderWriter,
+};
+
+/// A modifier to set the position of particles on or inside a circle/disc,
+/// randomly.
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::POSITION`]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct SetPositionCircleModifier {
+ /// The circle center, relative to the emitter position.
+ ///
+ /// Expression type: `Vec3`
+ pub center: ExprHandle,
+ /// The circle axis, which is the normalized normal of the circle's plane.
+ /// Set this to `Vec3::Z` for a 2D game.
+ ///
+ /// Expression type: `Vec3`
+ pub axis: ExprHandle,
+ /// The circle radius.
+ ///
+ /// Expression type: `f32`
+ pub radius: ExprHandle,
+ /// The shape dimension to set the position to.
+ ///
+ /// Note the particular interpretation of the dimension for this shape,
+ /// which unlike other shapes is a 2D one to begin with:
+ /// - [`ShapeDimension::Volume`] randomly position the particle anywhere on
+ /// the "volume" of the shape, which here is understood to be the 2D disc
+ /// surface including its origin (`dist <= r`).
+ /// - [`ShapeDimension::Surface`] randomly position the particle anywhere on
+ /// the "surface" of the shape, which here is understood to be the
+ /// perimeter circle, the set of points at a distance from the center
+ /// exactly equal to the radius (`dist == r`).
+ pub dimension: ShapeDimension,
+}
+
+impl SetPositionCircleModifier {
+ fn eval(
+ &self,
+ module: &mut Module,
+ context: &mut dyn EvalContext,
+ ) -> Result<String, ExprError> {
+ let func_id = calc_func_id(self);
+ let func_name = format!("set_position_circle_{0:016X}", func_id);
+
+ context.make_fn(
+ &func_name,
+ "particle: ptr<function, Particle>",
+ None,
+ module,
+ &mut |m: &mut Module, ctx: &mut dyn EvalContext| -> Result<String, ExprError> {
+ let center = ctx.eval(m, self.center)?;
+ let axis = ctx.eval(m, self.axis)?;
+
+ let radius = match self.dimension {
+ ShapeDimension::Surface => {
+ // Constant radius
+ format!("let r = {};", ctx.eval(m, self.radius)?)
+ }
+ ShapeDimension::Volume => {
+ // Radius uniformly distributed in [0:1], then square-rooted
+ // to account for the increased perimeter covered by increased radii.
+ format!("let r = sqrt(frand()) * ({});", ctx.eval(m, self.radius)?)
+ }
+ };
+
+ Ok(format!(
+ r##" // Circle center
+ let c = {};
+ // Circle basis
+ let n = {};
+ let sign = step(0.0, n.z) * 2.0 - 1.0;
+ let a = -1.0 / (sign + n.z);
+ let b = n.x * n.y * a;
+ let tangent = vec3<f32>(1.0 + sign * n.x * n.x * a, sign * b, -sign * n.x);
+ let bitangent = vec3<f32>(b, sign + n.y * n.y * a, -n.y);
+ // Circle radius
+ {}
+ // Spawn random point on/in circle
+ let theta = frand() * tau;
+ let dir = tangent * cos(theta) + bitangent * sin(theta);
+ (*particle).{} = c + r * dir;
+"##,
+ center,
+ axis,
+ radius,
+ Attribute::POSITION.name(),
+ ))
+ },
+ )?;
+
+ let code = format!("{}(&particle);\n", func_name);
+
+ Ok(code)
+ }
+}
+
+impl Modifier for SetPositionCircleModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Init | ModifierContext::Update
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ &[Attribute::POSITION]
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let code = self.eval(module, context)?;
+ context.main_code += &code;
+ Ok(())
+ }
+}
+
+/// A modifier to set the position of particles on or inside a sphere, randomly.
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::POSITION`]
+#[derive(Debug, Clone, Copy, PartialEq, Hash, Reflect, Serialize, Deserialize)]
+pub struct SetPositionSphereModifier {
+ /// The sphere center, relative to the emitter position.
+ ///
+ /// Expression type: `Vec3`
+ pub center: ExprHandle,
+ /// The sphere radius.
+ ///
+ /// Expression type: `f32`
+ pub radius: ExprHandle,
+ /// The shape dimension to set the position to.
+ pub dimension: ShapeDimension,
+}
+
+impl SetPositionSphereModifier {
+ fn eval(
+ &self,
+ module: &mut Module,
+ context: &mut dyn EvalContext,
+ ) -> Result<String, ExprError> {
+ let func_id = calc_func_id(self);
+ let func_name = format!("set_position_sphere_{0:016X}", func_id);
+
+ context.make_fn(
+ &func_name,
+ "particle: ptr<function, Particle>",
+ None,
+ module,
+ &mut |m: &mut Module, ctx: &mut dyn EvalContext| -> Result<String, ExprError> {
+ let center = ctx.eval(m, self.center)?;
+
+ let radius = match self.dimension {
+ ShapeDimension::Surface => {
+ // Constant radius
+ format!("let r = {};", ctx.eval(m, self.radius)?)
+ }
+ ShapeDimension::Volume => {
+ // Radius uniformly distributed in [0:1], then scaled by ^(1/3) in 3D
+ // to account for the increased surface covered by increased radii.
+ // https://stackoverflow.com/questions/54544971/how-to-generate-uniform-random-points-inside-d-dimension-ball-sphere
+ format!(
+ "let r = pow(frand(), 1./3.) * ({});",
+ ctx.eval(m, self.radius)?
+ )
+ }
+ };
+
+ Ok(format!(
+ r##" // Sphere center
+ let c = {};
+
+ // Sphere radius
+ {}
+
+ // Spawn randomly along the sphere surface using Archimedes's theorem
+ let theta = frand() * tau;
+ let z = frand() * 2. - 1.;
+ let phi = acos(z);
+ let sinphi = sin(phi);
+ let x = sinphi * cos(theta);
+ let y = sinphi * sin(theta);
+ let dir = vec3<f32>(x, y, z);
+ (*particle).{} = c + r * dir;
+"##,
+ center,
+ radius,
+ Attribute::POSITION.name(),
+ ))
+ },
+ )?;
+
+ let code = format!("{}(&particle);\n", func_name);
+
+ Ok(code)
+ }
+}
+
+impl Modifier for SetPositionSphereModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Init | ModifierContext::Update
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ &[Attribute::POSITION]
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let code = self.eval(module, context)?;
+ context.main_code += &code;
+ Ok(())
+ }
+}
+
+/// A modifier to set the position of particles on a truncated 3D cone.
+///
+/// The 3D cone is oriented along the Y axis, with its origin at the center of
+/// the base circle of the cone. The center of the top circle truncating the
+/// cone is located at a positive Y.
+///
+/// Particles are moved somewhere inside the volume or on the surface of a
+/// truncated 3D cone defined by its base radius, its top radius, and the height
+/// of the cone section.
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::POSITION`]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct SetPositionCone3dModifier {
+ /// The cone height along its axis, between the base and top radii.
+ ///
+ /// Expression type: `f32`
+ pub height: ExprHandle,
+ /// The cone radius at its base, perpendicularly to its axis.
+ ///
+ /// Expression type: `f32`
+ pub base_radius: ExprHandle,
+ /// The cone radius at its truncated top, perpendicularly to its axis.
+ /// This can be set to zero to get a non-truncated cone.
+ ///
+ /// Expression type: `f32`
+ pub top_radius: ExprHandle,
+ /// The shape dimension to set the position to.
+ pub dimension: ShapeDimension,
+}
+
+impl SetPositionCone3dModifier {
+ fn eval(
+ &self,
+ module: &mut Module,
+ context: &mut dyn EvalContext,
+ ) -> Result<String, ExprError> {
+ let func_id = calc_func_id(self);
+ let func_name = format!("set_position_cone3d_{0:016X}", func_id);
+
+ context.make_fn(
+ &func_name,
+ "particle: ptr<function, Particle>",
+ None,
+ module,
+ &mut |m: &mut Module, ctx: &mut dyn EvalContext| -> Result<String, ExprError> {
+ let height = ctx.eval(m, self.height)?;
+ let top_radius = ctx.eval(m, self.top_radius)?;
+ let base_radius = ctx.eval(m, self.base_radius)?;
+
+ Ok(format!(
+ r##" // Truncated cone height
+ let h0 = {0};
+ // Random height ratio
+ let alpha_h = pow(frand(), 1.0 / 3.0);
+ // Random delta height from top
+ let h = h0 * alpha_h;
+ // Top radius
+ let rt = {1};
+ // Bottom radius
+ let rb = {2};
+ // Radius at height h
+ let r0 = rb + (rt - rb) * alpha_h;
+ // Random delta radius
+ let alpha_r = sqrt(frand());
+ // Random radius at height h
+ let r = r0 * alpha_r;
+ // Random base angle
+ let theta = frand() * tau;
+ let cost = cos(theta);
+ let sint = sin(theta);
+ // Random position relative to truncated cone origin (not apex)
+ let x = r * cost;
+ let y = h;
+ let z = r * sint;
+ (*particle).{3} = vec3<f32>(x, y, z);
+"##,
+ height,
+ top_radius,
+ base_radius,
+ Attribute::POSITION.name(),
+ ))
+ },
+ )?;
+
+ let code = format!("{}(&particle);\n", func_name);
+
+ Ok(code)
+ }
+}
+
+impl Modifier for SetPositionCone3dModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Init | ModifierContext::Update
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ &[Attribute::POSITION]
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let code = self.eval(module, context)?;
+ context.main_code += &code;
+ Ok(())
+ }
+}
+
+/// A modifier to set the position of particles on a box.
+///
+/// The box is axis aligned.
+///
+/// Particles are moved somewhere inside the volume or on the surface of a
+/// box defined by its extent.
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::POSITION`]
+#[derive(Clone, Copy, Hash, Reflect)]
+pub struct SetPositionBoxModifier {
+ /// The box center, relative to the emitter position.
+ ///
+ /// Expression type: `Vec3`
+ pub center: ExprHandle,
+ /// The extent of the box.
+ ///
+ /// Expression type: `Vec3`
+ pub extent: ExprHandle,
+ /// The shape dimension to set the position to.
+ pub dimension: ShapeDimension,
+}
+
+impl SetPositionBoxModifier {
+ fn eval(
+ &self,
+ module: &mut Module,
+ context: &mut dyn EvalContext,
+ ) -> Result<String, ExprError> {
+ let func_id = calc_func_id(self);
+ let func_name = format!("set_position_box_{0:016X}", func_id);
+
+ context.make_fn(
+ &func_name,
+ "particle: ptr<function, Particle>",
+ None,
+ module,
+ &mut |m: &mut Module, ctx: &mut dyn EvalContext| -> Result<String, ExprError> {
+ let center = ctx.eval(m, self.center)?;
+ let extent = ctx.eval(m, self.extent)?;
+
+ let code = match self.dimension {
+ ShapeDimension::Surface => {
+ format!(
+ r#" let center = {};
+ let extent = {};
+
+ let face = frand();
+ let rand1 = frand() - 0.5;
+ let rand2 = frand() - 0.5;
+ let fixed = 0.5;
+
+ var x: f32;
+ var y: f32;
+ var z: f32;
+
+ if face < (1. / 6.) {{
+ x = rand1 * extent.x;
+ y = fixed * extent.y;
+ z = rand2 * extent.z;
+ }} else if face < (2. / 6.) {{
+ x = rand1 * extent.x;
+ y = -fixed * extent.y;
+ z = rand2 * extent.z;
+ }} else if face < (3. / 6.) {{
+ x = fixed * extent.x;
+ y = rand1 * extent.y;
+ z = rand2 * extent.z;
+ }} else if face < (4. / 6.) {{
+ x = -fixed * extent.x;
+ y = rand1 * extent.y;
+ z = rand2 * extent.z;
+ }} else if face < (5. / 6.) {{
+ x = rand1 * extent.x;
+ y = rand2 * extent.y;
+ z = fixed * extent.z;
+ }} else {{
+ x = rand1 * extent.x;
+ y = rand2 * extent.y;
+ z = -fixed * extent.z;
+ }}
+ (*particle).{} = center + vec3(x, y, z);
+"#,
+ center,
+ extent,
+ Attribute::POSITION.name()
+ )
+ }
+ ShapeDimension::Volume => format!(
+ r#" let center = {};
+ let extent = {};
+ let mult = frand3() - 0.5;
+ (*particle).{} = center + extent * mult;
+"#,
+ center,
+ extent,
+ Attribute::POSITION.name()
+ ),
+ };
+
+ Ok(code)
+ },
+ )?;
+
+ let code = format!("{}(&particle);\n", func_name);
+
+ Ok(code)
+ }
+}
+
+impl Modifier for SetPositionBoxModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Init | ModifierContext::Update
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ &[Attribute::POSITION]
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let code = self.eval(module, context)?;
+ context.main_code += &code;
+ Ok(())
+ }
+}
diff --git a/vendor/bevy_hanabi/src/modifier/registry.rs b/vendor/bevy_hanabi/src/modifier/registry.rs
new file mode 100644
index 00000000..2d8a4ca0
--- /dev/null
+++ b/vendor/bevy_hanabi/src/modifier/registry.rs
@@ -0,0 +1,449 @@
+//! Type registration for modifiers.
+//!
+//! This module contains utilities used to reflect and serialize
+//! [`EffectAsset`]. In general, you don't need to directly interact with those;
+//! instead, use [`EffectAsset::serialize`], as well as the
+//! [`EffectAssetSerializer`] and [`EffectAssetDeserializer`].
+//!
+//! _Modifiers_ are objects implementing the [`Modifier`] trait. Because a trait
+//! abstracts the concrete object type, it cannot be used as is with the Bevy
+//! reflection and serialization infrastructure. Bevy does allow reflecting
+//! traits with `#[reflect_trait]`, but due to other limitations (notably,
+//! `Box<T>` not being reflected), this is not sufficient to easily make
+//! modifiers reflected and serializable.
+//!
+//! This module contains some utilities to enable reflecting and serializing
+//! modifiers. At the core, we register for each conrete modifier type some
+//! [`ReflectModifier`] type data, which essentially contains a factory function
+//! used to construct an instance of that type during deserialization. We also
+//! define [`Modifiers`], an ordered collection (`Vec`) of [`BoxedModifier`]
+//! objects, and provide some implementation of Bevy's [`SerializeWithRegistry`]
+//! and [`DeserializeWithRegistry`]. Those trait are automatically picked up by
+//! Bevy's reflect-based serialization utilities like [`TypedReflectSerializer`]
+//! and [`TypedReflectDeserializer`]. They are in turn used by
+//! [`EffectAssetSerializer`] and [`EffectAssetDeserializer`], which are custom
+//! de/serializer implementations for [`EffectAsset`] which handle the
+//! collections of modifiers for the init, update, and render passes of each
+//! effect.
+//!
+//! [`EffectAsset`]: crate::EffectAsset
+//! [`EffectAsset::serialize`]: crate::EffectAsset::serialize
+//! [`EffectAssetSerializer`]: crate::EffectAssetSerializer
+//! [`EffectAssetDeserializer`]: crate::EffectAssetDeserializer
+//! [`SerializeWithRegistry`]: bevy::reflect::serde::SerializeWithRegistry
+//! [`DeserializeWithRegistry`]: bevy::reflect::serde::DeserializeWithRegistry
+//! [`TypedReflectSerializer`]: bevy::reflect::serde::TypedReflectSerializer
+//! [`TypedReflectDeserializer`]: bevy::reflect::serde::TypedReflectDeserializer
+
+use std::any::TypeId;
+
+use bevy::{
+ ecs::reflect::AppTypeRegistry,
+ log::warn,
+ reflect::{
+ serde::{ReflectDeserializer, TypedReflectSerializer},
+ PartialReflect, Reflect, TypeRegistry,
+ },
+};
+use serde::{
+ de::DeserializeSeed,
+ ser::{Error as _, SerializeMap as _},
+ Serializer,
+};
+
+use crate::{BoxedModifier, Modifier, ModifierContext, Module};
+
+/// Factory function to build a default modifier instance.
+///
+/// The factory can use the given [`Module`] to register some expressions in
+/// order to default-initialize itself.
+pub type ModifierFactory = fn(&mut Module) -> BoxedModifier;
+
+/// Type data attached to a modifier type's registration in
+/// [`AppTypeRegistry`]. Carrying both fields here means the editor
+/// never needs to construct an instance just to query
+/// `Modifier::context()`.
+#[derive(Clone, Copy)]
+pub struct ReflectModifier {
+ /// Factory function.
+ pub factory: ModifierFactory,
+ /// Modifier context, cached from [`Modifier::context()`].
+ pub context: ModifierContext,
+}
+
+impl ReflectModifier {}
+
+/// Register a [`ReflectModifier`] type data for the given [`Modifier`].
+pub fn register_reflect_modifier<T: Modifier>(
+ type_registry: &AppTypeRegistry,
+ factory: ModifierFactory,
+) {
+ // Create a dummy instance to cache its context. This also serves as a
+ // validation layer to check the returned object type is correct.
+ let context = {
+ let mut module = Module::default();
+ let modifier = factory(&mut module);
+ let context = modifier.context();
+ let any = modifier.into_any();
+ assert_eq!(
+ any.type_id(),
+ TypeId::of::<T>(),
+ "Factory for modifier type '{}' returned a different object of type.",
+ std::any::type_name::<T>()
+ );
+ context
+ };
+
+ let reflect_modifier = ReflectModifier { factory, context };
+
+ match type_registry.write().get_mut(TypeId::of::<T>()) {
+ Some(type_registration) => type_registration.insert(reflect_modifier),
+ None => warn!(
+ "insert_reflect_modifier: type {} not found in TypeRegistry",
+ std::any::type_name::<T>()
+ ),
+ }
+}
+
+// Serialize a Box<dyn Modifier> by delegating to the reflect serializer. The
+// reflect serializer emits the type tag and the inner data as a single map
+// entry.
+impl bevy::reflect::serde::SerializeWithRegistry for BoxedModifier {
+ fn serialize<S>(&self, serializer: S, registry: &TypeRegistry) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ // Get an &dyn Reflect for the boxed modifier
+ let reflect: &dyn Reflect = Reflect::as_reflect(&**self);
+
+ // Serialize as a single-entry map { "full::type::Path": <typed-data> }
+ let type_path = reflect
+ .get_represented_type_info()
+ .ok_or_else(|| {
+ S::Error::custom("cannot serialize dynamic value without represented type")
+ })?
+ .type_path();
+
+ let mut map = serializer.serialize_map(Some(1))?;
+ map.serialize_entry(type_path, &TypedReflectSerializer::new(reflect, registry))?;
+ map.end()
+ }
+}
+
+// Deserialize a Box<dyn Modifier> using the reflect deserializer and the
+// ReflectModifier type data to construct the concrete Modifier instance.
+impl<'de> bevy::reflect::serde::DeserializeWithRegistry<'de> for BoxedModifier {
+ fn deserialize<D>(deserializer: D, registry: &TypeRegistry) -> Result<Self, D::Error>
+ where
+ D: serde::de::Deserializer<'de>,
+ {
+ // First, use the generic reflect deserializer which expects a single-entry map
+ // { "full::type::Path": <value> } and returns a Box<dyn PartialReflect> (e.g.
+ // DynamicStruct).
+ let reflect_seed = ReflectDeserializer::new(registry);
+ let boxed_partial: Box<dyn PartialReflect> = reflect_seed
+ .deserialize(deserializer)
+ .map_err(serde::de::Error::custom)?;
+
+ // Obtain the type id represented by the deserialized reflect value.
+ let type_info = boxed_partial.get_represented_type_info().ok_or_else(|| {
+ serde::de::Error::custom("reflected value has no represented type info")
+ })?;
+ let type_id = type_info.type_id();
+
+ // Lookup the ReflectModifier type data that must have been registered for this
+ // concrete modifier type (register_reflect_modifier<T>). That type-data
+ // contains the factory used to create a default instance and cached
+ // ModifierContext.
+ let reflect_modifier = registry
+ .get_type_data::<ReflectModifier>(type_id)
+ .ok_or_else(|| {
+ serde::de::Error::custom(format!(
+ "no ReflectModifier type data for '{}'",
+ type_info.type_path()
+ ))
+ })?;
+
+ // Build a default instance using the stored factory. The factory currently
+ // takes a &mut Module; construct a temporary Module (same as
+ // register_reflect_modifier).
+ let mut module = Module::default();
+ let mut modifier: BoxedModifier = (reflect_modifier.factory)(&mut module);
+
+ // Apply the deserialized partial reflect value into the instance.
+ let reflect_mut: &mut dyn Reflect = Reflect::as_reflect_mut(&mut *modifier);
+ reflect_mut.apply(boxed_partial.as_partial_reflect());
+
+ Ok(modifier)
+ }
+}
+
+use std::fmt::Formatter;
+use std::ops::{Deref, DerefMut};
+
+use bevy::reflect::serde::{ReflectDeserializeWithRegistry, ReflectSerializeWithRegistry};
+use serde::de::{SeqAccess, Visitor};
+use serde::ser::SerializeSeq;
+
+/// Ordered collection of [`BoxedModifier`] objects.
+///
+/// This is a wrapper over a `Vec<BoxedModifier>`, with additional reflection
+/// and serialization features.
+#[derive(Default, Clone, Reflect)]
+#[reflect(SerializeWithRegistry, DeserializeWithRegistry, from_reflect = false)]
+pub struct Modifiers(#[reflect(ignore)] pub Vec<BoxedModifier>);
+
+impl Deref for Modifiers {
+ type Target = Vec<BoxedModifier>;
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+impl DerefMut for Modifiers {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.0
+ }
+}
+
+impl bevy::reflect::serde::SerializeWithRegistry for Modifiers {
+ fn serialize<S>(&self, serializer: S, registry: &TypeRegistry) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ struct Elem<'a> {
+ boxed: &'a BoxedModifier,
+ registry: &'a TypeRegistry,
+ }
+
+ impl<'a> serde::Serialize for Elem<'a> {
+ fn serialize<S2>(&self, serializer: S2) -> Result<S2::Ok, S2::Error>
+ where
+ S2: serde::Serializer,
+ {
+ use bevy::reflect::serde::SerializeWithRegistry;
+ self.boxed.serialize(serializer, self.registry)
+ }
+ }
+
+ let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
+ for m in &self.0 {
+ seq.serialize_element(&Elem { boxed: m, registry })?;
+ }
+ seq.end()
+ }
+}
+
+impl<'de> bevy::reflect::serde::DeserializeWithRegistry<'de> for Modifiers {
+ fn deserialize<D>(deserializer: D, registry: &TypeRegistry) -> Result<Self, D::Error>
+ where
+ D: serde::de::Deserializer<'de>,
+ {
+ // Deserialize the Modifiers collection, which is a sequence of single-item
+ // {typename:value} maps.
+
+ struct ModifiersVisitor<'a> {
+ registry: &'a TypeRegistry,
+ }
+
+ impl<'a, 'de> Visitor<'de> for ModifiersVisitor<'a> {
+ type Value = Modifiers;
+
+ fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
+ write!(formatter, "a list of modifiers")
+ }
+
+ fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
+ where
+ A: SeqAccess<'de>,
+ {
+ // Each element is a single-entry map { "full::type::Path": <value> }.
+ // Implement a DeserializeSeed that parses that map into a BoxedModifier.
+ struct ElemSeed<'a> {
+ registry: &'a TypeRegistry,
+ }
+
+ impl<'de2, 'a> serde::de::DeserializeSeed<'de2> for ElemSeed<'a> {
+ type Value = BoxedModifier;
+
+ fn deserialize<D2>(self, deserializer: D2) -> Result<Self::Value, D2::Error>
+ where
+ D2: serde::de::Deserializer<'de2>,
+ {
+ use bevy::reflect::serde::DeserializeWithRegistry;
+ BoxedModifier::deserialize(deserializer, self.registry)
+ }
+ }
+
+ let mut vec = Vec::new();
+ while let Some(modifier) = seq.next_element_seed(ElemSeed {
+ registry: self.registry,
+ })? {
+ vec.push(modifier);
+ }
+
+ Ok(Modifiers(vec))
+ }
+ }
+
+ let modifiers: Self = deserializer.deserialize_seq(ModifiersVisitor { registry })?;
+ Ok(modifiers)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use bevy::math::Vec3;
+ use ron::ser::PrettyConfig;
+ use serde::de::DeserializeSeed;
+
+ use super::*;
+ use crate::{
+ register_modifiers, AccelModifier, EffectAsset, EffectAssetDeserializer,
+ EffectAssetSerializer, RenderModifier, SpawnerSettings,
+ };
+
+ /// Serialize and deserialize a [`Modifiers`] container.
+ #[test]
+ fn serde_modifiers() {
+ use bevy::reflect::{
+ serde::{TypedReflectDeserializer, TypedReflectSerializer},
+ Reflect,
+ };
+
+ use crate::{Attribute, SetAttributeModifier, SetPositionSphereModifier, ShapeDimension};
+
+ let mut module = Module::default();
+
+ // Create a Modifiers container with 2 different modifiers
+ let mut modifiers = vec![];
+ let m1 = SetAttributeModifier::new(Attribute::SIZE, module.lit(2.));
+ let bm1: BoxedModifier = Box::new(m1);
+ modifiers.push(bm1);
+ let m2 = SetPositionSphereModifier {
+ center: module.lit(Vec3::ZERO),
+ radius: module.lit(1.),
+ dimension: ShapeDimension::Surface,
+ };
+ let bm2: BoxedModifier = Box::new(m2);
+ modifiers.push(bm2);
+ let modifiers = Modifiers(modifiers);
+
+ // Prepare a type registry with all known modifiers registered.
+ let type_registry = AppTypeRegistry::new_with_derived_types();
+ register_modifiers(&type_registry);
+ let registry = type_registry.read();
+
+ // Serialize via reflection, so that the SerializeWithRegistry impl of Modifiers
+ // get automatically picked up and used.
+ let s = ron::ser::to_string_pretty(
+ &TypedReflectSerializer::new(modifiers.as_reflect(), &registry),
+ PrettyConfig::default(),
+ )
+ .unwrap();
+ println!("{s}");
+
+ // The serialized string must contain the type names of all modifiers, because
+ // they use dynamic dispatching.
+ assert!(s.contains(std::any::type_name::<SetAttributeModifier>()));
+ assert!(s.contains(std::any::type_name::<SetPositionSphereModifier>()));
+ // The Modifiers wrapper itself does not necessarily appear in the serialized
+ // form here because we're serializing the inner representation
+ // directly.
+ assert!(!s.contains(std::any::type_name::<Modifiers>()));
+
+ // Deserialize via reflection again. This also picks up the
+ // DeserializeWithRegistry impl of Modifiers automatically, which recovers the
+ // concrete object via the ReflectModifier type data factory.
+ let mut de = ron::de::Deserializer::from_str(&s).unwrap();
+ let type_registration = registry.get(std::any::TypeId::of::<Modifiers>()).unwrap();
+ let deserializer = TypedReflectDeserializer::new(type_registration, &registry);
+ let mods = deserializer.deserialize(&mut de).unwrap();
+
+ // Recover and check the deserialized Modifiers
+ assert!(mods.represents::<Modifiers>());
+ let mods = mods.try_downcast::<Modifiers>().unwrap();
+ assert_eq!(mods.0.len(), modifiers.0.len());
+ for (mi, smi) in mods.0.iter().zip(modifiers.0.iter()) {
+ use std::any::Any;
+
+ assert_eq!(
+ mi.get_represented_type_info().type_id(),
+ smi.get_represented_type_info().type_id()
+ );
+ }
+
+ // Recover and check the individual modifiers
+ let serde_m1 = mods.0[0]
+ .as_reflect()
+ .downcast_ref::<SetAttributeModifier>()
+ .unwrap();
+ let serde_m2 = mods.0[1]
+ .as_reflect()
+ .downcast_ref::<SetPositionSphereModifier>()
+ .unwrap();
+ assert_eq!(m1, *serde_m1);
+ assert_eq!(m2, *serde_m2);
+ }
+
+ fn cmp_modifiers<'a>(
+ a: impl Iterator<Item = &'a dyn Modifier>,
+ b: impl Iterator<Item = &'a dyn Modifier>,
+ ) {
+ let a = a.collect::<Vec<_>>();
+ let b = b.collect::<Vec<_>>();
+ assert_eq!(a.len(), b.len());
+ for (a, b) in a.iter().zip(b.iter()) {
+ assert_eq!(a.context(), b.context());
+ }
+ }
+
+ fn cmp_render_modifiers<'a>(
+ a: impl Iterator<Item = &'a dyn RenderModifier>,
+ b: impl Iterator<Item = &'a dyn RenderModifier>,
+ ) {
+ let a = a.collect::<Vec<_>>();
+ let b = b.collect::<Vec<_>>();
+ assert_eq!(a.len(), b.len());
+ for (a, b) in a.iter().zip(b.iter()) {
+ assert_eq!(a.context(), b.context());
+ }
+ }
+
+ /// Serialize and deserialize a full [`EffectAsset`].
+ #[test]
+ fn serde_asset() {
+ let mut module = Module::default();
+ let accel_mod = AccelModifier::new(module.lit(Vec3::X));
+ let asset =
+ EffectAsset::new(24, SpawnerSettings::once(3.0.into()), module).update(accel_mod);
+
+ let type_registry = AppTypeRegistry::new_with_derived_types();
+ register_modifiers(&type_registry);
+
+ // ser
+ let registry = type_registry.read();
+ let serializer = EffectAssetSerializer::new(&asset, &registry);
+ let json = ron::ser::to_string_pretty(&serializer, PrettyConfig::default()).unwrap();
+ println!("{json}");
+
+ // de
+ let mut deserializer = ron::de::Deserializer::from_str(&json).unwrap();
+ let deserialize = EffectAssetDeserializer::new(&registry);
+ let serde_asset = deserialize.deserialize(&mut deserializer).unwrap();
+
+ // Validate what can be
+ assert_eq!(asset.name, serde_asset.name);
+ assert_eq!(asset.capacity(), serde_asset.capacity());
+ assert_eq!(asset.spawner, serde_asset.spawner);
+ assert_eq!(asset.z_layer_2d, serde_asset.z_layer_2d);
+ assert_eq!(asset.simulation_space, serde_asset.simulation_space);
+ assert_eq!(asset.simulation_condition, serde_asset.simulation_condition);
+ assert_eq!(asset.prng_seed, serde_asset.prng_seed);
+ assert_eq!(asset.motion_integration, serde_asset.motion_integration);
+ assert_eq!(asset.alpha_mode, serde_asset.alpha_mode);
+ cmp_modifiers(asset.init_modifiers(), serde_asset.init_modifiers());
+ cmp_modifiers(asset.update_modifiers(), serde_asset.update_modifiers());
+ cmp_render_modifiers(asset.render_modifiers(), serde_asset.render_modifiers());
+ }
+}
diff --git a/vendor/bevy_hanabi/src/modifier/velocity.rs b/vendor/bevy_hanabi/src/modifier/velocity.rs
new file mode 100644
index 00000000..4f7e9bf9
--- /dev/null
+++ b/vendor/bevy_hanabi/src/modifier/velocity.rs
@@ -0,0 +1,244 @@
+//! Modifiers to set the velocity of particles.
+//!
+//! These modifiers directly manipulate a particle's velocity. They're generally
+//! useful to initialize the velocity at spawn time, but can occasionally be
+//! used during simulation update to enforce a particular velocity. The velocity
+//! in turn drives the position update during Euler motion integration.
+//!
+//! ```txt
+//! particle.position += particle.velocity * simulation.delta_time;
+//! ```
+
+use bevy::prelude::*;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ calc_func_id, graph::ExprError, Attribute, BoxedModifier, EvalContext, ExprHandle, Modifier,
+ ModifierContext, Module, ShaderWriter,
+};
+
+/// A modifier to set the velocity of particles radially on a circle.
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::POSITION`]
+/// - [`Attribute::VELOCITY`]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct SetVelocityCircleModifier {
+ /// The circle center, relative to the emitter position.
+ ///
+ /// Expression type: `Vec3`
+ pub center: ExprHandle,
+ /// The circle axis, which is the normalized normal of the circle's plane.
+ /// Set this to `Vec3::Z` for a 2D game.
+ ///
+ /// Expression type: `Vec3`
+ pub axis: ExprHandle,
+ /// The initial speed distribution of a particle when it spawns.
+ ///
+ /// Expression type: `f32`
+ pub speed: ExprHandle,
+}
+
+impl SetVelocityCircleModifier {
+ fn eval(
+ &self,
+ module: &mut Module,
+ context: &mut dyn EvalContext,
+ ) -> Result<String, ExprError> {
+ let func_id = calc_func_id(self);
+ let func_name = format!("set_velocity_circle_{0:016X}", func_id);
+
+ context.make_fn(
+ &func_name,
+ "particle: ptr<function, Particle>",
+ None,
+ module,
+ &mut |m: &mut Module, ctx: &mut dyn EvalContext| -> Result<String, ExprError> {
+ let center = ctx.eval(m, self.center)?;
+ let axis = ctx.eval(m, self.axis)?;
+ let speed = ctx.eval(m, self.speed)?;
+
+ Ok(format!(
+ r##" let delta = (*particle).{0} - ({1});
+ let radial = normalize(delta - dot(delta, {2}) * ({2}));
+ (*particle).{3} = radial * ({4});
+"##,
+ Attribute::POSITION.name(),
+ center,
+ axis,
+ Attribute::VELOCITY.name(),
+ speed,
+ ))
+ },
+ )?;
+
+ let code = format!("{}(&particle);\n", func_name);
+
+ Ok(code)
+ }
+}
+
+impl Modifier for SetVelocityCircleModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Init | ModifierContext::Update
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ &[Attribute::POSITION, Attribute::VELOCITY]
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let code = self.eval(module, context)?;
+ context.main_code += &code;
+ Ok(())
+ }
+}
+
+/// A modifier to set the velocity of particles to a spherical distribution.
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::POSITION`]
+/// - [`Attribute::VELOCITY`]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct SetVelocitySphereModifier {
+ /// Center of the sphere. The radial direction of the velocity is the
+ /// direction from the sphere center to the particle position.
+ ///
+ /// Expression type: `Vec3`
+ pub center: ExprHandle,
+ /// The initial speed distribution of a particle when it spawns.
+ ///
+ /// Expression type: `f32`
+ pub speed: ExprHandle,
+}
+
+impl SetVelocitySphereModifier {
+ fn eval(
+ &self,
+ module: &mut Module,
+ context: &mut dyn EvalContext,
+ ) -> Result<String, ExprError> {
+ let center = context.eval(module, self.center)?;
+ let speed = context.eval(module, self.speed)?;
+ let code = format!(
+ "particle.{} = normalize(particle.{} - ({})) * ({});\n",
+ Attribute::VELOCITY.name(),
+ Attribute::POSITION.name(),
+ center,
+ speed
+ );
+ Ok(code)
+ }
+}
+
+impl Modifier for SetVelocitySphereModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Init | ModifierContext::Update
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ &[Attribute::POSITION, Attribute::VELOCITY]
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let code = self.eval(module, context)?;
+ context.main_code += &code;
+ Ok(())
+ }
+}
+
+/// A modifier to set the velocity of particles along the tangent to an axis.
+///
+/// # Attributes
+///
+/// This modifier requires the following particle attributes:
+/// - [`Attribute::POSITION`]
+/// - [`Attribute::VELOCITY`]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
+pub struct SetVelocityTangentModifier {
+ /// Origin from which to derive the radial axis based on the particle
+ /// position.
+ ///
+ /// Expression type: `Vec3`
+ pub origin: ExprHandle,
+ /// Axis defining the normal to the plane containing the radial and tangent
+ /// axes.
+ ///
+ /// Expression type: `Vec3`
+ pub axis: ExprHandle,
+ /// The initial speed distribution of a particle when it spawns.
+ ///
+ /// Expression type: `f32`
+ pub speed: ExprHandle,
+}
+
+impl SetVelocityTangentModifier {
+ fn eval(
+ &self,
+ module: &mut Module,
+ context: &mut dyn EvalContext,
+ ) -> Result<String, ExprError> {
+ let func_id = calc_func_id(self);
+ let func_name = format!("set_velocity_tangent_{0:016X}", func_id);
+
+ context.make_fn(
+ &func_name,
+ "particle: ptr<function, Particle>",
+ None,
+ module,
+ &mut |m: &mut Module, ctx: &mut dyn EvalContext| -> Result<String, ExprError> {
+ let origin = ctx.eval(m, self.origin)?;
+ let axis = ctx.eval(m, self.axis)?;
+ let speed = ctx.eval(m, self.speed)?;
+
+ Ok(format!(
+ r##" let radial = (*particle).{0} - ({1});
+ let tangent = normalize(cross({2}, radial));
+ (*particle).{3} = tangent * ({4});
+"##,
+ Attribute::POSITION.name(),
+ origin,
+ axis,
+ Attribute::VELOCITY.name(),
+ speed,
+ ))
+ },
+ )?;
+
+ let code = format!("{}(&particle);\n", func_name);
+
+ Ok(code)
+ }
+}
+
+impl Modifier for SetVelocityTangentModifier {
+ fn context(&self) -> ModifierContext {
+ ModifierContext::Init | ModifierContext::Update
+ }
+
+ fn attributes(&self) -> &[Attribute] {
+ &[Attribute::POSITION, Attribute::VELOCITY]
+ }
+
+ fn boxed_clone(&self) -> BoxedModifier {
+ Box::new(*self)
+ }
+
+ fn apply(&self, module: &mut Module, context: &mut ShaderWriter) -> Result<(), ExprError> {
+ let code = self.eval(module, context)?;
+ context.main_code += &code;
+ Ok(())
+ }
+}
diff --git a/vendor/bevy_hanabi/src/plugin.rs b/vendor/bevy_hanabi/src/plugin.rs
new file mode 100644
index 00000000..cc0c5596
--- /dev/null
+++ b/vendor/bevy_hanabi/src/plugin.rs
@@ -0,0 +1,590 @@
+use std::borrow::Cow;
+
+#[cfg(feature = "2d")]
+use bevy::core_pipeline::core_2d::Transparent2d;
+#[cfg(feature = "3d")]
+use bevy::core_pipeline::core_3d::{AlphaMask3d, Opaque3d, Transparent3d};
+use bevy::{
+ asset::uuid_handle,
+ camera::visibility::VisibilitySystems,
+ prelude::*,
+ render::{
+ extract_component::ExtractComponentPlugin,
+ render_asset::prepare_assets,
+ render_phase::DrawFunctions,
+ render_resource::{SpecializedComputePipelines, SpecializedRenderPipelines},
+ renderer::{RenderAdapterInfo, RenderDevice},
+ texture::GpuImage,
+ view::prepare_view_uniforms,
+ Render, RenderApp, RenderSystems,
+ },
+ time::{time_system, TimeSystems},
+};
+
+use crate::{asset::EffectAssetLoader, render::extract_main_view};
+use crate::{
+ asset::{DefaultMesh, EffectAsset},
+ compile_effects,
+ properties::EffectProperties,
+ register_modifiers,
+ render::{
+ allocate_effects, allocate_events, allocate_metadata, allocate_parent_child_infos,
+ allocate_properties, batch_effects, clear_previous_frame_resizes,
+ clear_transient_batch_inputs, extract_effect_events, extract_effects, extract_sim_params,
+ fixup_parents, on_remove_cached_draw_indirect_args, on_remove_cached_effect,
+ on_remove_cached_effect_events, on_remove_cached_metadata, on_remove_cached_properties,
+ prepare_batch_inputs, prepare_bind_groups, prepare_effect_metadata, prepare_gpu_resources,
+ prepare_indirect_pipeline, prepare_init_update_pipelines, prepare_property_buffers,
+ propagate_ready_state, queue_effects, queue_init_fill_dispatch_ops,
+ queue_init_indirect_workgroup_update, queue_sort_fill_dispatch_ops, report_ready_state,
+ start_stop_gpu_debug_capture, update_mesh_locations, Batcher, DebugSettings,
+ DispatchIndirectPipeline, DrawEffects, EffectAssetEvents, EffectBindGroups, EffectCache,
+ EffectsMeta, EventCache, GpuBatchInfo, GpuBufferOperations, GpuSpawnerParams,
+ HanabiRenderPlugin, InitFillDispatchQueue, ParticlesInitPipeline, ParticlesRenderPipeline,
+ ParticlesUpdatePipeline, PrefixSumPipeline, PropertyBindGroups, PropertyCache,
+ RenderDebugSettings, ShaderCache, SimParams, SortBindGroups, SortFillDispatchQueue,
+ StorageType as _, UtilsPipeline,
+ },
+ spawn::{self, Random},
+ tick_spawners,
+ time::effect_simulation_time_system,
+ update_properties_from_asset, EffectSimulation, EffectVisibilityClass, ParticleEffect,
+ SpawnerSettings,
+};
+
+/// Source code for the `vfx_sort` compute shader.
+pub(crate) const VFX_SORT_WESL: Cow<'static, str> =
+ Cow::Borrowed(include_str!("render/vfx_sort.wesl"));
+
+/// Source code for the `vfx_sort_merge` compute shader.
+pub(crate) const VFX_SORT_MERGE_WESL: Cow<'static, str> =
+ Cow::Borrowed(include_str!("render/vfx_sort_merge.wesl"));
+
+/// Labels for the Hanabi systems.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, SystemSet)]
+pub enum EffectSystems {
+ /// Tick all effect instances to generate particle spawn counts.
+ ///
+ /// This system runs during the [`PostUpdate`] schedule. Any system which
+ /// modifies an effect spawner should run before this set to ensure the
+ /// spawner takes into account the newly set values during its ticking.
+ TickSpawners,
+
+ /// Compile the effect instances, updating the [`CompiledParticleEffect`]
+ /// components.
+ ///
+ /// This system runs during the [`PostUpdate`] schedule. This is largely an
+ /// internal task which can be ignored by most users.
+ ///
+ /// [`CompiledParticleEffect`]: crate::CompiledParticleEffect
+ CompileEffects,
+
+ /// Update the properties of the effect instance based on the declared
+ /// properties in the [`EffectAsset`], updating the associated
+ /// [`EffectProperties`] component.
+ ///
+ /// This system runs during the [`PostUpdate`] schedule, after the assets
+ /// have been updated. Any system which modifies an [`EffectAsset`]'s
+ /// declared properties should run before this set in order for changes to
+ /// be taken into account in the same frame.
+ UpdatePropertiesFromAsset,
+
+ /// Prepare effect assets for the extracted effects.
+ ///
+ /// Part of Bevy's own [`RenderSystems::PrepareAssets`].
+ PrepareEffectAssets,
+
+ /// Queue the GPU commands for the extracted effects.
+ ///
+ /// Part of Bevy's own [`RenderSystems::Queue`].
+ QueueEffects,
+
+ /// Prepare GPU data for the queued effects.
+ ///
+ /// Part of Bevy's own [`RenderSystems::PrepareResources`].
+ PrepareEffectGpuResources,
+
+ /// Prepare the GPU bind groups once all buffers have been (re-)allocated
+ /// and won't change this frame.
+ ///
+ /// Part of Bevy's own [`RenderSystems::PrepareBindGroups`].
+ PrepareBindGroups,
+}
+
+const HANABI_COMMON_TEMPLATE_HANDLE: Handle<Shader> =
+ uuid_handle!("626E7AD3-4E54-487E-B796-9A90E34CC1EC");
+
+/// Plugin to add systems related to Hanabi.
+#[derive(Debug, Clone, Copy)]
+pub struct HanabiPlugin;
+
+impl HanabiPlugin {
+ /// Create the `vfx_common.wesl` shader with proper alignment.
+ ///
+ /// This creates a new [`Shader`] from the `vfx_common.wesl` template file,
+ /// by applying the given alignment for storage buffers. This produces a
+ /// shader ready for the specific GPU device associated with that
+ /// alignment.
+ pub(crate) fn make_common_shader(min_storage_buffer_offset_alignment: u32) -> Shader {
+ let spawner_padding_code =
+ GpuSpawnerParams::padding_code(min_storage_buffer_offset_alignment);
+ let batch_info_padding_code =
+ GpuBatchInfo::padding_code(min_storage_buffer_offset_alignment);
+ let common_code = include_str!("render/vfx_common.wesl")
+ .replace("{{SPAWNER_PADDING}}", &spawner_padding_code)
+ .replace("{{BATCH_INFO_PADDING}}", &batch_info_padding_code);
+ Shader::from_wesl(common_code, "embedded://bevy_hanabi/render/vfx_common.wesl")
+ }
+
+ /// Create the `vfx_indirect.wesl` shader with proper alignment.
+ ///
+ /// This creates a new [`Shader`] from the `vfx_indirect.wesl` template
+ /// file, by applying the given alignment for storage buffers. This
+ /// produces a shader ready for the specific GPU device associated with
+ /// that alignment.
+ pub(crate) fn make_indirect_shader(
+ min_storage_buffer_offset_alignment: u32,
+ has_events: bool,
+ ) -> Shader {
+ let indirect_code = include_str!("render/vfx_indirect.wesl");
+ Shader::from_wesl(
+ indirect_code,
+ std::path::Path::new(file!())
+ .parent()
+ .unwrap()
+ .join(format!(
+ "render/vfx_indirect_{}_{}.wesl",
+ min_storage_buffer_offset_alignment,
+ if has_events { "events" } else { "noevent" },
+ ))
+ .to_string_lossy(),
+ )
+ }
+
+ /// Create the `vfx_prefix_sum.wesl` shader.
+ ///
+ /// This creates a new [`Shader`] from the `vfx_prefix_sum.wesl` template
+ /// file.
+ pub(crate) fn make_prefix_sum_shader() -> Shader {
+ let prefix_sum_code = include_str!("render/vfx_prefix_sum.wesl");
+ Shader::from_wesl(
+ prefix_sum_code,
+ std::path::Path::new(file!())
+ .parent()
+ .unwrap()
+ .join("render/vfx_prefix_sum.wesl")
+ .to_string_lossy(),
+ )
+ }
+}
+
+impl Plugin for HanabiPlugin {
+ fn build(&self, app: &mut App) {
+ // Register modifiers
+ {
+ let type_registry = app.world().resource::<AppTypeRegistry>();
+ register_modifiers(type_registry);
+ }
+
+ // Register asset
+ app.init_asset::<EffectAsset>()
+ .insert_resource(Random(spawn::new_rng()))
+ .add_plugins(HanabiRenderPlugin)
+ .add_plugins(ExtractComponentPlugin::<EffectVisibilityClass>::default())
+ .init_resource::<DefaultMesh>()
+ .init_resource::<ShaderCache>()
+ .init_resource::<DebugSettings>()
+ .init_resource::<Time<EffectSimulation>>()
+ .configure_sets(
+ PostUpdate,
+ (
+ EffectSystems::TickSpawners
+ // This checks the visibility to skip work, so needs to run after
+ // ComputedVisibility was updated.
+ .after(VisibilitySystems::VisibilityPropagate),
+ EffectSystems::CompileEffects,
+ ),
+ )
+ .configure_sets(
+ PreUpdate,
+ EffectSystems::UpdatePropertiesFromAsset.after(bevy::asset::AssetTrackingSystems),
+ )
+ .add_systems(
+ First,
+ effect_simulation_time_system
+ .after(time_system)
+ .in_set(TimeSystems),
+ )
+ .add_systems(
+ PostUpdate,
+ (
+ tick_spawners.in_set(EffectSystems::TickSpawners),
+ compile_effects.in_set(EffectSystems::CompileEffects),
+ update_properties_from_asset.in_set(EffectSystems::UpdatePropertiesFromAsset),
+ ),
+ );
+
+ app.init_asset_loader::<EffectAssetLoader>();
+
+ // Register types with reflection
+ app.register_type::<EffectAsset>()
+ .register_type::<ParticleEffect>()
+ .register_type::<EffectProperties>()
+ .register_type::<SpawnerSettings>()
+ .register_type::<Time<EffectSimulation>>();
+ }
+
+ fn finish(&self, app: &mut App) {
+ let render_device = app
+ .sub_app(RenderApp)
+ .world()
+ .resource::<RenderDevice>()
+ .clone();
+
+ let adapter_name = app
+ .world()
+ .get_resource::<RenderAdapterInfo>()
+ .map(|ai| &ai.name[..])
+ .unwrap_or("<unknown>");
+
+ // Check device limits
+ let limits = render_device.limits();
+ if limits.max_bind_groups < 4 {
+ error!("Hanabi requires a GPU device supporting at least 4 bind groups (Limits::max_bind_groups).\n Current adapter: {}\n Supported bind groups: {}", adapter_name, limits.max_bind_groups);
+ return;
+ } else {
+ info!("Initializing Hanabi for GPU adapter {}", adapter_name);
+ }
+
+ // Insert the properly aligned `vfx_common.wesl` shader into Assets<Shader>, so
+ // that the automated Bevy shader processing finds it as an import. This is used
+ // for init/update/render shaders (but not the indirect one).
+ {
+ let common_shader = HanabiPlugin::make_common_shader(
+ render_device.limits().min_storage_buffer_offset_alignment,
+ );
+ let mut assets = app.world_mut().resource_mut::<Assets<Shader>>();
+ assets
+ .insert(&HANABI_COMMON_TEMPLATE_HANDLE, common_shader)
+ .unwrap();
+ }
+
+ // Insert the two variants of the properly aligned `vfx_indirect.wesl` shaders
+ // into Assets<Shader>.
+ let (
+ indirect_shader_noevent,
+ indirect_shader_events,
+ prefix_sum_shader,
+ sort_fill_shader,
+ sort_shader,
+ sort_merge_shader,
+ sort_copy_shader,
+ ) = {
+ let align = render_device.limits().min_storage_buffer_offset_alignment;
+ let indirect_shader_noevent = HanabiPlugin::make_indirect_shader(align, false);
+ let indirect_shader_events = HanabiPlugin::make_indirect_shader(align, true);
+ let prefix_sum_shader = HanabiPlugin::make_prefix_sum_shader();
+ let sort_fill_shader = Shader::from_wesl(
+ include_str!("render/vfx_sort_fill.wesl"),
+ std::path::Path::new(file!())
+ .parent()
+ .unwrap()
+ .join("render/vfx_sort_fill.wesl")
+ .to_string_lossy(),
+ );
+ let sort_shader = Shader::from_wesl(
+ VFX_SORT_WESL,
+ std::path::Path::new(file!())
+ .parent()
+ .unwrap()
+ .join("render/vfx_sort.wesl")
+ .to_string_lossy(),
+ );
+ let sort_merge_shader = Shader::from_wesl(
+ VFX_SORT_MERGE_WESL,
+ std::path::Path::new(file!())
+ .parent()
+ .unwrap()
+ .join("render/vfx_sort_merge.wesl")
+ .to_string_lossy(),
+ );
+ let sort_copy_shader = Shader::from_wesl(
+ include_str!("render/vfx_sort_copy.wesl"),
+ std::path::Path::new(file!())
+ .parent()
+ .unwrap()
+ .join("render/vfx_sort_copy.wesl")
+ .to_string_lossy(),
+ );
+
+ let mut assets = app.world_mut().resource_mut::<Assets<Shader>>();
+ let indirect_shader_noevent = assets.add(indirect_shader_noevent);
+ let indirect_shader_events = assets.add(indirect_shader_events);
+ let prefix_sum_shader = assets.add(prefix_sum_shader);
+ let sort_fill_shader = assets.add(sort_fill_shader);
+ let sort_shader = assets.add(sort_shader);
+ let sort_merge_shader = assets.add(sort_merge_shader);
+ let sort_copy_shader = assets.add(sort_copy_shader);
+
+ (
+ indirect_shader_noevent,
+ indirect_shader_events,
+ prefix_sum_shader,
+ sort_fill_shader,
+ sort_shader,
+ sort_merge_shader,
+ sort_copy_shader,
+ )
+ };
+
+ let effects_meta = EffectsMeta::new(
+ render_device.clone(),
+ indirect_shader_noevent,
+ indirect_shader_events,
+ prefix_sum_shader,
+ );
+
+ let effect_cache = EffectCache::new(render_device.clone());
+ let property_cache = PropertyCache::new(&render_device);
+ let event_cache = EventCache::new(render_device);
+
+ let render_app = app.sub_app_mut(RenderApp);
+ let sort_bind_groups = SortBindGroups::new(
+ render_app.world_mut(),
+ sort_fill_shader,
+ sort_shader,
+ sort_merge_shader,
+ sort_copy_shader,
+ );
+
+ // Register the custom render pipeline
+ render_app
+ .insert_resource(effects_meta)
+ .insert_resource(effect_cache)
+ .insert_resource(property_cache)
+ .insert_resource(event_cache)
+ .init_resource::<RenderDebugSettings>()
+ .init_resource::<EffectBindGroups>()
+ .init_resource::<PropertyBindGroups>()
+ .init_resource::<InitFillDispatchQueue>()
+ .init_resource::<SortFillDispatchQueue>()
+ .insert_resource(sort_bind_groups)
+ .init_resource::<UtilsPipeline>()
+ .init_resource::<GpuBufferOperations>()
+ .init_resource::<PrefixSumPipeline>()
+ .init_resource::<DispatchIndirectPipeline>()
+ .init_resource::<SpecializedComputePipelines<DispatchIndirectPipeline>>()
+ .init_resource::<ParticlesInitPipeline>()
+ .init_resource::<SpecializedComputePipelines<ParticlesInitPipeline>>()
+ .init_resource::<ParticlesInitPipeline>()
+ .init_resource::<SpecializedComputePipelines<ParticlesInitPipeline>>()
+ .init_resource::<ParticlesUpdatePipeline>()
+ .init_resource::<SpecializedComputePipelines<ParticlesUpdatePipeline>>()
+ .init_resource::<ParticlesRenderPipeline>()
+ .init_resource::<SpecializedRenderPipelines<ParticlesRenderPipeline>>()
+ .init_resource::<EffectAssetEvents>()
+ .init_resource::<SimParams>()
+ .init_resource::<Batcher>()
+ .configure_sets(
+ Render,
+ (
+ EffectSystems::PrepareEffectAssets.in_set(RenderSystems::PrepareAssets),
+ EffectSystems::QueueEffects.in_set(RenderSystems::Queue),
+ EffectSystems::PrepareEffectGpuResources
+ .in_set(RenderSystems::PrepareResources),
+ EffectSystems::PrepareBindGroups.in_set(RenderSystems::PrepareBindGroups),
+ ),
+ )
+ .edit_schedule(ExtractSchedule, |schedule| {
+ schedule.add_systems((
+ start_stop_gpu_debug_capture,
+ report_ready_state.before(extract_effects),
+ extract_effects,
+ extract_sim_params,
+ extract_effect_events,
+ extract_main_view.after(bevy::render::camera::extract_cameras),
+ ));
+ })
+ .add_systems(
+ Render,
+ (
+ (
+ // Do all clears from previous frame; they can run in parallel as they
+ // clear different resources.
+ (clear_transient_batch_inputs, clear_previous_frame_resizes),
+ // Allocate GPU resources depending only on the extracted data; they can
+ // run in parallel as they touch different components.
+ (
+ // Allocate GPU storage for the effect particles
+ allocate_effects,
+ // Allocate GPU storage for GPU events (for child effects)
+ allocate_events,
+ // Allocate GPU storage for properties
+ allocate_properties,
+ // Update draw indirect args if Bevy relocated a render mesh
+ update_mesh_locations
+ // Need Bevy to have allocated the mesh in the MeshAllocator
+ .after(bevy::render::mesh::allocator::allocate_and_free_meshes)
+ // Need Bevy to have prepared the RenderMesh to read it
+ .after(prepare_assets::<bevy::render::mesh::RenderMesh>),
+ // Allocate GPU effect metadata
+ allocate_metadata,
+ ),
+ // Allocate parent and child infos. Those need all effects allocated and
+ // all parents resolved first, as well as event buffers allocated.
+ allocate_parent_child_infos
+ // Need the effects allocated to fetch the parent's slab ID
+ .after(allocate_effects)
+ // Need the events allocated to fetch the event buffer of children
+ .after(allocate_events),
+ fixup_parents
+ // Second pass fixup after allocate_parent_child_infos()
+ .after(allocate_parent_child_infos),
+ // Prepare pipelines; they can run in parallel as they touch different
+ // resources.
+ (
+ // Resolve the init and update pipelines, queue them if needed, and
+ // check their state to determine if the
+ // effect can be used this frame.
+ prepare_init_update_pipelines
+ // Need the bind group layout for the effect itself, which depends
+ // on the particle layout.
+ .after(allocate_effects)
+ // Need the bind group layout for properties, which depends on the
+ // property layout.
+ .after(allocate_properties)
+ // Need the number of event buffers to bind
+ .after(fixup_parents),
+ // Prepare the indirect pipeline depending on whether there's any child
+ // info.
+ prepare_indirect_pipeline
+ // Need to know if any GPU event using effect is active or not
+ .after(allocate_events),
+ ),
+ propagate_ready_state
+ // Need the ready state of parents, which depends on the init/update
+ // pipeline states
+ .after(prepare_init_update_pipelines),
+ prepare_batch_inputs,
+ batch_effects,
+ )
+ // TODO: remove this chain() once all system dependencies are setup
+ // correctly above.
+ .chain()
+ .in_set(EffectSystems::PrepareEffectAssets),
+ // Once batched, queue the effects/batches which are ready to be
+ // updated/rendered this frame.
+ queue_effects
+ .in_set(EffectSystems::QueueEffects)
+ .after(batch_effects),
+ // Queue the dispatch ops to fill the indirect dispatch args of the init pass
+ // of child effects.
+ queue_init_indirect_workgroup_update
+ .in_set(EffectSystems::QueueEffects)
+ .after(batch_effects)
+ .after(fixup_parents),
+ prepare_gpu_resources
+ .in_set(EffectSystems::PrepareEffectGpuResources)
+ // This creates the bind group for the view
+ .after(prepare_view_uniforms)
+ // Upload and optionally resize the draw indirect args buffer
+ .after(update_mesh_locations)
+ // Bind groups depend on buffers being re-/allocated
+ .before(prepare_bind_groups),
+ prepare_property_buffers
+ .in_set(EffectSystems::PrepareEffectGpuResources)
+ .before(prepare_bind_groups),
+ prepare_effect_metadata
+ .in_set(EffectSystems::PrepareEffectGpuResources)
+ //
+ .after(allocate_effects)
+ // Need the draw indirect args to be allocated
+ .after(update_mesh_locations)
+ // Need the local/global/base child index
+ .after(fixup_parents)
+ // Need the indirect dispatch args index for GPU event based init pass
+ .after(allocate_events)
+ // Need the properties block offset in GPU slab
+ .after(allocate_properties)
+ // This may invalidate some bind groups when resizing the metadata buffer
+ .before(prepare_bind_groups),
+ // Queue the dispatch ops to fill the indirect dispatch args of the ribbon
+ // particle sort pass. Deferred from batch_effects() so it runs after the
+ // effect metadata buffer has been (re-)allocated to this frame's size.
+ queue_sort_fill_dispatch_ops
+ .in_set(EffectSystems::PrepareEffectGpuResources)
+ // The prefix sum buffer is allocated and uploaded while batching.
+ .after(batch_effects)
+ // Need the metadata buffer (re-)allocated so the captured handle and
+ // dynamic offsets are correct and in-bounds
+ .after(prepare_effect_metadata)
+ // Keep this aligned with other queue submissions that capture GPU buffers.
+ .after(prepare_gpu_resources)
+ // Must submit into the shared GpuBufferOperations before
+ // queue_init_fill_dispatch_ops uploads its args buffer (end_frame)
+ .before(queue_init_fill_dispatch_ops)
+ .before(prepare_bind_groups),
+ queue_init_fill_dispatch_ops
+ .in_set(EffectSystems::PrepareEffectGpuResources)
+ .after(prepare_gpu_resources)
+ .before(prepare_bind_groups),
+ // Prepare the bind groups
+ prepare_bind_groups
+ .in_set(EffectSystems::PrepareBindGroups)
+ .after(queue_effects)
+ .after(prepare_assets::<GpuImage>),
+ ),
+ );
+
+ // Register observers to deallocate GPU resources
+ {
+ let world = render_app.world_mut();
+ world.add_observer(on_remove_cached_effect);
+ world.add_observer(on_remove_cached_metadata);
+ world.add_observer(on_remove_cached_draw_indirect_args);
+ world.add_observer(on_remove_cached_effect_events);
+ world.add_observer(on_remove_cached_properties);
+ }
+
+ // Register the draw function for drawing the particles. This will be called
+ // during the main 2D/3D pass, at the Transparent2d/3d phase, after the
+ // opaque objects have been rendered (or, rather, commands for those
+ // have been recorded).
+ #[cfg(feature = "2d")]
+ {
+ let draw_particles = DrawEffects::new(render_app.world_mut());
+ render_app
+ .world()
+ .get_resource::<DrawFunctions<Transparent2d>>()
+ .unwrap()
+ .write()
+ .add(draw_particles);
+ }
+ #[cfg(feature = "3d")]
+ {
+ let draw_particles = DrawEffects::new(render_app.world_mut());
+ render_app
+ .world()
+ .get_resource::<DrawFunctions<Transparent3d>>()
+ .unwrap()
+ .write()
+ .add(draw_particles);
+
+ let draw_particles = DrawEffects::new(render_app.world_mut());
+ render_app
+ .world()
+ .get_resource::<DrawFunctions<AlphaMask3d>>()
+ .unwrap()
+ .write()
+ .add(draw_particles);
+
+ let draw_particles = DrawEffects::new(render_app.world_mut());
+ render_app
+ .world()
+ .get_resource::<DrawFunctions<Opaque3d>>()
+ .unwrap()
+ .write()
+ .add(draw_particles);
+ }
+ }
+}
diff --git a/vendor/bevy_hanabi/src/properties.rs b/vendor/bevy_hanabi/src/properties.rs
new file mode 100644
index 00000000..3bab11b7
--- /dev/null
+++ b/vendor/bevy_hanabi/src/properties.rs
@@ -0,0 +1,1427 @@
+//! Effect properties.
+//!
+//! An _effect property_ is a named variable stored per effect, and mutable at
+//! runtime from the application (CPU). Unlike [attributes](crate::attributes),
+//! all particles see the same property value while the effect simulates or
+//! renders. As such, properties are a much more compact way to represent
+//! time-varying quantities when there's no per-particle variation.
+//!
+//! # Definition
+//!
+//! An effect property is represented by the [`Property`] type. Each
+//! [`Module`] can have zero or more properties.
+//!
+//! The property has a name unique within the expression module; different
+//! effects can have a property with the same name, but a single effect cannot
+//! have multiple properties with a duplicate name (since each effect has a
+//! single expression module).
+//!
+//! The property is created with a default value used to initialize it. Like for
+//! attributes, this can be any [`Value`]. The type of the default value also
+//! defines the type of the property itself, which is immutable. Assigning a new
+//! value to the property requires assigning a value of the same type as the
+//! default value passed to [`Module::add_property()`].
+//!
+//! # Use case
+//!
+//! Use properties to ensure a value from an [expression](crate::expr) can be
+//! mutated while the effect is instantiated, without having to destroy and
+//! re-create a new effect. Using properties is a bit more costly in terms of
+//! GPU processing than using a hard-coded constant, so avoid using properties
+//! if a value doesn’t need to change dynamically at runtime, or changes very
+//! infrequently.
+//!
+//! # Layout
+//!
+//! Like attributes, particle properties are tightly packed to be efficiently
+//! uploaded from CPU to GPU when a change is detected. The [`PropertyLayout`]
+//! defines this memory layout, with the same rules as attributes. See the
+//! [attribute layout](crate::attributes#layout-1) section for more details.
+//!
+//! # Usage
+//!
+//! To use properties, create a new property using [`Module::add_property()`],
+//! giving it a unique name and a default value. The default value determines
+//! the type of the property.
+//!
+//! ```
+//! # use bevy_hanabi::*;
+//! # use bevy::prelude::*;
+//! let mut module = Module::default();
+//! module.add_property("my_color", LinearRgba::WHITE.as_u32().into());
+//! ```
+//!
+//! Once the module is assigned to an [`EffectAsset`], any instance of that
+//! effect (that is, any [`ParticleEffect`] component referencing that
+//! [`EffectAsset`]) will have the defined a property.
+//!
+//! Property values are stored in the [`EffectProperties`] component, attached
+//! to the same entity containing the [`ParticleEffect`] component. This
+//! component can be mutated by a system you own to change the value of one or
+//! more properties; when doing so, the Bevy change detection mechanism will
+//! trigger a re-upload of the new property values from CPU to GPU. If the
+//! [`EffectProperties`] component is missing, and the effect has properties
+//! defined in the [`Module`] of its [`EffectAsset`], then πŸŽ† Hanabi will add
+//! the component automatically, using the default value of each property. One
+//! advantage of manually adding that component is that you can override the
+//! initial value of some or all of the properties. Note that the component is
+//! not automatically added if the [`Module`] doesn't declare any property.
+//!
+//! To change the value of a property, call [`EffectProperties::set()`] or
+//! [`EffectProperties::set_if_changed()`]. The former is easier to use but
+//! always triggers the change detection mechanism, even if the value assigned
+//! is the same as the previous one. [`EffectProperties::set_if_changed()`] on
+//! the other hand will compare the current value and only assign if different.
+//! This minimizes the need for a GPU re-upload.
+//!
+//! ```
+//! # use bevy_hanabi::*;
+//! # use bevy::prelude::*;
+//! fn change_property(mut query: Query<&mut EffectProperties>) {
+//! let mut effect_properties = query.single_mut().unwrap();
+//! let color = LinearRgba::rgb(1., 0., 0.).as_u32();
+//! // If the current color is not already red, it will be updated, and
+//! // the properties will be re-uploaded to the GPU.
+//! EffectProperties::set_if_changed(effect_properties, "my_color", color.into());
+//! }
+//! ```
+//!
+//! [`Module`]: crate::Module
+//! [`Module::add_property()`]: crate::Module::add_property
+//! [`EffectAsset`]: crate::EffectAsset
+//! [`add_property()`]: crate::Module::add_property
+//! [`ParticleEffect`]: crate::ParticleEffect
+
+use std::num::NonZeroU64;
+
+use bevy::{
+ ecs::{component::Component, reflect::ReflectComponent, world::Mut},
+ log::trace,
+ platform::collections::HashSet,
+ reflect::Reflect,
+};
+use serde::{Deserialize, Serialize};
+
+use crate::{graph::Value, ToWgslString, ValueType};
+
+/// A single property of an [`EffectAsset`].
+///
+/// See the [`properties`](crate::properties) module documentation for details.
+///
+/// [`EffectAsset`]: crate::EffectAsset
+#[derive(Debug, Clone, PartialEq, Hash, Reflect, Serialize, Deserialize)]
+pub struct Property {
+ name: String,
+ default_value: Value,
+}
+
+impl Property {
+ /// Create a new property.
+ ///
+ /// In general properties are created internally by the [`EffectAsset`]
+ /// they're defined on, when calling [`Module::add_property()`].
+ ///
+ /// [`EffectAsset`]: crate::EffectAsset
+ /// [`Module::add_property()`]: crate::Module::add_property
+ #[inline]
+ pub fn new(name: impl Into<String>, default_value: impl Into<Value>) -> Self {
+ Self {
+ name: name.into(),
+ default_value: default_value.into(),
+ }
+ }
+
+ /// The property name.
+ ///
+ /// The name of a property is unique within a given effect, and corresponds
+ /// to the name of the variable in the generated WGSL code.
+ #[inline]
+ pub fn name(&self) -> &str {
+ self.name.as_ref()
+ }
+
+ /// The default value of the property.
+ ///
+ /// The default value is used to initialize the property.
+ #[inline]
+ pub fn default_value(&self) -> &Value {
+ &self.default_value
+ }
+
+ /// The property type.
+ ///
+ /// This is the type of the value stored in the property.
+ #[inline]
+ pub fn value_type(&self) -> ValueType {
+ self.default_value.value_type()
+ }
+
+ /// The property size, in bytes.
+ ///
+ /// This is a shortcut for `self.value_type().size()`.
+ #[inline]
+ pub fn size(&self) -> usize {
+ self.default_value.value_type().size()
+ }
+}
+
+impl ToWgslString for Property {
+ fn to_wgsl_string(&self) -> String {
+ format!("properties[properties_array_index].{}", self.name)
+ }
+}
+
+/// Instance of a [`Property`] owned by a specific [`ParticleEffect`] component.
+///
+/// The property instance is stored inside an [`EffectProperties`].
+///
+/// [`ParticleEffect`]: crate::ParticleEffect
+/// [`EffectProperties`]: crate::EffectProperties
+#[derive(Debug, Clone, Reflect)]
+pub(crate) struct PropertyInstance {
+ /// The property definition, including its default value.
+ pub def: Property,
+ /// The current runtime value of the property.
+ pub value: Value,
+}
+
+/// Runtime storage component for the properties of a [`ParticleEffect`].
+///
+/// This component stores the list of properties of a single [`ParticleEffect`]
+/// instance and their current value. It represents the CPU side copy of the
+/// values actually present in GPU memory and used by the particle effect.
+///
+/// A new value can be assigned to a property via [`set()`] or
+/// [`set_if_changed()`], which will trigger a GPU (re-)upload
+/// of the properties by reading them during the render extract phase.
+///
+/// # Asset changes
+///
+/// When a declared property is added to or removed from the underlying
+/// [`EffectAsset`], an internal system automatically updates the component
+/// during the [`EffectSystems::UpdatePropertiesFromAsset`] stage, which runs in
+/// [`PostUpdate`] schedule. Note however that changing a declared property's
+/// default value has no effect on the instance already stored in the
+/// [`EffectProperties`], and will only affect other components spawned after
+/// the change.
+///
+/// [`ParticleEffect`]: crate::ParticleEffect
+/// [`EffectAsset`]: crate::asset::EffectAsset
+/// [`set()`]: crate::EffectProperties::set
+/// [`set_if_changed()`]: crate::EffectProperties::set_if_changed
+/// [`EffectSystems::UpdatePropertiesFromAsset`]: crate::EffectSystems::UpdatePropertiesFromAsset
+/// [`PostUpdate`]: bevy::app::PostUpdate
+#[derive(Debug, Default, Clone, Component, Reflect)]
+#[reflect(Component)]
+pub struct EffectProperties {
+ /// Instances of all declared properties, as well as any property manually
+ /// added with [`set()`] this frame.
+ properties: Vec<PropertyInstance>,
+}
+
+impl EffectProperties {
+ /// Create or set some properties.
+ ///
+ /// Add new properties or overwrite the value of existing ones. This
+ /// function takes an iterator of pairs of `(name, value)`, where `name`
+ /// defines the property name and `value` its value.
+ ///
+ /// If a property with the same name doesn't already exist, a new property
+ /// is created with a default value equal to the provided `value`.
+ ///
+ /// Conversely, if a property with the same name already exists in the
+ /// `EffectProperties`, it's overwritten with the new value, unless its
+ /// type mismatches in which case this function panics (to prevent
+ /// unexpected overwrites). However the property keeps the default value
+ /// initially set when first created.
+ ///
+ /// # Panics
+ ///
+ /// Panics if a property with the same name already exists in the
+ /// `EffectProperties`, and the new property type, as derived from its
+ /// default value, is different from the type of the existing property.
+ pub fn with_properties(
+ mut self,
+ properties: impl IntoIterator<Item = (String, Value)>,
+ ) -> Self {
+ let iter = properties.into_iter();
+ for (name, value) in iter {
+ if let Some(index) = self.properties.iter().position(|p| p.def.name() == name) {
+ assert_eq!(
+ self.properties[index].value.value_type(),
+ value.value_type(),
+ "Trying to overwrite existing property '{}' with value of type {:?}, but property has type {:?}",
+ name,
+ value.value_type(),
+ self.properties[index].value.value_type()
+ );
+ self.properties[index].value = value;
+ } else {
+ self.properties.push(PropertyInstance {
+ def: Property::new(name, value),
+ value,
+ });
+ }
+ }
+ self
+ }
+
+ /// Get all properties currently stored in this component.
+ #[allow(dead_code)] // used in tests
+ pub(crate) fn properties(&self) -> &[PropertyInstance] {
+ &self.properties
+ }
+
+ /// Get the value of a stored property.
+ ///
+ /// The property will be matched by name against the properties already
+ /// stored in this [`EffectProperties`] component. If no property exists
+ /// with that name, `None` is returned, which either indicates that the
+ /// [`Module`] of the effect does not declare such a property, or that the
+ /// [`EffectProperties`] component didn't observe the property yet. This
+ /// means that [`get_stored()`] is only relevant when called after a
+ /// [`set()`] of the same property, or after the
+ /// [`EffectSystems::UpdatePropertiesFromAsset`] stage has added any
+ /// property declared in the [`Module`] of the effect but missing in the
+ /// [`EffectProperties`]. This also means that [`get_stored()`] may
+ /// return a property which was [`set()`] but is not in fact declared in
+ /// the [`EffectAsset`].
+ ///
+ /// Note that this behavior is not symmetric with [`set()`], which allows
+ /// setting any property even if not declared.
+ ///
+ /// [`Module`]: crate::Module
+ /// [`EffectAsset`]: crate::asset::EffectAsset
+ /// [`EffectSystems::UpdatePropertiesFromAsset`]: crate::EffectSystems::UpdatePropertiesFromAsset
+ /// [`get_stored()`]: crate::EffectProperties::get_stored
+ /// [`set()`]: crate::EffectProperties::set
+ pub fn get_stored(&self, name: &str) -> Option<Value> {
+ self.properties
+ .iter()
+ .find(|prop| prop.def.name() == name)
+ .map(|prop| prop.value)
+ }
+
+ /// Set the value of a property.
+ ///
+ /// The property will be matched by name against the properties of the
+ /// associated [`EffectAsset`] on next update. If no property exists with
+ /// that name, the value will be discarded. Otherwise it will be used to
+ /// replace the current property's value, and if different will trigger a
+ /// GPU re-upload of the properties.
+ ///
+ /// Note that this behavior is not symmetric with [`get_stored()`], which
+ /// only returns properties already stored in this [`EffectProperties`]
+ /// component.
+ ///
+ /// [`EffectAsset`]: crate::asset::EffectAsset
+ /// [`get_stored()`]: crate::EffectProperties::get_stored
+ pub fn set(&mut self, name: &str, value: Value) {
+ if let Some(index) = self
+ .properties
+ .iter()
+ .position(|prop| prop.def.name() == name)
+ {
+ let prop = &mut self.properties[index];
+ assert_eq!(
+ prop.def.value_type(),
+ value.value_type(),
+ "Cannot assign value of type {:?} to property '{}' of type {:?}",
+ value.value_type(),
+ prop.def.name(),
+ prop.def.value_type()
+ );
+ prop.value = value;
+ } else {
+ self.properties.push(PropertyInstance {
+ def: Property::new(name, value),
+ value,
+ });
+ }
+ }
+
+ /// Set the value of a property, only if it changed.
+ ///
+ /// This is similar to [`set()`], with the notable difference that this
+ /// associated function takes a [`Mut`] reference, and will only trigger
+ /// change detection on the target component if the property either isn't
+ /// already stored, or has a different value than `value`. This means in
+ /// particular that a full value comparison is performed, which is never the
+ /// case with [`set()`].
+ ///
+ /// [`set()`]: crate::EffectProperties::set
+ pub fn set_if_changed<'p>(
+ mut this: Mut<'p, EffectProperties>,
+ name: &str,
+ value: Value,
+ ) -> Mut<'p, EffectProperties> {
+ if let Some(index) = this
+ .properties
+ .iter()
+ .position(|prop| prop.def.name() == name)
+ {
+ let prop = &this.properties[index];
+ assert_eq!(
+ prop.def.value_type(),
+ value.value_type(),
+ "Cannot assign value of type {:?} to property '{}' of type {:?}",
+ value.value_type(),
+ prop.def.name(),
+ prop.def.value_type()
+ );
+ if prop.value != value {
+ this.properties[index].value = value;
+ }
+ } else {
+ this.properties.push(PropertyInstance {
+ def: Property::new(name, value),
+ value,
+ });
+ }
+
+ this
+ }
+
+ /// Update the properties from the asset.
+ ///
+ /// Compare the properties declared in the asset with the properties
+ /// actually stored in the [`EffectProperties`] component, and update the
+ /// latter:
+ /// - Add any missing property, using their default value.
+ /// - Remove any unknown property not declared in the asset.
+ ///
+ /// Change detection on the [`EffectProperties`] component is guaranteed not
+ /// to trigger unless some property was added or removed.
+ pub(crate) fn update(
+ mut this: Mut<'_, EffectProperties>,
+ asset_properties: &[Property],
+ is_added: bool,
+ ) {
+ trace!(
+ "Updating effect properties from asset (is_added: {})",
+ is_added
+ );
+
+ let mut new_props = vec![];
+ let mut intersect = HashSet::new();
+ for prop in asset_properties {
+ if this.properties.iter().any(|p| p.def.name() == prop.name()) {
+ intersect.insert(prop.name());
+ continue;
+ }
+ new_props.push(PropertyInstance {
+ def: prop.clone(),
+ value: *prop.default_value(),
+ });
+ }
+
+ // Only mutate if needed to avoid triggering change detection
+ if intersect.len() != this.properties.len() {
+ // Delete instances for unknown properties
+ this.properties
+ .retain(|prop| intersect.contains(prop.def.name()));
+ }
+
+ // Only mutate if needed to avoid triggering change detection
+ if !new_props.is_empty() {
+ // Append new instances (with their default value) for missing properties
+ this.properties.append(&mut new_props);
+ }
+ }
+
+ /// Serialize properties into a binary blob ready for GPU upload.
+ ///
+ /// Return the binary blob where properties have been written according to
+ /// the given property layout. The size of the output blob is guaranteed
+ /// to be equal to the size of the layout.
+ pub(crate) fn serialize(&self, layout: &PropertyLayout) -> Vec<u8> {
+ let size = layout.cpu_size() as usize;
+ let mut data = vec![0; size];
+ // FIXME: O(n^2) search due to offset() being O(n) linear search already
+ for property in &self.properties {
+ if let Some(offset) = layout.offset(property.def.name()) {
+ let offset = offset as usize;
+ let size = property.def.size();
+ let src = property.value.as_bytes();
+ debug_assert_eq!(src.len(), size);
+ let dst = &mut data[offset..offset + size];
+ dst.copy_from_slice(src);
+ }
+ }
+ data
+ }
+}
+
+#[derive(Clone)]
+struct PropertyLayoutEntry {
+ property: Property,
+ offset: u32,
+}
+
+impl PartialEq for PropertyLayoutEntry {
+ fn eq(&self, other: &Self) -> bool {
+ // Compare property's name and type, and offset inside layout, but not default
+ // value since two properties cannot differ only by default value (the property
+ // name is unique).
+ self.property.name() == other.property.name()
+ && self.property.value_type() == other.property.value_type()
+ && self.offset == other.offset
+ }
+}
+
+impl Eq for PropertyLayoutEntry {}
+
+impl std::hash::Hash for PropertyLayoutEntry {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ // Hash property's name and type, and offset inside layout, but not default
+ // value since two properties cannot differ only by default value (the property
+ // name is unique).
+ self.property.name().hash(state);
+ self.property.value_type().hash(state);
+ self.offset.hash(state);
+ }
+}
+
+impl std::fmt::Debug for PropertyLayoutEntry {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ // "(+offset) name: type"
+ f.write_fmt(format_args!(
+ "(+{}) {}: {}",
+ self.offset,
+ self.property.name(),
+ self.property.value_type().to_wgsl_string(),
+ ))
+ }
+}
+
+/// Layout of properties for an effect.
+///
+/// The [`PropertyLayout`] describes the memory layout of properties inside the
+/// GPU buffer where their values are stored. This forms a contract between the
+/// CPU side where properties are written each frame, and the GPU shaders where
+/// they're subsequently read.
+///
+/// The layout is immutable once created. To create a different layout, build a
+/// new [`PropertyLayout`] from scratch, typically with [`new()`].
+///
+/// # Example
+///
+/// ```
+/// # use bevy_hanabi::{Property, PropertyLayout};
+/// # use bevy::math::Vec3;
+/// let layout = PropertyLayout::new(&[
+/// Property::new("my_property", Vec3::ZERO),
+/// Property::new("other_property", 3.4_f32),
+/// ]);
+/// assert_eq!(layout.cpu_size(), 16);
+/// ```
+///
+/// [`new()`]: crate::PropertyLayout::new
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct PropertyLayout {
+ layout: Vec<PropertyLayoutEntry>,
+}
+
+impl PropertyLayout {
+ /// Create a new empty property layout.
+ ///
+ /// An empty layout contains no property. This is often used as a
+ /// placeholder where a property layout is expected but no property is
+ /// available.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::PropertyLayout;
+ /// let layout = PropertyLayout::empty();
+ /// assert!(layout.is_empty());
+ /// ```
+ pub const fn empty() -> Self {
+ Self { layout: vec![] }
+ }
+
+ /// Create a new collection from an iterator.
+ ///
+ /// In general a property layout is directly built from an asset via
+ /// [`EffectAsset::property_layout()`], so this method is mostly used for
+ /// advanced use cases or testing.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::{Property, PropertyLayout};
+ /// # use bevy::math::Vec3;
+ /// let layout = PropertyLayout::new(&[
+ /// Property::new("my_property", Vec3::ZERO),
+ /// Property::new("other_property", 3.4_f32),
+ /// ]);
+ /// ```
+ ///
+ /// [`EffectAsset::property_layout()`]: crate::EffectAsset::property_layout
+ pub fn new<'a>(iter: impl IntoIterator<Item = &'a Property>) -> Self {
+ let mut properties = iter.into_iter().collect::<Vec<_>>();
+
+ // Sort by size
+ properties.sort_unstable_by_key(|prop| prop.size());
+ let properties = properties; // un-mut
+
+ let mut layout = vec![];
+ let mut offset = 0;
+
+ // Enqueue all Float4, which are already aligned
+ let index4 = properties.partition_point(|prop| prop.size() < 16);
+ for &prop in properties.iter().skip(index4) {
+ let entry = PropertyLayoutEntry {
+ property: prop.clone(),
+ offset,
+ };
+ offset += 16;
+ layout.push(entry);
+ }
+
+ // Enqueue paired { Float3 + Float1 }
+ let index2 = properties.partition_point(|prop| prop.size() < 8);
+ let num1 = index2;
+ let index3 = properties.partition_point(|prop| prop.size() < 12);
+ let num2 = (index2..index3).len();
+ let num3 = (index3..index4).len();
+ let num_pairs = num1.min(num3);
+ for i in 0..num_pairs {
+ // Float3
+ let prop = properties[index3 + i];
+ let entry = PropertyLayoutEntry {
+ property: prop.clone(),
+ offset,
+ };
+ offset += 12;
+ layout.push(entry);
+
+ // Float
+ let prop = properties[i];
+ let entry = PropertyLayoutEntry {
+ property: prop.clone(),
+ offset,
+ };
+ offset += 4;
+ layout.push(entry);
+ }
+ let index1 = num_pairs;
+ let index3 = index3 + num_pairs;
+ let num1 = num1 - num_pairs;
+ let num3 = num3 - num_pairs;
+
+ // Enqueue paired { Float2 + Float2 }
+ for i in 0..(num2 / 2) {
+ for j in 0..2 {
+ let prop = properties[index2 + i * 2 + j];
+ let entry = PropertyLayoutEntry {
+ property: prop.clone(),
+ offset,
+ };
+ offset += 8;
+ layout.push(entry);
+ }
+ }
+ let index2 = index2 + (num2 / 2) * 2;
+ let num2 = num2 % 2;
+
+ // Here we're always 16-byte aligned
+
+ // Enqueue { Float3+, Float2? } or { Float2?, Float1+ }
+ if num3 > num1 {
+ // Float1 is done, some Float3 left, and at most one Float2
+ debug_assert_eq!(num1, 0);
+
+ // Note: WGSL doesn't support packing 3/3/2 in 32 bytes, because vec3<f32> needs
+ // to be aligned to 16 bytes always. So we just output all remaining types as is
+ // proper align.
+
+ for i in 0..num3 {
+ let prop = properties[index3 + i];
+ let entry = PropertyLayoutEntry {
+ property: prop.clone(),
+ offset,
+ };
+ // WARN: vec3<f32> is 16-byte aligned, not 12! And the last vec2<f32> if any
+ // will also benefit from this since it needs 8-byte alignment.
+ offset += 16;
+ layout.push(entry);
+ }
+
+ // Emit the single Float2 now if any
+ if num2 > 0 {
+ debug_assert_eq!(num2, 1);
+ let prop = properties[index2];
+ let entry = PropertyLayoutEntry {
+ property: prop.clone(),
+ offset,
+ };
+ layout.push(entry);
+ }
+ } else {
+ // Float3 is done, some Float1 left, and at most one Float2
+ debug_assert_eq!(num3, 0);
+
+ // Emit the single Float2 now if any
+ if num2 > 0 {
+ debug_assert_eq!(num2, 1);
+ let prop = properties[index2];
+ let entry = PropertyLayoutEntry {
+ property: prop.clone(),
+ offset,
+ };
+ offset += 8;
+ layout.push(entry);
+ }
+
+ // End with remaining Float1
+ for i in 0..num1 {
+ let prop = properties[index1 + i];
+ let entry = PropertyLayoutEntry {
+ property: prop.clone(),
+ offset,
+ };
+ offset += 4;
+ layout.push(entry);
+ }
+ }
+
+ Self { layout }
+ }
+
+ /// Returns `true` if the layout contains no properties.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::PropertyLayout;
+ /// let layout = PropertyLayout::empty();
+ /// assert!(layout.is_empty());
+ /// ```
+ pub fn is_empty(&self) -> bool {
+ self.layout.is_empty()
+ }
+
+ /// Get the CPU size of the layout in bytes.
+ ///
+ /// The CPU size of a layout is the size of the data when serialized on the
+ /// CPU side. It's the sum of the offset and size of its last property. The
+ /// last property doesn't have any padding.
+ ///
+ /// If the layout is empty, this returns zero.
+ ///
+ /// When the data is uploaded on GPU, its size is [`min_binding_size()`],
+ /// which can be greater than the CPU size due to WGSL padding rules.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::{Property, PropertyLayout};
+ /// # use bevy::math::Vec3;
+ /// let layout = PropertyLayout::new(&[
+ /// Property::new("my_property", Vec3::ZERO),
+ /// Property::new("other_property", 3.4_f32),
+ /// ]);
+ /// assert_eq!(layout.cpu_size(), 16);
+ /// ```
+ ///
+ /// [`min_binding_size()`]: Self::min_binding_size()
+ pub fn cpu_size(&self) -> u32 {
+ if self.layout.is_empty() {
+ 0
+ } else {
+ let last_entry = self.layout.last().unwrap();
+ last_entry.offset + last_entry.property.size() as u32
+ }
+ }
+
+ /// Get the GPU alignment of the layout in bytes.
+ ///
+ /// This is the largest alignment of all the properties, as defined by WGSL.
+ /// If the layout is empty, this returns zero.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::{Property, PropertyLayout};
+ /// # use bevy::math::Vec3;
+ /// let layout = PropertyLayout::new(&[
+ /// Property::new("my_property", Vec3::ZERO),
+ /// Property::new("other_property", 3.4_f32),
+ /// ]);
+ /// assert_eq!(layout.align(), 16);
+ /// ```
+ pub fn align(&self) -> usize {
+ if self.layout.is_empty() {
+ 0
+ } else {
+ self.layout
+ .iter()
+ .map(|entry| entry.property.value_type().align())
+ .max()
+ .unwrap()
+ }
+ }
+
+ /// Iterate over the properties of the layout and their byte offset.
+ ///
+ /// This returns an iterator over the offset, in bytes, of a property in the
+ /// layout, and a reference to the corresponding property, as a pair.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::{Property, PropertyLayout};
+ /// # use bevy::math::Vec3;
+ /// let layout = PropertyLayout::new(&[
+ /// Property::new("my_property", Vec3::ZERO),
+ /// Property::new("other_property", 3.4_f32),
+ /// ]);
+ /// for (offset, property) in layout.properties() {
+ /// println!("+{}: {}", offset, property.name());
+ /// }
+ /// ```
+ pub fn properties(&self) -> impl Iterator<Item = (u32, &Property)> {
+ self.layout
+ .iter()
+ .map(|entry| (entry.offset, &entry.property))
+ }
+
+ /// Minimum binding size in bytes (GPU size).
+ ///
+ /// This corresponds to the stride of the properties struct in WGSL, and
+ /// therefore the minimum size of a buffer to store the properties.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the layout is empty, which is not valid once used on GPU.
+ pub fn min_binding_size(&self) -> NonZeroU64 {
+ assert!(
+ !self.layout.is_empty(),
+ "Cannot compute min binding size for empty property layout."
+ );
+ let size = self.cpu_size() as usize;
+ let align = self.align();
+ NonZeroU64::new(size.next_multiple_of(align) as u64).unwrap()
+ }
+
+ /// Check if the layout contains the property with the given name.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::{Property, PropertyLayout};
+ /// # use bevy::math::Vec3;
+ /// let layout = PropertyLayout::new(&[
+ /// Property::new("my_property", Vec3::ZERO),
+ /// Property::new("other_property", 3.4_f32),
+ /// ]);
+ /// assert!(layout.contains("other_property"));
+ /// ```
+ pub fn contains(&self, name: &str) -> bool {
+ self.layout.iter().any(|entry| entry.property.name == name)
+ }
+
+ /// Generate the WGSL code of the property struct corresponding to the
+ /// layout.
+ ///
+ /// This generates code declaring the `Properties` struct in WGSL, or `None`
+ /// if the layout is empty. The `Properties` struct contains the values
+ /// of all the effect properties, as defined by this layout.
+ pub fn generate_property_struct_code(&self) -> Option<String> {
+ // debug_assert!(self.layout.is_sorted_by_key(|entry| entry.offset));
+ if self.layout.is_empty() {
+ return None;
+ }
+ let content = self
+ .layout
+ .iter()
+ .map(|entry| {
+ format!(
+ " {}: {},",
+ entry.property.name(),
+ entry.property.value_type().to_wgsl_string()
+ )
+ })
+ .fold("struct Properties {\n".to_string(), |mut a, b| {
+ a.reserve(b.len() + 1);
+ a.push_str(&b);
+ a.push('\n');
+ a
+ })
+ + "}\n";
+ Some(content)
+ }
+
+ /// Get the offset in byte of the property with the given name.
+ ///
+ /// If no property with the given name is found, this returns `None`.
+ pub(crate) fn offset(&self, name: &str) -> Option<u32> {
+ self.layout.iter().find_map(|entry| {
+ if entry.property.name == name {
+ Some(entry.offset)
+ } else {
+ None
+ }
+ })
+ }
+}
+
+impl Default for PropertyLayout {
+ fn default() -> Self {
+ PropertyLayout::empty()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::{
+ collections::hash_map::DefaultHasher,
+ hash::{Hash, Hasher},
+ };
+
+ use bevy::{
+ ecs::change_detection::{MaybeLocation, Tick},
+ math::{Vec2, Vec3, Vec4},
+ };
+
+ use super::*;
+
+ #[test]
+ fn property_basic() {
+ let value = Value::Scalar(3_f32.into());
+ let p = Property::new("my_prop", value);
+ assert_eq!(p.name(), "my_prop");
+ assert_eq!(*p.default_value(), value);
+ assert_eq!(p.value_type(), value.value_type());
+ assert_eq!(p.size(), value.value_type().size());
+ assert_eq!(
+ p.to_wgsl_string(),
+ format!("properties[properties_array_index].{}", p.name())
+ );
+ }
+
+ #[test]
+ fn property_serde() {
+ let p = Property::new("my_prop", Value::Scalar(3_f32.into()));
+ let s = ron::to_string(&p).unwrap();
+ println!("property: {:?}", s);
+ let p_serde: Property = ron::from_str(&s).unwrap();
+ assert_eq!(p_serde, p);
+ }
+
+ /// Hash the given PropertyLayoutEntry.
+ fn hash_ple(ple: &PropertyLayoutEntry) -> u64 {
+ let mut hasher = DefaultHasher::default();
+ ple.hash(&mut hasher);
+ hasher.finish()
+ }
+
+ #[test]
+ fn property_layout_entry() {
+ // self == self
+ let prop1 = Property::new("my_prop", Vec3::NEG_X);
+ let entry1 = PropertyLayoutEntry {
+ property: prop1,
+ offset: 16,
+ };
+ assert_eq!(
+ format!("{:?}", entry1),
+ "(+16) my_prop: vec3<f32>".to_string()
+ );
+ assert_eq!(entry1, entry1);
+ assert_eq!(hash_ple(&entry1), hash_ple(&entry1));
+
+ // same name, offset, type
+ let prop1b = Property::new("my_prop", Vec3::X);
+ let entry1b = PropertyLayoutEntry {
+ property: prop1b,
+ offset: 16,
+ };
+ assert_eq!(
+ format!("{:?}", entry1b),
+ "(+16) my_prop: vec3<f32>".to_string()
+ );
+ assert_eq!(entry1, entry1b);
+ assert_eq!(hash_ple(&entry1), hash_ple(&entry1b));
+
+ // different name (shouldn't happen within same layout)
+ let prop2 = Property::new("other_prop", Vec3::Y);
+ let entry2 = PropertyLayoutEntry {
+ property: prop2,
+ offset: 16,
+ };
+ assert_eq!(
+ format!("{:?}", entry2),
+ "(+16) other_prop: vec3<f32>".to_string()
+ );
+ assert_ne!(entry1, entry2);
+ assert_ne!(hash_ple(&entry1), hash_ple(&entry2));
+ assert_ne!(entry1b, entry2);
+ assert_ne!(hash_ple(&entry1b), hash_ple(&entry2));
+
+ // different type (shouldn't happen within same layout)
+ let prop3 = Property::new("my_prop", 3.4_f32);
+ let entry3 = PropertyLayoutEntry {
+ property: prop3,
+ offset: 16,
+ };
+ assert_eq!(format!("{:?}", entry3), "(+16) my_prop: f32".to_string());
+ assert_ne!(entry1, entry3);
+ assert_ne!(hash_ple(&entry1), hash_ple(&entry3));
+ assert_ne!(entry1b, entry3);
+ assert_ne!(hash_ple(&entry1b), hash_ple(&entry3));
+
+ // different offset (shouldn't happen within same layout)
+ let prop4 = Property::new("my_prop", Vec3::NEG_X);
+ let entry4 = PropertyLayoutEntry {
+ property: prop4,
+ offset: 24,
+ };
+ assert_eq!(
+ format!("{:?}", entry4),
+ "(+24) my_prop: vec3<f32>".to_string()
+ );
+ assert_ne!(entry1, entry4);
+ assert_ne!(hash_ple(&entry1), hash_ple(&entry4));
+ assert_ne!(entry1b, entry4);
+ assert_ne!(hash_ple(&entry1b), hash_ple(&entry4));
+ }
+
+ #[test]
+ fn layout_empty() {
+ let l = PropertyLayout::empty();
+ assert!(l.is_empty());
+ assert_eq!(l.cpu_size(), 0);
+ assert_eq!(l.align(), 0);
+ assert_eq!(l.properties().next(), None);
+ let s = l.generate_property_struct_code();
+ assert!(s.is_none());
+ }
+
+ #[test]
+ #[should_panic]
+ fn layout_empty_min_binding_size_panic() {
+ let l = PropertyLayout::empty();
+ _ = l.min_binding_size();
+ }
+
+ #[test]
+ fn layout_valid() {
+ let prop1 = Property::new("f32", 3.4_f32);
+ let prop2 = Property::new("vec3", Vec3::ZERO);
+ let prop3 = Property::new("vec2", Vec2::NEG_Y);
+ let prop4 = Property::new("vec4", Vec4::Y);
+ let layout = PropertyLayout::new([&prop1, &prop2, &prop3, &prop4]);
+ assert!(!layout.is_empty());
+ assert_eq!(layout.cpu_size(), 40);
+ assert_eq!(layout.align(), 16);
+ assert_eq!(layout.min_binding_size(), NonZeroU64::new(48).unwrap());
+ let mut it = layout.properties();
+ // vec4 goes first as it doesn't disrupt the align
+ assert_eq!(it.next(), Some((0, &prop4)));
+ // vec3 and f32 go next, in pairs, for same reason
+ assert_eq!(it.next(), Some((16, &prop2)));
+ assert_eq!(it.next(), Some((28, &prop1)));
+ // anything left go last
+ assert_eq!(it.next(), Some((32, &prop3)));
+ assert_eq!(it.next(), None);
+ let s = layout.generate_property_struct_code();
+ assert_eq!(
+ s,
+ Some(
+ r#"struct Properties {
+ vec4: vec4<f32>,
+ vec3: vec3<f32>,
+ f32: f32,
+ vec2: vec2<f32>,
+}
+"#
+ .to_string()
+ )
+ );
+ }
+
+ // Regression test for #478
+ #[test]
+ fn layout_padding_vec3() {
+ let prop1 = Property::new("vec4a", Vec4::Y);
+ let prop2 = Property::new("vec3b", Vec3::ZERO);
+ let prop3 = Property::new("vec3c", Vec3::ONE);
+ let layout = PropertyLayout::new([&prop1, &prop2, &prop3]);
+ assert!(!layout.is_empty());
+ assert_eq!(layout.cpu_size(), 44); // 16 + 16 + 12
+ assert_eq!(layout.align(), 16);
+ assert_eq!(layout.min_binding_size(), NonZeroU64::new(48).unwrap());
+ let mut it = layout.properties();
+ // vec4 goes first as it doesn't disrupt the align
+ assert_eq!(it.next(), Some((0, &prop1)));
+ // vec3 goes next, with padding
+ assert_eq!(it.next(), Some((16, &prop2)));
+ // [padding] @24,+4
+ assert_eq!(it.next(), Some((32, &prop3)));
+ assert_eq!(it.next(), None);
+ let s = layout.generate_property_struct_code();
+ assert_eq!(
+ s,
+ Some(
+ r#"struct Properties {
+ vec4a: vec4<f32>,
+ vec3b: vec3<f32>,
+ vec3c: vec3<f32>,
+}
+"#
+ .to_string()
+ )
+ );
+ }
+
+ #[test]
+ fn layout_tail_332() {
+ let prop1 = Property::new("vec2", Vec2::NEG_Y);
+ let prop2 = Property::new("vec3a", Vec3::ZERO);
+ let prop3 = Property::new("vec3b", Vec3::NEG_X);
+ let layout = PropertyLayout::new([&prop1, &prop2, &prop3]);
+ assert!(!layout.is_empty());
+ assert_eq!(layout.cpu_size(), 40);
+ assert_eq!(layout.align(), 16);
+ assert_eq!(layout.min_binding_size(), NonZeroU64::new(48).unwrap());
+ let mut it = layout.properties();
+ // 3/3/2
+ assert_eq!(it.next(), Some((0, &prop2)));
+ assert_eq!(it.next(), Some((16, &prop3)));
+ assert_eq!(it.next(), Some((32, &prop1)));
+ assert_eq!(it.next(), None);
+ let s = layout.generate_property_struct_code();
+ assert_eq!(
+ s,
+ Some(
+ r#"struct Properties {
+ vec3a: vec3<f32>,
+ vec3b: vec3<f32>,
+ vec2: vec2<f32>,
+}
+"#
+ .to_string()
+ )
+ );
+ }
+
+ #[test]
+ fn layout_tail_32() {
+ let prop1 = Property::new("vec2", Vec2::NEG_Y);
+ let prop2 = Property::new("vec3", Vec3::ZERO);
+ let layout = PropertyLayout::new([&prop1, &prop2]);
+ assert!(!layout.is_empty());
+ assert_eq!(layout.cpu_size(), 24);
+ assert_eq!(layout.align(), 16);
+ assert_eq!(layout.min_binding_size(), NonZeroU64::new(32).unwrap());
+ let mut it = layout.properties();
+ // 3/2
+ assert_eq!(it.next(), Some((0, &prop2)));
+ assert_eq!(it.next(), Some((16, &prop1)));
+ assert_eq!(it.next(), None);
+ let s = layout.generate_property_struct_code();
+ assert_eq!(
+ s,
+ Some(
+ r#"struct Properties {
+ vec3: vec3<f32>,
+ vec2: vec2<f32>,
+}
+"#
+ .to_string()
+ )
+ );
+ }
+
+ #[test]
+ fn layout_tail_21() {
+ let prop1 = Property::new("f32", 3.4_f32);
+ let prop2 = Property::new("vec2", Vec2::NEG_Y);
+ let layout = PropertyLayout::new([&prop1, &prop2]);
+ assert!(!layout.is_empty());
+ assert_eq!(layout.cpu_size(), 12);
+ assert_eq!(layout.align(), 8);
+ assert_eq!(layout.min_binding_size(), NonZeroU64::new(16).unwrap());
+ let mut it = layout.properties();
+ // 2/1
+ assert_eq!(it.next(), Some((0, &prop2)));
+ assert_eq!(it.next(), Some((8, &prop1)));
+ assert_eq!(it.next(), None);
+ let s = layout.generate_property_struct_code();
+ assert_eq!(
+ s,
+ Some(
+ r#"struct Properties {
+ vec2: vec2<f32>,
+ f32: f32,
+}
+"#
+ .to_string()
+ )
+ );
+ }
+
+ #[test]
+ fn effect_properties_with_properties() {
+ let ep = EffectProperties::default()
+ .with_properties([
+ ("a".to_string(), 3.0.into()),
+ ("b".to_string(), Vec3::ZERO.into()),
+ ])
+ .with_properties([
+ ("a".to_string(), 7.0.into()),
+ ("c".to_string(), Vec2::ONE.into()),
+ ]);
+
+ assert_eq!(ep.properties.len(), 3);
+
+ assert_eq!(ep.properties[0].def.name(), "a");
+ // kept original 3.0 default
+ assert_eq!(
+ ep.properties[0].def.default_value(),
+ &Value::Scalar(3.0.into())
+ );
+ // overwrote current value as 7.0
+ assert_eq!(ep.properties[0].value, 7.0.into());
+
+ assert_eq!(ep.properties[1].def.name(), "b");
+ assert_eq!(
+ ep.properties[1].def.default_value(),
+ &Value::Vector(Vec3::ZERO.into())
+ );
+ assert_eq!(ep.properties[1].value, Vec3::ZERO.into());
+
+ assert_eq!(ep.properties[2].def.name(), "c");
+ assert_eq!(
+ ep.properties[2].def.default_value(),
+ &Value::Vector(Vec2::ONE.into())
+ );
+ assert_eq!(ep.properties[2].value, Vec2::ONE.into());
+ }
+
+ #[test]
+ #[should_panic]
+ fn effect_properties_with_properties_type_mismatch() {
+ let _ = EffectProperties::default()
+ .with_properties([("a".to_string(), 3.0.into())])
+ // Mismatching type for existing property; will panic
+ .with_properties([("a".to_string(), Vec2::ONE.into())]);
+ }
+
+ #[test]
+ fn effect_properties_get_stored() {
+ let ep = EffectProperties::default()
+ .with_properties([
+ ("a".to_string(), 3.0.into()),
+ ("b".to_string(), Vec3::ZERO.into()),
+ ])
+ .with_properties([
+ ("a".to_string(), 7.0.into()),
+ ("c".to_string(), Vec2::ONE.into()),
+ ]);
+
+ assert!(ep.get_stored("a").is_some());
+ assert!(ep.get_stored("b").is_some());
+ assert!(ep.get_stored("c").is_some());
+ assert!(ep.get_stored("x").is_none());
+ }
+
+ #[test]
+ fn effect_properties_set() {
+ let mut ep = EffectProperties::default().with_properties([
+ ("a".to_string(), 3.0.into()),
+ ("b".to_string(), Vec3::ZERO.into()),
+ ]);
+
+ ep.set("a", 7.0.into());
+ ep.set("x", 3.0.into());
+ }
+
+ #[test]
+ #[should_panic]
+ fn effect_properties_set_type_mismatch() {
+ let mut ep = EffectProperties::default().with_properties([("a".to_string(), 3.0.into())]);
+ ep.set("a", Vec3::ZERO.into());
+ }
+
+ #[test]
+ fn effect_properties_update_empty() {
+ // Empty asset vs. empty runtime == empty
+ let mut ep = EffectProperties::default();
+ let mut added = Tick::new(0);
+ let last_changed_prev = Tick::new(0u32.wrapping_sub(1u32));
+ let mut last_changed = last_changed_prev;
+ let last_run = last_changed;
+ let this_run = added;
+ let asset_properties = vec![];
+ {
+ let mut caller = MaybeLocation::caller();
+ let this = Mut::new(
+ &mut ep,
+ &mut added,
+ &mut last_changed,
+ None,
+ last_run,
+ this_run,
+ caller.as_mut(),
+ );
+ let is_added = true;
+ EffectProperties::update(this, &asset_properties, is_added);
+ }
+ assert!(ep.properties.is_empty());
+ assert_eq!(last_changed, last_changed_prev); // unchanged (no-op)
+ }
+
+ #[test]
+ fn effect_properties_update_added() {
+ // Some asset vs. empty runtime == some
+ let mut ep = EffectProperties::default();
+ let mut added = Tick::new(0);
+ let last_changed_prev = Tick::new(0u32.wrapping_sub(1u32));
+ let mut last_changed = last_changed_prev;
+ let last_run = last_changed;
+ let this_run = added;
+ let asset_properties = vec![Property::new("prop1", 32.)];
+ {
+ let mut caller = MaybeLocation::caller();
+ let this = Mut::new(
+ &mut ep,
+ &mut added,
+ &mut last_changed,
+ None,
+ last_run,
+ this_run,
+ caller.as_mut(),
+ );
+ let is_added = true;
+ EffectProperties::update(this, &asset_properties, is_added);
+ }
+ assert_eq!(ep.properties.len(), 1);
+ assert_eq!(ep.properties[0].def, asset_properties[0]);
+ assert_eq!(last_changed, this_run); // changed (added missing property)
+ }
+
+ #[test]
+ fn effect_properties_update_removed() {
+ // Empty asset vs. some runtime == empty
+ let mut ep = EffectProperties::default();
+ ep.set("unknown", 3.into());
+ let mut added = Tick::new(0);
+ let last_changed_prev = Tick::new(0u32.wrapping_sub(1u32));
+ let mut last_changed = last_changed_prev;
+ let last_run = last_changed;
+ let this_run = added;
+ let asset_properties = vec![];
+ {
+ let mut caller = MaybeLocation::caller();
+ let this = Mut::new(
+ &mut ep,
+ &mut added,
+ &mut last_changed,
+ None,
+ last_run,
+ this_run,
+ caller.as_mut(),
+ );
+ let is_added = true;
+ EffectProperties::update(this, &asset_properties, is_added);
+ }
+ assert!(ep.properties.is_empty());
+ assert_eq!(last_changed, this_run); // changed (removed unknown
+ // property)
+ }
+
+ #[test]
+ fn effect_properties_update_override() {
+ // Some asset vs. same runtime == same(runtime)
+ let mut ep = EffectProperties::default();
+ ep.set("prop1", 5_f32.into());
+ let mut added = Tick::new(0);
+ let last_changed_prev = Tick::new(0u32.wrapping_sub(1u32));
+ let mut last_changed = last_changed_prev;
+ let last_run = last_changed;
+ let this_run = added;
+ let asset_properties = vec![Property::new("prop1", 32.)];
+ {
+ let mut caller = MaybeLocation::caller();
+ let this = Mut::new(
+ &mut ep,
+ &mut added,
+ &mut last_changed,
+ None,
+ last_run,
+ this_run,
+ caller.as_mut(),
+ );
+ let is_added = true;
+ EffectProperties::update(this, &asset_properties, is_added);
+ }
+ assert_eq!(ep.properties.len(), 1);
+ assert_eq!(ep.properties[0].def.name(), asset_properties[0].name());
+ assert_eq!(ep.properties[0].value, 5_f32.into());
+ assert_eq!(last_changed, last_changed_prev); // unchanged
+ }
+
+ #[test]
+ fn effect_properties_update_mixed() {
+ // Some asset vs. some runtime, one override and one default
+ let mut ep = EffectProperties::default();
+ ep.set("prop1", 5_f32.into());
+ let mut added = Tick::new(0);
+ let last_changed_prev = Tick::new(0u32.wrapping_sub(1u32));
+ let mut last_changed = last_changed_prev;
+ let last_run = last_changed;
+ let this_run = added;
+ let asset_properties = vec![Property::new("prop1", 32.), Property::new("prop2", false)];
+ {
+ let mut caller = MaybeLocation::caller();
+ let this = Mut::new(
+ &mut ep,
+ &mut added,
+ &mut last_changed,
+ None,
+ last_run,
+ this_run,
+ caller.as_mut(),
+ );
+ let is_added = true;
+ EffectProperties::update(this, &asset_properties, is_added);
+ }
+ assert_eq!(ep.properties.len(), 2);
+ assert_eq!(ep.properties[0].def.name(), asset_properties[0].name());
+ assert_eq!(ep.properties[0].value, 5_f32.into());
+ assert_eq!(ep.properties[1].def, asset_properties[1]);
+ assert_eq!(last_changed, this_run); // changed (added missing property)
+ }
+
+ #[test]
+ fn effect_properties_serialize() {
+ let ep = EffectProperties::default().with_properties([
+ ("a".to_string(), 3.0.into()),
+ ("b".to_string(), Vec3::ONE.into()),
+ ]);
+ let layout = PropertyLayout::new(ep.properties().iter().map(|pi| &pi.def));
+ let blob = ep.serialize(&layout);
+ assert_eq!(blob.len(), layout.cpu_size() as usize);
+
+ let pi_a = &ep.properties()[0];
+ let size = pi_a.def.size();
+ assert_eq!(size, 4); // f32
+ let offset = layout.offset(pi_a.def.name()).unwrap() as usize;
+ let raw = &blob[offset..offset + size];
+ #[allow(unsafe_code)]
+ let raw_ref: &[u8; 4] = unsafe { std::mem::transmute(&[3.0_f32]) };
+ assert_eq!(raw, raw_ref);
+
+ let pi_b = &ep.properties()[1];
+ let size = pi_b.def.size();
+ assert_eq!(size, 12); // Vec3
+ let offset = layout.offset(pi_b.def.name()).unwrap() as usize;
+ let raw = &blob[offset..offset + size];
+ #[allow(unsafe_code)]
+ let raw_ref: &[u8; 12] = unsafe { std::mem::transmute(&[1_f32, 1_f32, 1_f32]) };
+ assert_eq!(raw, raw_ref);
+ }
+}
diff --git a/vendor/bevy_hanabi/src/render/aligned_buffer_vec.rs b/vendor/bevy_hanabi/src/render/aligned_buffer_vec.rs
new file mode 100644
index 00000000..a5d2fa40
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/aligned_buffer_vec.rs
@@ -0,0 +1,1269 @@
+use std::{num::NonZeroU64, ops::Range};
+
+use bevy::{
+ log::trace,
+ render::{
+ render_resource::{
+ BindingResource, Buffer, BufferAddress, BufferBinding, BufferDescriptor, BufferUsages,
+ ShaderSize, ShaderType,
+ },
+ renderer::{RenderDevice, RenderQueue},
+ },
+};
+use bytemuck::{cast_slice, Pod};
+
+/// Like Bevy's [`BufferVec`], but with extra per-item alignment.
+///
+/// This helper ensures the individual array elements are properly aligned,
+/// depending on the device constraints and the WGSL rules. In general using
+/// [`BufferVec`] is enough to ensure alignment; however when some array items
+/// also need to be bound individually, then each item (not only the array
+/// itself) needs to be aligned to the device requirements. This is admittedly a
+/// very specific case, because the device alignment might be very large (256
+/// bytes) and this causes a lot of wasted space (padding per-element, instead
+/// of padding for the entire array).
+///
+/// For this buffer to work correctly and items be bindable individually, the
+/// alignment must come from one of the [`WgpuLimits`]. For example for a
+/// storage buffer, to be able to bind the entire buffer but also any subset of
+/// it (including individual elements), the extra alignment must
+/// be [`WgpuLimits::min_storage_buffer_offset_alignment`].
+///
+/// The element type `T` needs to implement the following traits:
+/// - [`Pod`] to allow copy.
+/// - [`ShaderType`] because it needs to be mapped for a shader.
+/// - [`ShaderSize`] to ensure a fixed footprint, to allow packing multiple
+/// instances inside a single buffer. This therefore excludes any
+/// runtime-sized array.
+///
+/// [`BufferVec`]: bevy::render::render_resource::BufferVec
+/// [`WgpuLimits`]: bevy::render::settings::WgpuLimits
+pub struct AlignedBufferVec<T: Pod + ShaderSize> {
+ /// Pending values accumulated on CPU and not yet written to GPU.
+ values: Vec<T>,
+ /// GPU buffer if already allocated, or `None` otherwise.
+ buffer: Option<Buffer>,
+ /// Capacity of the buffer, in number of elements.
+ capacity: usize,
+ /// Size of a single buffer element, in bytes, in CPU memory (Rust layout).
+ item_size: usize,
+ /// Size of a single buffer element, in bytes, aligned to GPU memory
+ /// constraints.
+ aligned_size: usize,
+ /// GPU buffer usages.
+ buffer_usage: BufferUsages,
+ /// Optional GPU buffer name, for debugging.
+ label: Option<String>,
+}
+
+impl<T: Pod + ShaderSize> Default for AlignedBufferVec<T> {
+ fn default() -> Self {
+ let item_size = std::mem::size_of::<T>();
+ let aligned_size = <T as ShaderSize>::SHADER_SIZE.get() as usize;
+ assert!(aligned_size >= item_size);
+ Self {
+ values: Vec::new(),
+ buffer: None,
+ capacity: 0,
+ buffer_usage: BufferUsages::all(),
+ item_size,
+ aligned_size,
+ label: None,
+ }
+ }
+}
+
+impl<T: Pod + ShaderSize> AlignedBufferVec<T> {
+ /// Create a new collection.
+ ///
+ /// `item_align` is an optional additional alignment for items in the
+ /// collection. If greater than the natural alignment dictated by WGSL
+ /// rules, this extra alignment is enforced. Otherwise it's ignored (so you
+ /// can pass `0` to ignore).
+ ///
+ /// # Panics
+ ///
+ /// Panics if `buffer_usage` contains [`BufferUsages::UNIFORM`] and the
+ /// layout of the element type `T` does not meet the requirements of the
+ /// uniform address space, as tested by
+ /// [`ShaderType::assert_uniform_compat()`].
+ ///
+ /// [`BufferUsages::UNIFORM`]: bevy::render::render_resource::BufferUsages::UNIFORM
+ pub fn new(
+ buffer_usage: BufferUsages,
+ item_align: Option<NonZeroU64>,
+ label: Option<String>,
+ ) -> Self {
+ // GPU-aligned item size, compatible with WGSL rules
+ let item_size = <T as ShaderSize>::SHADER_SIZE.get() as usize;
+ // Extra manual alignment for device constraints
+ let aligned_size = if let Some(item_align) = item_align {
+ let item_align = item_align.get() as usize;
+ let aligned_size = item_size.next_multiple_of(item_align);
+ assert!(aligned_size >= item_size);
+ assert!(aligned_size.is_multiple_of(item_align));
+ aligned_size
+ } else {
+ item_size
+ };
+ trace!(
+ "AlignedBufferVec['{}']: item_size={} aligned_size={}",
+ label.as_ref().map(|s| &s[..]).unwrap_or(""),
+ item_size,
+ aligned_size
+ );
+ if buffer_usage.contains(BufferUsages::UNIFORM) {
+ <T as ShaderType>::assert_uniform_compat();
+ }
+ Self {
+ buffer_usage,
+ aligned_size,
+ label,
+ ..Default::default()
+ }
+ }
+
+ fn safe_label(&self) -> &str {
+ self.label.as_ref().map(|s| &s[..]).unwrap_or("")
+ }
+
+ #[inline]
+ pub fn buffer(&self) -> Option<&Buffer> {
+ self.buffer.as_ref()
+ }
+
+ /// Get a binding for the entire buffer.
+ #[inline]
+ #[allow(dead_code)]
+ pub fn binding(&self) -> Option<BindingResource<'_>> {
+ // FIXME - Return a Buffer wrapper first, which can be unwrapped, then from that
+ // wrapper implement all the xxx_binding() helpers. That avoids a bunch of "if
+ // let Some()" everywhere when we know the buffer is valid. The only reason the
+ // buffer might not be valid is if it was not created, and in that case
+ // we wouldn't be calling the xxx_bindings() helpers, we'd have earlied out
+ // before.
+ let buffer = self.buffer()?;
+ Some(buffer.as_entire_binding())
+ }
+
+ /// Get a binding for a subset of the elements of the buffer.
+ ///
+ /// Returns a binding for the elements in the range `offset..offset+count`.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `count` is zero.
+ #[inline]
+ #[allow(dead_code)]
+ pub fn range_binding(&self, offset: u32, count: u32) -> Option<BindingResource<'_>> {
+ assert!(count > 0);
+ let buffer = self.buffer()?;
+ let offset = self.aligned_size as u64 * offset as u64;
+ let size = NonZeroU64::new(self.aligned_size as u64 * count as u64).unwrap();
+ Some(BindingResource::Buffer(BufferBinding {
+ buffer,
+ offset,
+ size: Some(size),
+ }))
+ }
+
+ #[inline]
+ #[allow(dead_code)]
+ pub fn capacity(&self) -> usize {
+ self.capacity
+ }
+
+ #[inline]
+ pub fn len(&self) -> usize {
+ self.values.len()
+ }
+
+ /// Size in bytes of a single item in the buffer, aligned to the item
+ /// alignment.
+ #[inline]
+ pub fn aligned_size(&self) -> usize {
+ self.aligned_size
+ }
+
+ /// Calculate a dynamic byte offset for a bind group from an array element
+ /// index.
+ ///
+ /// This returns the product of `index` by the internal [`aligned_size()`].
+ ///
+ /// # Panic
+ ///
+ /// Panics if the `index` is too large, producing a byte offset larger than
+ /// `u32::MAX`.
+ ///
+ /// [`aligned_size()`]: crate::AlignedBufferVec::aligned_size
+ #[inline]
+ #[must_use]
+ pub fn dynamic_offset(&self, index: usize) -> u32 {
+ let offset = self.aligned_size * index;
+ assert!(offset <= u32::MAX as usize);
+ u32::try_from(offset).expect("AlignedBufferVec index out of bounds")
+ }
+
+ #[inline]
+ #[must_use]
+ #[allow(dead_code)]
+ pub fn is_empty(&self) -> bool {
+ self.values.is_empty()
+ }
+
+ /// Append a value to the buffer.
+ ///
+ /// The content is stored on the CPU and uploaded on the GPU once
+ /// [`write_buffer()`] is called.
+ ///
+ /// [`write_buffer()`]: crate::AlignedBufferVec::write_buffer
+ pub fn push(&mut self, value: T) -> usize {
+ let index = self.values.len();
+ self.values.push(value);
+ index
+ }
+
+ #[inline]
+ #[must_use]
+ #[allow(dead_code)]
+ pub fn last(&self) -> Option<&T> {
+ self.values.last()
+ }
+
+ #[inline]
+ #[must_use]
+ pub fn last_mut(&mut self) -> Option<&mut T> {
+ self.values.last_mut()
+ }
+
+ /// Reserve some capacity into the buffer.
+ ///
+ /// If the buffer is reallocated, the old content (on the GPU) is lost, and
+ /// needs to be re-uploaded to the newly-created buffer. This is done with
+ /// [`write_buffer()`].
+ ///
+ /// # Returns
+ ///
+ /// `true` if the buffer was (re)allocated, or `false` if an existing buffer
+ /// was reused which already had enough capacity.
+ ///
+ /// [`write_buffer()`]: crate::AlignedBufferVec::write_buffer
+ #[must_use]
+ pub fn reserve(&mut self, capacity: usize, device: &RenderDevice) -> bool {
+ if capacity > self.capacity {
+ let size = self.aligned_size * capacity;
+ trace!(
+ "reserve['{}']: increase capacity from {} to {} elements, new size {} bytes",
+ self.safe_label(),
+ self.capacity,
+ capacity,
+ size
+ );
+ self.capacity = capacity;
+ if let Some(old_buffer) = self.buffer.take() {
+ trace!(
+ "reserve['{}']: forgetting old buffer #{:?}",
+ self.safe_label(),
+ old_buffer.id()
+ );
+ // Do not explicitly destroy the old buffer here; let the
+ // backend drop it safely.
+ }
+ let new_buffer = device.create_buffer(&BufferDescriptor {
+ label: self.label.as_ref().map(|s| &s[..]),
+ size: size as BufferAddress,
+ usage: BufferUsages::COPY_DST | self.buffer_usage,
+ mapped_at_creation: false,
+ });
+ trace!(
+ "reserve['{}']: created new buffer #{:?}",
+ self.safe_label(),
+ new_buffer.id(),
+ );
+ self.buffer = Some(new_buffer);
+ // FIXME - this discards the old content if any!!!
+ true
+ } else {
+ false
+ }
+ }
+
+ /// Schedule the buffer write to GPU.
+ ///
+ /// # Returns
+ ///
+ /// `true` if the buffer was (re)allocated, `false` otherwise. This
+ /// indicates whether bind groups need to be re-created.
+ #[must_use]
+ pub fn write_buffer(&mut self, device: &RenderDevice, queue: &RenderQueue) -> bool {
+ if self.values.is_empty() {
+ return false;
+ }
+ trace!(
+ "write_buffer['{}']: values.len={} item_size={} aligned_size={}",
+ self.safe_label(),
+ self.values.len(),
+ self.item_size,
+ self.aligned_size
+ );
+ let buffer_changed = self.reserve(self.values.len(), device);
+ if let Some(buffer) = &self.buffer {
+ let aligned_size = self.aligned_size * self.values.len();
+ if self.aligned_size == self.item_size {
+ // The CPU storage already contains aligned items; directly write to GPU buffer.
+ trace!(
+ "+ direct-write['{}']: size={}B buffer={:?}",
+ self.safe_label(),
+ aligned_size,
+ buffer.id(),
+ );
+ let src: &[u8] = cast_slice(&self.values[..]);
+ queue.write_buffer(buffer, 0, src);
+ } else {
+ // The CPU storage contains items smaller than the aligned size; copy with
+ // padding into a temporary storage to align items, then write from that
+ // temporary to the GPU buffer.
+ trace!(
+ "+ aligned_buffer['{}']: size={}B buffer={:?}",
+ self.safe_label(),
+ aligned_size,
+ buffer.id(),
+ );
+ let mut aligned_buffer: Vec<u8> = vec![0; aligned_size];
+ for i in 0..self.values.len() {
+ let src: &[u8] = cast_slice(std::slice::from_ref(&self.values[i]));
+ let dst_offset = i * self.aligned_size;
+ let dst_range = dst_offset..dst_offset + self.item_size;
+ trace!(
+ "+ copy: src={:?} ({}B) dst={:?}",
+ src.as_ptr(),
+ self.item_size,
+ dst_range
+ );
+ let dst = &mut aligned_buffer[dst_range];
+ dst.copy_from_slice(src);
+ }
+ queue.write_buffer(buffer, 0, &aligned_buffer[..]);
+ }
+ }
+ buffer_changed
+ }
+
+ pub fn clear(&mut self) {
+ self.values.clear();
+ }
+}
+
+impl<T: Pod + ShaderSize> std::ops::Index<usize> for AlignedBufferVec<T> {
+ type Output = T;
+
+ fn index(&self, index: usize) -> &Self::Output {
+ &self.values[index]
+ }
+}
+
+impl<T: Pod + ShaderSize> std::ops::IndexMut<usize> for AlignedBufferVec<T> {
+ fn index_mut(&mut self, index: usize) -> &mut Self::Output {
+ &mut self.values[index]
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+struct FreeRow(pub Range<u32>);
+
+impl PartialOrd for FreeRow {
+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+ Some(self.cmp(other))
+ }
+}
+
+impl Ord for FreeRow {
+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+ self.0.start.cmp(&other.0.start)
+ }
+}
+
+/// Like [`AlignedBufferVec`], but for heterogenous data.
+#[derive(Debug)]
+pub struct HybridAlignedBufferVec {
+ /// Pending values accumulated on CPU and not yet written to GPU.
+ values: Vec<u8>,
+ /// GPU buffer if already allocated, or `None` otherwise.
+ buffer: Option<Buffer>,
+ /// Capacity of the buffer, in bytes.
+ capacity: usize,
+ /// Alignment of each element, in bytes.
+ item_align: usize,
+ /// GPU buffer usages.
+ buffer_usage: BufferUsages,
+ /// Optional GPU buffer name, for debugging.
+ label: Option<String>,
+ /// Free ranges available for re-allocation. Those are row ranges; byte
+ /// ranges are obtained by multiplying these by `item_align`.
+ free_rows: Vec<FreeRow>,
+ /// Is the GPU buffer stale and the CPU one need to be re-uploaded?
+ is_stale: bool,
+}
+
+impl HybridAlignedBufferVec {
+ /// Create a new collection.
+ ///
+ /// `item_align` is the alignment for items in the collection.
+ pub fn new(buffer_usage: BufferUsages, item_align: NonZeroU64, label: Option<String>) -> Self {
+ let item_align = item_align.get() as usize;
+ trace!(
+ "HybridAlignedBufferVec['{}']: item_align={} byte",
+ label.as_ref().map(|s| &s[..]).unwrap_or(""),
+ item_align,
+ );
+ Self {
+ values: vec![],
+ buffer: None,
+ capacity: 0,
+ item_align,
+ buffer_usage,
+ label,
+ free_rows: vec![],
+ is_stale: true,
+ }
+ }
+
+ #[inline]
+ pub fn buffer(&self) -> Option<&Buffer> {
+ self.buffer.as_ref()
+ }
+
+ /// Get a binding for the entire buffer.
+ #[allow(dead_code)]
+ #[inline]
+ pub fn max_binding(&self) -> Option<BindingResource<'_>> {
+ // FIXME - Return a Buffer wrapper first, which can be unwrapped, then from that
+ // wrapper implement all the xxx_binding() helpers. That avoids a bunch of "if
+ // let Some()" everywhere when we know the buffer is valid. The only reason the
+ // buffer might not be valid is if it was not created, and in that case
+ // we wouldn't be calling the xxx_bindings() helpers, we'd have earlied out
+ // before.
+ let buffer = self.buffer()?;
+ Some(BindingResource::Buffer(BufferBinding {
+ buffer,
+ offset: 0,
+ size: None, // entire buffer
+ }))
+ }
+
+ /// Get a binding for the first `size` bytes of the buffer.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `size` is zero.
+ #[allow(dead_code)]
+ #[inline]
+ pub fn lead_binding(&self, size: u32) -> Option<BindingResource<'_>> {
+ let buffer = self.buffer()?;
+ let size = NonZeroU64::new(size as u64).unwrap();
+ Some(BindingResource::Buffer(BufferBinding {
+ buffer,
+ offset: 0,
+ size: Some(size),
+ }))
+ }
+
+ /// Get a binding for a subset of the elements of the buffer.
+ ///
+ /// Returns a binding for the elements in the range `offset..offset+count`.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `offset` is not a multiple of the alignment specified on
+ /// construction.
+ ///
+ /// Panics if `size` is zero.
+ #[allow(dead_code)]
+ #[inline]
+ pub fn range_binding(&self, offset: u32, size: u32) -> Option<BindingResource<'_>> {
+ assert!((offset as usize).is_multiple_of(self.item_align));
+ let buffer = self.buffer()?;
+ let size = NonZeroU64::new(size as u64).unwrap();
+ Some(BindingResource::Buffer(BufferBinding {
+ buffer,
+ offset: offset as u64,
+ size: Some(size),
+ }))
+ }
+
+ /// Capacity of the allocated GPU buffer, in bytes.
+ ///
+ /// This may be zero if the buffer was not allocated yet. In general, this
+ /// can differ from the actual data size cached on CPU and waiting to be
+ /// uploaded to GPU.
+ #[inline]
+ #[allow(dead_code)]
+ pub fn capacity(&self) -> usize {
+ self.capacity
+ }
+
+ /// Current buffer size, in bytes.
+ ///
+ /// This represents the size of the CPU data uploaded to GPU. Pending a GPU
+ /// buffer re-allocation or re-upload, this size might differ from the
+ /// actual GPU buffer size. But they're eventually consistent.
+ #[allow(dead_code)]
+ #[inline]
+ pub fn len(&self) -> usize {
+ self.values.len()
+ }
+
+ /// Alignment, in bytes, of all the elements.
+ #[allow(dead_code)]
+ #[inline]
+ pub fn item_align(&self) -> usize {
+ self.item_align
+ }
+
+ /// Calculate a dynamic byte offset for a bind group from an array element
+ /// index.
+ ///
+ /// This returns the product of `index` by the internal [`item_align()`].
+ ///
+ /// # Panic
+ ///
+ /// Panics if the `index` is too large, producing a byte offset larger than
+ /// `u32::MAX`.
+ ///
+ /// [`item_align()`]: crate::HybridAlignedBufferVec::item_align
+ #[allow(dead_code)]
+ #[inline]
+ pub fn dynamic_offset(&self, index: usize) -> u32 {
+ let offset = self.item_align * index;
+ assert!(offset <= u32::MAX as usize);
+ u32::try_from(offset).expect("HybridAlignedBufferVec index out of bounds")
+ }
+
+ #[inline]
+ #[allow(dead_code)]
+ pub fn is_empty(&self) -> bool {
+ self.values.is_empty()
+ }
+
+ /// Append a value to the buffer.
+ ///
+ /// As with [`set_content()`], the content is stored on the CPU and uploaded
+ /// on the GPU once [`write_buffers()`] is called.
+ ///
+ /// # Returns
+ ///
+ /// Returns a range starting at the byte offset at which the new element was
+ /// inserted, which is guaranteed to be a multiple of [`item_align()`].
+ /// The range span is the item byte size.
+ ///
+ /// [`item_align()`]: self::HybridAlignedBufferVec::item_align
+ #[allow(dead_code)]
+ pub fn push<T: Pod + ShaderSize>(&mut self, value: &T) -> Range<u32> {
+ let src: &[u8] = cast_slice(std::slice::from_ref(value));
+ assert_eq!(value.size().get() as usize, src.len());
+ self.push_raw(src)
+ }
+
+ /// Append a slice of values to the buffer.
+ ///
+ /// The values are assumed to be tightly packed, and will be copied
+ /// back-to-back into the buffer, without any padding between them. This
+ /// means that the individul slice items must be properly aligned relative
+ /// to the beginning of the slice.
+ ///
+ /// As with [`set_content()`], the content is stored on the CPU and uploaded
+ /// on the GPU once [`write_buffers()`] is called.
+ ///
+ /// # Returns
+ ///
+ /// Returns a range starting at the byte offset at which the new element
+ /// (the slice) was inserted, which is guaranteed to be a multiple of
+ /// [`item_align()`]. The range span is the item byte size.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the byte size of the element `T` is not at least a multiple of
+ /// the minimum GPU alignment, which is 4 bytes. Note that this doesn't
+ /// guarantee that the written data is well-formed for use on GPU, as array
+ /// elements on GPU have other alignment requirements according to WGSL, but
+ /// at least this catches obvious errors.
+ ///
+ /// [`item_align()`]: self::HybridAlignedBufferVec::item_align
+ #[allow(dead_code)]
+ pub fn push_many<T: Pod + ShaderSize>(&mut self, value: &[T]) -> Range<u32> {
+ assert_eq!(size_of::<T>() % 4, 0);
+ let src: &[u8] = cast_slice(value);
+ self.push_raw(src)
+ }
+
+ pub fn push_raw(&mut self, src: &[u8]) -> Range<u32> {
+ self.is_stale = true;
+
+ // Calculate the number of (aligned) rows to allocate
+ let num_rows = src.len().div_ceil(self.item_align) as u32;
+
+ // Try to find a block of free rows which can accomodate it, and pick the
+ // smallest one in order to limit wasted space.
+ let mut best_slot: Option<(u32, usize)> = None;
+ for (index, range) in self.free_rows.iter().enumerate() {
+ let free_rows = range.0.end - range.0.start;
+ if free_rows >= num_rows {
+ let wasted_rows = free_rows - num_rows;
+ // If we found a slot with the exact size, just use it already
+ if wasted_rows == 0 {
+ best_slot = Some((0, index));
+ break;
+ }
+ // Otherwise try to find the smallest oversized slot to reduce wasted space
+ if let Some(best_slot) = best_slot.as_mut() {
+ if wasted_rows < best_slot.0 {
+ *best_slot = (wasted_rows, index);
+ }
+ } else {
+ best_slot = Some((wasted_rows, index));
+ }
+ }
+ }
+
+ // Insert into existing space
+ if let Some((_, index)) = best_slot {
+ let row_range = self.free_rows.remove(index);
+ let offset = row_range.0.start as usize * self.item_align;
+ let free_size = (row_range.0.end - row_range.0.start) as usize * self.item_align;
+ let size = src.len();
+ assert!(size <= free_size);
+
+ let dst = self.values.as_mut_ptr();
+ // SAFETY: dst is guaranteed to point to allocated bytes, which are already
+ // initialized from a previous call, and are initialized by overwriting the
+ // bytes with those of a POD type.
+ #[allow(unsafe_code)]
+ unsafe {
+ let dst = dst.add(offset);
+ dst.copy_from_nonoverlapping(src.as_ptr(), size);
+ }
+
+ let start = offset as u32;
+ let end = start + size as u32;
+ start..end
+ }
+ // Insert at end of vector, after resizing it
+ else {
+ // Calculate new aligned insertion offset and new capacity
+ let offset = self.values.len().next_multiple_of(self.item_align);
+ let size = src.len();
+ let new_capacity = offset + size;
+ if new_capacity > self.values.capacity() {
+ let additional = new_capacity - self.values.len();
+ self.values.reserve(additional)
+ }
+
+ // Insert padding if needed
+ if offset > self.values.len() {
+ self.values.resize(offset, 0);
+ }
+
+ // Insert serialized value
+ // Dealing with safe code via Vec::spare_capacity_mut() is quite difficult
+ // without the upcoming (unstable) additions to MaybeUninit to deal with arrays.
+ // To prevent having to loop over individual u8, we use direct pointers instead.
+ assert!(self.values.capacity() >= offset + size);
+ assert_eq!(self.values.len(), offset);
+ let dst = self.values.as_mut_ptr();
+ // SAFETY: dst is guaranteed to point to allocated (offset+size) bytes, which
+ // are written by copying a Pod type, so ensures those values are initialized,
+ // and the final size is set to exactly (offset+size).
+ #[allow(unsafe_code)]
+ unsafe {
+ let dst = dst.add(offset);
+ dst.copy_from_nonoverlapping(src.as_ptr(), size);
+ self.values.set_len(offset + size);
+ }
+
+ debug_assert_eq!(offset % self.item_align, 0);
+ let start = offset as u32;
+ let end = start + size as u32;
+ start..end
+ }
+ }
+
+ /// Remove a range of bytes previously added.
+ ///
+ /// Remove a range of bytes previously returned by adding one or more
+ /// elements with [`push()`] or [`push_many()`].
+ ///
+ /// # Returns
+ ///
+ /// Returns `true` if the range was valid and the corresponding data was
+ /// removed, or `false` otherwise. In that case, the buffer is not modified.
+ ///
+ /// [`push()`]: Self::push
+ /// [`push_many()`]: Self::push_many
+ pub fn remove(&mut self, range: Range<u32>) -> bool {
+ // Can only remove entire blocks starting at an aligned size
+ let align = self.item_align as u32;
+ if !range.start.is_multiple_of(align) {
+ return false;
+ }
+
+ // Check for out of bounds argument
+ let end = self.values.len() as u32;
+ if range.start >= end || range.end > end {
+ return false;
+ }
+
+ // Note: See below, sometimes self.values() has some padding left we couldn't
+ // recover earlier beause we didn't know the size of this allocation, but we
+ // need to still deallocate the row here.
+ if range.end == end || range.end.next_multiple_of(align) == end {
+ // If the allocation is at the end of the buffer, shorten the CPU values. This
+ // ensures is_empty() eventually returns true.
+ let mut new_row_end = range.start.div_ceil(align);
+
+ // Walk the (sorted) free list to also dequeue any range which is now at the end
+ // of the buffer
+ while let Some(free_row) = self.free_rows.pop() {
+ if free_row.0.end == new_row_end {
+ new_row_end = free_row.0.start;
+ } else {
+ self.free_rows.push(free_row);
+ break;
+ }
+ }
+
+ // Note: we can't really recover any padding here because we don't know the
+ // exact size of that allocation, only its row-aligned size.
+ self.values.truncate((new_row_end * align) as usize);
+ } else {
+ // Otherwise, save the row into the free list.
+ let start = range.start / align;
+ let end = range.end.div_ceil(align);
+ let free_row = FreeRow(start..end);
+
+ // Insert as sorted
+ if self.free_rows.is_empty() {
+ // Special case to simplify below, and to avoid binary_search()
+ self.free_rows.push(free_row);
+ } else if let Err(index) = self.free_rows.binary_search(&free_row) {
+ if index >= self.free_rows.len() {
+ // insert at end
+ let prev = self.free_rows.last_mut().unwrap(); // known
+ if prev.0.end == free_row.0.start {
+ // merge with last value
+ prev.0.end = free_row.0.end;
+ } else {
+ // insert last, with gap
+ self.free_rows.push(free_row);
+ }
+ } else if index == 0 {
+ // insert at start
+ let next = &mut self.free_rows[0];
+ if free_row.0.end == next.0.start {
+ // merge with next
+ next.0.start = free_row.0.start;
+ } else {
+ // insert first, with gap
+ self.free_rows.insert(0, free_row);
+ }
+ } else {
+ // insert between 2 existing elements
+ let prev = &mut self.free_rows[index - 1];
+ if prev.0.end == free_row.0.start {
+ // merge with previous value
+ prev.0.end = free_row.0.end;
+
+ let prev = self.free_rows[index - 1].clone();
+ let next = &mut self.free_rows[index];
+ if prev.0.end == next.0.start {
+ // also merge prev with next, and remove prev
+ next.0.start = prev.0.start;
+ self.free_rows.remove(index - 1);
+ }
+ } else {
+ let next = &mut self.free_rows[index];
+ if free_row.0.end == next.0.start {
+ // merge with next value
+ next.0.start = free_row.0.start;
+ } else {
+ // insert between 2 values, with gaps on both sides
+ self.free_rows.insert(0, free_row);
+ }
+ }
+ }
+ } else {
+ // The range exists in the free list, this means it's already removed. This is a
+ // duplicate; ignore it.
+ return false;
+ }
+ }
+ self.is_stale = true;
+ true
+ }
+
+ /// Update an allocated entry with a new value.
+ #[allow(dead_code)]
+ #[inline]
+ pub fn update<T: Pod + ShaderSize>(&mut self, offset: u32, value: &T) {
+ let data: &[u8] = cast_slice(std::slice::from_ref(value));
+ assert_eq!(value.size().get() as usize, data.len());
+ self.update_raw(offset, data);
+ }
+
+ /// Update an allocated entry with new data.
+ pub fn update_raw(&mut self, offset: u32, data: &[u8]) {
+ // Can only update entire blocks starting at an aligned size
+ let align = self.item_align as u32;
+ if !offset.is_multiple_of(align) {
+ return;
+ }
+
+ // Check for out of bounds argument
+ let end = self.values.len() as u32;
+ let data_end = offset + data.len() as u32;
+ if offset >= end || data_end > end {
+ return;
+ }
+
+ let dst: &mut [u8] = &mut self.values[offset as usize..data_end as usize];
+ dst.copy_from_slice(data);
+
+ self.is_stale = true;
+ }
+
+ /// Reserve some capacity into the buffer.
+ ///
+ /// If the buffer is reallocated, the old content (on the GPU) is lost, and
+ /// needs to be re-uploaded to the newly-created buffer. This is done with
+ /// [`write_buffer()`].
+ ///
+ /// # Returns
+ ///
+ /// `true` if the buffer was (re)allocated, or `false` if an existing buffer
+ /// was reused which already had enough capacity.
+ ///
+ /// [`write_buffer()`]: crate::AlignedBufferVec::write_buffer
+ pub fn reserve(&mut self, capacity: usize, device: &RenderDevice) -> bool {
+ if capacity > self.capacity {
+ trace!(
+ "reserve: increase capacity from {} to {} bytes",
+ self.capacity,
+ capacity,
+ );
+ self.capacity = capacity;
+ if let Some(old_buffer) = self.buffer.take() {
+ trace!("reserve: forgetting old buffer #{:?}", old_buffer.id());
+ // Do not explicitly destroy the old buffer here; let the
+ // backend drop it safely.
+ }
+ self.buffer = Some(device.create_buffer(&BufferDescriptor {
+ label: self.label.as_ref().map(|s| &s[..]),
+ size: capacity as BufferAddress,
+ usage: BufferUsages::COPY_DST | self.buffer_usage,
+ mapped_at_creation: false,
+ }));
+ self.is_stale = !self.values.is_empty();
+ // FIXME - this discards the old content if any!!!
+ true
+ } else {
+ false
+ }
+ }
+
+ /// Schedule the buffer write to GPU.
+ ///
+ /// # Returns
+ ///
+ /// `true` if the buffer was (re)allocated, `false` otherwise. If the buffer
+ /// was reallocated, all bind groups referencing the old buffer should be
+ /// destroyed.
+ pub fn write_buffer(&mut self, device: &RenderDevice, queue: &RenderQueue) -> bool {
+ if self.values.is_empty() || !self.is_stale {
+ return false;
+ }
+ let size = self.values.len();
+ trace!(
+ "hybrid abv: write_buffer: size={}B item_align={}B",
+ size,
+ self.item_align,
+ );
+ let buffer_changed = self.reserve(size, device);
+ if let Some(buffer) = &self.buffer {
+ queue.write_buffer(buffer, 0, self.values.as_slice());
+ self.is_stale = false;
+ }
+ buffer_changed
+ }
+
+ #[allow(dead_code)]
+ pub fn clear(&mut self) {
+ if !self.values.is_empty() {
+ self.is_stale = true;
+ }
+ self.values.clear();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::num::NonZeroU64;
+
+ use bevy::math::Vec3;
+ use bytemuck::{Pod, Zeroable};
+
+ use super::*;
+
+ #[repr(C)]
+ #[derive(Debug, Default, Clone, Copy, Pod, Zeroable, ShaderType)]
+ pub(crate) struct GpuDummy {
+ pub v: Vec3,
+ }
+
+ #[repr(C)]
+ #[derive(Debug, Default, Clone, Copy, Pod, Zeroable, ShaderType)]
+ pub(crate) struct GpuDummyComposed {
+ pub simple: GpuDummy,
+ pub tag: u32,
+ // GPU padding to 16 bytes due to GpuDummy forcing align to 16 bytes
+ }
+
+ #[repr(C)]
+ #[derive(Debug, Clone, Copy, Pod, Zeroable, ShaderType)]
+ pub(crate) struct GpuDummyLarge {
+ pub simple: GpuDummy,
+ pub tag: u32,
+ pub large: [f32; 128],
+ }
+
+ #[test]
+ fn abv_sizes() {
+ // Rust
+ assert_eq!(std::mem::size_of::<GpuDummy>(), 12);
+ assert_eq!(std::mem::align_of::<GpuDummy>(), 4);
+ assert_eq!(std::mem::size_of::<GpuDummyComposed>(), 16); // tight packing
+ assert_eq!(std::mem::align_of::<GpuDummyComposed>(), 4);
+ assert_eq!(std::mem::size_of::<GpuDummyLarge>(), 132 * 4); // tight packing
+ assert_eq!(std::mem::align_of::<GpuDummyLarge>(), 4);
+
+ // GPU
+ assert_eq!(<GpuDummy as ShaderType>::min_size().get(), 16); // Vec3 gets padded to 16 bytes
+ assert_eq!(<GpuDummy as ShaderSize>::SHADER_SIZE.get(), 16);
+ assert_eq!(<GpuDummyComposed as ShaderType>::min_size().get(), 32); // align is 16 bytes, forces padding
+ assert_eq!(<GpuDummyComposed as ShaderSize>::SHADER_SIZE.get(), 32);
+ assert_eq!(<GpuDummyLarge as ShaderType>::min_size().get(), 544); // align is 16 bytes, forces padding
+ assert_eq!(<GpuDummyLarge as ShaderSize>::SHADER_SIZE.get(), 544);
+
+ for (item_align, expected_aligned_size) in [
+ (0, 16),
+ (4, 16),
+ (8, 16),
+ (16, 16),
+ (32, 32),
+ (256, 256),
+ (512, 512),
+ ] {
+ let mut abv = AlignedBufferVec::<GpuDummy>::new(
+ BufferUsages::STORAGE,
+ NonZeroU64::new(item_align),
+ None,
+ );
+ assert_eq!(abv.aligned_size(), expected_aligned_size);
+ assert!(abv.is_empty());
+ abv.push(GpuDummy::default());
+ assert!(!abv.is_empty());
+ assert_eq!(abv.len(), 1);
+ }
+
+ for (item_align, expected_aligned_size) in [
+ (0, 32),
+ (4, 32),
+ (8, 32),
+ (16, 32),
+ (32, 32),
+ (256, 256),
+ (512, 512),
+ ] {
+ let mut abv = AlignedBufferVec::<GpuDummyComposed>::new(
+ BufferUsages::STORAGE,
+ NonZeroU64::new(item_align),
+ None,
+ );
+ assert_eq!(abv.aligned_size(), expected_aligned_size);
+ assert!(abv.is_empty());
+ abv.push(GpuDummyComposed::default());
+ assert!(!abv.is_empty());
+ assert_eq!(abv.len(), 1);
+ }
+
+ for (item_align, expected_aligned_size) in [
+ (0, 544),
+ (4, 544),
+ (8, 544),
+ (16, 544),
+ (32, 544),
+ (256, 768),
+ (512, 1024),
+ ] {
+ let mut abv = AlignedBufferVec::<GpuDummyLarge>::new(
+ BufferUsages::STORAGE,
+ NonZeroU64::new(item_align),
+ None,
+ );
+ assert_eq!(abv.aligned_size(), expected_aligned_size);
+ assert!(abv.is_empty());
+ abv.push(GpuDummyLarge {
+ simple: Default::default(),
+ tag: 0,
+ large: [0.; 128],
+ });
+ assert!(!abv.is_empty());
+ assert_eq!(abv.len(), 1);
+ }
+ }
+
+ #[test]
+ fn habv_remove() {
+ let mut habv =
+ HybridAlignedBufferVec::new(BufferUsages::STORAGE, NonZeroU64::new(32).unwrap(), None);
+ assert!(habv.is_empty());
+ assert_eq!(habv.item_align, 32);
+
+ // +r -r
+ {
+ let r = habv.push(&42u32);
+ assert_eq!(r, 0..4);
+ assert!(!habv.is_empty());
+ assert_eq!(habv.values.len(), 4);
+ assert!(habv.free_rows.is_empty());
+
+ assert!(habv.remove(r));
+ assert!(habv.is_empty());
+ assert!(habv.values.is_empty());
+ assert!(habv.free_rows.is_empty());
+ }
+
+ // +r0 +r1 +r2 -r0 -r0 -r1 -r2
+ {
+ let r0 = habv.push(&42u32);
+ let r1 = habv.push(&84u32);
+ let r2 = habv.push(&84u32);
+ assert_eq!(r0, 0..4);
+ assert_eq!(r1, 32..36);
+ assert_eq!(r2, 64..68);
+ assert!(!habv.is_empty());
+ assert_eq!(habv.values.len(), 68);
+ assert!(habv.free_rows.is_empty());
+
+ assert!(habv.remove(r0.clone()));
+ assert!(!habv.is_empty());
+ assert_eq!(habv.values.len(), 68);
+ assert_eq!(habv.free_rows.len(), 1);
+ assert_eq!(habv.free_rows[0], FreeRow(0..1));
+
+ // dupe; no-op
+ assert!(!habv.remove(r0));
+
+ assert!(habv.remove(r1.clone()));
+ assert!(!habv.is_empty());
+ assert_eq!(habv.values.len(), 68);
+ assert_eq!(habv.free_rows.len(), 1); // merged!
+ assert_eq!(habv.free_rows[0], FreeRow(0..2));
+
+ assert!(habv.remove(r2));
+ assert!(habv.is_empty());
+ assert_eq!(habv.values.len(), 0);
+ assert!(habv.free_rows.is_empty());
+ }
+
+ // +r0 +r1 +r2 -r1 -r0 -r2
+ {
+ let r0 = habv.push(&42u32);
+ let r1 = habv.push(&84u32);
+ let r2 = habv.push(&84u32);
+ assert_eq!(r0, 0..4);
+ assert_eq!(r1, 32..36);
+ assert_eq!(r2, 64..68);
+ assert!(!habv.is_empty());
+ assert_eq!(habv.values.len(), 68);
+ assert!(habv.free_rows.is_empty());
+
+ assert!(habv.remove(r1.clone()));
+ assert!(!habv.is_empty());
+ assert_eq!(habv.values.len(), 68);
+ assert_eq!(habv.free_rows.len(), 1);
+ assert_eq!(habv.free_rows[0], FreeRow(1..2));
+
+ assert!(habv.remove(r0.clone()));
+ assert!(!habv.is_empty());
+ assert_eq!(habv.values.len(), 68);
+ assert_eq!(habv.free_rows.len(), 1); // merged!
+ assert_eq!(habv.free_rows[0], FreeRow(0..2));
+
+ assert!(habv.remove(r2));
+ assert!(habv.is_empty());
+ assert_eq!(habv.values.len(), 0);
+ assert!(habv.free_rows.is_empty());
+ }
+
+ // +r0 +r1 +r2 -r1 -r2 -r0
+ {
+ let r0 = habv.push(&42u32);
+ let r1 = habv.push(&84u32);
+ let r2 = habv.push(&84u32);
+ assert_eq!(r0, 0..4);
+ assert_eq!(r1, 32..36);
+ assert_eq!(r2, 64..68);
+ assert!(!habv.is_empty());
+ assert_eq!(habv.values.len(), 68);
+ assert!(habv.free_rows.is_empty());
+
+ assert!(habv.remove(r1.clone()));
+ assert!(!habv.is_empty());
+ assert_eq!(habv.values.len(), 68);
+ assert_eq!(habv.free_rows.len(), 1);
+ assert_eq!(habv.free_rows[0], FreeRow(1..2));
+
+ assert!(habv.remove(r2.clone()));
+ assert!(!habv.is_empty());
+ assert_eq!(habv.values.len(), 32); // can't recover exact alloc (4), only row-aligned size (32)
+ assert!(habv.free_rows.is_empty()); // merged!
+
+ assert!(habv.remove(r0));
+ assert!(habv.is_empty());
+ assert_eq!(habv.values.len(), 0);
+ assert!(habv.free_rows.is_empty());
+ }
+
+ // +r0 +r1 +r2 +r3 +r4 -r3 -r1 -r2 -r4 r0
+ {
+ let r0 = habv.push(&42u32);
+ let r1 = habv.push(&84u32);
+ let r2 = habv.push(&84u32);
+ let r3 = habv.push(&84u32);
+ let r4 = habv.push(&84u32);
+ assert_eq!(r0, 0..4);
+ assert_eq!(r1, 32..36);
+ assert_eq!(r2, 64..68);
+ assert_eq!(r3, 96..100);
+ assert_eq!(r4, 128..132);
+ assert!(!habv.is_empty());
+ assert_eq!(habv.values.len(), 132);
+ assert!(habv.free_rows.is_empty());
+
+ assert!(habv.remove(r3.clone()));
+ assert!(!habv.is_empty());
+ assert_eq!(habv.values.len(), 132);
+ assert_eq!(habv.free_rows.len(), 1);
+ assert_eq!(habv.free_rows[0], FreeRow(3..4));
+
+ assert!(habv.remove(r1.clone()));
+ assert!(!habv.is_empty());
+ assert_eq!(habv.values.len(), 132);
+ assert_eq!(habv.free_rows.len(), 2);
+ assert_eq!(habv.free_rows[0], FreeRow(1..2)); // sorted!
+ assert_eq!(habv.free_rows[1], FreeRow(3..4));
+
+ assert!(habv.remove(r2.clone()));
+ assert!(!habv.is_empty());
+ assert_eq!(habv.values.len(), 132);
+ assert_eq!(habv.free_rows.len(), 1); // merged!
+ assert_eq!(habv.free_rows[0], FreeRow(1..4)); // merged!
+
+ assert!(habv.remove(r4.clone()));
+ assert!(!habv.is_empty());
+ assert_eq!(habv.values.len(), 32); // can't recover exact alloc (4), only row-aligned size (32)
+ assert!(habv.free_rows.is_empty());
+
+ assert!(habv.remove(r0));
+ assert!(habv.is_empty());
+ assert_eq!(habv.values.len(), 0);
+ assert!(habv.free_rows.is_empty());
+ }
+ }
+}
+
+#[cfg(all(test, feature = "gpu_tests"))]
+mod gpu_tests {
+ use tests::*;
+
+ use super::*;
+ use crate::test_utils::MockRenderer;
+
+ #[test]
+ fn abv_write() {
+ let renderer = MockRenderer::new();
+ let device = renderer.device();
+ let queue = renderer.queue();
+
+ // Create a dummy CommandBuffer to force the write_buffer() call to have any
+ // effect.
+ let encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("test"),
+ });
+ let command_buffer = encoder.finish();
+
+ let item_align = device.limits().min_storage_buffer_offset_alignment as u64;
+ let mut abv = AlignedBufferVec::<GpuDummyComposed>::new(
+ BufferUsages::STORAGE | BufferUsages::MAP_READ,
+ NonZeroU64::new(item_align),
+ None,
+ );
+ let final_align = item_align.max(<GpuDummyComposed as ShaderSize>::SHADER_SIZE.get());
+ assert_eq!(abv.aligned_size(), final_align as usize);
+
+ const CAPACITY: usize = 42;
+
+ // Write buffer (CPU -> GPU)
+ abv.push(GpuDummyComposed {
+ tag: 1,
+ ..Default::default()
+ });
+ abv.push(GpuDummyComposed {
+ tag: 2,
+ ..Default::default()
+ });
+ abv.push(GpuDummyComposed {
+ tag: 3,
+ ..Default::default()
+ });
+ assert!(abv.reserve(CAPACITY, &device));
+ assert!(!abv.write_buffer(&device, &queue));
+ // need a submit() for write_buffer() to be processed
+ queue.submit([command_buffer]);
+ let (tx, rx) = futures::channel::oneshot::channel();
+ queue.on_submitted_work_done(move || {
+ tx.send(()).unwrap();
+ });
+ let _ = device.poll(wgpu::PollType::Wait {
+ submission_index: None,
+ timeout: None,
+ });
+ let _ = futures::executor::block_on(rx);
+ println!("Buffer written");
+
+ // Read back (GPU -> CPU)
+ let buffer = abv.buffer();
+ let buffer = buffer.as_ref().expect("Buffer was not allocated");
+ let buffer = buffer.slice(..);
+ let (tx, rx) = futures::channel::oneshot::channel();
+ buffer.map_async(wgpu::MapMode::Read, move |result| {
+ tx.send(result).unwrap();
+ });
+ let _ = device.poll(wgpu::PollType::Wait {
+ submission_index: None,
+ timeout: None,
+ });
+ let _result = futures::executor::block_on(rx);
+ let view = buffer
+ .get_mapped_range()
+ .expect("Buffer must be mapped for reading");
+
+ // Validate content
+ assert_eq!(view.len(), final_align as usize * CAPACITY);
+ for i in 0..3 {
+ let offset = i * final_align as usize;
+ let dummy_composed: &[GpuDummyComposed] =
+ cast_slice(&view[offset..offset + std::mem::size_of::<GpuDummyComposed>()]);
+ assert_eq!(dummy_composed[0].tag, (i + 1) as u32);
+ }
+ }
+}
diff --git a/vendor/bevy_hanabi/src/render/batch.rs b/vendor/bevy_hanabi/src/render/batch.rs
new file mode 100644
index 00000000..09e7557b
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/batch.rs
@@ -0,0 +1,898 @@
+use std::{fmt::Debug, num::NonZeroU32};
+
+use bevy::{
+ ecs::entity::EntityHashMap,
+ prelude::*,
+ render::{
+ render_resource::{Buffer, BufferVec, CachedComputePipelineId},
+ renderer::{RenderDevice, RenderQueue},
+ sync_world::MainEntity,
+ },
+};
+use fixedbitset::FixedBitSet;
+use wgpu::BufferUsages;
+
+use super::{
+ effect_cache::EffectSlice,
+ event::{CachedChildInfo, CachedEffectEvents},
+ BufferBindingSource, ExtractedEffectMesh, LayoutFlags, PropertyBindGroupKey,
+};
+use crate::{
+ render::{
+ aligned_buffer_vec::AlignedBufferVec, buffer_table::BufferTableId, effect_cache::SlabId,
+ ExtractedEffect, ExtractedSpawner, GpuBatchInfo, GpuSpawnerParams,
+ },
+ AlphaMode, EffectAsset, ParticleLayout, TextureLayout,
+};
+
+/// Info about particle spawning for an entire batch of effects.
+#[derive(Debug, Clone, Copy)]
+pub(crate) enum BatchSpawnInfo {
+ /// Spawn a number of particles uploaded from CPU each frame.
+ CpuSpawner {
+ /// Total number of particles to spawn for the batch. This is only used
+ /// to calculate the number of compute workgroups to dispatch. This is
+ /// the sum of all spawn counts for all effects in the batch.
+ total_spawn_count: u32,
+ },
+
+ /// Spawn a number of particles calculated on GPU from "spawn events", which
+ /// generally emitted by another effect.
+ GpuSpawner {
+ /// Index into the init indirect dispatch buffer of the
+ /// [`GpuDispatchIndirect`] instance for this batch.
+ ///
+ /// [`GpuDispatchIndirect`]: super::GpuDispatchIndirect
+ init_indirect_dispatch_index: u32,
+ /// Index of the [`EventBuffer`] where the GPU spawn events consumed by
+ /// this batch are stored.
+ ///
+ /// [`EventBuffer`]: super::event::EventBuffer
+ #[allow(dead_code)]
+ event_buffer_index: u32,
+ },
+}
+
+impl BatchSpawnInfo {
+ /// Check if this batch uses CPU-based spawning.
+ ///
+ /// # Returns
+ ///
+ /// Returns `true` if this instance is a `BatchSpawnInfo::CpuSpawner`.
+ #[inline]
+ #[must_use]
+ pub fn is_cpu(&self) -> bool {
+ matches!(self, Self::CpuSpawner { .. })
+ }
+
+ /// Check if this batch uses GPU-based spawning.
+ ///
+ /// # Returns
+ ///
+ /// Returns `true` if this instance is a `BatchSpawnInfo::GpuSpawner`.
+ #[inline]
+ #[must_use]
+ #[allow(dead_code)]
+ pub fn is_gpu(&self) -> bool {
+ matches!(self, Self::GpuSpawner { .. })
+ }
+
+ /// Retrieve the CPU spawn count, if this batch is CPU-based.
+ ///
+ /// # Returns
+ ///
+ /// Returns `Some(count)` with the total spawn count if this instance is a
+ /// `BatchSpawnInfo::CpuSpawner`. Otherwise returns `None`.
+ #[inline]
+ #[must_use]
+ #[allow(dead_code)]
+ pub fn as_cpu(&self) -> Option<&u32> {
+ if let Self::CpuSpawner { total_spawn_count } = self {
+ Some(total_spawn_count)
+ } else {
+ None
+ }
+ }
+
+ /// Retrieve the CPU spawn count or a default value.
+ ///
+ /// This variant is used as a shortcut to
+ /// `.as_cpu().unwrap_or(<unspecified>)` when filling out GPU buffers,
+ /// where we need a value whatever the case, but will ignore it if GPU
+ /// based.
+ ///
+ /// # Returns
+ ///
+ /// Returns the total spawn count if this instance is a
+ /// `BatchSpawnInfo::CpuSpawner`. Otherwise returns an unspecified value,
+ /// which should be ignored.
+ #[inline]
+ #[must_use]
+ #[allow(unused)]
+ pub fn cpu_spawn_count(&self) -> u32 {
+ if let Self::CpuSpawner { total_spawn_count } = self {
+ *total_spawn_count
+ } else {
+ u32::MAX
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy)]
+pub(crate) struct BatchEffectData {
+ /// Main [`Entity`] this effect instance was extracted from.
+ pub entity: u32,
+ /// Offset into the GPU buffer where the particles for this effect instance
+ /// are located. This is uploaded to GPU as [`GpuBatchInfo::base_particle`].
+ pub slab_offset: u32,
+ pub draw_indirect_buffer_row_index: BufferTableId,
+ pub metadata_table_id: BufferTableId,
+ pub sort_fill_indirect_dispatch_index: Option<u32>,
+ pub sort_indirect_dispatch_index: Option<u32>,
+ /// Offset in bytes of the [`GpuBatchInfo`] into the
+ /// [`Batcher::batch_info_buffer`], which contains the location of the
+ /// particles to render for this effect instance. Ready for bind group
+ /// dynamic offset usage.
+ pub render_batch_info_offset: u32,
+}
+
+/// Batch of effects dispatched and rendered together.
+#[derive(Debug, Clone)]
+pub(crate) struct EffectBatch {
+ /// ID of the [`GpuBatchInfo`] in the global shared array for this batch.
+ pub batch_info_id: u32,
+ /// Handle of the underlying effect asset describing the effect. The batch
+ /// only contains effect instances of the same asset.
+ pub handle: Handle<EffectAsset>,
+ /// Effect instance capacity, in number of particles.
+ pub capacity: u32,
+ /// ID of the particle slab in the [`EffectBuffer`] where all the batched
+ /// effects are stored.
+ ///
+ /// [`EffectBuffer`]: super::effect_cache::EffectBuffer
+ pub slab_id: SlabId,
+ /// Spawn info for this batch
+ pub spawn_info: BatchSpawnInfo,
+ /// Specialized init and update compute pipelines.
+ pub init_and_update_pipeline_ids: InitAndUpdatePipelineIds,
+ /// Configured shader used for the particle rendering of this group.
+ /// Note that we don't need to keep the init/update shaders alive because
+ /// their pipeline specialization is doing it via the specialization key.
+ pub render_shader: Handle<Shader>,
+ /// ID of the particle slab where the parent effect is stored, if any. If a
+ /// parent exists, its particle buffer is made available (read-only) for
+ /// a child effect to read its attributes.
+ #[allow(dead_code)]
+ pub parent_slab_id: Option<SlabId>,
+ pub parent_min_binding_size: Option<NonZeroU32>,
+ pub parent_binding_source: Option<BufferBindingSource>,
+ /// Event buffers of child effects, if any.
+ pub child_event_buffers: Vec<(Entity, BufferBindingSource)>,
+ /// Key for the "property" bind group (including textures).
+ pub property_key: PropertyBindGroupKey,
+ /// Index of the first [`GpuSpawnerParams`] entry of the effects in the
+ /// batch. Subsequent batched effects have their entries following linearly
+ /// after that one.
+ ///
+ /// [`GpuSpawnerParams`]: super::GpuSpawnerParams
+ pub spawner_base: u32,
+ /// Per-effect metadata used for draw and sorting. The number of elements
+ /// equals the number of effects batched together inside this batch.
+ pub effect_data: Vec<BatchEffectData>,
+ /// Particle layout shared by all batched effects and groups.
+ pub particle_layout: ParticleLayout,
+ /// Flags describing the render layout.
+ pub layout_flags: LayoutFlags,
+ /// Asset ID of the effect mesh to draw.
+ pub mesh: AssetId<Mesh>,
+ /// Texture layout.
+ pub texture_layout: TextureLayout,
+ /// Textures.
+ pub textures: Vec<Handle<Image>>,
+ /// Alpha mode.
+ pub alpha_mode: AlphaMode,
+ pub cached_effect_events: Option<CachedEffectEvents>,
+}
+
+impl EffectBatch {
+ /// Try to merge another batch into this one.
+ ///
+ /// # Returns
+ ///
+ /// Returns `Ok(())` if merged successfully. Returns `Err(input)` if the
+ /// input couldn't be merged.
+ #[allow(clippy::result_large_err)]
+ pub fn try_merge(&mut self, input: EffectBatch) -> Result<(), EffectBatch> {
+ // Keep merging conservative; parent/child/event-linked effects require
+ // additional per-effect bindings and aren't safe to merge yet.
+ if self.handle != input.handle
+ || self.slab_id != input.slab_id
+ || self.init_and_update_pipeline_ids != input.init_and_update_pipeline_ids
+ || self.mesh != input.mesh
+ || self.alpha_mode != input.alpha_mode
+ || self.texture_layout != input.texture_layout
+ || self.textures != input.textures
+ || self.property_key != input.property_key
+ || self.parent_slab_id != input.parent_slab_id
+ || self.parent_binding_source != input.parent_binding_source
+ || self.child_event_buffers != input.child_event_buffers
+ || self.cached_effect_events.is_some()
+ || input.cached_effect_events.is_some()
+ || !self.spawn_info.is_cpu()
+ || !input.spawn_info.is_cpu()
+ {
+ return Err(input);
+ }
+
+ self.effect_data.extend(input.effect_data);
+ if let (
+ BatchSpawnInfo::CpuSpawner {
+ total_spawn_count: self_count,
+ },
+ BatchSpawnInfo::CpuSpawner {
+ total_spawn_count: input_count,
+ },
+ ) = (&mut self.spawn_info, input.spawn_info)
+ {
+ *self_count += input_count;
+ }
+ Ok(())
+ }
+}
+
+#[derive(Debug, Clone, Copy)]
+pub(crate) struct EffectBatchIndex(pub u32);
+
+#[derive(Resource)]
+pub(crate) struct Batcher {
+ /// Effect batches in the order they were inserted by [`push()`], indexed by
+ /// the returned [`EffectBatchIndex`].
+ ///
+ /// [`push()`]: Self::push
+ batches: Vec<EffectBatch>,
+ /// Index of the dispatch queue used for indirect fill dispatch and
+ /// submitted to [`GpuBufferOperations`].
+ pub(super) fill_dispatch_queue_index: Option<u32>,
+ /// Index of the queue which copies post-update alive counts into the prefix
+ /// sum buffer before the ribbon sort prefix sum pass.
+ pub(super) sort_fill_prefix_sum_queue_index: Option<u32>,
+ /// Index of the dispatch queue used for indirect fill dispatch of the sort
+ /// pass, and submitted to [`GpuBufferOperations`].
+ pub(super) sort_dispatch_queue_index: Option<u32>,
+ /// Global shared GPU buffer storing the various `BatchInfo` structs for the
+ /// active batches. This is dynamically updated each frame based on current
+ /// batching, with one entry per batch (= one entry per dispatch/draw).
+ batch_info_buffer: AlignedBufferVec<GpuBatchInfo>,
+ /// Debug: was begin_batch() called without end_batch()?
+ is_batch_open: bool,
+ /// Buffer containing the prefix sums for all batches.
+ prefix_sum_buffer: BufferVec<u32>,
+ /// Current running prefix sum counter of CPU values passed to
+ /// [`Self::push()`], and used to initialize the prefix sum of each batch
+ /// for the next init pass.
+ cpu_prefix_sum_value: u32,
+}
+
+impl FromWorld for Batcher {
+ fn from_world(world: &mut World) -> Self {
+ let device = world.resource::<RenderDevice>();
+ let item_align =
+ NonZeroU32::new(device.limits().min_storage_buffer_offset_alignment).unwrap();
+ let batch_info_buffer = AlignedBufferVec::new(
+ BufferUsages::STORAGE,
+ Some(item_align.into()),
+ Some("hanabi:buffer:batch_info".to_string()),
+ );
+ let mut prefix_sum_buffer = BufferVec::new(BufferUsages::STORAGE);
+ prefix_sum_buffer.set_label(Some("prefix_sum_buffer"));
+ Self {
+ batches: vec![],
+ fill_dispatch_queue_index: None,
+ sort_fill_prefix_sum_queue_index: None,
+ sort_dispatch_queue_index: None,
+ batch_info_buffer,
+ is_batch_open: false,
+ prefix_sum_buffer,
+ cpu_prefix_sum_value: 0,
+ }
+ }
+}
+
+impl Batcher {
+ #[inline]
+ pub fn batch_info_buffer(&self) -> Option<&Buffer> {
+ self.batch_info_buffer.buffer()
+ }
+
+ #[inline]
+ pub fn batch_info_buffer_aligned_size(&self) -> u32 {
+ self.batch_info_buffer.aligned_size() as u32
+ }
+
+ #[inline]
+ pub fn prefix_sum_buffer(&self) -> Option<&Buffer> {
+ self.prefix_sum_buffer.buffer()
+ }
+
+ pub fn clear(&mut self) {
+ self.batches.clear();
+ self.fill_dispatch_queue_index = None;
+ self.sort_fill_prefix_sum_queue_index = None;
+ self.sort_dispatch_queue_index = None;
+ self.prefix_sum_buffer.clear();
+ self.batch_info_buffer.clear();
+ }
+
+ /// Begin a new batch of effects.
+ fn begin_batch(&mut self, base_particle: u32, spawner_base: u32) -> u32 {
+ assert!(!self.is_batch_open, "Duplicate call to begin_batch()");
+
+ let prefix_sum_offset = self.prefix_sum_buffer.len() as u32;
+
+ let batch_info_base = self.batch_info_buffer.len() as u32;
+ let batch_info = GpuBatchInfo {
+ total_spawn_count: 0, // set in end_batch()
+ total_update_count: 0, // calculated on GPU
+ spawner_base,
+ base_particle,
+ prefix_sum_offset,
+ prefix_sum_count: u32::MAX, // invalid; set in end_batch()
+ };
+ trace!("batch info = {:?}", batch_info);
+ self.batch_info_buffer.push(batch_info);
+ self.is_batch_open = true;
+
+ batch_info_base
+ }
+
+ /// Add a single effect instance entry to the current batch prefix array.
+ fn add_effect_to_batch(&mut self, prefix_value: u32) {
+ assert!(
+ self.is_batch_open,
+ "Cannot add effect before calling begin_batch()"
+ );
+ self.prefix_sum_buffer.push(prefix_value);
+ }
+
+ /// Try to end the current batch, if any. Does nothing if no batch is
+ /// pending.
+ ///
+ /// # Returns
+ ///
+ /// Returns `true` if a batch was closed, or `false` otherwise.
+ pub fn try_end_batch(&mut self) -> bool {
+ if self.is_batch_open {
+ self.end_batch();
+ true
+ } else {
+ false
+ }
+ }
+
+ /// End the current batch.
+ ///
+ /// # Panics
+ ///
+ /// Panics if no batch is pending.
+ fn end_batch(&mut self) {
+ assert!(
+ self.is_batch_open,
+ "Call to end_batch() without begin_batch()"
+ );
+
+ // Get the open batch
+ let batch = self
+ .batch_info_buffer
+ .last_mut()
+ .expect("No open batch. Missing begin_batch() call?");
+
+ // Record prefix sum
+ let end = self.prefix_sum_buffer.len() as u32;
+ assert!(end >= batch.prefix_sum_offset);
+ batch.prefix_sum_count = end - batch.prefix_sum_offset;
+
+ // Record total number of CPU spawn, to clamp the number of GPU threads
+ batch.total_spawn_count = self.cpu_prefix_sum_value;
+
+ self.is_batch_open = false;
+ }
+
+ /// Insert a new batch into the collection.
+ ///
+ /// Try to merge the `effect_batch` into the last pushed batch, or create a
+ /// new standalone batch if not possible (incompatible effects, or first
+ /// one). The `instance_spawn_count` is the number of particles to spawn
+ /// from CPU, and is used to initialize the prefix sum buffer, for use by
+ /// the init pass (CPU spawn). The update pass' prefix sum is recomputed
+ /// inside the same buffer between the init and update passes, directly on
+ /// GPU.
+ ///
+ /// # Returns
+ ///
+ /// This returns the index of the new batch if the inserted one couldn't be
+ /// merged with a previous batch. Otherwise the input batch was merged with
+ /// an existing one, and therefore share its index; in that case `None` is
+ /// returned.
+ ///
+ /// Also returns the index of that effect batch in the prefix sum buffer.
+ pub fn push(
+ &mut self,
+ effect_batch: EffectBatch,
+ instance_spawn_count: u32,
+ ) -> (Option<EffectBatchIndex>, u32) {
+ assert!(effect_batch.effect_data.len() == 1);
+
+ let prefix_sum_index = self.prefix_sum_buffer.len() as u32;
+
+ let effect_batch = if let Some(batch) = self.batches.last_mut() {
+ let Err(effect_batch) = batch.try_merge(effect_batch) else {
+ // Successfully batched
+ self.add_effect_to_batch(self.cpu_prefix_sum_value);
+ self.cpu_prefix_sum_value += instance_spawn_count;
+ return (None, prefix_sum_index);
+ };
+ // Failed to merge incompatible batches
+ effect_batch
+ } else {
+ // No prior batch to merge with
+ effect_batch
+ };
+
+ // Close the previous batch if any
+ self.try_end_batch();
+
+ // Start a new batch
+ let index = self.batches.len() as u32;
+ let base_particle = effect_batch.effect_data[0].slab_offset;
+ self.batches.push(effect_batch);
+
+ // Begin a new batch with this new effect instance
+ let batch_info_id = self.begin_batch(base_particle, self.last().unwrap().spawner_base);
+ self.last_mut().unwrap().batch_info_id = batch_info_id;
+ self.cpu_prefix_sum_value = 0;
+
+ self.add_effect_to_batch(self.cpu_prefix_sum_value);
+ self.cpu_prefix_sum_value += instance_spawn_count;
+
+ (Some(EffectBatchIndex(index)), prefix_sum_index)
+ }
+
+ #[inline]
+ #[must_use]
+ pub fn last(&self) -> Option<&EffectBatch> {
+ self.batches.last()
+ }
+
+ #[inline]
+ #[must_use]
+ pub fn last_mut(&mut self) -> Option<&mut EffectBatch> {
+ self.batches.last_mut()
+ }
+
+ pub fn len(&self) -> usize {
+ self.batches.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.batches.is_empty()
+ }
+
+ /// Get an iterator over the sorted sequence of effect batches.
+ #[inline]
+ pub fn iter(&self) -> &[EffectBatch] {
+ &self.batches
+ }
+
+ pub fn get(&self, index: EffectBatchIndex) -> Option<&EffectBatch> {
+ if index.0 < self.batches.len() as u32 {
+ Some(&self.batches[index.0 as usize])
+ } else {
+ None
+ }
+ }
+
+ /// Allocate the render batches.
+ ///
+ /// Allocate one render batch info entry per effect instance after compute
+ /// batching is finalized, to avoid nesting begin_batch()/end_batch() calls.
+ /// Currently there's no rendering batching, so we allocate one GpuBatchInfo
+ /// per effect instance.
+ pub fn allocate_render_batches(&mut self) {
+ let batch_info_aligned_size = self.batch_info_buffer_aligned_size();
+ let num_batches = self.batches.len();
+ for batch_index in 0..num_batches {
+ let num_effects = self.batches[batch_index].effect_data.len();
+ for effect_index in 0..num_effects {
+ let effect_batch = &self.batches[batch_index];
+ let effect_data = &effect_batch.effect_data[effect_index];
+ if effect_data.render_batch_info_offset != u32::MAX {
+ continue;
+ }
+ let spawner_index = effect_batch.spawner_base + effect_index as u32;
+
+ let base_particle = effect_data.slab_offset;
+ let render_batch_info_id = self.begin_batch(base_particle, spawner_index);
+ // Render-only batch infos are not processed by vfx_prefix_sum; keep
+ // a relative offset of 0 for the single effect in that batch.
+ self.add_effect_to_batch(0);
+ self.end_batch();
+ let render_batch_info_offset = render_batch_info_id
+ .checked_mul(batch_info_aligned_size)
+ .unwrap();
+
+ self.batches[batch_index].effect_data[effect_index].render_batch_info_offset =
+ render_batch_info_offset;
+ }
+ }
+ }
+
+ #[inline]
+ pub fn write_batch_info_buffer(&mut self, device: &RenderDevice, queue: &RenderQueue) -> bool {
+ self.batch_info_buffer.write_buffer(device, queue)
+ }
+
+ pub fn write_prefix_sum_buffer(&mut self, device: &RenderDevice, queue: &RenderQueue) -> bool {
+ let mut reallocated = false;
+ let cpu_len = self.prefix_sum_buffer.len();
+ if cpu_len > 0 {
+ let gpu_capacity = self.prefix_sum_buffer.capacity();
+ if cpu_len > gpu_capacity {
+ self.prefix_sum_buffer.reserve(cpu_len, device);
+ reallocated = true;
+ }
+ assert!(self.prefix_sum_buffer.buffer().is_some());
+ self.prefix_sum_buffer.write_buffer(device, queue);
+ }
+ reallocated
+ }
+}
+
+/// Information that the [`EffectSorter`] maintains in order to sort each
+/// effect into the proper order.
+pub(crate) struct EffectToBeSorted {
+ /// The render-world entity of the effect.
+ pub(crate) entity: Entity,
+ /// The index of the buffer that the indirect indices for this effect are
+ /// stored in.
+ pub(crate) slab_id: SlabId,
+ /// The offset within the buffer described above at which the indirect
+ /// indices for this effect start.
+ ///
+ /// This is in elements, not bytes.
+ pub(crate) base_instance: u32,
+}
+
+/// The key that we sort effects by for optimum batching.
+#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
+struct EffectSortKey {
+ /// The level in the dependency graph.
+ ///
+ /// Parents always have lower levels than their children.
+ level: u32,
+ /// The index of the buffer that the indirect indices for this effect are
+ /// stored in.
+ slab_id: SlabId,
+ /// The offset within the buffer described above at which the indirect
+ /// indices for this effect start.
+ base_instance: u32,
+}
+
+/// Sorts effects into the proper order for batching.
+///
+/// This places parents before children and also tries to place effects in the
+/// same slab together.
+pub(crate) struct EffectSorter {
+ /// Information that we keep about each effect.
+ pub effects: Vec<EffectToBeSorted>,
+ /// A mapping from a child to its parent, if it has one.
+ pub child_to_parent: EntityHashMap<Entity>,
+}
+
+impl EffectSorter {
+ /// Creates a new [`EffectSorter`].
+ pub fn new() -> EffectSorter {
+ EffectSorter {
+ effects: vec![],
+ child_to_parent: default(),
+ }
+ }
+
+ /// Insert an effect to be sorted.
+ pub fn insert(
+ &mut self,
+ entity: Entity,
+ slab_id: SlabId,
+ base_instance: u32,
+ parent: Option<Entity>,
+ ) {
+ self.effects.push(EffectToBeSorted {
+ entity,
+ slab_id,
+ base_instance,
+ });
+ if let Some(parent) = parent {
+ self.child_to_parent.insert(entity, parent);
+ }
+ }
+
+ /// Sorts all the effects into the optimal order for batching.
+ pub fn sort(&mut self) {
+ // trace!("Sorting {} effects...", self.effects.len());
+ // for effect in &self.effects {
+ // trace!(
+ // "+ {}: slab={:?} base_instance={:?}",
+ // effect.entity,
+ // effect.slab_id,
+ // effect.base_instance
+ // );
+ // }
+ // trace!("child->parent:");
+ // for (k, v) in &self.child_to_parent {
+ // trace!("+ c[{k}] -> p[{v}]");
+ // }
+
+ // First, create a map of entity to index.
+ let mut entity_to_index = EntityHashMap::default();
+ for (index, effect) in self.effects.iter().enumerate() {
+ entity_to_index.insert(effect.entity, index);
+ }
+
+ // Next, create a map of children to their parents.
+ let mut children_to_parent: Vec<_> = (0..self.effects.len()).map(|_| vec![]).collect();
+ for (kid, parent) in self.child_to_parent.iter() {
+ let (parent_index, kid_index) = (entity_to_index[parent], entity_to_index[kid]);
+ children_to_parent[kid_index].push(parent_index);
+ }
+
+ // Now topologically sort the graph. Create an ordering that places
+ // children before parents.
+ // https://en.wikipedia.org/wiki/Topological_sorting#Depth-first_search
+ let mut ordering = vec![0; self.effects.len()];
+ let mut visiting = FixedBitSet::with_capacity(self.effects.len());
+ let mut visited = FixedBitSet::with_capacity(self.effects.len());
+ while let Some(effect_index) = visited.zeroes().next() {
+ visit(
+ &mut ordering,
+ &mut visiting,
+ &mut visited,
+ &children_to_parent,
+ effect_index,
+ );
+ }
+
+ // Compute levels.
+ let mut levels = vec![0; self.effects.len()];
+ for effect_index in ordering.into_iter().rev() {
+ let level = levels[effect_index];
+ for &parent in &children_to_parent[effect_index] {
+ levels[parent] = levels[parent].max(level + 1);
+ }
+ }
+
+ // Now sort the result.
+ self.effects.sort_unstable_by_key(|effect| EffectSortKey {
+ level: levels[entity_to_index[&effect.entity]],
+ slab_id: effect.slab_id,
+ base_instance: effect.base_instance,
+ });
+
+ // Helper function for topologically sorting the effect dependency graph
+ fn visit(
+ ordering: &mut Vec<usize>,
+ visiting: &mut FixedBitSet,
+ visited: &mut FixedBitSet,
+ children_to_parent: &[Vec<usize>],
+ effect_index: usize,
+ ) {
+ if visited.contains(effect_index) {
+ return;
+ }
+ debug_assert!(
+ !visiting.contains(effect_index),
+ "Parent-child effect relation contains a cycle"
+ );
+
+ visiting.insert(effect_index);
+
+ for &parent in &children_to_parent[effect_index] {
+ visit(ordering, visiting, visited, children_to_parent, parent);
+ }
+
+ visited.insert(effect_index);
+ ordering.push(effect_index);
+ }
+ }
+
+ /// Iterate over the effects. This only iterates in sorted order if
+ /// [`Self::sort()`] was called beforehand.
+ #[inline]
+ pub fn iter(&self) -> impl Iterator<Item = Entity> + use<'_> {
+ self.effects.iter().map(|e| e.entity)
+ }
+}
+
+/// Single effect batch to drive rendering.
+///
+/// This component is spawned into the render world during the prepare phase
+/// ([`prepare_effects()`]), once per effect batch per group. In turns it
+/// references an [`EffectBatch`] component containing all the shared data for
+/// all the groups of the effect.
+#[derive(Debug, Component)]
+pub(crate) struct EffectDrawBatch {
+ /// Index of the [`EffectBatch`] in the [`SortedEffectBatches`] this draw
+ /// batch is part of.
+ ///
+ /// Note: currently there's a 1:1 mapping between effect batch and draw
+ /// batch.
+ pub effect_batch_index: EffectBatchIndex,
+ /// Position of the emitter so we can compute distance to camera.
+ pub translation: Vec3,
+ /// The main-world entity that contains this effect.
+ #[allow(dead_code)]
+ pub main_entity: MainEntity,
+}
+
+impl EffectBatch {
+ /// Create a new batch from a single input.
+ pub fn from_input(
+ main_entity: Entity,
+ extracted_effect: &ExtractedEffect,
+ extracted_spawner: &ExtractedSpawner,
+ cached_mesh: &ExtractedEffectMesh,
+ cached_effect_events: Option<&CachedEffectEvents>,
+ cached_child_info: Option<&CachedChildInfo>,
+ spawner_index: u32,
+ input: &mut BatchInput,
+ draw_indirect_buffer_row_index: BufferTableId,
+ metadata_table_id: BufferTableId,
+ property_key: PropertyBindGroupKey,
+ ) -> EffectBatch {
+ assert_eq!(
+ input.event_buffer_index.is_some(),
+ input.init_indirect_dispatch_index.is_some()
+ );
+
+ let spawn_info = if let Some(event_buffer_index) = input.event_buffer_index {
+ BatchSpawnInfo::GpuSpawner {
+ init_indirect_dispatch_index: input.init_indirect_dispatch_index.unwrap(),
+ event_buffer_index,
+ }
+ } else {
+ BatchSpawnInfo::CpuSpawner {
+ total_spawn_count: extracted_spawner.spawn_count,
+ }
+ };
+
+ EffectBatch {
+ batch_info_id: u32::MAX, // allocated later once the batch is completed
+ handle: extracted_effect.handle.clone(),
+ capacity: extracted_effect.capacity,
+ slab_id: input.effect_slice.slab_id,
+ spawn_info,
+ init_and_update_pipeline_ids: input.init_and_update_pipeline_ids,
+ render_shader: extracted_effect.effect_shaders.render.clone(),
+ parent_slab_id: input.parent_slab_id,
+ parent_min_binding_size: cached_child_info
+ .map(|cci| cci.parent_particle_layout.min_binding_size32()),
+ parent_binding_source: cached_child_info
+ .map(|cci| cci.parent_buffer_binding_source.clone()),
+ child_event_buffers: input.child_effects.clone(),
+ property_key,
+ spawner_base: spawner_index,
+ effect_data: vec![BatchEffectData {
+ entity: main_entity.index_u32(),
+ slab_offset: input.effect_slice.slice.start,
+ draw_indirect_buffer_row_index,
+ metadata_table_id,
+ sort_fill_indirect_dispatch_index: None,
+ sort_indirect_dispatch_index: None,
+ render_batch_info_offset: u32::MAX,
+ }],
+ particle_layout: input.effect_slice.particle_layout.clone(),
+ layout_flags: extracted_effect.layout_flags,
+ mesh: cached_mesh.mesh,
+ texture_layout: extracted_effect.texture_layout.clone(),
+ textures: extracted_effect.textures.clone(),
+ alpha_mode: extracted_effect.alpha_mode,
+ cached_effect_events: cached_effect_events.cloned(),
+ }
+ }
+}
+
+/// Effect batching input, obtained from extracted effects.
+#[derive(Debug, Component)]
+pub(crate) struct BatchInput {
+ /// Effect slices.
+ pub effect_slice: EffectSlice,
+ /// Compute pipeline IDs of the specialized and cached pipelines.
+ pub init_and_update_pipeline_ids: InitAndUpdatePipelineIds,
+ /// ID of the particle slab of the parent effect, if any.
+ pub parent_slab_id: Option<SlabId>,
+ /// Index of the event buffer, if this effect consumes GPU spawn events.
+ pub event_buffer_index: Option<u32>,
+ /// Child effects, if any.
+ pub child_effects: Vec<(Entity, BufferBindingSource)>,
+ /// [`GpuSpawnerParams`] for this instance.
+ pub gpu_spawner_params: GpuSpawnerParams,
+ /// Index of the init indirect dispatch struct, if any.
+ // FIXME - Contains a single effect's data; should handle multiple ones.
+ pub init_indirect_dispatch_index: Option<u32>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub(crate) struct InitAndUpdatePipelineIds {
+ pub init: CachedComputePipelineId,
+ pub update: CachedComputePipelineId,
+}
+
+#[cfg(test)]
+mod tests {
+ use bevy::ecs::entity::Entity;
+
+ use super::*;
+
+ fn insert_entry(
+ sorter: &mut EffectSorter,
+ entity: Entity,
+ slab_id: SlabId,
+ base_instance: u32,
+ parent: Option<Entity>,
+ ) {
+ sorter.effects.push(EffectToBeSorted {
+ entity,
+ base_instance,
+ slab_id,
+ });
+ if let Some(parent) = parent {
+ sorter.child_to_parent.insert(entity, parent);
+ }
+ }
+
+ #[test]
+ fn toposort_batches() {
+ let mut sorter = EffectSorter::new();
+
+ // Some "parent" effect
+ let e1 = Entity::from_raw_u32(1).unwrap();
+ insert_entry(&mut sorter, e1, SlabId::new(42), 0, None);
+ assert_eq!(sorter.effects.len(), 1);
+ assert_eq!(sorter.effects[0].entity, e1);
+ assert!(sorter.child_to_parent.is_empty());
+
+ // Some "child" effect in a different buffer
+ let e2 = Entity::from_raw_u32(2).unwrap();
+ insert_entry(&mut sorter, e2, SlabId::new(5), 30, Some(e1));
+ assert_eq!(sorter.effects.len(), 2);
+ assert_eq!(sorter.effects[0].entity, e1);
+ assert_eq!(sorter.effects[1].entity, e2);
+ assert_eq!(sorter.child_to_parent.len(), 1);
+ assert_eq!(sorter.child_to_parent[&e2], e1);
+
+ sorter.sort();
+ assert_eq!(sorter.effects.len(), 2);
+ assert_eq!(sorter.effects[0].entity, e2); // child first
+ assert_eq!(sorter.effects[1].entity, e1); // parent after
+ assert_eq!(sorter.child_to_parent.len(), 1); // unchanged
+ assert_eq!(sorter.child_to_parent[&e2], e1); // unchanged
+
+ // Some "child" effect in the same buffer as its parent
+ let e3 = Entity::from_raw_u32(3).unwrap();
+ insert_entry(&mut sorter, e3, SlabId::new(42), 20, Some(e1));
+ assert_eq!(sorter.effects.len(), 3);
+ assert_eq!(sorter.effects[0].entity, e2); // from previous sort
+ assert_eq!(sorter.effects[1].entity, e1); // from previous sort
+ assert_eq!(sorter.effects[2].entity, e3); // simply appended
+ assert_eq!(sorter.child_to_parent.len(), 2);
+ assert_eq!(sorter.child_to_parent[&e2], e1);
+ assert_eq!(sorter.child_to_parent[&e3], e1);
+
+ sorter.sort();
+ assert_eq!(sorter.effects.len(), 3);
+ assert_eq!(sorter.effects[0].entity, e2); // child first
+ assert_eq!(sorter.effects[1].entity, e3); // other child next (in same buffer as parent)
+ assert_eq!(sorter.effects[2].entity, e1); // finally, parent
+ assert_eq!(sorter.child_to_parent.len(), 2);
+ assert_eq!(sorter.child_to_parent[&e2], e1);
+ assert_eq!(sorter.child_to_parent[&e3], e1);
+ }
+}
diff --git a/vendor/bevy_hanabi/src/render/buffer_table.rs b/vendor/bevy_hanabi/src/render/buffer_table.rs
new file mode 100644
index 00000000..0bff9adb
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/buffer_table.rs
@@ -0,0 +1,1566 @@
+use std::{
+ borrow::Cow,
+ num::{NonZeroU32, NonZeroU64},
+ ops::Range,
+};
+
+use bevy::{
+ log::trace,
+ render::{
+ render_resource::{
+ Buffer, BufferAddress, BufferDescriptor, BufferUsages, CommandEncoder, ShaderSize,
+ ShaderType,
+ },
+ renderer::{RenderDevice, RenderQueue},
+ },
+};
+use bytemuck::{cast_slice, Pod};
+
+/// Round a range start down to a given alignment, and return the new range and
+/// the start offset inside the new range of the old range.
+fn round_range_start_down(range: Range<u64>, align: u64) -> (Range<u64>, u64) {
+ assert!(align > 0);
+ let delta = align - 1;
+ if range.start >= delta {
+ // Snap range start to previous multiple of align
+ let old_start = range.start;
+ let new_start = (range.start - delta).next_multiple_of(align);
+ let offset = old_start - new_start;
+ (new_start..range.end, offset)
+ } else {
+ // Snap range start to 0
+ (0..range.end, range.start)
+ }
+}
+
+/// Index of a row in a [`BufferTable`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct BufferTableId(pub(crate) u32); // TEMP: pub(crate)
+
+impl BufferTableId {
+ /// An invalid value, often used as placeholder.
+ pub const INVALID: BufferTableId = BufferTableId(u32::MAX);
+
+ /// Check if the current ID is valid, that is, is different from
+ /// [`INVALID`].
+ ///
+ /// [`INVALID`]: Self::INVALID
+ #[inline]
+ pub fn is_valid(&self) -> bool {
+ *self != Self::INVALID
+ }
+
+ /// Compute a new buffer table ID by offseting an existing one by `count`
+ /// rows.
+ #[inline]
+ #[allow(dead_code)]
+ pub fn offset(&self, count: u32) -> BufferTableId {
+ debug_assert!(self.is_valid());
+ BufferTableId(self.0 + count)
+ }
+}
+
+impl Default for BufferTableId {
+ fn default() -> Self {
+ Self::INVALID
+ }
+}
+
+#[derive(Debug)]
+struct AllocatedBuffer {
+ /// Currently allocated buffer, of size equal to `size`.
+ buffer: Buffer,
+ /// Size of the currently allocated buffer, in number of rows.
+ count: u32,
+ /// Previously allocated buffer if any, cached until the next buffer write
+ /// so that old data can be copied into the newly-allocated buffer.
+ old_buffer: Option<Buffer>,
+ /// Size of the old buffer if any, in number of rows.
+ old_count: u32,
+}
+
+impl AllocatedBuffer {
+ /// Get the number of rows of the currently allocated GPU buffer.
+ ///
+ /// On capacity grow, the count is valid until the next buffer swap.
+ pub fn allocated_count(&self) -> u32 {
+ if self.old_buffer.is_some() {
+ self.old_count
+ } else {
+ self.count
+ }
+ }
+}
+
+/// GPU buffer holding a table with concurrent interleaved CPU/GPU access.
+///
+/// The buffer table data structure represents a GPU buffer holding a table made
+/// of individual rows. Each row of the table has the same layout (same size),
+/// and can be allocated (assigned to an existing index) or free (available for
+/// future allocation). The data structure manages a free list of rows, and copy
+/// of rows modified on CPU to the GPU without touching other rows. This ensures
+/// that existing rows in the GPU buffer can be accessed and modified by the GPU
+/// without being overwritten by the CPU and without the need for the CPU to
+/// read the data back from GPU into CPU memory.
+///
+/// The element type `T` needs to implement the following traits:
+/// - [`Pod`] to allow copy.
+/// - [`ShaderType`] because it needs to be mapped for a shader.
+/// - [`ShaderSize`] to ensure a fixed footprint, to allow packing multiple
+/// instances inside a single buffer. This therefore excludes any
+/// runtime-sized array.
+///
+/// This is similar to a [`BufferVec`] or [`AlignedBufferVec`], but unlike those
+/// data structures a buffer table preserves rows modified by the GPU without
+/// overwriting. This is useful when the buffer is also modified by GPU shaders,
+/// so neither the CPU side nor the GPU side have an up-to-date view of the
+/// entire table, and so the CPU cannot re-upload the entire table on changes.
+///
+/// # Usage
+///
+/// - During the [`RenderStage::Prepare`] stage, call
+/// [`clear_previous_frame_resizes()`] to clear any stale buffer from the
+/// previous frame. Then insert new rows with [`insert()`] and if you made
+/// changes call [`allocate_gpu()`] at the end to allocate any new buffer
+/// needed.
+/// - During the [`RenderStage::Render`] stage, call [`write_buffer()`] from a
+/// command encoder before using any row, to perform any buffer resize copy
+/// pending.
+///
+/// [`BufferVec`]: bevy::render::render_resource::BufferVec
+/// [`AlignedBufferVec`]: crate::render::aligned_buffer_vec::AlignedBufferVec
+#[derive(Debug)]
+pub struct BufferTable<T: Pod + ShaderSize> {
+ /// GPU buffer if already allocated, or `None` otherwise.
+ buffer: Option<AllocatedBuffer>,
+ /// GPU buffer usages.
+ buffer_usage: BufferUsages,
+ /// Optional GPU buffer name, for debugging.
+ label: Option<String>,
+ /// Size of a single buffer element, in bytes, in CPU memory (Rust layout).
+ item_size: usize,
+ /// Size of a single buffer element, in bytes, aligned to GPU memory
+ /// constraints.
+ aligned_size: usize,
+ /// Capacity of the buffer, in number of rows.
+ ///
+ /// This is the expected capacity, as requested by CPU side allocations and
+ /// deallocations. The GPU buffer might not have been resized yet to handle
+ /// it, so might be allocated with a different size.
+ capacity: u32,
+ /// Size of the "active" portion of the table, which includes allocated rows
+ /// and any row in the free list. All other rows in the
+ /// `active_size..capacity` range are implicitly unallocated.
+ active_count: u32,
+ /// Free list of rows available in the GPU buffer for a new allocation. This
+ /// only contains indices in the `0..active_size` range; all row indices in
+ /// `active_size..capacity` are assumed to be unallocated.
+ free_indices: Vec<u32>,
+ /// Pending values accumulated on CPU and not yet written to GPU, and their
+ /// rows.
+ pending_values: Vec<(u32, T)>,
+ /// Extra pending values accumulated on CPU like `pending_values`, but for
+ /// which there's not enough space in the current GPU buffer. Those values
+ /// are sorted in index order, occupying the range `buffer.size..`.
+ extra_pending_values: Vec<T>,
+}
+
+impl<T: Pod + ShaderSize> Default for BufferTable<T> {
+ fn default() -> Self {
+ let item_size = std::mem::size_of::<T>();
+ let aligned_size = <T as ShaderSize>::SHADER_SIZE.get() as usize;
+ assert!(aligned_size >= item_size);
+ Self {
+ buffer: None,
+ buffer_usage: BufferUsages::all(),
+ label: None,
+ item_size,
+ aligned_size,
+ capacity: 0,
+ active_count: 0,
+ free_indices: Vec::new(),
+ pending_values: Vec::new(),
+ extra_pending_values: Vec::new(),
+ }
+ }
+}
+
+impl<T: Pod + ShaderSize> BufferTable<T> {
+ /// Create a new collection.
+ ///
+ /// `item_align` is an optional additional alignment for items in the
+ /// collection. If greater than the natural alignment dictated by WGSL
+ /// rules, this extra alignment is enforced. Otherwise it's ignored (so you
+ /// can pass `None` to ignore). This is useful if for example you want to
+ /// bind individual rows or any subset of the table, to ensure each row is
+ /// aligned to the device constraints.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `buffer_usage` contains [`BufferUsages::UNIFORM`] and the
+ /// layout of the element type `T` does not meet the requirements of the
+ /// uniform address space, as tested by
+ /// [`ShaderType::assert_uniform_compat()`].
+ ///
+ /// [`BufferUsages::UNIFORM`]: bevy::render::render_resource::BufferUsages::UNIFORM
+ pub fn new(
+ buffer_usage: BufferUsages,
+ item_align: Option<NonZeroU64>,
+ label: Option<String>,
+ ) -> Self {
+ // GPU-aligned item size, compatible with WGSL rules
+ let item_size = <T as ShaderSize>::SHADER_SIZE.get() as usize;
+ // Extra manual alignment for device constraints
+ let aligned_size = if let Some(item_align) = item_align {
+ let item_align = item_align.get() as usize;
+ let aligned_size = item_size.next_multiple_of(item_align);
+ assert!(aligned_size >= item_size);
+ assert!(aligned_size.is_multiple_of(item_align));
+ aligned_size
+ } else {
+ item_size
+ };
+ trace!(
+ "BufferTable[\"{}\"]: item_size={} aligned_size={}",
+ label.as_ref().unwrap_or(&String::new()),
+ item_size,
+ aligned_size
+ );
+ if buffer_usage.contains(BufferUsages::UNIFORM) {
+ <T as ShaderType>::assert_uniform_compat();
+ }
+ Self {
+ // Need COPY_SRC and COPY_DST to copy from old to new buffer on resize
+ buffer_usage: buffer_usage | BufferUsages::COPY_SRC | BufferUsages::COPY_DST,
+ aligned_size,
+ label,
+ ..Default::default()
+ }
+ }
+
+ /// Get a safe buffer label for debug display.
+ ///
+ /// Falls back to an empty string if no label was specified.
+ pub fn safe_label(&self) -> Cow<'_, str> {
+ self.label
+ .as_ref()
+ .map(|s| Cow::Borrowed(&s[..]))
+ .unwrap_or(Cow::Borrowed(""))
+ }
+
+ /// Get a safe buffer name for debug display.
+ ///
+ /// Same as [`safe_label()`] but includes the buffer ID as well.
+ ///
+ /// [`safe_label()`]: self::BufferTable::safe_label
+ pub fn safe_name(&self) -> String {
+ let id = self
+ .buffer
+ .as_ref()
+ .map(|ab| {
+ let id: NonZeroU32 = ab.buffer.id().into();
+ id.get()
+ })
+ .unwrap_or(0);
+ format!("#{}:{}", id, self.safe_label())
+ }
+
+ /// Reference to the GPU buffer, if already allocated.
+ ///
+ /// This reference corresponds to the currently allocated GPU buffer, which
+ /// may not contain all data since the last [`insert()`] call, and could
+ /// become invalid if a new larger buffer needs to be allocated to store the
+ /// pending values inserted with [`insert()`].
+ ///
+ /// [`insert()]`: BufferTable::insert
+ #[inline]
+ pub fn buffer(&self) -> Option<&Buffer> {
+ self.buffer.as_ref().map(|ab| &ab.buffer)
+ }
+
+ /// Maximum number of rows the table can hold without reallocation.
+ ///
+ /// This is the maximum number of rows that can be added to the table
+ /// without forcing a new GPU buffer to be allocated and a copy from the old
+ /// to the new buffer.
+ ///
+ /// Note that this doesn't imply that no GPU buffer allocation will ever
+ /// occur; if a GPU buffer was never allocated, and there are pending
+ /// CPU rows to insert, then a new buffer will be allocated on next
+ /// update with this capacity.
+ #[inline]
+ #[allow(dead_code)]
+ pub fn capacity(&self) -> u32 {
+ self.capacity
+ }
+
+ /// Current number of rows in use in the table.
+ ///
+ /// Note that rows in use are not necessarily contiguous. There may be gaps
+ /// between used rows.
+ #[inline]
+ #[allow(dead_code)]
+ pub fn len(&self) -> u32 {
+ self.active_count - self.free_indices.len() as u32
+ }
+
+ /// Size of a single row in the table, in bytes, aligned to GPU constraints.
+ #[inline]
+ #[allow(dead_code)]
+ pub fn aligned_size(&self) -> usize {
+ self.aligned_size
+ }
+
+ /// Is the table empty?
+ #[inline]
+ #[allow(dead_code)]
+ pub fn is_empty(&self) -> bool {
+ self.active_count == 0
+ }
+
+ /// Clear all rows of the table without deallocating any existing GPU
+ /// buffer.
+ ///
+ /// This operation only updates the CPU cache of the table, without touching
+ /// any GPU buffer. On next GPU buffer update, the GPU buffer will be
+ /// deallocated.
+ #[allow(dead_code)]
+ pub fn clear(&mut self) {
+ self.pending_values.clear();
+ self.extra_pending_values.clear();
+ self.free_indices.clear();
+ self.active_count = 0;
+ }
+
+ /// Clear any stale buffer used for resize in the previous frame during
+ /// rendering while the data structure was immutable.
+ ///
+ /// This must be called before any new [`insert()`].
+ ///
+ /// [`insert()`]: crate::BufferTable::insert
+ pub fn clear_previous_frame_resizes(&mut self) {
+ if let Some(ab) = self.buffer.as_mut() {
+ ab.old_buffer = None;
+ ab.old_count = 0;
+ }
+ }
+
+ /// Calculate the size in byte of `count` rows.
+ #[inline]
+ fn to_byte_size(&self, count: u32) -> usize {
+ count as usize * self.aligned_size
+ }
+
+ /// Insert a new row into the table.
+ ///
+ /// For performance reasons, this buffers the row content on the CPU until
+ /// the next GPU update, to minimize the number of CPU to GPU transfers.
+ pub fn insert(&mut self, value: T) -> BufferTableId {
+ trace!(
+ "Inserting into table buffer '{}' with {} free indices, capacity: {}, active_size: {}",
+ self.safe_name(),
+ self.free_indices.len(),
+ self.capacity,
+ self.active_count
+ );
+ let index = if self.free_indices.is_empty() {
+ let index = self.active_count;
+ if index == self.capacity {
+ self.capacity += 1;
+ }
+ debug_assert!(index < self.capacity);
+ self.active_count += 1;
+ index
+ } else {
+ self.free_indices.pop().unwrap()
+ };
+ let allocated_count = self
+ .buffer
+ .as_ref()
+ .map(|ab| ab.allocated_count())
+ .unwrap_or(0);
+ trace!(
+ "Found free index {}, capacity: {}, active_count: {}, allocated_count: {}",
+ index,
+ self.capacity,
+ self.active_count,
+ allocated_count
+ );
+ if index < allocated_count {
+ self.pending_values.push((index, value));
+ } else {
+ let extra_index = index - allocated_count;
+ if extra_index < self.extra_pending_values.len() as u32 {
+ self.extra_pending_values[extra_index as usize] = value;
+ } else {
+ self.extra_pending_values.push(value);
+ }
+ }
+ BufferTableId(index)
+ }
+
+ /// Calculate a dynamic byte offset for a bind group from a table entry.
+ ///
+ /// This returns the product of `id` by the internal [`aligned_size()`].
+ ///
+ /// # Panic
+ ///
+ /// Panics if the `index` is too large, producing a byte offset larger than
+ /// `u32::MAX`.
+ ///
+ /// [`aligned_size()`]: Self::aligned_size
+ #[inline]
+ #[allow(dead_code)]
+ pub fn dynamic_offset(&self, id: BufferTableId) -> u32 {
+ let offset = self.aligned_size * id.0 as usize;
+ assert!(offset <= u32::MAX as usize);
+ u32::try_from(offset).expect("BufferTable index out of bounds")
+ }
+
+ /// Update an existing row in the table.
+ ///
+ /// For performance reasons, this buffers the row content on the CPU until
+ /// the next GPU update, to minimize the number of CPU to GPU transfers.
+ ///
+ /// Calling this function multiple times overwrites the previous value. Only
+ /// the last value recorded each frame will be uploaded to GPU.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the `id` is invalid.
+ pub fn update(&mut self, id: BufferTableId, value: T) {
+ assert!(id.is_valid());
+ trace!(
+ "Updating row {} of table buffer '{}'",
+ id.0,
+ self.safe_name(),
+ );
+ let allocated_count = self
+ .buffer
+ .as_ref()
+ .map(|ab| ab.allocated_count())
+ .unwrap_or(0);
+ if id.0 < allocated_count {
+ if let Some(idx) = self
+ .pending_values
+ .iter()
+ .position(|&(index, _)| index == id.0)
+ {
+ // Overwrite a previous update. This ensures we never upload more than one
+ // update per row, which would waste GPU bandwidth.
+ self.pending_values[idx] = (id.0, value);
+ } else {
+ self.pending_values.push((id.0, value));
+ }
+ } else {
+ let extra_index = (id.0 - allocated_count) as usize;
+ assert!(extra_index < self.extra_pending_values.len());
+ // Overwrite a previous update. This ensures we never upload more than one
+ // update per row, which would waste GPU bandwidth.
+ self.extra_pending_values[extra_index] = value;
+ }
+ }
+
+ /// Insert several new contiguous rows into the table.
+ ///
+ /// For performance reasons, this buffers the row content on the CPU until
+ /// the next GPU update, to minimize the number of CPU to GPU transfers.
+ ///
+ /// # Returns
+ ///
+ /// Returns the index of the first entry. Other entries follow right after
+ /// it.
+ #[allow(dead_code)] // unused but annoying to write, so keep if we need in the future
+ pub fn insert_contiguous(&mut self, values: impl ExactSizeIterator<Item = T>) -> BufferTableId {
+ let count = values.len() as u32;
+ trace!(
+ "Inserting {} contiguous values into table buffer '{}' with {} free indices, capacity: {}, active_size: {}",
+ count,
+ self.safe_name(),
+ self.free_indices.len(),
+ self.capacity,
+ self.active_count
+ );
+ let first_index = if self.free_indices.is_empty() {
+ let index = self.active_count;
+ if index == self.capacity {
+ self.capacity += count;
+ }
+ debug_assert!(index < self.capacity);
+ self.active_count += count;
+ index
+ } else {
+ let mut s = 0;
+ let mut n = 1;
+ let mut i = 1;
+ while i < self.free_indices.len() {
+ debug_assert!(self.free_indices[i] > self.free_indices[i - 1]); // always sorted
+ if self.free_indices[i] == self.free_indices[i - 1] + 1 {
+ // contiguous
+ n += 1;
+ if n == count {
+ break;
+ }
+ } else {
+ // non-contiguous; restart a new sequence
+ debug_assert!(n < count);
+ s = i;
+ }
+ i += 1;
+ }
+ if n == count {
+ // Found a range of 'count' consecutive entries. Consume it.
+ let index = self.free_indices[s];
+ self.free_indices.splice(s..=i, []);
+ index
+ } else {
+ // No free range for 'count' consecutive entries. Allocate at end instead.
+ let index = self.active_count;
+ if index == self.capacity {
+ self.capacity += count;
+ }
+ debug_assert!(index < self.capacity);
+ self.active_count += count;
+ index
+ }
+ };
+ let allocated_count = self
+ .buffer
+ .as_ref()
+ .map(|ab| ab.allocated_count())
+ .unwrap_or(0);
+ trace!(
+ "Found {} free indices {}..{}, capacity: {}, active_count: {}, allocated_count: {}",
+ count,
+ first_index,
+ first_index + count,
+ self.capacity,
+ self.active_count,
+ allocated_count
+ );
+ for (i, value) in values.enumerate() {
+ let index = first_index + i as u32;
+ if index < allocated_count {
+ self.pending_values.push((index, value));
+ } else {
+ let extra_index = index - allocated_count;
+ if extra_index < self.extra_pending_values.len() as u32 {
+ self.extra_pending_values[extra_index as usize] = value;
+ } else {
+ self.extra_pending_values.push(value);
+ }
+ }
+ }
+ BufferTableId(first_index)
+ }
+
+ /// Remove a row from the table.
+ #[allow(dead_code)]
+ pub fn remove(&mut self, id: BufferTableId) {
+ let index = id.0;
+ assert!(index < self.active_count);
+
+ // If this is the last item in the active zone, just shrink the active zone
+ // (implicit free list).
+ if index == self.active_count - 1 {
+ self.active_count -= 1;
+ self.capacity -= 1;
+ } else {
+ // This is very inefficient but we need to apply the same logic as the
+ // EffectCache because we rely on indices being in sync.
+ let pos = self
+ .free_indices
+ .binary_search(&index) // will fail
+ .unwrap_or_else(|e| e); // will get position of insertion
+ self.free_indices.insert(pos, index);
+ }
+ }
+
+ /// Remove a range of rows from the table.
+ #[allow(dead_code)]
+ pub fn remove_range(&mut self, first: BufferTableId, count: u32) {
+ let index = first.0;
+ assert!(index + count <= self.active_count);
+
+ // If this is the last item in the active zone, just shrink the active zone
+ // (implicit free list).
+ if index == self.active_count - count {
+ self.active_count -= count;
+ self.capacity -= count;
+
+ // Also try to remove free indices
+ if self.free_indices.len() as u32 == self.active_count {
+ // Easy case: everything is free, clear everything
+ self.free_indices.clear();
+ self.active_count = 0;
+ self.capacity = 0;
+ } else {
+ // Some rows are still allocated. Dequeue from end while we have a contiguous
+ // tail of free indices.
+ let mut num_popped = 0;
+ while let Some(idx) = self.free_indices.pop() {
+ if idx < self.active_count - 1 - num_popped {
+ self.free_indices.push(idx);
+ break;
+ }
+ num_popped += 1;
+ }
+ self.active_count -= num_popped;
+ self.capacity -= num_popped;
+ }
+ } else {
+ // This is very inefficient but we need to apply the same logic as the
+ // EffectCache because we rely on indices being in sync.
+ let pos = self
+ .free_indices
+ .binary_search(&index) // will fail
+ .unwrap_or_else(|e| e); // will get position of insertion
+ self.free_indices.splice(pos..pos, index..(index + count));
+ }
+
+ debug_assert!(
+ (self.free_indices.is_empty() && self.active_count == 0)
+ || (self.free_indices.len() as u32) < self.active_count
+ );
+ }
+
+ /// Allocate any GPU buffer if needed, based on the most recent capacity
+ /// requested.
+ ///
+ /// This should be called only once per frame after all allocation requests
+ /// have been made via [`insert()`] but before the GPU buffer is actually
+ /// updated. This is an optimization to enable allocating the GPU buffer
+ /// earlier than it's actually needed. Calling this multiple times is not
+ /// supported, and might assert. Not calling it is safe, as the next
+ /// update will call it just-in-time anyway.
+ ///
+ /// # Returns
+ ///
+ /// Returns `true` if a new buffer was (re-)allocated, to indicate any bind
+ /// group needs to be re-created.
+ ///
+ /// [`insert()]`: crate::render::BufferTable::insert
+ pub fn allocate_gpu(&mut self, device: &RenderDevice, queue: &RenderQueue) -> bool {
+ // The allocated capacity is the capacity of the currently allocated GPU buffer,
+ // which can be different from the expected capacity (self.capacity) for next
+ // update.
+ let allocated_count = self.buffer.as_ref().map(|ab| ab.count).unwrap_or(0);
+ let reallocated = if self.capacity > allocated_count {
+ let byte_size = self.to_byte_size(self.capacity);
+ trace!(
+ "reserve('{}'): increase capacity from {} to {} elements, old size {} bytes, new size {} bytes",
+ self.safe_name(),
+ allocated_count,
+ self.capacity,
+ self.to_byte_size(allocated_count),
+ byte_size
+ );
+
+ // Create the new buffer, swapping with the old one if any
+ let has_init_data = !self.extra_pending_values.is_empty();
+ let new_buffer = device.create_buffer(&BufferDescriptor {
+ label: self.label.as_ref().map(|s| &s[..]),
+ size: byte_size as BufferAddress,
+ usage: self.buffer_usage,
+ mapped_at_creation: has_init_data,
+ });
+
+ // Use any pending data to initialize the buffer. We only use CPU-available
+ // data, which was inserted after the buffer was (re-)allocated and
+ // has not been uploaded to GPU yet.
+ if has_init_data {
+ // Leave some space to copy the old buffer if any
+ let base_size = self.to_byte_size(allocated_count) as u64;
+ let extra_count = self.extra_pending_values.len() as u32;
+ let extra_size = self.to_byte_size(extra_count) as u64;
+
+ // Scope get_mapped_range_mut() to force a drop before unmap()
+ {
+ // Note: get_mapped_range_mut() requires 8-byte alignment of the start offset.
+ let unaligned_range = base_size..(base_size + extra_size);
+ let (range, byte_offset) = round_range_start_down(unaligned_range, 8);
+
+ let mut dst_slice = new_buffer
+ .slice(range)
+ .get_mapped_range_mut()
+ .expect("Buffer must be mapped for writing");
+
+ let base_offset = byte_offset as usize;
+ let byte_size = self.aligned_size; // single row
+ for (index, content) in self.extra_pending_values.drain(..).enumerate() {
+ let byte_offset = base_offset + byte_size * index;
+
+ // Copy Rust value into a GPU-ready format, including GPU padding.
+ let src: &[u8] = cast_slice(std::slice::from_ref(&content));
+ let dst_range = byte_offset..(byte_offset + self.item_size);
+ trace!(
+ "+ init_copy: index={} src={:?} dst={:?} byte_offset={} byte_size={}",
+ index,
+ src.as_ptr(),
+ dst_range,
+ byte_offset,
+ byte_size
+ );
+ dst_slice.slice(dst_range).copy_from_slice(src);
+ }
+ }
+
+ new_buffer.unmap();
+ }
+
+ if let Some(ab) = self.buffer.as_mut() {
+ // If there's any data currently in the GPU buffer, we need to copy it on next
+ // update to preserve it.
+ if self.active_count > 0 {
+ // Current buffer has value to preserve, save it into old_buffer before
+ // replacing it with the newly-allocated one.
+
+ // By design we can't have all active entries as free ones; we should have
+ // updated active_count=0 and cleared the free list if that was the case.
+ debug_assert!(self.free_indices.len() < self.active_count as usize);
+
+ // If we already have an old buffer, that means we already have scheduled a copy
+ // to preserve some values. And we can't do that twice per frame.
+ assert!(
+ ab.old_buffer.is_none(),
+ "allocate_gpu() called twice before write_buffer() took effect."
+ );
+
+ // Swap old <-> new
+ let mut old_buffer = new_buffer;
+ std::mem::swap(&mut old_buffer, &mut ab.buffer);
+ ab.old_buffer = Some(old_buffer);
+ ab.old_count = ab.count;
+ } else {
+ // Current buffer is unused, so we don't need to preserve anything.
+
+ // It could happen we reallocate during the frame then immediately free the rows
+ // to preserve, such that we don't need in the end to preserve anything.
+ if let Some(old_buffer) = ab.old_buffer.take() {
+ old_buffer.destroy();
+ }
+
+ ab.buffer.destroy();
+ ab.buffer = new_buffer;
+ }
+ ab.count = self.capacity;
+ } else {
+ self.buffer = Some(AllocatedBuffer {
+ buffer: new_buffer,
+ count: self.capacity,
+ old_buffer: None,
+ old_count: 0,
+ });
+ }
+
+ true
+ } else {
+ false
+ };
+
+ // Immediately schedule a copy of old rows.
+ // - For old rows, copy into the old buffer because the old-to-new buffer copy
+ // will be executed during a command queue while any CPU to GPU upload is
+ // prepended before the next command queue. To ensure things do get out of
+ // order with the CPU upload overwriting the GPU-to-GPU copy, make sure those
+ // two are disjoint.
+ if let Some(ab) = self.buffer.as_ref() {
+ let buffer = ab.old_buffer.as_ref().unwrap_or(&ab.buffer);
+ for (index, content) in self.pending_values.drain(..) {
+ let byte_size = self.aligned_size;
+ let byte_offset = byte_size * index as usize;
+
+ // Copy Rust value into a GPU-ready format, including GPU padding.
+ // TODO - Do that in insert()!
+ let mut aligned_buffer: Vec<u8> = vec![0; self.aligned_size];
+ let src: &[u8] = cast_slice(std::slice::from_ref(&content));
+ let dst_range = ..self.item_size;
+ trace!(
+ "+ old_copy: index={} src={:?} dst={:?} byte_offset={} byte_size={}",
+ index,
+ src.as_ptr(),
+ dst_range,
+ byte_offset,
+ byte_size
+ );
+ let dst = &mut aligned_buffer[dst_range];
+ dst.copy_from_slice(src);
+
+ // Upload to GPU
+ // TODO - Merge contiguous blocks into a single write_buffer()
+ let bytes: &[u8] = cast_slice(&aligned_buffer);
+ queue.write_buffer(buffer, byte_offset as u64, bytes);
+ }
+ } else {
+ debug_assert!(self.pending_values.is_empty());
+ debug_assert!(self.extra_pending_values.is_empty());
+ }
+
+ reallocated
+ }
+
+ /// Write CPU data to the GPU buffer, (re)allocating it as needed.
+ pub fn write_buffer(&self, encoder: &mut CommandEncoder) {
+ // Check if there's any work to do: either some pending values to upload or some
+ // existing buffer to copy into a newly-allocated one.
+ if self.pending_values.is_empty()
+ && self
+ .buffer
+ .as_ref()
+ .map(|ab| ab.old_buffer.is_none())
+ .unwrap_or(true)
+ {
+ trace!("write_buffer({}): nothing to do", self.safe_name());
+ return;
+ }
+
+ trace!(
+ "write_buffer({}): pending_values.len={} item_size={} aligned_size={} buffer={:?}",
+ self.safe_name(),
+ self.pending_values.len(),
+ self.item_size,
+ self.aligned_size,
+ self.buffer,
+ );
+
+ // If there's no more GPU buffer, there's nothing to do
+ let Some(ab) = self.buffer.as_ref() else {
+ return;
+ };
+
+ // Copy any old buffer into the new one, and clear the old buffer. Note that we
+ // only clear the ref-counted reference to the buffer, not the actual buffer,
+ // which stays alive until the copy is done (but we don't need to care about
+ // keeping it alive, wgpu does that for us).
+ if let Some(old_buffer) = ab.old_buffer.as_ref() {
+ let old_size = self.to_byte_size(ab.old_count) as u64;
+ trace!("Copy old buffer id {:?} of size {} bytes into newly-allocated buffer {:?} of size {} bytes.", old_buffer.id(), old_size, ab.buffer.id(), self.to_byte_size(ab.count));
+ encoder.copy_buffer_to_buffer(old_buffer, 0, &ab.buffer, 0, old_size);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use bevy::math::Vec3;
+ use bytemuck::{Pod, Zeroable};
+
+ use super::*;
+
+ #[test]
+ fn test_round_range_start_down() {
+ // r8(0..7) : no-op
+ {
+ let (r, o) = round_range_start_down(0..7, 8);
+ assert_eq!(r, 0..7);
+ assert_eq!(o, 0);
+ }
+
+ // r8(2..7) = 0..7, +2
+ {
+ let (r, o) = round_range_start_down(2..7, 8);
+ assert_eq!(r, 0..7);
+ assert_eq!(o, 2);
+ }
+
+ // r8(7..32) = 0..32, +7
+ {
+ let (r, o) = round_range_start_down(7..32, 8);
+ assert_eq!(r, 0..32);
+ assert_eq!(o, 7);
+ }
+
+ // r8(8..32) = no-op
+ {
+ let (r, o) = round_range_start_down(8..32, 8);
+ assert_eq!(r, 8..32);
+ assert_eq!(o, 0);
+ }
+ }
+
+ #[repr(C)]
+ #[derive(Debug, Default, Clone, Copy, Pod, Zeroable, ShaderType)]
+ pub(crate) struct GpuDummy {
+ pub v: Vec3,
+ }
+
+ #[repr(C)]
+ #[derive(Debug, Default, Clone, Copy, Pod, Zeroable, ShaderType)]
+ pub(crate) struct GpuDummyComposed {
+ pub simple: GpuDummy,
+ pub tag: u32,
+ // GPU padding to 16 bytes due to GpuDummy forcing align to 16 bytes
+ }
+
+ #[repr(C)]
+ #[derive(Debug, Clone, Copy, Pod, Zeroable, ShaderType)]
+ pub(crate) struct GpuDummyLarge {
+ pub simple: GpuDummy,
+ pub tag: u32,
+ pub large: [f32; 128],
+ }
+
+ #[test]
+ fn buffer_table_sizes() {
+ // Rust
+ assert_eq!(std::mem::size_of::<GpuDummy>(), 12);
+ assert_eq!(std::mem::align_of::<GpuDummy>(), 4);
+ assert_eq!(std::mem::size_of::<GpuDummyComposed>(), 16); // tight packing
+ assert_eq!(std::mem::align_of::<GpuDummyComposed>(), 4);
+ assert_eq!(std::mem::size_of::<GpuDummyLarge>(), 132 * 4); // tight packing
+ assert_eq!(std::mem::align_of::<GpuDummyLarge>(), 4);
+
+ // GPU
+ assert_eq!(<GpuDummy as ShaderType>::min_size().get(), 16); // Vec3 gets padded to 16 bytes
+ assert_eq!(<GpuDummy as ShaderSize>::SHADER_SIZE.get(), 16);
+ assert_eq!(<GpuDummyComposed as ShaderType>::min_size().get(), 32); // align is 16 bytes, forces padding
+ assert_eq!(<GpuDummyComposed as ShaderSize>::SHADER_SIZE.get(), 32);
+ assert_eq!(<GpuDummyLarge as ShaderType>::min_size().get(), 544); // align is 16 bytes, forces padding
+ assert_eq!(<GpuDummyLarge as ShaderSize>::SHADER_SIZE.get(), 544);
+
+ for (item_align, expected_aligned_size) in [
+ (0, 16),
+ (4, 16),
+ (8, 16),
+ (16, 16),
+ (32, 32),
+ (256, 256),
+ (512, 512),
+ ] {
+ let mut table = BufferTable::<GpuDummy>::new(
+ BufferUsages::STORAGE,
+ NonZeroU64::new(item_align),
+ None,
+ );
+ assert_eq!(table.aligned_size(), expected_aligned_size);
+ assert!(table.is_empty());
+ table.insert(GpuDummy::default());
+ assert!(!table.is_empty());
+ assert_eq!(table.len(), 1);
+ }
+
+ for (item_align, expected_aligned_size) in [
+ (0, 32),
+ (4, 32),
+ (8, 32),
+ (16, 32),
+ (32, 32),
+ (256, 256),
+ (512, 512),
+ ] {
+ let mut table = BufferTable::<GpuDummyComposed>::new(
+ BufferUsages::STORAGE,
+ NonZeroU64::new(item_align),
+ None,
+ );
+ assert_eq!(table.aligned_size(), expected_aligned_size);
+ assert!(table.is_empty());
+ table.insert(GpuDummyComposed::default());
+ assert!(!table.is_empty());
+ assert_eq!(table.len(), 1);
+ }
+
+ for (item_align, expected_aligned_size) in [
+ (0, 544),
+ (4, 544),
+ (8, 544),
+ (16, 544),
+ (32, 544),
+ (256, 768),
+ (512, 1024),
+ ] {
+ let mut table = BufferTable::<GpuDummyLarge>::new(
+ BufferUsages::STORAGE,
+ NonZeroU64::new(item_align),
+ None,
+ );
+ assert_eq!(table.aligned_size(), expected_aligned_size);
+ assert!(table.is_empty());
+ table.insert(GpuDummyLarge {
+ simple: Default::default(),
+ tag: 0,
+ large: [0.; 128],
+ });
+ assert!(!table.is_empty());
+ assert_eq!(table.len(), 1);
+ }
+ }
+
+ #[test]
+ fn buffer_table_insert() {
+ let mut table =
+ BufferTable::<GpuDummy>::new(BufferUsages::STORAGE, NonZeroU64::new(32), None);
+
+ // [x]
+ let id1 = table.insert(GpuDummy::default());
+ assert_eq!(id1.0, 0);
+ assert_eq!(table.active_count, 1);
+ assert!(table.free_indices.is_empty());
+
+ // [x x]
+ let id2 = table.insert(GpuDummy::default());
+ assert_eq!(id2.0, 1);
+ assert_eq!(table.active_count, 2);
+ assert!(table.free_indices.is_empty());
+
+ // [- x]
+ table.remove(id1);
+ assert_eq!(table.active_count, 2);
+ assert_eq!(table.free_indices.len(), 1);
+ assert_eq!(table.free_indices[0], 0);
+
+ // [- x x x]
+ let id3 = table.insert_contiguous([GpuDummy::default(); 2].into_iter());
+ assert_eq!(id3.0, 2); // at the end (doesn't fit in free slot #0)
+ assert_eq!(table.active_count, 4);
+ assert_eq!(table.free_indices.len(), 1);
+ assert_eq!(table.free_indices[0], 0);
+
+ // [- - x x]
+ table.remove(id2);
+ assert_eq!(table.active_count, 4);
+ assert_eq!(table.free_indices.len(), 2);
+ assert_eq!(table.free_indices[0], 0);
+ assert_eq!(table.free_indices[1], 1);
+
+ // [x x x x]
+ let id4 = table.insert_contiguous([GpuDummy::default(); 2].into_iter());
+ assert_eq!(id4.0, 0); // this times it fit into slot #0-#1
+ assert_eq!(table.active_count, 4);
+ assert!(table.free_indices.is_empty());
+
+ // [- - x x]
+ table.remove_range(id4, 2);
+ assert_eq!(table.active_count, 4);
+ assert_eq!(table.free_indices.len(), 2);
+ assert_eq!(table.free_indices[0], 0);
+ assert_eq!(table.free_indices[1], 1);
+
+ // []
+ table.remove_range(id3, 2);
+ assert_eq!(table.active_count, 0);
+ assert!(table.free_indices.is_empty());
+
+ // [x x]
+ let id5 = table.insert_contiguous([GpuDummy::default(); 2].into_iter());
+ assert_eq!(id5.0, 0);
+ assert_eq!(table.active_count, 2);
+ assert!(table.free_indices.is_empty());
+
+ // [x x x x]
+ let id6 = table.insert_contiguous([GpuDummy::default(); 2].into_iter());
+ assert_eq!(id6.0, 2);
+ assert_eq!(table.active_count, 4);
+ assert!(table.free_indices.is_empty());
+
+ // [x x x x x x]
+ let id7 = table.insert_contiguous([GpuDummy::default(); 2].into_iter());
+ assert_eq!(id7.0, 4);
+ assert_eq!(table.active_count, 6);
+ assert!(table.free_indices.is_empty());
+
+ // [x x - - x x]
+ table.remove_range(id6, 2);
+ assert_eq!(table.active_count, 6);
+ assert_eq!(table.free_indices.len(), 2);
+ assert_eq!(table.free_indices[0], 2);
+ assert_eq!(table.free_indices[1], 3);
+
+ // [x x]
+ table.remove_range(id7, 2);
+ assert_eq!(table.active_count, 2);
+ assert!(table.free_indices.is_empty());
+ }
+}
+
+#[cfg(all(test, feature = "gpu_tests"))]
+mod gpu_tests {
+ use std::fmt::Write;
+
+ use bevy::render::render_resource::BufferSlice;
+ use tests::*;
+ use wgpu::{BufferView, CommandBuffer};
+
+ use super::*;
+ use crate::test_utils::MockRenderer;
+
+ /// Read data from GPU back into CPU memory.
+ ///
+ /// This call blocks until the data is available on CPU. Used for testing
+ /// only.
+ fn read_back_gpu(device: &RenderDevice, slice: BufferSlice<'_>) -> BufferView {
+ let (tx, rx) = futures::channel::oneshot::channel();
+ slice.map_async(wgpu::MapMode::Read, move |result| {
+ tx.send(result).unwrap();
+ });
+ let _ = device.poll(wgpu::PollType::Wait {
+ submission_index: None,
+ timeout: None,
+ });
+ let result = futures::executor::block_on(rx);
+ assert!(result.is_ok());
+ slice
+ .get_mapped_range()
+ .expect("Buffer must be mapped for reading")
+ }
+
+ /// Submit a command buffer to GPU and wait for completion.
+ ///
+ /// This call blocks until the GPU executed the command buffer. Used for
+ /// testing only.
+ fn submit_gpu_and_wait(
+ device: &RenderDevice,
+ queue: &RenderQueue,
+ command_buffer: CommandBuffer,
+ ) {
+ // Queue command
+ queue.submit([command_buffer]);
+
+ // Register callback to observe completion
+ let (tx, rx) = futures::channel::oneshot::channel();
+ queue.on_submitted_work_done(move || {
+ tx.send(()).unwrap();
+ });
+
+ // Poll device, checking for completion and raising callback
+ let _ = device.poll(wgpu::PollType::Wait {
+ submission_index: None,
+ timeout: None,
+ });
+
+ // Wait for callback to be raised. This was need in previous versions, however
+ // it's a bit unclear if it's still needed or if device.poll() is enough to
+ // guarantee that the command was executed.
+ let _ = futures::executor::block_on(rx);
+ }
+
+ /// Convert a byte slice to a string of hexadecimal values separated by a
+ /// blank space.
+ fn to_hex_string(slice: &[u8]) -> String {
+ let len = slice.len();
+ let num_chars = len * 3 - 1;
+ let mut s = String::with_capacity(num_chars);
+ for b in &slice[..len - 1] {
+ write!(&mut s, "{:02x} ", *b).unwrap();
+ }
+ write!(&mut s, "{:02x}", slice[len - 1]).unwrap();
+ debug_assert_eq!(s.len(), num_chars);
+ s
+ }
+
+ fn write_buffers_and_wait<T: Pod + ShaderSize>(
+ table: &BufferTable<T>,
+ device: &RenderDevice,
+ queue: &RenderQueue,
+ ) {
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("test"),
+ });
+ table.write_buffer(&mut encoder);
+ let command_buffer = encoder.finish();
+ submit_gpu_and_wait(device, queue, command_buffer);
+ println!("Buffer written to GPU");
+ }
+
+ #[test]
+ fn table_write() {
+ let renderer = MockRenderer::new();
+ let device = renderer.device();
+ let queue = renderer.queue();
+
+ let item_align = device.limits().min_storage_buffer_offset_alignment as u64;
+ println!("min_storage_buffer_offset_alignment = {item_align}");
+ let mut table = BufferTable::<GpuDummyComposed>::new(
+ BufferUsages::STORAGE | BufferUsages::MAP_READ,
+ NonZeroU64::new(item_align),
+ None,
+ );
+ let final_align = item_align.max(<GpuDummyComposed as ShaderSize>::SHADER_SIZE.get());
+ assert_eq!(table.aligned_size(), final_align as usize);
+
+ // Initial state
+ assert!(table.is_empty());
+ assert_eq!(table.len(), 0);
+ assert_eq!(table.capacity(), 0);
+ assert!(table.buffer.is_none());
+
+ // This has no effect while the table is empty
+ table.clear_previous_frame_resizes();
+ table.allocate_gpu(&device, &queue);
+ write_buffers_and_wait(&table, &device, &queue);
+ assert!(table.is_empty());
+ assert_eq!(table.len(), 0);
+ assert_eq!(table.capacity(), 0);
+ assert!(table.buffer.is_none());
+
+ // New frame
+ table.clear_previous_frame_resizes();
+
+ // Insert some entries
+ let len = 3;
+ for i in 0..len {
+ let row = table.insert(GpuDummyComposed {
+ tag: i + 1,
+ ..Default::default()
+ });
+ assert_eq!(row.0, i);
+ }
+ assert!(!table.is_empty());
+ assert_eq!(table.len(), len);
+ assert!(table.capacity() >= len); // contract: could over-allocate...
+ assert!(table.buffer.is_none()); // not yet allocated on GPU
+
+ // Allocate GPU buffer for current requested state
+ table.allocate_gpu(&device, &queue);
+ assert!(!table.is_empty());
+ assert_eq!(table.len(), len);
+ assert!(table.capacity() >= len);
+ let ab = table
+ .buffer
+ .as_ref()
+ .expect("GPU buffer should be allocated after allocate_gpu()");
+ assert!(ab.old_buffer.is_none()); // no previous copy
+ assert_eq!(ab.count, len);
+ println!(
+ "Allocated buffer #{:?} of {} rows",
+ ab.buffer.id(),
+ ab.count
+ );
+ let ab_buffer = ab.buffer.clone();
+
+ // Another allocate_gpu() is a no-op
+ table.allocate_gpu(&device, &queue);
+ assert!(!table.is_empty());
+ assert_eq!(table.len(), len);
+ assert!(table.capacity() >= len);
+ let ab = table
+ .buffer
+ .as_ref()
+ .expect("GPU buffer should be allocated after allocate_gpu()");
+ assert!(ab.old_buffer.is_none()); // no previous copy
+ assert_eq!(ab.count, len);
+ assert_eq!(ab_buffer.id(), ab.buffer.id()); // same buffer
+
+ // Write buffer (CPU -> GPU)
+ write_buffers_and_wait(&table, &device, &queue);
+
+ {
+ // Read back (GPU -> CPU)
+ let buffer = table.buffer().expect("Buffer was not allocated").clone(); // clone() for lifetime
+ {
+ let slice = buffer.slice(..);
+ let view = read_back_gpu(&device, slice);
+ println!(
+ "GPU data read back to CPU for validation: {} bytes",
+ view.len()
+ );
+
+ // Validate content
+ assert_eq!(view.len(), final_align as usize * table.capacity() as usize);
+ for i in 0..len as usize {
+ let offset = i * final_align as usize;
+ let item_size = std::mem::size_of::<GpuDummyComposed>();
+ let src = &view[offset..offset + 16];
+ println!("{}", to_hex_string(src));
+ let dummy_composed: &[GpuDummyComposed] =
+ cast_slice(&view[offset..offset + item_size]);
+ assert_eq!(dummy_composed[0].tag, (i + 1) as u32);
+ }
+ }
+ buffer.unmap();
+ }
+
+ // New frame
+ table.clear_previous_frame_resizes();
+
+ // Insert more entries
+ let old_capacity = table.capacity();
+ let mut len = len;
+ while table.capacity() == old_capacity {
+ let row = table.insert(GpuDummyComposed {
+ tag: len + 1,
+ ..Default::default()
+ });
+ assert_eq!(row.0, len);
+ len += 1;
+ }
+ println!(
+ "Added {} rows to grow capacity from {} to {}.",
+ len - 3,
+ old_capacity,
+ table.capacity()
+ );
+
+ // This re-allocates a new GPU buffer because the capacity changed
+ table.allocate_gpu(&device, &queue);
+ assert!(!table.is_empty());
+ assert_eq!(table.len(), len);
+ assert!(table.capacity() >= len);
+ let ab = table
+ .buffer
+ .as_ref()
+ .expect("GPU buffer should be allocated after allocate_gpu()");
+ assert_eq!(ab.count, len);
+ assert!(ab.old_buffer.is_some()); // old buffer to copy
+ assert_ne!(ab.old_buffer.as_ref().unwrap().id(), ab.buffer.id());
+ println!(
+ "Allocated new buffer #{:?} of {} rows",
+ ab.buffer.id(),
+ ab.count
+ );
+
+ // Write buffer (CPU -> GPU)
+ write_buffers_and_wait(&table, &device, &queue);
+
+ {
+ // Read back (GPU -> CPU)
+ let buffer = table.buffer().expect("Buffer was not allocated").clone(); // clone() for lifetime
+ {
+ let slice = buffer.slice(..);
+ let view = read_back_gpu(&device, slice);
+ println!(
+ "GPU data read back to CPU for validation: {} bytes",
+ view.len()
+ );
+
+ // Validate content
+ assert_eq!(view.len(), final_align as usize * table.capacity() as usize);
+ for i in 0..len as usize {
+ let offset = i * final_align as usize;
+ let item_size = std::mem::size_of::<GpuDummyComposed>();
+ let src = &view[offset..offset + 16];
+ println!("{}", to_hex_string(src));
+ let dummy_composed: &[GpuDummyComposed] =
+ cast_slice(&view[offset..offset + item_size]);
+ assert_eq!(dummy_composed[0].tag, (i + 1) as u32);
+ }
+ }
+ buffer.unmap();
+ }
+
+ // New frame
+ table.clear_previous_frame_resizes();
+
+ // Delete the last allocated row
+ let old_capacity = table.capacity();
+ let len = len - 1;
+ table.remove(BufferTableId(len));
+ println!(
+ "Removed last row to shrink capacity from {} to {}.",
+ old_capacity,
+ table.capacity()
+ );
+
+ // This doesn't do anything since we removed a row only
+ table.allocate_gpu(&device, &queue);
+ assert!(!table.is_empty());
+ assert_eq!(table.len(), len);
+ assert!(table.capacity() >= len);
+ let ab = table
+ .buffer
+ .as_ref()
+ .expect("GPU buffer should be allocated after allocate_gpu()");
+ assert_eq!(ab.count, len + 1); // GPU buffer kept its size
+ assert!(ab.old_buffer.is_none());
+
+ // Write buffer (CPU -> GPU)
+ write_buffers_and_wait(&table, &device, &queue);
+
+ {
+ // Read back (GPU -> CPU)
+ let buffer = table.buffer().expect("Buffer was not allocated").clone(); // clone() for lifetime
+ {
+ let slice = buffer.slice(..);
+ let view = read_back_gpu(&device, slice);
+ println!(
+ "GPU data read back to CPU for validation: {} bytes",
+ view.len()
+ );
+
+ // Validate content
+ assert!(view.len() >= final_align as usize * table.capacity() as usize); // note the >=, the buffer is over-allocated
+ for i in 0..len as usize {
+ let offset = i * final_align as usize;
+ let item_size = std::mem::size_of::<GpuDummyComposed>();
+ let src = &view[offset..offset + 16];
+ println!("{}", to_hex_string(src));
+ let dummy_composed: &[GpuDummyComposed] =
+ cast_slice(&view[offset..offset + item_size]);
+ assert_eq!(dummy_composed[0].tag, (i + 1) as u32);
+ }
+ }
+ buffer.unmap();
+ }
+
+ // New frame
+ table.clear_previous_frame_resizes();
+
+ // Delete the first allocated row
+ let old_capacity = table.capacity();
+ let mut len = len - 1;
+ table.remove(BufferTableId(0));
+ assert_eq!(old_capacity, table.capacity());
+ println!(
+ "Removed first row to shrink capacity from {} to {} (no change).",
+ old_capacity,
+ table.capacity()
+ );
+
+ // This doesn't do anything since we only removed a row
+ table.allocate_gpu(&device, &queue);
+ assert!(!table.is_empty());
+ assert_eq!(table.len(), len);
+ assert!(table.capacity() >= len);
+ let ab = table
+ .buffer
+ .as_ref()
+ .expect("GPU buffer should be allocated after allocate_gpu()");
+ assert_eq!(ab.count, len + 2); // GPU buffer kept its size
+ assert!(ab.old_buffer.is_none());
+
+ // Write buffer (CPU -> GPU)
+ write_buffers_and_wait(&table, &device, &queue);
+
+ {
+ // Read back (GPU -> CPU)
+ let buffer = table.buffer().expect("Buffer was not allocated").clone(); // clone() for lifetime
+ {
+ let slice = buffer.slice(..);
+ let view = read_back_gpu(&device, slice);
+ println!(
+ "GPU data read back to CPU for validation: {} bytes",
+ view.len()
+ );
+
+ // Validate content
+ assert!(view.len() >= final_align as usize * table.capacity() as usize); // note the >=, the buffer is over-allocated
+ for i in 0..len as usize {
+ let offset = i * final_align as usize;
+ let item_size = std::mem::size_of::<GpuDummyComposed>();
+ let src = &view[offset..offset + 16];
+ println!("{}", to_hex_string(src));
+ if i > 0 {
+ let dummy_composed: &[GpuDummyComposed] =
+ cast_slice(&view[offset..offset + item_size]);
+ assert_eq!(dummy_composed[0].tag, (i + 1) as u32);
+ }
+ }
+ }
+ buffer.unmap();
+ }
+
+ // New frame
+ table.clear_previous_frame_resizes();
+
+ // Insert a row; this should get into row #0 in the buffer
+ let row = table.insert(GpuDummyComposed {
+ tag: 1,
+ ..Default::default()
+ });
+ assert_eq!(row.0, 0);
+ len += 1;
+ println!(
+ "Added 1 row to grow capacity from {} to {}.",
+ old_capacity,
+ table.capacity()
+ );
+
+ // This doesn't reallocate the GPU buffer since we used a free list entry
+ table.allocate_gpu(&device, &queue);
+ assert!(!table.is_empty());
+ assert_eq!(table.len(), len);
+ assert!(table.capacity() >= len);
+ let ab = table
+ .buffer
+ .as_ref()
+ .expect("GPU buffer should be allocated after allocate_gpu()");
+ assert_eq!(ab.count, 4); // 4 == last time we grew
+ assert!(ab.old_buffer.is_none());
+
+ // Write buffer (CPU -> GPU)
+ write_buffers_and_wait(&table, &device, &queue);
+
+ {
+ // Read back (GPU -> CPU)
+ let buffer = table.buffer().expect("Buffer was not allocated").clone(); // clone() for lifetime
+ {
+ let slice = buffer.slice(..);
+ let view = read_back_gpu(&device, slice);
+ println!(
+ "GPU data read back to CPU for validation: {} bytes",
+ view.len()
+ );
+
+ // Validate content
+ assert!(view.len() >= final_align as usize * table.capacity() as usize);
+ for i in 0..len as usize {
+ let offset = i * final_align as usize;
+ let item_size = std::mem::size_of::<GpuDummyComposed>();
+ let src = &view[offset..offset + 16];
+ println!("{}", to_hex_string(src));
+ let dummy_composed: &[GpuDummyComposed] =
+ cast_slice(&view[offset..offset + item_size]);
+ assert_eq!(dummy_composed[0].tag, (i + 1) as u32);
+ }
+ }
+ buffer.unmap();
+ }
+
+ // New frame
+ table.clear_previous_frame_resizes();
+
+ // Insert a row; this should get into row #3 at the end of the allocated buffer
+ let row = table.insert(GpuDummyComposed {
+ tag: 4,
+ ..Default::default()
+ });
+ assert_eq!(row.0, 3);
+ len += 1;
+ println!(
+ "Added 1 row to grow capacity from {} to {}.",
+ old_capacity,
+ table.capacity()
+ );
+
+ // This doesn't reallocate the GPU buffer since we used an implicit free entry
+ table.allocate_gpu(&device, &queue);
+ assert!(!table.is_empty());
+ assert_eq!(table.len(), len);
+ assert!(table.capacity() >= len);
+ let ab = table
+ .buffer
+ .as_ref()
+ .expect("GPU buffer should be allocated after allocate_gpu()");
+ assert_eq!(ab.count, 4); // 4 == last time we grew
+ assert!(ab.old_buffer.is_none());
+
+ // Write buffer (CPU -> GPU)
+ write_buffers_and_wait(&table, &device, &queue);
+
+ {
+ // Read back (GPU -> CPU)
+ let buffer = table.buffer().expect("Buffer was not allocated").clone(); // clone() for lifetime
+ {
+ let slice = buffer.slice(..);
+ let view = read_back_gpu(&device, slice);
+ println!(
+ "GPU data read back to CPU for validation: {} bytes",
+ view.len()
+ );
+
+ // Validate content
+ assert!(view.len() >= final_align as usize * table.capacity() as usize);
+ for i in 0..len as usize {
+ let offset = i * final_align as usize;
+ let item_size = std::mem::size_of::<GpuDummyComposed>();
+ let src = &view[offset..offset + 16];
+ println!("{}", to_hex_string(src));
+ let dummy_composed: &[GpuDummyComposed] =
+ cast_slice(&view[offset..offset + item_size]);
+ assert_eq!(dummy_composed[0].tag, (i + 1) as u32);
+ }
+ }
+ buffer.unmap();
+ }
+ }
+}
diff --git a/vendor/bevy_hanabi/src/render/effect_cache.rs b/vendor/bevy_hanabi/src/render/effect_cache.rs
new file mode 100644
index 00000000..cf082e93
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/effect_cache.rs
@@ -0,0 +1,1547 @@
+use std::{
+ cmp::Ordering,
+ num::{NonZeroU32, NonZeroU64},
+ ops::Range,
+};
+
+use bevy::{
+ asset::Handle,
+ ecs::{component::Component, resource::Resource},
+ log::{trace, warn},
+ platform::collections::HashMap,
+ render::{
+ mesh::allocator::MeshBufferSlice,
+ render_resource::{
+ binding_types::{storage_buffer_read_only, storage_buffer_read_only_sized},
+ *,
+ },
+ renderer::RenderDevice,
+ },
+ utils::default,
+};
+use bytemuck::cast_slice;
+
+use super::{buffer_table::BufferTableId, BufferBindingSource};
+use crate::{
+ asset::EffectAsset,
+ render::{
+ calc_hash, event::GpuChildInfo, GpuDrawIndexedIndirectArgs, GpuDrawIndirectArgs,
+ GpuEffectMetadata, GpuIndirectIndex,
+ },
+ ParticleLayout,
+};
+
+/// Describes all particle slices of particles in the particle buffer
+/// for a single effect.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct EffectSlice {
+ /// Slice into the underlying [`BufferVec`].
+ ///
+ /// This is measured in items, not bytes.
+ pub slice: Range<u32>,
+ /// ID of the particle slab in the [`EffectCache`].
+ pub slab_id: SlabId,
+ /// Particle layout of the effect.
+ pub particle_layout: ParticleLayout,
+}
+
+impl Ord for EffectSlice {
+ fn cmp(&self, other: &Self) -> Ordering {
+ match self.slab_id.cmp(&other.slab_id) {
+ Ordering::Equal => self.slice.start.cmp(&other.slice.start),
+ ord => ord,
+ }
+ }
+}
+
+impl PartialOrd for EffectSlice {
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+ Some(self.cmp(other))
+ }
+}
+
+/// A reference to a slice allocated inside an [`ParticleSlab`].
+#[derive(Debug, Default, Clone, PartialEq, Eq)]
+pub struct SlabSliceRef {
+ /// Range into a [`ParticleSlab`], in item count.
+ range: Range<u32>,
+ /// Particle layout for the effect stored in that slice.
+ pub(crate) particle_layout: ParticleLayout,
+}
+
+impl SlabSliceRef {
+ /// The length of the slice, in number of items.
+ #[allow(dead_code)]
+ pub fn len(&self) -> u32 {
+ self.range.end - self.range.start
+ }
+
+ /// The size in bytes of the slice.
+ #[allow(dead_code)]
+ pub fn byte_size(&self) -> usize {
+ (self.len() as usize) * (self.particle_layout.min_binding_size().get() as usize)
+ }
+
+ pub fn range(&self) -> Range<u32> {
+ self.range.clone()
+ }
+}
+
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
+struct SimBindGroupKey {
+ buffer: Option<BufferId>,
+ offset: u32,
+ size: u32,
+}
+
+impl SimBindGroupKey {
+ /// Invalid key, often used as placeholder.
+ pub const INVALID: Self = Self {
+ buffer: None,
+ offset: u32::MAX,
+ size: 0,
+ };
+}
+
+impl From<&BufferBindingSource> for SimBindGroupKey {
+ fn from(value: &BufferBindingSource) -> Self {
+ Self {
+ buffer: Some(value.buffer.id()),
+ offset: value.offset,
+ size: value.size.get(),
+ }
+ }
+}
+
+impl From<Option<&BufferBindingSource>> for SimBindGroupKey {
+ fn from(value: Option<&BufferBindingSource>) -> Self {
+ if let Some(bbs) = value {
+ Self {
+ buffer: Some(bbs.buffer.id()),
+ offset: bbs.offset,
+ size: bbs.size.get(),
+ }
+ } else {
+ Self::INVALID
+ }
+ }
+}
+
+/// State of a [`ParticleSlab`] after an insertion or removal operation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SlabState {
+ /// The slab is in use, with allocated resources.
+ Used,
+ /// Like `Used`, but the slab was resized, so any bind group is
+ /// nonetheless invalid.
+ Resized,
+ /// The slab is free (its resources were deallocated).
+ Free,
+}
+
+/// ID of a [`ParticleSlab`] inside an [`EffectCache`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct SlabId(u32);
+
+impl SlabId {
+ /// An invalid value, often used as placeholder.
+ pub const INVALID: SlabId = SlabId(u32::MAX);
+
+ /// Create a new slab ID from its underlying index.
+ pub const fn new(index: u32) -> Self {
+ assert!(index != u32::MAX);
+ Self(index)
+ }
+
+ /// Check if the current ID is valid, that is, is different from
+ /// [`INVALID`].
+ ///
+ /// [`INVALID`]: Self::INVALID
+ #[inline]
+ #[allow(dead_code)]
+ pub const fn is_valid(&self) -> bool {
+ self.0 != Self::INVALID.0
+ }
+
+ /// Get the raw underlying index.
+ ///
+ /// This is mostly used for debugging / logging.
+ #[inline]
+ pub const fn index(&self) -> u32 {
+ self.0
+ }
+}
+
+impl Default for SlabId {
+ fn default() -> Self {
+ Self::INVALID
+ }
+}
+
+/// Storage for the per-particle data of effects sharing compatible layouts.
+///
+/// Currently only accepts a single unique particle layout, fixed at creation.
+/// If an effect has a different particle layout, it needs to be stored in a
+/// different slab.
+///
+/// Also currently only accepts instances of a unique effect asset, although
+/// this restriction is purely for convenience and may be relaxed in the future
+/// to improve batching.
+#[derive(Debug)]
+pub struct ParticleSlab {
+ /// GPU buffer storing all particles for the entire slab of effects.
+ ///
+ /// Each particle is a collection of attributes arranged according to
+ /// [`Self::particle_layout`]. The buffer contains storage for exactly
+ /// [`Self::capacity`] particles.
+ particle_buffer: Buffer,
+ /// GPU buffer storing the indirection indices for the entire slab of
+ /// effects.
+ ///
+ /// Each indirection item contains 3 values:
+ /// - the ping-pong alive particles and render indirect indices at offsets 0
+ /// and 1
+ /// - the dead particle indices at offset 2
+ ///
+ /// The buffer contains storage for exactly [`Self::capacity`] items.
+ indirect_index_buffer: Buffer,
+ /// Layout of particles.
+ particle_layout: ParticleLayout,
+ /// Total slab capacity, in number of particles.
+ capacity: u32,
+ /// Used slab size, in number of particles, either from allocated slices
+ /// or from slices in the free list.
+ used_size: u32,
+ /// Array of free slices for new allocations, sorted in increasing order
+ /// inside the slab buffers.
+ free_slices: Vec<Range<u32>>,
+
+ /// Handle of all effects common in this slab. TODO - replace with
+ /// compatible layout.
+ asset: Handle<EffectAsset>,
+ /// Layout of the particle@1 bind group for the render pass.
+ // TODO - move; this only depends on the particle and spawner layouts, can be shared across
+ // slabs
+ render_particles_buffer_layout: BindGroupLayout,
+ /// Bind group particle@1 of the simulation passes (init and udpate).
+ sim_bind_group: Option<BindGroup>,
+ /// Key the `sim_bind_group` was created from.
+ sim_bind_group_key: SimBindGroupKey,
+}
+
+impl ParticleSlab {
+ /// Minimum buffer capacity to allocate, in number of particles.
+ pub const MIN_CAPACITY: u32 = 65536; // at least 64k particles
+
+ /// Create a new slab and the GPU resources to back it up.
+ ///
+ /// The slab cannot contain less than [`MIN_CAPACITY`] particles. If the
+ /// input `capacity` is smaller, it's rounded up to [`MIN_CAPACITY`].
+ ///
+ /// # Panics
+ ///
+ /// This panics if the `capacity` is zero.
+ ///
+ /// [`MIN_CAPACITY`]: Self::MIN_CAPACITY
+ pub fn new(
+ slab_id: SlabId,
+ asset: Handle<EffectAsset>,
+ capacity: u32,
+ particle_layout: ParticleLayout,
+ render_device: &RenderDevice,
+ ) -> Self {
+ trace!(
+ "ParticleSlab::new(slab_id={}, capacity={}, particle_layout={:?}, item_size={}B)",
+ slab_id.0,
+ capacity,
+ particle_layout,
+ particle_layout.min_binding_size().get(),
+ );
+
+ // Calculate the clamped capacity of the group, in number of particles.
+ let capacity = capacity.max(Self::MIN_CAPACITY);
+ assert!(
+ capacity > 0,
+ "Attempted to create a zero-sized effect buffer."
+ );
+
+ // Allocate the particle buffer itself, containing the attributes of each
+ // particle.
+ #[cfg(debug_assertions)]
+ let mapped_at_creation = true;
+ #[cfg(not(debug_assertions))]
+ let mapped_at_creation = false;
+ let particle_capacity_bytes: BufferAddress =
+ capacity as u64 * particle_layout.min_binding_size().get();
+ let particle_label = format!("hanabi:buffer:slab{}:particle", slab_id.0);
+ let particle_buffer = render_device.create_buffer(&BufferDescriptor {
+ label: Some(&particle_label),
+ size: particle_capacity_bytes,
+ usage: BufferUsages::COPY_DST | BufferUsages::STORAGE,
+ mapped_at_creation,
+ });
+ // Set content
+ #[cfg(debug_assertions)]
+ {
+ // Scope get_mapped_range_mut() to force a drop before unmap()
+ {
+ let mut mapped = particle_buffer
+ .slice(..particle_capacity_bytes)
+ .get_mapped_range_mut()
+ .expect("Buffer must be mapped for writing");
+ let particle_count_u32 = (particle_capacity_bytes / 4) as usize;
+ let values = vec![0xFFFF_FFFFu32; particle_count_u32];
+ mapped.copy_from_slice(cast_slice(values.as_slice()));
+ }
+ particle_buffer.unmap();
+ }
+
+ // Each indirect buffer stores 3 arrays of u32, of length the number of
+ // particles.
+ let indirect_capacity_bytes: BufferAddress = capacity as u64 * 4 * 3;
+ let indirect_label = format!("hanabi:buffer:slab{}:indirect", slab_id.0);
+ let indirect_index_buffer = render_device.create_buffer(&BufferDescriptor {
+ label: Some(&indirect_label),
+ size: indirect_capacity_bytes,
+ usage: BufferUsages::COPY_DST | BufferUsages::STORAGE,
+ mapped_at_creation: true,
+ });
+ // Set content
+ {
+ // Scope get_mapped_range_mut() to force a drop before unmap()
+ {
+ let mut mapped = indirect_index_buffer
+ .slice(..indirect_capacity_bytes)
+ .get_mapped_range_mut()
+ .expect("Buffer must be mapped for writing");
+ let mut values = vec![0u32; capacity as usize * 3];
+ let slice: &mut [u32] = values.as_mut_slice();
+ for index in 0..capacity {
+ slice[3 * index as usize + 2] = index;
+ }
+ mapped.copy_from_slice(cast_slice(values.as_slice()));
+ }
+ indirect_index_buffer.unmap();
+ }
+
+ // Create the render layout.
+ // TODO - move; this only depends on the particle and spawner layouts, can be
+ // shared across slabs
+ // FIXME - duplicated in ParticlesRenderPipeline::specialize()
+ let label = format!("hanabi:bgl:render:particles@1:slab{}", slab_id.0);
+ let render_particles_buffer_layout = render_device.create_bind_group_layout(
+ &label[..],
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::VERTEX,
+ (
+ // @group(1) @binding(0) var<storage, read> particle_buffer : ParticleBuffer;
+ storage_buffer_read_only_sized(false, Some(particle_layout.min_binding_size()))
+ .visibility(ShaderStages::VERTEX_FRAGMENT),
+ // @group(1) @binding(1) var<storage, read> indirect_buffer : IndirectBuffer;
+ storage_buffer_read_only::<GpuIndirectIndex>(false),
+ ),
+ ),
+ );
+
+ Self {
+ particle_buffer,
+ indirect_index_buffer,
+ particle_layout,
+ render_particles_buffer_layout,
+ capacity,
+ used_size: 0,
+ free_slices: vec![],
+ asset,
+ sim_bind_group: None,
+ sim_bind_group_key: SimBindGroupKey::INVALID,
+ }
+ }
+
+ // TODO - move; this only depends on the particle and spawner layouts, can be
+ // shared across slabs
+ pub fn render_particles_buffer_layout(&self) -> &BindGroupLayout {
+ &self.render_particles_buffer_layout
+ }
+
+ #[inline]
+ pub fn particle_buffer(&self) -> &Buffer {
+ &self.particle_buffer
+ }
+
+ #[inline]
+ pub fn indirect_index_buffer(&self) -> &Buffer {
+ &self.indirect_index_buffer
+ }
+
+ /// Return a binding for the entire particle buffer.
+ pub fn as_entire_binding_particle(&self) -> BindingResource<'_> {
+ let capacity_bytes = self.capacity as u64 * self.particle_layout.min_binding_size().get();
+ BindingResource::Buffer(BufferBinding {
+ buffer: &self.particle_buffer,
+ offset: 0,
+ size: Some(NonZeroU64::new(capacity_bytes).unwrap()),
+ })
+ //self.particle_buffer.as_entire_binding()
+ }
+
+ /// Return a binding source for the entire particle buffer.
+ pub fn max_binding_source(&self) -> BufferBindingSource {
+ let capacity_bytes = self.capacity * self.particle_layout.min_binding_size32().get();
+ BufferBindingSource {
+ buffer: self.particle_buffer.clone(),
+ offset: 0,
+ size: NonZeroU32::new(capacity_bytes).unwrap(),
+ }
+ }
+
+ /// Return a binding for the entire indirect buffer associated with the
+ /// current effect buffer.
+ pub fn as_entire_binding_indirect(&self) -> BindingResource<'_> {
+ let capacity_bytes = self.capacity as u64 * 12;
+ BindingResource::Buffer(BufferBinding {
+ buffer: &self.indirect_index_buffer,
+ offset: 0,
+ size: Some(NonZeroU64::new(capacity_bytes).unwrap()),
+ })
+ //self.indirect_index_buffer.as_entire_binding()
+ }
+
+ /// Create the "particle" bind group @1 for the init and update passes if
+ /// needed.
+ ///
+ /// The `slab_id` must be the ID of the current [`ParticleSlab`] inside the
+ /// [`EffectCache`].
+ pub fn create_particle_sim_bind_group(
+ &mut self,
+ layout: &BindGroupLayout,
+ slab_id: &SlabId,
+ render_device: &RenderDevice,
+ parent_binding_source: Option<&BufferBindingSource>,
+ ) {
+ let key: SimBindGroupKey = parent_binding_source.into();
+ if self.sim_bind_group.is_some() && self.sim_bind_group_key == key {
+ return;
+ }
+
+ let label = format!("hanabi:bg:sim:particle@1:vfx{}", slab_id.index());
+ let entries: &[BindGroupEntry] = if let Some(parent_binding) =
+ parent_binding_source.as_ref().map(|bbs| bbs.as_binding())
+ {
+ &BindGroupEntries::sequential((
+ self.as_entire_binding_particle(),
+ self.as_entire_binding_indirect(),
+ parent_binding,
+ ))
+ } else {
+ &BindGroupEntries::sequential((
+ self.as_entire_binding_particle(),
+ self.as_entire_binding_indirect(),
+ ))
+ };
+
+ trace!(
+ "Create particle simulation bind group '{}' with {} entries (has_parent:{})",
+ label,
+ entries.len(),
+ parent_binding_source.is_some(),
+ );
+ let bind_group = render_device.create_bind_group(Some(&label[..]), layout, entries);
+ self.sim_bind_group = Some(bind_group);
+ self.sim_bind_group_key = key;
+ }
+
+ /// Invalidate any existing simulate bind group.
+ ///
+ /// Invalidate any existing bind group previously created by
+ /// [`create_particle_sim_bind_group()`], generally because a buffer was
+ /// re-allocated. This forces a re-creation of the bind group
+ /// next time [`create_particle_sim_bind_group()`] is called.
+ ///
+ /// [`create_particle_sim_bind_group()`]: self::ParticleSlab::create_particle_sim_bind_group
+ #[allow(dead_code)] // FIXME - review this...
+ fn invalidate_particle_sim_bind_group(&mut self) {
+ self.sim_bind_group = None;
+ self.sim_bind_group_key = SimBindGroupKey::INVALID;
+ }
+
+ /// Return the cached particle@1 bind group for the simulation (init and
+ /// update) passes.
+ ///
+ /// This is the per-buffer bind group at binding @1 which binds all
+ /// per-buffer resources shared by all effect instances batched in a single
+ /// buffer. The bind group is created by
+ /// [`create_particle_sim_bind_group()`], and cached until a call to
+ /// [`invalidate_particle_sim_bind_groups()`] clears the
+ /// cached reference.
+ ///
+ /// [`create_particle_sim_bind_group()`]: self::ParticleSlab::create_particle_sim_bind_group
+ /// [`invalidate_particle_sim_bind_groups()`]: self::ParticleSlab::invalidate_particle_sim_bind_groups
+ pub fn particle_sim_bind_group(&self) -> Option<&BindGroup> {
+ self.sim_bind_group.as_ref()
+ }
+
+ /// Try to recycle a free slice to store `size` items.
+ fn pop_free_slice(&mut self, size: u32) -> Option<Range<u32>> {
+ if self.free_slices.is_empty() {
+ return None;
+ }
+
+ struct BestRange {
+ range: Range<u32>,
+ capacity: u32,
+ index: usize,
+ }
+
+ let mut result = BestRange {
+ range: 0..0, // marker for "invalid"
+ capacity: u32::MAX,
+ index: usize::MAX,
+ };
+ for (index, slice) in self.free_slices.iter().enumerate() {
+ let capacity = slice.end - slice.start;
+ if size > capacity {
+ continue;
+ }
+ if capacity < result.capacity {
+ result = BestRange {
+ range: slice.clone(),
+ capacity,
+ index,
+ };
+ }
+ }
+ if !result.range.is_empty() {
+ if result.capacity > size {
+ // split
+ let start = result.range.start;
+ let used_end = start + size;
+ let free_end = result.range.end;
+ let range = start..used_end;
+ self.free_slices[result.index] = used_end..free_end;
+ Some(range)
+ } else {
+ // recycle entirely
+ self.free_slices.remove(result.index);
+ Some(result.range)
+ }
+ } else {
+ None
+ }
+ }
+
+ /// Allocate a new entry in the slab to store the particles of a single
+ /// effect.
+ pub fn allocate(&mut self, capacity: u32) -> Option<SlabSliceRef> {
+ trace!("ParticleSlab::allocate(capacity={})", capacity);
+
+ if capacity > self.capacity {
+ return None;
+ }
+
+ let range = if let Some(range) = self.pop_free_slice(capacity) {
+ range
+ } else {
+ let new_size = self.used_size.checked_add(capacity).unwrap();
+ if new_size <= self.capacity {
+ let range = self.used_size..new_size;
+ self.used_size = new_size;
+ range
+ } else {
+ if self.used_size == 0 {
+ warn!(
+ "Cannot allocate slice of size {} in particle slab of capacity {}.",
+ capacity, self.capacity
+ );
+ }
+ return None;
+ }
+ };
+
+ trace!("-> allocated slice {:?}", range);
+ Some(SlabSliceRef {
+ range,
+ particle_layout: self.particle_layout.clone(),
+ })
+ }
+
+ /// Free an allocated slice, and if this was the last allocated slice also
+ /// free the buffer.
+ pub fn free_slice(&mut self, slice: SlabSliceRef) -> SlabState {
+ // If slice is at the end of the buffer, reduce total used size
+ if slice.range.end == self.used_size {
+ self.used_size = slice.range.start;
+ // Check other free slices to further reduce used size and drain the free slice
+ // list
+ while let Some(free_slice) = self.free_slices.last() {
+ if free_slice.end == self.used_size {
+ self.used_size = free_slice.start;
+ self.free_slices.pop();
+ } else {
+ break;
+ }
+ }
+ if self.used_size == 0 {
+ assert!(self.free_slices.is_empty());
+ // The buffer is not used anymore, free it too
+ SlabState::Free
+ } else {
+ // There are still some slices used, the last one of which ends at
+ // self.used_size
+ SlabState::Used
+ }
+ } else {
+ // Free slice is not at end; insert it in free list
+ let range = slice.range;
+ match self.free_slices.binary_search_by(|s| {
+ if s.end <= range.start {
+ Ordering::Less
+ } else if s.start >= range.end {
+ Ordering::Greater
+ } else {
+ Ordering::Equal
+ }
+ }) {
+ Ok(_) => warn!("Range {:?} already present in free list!", range),
+ Err(index) => self.free_slices.insert(index, range),
+ }
+ SlabState::Used
+ }
+ }
+
+ /// Check whether this slab is compatible with the given asset.
+ ///
+ /// This allows determining whether an instance of the effect can be stored
+ /// inside this slab.
+ pub fn is_compatible(
+ &self,
+ handle: &Handle<EffectAsset>,
+ _particle_layout: &ParticleLayout,
+ ) -> bool {
+ // TODO - replace with check particle layout is compatible to allow tighter
+ // packing in less buffers, and update in the less dispatch calls
+ *handle == self.asset
+ }
+}
+
+/// A single cached effect in the [`EffectCache`].
+#[derive(Debug, Component)]
+pub(crate) struct CachedEffect {
+ /// ID of the slab of the slab storing the particles for this effect in the
+ /// [`EffectCache`].
+ pub slab_id: SlabId,
+ /// The allocated effect slice within that slab.
+ pub slice: SlabSliceRef,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum AnyDrawIndirectArgs {
+ /// Args of a non-indexed draw call.
+ NonIndexed(GpuDrawIndirectArgs),
+ /// Args of an indexed draw call.
+ Indexed(GpuDrawIndexedIndirectArgs),
+}
+
+impl AnyDrawIndirectArgs {
+ /// Create from a vertex buffer slice and an optional index buffer one.
+ pub fn from_slices(
+ vertex_slice: &MeshBufferSlice<'_>,
+ index_slice: Option<&MeshBufferSlice<'_>>,
+ ) -> Self {
+ if let Some(index_slice) = index_slice {
+ Self::Indexed(GpuDrawIndexedIndirectArgs {
+ index_count: index_slice.range.len() as u32,
+ instance_count: 0,
+ first_index: index_slice.range.start,
+ base_vertex: vertex_slice.range.start as i32,
+ first_instance: 0,
+ })
+ } else {
+ Self::NonIndexed(GpuDrawIndirectArgs {
+ vertex_count: vertex_slice.range.len() as u32,
+ instance_count: 0,
+ first_vertex: vertex_slice.range.start,
+ first_instance: 0,
+ })
+ }
+ }
+
+ /// Check if this args are for an indexed draw call.
+ #[inline(always)]
+ #[allow(dead_code)]
+ pub fn is_indexed(&self) -> bool {
+ matches!(*self, Self::Indexed(..))
+ }
+
+ /// Bit-cast the args to the row entry of the GPU buffer.
+ ///
+ /// If non-indexed, this returns an indexed struct bit-cast from the actual
+ /// non-indexed one, ready for GPU upload.
+ pub fn bitcast_to_row_entry(&self) -> GpuDrawIndexedIndirectArgs {
+ match self {
+ AnyDrawIndirectArgs::NonIndexed(args) => GpuDrawIndexedIndirectArgs {
+ index_count: args.vertex_count,
+ instance_count: args.instance_count,
+ first_index: args.first_vertex,
+ base_vertex: args.first_instance as i32,
+ first_instance: 0,
+ },
+ AnyDrawIndirectArgs::Indexed(args) => *args,
+ }
+ }
+}
+
+impl From<GpuDrawIndirectArgs> for AnyDrawIndirectArgs {
+ fn from(args: GpuDrawIndirectArgs) -> Self {
+ Self::NonIndexed(args)
+ }
+}
+
+impl From<GpuDrawIndexedIndirectArgs> for AnyDrawIndirectArgs {
+ fn from(args: GpuDrawIndexedIndirectArgs) -> Self {
+ Self::Indexed(args)
+ }
+}
+
+/// Index of a row (entry) into the [`BufferTable`] storing the indirect draw
+/// args of a single draw call.
+#[derive(Debug, Clone, Copy, Component)]
+pub(crate) struct CachedDrawIndirectArgs {
+ pub row: BufferTableId,
+ pub args: AnyDrawIndirectArgs,
+}
+
+impl Default for CachedDrawIndirectArgs {
+ fn default() -> Self {
+ Self {
+ row: BufferTableId::INVALID,
+ args: AnyDrawIndirectArgs::NonIndexed(default()),
+ }
+ }
+}
+
+impl CachedDrawIndirectArgs {
+ /// Check if the index is valid.
+ ///
+ /// An invalid index doesn't correspond to any allocated args entry. A valid
+ /// one may, but note that the args entry in the buffer may have been freed
+ /// already with this index. There's no mechanism to detect reuse either.
+ #[inline(always)]
+ #[allow(dead_code)]
+ pub fn is_valid(&self) -> bool {
+ self.get_row_raw().is_valid()
+ }
+
+ /// Check if this row index refers to an indexed draw args entry.
+ #[inline(always)]
+ #[allow(dead_code)]
+ pub fn is_indexed(&self) -> bool {
+ self.args.is_indexed()
+ }
+
+ /// Get the raw index value.
+ ///
+ /// Retrieve the raw index value, losing the discriminant between indexed
+ /// and non-indexed draw. This is useful when storing the index value into a
+ /// GPU buffer. The rest of the time, prefer retaining the typed enum for
+ /// safety.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the index is invalid, whether indexed or non-indexed.
+ pub fn get_row(&self) -> BufferTableId {
+ let idx = self.get_row_raw();
+ assert!(idx.is_valid());
+ idx
+ }
+
+ #[inline(always)]
+ fn get_row_raw(&self) -> BufferTableId {
+ self.row
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+struct ParticleBindGroupLayoutKey {
+ pub min_binding_size: NonZeroU32,
+ pub parent_min_binding_size: Option<NonZeroU32>,
+}
+
+/// Cache for effect instances sharing common GPU data structures.
+#[derive(Resource)]
+pub struct EffectCache {
+ /// Render device the GPU resources (buffers) are allocated from.
+ render_device: RenderDevice,
+ /// Collection of particle slabs managed by this cache. Some slabs might be
+ /// `None` if the entry is not used. Since the slabs are referenced
+ /// by index, we cannot move them once they're allocated.
+ particle_slabs: Vec<Option<ParticleSlab>>,
+ /// Cache of bind group layouts for the particle@1 bind groups of the
+ /// simulation passes (init and update). Since all bindings depend only
+ /// on buffers managed by the [`EffectCache`], we also cache the layouts
+ /// here for convenience.
+ particle_bind_group_layout_descs:
+ HashMap<ParticleBindGroupLayoutKey, BindGroupLayoutDescriptor>,
+ /// Cache of bind group layouts for the metadata@3 bind group of the init
+ /// pass.
+ metadata_init_bind_group_layout_desc: [Option<BindGroupLayoutDescriptor>; 2],
+ /// Cache of bind group layouts for the metadata@3 bind group of the
+ /// updatepass.
+ metadata_update_bind_group_layout_descs: HashMap<u32, BindGroupLayoutDescriptor>,
+}
+
+impl EffectCache {
+ /// Create a new empty cache.
+ pub fn new(device: RenderDevice) -> Self {
+ Self {
+ render_device: device,
+ particle_slabs: vec![],
+ particle_bind_group_layout_descs: default(),
+ metadata_init_bind_group_layout_desc: [None, None],
+ metadata_update_bind_group_layout_descs: default(),
+ }
+ }
+
+ /// Get all the particle slab slots. Unallocated slots are `None`. This can
+ /// be indexed by the slab index.
+ #[allow(dead_code)]
+ #[inline]
+ pub fn slabs(&self) -> &[Option<ParticleSlab>] {
+ &self.particle_slabs
+ }
+
+ /// Get all the particle slab slots. Unallocated slots are `None`. This can
+ /// be indexed by the slab ID.
+ #[allow(dead_code)]
+ #[inline]
+ pub fn slabs_mut(&mut self) -> &mut [Option<ParticleSlab>] {
+ &mut self.particle_slabs
+ }
+
+ /// Fetch a specific slab by ID.
+ #[inline]
+ pub fn get_slab(&self, slab_id: &SlabId) -> Option<&ParticleSlab> {
+ self.particle_slabs.get(slab_id.0 as usize)?.as_ref()
+ }
+
+ /// Fetch a specific buffer by ID.
+ #[allow(dead_code)]
+ #[inline]
+ pub fn get_slab_mut(&mut self, slab_id: &SlabId) -> Option<&mut ParticleSlab> {
+ self.particle_slabs.get_mut(slab_id.0 as usize)?.as_mut()
+ }
+
+ /// Invalidate all the particle@1 bind group for all buffers.
+ ///
+ /// This iterates over all valid buffers and calls
+ /// [`ParticleSlab::invalidate_particle_sim_bind_group()`] on each one.
+ #[allow(dead_code)] // FIXME - review this...
+ pub fn invalidate_particle_sim_bind_groups(&mut self) {
+ for buffer in self.particle_slabs.iter_mut().flatten() {
+ buffer.invalidate_particle_sim_bind_group();
+ }
+ }
+
+ /// Insert a new effect instance in the cache.
+ pub fn insert(
+ &mut self,
+ asset: Handle<EffectAsset>,
+ capacity: u32,
+ particle_layout: &ParticleLayout,
+ ) -> CachedEffect {
+ trace!("Inserting new effect into cache: capacity={capacity}");
+ let (slab_id, slice) = self
+ .particle_slabs
+ .iter_mut()
+ .enumerate()
+ .find_map(|(slab_index, maybe_slab)| {
+ // Ignore empty (non-allocated) entries as we're trying to fit the new allocation inside an existing slab.
+ let Some(slab) = maybe_slab else { return None; };
+
+ // The slab must be compatible with the effect's layout, otherwise ignore it.
+ if !slab.is_compatible(&asset, particle_layout) {
+ return None;
+ }
+
+ // Try to allocate a slice into the slab
+ slab
+ .allocate(capacity)
+ .map(|slice| (SlabId::new(slab_index as u32), slice))
+ })
+ .unwrap_or_else(|| {
+ // Cannot find any suitable slab; allocate a new one
+ let index = self.particle_slabs.iter().position(|buf| buf.is_none()).unwrap_or(self.particle_slabs.len());
+ let byte_size = capacity.checked_mul(particle_layout.min_binding_size().get() as u32).unwrap_or_else(|| panic!(
+ "Effect size overflow: capacity={:?} particle_layout={:?} item_size={}",
+ capacity, particle_layout, particle_layout.min_binding_size().get()
+ ));
+ trace!(
+ "Creating new particle slab #{} for effect {:?} (capacity={:?}, particle_layout={:?} item_size={}, byte_size={})",
+ index,
+ asset,
+ capacity,
+ particle_layout,
+ particle_layout.min_binding_size().get(),
+ byte_size
+ );
+ let slab_id = SlabId::new(index as u32);
+ let mut slab = ParticleSlab::new(
+ slab_id,
+ asset,
+ capacity,
+ particle_layout.clone(),
+ &self.render_device,
+ );
+ let slice_ref = slab.allocate(capacity).unwrap();
+ if index >= self.particle_slabs.len() {
+ self.particle_slabs.push(Some(slab));
+ } else {
+ debug_assert!(self.particle_slabs[index].is_none());
+ self.particle_slabs[index] = Some(slab);
+ }
+ (slab_id, slice_ref)
+ });
+
+ let slice = SlabSliceRef {
+ range: slice.range.clone(),
+ particle_layout: slice.particle_layout,
+ };
+
+ trace!(
+ "Insert effect slab_id={} slice={}B particle_layout={:?}",
+ slab_id.0,
+ slice.particle_layout.min_binding_size().get(),
+ slice.particle_layout,
+ );
+ CachedEffect { slab_id, slice }
+ }
+
+ /// Remove an effect from the cache. If this was the last effect, drop the
+ /// underlying buffer and return the index of the dropped buffer.
+ pub fn remove(&mut self, cached_effect: &CachedEffect) -> Result<SlabState, ()> {
+ // Resolve the buffer by index
+ let Some(maybe_buffer) = self
+ .particle_slabs
+ .get_mut(cached_effect.slab_id.0 as usize)
+ else {
+ return Err(());
+ };
+ let Some(buffer) = maybe_buffer.as_mut() else {
+ return Err(());
+ };
+
+ // Free the slice inside the resolved buffer
+ if buffer.free_slice(cached_effect.slice.clone()) == SlabState::Free {
+ *maybe_buffer = None;
+ return Ok(SlabState::Free);
+ }
+
+ Ok(SlabState::Used)
+ }
+
+ //
+ // Bind group layouts
+ //
+
+ /// Ensure a bind group layout exists for the bind group @1 ("particles")
+ /// for use with the given min binding sizes.
+ pub fn ensure_particle_bind_group_layout_desc(
+ &mut self,
+ min_binding_size: NonZeroU32,
+ parent_min_binding_size: Option<NonZeroU32>,
+ ) -> &BindGroupLayoutDescriptor {
+ // FIXME - This "ensure" pattern means we never de-allocate entries. This is
+ // probably fine, because there's a limited number of realistic combinations,
+ // but could cause wastes if e.g. loading widely different scenes.
+ let key = ParticleBindGroupLayoutKey {
+ min_binding_size,
+ parent_min_binding_size,
+ };
+ self.particle_bind_group_layout_descs
+ .entry(key)
+ .or_insert_with(|| {
+ trace!("Creating new particle sim bind group @1 for min_binding_size={} parent_min_binding_size={:?}", min_binding_size, parent_min_binding_size);
+ create_particle_sim_bind_group_layout_desc(
+ min_binding_size,
+ parent_min_binding_size,
+ )
+ })
+ }
+
+ /// Get the bind group layout for the bind group @1 ("particles") for use
+ /// with the given min binding sizes.
+ pub fn particle_bind_group_layout_desc(
+ &self,
+ min_binding_size: NonZeroU32,
+ parent_min_binding_size: Option<NonZeroU32>,
+ ) -> Option<&BindGroupLayoutDescriptor> {
+ let key = ParticleBindGroupLayoutKey {
+ min_binding_size,
+ parent_min_binding_size,
+ };
+ self.particle_bind_group_layout_descs.get(&key)
+ }
+
+ /// Ensure a bind group layout exists for the metadata@3 bind group of
+ /// the init pass.
+ pub fn ensure_metadata_init_bind_group_layout_desc(&mut self, consume_gpu_spawn_events: bool) {
+ let layout =
+ &mut self.metadata_init_bind_group_layout_desc[consume_gpu_spawn_events as usize];
+ if layout.is_none() {
+ *layout = Some(create_metadata_init_bind_group_layout_desc(
+ consume_gpu_spawn_events,
+ ));
+ }
+ }
+
+ /// Get the bind group layout for the metadata@3 bind group of the init
+ /// pass.
+ pub fn metadata_init_bind_group_layout_desc(
+ &self,
+ consume_gpu_spawn_events: bool,
+ ) -> Option<&BindGroupLayoutDescriptor> {
+ self.metadata_init_bind_group_layout_desc[consume_gpu_spawn_events as usize].as_ref()
+ }
+
+ /// Ensure a bind group layout exists for the metadata@3 bind group of
+ /// the update pass.
+ pub fn ensure_metadata_update_bind_group_layout_desc(&mut self, num_event_buffers: u32) {
+ self.metadata_update_bind_group_layout_descs
+ .entry(num_event_buffers)
+ .or_insert_with(|| create_metadata_update_bind_group_layout_desc(num_event_buffers));
+ }
+
+ /// Get the bind group layout for the metadata@3 bind group of the
+ /// update pass.
+ pub fn metadata_update_bind_group_layout_desc(
+ &self,
+ num_event_buffers: u32,
+ ) -> Option<&BindGroupLayoutDescriptor> {
+ self.metadata_update_bind_group_layout_descs
+ .get(&num_event_buffers)
+ }
+
+ //
+ // Bind groups
+ //
+
+ /// Get the "particle" bind group for the simulation (init and update)
+ /// passes a cached effect stored in a given GPU particle buffer.
+ pub fn particle_sim_bind_group(&self, slab_id: &SlabId) -> Option<&BindGroup> {
+ self.get_slab(slab_id)
+ .and_then(|slab| slab.particle_sim_bind_group())
+ }
+
+ pub fn create_particle_sim_bind_group(
+ &mut self,
+ slab_id: &SlabId,
+ render_device: &RenderDevice,
+ min_binding_size: NonZeroU32,
+ parent_min_binding_size: Option<NonZeroU32>,
+ parent_binding_source: Option<&BufferBindingSource>,
+ pipeline_cache: &PipelineCache,
+ ) -> Result<(), ()> {
+ // Create the bind group
+ let layout = self
+ .ensure_particle_bind_group_layout_desc(min_binding_size, parent_min_binding_size)
+ .clone();
+ let slot = self
+ .particle_slabs
+ .get_mut(slab_id.index() as usize)
+ .ok_or(())?;
+ let effect_buffer = slot.as_mut().ok_or(())?;
+ effect_buffer.create_particle_sim_bind_group(
+ &pipeline_cache.get_bind_group_layout(&layout),
+ slab_id,
+ render_device,
+ parent_binding_source,
+ );
+ Ok(())
+ }
+}
+
+/// Create the bind group layout for the "particle" group (@1) of the init and
+/// update passes.
+fn create_particle_sim_bind_group_layout_desc(
+ particle_layout_min_binding_size: NonZeroU32,
+ parent_particle_layout_min_binding_size: Option<NonZeroU32>,
+) -> BindGroupLayoutDescriptor {
+ let mut entries = Vec::with_capacity(3);
+
+ // @group(1) @binding(0) var<storage, read_write> particle_buffer :
+ // ParticleBuffer
+ entries.push(BindGroupLayoutEntry {
+ binding: 0,
+ visibility: ShaderStages::COMPUTE,
+ ty: BindingType::Buffer {
+ ty: BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: Some(particle_layout_min_binding_size.into()),
+ },
+ count: None,
+ });
+
+ // @group(1) @binding(1) var<storage, read_write> indirect_buffer :
+ // IndirectBuffer
+ entries.push(BindGroupLayoutEntry {
+ binding: 1,
+ visibility: ShaderStages::COMPUTE,
+ ty: BindingType::Buffer {
+ ty: BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: Some(GpuIndirectIndex::SHADER_SIZE),
+ },
+ count: None,
+ });
+
+ // @group(1) @binding(2) var<storage, read> parent_particle_buffer :
+ // ParentParticleBuffer;
+ if let Some(min_binding_size) = parent_particle_layout_min_binding_size {
+ entries.push(BindGroupLayoutEntry {
+ binding: 2,
+ visibility: ShaderStages::COMPUTE,
+ ty: BindingType::Buffer {
+ ty: BufferBindingType::Storage { read_only: true },
+ has_dynamic_offset: false,
+ min_binding_size: Some(min_binding_size.into()),
+ },
+ count: None,
+ });
+ }
+
+ let hash = calc_hash(&entries);
+ let label = format!("hanabi:bgl:sim:particles_{:016X}", hash);
+ trace!(
+ "Creating particle bind group layout '{}' for init pass with {} entries. (parent_buffer:{})",
+ label,
+ entries.len(),
+ parent_particle_layout_min_binding_size.is_some(),
+ );
+ BindGroupLayoutDescriptor::new(label, &entries)
+}
+
+/// Create the bind group layout for the metadata@3 bind group of the init pass.
+fn create_metadata_init_bind_group_layout_desc(
+ consume_gpu_spawn_events: bool,
+) -> BindGroupLayoutDescriptor {
+ let mut entries = Vec::with_capacity(3);
+
+ // @group(3) @binding(0) var<storage, read_write> effect_metadatas :
+ // array<EffectMetadata>
+ entries.push(BindGroupLayoutEntry {
+ binding: 0,
+ visibility: ShaderStages::COMPUTE,
+ ty: BindingType::Buffer {
+ ty: BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: Some(GpuEffectMetadata::SHADER_SIZE),
+ },
+ count: None,
+ });
+
+ if consume_gpu_spawn_events {
+ // @group(3) @binding(1) var<storage, read> child_info_buffer : ChildInfoBuffer;
+ entries.push(BindGroupLayoutEntry {
+ binding: 1,
+ visibility: ShaderStages::COMPUTE,
+ ty: BindingType::Buffer {
+ ty: BufferBindingType::Storage { read_only: true },
+ has_dynamic_offset: false,
+ min_binding_size: Some(GpuChildInfo::min_size()),
+ },
+ count: None,
+ });
+
+ // @group(3) @binding(2) var<storage, read> event_buffer : EventBuffer;
+ entries.push(BindGroupLayoutEntry {
+ binding: 2,
+ visibility: ShaderStages::COMPUTE,
+ ty: BindingType::Buffer {
+ ty: BufferBindingType::Storage { read_only: true },
+ has_dynamic_offset: false,
+ min_binding_size: Some(NonZeroU64::new(4).unwrap()),
+ },
+ count: None,
+ });
+ }
+
+ let hash = calc_hash(&entries);
+ let label = format!(
+ "hanabi:bgl:init:metadata@3_{}{:016X}",
+ if consume_gpu_spawn_events {
+ "events"
+ } else {
+ "noevent"
+ },
+ hash
+ );
+ trace!(
+ "Creating metadata@3 bind group layout '{}' for init pass with {} entries. (consume_gpu_spawn_events:{})",
+ label,
+ entries.len(),
+ consume_gpu_spawn_events,
+ );
+ BindGroupLayoutDescriptor::new(label, &entries)
+}
+
+/// Create the bind group layout for the metadata@3 bind group of the update
+/// pass.
+fn create_metadata_update_bind_group_layout_desc(
+ num_event_buffers: u32,
+) -> BindGroupLayoutDescriptor {
+ let mut entries = Vec::with_capacity(num_event_buffers as usize + 2);
+
+ // @group(3) @binding(0) var<storage, read_write> effect_metadatas :
+ // array<EffectMetadata>
+ entries.push(BindGroupLayoutEntry {
+ binding: 0,
+ visibility: ShaderStages::COMPUTE,
+ ty: BindingType::Buffer {
+ ty: BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: Some(GpuEffectMetadata::SHADER_SIZE),
+ },
+ count: None,
+ });
+
+ if num_event_buffers > 0 {
+ // @group(3) @binding(1) var<storage, read_write> child_infos : array<ChildInfo,
+ // N>;
+ entries.push(BindGroupLayoutEntry {
+ binding: 1,
+ visibility: ShaderStages::COMPUTE,
+ ty: BindingType::Buffer {
+ ty: BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: Some(GpuChildInfo::min_size()),
+ },
+ count: None,
+ });
+
+ for i in 0..num_event_buffers {
+ // @group(3) @binding(2+i) var<storage, read_write> event_buffer_#i :
+ // EventBuffer;
+ entries.push(BindGroupLayoutEntry {
+ binding: 2 + i,
+ visibility: ShaderStages::COMPUTE,
+ ty: BindingType::Buffer {
+ ty: BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: Some(NonZeroU64::new(4).unwrap()),
+ },
+ count: None,
+ });
+ }
+ }
+
+ let hash = calc_hash(&entries);
+ let label = format!("hanabi:bgl:update:metadata_{:016X}", hash);
+ trace!(
+ "Creating particle bind group layout '{}' for init update with {} entries. (num_event_buffers:{})",
+ label,
+ entries.len(),
+ num_event_buffers,
+ );
+ BindGroupLayoutDescriptor::new(label, &entries)
+}
+
+#[cfg(all(test, feature = "gpu_tests"))]
+mod gpu_tests {
+ use std::borrow::Cow;
+
+ use bevy::math::Vec4;
+
+ use super::*;
+ use crate::{
+ graph::{Value, VectorValue},
+ test_utils::MockRenderer,
+ Attribute, AttributeInner,
+ };
+
+ #[test]
+ fn effect_slice_ord() {
+ let particle_layout = ParticleLayout::new().append(Attribute::POSITION).build();
+ let slice1 = EffectSlice {
+ slice: 0..32,
+ slab_id: SlabId::new(1),
+ particle_layout: particle_layout.clone(),
+ };
+ let slice2 = EffectSlice {
+ slice: 32..64,
+ slab_id: SlabId::new(1),
+ particle_layout: particle_layout.clone(),
+ };
+ assert!(slice1 < slice2);
+ assert!(slice1 <= slice2);
+ assert!(slice2 > slice1);
+ assert!(slice2 >= slice1);
+
+ let slice3 = EffectSlice {
+ slice: 0..32,
+ slab_id: SlabId::new(0),
+ particle_layout,
+ };
+ assert!(slice3 < slice1);
+ assert!(slice3 < slice2);
+ assert!(slice1 > slice3);
+ assert!(slice2 > slice3);
+ }
+
+ const F4A_INNER: &AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("F4A"),
+ Value::Vector(VectorValue::new_vec4(Vec4::ONE)),
+ );
+ const F4B_INNER: &AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("F4B"),
+ Value::Vector(VectorValue::new_vec4(Vec4::ONE)),
+ );
+ const F4C_INNER: &AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("F4C"),
+ Value::Vector(VectorValue::new_vec4(Vec4::ONE)),
+ );
+ const F4D_INNER: &AttributeInner = &AttributeInner::new(
+ Cow::Borrowed("F4D"),
+ Value::Vector(VectorValue::new_vec4(Vec4::ONE)),
+ );
+
+ const F4A: Attribute = Attribute(F4A_INNER);
+ const F4B: Attribute = Attribute(F4B_INNER);
+ const F4C: Attribute = Attribute(F4C_INNER);
+ const F4D: Attribute = Attribute(F4D_INNER);
+
+ #[test]
+ fn slice_ref() {
+ let l16 = ParticleLayout::new().append(F4A).build();
+ assert_eq!(16, l16.size());
+ let l32 = ParticleLayout::new().append(F4A).append(F4B).build();
+ assert_eq!(32, l32.size());
+ let l48 = ParticleLayout::new()
+ .append(F4A)
+ .append(F4B)
+ .append(F4C)
+ .build();
+ assert_eq!(48, l48.size());
+ for (range, particle_layout, len, byte_size) in [
+ (0..0, &l16, 0, 0),
+ (0..16, &l16, 16, 16 * 16),
+ (0..16, &l32, 16, 16 * 32),
+ (240..256, &l48, 16, 16 * 48),
+ ] {
+ let sr = SlabSliceRef {
+ range,
+ particle_layout: particle_layout.clone(),
+ };
+ assert_eq!(sr.len(), len);
+ assert_eq!(sr.byte_size(), byte_size);
+ }
+ }
+
+ #[test]
+ fn effect_buffer() {
+ let renderer = MockRenderer::new();
+ let render_device = renderer.device();
+
+ let l64 = ParticleLayout::new()
+ .append(F4A)
+ .append(F4B)
+ .append(F4C)
+ .append(F4D)
+ .build();
+ assert_eq!(64, l64.size());
+
+ let asset = Handle::<EffectAsset>::default();
+ let capacity = 4096;
+ let mut buffer = ParticleSlab::new(
+ SlabId::new(42),
+ asset,
+ capacity,
+ l64.clone(),
+ &render_device,
+ );
+
+ assert_eq!(buffer.capacity, capacity.max(ParticleSlab::MIN_CAPACITY));
+ assert_eq!(64, buffer.particle_layout.size());
+ assert_eq!(64, buffer.particle_layout.min_binding_size().get());
+ assert_eq!(0, buffer.used_size);
+ assert!(buffer.free_slices.is_empty());
+
+ assert_eq!(None, buffer.allocate(buffer.capacity + 1));
+
+ let mut offset = 0;
+ let mut slices = vec![];
+ for size in [32, 128, 55, 148, 1, 2048, 42] {
+ let slice = buffer.allocate(size);
+ assert!(slice.is_some());
+ let slice = slice.unwrap();
+ assert_eq!(64, slice.particle_layout.size());
+ assert_eq!(64, buffer.particle_layout.min_binding_size().get());
+ assert_eq!(offset..offset + size, slice.range);
+ slices.push(slice);
+ offset += size;
+ }
+ assert_eq!(offset, buffer.used_size);
+
+ assert_eq!(SlabState::Used, buffer.free_slice(slices[2].clone()));
+ assert_eq!(1, buffer.free_slices.len());
+ let free_slice = &buffer.free_slices[0];
+ assert_eq!(160..215, *free_slice);
+ assert_eq!(offset, buffer.used_size); // didn't move
+
+ assert_eq!(SlabState::Used, buffer.free_slice(slices[3].clone()));
+ assert_eq!(SlabState::Used, buffer.free_slice(slices[4].clone()));
+ assert_eq!(SlabState::Used, buffer.free_slice(slices[5].clone()));
+ assert_eq!(4, buffer.free_slices.len());
+ assert_eq!(offset, buffer.used_size); // didn't move
+
+ // this will collapse all the way to slices[1], the highest allocated
+ assert_eq!(SlabState::Used, buffer.free_slice(slices[6].clone()));
+ assert_eq!(0, buffer.free_slices.len()); // collapsed
+ assert_eq!(160, buffer.used_size); // collapsed
+
+ assert_eq!(SlabState::Used, buffer.free_slice(slices[0].clone()));
+ assert_eq!(1, buffer.free_slices.len());
+ assert_eq!(160, buffer.used_size); // didn't move
+
+ // collapse all, and free buffer
+ assert_eq!(SlabState::Free, buffer.free_slice(slices[1].clone()));
+ assert_eq!(0, buffer.free_slices.len());
+ assert_eq!(0, buffer.used_size); // collapsed and empty
+ }
+
+ #[test]
+ fn pop_free_slice() {
+ let renderer = MockRenderer::new();
+ let render_device = renderer.device();
+
+ let l64 = ParticleLayout::new()
+ .append(F4A)
+ .append(F4B)
+ .append(F4C)
+ .append(F4D)
+ .build();
+ assert_eq!(64, l64.size());
+
+ let asset = Handle::<EffectAsset>::default();
+ let capacity = 2048; // ParticleSlab::MIN_CAPACITY;
+ assert!(capacity >= 2048); // otherwise the logic below breaks
+ let mut buffer = ParticleSlab::new(
+ SlabId::new(42),
+ asset,
+ capacity,
+ l64.clone(),
+ &render_device,
+ );
+
+ let slice0 = buffer.allocate(32);
+ assert!(slice0.is_some());
+ let slice0 = slice0.unwrap();
+ assert_eq!(slice0.range, 0..32);
+ assert!(buffer.free_slices.is_empty());
+
+ let slice1 = buffer.allocate(1024);
+ assert!(slice1.is_some());
+ let slice1 = slice1.unwrap();
+ assert_eq!(slice1.range, 32..1056);
+ assert!(buffer.free_slices.is_empty());
+
+ let state = buffer.free_slice(slice0);
+ assert_eq!(state, SlabState::Used);
+ assert_eq!(buffer.free_slices.len(), 1);
+ assert_eq!(buffer.free_slices[0], 0..32);
+
+ // Try to allocate a slice larger than slice0, such that slice0 cannot be
+ // recycled, and instead the new slice has to be appended after all
+ // existing ones.
+ let slice2 = buffer.allocate(64);
+ assert!(slice2.is_some());
+ let slice2 = slice2.unwrap();
+ assert_eq!(slice2.range.start, slice1.range.end); // after slice1
+ assert_eq!(slice2.range, 1056..1120);
+ assert_eq!(buffer.free_slices.len(), 1);
+
+ // Now allocate a small slice that fits, to recycle (part of) slice0.
+ let slice3 = buffer.allocate(16);
+ assert!(slice3.is_some());
+ let slice3 = slice3.unwrap();
+ assert_eq!(slice3.range, 0..16);
+ assert_eq!(buffer.free_slices.len(), 1); // split
+ assert_eq!(buffer.free_slices[0], 16..32);
+
+ // Allocate a second small slice that fits exactly the left space, completely
+ // recycling
+ let slice4 = buffer.allocate(16);
+ assert!(slice4.is_some());
+ let slice4 = slice4.unwrap();
+ assert_eq!(slice4.range, 16..32);
+ assert!(buffer.free_slices.is_empty()); // recycled
+ }
+
+ #[test]
+ fn effect_cache() {
+ let renderer = MockRenderer::new();
+ let render_device = renderer.device();
+
+ let l32 = ParticleLayout::new().append(F4A).append(F4B).build();
+ assert_eq!(32, l32.size());
+
+ let mut effect_cache = EffectCache::new(render_device);
+ assert_eq!(effect_cache.slabs().len(), 0);
+
+ let asset = Handle::<EffectAsset>::default();
+ let capacity = ParticleSlab::MIN_CAPACITY;
+ let item_size = l32.size();
+
+ // Insert an effect
+ let effect1 = effect_cache.insert(asset.clone(), capacity, &l32);
+ //assert!(effect1.is_valid());
+ let slice1 = &effect1.slice;
+ assert_eq!(slice1.len(), capacity);
+ assert_eq!(
+ slice1.particle_layout.min_binding_size().get() as u32,
+ item_size
+ );
+ assert_eq!(slice1.range, 0..capacity);
+ assert_eq!(effect_cache.slabs().len(), 1);
+
+ // Insert a second copy of the same effect
+ let effect2 = effect_cache.insert(asset.clone(), capacity, &l32);
+ //assert!(effect2.is_valid());
+ let slice2 = &effect2.slice;
+ assert_eq!(slice2.len(), capacity);
+ assert_eq!(
+ slice2.particle_layout.min_binding_size().get() as u32,
+ item_size
+ );
+ assert_eq!(slice2.range, 0..capacity);
+ assert_eq!(effect_cache.slabs().len(), 2);
+
+ // Remove the first effect instance
+ let buffer_state = effect_cache.remove(&effect1).unwrap();
+ // Note: currently batching is disabled, so each instance has its own buffer,
+ // which becomes unused once the instance is destroyed.
+ assert_eq!(buffer_state, SlabState::Free);
+ assert_eq!(effect_cache.slabs().len(), 2);
+ {
+ let slabs = effect_cache.slabs();
+ assert!(slabs[0].is_none());
+ assert!(slabs[1].is_some()); // id2
+ }
+
+ // Regression #60
+ let effect3 = effect_cache.insert(asset, capacity, &l32);
+ //assert!(effect3.is_valid());
+ let slice3 = &effect3.slice;
+ assert_eq!(slice3.len(), capacity);
+ assert_eq!(
+ slice3.particle_layout.min_binding_size().get() as u32,
+ item_size
+ );
+ assert_eq!(slice3.range, 0..capacity);
+ // Note: currently batching is disabled, so each instance has its own buffer.
+ assert_eq!(effect_cache.slabs().len(), 2);
+ {
+ let slabs = effect_cache.slabs();
+ assert!(slabs[0].is_some()); // id3
+ assert!(slabs[1].is_some()); // id2
+ }
+ }
+}
diff --git a/vendor/bevy_hanabi/src/render/event.rs b/vendor/bevy_hanabi/src/render/event.rs
new file mode 100644
index 00000000..cfe47bbb
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/event.rs
@@ -0,0 +1,657 @@
+use std::{num::NonZeroU64, ops::Range};
+
+use bevy::{
+ ecs::{
+ lifecycle::Remove,
+ observer::On,
+ query::{With, Without},
+ system::{Commands, Query},
+ },
+ log::{error, trace},
+ prelude::{Component, Entity, ResMut, Resource},
+ render::{
+ render_resource::{
+ binding_types::storage_buffer, BindGroup, BindGroupEntries, BindGroupLayout,
+ BindGroupLayoutEntries, Buffer, ShaderSize as _, ShaderType,
+ },
+ renderer::{RenderDevice, RenderQueue},
+ },
+};
+use bytemuck::{Pod, Zeroable};
+use thiserror::Error;
+#[cfg(debug_assertions)]
+use wgpu::util::BufferInitDescriptor;
+#[cfg(not(debug_assertions))]
+use wgpu::BufferDescriptor;
+use wgpu::{BufferUsages, CommandEncoder, ShaderStages};
+
+use super::{
+ aligned_buffer_vec::HybridAlignedBufferVec, effect_cache::SlabState, gpu_buffer::GpuBuffer,
+ BufferBindingSource, EffectBindGroups, GpuDispatchIndirectArgs,
+};
+use crate::{
+ render::{effect_cache::SlabId, ChildEffectOf},
+ ParticleLayout,
+};
+
+#[derive(Debug, Default, Clone, PartialEq, Eq)]
+pub struct EventSlice {
+ slice: Range<u32>,
+}
+
+/// GPU buffer storing the spawn events emitted by parent effects for their
+/// children.
+///
+/// The event buffer contains for each effect the number of particles to spawn
+/// this frame. That number is incremented by another effect when it
+/// emits a spawn event, and reset to zero on next frame after the indirect init
+/// pass spawned new particles, and before the new update pass of the
+/// source effect optionally emits more spawn events.
+///
+/// GPU spawn events are never accumulated over frames; if a source emits too
+/// many events and the target effect cannot spawn that many particles, for
+/// example because it reached its capacity, then the extra events are
+/// discarded. This is consistent with the CPU behavior of
+/// [`EffectSpawner::spawn_count`].
+///
+/// Note that the number of allocated events in the buffer slice associated with
+/// a child effect instance is not recorded here; instead it's stored in
+/// [`GpuChildInfo::event_count`]. This buffer only stores the events
+/// themselves.
+pub struct EventBuffer {
+ /// GPU buffer storing the spawn events.
+ buffer: Buffer,
+ /// Buffer capacity, in words (4 bytes).
+ capacity: u32,
+ /// Allocated (used) buffer size, in words (4 bytes).
+ size: u32,
+ /// Slices into the GPU buffer where event sub-allocations for each effect
+ /// are located. Slices are stored ordered by location in the buffer, for
+ /// convenience of allocation.
+ slices: Vec<EventSlice>,
+}
+
+impl EventBuffer {
+ /// Create a new event buffer to store the spawn events of the specified
+ /// child effect.
+ pub fn new(buffer: Buffer, capacity: u32) -> Self {
+ Self {
+ buffer,
+ capacity,
+ size: 0,
+ slices: vec![],
+ }
+ }
+
+ /// Get a reference to the underlying GPU buffer.
+ pub fn buffer(&self) -> &Buffer {
+ &self.buffer
+ }
+
+ /// Allocate a new slice for a child effect.
+ pub fn allocate(&mut self, size: u32) -> Option<EventSlice> {
+ if self.size + size > self.capacity {
+ return None;
+ }
+
+ if self.slices.is_empty() {
+ let slice = EventSlice { slice: 0..size };
+ self.slices.push(slice.clone());
+ self.size += size;
+ return Some(slice);
+ }
+
+ let mut start = 0;
+ for (idx, es) in self.slices.iter().enumerate() {
+ let avail_size = es.slice.start - start;
+ if size > avail_size {
+ start = es.slice.end;
+ continue;
+ }
+
+ let slice = EventSlice {
+ slice: start..start + size,
+ };
+ self.slices.insert(idx, slice.clone());
+ self.size += size;
+ return Some(slice);
+ }
+
+ if start + size <= self.capacity {
+ let slice = EventSlice {
+ slice: start..start + size,
+ };
+ self.slices.push(slice.clone());
+ self.size += size;
+ Some(slice)
+ } else {
+ None
+ }
+ }
+
+ /// Free the slice of a consumer effect once that effect is deallocated.
+ pub fn free(&mut self, slice: &EventSlice) -> SlabState {
+ // Note: could use binary search, but likely not enough elements to be worth it
+ if let Some(idx) = self.slices.iter().position(|es| es == slice) {
+ self.slices.remove(idx);
+ }
+ if self.slices.is_empty() {
+ SlabState::Free
+ } else {
+ SlabState::Used
+ }
+ }
+}
+
+/// Data about the child effect(s) of this effect. This component is only
+/// present on an effect instance if that effect is the parent effect for at
+/// least one child effect.
+#[derive(Debug, PartialEq, Component)]
+pub(crate) struct CachedParentInfo {
+ /// Render world entities of the child effects, and their associated event
+ /// buffer binding source.
+ pub children: Vec<(Entity, BufferBindingSource)>,
+ /// Indices in bytes into the global [`EffectCache::child_infos_buffer`] of
+ /// the [`GpuChildInfo`]s for all the child effects of this parent effect.
+ /// The child effects are always allocated as a single contiguous block,
+ /// which needs to be mapped into a shader binding point.
+ pub byte_range: Range<u32>,
+}
+
+/// Data about this effect as a child of another effect.
+///
+/// This component is only present on an effect instance if that effect is the
+/// child effect for another effect (that is, this effect has a parent effect).
+#[derive(Debug, Clone, PartialEq, Component)]
+pub(crate) struct CachedChildInfo {
+ /// ID of the slab storing the parent effect.
+ pub parent_slab_id: SlabId,
+ /// Offset into the slab of the parent's particles.
+ pub parent_slab_offset: u32,
+ /// Parent's particle layout.
+ pub parent_particle_layout: ParticleLayout,
+ /// Parent's buffer.
+ pub parent_buffer_binding_source: BufferBindingSource,
+ /// Index of this child effect into its parent's [`GpuChildInfo`] array.
+ /// This starts at zero for the first child of each effect, and is only
+ /// unique per parent only, not globally.
+ pub local_child_index: u32,
+ /// Global index of this child effect into the shared global
+ /// [`EventCache::child_infos_buffer`] array. This is a unique index across
+ /// all effects.
+ pub global_child_index: u32,
+ /// Index of the [`GpuDispatchIndirectArgs`] entry into the
+ /// [`EventCache::init_indirect_dispatch_buffer`] array.
+ pub init_indirect_dispatch_index: u32,
+}
+
+impl CachedChildInfo {
+ pub fn is_locally_equal(&self, other: &CachedChildInfo) -> bool {
+ self.parent_slab_id == other.parent_slab_id
+ && self.parent_slab_offset == other.parent_slab_offset
+ && self.parent_particle_layout == other.parent_particle_layout
+ && self.parent_buffer_binding_source == other.parent_buffer_binding_source
+ && self.local_child_index == other.local_child_index
+ // skip global_child_index here!
+ && self.init_indirect_dispatch_index == other.init_indirect_dispatch_index
+ }
+}
+
+/// GPU representation of the child info data structure storing some data for a
+/// child effect. The associated CPU representation is [`CachedEffectEvents`].
+#[repr(C)]
+#[derive(Debug, Default, Clone, Copy, Pod, Zeroable, ShaderType)]
+pub struct GpuChildInfo {
+ /// Index of the [`GpuDispatchIndirectArgs`] inside the
+ /// [`EventCache::init_indirect_dispatch_buffer`] used to dispatch the init
+ /// pass of this child effect.
+ pub init_indirect_dispatch_index: u32,
+ /// Number of events currently stored inside the [`EventBuffer`] slice
+ /// associated with this child effect. This is updated atomically by the
+ /// GPU while stored in the [`EventCache::child_infos_buffer`].
+ pub event_count: i32,
+}
+
+/// Cached allocation info for the GPU events of a child effect.
+///
+/// This component is automitically inserted by [`allocate_events()`] when a
+/// child effect uses GPU events.
+#[derive(Debug, Clone, Component)]
+pub struct CachedEffectEvents {
+ /// Index of the [`EventBuffer`] inside the [`EventCache::buffers`]
+ /// collection where a slice of events is allocated, for this effect to
+ /// consume.
+ pub buffer_index: u32,
+ /// Range, in items (4 bytes), where the events are stored inside the
+ /// [`EventBuffer`]. This determines the capacity, in event count, for this
+ /// effect. The number of used events is stored on the GPU in
+ /// [`GpuChildInfo::event_count`].
+ pub range: Range<u32>,
+ /// Index of the [`GpuDispatchIndirectArgs`] inside the
+ /// [`EventCache::init_indirect_dispatch_buffer`].
+ pub init_indirect_dispatch_index: u32,
+}
+
+impl CachedEffectEvents {
+ /// Capacity of this allocation, in number of GPU events. The number of used
+ /// events is stored on the GPU in [`GpuChildInfo::event_count`].
+ #[allow(dead_code)]
+ pub fn capacity(&self) -> u32 {
+ self.range.len() as u32
+ }
+}
+
+/// Allocate storage for GPU events for all child effects.
+///
+/// This system manages allocating storage for GPU events of child effects, and
+/// spawning the [`CachedEffectEvents`] storing that allocation.
+pub(crate) fn allocate_events(
+ mut commands: Commands,
+ mut event_cache: ResMut<EventCache>,
+ mut q_child_effects: Query<(Entity, Option<&mut CachedEffectEvents>), With<ChildEffectOf>>,
+ q_old_child_effects: Query<Entity, (With<CachedEffectEvents>, Without<ChildEffectOf>)>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("allocate_events").entered();
+ trace!("allocate_events");
+
+ event_cache.clear_previous_frame_resizes();
+
+ // Allocate storage and add the component to childs missing it.
+ for (entity, maybe_cached_events) in &mut q_child_effects {
+ if let Some(_cached_events) = maybe_cached_events {
+ // Nothing really to do for now because we hardcode a number of
+ // events, so the allocation won't ever change...
+ } else {
+ const FIXME_HARD_CODED_EVENT_COUNT: u32 = 256;
+ let cached_effect_events = event_cache.allocate(FIXME_HARD_CODED_EVENT_COUNT);
+ commands.entity(entity).insert(cached_effect_events);
+ }
+ }
+
+ // Remove the component from effects which are not a child anymore. This should
+ // be pretty rare; in general the effect is just despawned.
+ for entity in &q_old_child_effects {
+ commands.entity(entity).remove::<CachedEffectEvents>();
+ }
+}
+
+/// Observer raised when the [`CachedEffectEvents`] component is removed,
+/// which indicates that the effect doesn't use GPU events anymore.
+pub(crate) fn on_remove_cached_effect_events(
+ trigger: On<Remove<CachedEffectEvents>>,
+ query: Query<(Entity, &CachedEffectEvents)>,
+ mut event_cache: ResMut<EventCache>,
+ mut effect_bind_groups: ResMut<EffectBindGroups>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("on_remove_cached_effect_events").entered();
+ trace!("on_remove_cached_effect_events");
+
+ if let Ok((entity, cached_effect_events)) = query.get(trigger.event().entity) {
+ match event_cache.free(cached_effect_events) {
+ Err(err) => {
+ error!("Error while freeing cached events for effect {entity:?}: {err:?}");
+ }
+ Ok(buffer_state) => {
+ if buffer_state != SlabState::Used {
+ // Clear bind groups associated with the old buffer
+ effect_bind_groups.init_metadata_bind_groups.clear();
+ effect_bind_groups.update_metadata_bind_groups.clear();
+ }
+ }
+ }
+ };
+}
+
+/// Error code for [`EventCache::free()`].
+#[derive(Debug, Error)]
+pub enum CachedEventsError {
+ /// The given buffer index is invalid. The [`EventCache`] doesn't contain
+ /// any buffer with such index.
+ #[error("Invalid buffer index #{0}.")]
+ InvalidBufferIndex(u32),
+ /// The given buffer index corresponds to a [`EventCache`] buffer which
+ /// was already deallocated.
+ #[error("Buffer at index #{0} was deallocated.")]
+ BufferDeallocated(u32),
+}
+
+/// Cache for effect events.
+#[derive(Resource)]
+pub struct EventCache {
+ /// Render device to allocate GPU resources as needed.
+ device: RenderDevice,
+ /// Single shared GPU buffer storing all the [`GpuChildInfo`] structs
+ /// for all the parent effects.
+ child_infos_buffer: HybridAlignedBufferVec,
+ /// Collection of event buffers managed by this cache. Some buffers might
+ /// be `None` if the entry is not used. Since the buffers are referenced
+ /// by index, we cannot move them once they're allocated.
+ buffers: Vec<Option<EventBuffer>>,
+ /// Single shared GPU buffer storing all the [`GpuDispatchIndirectArgs`]
+ /// structs for all the indirect init passes. Any effect allocating storage
+ /// for GPU events also get an entry into this buffer, to allow consuming
+ /// the events from an init pass indirectly dispatched (GPU-driven).
+ // FIXME - merge with the update pass one, we don't need 2 buffers storing the same type; on
+ // the other hand if we sync the allocations with GpuChildInfo we can guarantee a perfect
+ // batching for the init fill dispatch pass (single dispatch for all instances at once).
+ init_indirect_dispatch_buffer: GpuBuffer<GpuDispatchIndirectArgs>,
+ /// Bind group layout for the indirect dispatch pass, which clears the GPU
+ /// event counts ([`GpuChildInfo::event_count`]).
+ indirect_child_info_buffer_bind_group_layout: BindGroupLayout,
+ /// Bind group for the indirect dispatch pass, which clears the GPU event
+ /// counts ([`GpuChildInfo::event_count`]).
+ indirect_child_info_buffer_bind_group: Option<BindGroup>,
+}
+
+impl EventCache {
+ /// Create a new event cache.
+ pub fn new(device: RenderDevice) -> Self {
+ let init_indirect_dispatch_buffer = GpuBuffer::new(
+ BufferUsages::STORAGE | BufferUsages::INDIRECT,
+ Some("hanabi:buffer:init_indirect_dispatch".to_string()),
+ );
+
+ let child_infos_bind_group_layout = device.create_bind_group_layout(
+ "hanabi:bgl:indirect:child_infos@3",
+ &BindGroupLayoutEntries::single(
+ ShaderStages::COMPUTE,
+ storage_buffer::<GpuChildInfo>(false),
+ ),
+ );
+
+ Self {
+ device,
+ child_infos_buffer: HybridAlignedBufferVec::new(
+ BufferUsages::STORAGE,
+ NonZeroU64::new(4).unwrap(),
+ Some("hanabi:buffer:child_infos".to_string()),
+ ),
+ buffers: vec![],
+ init_indirect_dispatch_buffer,
+ indirect_child_info_buffer_bind_group_layout: child_infos_bind_group_layout,
+ // Can't create until the buffer is ready
+ indirect_child_info_buffer_bind_group: None,
+ }
+ }
+
+ #[allow(dead_code)]
+ #[inline]
+ pub fn buffers(&self) -> &[Option<EventBuffer>] {
+ &self.buffers
+ }
+
+ #[allow(dead_code)]
+ #[inline]
+ pub fn buffers_mut(&mut self) -> &mut [Option<EventBuffer>] {
+ &mut self.buffers
+ }
+
+ #[inline]
+ pub fn get_buffer(&self, index: u32) -> Option<&Buffer> {
+ self.buffers
+ .get(index as usize)
+ .and_then(|opt_eb| opt_eb.as_ref().map(|eb| eb.buffer()))
+ }
+
+ #[inline]
+ pub fn child_infos_buffer(&self) -> Option<&Buffer> {
+ self.child_infos_buffer.buffer()
+ }
+
+ /// Allocate a memory block to store the given number of GPU events.
+ ///
+ /// The allocation always succeeds, allocating a new GPU event buffer if
+ /// none of the existing ones can store the requested number of events.
+ ///
+ /// # Returns
+ ///
+ /// The [`CachedEffectEvents`] component representing the allocation.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the number of events `num_events` is zero.
+ pub fn allocate(&mut self, num_events: u32) -> CachedEffectEvents {
+ assert!(num_events > 0);
+
+ // Allocate an entry into the indirect dispatch buffer
+ // The value pushed is a dummy; see allocate_frame_buffers().
+ let init_indirect_dispatch_index = self.init_indirect_dispatch_buffer.allocate();
+
+ // Try to find an allocated GPU buffer with enough capacity
+ let mut empty_index = None;
+ for (buffer_index, buffer) in self.buffers.iter_mut().enumerate() {
+ let Some(buffer) = buffer.as_mut() else {
+ // Remember the first empty slot in case we need to allocate a new GPU buffer
+ if empty_index.is_none() {
+ empty_index = Some(buffer_index);
+ }
+ continue;
+ };
+
+ // Try to allocate a slice into the buffer
+ if let Some(event_slice) = buffer.allocate(num_events) {
+ trace!("Allocate new slice in event buffer #{buffer_index} for {num_events} events: range={event_slice:?}");
+ return CachedEffectEvents {
+ buffer_index: buffer_index as u32,
+ init_indirect_dispatch_index,
+ range: event_slice.slice,
+ };
+ }
+ }
+
+ // Cannot find any suitable GPU event buffer; allocate a new one
+
+ // Compute the slot where to store the new buffer
+ let buffer_index = empty_index.unwrap_or(self.buffers.len());
+
+ // Create the GPU bfufer
+ let label = format!("hanabi:buffer:event_buffer{buffer_index}");
+ let align = self.device.limits().min_storage_buffer_offset_alignment;
+ let capacity = num_events.max(16 * 1024); // min capacity
+ let byte_size = (capacity as u64 * 4).next_multiple_of(align as u64);
+ let capacity = (byte_size / 4) as u32;
+ // In debug, fill the buffer with some debug marker
+ #[cfg(debug_assertions)]
+ let buffer = {
+ let mut contents: Vec<u32> = Vec::with_capacity(capacity as usize);
+ contents.resize(capacity as usize, 0xDEADBEEF);
+ self.device.create_buffer_with_data(&BufferInitDescriptor {
+ label: Some(&label[..]),
+ usage: BufferUsages::COPY_DST | BufferUsages::STORAGE,
+ contents: bytemuck::cast_slice(contents.as_slice()),
+ })
+ };
+ // In release, don't initialize the buffer for performance
+ #[cfg(not(debug_assertions))]
+ let buffer = self.device.create_buffer(&BufferDescriptor {
+ label: Some(&label[..]),
+ size: byte_size,
+ usage: BufferUsages::COPY_DST | BufferUsages::STORAGE,
+ mapped_at_creation: false,
+ });
+ trace!("Created new event buffer #{buffer_index} '{label}' with {byte_size} bytes ({capacity} events; align={align}B)");
+ let mut buffer = EventBuffer::new(buffer, capacity);
+
+ // Allocate a slice from the new event buffer
+ let event_slice = buffer.allocate(num_events).expect("Failed to allocate event slice inside new buffer specifically created for this allocation.");
+ trace!("Allocate new slice in event buffer #{buffer_index} for {num_events} events: range={event_slice:?}");
+
+ // Store the event buffer at the selected slot
+ if buffer_index >= self.buffers.len() {
+ self.buffers.push(Some(buffer));
+ } else {
+ debug_assert!(self.buffers[buffer_index].is_none());
+ self.buffers[buffer_index] = Some(buffer);
+ }
+
+ CachedEffectEvents {
+ buffer_index: buffer_index as u32,
+ init_indirect_dispatch_index,
+ range: event_slice.slice,
+ }
+ }
+
+ /// Deallocated and remove an event block allocation from the cache.
+ pub fn free(
+ &mut self,
+ cached_effect_events: &CachedEffectEvents,
+ ) -> Result<SlabState, CachedEventsError> {
+ trace!(
+ "Removing cached event {:?} from cache.",
+ cached_effect_events
+ );
+
+ self.init_indirect_dispatch_buffer
+ .free(cached_effect_events.init_indirect_dispatch_index);
+
+ let entry = self
+ .buffers
+ .get_mut(cached_effect_events.buffer_index as usize)
+ .ok_or(CachedEventsError::InvalidBufferIndex(
+ cached_effect_events.buffer_index,
+ ))?;
+ let buffer = entry.as_mut().ok_or(CachedEventsError::BufferDeallocated(
+ cached_effect_events.buffer_index,
+ ))?;
+ if buffer.free(&EventSlice {
+ slice: cached_effect_events.range.clone(),
+ }) == SlabState::Free
+ {
+ let buffer = entry.take().unwrap();
+ buffer.buffer.destroy();
+ Ok(SlabState::Free)
+ } else {
+ Ok(SlabState::Used)
+ }
+ }
+
+ /// Allocate a new block of [`GpuChildInfo`] structures for a list of
+ /// children.
+ pub fn allocate_child_infos(
+ &mut self,
+ parent_entity: Entity,
+ children: Vec<(Entity, BufferBindingSource)>,
+ child_infos: &[GpuChildInfo],
+ ) -> CachedParentInfo {
+ assert_eq!(children.len(), child_infos.len());
+ assert!(!children.is_empty());
+
+ let byte_range = self.child_infos_buffer.push_many(child_infos);
+ assert_eq!(byte_range.start as usize % size_of::<GpuChildInfo>(), 0);
+ trace!(
+ "Parent {:?}: newly allocated ChildInfo[] array at +{}",
+ parent_entity,
+ byte_range.start
+ );
+
+ CachedParentInfo {
+ children,
+ byte_range,
+ }
+ }
+
+ /// Re-allocate a block of [`GpuChildInfo`] structures for a modified list
+ /// of children.
+ pub fn reallocate_child_infos(
+ &mut self,
+ parent_entity: Entity,
+ children: Vec<(Entity, BufferBindingSource)>,
+ child_infos: &[GpuChildInfo],
+ cached_parent_info: &mut CachedParentInfo,
+ ) {
+ trace!(
+ "Parent {:?}: De-allocating old ChildInfo[] entry at range {:?}",
+ parent_entity,
+ cached_parent_info.byte_range
+ );
+ self.child_infos_buffer
+ .remove(cached_parent_info.byte_range.clone());
+
+ let byte_range = self.child_infos_buffer.push_many(child_infos);
+ assert_eq!(
+ byte_range.start as usize % GpuChildInfo::SHADER_SIZE.get() as usize,
+ 0
+ );
+ trace!(
+ "Parent {:?}: Allocated new ChildInfo[] entry at byte range {:?}",
+ parent_entity,
+ byte_range
+ );
+
+ cached_parent_info.children = children;
+ cached_parent_info.byte_range = byte_range;
+ }
+
+ /// Re-/allocate any buffer for the current frame.
+ pub fn prepare_buffers(
+ &mut self,
+ render_device: &RenderDevice,
+ render_queue: &RenderQueue,
+ // FIXME
+ _effect_bind_groups: &mut ResMut<EffectBindGroups>,
+ ) {
+ // This buffer is only ever used in the bind groups of a `GpuBufferOperations`,
+ // which manages its bind groups automatically each frame. So there's no
+ // invalidation to do here on re-allocation.
+ self.init_indirect_dispatch_buffer
+ .prepare_buffers(render_device);
+
+ self.child_infos_buffer
+ .write_buffer(render_device, render_queue);
+ }
+
+ /// Schedule any pending buffer copy.
+ ///
+ /// This is necessary when a buffer is reallocated, to copy the old content.
+ /// This must be called once per frame after the buffers have been
+ /// reallocated with `prepare_buffers()`.
+ #[inline]
+ pub fn write_buffers(&self, command_encoder: &mut CommandEncoder) {
+ self.init_indirect_dispatch_buffer
+ .write_buffers(command_encoder);
+ }
+
+ /// Destroy old copies of buffers reallocated last frame and copied to a new
+ /// buffer.
+ ///
+ /// This must be called once per frame after any content was effectively
+ /// copied from an old to a new buffer. This means that, due to Bevy's
+ /// limitations, this must be called on the next frame, as we don't have
+ /// write access to anything nor any hint as to when copies are done until
+ /// the next frame rendering actually starts.
+ #[inline]
+ pub fn clear_previous_frame_resizes(&mut self) {
+ self.init_indirect_dispatch_buffer
+ .clear_previous_frame_resizes();
+ }
+
+ #[inline]
+ pub fn init_indirect_dispatch_buffer(&self) -> Option<&Buffer> {
+ self.init_indirect_dispatch_buffer.buffer()
+ }
+
+ #[inline]
+ pub fn child_infos(&self) -> &HybridAlignedBufferVec {
+ &self.child_infos_buffer
+ }
+
+ pub fn ensure_indirect_child_info_buffer_bind_group(
+ &mut self,
+ device: &RenderDevice,
+ ) -> Option<&BindGroup> {
+ let buffer = self.child_infos_buffer()?;
+ // TODO - stop re-creating each frame...
+ self.indirect_child_info_buffer_bind_group = Some(device.create_bind_group(
+ "hanabi:bg:indirect:child_infos@3",
+ &self.indirect_child_info_buffer_bind_group_layout,
+ &BindGroupEntries::single(buffer.as_entire_binding()),
+ ));
+ self.indirect_child_info_buffer_bind_group.as_ref()
+ }
+
+ pub fn indirect_child_info_buffer_bind_group(&self) -> Option<&BindGroup> {
+ self.indirect_child_info_buffer_bind_group.as_ref()
+ }
+}
diff --git a/vendor/bevy_hanabi/src/render/gpu_buffer.rs b/vendor/bevy_hanabi/src/render/gpu_buffer.rs
new file mode 100644
index 00000000..bb203f4a
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/gpu_buffer.rs
@@ -0,0 +1,381 @@
+use std::marker::PhantomData;
+
+use bevy::{
+ log::trace,
+ render::{
+ render_resource::{
+ BindingResource, Buffer, BufferAddress, BufferDescriptor, BufferUsages, ShaderSize,
+ ShaderType,
+ },
+ renderer::RenderDevice,
+ },
+};
+use bytemuck::Pod;
+use wgpu::CommandEncoder;
+
+struct BufferAndSize {
+ /// Allocate GPU buffer.
+ pub buffer: Buffer,
+ /// Size of the buffer, in number of elements.
+ pub size: u32,
+}
+
+/// GPU-only buffer without CPU-side storage.
+///
+/// This is a rather specialized helper to allocate an array on the GPU and
+/// manage its buffer, depending on the device constraints and the WGSL rules
+/// for data alignment, and allowing to resize the buffer without losing its
+/// content (so, scheduling a buffer-to-buffer copy on GPU after reallocatin).
+///
+/// The element type `T` needs to implement the following traits:
+/// - [`Pod`] to prevent user error. This is not strictly necessary, as there's
+/// no copy from or to CPU, but if the placeholder type is not POD this might
+/// indicate some user error.
+/// - [`ShaderSize`] to ensure a fixed footprint, to allow packing multiple
+/// instances inside a single buffer. This therefore excludes any
+/// runtime-sized array (T being the element type here; it will itself be part
+/// of an array).
+pub struct GpuBuffer<T: Pod + ShaderSize> {
+ /// GPU buffer if already allocated, or `None` otherwise.
+ buffer: Option<BufferAndSize>,
+ /// Previous GPU buffer, pending copy.
+ old_buffer: Option<BufferAndSize>,
+ /// GPU buffer usages.
+ buffer_usage: BufferUsages,
+ /// Optional GPU buffer name, for debugging.
+ label: Option<String>,
+ /// Used size, in element count. Elements past this are all free. Elements
+ /// with a lower index are either allocated or in the free list.
+ used_size: u32,
+ /// Free list.
+ free_list: Vec<u32>,
+ _phantom: PhantomData<T>,
+}
+
+impl<T: Pod + ShaderType + ShaderSize> Default for GpuBuffer<T> {
+ fn default() -> Self {
+ Self {
+ buffer: None,
+ old_buffer: None,
+ buffer_usage: BufferUsages::all(),
+ label: None,
+ used_size: 0,
+ free_list: vec![],
+ _phantom: PhantomData,
+ }
+ }
+}
+
+impl<T: Pod + ShaderType + ShaderSize> GpuBuffer<T> {
+ /// Create a new collection.
+ ///
+ /// The buffer usage is always augmented by [`BufferUsages::COPY_SRC`] and
+ /// [`BufferUsages::COPY_DST`] in order to allow buffer-to-buffer copy when
+ /// reallocating, to preserve old content.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `buffer_usage` contains [`BufferUsages::UNIFORM`] and the
+ /// layout of the element type `T` does not meet the requirements of the
+ /// uniform address space, as tested by
+ /// [`ShaderType::assert_uniform_compat()`].
+ ///
+ /// [`BufferUsages::UNIFORM`]: bevy::render::render_resource::BufferUsages::UNIFORM
+ #[allow(dead_code)]
+ pub fn new(buffer_usage: BufferUsages, label: Option<String>) -> Self {
+ // GPU-aligned item size, compatible with WGSL rules
+ let item_size = <T as ShaderSize>::SHADER_SIZE.get() as usize;
+ trace!("GpuBuffer: item_size={}", item_size);
+ if buffer_usage.contains(BufferUsages::UNIFORM) {
+ <T as ShaderType>::assert_uniform_compat();
+ }
+ Self {
+ // We need both COPY_SRC and COPY_DST for copy_buffer_to_buffer() on realloc
+ buffer_usage: buffer_usage | BufferUsages::COPY_SRC | BufferUsages::COPY_DST,
+ label,
+ ..Default::default()
+ }
+ }
+
+ /// Create a new collection from an allocated buffer.
+ ///
+ /// The buffer usage must contain [`BufferUsages::COPY_SRC`] and
+ /// [`BufferUsages::COPY_DST`] in order to allow buffer-to-buffer copy when
+ /// reallocating, to preserve old content.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `buffer_usage` doesn't contain [`BufferUsages::COPY_SRC`] or
+ /// [`BufferUsages::COPY_DST`].
+ ///
+ /// Panics if `buffer_usage` contains [`BufferUsages::UNIFORM`] and the
+ /// layout of the element type `T` does not meet the requirements of the
+ /// uniform address space, as tested by
+ /// [`ShaderType::assert_uniform_compat()`].
+ ///
+ /// [`BufferUsages::UNIFORM`]: bevy::render::render_resource::BufferUsages::UNIFORM
+ pub fn new_allocated(buffer: Buffer, label: Option<String>) -> Self {
+ // GPU-aligned item size, compatible with WGSL rules.
+ let item_size = <T as ShaderSize>::SHADER_SIZE.get();
+ let buffer_usage = buffer.usage();
+ assert!(
+ buffer_usage.contains(BufferUsages::COPY_SRC | BufferUsages::COPY_DST),
+ "GpuBuffer requires COPY_SRC and COPY_DST buffer usages to allow copy on reallocation."
+ );
+ if buffer_usage.contains(BufferUsages::UNIFORM) {
+ <T as ShaderType>::assert_uniform_compat();
+ }
+ // Capacity is derived from the physical buffer so the two can't disagree.
+ debug_assert_eq!(
+ buffer.size() % item_size,
+ 0,
+ "GpuBuffer physical size ({} bytes) is not a multiple of the element size ({} bytes)",
+ buffer.size(),
+ item_size,
+ );
+ let size = (buffer.size() / item_size) as u32;
+ trace!("GpuBuffer: item_size={item_size} capacity={size}");
+ Self {
+ buffer: Some(BufferAndSize { buffer, size }),
+ buffer_usage,
+ label,
+ ..Default::default()
+ }
+ }
+
+ /// Clear the buffer.
+ ///
+ /// This doesn't de-allocate any GPU buffer.
+ pub fn clear(&mut self) {
+ self.free_list.clear();
+ self.used_size = 0;
+ }
+
+ /// Allocate a new entry in the buffer.
+ ///
+ /// If the GPU buffer has not enough storage, or is not allocated yet, this
+ /// schedules a (re-)allocation, which must be applied by calling
+ /// [`allocate_gpu()`] once a frame after all [`allocate()`] calls were made
+ /// for that frame.
+ ///
+ /// # Returns
+ ///
+ /// The index of the allocated entry.
+ ///
+ /// [`allocate_gpu()`]: Self::allocate_gpu
+ /// [`allocate()`]: Self::allocate
+ pub fn allocate(&mut self) -> u32 {
+ if let Some(index) = self.free_list.pop() {
+ index
+ } else {
+ // Note: we may return an index past the buffer capacity. This will instruct
+ // allocate_gpu() to re-allocate the buffer.
+ let index = self.used_size;
+ self.used_size += 1;
+ index
+ }
+ }
+
+ /// Allocate a contiguous slice of new entries in the buffer.
+ ///
+ /// If the GPU buffer has not enough storage, or is not allocated yet, this
+ /// schedules a (re-)allocation, which must be applied by calling
+ /// [`allocate_gpu()`] once a frame after all [`allocate()`] calls were made
+ /// for that frame.
+ ///
+ /// # Returns
+ ///
+ /// The index of the first allocated entry.
+ ///
+ /// [`allocate_gpu()`]: Self::allocate_gpu
+ /// [`allocate()`]: Self::allocate
+ pub fn allocate_slice(&mut self, count: u32) -> u32 {
+ // FIXME - we bypass the free list to be sure to have a contiguous slice
+ // Note: we may return an index past the buffer capacity. This will instruct
+ // allocate_gpu() to re-allocate the buffer.
+ let base_index = self.used_size;
+ self.used_size += count;
+ base_index
+ }
+
+ /// Free an existing entry.
+ ///
+ /// # Panics
+ ///
+ /// In debug only, panics if the entry is not allocated (double-free). In
+ /// non-debug, the behavior is undefined and will generally lead to bugs.
+ // Currently we use GpuBuffer in sorting, and re-allocate everything each frame.
+ #[allow(dead_code)]
+ pub fn free(&mut self, index: u32) {
+ if index < self.used_size {
+ debug_assert!(
+ !self.free_list.contains(&index),
+ "Double-free in GpuBuffer at index #{}",
+ index
+ );
+ self.free_list.push(index);
+ }
+ }
+
+ /// Get the current GPU buffer, if allocated.
+ #[inline]
+ pub fn buffer(&self) -> Option<&Buffer> {
+ self.buffer.as_ref().map(|b| &b.buffer)
+ }
+
+ /// Get a binding for the entire GPU buffer, if allocated.
+ #[inline]
+ #[allow(dead_code)]
+ pub fn as_entire_binding(&self) -> Option<BindingResource<'_>> {
+ let buffer = self.buffer()?;
+ Some(buffer.as_entire_binding())
+ }
+
+ /// Get the current buffer capacity, in element count.
+ ///
+ /// This is the CPU view of allocations, which counts the number of
+ /// [`allocate()`] and [`free()`] calls.
+ ///
+ /// [`allocate()`]: Self::allocate
+ /// [`free()`]: Self::allocate_gpu
+ #[inline]
+ #[allow(dead_code)]
+ pub fn capacity(&self) -> u32 {
+ debug_assert!(self.used_size >= self.free_list.len() as u32);
+ self.used_size - self.free_list.len() as u32
+ }
+
+ /// Get the current GPU buffer capacity, in element count.
+ ///
+ /// Note that it is possible for [`allocate()`] to return an index greater
+ /// than or equal to the value returned by [`capacity()`], at least
+ /// temporarily until [`allocate_gpu()`] is called.
+ ///
+ /// [`allocate()`]: Self::allocate
+ /// [`gpu_capacity()`]: Self::gpu_capacity
+ /// [`allocate_gpu()`]: Self::allocate_gpu
+ #[inline]
+ pub fn gpu_capacity(&self) -> u32 {
+ self.buffer.as_ref().map(|b| b.size).unwrap_or(0)
+ }
+
+ /// Size in bytes of a single item in the buffer.
+ ///
+ /// This is equal to [`ShaderSize::SHADER_SIZE`] for the buffer element `T`.
+ #[inline]
+ pub fn item_size(&self) -> usize {
+ <T as ShaderSize>::SHADER_SIZE.get() as usize
+ }
+
+ /// Check if the buffer is empty.
+ ///
+ /// The check is based on the CPU representation of the buffer, that is the
+ /// number of calls to [`allocate()`]. The buffer is considered empty if no
+ /// [`allocate()`] call was made, or they all have been followed by a
+ /// corresponding [`free()`] call. This makes no assumption about the GPU
+ /// buffer.
+ ///
+ /// [`allocate()`]: Self::allocate
+ /// [`free()`]: Self::free
+ #[inline]
+ #[allow(dead_code)]
+ pub fn is_empty(&self) -> bool {
+ self.used_size == 0
+ }
+
+ /// Allocate or reallocate the GPU buffer if needed.
+ ///
+ /// This allocates or reallocates a GPU buffer to ensure storage for all
+ /// previous calls to [`allocate()`]. This is a no-op if a GPU buffer is
+ /// already allocated and has sufficient storage.
+ ///
+ /// This should be called once a frame after any new [`allocate()`] in that
+ /// frame. After this call, [`buffer()`] is guaranteed to return `Some(..)`.
+ ///
+ /// # Returns
+ ///
+ /// `true` if the buffer was (re)allocated, or `false` if an existing buffer
+ /// was reused which already had enough capacity.
+ ///
+ /// [`reserve()`]: Self::reserve
+ /// [`allocate()`]: Self::allocate
+ /// [`buffer()`]: Self::buffer
+ pub fn prepare_buffers(&mut self, render_device: &RenderDevice) -> bool {
+ // Don't do anything if we still have some storage.
+ let old_capacity = self.gpu_capacity();
+ if self.used_size <= old_capacity {
+ return false;
+ }
+
+ // Ensure we allocate at least 256 more entries than what we need this frame,
+ // and round that to make it nicer for the GPU.
+ let new_capacity = (self.used_size + 256).next_multiple_of(1024);
+ if new_capacity <= old_capacity {
+ return false;
+ }
+
+ // Save the old buffer, we will need to copy it to the new one later.
+ assert!(self.old_buffer.is_none(), "Multiple calls to GpuTable::prepare_buffers() before write_buffers() was called to copy old content.");
+ self.old_buffer = self.buffer.take();
+
+ // Allocate a new buffer of the appropriate size.
+ let byte_size = self.item_size() * new_capacity as usize;
+ trace!(
+ "prepare_buffers(): increase capacity from {} to {} elements, new size {} bytes",
+ old_capacity,
+ new_capacity,
+ byte_size
+ );
+ let buffer = render_device.create_buffer(&BufferDescriptor {
+ label: self.label.as_ref().map(|s| &s[..]),
+ size: byte_size as BufferAddress,
+ usage: BufferUsages::COPY_DST | self.buffer_usage,
+ mapped_at_creation: false,
+ });
+ self.buffer = Some(BufferAndSize {
+ buffer,
+ size: new_capacity,
+ });
+
+ true
+ }
+
+ /// Schedule any pending buffer copy.
+ ///
+ /// If a new buffer was (re-)allocated this frame, this schedules a
+ /// buffer-to-buffer copy from the old buffer to the new one, then releases
+ /// the old buffer.
+ ///
+ /// This should be called once a frame after [`prepare_buffers()`]. This is
+ /// a no-op if there's no need for a buffer copy.
+ ///
+ /// [`prepare_buffers()`]: Self::prepare_buffers
+ pub fn write_buffers(&self, command_encoder: &mut CommandEncoder) {
+ if let Some(old_buffer) = self.old_buffer.as_ref() {
+ let new_buffer = self.buffer.as_ref().unwrap();
+ assert!(
+ new_buffer.size >= old_buffer.size,
+ "Old buffer is smaller than the new one. This is unexpected."
+ );
+ command_encoder.copy_buffer_to_buffer(
+ &old_buffer.buffer,
+ 0,
+ &new_buffer.buffer,
+ 0,
+ old_buffer.size as u64,
+ );
+ }
+ }
+
+ /// Clear any stale buffer used for resize in the previous frame during
+ /// rendering while the data structure was immutable.
+ ///
+ /// This must be called before any new [`allocate()`].
+ ///
+ /// [`allocate()`]: Self::allocate
+ pub fn clear_previous_frame_resizes(&mut self) {
+ if let Some(old_buffer) = self.old_buffer.take() {
+ old_buffer.buffer.destroy();
+ }
+ }
+}
diff --git a/vendor/bevy_hanabi/src/render/headless_batching_tests.rs b/vendor/bevy_hanabi/src/render/headless_batching_tests.rs
new file mode 100644
index 00000000..ae769f1c
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/headless_batching_tests.rs
@@ -0,0 +1,166 @@
+#![cfg(test)]
+
+mod tests {
+ use crate::render::GpuDispatchIndirectArgs;
+
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ struct BatchInfo {
+ spawner_base: u32,
+ base_particle: u32,
+ prefix_sum_offset: u32,
+ prefix_sum_count: u32,
+ total_update_count: u32,
+ }
+
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ struct EffectLocation {
+ effect_index: u32,
+ base_particle: u32,
+ update_index: u32,
+ }
+
+ fn run_prefix_sum_pass(
+ batch_infos: &mut [BatchInfo],
+ prefix_sum: &mut [u32],
+ dispatch: &mut [GpuDispatchIndirectArgs],
+ ) {
+ for (batch_index, batch) in batch_infos.iter_mut().enumerate() {
+ let offset = batch.prefix_sum_offset as usize;
+ let end = offset + batch.prefix_sum_count as usize;
+ let mut sum = 0_u32;
+ for value in prefix_sum.iter_mut().take(end).skip(offset) {
+ let count = *value;
+ *value = sum;
+ sum += count;
+ }
+ batch.total_update_count = sum;
+ dispatch[batch_index] = GpuDispatchIndirectArgs {
+ x: sum.div_ceil(64),
+ y: 1,
+ z: 1,
+ };
+ }
+ }
+
+ fn find_location_from_particle(
+ batch: BatchInfo,
+ prefix_sum: &[u32],
+ slab_particle_index: u32,
+ ) -> EffectLocation {
+ // Compute passes use packed indices (alive-count domain), not slab indices.
+ let update_particle_index = slab_particle_index;
+ let mut lo = batch.prefix_sum_offset;
+ let mut hi = lo + batch.prefix_sum_count;
+ while lo < hi {
+ let mid = (hi + lo) >> 1;
+ let base_particle = prefix_sum[mid as usize];
+ if update_particle_index >= base_particle {
+ lo = mid + 1;
+ } else {
+ hi = mid;
+ }
+ }
+ let base_particle = prefix_sum[(lo - 1) as usize];
+ let effect_index = lo - 1 - batch.prefix_sum_offset;
+ let update_index = update_particle_index - base_particle;
+ EffectLocation {
+ effect_index,
+ base_particle,
+ update_index,
+ }
+ }
+
+ #[test]
+ fn batching_prefix_sum_contract() {
+ // Simulate the vfx_indirect output: alive counts for each effect instance.
+ let mut prefix_sum = vec![10, 5, 8, 6];
+ let mut batches = vec![
+ BatchInfo {
+ spawner_base: 0,
+ base_particle: 100,
+ prefix_sum_offset: 0,
+ prefix_sum_count: 3,
+ total_update_count: 0,
+ },
+ BatchInfo {
+ spawner_base: 3,
+ base_particle: 500,
+ prefix_sum_offset: 3,
+ prefix_sum_count: 1,
+ total_update_count: 0,
+ },
+ ];
+ let mut dispatch = vec![
+ GpuDispatchIndirectArgs { x: 0, y: 0, z: 0 },
+ GpuDispatchIndirectArgs { x: 0, y: 0, z: 0 },
+ ];
+
+ run_prefix_sum_pass(&mut batches, &mut prefix_sum, &mut dispatch);
+
+ // Batch #0: [10,5,8] -> exclusive prefix [0,10,15], total 23
+ // Batch #1: [6] -> exclusive prefix [0], total 6
+ assert_eq!(prefix_sum, vec![0, 10, 15, 0]);
+ assert_eq!(batches[0].total_update_count, 23);
+ assert_eq!(batches[1].total_update_count, 6);
+ assert_eq!(dispatch[0], GpuDispatchIndirectArgs { x: 1, y: 1, z: 1 });
+ assert_eq!(dispatch[1], GpuDispatchIndirectArgs { x: 1, y: 1, z: 1 });
+ }
+
+ #[test]
+ fn location_mapping_uses_batch_base_particle() {
+ // Exclusive prefix sums for 3 effects in a batch.
+ let prefix_sum = vec![0, 10, 15];
+ let batch = BatchInfo {
+ spawner_base: 7,
+ base_particle: 0,
+ prefix_sum_offset: 0,
+ prefix_sum_count: 3,
+ total_update_count: 23,
+ };
+
+ // First effect
+ assert_eq!(
+ find_location_from_particle(batch, &prefix_sum, 0),
+ EffectLocation {
+ effect_index: 0,
+ base_particle: 0,
+ update_index: 0
+ }
+ );
+
+ // Second effect starts at packed index 10
+ assert_eq!(
+ find_location_from_particle(batch, &prefix_sum, 10),
+ EffectLocation {
+ effect_index: 1,
+ base_particle: 10,
+ update_index: 0
+ }
+ );
+
+ // Third effect starts at packed index 15
+ assert_eq!(
+ find_location_from_particle(batch, &prefix_sum, 20),
+ EffectLocation {
+ effect_index: 2,
+ base_particle: 15,
+ update_index: 5
+ }
+ );
+ }
+
+ #[test]
+ fn render_batch_ids_must_be_initialized_for_all_merged_effects() {
+ let mut render_batch_info_ids = vec![u32::MAX, u32::MAX, u32::MAX, u32::MAX];
+ let mut next_id = 42_u32;
+ for id in &mut render_batch_info_ids {
+ if *id == u32::MAX {
+ *id = next_id;
+ next_id += 1;
+ }
+ }
+
+ assert!(render_batch_info_ids.iter().all(|id| *id != u32::MAX));
+ assert_eq!(render_batch_info_ids, vec![42, 43, 44, 45]);
+ }
+}
diff --git a/vendor/bevy_hanabi/src/render/mod.rs b/vendor/bevy_hanabi/src/render/mod.rs
new file mode 100644
index 00000000..a465ff2e
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/mod.rs
@@ -0,0 +1,7989 @@
+use std::{
+ borrow::Cow,
+ hash::{DefaultHasher, Hash, Hasher},
+ marker::PhantomData,
+ num::{NonZeroU32, NonZeroU64},
+ ops::{Deref, DerefMut, Range},
+ time::Duration,
+ vec,
+};
+
+#[cfg(feature = "2d")]
+use bevy::core_pipeline::core_2d::{Transparent2d, CORE_2D_DEPTH_FORMAT};
+#[cfg(feature = "2d")]
+use bevy::math::FloatOrd;
+use bevy::{
+ camera::primitives::Frustum,
+ ecs::{
+ change_detection::Tick,
+ prelude::*,
+ system::{lifetimeless::*, SystemParam, SystemState},
+ },
+ log::trace,
+ mesh::MeshVertexBufferLayoutRef,
+ platform::collections::HashMap,
+ prelude::*,
+ render::{
+ mesh::{allocator::MeshAllocator, RenderMesh, RenderMeshBufferInfo},
+ render_asset::RenderAssets,
+ render_phase::{
+ Draw, DrawError, DrawFunctions, PhaseItemExtraIndex, SortedPhaseItem,
+ TrackedRenderPass, ViewSortedRenderPhases,
+ },
+ render_resource::{
+ binding_types::{
+ storage_buffer, storage_buffer_read_only, storage_buffer_read_only_sized,
+ storage_buffer_sized, uniform_buffer,
+ },
+ *,
+ },
+ renderer::{RenderContext, RenderDevice, RenderGraph, RenderGraphSystems, RenderQueue},
+ sync_world::{MainEntity, RenderEntity, TemporaryRenderEntity},
+ texture::GpuImage,
+ view::{
+ ExtractedView, RenderVisibleEntities, ViewUniform, ViewUniformOffset, ViewUniforms,
+ },
+ Extract, MainWorld,
+ },
+};
+#[cfg(feature = "3d")]
+use bevy::{
+ core_pipeline::{
+ core_3d::{
+ AlphaMask3d, Opaque3d, Opaque3dBatchSetKey, Opaque3dBinKey, Transparent3d,
+ CORE_3D_DEPTH_FORMAT,
+ },
+ prepass::{OpaqueNoLightmap3dBatchSetKey, OpaqueNoLightmap3dBinKey},
+ },
+ render::{
+ mesh::allocator::MeshSlabs,
+ render_phase::{BinnedPhaseItem, ViewBinnedRenderPhases},
+ },
+};
+use bitflags::bitflags;
+use bytemuck::{Pod, Zeroable};
+use effect_cache::{CachedEffect, EffectSlice, SlabState};
+use event::{CachedChildInfo, CachedEffectEvents, CachedParentInfo, GpuChildInfo};
+use fixedbitset::FixedBitSet;
+use gpu_buffer::GpuBuffer;
+
+use crate::{
+ asset::{DefaultMesh, EffectAsset},
+ calc_func_id,
+ render::{
+ batch::{BatchInput, EffectDrawBatch, EffectSorter, InitAndUpdatePipelineIds},
+ effect_cache::{AnyDrawIndirectArgs, CachedDrawIndirectArgs, SlabId},
+ },
+ AlphaMode, Attribute, CompiledParticleEffect, EffectProperties, EffectShaders,
+ EffectSimulation, EffectSpawner, EffectVisibilityClass, HanabiMainCamera, ParticleLayout,
+ PropertyLayout, SimulationCondition, TextureLayout,
+};
+
+mod aligned_buffer_vec;
+mod batch;
+mod buffer_table;
+mod effect_cache;
+mod event;
+mod gpu_buffer;
+#[cfg(test)]
+mod headless_batching_tests;
+mod property;
+mod shader_cache;
+#[cfg(all(test, feature = "gpu_tests"))]
+mod shader_contract_tests;
+mod sort;
+
+use aligned_buffer_vec::AlignedBufferVec;
+use batch::BatchSpawnInfo;
+pub(crate) use batch::Batcher;
+use buffer_table::{BufferTable, BufferTableId};
+pub(crate) use effect_cache::EffectCache;
+pub(crate) use event::{allocate_events, on_remove_cached_effect_events, EventCache};
+pub(crate) use property::{
+ allocate_properties, on_remove_cached_properties, prepare_property_buffers, PropertyBindGroups,
+ PropertyCache,
+};
+use property::{CachedEffectProperties, PropertyBindGroupKey};
+pub use shader_cache::ShaderCache;
+pub(crate) use sort::SortBindGroups;
+
+use self::batch::EffectBatch;
+
+/// Plugin to add systems related to Hanabi rendering.
+#[derive(Debug, Clone, Copy)]
+pub struct HanabiRenderPlugin;
+
+impl Plugin for HanabiRenderPlugin {
+ fn name(&self) -> &str {
+ "hanabi:render"
+ }
+
+ fn build(&self, app: &mut App) {
+ let Some(render_app) = app.get_sub_app_mut(bevy::render::RenderApp) else {
+ return;
+ };
+
+ render_app.add_systems(
+ RenderGraph,
+ simulate
+ .in_set(RenderGraphSystems::Render)
+ .before(bevy::core_pipeline::schedule::camera_driver),
+ );
+ }
+}
+
+/// GPU representation of a single entry in the indirect index buffer of
+/// particles.
+#[repr(C)]
+#[derive(Debug, Copy, Clone, Pod, Zeroable, ShaderType)]
+struct GpuIndirectIndex {
+ /// Ping-pong indirection index for particles (ping).
+ pub ping: u32,
+ /// Ping-pong indirection index for particles (pong).
+ pub pong: u32,
+ /// Indirection index for dead particles, for recycling.
+ pub dead: u32,
+}
+
+/// Helper to calculate a hash of a given hashable value.
+fn calc_hash<H: Hash>(value: &H) -> u64 {
+ let mut hasher = DefaultHasher::default();
+ value.hash(&mut hasher);
+ hasher.finish()
+}
+
+/// Source data (buffer and range inside the buffer) to create a buffer binding.
+#[derive(Debug, Clone)]
+pub(crate) struct BufferBindingSource {
+ buffer: Buffer,
+ offset: u32,
+ size: NonZeroU32,
+}
+
+impl BufferBindingSource {
+ /// Get a binding over the source data.
+ pub fn as_binding(&self) -> BindingResource<'_> {
+ BindingResource::Buffer(BufferBinding {
+ buffer: &self.buffer,
+ offset: self.offset as u64 * 4,
+ size: Some(self.size.into()),
+ })
+ }
+}
+
+impl PartialEq for BufferBindingSource {
+ fn eq(&self, other: &Self) -> bool {
+ self.buffer.id() == other.buffer.id()
+ && self.offset == other.offset
+ && self.size == other.size
+ }
+}
+
+impl<'a> From<&'a BufferBindingSource> for BufferBinding<'a> {
+ fn from(value: &'a BufferBindingSource) -> Self {
+ BufferBinding {
+ buffer: &value.buffer,
+ offset: value.offset as u64,
+ size: Some(value.size.into()),
+ }
+ }
+}
+
+/// Simulation parameters, available to all shaders of all effects.
+#[derive(Debug, Default, Clone, Copy, Resource)]
+pub(crate) struct SimParams {
+ /// Current effect system simulation time since startup, in seconds.
+ /// This is based on the [`Time<EffectSimulation>`](EffectSimulation) clock.
+ time: f64,
+ /// Delta time, in seconds, since last effect system update.
+ delta_time: f32,
+
+ /// Current virtual time since startup, in seconds.
+ /// This is based on the [`Time<Virtual>`](Virtual) clock.
+ virtual_time: f64,
+ /// Virtual delta time, in seconds, since last effect system update.
+ virtual_delta_time: f32,
+
+ /// Current real time since startup, in seconds.
+ /// This is based on the [`Time<Real>`](Real) clock.
+ real_time: f64,
+ /// Real delta time, in seconds, since last effect system update.
+ real_delta_time: f32,
+}
+
+/// GPU representation of [`SimParams`], as well as additional per-frame
+/// effect-independent values.
+#[repr(C)]
+#[repr(align(16))] // vec4<f32>
+#[derive(Debug, Copy, Clone, Pod, Zeroable, ShaderType)]
+struct GpuSimParams {
+ /// Main view/camera frustum planes, for things like frustum culling. Each
+ /// plane is encoded as (normal, distance) over 4 components, in world
+ /// space.
+ frustum: [Vec4; 6],
+ /// World space position of the main view/camera, for things like
+ /// distance-based sorting. The W component is unused (but required for
+ /// padding in WGSL).
+ camera_position: Vec4,
+ /// Delta time, in seconds, since last effect system update.
+ delta_time: f32,
+ /// Current effect system simulation time since startup, in seconds.
+ ///
+ /// This is a lower-precision variant of [`SimParams::time`].
+ time: f32,
+ /// Virtual delta time, in seconds, since last effect system update.
+ virtual_delta_time: f32,
+ /// Current virtual time since startup, in seconds.
+ ///
+ /// This is a lower-precision variant of [`SimParams::time`].
+ virtual_time: f32,
+ /// Real delta time, in seconds, since last effect system update.
+ real_delta_time: f32,
+ /// Current real time since startup, in seconds.
+ ///
+ /// This is a lower-precision variant of [`SimParams::time`].
+ real_time: f32,
+ /// Total number of effects to update this frame. Used by the indirect
+ /// compute pipeline to cap the compute thread to the actual number of
+ /// effects to process.
+ ///
+ /// This is only used by the `vfx_indirect` compute shader.
+ num_effects: u32,
+
+ pad0: u32,
+}
+
+impl Default for GpuSimParams {
+ fn default() -> Self {
+ Self {
+ frustum: [Vec4::ZERO; 6],
+ camera_position: Vec4::ZERO,
+ delta_time: 0.04,
+ time: 0.0,
+ virtual_delta_time: 0.04,
+ virtual_time: 0.0,
+ real_delta_time: 0.04,
+ real_time: 0.0,
+ num_effects: 0,
+ pad0: 0,
+ }
+ }
+}
+
+impl From<SimParams> for GpuSimParams {
+ #[inline]
+ fn from(src: SimParams) -> Self {
+ Self::from(&src)
+ }
+}
+
+impl From<&SimParams> for GpuSimParams {
+ fn from(src: &SimParams) -> Self {
+ Self {
+ delta_time: src.delta_time,
+ time: src.time as f32,
+ virtual_delta_time: src.virtual_delta_time,
+ virtual_time: src.virtual_time as f32,
+ real_delta_time: src.real_delta_time,
+ real_time: src.real_time as f32,
+ ..default()
+ }
+ }
+}
+
+/// Compressed representation of a transform for GPU transfer.
+///
+/// The transform is stored as the three first rows of a transposed [`Mat4`],
+/// assuming the last row is the unit row [`Vec4::W`]. The transposing ensures
+/// that the three values are [`Vec4`] types which are naturally aligned and
+/// without padding when used in WGSL. Without this, storing only the first
+/// three components of each column would introduce padding, and would use the
+/// same storage size on GPU as a full [`Mat4`].
+#[repr(C)]
+#[repr(align(16))] // alignof(mat3x4)
+#[derive(Debug, Default, Clone, Copy, Pod, Zeroable, ShaderType)]
+pub(crate) struct GpuCompressedTransform {
+ pub x_row: [f32; 4],
+ pub y_row: [f32; 4],
+ pub z_row: [f32; 4],
+}
+
+impl From<Mat4> for GpuCompressedTransform {
+ fn from(value: Mat4) -> Self {
+ let tr = value.transpose();
+ #[cfg(test)]
+ crate::test_utils::assert_approx_eq!(tr.w_axis, Vec4::W);
+ Self {
+ x_row: tr.x_axis.to_array(),
+ y_row: tr.y_axis.to_array(),
+ z_row: tr.z_axis.to_array(),
+ }
+ }
+}
+
+impl From<&Mat4> for GpuCompressedTransform {
+ fn from(value: &Mat4) -> Self {
+ let tr = value.transpose();
+ #[cfg(test)]
+ crate::test_utils::assert_approx_eq!(tr.w_axis, Vec4::W);
+ Self {
+ x_row: tr.x_axis.to_array(),
+ y_row: tr.y_axis.to_array(),
+ z_row: tr.z_axis.to_array(),
+ }
+ }
+}
+
+impl GpuCompressedTransform {
+ /// Returns the translation as represented by this transform.
+ #[allow(dead_code)]
+ pub fn translation(&self) -> Vec3 {
+ Vec3 {
+ x: self.x_row[3],
+ y: self.y_row[3],
+ z: self.z_row[3],
+ }
+ }
+}
+
+/// Extension trait for shader types stored in a WGSL storage buffer.
+pub(crate) trait StorageType {
+ /// Get the aligned size, in bytes, of this type such that it aligns to the
+ /// given alignment, in bytes.
+ ///
+ /// This is mainly used to align GPU types to device requirements.
+ fn aligned_size(alignment: u32) -> NonZeroU64;
+
+ /// Get the WGSL padding code to append to the GPU struct to align it.
+ ///
+ /// This is useful if the struct needs to be bound directly with a dynamic
+ /// bind group offset, which requires the offset to be a multiple of a GPU
+ /// device specific alignment value.
+ fn padding_code(alignment: u32) -> String;
+}
+
+impl<T: ShaderType> StorageType for T {
+ fn aligned_size(alignment: u32) -> NonZeroU64 {
+ NonZeroU64::new(T::min_size().get().next_multiple_of(alignment as u64)).unwrap()
+ }
+
+ fn padding_code(alignment: u32) -> String {
+ let aligned_size = T::aligned_size(alignment);
+ trace!(
+ "Aligning {} to {} bytes as device limits requires. Orignal size: {} bytes. Aligned size: {} bytes.",
+ std::any::type_name::<T>(),
+ alignment,
+ T::min_size().get(),
+ aligned_size
+ );
+
+ // We need to pad the Spawner WGSL struct based on the device padding so that we
+ // can use it as an array element but also has a direct struct binding.
+ if T::min_size() != aligned_size {
+ let padding_size = aligned_size.get() - T::min_size().get();
+ assert!(padding_size % 4 == 0);
+ format!("padding: array<u32, {}>", padding_size / 4)
+ } else {
+ "".to_string()
+ }
+ }
+}
+
+/// GPU representation of spawner parameters.
+#[repr(C)]
+#[derive(Debug, Default, Clone, Copy, Pod, Zeroable, ShaderType)]
+pub(crate) struct GpuSpawnerParams {
+ /// Transform of the effect (origin of the emitter). This is either added to
+ /// emitted particles at spawn time, if the effect simulated in world
+ /// space, or to all simulated particles during rendering if the effect is
+ /// simulated in local space.
+ transform: GpuCompressedTransform,
+ /// Inverse of [`transform`], stored with the same convention.
+ ///
+ /// [`transform`]: Self::transform
+ inverse_transform: GpuCompressedTransform,
+ /// Number of particles to spawn this frame.
+ spawn: i32,
+ /// Spawn seed, for randomized modifiers.
+ seed: u32,
+ /// Index of the pong (read) buffer for indirect indices, used by the render
+ /// shader to fetch particles and render them. Only temporarily stored
+ /// between indirect and render passes, and overwritten each frame by CPU
+ /// upload. This is mostly a hack to transfer a value between those 2
+ /// compute passes.
+ render_pong: u32,
+ /// Index of the [`GpuEffectMetadata`] for this effect.
+ effect_metadata_index: u32,
+ /// Index of the [`GpuDrawIndirect`] or [`GpuDrawIndexedIndirect`] for this
+ /// effect.
+ draw_indirect_index: u32,
+ /// Start offset of the particles and indirect indices into the effect's
+ /// slab, in number of particles (row index).
+ slab_offset: u32,
+ /// Start offset of the particles and indirect indices into the parent
+ /// effect's slab (if the effect has a parent effect), in number of
+ /// particles (row index). This is ignored if the effect has no parent.
+ parent_slab_offset: u32,
+ // For Pod
+ _padding0: u32,
+}
+
+impl GpuSpawnerParams {
+ /// Create a new [`GpuSpawnerParams`] from gathered CPU data.
+ pub fn new(
+ global_transform: &GlobalTransform,
+ spawn_count: u32,
+ prng_seed: u32,
+ slab_offset: u32,
+ parent_slab_offset: Option<u32>,
+ effect_metadata_buffer_table_id: BufferTableId,
+ maybe_cached_draw_indirect_args: Option<&CachedDrawIndirectArgs>,
+ ) -> Self {
+ let transform = global_transform.to_matrix().into();
+ let inverse_transform = Mat4::from(
+ // Inverse the Affine3A first, then convert to Mat4. This is a lot more
+ // efficient than inversing the Mat4.
+ global_transform.affine().inverse(),
+ )
+ .into();
+ Self {
+ transform,
+ inverse_transform,
+ spawn: spawn_count as i32,
+ seed: prng_seed,
+ effect_metadata_index: effect_metadata_buffer_table_id.0,
+ draw_indirect_index: maybe_cached_draw_indirect_args
+ .map(|cdia| cdia.get_row().0)
+ .unwrap_or_default(),
+ slab_offset,
+ parent_slab_offset: parent_slab_offset.unwrap_or(u32::MAX),
+ ..default()
+ }
+ }
+}
+
+/// GPU representation of an indirect compute dispatch input.
+///
+/// Note that unlike most other data structure, this doesn't need to be aligned
+/// (except for the default 4-byte align for most GPU types) to any uniform or
+/// storage buffer offset alignment, because the buffer storing this is only
+/// ever used as input to indirect dispatch commands, and never bound as a
+/// shader resource.
+///
+/// See https://docs.rs/wgpu/latest/wgpu/util/struct.DispatchIndirectArgs.html.
+#[repr(C)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Pod, Zeroable, ShaderType)]
+pub struct GpuDispatchIndirectArgs {
+ pub x: u32,
+ pub y: u32,
+ pub z: u32,
+}
+
+impl Default for GpuDispatchIndirectArgs {
+ fn default() -> Self {
+ Self { x: 0, y: 1, z: 1 }
+ }
+}
+
+/// GPU representation of an indirect (non-indexed) render input.
+///
+/// Note that unlike most other data structure, this doesn't need to be aligned
+/// (except for the default 4-byte align for most GPU types) to any uniform or
+/// storage buffer offset alignment, because the buffer storing this is only
+/// ever used as input to indirect render commands, and never bound as a shader
+/// resource.
+///
+/// See https://docs.rs/wgpu/latest/wgpu/util/struct.DrawIndirectArgs.html.
+#[repr(C)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Pod, Zeroable, ShaderType)]
+pub struct GpuDrawIndirectArgs {
+ pub vertex_count: u32,
+ pub instance_count: u32,
+ pub first_vertex: u32,
+ pub first_instance: u32,
+}
+
+impl Default for GpuDrawIndirectArgs {
+ fn default() -> Self {
+ Self {
+ vertex_count: 0,
+ instance_count: 1,
+ first_vertex: 0,
+ first_instance: 0,
+ }
+ }
+}
+
+/// GPU representation of an indirect indexed render input.
+///
+/// Note that unlike most other data structure, this doesn't need to be aligned
+/// (except for the default 4-byte align for most GPU types) to any uniform or
+/// storage buffer offset alignment, because the buffer storing this is only
+/// ever used as input to indirect render commands, and never bound as a shader
+/// resource.
+///
+/// See https://docs.rs/wgpu/latest/wgpu/util/struct.DrawIndexedIndirectArgs.html.
+#[repr(C)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Pod, Zeroable, ShaderType)]
+pub struct GpuDrawIndexedIndirectArgs {
+ pub index_count: u32,
+ pub instance_count: u32,
+ pub first_index: u32,
+ pub base_vertex: i32,
+ pub first_instance: u32,
+}
+
+impl Default for GpuDrawIndexedIndirectArgs {
+ fn default() -> Self {
+ Self {
+ index_count: 0,
+ instance_count: 1,
+ first_index: 0,
+ base_vertex: 0,
+ first_instance: 0,
+ }
+ }
+}
+
+/// Shared info for a single batch (single shader invocation).
+#[repr(C)]
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Pod, Zeroable, ShaderType)]
+pub struct GpuBatchInfo {
+ /// Total number of CPU particles to spawn. This is the sum of all `spawn`
+ /// counts of all effect instances in this batch which spawn CPU-based
+ /// particles. This is uploaded from CPU each frame.
+ pub total_spawn_count: u32,
+ /// Total number of CPU particles to update. This is the sum of all
+ /// `alive_count` of all effect instances in this batch. This is calculated
+ /// on GPU each frame, between the init and update passes.
+ pub total_update_count: u32,
+ /// Start index of the slice of [`GpuSpawnerInfo`] for this batch, into the
+ /// [`EffectsMeta::spawner_buffer`]. The slice length is equal to the number
+ /// of effects instances batched together.
+ pub spawner_base: u32,
+ /// Offset to apply to the workgroup thread index to determine the global
+ /// particle index in the currently bound slab. This is often (and ideally)
+ /// zero, but may be > 0 if the entire slab cannot be processed with a
+ /// single batch.
+ pub base_particle: u32,
+ /// Offset, in u32 count (4 bytes), into the prefix sum buffer where the
+ /// first value for this batch is located.
+ pub prefix_sum_offset: u32,
+ /// Number of consecutive values in the prefix sum buffer for this batch.
+ /// This is the number of effects batches together in the batch.
+ pub prefix_sum_count: u32,
+}
+
+/// Metadata describing a single effect instance.
+///
+/// The metadata describes various effect settings, as well we the location in
+/// GPU buffers of the piece of data associated with that instance.
+///
+/// This is the CPU representation equivalent to the WGSL structure on GPU
+/// `EffectMetadata`.
+#[repr(C)]
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Pod, Zeroable, ShaderType)]
+pub struct GpuEffectMetadata {
+ //
+ // Some runtime variables modified on GPU only (capacity is constant)
+ /// Effect capacity, in number of particles.
+ pub capacity: u32,
+ // Additional data not part of the required draw indirect args
+ /// Number of alive particles.
+ pub alive_count: u32,
+ /// Cached value of `alive_count` to cap threads in update pass.
+ pub max_update: u32,
+ /// Cached value of `dead_count` to cap threads in init pass.
+ pub max_spawn: u32,
+ /// Index of the ping buffer for particle indices. Init and update compute
+ /// passes always write into the ping buffer and read from the pong buffer.
+ /// The buffers are swapped (ping = 1 - ping) during the indirect dispatch.
+ pub indirect_write_index: u32,
+
+ /// Index of the [`GpuDrawIndirect`] or [`GpuDrawIndexedIndirect`] struct
+ /// inside the global [`EffectsMeta::draw_indirect_buffer`] or
+ /// [`EffectsMeta::draw_indexed_indirect_buffer`]. The actual buffer depends
+ /// on whether the mesh is indexed or not, which is stored in
+ /// [`CachedMeshLocation`].
+ pub indirect_draw_index: u32,
+ /// Offset (in u32 count) of the init indirect dispatch struct inside its
+ /// buffer. This avoids having to align those 16-byte structs to the GPU
+ /// alignment (at least 32 bytes, even 256 bytes on some).
+ pub init_indirect_dispatch_index: u32,
+ /// Array index of the property block for this
+ /// effect. This is ignored if the effect doesn't use properties.
+ pub properties_array_index: u32,
+ /// Index of this effect into its parent's ChildInfo array
+ /// ([`EffectChildren::effect_cache_ids`] and its associated GPU
+ /// array). This starts at zero for the first child of each effect, and is
+ /// only unique per parent, not globally. Only available if this effect is a
+ /// child of another effect (i.e. if it has a parent).
+ pub local_child_index: u32,
+ /// For children, global index of the ChildInfo into the shared array.
+ pub global_child_index: u32,
+ /// For parents, base index of the their first ChildInfo into the shared
+ /// array.
+ pub base_child_index: u32,
+
+ /// Particle stride, in number of u32.
+ pub particle_stride: u32,
+ /// Offset from the particle start to the first sort key, in number of u32.
+ pub sort_key_offset: u32,
+ /// Offset from the particle start to the second sort key, in number of u32.
+ pub sort_key2_offset: u32,
+
+ //
+ // Again some runtime-only GPU-mutated data
+ /// Atomic counter incremented each time a particle spawns. Useful for
+ /// things like RIBBON_ID or any other use where a unique value is needed.
+ /// The value loops back after some time, but unless some particle lives
+ /// forever there's little chance of repetition.
+ pub particle_counter: u32,
+}
+
+/// Single init fill dispatch item in an [`InitFillDispatchQueue`].
+#[derive(Debug)]
+pub(super) struct InitFillDispatchItem {
+ /// Index of the source [`GpuChildInfo`] entry to read the event count from.
+ pub global_child_index: u32,
+ /// Index of the [`GpuDispatchIndirect`] entry to write the workgroup count
+ /// to.
+ pub dispatch_indirect_index: u32,
+}
+
+/// Queue of fill dispatch operations for the init indirect pass.
+///
+/// The queue stores the init fill dispatch operations for the current frame,
+/// without the reference to the source and destination buffers, which may be
+/// reallocated later in the frame. This allows enqueuing operations during the
+/// prepare rendering phase, while deferring GPU buffer (re-)allocation to a
+/// later stage.
+#[derive(Debug, Default, Resource)]
+pub(super) struct InitFillDispatchQueue {
+ queue: Vec<InitFillDispatchItem>,
+ submitted_queue_index: Option<u32>,
+}
+
+impl InitFillDispatchQueue {
+ /// Clear the queue.
+ #[inline]
+ pub fn clear(&mut self) {
+ self.queue.clear();
+ self.submitted_queue_index = None;
+ }
+
+ /// Check if the queue is empty.
+ #[inline]
+ pub fn is_empty(&self) -> bool {
+ self.queue.is_empty()
+ }
+
+ /// Enqueue a new operation.
+ #[inline]
+ pub fn enqueue(&mut self, global_child_index: u32, dispatch_indirect_index: u32) {
+ assert!(global_child_index != u32::MAX);
+ self.queue.push(InitFillDispatchItem {
+ global_child_index,
+ dispatch_indirect_index,
+ });
+ }
+
+ /// Submit pending operations for this frame.
+ pub fn submit(
+ &mut self,
+ src_buffer: &Buffer,
+ dst_buffer: &Buffer,
+ gpu_buffer_operations: &mut GpuBufferOperations,
+ ) {
+ if self.queue.is_empty() {
+ return;
+ }
+
+ // Sort by source. We can only batch if the destination is also contiguous, so
+ // we can check with a linear walk if the source is already sorted.
+ self.queue
+ .sort_unstable_by_key(|item| item.global_child_index);
+
+ let mut fill_queue = GpuBufferOperationQueue::new();
+
+ // Batch and schedule all init indirect dispatch operations
+ assert!(
+ self.queue[0].global_child_index != u32::MAX,
+ "Global child index not initialized"
+ );
+ let mut src_start = self.queue[0].global_child_index;
+ let mut dst_start = self.queue[0].dispatch_indirect_index;
+ let mut src_end = src_start + 1;
+ let mut dst_end = dst_start + 1;
+ let src_stride = GpuChildInfo::min_size().get() as u32 / 4;
+ let dst_stride = GpuDispatchIndirectArgs::SHADER_SIZE.get() as u32 / 4;
+ for i in 1..self.queue.len() {
+ let InitFillDispatchItem {
+ global_child_index: src,
+ dispatch_indirect_index: dst,
+ } = self.queue[i];
+ if src != src_end || dst != dst_end {
+ let count = src_end - src_start;
+ debug_assert_eq!(count, dst_end - dst_start);
+ let args = GpuBufferOperationArgs {
+ src_offset: src_start * src_stride + 1,
+ src_stride,
+ dst_offset: dst_start * dst_stride,
+ dst_stride,
+ count,
+ thread_group_size: 1,
+ };
+ trace!(
+ "enqueue_init_fill(): src:global_child_index={} dst:init_indirect_dispatch_index={} args={:?} src_buffer={:?} dst_buffer={:?}",
+ src_start,
+ dst_start,
+ args,
+ src_buffer.id(),
+ dst_buffer.id(),
+ );
+ fill_queue.enqueue(
+ GpuBufferOperationType::FillDispatchArgs,
+ args,
+ src_buffer.clone(),
+ None,
+ dst_buffer.clone(),
+ None,
+ );
+ src_start = src;
+ dst_start = dst;
+ }
+ src_end = src + 1;
+ dst_end = dst + 1;
+ }
+ if src_start != src_end || dst_start != dst_end {
+ let count = src_end - src_start;
+ debug_assert_eq!(count, dst_end - dst_start);
+ let args = GpuBufferOperationArgs {
+ src_offset: src_start * src_stride + 1,
+ src_stride,
+ dst_offset: dst_start * dst_stride,
+ dst_stride,
+ count,
+ thread_group_size: 1,
+ };
+ trace!(
+ "IFDA::submit(): src:global_child_index={} dst:init_indirect_dispatch_index={} args={:?} src_buffer={:?} dst_buffer={:?}",
+ src_start,
+ dst_start,
+ args,
+ src_buffer.id(),
+ dst_buffer.id(),
+ );
+ fill_queue.enqueue(
+ GpuBufferOperationType::FillDispatchArgs,
+ args,
+ src_buffer.clone(),
+ None,
+ dst_buffer.clone(),
+ None,
+ );
+ }
+
+ debug_assert!(self.submitted_queue_index.is_none());
+ if !fill_queue.operation_queue.is_empty() {
+ self.submitted_queue_index = Some(gpu_buffer_operations.submit(fill_queue));
+ }
+ }
+}
+
+/// Single sort fill dispatch item in a [`SortFillDispatchQueue`].
+#[derive(Debug)]
+pub(super) struct SortFillDispatchItem {
+ /// Metadata table entry of the ribbon effect batch to read the
+ /// [`GpuEffectMetadata::alive_count`] from.
+ pub metadata_table_id: BufferTableId,
+ /// Index into the prefix sum buffer where the post-update alive count is
+ /// copied before calculating the sort prefix sum.
+ pub prefix_sum_index: u32,
+ /// Index of the [`GpuDispatchIndirect`] entry to write the workgroup count
+ /// to, for the sort-fill pass (1 thread per particle).
+ pub sort_fill_indirect_dispatch_index: u32,
+ /// Index of the [`GpuDispatchIndirect`] entry to write the workgroup count
+ /// to, for the sort pass (1 thread per 16-particle group).
+ pub sort_indirect_dispatch_index: u32,
+}
+
+/// Indices of the GPU operation queues needed to prepare a ribbon sort.
+#[derive(Debug, Default)]
+pub(super) struct SortFillDispatchQueueIndices {
+ /// Queue which copies post-update alive counts into the prefix sum buffer.
+ pub alive_count_copy: Option<u32>,
+ /// Queue which creates the indirect sort-fill dispatch arguments. This uses
+ /// 1 thread per particle, total alive_count threads.
+ pub fill_dispatch: Option<u32>,
+ /// Queue which creates the indirect sort dispatch arguments. This uses 1
+ /// thread per 16 particles, total alive_count.div_ceil(16) threads.
+ pub sort_dispatch: Option<u32>,
+}
+
+/// Queue of fill dispatch operations for the ribbon particle sort pass.
+///
+/// The queue stores the sort fill dispatch operations for the current frame,
+/// without the reference to the effect metadata buffer, which may be
+/// reallocated later in the frame. This allows enqueuing operations during
+/// batching, while deferring the buffer capture to after the metadata buffer is
+/// (re-)allocated. Mirrors [`InitFillDispatchQueue`].
+#[derive(Debug, Default, Resource)]
+pub(super) struct SortFillDispatchQueue {
+ queue: Vec<SortFillDispatchItem>,
+}
+
+impl SortFillDispatchQueue {
+ /// Clear the queue.
+ #[inline]
+ pub fn clear(&mut self) {
+ self.queue.clear();
+ }
+
+ /// Check if no ribbon sort dispatch operations were queued this frame.
+ #[inline]
+ pub fn is_empty(&self) -> bool {
+ self.queue.is_empty()
+ }
+
+ /// Enqueue a new operation.
+ #[inline]
+ pub fn enqueue(
+ &mut self,
+ metadata_table_id: BufferTableId,
+ prefix_sum_index: u32,
+ sort_fill_indirect_dispatch_index: u32,
+ sort_indirect_dispatch_index: u32,
+ ) {
+ self.queue.push(SortFillDispatchItem {
+ metadata_table_id,
+ prefix_sum_index,
+ sort_fill_indirect_dispatch_index,
+ sort_indirect_dispatch_index,
+ });
+ }
+
+ /// Submit the queued operations, returning the index of the submitted queue
+ /// (or `None` if there was nothing to submit). Must be called after
+ /// `effect_metadata_buffer` has been (re-)allocated for the frame.
+ pub fn submit(
+ &self,
+ effect_metadata_buffer: &BufferTable<GpuEffectMetadata>,
+ prefix_sum_buffer: &Buffer,
+ sort_bind_groups: &SortBindGroups,
+ gpu_buffer_operations: &mut GpuBufferOperations,
+ ) -> SortFillDispatchQueueIndices {
+ if self.queue.is_empty() {
+ return default();
+ }
+
+ let Some(src_buffer) = effect_metadata_buffer.buffer() else {
+ error!("Failed to find effect metadata buffer. This is a bug.");
+ return default();
+ };
+ let Some(dst_buffer) = sort_bind_groups.indirect_args_buffer() else {
+ error!("Missing indirect dispatch buffer for sorting, cannot schedule particle sort for ribbons. This is a bug.");
+ return default();
+ };
+
+ let alive_count_offset = std::mem::offset_of!(GpuEffectMetadata, alive_count) as u32 / 4;
+ debug_assert_eq!(
+ alive_count_offset, 1,
+ "GpuEffectMetadata changed, update this assert."
+ );
+ let src_stride = GpuEffectMetadata::SHADER_SIZE.get() as u32 / 4;
+ let dst_stride = GpuDispatchIndirectArgs::SHADER_SIZE.get() as u32 / 4;
+
+ let mut alive_count_copy_queue = GpuBufferOperationQueue::new();
+ let mut fill_queue = GpuBufferOperationQueue::new();
+ let mut sort_queue = GpuBufferOperationQueue::new();
+ for item in &self.queue {
+ let src_binding_offset = effect_metadata_buffer.dynamic_offset(item.metadata_table_id);
+ debug_assert_eq!(
+ src_binding_offset % 4,
+ 0,
+ "Effect metadata offset must be u32-aligned."
+ );
+ let src_offset = src_binding_offset / 4 + alive_count_offset;
+ trace!(
+ "queue_sort_alive_count_copy(): src#{:?}@+{}B -> dst#{:?}[{}]",
+ src_buffer.id(),
+ src_binding_offset,
+ prefix_sum_buffer.id(),
+ item.prefix_sum_index,
+ );
+
+ // Enqueue an op to copy alive_count into the prefix sum buffer
+ alive_count_copy_queue.enqueue(
+ GpuBufferOperationType::Copy,
+ GpuBufferOperationArgs {
+ src_offset,
+ src_stride,
+ dst_offset: item.prefix_sum_index,
+ dst_stride: 1,
+ count: 1,
+ thread_group_size: 1,
+ },
+ src_buffer.clone(),
+ None,
+ prefix_sum_buffer.clone(),
+ None,
+ );
+
+ // Enqueue an op to calculate from alive_count the number of workgroups for the
+ // sort-fill pass
+ let dst_offset = sort_bind_groups
+ .get_indirect_args_byte_offset(item.sort_fill_indirect_dispatch_index)
+ / 4;
+ fill_queue.enqueue(
+ GpuBufferOperationType::FillDispatchArgs,
+ GpuBufferOperationArgs {
+ src_offset,
+ src_stride,
+ dst_offset: dst_offset as u32,
+ dst_stride,
+ count: 1,
+ thread_group_size: 1,
+ },
+ src_buffer.clone(),
+ None,
+ dst_buffer.clone(),
+ None,
+ );
+
+ // Enqueue an op to calculate from alive_count the number of workgroups for the
+ // sort pass
+ let dst_offset = sort_bind_groups
+ .get_indirect_args_byte_offset(item.sort_indirect_dispatch_index)
+ / 4;
+ sort_queue.enqueue(
+ GpuBufferOperationType::FillDispatchArgs,
+ GpuBufferOperationArgs {
+ src_offset,
+ src_stride,
+ dst_offset: dst_offset as u32,
+ dst_stride,
+ count: 1,
+ thread_group_size: 16, // numItemPerThread=16; see shader
+ },
+ src_buffer.clone(),
+ None,
+ dst_buffer.clone(),
+ None,
+ );
+
+ trace!(
+ "queue_sort_fill_dispatch(): src#{:?}@+{}B ({}B) -> dst#{:?}@+{}B (whole)",
+ src_buffer.id(),
+ src_binding_offset,
+ src_stride,
+ dst_buffer.id(),
+ dst_offset * 4,
+ );
+ }
+
+ let alive_count_copy = if alive_count_copy_queue.operation_queue.is_empty() {
+ None
+ } else {
+ Some(gpu_buffer_operations.submit(alive_count_copy_queue))
+ };
+ let fill_dispatch = if fill_queue.operation_queue.is_empty() {
+ None
+ } else {
+ Some(gpu_buffer_operations.submit(fill_queue))
+ };
+ let sort_dispatch = if sort_queue.operation_queue.is_empty() {
+ None
+ } else {
+ Some(gpu_buffer_operations.submit(sort_queue))
+ };
+ SortFillDispatchQueueIndices {
+ alive_count_copy,
+ fill_dispatch,
+ sort_dispatch,
+ }
+ }
+}
+
+/// Compute pipeline to run the `vfx_indirect` dispatch workgroup calculation
+/// shader.
+#[derive(Resource)]
+pub(crate) struct DispatchIndirectPipeline {
+ /// Layout of bind group sim_params@0.
+ sim_params_bind_group_layout_desc: BindGroupLayoutDescriptor,
+ /// Layout of bind group effect_metadata@1.
+ effect_metadata_bind_group_layout_desc: BindGroupLayoutDescriptor,
+ /// Layout of bind group spawner@2.
+ spawner_bind_group_layout_desc: BindGroupLayoutDescriptor,
+ /// Layout of bind group child_infos@3.
+ child_infos_bind_group_layout_desc: BindGroupLayoutDescriptor,
+ /// Shader when no GPU events are used (no bind group @3).
+ indirect_shader_noevent: Handle<Shader>,
+ /// Shader when GPU events are used (bind group @3 present).
+ indirect_shader_events: Handle<Shader>,
+}
+
+impl FromWorld for DispatchIndirectPipeline {
+ fn from_world(world: &mut World) -> Self {
+ let render_device = world.get_resource::<RenderDevice>().unwrap();
+
+ // Copy the indirect pipeline shaders to self, because we can't access anything
+ // else during pipeline specialization.
+ let (indirect_shader_noevent, indirect_shader_events) = {
+ let effects_meta = world.get_resource::<EffectsMeta>().unwrap();
+ (
+ effects_meta.indirect_shader_noevent.clone(),
+ effects_meta.indirect_shader_events.clone(),
+ )
+ };
+
+ let storage_alignment = render_device.limits().min_storage_buffer_offset_alignment;
+ let spawner_min_binding_size = GpuSpawnerParams::aligned_size(storage_alignment);
+
+ // @group(0) @binding(0) var<uniform> sim_params : SimParams;
+ trace!("GpuSimParams: min_size={}", GpuSimParams::min_size());
+ let sim_params_bind_group_layout_desc = BindGroupLayoutDescriptor::new(
+ "hanabi:bgl:dispatch_indirect:sim_params",
+ &BindGroupLayoutEntries::single(
+ ShaderStages::COMPUTE,
+ uniform_buffer::<GpuSimParams>(false),
+ ),
+ );
+
+ trace!(
+ "GpuEffectMetadata: min_size={}",
+ GpuEffectMetadata::min_size()
+ );
+ let effect_metadata_bind_group_layout_desc = BindGroupLayoutDescriptor::new(
+ "hanabi:bgl:dispatch_indirect:effect_metadata@1",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE,
+ (
+ // @group(1) @binding(0) var<storage, read_write> effect_metadatas :
+ // array<EffectMetadata>;
+ storage_buffer::<GpuEffectMetadata>(false),
+ // @group(1) @binding(1) var<storage, read_write> draw_indirect_buffer :
+ // array<u32>;
+ storage_buffer::<GpuDrawIndexedIndirectArgs>(false),
+ ),
+ ),
+ );
+
+ trace!(
+ "GpuSpawnerParams: min_size={} spawner_min_binding_size={}",
+ GpuSpawnerParams::min_size(),
+ spawner_min_binding_size
+ );
+ let spawner_bind_group_layout_desc = BindGroupLayoutDescriptor::new(
+ "hanabi:bgl:dispatch_indirect:spawner@2",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE,
+ (
+ // @group(2) @binding(0) var<storage, read_write> spawner_buffer :
+ // array<Spawner>;
+ //storage_buffer::<GpuSpawnerParams>(false), // TODO - vfx_sort_fill still
+ // needs aligned
+ storage_buffer_sized(false, Some(spawner_min_binding_size)),
+ // @group(2) @binding(1) var<storage, read_write> prefix_sum : array<u32>;
+ storage_buffer::<u32>(false),
+ ),
+ ),
+ );
+
+ trace!("GpuChildInfo: min_size={}", GpuChildInfo::min_size());
+ let child_infos_bind_group_layout_desc = BindGroupLayoutDescriptor::new(
+ "hanabi:bgl:dispatch_indirect:child_infos@3",
+ &BindGroupLayoutEntries::single(
+ ShaderStages::COMPUTE,
+ // @group(3) @binding(0) var<storage, read_write> child_info_buffer :
+ // ChildInfoBuffer;
+ storage_buffer::<GpuChildInfo>(false),
+ ),
+ );
+
+ Self {
+ sim_params_bind_group_layout_desc,
+ effect_metadata_bind_group_layout_desc,
+ spawner_bind_group_layout_desc,
+ child_infos_bind_group_layout_desc,
+ indirect_shader_noevent,
+ indirect_shader_events,
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub(crate) struct DispatchIndirectPipelineKey {
+ /// True if any allocated effect uses GPU spawn events. In that case, the
+ /// pipeline is specialized to clear all GPU events each frame after the
+ /// indirect init pass consumed them to spawn particles, and before the
+ /// update pass optionally produce more events.
+ /// Key: HAS_GPU_SPAWN_EVENTS
+ has_events: bool,
+}
+
+impl SpecializedComputePipeline for DispatchIndirectPipeline {
+ type Key = DispatchIndirectPipelineKey;
+
+ fn specialize(&self, key: Self::Key) -> ComputePipelineDescriptor {
+ trace!(
+ "Specializing indirect pipeline (has_events={})",
+ key.has_events
+ );
+
+ let mut shader_defs = Vec::with_capacity(2);
+ if key.has_events {
+ shader_defs.push("HAS_GPU_SPAWN_EVENTS".into());
+ }
+
+ let mut layout = Vec::with_capacity(4);
+ layout.push(self.sim_params_bind_group_layout_desc.clone());
+ layout.push(self.effect_metadata_bind_group_layout_desc.clone());
+ layout.push(self.spawner_bind_group_layout_desc.clone());
+ if key.has_events {
+ layout.push(self.child_infos_bind_group_layout_desc.clone());
+ }
+
+ let label = format!(
+ "hanabi:compute_pipeline:dispatch_indirect{}",
+ if key.has_events {
+ "_events"
+ } else {
+ "_noevent"
+ }
+ );
+
+ ComputePipelineDescriptor {
+ constants: default(),
+ label: Some(label.into()),
+ layout,
+ immediate_size: 0,
+ shader: if key.has_events {
+ self.indirect_shader_events.clone()
+ } else {
+ self.indirect_shader_noevent.clone()
+ },
+ shader_defs,
+ entry_point: Some("main".into()),
+ zero_initialize_workgroup_memory: false,
+ }
+ }
+}
+
+/// Compute pipeline to run the `vfx_prefix_sum` dispatch workgroup calculation
+/// shader.
+#[derive(Resource)]
+pub(crate) struct PrefixSumPipeline {
+ /// Layout of the (only) bind group.
+ bind_group_layout_desc: BindGroupLayoutDescriptor,
+ /// Shader.
+ compute_shader: Handle<Shader>,
+}
+
+impl FromWorld for PrefixSumPipeline {
+ fn from_world(world: &mut World) -> Self {
+ // FIXME - we don't really need to keep this in EffectsMeta, could move here,
+ // and replace the FromWorld with Default
+ let compute_shader = {
+ let effects_meta = world.get_resource::<EffectsMeta>().unwrap();
+ effects_meta.prefix_sum_shader.clone()
+ };
+ let min_storage_buffer_offset_alignment = {
+ let render_device = world.get_resource::<RenderDevice>().unwrap();
+ render_device.limits().min_storage_buffer_offset_alignment
+ };
+
+ let bind_group_layout_desc = BindGroupLayoutDescriptor::new(
+ "hanabi:bgl:prefix_sum:@0",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE,
+ (
+ // @group(0) @binding(0) var<storage, read_write> batch_infos :
+ // array<BatchInfo>;
+ storage_buffer_sized(
+ false,
+ Some(GpuBatchInfo::aligned_size(
+ min_storage_buffer_offset_alignment,
+ )),
+ ),
+ // @group(0) @binding(1) var<storage, read_write> prefix_sum : array<u32>;
+ storage_buffer::<u32>(false),
+ // @group(0) @binding(2) var<storage, read_write> dispatch_indirect_buffer :
+ // array<DispatchIndirectArgs>;
+ storage_buffer::<GpuDispatchIndirectArgs>(false),
+ ),
+ ),
+ );
+
+ Self {
+ bind_group_layout_desc,
+ compute_shader,
+ }
+ }
+}
+
+impl PrefixSumPipeline {
+ pub fn make_pipeline_desc(&self) -> ComputePipelineDescriptor {
+ trace!("Create prefix sum pipeline");
+
+ ComputePipelineDescriptor {
+ constants: default(),
+ label: Some("hanabi:compute_pipeline:prefix_sum".into()),
+ layout: vec![self.bind_group_layout_desc.clone()],
+ immediate_size: 0,
+ shader: self.compute_shader.clone(),
+ shader_defs: vec![],
+ entry_point: Some("main".into()),
+ zero_initialize_workgroup_memory: false,
+ }
+ }
+}
+
+/// Type of GPU buffer operation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(super) enum GpuBufferOperationType {
+ /// Clear the destination buffer to zero.
+ ///
+ /// The source parameters [`src_offset`] and [`src_stride`] are ignored.
+ ///
+ /// [`src_offset`]: crate::GpuBufferOperationArgs::src_offset
+ /// [`src_stride`]: crate::GpuBufferOperationArgs::src_stride
+ #[allow(dead_code)]
+ Zero,
+ /// Copy a source buffer into a destination buffer.
+ ///
+ /// The source can have a stride between each `u32` copied. The destination
+ /// is always a contiguous buffer.
+ #[allow(dead_code)]
+ Copy,
+ /// Fill the arguments for a later indirect dispatch call.
+ ///
+ /// This is similar to a copy, but will round up the source value to the
+ /// number of threads per workgroup (64) before writing it into the
+ /// destination.
+ FillDispatchArgs,
+ /// Fill the arguments for a later indirect dispatch call.
+ ///
+ /// This is the same as [`FillDispatchArgs`], but the source element count
+ /// is read from the fourth entry in the destination buffer directly,
+ /// and the source buffer and source arguments are unused.
+ #[allow(dead_code)]
+ FillDispatchArgsSelf,
+}
+
+/// GPU representation of the arguments of a block operation on a buffer.
+#[repr(C)]
+#[derive(Debug, Copy, Clone, PartialEq, Eq, Pod, Zeroable, ShaderType)]
+pub(super) struct GpuBufferOperationArgs {
+ /// Offset, as u32 count, where the operation starts in the source buffer.
+ src_offset: u32,
+ /// Stride, as u32 count, between elements in the source buffer.
+ src_stride: u32,
+ /// Offset, as u32 count, where the operation starts in the destination
+ /// buffer.
+ dst_offset: u32,
+ /// Stride, as u32 count, between elements in the destination buffer.
+ dst_stride: u32,
+ /// Number of u32 elements to process for this operation.
+ count: u32,
+ /// Thread group size.
+ thread_group_size: u32,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+struct QueuedOperationBindGroupKey {
+ src_buffer: BufferId,
+ src_binding_size: Option<NonZeroU32>,
+ dst_buffer: BufferId,
+ dst_binding_size: Option<NonZeroU32>,
+}
+
+/// A single GPU operation queued on the CPU.
+///
+/// The operation may involve multiple reads/writes; see
+/// [`GpuBufferOperationArgs::count`]. However it is guaranteed to be performed
+/// as a single transactional compute dispatch.
+#[derive(Debug, Clone)]
+struct QueuedOperation {
+ /// Type of GPU operation. This determines which compute shader is running.
+ op: GpuBufferOperationType,
+ /// Index into the shared arguments buffer of the arguments for this single
+ /// operation.
+ args_index: u32,
+ /// Source buffer the operation reads from.
+ src_buffer: Buffer,
+ /// Binding size of the source buffer, or `None` to bind the whole buffer.
+ src_binding_size: Option<NonZeroU32>,
+ /// Destination buffer the operation writes to.
+ dst_buffer: Buffer,
+ /// Binding size of the destination buffer, or `None` to bind the whole
+ /// buffer.
+ dst_binding_size: Option<NonZeroU32>,
+}
+
+impl QueuedOperation {
+ /// Get the buffer binding for the source buffer.
+ pub fn src_binding(&self) -> BindingResource<'_> {
+ BindingResource::Buffer(BufferBinding {
+ buffer: &self.src_buffer,
+ offset: 0,
+ size: self.src_binding_size.map(Into::into),
+ })
+ }
+
+ /// Get the buffer binding for the destination buffer.
+ pub fn dst_binding(&self) -> BindingResource<'_> {
+ BindingResource::Buffer(BufferBinding {
+ buffer: &self.dst_buffer,
+ offset: 0,
+ size: self.dst_binding_size.map(Into::into),
+ })
+ }
+}
+
+impl From<&QueuedOperation> for QueuedOperationBindGroupKey {
+ fn from(value: &QueuedOperation) -> Self {
+ Self {
+ src_buffer: value.src_buffer.id(),
+ src_binding_size: value.src_binding_size,
+ dst_buffer: value.dst_buffer.id(),
+ dst_binding_size: value.dst_binding_size,
+ }
+ }
+}
+
+/// Queue of GPU buffer operations.
+///
+/// The queue records a series of ordered operations on GPU buffers. It can be
+/// submitted for this frame via [`GpuBufferOperations::submit()`], and
+/// subsequently dispatched as a compute pass via
+/// [`GpuBufferOperations::dispatch()`].
+pub struct GpuBufferOperationQueue {
+ /// Operation arguments, one per queued operation. The meaning depends on
+ /// the [`GpuBufferOperationType`].
+ args: Vec<GpuBufferOperationArgs>,
+ /// Queued operations.
+ operation_queue: Vec<QueuedOperation>,
+}
+
+impl GpuBufferOperationQueue {
+ /// Create a new empty queue.
+ pub fn new() -> Self {
+ Self {
+ args: vec![],
+ operation_queue: vec![],
+ }
+ }
+
+ /// Enqueue a generic operation.
+ pub fn enqueue(
+ &mut self,
+ op: GpuBufferOperationType,
+ args: GpuBufferOperationArgs,
+ src_buffer: Buffer,
+ src_binding_size: Option<NonZeroU32>,
+ dst_buffer: Buffer,
+ dst_binding_size: Option<NonZeroU32>,
+ ) -> u32 {
+ assert!(args.thread_group_size > 0);
+ trace!(
+ "Queue {:?} op: args={:?} src_buffer={:?} src_binding_size={:?} dst_buffer={:?} dst_binding_size={:?}",
+ op,
+ args,
+ src_buffer,
+ src_binding_size,
+ dst_buffer,
+ dst_binding_size,
+ );
+ let args_index = self.args.len() as u32;
+ self.args.push(args);
+ self.operation_queue.push(QueuedOperation {
+ op,
+ args_index,
+ src_buffer,
+ src_binding_size,
+ dst_buffer,
+ dst_binding_size,
+ });
+ args_index
+ }
+}
+
+/// GPU buffer operations for this frame.
+///
+/// This resource contains a list of submitted [`GpuBufferOperationQueue`] for
+/// the current frame, and ensures the bind groups for those operations are up
+/// to date.
+#[derive(Resource)]
+pub(super) struct GpuBufferOperations {
+ /// Arguments for the buffer operations submitted this frame.
+ args_buffer: AlignedBufferVec<GpuBufferOperationArgs>,
+
+ /// Bind groups for the submitted operations.
+ bind_groups: HashMap<QueuedOperationBindGroupKey, BindGroup>,
+
+ /// Submitted queues for this frame.
+ queues: Vec<Vec<QueuedOperation>>,
+}
+
+impl FromWorld for GpuBufferOperations {
+ fn from_world(world: &mut World) -> Self {
+ let render_device = world.get_resource::<RenderDevice>().unwrap();
+ let align = render_device.limits().min_uniform_buffer_offset_alignment;
+ Self::new(align)
+ }
+}
+
+impl GpuBufferOperations {
+ pub fn new(align: u32) -> Self {
+ let args_buffer = AlignedBufferVec::new(
+ BufferUsages::UNIFORM,
+ Some(NonZeroU64::new(align as u64).unwrap()),
+ Some("hanabi:buffer:gpu_operation_args".to_string()),
+ );
+ Self {
+ args_buffer,
+ bind_groups: default(),
+ queues: vec![],
+ }
+ }
+
+ /// Clear the queue and begin recording operations for a new frame.
+ pub fn begin_frame(&mut self) {
+ self.args_buffer.clear();
+ self.bind_groups.clear(); // for now; might consider caching frame-to-frame
+ self.queues.clear();
+ }
+
+ /// Submit a recorded queue.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the queue submitted is empty.
+ pub fn submit(&mut self, mut queue: GpuBufferOperationQueue) -> u32 {
+ assert!(!queue.operation_queue.is_empty());
+ let queue_index = self.queues.len() as u32;
+ for qop in &mut queue.operation_queue {
+ qop.args_index = self.args_buffer.push(queue.args[qop.args_index as usize]) as u32;
+ }
+ self.queues.push(queue.operation_queue);
+ queue_index
+ }
+
+ /// Finish recording operations for this frame, and schedule buffer writes
+ /// to GPU.
+ pub fn end_frame(&mut self, device: &RenderDevice, render_queue: &RenderQueue) {
+ assert_eq!(
+ self.args_buffer.len(),
+ self.queues.iter().fold(0, |len, q| len + q.len())
+ );
+
+ // Upload to GPU buffer
+ if self.args_buffer.write_buffer(device, render_queue) {
+ // Buffer was reallocated; clear all bind groups depending on it
+ self.bind_groups.clear();
+ }
+ }
+
+ /// Create all necessary bind groups for all queued operations.
+ pub fn create_bind_groups(
+ &mut self,
+ render_device: &RenderDevice,
+ utils_pipeline: &UtilsPipeline,
+ ) {
+ trace!(
+ "Creating bind groups for {} operation queues...",
+ self.queues.len()
+ );
+ for queue in &self.queues {
+ for qop in queue {
+ let key: QueuedOperationBindGroupKey = qop.into();
+ self.bind_groups.entry(key).or_insert_with(|| {
+ let src_id: NonZeroU32 = qop.src_buffer.id().into();
+ let dst_id: NonZeroU32 = qop.dst_buffer.id().into();
+ let label = format!(
+ "hanabi:bg:util_{:?}_{}_{}",
+ qop.op,
+ src_id.get(),
+ dst_id.get()
+ );
+ let use_dynamic_offset = matches!(
+ qop.op,
+ GpuBufferOperationType::FillDispatchArgs | GpuBufferOperationType::Copy
+ );
+ let bind_group_layout: &BindGroupLayout =
+ utils_pipeline.bind_group_layout(qop.op, use_dynamic_offset);
+ trace!(
+ "-> Creating new bind group '{}': src#{} ({:?}B) -> dst#{} ({:?}B)",
+ label,
+ src_id,
+ qop.src_binding_size,
+ dst_id,
+ qop.dst_binding_size,
+ );
+ render_device.create_bind_group(
+ Some(&label[..]),
+ bind_group_layout,
+ &BindGroupEntries::sequential((
+ BindingResource::Buffer(BufferBinding {
+ buffer: self.args_buffer.buffer().unwrap(),
+ offset: 0,
+ // We always bind exactly 1 row of arguments
+ size: Some(
+ NonZeroU64::new(self.args_buffer.aligned_size() as u64)
+ .unwrap(),
+ ),
+ }),
+ qop.src_binding(),
+ qop.dst_binding(),
+ )),
+ )
+ });
+ }
+ }
+ }
+
+ /// Dispatch a submitted queue by index.
+ ///
+ /// This creates a new, optionally labelled, compute pass, and records to
+ /// the render context a series of compute workgroup dispatch, one for each
+ /// enqueued operation.
+ ///
+ /// The compute pipeline(s) used for each operation are fetched from the
+ /// [`UtilsPipeline`], and the associated bind groups are used from a
+ /// previous call to [`Self::create_bind_groups()`].
+ pub fn dispatch(
+ &self,
+ index: u32,
+ render_context: &mut RenderContext,
+ utils_pipeline: &UtilsPipeline,
+ compute_pass_label: Option<&str>,
+ ) {
+ let queue = &self.queues[index as usize];
+ trace!(
+ "Recording GPU commands for queue #{} ({} ops)...",
+ index,
+ queue.len(),
+ );
+
+ if queue.is_empty() {
+ return;
+ }
+
+ let mut compute_pass =
+ render_context
+ .command_encoder()
+ .begin_compute_pass(&ComputePassDescriptor {
+ label: compute_pass_label,
+ timestamp_writes: None,
+ });
+
+ let mut prev_op = None;
+ let mut prev_key = None;
+ let mut prev_dynamic_args_index = None;
+ for qop in queue {
+ trace!("qop={:?}", qop);
+
+ let pipeline_changed = Some(qop.op) != prev_op;
+ if pipeline_changed {
+ compute_pass.set_pipeline(utils_pipeline.get_pipeline(qop.op));
+ prev_op = Some(qop.op);
+ }
+
+ let key: QueuedOperationBindGroupKey = qop.into();
+ let use_dynamic_offset = matches!(
+ qop.op,
+ GpuBufferOperationType::FillDispatchArgs | GpuBufferOperationType::Copy
+ );
+ let bind_group_changed = Some(key) != prev_key;
+ let requires_bind_group_rebind = pipeline_changed
+ || bind_group_changed
+ || (use_dynamic_offset && Some(qop.args_index) != prev_dynamic_args_index);
+ if requires_bind_group_rebind {
+ if let Some(bind_group) = self.bind_groups.get(&key) {
+ if use_dynamic_offset {
+ let args_offset = self.args_buffer.dynamic_offset(qop.args_index as usize);
+ compute_pass.set_bind_group(0, bind_group, &[args_offset]);
+ trace!(
+ "set bind group with dynamic offsets: op={:?} args=+{}B",
+ qop.op,
+ args_offset,
+ );
+ } else {
+ compute_pass.set_bind_group(0, bind_group, &[]);
+ trace!("set bind group without dynamic offsets: op={:?}", qop.op);
+ }
+ } else {
+ error!("GPU fill dispatch buffer operation bind group not found for buffers src#{:?} dst#{:?}", qop.src_buffer.id(), qop.dst_buffer.id());
+ continue;
+ }
+ prev_key = Some(key);
+ prev_dynamic_args_index = use_dynamic_offset.then_some(qop.args_index);
+ }
+
+ // Dispatch the operations for this buffer
+ const WORKGROUP_SIZE: u32 = 64;
+ let num_ops = 1u32; // TODO - batching!
+ let workgroup_count = num_ops.div_ceil(WORKGROUP_SIZE);
+ compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
+ trace!(
+ "-> fill dispatch compute dispatched: num_ops={} workgroup_count={}",
+ num_ops,
+ workgroup_count
+ );
+ }
+ }
+}
+
+/// Compute pipeline to run the `vfx_utils` shader.
+#[derive(Resource)]
+pub(crate) struct UtilsPipeline {
+ #[allow(dead_code)]
+ bind_group_layout: BindGroupLayout,
+ bind_group_layout_dyn: BindGroupLayout,
+ bind_group_layout_no_src: BindGroupLayout,
+ pipelines: [ComputePipeline; 4],
+}
+
+impl FromWorld for UtilsPipeline {
+ fn from_world(world: &mut World) -> Self {
+ let render_device = world.get_resource::<RenderDevice>().unwrap();
+
+ let bind_group_layout = render_device.create_bind_group_layout(
+ "hanabi:bgl:utils",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE,
+ (
+ uniform_buffer::<GpuBufferOperationArgs>(false),
+ storage_buffer_read_only::<u32>(false),
+ storage_buffer::<u32>(false),
+ ),
+ ),
+ );
+
+ let pipeline_layout = render_device.create_pipeline_layout(&PipelineLayoutDescriptor {
+ label: Some("hanabi:pipeline_layout:utils"),
+ bind_group_layouts: &[Some(&bind_group_layout)],
+ immediate_size: 0,
+ });
+
+ let bind_group_layout_dyn = render_device.create_bind_group_layout(
+ "hanabi:bgl:utils_dyn",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE,
+ (
+ uniform_buffer::<GpuBufferOperationArgs>(true),
+ storage_buffer_read_only::<u32>(false),
+ storage_buffer::<u32>(false),
+ ),
+ ),
+ );
+
+ let pipeline_layout_dyn = render_device.create_pipeline_layout(&PipelineLayoutDescriptor {
+ label: Some("hanabi:pipeline_layout:utils_dyn"),
+ bind_group_layouts: &[Some(&bind_group_layout_dyn)],
+ immediate_size: 0,
+ });
+
+ let bind_group_layout_no_src = render_device.create_bind_group_layout(
+ "hanabi:bind_group_layout:utils_no_src",
+ &BindGroupLayoutEntries::with_indices(
+ ShaderStages::COMPUTE,
+ (
+ (0, uniform_buffer::<GpuBufferOperationArgs>(false)),
+ (2, storage_buffer::<u32>(false)),
+ ),
+ ),
+ );
+
+ let pipeline_layout_no_src =
+ render_device.create_pipeline_layout(&PipelineLayoutDescriptor {
+ label: Some("hanabi:pipeline_layout:utils_no_src"),
+ bind_group_layouts: &[Some(&bind_group_layout_no_src)],
+ immediate_size: 0,
+ });
+
+ let shader_code = include_str!("vfx_utils.wgsl");
+
+ let shader_source = ShaderSource::Wgsl(Cow::Borrowed(shader_code));
+
+ debug!("Create utils shader module:\n{}", shader_code);
+ #[allow(unsafe_code)]
+ let shader_module = unsafe {
+ render_device.create_shader_module(ShaderModuleDescriptor {
+ label: Some("hanabi:shader:utils"),
+ source: shader_source,
+ })
+ };
+
+ trace!("Create vfx_utils pipelines...");
+ let zero_pipeline = render_device.create_compute_pipeline(&RawComputePipelineDescriptor {
+ label: Some("hanabi:compute_pipeline:zero_buffer"),
+ layout: Some(&pipeline_layout),
+ module: &shader_module,
+ entry_point: Some("zero_buffer"),
+ compilation_options: PipelineCompilationOptions {
+ constants: &[],
+ zero_initialize_workgroup_memory: false,
+ },
+ cache: None,
+ });
+ let copy_pipeline = render_device.create_compute_pipeline(&RawComputePipelineDescriptor {
+ label: Some("hanabi:compute_pipeline:copy_buffer"),
+ layout: Some(&pipeline_layout_dyn),
+ module: &shader_module,
+ entry_point: Some("copy_buffer"),
+ compilation_options: PipelineCompilationOptions {
+ constants: &[],
+ zero_initialize_workgroup_memory: false,
+ },
+ cache: None,
+ });
+ let fill_dispatch_args_pipeline =
+ render_device.create_compute_pipeline(&RawComputePipelineDescriptor {
+ label: Some("hanabi:compute_pipeline:fill_dispatch_args"),
+ layout: Some(&pipeline_layout_dyn),
+ module: &shader_module,
+ entry_point: Some("fill_dispatch_args"),
+ compilation_options: PipelineCompilationOptions {
+ constants: &[],
+ zero_initialize_workgroup_memory: false,
+ },
+ cache: None,
+ });
+ let fill_dispatch_args_self_pipeline =
+ render_device.create_compute_pipeline(&RawComputePipelineDescriptor {
+ label: Some("hanabi:compute_pipeline:fill_dispatch_args_self"),
+ layout: Some(&pipeline_layout_no_src),
+ module: &shader_module,
+ entry_point: Some("fill_dispatch_args_self"),
+ compilation_options: PipelineCompilationOptions {
+ constants: &[],
+ zero_initialize_workgroup_memory: false,
+ },
+ cache: None,
+ });
+
+ Self {
+ bind_group_layout,
+ bind_group_layout_dyn,
+ bind_group_layout_no_src,
+ pipelines: [
+ zero_pipeline,
+ copy_pipeline,
+ fill_dispatch_args_pipeline,
+ fill_dispatch_args_self_pipeline,
+ ],
+ }
+ }
+}
+
+impl UtilsPipeline {
+ fn get_pipeline(&self, op: GpuBufferOperationType) -> &ComputePipeline {
+ match op {
+ GpuBufferOperationType::Zero => &self.pipelines[0],
+ GpuBufferOperationType::Copy => &self.pipelines[1],
+ GpuBufferOperationType::FillDispatchArgs => &self.pipelines[2],
+ GpuBufferOperationType::FillDispatchArgsSelf => &self.pipelines[3],
+ }
+ }
+
+ fn bind_group_layout(
+ &self,
+ op: GpuBufferOperationType,
+ with_dynamic_offsets: bool,
+ ) -> &BindGroupLayout {
+ if op == GpuBufferOperationType::FillDispatchArgsSelf {
+ assert!(
+ !with_dynamic_offsets,
+ "FillDispatchArgsSelf op cannot use dynamic offset (not implemented)"
+ );
+ &self.bind_group_layout_no_src
+ } else if with_dynamic_offsets {
+ &self.bind_group_layout_dyn
+ } else {
+ &self.bind_group_layout
+ }
+ }
+}
+
+#[derive(Resource)]
+pub(crate) struct ParticlesInitPipeline {
+ sim_params_layout_desc: BindGroupLayoutDescriptor,
+}
+
+impl Default for ParticlesInitPipeline {
+ fn default() -> Self {
+ let sim_params_layout_desc = BindGroupLayoutDescriptor::new(
+ "hanabi:bgl:vfx_init:sim_params@0",
+ // @group(0) @binding(0) var<uniform> sim_params: SimParams;
+ &BindGroupLayoutEntries::single(
+ ShaderStages::COMPUTE,
+ uniform_buffer::<GpuSimParams>(false),
+ ),
+ );
+
+ Self {
+ sim_params_layout_desc,
+ }
+ }
+}
+
+bitflags! {
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+ pub struct ParticleInitPipelineKeyFlags: u8 {
+ //const CLONE = (1u8 << 0); // DEPRECATED
+ const ATTRIBUTE_PREV = (1u8 << 1);
+ const ATTRIBUTE_NEXT = (1u8 << 2);
+ const CONSUME_GPU_SPAWN_EVENTS = (1u8 << 3);
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub(crate) struct ParticleInitPipelineKey {
+ /// Compute shader, with snippets applied, but not preprocessed yet.
+ shader: Handle<Shader>,
+ /// Minimum binding size in bytes for the particle layout buffer.
+ particle_layout_min_binding_size: NonZeroU32,
+ /// Minimum binding size in bytes for the particle layout buffer of the
+ /// parent effect, if any.
+ /// Key: READ_PARENT_PARTICLE
+ parent_particle_layout_min_binding_size: Option<NonZeroU32>,
+ /// Pipeline flags.
+ flags: ParticleInitPipelineKeyFlags,
+ /// Layout of the particle@1 bind group this pipeline was specialized with.
+ particle_bind_group_layout_desc: BindGroupLayoutDescriptor,
+ /// Layout of the spawner@2 bind group this pipeline was specialized with.
+ spawner_bind_group_layout_desc: BindGroupLayoutDescriptor,
+ /// Layout of the metadata@3 bind group this pipeline was specialized with.
+ metadata_bind_group_layout_desc: BindGroupLayoutDescriptor,
+}
+
+impl SpecializedComputePipeline for ParticlesInitPipeline {
+ type Key = ParticleInitPipelineKey;
+
+ fn specialize(&self, key: Self::Key) -> ComputePipelineDescriptor {
+ // We use the hash to correlate the key content with the GPU resource name
+ let hash = calc_hash(&key);
+ trace!("Specializing init pipeline {hash:016X} with key {key:?}");
+
+ let mut shader_defs = Vec::with_capacity(4);
+ if key
+ .flags
+ .contains(ParticleInitPipelineKeyFlags::ATTRIBUTE_PREV)
+ {
+ shader_defs.push("ATTRIBUTE_PREV".into());
+ }
+ if key
+ .flags
+ .contains(ParticleInitPipelineKeyFlags::ATTRIBUTE_NEXT)
+ {
+ shader_defs.push("ATTRIBUTE_NEXT".into());
+ }
+ let consume_gpu_spawn_events = key
+ .flags
+ .contains(ParticleInitPipelineKeyFlags::CONSUME_GPU_SPAWN_EVENTS);
+ if consume_gpu_spawn_events {
+ shader_defs.push("CONSUME_GPU_SPAWN_EVENTS".into());
+ }
+ // FIXME - for now this needs to keep in sync with consume_gpu_spawn_events
+ if key.parent_particle_layout_min_binding_size.is_some() {
+ assert!(consume_gpu_spawn_events);
+ shader_defs.push("READ_PARENT_PARTICLE".into());
+ } else {
+ assert!(!consume_gpu_spawn_events);
+ }
+
+ let label = format!("hanabi:pipeline:init_{hash:016X}");
+ trace!(
+ "-> creating pipeline '{}' with shader defs:{}",
+ label,
+ shader_defs
+ .iter()
+ .fold(String::new(), |acc, x| acc + &format!(" {x:?}"))
+ );
+
+ ComputePipelineDescriptor {
+ constants: default(),
+ label: Some(label.into()),
+ layout: vec![
+ self.sim_params_layout_desc.clone(),
+ key.particle_bind_group_layout_desc.clone(),
+ key.spawner_bind_group_layout_desc.clone(),
+ key.metadata_bind_group_layout_desc.clone(),
+ ],
+ immediate_size: 0,
+ shader: key.shader,
+ shader_defs,
+ entry_point: Some("main".into()),
+ zero_initialize_workgroup_memory: false,
+ }
+ }
+}
+
+#[derive(Resource)]
+pub(crate) struct ParticlesUpdatePipeline {
+ sim_params_layout_desc: BindGroupLayoutDescriptor,
+}
+
+impl Default for ParticlesUpdatePipeline {
+ fn default() -> Self {
+ let sim_params_layout_desc = BindGroupLayoutDescriptor::new(
+ "hanabi:bgl:vfx_update:sim_params@0",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE,
+ (
+ // @group(0) @binding(0) var<uniform> sim_params : SimParams;
+ uniform_buffer::<GpuSimParams>(false),
+ // @group(0) @binding(1) var<storage, read_write> draw_indirect_buffer :
+ // array<DrawIndexedIndirectArgs>;
+ storage_buffer::<GpuDrawIndexedIndirectArgs>(false),
+ ),
+ ),
+ );
+
+ Self {
+ sim_params_layout_desc,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Hash, PartialEq, Eq)]
+pub(crate) struct ParticleUpdatePipelineKey {
+ /// Compute shader, with snippets applied, but not preprocessed yet.
+ shader: Handle<Shader>,
+ /// Particle layout.
+ particle_layout: ParticleLayout,
+ /// Key: LOCAL_SPACE_SIMULATION
+ /// The effect is simulated in local space. The particle positions are
+ /// stored in simulation space.
+ local_space_simulation: bool,
+ /// Minimum binding size in bytes for the particle layout buffer of the
+ /// parent effect, if any.
+ /// Key: READ_PARENT_PARTICLE
+ parent_particle_layout_min_binding_size: Option<NonZeroU32>,
+ /// Key: EMITS_GPU_SPAWN_EVENTS
+ num_event_buffers: u32,
+ /// Layout of the particle@1 bind group this pipeline was specialized with.
+ particle_bind_group_layout_desc: BindGroupLayoutDescriptor,
+ /// Layout of the spawner@2 bind group this pipeline was specialized with.
+ spawner_bind_group_layout_desc: BindGroupLayoutDescriptor,
+ /// Layout of the metadata@3 bind group this pipeline was specialized with.
+ metadata_bind_group_layout_desc: BindGroupLayoutDescriptor,
+}
+
+impl SpecializedComputePipeline for ParticlesUpdatePipeline {
+ type Key = ParticleUpdatePipelineKey;
+
+ fn specialize(&self, key: Self::Key) -> ComputePipelineDescriptor {
+ // We use the hash to correlate the key content with the GPU resource name
+ let hash = calc_hash(&key);
+ trace!("Specializing update pipeline {hash:016X} with key {key:?}");
+
+ let mut shader_defs = Vec::with_capacity(6);
+ shader_defs.push("EM_MAX_SPAWN_ATOMIC".into());
+ // ChildInfo needs atomic event_count because all threads append to the event
+ // buffer(s) in parallel.
+ shader_defs.push("CHILD_INFO_EVENT_COUNT_IS_ATOMIC".into());
+ if key.particle_layout.contains(Attribute::PREV) {
+ shader_defs.push("ATTRIBUTE_PREV".into());
+ }
+ if key.particle_layout.contains(Attribute::NEXT) {
+ shader_defs.push("ATTRIBUTE_NEXT".into());
+ }
+ if key.parent_particle_layout_min_binding_size.is_some() {
+ shader_defs.push("READ_PARENT_PARTICLE".into());
+ }
+ if key.num_event_buffers > 0 {
+ shader_defs.push("EMITS_GPU_SPAWN_EVENTS".into());
+ }
+ if key.local_space_simulation {
+ shader_defs.push("LOCAL_SPACE_SIMULATION".into());
+ }
+
+ let hash = calc_func_id(&key);
+ let label = format!("hanabi:pipeline:update_{hash:016X}");
+ trace!(
+ "-> creating pipeline '{}' with shader defs:{}",
+ label,
+ shader_defs
+ .iter()
+ .fold(String::new(), |acc, x| acc + &format!(" {x:?}"))
+ );
+
+ ComputePipelineDescriptor {
+ constants: default(),
+ label: Some(label.into()),
+ layout: vec![
+ self.sim_params_layout_desc.clone(),
+ key.particle_bind_group_layout_desc.clone(),
+ key.spawner_bind_group_layout_desc.clone(),
+ key.metadata_bind_group_layout_desc.clone(),
+ ],
+ immediate_size: 0,
+ shader: key.shader,
+ shader_defs,
+ entry_point: Some("main".into()),
+ zero_initialize_workgroup_memory: false,
+ }
+ }
+}
+
+#[derive(Resource)]
+pub(crate) struct ParticlesRenderPipeline {
+ view_layout_desc: BindGroupLayoutDescriptor,
+}
+
+impl FromWorld for ParticlesRenderPipeline {
+ fn from_world(_world: &mut World) -> Self {
+ let view_layout_desc = BindGroupLayoutDescriptor::new(
+ "hanabi:bgl:render:view@0",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::VERTEX_FRAGMENT,
+ (
+ // @group(0) @binding(0) var<uniform> view: View;
+ uniform_buffer::<ViewUniform>(true),
+ // @group(0) @binding(1) var<uniform> sim_params : SimParams;
+ uniform_buffer::<GpuSimParams>(false),
+ ),
+ ),
+ );
+
+ Self { view_layout_desc }
+ }
+}
+
+#[cfg(all(feature = "2d", feature = "3d"))]
+#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
+enum PipelineMode {
+ Camera2d,
+ Camera3d,
+}
+
+#[derive(Debug, Clone, Hash, PartialEq, Eq)]
+pub(crate) struct ParticleRenderPipelineKey {
+ /// Render shader, with snippets applied, but not preprocessed yet.
+ shader: Handle<Shader>,
+ /// Particle layout.
+ particle_layout: ParticleLayout,
+ mesh_layout: Option<MeshVertexBufferLayoutRef>,
+ /// Texture layout.
+ texture_layout: TextureLayout,
+ /// Key: LOCAL_SPACE_SIMULATION
+ /// The effect is simulated in local space, and during rendering all
+ /// particles are transformed by the effect's [`GlobalTransform`].
+ local_space_simulation: bool,
+ /// Key: USE_ALPHA_MASK, OPAQUE
+ /// The particle's alpha masking behavior.
+ alpha_mask: ParticleRenderAlphaMaskPipelineKey,
+ /// The effect needs Alpha blend.
+ alpha_mode: AlphaMode,
+ /// Key: FLIPBOOK
+ /// The effect is rendered with flipbook texture animation based on the
+ /// sprite index of each particle.
+ flipbook: bool,
+ /// Key: NEEDS_UV
+ /// The effect needs UVs.
+ needs_uv: bool,
+ /// Key: NEEDS_NORMAL
+ /// The effect needs normals.
+ needs_normal: bool,
+ /// Key: NEEDS_PARTICLE_IN_FRAGMENT
+ /// The effect needs access to the particle index and buffer in the fragment
+ /// shader.
+ needs_particle_fragment: bool,
+ /// Key: RIBBONS
+ /// The effect has ribbons.
+ ribbons: bool,
+ /// For dual-mode configurations only, the actual mode of the current render
+ /// pipeline. Otherwise the mode is implicitly determined by the active
+ /// feature.
+ #[cfg(all(feature = "2d", feature = "3d"))]
+ pipeline_mode: PipelineMode,
+ /// MSAA sample count.
+ msaa_samples: u32,
+ /// Camera output format.
+ target_format: TextureFormat,
+ /// Layout of the spawner@2 bind group this pipeline was specialized with.
+ spawner_bind_group_layout_desc: BindGroupLayoutDescriptor,
+}
+
+#[derive(Clone, Copy, Default, Hash, PartialEq, Eq, Debug)]
+pub(crate) enum ParticleRenderAlphaMaskPipelineKey {
+ #[default]
+ Blend,
+ /// Key: USE_ALPHA_MASK
+ /// The effect is rendered with alpha masking.
+ AlphaMask,
+ /// Key: OPAQUE
+ /// The effect is rendered fully-opaquely.
+ Opaque,
+}
+
+impl SpecializedRenderPipeline for ParticlesRenderPipeline {
+ type Key = ParticleRenderPipelineKey;
+
+ fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor {
+ trace!("Specializing render pipeline for key: {key:?}");
+
+ trace!("Creating layout for bind group particle@1 of render pass");
+ // FIXME - duplicated in ParticleSlab::new()
+ let particle_bind_group_layout_desc = BindGroupLayoutDescriptor::new(
+ "hanabi:bgl:render:particle@1",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::VERTEX,
+ (
+ // @group(1) @binding(0) var<storage, read> particle_buffer : ParticleBuffer;
+ storage_buffer_read_only_sized(
+ false,
+ Some(key.particle_layout.min_binding_size()),
+ )
+ .visibility(ShaderStages::VERTEX_FRAGMENT),
+ // @group(1) @binding(1) var<storage, read> indirect_buffer : IndirectBuffer;
+ storage_buffer_read_only::<GpuIndirectIndex>(false),
+ ),
+ ),
+ );
+
+ let layout = vec![
+ self.view_layout_desc.clone(),
+ particle_bind_group_layout_desc,
+ key.spawner_bind_group_layout_desc.clone(),
+ ];
+
+ let mut shader_defs = vec![];
+ if !key.texture_layout.layout.is_empty() {
+ shader_defs.push("HAS_MATERIAL".into());
+ }
+
+ let vertex_buffer_layout = key.mesh_layout.as_ref().and_then(|mesh_layout| {
+ mesh_layout
+ .0
+ .get_layout(&[
+ Mesh::ATTRIBUTE_POSITION.at_shader_location(0),
+ Mesh::ATTRIBUTE_UV_0.at_shader_location(1),
+ Mesh::ATTRIBUTE_NORMAL.at_shader_location(2),
+ ])
+ .ok()
+ });
+
+ // Key: LOCAL_SPACE_SIMULATION
+ if key.local_space_simulation {
+ shader_defs.push("LOCAL_SPACE_SIMULATION".into());
+ }
+
+ match key.alpha_mask {
+ ParticleRenderAlphaMaskPipelineKey::Blend => {}
+ ParticleRenderAlphaMaskPipelineKey::AlphaMask => {
+ // Key: USE_ALPHA_MASK
+ shader_defs.push("USE_ALPHA_MASK".into())
+ }
+ ParticleRenderAlphaMaskPipelineKey::Opaque => {
+ // Key: OPAQUE
+ shader_defs.push("OPAQUE".into())
+ }
+ }
+
+ // Key: FLIPBOOK
+ if key.flipbook {
+ shader_defs.push("FLIPBOOK".into());
+ }
+
+ // Key: NEEDS_UV
+ if key.needs_uv {
+ shader_defs.push("NEEDS_UV".into());
+ }
+
+ // Key: NEEDS_NORMAL
+ if key.needs_normal {
+ shader_defs.push("NEEDS_NORMAL".into());
+ }
+
+ if key.needs_particle_fragment {
+ shader_defs.push("NEEDS_PARTICLE_FRAGMENT".into());
+ }
+
+ // Key: RIBBONS
+ if key.ribbons {
+ shader_defs.push("RIBBONS".into());
+ }
+
+ #[cfg(feature = "2d")]
+ let depth_stencil_2d = DepthStencilState {
+ format: CORE_2D_DEPTH_FORMAT,
+ // Use depth buffer with alpha-masked particles, not with transparent ones
+ depth_write_enabled: Some(false), // TODO - opaque/alphamask 2d
+ // Bevy uses reverse-Z, so GreaterEqual really means closer
+ depth_compare: Some(CompareFunction::GreaterEqual),
+ stencil: StencilState::default(),
+ bias: DepthBiasState::default(),
+ };
+
+ #[cfg(feature = "3d")]
+ let depth_stencil_3d = DepthStencilState {
+ format: CORE_3D_DEPTH_FORMAT,
+ // Use depth buffer with alpha-masked or opaque particles, not
+ // with transparent ones
+ depth_write_enabled: Some(matches!(
+ key.alpha_mask,
+ ParticleRenderAlphaMaskPipelineKey::AlphaMask
+ | ParticleRenderAlphaMaskPipelineKey::Opaque
+ )),
+ // Bevy uses reverse-Z, so GreaterEqual really means closer
+ depth_compare: Some(CompareFunction::GreaterEqual),
+ stencil: StencilState::default(),
+ bias: DepthBiasState::default(),
+ };
+
+ #[cfg(all(feature = "2d", feature = "3d"))]
+ assert_eq!(CORE_2D_DEPTH_FORMAT, CORE_3D_DEPTH_FORMAT);
+ #[cfg(all(feature = "2d", feature = "3d"))]
+ let depth_stencil = match key.pipeline_mode {
+ PipelineMode::Camera2d => Some(depth_stencil_2d),
+ PipelineMode::Camera3d => Some(depth_stencil_3d),
+ };
+
+ #[cfg(all(feature = "2d", not(feature = "3d")))]
+ let depth_stencil = Some(depth_stencil_2d);
+
+ #[cfg(all(feature = "3d", not(feature = "2d")))]
+ let depth_stencil = Some(depth_stencil_3d);
+
+ let format = key.target_format;
+
+ let hash = calc_func_id(&key);
+ let label = format!("hanabi:pipeline:render_{hash:016X}");
+ trace!(
+ "-> creating pipeline '{}' with shader defs:{}",
+ label,
+ shader_defs
+ .iter()
+ .fold(String::new(), |acc, x| acc + &format!(" {x:?}"))
+ );
+
+ RenderPipelineDescriptor {
+ label: Some(label.into()),
+ layout,
+ immediate_size: 0,
+ vertex: VertexState {
+ constants: default(),
+ shader: key.shader.clone(),
+ entry_point: Some("vertex".into()),
+ shader_defs: shader_defs.clone(),
+ buffers: vec![vertex_buffer_layout.expect("Vertex buffer layout not present")],
+ },
+ fragment: Some(FragmentState {
+ constants: default(),
+ shader: key.shader,
+ shader_defs,
+ entry_point: Some("fragment".into()),
+ targets: vec![Some(ColorTargetState {
+ format,
+ blend: Some(key.alpha_mode.into()),
+ write_mask: ColorWrites::ALL,
+ })],
+ }),
+ primitive: PrimitiveState {
+ front_face: FrontFace::Ccw,
+ cull_mode: None,
+ unclipped_depth: false,
+ polygon_mode: PolygonMode::Fill,
+ conservative: false,
+ topology: PrimitiveTopology::TriangleList,
+ strip_index_format: None,
+ },
+ depth_stencil,
+ multisample: MultisampleState {
+ count: key.msaa_samples,
+ mask: !0,
+ alpha_to_coverage_enabled: false,
+ },
+ zero_initialize_workgroup_memory: false,
+ }
+ }
+}
+
+/// A single effect instance extracted from a [`ParticleEffect`] as a
+/// render world item.
+///
+/// [`ParticleEffect`]: crate::ParticleEffect
+#[derive(Debug, Clone, PartialEq, Component)]
+#[require(CachedPipelines, CachedReadyState, CachedEffectMetadata)]
+pub(crate) struct ExtractedEffect {
+ /// Handle to the effect asset this instance is based on.
+ /// The handle is weak to prevent refcount cycles and gracefully handle
+ /// assets unloaded or destroyed after a draw call has been submitted.
+ pub handle: Handle<EffectAsset>,
+ /// Particle layout for the effect.
+ pub particle_layout: ParticleLayout,
+ /// Effect capacity, in number of particles.
+ pub capacity: u32,
+ /// Layout flags.
+ pub layout_flags: LayoutFlags,
+ /// Texture layout.
+ pub texture_layout: TextureLayout,
+ /// Textures.
+ pub textures: Vec<Handle<Image>>,
+ /// Alpha mode.
+ pub alpha_mode: AlphaMode,
+ /// Effect shaders.
+ pub effect_shaders: EffectShaders,
+ /// Condition under which the effect is simulated.
+ pub simulation_condition: SimulationCondition,
+}
+
+/// Extracted data for the [`GpuSpawnerParams`].
+///
+/// This contains all data which may change each frame during the regular usage
+/// of the effect, but doesn't require any particular GPU resource update
+/// (except re-uploading that new data to GPU, of course).
+#[derive(Debug, Clone, PartialEq, Component)]
+pub(crate) struct ExtractedSpawner {
+ /// Number of particles to spawn this frame.
+ ///
+ /// This is ignored if the effect is a child effect consuming GPU spawn
+ /// events.
+ pub spawn_count: u32,
+ /// PRNG seed.
+ pub prng_seed: u32,
+ /// Global transform of the effect origin.
+ pub transform: GlobalTransform,
+ /// Is the effect visible this frame?
+ pub is_visible: bool,
+}
+
+/// Cache info for the metadata of the effect.
+///
+/// This manages the GPU allocation of the [`GpuEffectMetadata`] for this
+/// effect.
+#[derive(Debug, Default, Component)]
+pub(crate) struct CachedEffectMetadata {
+ /// Allocation ID.
+ pub table_id: BufferTableId,
+ /// Current metadata values, cached on CPU for change detection.
+ pub metadata: GpuEffectMetadata,
+}
+
+/// Extracted parent information for a child effect.
+///
+/// This component is present on the [`RenderEntity`] of an extracted effect if
+/// the effect has a parent effect. Otherwise, it's removed.
+///
+/// This components forms an ECS relationship with [`ChildrenEffects`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Component)]
+#[relationship(relationship_target = ChildrenEffects)]
+pub(crate) struct ChildEffectOf {
+ /// Render entity of the parent.
+ pub parent: Entity,
+}
+
+/// Extracted children information for a parent effect.
+///
+/// This component is present on the [`RenderEntity`] of an extracted effect if
+/// the effect is a parent effect for one or more child effects. Otherwise, it's
+/// removed.
+///
+/// This components forms an ECS relationship with [`ChildEffectOf`]. Note that
+/// we don't use `linked_spawn` because:
+/// 1. This would fight with the `SyncToRenderWorld` as the main world
+/// parent-child hierarchy is by design not an ECS relationship (it's a lose
+/// declarative coupling).
+/// 2. The components on the render entity often store GPU resources or other
+/// data we need to clean-up manually, and not all of them currently use
+/// lifecycle hooks, so we want to manage despawning manually to prevent
+/// leaks.
+#[derive(Debug, Clone, PartialEq, Eq, Component)]
+#[relationship_target(relationship = ChildEffectOf)]
+pub(crate) struct ChildrenEffects(Vec<Entity>);
+
+impl<'a> IntoIterator for &'a ChildrenEffects {
+ type Item = <Self::IntoIter as Iterator>::Item;
+
+ type IntoIter = std::slice::Iter<'a, Entity>;
+
+ #[inline(always)]
+ fn into_iter(self) -> Self::IntoIter {
+ self.0.iter()
+ }
+}
+
+impl Deref for ChildrenEffects {
+ type Target = [Entity];
+
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+/// Extracted data for an effect's properties, if any.
+///
+/// This component is present on the [`RenderEntity`] of an extracted effect if
+/// that effect has properties. It optionally contains new CPU data to
+/// (re-)upload this frame. If the effect has no property, this component is
+/// removed.
+#[derive(Debug, Component)]
+pub(crate) struct ExtractedProperties {
+ /// Property layout for the effect.
+ pub property_layout: PropertyLayout,
+ /// Values of properties written in a binary blob according to
+ /// [`property_layout`].
+ ///
+ /// This is `Some(blob)` if the data needs to be (re)uploaded to GPU, or
+ /// `None` if nothing needs to be done for this frame.
+ ///
+ /// [`property_layout`]: crate::render::ExtractedEffect::property_layout
+ pub property_data: Option<Vec<u8>>,
+}
+
+#[derive(Default, Resource)]
+pub(crate) struct EffectAssetEvents {
+ pub images: Vec<AssetEvent<Image>>,
+}
+
+/// System extracting all the asset events for the [`Image`] assets to enable
+/// dynamic update of images bound to any effect.
+///
+/// This system runs in parallel of [`extract_effects`].
+pub(crate) fn extract_effect_events(
+ mut events: ResMut<EffectAssetEvents>,
+ mut image_events: Extract<MessageReader<AssetEvent<Image>>>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("extract_effect_events").entered();
+ trace!("extract_effect_events()");
+
+ let EffectAssetEvents { ref mut images } = *events;
+ *images = image_events.read().copied().collect();
+}
+
+/// Debugging settings.
+///
+/// Settings used to debug Hanabi. These have no effect on the actual behavior
+/// of Hanabi, but may affect its performance.
+///
+/// # Example
+///
+/// ```
+/// # use bevy::prelude::*;
+/// # use bevy_hanabi::*;
+/// fn startup(mut debug_settings: ResMut<DebugSettings>) {
+/// // Each time a new effect is spawned, capture 2 frames
+/// debug_settings.start_capture_on_new_effect = true;
+/// debug_settings.capture_frame_count = 2;
+/// }
+/// ```
+#[derive(Debug, Default, Clone, Copy, Resource)]
+pub struct DebugSettings {
+ /// Enable automatically starting a GPU debugger capture as soon as this
+ /// frame starts rendering (extract phase).
+ ///
+ /// Enable this feature to automatically capture one or more GPU frames when
+ /// the `extract_effects()` system runs next. This instructs any attached
+ /// GPU debugger to start a capture; this has no effect if no debugger
+ /// is attached.
+ ///
+ /// If a capture is already on-going this has no effect; the on-going
+ /// capture needs to be terminated first. Note however that a capture can
+ /// stop and another start in the same frame.
+ ///
+ /// This value is not reset automatically. If you set this to `true`, you
+ /// should set it back to `false` on next frame to avoid capturing forever.
+ pub start_capture_this_frame: bool,
+
+ /// Enable automatically starting a GPU debugger capture when one or more
+ /// effects are spawned.
+ ///
+ /// Enable this feature to automatically capture one or more GPU frames when
+ /// a new effect is spawned (as detected by ECS change detection). This
+ /// instructs any attached GPU debugger to start a capture; this has no
+ /// effect if no debugger is attached.
+ pub start_capture_on_new_effect: bool,
+
+ /// Number of frames to capture with a GPU debugger.
+ ///
+ /// By default this value is zero, and a GPU debugger capture runs for a
+ /// single frame. If a non-zero frame count is specified here, the capture
+ /// will instead stop once the specified number of frames has been recorded.
+ ///
+ /// You should avoid setting this to a value too large, to prevent the
+ /// capture size from getting out of control. A typical value is 1 to 3
+ /// frames, or possibly more (up to 10) for exceptional contexts. Some GPU
+ /// debuggers or graphics APIs might further limit this value on their own,
+ /// so there's no guarantee the graphics API will honor this value.
+ pub capture_frame_count: u32,
+}
+
+#[derive(Debug, Default, Clone, Copy, Resource)]
+pub(crate) struct RenderDebugSettings {
+ /// Is a GPU debugger capture on-going?
+ is_capturing: bool,
+ /// Start time of any on-going GPU debugger capture.
+ capture_start: Duration,
+ /// Number of frames captured so far for on-going GPU debugger capture.
+ captured_frames: u32,
+}
+
+/// Manage GPU debug capture start/stop.
+///
+/// If any GPU debug capture is configured to start or stop in
+/// [`DebugSettings`], they do so during this system's run. This ensures
+/// that all GPU commands produced by Hanabi are recorded (but may miss some
+/// from Bevy itself, if another Bevy system runs before this one).
+///
+/// We do this during extract to try and capture as close as possible to an
+/// entire GPU frame.
+pub(crate) fn start_stop_gpu_debug_capture(
+ real_time: Extract<Res<Time<Real>>>,
+ render_device: Res<RenderDevice>,
+ debug_settings: Extract<Res<DebugSettings>>,
+ mut render_debug_settings: ResMut<RenderDebugSettings>,
+ q_added_effects: Extract<Query<(), Added<CompiledParticleEffect>>>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("start_stop_debug_capture").entered();
+ trace!("start_stop_debug_capture()");
+
+ // Stop any pending capture if needed
+ if render_debug_settings.is_capturing {
+ render_debug_settings.captured_frames += 1;
+
+ if render_debug_settings.captured_frames >= debug_settings.capture_frame_count {
+ #[expect(unsafe_code, reason = "Debugging only")]
+ unsafe {
+ render_device.wgpu_device().stop_graphics_debugger_capture();
+ }
+ render_debug_settings.is_capturing = false;
+ warn!(
+ "Stopped GPU debug capture after {} frames, at t={}s.",
+ render_debug_settings.captured_frames,
+ real_time.elapsed().as_secs_f64()
+ );
+ }
+ }
+
+ // If no pending capture, consider starting a new one
+ if !render_debug_settings.is_capturing
+ && (debug_settings.start_capture_this_frame
+ || (debug_settings.start_capture_on_new_effect && !q_added_effects.is_empty()))
+ {
+ #[expect(unsafe_code, reason = "Debugging only")]
+ unsafe {
+ render_device
+ .wgpu_device()
+ .start_graphics_debugger_capture();
+ }
+ render_debug_settings.is_capturing = true;
+ render_debug_settings.capture_start = real_time.elapsed();
+ render_debug_settings.captured_frames = 0;
+ warn!(
+ "Started GPU debug capture of {} frames at t={}s.",
+ debug_settings.capture_frame_count,
+ render_debug_settings.capture_start.as_secs_f64()
+ );
+ }
+}
+
+/// Write the ready state of all render world effects back into their source
+/// effect in the main world.
+pub(crate) fn report_ready_state(
+ mut main_world: ResMut<MainWorld>,
+ q_ready_state: Query<&CachedReadyState>,
+) {
+ let mut q_effects = main_world.query::<(RenderEntity, &mut CompiledParticleEffect)>();
+ for (render_entity, mut compiled_particle_effect) in q_effects.iter_mut(&mut main_world) {
+ if let Ok(cached_ready_state) = q_ready_state.get(render_entity) {
+ compiled_particle_effect.is_ready = cached_ready_state.is_ready();
+ }
+ }
+}
+
+/// System extracting data for rendering of all active [`ParticleEffect`]
+/// components.
+///
+/// [`ParticleEffect`]: crate::ParticleEffect
+pub(crate) fn extract_effects(
+ mut commands: Commands,
+ effects: Extract<Res<Assets<EffectAsset>>>,
+ default_mesh: Extract<Res<DefaultMesh>>,
+ // Main world effects to extract
+ q_effects: Extract<
+ Query<(
+ Entity,
+ RenderEntity,
+ Option<&InheritedVisibility>,
+ Option<&ViewVisibility>,
+ &EffectSpawner,
+ &CompiledParticleEffect,
+ Option<Ref<EffectProperties>>,
+ &GlobalTransform,
+ )>,
+ >,
+ // Render world effects extracted from a previous frame, if any
+ mut q_extracted_effects: Query<(
+ &mut ExtractedEffect,
+ Option<&mut ExtractedSpawner>,
+ Option<&ChildEffectOf>, // immutable, because of relationship
+ Option<&mut ExtractedEffectMesh>,
+ Option<&mut ExtractedProperties>,
+ )>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("extract_effects").entered();
+ trace!("extract_effects()");
+
+ // Loop over all existing effects to extract them
+ trace!("Extracting {} effects...", q_effects.iter().len());
+ for (
+ main_entity,
+ render_entity,
+ maybe_inherited_visibility,
+ maybe_view_visibility,
+ effect_spawner,
+ compiled_effect,
+ maybe_properties,
+ transform,
+ ) in q_effects.iter()
+ {
+ // Check if shaders are configured
+ let Some(effect_shaders) = compiled_effect.get_configured_shaders() else {
+ trace!("Effect {:?}: no configured shader, skipped.", main_entity);
+ continue;
+ };
+
+ // Check if asset is available, otherwise silently ignore
+ let Some(asset) = effects.get(&compiled_effect.asset) else {
+ trace!(
+ "Effect {:?}: EffectAsset not ready, skipped. asset:{:?}",
+ main_entity,
+ compiled_effect.asset
+ );
+ continue;
+ };
+
+ let is_visible = maybe_inherited_visibility
+ .map(|cv| cv.get())
+ .unwrap_or(true)
+ && maybe_view_visibility.map(|cv| cv.get()).unwrap_or(true);
+
+ let mut cmd = commands.entity(render_entity);
+
+ // Fetch the existing extraction compoennts, if any, which we need to update.
+ // Because we use SyncToRenderWorld, there's always a render entity, but it may
+ // miss all components. And because we can't query only optional components
+ // (that would match all entities in the entire world), we force querying
+ // ExtractedEffect, which means we get a miss if it's the first extraction and
+ // it's not spawned yet. That's OK, we'll spawn it below.
+ let (
+ maybe_extracted_effect,
+ maybe_extracted_spawner,
+ maybe_child_of,
+ maybe_extracted_mesh,
+ maybe_extracted_properties,
+ ) = q_extracted_effects
+ .get_mut(render_entity)
+ .map(|(extracted_effect, b, c, d, e)| (Some(extracted_effect), b, c, d, e))
+ .unwrap_or((None, None, None, None, None));
+
+ // Validate material
+ let texture_layout = asset.module().texture_layout();
+ let num_expected_tex = texture_layout.layout.len();
+ if compiled_effect.textures.len() < num_expected_tex {
+ error!(
+ "Instance of effect '{}' on entity {:?} is missing some textures. Layout expected {} textures, but CompiledParticleEffect got {} instead.",
+ asset.name,
+ main_entity,
+ num_expected_tex,
+ compiled_effect.textures.len()
+ );
+ continue;
+ }
+ let textures = if compiled_effect.textures.len() > num_expected_tex {
+ trace!(
+ "Instance of effect '{}' on entity {:?} has too many textures. Layout expected {} textures, but CompiledParticleEffect got {} instead. Ignoring the extra ones.",
+ asset.name,
+ main_entity,
+ num_expected_tex,
+ compiled_effect.textures.len()
+ );
+ compiled_effect.textures[..num_expected_tex].to_vec()
+ } else {
+ compiled_effect.textures.clone()
+ };
+
+ // Extract general effect data
+ let layout_flags = compiled_effect.layout_flags;
+ let alpha_mode = compiled_effect.alpha_mode;
+ trace!(
+ "Extracted instance of effect '{}' on entity {:?} (render entity {:?}): texture_layout_count={} texture_count={} layout_flags={:?}",
+ asset.name,
+ main_entity,
+ render_entity,
+ texture_layout.layout.len(),
+ textures.len(),
+ layout_flags,
+ );
+ let new_extracted_effect = ExtractedEffect {
+ handle: compiled_effect.asset.clone(),
+ particle_layout: asset.particle_layout().clone(),
+ capacity: asset.capacity(),
+ layout_flags,
+ texture_layout,
+ textures,
+ alpha_mode,
+ effect_shaders: effect_shaders.clone(),
+ simulation_condition: asset.simulation_condition,
+ };
+ if let Some(mut extracted_effect) = maybe_extracted_effect {
+ extracted_effect.set_if_neq(new_extracted_effect);
+ } else {
+ trace!(
+ "Inserting new ExtractedEffect component on {:?}",
+ render_entity
+ );
+ cmd.insert(new_extracted_effect);
+ }
+
+ // Extract the spawner data
+ let new_spawner = ExtractedSpawner {
+ spawn_count: effect_spawner.spawn_count,
+ prng_seed: compiled_effect.prng_seed,
+ transform: *transform,
+ is_visible,
+ };
+ trace!(
+ "[Effect {}] spawn_count={} prng_seed={}",
+ render_entity,
+ new_spawner.spawn_count,
+ new_spawner.prng_seed
+ );
+ if let Some(mut extracted_spawner) = maybe_extracted_spawner {
+ extracted_spawner.set_if_neq(new_spawner);
+ } else {
+ trace!(
+ "Inserting new ExtractedSpawner component on {}",
+ render_entity
+ );
+ cmd.insert(new_spawner);
+ }
+
+ // Extract the effect mesh
+ let mesh = compiled_effect
+ .mesh
+ .clone()
+ .unwrap_or(default_mesh.0.clone());
+ let new_mesh = ExtractedEffectMesh { mesh: mesh.id() };
+ if let Some(mut extracted_mesh) = maybe_extracted_mesh {
+ extracted_mesh.set_if_neq(new_mesh);
+ } else {
+ trace!(
+ "Inserting new ExtractedEffectMesh component on {:?}",
+ render_entity
+ );
+ cmd.insert(new_mesh);
+ }
+
+ // Extract the parent, if any, and resolve its render entity
+ let parent_render_entity = if let Some(main_entity) = compiled_effect.parent {
+ let Ok((_, render_entity, _, _, _, _, _, _)) = q_effects.get(main_entity) else {
+ error!(
+ "Failed to resolve render entity of parent with main entity {:?}.",
+ main_entity
+ );
+ cmd.remove::<ChildEffectOf>();
+ // TODO - prevent extraction altogether here, instead of just de-parenting?
+ continue;
+ };
+ Some(render_entity)
+ } else {
+ None
+ };
+ if let Some(render_entity) = parent_render_entity {
+ let new_child_of = ChildEffectOf {
+ parent: render_entity,
+ };
+ // If there's already an ExtractedParent component, ensure we overwrite only if
+ // different, to not trigger ECS change detection that we rely on.
+ if let Some(child_effect_of) = maybe_child_of {
+ // The relationship makes ChildEffectOf immutable, so re-insert to mutate
+ if *child_effect_of != new_child_of {
+ cmd.insert(new_child_of);
+ }
+ } else {
+ trace!(
+ "Inserting new ChildEffectOf component on {:?}",
+ render_entity
+ );
+ cmd.insert(new_child_of);
+ }
+ } else {
+ cmd.remove::<ChildEffectOf>();
+ }
+
+ // Extract property data
+ let property_layout = asset.property_layout();
+ if property_layout.is_empty() {
+ cmd.remove::<ExtractedProperties>();
+ } else {
+ // Re-extract CPU property data if any. Note that this data is not a "new value"
+ // but instead a "value that must be uploaded this frame", and therefore is
+ // empty when there's no change (as opposed to, having a constant value
+ // frame-to-frame).
+ let property_data = if let Some(properties) = maybe_properties {
+ if properties.is_changed() {
+ trace!("Detected property change, re-serializing...");
+ Some(properties.serialize(&property_layout))
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
+ let new_properties = ExtractedProperties {
+ property_layout,
+ property_data,
+ };
+ trace!("new_properties = {new_properties:?}");
+
+ if let Some(mut extracted_properties) = maybe_extracted_properties {
+ // Always mutate if there's new CPU data to re-upload. Otherwise check for any
+ // other change.
+ if new_properties.property_data.is_some()
+ || (extracted_properties.property_layout != new_properties.property_layout)
+ {
+ trace!(
+ "Updating existing ExtractedProperties (was: {:?})",
+ extracted_properties.as_ref()
+ );
+ *extracted_properties = new_properties;
+ }
+ } else {
+ trace!(
+ "Inserting new ExtractedProperties component on {:?}",
+ render_entity
+ );
+ cmd.insert(new_properties);
+ }
+ }
+ }
+}
+
+pub(crate) fn extract_sim_params(
+ real_time: Extract<Res<Time<Real>>>,
+ virtual_time: Extract<Res<Time<Virtual>>>,
+ time: Extract<Res<Time<EffectSimulation>>>,
+ mut sim_params: ResMut<SimParams>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("extract_sim_params").entered();
+ trace!("extract_sim_params()");
+
+ // Save simulation params into render world
+ sim_params.time = time.elapsed_secs_f64();
+ sim_params.delta_time = time.delta_secs();
+ sim_params.virtual_time = virtual_time.elapsed_secs_f64();
+ sim_params.virtual_delta_time = virtual_time.delta_secs();
+ sim_params.real_time = real_time.elapsed_secs_f64();
+ sim_params.real_delta_time = real_time.delta_secs();
+ trace!(
+ "SimParams: time={} delta_time={} vtime={} delta_vtime={} rtime={} delta_rtime={}",
+ sim_params.time,
+ sim_params.delta_time,
+ sim_params.virtual_time,
+ sim_params.virtual_delta_time,
+ sim_params.real_time,
+ sim_params.real_delta_time,
+ );
+}
+
+/// Extracted [`HanabiMainCamera`], with additional extracted data.
+///
+/// This component is added inside the render world to the render view
+/// corresponding to the extracted camera of the main camera holding the
+/// [`HanabiMainCamera`] component, if any.
+#[derive(Debug, Component)]
+pub(crate) struct HanabiRenderCamera {
+ /// Main entity the camera/view was extracted from, which contains the
+ /// [`Camera`], the [`HanabiMainCamera`], and the original data extracted.
+ #[allow(dead_code)]
+ pub view: MainEntity,
+ /// Camera position in world space.
+ pub position: Vec3,
+ /// Frustum planes of the camera.
+ pub frustum: [Vec4; 6],
+}
+
+/// Extract camera related data for the main Hanabi view.
+///
+/// The main Hanabi view is the view of the [`Camera`] tagged with the
+/// [`HanabiMainCamera`], if any. That camera and its view data are used for
+/// various features that require a single camera.
+pub(crate) fn extract_main_view(
+ mut commands: Commands,
+ q_views: Extract<
+ Query<
+ (Entity, RenderEntity, &GlobalTransform, &Frustum),
+ (With<Camera>, With<HanabiMainCamera>),
+ >,
+ >,
+ q_render_view: Query<Entity, With<HanabiRenderCamera>>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("extract_main_view").entered();
+ trace!("extract_main_view()");
+
+ // Get the unique main view from the main world.
+ let Ok((entity, render_entity, global_transform, frustum)) = q_views.single() else {
+ trace!("No HanabiMainCamera component found (or multiple; this is not allowed).");
+ // Delete any previous (now invalid) render world camera
+ for entity in q_render_view.iter() {
+ commands.entity(entity).remove::<HanabiRenderCamera>();
+ }
+ return;
+ };
+
+ // Ensure uniqueness; delete any previous camera if it's on a different entity
+ // that the expected one.
+ q_render_view.iter().for_each(|e| {
+ if e != render_entity {
+ commands.entity(e).remove::<HanabiRenderCamera>();
+ }
+ });
+
+ let render_camera = HanabiRenderCamera {
+ view: entity.into(),
+ position: global_transform.translation(),
+ frustum: frustum.half_spaces.map(|h| h.normal_d()),
+ };
+ trace!("HanabiRenderCamera: {render_camera:?}");
+
+ let mut commands = commands.entity(render_entity);
+ commands.insert(render_camera);
+}
+
+/// Various GPU limits and aligned sizes computed once and cached.
+struct GpuLimits {
+ /// Value of [`WgpuLimits::min_storage_buffer_offset_alignment`].
+ ///
+ /// [`WgpuLimits::min_storage_buffer_offset_alignment`]: bevy::render::settings::WgpuLimits::min_storage_buffer_offset_alignment
+ storage_buffer_align: NonZeroU32,
+
+ /// Size of [`GpuSpawnerParams`] aligned to the contraint of
+ /// [`WgpuLimits::min_storage_buffer_offset_alignment`].
+ ///
+ /// [`WgpuLimits::min_storage_buffer_offset_alignment`]: bevy::render::settings::WgpuLimits::min_storage_buffer_offset_alignment
+ #[allow(dead_code)]
+ spawner_params_aligned_size: NonZeroU32,
+}
+
+impl GpuLimits {
+ pub fn from_device(render_device: &RenderDevice) -> Self {
+ let storage_buffer_align =
+ render_device.limits().min_storage_buffer_offset_alignment as u64;
+
+ let spawner_params_aligned_size = NonZeroU32::new(
+ GpuSpawnerParams::min_size()
+ .get()
+ .next_multiple_of(storage_buffer_align) as u32,
+ )
+ .unwrap();
+
+ trace!(
+ "GPU-aligned sizes (align: {} B):\n- GpuSpawnerParams: {} B -> {} B",
+ storage_buffer_align,
+ GpuSpawnerParams::min_size().get(),
+ spawner_params_aligned_size.get(),
+ );
+
+ Self {
+ storage_buffer_align: NonZeroU32::new(storage_buffer_align as u32).unwrap(),
+ spawner_params_aligned_size,
+ }
+ }
+
+ /// Byte alignment for any storage buffer binding.
+ pub fn storage_buffer_align(&self) -> NonZeroU32 {
+ self.storage_buffer_align
+ }
+}
+
+/// Global render world resource containing the GPU data to draw all the
+/// particle effects in all views.
+///
+/// The resource is populated by [`prepare_effects()`] with all the effects to
+/// render for the current frame, for all views in the frame, and consumed by
+/// [`queue_effects()`] to actually enqueue the drawning commands to draw those
+/// effects.
+#[derive(Resource)]
+pub struct EffectsMeta {
+ /// Bind group for the camera view, containing the camera projection and
+ /// other uniform values related to the camera.
+ view_bind_group: Option<BindGroup>,
+ /// Bind group #0 of the vfx_update shader, for the simulation parameters
+ /// like the current time and frame delta time.
+ update_sim_params_bind_group: Option<BindGroup>,
+ /// Bind group #0 of the vfx_init and vfx_indirect shaders, for the
+ /// simulation parameters like the current time and frame delta time.
+ init_and_indirect_sim_params_bind_group: Option<BindGroup>,
+ /// Bind group #1 of the vfx_indirect shader, containing both the indirect
+ /// compute dispatch and render buffers.
+ indirect_metadata_bind_group: Option<BindGroup>,
+ /// Bind group #2 of the vfx_indirect shader, containing the spawners.
+ indirect_spawner_bind_group: Option<BindGroup>,
+ /// Global shared GPU uniform buffer storing the simulation parameters,
+ /// uploaded each frame from CPU to GPU.
+ sim_params_uniforms: UniformBuffer<GpuSimParams>,
+ /// Global shared GPU buffer storing the various spawner parameter structs
+ /// for the active effect instances.
+ // Note: we're still binding individual spawners in vfx_sort_fill.
+ spawner_buffer: AlignedBufferVec<GpuSpawnerParams>,
+ /// Global shared GPU buffer storing the various indirect dispatch args
+ /// structs for the indirect dispatch of the Update pass.
+ dispatch_indirect_args_buffer: GpuBuffer<GpuDispatchIndirectArgs>,
+ /// Global shared GPU buffer storing the various indirect draw args structs
+ /// for the indirect Render pass. Note that we use
+ /// [`GpuDrawIndexedIndirectArgs`] as the largest of the two variants (the
+ /// other being [`GpuDrawIndirectArgs`]). For non-indexed entries, we ignore
+ /// the last `u32` value.
+ draw_indirect_args_buffer: BufferTable<GpuDrawIndexedIndirectArgs>,
+ /// Global shared GPU buffer storing the various `EffectMetadata`
+ /// structs for the active effect instances.
+ effect_metadata_buffer: BufferTable<GpuEffectMetadata>,
+ /// Various GPU limits and aligned sizes lazily allocated and cached for
+ /// convenience.
+ #[allow(dead_code)]
+ gpu_limits: GpuLimits,
+ indirect_shader_noevent: Handle<Shader>,
+ indirect_shader_events: Handle<Shader>,
+ /// Pipeline cache ID of the two indirect dispatch pass pipelines (the
+ /// -noevent and -events variants).
+ indirect_pipeline_ids: [CachedComputePipelineId; 2],
+ /// Pipeline cache ID of the active indirect dispatch pass pipeline, which
+ /// is either the -noevent or -events variant depending on whether there's
+ /// any child effect with GPU events currently active.
+ active_indirect_pipeline_id: CachedComputePipelineId,
+
+ prefix_sum_shader: Handle<Shader>,
+ prefix_sum_bind_group: Option<BindGroup>,
+ prefix_sum_pipeline_id: CachedComputePipelineId,
+}
+
+impl EffectsMeta {
+ pub fn new(
+ device: RenderDevice,
+ indirect_shader_noevent: Handle<Shader>,
+ indirect_shader_events: Handle<Shader>,
+ prefix_sum_shader: Handle<Shader>,
+ ) -> Self {
+ let gpu_limits = GpuLimits::from_device(&device);
+
+ // Ensure individual GpuSpawnerParams elements are properly aligned so they can
+ // be addressed individually by the computer shaders.
+ let item_align = gpu_limits.storage_buffer_align();
+ trace!(
+ "Aligning storage buffers to {} bytes as device limits requires.",
+ item_align.get()
+ );
+
+ Self {
+ view_bind_group: None,
+ update_sim_params_bind_group: None,
+ init_and_indirect_sim_params_bind_group: None,
+ indirect_metadata_bind_group: None,
+ indirect_spawner_bind_group: None,
+ sim_params_uniforms: UniformBuffer::default(),
+ spawner_buffer: AlignedBufferVec::new(
+ BufferUsages::STORAGE,
+ Some(item_align.into()),
+ Some("hanabi:buffer:spawner".to_string()),
+ ),
+ dispatch_indirect_args_buffer: GpuBuffer::new(
+ BufferUsages::STORAGE | BufferUsages::INDIRECT,
+ Some("hanabi:buffer:dispatch_indirect_args".to_string()),
+ ),
+ draw_indirect_args_buffer: BufferTable::new(
+ BufferUsages::STORAGE | BufferUsages::INDIRECT,
+ Some(GpuDrawIndexedIndirectArgs::SHADER_SIZE),
+ Some("hanabi:buffer:draw_indirect_args".to_string()),
+ ),
+ effect_metadata_buffer: BufferTable::new(
+ BufferUsages::STORAGE | BufferUsages::INDIRECT,
+ None,
+ Some("hanabi:buffer:effect_metadata".to_string()),
+ ),
+ gpu_limits,
+ indirect_shader_noevent,
+ indirect_shader_events,
+ indirect_pipeline_ids: [
+ CachedComputePipelineId::INVALID,
+ CachedComputePipelineId::INVALID,
+ ],
+ active_indirect_pipeline_id: CachedComputePipelineId::INVALID,
+ prefix_sum_shader,
+ prefix_sum_bind_group: None,
+ prefix_sum_pipeline_id: CachedComputePipelineId::INVALID,
+ }
+ }
+
+ /// Allocate a [`GpuSpawnerParams`] entry into the global shared GPU buffer.
+ ///
+ /// The entry is allocated for a single render frame. It's automatically
+ /// deallocated at the end of this render frame.
+ ///
+ /// # Returns
+ ///
+ /// This returns the index of the entry into the global GPU buffer.
+ pub fn allocate_spawner(&mut self, gpu_spawner_params: GpuSpawnerParams) -> u32 {
+ let spawner_base = self.spawner_buffer.len() as u32;
+ self.spawner_buffer.push(gpu_spawner_params);
+ spawner_base
+ }
+
+ pub fn allocate_draw_indirect(
+ &mut self,
+ draw_args: &AnyDrawIndirectArgs,
+ ) -> CachedDrawIndirectArgs {
+ let row = self
+ .draw_indirect_args_buffer
+ .insert(draw_args.bitcast_to_row_entry());
+ CachedDrawIndirectArgs {
+ row,
+ args: *draw_args,
+ }
+ }
+
+ pub fn update_draw_indirect(&mut self, row_index: &CachedDrawIndirectArgs) {
+ self.draw_indirect_args_buffer
+ .update(row_index.get_row(), row_index.args.bitcast_to_row_entry());
+ }
+
+ pub fn free_draw_indirect(&mut self, row_index: &CachedDrawIndirectArgs) {
+ self.draw_indirect_args_buffer.remove(row_index.get_row());
+ }
+}
+
+bitflags! {
+ /// Effect flags.
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+ pub struct LayoutFlags: u32 {
+ /// No flags.
+ const NONE = 0;
+ // DEPRECATED - The effect uses an image texture.
+ //const PARTICLE_TEXTURE = (1 << 0);
+ /// The effect is simulated in local space.
+ const LOCAL_SPACE_SIMULATION = (1 << 2);
+ /// The effect uses alpha masking instead of alpha blending. Only used for 3D.
+ const USE_ALPHA_MASK = (1 << 3);
+ /// The effect is rendered with flipbook texture animation based on the
+ /// [`Attribute::SPRITE_INDEX`] of each particle.
+ const FLIPBOOK = (1 << 4);
+ /// The effect needs UVs.
+ const NEEDS_UV = (1 << 5);
+ /// The effect has ribbons.
+ const RIBBONS = (1 << 6);
+ /// The effects needs normals.
+ const NEEDS_NORMAL = (1 << 7);
+ /// The effect is fully-opaque.
+ const OPAQUE = (1 << 8);
+ /// The (update) shader emits GPU spawn events to instruct another effect to spawn particles.
+ const EMIT_GPU_SPAWN_EVENTS = (1 << 9);
+ /// The (init) shader spawns particles by consuming GPU spawn events, instead of
+ /// a single CPU spawn count.
+ const CONSUME_GPU_SPAWN_EVENTS = (1 << 10);
+ /// The (init or update) shader needs access to its parent particle. This allows
+ /// a particle init or update pass to read the data of a parent particle, for
+ /// example to inherit some of the attributes.
+ const READ_PARENT_PARTICLE = (1 << 11);
+ /// The effect access to the particle data in the fragment shader.
+ const NEEDS_PARTICLE_FRAGMENT = (1 << 12);
+ }
+}
+
+impl Default for LayoutFlags {
+ fn default() -> Self {
+ Self::NONE
+ }
+}
+
+// raea: blended particles drawn in a fixed order, so a frame is the same on every run (raea #52). The draw list is
+// built with atomics, in an order that differs from run to run, which only opaque and alpha-masked particles' depth
+// test hides; so blended effects are sorted like ribbons, by view depth from the main camera, far first (as Bevy sorts
+// its transparent phase). The sort key's offset carries two flags for vfx_sort_fill.wesl: the key is the depth of the
+// vec3 at that offset, and in local space (the effect's transform applies).
+pub(crate) const RAEA_SORT_BY_DISTANCE: u32 = 1 << 31;
+pub(crate) const RAEA_SORT_LOCAL: u32 = 1 << 30;
+
+impl LayoutFlags {
+ /// raea: the effect's particles are sorted before drawing: ribbons (upstream) and blended effects.
+ pub(crate) fn raea_sorted(&self) -> bool {
+ self.contains(LayoutFlags::RIBBONS) || !self.intersects(LayoutFlags::OPAQUE | LayoutFlags::USE_ALPHA_MASK)
+ }
+}
+
+/// Observer raised when the [`CachedEffect`] component is removed, which
+/// indicates that the effect instance was despawned.
+pub(crate) fn on_remove_cached_effect(
+ trigger: On<Remove<CachedEffect>>,
+ query: Query<(Entity, &MainEntity, &CachedEffect)>,
+ mut effect_cache: ResMut<EffectCache>,
+ mut effect_bind_groups: ResMut<EffectBindGroups>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("on_remove_cached_effect").entered();
+
+ // FIXME - review this Observer pattern; this triggers for each event one by
+ // one, which could kill performance if many effects are removed.
+
+ // Fecth the components of the effect being destroyed. Note that the despawn
+ // command above is not yet applied, so this query should always succeed.
+ let Ok((render_entity, main_entity, cached_effect)) = query.get(trigger.event().entity) else {
+ return;
+ };
+
+ // Deallocate the effect slice in the GPU effect buffer, and if this was the
+ // last slice, also deallocate the GPU buffer itself.
+ trace!(
+ "=> ParticleEffect on render entity {:?} associated with main entity {:?}, removing...",
+ render_entity,
+ main_entity,
+ );
+ let Ok(SlabState::Free) = effect_cache.remove(cached_effect) else {
+ // Buffer was not affected, so all bind groups are still valid. Nothing else to
+ // do.
+ return;
+ };
+
+ // Clear bind groups associated with the removed buffer
+ trace!(
+ "=> GPU particle slab #{} gone, destroying its bind groups...",
+ cached_effect.slab_id.index()
+ );
+ effect_bind_groups
+ .particle_slabs
+ .remove(&cached_effect.slab_id);
+}
+
+/// Observer raised when the [`CachedEffectMetadata`] component is removed, to
+/// deallocate the GPU resources associated with the indirect draw args.
+pub(crate) fn on_remove_cached_metadata(
+ trigger: On<Remove<CachedEffectMetadata>>,
+ query: Query<&CachedEffectMetadata>,
+ mut effects_meta: ResMut<EffectsMeta>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("on_remove_cached_metadata").entered();
+
+ if let Ok(cached_metadata) = query.get(trigger.event().entity) {
+ if cached_metadata.table_id.is_valid() {
+ effects_meta
+ .effect_metadata_buffer
+ .remove(cached_metadata.table_id);
+ }
+ };
+}
+
+/// Observer raised when the [`CachedDrawIndirectArgs`] component is removed, to
+/// deallocate the GPU resources associated with the indirect draw args.
+pub(crate) fn on_remove_cached_draw_indirect_args(
+ trigger: On<Remove<CachedDrawIndirectArgs>>,
+ query: Query<&CachedDrawIndirectArgs>,
+ mut effects_meta: ResMut<EffectsMeta>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("on_remove_cached_draw_indirect_args").entered();
+
+ if let Ok(cached_draw_args) = query.get(trigger.event().entity) {
+ effects_meta.free_draw_indirect(cached_draw_args);
+ };
+}
+
+/// Clear pending GPU resources left from previous frame.
+///
+/// Those generally are source buffers for buffer-to-buffer copies on capacity
+/// growth, which need the source buffer to be alive until the copy is done,
+/// then can be discarded here.
+pub(crate) fn clear_previous_frame_resizes(
+ mut effects_meta: ResMut<EffectsMeta>,
+ mut sort_bind_groups: ResMut<SortBindGroups>,
+ mut init_fill_dispatch_queue: ResMut<InitFillDispatchQueue>,
+ mut sort_fill_dispatch_queue: ResMut<SortFillDispatchQueue>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("clear_previous_frame_resizes").entered();
+ trace!("clear_previous_frame_resizes");
+
+ init_fill_dispatch_queue.clear();
+ sort_fill_dispatch_queue.clear();
+
+ // Clear last frame's buffer resizes which may have occured during last frame,
+ // during `simulate()` while the `BufferTable` could not be mutated. This is
+ // the first point at which we can do that where we're not blocking the main
+ // world (so, excluding the extract system).
+ effects_meta
+ .dispatch_indirect_args_buffer
+ .clear_previous_frame_resizes();
+ effects_meta
+ .draw_indirect_args_buffer
+ .clear_previous_frame_resizes();
+ effects_meta
+ .effect_metadata_buffer
+ .clear_previous_frame_resizes();
+ sort_bind_groups.clear_previous_frame_resizes();
+}
+
+// Fixup the [`CachedChildInfo::global_child_index`] once all child infos have
+// been allocated.
+pub fn fixup_parents(
+ q_changed_parents: Query<(Entity, Ref<CachedParentInfo>)>,
+ mut q_children: Query<&mut CachedChildInfo>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("fixup_parents").entered();
+ trace!("fixup_parents");
+
+ // Once all parents are (re-)allocated, fix up the global index of all
+ // children if the parent base index changed.
+ trace!(
+ "Updating the global index of children of parent effects whose child list just changed..."
+ );
+ for (parent_entity, cached_parent_info) in q_changed_parents.iter() {
+ let base_index =
+ cached_parent_info.byte_range.start / GpuChildInfo::SHADER_SIZE.get() as u32;
+ let parent_changed = cached_parent_info.is_changed();
+ trace!(
+ "Updating {} children of parent effect {:?} with base child index {} (parent_changed:{})...",
+ cached_parent_info.children.len(),
+ parent_entity,
+ base_index,
+ parent_changed
+ );
+ for (child_entity, _) in &cached_parent_info.children {
+ let Ok(mut cached_child_info) = q_children.get_mut(*child_entity) else {
+ error!(
+ "Cannot find child {:?} declared by parent {:?}",
+ *child_entity, parent_entity
+ );
+ continue;
+ };
+ if !cached_child_info.is_changed() && !parent_changed {
+ continue;
+ }
+ cached_child_info.global_child_index = base_index + cached_child_info.local_child_index;
+ trace!(
+ "+ Updated global index for child ID {:?} of parent {:?}: local={}, global={}",
+ child_entity,
+ parent_entity,
+ cached_child_info.local_child_index,
+ cached_child_info.global_child_index
+ );
+ }
+ }
+}
+
+/// Allocate the GPU resources for all extracted effects.
+///
+/// This adds the [`CachedEffect`] component as needed, and update it with the
+/// allocation in the [`EffectCache`].
+pub fn allocate_effects(
+ mut commands: Commands,
+ mut q_extracted_effects: Query<
+ (
+ Entity,
+ &ExtractedEffect,
+ Has<ChildEffectOf>,
+ Option<&mut CachedEffect>,
+ ),
+ Changed<ExtractedEffect>,
+ >,
+ mut effect_cache: ResMut<EffectCache>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("allocate_effects").entered();
+ trace!("allocate_effects");
+
+ for (entity, extracted_effect, has_parent, maybe_cached_effect) in &mut q_extracted_effects {
+ // Insert or update the effect into the EffectCache
+ if let Some(mut cached_effect) = maybe_cached_effect {
+ trace!("Updating EffectCache entry for entity {entity:?}...");
+ let _ = effect_cache.remove(cached_effect.as_ref());
+ *cached_effect = effect_cache.insert(
+ extracted_effect.handle.clone(),
+ extracted_effect.capacity,
+ &extracted_effect.particle_layout,
+ );
+ } else {
+ trace!("Allocating new entry in EffectCache for entity {entity:?}...");
+ let cached_effect = effect_cache.insert(
+ extracted_effect.handle.clone(),
+ extracted_effect.capacity,
+ &extracted_effect.particle_layout,
+ );
+ commands.entity(entity).insert(cached_effect);
+ }
+
+ // Ensure the particle@1 bind group layout exists for the given configuration of
+ // particle layout. We do this here only for effects without a parent; for those
+ // with a parent, we'll do it after we resolved that parent.
+ if !has_parent {
+ let parent_min_binding_size = None;
+ effect_cache.ensure_particle_bind_group_layout_desc(
+ extracted_effect.particle_layout.min_binding_size32(),
+ parent_min_binding_size,
+ );
+ }
+
+ // Ensure the metadata@3 bind group layout exists for the init pass.
+ {
+ let consume_gpu_spawn_events = extracted_effect
+ .layout_flags
+ .contains(LayoutFlags::CONSUME_GPU_SPAWN_EVENTS);
+ effect_cache.ensure_metadata_init_bind_group_layout_desc(consume_gpu_spawn_events);
+ }
+ }
+}
+
+/// Update any cached mesh info based on any relocation done by Bevy itself.
+///
+/// Bevy will merge small meshes into larger GPU buffers automatically. When
+/// this happens, the mesh location changes, and we need to update our
+/// references to it in order to know how to issue the draw commands.
+///
+/// This system updates both the [`CachedMeshLocation`] and the
+/// [`CachedIndirectDrawArgs`] components.
+pub fn update_mesh_locations(
+ mut commands: Commands,
+ mut effects_meta: ResMut<EffectsMeta>,
+ mesh_allocator: Res<MeshAllocator>,
+ render_meshes: Res<RenderAssets<RenderMesh>>,
+ mut q_cached_effects: Query<(
+ Entity,
+ &ExtractedEffectMesh,
+ Option<&mut CachedMeshLocation>,
+ Option<&mut CachedDrawIndirectArgs>,
+ )>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("update_mesh_locations").entered();
+ trace!("update_mesh_locations");
+
+ for (entity, extracted_mesh, maybe_cached_mesh_location, maybe_cached_draw_indirect_args) in
+ &mut q_cached_effects
+ {
+ let mut cmds = commands.entity(entity);
+
+ // Resolve the render mesh
+ let Some(render_mesh) = render_meshes.get(extracted_mesh.mesh) else {
+ warn!(
+ "Cannot find render mesh of particle effect instance on entity {:?}, despite applying default mesh. Invalid asset handle: {:?}",
+ entity, extracted_mesh.mesh
+ );
+ cmds.remove::<CachedMeshLocation>();
+ continue;
+ };
+
+ // Find the location where the render mesh was allocated. This is handled by
+ // Bevy itself in the allocate_and_free_meshes() system. Bevy might
+ // re-batch the vertex and optional index data of meshes together at any point,
+ // so we need to confirm that the location data we may have cached is still
+ // valid.
+ let Some(mesh_vertex_buffer_slice) = mesh_allocator.mesh_vertex_slice(&extracted_mesh.mesh)
+ else {
+ trace!(
+ "Effect main_entity {:?}: cannot find vertex slice of render mesh {:?}",
+ entity,
+ extracted_mesh.mesh
+ );
+ cmds.remove::<CachedMeshLocation>();
+ continue;
+ };
+ let mesh_index_buffer_slice = mesh_allocator.mesh_index_slice(&extracted_mesh.mesh);
+ let indexed =
+ if let RenderMeshBufferInfo::Indexed { index_format, .. } = render_mesh.buffer_info {
+ if let Some(ref slice) = mesh_index_buffer_slice {
+ Some(MeshIndexSlice {
+ format: index_format,
+ buffer: slice.buffer.clone(),
+ range: slice.range.clone(),
+ })
+ } else {
+ trace!(
+ "Effect main_entity {:?}: cannot find index slice of render mesh {:?}",
+ entity,
+ extracted_mesh.mesh
+ );
+ cmds.remove::<CachedMeshLocation>();
+ continue;
+ }
+ } else {
+ None
+ };
+
+ // Calculate the new draw args and mesh location based on Bevy's info
+ let new_draw_args = AnyDrawIndirectArgs::from_slices(
+ &mesh_vertex_buffer_slice,
+ mesh_index_buffer_slice.as_ref(),
+ );
+ let new_mesh_location = match &mesh_index_buffer_slice {
+ // Indexed mesh rendering
+ Some(mesh_index_buffer_slice) => CachedMeshLocation {
+ vertex_buffer: mesh_vertex_buffer_slice.buffer.id(),
+ vertex_or_index_count: mesh_index_buffer_slice.range.len() as u32,
+ first_index_or_vertex_offset: mesh_index_buffer_slice.range.start,
+ vertex_offset_or_base_instance: mesh_vertex_buffer_slice.range.start as i32,
+ indexed,
+ },
+ // Non-indexed mesh rendering
+ None => CachedMeshLocation {
+ vertex_buffer: mesh_vertex_buffer_slice.buffer.id(),
+ vertex_or_index_count: mesh_vertex_buffer_slice.range.len() as u32,
+ first_index_or_vertex_offset: mesh_vertex_buffer_slice.range.start,
+ vertex_offset_or_base_instance: 0,
+ indexed: None,
+ },
+ };
+
+ // We don't allocate the draw indirect args ahead of time because we need to
+ // select the indexed vs. non-indexed buffer. Now that we know whether the mesh
+ // is indexed, we can allocate it (or reallocate it if indexing mode changed).
+ if let Some(mut cached_draw_indirect) = maybe_cached_draw_indirect_args {
+ assert!(cached_draw_indirect.row.is_valid());
+
+ // If the GPU draw args changed, re-upload to GPU.
+ if new_draw_args != cached_draw_indirect.args {
+ debug!(
+ "Indirect draw args changed for asset {:?}\nold:{:?}\nnew:{:?}",
+ entity, cached_draw_indirect.args, new_draw_args
+ );
+ cached_draw_indirect.args = new_draw_args;
+ effects_meta.update_draw_indirect(cached_draw_indirect.as_ref());
+ }
+ } else {
+ cmds.insert(effects_meta.allocate_draw_indirect(&new_draw_args));
+ }
+
+ // Compare to any cached data and update if necessary, or insert if missing.
+ // This will trigger change detection in the ECS, which will in turn trigger
+ // GpuEffectMetadata re-upload.
+ if let Some(mut old_mesh_location) = maybe_cached_mesh_location {
+ if *old_mesh_location != new_mesh_location {
+ debug!(
+ "Mesh location changed for asset {:?}\nold:{:?}\nnew:{:?}",
+ entity, old_mesh_location, new_mesh_location
+ );
+ *old_mesh_location = new_mesh_location;
+ }
+ } else {
+ cmds.insert(new_mesh_location);
+ }
+ }
+}
+
+/// Allocate an entry in the GPU table for any [`CachedEffectMetadata`] missing
+/// one.
+///
+/// This system does NOT take care of (re-)uploading recent CPU data to GPU.
+/// This is done much later in the frame, after batching and once all data for
+/// it is ready. But it's necessary to ensure the allocation is determined
+/// already ahead of time, in order to do batching of contiguous metadata
+/// blocks (TODO; not currently used, also may end up using binary search in
+/// shader, in which case we won't need continguous-ness and can maybe remove
+/// this system).
+// TODO - consider using observer OnAdd instead?
+pub fn allocate_metadata(
+ mut effects_meta: ResMut<EffectsMeta>,
+ mut q_metadata: Query<&mut CachedEffectMetadata>,
+) {
+ for mut metadata in &mut q_metadata {
+ if !metadata.table_id.is_valid() {
+ metadata.table_id = effects_meta
+ .effect_metadata_buffer
+ .insert(metadata.metadata);
+ } else {
+ // Unless this is the first time we allocate the GPU entry (above),
+ // we should never reach the beginning of this frame
+ // with a changed metadata which has not
+ // been re-uploaded last frame.
+ // NO! We can only detect the change *since last run of THIS system*
+ // so wont' see that a latter system the data.
+ // assert!(!metadata.is_changed());
+ }
+ }
+}
+
+/// Update the [`CachedParentInfo`] of parent effects and the
+/// [`CachedChildInfo`] of child effects.
+pub fn allocate_parent_child_infos(
+ mut commands: Commands,
+ mut effect_cache: ResMut<EffectCache>,
+ mut event_cache: ResMut<EventCache>,
+ // All extracted child effects. May or may not already have a CachedChildInfo. If not, this
+ // will be spawned below.
+ mut q_child_effects: Query<(
+ Entity,
+ &ExtractedEffect,
+ &ChildEffectOf,
+ &CachedEffectEvents,
+ Option<&mut CachedChildInfo>,
+ )>,
+ // All parent effects from a previous frame (already have CachedParentInfo), which can be
+ // updated in-place without spawning a new CachedParentInfo.
+ mut q_parent_effects: Query<(
+ Entity,
+ &ExtractedEffect,
+ &CachedEffect,
+ &ChildrenEffects,
+ Option<&mut CachedParentInfo>,
+ )>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("allocate_child_infos").entered();
+ trace!("allocate_child_infos");
+
+ // Loop on all child effects and ensure their CachedChildInfo is up-to-date.
+ for (child_entity, _, child_effect_of, cached_effect_events, maybe_cached_child_info) in
+ &mut q_child_effects
+ {
+ // Fetch the parent effect
+ let parent_entity = child_effect_of.parent;
+ let Ok((_, _, parent_cached_effect, children_effects, _)) =
+ q_parent_effects.get(parent_entity)
+ else {
+ warn!("Unknown parent #{parent_entity:?} on child entity {child_entity:?}, removing CachedChildInfo.");
+ if maybe_cached_child_info.is_some() {
+ commands.entity(child_entity).remove::<CachedChildInfo>();
+ }
+ continue;
+ };
+
+ // Find the index of this child entity in its parent's storage
+ let Some(local_child_index) = children_effects.0.iter().position(|e| *e == child_entity)
+ else {
+ warn!("Cannot find child entity {child_entity:?} in the children collection of parent entity {parent_entity:?}. Relationship desync?");
+ if maybe_cached_child_info.is_some() {
+ commands.entity(child_entity).remove::<CachedChildInfo>();
+ }
+ continue;
+ };
+ let local_child_index = local_child_index as u32;
+
+ // Fetch the effect buffer of the parent effect
+ let Some(parent_buffer_binding_source) = effect_cache
+ .get_slab(&parent_cached_effect.slab_id)
+ .map(|effect_buffer| effect_buffer.max_binding_source())
+ else {
+ warn!(
+ "Unknown parent slab #{} on parent entity {:?}, removing CachedChildInfo.",
+ parent_cached_effect.slab_id.index(),
+ parent_entity
+ );
+ if maybe_cached_child_info.is_some() {
+ commands.entity(child_entity).remove::<CachedChildInfo>();
+ }
+ continue;
+ };
+
+ let new_cached_child_info = CachedChildInfo {
+ parent_slab_id: parent_cached_effect.slab_id,
+ parent_slab_offset: parent_cached_effect.slice.range().start,
+ parent_particle_layout: parent_cached_effect.slice.particle_layout.clone(),
+ parent_buffer_binding_source,
+ local_child_index,
+ global_child_index: u32::MAX, // fixed up later by fixup_parents()
+ init_indirect_dispatch_index: cached_effect_events.init_indirect_dispatch_index,
+ };
+ if let Some(mut cached_child_info) = maybe_cached_child_info {
+ if !cached_child_info.is_locally_equal(&new_cached_child_info) {
+ *cached_child_info = new_cached_child_info;
+ }
+ } else {
+ commands.entity(child_entity).insert(new_cached_child_info);
+ }
+ }
+
+ // Loop on all parent effects and ensure their CachedParentInfo is up-to-date.
+ for (parent_entity, parent_extracted_effect, _, children_effects, maybe_cached_parent_info) in
+ &mut q_parent_effects
+ {
+ let parent_min_binding_size = parent_extracted_effect.particle_layout.min_binding_size32();
+
+ // Loop over children and gather GpuChildInfo
+ let mut new_children = Vec::with_capacity(children_effects.0.len());
+ let mut new_child_infos = Vec::with_capacity(children_effects.0.len());
+ for child_entity in children_effects.0.iter() {
+ // Fetch the child's event buffer allocation info
+ let Ok((_, child_extracted_effect, _, cached_effect_events, _)) =
+ q_child_effects.get(*child_entity)
+ else {
+ warn!("Child entity {child_entity:?} from parent entity {parent_entity:?} didnt't resolve to a child instance. The parent effect cannot be processed.");
+ if maybe_cached_parent_info.is_some() {
+ commands.entity(parent_entity).remove::<CachedParentInfo>();
+ }
+ break;
+ };
+
+ // Fetch the GPU event buffer of the child
+ let Some(event_buffer) = event_cache.get_buffer(cached_effect_events.buffer_index)
+ else {
+ warn!("Child entity {child_entity:?} from parent entity {parent_entity:?} doesn't have an allocated GPU event buffer. The parent effect cannot be processed.");
+ break;
+ };
+
+ let buffer_binding_source = BufferBindingSource {
+ buffer: event_buffer.clone(),
+ offset: cached_effect_events.range.start,
+ size: NonZeroU32::new(cached_effect_events.range.len() as u32).unwrap(),
+ };
+ new_children.push((*child_entity, buffer_binding_source));
+
+ new_child_infos.push(GpuChildInfo {
+ event_count: 0,
+ init_indirect_dispatch_index: cached_effect_events.init_indirect_dispatch_index,
+ });
+
+ // Ensure the particle@1 bind group layout exists for the given configuration of
+ // particle layout. We do this here only for effects with a parent; for those
+ // without a parent, we already did this in allocate_effects().
+ effect_cache.ensure_particle_bind_group_layout_desc(
+ child_extracted_effect.particle_layout.min_binding_size32(),
+ Some(parent_min_binding_size),
+ );
+ }
+
+ // If we don't have all children, just abort this effect. We don't try to have
+ // partial relationships, this is too complex for shader bindings.
+ debug_assert_eq!(new_children.len(), new_child_infos.len());
+ if (new_children.len() < children_effects.len()) && maybe_cached_parent_info.is_some() {
+ warn!("One or more child effect(s) on parent effect {parent_entity:?} failed to configure. The parent effect cannot be processed.");
+ commands.entity(parent_entity).remove::<CachedParentInfo>();
+ continue;
+ }
+
+ // Insert or update the CachedParentInfo component of the parent effect
+ if let Some(mut cached_parent_info) = maybe_cached_parent_info {
+ if cached_parent_info.children != new_children {
+ // FIXME - missing way to just update in-place without changing the allocation
+ // size!
+ // if cached_parent_info.children.len() == new_children.len() {
+ //} else {
+ event_cache.reallocate_child_infos(
+ parent_entity,
+ new_children,
+ &new_child_infos[..],
+ cached_parent_info.as_mut(),
+ );
+ //}
+ }
+ } else {
+ let cached_parent_info =
+ event_cache.allocate_child_infos(parent_entity, new_children, &new_child_infos[..]);
+ commands.entity(parent_entity).insert(cached_parent_info);
+ }
+ }
+}
+
+/// Prepare the init and update compute pipelines for an effect.
+///
+/// This caches the pipeline IDs once resolved, and their compiling state when
+/// it changes, to determine when an effect is ready to be used.
+///
+/// Note that we do that proactively even if the effect will be skipped this
+/// frame (for example because it's not visible). This ensures we queue pipeline
+/// compilations ASAP, as they can take a long time (10+ frames). We also use
+/// the pipeline compiling state, which we query here, to inform whether the
+/// effect is ready for this frame. So in general if this is a new pipeline, it
+/// won't be ready this frame.
+pub fn prepare_init_update_pipelines(
+ mut q_effects: Query<(
+ Entity,
+ &ExtractedEffect,
+ &CachedEffect,
+ Option<&CachedChildInfo>,
+ Option<&CachedParentInfo>,
+ Option<&CachedEffectProperties>,
+ &mut CachedPipelines,
+ )>,
+ // FIXME - need mut for bind group layout creation; shouldn't be create there though
+ mut effect_cache: ResMut<EffectCache>,
+ pipeline_cache: Res<PipelineCache>,
+ property_cache: ResMut<PropertyCache>,
+ init_pipeline: Res<ParticlesInitPipeline>,
+ update_pipeline: Res<ParticlesUpdatePipeline>,
+ mut specialized_init_pipelines: ResMut<SpecializedComputePipelines<ParticlesInitPipeline>>,
+ mut specialized_update_pipelines: ResMut<SpecializedComputePipelines<ParticlesUpdatePipeline>>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("prepare_init_update_pipelines").entered();
+ trace!("prepare_init_update_pipelines");
+
+ // Note: As of Bevy 0.16 we can't evict old pipelines from the cache. They're
+ // inserted forever. https://github.com/bevyengine/bevy/issues/19925
+
+ for (
+ entity,
+ extracted_effect,
+ cached_effect,
+ maybe_cached_child_info,
+ maybe_cached_parent_info,
+ maybe_cached_properties,
+ mut cached_pipelines,
+ ) in &mut q_effects
+ {
+ trace!(
+ "Preparing pipelines for effect {:?}... (flags: {:?})",
+ entity,
+ cached_pipelines.flags
+ );
+
+ let particle_layout = &cached_effect.slice.particle_layout;
+ let particle_layout_min_binding_size = particle_layout.min_binding_size32();
+ let has_event_buffer = maybe_cached_child_info.is_some();
+ let parent_particle_layout_min_binding_size = maybe_cached_child_info
+ .as_ref()
+ .map(|cci| cci.parent_particle_layout.min_binding_size32());
+
+ let Some(particle_bind_group_layout_desc) = effect_cache.particle_bind_group_layout_desc(
+ particle_layout_min_binding_size,
+ parent_particle_layout_min_binding_size,
+ ) else {
+ error!("Failed to find particle sim bind group @1 for min_binding_size={} parent_min_binding_size={:?}",
+ particle_layout_min_binding_size, parent_particle_layout_min_binding_size);
+ continue;
+ };
+ let particle_bind_group_layout_desc = particle_bind_group_layout_desc.clone();
+
+ // This should always exist by the time we reach this point, because we should
+ // have inserted any property in the cache, which would have allocated the
+ // proper bind group layout (or the default no-property one).
+ let property_layout_min_binding_size =
+ maybe_cached_properties.map(|cp| cp.property_layout.min_binding_size());
+ let spawner_bind_group_layout_desc = property_cache
+ .bind_group_layout_desc(
+ property_layout_min_binding_size,
+ true,
+ &extracted_effect.texture_layout,
+ )
+ .unwrap_or_else(|| {
+ panic!(
+ "Failed to find spawner@2 bind group layout for property binding size {:?} and texture layout {:?}",
+ property_layout_min_binding_size,
+ extracted_effect.texture_layout,
+ )
+ });
+ trace!(
+ "Retrieved spawner@2 bind group layout desc for property binding size {}: {:?}.",
+ property_layout_min_binding_size
+ .as_ref()
+ .map(|size| size.get())
+ .unwrap_or(0),
+ spawner_bind_group_layout_desc,
+ );
+
+ // Resolve the init pipeline
+ let init_pipeline_id = if let Some(init_pipeline_id) = cached_pipelines.init.as_ref() {
+ *init_pipeline_id
+ } else {
+ // Clear flag just in case, to ensure consistency.
+ cached_pipelines
+ .flags
+ .remove(CachedPipelineFlags::INIT_PIPELINE_READY);
+
+ // Fetch the metadata@3 bind group layout from the cache
+ let metadata_bind_group_layout_desc = effect_cache
+ .metadata_init_bind_group_layout_desc(has_event_buffer)
+ .unwrap()
+ .clone();
+
+ let init_pipeline_key_flags = {
+ let mut flags = ParticleInitPipelineKeyFlags::empty();
+ flags.set(
+ ParticleInitPipelineKeyFlags::ATTRIBUTE_PREV,
+ particle_layout.contains(Attribute::PREV),
+ );
+ flags.set(
+ ParticleInitPipelineKeyFlags::ATTRIBUTE_NEXT,
+ particle_layout.contains(Attribute::NEXT),
+ );
+ flags.set(
+ ParticleInitPipelineKeyFlags::CONSUME_GPU_SPAWN_EVENTS,
+ has_event_buffer,
+ );
+ flags
+ };
+
+ let init_pipeline_id: CachedComputePipelineId = specialized_init_pipelines.specialize(
+ pipeline_cache.as_ref(),
+ &init_pipeline,
+ ParticleInitPipelineKey {
+ shader: extracted_effect.effect_shaders.init.clone(),
+ particle_layout_min_binding_size,
+ parent_particle_layout_min_binding_size,
+ flags: init_pipeline_key_flags,
+ particle_bind_group_layout_desc: particle_bind_group_layout_desc.clone(),
+ spawner_bind_group_layout_desc: spawner_bind_group_layout_desc.clone(),
+ metadata_bind_group_layout_desc,
+ },
+ );
+ trace!("Init pipeline specialized: id={:?}", init_pipeline_id);
+
+ cached_pipelines.init = Some(init_pipeline_id);
+ init_pipeline_id
+ };
+
+ // Resolve the update pipeline
+ let update_pipeline_id = if let Some(update_pipeline_id) = cached_pipelines.update.as_ref()
+ {
+ *update_pipeline_id
+ } else {
+ // Clear flag just in case, to ensure consistency.
+ cached_pipelines
+ .flags
+ .remove(CachedPipelineFlags::UPDATE_PIPELINE_READY);
+
+ let num_event_buffers = maybe_cached_parent_info
+ .as_ref()
+ .map(|p| p.children.len() as u32)
+ .unwrap_or_default();
+
+ let local_space_simulation = extracted_effect
+ .layout_flags
+ .contains(LayoutFlags::LOCAL_SPACE_SIMULATION);
+
+ // FIXME: currently don't hava a way to determine when this is needed, because
+ // we know the number of children per parent only after resolving
+ // all parents, but by that point we forgot if this is a newly added
+ // effect or not. So since we need to re-ensure for all effects, not
+ // only new ones, might as well do here...
+ effect_cache.ensure_metadata_update_bind_group_layout_desc(num_event_buffers);
+
+ // Fetch the bind group layouts from the cache
+ let metadata_bind_group_layout_desc = effect_cache
+ .metadata_update_bind_group_layout_desc(num_event_buffers)
+ .unwrap()
+ .clone();
+
+ let update_pipeline_id = specialized_update_pipelines.specialize(
+ pipeline_cache.as_ref(),
+ &update_pipeline,
+ ParticleUpdatePipelineKey {
+ shader: extracted_effect.effect_shaders.update.clone(),
+ particle_layout: particle_layout.clone(),
+ local_space_simulation,
+ parent_particle_layout_min_binding_size,
+ num_event_buffers,
+ particle_bind_group_layout_desc: particle_bind_group_layout_desc.clone(),
+ spawner_bind_group_layout_desc: spawner_bind_group_layout_desc.clone(),
+ metadata_bind_group_layout_desc,
+ },
+ );
+ trace!("Update pipeline specialized: id={:?}", update_pipeline_id);
+
+ cached_pipelines.update = Some(update_pipeline_id);
+ update_pipeline_id
+ };
+
+ // Never batch an effect with a pipeline not available; this will prevent its
+ // init/update pass from running, but the vfx_indirect pass will run
+ // nonetheless, which causes desyncs and leads to bugs.
+ if pipeline_cache
+ .get_compute_pipeline(init_pipeline_id)
+ .is_none()
+ {
+ match pipeline_cache.get_compute_pipeline_state(init_pipeline_id)
+ {
+ CachedPipelineState::Err(err) => error!("Skipping effect from render entity {:?} due to missing or not ready init pipeline (error: {:?})", entity, err),
+ other => trace!(
+ "Skipping effect from render entity {:?} due to missing or not ready init pipeline (status: {:?})",
+ entity,
+ other
+ ),
+ }
+ cached_pipelines
+ .flags
+ .remove(CachedPipelineFlags::INIT_PIPELINE_READY);
+ continue;
+ }
+
+ // PipelineCache::get_compute_pipeline() only returns a value if the pipeline is
+ // ready
+ cached_pipelines
+ .flags
+ .insert(CachedPipelineFlags::INIT_PIPELINE_READY);
+ trace!("[Effect {:?}] Init pipeline ready.", entity);
+
+ // Never batch an effect with a pipeline not available; this will prevent its
+ // init/update pass from running, but the vfx_indirect pass will run
+ // nonetheless, which causes desyncs and leads to bugs.
+ if pipeline_cache
+ .get_compute_pipeline(update_pipeline_id)
+ .is_none()
+ {
+ trace!(
+ "Skipping effect from render entity {:?} due to missing or not ready update pipeline (status: {:?})",
+ entity,
+ pipeline_cache.get_compute_pipeline_state(update_pipeline_id)
+ );
+ cached_pipelines
+ .flags
+ .remove(CachedPipelineFlags::UPDATE_PIPELINE_READY);
+ continue;
+ }
+
+ // PipelineCache::get_compute_pipeline() only returns a value if the pipeline is
+ // ready
+ cached_pipelines
+ .flags
+ .insert(CachedPipelineFlags::UPDATE_PIPELINE_READY);
+ trace!("[Effect {:?}] Update pipeline ready.", entity);
+ }
+}
+
+pub fn prepare_indirect_pipeline(
+ event_cache: Res<EventCache>,
+ mut effects_meta: ResMut<EffectsMeta>,
+ pipeline_cache: Res<PipelineCache>,
+ indirect_pipeline: Res<DispatchIndirectPipeline>,
+ mut specialized_indirect_pipelines: ResMut<
+ SpecializedComputePipelines<DispatchIndirectPipeline>,
+ >,
+ prefix_sum_pipeline: Res<PrefixSumPipeline>,
+) {
+ // Queue the vfx_prefix_sum pipeline if not already ready
+ // TODO - not really related to this system, should probably be moved?
+ if effects_meta.prefix_sum_pipeline_id == CachedComputePipelineId::INVALID {
+ effects_meta.prefix_sum_pipeline_id =
+ pipeline_cache.queue_compute_pipeline(prefix_sum_pipeline.make_pipeline_desc())
+ }
+
+ // Ensure the 2 variants of the indirect pipelines are created.
+ // TODO - move that elsewhere in some one-time setup?
+ if effects_meta.indirect_pipeline_ids[0] == CachedComputePipelineId::INVALID {
+ effects_meta.indirect_pipeline_ids[0] = specialized_indirect_pipelines.specialize(
+ pipeline_cache.as_ref(),
+ &indirect_pipeline,
+ DispatchIndirectPipelineKey { has_events: false },
+ );
+ }
+ if effects_meta.indirect_pipeline_ids[1] == CachedComputePipelineId::INVALID {
+ effects_meta.indirect_pipeline_ids[1] = specialized_indirect_pipelines.specialize(
+ pipeline_cache.as_ref(),
+ &indirect_pipeline,
+ DispatchIndirectPipelineKey { has_events: true },
+ );
+ }
+
+ // Select the active one depending on whether there's any child info to consume
+ let is_empty = event_cache.child_infos().is_empty();
+ if effects_meta.active_indirect_pipeline_id == CachedComputePipelineId::INVALID {
+ if is_empty {
+ effects_meta.active_indirect_pipeline_id = effects_meta.indirect_pipeline_ids[0];
+ } else {
+ effects_meta.active_indirect_pipeline_id = effects_meta.indirect_pipeline_ids[1];
+ }
+ } else {
+ // If this is the first time we insert an event buffer, we need to switch the
+ // indirect pass from non-event to event mode. That is, we need to re-allocate
+ // the pipeline with the child infos buffer binding. Conversely, if there's no
+ // more effect using GPU spawn events, we can deallocate.
+ let was_empty =
+ effects_meta.active_indirect_pipeline_id == effects_meta.indirect_pipeline_ids[0];
+ if was_empty && !is_empty {
+ trace!("First event buffer inserted; switching indirect pass to event mode...");
+ effects_meta.active_indirect_pipeline_id = effects_meta.indirect_pipeline_ids[1];
+ } else if is_empty && !was_empty {
+ trace!("Last event buffer removed; switching indirect pass to no-event mode...");
+ effects_meta.active_indirect_pipeline_id = effects_meta.indirect_pipeline_ids[0];
+ }
+ }
+}
+
+// TEMP - Mark all cached effects as invalid for this frame until another system
+// explicitly marks them as valid. Otherwise we early out in some parts, and
+// reuse by mistake the previous frame's extraction.
+pub fn clear_transient_batch_inputs(
+ mut commands: Commands,
+ mut q_cached_effects: Query<Entity, With<BatchInput>>,
+) {
+ for entity in &mut q_cached_effects {
+ if let Ok(mut cmd) = commands.get_entity(entity) {
+ cmd.remove::<BatchInput>();
+ }
+ }
+}
+
+/// Effect mesh extracted from the main world.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Component)]
+pub(crate) struct ExtractedEffectMesh {
+ /// Asset of the effect mesh to draw.
+ pub mesh: AssetId<Mesh>,
+}
+
+/// Indexed mesh metadata for [`CachedMesh`].
+#[derive(Debug, Clone)]
+#[allow(dead_code)]
+pub(crate) struct MeshIndexSlice {
+ /// Index format.
+ pub format: IndexFormat,
+ /// GPU buffer containing the indices.
+ pub buffer: Buffer,
+ /// Range inside [`Self::buffer`] where the indices are.
+ pub range: Range<u32>,
+}
+
+impl PartialEq for MeshIndexSlice {
+ fn eq(&self, other: &Self) -> bool {
+ self.format == other.format
+ && self.buffer.id() == other.buffer.id()
+ && self.range == other.range
+ }
+}
+
+impl Eq for MeshIndexSlice {}
+
+/// Cached info about a mesh location in a Bevy buffer. This information is
+/// uploaded to GPU into [`GpuEffectMetadata`] for indirect rendering, but is
+/// also kept CPU side in this component to detect when Bevy relocated a mesh,
+/// so we can invalidate that GPU data.
+#[derive(Debug, Clone, PartialEq, Eq, Component)]
+pub(crate) struct CachedMeshLocation {
+ /// Vertex buffer.
+ pub vertex_buffer: BufferId,
+ /// See [`GpuEffectMetadata::vertex_or_index_count`].
+ pub vertex_or_index_count: u32,
+ /// See [`GpuEffectMetadata::first_index_or_vertex_offset`].
+ pub first_index_or_vertex_offset: u32,
+ /// See [`GpuEffectMetadata::vertex_offset_or_base_instance`].
+ pub vertex_offset_or_base_instance: i32,
+ /// Indexed rendering metadata.
+ pub indexed: Option<MeshIndexSlice>,
+}
+
+bitflags! {
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+ pub struct CachedPipelineFlags: u8 {
+ const NONE = 0;
+ /// The init pipeline for this effect is ready for use. This means the compute pipeline is compiled and cached.
+ const INIT_PIPELINE_READY = (1u8 << 0);
+ /// The update pipeline for this effect is ready for use. This means the compute pipeline is compiled and cached.
+ const UPDATE_PIPELINE_READY = (1u8 << 1);
+ }
+}
+
+impl Default for CachedPipelineFlags {
+ fn default() -> Self {
+ Self::NONE
+ }
+}
+
+/// Render world cached shader pipelines for a [`CachedEffect`].
+///
+/// This is updated with the IDs of the pipelines when they are queued for
+/// compiling, and with the state of those pipelines to detect when the effect
+/// is ready to be used.
+///
+/// This component is always auto-inserted alongside [`ExtractedEffect`] as soon
+/// as a new effect instance is spawned, because it contains the readiness state
+/// of those pipelines, which we want to query each frame. The pipelines are
+/// also mandatory, so this component is always needed.
+#[derive(Debug, Default, Component)]
+pub(crate) struct CachedPipelines {
+ /// Caching flags indicating the pipelines readiness.
+ pub flags: CachedPipelineFlags,
+ /// ID of the cached init pipeline. This is valid once the pipeline is
+ /// queued for compilation, but this doesn't mean the pipeline is ready for
+ /// use. Readiness is encoded in [`Self::flags`].
+ pub init: Option<CachedComputePipelineId>,
+ /// ID of the cached update pipeline. This is valid once the pipeline is
+ /// queued for compilation, but this doesn't mean the pipeline is ready for
+ /// use. Readiness is encoded in [`Self::flags`].
+ pub update: Option<CachedComputePipelineId>,
+}
+
+impl CachedPipelines {
+ /// Check if all pipelines for this effect are ready.
+ #[inline]
+ pub fn is_ready(&self) -> bool {
+ self.flags.contains(
+ CachedPipelineFlags::INIT_PIPELINE_READY | CachedPipelineFlags::UPDATE_PIPELINE_READY,
+ )
+ }
+}
+
+/// Ready state for this effect.
+///
+/// An effect is ready if:
+/// - Its init and update pipelines are ready, as reported by
+/// [`CachedPipelines::is_ready()`].
+///
+/// This components holds the calculated ready state propagated from all
+/// ancestor effects, if any. That propagation is done by the
+/// [`propagate_ready_state()`] system.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Component)]
+pub(crate) struct CachedReadyState {
+ is_ready: bool,
+}
+
+impl CachedReadyState {
+ #[inline(always)]
+ pub fn new(is_ready: bool) -> Self {
+ Self { is_ready }
+ }
+
+ #[inline(always)]
+ pub fn and(mut self, ancestors_ready: bool) -> Self {
+ self.and_with(ancestors_ready);
+ self
+ }
+
+ #[inline(always)]
+ pub fn and_with(&mut self, ancestors_ready: bool) {
+ self.is_ready = self.is_ready && ancestors_ready;
+ }
+
+ #[inline(always)]
+ pub fn is_ready(&self) -> bool {
+ self.is_ready
+ }
+}
+
+#[derive(SystemParam)]
+pub struct PrepareEffectsReadOnlyParams<'w, 's> {
+ sim_params: Res<'w, SimParams>,
+ marker: PhantomData<&'s usize>,
+}
+
+/// Update the ready state of all effects, and propagate recursively to
+/// children.
+pub(crate) fn propagate_ready_state(
+ mut q_root_effects: Query<
+ (
+ Entity,
+ Option<&ChildrenEffects>,
+ Ref<CachedPipelines>,
+ &mut CachedReadyState,
+ ),
+ Without<ChildEffectOf>,
+ >,
+ mut orphaned: RemovedComponents<ChildEffectOf>,
+ q_ready_state: Query<
+ (
+ Ref<CachedPipelines>,
+ &mut CachedReadyState,
+ Option<&ChildrenEffects>,
+ ),
+ With<ChildEffectOf>,
+ >,
+ q_child_effects: Query<(Entity, Ref<ChildEffectOf>), With<CachedReadyState>>,
+ mut orphaned_entities: Local<Vec<Entity>>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("propagate_ready_state").entered();
+ trace!("propagate_ready_state");
+
+ // Update orphaned list for this frame, and sort it so we can efficiently binary
+ // search it
+ orphaned_entities.clear();
+ orphaned_entities.extend(orphaned.read());
+ orphaned_entities.sort_unstable();
+
+ // Iterate in parallel over all root effects (those without any parent). This is
+ // the most common case, so should take care of the heavy lifting of propagating
+ // to most effects. For child effects, we then descend recursively.
+ q_root_effects.par_iter_mut().for_each(
+ |(entity, maybe_children, cached_pipelines, mut cached_ready_state)| {
+ // Update the ready state of this root effect
+ let changed = cached_pipelines.is_changed() || cached_ready_state.is_added() || orphaned_entities.binary_search(&entity).is_ok();
+ trace!("[Entity {}] changed={} cached_pipelines={} ready_state={}", entity, changed, cached_pipelines.is_ready(), cached_ready_state.is_ready);
+ if changed {
+ // Root effects by default are ready since they have no ancestors to check. After that we check the ready conditions for this effect alone.
+ let new_ready_state = CachedReadyState::new(cached_pipelines.is_ready());
+ if *cached_ready_state != new_ready_state {
+ debug!(
+ "[Entity {}] Changed ready to: {}",
+ entity,
+ new_ready_state.is_ready()
+ );
+ *cached_ready_state = new_ready_state;
+ }
+ }
+
+ // Recursively update the ready state of its descendants
+ if let Some(children) = maybe_children {
+ for (child, child_of) in q_child_effects.iter_many(children).flatten() {
+ assert_eq!(
+ child_of.parent, entity,
+ "Malformed hierarchy. This probably means that your hierarchy has been improperly maintained, or contains a cycle"
+ );
+ // SAFETY:
+ // - `child` must have consistent parentage, or the above assertion would panic.
+ // Since `child` is parented to a root entity, the entire hierarchy leading to it
+ // is consistent.
+ // - We may operate as if all descendants are consistent, since
+ // `propagate_ready_state_recursive` will panic before continuing to propagate if it
+ // encounters an entity with inconsistent parentage.
+ // - Since each root entity is unique and the hierarchy is consistent and
+ // forest-like, other root entities' `propagate_ready_state_recursive` calls will not conflict
+ // with this one.
+ // - Since this is the only place where `transform_query` gets used, there will be
+ // no conflicting fetches elsewhere.
+ #[expect(unsafe_code, reason = "`propagate_ready_state_recursive()` is unsafe due to its use of `Query::get_unchecked()`.")]
+ unsafe {
+ propagate_ready_state_recursive(
+ &cached_ready_state,
+ &q_ready_state,
+ &q_child_effects,
+ child,
+ changed || child_of.is_changed(),
+ );
+ }
+ }
+ }
+ },
+ );
+}
+
+#[expect(
+ unsafe_code,
+ reason = "This function uses `Query::get_unchecked()`, which can result in multiple mutable references if the preconditions are not met."
+)]
+unsafe fn propagate_ready_state_recursive(
+ parent_state: &CachedReadyState,
+ q_ready_state: &Query<
+ (
+ Ref<CachedPipelines>,
+ &mut CachedReadyState,
+ Option<&ChildrenEffects>,
+ ),
+ With<ChildEffectOf>,
+ >,
+ q_child_of: &Query<(Entity, Ref<ChildEffectOf>), With<CachedReadyState>>,
+ entity: Entity,
+ mut changed: bool,
+) {
+ // Update this effect in-place by checking its own state and the state of its
+ // parent (which has already been propagated from all the parent's ancestors, so
+ // is correct for this frame).
+ let (cached_ready_state, maybe_children) = {
+ let Ok((cached_pipelines, mut cached_ready_state, maybe_children)) =
+ // SAFETY: Copied from Bevy's transform propagation, same reasoning
+ (unsafe { q_ready_state.get_unchecked(entity) }) else {
+ return;
+ };
+
+ changed |= cached_pipelines.is_changed() || cached_ready_state.is_added();
+ if changed {
+ let new_ready_state =
+ CachedReadyState::new(parent_state.is_ready()).and(cached_pipelines.is_ready());
+ // Ensure we don't trigger ECS change detection here if state didn't change, so
+ // we can avoid this effect branch on next iteration.
+ if *cached_ready_state != new_ready_state {
+ debug!(
+ "[Entity {}] Changed ready to: {}",
+ entity,
+ new_ready_state.is_ready()
+ );
+ *cached_ready_state = new_ready_state;
+ }
+ }
+ (cached_ready_state, maybe_children)
+ };
+
+ // Recurse into descendants
+ let Some(children) = maybe_children else {
+ return;
+ };
+ for (child, child_of) in q_child_of.iter_many(children).flatten() {
+ assert_eq!(
+ child_of.parent, entity,
+ "Malformed hierarchy. This probably means that your hierarchy has been improperly maintained, or contains a cycle"
+ );
+ // SAFETY: The caller guarantees that `transform_query` will not be fetched for
+ // any descendants of `entity`, so it is safe to call
+ // `propagate_recursive` for each child.
+ //
+ // The above assertion ensures that each child has one and only one unique
+ // parent throughout the entire hierarchy.
+ unsafe {
+ propagate_ready_state_recursive(
+ cached_ready_state.as_ref(),
+ q_ready_state,
+ q_child_of,
+ child,
+ changed || child_of.is_changed(),
+ );
+ }
+ }
+}
+
+/// Once all effects are extracted and all cached components are updated, it's
+/// time to prepare for sorting and batching. Collect all relevant data and
+/// insert/update the [`BatchInput`] for each effect.
+pub(crate) fn prepare_batch_inputs(
+ render_device: Res<RenderDevice>,
+ mut commands: Commands,
+ read_only_params: PrepareEffectsReadOnlyParams,
+ pipeline_cache: Res<PipelineCache>,
+ mut effects_meta: ResMut<EffectsMeta>,
+ q_cached_effects: Query<(
+ MainEntity,
+ Entity,
+ &ExtractedEffect,
+ &ExtractedSpawner,
+ &CachedEffect,
+ &CachedEffectMetadata,
+ &CachedReadyState,
+ &CachedPipelines,
+ Option<&CachedDrawIndirectArgs>,
+ Option<&CachedParentInfo>,
+ Option<&ChildEffectOf>,
+ Option<&CachedChildInfo>,
+ Option<&CachedEffectEvents>,
+ )>,
+ mut sort_bind_groups: ResMut<SortBindGroups>,
+ q_render_camera: Query<&HanabiRenderCamera>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("prepare_batch_inputs").entered();
+ trace!("prepare_batch_inputs");
+
+ // Workaround for too many params in system (TODO: refactor to split work?)
+ let sim_params = read_only_params.sim_params.into_inner();
+
+ // Clear per-instance buffers, which are filled below and re-uploaded each frame
+ effects_meta.spawner_buffer.clear();
+ effects_meta.dispatch_indirect_args_buffer.clear();
+
+ // Build batcher inputs from extracted effects, updating all cached components
+ // for each effect on the fly.
+ let mut extracted_effect_count = 0;
+ let mut prepared_effect_count = 0;
+ for (
+ main_entity,
+ render_entity,
+ extracted_effect,
+ extracted_spawner,
+ cached_effect,
+ cached_effect_metadata,
+ cached_ready_state,
+ cached_pipelines,
+ maybe_cached_draw_indirect_args,
+ maybe_cached_parent_info,
+ maybe_child_effect_of,
+ maybe_cached_child_info,
+ maybe_cached_effect_events,
+ ) in &q_cached_effects
+ {
+ extracted_effect_count += 1;
+
+ // Skip this effect if not ready
+ if !cached_ready_state.is_ready() {
+ trace!("Pipelines not ready for effect {}, skipped.", render_entity);
+ continue;
+ }
+
+ // Skip this effect if not visible and not simulating when hidden
+ if !extracted_spawner.is_visible
+ && (extracted_effect.simulation_condition == SimulationCondition::WhenVisible)
+ {
+ trace!(
+ "Effect {} not visible, and simulation condition is WhenVisible, so skipped.",
+ render_entity
+ );
+ continue;
+ }
+
+ // Fetch the init and update pipelines.
+ // SAFETY: If is_ready() returns true, this means the pipelines are cached and
+ // ready, so the IDs must be valid.
+ let init_and_update_pipeline_ids = InitAndUpdatePipelineIds {
+ init: cached_pipelines.init.unwrap(),
+ update: cached_pipelines.update.unwrap(),
+ };
+
+ let effect_slice = EffectSlice {
+ slice: cached_effect.slice.range(),
+ slab_id: cached_effect.slab_id,
+ particle_layout: cached_effect.slice.particle_layout.clone(),
+ };
+
+ // Fetch the bind group layouts from the cache
+ trace!("child_effect_of={:?}", maybe_child_effect_of);
+ let parent_slab_id = if let Some(child_effect_of) = maybe_child_effect_of {
+ let Ok((_, _, _, _, parent_cached_effect, _, _, _, _, _, _, _, _)) =
+ q_cached_effects.get(child_effect_of.parent)
+ else {
+ // At this point we should have discarded invalid effects with a missing parent,
+ // so if the parent is not found this is a bug.
+ error!(
+ "Effect main_entity {:?}: parent render entity {:?} not found.",
+ main_entity, child_effect_of.parent
+ );
+ continue;
+ };
+ Some(parent_cached_effect.slab_id)
+ } else {
+ None
+ };
+
+ // For ribbons, we need the sorting pipeline to be ready to sort the ribbon's
+ // particles by age in order to build a contiguous mesh.
+ if extracted_effect.layout_flags.raea_sorted() { // raea: and blended effects (#52)
+ // Ensure the bind group layout for sort-fill is ready. This will also ensure
+ // the pipeline is created and queued if needed.
+ if let Err(err) = sort_bind_groups.ensure_sort_fill_bind_group_layout_desc(
+ &render_device,
+ &pipeline_cache,
+ &extracted_effect.particle_layout,
+ ) {
+ error!(
+ "Failed to create bind group for ribbon effect sorting: {:?}",
+ err
+ );
+ continue;
+ }
+
+ // Check sort pipelines are ready, otherwise we might desync some buffers if
+ // running only some of them but not all.
+ if !sort_bind_groups
+ .is_pipeline_ready(&extracted_effect.particle_layout, &pipeline_cache)
+ {
+ trace!(
+ "Sort pipeline not ready for effect on main entity {:?}; skipped.",
+ main_entity
+ );
+ continue;
+ }
+ }
+
+ // Output some debug info
+ trace!("init_shader = {:?}", extracted_effect.effect_shaders.init);
+ trace!(
+ "update_shader = {:?}",
+ extracted_effect.effect_shaders.update
+ );
+ trace!(
+ "render_shader = {:?}",
+ extracted_effect.effect_shaders.render
+ );
+ trace!("layout_flags = {:?}", extracted_effect.layout_flags);
+ trace!("particle_layout = {:?}", effect_slice.particle_layout);
+
+ let parent_slab_offset = maybe_cached_child_info.map(|cci| cci.parent_slab_offset);
+
+ assert!(cached_effect_metadata.table_id.is_valid());
+ let gpu_spawner_params = GpuSpawnerParams::new(
+ &extracted_spawner.transform,
+ extracted_spawner.spawn_count,
+ extracted_spawner.prng_seed,
+ cached_effect.slice.range().start,
+ parent_slab_offset,
+ cached_effect_metadata.table_id,
+ maybe_cached_draw_indirect_args,
+ );
+
+ trace!("Updating cached effect at entity {render_entity:?}...");
+ let mut cmd = commands.entity(render_entity);
+ // Inserting the BatchInput component marks the effect as ready for this frame
+ cmd.insert(BatchInput {
+ effect_slice,
+ init_and_update_pipeline_ids,
+ parent_slab_id,
+ event_buffer_index: maybe_cached_effect_events.map(|cee| cee.buffer_index),
+ child_effects: maybe_cached_parent_info
+ .as_ref()
+ .map(|cp| cp.children.clone())
+ .unwrap_or_default(),
+ gpu_spawner_params,
+ init_indirect_dispatch_index: maybe_cached_child_info
+ .as_ref()
+ .map(|cc| cc.init_indirect_dispatch_index),
+ });
+
+ prepared_effect_count += 1;
+ }
+ trace!("Prepared {prepared_effect_count}/{extracted_effect_count} extracted effect(s)");
+
+ // Update simulation parameters, including the total effect count for this frame
+ {
+ let dummy = HanabiRenderCamera {
+ view: Entity::PLACEHOLDER.into(),
+ frustum: default(),
+ position: default(),
+ };
+ let render_camera = q_render_camera.single().unwrap_or(&dummy);
+
+ let mut gpu_sim_params: GpuSimParams = sim_params.into();
+ gpu_sim_params.frustum = render_camera.frustum;
+ gpu_sim_params.camera_position = render_camera.position.extend(0.0);
+ gpu_sim_params.num_effects = prepared_effect_count;
+ trace!(
+ "Simulation parameters: time={} delta_time={} virtual_time={} \
+ virtual_delta_time={} real_time={} real_delta_time={} num_effects={}",
+ gpu_sim_params.time,
+ gpu_sim_params.delta_time,
+ gpu_sim_params.virtual_time,
+ gpu_sim_params.virtual_delta_time,
+ gpu_sim_params.real_time,
+ gpu_sim_params.real_delta_time,
+ gpu_sim_params.num_effects,
+ );
+ effects_meta.sim_params_uniforms.set(gpu_sim_params);
+ }
+}
+
+/// Batch compatible effects together into a single pass.
+///
+/// For all effects marked as ready for this frame (have a BatchInput
+/// component), sort the effects by grouping compatible effects together, then
+/// batch those groups together. Each batch can be updated and rendered with a
+/// single compute dispatch or draw call.
+pub(crate) fn batch_effects(
+ render_device: Res<RenderDevice>,
+ render_queue: Res<RenderQueue>,
+ mut commands: Commands,
+ mut effects_meta: ResMut<EffectsMeta>,
+ mut sort_bind_groups: ResMut<SortBindGroups>,
+ mut q_cached_effects: Query<(
+ Entity,
+ &MainEntity,
+ &ExtractedEffect,
+ &ExtractedSpawner,
+ &ExtractedEffectMesh,
+ &CachedDrawIndirectArgs,
+ &CachedEffectMetadata,
+ Option<&CachedEffectEvents>,
+ Option<&ChildEffectOf>,
+ Option<&CachedChildInfo>,
+ Option<&CachedEffectProperties>,
+ // The presence of BatchInput ensure the effect is ready
+ &mut BatchInput,
+ )>,
+ mut batcher: ResMut<Batcher>,
+ mut gpu_buffer_operations: ResMut<GpuBufferOperations>,
+ mut effect_bind_groups: ResMut<EffectBindGroups>,
+ mut property_bind_groups: ResMut<PropertyBindGroups>,
+ mut sort_fill_dispatch_queue: ResMut<SortFillDispatchQueue>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("batch_effects").entered();
+ trace!("batch_effects");
+
+ // Sort effects in batching order, so that we can batch by simply doing a linear
+ // scan of the effects in this order. Currently compatible effects mean:
+ // - same effect slab (so we can bind the buffers once for all batched effects)
+ // - in order of increasing sub-allocation inside those buffers (to make the
+ // sort stable)
+ // - with parents before their children, to ensure ???? FIXME don't we need to
+ // opposite?!!!
+ let mut effect_sorter = EffectSorter::new();
+ for (entity, _, _, _, _, _, _, _, child_of, _, _, input) in &q_cached_effects {
+ effect_sorter.insert(
+ entity,
+ input.effect_slice.slab_id,
+ input.effect_slice.slice.start,
+ child_of.map(|co| co.parent),
+ );
+ }
+ effect_sorter.sort();
+
+ // For now we re-create that buffer each frame. Since there's no CPU -> GPU
+ // transfer, this is pretty cheap in practice.
+ sort_bind_groups.clear_indirect_args_buffer();
+
+ // Loop on all extracted effects in sorted order, and batch compatible
+ // effects together.
+ trace!("Batching {} effects...", q_cached_effects.iter().len());
+ batcher.clear();
+ for entity in effect_sorter.iter() {
+ let Ok((
+ entity,
+ main_entity,
+ extracted_effect,
+ extracted_spawner,
+ extracted_effect_mesh,
+ cached_draw_indirect_args,
+ cached_effect_metadata,
+ cached_effect_events,
+ _,
+ cached_child_info,
+ cached_properties,
+ mut input,
+ )) = q_cached_effects.get_mut(entity)
+ else {
+ continue;
+ };
+
+ let translation = extracted_spawner.transform.translation();
+ let instance_spawn_count = if input.event_buffer_index.is_some() {
+ // GPU spawn based effects are not currently batched.
+ 0
+ } else {
+ extracted_spawner.spawn_count
+ };
+
+ // Now that the effects are sorted in batching order, we can allocate the
+ // GpuSpawnerParams in the GPU buffer, such that they're contiguous for a single
+ // batch.
+ let spawner_index = effects_meta.allocate_spawner(input.gpu_spawner_params);
+
+ let texture_layout = extracted_effect.texture_layout.clone();
+ let property_key = if let Some(cp) = cached_properties.as_ref() {
+ PropertyBindGroupKey::new(cp, texture_layout)
+ } else {
+ PropertyBindGroupKey::texture_only(texture_layout)
+ };
+
+ // Create a single-effect batch candidate. It can be merged with the previous
+ // batch if fully compatible.
+ let mut effect_batch = EffectBatch::from_input(
+ main_entity.id(),
+ extracted_effect,
+ extracted_spawner,
+ extracted_effect_mesh,
+ cached_effect_events,
+ cached_child_info,
+ spawner_index,
+ &mut input,
+ cached_draw_indirect_args.row,
+ cached_effect_metadata.table_id,
+ property_key,
+ );
+
+ // If the batch has ribbons, we need to sort the particles by RIBBON_ID and AGE
+ // for ribbon meshing, in order to avoid gaps when some particles in the middle
+ // of the ribbon die (since we can't guarantee a linear lifetime through the
+ // ribbon).
+ let sort_indirect_dispatch_indices =
+ if extracted_effect.layout_flags.raea_sorted() { // raea: and blended effects (#52)
+ // Allocate a GpuDispatchIndirect entry
+ let sort_fill_indirect_dispatch_index = sort_bind_groups.allocate_indirect_args();
+ effect_batch.effect_data[0].sort_fill_indirect_dispatch_index =
+ Some(sort_fill_indirect_dispatch_index);
+
+ let sort_indirect_dispatch_index = sort_bind_groups.allocate_indirect_args();
+ effect_batch.effect_data[0].sort_indirect_dispatch_index =
+ Some(sort_indirect_dispatch_index);
+
+ // Ensure sort merge passes are allocated, if needed
+ sort_bind_groups.ensure_mergesort_passes(extracted_effect.capacity);
+
+ Some((
+ sort_fill_indirect_dispatch_index,
+ sort_indirect_dispatch_index,
+ ))
+ } else {
+ None
+ };
+
+ // Append to sorted compute batches; this may merge with the previous one.
+ let (new_effect_batch_index, sort_prefix_sum_index) =
+ batcher.push(effect_batch, instance_spawn_count);
+ if let Some(new_effect_batch_index) = new_effect_batch_index {
+ trace!(
+ "Spawned new effect batch #{:?} from cached instance on entity {:?}.",
+ new_effect_batch_index,
+ entity,
+ );
+
+ // Spawn an EffectDrawBatch to drive rendering for that batch. Note that
+ // technically nothing imposes we use the same batching for compute init/update
+ // and for rendering, so we could (and probably should) re-batch specifically
+ // for rendering. For now we just use the same batches.
+ commands
+ .spawn(EffectDrawBatch {
+ effect_batch_index: new_effect_batch_index,
+ translation,
+ main_entity: *main_entity,
+ })
+ .insert(TemporaryRenderEntity::default());
+ }
+ if let Some((sort_fill_indirect_dispatch_index, sort_indirect_dispatch_index)) =
+ sort_indirect_dispatch_indices
+ {
+ sort_fill_dispatch_queue.enqueue(
+ cached_effect_metadata.table_id,
+ sort_prefix_sum_index,
+ sort_fill_indirect_dispatch_index,
+ sort_indirect_dispatch_index,
+ );
+ }
+
+ // Ensure first_instance remains zero (required without INDIRECT_FIRST_INSTANCE
+ // support).
+ let mut draw_args = cached_draw_indirect_args.args;
+ match &mut draw_args {
+ AnyDrawIndirectArgs::NonIndexed(args) => args.first_instance = 0,
+ AnyDrawIndirectArgs::Indexed(args) => args.first_instance = 0,
+ }
+
+ effects_meta.draw_indirect_args_buffer.update(
+ cached_draw_indirect_args.row,
+ draw_args.bitcast_to_row_entry(),
+ );
+ }
+
+ batcher.try_end_batch();
+
+ // Allocate dispatch indirect args entries for all batches, so that we can
+ // dispatch the update pass. They are indexed by the same batch info index, so
+ // much map 1:1 with the GpuBatchInfo indices.
+ if !batcher.is_empty() {
+ let di_base = effects_meta
+ .dispatch_indirect_args_buffer
+ .allocate_slice(batcher.len() as u32);
+ // We cleared the Batcher and just enqueued the first batches
+ assert_eq!(di_base, 0);
+ }
+
+ // Once all batching for init/update is one, allocate the render "batches"
+ // (currently no batching; this allocates one entry per effect instance).
+ batcher.allocate_render_batches();
+
+ // Begin the GpuBufferOperations frame here; the matching submit()s happen in
+ // queue_sort_fill_dispatch_ops() and queue_init_fill_dispatch_ops(), and
+ // end_frame() at the tail of the latter. Render set ordering guarantees
+ // this begin precedes all submits.
+ gpu_buffer_operations.begin_frame();
+ debug_assert!(batcher.fill_dispatch_queue_index.is_none());
+ debug_assert!(batcher.sort_dispatch_queue_index.is_none());
+
+ // Write the entire spawner buffer for this frame, for all effects combined
+ if effects_meta
+ .spawner_buffer
+ .write_buffer(&render_device, &render_queue)
+ {
+ // Buffer was reallocated; clear all bind groups referencing the old buffer
+ effect_bind_groups.particle_slabs.clear();
+ property_bind_groups.clear();
+ effects_meta.indirect_spawner_bind_group = None;
+ }
+
+ // Write the entire batch info buffer for this frame, for all batches combined
+ if batcher.write_batch_info_buffer(&render_device, &render_queue) {
+ // Buffer was reallocated; clear all bind groups referencing the old buffer
+ effect_bind_groups.particle_slabs.clear();
+ property_bind_groups.clear();
+ effects_meta.indirect_spawner_bind_group = None;
+ effects_meta.prefix_sum_bind_group = None;
+ }
+
+ // Write the entire prefix sum buffer for this frame, for all batches combined
+ if batcher.write_prefix_sum_buffer(&render_device, &render_queue) {
+ // Buffer was reallocated; clear all bind groups referencing the old buffer
+ effect_bind_groups.particle_slabs.clear();
+ property_bind_groups.clear();
+ effects_meta.indirect_spawner_bind_group = None;
+ effects_meta.prefix_sum_bind_group = None;
+ }
+
+ let _ = sort_bind_groups.write_merge_params(&render_device, &render_queue);
+}
+
+/// Per-buffer bind groups for a GPU effect buffer.
+///
+/// This contains all bind groups specific to a single [`EffectBuffer`].
+///
+/// [`EffectBuffer`]: crate::render::effect_cache::EffectBuffer
+pub(crate) struct BufferBindGroups {
+ /// Bind group for the render shader.
+ ///
+ /// ```wgsl
+ /// @binding(0) var<storage, read> particle_buffer : ParticleBuffer;
+ /// @binding(1) var<storage, read> indirect_buffer : IndirectBuffer;
+ /// ```
+ render: BindGroup,
+ // /// Bind group for filling the indirect dispatch arguments of any child init
+ // /// pass.
+ // ///
+ // /// This bind group is optional; it's only created if the current effect has
+ // /// a GPU spawn event buffer, irrelevant of whether it has child effects
+ // /// (although normally the event buffer is not created if there's no
+ // /// children).
+ // ///
+ // /// The source buffer is always the current effect's event buffer. The
+ // /// destination buffer is the global shared buffer for indirect fill args
+ // /// operations owned by the [`EffectCache`]. The uniform buffer of operation
+ // /// args contains the data to index the relevant part of the global shared
+ // /// buffer for this effect buffer; it may contain multiple entries in case
+ // /// multiple effects are batched inside the current effect buffer.
+ // ///
+ // /// ```wgsl
+ // /// @group(0) @binding(0) var<uniform> args : BufferOperationArgs;
+ // /// @group(0) @binding(1) var<storage, read> src_buffer : array<u32>;
+ // /// @group(0) @binding(2) var<storage, read_write> dst_buffer : array<u32>;
+ // /// ```
+ // init_fill_dispatch: Option<BindGroup>,
+}
+
+/// Combination of a texture layout and the bound textures.
+#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
+struct Material {
+ layout: TextureLayout,
+ textures: Vec<AssetId<Image>>,
+}
+
+impl Material {
+ /// Get the bind group entries to create a bind group.
+ pub fn append_binding_entries<'a, 'b>(
+ &'b self,
+ binding_start: u32,
+ gpu_images: &'a RenderAssets<GpuImage>,
+ entries: &'b mut Vec<BindGroupEntry<'a>>,
+ ) -> bool {
+ if self.layout.layout.len() != self.textures.len() {
+ return false;
+ }
+
+ if self.textures.is_empty() {
+ return true;
+ }
+
+ let mut index = binding_start;
+ for (slot, asset_id) in self.layout.layout.iter().zip(self.textures.iter()) {
+ let Some(gpu_image) = gpu_images.get(*asset_id) else {
+ return false;
+ };
+ if gpu_image.texture_descriptor.sample_count > 1 {
+ return false;
+ }
+ if !slot.accepts(
+ gpu_image.texture_descriptor.dimension,
+ gpu_image.texture_descriptor.array_layer_count(),
+ gpu_image
+ .texture_descriptor
+ .format
+ .is_depth_stencil_format(),
+ ) {
+ return false;
+ }
+ entries.push(BindGroupEntry {
+ binding: index,
+ resource: BindingResource::TextureView(&gpu_image.texture_view),
+ });
+ entries.push(BindGroupEntry {
+ binding: index + 1,
+ resource: BindingResource::Sampler(&gpu_image.sampler),
+ });
+ index += 2;
+ }
+ true
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+struct BindingKey {
+ pub buffer_id: BufferId,
+ pub offset: u32,
+ pub size: NonZeroU32,
+}
+
+impl<'a> From<BufferSlice<'a>> for BindingKey {
+ fn from(value: BufferSlice<'a>) -> Self {
+ Self {
+ buffer_id: value.buffer.id(),
+ offset: value.offset,
+ size: value.size,
+ }
+ }
+}
+
+impl<'a> From<&BufferSlice<'a>> for BindingKey {
+ fn from(value: &BufferSlice<'a>) -> Self {
+ Self {
+ buffer_id: value.buffer.id(),
+ offset: value.offset,
+ size: value.size,
+ }
+ }
+}
+
+impl From<&BufferBindingSource> for BindingKey {
+ fn from(value: &BufferBindingSource) -> Self {
+ Self {
+ buffer_id: value.buffer.id(),
+ offset: value.offset,
+ size: value.size,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+struct ConsumeEventKey {
+ child_infos_buffer_id: BufferId,
+ events: BindingKey,
+}
+
+impl From<&ConsumeEventBuffers<'_>> for ConsumeEventKey {
+ fn from(value: &ConsumeEventBuffers) -> Self {
+ Self {
+ child_infos_buffer_id: value.child_infos_buffer.id(),
+ events: value.events.into(),
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+struct InitMetadataBindGroupKey {
+ pub slab_id: SlabId,
+ pub effect_metadata_buffer: BufferId,
+ pub consume_event_key: Option<ConsumeEventKey>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+struct UpdateMetadataBindGroupKey {
+ pub slab_id: SlabId,
+ pub effect_metadata_buffer: BufferId,
+ pub child_info_buffer_id: Option<BufferId>,
+ pub event_buffers_keys: Vec<BindingKey>,
+}
+
+/// Bind group cached with an associated key.
+///
+/// The cached bind group is associated with the given key representing the
+/// inputs that the bind group depends on. When those inputs change, the key
+/// should change, indicating the bind group needs to be recreated.
+///
+/// This object manages a single bind group and its key.
+struct CachedBindGroup<K: Eq> {
+ /// Key the bind group was created from. Each time the key changes, the bind
+ /// group should be re-created.
+ key: K,
+ /// Bind group created from the key.
+ bind_group: BindGroup,
+}
+
+#[derive(Debug, Clone, Copy)]
+struct BufferSlice<'a> {
+ pub buffer: &'a Buffer,
+ pub offset: u32,
+ pub size: NonZeroU32,
+}
+
+impl<'a> From<BufferSlice<'a>> for BufferBinding<'a> {
+ fn from(value: BufferSlice<'a>) -> Self {
+ Self {
+ buffer: value.buffer,
+ offset: value.offset.into(),
+ size: Some(value.size.into()),
+ }
+ }
+}
+
+impl<'a> From<&BufferSlice<'a>> for BufferBinding<'a> {
+ fn from(value: &BufferSlice<'a>) -> Self {
+ Self {
+ buffer: value.buffer,
+ offset: value.offset.into(),
+ size: Some(value.size.into()),
+ }
+ }
+}
+
+impl<'a> From<&'a BufferBindingSource> for BufferSlice<'a> {
+ fn from(value: &'a BufferBindingSource) -> Self {
+ Self {
+ buffer: &value.buffer,
+ offset: value.offset,
+ size: value.size,
+ }
+ }
+}
+
+/// Optional input to [`EffectBindGroups::get_or_create_init_metadata()`] when
+/// the init pass consumes GPU events as a mechanism to spawn particles.
+struct ConsumeEventBuffers<'a> {
+ /// Entire buffer containing the [`GpuChildInfo`] entries for all effects.
+ /// This is dynamically indexed inside the shader.
+ child_infos_buffer: &'a Buffer,
+ /// Slice of the [`EventBuffer`] where the GPU spawn events are stored.
+ events: BufferSlice<'a>,
+}
+
+#[derive(Default, Resource)]
+pub struct EffectBindGroups {
+ /// Map from a slab ID to the bind groups shared among all effects that
+ /// use that particle slab.
+ particle_slabs: HashMap<SlabId, BufferBindGroups>,
+ /// Map of bind groups for image assets used as particle textures.
+ images: HashMap<AssetId<Image>, BindGroup>,
+ /// Map from buffer index to its metadata bind group (group 3) for the init
+ /// pass.
+ // FIXME - doesn't work with batching; this should be the instance ID
+ init_metadata_bind_groups: HashMap<SlabId, CachedBindGroup<InitMetadataBindGroupKey>>,
+ /// Map from buffer index to its metadata bind group (group 3) for the
+ /// update pass.
+ // FIXME - doesn't work with batching; this should be the instance ID
+ update_metadata_bind_groups: HashMap<SlabId, CachedBindGroup<UpdateMetadataBindGroupKey>>,
+}
+
+impl EffectBindGroups {
+ pub fn particle_render(&self, slab_id: &SlabId) -> Option<&BindGroup> {
+ self.particle_slabs.get(slab_id).map(|bg| &bg.render)
+ }
+
+ /// Retrieve the metadata@3 bind group for the init pass, creating it if
+ /// needed.
+ pub(self) fn get_or_create_init_metadata(
+ &mut self,
+ effect_batch: &EffectBatch,
+ render_device: &RenderDevice,
+ layout: &BindGroupLayout,
+ effect_metadata_buffer: &Buffer,
+ consume_event_buffers: Option<ConsumeEventBuffers>,
+ ) -> Result<&BindGroup, ()> {
+ assert!(!effect_batch.effect_data.is_empty());
+ assert!(effect_batch.effect_data[0].metadata_table_id.is_valid());
+
+ let key = InitMetadataBindGroupKey {
+ slab_id: effect_batch.slab_id,
+ effect_metadata_buffer: effect_metadata_buffer.id(),
+ consume_event_key: consume_event_buffers.as_ref().map(Into::into),
+ };
+
+ let make_entry = || {
+ let mut entries = Vec::with_capacity(3);
+ entries.push(
+ // @group(3) @binding(0) var<storage, read_write> effect_metadatas :
+ // array<EffectMetadata>;
+ BindGroupEntry {
+ binding: 0,
+ resource: effect_metadata_buffer.as_entire_binding(),
+ },
+ );
+ if let Some(consume_event_buffers) = consume_event_buffers.as_ref() {
+ entries.push(
+ // @group(3) @binding(1) var<storage, read> child_info_buffer :
+ // ChildInfoBuffer;
+ BindGroupEntry {
+ binding: 1,
+ resource: BindingResource::Buffer(BufferBinding {
+ buffer: consume_event_buffers.child_infos_buffer,
+ offset: 0,
+ size: None,
+ }),
+ },
+ );
+ entries.push(
+ // @group(3) @binding(2) var<storage, read> event_buffer : EventBuffer;
+ BindGroupEntry {
+ binding: 2,
+ resource: BindingResource::Buffer(consume_event_buffers.events.into()),
+ },
+ );
+ }
+
+ let bind_group =
+ render_device.create_bind_group("hanabi:bg:init:metadata@3", layout, &entries[..]);
+
+ trace!(
+ "Created new metadata@3 bind group for init pass and buffer index {}: effect_metadata=#{}",
+ effect_batch.slab_id.index(),
+ effect_batch.effect_data[0].metadata_table_id.0,
+ );
+
+ bind_group
+ };
+
+ Ok(&self
+ .init_metadata_bind_groups
+ .entry(effect_batch.slab_id)
+ .and_modify(|cbg| {
+ if cbg.key != key {
+ trace!(
+ "Bind group key changed for init metadata@3, re-creating bind group... old={:?} new={:?}",
+ cbg.key,
+ key
+ );
+ cbg.key = key;
+ cbg.bind_group = make_entry();
+ }
+ })
+ .or_insert_with(|| {
+ trace!("Inserting new bind group for init metadata@3 with key={:?}", key);
+ CachedBindGroup {
+ key,
+ bind_group: make_entry(),
+ }
+ })
+ .bind_group)
+ }
+
+ /// Retrieve the metadata@3 bind group for the update pass, creating it if
+ /// needed.
+ pub(self) fn get_or_create_update_metadata(
+ &mut self,
+ effect_batch: &EffectBatch,
+ render_device: &RenderDevice,
+ layout: &BindGroupLayout,
+ effect_metadata_buffer: &Buffer,
+ child_info_buffer: Option<&Buffer>,
+ event_buffers: &[(Entity, BufferBindingSource)],
+ ) -> Result<&BindGroup, ()> {
+ assert!(!effect_batch.effect_data.is_empty());
+ assert!(effect_batch.effect_data[0].metadata_table_id.is_valid());
+
+ // Check arguments consistency
+ assert_eq!(effect_batch.child_event_buffers.len(), event_buffers.len());
+ let emits_gpu_spawn_events = !event_buffers.is_empty();
+ let child_info_buffer_id = if emits_gpu_spawn_events {
+ child_info_buffer.as_ref().map(|buffer| buffer.id())
+ } else {
+ // Note: child_info_buffer can be Some() if allocated, but we only consider it
+ // if relevant, that is if the effect emits GPU spawn events.
+ None
+ };
+ assert_eq!(emits_gpu_spawn_events, child_info_buffer_id.is_some());
+
+ let event_buffers_keys = event_buffers
+ .iter()
+ .map(|(_, buffer_binding_source)| buffer_binding_source.into())
+ .collect::<Vec<_>>();
+
+ let key = UpdateMetadataBindGroupKey {
+ slab_id: effect_batch.slab_id,
+ effect_metadata_buffer: effect_metadata_buffer.id(),
+ child_info_buffer_id,
+ event_buffers_keys,
+ };
+
+ let make_entry = || {
+ let mut entries = Vec::with_capacity(2 + event_buffers.len());
+ // @group(3) @binding(0) var<storage, read_write> effect_metadatas :
+ // array<EffectMetadata>;
+ entries.push(BindGroupEntry {
+ binding: 0,
+ resource: effect_metadata_buffer.as_entire_binding(),
+ });
+ if emits_gpu_spawn_events {
+ let child_info_buffer = child_info_buffer.unwrap();
+
+ // @group(3) @binding(1) var<storage, read_write> child_info_buffer :
+ // ChildInfoBuffer;
+ entries.push(BindGroupEntry {
+ binding: 1,
+ resource: BindingResource::Buffer(BufferBinding {
+ buffer: child_info_buffer,
+ offset: 0,
+ size: None,
+ }),
+ });
+
+ for (index, (_, buffer_binding_source)) in event_buffers.iter().enumerate() {
+ // @group(3) @binding(2+N) var<storage, read_write> event_buffer_N :
+ // EventBuffer;
+ // FIXME - BufferBindingSource originally was for Events, counting in u32, but
+ // then moved to counting in bytes, so now need some conversion. Need to review
+ // all of this...
+ let mut buffer_binding: BufferBinding = buffer_binding_source.into();
+ buffer_binding.offset *= 4;
+ buffer_binding.size = buffer_binding
+ .size
+ .map(|sz| NonZeroU64::new(sz.get() * 4).unwrap());
+ entries.push(BindGroupEntry {
+ binding: 2 + index as u32,
+ resource: BindingResource::Buffer(buffer_binding),
+ });
+ }
+ }
+
+ let bind_group = render_device.create_bind_group(
+ "hanabi:bg:update:metadata@3",
+ layout,
+ &entries[..],
+ );
+
+ trace!(
+ "Created new metadata@3 bind group for update pass and slab ID {}",
+ effect_batch.slab_id.index(),
+ );
+
+ bind_group
+ };
+
+ Ok(&self
+ .update_metadata_bind_groups
+ .entry(effect_batch.slab_id)
+ .and_modify(|cbg| {
+ if cbg.key != key {
+ trace!(
+ "Bind group key changed for update metadata@3, re-creating bind group... old={:?} new={:?}",
+ cbg.key,
+ key
+ );
+ cbg.key = key.clone();
+ cbg.bind_group = make_entry();
+ }
+ })
+ .or_insert_with(|| {
+ trace!(
+ "Inserting new bind group for update metadata@3 with key={:?}",
+ key
+ );
+ CachedBindGroup {
+ key: key.clone(),
+ bind_group: make_entry(),
+ }
+ })
+ .bind_group)
+ }
+}
+
+#[derive(SystemParam)]
+pub struct QueueEffectsReadOnlyParams<'w, 's> {
+ effects_meta: Res<'w, EffectsMeta>,
+ property_cache: Res<'w, PropertyCache>,
+ pipeline_cache: Res<'w, PipelineCache>,
+ #[cfg(feature = "2d")]
+ draw_functions_2d: Res<'w, DrawFunctions<Transparent2d>>,
+ #[cfg(feature = "3d")]
+ draw_functions_3d: Res<'w, DrawFunctions<Transparent3d>>,
+ #[cfg(feature = "3d")]
+ draw_functions_alpha_mask: Res<'w, DrawFunctions<AlphaMask3d>>,
+ #[cfg(feature = "3d")]
+ draw_functions_opaque: Res<'w, DrawFunctions<Opaque3d>>,
+ marker: PhantomData<&'s usize>,
+}
+
+fn emit_sorted_draw<T, F>(
+ views: &Query<(&RenderVisibleEntities, &ExtractedView, &Msaa)>,
+ render_phases: &mut ResMut<ViewSortedRenderPhases<T>>,
+ view_entities: &mut FixedBitSet,
+ batcher: &Batcher,
+ effect_draw_batches: &Query<(Entity, &mut EffectDrawBatch)>,
+ render_pipeline: &mut ParticlesRenderPipeline,
+ mut specialized_render_pipelines: Mut<SpecializedRenderPipelines<ParticlesRenderPipeline>>,
+ property_cache: &PropertyCache,
+ render_meshes: &RenderAssets<RenderMesh>,
+ pipeline_cache: &PipelineCache,
+ make_phase_item: F,
+ #[cfg(all(feature = "2d", feature = "3d"))] pipeline_mode: PipelineMode,
+) where
+ T: SortedPhaseItem,
+ F: Fn(CachedRenderPipelineId, (Entity, MainEntity), &EffectDrawBatch, &ExtractedView) -> T,
+{
+ trace!("emit_sorted_draw() {} views", views.iter().len());
+
+ for (visible_entities, view, msaa) in views.iter() {
+ let Some(visible_effect_entities) = visible_entities.get::<EffectVisibilityClass>() else {
+ continue;
+ };
+ trace!(
+ "Process new sorted view with {} visible particle effect entities",
+ visible_effect_entities.iter_visible().count()
+ );
+
+ let Some(render_phase) = render_phases.get_mut(&view.retained_view_entity) else {
+ continue;
+ };
+
+ {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("collect_view_entities").entered();
+
+ view_entities.clear();
+ view_entities.extend(
+ visible_effect_entities
+ .iter_visible()
+ .map(|(_, main_entity)| main_entity.index_u32() as usize),
+ );
+ }
+
+ // For each view, loop over all the effect batches to determine if the effect
+ // needs to be rendered for that view, and enqueue a view-dependent
+ // batch if so.
+ for (draw_entity, draw_batch) in effect_draw_batches.iter() {
+ #[cfg(feature = "trace")]
+ let _span_draw = bevy::log::info_span!("draw_batch").entered();
+
+ trace!(
+ "Process draw batch: draw_entity={:?} effect_batch_index={:?}",
+ draw_entity,
+ draw_batch.effect_batch_index,
+ );
+
+ // Get the EffectBatches this EffectDrawBatch is part of.
+ let Some(effect_batch) = batcher.get(draw_batch.effect_batch_index) else {
+ continue;
+ };
+
+ trace!(
+ "-> EffectBach: slab_id={} spawner_base={} layout_flags={:?}",
+ effect_batch.slab_id.index(),
+ effect_batch.spawner_base,
+ effect_batch.layout_flags,
+ );
+
+ // AlphaMask is a binned draw, so no sorted draw can possibly use it
+ if effect_batch
+ .layout_flags
+ .intersects(LayoutFlags::USE_ALPHA_MASK | LayoutFlags::OPAQUE)
+ {
+ trace!("Non-transparent batch. Skipped.");
+ continue;
+ }
+
+ // Check if batch contains any entity visible in the current view. Otherwise we
+ // can skip the entire batch. Note: This is O(n^2) but (unlike
+ // the Sprite renderer this is inspired from) we don't expect more than
+ // a handful of particle effect instances, so would rather not pay the memory
+ // cost of a FixedBitSet for the sake of an arguable speed-up.
+ // TODO - Profile to confirm.
+ #[cfg(feature = "trace")]
+ let _span_check_vis = bevy::log::info_span!("check_visibility").entered();
+ let has_visible_entity = effect_batch
+ .effect_data
+ .iter()
+ .any(|effect_data| view_entities.contains(effect_data.entity as usize));
+ if !has_visible_entity {
+ trace!("No visible entity for view, not emitting any draw call.");
+ continue;
+ }
+ #[cfg(feature = "trace")]
+ _span_check_vis.exit();
+
+ // FIXME - We draw the entire batch, but part of it may not be visible in this
+ // view! We should re-batch for the current view specifically!
+
+ let local_space_simulation = effect_batch
+ .layout_flags
+ .contains(LayoutFlags::LOCAL_SPACE_SIMULATION);
+ let alpha_mask = ParticleRenderAlphaMaskPipelineKey::from(effect_batch.layout_flags);
+ let flipbook = effect_batch.layout_flags.contains(LayoutFlags::FLIPBOOK);
+ let needs_uv = effect_batch.layout_flags.contains(LayoutFlags::NEEDS_UV);
+ let needs_normal = effect_batch
+ .layout_flags
+ .contains(LayoutFlags::NEEDS_NORMAL);
+ let needs_particle_fragment = effect_batch
+ .layout_flags
+ .contains(LayoutFlags::NEEDS_PARTICLE_FRAGMENT);
+ let ribbons = effect_batch.layout_flags.contains(LayoutFlags::RIBBONS);
+ let image_count = effect_batch.texture_layout.layout.len() as u8;
+
+ // FIXME - Maybe it's better to copy the mesh layout into the batch, instead of
+ // re-querying here...?
+ let Some(render_mesh) = render_meshes.get(effect_batch.mesh) else {
+ trace!("Batch has no render mesh, skipped.");
+ continue;
+ };
+ let mesh_layout = render_mesh.layout.clone();
+
+ // Specialize the render pipeline based on the effect batch
+ trace!(
+ "Specializing render pipeline: render_shader={:?} image_count={} alpha_mask={:?} flipbook={:?} target_format={:?}",
+ effect_batch.render_shader,
+ image_count,
+ alpha_mask,
+ flipbook,
+ view.target_format
+ );
+
+ // Add a draw pass for the effect batch
+ trace!("Emitting individual draw for batch");
+
+ let alpha_mode = effect_batch.alpha_mode;
+
+ // This should always exist by the time we reach this point, because we should
+ // have inserted any property in the cache, which would have allocated the
+ // proper bind group layout (or the default no-property one).
+ let has_multi_draw = false; // TODO?
+ let property_layout_min_binding_size =
+ NonZeroU64::new(effect_batch.property_key.binding_size as u64);
+ let spawner_bind_group_layout_desc = property_cache
+ .bind_group_layout_desc(
+ property_layout_min_binding_size,
+ has_multi_draw,
+ &effect_batch.texture_layout,
+ )
+ .unwrap_or_else(|| {
+ panic!(
+ "Failed to find spawner@2 bind group layout for property binding size {:?}",
+ property_layout_min_binding_size,
+ )
+ });
+
+ #[cfg(feature = "trace")]
+ let _span_specialize = bevy::log::info_span!("specialize").entered();
+ let render_pipeline_id = specialized_render_pipelines.specialize(
+ pipeline_cache,
+ render_pipeline,
+ ParticleRenderPipelineKey {
+ shader: effect_batch.render_shader.clone(),
+ mesh_layout: Some(mesh_layout),
+ particle_layout: effect_batch.particle_layout.clone(),
+ texture_layout: effect_batch.texture_layout.clone(),
+ local_space_simulation,
+ alpha_mask,
+ alpha_mode,
+ flipbook,
+ needs_uv,
+ needs_normal,
+ needs_particle_fragment,
+ ribbons,
+ #[cfg(all(feature = "2d", feature = "3d"))]
+ pipeline_mode,
+ msaa_samples: msaa.samples(),
+ target_format: view.target_format,
+ spawner_bind_group_layout_desc: spawner_bind_group_layout_desc.clone(),
+ },
+ );
+ #[cfg(feature = "trace")]
+ _span_specialize.exit();
+
+ trace!("+ Render pipeline specialized: id={:?}", render_pipeline_id,);
+ trace!(
+ "+ Add Transparent for batch on draw_entity {:?}: slab_id={} \
+ spawner_base={} handle={:?}",
+ draw_entity,
+ effect_batch.slab_id.index(),
+ effect_batch.spawner_base,
+ effect_batch.handle
+ );
+ render_phase.add_transient(make_phase_item(
+ render_pipeline_id,
+ (draw_entity, draw_batch.main_entity),
+ draw_batch,
+ view,
+ ));
+ }
+ }
+}
+
+#[cfg(feature = "3d")]
+fn emit_binned_draw<T, F, G>(
+ views: &Query<(&RenderVisibleEntities, &ExtractedView, &Msaa)>,
+ render_phases: &mut ResMut<ViewBinnedRenderPhases<T>>,
+ view_entities: &mut FixedBitSet,
+ batcher: &Batcher,
+ effect_draw_batches: &Query<(Entity, &mut EffectDrawBatch)>,
+ render_pipeline: &mut ParticlesRenderPipeline,
+ mut specialized_render_pipelines: Mut<SpecializedRenderPipelines<ParticlesRenderPipeline>>,
+ property_cache: &PropertyCache,
+ pipeline_cache: &PipelineCache,
+ render_meshes: &RenderAssets<RenderMesh>,
+ mesh_allocator: &MeshAllocator,
+ make_batch_set_key: F,
+ make_bin_key: G,
+ #[cfg(all(feature = "2d", feature = "3d"))] pipeline_mode: PipelineMode,
+ alpha_mask: ParticleRenderAlphaMaskPipelineKey,
+) where
+ T: BinnedPhaseItem,
+ F: Fn(CachedRenderPipelineId, &EffectDrawBatch, &ExtractedView, MeshSlabs) -> T::BatchSetKey,
+ G: Fn() -> T::BinKey,
+{
+ use bevy::render::render_phase::{BinnedRenderPhaseType, InputUniformIndex};
+
+ trace!("emit_binned_draw() {} views", views.iter().len());
+
+ for (visible_entities, view, msaa) in views.iter() {
+ let Some(visible_effect_entities) = visible_entities.get::<EffectVisibilityClass>() else {
+ continue;
+ };
+ trace!("Process new binned view (alpha_mask={:?})", alpha_mask);
+
+ let Some(render_phase) = render_phases.get_mut(&view.retained_view_entity) else {
+ continue;
+ };
+
+ {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("collect_view_entities").entered();
+
+ view_entities.clear();
+ view_entities.extend(
+ visible_effect_entities
+ .iter_visible()
+ .map(|(_, main_entity)| main_entity.index_u32() as usize),
+ );
+ }
+
+ // For each view, loop over all the effect batches to determine if the effect
+ // needs to be rendered for that view, and enqueue a view-dependent
+ // batch if so.
+ for (draw_entity, draw_batch) in effect_draw_batches.iter() {
+ #[cfg(feature = "trace")]
+ let _span_draw = bevy::log::info_span!("draw_batch").entered();
+
+ trace!(
+ "Process draw batch: draw_entity={:?} effect_batch_index={:?}",
+ draw_entity,
+ draw_batch.effect_batch_index,
+ );
+
+ // Get the EffectBatches this EffectDrawBatch is part of.
+ let Some(effect_batch) = batcher.get(draw_batch.effect_batch_index) else {
+ continue;
+ };
+
+ trace!(
+ "-> EffectBaches: slab_id={} spawner_base={} layout_flags={:?}",
+ effect_batch.slab_id.index(),
+ effect_batch.spawner_base,
+ effect_batch.layout_flags,
+ );
+
+ if ParticleRenderAlphaMaskPipelineKey::from(effect_batch.layout_flags) != alpha_mask {
+ trace!(
+ "Mismatching alpha mask pipeline key (batches={:?}, expected={:?}). Skipped.",
+ effect_batch.layout_flags,
+ alpha_mask
+ );
+ continue;
+ }
+
+ // Check if batch contains any entity visible in the current view. Otherwise we
+ // can skip the entire batch. Note: This is O(n^2) but (unlike
+ // the Sprite renderer this is inspired from) we don't expect more than
+ // a handful of particle effect instances, so would rather not pay the memory
+ // cost of a FixedBitSet for the sake of an arguable speed-up.
+ // TODO - Profile to confirm.
+ #[cfg(feature = "trace")]
+ let _span_check_vis = bevy::log::info_span!("check_visibility").entered();
+ let has_visible_entity = effect_batch
+ .effect_data
+ .iter()
+ .any(|effect_data| view_entities.contains(effect_data.entity as usize));
+ if !has_visible_entity {
+ trace!("No visible entity for view, not emitting any draw call.");
+ continue;
+ }
+ #[cfg(feature = "trace")]
+ _span_check_vis.exit();
+
+ // FIXME - We draw the entire batch, but part of it may not be visible in this
+ // view! We should re-batch for the current view specifically!
+
+ let local_space_simulation = effect_batch
+ .layout_flags
+ .contains(LayoutFlags::LOCAL_SPACE_SIMULATION);
+ let alpha_mask = ParticleRenderAlphaMaskPipelineKey::from(effect_batch.layout_flags);
+ let flipbook = effect_batch.layout_flags.contains(LayoutFlags::FLIPBOOK);
+ let needs_uv = effect_batch.layout_flags.contains(LayoutFlags::NEEDS_UV);
+ let needs_normal = effect_batch
+ .layout_flags
+ .contains(LayoutFlags::NEEDS_NORMAL);
+ let needs_particle_fragment = effect_batch
+ .layout_flags
+ .contains(LayoutFlags::NEEDS_PARTICLE_FRAGMENT);
+ let ribbons = effect_batch.layout_flags.contains(LayoutFlags::RIBBONS);
+ let image_count = effect_batch.texture_layout.layout.len() as u8;
+ let render_mesh = render_meshes.get(effect_batch.mesh);
+
+ // Specialize the render pipeline based on the effect batch
+ trace!(
+ "Specializing render pipeline: render_shaders={:?} image_count={} alpha_mask={:?} flipbook={:?} target_format={:?}",
+ effect_batch.render_shader,
+ image_count,
+ alpha_mask,
+ flipbook,
+ view.target_format
+ );
+
+ // Add a draw pass for the effect batch
+ trace!("Emitting individual draw for batch");
+
+ let alpha_mode = effect_batch.alpha_mode;
+
+ let Some(mesh_layout) = render_mesh.map(|gpu_mesh| gpu_mesh.layout.clone()) else {
+ trace!("Missing mesh vertex buffer layout. Skipped.");
+ continue;
+ };
+
+ // This should always exist by the time we reach this point, because we should
+ // have inserted any property in the cache, which would have allocated the
+ // proper bind group layout (or the default no-property one).
+ let has_multi_draw = false; // TODO?
+ let property_layout_min_binding_size =
+ NonZeroU64::new(effect_batch.property_key.binding_size as u64);
+ let spawner_bind_group_layout_desc = property_cache
+ .bind_group_layout_desc(
+ property_layout_min_binding_size,
+ has_multi_draw,
+ &effect_batch.texture_layout,
+ )
+ .unwrap_or_else(|| {
+ panic!(
+ "Failed to find spawner@2 bind group layout for property binding size {:?}",
+ property_layout_min_binding_size,
+ )
+ });
+
+ #[cfg(feature = "trace")]
+ let _span_specialize = bevy::log::info_span!("specialize").entered();
+ let render_pipeline_id = specialized_render_pipelines.specialize(
+ pipeline_cache,
+ render_pipeline,
+ ParticleRenderPipelineKey {
+ shader: effect_batch.render_shader.clone(),
+ mesh_layout: Some(mesh_layout),
+ particle_layout: effect_batch.particle_layout.clone(),
+ texture_layout: effect_batch.texture_layout.clone(),
+ local_space_simulation,
+ alpha_mask,
+ alpha_mode,
+ flipbook,
+ needs_uv,
+ needs_normal,
+ needs_particle_fragment,
+ ribbons,
+ #[cfg(all(feature = "2d", feature = "3d"))]
+ pipeline_mode,
+ msaa_samples: msaa.samples(),
+ target_format: view.target_format,
+ spawner_bind_group_layout_desc: spawner_bind_group_layout_desc.clone(),
+ },
+ );
+ #[cfg(feature = "trace")]
+ _span_specialize.exit();
+
+ trace!("+ Render pipeline specialized: id={:?}", render_pipeline_id,);
+ trace!(
+ "+ Add Transparent for batch on draw_entity {:?}: slab_id={} \
+ spawner_base={} handle={:?}",
+ draw_entity,
+ effect_batch.slab_id.index(),
+ effect_batch.spawner_base,
+ effect_batch.handle
+ );
+ let slabs = mesh_allocator
+ .mesh_slabs(&effect_batch.mesh)
+ .unwrap_or_default();
+ render_phase.add(
+ make_batch_set_key(render_pipeline_id, draw_batch, view, slabs),
+ make_bin_key(),
+ (draw_entity, draw_batch.main_entity),
+ InputUniformIndex::default(),
+ BinnedRenderPhaseType::NonMesh,
+ );
+ }
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn queue_effects(
+ views: Query<(&RenderVisibleEntities, &ExtractedView, &Msaa)>,
+ mut render_pipeline: ResMut<ParticlesRenderPipeline>,
+ mut specialized_render_pipelines: ResMut<SpecializedRenderPipelines<ParticlesRenderPipeline>>,
+ mut effect_bind_groups: ResMut<EffectBindGroups>,
+ batcher: Res<Batcher>,
+ effect_draw_batches: Query<(Entity, &mut EffectDrawBatch)>,
+ events: Res<EffectAssetEvents>,
+ render_meshes: Res<RenderAssets<RenderMesh>>,
+ #[cfg(feature = "3d")] mesh_allocator: Res<MeshAllocator>,
+ read_params: QueueEffectsReadOnlyParams,
+ mut view_entities: Local<FixedBitSet>,
+ #[cfg(feature = "2d")] mut transparent_2d_render_phases: ResMut<
+ ViewSortedRenderPhases<Transparent2d>,
+ >,
+ #[cfg(feature = "3d")] mut transparent_3d_render_phases: ResMut<
+ ViewSortedRenderPhases<Transparent3d>,
+ >,
+ #[cfg(feature = "3d")] (mut opaque_3d_render_phases, mut alpha_mask_3d_render_phases): (
+ ResMut<ViewBinnedRenderPhases<Opaque3d>>,
+ ResMut<ViewBinnedRenderPhases<AlphaMask3d>>,
+ ),
+ mut change_tick: Local<Tick>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("hanabi:queue_effects").entered();
+
+ trace!("queue_effects");
+
+ let effects_meta = read_params.effects_meta.into_inner();
+ let property_cache = read_params.property_cache.into_inner();
+ let pipeline_cache = read_params.pipeline_cache.into_inner();
+
+ // Bump the change tick so that Bevy is forced to rebuild the binned render
+ // phase bins. We don't use the built-in caching so we don't want Bevy to
+ // reuse stale data.
+ let next_change_tick = change_tick.get() + 1;
+ change_tick.set(next_change_tick);
+
+ // If an image has changed, the GpuImage has (probably) changed
+ for event in &events.images {
+ match event {
+ AssetEvent::Added { .. } => (),
+ AssetEvent::LoadedWithDependencies { .. } => (),
+ AssetEvent::Unused { .. } => (),
+ AssetEvent::Modified { id } => {
+ if effect_bind_groups.images.remove(id).is_some() {
+ trace!("Destroyed bind group of modified image asset {:?}", id);
+ }
+ }
+ AssetEvent::Removed { id } => {
+ if effect_bind_groups.images.remove(id).is_some() {
+ trace!("Destroyes bind group of removed image asset {:?}", id);
+ }
+ }
+ };
+ }
+
+ if effects_meta.spawner_buffer.buffer().is_none() || effects_meta.spawner_buffer.is_empty() {
+ // No spawners are active
+ return;
+ }
+
+ // Loop over all 2D cameras/views that need to render effects
+ #[cfg(feature = "2d")]
+ {
+ #[cfg(feature = "trace")]
+ let _span_draw = bevy::log::info_span!("draw_2d").entered();
+
+ let draw_effects_function_2d = read_params
+ .draw_functions_2d
+ .read()
+ .get_id::<DrawEffects>()
+ .unwrap();
+
+ // Effects with full alpha blending
+ if !views.is_empty() {
+ trace!("Emit effect draw calls for alpha blended 2D views...");
+ emit_sorted_draw(
+ &views,
+ &mut transparent_2d_render_phases,
+ &mut view_entities,
+ &batcher,
+ &effect_draw_batches,
+ &mut render_pipeline,
+ specialized_render_pipelines.reborrow(),
+ property_cache,
+ &render_meshes,
+ pipeline_cache,
+ |id, entity, draw_batch, _view| Transparent2d {
+ sort_key: FloatOrd(draw_batch.translation.z),
+ entity,
+ pipeline: id,
+ draw_function: draw_effects_function_2d,
+ batch_range: 0..1,
+ extracted_index: 0, // ???
+ extra_index: PhaseItemExtraIndex::None,
+ indexed: true, // ???
+ },
+ #[cfg(feature = "3d")]
+ PipelineMode::Camera2d,
+ );
+ }
+ }
+
+ // Loop over all 3D cameras/views that need to render effects
+ #[cfg(feature = "3d")]
+ {
+ #[cfg(feature = "trace")]
+ let _span_draw = bevy::log::info_span!("draw_3d").entered();
+
+ // Effects with full alpha blending
+ if !views.is_empty() {
+ use bevy::core_pipeline::core_3d::TransparentSortingInfo3d;
+
+ trace!("Emit effect draw calls for alpha blended 3D views...");
+
+ let draw_effects_function_3d = read_params
+ .draw_functions_3d
+ .read()
+ .get_id::<DrawEffects>()
+ .unwrap();
+
+ emit_sorted_draw(
+ &views,
+ &mut transparent_3d_render_phases,
+ &mut view_entities,
+ &batcher,
+ &effect_draw_batches,
+ &mut render_pipeline,
+ specialized_render_pipelines.reborrow(),
+ property_cache,
+ &render_meshes,
+ pipeline_cache,
+ |id, entity, batch, view| Transparent3d {
+ sorting_info: TransparentSortingInfo3d::Sorted {
+ mesh_center: batch.translation,
+ depth_bias: 0.0,
+ },
+ distance: view.rangefinder3d().distance(&batch.translation),
+ pipeline: id,
+ entity,
+ draw_function: draw_effects_function_3d,
+ batch_range: 0..1,
+ extra_index: PhaseItemExtraIndex::None,
+ indexed: true, // ???
+ },
+ #[cfg(feature = "2d")]
+ PipelineMode::Camera3d,
+ );
+ }
+
+ // Effects with alpha mask
+ if !views.is_empty() {
+ #[cfg(feature = "trace")]
+ let _span_draw = bevy::log::info_span!("draw_alphamask").entered();
+
+ trace!("Emit effect draw calls for alpha masked 3D views...");
+
+ let draw_effects_function_alpha_mask = read_params
+ .draw_functions_alpha_mask
+ .read()
+ .get_id::<DrawEffects>()
+ .unwrap();
+
+ emit_binned_draw(
+ &views,
+ &mut alpha_mask_3d_render_phases,
+ &mut view_entities,
+ &batcher,
+ &effect_draw_batches,
+ &mut render_pipeline,
+ specialized_render_pipelines.reborrow(),
+ property_cache,
+ pipeline_cache,
+ &render_meshes,
+ &mesh_allocator,
+ |id, _batch, _view, slabs| OpaqueNoLightmap3dBatchSetKey {
+ pipeline: id,
+ draw_function: draw_effects_function_alpha_mask,
+ material_bind_group_index: None,
+ slabs,
+ },
+ // Unused for now
+ || OpaqueNoLightmap3dBinKey {
+ asset_id: AssetId::<Mesh>::default().untyped(),
+ },
+ #[cfg(feature = "2d")]
+ PipelineMode::Camera3d,
+ ParticleRenderAlphaMaskPipelineKey::AlphaMask,
+ );
+ }
+
+ // Opaque particles
+ if !views.is_empty() {
+ #[cfg(feature = "trace")]
+ let _span_draw = bevy::log::info_span!("draw_opaque").entered();
+
+ trace!("Emit effect draw calls for opaque 3D views...");
+
+ let draw_effects_function_opaque = read_params
+ .draw_functions_opaque
+ .read()
+ .get_id::<DrawEffects>()
+ .unwrap();
+
+ emit_binned_draw(
+ &views,
+ &mut opaque_3d_render_phases,
+ &mut view_entities,
+ &batcher,
+ &effect_draw_batches,
+ &mut render_pipeline,
+ specialized_render_pipelines.reborrow(),
+ property_cache,
+ pipeline_cache,
+ &render_meshes,
+ &mesh_allocator,
+ |id, _batch, _view, slabs| Opaque3dBatchSetKey {
+ pipeline: id,
+ draw_function: draw_effects_function_opaque,
+ material_bind_group_index: None,
+ slabs,
+ lightmap_slab: None,
+ },
+ // Unused for now
+ || Opaque3dBinKey {
+ asset_id: AssetId::<Mesh>::default().untyped(),
+ },
+ #[cfg(feature = "2d")]
+ PipelineMode::Camera3d,
+ ParticleRenderAlphaMaskPipelineKey::Opaque,
+ );
+ }
+ }
+}
+
+/// Once a child effect is batched, and therefore passed validations to be
+/// updated and rendered this frame, dispatch a new GPU operation to fill the
+/// indirect dispatch args of its init pass based on the number of GPU events
+/// emitted in the previous frame and stored in its event buffer.
+pub fn queue_init_indirect_workgroup_update(
+ q_cached_effects: Query<(
+ Entity,
+ &CachedChildInfo,
+ &CachedEffectEvents,
+ &CachedReadyState,
+ )>,
+ mut init_fill_dispatch_queue: ResMut<InitFillDispatchQueue>,
+) {
+ debug_assert_eq!(
+ GpuChildInfo::min_size().get() % 4,
+ 0,
+ "Invalid GpuChildInfo alignment."
+ );
+
+ // Schedule some GPU buffer operation to update the number of workgroups to
+ // dispatch during the indirect init pass of this effect based on the number of
+ // GPU spawn events written in its buffer.
+ for (entity, cached_child_info, cached_effect_events, cached_ready_state) in &q_cached_effects {
+ if !cached_ready_state.is_ready() {
+ trace!(
+ "[Effect {:?}] Skipping init_fill_dispatch.enqueue() because effect is not ready.",
+ entity
+ );
+ continue;
+ }
+ let init_indirect_dispatch_index = cached_effect_events.init_indirect_dispatch_index;
+ let global_child_index = cached_child_info.global_child_index;
+ trace!(
+ "[Effect {:?}] init_fill_dispatch.enqueue(): src:global_child_index={} dst:init_indirect_dispatch_index={}",
+ entity,
+ global_child_index,
+ init_indirect_dispatch_index,
+ );
+ assert!(global_child_index != u32::MAX);
+ init_fill_dispatch_queue.enqueue(global_child_index, init_indirect_dispatch_index);
+ }
+}
+
+/// Prepare GPU resources for effect rendering.
+///
+/// This system runs in the [`RenderSet::PrepareResources`] render set, after
+/// Bevy has updated the [`ViewUniforms`], which need to be referenced to get
+/// access to the current camera view.
+pub(crate) fn prepare_gpu_resources(
+ mut effects_meta: ResMut<EffectsMeta>,
+ //mut effect_cache: ResMut<EffectCache>,
+ mut event_cache: ResMut<EventCache>,
+ mut effect_bind_groups: ResMut<EffectBindGroups>,
+ mut sort_bind_groups: ResMut<SortBindGroups>,
+ render_device: Res<RenderDevice>,
+ render_queue: Res<RenderQueue>,
+ view_uniforms: Res<ViewUniforms>,
+ render_pipeline: Res<ParticlesRenderPipeline>,
+ pipeline_cache: Res<PipelineCache>,
+) {
+ // Get the binding for the ViewUniform, the uniform data structure containing
+ // the Camera data for the current view. If not available, we cannot render
+ // anything.
+ let Some(view_binding) = view_uniforms.uniforms.binding() else {
+ return;
+ };
+
+ // Upload simulation parameters for this frame
+ let prev_buffer_id = effects_meta.sim_params_uniforms.buffer().map(|b| b.id());
+ effects_meta
+ .sim_params_uniforms
+ .write_buffer(&render_device, &render_queue);
+ if prev_buffer_id != effects_meta.sim_params_uniforms.buffer().map(|b| b.id()) {
+ // Buffer changed, invalidate bind groups
+ effects_meta.update_sim_params_bind_group = None;
+ effects_meta.init_and_indirect_sim_params_bind_group = None;
+ }
+
+ // Create the bind group for the camera/view parameters
+ // FIXME - Not here!
+ effects_meta.view_bind_group = Some(render_device.create_bind_group(
+ "hanabi:bg:camera_view",
+ &pipeline_cache.get_bind_group_layout(&render_pipeline.view_layout_desc),
+ &BindGroupEntries::sequential((
+ view_binding,
+ effects_meta.sim_params_uniforms.binding().unwrap(),
+ )),
+ ));
+
+ // Re-/allocate the draw indirect args buffer if needed
+ if effects_meta
+ .draw_indirect_args_buffer
+ .allocate_gpu(&render_device, &render_queue)
+ {
+ // All those bind groups use the buffer so need to be re-created
+ trace!("*** Draw indirect args buffer re-allocated; clearing all bind groups using it.");
+ effects_meta.update_sim_params_bind_group = None;
+ effects_meta.indirect_metadata_bind_group = None;
+ }
+
+ // Re-/allocate any GPU buffer if needed
+ //effect_cache.prepare_buffers(&render_device, &render_queue, &mut
+ // effect_bind_groups);
+ event_cache.prepare_buffers(&render_device, &render_queue, &mut effect_bind_groups);
+ sort_bind_groups.prepare_buffers(&render_device);
+ if effects_meta
+ .dispatch_indirect_args_buffer
+ .prepare_buffers(&render_device)
+ {
+ // All those bind groups use the buffer so need to be re-created
+ trace!("*** Dispatch indirect buffer for update pass re-allocated; clearing all bind groups using it.");
+ effect_bind_groups.particle_slabs.clear();
+ }
+}
+
+/// Update the [`GpuEffectMetadata`] of all the effects queued for update/render
+/// this frame.
+///
+/// By this point, all effects should have a [`CachedEffectMetadata`] with a
+/// valid allocation in the GPU table for a [`GpuEffectMetadata`] entry. This
+/// system actually synchronize the CPU value with the GPU one in case of
+/// change.
+pub(crate) fn prepare_effect_metadata(
+ render_device: Res<RenderDevice>,
+ render_queue: Res<RenderQueue>,
+ mut q_effects: Query<(
+ MainEntity,
+ Ref<ExtractedEffect>,
+ Ref<CachedEffect>,
+ Option<Ref<CachedChildInfo>>,
+ Option<Ref<CachedParentInfo>>,
+ Option<Ref<CachedDrawIndirectArgs>>,
+ Option<Ref<CachedEffectEvents>>,
+ Option<Ref<CachedEffectProperties>>,
+ &mut CachedEffectMetadata,
+ )>,
+ mut effects_meta: ResMut<EffectsMeta>,
+ mut effect_bind_groups: ResMut<EffectBindGroups>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("prepare_effect_metadata").entered();
+ trace!("prepare_effect_metadata");
+
+ for (
+ main_entity,
+ extracted_effect,
+ cached_effect,
+ maybe_cached_child_info,
+ maybe_cached_parent_info,
+ maybe_cached_draw_indirect_args,
+ maybe_cached_effect_events,
+ maybe_cached_effect_properties,
+ mut cached_effect_metadata,
+ ) in &mut q_effects
+ {
+ // Check if anything relevant to GpuEffectMetadata changed this frame; otherwise
+ // early out and skip this effect.
+ let is_changed_ee = extracted_effect.is_changed();
+ let is_changed_ce = cached_effect.is_changed();
+ let is_changed_cci = maybe_cached_child_info
+ .as_ref()
+ .map(|cci| cci.is_changed())
+ .unwrap_or(false);
+ let is_changed_cpi = maybe_cached_parent_info
+ .as_ref()
+ .map(|cpi| cpi.is_changed())
+ .unwrap_or(false);
+ let is_changed_cdia = maybe_cached_draw_indirect_args
+ .as_ref()
+ .map(|cdia| cdia.is_changed())
+ .unwrap_or(false);
+ let is_changed_cee = maybe_cached_effect_events
+ .as_ref()
+ .map(|cee| cee.is_changed())
+ .unwrap_or(false);
+ let is_changed_cep = maybe_cached_effect_properties
+ .as_ref()
+ .map(|cep| cep.is_changed())
+ .unwrap_or(false);
+ trace!(
+ "Preparting GpuEffectMetadata for effect {:?}: is_changed[] = {} {} {} {} {} {} {}",
+ main_entity,
+ is_changed_ee,
+ is_changed_ce,
+ is_changed_cci,
+ is_changed_cpi,
+ is_changed_cdia,
+ is_changed_cee,
+ is_changed_cep
+ );
+ if !is_changed_ee
+ && !is_changed_ce
+ && !is_changed_cci
+ && !is_changed_cpi
+ && !is_changed_cdia
+ && !is_changed_cee
+ && !is_changed_cep
+ {
+ continue;
+ }
+
+ let capacity = cached_effect.slice.len();
+
+ // Global and local indices of this effect as a child of another (parent) effect
+ let (global_child_index, local_child_index) = maybe_cached_child_info
+ .map(|cci| (cci.global_child_index, cci.local_child_index))
+ .unwrap_or((u32::MAX, u32::MAX));
+
+ // Base index of all children of this (parent) effect
+ let base_child_index = maybe_cached_parent_info
+ .map(|cpi| {
+ debug_assert_eq!(
+ cpi.byte_range.start % GpuChildInfo::SHADER_SIZE.get() as u32,
+ 0
+ );
+ cpi.byte_range.start / GpuChildInfo::SHADER_SIZE.get() as u32
+ })
+ .unwrap_or(u32::MAX);
+
+ let particle_stride = extracted_effect.particle_layout.min_binding_size32().get() / 4;
+ let sort_key_offset = extracted_effect
+ .particle_layout
+ .byte_offset(Attribute::RIBBON_ID)
+ .map(|byte_offset| byte_offset / 4)
+ .unwrap_or(u32::MAX);
+ // raea: a blended effect (no ribbons) sorts by its particles' view depth from the main camera, far first
+ // (vfx_sort_fill.wesl reads the flags; raea #52)
+ let sort_key_offset = match extracted_effect.layout_flags.raea_sorted()
+ && !extracted_effect.layout_flags.contains(LayoutFlags::RIBBONS)
+ {
+ true => extracted_effect
+ .particle_layout
+ .byte_offset(Attribute::POSITION)
+ .map(|byte_offset| {
+ let local = extracted_effect
+ .layout_flags
+ .contains(LayoutFlags::LOCAL_SPACE_SIMULATION);
+ byte_offset / 4 | RAEA_SORT_BY_DISTANCE | if local { RAEA_SORT_LOCAL } else { 0 }
+ })
+ .unwrap_or(u32::MAX),
+ false => sort_key_offset,
+ };
+ let sort_key2_offset = extracted_effect
+ .particle_layout
+ .byte_offset(Attribute::AGE)
+ .map(|byte_offset| byte_offset / 4)
+ .unwrap_or(u32::MAX);
+
+ let gpu_effect_metadata = GpuEffectMetadata {
+ capacity,
+ alive_count: 0,
+ max_update: 0,
+ max_spawn: capacity,
+ indirect_write_index: 0,
+ indirect_draw_index: maybe_cached_draw_indirect_args
+ .map(|cdia| cdia.get_row().0)
+ .unwrap_or(u32::MAX),
+ init_indirect_dispatch_index: maybe_cached_effect_events
+ .map(|cee| cee.init_indirect_dispatch_index)
+ .unwrap_or(u32::MAX),
+ properties_array_index: maybe_cached_effect_properties
+ .map(|cep| cep.array_index)
+ .unwrap_or(u32::MAX),
+ local_child_index,
+ global_child_index,
+ base_child_index,
+ particle_stride,
+ sort_key_offset,
+ sort_key2_offset,
+ ..default()
+ };
+
+ // Insert of update entry in GPU buffer table
+ assert!(cached_effect_metadata.table_id.is_valid());
+ if gpu_effect_metadata != cached_effect_metadata.metadata {
+ effects_meta
+ .effect_metadata_buffer
+ .update(cached_effect_metadata.table_id, gpu_effect_metadata);
+
+ cached_effect_metadata.metadata = gpu_effect_metadata;
+
+ // This triggers on all new spawns and annoys everyone; silence until we can at
+ // least warn only on non-first-spawn, and ideally split indirect data from that
+ // struct so we don't overwrite it and solve the issue.
+ debug!(
+ "Updated metadata entry {} for effect {:?}, this will reset it.",
+ cached_effect_metadata.table_id.0, main_entity
+ );
+ }
+ }
+
+ // Once all EffectMetadata values are written, schedule a GPU upload
+ if effects_meta
+ .effect_metadata_buffer
+ .allocate_gpu(render_device.as_ref(), render_queue.as_ref())
+ {
+ // All those bind groups use the buffer so need to be re-created
+ trace!("*** Effect metadata buffer re-allocated; clearing all bind groups using it.");
+ effects_meta.indirect_metadata_bind_group = None;
+ effect_bind_groups.init_metadata_bind_groups.clear();
+ effect_bind_groups.update_metadata_bind_groups.clear();
+ }
+}
+
+/// Read the queued ribbon sort fill dispatch operations and enqueue the
+/// corresponding GPU buffer fill dispatch operations.
+///
+/// This system runs after [`prepare_effect_metadata()`] has (re-)allocated the
+/// effect metadata buffer to this frame's effect count, so that it captures the
+/// correctly-sized buffer and computes in-bounds dynamic offsets. It must run
+/// before [`queue_init_fill_dispatch_ops()`], which uploads the shared
+/// [`GpuBufferOperations`] args buffer to the GPU at the end of the frame.
+pub(crate) fn queue_sort_fill_dispatch_ops(
+ effects_meta: Res<EffectsMeta>,
+ sort_bind_groups: Res<SortBindGroups>,
+ sort_fill_dispatch_queue: Res<SortFillDispatchQueue>,
+ mut gpu_buffer_operations: ResMut<GpuBufferOperations>,
+ mut batcher: ResMut<Batcher>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("queue_sort_fill_dispatch_ops").entered();
+ trace!("queue_sort_fill_dispatch_ops");
+
+ if sort_fill_dispatch_queue.is_empty() {
+ return;
+ }
+
+ debug_assert!(batcher.sort_fill_prefix_sum_queue_index.is_none());
+ debug_assert!(batcher.fill_dispatch_queue_index.is_none());
+ debug_assert!(batcher.sort_dispatch_queue_index.is_none());
+ let Some(prefix_sum_buffer) = batcher.prefix_sum_buffer() else {
+ error!("Missing prefix sum buffer for ribbon sort. This is a bug.");
+ return;
+ };
+ let queue_indices = sort_fill_dispatch_queue.submit(
+ &effects_meta.effect_metadata_buffer,
+ prefix_sum_buffer,
+ &sort_bind_groups,
+ &mut gpu_buffer_operations,
+ );
+ batcher.sort_fill_prefix_sum_queue_index = queue_indices.alive_count_copy;
+ batcher.fill_dispatch_queue_index = queue_indices.fill_dispatch;
+ batcher.sort_dispatch_queue_index = queue_indices.sort_dispatch;
+}
+
+/// Read the queued init fill dispatch operations, batch them together by
+/// contiguous source and destination entries in the buffers, and enqueue
+/// corresponding GPU buffer fill dispatch operations for all batches.
+///
+/// This system runs after the GPU buffers have been (re-)allocated in
+/// [`prepare_gpu_resources()`], so that it can read the new buffer IDs and
+/// reference them from the generic [`GpuBufferOperationQueue`].
+pub(crate) fn queue_init_fill_dispatch_ops(
+ event_cache: Res<EventCache>,
+ render_device: Res<RenderDevice>,
+ render_queue: Res<RenderQueue>,
+ mut init_fill_dispatch_queue: ResMut<InitFillDispatchQueue>,
+ mut gpu_buffer_operations: ResMut<GpuBufferOperations>,
+) {
+ // Submit all queued init fill dispatch operations with the proper buffers
+ if !init_fill_dispatch_queue.is_empty() {
+ let src_buffer = event_cache.child_infos().buffer();
+ let dst_buffer = event_cache.init_indirect_dispatch_buffer();
+ if let (Some(src_buffer), Some(dst_buffer)) = (src_buffer, dst_buffer) {
+ init_fill_dispatch_queue.submit(src_buffer, dst_buffer, &mut gpu_buffer_operations);
+ } else {
+ if src_buffer.is_none() {
+ warn!("Event cache has no allocated GpuChildInfo buffer, but there's {} init fill dispatch operation(s) queued. Ignoring those operations. This will prevent child particles from spawning.", init_fill_dispatch_queue.queue.len());
+ }
+ if dst_buffer.is_none() {
+ warn!("Event cache has no allocated GpuDispatchIndirect buffer, but there's {} init fill dispatch operation(s) queued. Ignoring those operations. This will prevent child particles from spawning.", init_fill_dispatch_queue.queue.len());
+ }
+ }
+ }
+
+ // End the GpuBufferOperations frame and upload the args buffer to GPU, after
+ // every submit() for the frame (the sort submit in
+ // queue_sort_fill_dispatch_ops() is ordered before this system,
+ // the init submit is just above). See begin_frame() in batch_effects() for the
+ // full lifecycle.
+ gpu_buffer_operations.end_frame(&render_device, &render_queue);
+}
+
+#[derive(SystemParam)]
+pub struct PipelineParams<'w, 's> {
+ dispatch_indirect_pipeline: Res<'w, DispatchIndirectPipeline>,
+ prefix_sum_pipeline: Res<'w, PrefixSumPipeline>,
+ utils_pipeline: Res<'w, UtilsPipeline>,
+ init_pipeline: Res<'w, ParticlesInitPipeline>,
+ update_pipeline: Res<'w, ParticlesUpdatePipeline>,
+ marker: PhantomData<&'s usize>,
+}
+
+pub(crate) fn prepare_bind_groups(
+ mut effects_meta: ResMut<EffectsMeta>,
+ mut effect_cache: ResMut<EffectCache>,
+ mut event_cache: ResMut<EventCache>,
+ mut effect_bind_groups: ResMut<EffectBindGroups>,
+ mut property_bind_groups: ResMut<PropertyBindGroups>,
+ mut sort_bind_groups: ResMut<SortBindGroups>,
+ property_cache: Res<PropertyCache>,
+ batcher: Res<Batcher>,
+ render_device: Res<RenderDevice>,
+ pipeline_cache: Res<PipelineCache>,
+ pipelines: PipelineParams,
+ gpu_images: Res<RenderAssets<GpuImage>>,
+ mut gpu_buffer_operation_queue: ResMut<GpuBufferOperations>,
+) {
+ // We can't simulate nor render anything without at least the spawner buffer
+ if effects_meta.spawner_buffer.is_empty() {
+ return;
+ }
+ let Some(spawner_buffer) = effects_meta.spawner_buffer.buffer().cloned() else {
+ error!("Missing spawner GPU buffer!");
+ return;
+ };
+ let Some(prefix_sum_buffer) = batcher.prefix_sum_buffer().cloned() else {
+ error!("Missing prefix sum GPU buffer!");
+ return;
+ };
+ let Some(batch_info_buffer) = batcher.batch_info_buffer().cloned() else {
+ error!("Missing batch info GPU buffer!");
+ return;
+ };
+ let Some(dispatch_indirect_args_buffer) =
+ effects_meta.dispatch_indirect_args_buffer.buffer().cloned()
+ else {
+ error!("Missing dispatch indirect GPU buffer!");
+ return;
+ };
+
+ // Workaround for too many params in system (TODO: refactor to split work?)
+ let dispatch_indirect_pipeline = pipelines.dispatch_indirect_pipeline.into_inner();
+ let prefix_sum_pipeline = pipelines.prefix_sum_pipeline.into_inner();
+ let utils_pipeline = pipelines.utils_pipeline.into_inner();
+ let init_pipeline = pipelines.init_pipeline.into_inner();
+ let update_pipeline = pipelines.update_pipeline.into_inner();
+
+ // Ensure child_infos@3 bind group for the indirect pass is available if needed.
+ // This returns `None` if the buffer is not ready, either because it's not
+ // created yet or because it's not needed (no child effect).
+ event_cache.ensure_indirect_child_info_buffer_bind_group(&render_device);
+
+ {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("shared_bind_groups").entered();
+
+ // Create the sim_params@0 bind group for the global simulation parameters,
+ // which is shared by the init and update passes.
+ if effects_meta.update_sim_params_bind_group.is_none() {
+ if let Some(draw_indirect_buffer) = effects_meta.draw_indirect_args_buffer.buffer() {
+ effects_meta.update_sim_params_bind_group = Some(render_device.create_bind_group(
+ "hanabi:bg:vfx_update:sim_params@0",
+ &pipeline_cache.get_bind_group_layout(&update_pipeline.sim_params_layout_desc),
+ &BindGroupEntries::sequential((
+ // @group(0) @binding(0) var<uniform> sim_params : SimParams;
+ effects_meta.sim_params_uniforms.binding().unwrap(),
+ // @group(0) @binding(1) var<storage, read_write> draw_indirect_buffer :
+ // array<DrawIndexedIndirectArgs>;
+ draw_indirect_buffer.as_entire_binding(),
+ )),
+ ));
+ } else {
+ debug!("Cannot allocate bind group for vfx_update:sim_params@0 - draw_indirect_buffer not ready");
+ }
+ }
+ if effects_meta
+ .init_and_indirect_sim_params_bind_group
+ .is_none()
+ {
+ debug!("Re-creating init_and_indirect_sim_params_bind_group...");
+ effects_meta.init_and_indirect_sim_params_bind_group =
+ Some(render_device.create_bind_group(
+ "hanabi:bg:vfx_indirect:sim_params@0",
+ &pipeline_cache.get_bind_group_layout(&init_pipeline.sim_params_layout_desc), // FIXME - Shared with init
+ // @group(0) @binding(0) var<uniform> sim_params : SimParams;
+ &BindGroupEntries::single(effects_meta.sim_params_uniforms.binding().unwrap()),
+ ));
+ }
+
+ // Create the @1 bind group for the indirect dispatch preparation pass of all
+ // effects at once
+ effects_meta.indirect_metadata_bind_group = match (
+ effects_meta.effect_metadata_buffer.buffer(),
+ effects_meta.draw_indirect_args_buffer.buffer(),
+ ) {
+ (Some(effect_metadata_buffer), Some(draw_indirect_buffer)) => {
+ // Base bind group for indirect pass
+ Some(render_device.create_bind_group(
+ "hanabi:bg:vfx_indirect:metadata@1",
+ &pipeline_cache.get_bind_group_layout(
+ &dispatch_indirect_pipeline.effect_metadata_bind_group_layout_desc,
+ ),
+ &BindGroupEntries::sequential((
+ // @group(1) @binding(0) var<storage, read_write> effect_metadatas :
+ // array<EffectMetadata>;
+ effect_metadata_buffer.as_entire_binding(),
+ // @group(1) @binding(1) var<storage, read_write> draw_indirect_buffer :
+ // array<u32>;
+ draw_indirect_buffer.as_entire_binding(),
+ )),
+ ))
+ }
+
+ // Some buffer is not yet available, can't create the bind group
+ _ => None,
+ };
+
+ // Create the @2 bind group for the indirect dispatch preparation pass of all
+ // effects at once
+ if effects_meta.indirect_spawner_bind_group.is_none() {
+ let bind_group = render_device.create_bind_group(
+ "hanabi:bg:vfx_indirect:spawner@2",
+ &pipeline_cache.get_bind_group_layout(
+ &dispatch_indirect_pipeline.spawner_bind_group_layout_desc,
+ ),
+ &BindGroupEntries::sequential((
+ // @group(2) @binding(0) var<storage, read> spawner_buffer : array<Spawner>;
+ spawner_buffer.as_entire_binding(),
+ // @group(2) @binding(1) var<storage, read_write> prefix_sum : array<u32>;
+ prefix_sum_buffer.as_entire_binding(),
+ )),
+ );
+
+ effects_meta.indirect_spawner_bind_group = Some(bind_group);
+ }
+
+ // Create the @0 bind group for the prefix sum pass of all batches at once
+ if effects_meta.prefix_sum_bind_group.is_none() {
+ effects_meta.prefix_sum_bind_group = Some(render_device.create_bind_group(
+ "hanabi:bind_group:vfx_prefix_sum:@0",
+ &pipeline_cache.get_bind_group_layout(&prefix_sum_pipeline.bind_group_layout_desc),
+ &BindGroupEntries::sequential((
+ // @group(0) @binding(0) var<storage, read> batch_infos :
+ // array<BatchInfo>;
+ batch_info_buffer.as_entire_binding(),
+ // @group(0) @binding(1) var<storage, read_write> prefix_sum :
+ // array<u32>;
+ prefix_sum_buffer.as_entire_binding(),
+ // @group(0) @binding(2) var<storage, read_write>
+ // dispatch_indirect_buffer : array<DispatchIndirectArgs>;
+ dispatch_indirect_args_buffer.as_entire_binding(),
+ )),
+ ));
+ }
+ }
+
+ // Create the per-slab bind groups
+ trace!("Create per-slab bind groups...");
+ for (slab_index, particle_slab) in effect_cache.slabs().iter().enumerate() {
+ #[cfg(feature = "trace")]
+ let _span_buffer = bevy::log::info_span!("create_buffer_bind_groups").entered();
+
+ let Some(particle_slab) = particle_slab else {
+ trace!(
+ "Particle slab index #{} has no allocated EffectBuffer, skipped.",
+ slab_index
+ );
+ continue;
+ };
+
+ // Ensure all effects in this batch have a bind group for the entire buffer of
+ // the group, since the update phase runs on an entire group/buffer at once,
+ // with all the effect instances in it batched together.
+ trace!("effect particle slab_index=#{}", slab_index);
+ effect_bind_groups
+ .particle_slabs
+ .entry(SlabId::new(slab_index as u32))
+ .or_insert_with(|| {
+ // Bind group particle@1 for render pass
+ trace!("Creating particle@1 bind group for buffer #{slab_index} in render pass");
+ let render = render_device.create_bind_group(
+ &format!("hanabi:bg:render:particles@1:vfx{slab_index}")[..],
+ particle_slab.render_particles_buffer_layout(),
+ &BindGroupEntries::sequential((
+ // @group(1) @binding(0) var<storage, read> particle_buffer :
+ // ParticleBuffer;
+ particle_slab.as_entire_binding_particle(),
+ // @group(1) @binding(1) var<storage, read> indirect_buffer :
+ // IndirectBuffer;
+ particle_slab.as_entire_binding_indirect(),
+ )),
+ );
+
+ BufferBindGroups { render }
+ });
+ }
+
+ // Create bind groups for queued GPU buffer operations
+ gpu_buffer_operation_queue.create_bind_groups(&render_device, utils_pipeline);
+
+ // Create the per-effect-batch bind groups
+ for effect_batch in batcher.iter() {
+ #[cfg(feature = "trace")]
+ let _span_buffer = bevy::log::info_span!("create_batch_bind_groups").entered();
+
+ // Create the property bind group @2 if needed
+ if let Err(err) = property_bind_groups.ensure_exists(
+ &effect_batch.property_key,
+ &property_cache,
+ &spawner_buffer,
+ &prefix_sum_buffer,
+ &effect_batch.texture_layout,
+ &effect_batch.textures[..],
+ &batch_info_buffer,
+ &render_device,
+ &pipeline_cache,
+ &gpu_images,
+ ) {
+ error!("Failed to create property bind group for effect batch: {err:?}");
+ continue;
+ }
+
+ // Bind group particle@1 for the simulate compute shaders (init and udpate) to
+ // simulate particles.
+ if effect_cache
+ .create_particle_sim_bind_group(
+ &effect_batch.slab_id,
+ &render_device,
+ effect_batch.particle_layout.min_binding_size32(),
+ effect_batch.parent_min_binding_size,
+ effect_batch.parent_binding_source.as_ref(),
+ &pipeline_cache,
+ )
+ .is_err()
+ {
+ error!("No particle buffer allocated for effect batch.");
+ continue;
+ }
+
+ // Bind group @3 of init pass
+ // FIXME - this is instance-dependent, not buffer-dependent
+ {
+ let consume_gpu_spawn_events = effect_batch
+ .layout_flags
+ .contains(LayoutFlags::CONSUME_GPU_SPAWN_EVENTS);
+ let consume_event_buffers = if let BatchSpawnInfo::GpuSpawner { .. } =
+ effect_batch.spawn_info
+ {
+ assert!(consume_gpu_spawn_events);
+ let cached_effect_events = effect_batch.cached_effect_events.as_ref().unwrap();
+ Some(ConsumeEventBuffers {
+ child_infos_buffer: event_cache.child_infos_buffer().unwrap(),
+ events: BufferSlice {
+ buffer: event_cache
+ .get_buffer(cached_effect_events.buffer_index)
+ .unwrap(),
+ // Note: event range is in u32 count, not bytes
+ offset: cached_effect_events.range.start * 4,
+ size: NonZeroU32::new(cached_effect_events.range.len() as u32 * 4).unwrap(),
+ },
+ })
+ } else {
+ assert!(!consume_gpu_spawn_events);
+ None
+ };
+ let Some(init_metadata_layout_desc) =
+ effect_cache.metadata_init_bind_group_layout_desc(consume_gpu_spawn_events)
+ else {
+ continue;
+ };
+ if effect_bind_groups
+ .get_or_create_init_metadata(
+ effect_batch,
+ &render_device,
+ &pipeline_cache.get_bind_group_layout(init_metadata_layout_desc),
+ effects_meta.effect_metadata_buffer.buffer().unwrap(),
+ consume_event_buffers,
+ )
+ .is_err()
+ {
+ continue;
+ }
+ }
+
+ // Bind group @3 of update pass
+ // FIXME - this is instance-dependent, not buffer-dependent#
+ {
+ let num_event_buffers = effect_batch.child_event_buffers.len() as u32;
+
+ let Some(update_metadata_layout_desc) =
+ effect_cache.metadata_update_bind_group_layout_desc(num_event_buffers)
+ else {
+ continue;
+ };
+ if effect_bind_groups
+ .get_or_create_update_metadata(
+ effect_batch,
+ &render_device,
+ &pipeline_cache.get_bind_group_layout(update_metadata_layout_desc),
+ effects_meta.effect_metadata_buffer.buffer().unwrap(),
+ event_cache.child_infos_buffer(),
+ &effect_batch.child_event_buffers[..],
+ )
+ .is_err()
+ {
+ continue;
+ }
+ }
+
+ if effect_batch.layout_flags.raea_sorted() { // raea: and blended effects (#52)
+ let effect_buffer = effect_cache.get_slab(&effect_batch.slab_id).unwrap();
+
+ // Bind group @0 of sort-fill pass
+ let particle_buffer = effect_buffer.particle_buffer();
+ let indirect_index_buffer = effect_buffer.indirect_index_buffer();
+ let effect_metadata_buffer = effects_meta.effect_metadata_buffer.buffer().unwrap();
+ if let Err(err) = sort_bind_groups.ensure_sort_fill_bind_group(
+ &render_device,
+ &effect_batch.particle_layout,
+ particle_buffer,
+ indirect_index_buffer,
+ effect_metadata_buffer,
+ &spawner_buffer,
+ effects_meta.sim_params_uniforms.buffer().unwrap(), // raea: (#52)
+ &pipeline_cache,
+ ) {
+ error!(
+ "Failed to create sort-fill bind group @0 for ribbon effect: {:?}",
+ err
+ );
+ continue;
+ }
+
+ // Bind group @0 of sort pass
+ sort_bind_groups.ensure_sort_bind_group(&render_device, &pipeline_cache);
+ sort_bind_groups.ensure_sort_merge_bind_group(&render_device, &pipeline_cache);
+
+ // Bind group @0 of sort-copy pass
+ let indirect_index_buffer = effect_buffer.indirect_index_buffer();
+ if let Err(err) = sort_bind_groups.ensure_sort_copy_bind_group(
+ &render_device,
+ indirect_index_buffer,
+ effect_metadata_buffer,
+ &spawner_buffer,
+ &pipeline_cache,
+ ) {
+ error!(
+ "Failed to create sort-copy bind group @0 for ribbon effect: {:?}",
+ err
+ );
+ continue;
+ }
+ }
+ }
+}
+
+type DrawEffectsSystemState = SystemState<(
+ SRes<EffectsMeta>,
+ SRes<EffectBindGroups>,
+ SRes<PropertyBindGroups>,
+ SRes<PipelineCache>,
+ SRes<RenderAssets<RenderMesh>>,
+ SRes<MeshAllocator>,
+ SQuery<Read<ViewUniformOffset>>,
+ SRes<Batcher>,
+ SQuery<Read<EffectDrawBatch>>,
+)>;
+
+/// Draw function for rendering all active effects for the current frame.
+///
+/// Effects are rendered in the [`Transparent2d`] phase of the main 2D pass,
+/// and the [`Transparent3d`] phase of the main 3D pass.
+pub(crate) struct DrawEffects {
+ params: DrawEffectsSystemState,
+}
+
+impl DrawEffects {
+ pub fn new(world: &mut World) -> Self {
+ Self {
+ params: SystemState::new(world),
+ }
+ }
+}
+
+/// Draw all particles of a single effect in view, in 2D or 3D.
+///
+/// FIXME: use pipeline ID to look up which group index it is.
+fn draw<'w>(
+ world: &'w World,
+ pass: &mut TrackedRenderPass<'w>,
+ view: Entity,
+ entity: (Entity, MainEntity),
+ pipeline_id: CachedRenderPipelineId,
+ params: &mut DrawEffectsSystemState,
+) {
+ let (
+ effects_meta,
+ effect_bind_groups,
+ property_bind_groups,
+ pipeline_cache,
+ meshes,
+ mesh_allocator,
+ views,
+ batcher,
+ effect_draw_batches,
+ ) = params.get(world).unwrap();
+ let view_uniform = views.get(view).unwrap();
+ let effects_meta = effects_meta.into_inner();
+ let effect_bind_groups = effect_bind_groups.into_inner();
+ let property_bind_groups = property_bind_groups.into_inner();
+ let meshes = meshes.into_inner();
+ let mesh_allocator = mesh_allocator.into_inner();
+ let effect_draw_batch = effect_draw_batches.get(entity.0).unwrap();
+ let effect_batch = batcher.get(effect_draw_batch.effect_batch_index).unwrap();
+
+ let Some(pipeline) = pipeline_cache.into_inner().get_render_pipeline(pipeline_id) else {
+ trace!("ERROR: Failed to find render pipeline ID {:?}", pipeline_id);
+ return;
+ };
+
+ trace!("render pass");
+
+ pass.set_render_pipeline(pipeline);
+
+ let Some(render_mesh): Option<&RenderMesh> = meshes.get(effect_batch.mesh) else {
+ trace!("Missing render mesh; can't draw. Skipped.");
+ return;
+ };
+ let Some(vertex_buffer_slice) = mesh_allocator.mesh_vertex_slice(&effect_batch.mesh) else {
+ trace!("Missing vertex buffer slice; can't draw. Skipped.");
+ return;
+ };
+
+ // Vertex buffer containing the particle model to draw. Generally a quad.
+ // FIXME - need to upload "vertex_buffer_slice.range.start as i32" into
+ // "base_vertex" in the indirect struct...
+ pass.set_vertex_buffer(0, vertex_buffer_slice.buffer.slice(..));
+
+ // View properties (camera matrix, etc.)
+ pass.set_bind_group(
+ 0,
+ effects_meta.view_bind_group.as_ref().unwrap(),
+ &[view_uniform.offset],
+ );
+
+ // Particles buffer
+ pass.set_bind_group(
+ 1,
+ effect_bind_groups
+ .particle_render(&effect_batch.slab_id)
+ .unwrap(),
+ &[],
+ );
+
+ let Some(indirect_buffer) = effects_meta.draw_indirect_args_buffer.buffer() else {
+ trace!(
+ "The draw indirect buffer containing the indirect draw args is not ready for batch slab_id=#{}. Skipping draw call.",
+ effect_batch.slab_id.index(),
+ );
+ return;
+ };
+
+ let spawner_size = effects_meta.spawner_buffer.aligned_size() as u32;
+ assert!(spawner_size >= GpuSpawnerParams::min_size().get() as u32);
+
+ match render_mesh.buffer_info {
+ RenderMeshBufferInfo::Indexed { index_format, .. } => {
+ let Some(index_buffer_slice) = mesh_allocator.mesh_index_slice(&effect_batch.mesh)
+ else {
+ trace!(
+ "The index buffer for indexed rendering is not ready for batch slab_id=#{}. Skipping draw call.",
+ effect_batch.slab_id.index(),
+ );
+ return;
+ };
+
+ pass.set_index_buffer(index_buffer_slice.buffer.slice(..), index_format);
+ // Note: multi_draw_indexed_indirect() only works if first_instance is
+ // available, which doesn't work without validation in wgpu. This is due to a
+ // limitation in DX12. We could have multidraw in Vulkan only though, but that
+ // requires dynamically switching.
+ // pass.multi_draw_indexed_indirect(
+ // indirect_buffer,
+ // draw_indirect_offset,
+ // effect_batch.effect_count,
+ // );
+ let with_prefix_sum = false; // per-effect, no draw batching
+ trace!(
+ "Emit non-batched draw_indexed_indirect() for {} effect instances...",
+ effect_batch.effect_data.len()
+ );
+ for effect_data in &effect_batch.effect_data {
+ pass.set_bind_group(
+ 2,
+ property_bind_groups
+ .get(&effect_batch.property_key, with_prefix_sum)
+ .unwrap(),
+ &[effect_data.render_batch_info_offset],
+ );
+ let draw_indirect_index = effect_data.draw_indirect_buffer_row_index.0;
+ assert_eq!(GpuDrawIndexedIndirectArgs::SHADER_SIZE.get(), 20);
+ let draw_indirect_offset =
+ draw_indirect_index as u64 * GpuDrawIndexedIndirectArgs::SHADER_SIZE.get();
+ trace!(
+ "+ batch-info @+{}B (row #{}), draw_indirect_offset=+{}B (row #{})",
+ effect_data.render_batch_info_offset,
+ effect_data.render_batch_info_offset / GpuBatchInfo::SHADER_SIZE.get() as u32,
+ draw_indirect_offset,
+ draw_indirect_index,
+ );
+ pass.draw_indexed_indirect(indirect_buffer, draw_indirect_offset);
+ }
+ }
+ RenderMeshBufferInfo::NonIndexed => {
+ // Note: multi_draw_indexed_indirect() only works if first_instance is
+ // available, which doesn't work without validation in wgpu. This is due to a
+ // limitation in DX12. We could have multidraw in Vulkan only though, but that
+ // requires dynamically switching.
+ // pass.multi_draw_indirect(
+ // indirect_buffer,
+ // draw_indirect_offset,
+ // effect_batch.effect_count,
+ // );
+ let with_prefix_sum = false; // per-effect, no draw batching
+ trace!(
+ "Emit non-batched draw_indirect() for {} effect instances...",
+ effect_batch.effect_data.len()
+ );
+ for effect_data in &effect_batch.effect_data {
+ pass.set_bind_group(
+ 2,
+ property_bind_groups
+ .get(&effect_batch.property_key, with_prefix_sum)
+ .unwrap(),
+ &[effect_data.render_batch_info_offset],
+ );
+ let draw_indirect_index = effect_data.draw_indirect_buffer_row_index.0;
+ assert_eq!(GpuDrawIndexedIndirectArgs::SHADER_SIZE.get(), 20);
+ let draw_indirect_offset =
+ draw_indirect_index as u64 * GpuDrawIndexedIndirectArgs::SHADER_SIZE.get();
+ pass.draw_indirect(indirect_buffer, draw_indirect_offset);
+ }
+ }
+ }
+}
+
+#[cfg(feature = "2d")]
+impl Draw<Transparent2d> for DrawEffects {
+ fn draw<'w>(
+ &mut self,
+ world: &'w World,
+ pass: &mut TrackedRenderPass<'w>,
+ view: Entity,
+ item: &Transparent2d,
+ ) -> Result<(), DrawError> {
+ trace!("Draw<Transparent2d>: view={:?}", view);
+ draw(
+ world,
+ pass,
+ view,
+ item.entity,
+ item.pipeline,
+ &mut self.params,
+ );
+ Ok(())
+ }
+}
+
+#[cfg(feature = "3d")]
+impl Draw<Transparent3d> for DrawEffects {
+ fn draw<'w>(
+ &mut self,
+ world: &'w World,
+ pass: &mut TrackedRenderPass<'w>,
+ view: Entity,
+ item: &Transparent3d,
+ ) -> Result<(), DrawError> {
+ trace!("Draw<Transparent3d>: view={:?}", view);
+ draw(
+ world,
+ pass,
+ view,
+ item.entity,
+ item.pipeline,
+ &mut self.params,
+ );
+ Ok(())
+ }
+}
+
+#[cfg(feature = "3d")]
+impl Draw<AlphaMask3d> for DrawEffects {
+ fn draw<'w>(
+ &mut self,
+ world: &'w World,
+ pass: &mut TrackedRenderPass<'w>,
+ view: Entity,
+ item: &AlphaMask3d,
+ ) -> Result<(), DrawError> {
+ trace!("Draw<AlphaMask3d>: view={:?}", view);
+ draw(
+ world,
+ pass,
+ view,
+ item.representative_entity,
+ item.batch_set_key.pipeline,
+ &mut self.params,
+ );
+ Ok(())
+ }
+}
+
+#[cfg(feature = "3d")]
+impl Draw<Opaque3d> for DrawEffects {
+ fn draw<'w>(
+ &mut self,
+ world: &'w World,
+ pass: &mut TrackedRenderPass<'w>,
+ view: Entity,
+ item: &Opaque3d,
+ ) -> Result<(), DrawError> {
+ trace!("Draw<Opaque3d>: view={:?}", view);
+ draw(
+ world,
+ pass,
+ view,
+ item.representative_entity,
+ item.batch_set_key.pipeline,
+ &mut self.params,
+ );
+ Ok(())
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum HanabiPipelineId {
+ Invalid,
+ Cached(CachedComputePipelineId),
+}
+
+#[derive(Debug)]
+pub(crate) enum ComputePipelineError {
+ Queued,
+ Creating,
+ Error,
+}
+
+impl From<&CachedPipelineState> for ComputePipelineError {
+ fn from(value: &CachedPipelineState) -> Self {
+ match value {
+ CachedPipelineState::Queued => Self::Queued,
+ CachedPipelineState::Creating(_) => Self::Creating,
+ CachedPipelineState::Err(_) => Self::Error,
+ _ => panic!("Trying to convert Ok state to error."),
+ }
+ }
+}
+
+pub(crate) struct HanabiComputePass<'a> {
+ /// Pipeline cache to fetch cached compute pipelines by ID.
+ pipeline_cache: &'a PipelineCache,
+ /// WGPU compute pass.
+ compute_pass: ComputePass<'a>,
+ /// Current pipeline (cached).
+ pipeline_id: HanabiPipelineId,
+}
+
+impl<'a> Deref for HanabiComputePass<'a> {
+ type Target = ComputePass<'a>;
+
+ fn deref(&self) -> &Self::Target {
+ &self.compute_pass
+ }
+}
+
+impl DerefMut for HanabiComputePass<'_> {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.compute_pass
+ }
+}
+
+impl<'a> HanabiComputePass<'a> {
+ pub fn new(
+ label: &str,
+ pipeline_cache: &'a PipelineCache,
+ render_context: &'a mut RenderContext,
+ ) -> Self {
+ let compute_pass =
+ render_context
+ .command_encoder()
+ .begin_compute_pass(&ComputePassDescriptor {
+ label: Some(label),
+ timestamp_writes: None,
+ });
+ Self {
+ pipeline_cache,
+ compute_pass,
+ pipeline_id: HanabiPipelineId::Invalid,
+ }
+ }
+
+ pub fn set_cached_compute_pipeline(
+ &mut self,
+ pipeline_id: CachedComputePipelineId,
+ ) -> Result<(), ComputePipelineError> {
+ if HanabiPipelineId::Cached(pipeline_id) == self.pipeline_id {
+ trace!("set_cached_compute_pipeline() id={pipeline_id:?} -> already set; skipped");
+ return Ok(());
+ }
+ trace!("set_cached_compute_pipeline() id={pipeline_id:?}");
+ let Some(pipeline) = self.pipeline_cache.get_compute_pipeline(pipeline_id) else {
+ let state = self.pipeline_cache.get_compute_pipeline_state(pipeline_id);
+ if let CachedPipelineState::Err(err) = state {
+ error!(
+ "Failed to find compute pipeline #{}: {:?}",
+ pipeline_id.id(),
+ err
+ );
+ } else {
+ debug!("Compute pipeline not ready #{}", pipeline_id.id());
+ }
+ return Err(state.into());
+ };
+ self.compute_pass.set_pipeline(pipeline);
+ self.pipeline_id = HanabiPipelineId::Cached(pipeline_id);
+ Ok(())
+ }
+}
+
+fn simulate(
+ mut render_context: RenderContext,
+ pipeline_cache: Res<PipelineCache>,
+ effects_meta: Res<EffectsMeta>,
+ effect_bind_groups: Res<EffectBindGroups>,
+ property_bind_groups: Res<PropertyBindGroups>,
+ sort_bind_groups: Res<SortBindGroups>,
+ utils_pipeline: Res<UtilsPipeline>,
+ effect_cache: Res<EffectCache>,
+ event_cache: Res<EventCache>,
+ gpu_buffer_operations: Res<GpuBufferOperations>,
+ batcher: Res<Batcher>,
+ init_fill_dispatch_queue: Res<InitFillDispatchQueue>,
+) {
+ trace!("simulate()");
+
+ // Make sure to schedule any buffer copy before accessing their content later in
+ // the GPU commands below.
+ {
+ let command_encoder = render_context.command_encoder();
+ effects_meta
+ .dispatch_indirect_args_buffer
+ .write_buffers(command_encoder);
+ effects_meta
+ .draw_indirect_args_buffer
+ .write_buffer(command_encoder);
+ effects_meta
+ .effect_metadata_buffer
+ .write_buffer(command_encoder);
+ event_cache.write_buffers(command_encoder);
+ sort_bind_groups.write_buffers(command_encoder);
+ }
+
+ // Compute init fill dispatch pass - Fill the indirect dispatch structs for any
+ // upcoming init pass of this frame, based on the GPU spawn events emitted by
+ // the update pass of their parent effect during the previous frame.
+ if let Some(queue_index) = init_fill_dispatch_queue.submitted_queue_index.as_ref() {
+ gpu_buffer_operations.dispatch(
+ *queue_index,
+ &mut render_context,
+ &utils_pipeline,
+ Some("hanabi:init_indirect_fill_dispatch"),
+ );
+ }
+
+ // If there's no batch, there's nothing more to do. Avoid continuing because
+ // some GPU resources are missing, which is expected when there's no effect but
+ // is an error (and will log warnings/errors) otherwise.
+ if batcher.is_empty() {
+ return;
+ }
+
+ // Validate that the main buffers and other core resources are available. Avoid
+ // dispatching partial work if not all passes will complete, as this generally
+ // desynchronizes the buffers.
+ let (
+ Some(_),
+ true,
+ Some(indirect_metadata_bind_group),
+ Some(init_and_indirect_sim_params_bind_group),
+ Some(indirect_spawner_bind_group),
+ ) = (
+ effects_meta.spawner_buffer.buffer(),
+ !effects_meta.spawner_buffer.is_empty(),
+ &effects_meta.indirect_metadata_bind_group,
+ &effects_meta.init_and_indirect_sim_params_bind_group,
+ &effects_meta.indirect_spawner_bind_group,
+ )
+ else {
+ trace!("WARN - Some resource not ready, can't simulate this frame.");
+ return;
+ };
+ let Some(prefix_sum_bind_group) = &effects_meta.prefix_sum_bind_group else {
+ trace!("WARN - Prefix sum bind group not ready, can't simulate this frame.");
+ return;
+ };
+ let Some(indirect_buffer) = effects_meta.dispatch_indirect_args_buffer.buffer() else {
+ trace!("WARN - Missing indirect buffer for update pass, can't simulate this frame.");
+ // FIXME - Bevy doesn't allow returning custom errors here...
+ return;
+ };
+
+ // Compute init pass
+ {
+ trace!("init: loop over effect batches...");
+
+ let mut compute_pass =
+ HanabiComputePass::new("hanabi:init", &pipeline_cache, &mut render_context);
+
+ // Bind group simparams@0 is common to everything, only set once per init pass
+ compute_pass.set_bind_group(
+ 0,
+ effects_meta
+ .init_and_indirect_sim_params_bind_group
+ .as_ref()
+ .unwrap(),
+ &[],
+ );
+
+ // Dispatch init compute jobs for all batches
+ for effect_batch in batcher.iter() {
+ // Do not dispatch any init work if there's nothing to spawn this frame for the
+ // batch. Note that this hopefully should have been skipped earlier.
+ {
+ let use_indirect_dispatch = effect_batch
+ .layout_flags
+ .contains(LayoutFlags::CONSUME_GPU_SPAWN_EVENTS);
+ match effect_batch.spawn_info {
+ BatchSpawnInfo::CpuSpawner { total_spawn_count } => {
+ assert!(!use_indirect_dispatch);
+ if total_spawn_count == 0 {
+ continue;
+ }
+ }
+ BatchSpawnInfo::GpuSpawner { .. } => {
+ assert!(use_indirect_dispatch);
+ }
+ }
+ }
+
+ // Fetch bind group particle@1
+ let Some(particle_bind_group) =
+ effect_cache.particle_sim_bind_group(&effect_batch.slab_id)
+ else {
+ error!(
+ "Failed to find init particle@1 bind group for slab #{}",
+ effect_batch.slab_id.index()
+ );
+ continue;
+ };
+
+ // Fetch bind group metadata@3
+ let Some(metadata_bind_group) = effect_bind_groups
+ .init_metadata_bind_groups
+ .get(&effect_batch.slab_id)
+ else {
+ error!(
+ "Failed to find init metadata@3 bind group for slab #{}",
+ effect_batch.slab_id.index()
+ );
+ continue;
+ };
+
+ if compute_pass
+ .set_cached_compute_pipeline(effect_batch.init_and_update_pipeline_ids.init)
+ .is_err()
+ {
+ error!("Failed to set init pipeline");
+ continue;
+ }
+
+ // Compute dynamic offsets
+ let spawner_base = effect_batch.spawner_base;
+ let spawner_aligned_size = effects_meta.spawner_buffer.aligned_size();
+ debug_assert!(spawner_aligned_size >= GpuSpawnerParams::min_size().get() as usize);
+ let spawner_offset = spawner_base * spawner_aligned_size as u32;
+ let batch_info_aligned_size = batcher.batch_info_buffer_aligned_size();
+ let batch_info_offset = effect_batch.batch_info_id * batch_info_aligned_size;
+
+ // Setup init pass
+ compute_pass.set_bind_group(1, particle_bind_group, &[]);
+ compute_pass.set_bind_group(
+ 2,
+ property_bind_groups
+ .get(&effect_batch.property_key, true)
+ .unwrap(),
+ &[batch_info_offset],
+ );
+ compute_pass.set_bind_group(3, &metadata_bind_group.bind_group, &[]);
+
+ // Dispatch init job
+ match effect_batch.spawn_info {
+ // Indirect dispatch via GPU spawn events
+ BatchSpawnInfo::GpuSpawner {
+ init_indirect_dispatch_index,
+ ..
+ } => {
+ assert!(effect_batch
+ .layout_flags
+ .contains(LayoutFlags::CONSUME_GPU_SPAWN_EVENTS));
+
+ // Note: the indirect offset of a dispatch workgroup only needs
+ // 4-byte alignment
+ assert_eq!(GpuDispatchIndirectArgs::min_size().get(), 12);
+ let indirect_offset = init_indirect_dispatch_index as u64 * 12;
+
+ trace!(
+ "record commands for indirect init pipeline of effect {:?} \
+ init_indirect_dispatch_index={} \
+ indirect_offset={} \
+ property_key={:?}...",
+ effect_batch.handle,
+ init_indirect_dispatch_index,
+ indirect_offset,
+ effect_batch.property_key,
+ );
+
+ compute_pass.dispatch_workgroups_indirect(
+ event_cache.init_indirect_dispatch_buffer().unwrap(),
+ indirect_offset,
+ );
+ }
+
+ // Direct dispatch via CPU spawn count
+ BatchSpawnInfo::CpuSpawner {
+ total_spawn_count: spawn_count,
+ } => {
+ assert!(!effect_batch
+ .layout_flags
+ .contains(LayoutFlags::CONSUME_GPU_SPAWN_EVENTS));
+
+ const WORKGROUP_SIZE: u32 = 64;
+ let workgroup_count = spawn_count.div_ceil(WORKGROUP_SIZE);
+
+ trace!(
+ "record commands for init pipeline of effect {:?} \
+ (spawn {} particles => {} workgroups) spawner_base={} \
+ spawner_offset={} \
+ property_key={:?}...",
+ effect_batch.handle,
+ spawn_count,
+ workgroup_count,
+ spawner_base,
+ spawner_offset,
+ effect_batch.property_key,
+ );
+
+ compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
+ }
+ }
+
+ trace!("init compute dispatched");
+ }
+ }
+
+ // Indirect dispatch compute pass
+ {
+ // Only start a compute pass if there's an effect; makes things clearer in
+ // debugger.
+ let mut compute_pass = HanabiComputePass::new(
+ "hanabi:indirect_dispatch",
+ &pipeline_cache,
+ &mut render_context,
+ );
+
+ // Dispatch indirect dispatch compute job
+ trace!("record commands for indirect dispatch pipeline...");
+
+ let has_gpu_spawn_events = !event_cache.child_infos().is_empty();
+ if has_gpu_spawn_events {
+ if let Some(indirect_child_info_buffer_bind_group) =
+ event_cache.indirect_child_info_buffer_bind_group()
+ {
+ assert!(has_gpu_spawn_events);
+ compute_pass.set_bind_group(3, indirect_child_info_buffer_bind_group, &[]);
+ } else {
+ error!("Missing child_info_buffer@3 bind group for the vfx_indirect pass.");
+ compute_pass.insert_debug_marker("ERROR:MissingIndirectBindGroup3");
+ // FIXME - Bevy doesn't allow returning custom errors here...
+ return;
+ }
+ }
+
+ if compute_pass
+ .set_cached_compute_pipeline(effects_meta.active_indirect_pipeline_id)
+ .is_err()
+ {
+ compute_pass.insert_debug_marker("ERROR:FailedToSetIndirectComputePipeline");
+ // FIXME - Bevy doesn't allow returning custom errors here...
+ return;
+ }
+
+ //error!("FIXME - effect_metadata_buffer has gaps!!!! this won't work. len() is
+ // the size exluding gaps!");
+ const WORKGROUP_SIZE: u32 = 64;
+ //let total_effect_count = effects_meta.effect_metadata_buffer.len();
+ let total_effect_count = effects_meta.spawner_buffer.len() as u32;
+ let workgroup_count = total_effect_count.div_ceil(WORKGROUP_SIZE);
+
+ // Setup vfx_indirect pass
+ compute_pass.set_bind_group(0, init_and_indirect_sim_params_bind_group, &[]);
+ compute_pass.set_bind_group(1, indirect_metadata_bind_group, &[]);
+ compute_pass.set_bind_group(2, indirect_spawner_bind_group, &[]);
+ compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
+ trace!(
+ "indirect dispatch compute dispatched: total_effect_count={} workgroup_count={}",
+ total_effect_count,
+ workgroup_count
+ );
+ }
+
+ // Update prefix sum compute pass
+ //
+ // Compute the prefix sum of alive particles before the update pass, so that we
+ // can dispatch batches of effects in the update pass. The alive count is
+ // copied into the prefix sum buffer during the indirect dispatch pass just
+ // before.
+ {
+ let mut compute_pass = HanabiComputePass::new(
+ "hanabi:update_prefix_sum",
+ &pipeline_cache,
+ &mut render_context,
+ );
+
+ trace!("record commands for update prefix sum pipeline...");
+
+ if compute_pass
+ .set_cached_compute_pipeline(effects_meta.prefix_sum_pipeline_id)
+ .is_err()
+ {
+ // FIXME - Bevy doesn't allow returning custom errors here...
+ trace!("ERROR - Failed to set prefix sum compute pipeline. Simulation aborted.");
+ return;
+ }
+
+ // Dispatch one thread per effect batch, to calculate the prefix sum of the
+ // number of particles to update per effect in that batch.
+ const WORKGROUP_SIZE: u32 = 64;
+ let total_batch_count = batcher.len() as u32;
+ let workgroup_count = total_batch_count.div_ceil(WORKGROUP_SIZE);
+
+ // Setup vfx_prefix_sum pass
+ compute_pass.set_bind_group(0, prefix_sum_bind_group, &[]);
+ compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
+ trace!(
+ "prefix sum dispatched: total_batch_count={} workgroup_count={}",
+ total_batch_count,
+ workgroup_count
+ );
+ }
+
+ // Update compute pass
+ //
+ // Simulate all alive particles.
+ let mut needs_sort = false;
+ {
+ let mut compute_pass =
+ HanabiComputePass::new("hanabi:update", &pipeline_cache, &mut render_context);
+
+ // Bind group simparams@0 is common to everything, only set once per update pass
+ compute_pass.set_bind_group(
+ 0,
+ effects_meta.update_sim_params_bind_group.as_ref().unwrap(),
+ &[],
+ );
+
+ // Dispatch update compute jobs
+ for effect_batch in batcher.iter() {
+ // Remember if we need to sort any effect, for next pass
+ if effect_batch.layout_flags.raea_sorted() { // raea: and blended effects (#52)
+ needs_sort = true;
+ }
+
+ // Fetch bind group particle@1
+ let Some(particle_bind_group) =
+ effect_cache.particle_sim_bind_group(&effect_batch.slab_id)
+ else {
+ error!(
+ "Failed to find update particle@1 bind group for slab #{}",
+ effect_batch.slab_id.index()
+ );
+ compute_pass.insert_debug_marker("ERROR:MissingParticleSimBindGroup");
+ continue;
+ };
+
+ // Fetch bind group metadata@3
+ let Some(metadata_bind_group) = effect_bind_groups
+ .update_metadata_bind_groups
+ .get(&effect_batch.slab_id)
+ else {
+ error!(
+ "Failed to find update metadata@3 bind group for slab #{}",
+ effect_batch.slab_id.index()
+ );
+ compute_pass.insert_debug_marker("ERROR:MissingMetadataBindGroup");
+ continue;
+ };
+
+ // Fetch compute pipeline
+ if let Err(err) = compute_pass
+ .set_cached_compute_pipeline(effect_batch.init_and_update_pipeline_ids.update)
+ {
+ compute_pass.insert_debug_marker(&format!(
+ "ERROR:FailedToSetCachedUpdatePipeline:{:?}",
+ err
+ ));
+ continue;
+ }
+
+ // Compute dynamic offsets
+ let batch_info_aligned_size = batcher.batch_info_buffer_aligned_size();
+ let batch_info_offset = effect_batch.batch_info_id * batch_info_aligned_size;
+ trace!(
+ "record commands for update pipeline of effect {:?} spawner_base={} batch_info_id={} batch_info_offset={}B",
+ effect_batch.handle,
+ effect_batch.spawner_base,
+ effect_batch.batch_info_id,
+ batch_info_offset,
+ );
+
+ // Setup update pass
+ compute_pass.set_bind_group(1, particle_bind_group, &[]);
+ compute_pass.set_bind_group(
+ 2,
+ property_bind_groups
+ .get(&effect_batch.property_key, true)
+ .unwrap(),
+ &[batch_info_offset],
+ );
+ compute_pass.set_bind_group(3, &metadata_bind_group.bind_group, &[]);
+
+ // Dispatch update job
+ let dispatch_indirect_offset =
+ effect_batch.batch_info_id * GpuDispatchIndirectArgs::SHADER_SIZE.get() as u32;
+ trace!(
+ "dispatch_workgroups_indirect: buffer={:?} offset={}B",
+ indirect_buffer,
+ dispatch_indirect_offset,
+ );
+ compute_pass
+ .dispatch_workgroups_indirect(indirect_buffer, dispatch_indirect_offset as u64);
+
+ trace!("update compute dispatched");
+ }
+ }
+
+ // Do sorting for ribbons
+ if needs_sort {
+ // Copy alive counts for sort prefix sum compute pass
+ //
+ // After the update pass (atomically) updated the particle alive count per
+ // effect instance, copy that number into the prefix sum buffer, so that
+ // the prefix sum pass can calculate the prefix sum for sorting.
+ let Some(queue_index) = batcher.sort_fill_prefix_sum_queue_index else {
+ warn!("Missing alive count copy queue for ribbon sorting.");
+ return;
+ };
+ gpu_buffer_operations.dispatch(
+ queue_index,
+ &mut render_context,
+ &utils_pipeline,
+ Some("hanabi:sort_fill_prefix_sum"),
+ );
+
+ // Sort prefix sum compute pass
+ //
+ // Calculate the prefix sum of the number of alive particles to sort.
+ {
+ let mut compute_pass = HanabiComputePass::new(
+ "hanabi:sort_prefix_sum",
+ &pipeline_cache,
+ &mut render_context,
+ );
+
+ trace!("record commands for sort prefix sum pass...");
+
+ if compute_pass
+ .set_cached_compute_pipeline(effects_meta.prefix_sum_pipeline_id)
+ .is_err()
+ {
+ // FIXME - Bevy doesn't allow returning custom errors here...
+ trace!("ERROR - Failed to set prefix sum compute pipeline. Simulation aborted.");
+ return;
+ }
+
+ // Dispatch one thread per init effect batch.
+ const WORKGROUP_SIZE: u32 = 64;
+ // Note: This only works because we use the same batches for the init and update
+ // passes. A priori there's no reason why we couldn't split them, since likely
+ // the batches would be different.
+ let total_batch_count = batcher.len() as u32;
+ let workgroup_count = total_batch_count.div_ceil(WORKGROUP_SIZE);
+
+ // Setup vfx_prefix_sum pass
+ compute_pass.set_bind_group(0, prefix_sum_bind_group, &[]);
+ compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
+ trace!(
+ "prefix sum dispatched: total_batch_count={} workgroup_count={}",
+ total_batch_count,
+ workgroup_count
+ );
+ }
+
+ // Compute sort fill dispatch pass - Fill the indirect dispatch structs for any
+ // batch of particles which needs sorting, based on the actual number of alive
+ // particles in the batch after their update in the compute update pass. Since
+ // particles may die during update, this may be different from the number of
+ // particles updated.
+ let Some(queue_index) = batcher.fill_dispatch_queue_index else {
+ warn!("Missing indirect dispatch queue for ribbon sorting (fill).");
+ return;
+ };
+ gpu_buffer_operations.dispatch(
+ queue_index,
+ &mut render_context,
+ &utils_pipeline,
+ Some("hanabi:sort_fill_dispatch"),
+ );
+
+ // Compute sort sort dispatch pass - Fill the indirect dispatch structs for any
+ // batch of particles which needs sorting, based on the actual number of alive
+ // particles in the batch after their update in the compute update pass. Since
+ // particles may die during update, this may be different from the number of
+ // particles updated.
+ let Some(queue_index) = batcher.sort_dispatch_queue_index else {
+ warn!("Missing indirect dispatch queue for ribbon sorting (sort).");
+ return;
+ };
+ gpu_buffer_operations.dispatch(
+ queue_index,
+ &mut render_context,
+ &utils_pipeline,
+ Some("hanabi:sort_sort_dispatch"),
+ );
+
+ // Compute sort pass
+ {
+ let effect_metadata_buffer = effects_meta.effect_metadata_buffer.buffer().unwrap();
+ let indirect_args_buffer = sort_bind_groups.indirect_args_buffer().unwrap();
+
+ // Loop on batches and find those which need sorting
+ for effect_batch in batcher.iter() {
+ if !effect_batch.layout_flags.raea_sorted() { // raea: and blended effects (#52)
+ continue;
+ }
+ trace!("Processing RIBBONS effect batch for sorting...");
+ // raea: a blended effect sorts by POSITION and needs neither (#52)
+ if effect_batch.layout_flags.contains(LayoutFlags::RIBBONS) {
+ assert!(effect_batch.particle_layout.contains(Attribute::RIBBON_ID));
+ assert!(effect_batch.particle_layout.contains(Attribute::AGE)); // or is that optional?
+ }
+
+ let Some(effect_buffer) = effect_cache.get_slab(&effect_batch.slab_id) else {
+ warn!("Missing sort-fill effect buffer.");
+ continue;
+ };
+
+ // Loop on individual effects instances in the batch. Currently we can't sort an
+ // entire batch at once, only a single instance. This is in part because each
+ // instance already requires 2 keys to sort (RIBBON_ID + AGE), and it's not
+ // clear that adding a third key is faster than doing multiple dispatches.
+ for (effect_index, effect_data) in effect_batch.effect_data.iter().enumerate() {
+ let Some(fill_indirect_dispatch_index) =
+ effect_data.sort_fill_indirect_dispatch_index
+ else {
+ continue;
+ };
+ let Some(sort_indirect_dispatch_index) =
+ effect_data.sort_indirect_dispatch_index
+ else {
+ continue;
+ };
+ let fill_indirect_offset = sort_bind_groups
+ .get_indirect_args_byte_offset(fill_indirect_dispatch_index);
+ let sort_indirect_offset = sort_bind_groups
+ .get_indirect_args_byte_offset(sort_indirect_dispatch_index);
+
+ // Fill the sort buffer with the key-value pairs to sort
+ {
+ let mut compute_pass = HanabiComputePass::new(
+ "hanabi:sort_fill",
+ &pipeline_cache,
+ &mut render_context,
+ );
+ compute_pass.push_debug_group("hanabi:sort_fill");
+
+ let Some(pipeline_id) = sort_bind_groups
+ .get_sort_fill_pipeline_id(&effect_batch.particle_layout)
+ else {
+ warn!("Missing sort-fill pipeline.");
+ compute_pass.insert_debug_marker("ERROR:MissingSortFillPipeline");
+ continue;
+ };
+ if compute_pass
+ .set_cached_compute_pipeline(pipeline_id)
+ .is_err()
+ {
+ compute_pass.insert_debug_marker("ERROR:FailedToSetSortFillPipeline");
+ compute_pass.pop_debug_group();
+ return;
+ }
+
+ let spawner_aligned_size = effects_meta.spawner_buffer.aligned_size();
+ assert!(
+ spawner_aligned_size >= GpuSpawnerParams::min_size().get() as usize
+ );
+ let spawner_offset = (effect_batch.spawner_base + effect_index as u32)
+ * spawner_aligned_size as u32;
+
+ let particle_buffer = effect_buffer.particle_buffer();
+ let indirect_index_buffer = effect_buffer.indirect_index_buffer();
+ let Some(spawner_buffer) = effects_meta.spawner_buffer.buffer() else {
+ warn!("Missing spawner buffer for sort-fill.");
+ compute_pass.insert_debug_marker("ERROR:MissingSortFillSpawnerBuffer");
+ continue;
+ };
+ let Some(bind_group) = sort_bind_groups.sort_fill_bind_group(
+ particle_buffer.id(),
+ indirect_index_buffer.id(),
+ effect_metadata_buffer.id(),
+ spawner_buffer.id(),
+ effects_meta.sim_params_uniforms.buffer().unwrap().id(), // raea: (#52)
+ ) else {
+ warn!("Missing sort-fill bind group.");
+ compute_pass.insert_debug_marker("ERROR:MissingSortFillBindGroup");
+ continue;
+ };
+ compute_pass.set_bind_group(0, bind_group, &[spawner_offset]);
+
+ compute_pass.dispatch_workgroups_indirect(
+ indirect_args_buffer,
+ fill_indirect_offset,
+ );
+ compute_pass.pop_debug_group();
+ }
+
+ // Block-sort particles
+ {
+ let mut compute_pass = HanabiComputePass::new(
+ "hanabi:sort",
+ &pipeline_cache,
+ &mut render_context,
+ );
+ compute_pass.push_debug_group("hanabi:sort");
+
+ if compute_pass
+ .set_cached_compute_pipeline(sort_bind_groups.sort_pipeline_id())
+ .is_err()
+ {
+ compute_pass.insert_debug_marker("ERROR:FailedToSetSortPipeline");
+ compute_pass.pop_debug_group();
+ return;
+ }
+
+ let Some(bind_group) = sort_bind_groups.sort_bind_group() else {
+ warn!("Missing sort bind group.");
+ compute_pass.insert_debug_marker("ERROR:MissingSortBindGroup");
+ continue;
+ };
+ compute_pass.set_bind_group(0, bind_group, &[]);
+ compute_pass.dispatch_workgroups_indirect(
+ indirect_args_buffer,
+ sort_indirect_offset,
+ );
+
+ compute_pass.pop_debug_group();
+ }
+
+ // If the number of particles is larger than the block size (1024), we need to
+ // dispatch mergesort passes to merge pairs of lists until the full list is
+ // sorted. Since we don't know (from CPU) the number of particles, and so the
+ // number of required passes, we over-estimate from the total effect capacity.
+ let block_size = 1024; // see shader
+ let num_blocks = effect_batch.capacity.div_ceil(block_size);
+ let num_passes = if num_blocks > 1 {
+ 32 - (num_blocks - 1).leading_zeros() // log2(n-1) rounded up
+ } else {
+ 0
+ };
+ if num_passes > 0 {
+ let pipeline_id = sort_bind_groups.sort_merge_pipeline_id();
+ let Some(bind_group) = sort_bind_groups.sort_merge_bind_group() else {
+ warn!("Missing sort bind group.");
+ return;
+ };
+
+ let mut num_lists = num_blocks;
+ for ipass in 0..num_passes {
+ // A separate compute pass provides the storage-buffer visibility
+ // guarantee required before the next ping-pong merge stage reads
+ // this stage's output.
+ let mut compute_pass = HanabiComputePass::new(
+ "hanabi:sort_merge",
+ &pipeline_cache,
+ &mut render_context,
+ );
+ compute_pass.push_debug_group("hanabi:sort_merge");
+ if compute_pass
+ .set_cached_compute_pipeline(pipeline_id)
+ .is_err()
+ {
+ compute_pass
+ .insert_debug_marker("ERROR:FailedToSetSortMergePipeline");
+ compute_pass.pop_debug_group();
+ return;
+ }
+
+ let offset = sort_bind_groups.merge_params_buffer().dynamic_offset(
+ SortBindGroups::COPY_SOURCE_PARAM_COUNT + ipass as usize,
+ );
+ compute_pass.set_bind_group(0, bind_group, &[offset]);
+
+ // For now, each thread serially merges a pair of lists. A final
+ // unpaired list is copied to the other ping-pong half.
+ let num_threads = num_lists.div_ceil(2);
+ let num_workgroups = num_threads.div_ceil(64);
+ compute_pass.dispatch_workgroups(num_workgroups, 1, 1);
+
+ compute_pass.pop_debug_group();
+ num_lists = num_lists.div_ceil(2);
+ }
+ }
+
+ // Copy the sorted indices back into the indirect index buffer.
+ {
+ let mut compute_pass = HanabiComputePass::new(
+ "hanabi:sort_copy",
+ &pipeline_cache,
+ &mut render_context,
+ );
+ compute_pass.push_debug_group("hanabi:copy_sorted_indices");
+
+ let pipeline_id = sort_bind_groups.sort_copy_pipeline_id();
+ if compute_pass
+ .set_cached_compute_pipeline(pipeline_id)
+ .is_err()
+ {
+ compute_pass.insert_debug_marker("ERROR:FailedToSetSortCopyPipeline");
+ compute_pass.pop_debug_group();
+ return;
+ }
+
+ let spawner_aligned_size = effects_meta.spawner_buffer.aligned_size();
+ assert!(
+ spawner_aligned_size >= GpuSpawnerParams::min_size().get() as usize
+ );
+ let spawner_offset = (effect_batch.spawner_base + effect_index as u32)
+ * spawner_aligned_size as u32;
+
+ let indirect_index_buffer = effect_buffer.indirect_index_buffer();
+ let Some(spawner_buffer) = effects_meta.spawner_buffer.buffer() else {
+ warn!("Missing spawner buffer for sort-copy.");
+ compute_pass.insert_debug_marker("ERROR:MissingSortCopySpawnerBuffer");
+ continue;
+ };
+ let Some(bind_group) = sort_bind_groups.sort_copy_bind_group(
+ indirect_index_buffer.id(),
+ effect_metadata_buffer.id(),
+ spawner_buffer.id(),
+ ) else {
+ warn!("Missing sort-copy bind group.");
+ compute_pass.insert_debug_marker("ERROR:MissingSortCopyBindGroup");
+ continue;
+ };
+ let copy_source_offset = sort_bind_groups
+ .merge_params_buffer()
+ .dynamic_offset(num_passes as usize % 2);
+ compute_pass.set_bind_group(
+ 0,
+ bind_group,
+ &[spawner_offset, copy_source_offset],
+ );
+
+ compute_pass.dispatch_workgroups_indirect(
+ indirect_args_buffer,
+ fill_indirect_offset,
+ );
+
+ compute_pass.pop_debug_group();
+ }
+
+ // The sort-fill pass uses this counter as an atomic append index. It must
+ // remain valid through the block-sort, merge, and copy passes, then be
+ // cleared before sorting the next effect instance.
+ render_context.command_encoder().clear_buffer(
+ sort_bind_groups.sort_buffer(),
+ 0,
+ Some(4),
+ );
+ }
+ }
+ }
+ }
+}
+
+impl From<LayoutFlags> for ParticleRenderAlphaMaskPipelineKey {
+ fn from(layout_flags: LayoutFlags) -> Self {
+ if layout_flags.contains(LayoutFlags::USE_ALPHA_MASK) {
+ ParticleRenderAlphaMaskPipelineKey::AlphaMask
+ } else if layout_flags.contains(LayoutFlags::OPAQUE) {
+ ParticleRenderAlphaMaskPipelineKey::Opaque
+ } else {
+ ParticleRenderAlphaMaskPipelineKey::Blend
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn layout_flags() {
+ let flags = LayoutFlags::default();
+ assert_eq!(flags, LayoutFlags::NONE);
+ }
+
+ #[cfg(feature = "gpu_tests")]
+ #[test]
+ fn gpu_ops_ifda() {
+ use crate::test_utils::MockRenderer;
+
+ let renderer = MockRenderer::new();
+ let device = renderer.device();
+ let render_queue = renderer.queue();
+
+ let mut world = World::new();
+ world.insert_resource(device.clone());
+ let mut buffer_ops = GpuBufferOperations::from_world(&mut world);
+
+ let src_buffer = device.create_buffer(&BufferDescriptor {
+ label: None,
+ size: 256,
+ usage: BufferUsages::STORAGE,
+ mapped_at_creation: false,
+ });
+ let dst_buffer = device.create_buffer(&BufferDescriptor {
+ label: None,
+ size: 256,
+ usage: BufferUsages::STORAGE,
+ mapped_at_creation: false,
+ });
+
+ // Two consecutive ops can be merged. This includes having contiguous slices
+ // both in source and destination.
+ buffer_ops.begin_frame();
+ {
+ let mut q = InitFillDispatchQueue::default();
+ q.enqueue(0, 0);
+ assert_eq!(q.queue.len(), 1);
+ q.enqueue(1, 1);
+ // Ops are not batched yet
+ assert_eq!(q.queue.len(), 2);
+ // On submit, the ops get batched together
+ q.submit(&src_buffer, &dst_buffer, &mut buffer_ops);
+ assert_eq!(buffer_ops.args_buffer.len(), 1);
+ }
+ buffer_ops.end_frame(&device, &render_queue);
+
+ // Even if out of order, the init fill dispatch ops are batchable. Here the
+ // offsets are enqueued inverted.
+ buffer_ops.begin_frame();
+ {
+ let mut q = InitFillDispatchQueue::default();
+ q.enqueue(1, 1);
+ assert_eq!(q.queue.len(), 1);
+ q.enqueue(0, 0);
+ // Ops are not batched yet
+ assert_eq!(q.queue.len(), 2);
+ // On submit, the ops get batched together
+ q.submit(&src_buffer, &dst_buffer, &mut buffer_ops);
+ assert_eq!(buffer_ops.args_buffer.len(), 1);
+ }
+ buffer_ops.end_frame(&device, &render_queue);
+
+ // However, both the source and destination need to be contiguous at the same
+ // time. Here they are mixed so we can't batch.
+ buffer_ops.begin_frame();
+ {
+ let mut q = InitFillDispatchQueue::default();
+ q.enqueue(0, 1);
+ assert_eq!(q.queue.len(), 1);
+ q.enqueue(1, 0);
+ // Ops are not batched yet
+ assert_eq!(q.queue.len(), 2);
+ // On submit, the ops cannot get batched together
+ q.submit(&src_buffer, &dst_buffer, &mut buffer_ops);
+ assert_eq!(buffer_ops.args_buffer.len(), 2);
+ }
+ buffer_ops.end_frame(&device, &render_queue);
+ }
+}
diff --git a/vendor/bevy_hanabi/src/render/property.rs b/vendor/bevy_hanabi/src/render/property.rs
new file mode 100644
index 00000000..ef4a3e3e
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/property.rs
@@ -0,0 +1,1435 @@
+use std::{
+ num::{NonZeroU32, NonZeroU64},
+ ops::Range,
+};
+
+use bevy::{
+ asset::Handle,
+ ecs::{lifecycle::Remove, observer::On, query::Without, system::Commands, world::Mut},
+ image::Image,
+ log::{error, trace},
+ platform::collections::{hash_map::EntryRef, HashMap},
+ prelude::{Component, Entity, Query, Res, ResMut, Resource},
+ render::{
+ render_asset::RenderAssets,
+ render_resource::{
+ binding_types::{storage_buffer_read_only, storage_buffer_read_only_sized},
+ BindGroup, BindGroupEntries, BindGroupLayoutDescriptor, BindGroupLayoutEntries, Buffer,
+ PipelineCache, ShaderSize,
+ },
+ renderer::{RenderDevice, RenderQueue},
+ texture::GpuImage,
+ },
+ utils::default,
+};
+use bytemuck::{cast_slice, Pod};
+use wgpu::{
+ BindGroupEntry, BindingResource, BufferAddress, BufferBinding, BufferDescriptor, BufferUsages,
+ ShaderStages,
+};
+
+use super::effect_cache::SlabState;
+use crate::{
+ render::{
+ ExtractedEffect, ExtractedProperties, GpuBatchInfo, GpuSpawnerParams, Material,
+ StorageType as _,
+ },
+ PropertyLayout, TextureLayout,
+};
+
+/// Allocation into the [`PropertyCache`] for an effect instance. This component
+/// is only present on an effect instance if that effect uses properties.
+#[derive(Debug, Clone, PartialEq, Eq, Component)]
+pub struct CachedEffectProperties {
+ /// Property layout.
+ pub property_layout: PropertyLayout,
+ /// Index of the [`PropertyBuffer`] inside the [`PropertyCache`].
+ pub buffer_index: u32,
+ /// Array index inside the GPU buffer where the properties struct with the
+ /// current layout is allocated.
+ pub array_index: u32,
+}
+
+impl CachedEffectProperties {
+ /// Convert this allocation into a bind group key, used for bind group
+ /// re-creation when a change is detected in the key.
+ pub fn to_key(&self) -> PropertyBindGroupKey {
+ let binding_size = self.property_layout.min_binding_size().get() as u32;
+ PropertyBindGroupKey {
+ buffer_index: self.buffer_index,
+ binding_size,
+ ..default()
+ }
+ }
+}
+
+/// Error code for [`PropertyCache::remove_properties()`].
+#[derive(Debug)]
+pub enum CachedPropertiesError {
+ /// The given buffer index is invalid. The [`PropertyCache`] doesn't contain
+ /// any buffer with such index.
+ InvalidBufferIndex(u32),
+ /// The given buffer index corresponds to a [`PropertyCache`] buffer which
+ /// was already deallocated.
+ BufferDeallocated(u32),
+}
+
+/// Single free byte range inside a [`PropertyBuffer`].
+#[derive(Debug, Clone, PartialEq, Eq)]
+struct FreeRange(pub Range<u32>);
+
+impl PartialOrd for FreeRange {
+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+ Some(self.cmp(other))
+ }
+}
+
+impl Ord for FreeRange {
+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+ self.0.start.cmp(&other.0.start)
+ }
+}
+
+#[derive(Debug)]
+pub(crate) struct PropertyBuffer {
+ /// Pending values accumulated on CPU and not yet written to GPU.
+ values: Vec<u8>,
+ /// GPU buffer if already allocated, or `None` otherwise.
+ buffer: Option<Buffer>,
+ /// Capacity of the buffer, in bytes.
+ capacity: usize,
+ /// GPU buffer name, for debugging.
+ label: String,
+ /// Free ranges available for re-allocation (in bytes).
+ free_ranges: Vec<FreeRange>,
+ /// Is the GPU buffer stale and the CPU one need to be re-uploaded?
+ is_stale: bool,
+ buffer_usages: BufferUsages,
+}
+
+impl PropertyBuffer {
+ /// Create a new property buffer.
+ ///
+ /// The GPU resources are not yet allocated.
+ pub fn new(label: Option<String>, buffer_usages: BufferUsages) -> Self {
+ let label = label.unwrap_or("hanabi:buffer:properties".to_string());
+ trace!("PropertyBuffer['{}']::new()", label);
+ Self {
+ values: vec![],
+ buffer: None,
+ capacity: 0,
+ label,
+ free_ranges: vec![],
+ is_stale: true,
+ buffer_usages,
+ }
+ }
+
+ /// Get the GPU buffer, if allocated.
+ #[inline]
+ pub fn buffer(&self) -> Option<&Buffer> {
+ self.buffer.as_ref()
+ }
+
+ /// Get a binding for the entire buffer.
+ #[allow(dead_code)]
+ #[inline]
+ pub fn max_binding(&self) -> Option<BindingResource<'_>> {
+ // FIXME - Return a Buffer wrapper first, which can be unwrapped, then from that
+ // wrapper implement all the xxx_binding() helpers. That avoids a bunch of "if
+ // let Some()" everywhere when we know the buffer is valid. The only reason the
+ // buffer might not be valid is if it was not created, and in that case
+ // we wouldn't be calling the xxx_bindings() helpers, we'd have earlied out
+ // before.
+ let buffer = self.buffer()?;
+ Some(BindingResource::Buffer(BufferBinding {
+ buffer,
+ offset: 0,
+ size: None, // entire buffer
+ }))
+ }
+
+ /// Capacity of the allocated GPU buffer, in bytes.
+ ///
+ /// This may be zero if the buffer was not allocated yet. In general, this
+ /// can differ from the actual data size cached on CPU and waiting to be
+ /// uploaded to GPU.
+ #[inline]
+ #[allow(dead_code)]
+ pub fn capacity(&self) -> usize {
+ self.capacity
+ }
+
+ /// Current buffer size, in bytes.
+ ///
+ /// This represents the size of the CPU data uploaded to GPU. Pending a GPU
+ /// buffer re-allocation or re-upload, this size might differ from the
+ /// actual GPU buffer size. But they're eventually consistent.
+ #[inline]
+ pub fn len(&self) -> usize {
+ self.values.len()
+ }
+
+ #[inline]
+ #[allow(dead_code)]
+ pub fn is_empty(&self) -> bool {
+ self.values.is_empty()
+ }
+
+ /// Allocate storage for a property struct of the given size.
+ ///
+ /// The allocation is guaranteed to be aligned to the size itself. That
+ /// means that the returned byte offset is such that `offset % size == 0`.
+ /// This ensures `offset / size` forms a valid integral array index.
+ fn alloc_aligned(&mut self, size: u32) -> u32 {
+ self.is_stale = true;
+
+ // Try to find a free block which can accomodate it, and pick the
+ // smallest one in order to limit wasted space.
+ let mut best_slot: Option<(u32, usize)> = None;
+ for (index, range) in self.free_ranges.iter().enumerate() {
+ // Align the expected alloc start
+ let aligned_start = range.0.start.next_multiple_of(size);
+ if aligned_start >= range.0.end {
+ continue;
+ }
+ let align_padding = aligned_start - range.0.start;
+
+ // Check the remaining size
+ let free_size = range.0.end - aligned_start;
+ if free_size < size {
+ continue;
+ }
+
+ // If we found a slot with the exact size, just use it already
+ let wasted_size = (free_size - size) + align_padding;
+ if wasted_size == 0 {
+ best_slot = Some((0, index));
+ break;
+ }
+
+ // Otherwise try to find the smallest oversized slot to reduce wasted space
+ if let Some(best_slot) = best_slot.as_mut() {
+ if wasted_size < best_slot.0 {
+ *best_slot = (wasted_size, index);
+ }
+ } else {
+ best_slot = Some((wasted_size, index));
+ }
+ }
+
+ // Insert into existing space
+ if let Some((_, index)) = best_slot {
+ let range = self.free_ranges[index].0.clone();
+
+ let aligned_start = range.start.next_multiple_of(size);
+ let free_size = range.end - aligned_start;
+ assert!(size <= free_size);
+
+ let padding_bytes = aligned_start - range.start;
+ if padding_bytes > 0 {
+ // If the allocation doesn't span the entire free space, splice it.
+ self.free_ranges[index].0.end = aligned_start;
+ } else if size < free_size {
+ self.free_ranges[index].0.start += size;
+ } else {
+ // Otherwise, steal the entire block
+ self.free_ranges.remove(index);
+ }
+
+ debug_assert!(aligned_start.is_multiple_of(size));
+ aligned_start
+ }
+ // Insert at end of vector, after resizing it
+ else {
+ // Calculate new aligned insertion offset and new capacity
+ let old_len = self.values.len() as u32;
+ let aligned_start = old_len.next_multiple_of(size);
+ let new_capacity = aligned_start + size;
+ if new_capacity > old_len {
+ self.values.resize(new_capacity as usize, 0);
+ }
+
+ // Insert padding if needed (and mark as free)
+ if aligned_start > old_len {
+ self.free_ranges.push(FreeRange(old_len..aligned_start));
+ }
+
+ aligned_start
+ }
+ }
+
+ /// Remove a range of bytes previously added.
+ ///
+ /// Remove a range of bytes previously returned by adding one or more
+ /// elements with [`push()`] or [`push_many()`].
+ ///
+ /// # Returns
+ ///
+ /// Returns `true` if the range was valid and the corresponding data was
+ /// removed, or `false` otherwise. In that case, the buffer is not modified.
+ ///
+ /// [`push()`]: Self::push
+ /// [`push_many()`]: Self::push_many
+ fn remove(&mut self, range: Range<u32>) -> bool {
+ // Check for out of bounds argument
+ let end = self.values.len() as u32;
+ if range.start >= end || range.end > end {
+ return false;
+ }
+
+ if range.end == end {
+ // Walk the (sorted) free list to also dequeue any range which is now at the end
+ // of the buffer
+ let mut new_end = range.start;
+ while let Some(free_range) = self.free_ranges.pop() {
+ if free_range.0.end == new_end {
+ new_end = free_range.0.start;
+ } else {
+ self.free_ranges.push(free_range);
+ break;
+ }
+ }
+
+ // Note: we can't really recover any padding here because we don't know the
+ // exact size of that allocation, only its row-aligned size.
+ if new_end > 0 {
+ self.values.truncate(new_end as usize);
+ } else {
+ self.values.clear();
+ }
+ } else {
+ // Otherwise, save the row into the free list.
+ let free_range = FreeRange(range);
+
+ // Insert as sorted
+ if self.free_ranges.is_empty() {
+ // Special case to simplify below, and to avoid binary_search()
+ self.free_ranges.push(free_range);
+ } else if let Err(index) = self.free_ranges.binary_search(&free_range) {
+ if index >= self.free_ranges.len() {
+ // insert at end
+ let prev = self.free_ranges.last_mut().unwrap(); // known
+ if prev.0.end == free_range.0.start {
+ // merge with last value
+ prev.0.end = free_range.0.end;
+ } else {
+ // insert last, with gap
+ self.free_ranges.push(free_range);
+ }
+ } else if index == 0 {
+ // insert at start
+ let next = &mut self.free_ranges[0];
+ if free_range.0.end == next.0.start {
+ // merge with next
+ next.0.start = free_range.0.start;
+ } else {
+ // insert first, with gap
+ self.free_ranges.insert(0, free_range);
+ }
+ } else {
+ // insert between 2 existing elements
+ let prev = &mut self.free_ranges[index - 1];
+ if prev.0.end == free_range.0.start {
+ // merge with previous value
+ prev.0.end = free_range.0.end;
+
+ let prev = self.free_ranges[index - 1].clone();
+ let next = &mut self.free_ranges[index];
+ if prev.0.end == next.0.start {
+ // also merge prev with next, and remove prev
+ next.0.start = prev.0.start;
+ self.free_ranges.remove(index - 1);
+ }
+ } else {
+ let next = &mut self.free_ranges[index];
+ if free_range.0.end == next.0.start {
+ // merge with next value
+ next.0.start = free_range.0.start;
+ } else {
+ // insert between 2 values, with gaps on both sides
+ self.free_ranges.insert(0, free_range);
+ }
+ }
+ }
+ } else {
+ // The range exists in the free list, this means it's already removed. This is a
+ // duplicate; ignore it.
+ return false;
+ }
+ }
+ self.is_stale = true;
+ true
+ }
+
+ /// Update an allocated entry with a new value.
+ #[allow(dead_code)]
+ #[inline]
+ pub fn update<T: Pod + ShaderSize>(&mut self, offset: u32, value: &T) {
+ let data: &[u8] = cast_slice(std::slice::from_ref(value));
+ assert_eq!(value.size().get() as usize, data.len());
+ self.update_raw(offset, data);
+ }
+
+ /// Update an allocated entry with new data.
+ pub fn update_raw(&mut self, offset: u32, data: &[u8]) {
+ // Check for out of bounds argument
+ let end = self.values.len() as u32;
+ let data_end = offset + data.len() as u32;
+ if offset >= end || data_end > end {
+ return;
+ }
+
+ let dst: &mut [u8] = &mut self.values[offset as usize..data_end as usize];
+ dst.copy_from_slice(data);
+
+ self.is_stale = true;
+ }
+
+ /// Reserve some capacity into the buffer.
+ ///
+ /// If the buffer is reallocated, the old content (on the GPU) is lost, and
+ /// needs to be re-uploaded to the newly-created buffer. This is done with
+ /// [`write_buffer()`].
+ ///
+ /// # Returns
+ ///
+ /// `true` if the buffer was (re)allocated, or `false` if an existing buffer
+ /// was reused which already had enough capacity.
+ ///
+ /// [`write_buffer()`]: crate::AlignedBufferVec::write_buffer
+ pub fn reserve(&mut self, capacity: usize, device: &RenderDevice) -> bool {
+ if capacity > self.capacity {
+ trace!(
+ "reserve: increase capacity from {} to {} bytes",
+ self.capacity,
+ capacity,
+ );
+ self.capacity = capacity;
+ if let Some(old_buffer) = self.buffer.take() {
+ trace!("reserve: forgetting old buffer #{:?}", old_buffer.id());
+ // Do not explicitly destroy the old buffer here; let the
+ // backend drop it safely.
+ }
+ self.buffer = Some(device.create_buffer(&BufferDescriptor {
+ label: Some(&self.label[..]),
+ size: capacity as BufferAddress,
+ usage: BufferUsages::COPY_DST | self.buffer_usages,
+ mapped_at_creation: false,
+ }));
+ self.is_stale = !self.values.is_empty();
+ // FIXME - this discards the old content if any!!!
+ true
+ } else {
+ false
+ }
+ }
+
+ /// Schedule the buffer write to GPU.
+ ///
+ /// # Returns
+ ///
+ /// `true` if the buffer was (re)allocated, `false` otherwise. If the buffer
+ /// was reallocated, all bind groups referencing the old buffer should be
+ /// destroyed.
+ pub fn write_buffer(&mut self, device: &RenderDevice, queue: &RenderQueue) -> bool {
+ if self.values.is_empty() || !self.is_stale {
+ return false;
+ }
+ // Round GPU allocations to 256 bytes; we don't want to keep doing
+ // micro-allocations all the time.
+ let size = self.values.len();
+ let capacity = size.next_multiple_of(256);
+ trace!(
+ "property buffer: write_buffer: size={}B capacity={}B",
+ size,
+ capacity
+ );
+ let buffer_changed = self.reserve(capacity, device);
+ if let Some(buffer) = &self.buffer {
+ queue.write_buffer(buffer, 0, self.values.as_slice());
+ self.is_stale = false;
+ }
+ buffer_changed
+ }
+
+ #[allow(dead_code)]
+ pub fn clear(&mut self) {
+ if !self.values.is_empty() {
+ self.is_stale = true;
+ }
+ self.values.clear();
+ }
+
+ /// Allocate storage for a single property struct with the given layout.
+ ///
+ /// # Returns
+ ///
+ /// On success, this returns the index in the GPU buffer where the struct
+ /// was allocated. On failure, this returns `None`.
+ #[inline]
+ pub fn allocate(&mut self, layout: &PropertyLayout) -> Option<u32> {
+ // Note: allocate with min_binding_size() and not cpu_size(), because the buffer
+ // needs to be large enough to host at least one struct when bound to a shader,
+ // and in WGSL the struct is padded to its align size.
+ let size = layout.min_binding_size().get() as u32;
+ assert!(size > 0);
+
+ // For now, we expand a single buffer infinitely. TODO to add a limit...
+ let offset = self.alloc_aligned(size);
+ assert!(offset.is_multiple_of(size)); // by design of alloc_aligned()
+ Some(offset / size) // array index
+ }
+
+ #[inline]
+ pub fn free(&mut self, offset: u32, size: u32) -> SlabState {
+ let id = self
+ .buffer
+ .as_ref()
+ .map(|buf| {
+ let id: NonZeroU32 = buf.id().into();
+ id.get()
+ })
+ .unwrap_or(u32::MAX);
+ let buffer_size = self.len();
+ if self.remove(offset..(offset + size)) {
+ if self.is_empty() {
+ SlabState::Free
+ } else if self.len() != buffer_size
+ || self
+ .buffer
+ .as_ref()
+ .map(|buf| {
+ let id: NonZeroU32 = buf.id().into();
+ id.get()
+ })
+ .unwrap_or(u32::MAX)
+ != id
+ {
+ SlabState::Resized
+ } else {
+ SlabState::Used
+ }
+ } else {
+ SlabState::Used
+ }
+ }
+
+ pub fn write(&mut self, offset: u32, data: &[u8]) {
+ self.update_raw(offset, data);
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+struct BindGroupLayoutKey {
+ /// Binding size, in bytes, of the property block.
+ pub binding_byte_size: u32,
+ /// Is this binding using the prefix sum buffer?
+ pub with_prefix_sum: bool,
+ /// Texture layout for the material bindings.
+ pub texture_layout: TextureLayout,
+}
+
+impl BindGroupLayoutKey {
+ /// Get the base variant, without any property nor texture.
+ fn base(with_prefix_sum: bool) -> Self {
+ Self {
+ binding_byte_size: 0,
+ with_prefix_sum,
+ texture_layout: TextureLayout::default(),
+ }
+ }
+}
+
+/// Cache for effect properties.
+#[derive(Resource)]
+pub struct PropertyCache {
+ /// Collection of property buffers managed by this cache. Some buffers might
+ /// be `None` if the entry is not used. Since the buffers are referenced
+ /// by index, we cannot move them once they're allocated.
+ buffers: Vec<Option<PropertyBuffer>>,
+ /// Map from an effect layout (properties and material textures) to its bind
+ /// group layout. The binding size zero is valid, and corresponds to the
+ /// variant without properties, which by abuse is stored here even
+ /// though it's not related to properties (contains only the spawner
+ /// binding).
+ bind_group_layout_descs: HashMap<BindGroupLayoutKey, BindGroupLayoutDescriptor>,
+}
+
+impl PropertyCache {
+ pub fn new(device: &RenderDevice) -> Self {
+ let align = device.limits().min_storage_buffer_offset_alignment;
+ let spawner_min_binding_size = GpuSpawnerParams::aligned_size(align);
+ let batch_info_min_binding_size = GpuBatchInfo::aligned_size(align);
+
+ // HAS_BATCHED_DRAW
+ // let has_multi_draw = false;
+ // TODO
+ // device
+ // .features()
+ // .features_webgpu
+ // .contains(FeaturesWebGPU::INDIRECT_FIRST_INSTANCE)
+ // && (instance.has(VALIDATION_INDIRECT_CALL) || (backend != DX12));
+ //
+ // Anyway we create both with/without prefix sum variants, because init/update
+ // unconditionally use the "with" variant, and render conditionally use one or
+ // the other depending on multi-draw availability. Technically we could skip the
+ // no-prefix-sum variant if we're sure we always use multi-draw though.
+
+ // Create the default bind group layout when no properties and no material
+ // textures are present.
+ let bgl_prefix = BindGroupLayoutDescriptor::new(
+ "hanabi:bgl:no_property",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE | ShaderStages::VERTEX,
+ (
+ // @group(2) @binding(0) var<storage, read> spawners : array<Spawner>;
+ storage_buffer_read_only_sized(false, Some(spawner_min_binding_size)),
+ // @group(2) @binding(1) var<storage, read> prefix_sum : array<u32>;
+ storage_buffer_read_only::<u32>(false),
+ // @group(2) @binding(2) var<storage, read> batch_info : BatchInfo;
+ storage_buffer_read_only_sized(true, Some(batch_info_min_binding_size)),
+ ),
+ ),
+ );
+ trace!(
+ "-> created bind group layout desc for no-property variant: {:?}",
+ bgl_prefix
+ );
+ let bgl_noprefix = BindGroupLayoutDescriptor::new(
+ "hanabi:bgl:no_property",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE | ShaderStages::VERTEX,
+ (
+ // @group(2) @binding(0) var<storage, read> spawner : Spawner;
+ storage_buffer_read_only_sized(false, Some(spawner_min_binding_size)),
+ // @group(2) @binding(1) var<storage, read> batch_info : BatchInfo;
+ storage_buffer_read_only_sized(true, Some(batch_info_min_binding_size)),
+ ),
+ ),
+ );
+ trace!(
+ "-> created bind group layout desc for no-property variant: {:?}",
+ bgl_noprefix
+ );
+ let mut bind_group_layout_descs = HashMap::with_capacity_and_hasher(16, Default::default());
+ bind_group_layout_descs.insert(BindGroupLayoutKey::base(true), bgl_prefix);
+ bind_group_layout_descs.insert(BindGroupLayoutKey::base(false), bgl_noprefix);
+
+ Self {
+ buffers: vec![],
+ bind_group_layout_descs,
+ }
+ }
+
+ #[allow(dead_code)]
+ #[inline]
+ pub fn buffers(&self) -> &[Option<PropertyBuffer>] {
+ &self.buffers
+ }
+
+ #[allow(dead_code)]
+ #[inline]
+ pub fn buffers_mut(&mut self) -> &mut [Option<PropertyBuffer>] {
+ &mut self.buffers
+ }
+
+ pub fn bind_group_layout_desc(
+ &self,
+ min_binding_size: Option<NonZeroU64>,
+ with_prefix_sum: bool,
+ texture_layout: &TextureLayout,
+ ) -> Option<&BindGroupLayoutDescriptor> {
+ let binding_byte_size = min_binding_size.map(NonZeroU64::get).unwrap_or(0) as u32;
+ let key = BindGroupLayoutKey {
+ binding_byte_size,
+ with_prefix_sum,
+ texture_layout: texture_layout.clone(), // TODO - Q: Equivalent<K> to avoid clone
+ };
+ self.bind_group_layout_descs.get(&key)
+ }
+
+ /// Ensure there's a bind group layout for the property variant with that
+ /// binding size and the given texture layout.
+ pub fn ensure_layout_exists(
+ &mut self,
+ property_layout: &PropertyLayout,
+ texture_layout: &TextureLayout,
+ ) {
+ let properties_min_binding_size = if property_layout.is_empty() {
+ 0
+ } else {
+ property_layout.min_binding_size().get() as u32
+ };
+ for with_prefix_sum in [false, true] {
+ // Get the base layout that we will clone and modify
+ let base_key = BindGroupLayoutKey::base(with_prefix_sum);
+ let mut bgl = self.bind_group_layout_descs.get(&base_key).unwrap().clone();
+
+ // Make a layout for the given binding size and texture layout if needed
+ let key = BindGroupLayoutKey {
+ binding_byte_size: properties_min_binding_size,
+ with_prefix_sum,
+ texture_layout: texture_layout.clone(), // TODO - Q: Equivalent<K> to avoid clone
+ };
+ self.bind_group_layout_descs.entry(key).or_insert_with(|| {
+ let label = format!(
+ "hanabi:bgl:property_size{}_tex{}",
+ properties_min_binding_size,
+ texture_layout.layout.len(),
+ );
+ trace!(
+ "Create new property bind group layout '{}' for binding size {} bytes with {} textures.",
+ label,
+ properties_min_binding_size,
+ texture_layout.layout.len(),
+ );
+ bgl.label = label.into();
+
+ // Append the Properties array binding
+ if properties_min_binding_size > 0 {
+ bgl.entries.push(
+ storage_buffer_read_only_sized(false, Some(NonZeroU64::new(properties_min_binding_size as u64).unwrap()))
+ .build(3, ShaderStages::COMPUTE | ShaderStages::VERTEX | ShaderStages::FRAGMENT),
+ );
+ }
+
+ // Append the texture bindings, if any
+ texture_layout.append_layout_bindings(4, &mut bgl.entries);
+
+ trace!(
+ "-> created bind group layout desc for size {} with {} textures: {:?}",
+ properties_min_binding_size,
+ texture_layout.layout.len(),
+ bgl,
+ );
+ bgl
+ });
+ }
+ }
+
+ pub fn allocate(
+ &mut self,
+ property_layout: &PropertyLayout,
+ texture_layout: &TextureLayout,
+ ) -> CachedEffectProperties {
+ self.ensure_layout_exists(property_layout, texture_layout);
+
+ self.buffers
+ .iter_mut()
+ .enumerate()
+ .find_map(|(buffer_index, buffer)| {
+ let buffer = buffer.as_mut()?;
+ let array_index= buffer.allocate(property_layout)?;
+ trace!("Allocated new slice in property buffer #{buffer_index} for layout {property_layout:?}: array_index={array_index}");
+ Some(CachedEffectProperties {
+ property_layout: property_layout.clone(),
+ buffer_index: buffer_index as u32,
+ array_index,
+ })
+ })
+ .unwrap_or_else(|| {
+ // Cannot find any suitable buffer; allocate a new one
+ let buffer_index = self
+ .buffers
+ .iter()
+ .position(|buf| buf.is_none())
+ .unwrap_or(self.buffers.len());
+ let label = format!("hanabi:buffer:properties{buffer_index}");
+ trace!("Creating new property buffer #{buffer_index} '{label}'");
+ let mut buffer = PropertyBuffer::new(Some(label), BufferUsages::STORAGE);
+ // FIXME - Currently PropertyBuffer::allocate() always succeeds and grows
+ // indefinitely
+ let array_index = buffer.allocate(property_layout).unwrap();
+ if buffer_index >= self.buffers.len() {
+ self.buffers.push(Some(buffer));
+ } else {
+ debug_assert!(self.buffers[buffer_index].is_none());
+ self.buffers[buffer_index] = Some(buffer);
+ }
+ CachedEffectProperties {
+ property_layout: property_layout.clone(),
+ buffer_index: buffer_index as u32,
+ array_index,
+ }
+ })
+ }
+
+ pub fn get_buffer(&self, buffer_index: u32) -> Option<&Buffer> {
+ self.buffers
+ .get(buffer_index as usize)
+ .and_then(|opt_pb| opt_pb.as_ref().map(|pb| pb.buffer()))
+ .flatten()
+ }
+
+ /// Deallocated and remove properties from the cache.
+ pub fn free(
+ &mut self,
+ cached_effect_properties: &CachedEffectProperties,
+ ) -> Result<SlabState, CachedPropertiesError> {
+ trace!(
+ "Removing cached properties {:?} from cache.",
+ cached_effect_properties
+ );
+ let entry = self
+ .buffers
+ .get_mut(cached_effect_properties.buffer_index as usize)
+ .ok_or(CachedPropertiesError::InvalidBufferIndex(
+ cached_effect_properties.buffer_index,
+ ))?;
+ let buffer = entry
+ .as_mut()
+ .ok_or(CachedPropertiesError::BufferDeallocated(
+ cached_effect_properties.buffer_index,
+ ))?;
+ let size = cached_effect_properties
+ .property_layout
+ .min_binding_size()
+ .get() as u32;
+ let offset = cached_effect_properties.array_index * size;
+ Ok(buffer.free(offset, size))
+ }
+}
+
+/// Bind group key for the effect batch "property" binding.
+#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
+pub struct PropertyBindGroupKey {
+ /// Index of the property buffer.
+ pub buffer_index: u32,
+ /// Binding size, in bytes, of the property block. 0 means no property use.
+ pub binding_size: u32,
+ /// Texture layout for the material binding points.
+ pub texture_layout: TextureLayout,
+}
+
+// Note: use by HashMap to turn a key reference into an owned key when inserting
+// an entry. We use the same struct (even if we shouldn't, to avoid
+// TextureLayout cloning) for both.
+impl From<&PropertyBindGroupKey> for PropertyBindGroupKey {
+ fn from(value: &PropertyBindGroupKey) -> Self {
+ value.clone()
+ }
+}
+
+impl PropertyBindGroupKey {
+ pub fn new(properties: &CachedEffectProperties, texture_layout: TextureLayout) -> Self {
+ Self {
+ buffer_index: properties.buffer_index,
+ binding_size: properties.property_layout.min_binding_size().get() as u32,
+ texture_layout,
+ }
+ }
+
+ /// Get a key for an effect without property.
+ pub fn texture_only(texture_layout: TextureLayout) -> Self {
+ Self {
+ buffer_index: 0,
+ binding_size: 0,
+ texture_layout,
+ }
+ }
+
+ pub fn has_properties(&self) -> bool {
+ self.binding_size > 0
+ }
+
+ #[allow(dead_code)]
+ pub fn has_textures(&self) -> bool {
+ !self.texture_layout.layout.is_empty()
+ }
+}
+
+#[derive(Default, Resource)]
+pub struct PropertyBindGroups {
+ /// Map from a [`PropertyBuffer`] index and a binding size to the
+ /// corresponding bind group.
+ property_bind_groups: HashMap<PropertyBindGroupKey, [BindGroup; 2]>,
+}
+
+impl PropertyBindGroups {
+ /// Clear all cached bind groups.
+ pub fn clear(&mut self) {
+ self.property_bind_groups.clear();
+ }
+
+ fn make_bind_group(
+ property_key: &PropertyBindGroupKey,
+ property_cache: &PropertyCache,
+ with_prefix_sum: bool,
+ texture_layout: &TextureLayout,
+ textures: &[Handle<Image>],
+ spawner_buffer: &Buffer,
+ prefix_sum_buffer: &Buffer,
+ batch_info_buffer: &Buffer,
+ property_buffer: Option<&Buffer>,
+ render_device: &RenderDevice,
+ pipeline_cache: &PipelineCache,
+ gpu_images: &RenderAssets<GpuImage>,
+ ) -> Result<BindGroup, ()> {
+ trace!(
+ "Creating new spawner@2 bind group for property buffer #{} and binding size {} (w/ prefix sum: {})",
+ property_key.buffer_index,
+ property_key.binding_size,
+ with_prefix_sum
+ );
+
+ // This should always be non-zero if the property key is Some().
+ let property_binding_size = if property_key.has_properties() {
+ Some(NonZeroU64::new(property_key.binding_size as u64).unwrap())
+ } else {
+ None
+ };
+ let Some(layout_desc) = property_cache.bind_group_layout_desc(
+ property_binding_size,
+ with_prefix_sum,
+ texture_layout,
+ ) else {
+ error!(
+ "Missing property bind group layout for binding size {:?}, referenced by effect batch.",
+ property_binding_size,
+ );
+ return Err(());
+ };
+
+ let align = render_device.limits().min_storage_buffer_offset_alignment;
+
+ let mut entries = if with_prefix_sum {
+ (*BindGroupEntries::sequential((
+ spawner_buffer.as_entire_binding(),
+ prefix_sum_buffer.as_entire_binding(),
+ BufferBinding {
+ buffer: batch_info_buffer,
+ offset: 0,
+ size: Some(GpuBatchInfo::aligned_size(align)),
+ },
+ )))
+ .to_vec()
+ } else {
+ (*BindGroupEntries::with_indices((
+ (0, spawner_buffer.as_entire_binding()),
+ (
+ 1,
+ BufferBinding {
+ buffer: batch_info_buffer,
+ offset: 0,
+ size: Some(GpuBatchInfo::aligned_size(align)),
+ },
+ ),
+ )))
+ .to_vec()
+ };
+ if let Some(property_buffer) = property_buffer {
+ // @group(2) @binding(3) var<storage, read> properties : array<Properties>
+ entries.push(BindGroupEntry {
+ binding: 3,
+ resource: property_buffer.as_entire_binding(),
+ });
+ }
+ // TODO = move
+ let material = Material {
+ layout: texture_layout.clone(),
+ textures: textures.iter().map(|h| h.id()).collect(),
+ };
+ assert_eq!(material.layout.layout.len(), material.textures.len());
+ material.append_binding_entries(4, gpu_images, &mut entries);
+
+ trace!("Creating @2 bind group with {} entries:", entries.len());
+ for e in &entries {
+ trace!("+ {}: {:?}", e.binding, e.resource);
+ }
+
+ let bind_group = if with_prefix_sum {
+ render_device.create_bind_group(
+ Some(
+ &format!(
+ "hanabi:bg:spawner@2:property{}_size{}_md",
+ property_key.buffer_index, property_key.binding_size
+ )[..],
+ ),
+ &pipeline_cache.get_bind_group_layout(layout_desc),
+ &entries[..],
+ )
+ } else {
+ render_device.create_bind_group(
+ Some(
+ &format!(
+ "hanabi:bg:spawner@2:property{}_size{}",
+ property_key.buffer_index, property_key.binding_size
+ )[..],
+ ),
+ &pipeline_cache.get_bind_group_layout(layout_desc),
+ &entries[..],
+ )
+ };
+ Ok(bind_group)
+ }
+
+ /// Ensure the bind group for the given key exists, creating it if needed.
+ pub fn ensure_exists(
+ &mut self,
+ property_key: &PropertyBindGroupKey,
+ property_cache: &PropertyCache,
+ spawner_buffer: &Buffer,
+ prefix_sum_buffer: &Buffer,
+ texture_layout: &TextureLayout,
+ textures: &[Handle<Image>],
+ batch_info_buffer: &Buffer,
+ render_device: &RenderDevice,
+ pipeline_cache: &PipelineCache,
+ gpu_images: &RenderAssets<GpuImage>,
+ ) -> Result<(), ()> {
+ trace!("PropertyBindGroups::ensure_exists() key={property_key:?}");
+
+ let property_buffer = if property_key.has_properties() {
+ let Some(property_buffer) = property_cache.get_buffer(property_key.buffer_index) else {
+ error!(
+ "Missing property buffer #{}, referenced by effect batch.",
+ property_key.buffer_index,
+ );
+ return Err(());
+ };
+ Some(property_buffer)
+ } else {
+ None
+ };
+
+ match self.property_bind_groups.entry_ref(property_key) {
+ EntryRef::Vacant(entry) => {
+ let without = Self::make_bind_group(
+ property_key,
+ property_cache,
+ false,
+ texture_layout,
+ textures,
+ spawner_buffer,
+ prefix_sum_buffer,
+ batch_info_buffer,
+ property_buffer,
+ render_device,
+ pipeline_cache,
+ gpu_images,
+ )?;
+ let with = Self::make_bind_group(
+ property_key,
+ property_cache,
+ true,
+ texture_layout,
+ textures,
+ spawner_buffer,
+ prefix_sum_buffer,
+ batch_info_buffer,
+ property_buffer,
+ render_device,
+ pipeline_cache,
+ gpu_images,
+ )?;
+ entry.insert([without, with]);
+ }
+ EntryRef::Occupied(_) => (),
+ };
+ Ok(())
+ }
+
+ /// Get the bind group for the given key.
+ pub fn get(&self, key: &PropertyBindGroupKey, with_prefix_sum: bool) -> Option<&BindGroup> {
+ self.property_bind_groups
+ .get(key)
+ .map(|arr| &arr[with_prefix_sum as usize])
+ }
+}
+
+fn upload_properties(
+ extracted_properties: &ExtractedProperties,
+ cached_effect_properties: &CachedEffectProperties,
+ mut property_cache: Mut<'_, PropertyCache>,
+) {
+ if let Some(property_data) = &extracted_properties.property_data {
+ let size = cached_effect_properties
+ .property_layout
+ .min_binding_size()
+ .get() as u32;
+ trace!(
+ "Properties changed; (re-)uploading to GPU... New data: {} bytes. Capacity: {} bytes.",
+ property_data.len(),
+ size,
+ );
+ if property_data.len() <= size as usize {
+ let property_buffer = property_cache.buffers_mut()
+ [cached_effect_properties.buffer_index as usize]
+ .as_mut()
+ .unwrap();
+ property_buffer.write(cached_effect_properties.array_index * size, property_data);
+ } else {
+ error!(
+ "Cannot upload properties: existing property slice in property buffer #{} is too small ({} bytes) for the new data ({} bytes).",
+ cached_effect_properties.buffer_index,
+ size,
+ property_data.len()
+ );
+ }
+ }
+}
+
+/// Allocate GPU resources to store an effect's properties.
+///
+/// This insert or updates the [`CachedEffectProperties`] component with the
+/// allocation details.
+pub(crate) fn allocate_properties(
+ mut commands: Commands,
+ mut property_cache: ResMut<PropertyCache>,
+ mut q_effects: Query<(
+ Entity,
+ &ExtractedEffect,
+ &ExtractedProperties,
+ Option<&mut CachedEffectProperties>,
+ )>,
+ q_noprop_effects: Query<&ExtractedEffect, Without<ExtractedProperties>>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("allocate_properties").entered();
+ trace!("allocate_properties");
+
+ for (entity, extracted_effect, extracted_properties, maybe_cached_effect_properties) in
+ &mut q_effects
+ {
+ if let Some(mut cached_effect_properties) = maybe_cached_effect_properties {
+ // Note: Technically we should compare the entire layout, but in practice the
+ // allocation only cares about the size of the layout to store all properties,
+ // and not about the actual layout itself (where each property is). So to reduce
+ // updates and maximize the chance of reuse, compare the allocation size only.
+ if cached_effect_properties.property_layout.min_binding_size()
+ != extracted_properties.property_layout.min_binding_size()
+ {
+ // Free the old allocations. We're sure there's one because the component
+ // exists.
+ // TODO - handle SlabState return value to invalidate property bind groups!!
+ if let Err(err) = property_cache.free(cached_effect_properties.as_ref()) {
+ error!("Error while freeing cached properties for effect {entity:?}: {err:?}");
+ }
+
+ // If the layout is not empty, which means we need to store at least one
+ // property, then allocate a new storate. Otherwise remove the component.
+ if extracted_properties.property_layout.is_empty() {
+ commands.entity(entity).remove::<CachedEffectProperties>();
+ } else {
+ *cached_effect_properties = property_cache.allocate(
+ &extracted_properties.property_layout,
+ &extracted_effect.texture_layout,
+ );
+ }
+ }
+
+ // Re-upload new properties
+ if !extracted_properties.property_layout.is_empty() {
+ debug_assert_eq!(
+ extracted_properties.property_layout,
+ cached_effect_properties.property_layout
+ );
+ upload_properties(
+ extracted_properties,
+ cached_effect_properties.as_ref(),
+ property_cache.reborrow(),
+ );
+ }
+ } else {
+ let cached_effect_properties = property_cache.allocate(
+ &extracted_properties.property_layout,
+ &extracted_effect.texture_layout,
+ );
+ trace!("First-time properties, allocated a new CachedEffectProperties : {cached_effect_properties:?}");
+ upload_properties(
+ extracted_properties,
+ &cached_effect_properties,
+ property_cache.reborrow(),
+ );
+ commands.entity(entity).insert(cached_effect_properties);
+ }
+ }
+
+ // For no-property bind groups, just ensure the layout exists because we will
+ // need it when creating the pipelines.
+ let empty_propert_layout = PropertyLayout::default();
+ for extracted_effect in &q_noprop_effects {
+ property_cache
+ .ensure_layout_exists(&empty_propert_layout, &extracted_effect.texture_layout);
+ }
+}
+
+/// Observer raised when the [`CachedEffectProperties`] component is removed,
+/// which indicates that the effect doesn't use properties anymore (including,
+/// when the effect itself is despawned).
+pub(crate) fn on_remove_cached_properties(
+ trigger: On<Remove<CachedEffectProperties>>,
+ query: Query<(Entity, &CachedEffectProperties)>,
+ mut property_cache: ResMut<PropertyCache>,
+ mut property_bind_groups: ResMut<PropertyBindGroups>,
+) {
+ // FIXME - review this Observer pattern; this triggers for each event one by
+ // one, which could kill performance if many effects are removed.
+
+ let Ok((render_entity, cached_effect_properties)) = query.get(trigger.event().entity) else {
+ return;
+ };
+
+ match property_cache.free(cached_effect_properties) {
+ Err(err) => match err {
+ CachedPropertiesError::InvalidBufferIndex(buffer_index)
+ => error!("Failed to remove cached properties of render entity {render_entity:?} from buffer #{buffer_index}: the index is invalid."),
+ CachedPropertiesError::BufferDeallocated(buffer_index)
+ => error!("Failed to remove cached properties of render entity {render_entity:?} from buffer #{buffer_index}: the buffer is not allocated."),
+ }
+ Ok(buffer_state) => if buffer_state != SlabState::Used {
+ // The entire buffer was deallocated, or it was resized; destroy all bind groups referencing it
+ let key = cached_effect_properties.to_key();
+ trace!("Destroying property bind group for key {key:?} due to property buffer deallocated.");
+ property_bind_groups
+ .property_bind_groups
+ .retain(|k, _| k.buffer_index != key.buffer_index);
+ }
+ }
+}
+
+/// Prepare GPU buffers storing effect properties.
+pub(crate) fn prepare_property_buffers(
+ render_device: Res<RenderDevice>,
+ render_queue: Res<RenderQueue>,
+ mut property_cache: ResMut<PropertyCache>,
+ mut bind_groups: ResMut<PropertyBindGroups>,
+) {
+ // Allocate all the property buffer(s) as needed, before we move to the next
+ // step which will need those buffers to schedule data copies from CPU.
+ for (buffer_index, buffer_slot) in property_cache.buffers_mut().iter_mut().enumerate() {
+ let Some(property_buffer) = buffer_slot.as_mut() else {
+ continue;
+ };
+ let changed = property_buffer.write_buffer(&render_device, &render_queue);
+ if changed {
+ trace!("Destroying all bind groups for property buffer #{buffer_index}");
+ bind_groups
+ .property_bind_groups
+ .retain(|k, _| k.buffer_index != buffer_index as u32);
+ }
+ }
+}
+
+#[cfg(all(test, feature = "gpu_tests"))]
+mod gpu_tests {
+ use bevy::math::Vec3;
+ use wgpu::BufferView;
+
+ use super::*;
+ use crate::{test_utils::MockRenderer, Property};
+
+ fn submit_and_wait(device: &RenderDevice, queue: &RenderQueue) {
+ // Create a dummy CommandBuffer to force the write_buffer() call to have any
+ // effect.
+ let encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("test"),
+ });
+ let command_buffer = encoder.finish();
+
+ queue.submit([command_buffer]);
+ let (tx, rx) = futures::channel::oneshot::channel();
+ queue.on_submitted_work_done(move || {
+ tx.send(()).unwrap();
+ });
+ let _ = device.poll(wgpu::PollType::Wait {
+ submission_index: None,
+ timeout: None,
+ });
+ let _ = futures::executor::block_on(rx);
+ }
+
+ fn gpu_read_back_and_wait(device: &RenderDevice, buffer: &Buffer) -> BufferView {
+ let buffer = buffer.slice(..);
+ let (tx, rx) = futures::channel::oneshot::channel();
+ buffer.map_async(wgpu::MapMode::Read, move |result| {
+ tx.send(result).unwrap();
+ });
+ let _ = device.poll(wgpu::PollType::Wait {
+ submission_index: None,
+ timeout: None,
+ });
+ futures::executor::block_on(rx).unwrap().unwrap();
+ buffer
+ .get_mapped_range()
+ .expect("Buffer must be mapped for reading")
+ }
+
+ #[test]
+ fn pb_alloc_free() {
+ let mut pb = PropertyBuffer::new(None, BufferUsages::STORAGE | BufferUsages::MAP_READ);
+
+ let layout16 = PropertyLayout::new(&[
+ Property::new("my_property", Vec3::new(1., 4., 9.)),
+ Property::new("other_property", 3.4_f32),
+ ]);
+ let size16 = layout16.min_binding_size().get() as u32;
+ let layout4 = PropertyLayout::new(&[Property::new("prop", 3.4_f32)]);
+ let size4 = layout4.min_binding_size().get() as u32;
+
+ // Alloc 16 + 4
+ let index1 = pb.allocate(&layout16).unwrap();
+ let index2 = pb.allocate(&layout4).unwrap();
+ assert_eq!(index1, 0);
+ assert_eq!(index2, size16 / size4);
+ assert!(pb.free_ranges.is_empty());
+
+ // [1111][2]
+
+ // Alloc 16; makes a gap
+ let index3 = pb.allocate(&layout16).unwrap();
+ assert_eq!(index3, (size16 + size4).div_ceil(size16));
+ assert_eq!(pb.free_ranges.len(), 1);
+
+ // [1111][2---][3333]
+
+ // Free first; buffer stay in full use (with a gap)
+ let slab_state = pb.free(index1 * size16, size16);
+ assert_eq!(slab_state, SlabState::Used);
+
+ // [----][2---][3333]
+
+ // Alloc 4 (x2); fit inside start of buffer (16B), but gap after #2 is smaller
+ // (12B)
+ let index4 = pb.allocate(&layout4).unwrap();
+ let index5 = pb.allocate(&layout4).unwrap();
+ let end2 = (index2 + 1) * size4;
+ assert_eq!(index4, end2.div_ceil(size4));
+ assert_eq!(index5, index4 + 1);
+
+ // [----][245-][3333]
+
+ // Free #2 and #4; should merge with start
+ assert_eq!(pb.free(index2 * size4, size4), SlabState::Used);
+ assert_eq!(pb.free(index4 * size4, size4), SlabState::Used);
+ assert_eq!(pb.free_ranges.len(), 2);
+
+ // [----][--5-][3333]
+
+ // Free #5; merge 2 free ranges
+ assert_eq!(pb.free(index5 * size4, size4), SlabState::Used);
+ assert_eq!(pb.free_ranges.len(), 1);
+
+ // [----][----][3333]
+
+ // Free last
+ assert_eq!(pb.free(index3 * size16, size16), SlabState::Free);
+ assert!(pb.free_ranges.is_empty());
+ assert!(pb.is_empty());
+
+ // []
+
+ // Alloc 16 + 16
+ let index6 = pb.allocate(&layout16).unwrap();
+ let index7 = pb.allocate(&layout16).unwrap();
+ assert_eq!(index6, 0);
+ assert_eq!(index7, 1);
+ assert!(pb.free_ranges.is_empty());
+
+ // [6666][7777]
+
+ // Free #75; resize
+ assert_eq!(pb.free(index7 * size16, size16), SlabState::Resized);
+ assert!(pb.free_ranges.is_empty());
+
+ // [6666]
+ }
+
+ #[test]
+ fn pb_write() {
+ let renderer = MockRenderer::new();
+ let device = renderer.device();
+ let queue = renderer.queue();
+
+ let mut pb = PropertyBuffer::new(None, BufferUsages::STORAGE | BufferUsages::MAP_READ);
+ assert!(pb.is_empty());
+ assert_eq!(pb.len(), 0);
+ assert!(pb.buffer().is_none());
+ assert_eq!(pb.capacity(), 0);
+
+ let layout1 = PropertyLayout::new(&[
+ Property::new("my_property", Vec3::new(1., 4., 9.)),
+ Property::new("other_property", 3.4_f32),
+ ]);
+ assert_eq!(layout1.min_binding_size().get(), 16);
+ let offset1 = pb.allocate(&layout1).unwrap();
+ assert_eq!(offset1, 0);
+ assert!(!pb.is_empty());
+ assert_eq!(pb.len(), 16);
+ // GPU buffer not yet allocated
+ assert!(pb.buffer().is_none());
+ assert_eq!(pb.capacity(), 0);
+
+ let layout2 = PropertyLayout::new(&[Property::new("prop", 3.4_f32)]);
+ let offset2 = pb.allocate(&layout2).unwrap();
+ assert_eq!(offset2, 4); // 16 B / size == 4
+ assert!(!pb.is_empty());
+ assert_eq!(pb.len(), 20);
+ // GPU buffer not yet allocated
+ assert!(pb.buffer().is_none());
+ assert_eq!(pb.capacity(), 0);
+
+ pb.write(offset2 * 4, bytemuck::cast_slice(&[24.99f32; 1]));
+ pb.write(
+ offset1 * 16,
+ bytemuck::cast_slice(&[55.2f32, -32.1f32, 99.07f32, 34.5f32]),
+ );
+ // GPU buffer not yet allocated
+ assert!(pb.buffer().is_none());
+ assert_eq!(pb.capacity(), 0);
+
+ let buffer_changed = pb.write_buffer(&device, &queue);
+ // GPU buffer now allocated
+ assert!(buffer_changed);
+ assert!(pb.buffer().is_some());
+ assert!(pb.capacity() >= 20);
+
+ submit_and_wait(&device, &queue);
+ println!("Buffer written");
+
+ // Read back (GPU -> CPU)
+ let buffer = pb.buffer().unwrap();
+ let view = gpu_read_back_and_wait(&device, buffer);
+
+ // Validate content
+ assert!(view.len() >= 20);
+ let v: &[f32] = bytemuck::cast_slice(&view[..256]);
+ assert_eq!(v[0], 55.2f32);
+ assert_eq!(v[1], -32.1f32);
+ assert_eq!(v[2], 99.07f32);
+ assert_eq!(v[3], 34.5f32);
+ assert_eq!(v[4], 24.99f32);
+ drop(view);
+ buffer.unmap();
+
+ pb.write(offset1 * 16, bytemuck::cast_slice(&[0f32, 1f32, 2f32]));
+ // GPU buffer still allocated
+ assert!(pb.buffer().is_some());
+ assert!(pb.capacity() >= 20);
+
+ let buffer_changed = pb.write_buffer(&device, &queue);
+ // GPU buffer NOT re-allocated (only content changed)
+ assert!(!buffer_changed);
+ assert!(pb.buffer().is_some());
+ assert!(pb.capacity() >= 20);
+
+ submit_and_wait(&device, &queue);
+ println!("Buffer written");
+
+ // Read back (GPU -> CPU)
+ let buffer = pb.buffer().unwrap();
+ let view = gpu_read_back_and_wait(&device, buffer);
+
+ // Validate content
+ assert!(view.len() >= 20);
+ let v: &[f32] = bytemuck::cast_slice(&view[..256]);
+ assert_eq!(v[0], 0f32);
+ assert_eq!(v[1], 1f32);
+ assert_eq!(v[2], 2f32);
+ assert_eq!(v[3], 34.5f32);
+ assert_eq!(v[4], 24.99f32);
+ drop(view);
+ buffer.unmap();
+ }
+}
diff --git a/vendor/bevy_hanabi/src/render/shader_cache.rs b/vendor/bevy_hanabi/src/render/shader_cache.rs
new file mode 100644
index 00000000..2dfaadf3
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/shader_cache.rs
@@ -0,0 +1,62 @@
+use std::hash::BuildHasher;
+
+use bevy::{
+ asset::{Assets, Handle},
+ ecs::{change_detection::ResMut, resource::Resource},
+ log::{debug, trace},
+ platform::collections::HashMap,
+ shader::Shader,
+};
+
+/// Cache of baked shaders variants.
+///
+/// Baked shader variants are shaders where the placeholders `{{PLACEHOLDER}}`
+/// present in the WESL template code have been replaced by actual WGSL code,
+/// making them a valid shader from the point of view of the Bevy renderer.
+///
+/// Shaders present in the cache are allocated [`Shader`] resources. Note that a
+/// [`Shader`] resource _may_ further be preprocessed to replace `@if`
+/// directives; to this extent, some entries may not be compilable WGSL as is.
+#[derive(Default, Resource)]
+pub struct ShaderCache {
+ /// Map of allocated shader resources from their baked shader code.
+ cache: HashMap<String, Handle<Shader>>,
+}
+
+impl ShaderCache {
+ /// Get an existing baked shader variant, or insert it into the cache and
+ /// allocate a new [`Shader`] resource for it.
+ ///
+ /// Returns the [`Shader`] resource associated with `source`.
+ pub fn get_or_insert(
+ &mut self,
+ filename: &str,
+ suffix: &str,
+ source: &str,
+ shaders: &mut ResMut<Assets<Shader>>,
+ ) -> Handle<Shader> {
+ if let Some(handle) = self.cache.get(source) {
+ handle.clone()
+ } else {
+ let hash = bevy::platform::hash::FixedHasher.hash_one(source);
+ let shader = Shader::from_wesl(
+ source.to_string(),
+ format!("hanabi/{}_{}_{}.wesl", filename, suffix, hash),
+ );
+ trace!(
+ "Shader path={} import_path={:?} imports={:?}",
+ shader.path,
+ shader.import_path,
+ shader.imports
+ );
+ let shader_path = shader.path.clone();
+ let handle = shaders.add(shader);
+ debug!(
+ "Inserted new configured shader {}: {:?}\n{}",
+ shader_path, handle, source
+ );
+ self.cache.insert(source.to_string(), handle.clone());
+ handle
+ }
+ }
+}
diff --git a/vendor/bevy_hanabi/src/render/shader_contract_tests.rs b/vendor/bevy_hanabi/src/render/shader_contract_tests.rs
new file mode 100644
index 00000000..266015b3
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/shader_contract_tests.rs
@@ -0,0 +1,1866 @@
+use std::{borrow::Cow, num::NonZeroU64};
+
+use bevy::{prelude::Vec3, render::renderer::RenderQueue};
+use bytemuck::{cast_slice, Pod, Zeroable};
+use futures::channel::oneshot;
+use wgpu::util::DeviceExt;
+
+use super::*;
+use crate::{
+ plugin::VFX_SORT_WESL, test_utils::MockRenderer, Attribute, EffectAsset, EffectShaderSources,
+ ExprWriter, SetAttributeModifier, SpawnerSettings,
+};
+
+#[repr(C)]
+#[derive(Clone, Copy, Debug, Pod, Zeroable)]
+struct ParticleGpu {
+ position: [f32; 4],
+}
+
+#[repr(C)]
+#[derive(Clone, Copy, Debug, Pod, Zeroable)]
+struct IndirectEntryGpu {
+ particle_index: [u32; 2],
+ dead_index: u32,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy, Debug, Pod, Zeroable)]
+struct LocateBatch {
+ base_particle: u32,
+ prefix_sum_offset: u32,
+ prefix_sum_count: u32,
+ _pad0: u32,
+}
+
+fn submit_and_wait(
+ device: &RenderDevice,
+ queue: &RenderQueue,
+ command_buffer: wgpu::CommandBuffer,
+) {
+ queue.submit([command_buffer]);
+ let (tx, rx) = oneshot::channel();
+ queue.on_submitted_work_done(move || {
+ let _ = tx.send(());
+ });
+ let _ = device.poll(wgpu::PollType::Wait {
+ submission_index: None,
+ timeout: None,
+ });
+ let _ = futures::executor::block_on(rx);
+}
+
+fn readback_vec<T: Pod>(
+ device: &RenderDevice,
+ queue: &RenderQueue,
+ src: &wgpu::Buffer,
+ bytes: u64,
+) -> Vec<T> {
+ let wgpu_device = device.wgpu_device();
+ let staging = wgpu_device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("hanabi:test:staging"),
+ size: bytes,
+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
+ mapped_at_creation: false,
+ });
+ let mut encoder = wgpu_device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("hanabi:test:readback_encoder"),
+ });
+ encoder.copy_buffer_to_buffer(src, 0, &staging, 0, bytes);
+ submit_and_wait(device, queue, encoder.finish());
+
+ let slice = staging.slice(..);
+ let (tx, rx) = oneshot::channel();
+ slice.map_async(wgpu::MapMode::Read, move |result| {
+ let _ = tx.send(result);
+ });
+ let _ = device.poll(wgpu::PollType::Wait {
+ submission_index: None,
+ timeout: None,
+ });
+ futures::executor::block_on(rx).unwrap().unwrap();
+ let mapped = slice
+ .get_mapped_range()
+ .expect("Buffer must be mapped for reading");
+ let out = cast_slice::<u8, T>(&mapped).to_vec();
+ drop(mapped);
+ staging.unmap();
+ out
+}
+
+fn create_composed_shader_module(
+ device: &RenderDevice,
+ storage_alignment: u32,
+ shader_source: &str,
+ file_path: &str,
+) -> Result<wgpu::ShaderModule, Box<dyn std::error::Error>> {
+ let spawner_padding_code = GpuSpawnerParams::padding_code(storage_alignment);
+ let batch_info_padding_code = GpuBatchInfo::padding_code(storage_alignment);
+ let common_code = include_str!("vfx_common.wesl")
+ .replace("{{SPAWNER_PADDING}}", &spawner_padding_code)
+ .replace("{{BATCH_INFO_PADDING}}", &batch_info_padding_code);
+
+ let source = crate::test_utils::compile_wesl(
+ shader_source,
+ &[],
+ &[("bevy_hanabi::render::vfx_common", &common_code)],
+ )?;
+
+ Ok(device
+ .wgpu_device()
+ .create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some(file_path),
+ source: wgpu::ShaderSource::Wgsl(Cow::Owned(source)),
+ }))
+}
+
+fn write_aligned_spawners(
+ device: &RenderDevice,
+ queue: &RenderQueue,
+ storage_alignment: u32,
+ rows: &[GpuSpawnerParams],
+) -> AlignedBufferVec<GpuSpawnerParams> {
+ let mut buffer = AlignedBufferVec::<GpuSpawnerParams>::new(
+ BufferUsages::STORAGE | BufferUsages::COPY_SRC,
+ NonZeroU64::new(storage_alignment as u64),
+ None,
+ );
+ for row in rows {
+ buffer.push(*row);
+ }
+ assert!(buffer.write_buffer(device, queue));
+ submit_and_wait(
+ device,
+ queue,
+ device
+ .wgpu_device()
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("hanabi:test:flush_spawner_upload"),
+ })
+ .finish(),
+ );
+ buffer
+}
+
+/// Create an array containing the input slice content padded to the given
+/// alignment.
+fn padded_slice_content<T: ShaderType + Pod>(arr: &[T], align: u32) -> Vec<u8> {
+ let aligned_size = (T::min_size().get() as usize).next_multiple_of(align as usize);
+ let total_size = arr.len() * aligned_size;
+ let mut data = vec![0u8; total_size];
+ let cpu_size = size_of::<T>();
+ for (index, item) in arr.iter().enumerate() {
+ let offset = index * aligned_size;
+ let item_bytes = cast_slice(std::slice::from_ref(item));
+ data[offset..offset + cpu_size].copy_from_slice(item_bytes);
+ }
+ data
+}
+
+fn create_sort_pipeline(
+ wgpu_device: &wgpu::Device,
+ sort_buffer: &wgpu::Buffer,
+) -> (wgpu::ComputePipeline, wgpu::BindGroup) {
+ let bgl = wgpu_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("hanabi:test:sort:bgl"),
+ entries: &[wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ }],
+ });
+ let bg = wgpu_device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("hanabi:test:sort:bg"),
+ layout: &bgl,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 0,
+ resource: sort_buffer.as_entire_binding(),
+ }],
+ });
+ let pl = wgpu_device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("hanabi:test:sort:pl"),
+ bind_group_layouts: &[Some(&bgl)],
+ immediate_size: 0,
+ });
+ let source =
+ crate::test_utils::compile_wesl(VFX_SORT_WESL.as_ref(), &["HAS_DUAL_KEY", "TEST"], &[])
+ .unwrap();
+ let shader = wgpu_device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("hanabi:test:vfx_sort"),
+ source: wgpu::ShaderSource::Wgsl(source.into()),
+ });
+ let pipeline = wgpu_device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("hanabi:test:sort:pipe"),
+ layout: Some(&pl),
+ module: &shader,
+ entry_point: Some("sort_blocks"),
+ cache: None,
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ });
+ (pipeline, bg)
+}
+
+#[test]
+fn real_ribbon_sort_chain_isolated_per_instance() -> Result<(), Box<dyn std::error::Error>> {
+ let renderer = MockRenderer::new();
+ let device = renderer.device();
+ let queue = renderer.queue();
+ let wgpu_device = device.wgpu_device();
+ let storage_alignment = device.limits().min_storage_buffer_offset_alignment;
+
+ let fill_shader = create_composed_shader_module(
+ &device,
+ storage_alignment,
+ include_str!("vfx_sort_fill.wesl"),
+ "bevy_hanabi::vfx_sort_fill",
+ )?;
+ let copy_shader = create_composed_shader_module(
+ &device,
+ storage_alignment,
+ include_str!("vfx_sort_copy.wesl"),
+ "bevy_hanabi::vfx_sort_copy",
+ )?;
+
+ let metadatas = [
+ GpuEffectMetadata {
+ capacity: 4,
+ alive_count: 4,
+ indirect_write_index: 0,
+ particle_stride: 2,
+ sort_key_offset: 0,
+ sort_key2_offset: 1,
+ ..default()
+ },
+ GpuEffectMetadata {
+ capacity: 4,
+ alive_count: 4,
+ indirect_write_index: 0,
+ particle_stride: 2,
+ sort_key_offset: 0,
+ sort_key2_offset: 1,
+ ..default()
+ },
+ ];
+ let spawners = [
+ GpuSpawnerParams {
+ effect_metadata_index: 0,
+ slab_offset: 0,
+ ..default()
+ },
+ GpuSpawnerParams {
+ effect_metadata_index: 1,
+ slab_offset: 4,
+ ..default()
+ },
+ ];
+ let particles = [
+ 1_u32,
+ 3.0_f32.to_bits(),
+ 0,
+ 1.0_f32.to_bits(),
+ 1,
+ 2.0_f32.to_bits(),
+ 0,
+ 4.0_f32.to_bits(), // Instance 0
+ 2,
+ 1.0_f32.to_bits(),
+ 1,
+ 4.0_f32.to_bits(),
+ 2,
+ 3.0_f32.to_bits(),
+ 1,
+ 2.0_f32.to_bits(), // Instance 1
+ ];
+ let indirect_indices = [
+ 3_u32,
+ 0,
+ u32::MAX,
+ 2,
+ 0,
+ u32::MAX,
+ 1,
+ 0,
+ u32::MAX,
+ 0,
+ 0,
+ u32::MAX,
+ 2,
+ 0,
+ u32::MAX,
+ 0,
+ 0,
+ u32::MAX,
+ 3,
+ 0,
+ u32::MAX,
+ 1,
+ 0,
+ u32::MAX,
+ ];
+ let particle_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:ribbon:particles"),
+ contents: cast_slice(&particles),
+ usage: wgpu::BufferUsages::STORAGE,
+ });
+ let indirect_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:ribbon:indirect"),
+ contents: cast_slice(&indirect_indices),
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ });
+ let metadata_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:ribbon:metadata"),
+ contents: cast_slice(&metadatas),
+ usage: wgpu::BufferUsages::STORAGE,
+ });
+ let spawner_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:ribbon:spawners"),
+ contents: &padded_slice_content(&spawners, storage_alignment),
+ usage: wgpu::BufferUsages::STORAGE,
+ });
+ let copy_source_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:ribbon:copy_source"),
+ contents: cast_slice(&[0_u32, 0]),
+ usage: wgpu::BufferUsages::STORAGE,
+ });
+ let sort_buffer = wgpu_device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("hanabi:test:ribbon:sort"),
+ size: 4 + 4 * 12,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ let dispatch_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:ribbon:dispatch"),
+ contents: cast_slice(&[
+ GpuDispatchIndirectArgs { x: 1, y: 1, z: 1 },
+ GpuDispatchIndirectArgs { x: 1, y: 1, z: 1 },
+ ]),
+ usage: wgpu::BufferUsages::INDIRECT,
+ });
+
+ let storage = |binding, read_only, dynamic| wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only },
+ has_dynamic_offset: dynamic,
+ min_binding_size: None,
+ },
+ count: None,
+ };
+ let fill_bgl = wgpu_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("hanabi:test:ribbon:fill:bgl"),
+ entries: &[
+ storage(0, false, false),
+ storage(1, true, false),
+ storage(2, true, false),
+ storage(3, false, false),
+ storage(4, true, true),
+ ],
+ });
+ let copy_bgl = wgpu_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("hanabi:test:ribbon:copy:bgl"),
+ entries: &[
+ storage(0, false, false),
+ storage(1, true, false),
+ storage(2, false, false),
+ storage(3, true, true),
+ storage(4, true, true),
+ ],
+ });
+ let fill_bg = wgpu_device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("hanabi:test:ribbon:fill:bg"),
+ layout: &fill_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: sort_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: particle_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: indirect_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: metadata_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &spawner_buffer,
+ offset: 0,
+ size: NonZeroU64::new(storage_alignment as u64),
+ }),
+ },
+ ],
+ });
+ let copy_bg = wgpu_device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("hanabi:test:ribbon:copy:bg"),
+ layout: &copy_bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: indirect_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: sort_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: metadata_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &spawner_buffer,
+ offset: 0,
+ size: NonZeroU64::new(storage_alignment as u64),
+ }),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: copy_source_buffer.as_entire_binding(),
+ },
+ ],
+ });
+ let fill_pl = wgpu_device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("hanabi:test:ribbon:fill:pl"),
+ bind_group_layouts: &[Some(&fill_bgl)],
+ immediate_size: 0,
+ });
+ let copy_pl = wgpu_device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("hanabi:test:ribbon:copy:pl"),
+ bind_group_layouts: &[Some(&copy_bgl)],
+ immediate_size: 0,
+ });
+ let fill_pipeline = wgpu_device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("hanabi:test:ribbon:fill"),
+ layout: Some(&fill_pl),
+ module: &fill_shader,
+ entry_point: Some("sort_fill"),
+ cache: None,
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ });
+ let copy_pipeline = wgpu_device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("hanabi:test:ribbon:copy"),
+ layout: Some(&copy_pl),
+ module: &copy_shader,
+ entry_point: Some("sort_copy"),
+ cache: None,
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ });
+ let (sort_pipeline, sort_bg) = create_sort_pipeline(wgpu_device, &sort_buffer);
+
+ let mut encoder = wgpu_device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("hanabi:test:ribbon:chain"),
+ });
+ for instance in 0..2 {
+ encoder.clear_buffer(&sort_buffer, 0, Some(4));
+ {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("hanabi:test:ribbon:fill"),
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(&fill_pipeline);
+ pass.set_bind_group(
+ 0,
+ &fill_bg,
+ &[(instance * storage_alignment as usize) as u32],
+ );
+ pass.dispatch_workgroups_indirect(
+ &dispatch_buffer,
+ instance as u64 * std::mem::size_of::<GpuDispatchIndirectArgs>() as u64,
+ );
+ }
+ {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("hanabi:test:ribbon:sort"),
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(&sort_pipeline);
+ pass.set_bind_group(0, &sort_bg, &[]);
+ pass.dispatch_workgroups_indirect(
+ &dispatch_buffer,
+ instance as u64 * std::mem::size_of::<GpuDispatchIndirectArgs>() as u64,
+ );
+ }
+ {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("hanabi:test:ribbon:copy"),
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(&copy_pipeline);
+ pass.set_bind_group(
+ 0,
+ &copy_bg,
+ &[(instance * storage_alignment as usize) as u32, 0],
+ );
+ pass.dispatch_workgroups_indirect(
+ &dispatch_buffer,
+ instance as u64 * std::mem::size_of::<GpuDispatchIndirectArgs>() as u64,
+ );
+ }
+ }
+ submit_and_wait(&device, &queue, encoder.finish());
+
+ let indirect_out = readback_vec::<u32>(
+ &device,
+ &queue,
+ &indirect_buffer,
+ (indirect_indices.len() * std::mem::size_of::<u32>()) as u64,
+ );
+ assert_eq!(
+ &indirect_out[0..12],
+ &[
+ 1,
+ 0,
+ u32::MAX,
+ 3,
+ 0,
+ u32::MAX,
+ 2,
+ 0,
+ u32::MAX,
+ 0,
+ 0,
+ u32::MAX
+ ]
+ );
+ assert_eq!(
+ &indirect_out[12..24],
+ &[
+ 3,
+ 0,
+ u32::MAX,
+ 1,
+ 0,
+ u32::MAX,
+ 0,
+ 0,
+ u32::MAX,
+ 2,
+ 0,
+ u32::MAX
+ ]
+ );
+ Ok(())
+}
+
+#[test]
+fn real_vfx_prefix_sum_contracts() -> Result<(), Box<dyn std::error::Error>> {
+ let renderer = MockRenderer::new();
+ let device = renderer.device();
+ let queue = renderer.queue();
+ let wgpu_device = device.wgpu_device();
+ let storage_alignment = device.limits().min_storage_buffer_offset_alignment;
+
+ let shader = create_composed_shader_module(
+ &device,
+ storage_alignment,
+ include_str!("vfx_prefix_sum.wesl"),
+ "bevy_hanabi::vfx_prefix_sum",
+ )?;
+
+ let batches = [
+ GpuBatchInfo {
+ base_particle: 100,
+ prefix_sum_offset: 0,
+ prefix_sum_count: 3,
+ ..default()
+ },
+ GpuBatchInfo {
+ spawner_base: 3,
+ base_particle: 500,
+ prefix_sum_offset: 3,
+ prefix_sum_count: 1,
+ ..default()
+ },
+ ];
+ let prefix_init = [10_u32, 5, 8, 6];
+ let dispatch_init = [
+ GpuDispatchIndirectArgs::default(),
+ GpuDispatchIndirectArgs::default(),
+ ];
+
+ let batch_content = padded_slice_content(
+ &batches,
+ wgpu_device.limits().min_storage_buffer_offset_alignment,
+ );
+ let batch_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:prefix:batch"),
+ contents: &batch_content,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ });
+ let prefix_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:prefix:sum"),
+ contents: cast_slice(&prefix_init),
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ });
+ let dispatch_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:prefix:dispatch"),
+ contents: cast_slice(&dispatch_init),
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ });
+
+ let bgl = wgpu_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("hanabi:test:prefix:bgl"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 2,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ ],
+ });
+ let bg = wgpu_device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("hanabi:test:prefix:bg"),
+ layout: &bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: batch_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: prefix_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: dispatch_buffer.as_entire_binding(),
+ },
+ ],
+ });
+ let pl = wgpu_device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("hanabi:test:prefix:pl"),
+ bind_group_layouts: &[Some(&bgl)],
+ immediate_size: 0,
+ });
+ let pipeline = wgpu_device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("hanabi:test:prefix:pipe"),
+ layout: Some(&pl),
+ module: &shader,
+ entry_point: Some("main"),
+ cache: None,
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ });
+
+ let mut encoder = wgpu_device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("hanabi:test:prefix:enc"),
+ });
+ {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("hanabi:test:prefix:pass"),
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &bg, &[]);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+ submit_and_wait(&device, &queue, encoder.finish());
+
+ let prefix_out = readback_vec::<u32>(
+ &device,
+ &queue,
+ &prefix_buffer,
+ (prefix_init.len() * 4) as u64,
+ );
+ assert_eq!(prefix_out, vec![0, 10, 15, 0]);
+
+ let dispatch_out = readback_vec::<GpuDispatchIndirectArgs>(
+ &device,
+ &queue,
+ &dispatch_buffer,
+ (std::mem::size_of::<GpuDispatchIndirectArgs>() * dispatch_init.len()) as u64,
+ );
+ assert_eq!(dispatch_out[0].x, 1);
+ assert_eq!(dispatch_out[0].y, 1);
+ assert_eq!(dispatch_out[0].z, 1);
+ assert_eq!(dispatch_out[1].x, 1);
+ assert_eq!(dispatch_out[1].y, 1);
+ assert_eq!(dispatch_out[1].z, 1);
+
+ Ok(())
+}
+
+#[test]
+fn location_mapping_contracts() {
+ let renderer = MockRenderer::new();
+ let device = renderer.device();
+ let queue = renderer.queue();
+ let wgpu_device = device.wgpu_device();
+
+ let shader = wgpu_device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("hanabi:test:location:shader"),
+ source: wgpu::ShaderSource::Wgsl(
+ r#"
+struct BatchInfo {
+ base_particle: u32,
+ prefix_sum_offset: u32,
+ prefix_sum_count: u32,
+ _pad0: u32,
+}
+@group(0) @binding(0) var<storage, read> batch_info : BatchInfo;
+@group(0) @binding(1) var<storage, read> prefix_sum : array<u32>;
+@group(0) @binding(2) var<storage, read> slab_indices : array<u32>;
+@group(0) @binding(3) var<storage, read_write> out_effect_index : array<u32>;
+
+@compute @workgroup_size(64)
+fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
+ let i = gid.x;
+ if (i >= arrayLength(&slab_indices)) { return; }
+ let slab_particle_index = slab_indices[i];
+ var lo = batch_info.prefix_sum_offset;
+ var hi = lo + batch_info.prefix_sum_count;
+ while (lo < hi) {
+ let mid = (hi + lo) >> 1u;
+ let base_particle = batch_info.base_particle + prefix_sum[mid];
+ if (slab_particle_index >= base_particle) {
+ lo = mid + 1u;
+ } else {
+ hi = mid;
+ }
+ }
+ out_effect_index[i] = lo - 1u - batch_info.prefix_sum_offset;
+}
+"#
+ .into(),
+ ),
+ });
+
+ let locate_batch = LocateBatch {
+ base_particle: 100,
+ prefix_sum_offset: 0,
+ prefix_sum_count: 3,
+ _pad0: 0,
+ };
+ let locate_prefix = [0_u32, 10, 15];
+ let slab_indices = [100_u32, 109, 110, 114, 115, 122];
+ let out_zero = [0_u32; 6];
+
+ let batch_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:location:batch"),
+ contents: cast_slice(&[locate_batch]),
+ usage: wgpu::BufferUsages::STORAGE,
+ });
+ let prefix_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:location:prefix"),
+ contents: cast_slice(&locate_prefix),
+ usage: wgpu::BufferUsages::STORAGE,
+ });
+ let slab_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:location:slab"),
+ contents: cast_slice(&slab_indices),
+ usage: wgpu::BufferUsages::STORAGE,
+ });
+ let out_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:location:out"),
+ contents: cast_slice(&out_zero),
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ });
+
+ let bgl = wgpu_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("hanabi:test:location:bgl"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: true },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: true },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 2,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: true },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 3,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ ],
+ });
+ let bg = wgpu_device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("hanabi:test:location:bg"),
+ layout: &bgl,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: batch_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: prefix_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: slab_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: out_buffer.as_entire_binding(),
+ },
+ ],
+ });
+ let pl = wgpu_device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("hanabi:test:location:pl"),
+ bind_group_layouts: &[Some(&bgl)],
+ immediate_size: 0,
+ });
+ let pipeline = wgpu_device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("hanabi:test:location:pipe"),
+ layout: Some(&pl),
+ module: &shader,
+ entry_point: Some("main"),
+ cache: None,
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ });
+
+ let mut encoder = wgpu_device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("hanabi:test:location:enc"),
+ });
+ {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("hanabi:test:location:pass"),
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &bg, &[]);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+ submit_and_wait(&device, &queue, encoder.finish());
+ let out = readback_vec::<u32>(
+ &device,
+ &queue,
+ &out_buffer,
+ (slab_indices.len() * 4) as u64,
+ );
+ assert_eq!(out, vec![0, 0, 1, 1, 2, 2]);
+}
+
+#[test]
+fn indirect_plus_update_routing_contracts() {
+ #[repr(C)]
+ #[derive(Clone, Copy, Pod, Zeroable)]
+ struct SpawnerLite {
+ effect_metadata_index: u32,
+ draw_indirect_index: u32,
+ }
+ #[repr(C)]
+ #[derive(Clone, Copy, Pod, Zeroable)]
+ struct EffectMetadataLite {
+ alive_count: u32,
+ max_update: u32,
+ indirect_dispatch_index: u32,
+ }
+ #[repr(C)]
+ #[derive(Clone, Copy, Pod, Zeroable)]
+ struct BatchInfoLite {
+ total_update_count: u32,
+ spawner_base: u32,
+ base_particle: u32,
+ prefix_sum_offset: u32,
+ prefix_sum_count: u32,
+ }
+
+ let renderer = MockRenderer::new();
+ let device = renderer.device();
+ let queue = renderer.queue();
+ let wgpu_device = device.wgpu_device();
+
+ let indirect_shader = wgpu_device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("hanabi:test:indirect-lite"),
+ source: wgpu::ShaderSource::Wgsl(
+ r#"
+struct Spawner {
+ effect_metadata_index: u32,
+ draw_indirect_index: u32,
+}
+struct EffectMetadata {
+ alive_count: u32,
+ max_update: u32,
+ indirect_dispatch_index: u32,
+}
+struct DispatchIndirectArgs {
+ x: u32, y: u32, z: u32,
+}
+@group(0) @binding(0) var<storage, read_write> spawner_buffer : array<Spawner>;
+@group(0) @binding(1) var<storage, read_write> effect_metadata_buffer : array<EffectMetadata>;
+@group(0) @binding(2) var<storage, read_write> prefix_sum : array<u32>;
+@group(0) @binding(3) var<storage, read_write> dispatch_buffer : array<DispatchIndirectArgs>;
+
+@compute @workgroup_size(64)
+fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
+ let i = gid.x;
+ if (i >= arrayLength(&spawner_buffer)) { return; }
+ let sp = spawner_buffer[i];
+ let em = effect_metadata_buffer[sp.effect_metadata_index];
+ prefix_sum[i] = em.alive_count;
+ effect_metadata_buffer[sp.effect_metadata_index].max_update = em.alive_count;
+ let ddi = em.indirect_dispatch_index;
+ dispatch_buffer[ddi].x = (em.alive_count + 63u) >> 6u;
+ dispatch_buffer[ddi].y = 1u;
+ dispatch_buffer[ddi].z = 1u;
+}
+"#
+ .into(),
+ ),
+ });
+ let update_route_shader = wgpu_device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("hanabi:test:update-route"),
+ source: wgpu::ShaderSource::Wgsl(
+ r#"
+struct BatchInfo {
+ total_update_count: u32,
+ spawner_base: u32,
+ base_particle: u32,
+ prefix_sum_offset: u32,
+ prefix_sum_count: u32,
+}
+@group(0) @binding(0) var<storage, read> prefix_sum : array<u32>;
+@group(0) @binding(1) var<storage, read> batch_info : BatchInfo;
+@group(0) @binding(2) var<storage, read_write> routed_count : array<atomic<u32>>;
+
+fn find_effect(slab_particle_index: u32) -> u32 {
+ var lo = batch_info.prefix_sum_offset;
+ var hi = lo + batch_info.prefix_sum_count;
+ while (lo < hi) {
+ let mid = (hi + lo) >> 1u;
+ let base_particle = batch_info.base_particle + prefix_sum[mid];
+ if (slab_particle_index >= base_particle) {
+ lo = mid + 1u;
+ } else {
+ hi = mid;
+ }
+ }
+ return lo - 1u - batch_info.prefix_sum_offset;
+}
+
+@compute @workgroup_size(64)
+fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
+ let i = gid.x;
+ if (i >= batch_info.total_update_count) { return; }
+ let slab_particle_index = batch_info.base_particle + i;
+ let effect_index = find_effect(slab_particle_index);
+ atomicAdd(&routed_count[effect_index], 1u);
+}
+"#
+ .into(),
+ ),
+ });
+
+ let spawners = [
+ SpawnerLite {
+ effect_metadata_index: 0,
+ draw_indirect_index: 0,
+ },
+ SpawnerLite {
+ effect_metadata_index: 1,
+ draw_indirect_index: 1,
+ },
+ ];
+ let em = [
+ EffectMetadataLite {
+ alive_count: 7,
+ max_update: 0,
+ indirect_dispatch_index: 0,
+ },
+ EffectMetadataLite {
+ alive_count: 5,
+ max_update: 0,
+ indirect_dispatch_index: 1,
+ },
+ ];
+ let prefix_init = [0_u32, 0];
+ let ddi_init = [
+ GpuDispatchIndirectArgs::default(),
+ GpuDispatchIndirectArgs::default(),
+ ];
+
+ let sp_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:routing:spawner"),
+ contents: cast_slice(&spawners),
+ usage: wgpu::BufferUsages::STORAGE,
+ });
+ let em_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:routing:metadata"),
+ contents: cast_slice(&em),
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ });
+ let prefix_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:routing:prefix"),
+ contents: cast_slice(&prefix_init),
+ usage: wgpu::BufferUsages::STORAGE
+ | wgpu::BufferUsages::COPY_SRC
+ | wgpu::BufferUsages::COPY_DST,
+ });
+ let ddi_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:routing:ddi"),
+ contents: cast_slice(&ddi_init),
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ });
+
+ let bgl_i = wgpu_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("hanabi:test:routing:indirect:bgl"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 2,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 3,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ ],
+ });
+ let bg_i = wgpu_device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("hanabi:test:routing:indirect:bg"),
+ layout: &bgl_i,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: sp_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: em_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: prefix_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: ddi_buffer.as_entire_binding(),
+ },
+ ],
+ });
+ let pl_i = wgpu_device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("hanabi:test:routing:indirect:pl"),
+ bind_group_layouts: &[Some(&bgl_i)],
+ immediate_size: 0,
+ });
+ let pipe_i = wgpu_device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("hanabi:test:routing:indirect:pipe"),
+ layout: Some(&pl_i),
+ module: &indirect_shader,
+ entry_point: Some("main"),
+ cache: None,
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ });
+ let mut encoder = wgpu_device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("hanabi:test:routing:indirect:enc"),
+ });
+ {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("hanabi:test:routing:indirect:pass"),
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(&pipe_i);
+ pass.set_bind_group(0, &bg_i, &[]);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+ submit_and_wait(&device, &queue, encoder.finish());
+
+ let prefix = readback_vec::<u32>(&device, &queue, &prefix_buffer, 8);
+ assert_eq!(prefix, vec![7, 5]);
+
+ let prefix_after = [0_u32, 7_u32];
+ queue.write_buffer(&prefix_buffer, 0, cast_slice(&prefix_after));
+ let batch_lite = BatchInfoLite {
+ total_update_count: 12,
+ spawner_base: 0,
+ base_particle: 100,
+ prefix_sum_offset: 0,
+ prefix_sum_count: 2,
+ };
+ let batch_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:routing:batch"),
+ contents: cast_slice(&[batch_lite]),
+ usage: wgpu::BufferUsages::STORAGE,
+ });
+ let routed_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:routing:routed"),
+ contents: cast_slice(&[0_u32, 0_u32]),
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ });
+
+ let bgl_u = wgpu_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("hanabi:test:routing:update:bgl"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: true },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: true },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 2,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ ],
+ });
+ let bg_u = wgpu_device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("hanabi:test:routing:update:bg"),
+ layout: &bgl_u,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: prefix_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: batch_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: routed_buffer.as_entire_binding(),
+ },
+ ],
+ });
+ let pl_u = wgpu_device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("hanabi:test:routing:update:pl"),
+ bind_group_layouts: &[Some(&bgl_u)],
+ immediate_size: 0,
+ });
+ let pipe_u = wgpu_device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("hanabi:test:routing:update:pipe"),
+ layout: Some(&pl_u),
+ module: &update_route_shader,
+ entry_point: Some("main"),
+ cache: None,
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ });
+ let mut encoder = wgpu_device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("hanabi:test:routing:update:enc"),
+ });
+ {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("hanabi:test:routing:update:pass"),
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(&pipe_u);
+ pass.set_bind_group(0, &bg_u, &[]);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+ submit_and_wait(&device, &queue, encoder.finish());
+ let routed = readback_vec::<u32>(&device, &queue, &routed_buffer, 8);
+ assert_eq!(routed, vec![7, 5]);
+}
+
+#[test]
+fn real_vfx_update_contracts() -> Result<(), Box<dyn std::error::Error>> {
+ let renderer = MockRenderer::new();
+ let device = renderer.device();
+ let queue = renderer.queue();
+ let wgpu_device = device.wgpu_device();
+ let storage_alignment = device.limits().min_storage_buffer_offset_alignment;
+
+ let writer = ExprWriter::new();
+ let init_pos = SetAttributeModifier::new(Attribute::POSITION, writer.lit(Vec3::ZERO).expr());
+ let module = writer.finish();
+ let asset = EffectAsset::new(8, SpawnerSettings::rate(0.0.into()), module).init(init_pos);
+ let sources = EffectShaderSources::generate(&asset, None, 0)?;
+ let shader = create_composed_shader_module(
+ &device,
+ storage_alignment,
+ &sources.update_shader_source,
+ "bevy_hanabi::generated_vfx_update",
+ )?;
+
+ let sim_params = GpuSimParams {
+ delta_time: 1.0,
+ time: 0.0,
+ virtual_delta_time: 1.0,
+ virtual_time: 0.0,
+ real_delta_time: 1.0,
+ real_time: 0.0,
+ num_effects: 2,
+ ..default()
+ };
+ let draw_init = [
+ GpuDrawIndexedIndirectArgs {
+ index_count: 0,
+ instance_count: 0,
+ first_index: 0,
+ base_vertex: 0,
+ first_instance: 0,
+ },
+ GpuDrawIndexedIndirectArgs {
+ index_count: 0,
+ instance_count: 0,
+ first_index: 0,
+ base_vertex: 0,
+ first_instance: 0,
+ },
+ ];
+ let particles = [ParticleGpu::zeroed(); 8];
+ let mut indirect_rows = [IndirectEntryGpu::zeroed(); 8];
+ indirect_rows[0].particle_index = [0, 0];
+ indirect_rows[1].particle_index = [0, 1];
+ indirect_rows[4].particle_index = [0, 0];
+
+ let spawner_rows = [
+ GpuSpawnerParams {
+ seed: 1,
+ render_pong: 0,
+ effect_metadata_index: 0,
+ draw_indirect_index: 0,
+ slab_offset: 0,
+ parent_slab_offset: u32::MAX,
+ ..default()
+ },
+ GpuSpawnerParams {
+ seed: 2,
+ render_pong: 0,
+ effect_metadata_index: 1,
+ draw_indirect_index: 1,
+ slab_offset: 4,
+ parent_slab_offset: u32::MAX,
+ ..default()
+ },
+ ];
+ let spawners = write_aligned_spawners(&device, &queue, storage_alignment, &spawner_rows);
+ let spawner_buffer = spawners.buffer().unwrap();
+
+ let metadata_rows = [
+ GpuEffectMetadata {
+ capacity: 8,
+ alive_count: 2,
+ max_update: 2,
+ indirect_draw_index: 0,
+ particle_stride: 4,
+ ..default()
+ },
+ GpuEffectMetadata {
+ capacity: 8,
+ alive_count: 1,
+ max_update: 1,
+ indirect_draw_index: 1,
+ particle_stride: 4,
+ ..default()
+ },
+ ];
+
+ let sim_params_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:update:sim_params"),
+ contents: cast_slice(&[sim_params]),
+ usage: wgpu::BufferUsages::UNIFORM,
+ });
+ let draw_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:update:draw"),
+ contents: cast_slice(&draw_init),
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ });
+ let particle_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:update:particles"),
+ contents: cast_slice(&particles),
+ usage: wgpu::BufferUsages::STORAGE,
+ });
+ let indirect_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:update:indirect"),
+ contents: cast_slice(&indirect_rows),
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ });
+ let prefix_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:update:prefix"),
+ contents: cast_slice(&[0_u32, 2_u32]),
+ usage: wgpu::BufferUsages::STORAGE,
+ });
+ let batch_content = padded_slice_content(
+ &[GpuBatchInfo {
+ total_update_count: 3,
+ prefix_sum_count: 2,
+ ..default()
+ }],
+ wgpu_device.limits().min_storage_buffer_offset_alignment,
+ );
+ let batch_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:update:batch"),
+ contents: &batch_content,
+ usage: wgpu::BufferUsages::STORAGE,
+ });
+ let metadata_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:update:metadata"),
+ contents: cast_slice(&metadata_rows),
+ usage: wgpu::BufferUsages::STORAGE,
+ });
+
+ let bgl0 = wgpu_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("hanabi:test:update:bgl0"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ ],
+ });
+ let bgl1 = wgpu_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("hanabi:test:update:bgl1"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ ],
+ });
+ let bgl2 = wgpu_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("hanabi:test:update:bgl2"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: true },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: true },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 2,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: true },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ ],
+ });
+ let bgl3 = wgpu_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("hanabi:test:update:bgl3"),
+ entries: &[wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ }],
+ });
+
+ let bg0 = wgpu_device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("hanabi:test:update:bg0"),
+ layout: &bgl0,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: sim_params_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: draw_buffer.as_entire_binding(),
+ },
+ ],
+ });
+ let bg1 = wgpu_device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("hanabi:test:update:bg1"),
+ layout: &bgl1,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: particle_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: indirect_buffer.as_entire_binding(),
+ },
+ ],
+ });
+ let bg2 = wgpu_device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("hanabi:test:update:bg2"),
+ layout: &bgl2,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: spawner_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: prefix_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: batch_buffer.as_entire_binding(),
+ },
+ ],
+ });
+ let bg3 = wgpu_device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("hanabi:test:update:bg3"),
+ layout: &bgl3,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 0,
+ resource: metadata_buffer.as_entire_binding(),
+ }],
+ });
+
+ let pl = wgpu_device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("hanabi:test:update:pl"),
+ bind_group_layouts: &[Some(&bgl0), Some(&bgl1), Some(&bgl2), Some(&bgl3)],
+ immediate_size: 0,
+ });
+ let pipeline = wgpu_device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("hanabi:test:update:pipe"),
+ layout: Some(&pl),
+ module: &shader,
+ entry_point: Some("main"),
+ cache: None,
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ });
+
+ let mut encoder = wgpu_device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("hanabi:test:update:enc"),
+ });
+ {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("hanabi:test:update:pass"),
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &bg0, &[]);
+ pass.set_bind_group(1, &bg1, &[]);
+ pass.set_bind_group(2, &bg2, &[]);
+ pass.set_bind_group(3, &bg3, &[]);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+ submit_and_wait(&device, &queue, encoder.finish());
+
+ let draw_out = readback_vec::<u32>(
+ &device,
+ &queue,
+ &draw_buffer,
+ (std::mem::size_of::<GpuDrawIndexedIndirectArgs>() * draw_init.len()) as u64,
+ );
+ assert_eq!(draw_out[1], 2);
+ assert_eq!(draw_out[6], 1);
+
+ let indirect_out = readback_vec::<u32>(
+ &device,
+ &queue,
+ &indirect_buffer,
+ (std::mem::size_of::<IndirectEntryGpu>() * indirect_rows.len()) as u64,
+ );
+ assert_eq!(indirect_out[0], 0);
+ assert_eq!(indirect_out[3], 1);
+ assert_eq!(indirect_out[12], 0);
+
+ Ok(())
+}
+
+#[test]
+fn real_vfx_indirect_contracts() -> Result<(), Box<dyn std::error::Error>> {
+ let renderer = MockRenderer::new();
+ let device = renderer.device();
+ let queue = renderer.queue();
+ let wgpu_device = device.wgpu_device();
+ let storage_alignment = device.limits().min_storage_buffer_offset_alignment;
+
+ let shader = create_composed_shader_module(
+ &device,
+ storage_alignment,
+ include_str!("vfx_indirect.wesl"),
+ "bevy_hanabi::vfx_indirect",
+ )?;
+
+ let sim_params = GpuSimParams {
+ delta_time: 1.0,
+ time: 0.0,
+ virtual_delta_time: 1.0,
+ virtual_time: 0.0,
+ real_delta_time: 1.0,
+ real_time: 0.0,
+ num_effects: 2,
+ ..default()
+ };
+ let sim_params_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:indirect:sim"),
+ contents: cast_slice(&[sim_params]),
+ usage: wgpu::BufferUsages::UNIFORM,
+ });
+
+ let metadata_rows = [
+ GpuEffectMetadata {
+ capacity: 200,
+ alive_count: 130,
+ max_update: u32::MAX,
+ max_spawn: u32::MAX,
+ indirect_draw_index: 0,
+ indirect_write_index: 0,
+ ..default()
+ },
+ GpuEffectMetadata {
+ capacity: 5,
+ alive_count: 1,
+ max_update: u32::MAX,
+ max_spawn: u32::MAX,
+ indirect_draw_index: 1,
+ indirect_write_index: 1,
+ ..default()
+ },
+ ];
+ let metadata_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:indirect:metadata"),
+ contents: cast_slice(&metadata_rows),
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ });
+
+ let mut draw_init = [GpuDrawIndexedIndirectArgs::default(); 2];
+ draw_init[0].instance_count = 9;
+ draw_init[1].instance_count = 4;
+ let draw_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:indirect:draw"),
+ contents: cast_slice(&draw_init),
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ });
+
+ let spawner_rows = [
+ GpuSpawnerParams {
+ seed: 111,
+ render_pong: 0,
+ effect_metadata_index: 0,
+ draw_indirect_index: 0,
+ slab_offset: 0,
+ parent_slab_offset: u32::MAX,
+ ..default()
+ },
+ GpuSpawnerParams {
+ seed: 222,
+ render_pong: 1,
+ effect_metadata_index: 1,
+ draw_indirect_index: 1,
+ slab_offset: 64,
+ parent_slab_offset: u32::MAX,
+ ..default()
+ },
+ ];
+ let spawners = write_aligned_spawners(&device, &queue, storage_alignment, &spawner_rows);
+ let spawner_buffer = spawners.buffer().unwrap();
+
+ let prefix_buffer = wgpu_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("hanabi:test:indirect:prefix"),
+ contents: cast_slice(&[0_u32, 0_u32]),
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ });
+
+ let bgl0 = wgpu_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("hanabi:test:indirect:bgl0"),
+ entries: &[wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ }],
+ });
+ let bgl1 = wgpu_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("hanabi:test:indirect:bgl1"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ ],
+ });
+ let bgl2 = wgpu_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("hanabi:test:indirect:bgl2"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only: false },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ ],
+ });
+ let bg0 = wgpu_device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("hanabi:test:indirect:bg0"),
+ layout: &bgl0,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 0,
+ resource: sim_params_buffer.as_entire_binding(),
+ }],
+ });
+ let bg1 = wgpu_device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("hanabi:test:indirect:bg1"),
+ layout: &bgl1,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: metadata_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: draw_buffer.as_entire_binding(),
+ },
+ ],
+ });
+ let bg2 = wgpu_device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("hanabi:test:indirect:bg2"),
+ layout: &bgl2,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: spawner_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: prefix_buffer.as_entire_binding(),
+ },
+ ],
+ });
+
+ let pl = wgpu_device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("hanabi:test:indirect:pl"),
+ bind_group_layouts: &[Some(&bgl0), Some(&bgl1), Some(&bgl2)],
+ immediate_size: 0,
+ });
+ let pipeline = wgpu_device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("hanabi:test:indirect:pipe"),
+ layout: Some(&pl),
+ module: &shader,
+ entry_point: Some("main"),
+ cache: None,
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ });
+
+ let mut encoder = wgpu_device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("hanabi:test:indirect:enc"),
+ });
+ {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("hanabi:test:indirect:pass"),
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &bg0, &[]);
+ pass.set_bind_group(1, &bg1, &[]);
+ pass.set_bind_group(2, &bg2, &[]);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+ submit_and_wait(&device, &queue, encoder.finish());
+
+ let prefix_out = readback_vec::<u32>(&device, &queue, &prefix_buffer, 8);
+ assert_eq!(prefix_out, vec![130, 1]);
+
+ let metadata_raw_out = readback_vec::<u32>(
+ &device,
+ &queue,
+ &metadata_buffer,
+ (metadata_rows.len() * size_of::<GpuEffectMetadata>()) as u64,
+ );
+ let metadata_out: &[GpuEffectMetadata] = cast_slice(&metadata_raw_out);
+ assert_eq!(metadata_out[0].max_update, 130);
+ assert_eq!(metadata_out[0].max_spawn, 70);
+ assert_eq!(metadata_out[1].max_update, 1);
+ assert_eq!(metadata_out[1].max_spawn, 4);
+
+ let draw_out = readback_vec::<GpuDrawIndexedIndirectArgs>(
+ &device,
+ &queue,
+ &draw_buffer,
+ (std::mem::size_of::<GpuDrawIndexedIndirectArgs>() * 2) as u64,
+ );
+ assert_eq!(draw_out[0].instance_count, 0);
+ assert_eq!(draw_out[1].instance_count, 0);
+
+ let spawner_out = readback_vec::<u32>(
+ &device,
+ &queue,
+ spawner_buffer,
+ (spawners.aligned_size() * 2) as u64,
+ );
+ let spawner_stride_u32 = spawners.aligned_size() / 4;
+ let render_pong_offset_u32 = std::mem::offset_of!(GpuSpawnerParams, render_pong) / 4;
+ assert_eq!(spawner_out[render_pong_offset_u32], 1);
+ assert_eq!(spawner_out[spawner_stride_u32 + render_pong_offset_u32], 0);
+
+ Ok(())
+}
diff --git a/vendor/bevy_hanabi/src/render/sort.rs b/vendor/bevy_hanabi/src/render/sort.rs
new file mode 100644
index 00000000..42e49f57
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/sort.rs
@@ -0,0 +1,1621 @@
+use std::num::{NonZeroU32, NonZeroU64};
+
+use bevy::{
+ asset::Handle,
+ ecs::{resource::Resource, world::World},
+ platform::collections::{hash_map::Entry, HashMap},
+ render::{
+ render_resource::{
+ binding_types::{
+ storage_buffer, storage_buffer_read_only, storage_buffer_read_only_sized,
+ storage_buffer_sized, uniform_buffer,
+ },
+ BindGroup, BindGroupEntries, BindGroupLayoutDescriptor, BindGroupLayoutEntries, Buffer,
+ BufferId, CachedComputePipelineId, CachedPipelineState, ComputePipelineDescriptor,
+ PipelineCache, ShaderSize, ShaderType,
+ },
+ renderer::{RenderDevice, RenderQueue},
+ },
+ shader::Shader,
+ utils::default,
+};
+use bytemuck::{Pod, Zeroable};
+use wgpu::{
+ BufferAddress, BufferBinding, BufferDescriptor, BufferUsages, CommandEncoder, ShaderStages,
+};
+
+use super::{gpu_buffer::GpuBuffer, GpuDispatchIndirectArgs, GpuEffectMetadata, StorageType};
+// raea: the main camera's frustum for sort-fill (#52)
+use super::GpuSimParams;
+use crate::{
+ render::{aligned_buffer_vec::AlignedBufferVec, GpuIndirectIndex, GpuSpawnerParams},
+ Attribute, ParticleLayout,
+};
+
+/// GPU mergesort parameters.
+#[repr(C)]
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Pod, Zeroable, ShaderType)]
+pub(crate) struct GpuMergeParams {
+ /// Maximum number of items per list for this pass. The sort merge pass
+ /// merges two sorted lists, one of this size and the other of this size or
+ /// smaller, into a single sorted list.
+ pub max_list_size: u32,
+ /// Half of the ping-pong sort buffer to read from for this pass.
+ pub source_buffer: u32,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+struct SortFillBindGroupLayoutKey {
+ particle_min_binding_size: NonZeroU32,
+ particle_ribbon_id_offset: u32,
+ particle_age_offset: u32,
+}
+
+impl SortFillBindGroupLayoutKey {
+ pub fn from_particle_layout(particle_layout: &ParticleLayout) -> Result<Self, ()> {
+ // raea: a blended effect is sorted too, by POSITION, and may have neither (#52); the offsets only key layouts
+ let particle_ribbon_id_offset = particle_layout
+ .byte_offset(Attribute::RIBBON_ID)
+ .unwrap_or(u32::MAX);
+ let particle_age_offset = particle_layout.byte_offset(Attribute::AGE).unwrap_or(u32::MAX);
+ let key = SortFillBindGroupLayoutKey {
+ particle_min_binding_size: particle_layout.min_binding_size32(),
+ particle_ribbon_id_offset,
+ particle_age_offset,
+ };
+ Ok(key)
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+struct SortFillBindGroupKey {
+ particle: BufferId,
+ indirect_index: BufferId,
+ effect_metadata: BufferId,
+ // Bound at binding 4 with a per-effect dynamic offset; reallocates as
+ // effects grow, so it must be keyed or a stale buffer overruns the offset.
+ spawner: BufferId,
+ // raea: binding 5, the sim params (#52)
+ sim_params: BufferId,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+struct SortCopyBindGroupKey {
+ indirect_index: BufferId,
+ sort: BufferId,
+ effect_metadata: BufferId,
+ // Bound at binding 3 with a per-effect dynamic offset; reallocates as
+ // effects grow, so it must be keyed or a stale buffer overruns the offset.
+ spawner: BufferId,
+}
+
+/// GPU representation of a single dual-key value pair, with the added buffer
+/// count as prefix. This is mainly used for shorcuts in bindings, not directly
+/// as a type.
+#[repr(C)]
+#[derive(Debug, Copy, Clone, Pod, Zeroable, ShaderType)]
+struct GpuSortBufferSingleEntry {
+ /// Number of key-value pairs to sort. This is the first element of the
+ /// entire buffer.
+ pub count: u32,
+ /// Key for the first entry.
+ pub key: u32,
+ /// Secondary key for the first entry.
+ pub key2: u32,
+ /// Value for the first entry.
+ pub value: u32,
+}
+
+/// GPU resources for various compute passes related to particle sorting.
+#[derive(Resource)]
+pub struct SortBindGroups {
+ /// Sort-fill pass compute shader.
+ sort_fill_shader: Handle<Shader>,
+ /// GPU buffer of key-value pairs to sort. The buffer contains a header
+ /// 'count:u32' field storing the number of key-value pairs, and up to 2
+ /// copies of the pairs array (for ping-pong). Each kv-pair can be up to
+ /// 12B when using dual-key pairs.
+ sort_buffer: Buffer,
+ /// GPU buffer containing the [`GpuMergeParams`] structs for the various
+ /// mergesort passes.
+ merge_params_buffer: AlignedBufferVec<GpuMergeParams>,
+ /// Is any merge param changed? If so, the buffer needs to be uploaded again
+ /// to GPU, and the bind group re-created. This is quite infrequent though.
+ merge_params_changed: bool,
+ /// GPU buffer containing the [`GpuDispatchIndirect`] structs for the
+ /// sort-fill and sort passes.
+ indirect_args_buffer: GpuBuffer<GpuDispatchIndirectArgs>,
+ /// Bind group layouts for group #0 of the sort-fill compute pass.
+ sort_fill_bind_group_layout_descs:
+ HashMap<SortFillBindGroupLayoutKey, (BindGroupLayoutDescriptor, CachedComputePipelineId)>,
+ /// Bind groups for group #0 of the sort-fill compute pass.
+ sort_fill_bind_groups: HashMap<SortFillBindGroupKey, BindGroup>,
+ /// Bind group layout descriptor for group #0 of the sort compute pass.
+ sort_bind_group_layout_desc: BindGroupLayoutDescriptor,
+ /// Bind group for group #0 of the sort compute pass.
+ sort_bind_group: Option<BindGroup>,
+ /// Bind group for group #0 of the sort merge compute pass.
+ sort_merge_bind_group: Option<BindGroup>,
+ /// Bind group layout descriptor for group #0 of the sort-merge compute
+ /// pass.
+ sort_merge_bind_group_layout_desc: BindGroupLayoutDescriptor,
+ /// Bind group layout descriptor for group #0 of the sort-copy compute pass.
+ sort_copy_bind_group_layout_desc: BindGroupLayoutDescriptor,
+ /// Pipeline for sort pass.
+ sort_pipeline_id: CachedComputePipelineId,
+ /// Pipeline for sort-merge pass.
+ sort_merge_pipeline_id: CachedComputePipelineId,
+ /// Pipeline for sort-copy pass.
+ sort_copy_pipeline_id: CachedComputePipelineId,
+ /// Bind groups for group #0 of the sort-copy compute pass.
+ sort_copy_bind_groups: HashMap<SortCopyBindGroupKey, BindGroup>,
+}
+
+impl SortBindGroups {
+ /// Number of fixed merge parameter entries that select the final source
+ /// half for the sort-copy pass.
+ pub(crate) const COPY_SOURCE_PARAM_COUNT: usize = 2;
+
+ /// Size in bytes of the sort buffer.
+ ///
+ /// This includes the header 'count:u32' field, as well as up to 2 copies of
+ /// the 'pairs' array (used for ping-pong during sorting). This allows
+ /// sorting up to ~131k particles.
+ pub const SORT_BUFFER_BYTE_SIZE: u32 = 3 * 1024 * 1024;
+
+ /// Size in elements of a sort block.
+ ///
+ /// This is the number of elements that can be sorted at once by the sort
+ /// pipeline. Beyond that limit, the sort pipeline only sorts each block
+ /// individually, and we need to dispatch mergesort passes to merge those
+ /// blocks together into a single list.
+ pub const BLOCK_SIZE: u32 = 1024;
+
+ /// Allocate the GPU resources for the various sorting-related compute
+ /// passes.
+ pub fn new(
+ world: &mut World,
+ sort_fill_shader: Handle<Shader>,
+ sort_shader: Handle<Shader>,
+ sort_merge_shader: Handle<Shader>,
+ sort_copy_shader: Handle<Shader>,
+ ) -> Self {
+ let render_device = world.resource::<RenderDevice>();
+ let pipeline_cache = world.resource::<PipelineCache>();
+
+ let sort_buffer = render_device.create_buffer(&BufferDescriptor {
+ label: Some("hanabi:buffer:sort:pairs"),
+ size: Self::SORT_BUFFER_BYTE_SIZE as u64,
+ usage: BufferUsages::COPY_DST | BufferUsages::STORAGE,
+ mapped_at_creation: false,
+ });
+
+ let merge_params_align =
+ NonZeroU64::new(render_device.limits().min_storage_buffer_offset_alignment as u64)
+ .unwrap();
+ let mut merge_params_buffer = AlignedBufferVec::<GpuMergeParams>::new(
+ BufferUsages::STORAGE,
+ Some(merge_params_align),
+ Some("hanabi:buffer:merge_params".to_string()),
+ );
+ // These entries are selected by the copy pass after all merge stages.
+ // Entry 0 selects the first half and entry 1 selects the second half.
+ for source_buffer in 0..Self::COPY_SOURCE_PARAM_COUNT as u32 {
+ merge_params_buffer.push(GpuMergeParams {
+ max_list_size: 0,
+ source_buffer,
+ });
+ }
+
+ // Initial room for 256 ribbon sort dispatches; the GpuBuffer grows on demand.
+ let indirect_item_size = GpuDispatchIndirectArgs::SHADER_SIZE.get();
+ let indirect_buffer = render_device.create_buffer(&BufferDescriptor {
+ label: Some("hanabi:buffer:sort:indirect"),
+ size: 256 * indirect_item_size,
+ usage: BufferUsages::COPY_SRC
+ | BufferUsages::COPY_DST
+ | BufferUsages::STORAGE
+ | BufferUsages::INDIRECT,
+ mapped_at_creation: false,
+ });
+ let indirect_buffer = GpuBuffer::new_allocated(
+ indirect_buffer,
+ Some("hanabi:buffer:sort:indirect".to_string()),
+ );
+
+ let sort_bind_group_layout_desc = BindGroupLayoutDescriptor::new(
+ "hanabi:bgl:sort",
+ &BindGroupLayoutEntries::single(
+ ShaderStages::COMPUTE,
+ storage_buffer_sized(false, Some(NonZeroU64::new(16).unwrap())), /* count + dual
+ * kv pair */
+ ),
+ );
+
+ let sort_pipeline_id = pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
+ constants: default(),
+ label: Some("hanabi:pipeline:sort".into()),
+ layout: vec![sort_bind_group_layout_desc.clone()],
+ shader: sort_shader,
+ shader_defs: vec!["HAS_DUAL_KEY".into()],
+ entry_point: Some("sort_blocks".into()),
+ immediate_size: 0,
+ zero_initialize_workgroup_memory: false,
+ });
+
+ let sort_merge_bind_group_layout_desc = BindGroupLayoutDescriptor::new(
+ "hanabi:bgl:sort_merge",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE,
+ (
+ storage_buffer_sized(false, Some(NonZeroU64::new(16).unwrap())),
+ storage_buffer_read_only_sized(true, Some(GpuMergeParams::SHADER_SIZE)),
+ ),
+ ),
+ );
+
+ let sort_merge_pipeline_id =
+ pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
+ constants: default(),
+ label: Some("hanabi:pipeline:sort_merge".into()),
+ layout: vec![sort_merge_bind_group_layout_desc.clone()],
+ shader: sort_merge_shader,
+ shader_defs: vec!["HAS_DUAL_KEY".into()],
+ entry_point: Some("merge_sort".into()),
+ immediate_size: 0,
+ zero_initialize_workgroup_memory: false,
+ });
+
+ let alignment = render_device.limits().min_storage_buffer_offset_alignment;
+ let sort_copy_bind_group_layout_desc = BindGroupLayoutDescriptor::new(
+ "hanabi:bgl:sort_copy",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE,
+ (
+ // @group(0) @binding(0) var<storage, read_write> indirect_index_buffer :
+ // IndirectIndexBuffer;
+ storage_buffer::<GpuIndirectIndex>(false),
+ // @group(0) @binding(1) var<storage, read> sort_buffer : SortBuffer;
+ storage_buffer_read_only::<GpuSortBufferSingleEntry>(false),
+ // @group(0) @binding(2) var<storage, read_write> effect_metadatas :
+ // array<EffectMetadata>;
+ storage_buffer::<GpuEffectMetadata>(false),
+ // @group(0) @binding(3) var<storage, read> spawner : Spawner;
+ storage_buffer_read_only_sized(
+ true,
+ Some(GpuSpawnerParams::aligned_size(alignment)),
+ ),
+ // @group(0) @binding(4) var<storage, read> merge_params : MergeParams;
+ storage_buffer_read_only_sized(true, Some(GpuMergeParams::SHADER_SIZE)),
+ ),
+ ),
+ );
+
+ let sort_copy_pipeline_id =
+ pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
+ constants: default(),
+ label: Some("hanabi:pipeline:sort_copy".into()),
+ layout: vec![sort_copy_bind_group_layout_desc.clone()],
+ shader: sort_copy_shader,
+ shader_defs: vec![],
+ entry_point: Some("sort_copy".into()),
+ immediate_size: 0,
+ zero_initialize_workgroup_memory: false,
+ });
+
+ Self {
+ sort_fill_shader,
+ sort_buffer,
+ merge_params_buffer,
+ merge_params_changed: true,
+ indirect_args_buffer: indirect_buffer,
+ sort_fill_bind_group_layout_descs: default(),
+ sort_fill_bind_groups: default(),
+ sort_bind_group_layout_desc,
+ // This bind group is created later, once the pipeline and its bind group layouts are
+ // created by the pipeline cache. Technically we could create the bind group layout
+ // immediately because the PipelineCache pretends to but actually creates them
+ // on-the-fly in get_bind_group_layout(), but this is brittle as any behavior change
+ // would break Hanabi. Instead we create this bind group alongside all others, which is
+ // more consistent too.
+ sort_bind_group: None,
+ sort_merge_bind_group: None,
+ sort_merge_bind_group_layout_desc,
+ sort_copy_bind_group_layout_desc,
+ sort_pipeline_id,
+ sort_merge_pipeline_id,
+ sort_copy_pipeline_id,
+ sort_copy_bind_groups: default(),
+ }
+ }
+
+ #[inline]
+ pub fn merge_params_buffer(&self) -> &AlignedBufferVec<GpuMergeParams> {
+ &self.merge_params_buffer
+ }
+
+ /// Ensure the mergesort params are allocated for all passes to process a
+ /// given number of blocks.
+ pub fn ensure_mergesort_passes(&mut self, num_items: u32) {
+ let num_blocks = num_items.div_ceil(Self::BLOCK_SIZE);
+ if num_blocks <= 1 {
+ return;
+ }
+ let num_passes = 32 - (num_blocks - 1).leading_zeros(); // log2(n-1) rounded up
+
+ // Check if already allocated
+ let existing_num_passes =
+ (self.merge_params_buffer.len() - Self::COPY_SOURCE_PARAM_COUNT) as u32;
+ if existing_num_passes >= num_passes {
+ return;
+ }
+
+ // Allocate missing entries
+ let mut list_size = 1024u32 << existing_num_passes;
+ for pass in existing_num_passes..num_passes {
+ self.merge_params_buffer.push(GpuMergeParams {
+ max_list_size: list_size,
+ source_buffer: pass % 2,
+ });
+ list_size <<= 1;
+ }
+
+ self.merge_params_changed = true;
+ }
+
+ pub fn write_merge_params(
+ &mut self,
+ render_device: &RenderDevice,
+ render_queue: &RenderQueue,
+ ) -> bool {
+ if !self.merge_params_changed {
+ return false;
+ }
+ self.merge_params_changed = false;
+ if self
+ .merge_params_buffer
+ .write_buffer(render_device, render_queue)
+ {
+ self.sort_merge_bind_group = None;
+ self.sort_copy_bind_groups.clear();
+ true
+ } else {
+ false
+ }
+ }
+
+ #[inline]
+ pub fn clear_indirect_args_buffer(&mut self) {
+ self.indirect_args_buffer.clear();
+ }
+
+ /// Allocate a [`GpuDispatchIndirectArgs`] slot in the global shared buffer.
+ #[inline]
+ pub fn allocate_indirect_args(&mut self) -> u32 {
+ self.indirect_args_buffer.allocate()
+ }
+
+ #[inline]
+ pub fn get_indirect_args_byte_offset(&self, index: u32) -> BufferAddress {
+ self.indirect_args_buffer.item_size() as BufferAddress * index as BufferAddress
+ }
+
+ #[inline]
+ #[allow(dead_code)]
+ pub fn sort_buffer(&self) -> &Buffer {
+ &self.sort_buffer
+ }
+
+ #[inline]
+ pub fn indirect_args_buffer(&self) -> Option<&Buffer> {
+ self.indirect_args_buffer.buffer()
+ }
+
+ #[inline]
+ pub fn sort_pipeline_id(&self) -> CachedComputePipelineId {
+ self.sort_pipeline_id
+ }
+
+ #[inline]
+ pub fn sort_merge_pipeline_id(&self) -> CachedComputePipelineId {
+ self.sort_merge_pipeline_id
+ }
+
+ /// Check if the sort pipeline is ready to run for the given effect
+ /// instance.
+ ///
+ /// This ensures all compute pipelines are compiled and ready to be used
+ /// this frame.
+ pub fn is_pipeline_ready(
+ &self,
+ particle_layout: &ParticleLayout,
+ pipeline_cache: &PipelineCache,
+ ) -> bool {
+ // Validate the sort-fill pipeline. It was created and queued for compile by
+ // ensure_sort_fill_bind_group_layout(), which normally is called just before
+ // is_pipeline_ready().
+ let Some(pipeline_id) = self.get_sort_fill_pipeline_id(particle_layout) else {
+ return false;
+ };
+ if !matches!(
+ pipeline_cache.get_compute_pipeline_state(pipeline_id),
+ CachedPipelineState::Ok(_)
+ ) {
+ return false;
+ }
+
+ // The 2 pipelines below are created and queued for compile in new(), so are
+ // almost always ready.
+ // FIXME - they could be checked once a frame only, not once per effect...
+
+ // Validate the sort pipeline
+ if !matches!(
+ pipeline_cache.get_compute_pipeline_state(self.sort_pipeline_id()),
+ CachedPipelineState::Ok(_)
+ ) {
+ return false;
+ }
+
+ // Validate the sort-merge pipeline.
+ if !matches!(
+ pipeline_cache.get_compute_pipeline_state(self.sort_merge_pipeline_id()),
+ CachedPipelineState::Ok(_)
+ ) {
+ return false;
+ }
+
+ // Validate the sort-copy pipeline
+ if !matches!(
+ pipeline_cache.get_compute_pipeline_state(self.sort_copy_pipeline_id()),
+ CachedPipelineState::Ok(_)
+ ) {
+ return false;
+ }
+
+ true
+ }
+
+ #[inline]
+ pub fn prepare_buffers(&mut self, render_device: &RenderDevice) {
+ self.indirect_args_buffer.prepare_buffers(render_device);
+ }
+
+ #[inline]
+ pub fn write_buffers(&self, command_encoder: &mut CommandEncoder) {
+ self.indirect_args_buffer.write_buffers(command_encoder);
+ }
+
+ #[inline]
+ pub fn clear_previous_frame_resizes(&mut self) {
+ self.indirect_args_buffer.clear_previous_frame_resizes();
+ }
+
+ pub fn ensure_sort_fill_bind_group_layout_desc(
+ &mut self,
+ render_device: &RenderDevice,
+ pipeline_cache: &PipelineCache,
+ particle_layout: &ParticleLayout,
+ ) -> Result<&BindGroupLayoutDescriptor, ()> {
+ let key = SortFillBindGroupLayoutKey::from_particle_layout(particle_layout)?;
+ let (layout, _) = self
+ .sort_fill_bind_group_layout_descs
+ .entry(key)
+ .or_insert_with(|| {
+ let alignment = render_device.limits().min_storage_buffer_offset_alignment;
+ let bind_group_layout_desc = BindGroupLayoutDescriptor::new(
+ "hanabi:bgl:sort_fill",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE,
+ (
+ // @group(0) @binding(0) var<storage, read_write> sort_buffer :
+ // SortBuffer;
+ storage_buffer::<GpuSortBufferSingleEntry>(false),
+ // @group(0) @binding(1) var<storage, read> particle_buffer :
+ // RawParticleBuffer;
+ storage_buffer_read_only_sized(
+ false,
+ Some(key.particle_min_binding_size.into()),
+ ),
+ // @group(0) @binding(2) var<storage, read> indirect_index_buffer :
+ // array<u32>;
+ storage_buffer_read_only::<GpuIndirectIndex>(false),
+ // @group(0) @binding(3) var<storage, read_write> effect_metadatas :
+ // array<EffectMetadata>;
+ storage_buffer::<GpuEffectMetadata>(false),
+ // @group(0) @binding(4) var<storage, read> spawner : Spawner;
+ storage_buffer_read_only_sized(
+ true,
+ Some(GpuSpawnerParams::aligned_size(alignment)),
+ ),
+ // raea: @group(0) @binding(5) var<uniform> sim_params : SimParams; (#52)
+ uniform_buffer::<GpuSimParams>(false),
+ ),
+ ),
+ );
+ let pipeline_id =
+ pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
+ constants: default(),
+ label: Some("hanabi:pipeline:sort_fill".into()),
+ layout: vec![bind_group_layout_desc.clone()],
+ shader: self.sort_fill_shader.clone(),
+ shader_defs: vec!["HAS_DUAL_KEY".into()],
+ entry_point: Some("sort_fill".into()),
+ immediate_size: 0,
+ zero_initialize_workgroup_memory: false,
+ });
+ (bind_group_layout_desc, pipeline_id)
+ });
+ Ok(layout)
+ }
+
+ // We currently only use the bind group layout internally in
+ // ensure_sort_fill_bind_group()
+ #[allow(dead_code)]
+ pub fn get_sort_fill_bind_group_layout_desc(
+ &self,
+ particle_layout: &ParticleLayout,
+ ) -> Option<&BindGroupLayoutDescriptor> {
+ let key = SortFillBindGroupLayoutKey::from_particle_layout(particle_layout).ok()?;
+ self.sort_fill_bind_group_layout_descs
+ .get(&key)
+ .map(|(layout, _)| layout)
+ }
+
+ pub fn get_sort_fill_pipeline_id(
+ &self,
+ particle_layout: &ParticleLayout,
+ ) -> Option<CachedComputePipelineId> {
+ let key = SortFillBindGroupLayoutKey::from_particle_layout(particle_layout).ok()?;
+ self.sort_fill_bind_group_layout_descs
+ .get(&key)
+ .map(|(_, pipeline_id)| *pipeline_id)
+ }
+
+ pub fn sort_copy_pipeline_id(&self) -> CachedComputePipelineId {
+ self.sort_copy_pipeline_id
+ }
+
+ pub fn ensure_sort_fill_bind_group(
+ &mut self,
+ render_device: &RenderDevice,
+ particle_layout: &ParticleLayout,
+ particle: &Buffer,
+ indirect_index: &Buffer,
+ effect_metadata: &Buffer,
+ spawner_buffer: &Buffer,
+ sim_params: &Buffer, // raea: (#52)
+ pipeline_cache: &PipelineCache,
+ ) -> Result<&BindGroup, ()> {
+ let key = SortFillBindGroupKey {
+ particle: particle.id(),
+ indirect_index: indirect_index.id(),
+ effect_metadata: effect_metadata.id(),
+ spawner: spawner_buffer.id(),
+ sim_params: sim_params.id(), // raea: (#52)
+ };
+ let entry = self.sort_fill_bind_groups.entry(key);
+ let bind_group = match entry {
+ Entry::Occupied(entry) => entry.into_mut(),
+ Entry::Vacant(entry) => {
+ // Note: can't use get_bind_group_layout() because the function call mixes the
+ // lifetimes of the two hash maps and complains the bind group one is already
+ // borrowed. Doing a manual access to the layout one instead makes the compiler
+ // happy.
+ let key = SortFillBindGroupLayoutKey::from_particle_layout(particle_layout)?;
+ let layout_desc = &self
+ .sort_fill_bind_group_layout_descs
+ .get(&key)
+ .ok_or(())?
+ .0;
+ entry.insert(render_device.create_bind_group(
+ "hanabi:bg:sort_fill",
+ &pipeline_cache.get_bind_group_layout(layout_desc),
+ &BindGroupEntries::sequential((
+ // @group(0) @binding(0) var<storage, read_write> pairs:
+ // array<KeyValuePair>;
+ self.sort_buffer.as_entire_binding(),
+ // @group(0) @binding(1) var<storage, read> particle_buffer:
+ // ParticleBuffer;
+ particle.as_entire_binding(),
+ // @group(0) @binding(2) var<storage, read> indirect_index_buffer :
+ // array<u32>;
+ indirect_index.as_entire_binding(),
+ // @group(0) @binding(3) var<storage, read_write> effect_metadatas :
+ // array<EffectMetadata>;
+ effect_metadata.as_entire_binding(),
+ // @group(0) @binding(4) var<storage, read> spawner : Spawner;
+ BufferBinding {
+ buffer: spawner_buffer,
+ offset: 0,
+ size: Some(GpuSpawnerParams::aligned_size(
+ render_device.limits().min_storage_buffer_offset_alignment,
+ )),
+ },
+ // raea: @group(0) @binding(5) var<uniform> sim_params : SimParams; (#52)
+ sim_params.as_entire_binding(),
+ )),
+ ))
+ }
+ };
+ Ok(bind_group)
+ }
+
+ pub fn sort_fill_bind_group(
+ &self,
+ particle: BufferId,
+ indirect_index: BufferId,
+ effect_metadata: BufferId,
+ spawner: BufferId,
+ sim_params: BufferId, // raea: (#52)
+ ) -> Option<&BindGroup> {
+ let key = SortFillBindGroupKey {
+ particle,
+ indirect_index,
+ effect_metadata,
+ spawner,
+ sim_params,
+ };
+ self.sort_fill_bind_groups.get(&key)
+ }
+
+ /// Ensure the bind group for the sort pass is created.
+ pub fn ensure_sort_bind_group(
+ &mut self,
+ render_device: &RenderDevice,
+ pipeline_cache: &PipelineCache,
+ ) -> &BindGroup {
+ if self.sort_bind_group.is_none() {
+ let sort_bind_group = render_device.create_bind_group(
+ "hanabi:bg:sort",
+ &pipeline_cache.get_bind_group_layout(&self.sort_bind_group_layout_desc),
+ // @group(0) @binding(0) var<storage, read_write> pairs : array<KeyValuePair>;
+ &BindGroupEntries::single(self.sort_buffer.as_entire_binding()),
+ );
+ self.sort_bind_group = Some(sort_bind_group);
+ }
+ self.sort_bind_group.as_ref().unwrap()
+ }
+
+ #[inline]
+ pub fn sort_bind_group(&self) -> Option<&BindGroup> {
+ self.sort_bind_group.as_ref()
+ }
+
+ /// Ensure the bind group for the sort merge pass is created.
+ pub fn ensure_sort_merge_bind_group(
+ &mut self,
+ render_device: &RenderDevice,
+ pipeline_cache: &PipelineCache,
+ ) -> &BindGroup {
+ if self.sort_merge_bind_group.is_none() {
+ let sort_merge_bind_group = render_device.create_bind_group(
+ "hanabi:bg:sort_merge",
+ &pipeline_cache.get_bind_group_layout(&self.sort_merge_bind_group_layout_desc),
+ &BindGroupEntries::sequential((
+ // @group(0) @binding(0) var<storage, read_write> pairs : array<KeyValuePair>;
+ self.sort_buffer.as_entire_binding(),
+ // @group(0) @binding(1) var<storage, read> merge_params : MergeParams;
+ self.merge_params_buffer.range_binding(0, 1).unwrap(),
+ )),
+ );
+ self.sort_merge_bind_group = Some(sort_merge_bind_group);
+ }
+ self.sort_merge_bind_group.as_ref().unwrap()
+ }
+
+ #[inline]
+ pub fn sort_merge_bind_group(&self) -> Option<&BindGroup> {
+ self.sort_merge_bind_group.as_ref()
+ }
+
+ pub fn ensure_sort_copy_bind_group(
+ &mut self,
+ render_device: &RenderDevice,
+ indirect_index_buffer: &Buffer,
+ effect_metadata_buffer: &Buffer,
+ spawner_buffer: &Buffer,
+ pipeline_cache: &PipelineCache,
+ ) -> Result<&BindGroup, ()> {
+ let key = SortCopyBindGroupKey {
+ indirect_index: indirect_index_buffer.id(),
+ sort: self.sort_buffer.id(),
+ effect_metadata: effect_metadata_buffer.id(),
+ spawner: spawner_buffer.id(),
+ };
+ let entry = self.sort_copy_bind_groups.entry(key);
+ let bind_group = match entry {
+ Entry::Occupied(entry) => entry.into_mut(),
+ Entry::Vacant(entry) => {
+ entry.insert(render_device.create_bind_group(
+ "hanabi:bg:sort_copy",
+ &pipeline_cache.get_bind_group_layout(&self.sort_copy_bind_group_layout_desc),
+ &BindGroupEntries::sequential((
+ // @group(0) @binding(0) var<storage, read_write> indirect_index_buffer
+ // : IndirectIndexBuffer;
+ indirect_index_buffer.as_entire_binding(),
+ // @group(0) @binding(1) var<storage, read> sort_buffer : SortBuffer;
+ self.sort_buffer.as_entire_binding(),
+ // @group(0) @binding(2) var<storage, read_write> effect_metadatas :
+ // array<EffectMetadata>;
+ effect_metadata_buffer.as_entire_binding(),
+ // @group(0) @binding(3) var<storage, read> spawner : Spawner;
+ BufferBinding {
+ buffer: spawner_buffer,
+ offset: 0,
+ size: Some(GpuSpawnerParams::aligned_size(
+ render_device.limits().min_storage_buffer_offset_alignment,
+ )),
+ },
+ // @group(0) @binding(4) var<storage, read> merge_params : MergeParams;
+ self.merge_params_buffer.range_binding(0, 1).unwrap(),
+ )),
+ ))
+ }
+ };
+ Ok(bind_group)
+ }
+
+ pub fn sort_copy_bind_group(
+ &self,
+ indirect_index: BufferId,
+ effect_metadata: BufferId,
+ spawner: BufferId,
+ ) -> Option<&BindGroup> {
+ let key = SortCopyBindGroupKey {
+ indirect_index,
+ sort: self.sort_buffer.id(),
+ effect_metadata,
+ spawner,
+ };
+ self.sort_copy_bind_groups.get(&key)
+ }
+}
+
+#[cfg(all(test, feature = "gpu_tests"))]
+mod gpu_tests {
+ use bevy::{
+ math::{FloatOrd, UVec3},
+ render::{
+ render_resource::{
+ binding_types::{storage_buffer_read_only_sized, storage_buffer_sized},
+ BindGroupEntries, BindGroupLayoutEntries, ShaderSize, ShaderType,
+ },
+ renderer::{RenderDevice, RenderQueue},
+ },
+ };
+ use bytemuck::{cast_slice, Pod, Zeroable};
+ use rand::RngExt;
+ use wgpu::{
+ BufferDescriptor, BufferUsages, BufferView, ComputePassDescriptor,
+ ComputePipelineDescriptor, PipelineCompilationOptions, PipelineLayoutDescriptor,
+ ShaderModuleDescriptor, ShaderSource, ShaderStages,
+ };
+
+ use crate::{
+ plugin::{VFX_SORT_MERGE_WESL, VFX_SORT_WESL},
+ render::{aligned_buffer_vec::AlignedBufferVec, sort::GpuMergeParams, StorageType},
+ test_utils::*,
+ };
+
+ #[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable, ShaderType)]
+ #[repr(C)]
+ struct DualKeyValuePair {
+ pub key: u32,
+ pub key2: f32,
+ pub value: u32,
+ }
+
+ // Ignore weirdnesses with f32 NaN etc. here, we should never have a key with
+ // such values.
+ impl std::cmp::Eq for DualKeyValuePair {}
+
+ impl std::cmp::PartialOrd for DualKeyValuePair {
+ fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+ Some(self.cmp(other))
+ }
+ }
+
+ impl std::cmp::Ord for DualKeyValuePair {
+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+ if self.key != other.key {
+ return self.key.cmp(&other.key);
+ }
+ FloatOrd(self.key2).cmp(&FloatOrd(other.key2))
+ }
+ }
+
+ /// Thread-level local register sort with Batcher's odd-even mergesort.
+ /// - spawn 64 threads (one workgroup)
+ /// - each thread sorts 16 elements (see numItemPerThreads in shader)
+ /// - no global sorting, only 16-element sorted sub-lists in the final array
+ #[test]
+ fn test_batcher_odd_even_mergesort() {
+ let mut test = SortTest::new();
+
+ let num_kv = 1024.min(test.max_block_size);
+
+ let mut expected = Vec::with_capacity(num_kv as usize);
+ for i in 0..num_kv as usize {
+ // Repeat both keys within each local run to exercise secondary-key
+ // ordering and duplicate-key payload preservation.
+ expected.push(DualKeyValuePair {
+ key: (i % 4) as u32,
+ key2: ((i / 4) % 2) as f32,
+ value: i as u32,
+ });
+ }
+
+ let num_items_per_thread = 16; // see shader
+
+ // Dispatch to GPU
+ let workgroups = UVec3::new(1, 1, 1);
+ let view = test.dispatch(
+ "test_batcher_odd_even_mergesort",
+ num_kv,
+ &expected[..],
+ workgroups,
+ );
+
+ // Validate content
+ let view_slice: &[DualKeyValuePair] = cast_slice(&view[4..]);
+ for (chunk_index, actual) in view_slice.chunks(num_items_per_thread).enumerate() {
+ assert!(
+ actual.windows(2).all(|pair| pair[0] <= pair[1]),
+ "local run {chunk_index} is not sorted"
+ );
+ let mut values: Vec<_> = actual.iter().map(|pair| pair.value).collect();
+ values.sort_unstable();
+ let first = chunk_index * num_items_per_thread;
+ let expected: Vec<_> = (first..first + actual.len()).map(|i| i as u32).collect();
+ assert_eq!(values, expected, "local run {chunk_index} lost a payload");
+ }
+ }
+
+ /// Workgroup-level sort.
+ ///
+ /// Dispatch a single sort of 1024 items, which fit inside workgroup-local
+ /// shared memory. Uses the block sort algorithm to co-operatively sort
+ /// the items in a single pass with 64 threads, without relying on
+ /// storage buffers (except for final output).
+ #[test]
+ fn test_block_sort() {
+ let mut test = SortTest::new();
+
+ println!("max_block_size = {}", test.max_block_size);
+ let block_size = 1024; // see shader
+ assert!(block_size <= test.max_block_size);
+
+ // Avoid multiples of the block size, try to exercise edge case sizes.
+ let num_kv = 500.min(block_size - 3);
+
+ let mut expected = Vec::with_capacity(num_kv as usize);
+ for i in 0..num_kv as usize {
+ // Repeat both keys within each local run to exercise secondary-key
+ // ordering and duplicate-key payload preservation.
+ expected.push(DualKeyValuePair {
+ key: 63 - (i % 64) as u32,
+ key2: ((i / 64) % 16) as f32,
+ value: i as u32,
+ });
+ }
+ let s = expected.chunks(8).fold("".to_string(), |acc, x| {
+ x.iter().fold(acc, |acc, x| {
+ format!("{acc} ({0:03},{1:03},{2:04})", x.key, x.key2, x.value)
+ }) + "\n"
+ });
+ eprintln!("input:\n{s}\n[...]");
+
+ //let num_items_per_thread = num_kv.div_ceil(64) as usize;
+ let num_items_per_thread = 16; // see shader
+
+ // Dispatch to GPU
+ let workgroups = UVec3::new(1, 1, 1);
+ let view = test.dispatch("test_block_sort", num_kv, &expected[..], workgroups);
+
+ // Validate content
+ let count_slice: &[u32] = cast_slice(&view[..4]);
+ assert_eq!(count_slice[0], num_kv); // should not be overwritten
+ let view_slice: &[DualKeyValuePair] = cast_slice(&view[4..]);
+ for (chunk_index, actual) in view_slice.chunks(block_size as usize).enumerate() {
+ let s = actual.chunks(8).fold("".to_string(), |acc, x| {
+ x.iter().fold(acc, |acc, x| {
+ format!("{acc} ({0:03},{1:03},{2:04})", x.key, x.key2, x.value)
+ }) + "\n"
+ });
+ eprintln!("output chunk #{chunk_index}:\n{s}");
+ assert!(
+ actual.windows(2).all(|pair| pair[0] <= pair[1]),
+ "local run {chunk_index} is not sorted"
+ );
+ let mut values: Vec<_> = actual.iter().map(|pair| pair.value).collect();
+ values.sort_unstable();
+ let first = chunk_index * num_items_per_thread;
+ let expected: Vec<_> = (first..first + actual.len()).map(|i| i as u32).collect();
+ assert_eq!(values, expected, "local run {chunk_index} lost a payload");
+ }
+ }
+
+ fn format_slice(data: &[DualKeyValuePair]) -> String {
+ let mut lid = 0;
+ data.chunks(8).fold("".to_string(), |acc, chunk| {
+ let sep = if lid % 1024 == 0 { "\n" } else { "" };
+ let line = chunk.iter().fold(format!("[{lid:04}]"), |acc, x| {
+ format!("{acc} ({0:03},{1:03},{2:04})", x.key, x.key2, x.value)
+ });
+ lid += chunk.len();
+ format!("{acc}{sep}{line}\n")
+ })
+ }
+
+ /// Test sorting a single non-full block (less than 1024 elements).
+ #[test]
+ fn test_sort_block() {
+ let mut test = SortTest::new();
+
+ let num_kv = 257u32;
+
+ let mut expected = Vec::with_capacity(num_kv as usize);
+ for i in 0..num_kv {
+ expected.push(DualKeyValuePair {
+ key: 256 - i,
+ key2: ((i / 4) % 3) as f32,
+ value: i,
+ });
+ }
+
+ // Dispatch to GPU
+ let workgroups = UVec3::new(1, 1, 1);
+ let view = test.dispatch("sort_blocks", num_kv, &expected[..], workgroups);
+
+ // Sort locally on CPU
+ expected.sort(); // stable
+
+ // Compare results
+ assert_eq!(cast_slice::<_, u32>(&view[..4]), &[num_kv]); // unmodified
+ let actual = cast_slice::<_, DualKeyValuePair>(&view[4..]);
+ assert_eq!(actual, expected.as_slice());
+ }
+
+ /// Calculate the merge path for a parallel merge.
+ #[test]
+ fn test_calc_merge_path() {
+ let mut test = SortTest::new();
+
+ let block_size = 1024.min(test.max_block_size); // total input buffer size
+ let list_len = block_size / 2 - 3;
+ let num_kv = list_len * 2; // ensure we don't have an odd size
+ println!("block_size = {}", block_size);
+ println!("list_len = {}", list_len);
+
+ let mut expected = Vec::with_capacity(num_kv as usize);
+ let mut values = vec![
+ DualKeyValuePair {
+ key: 0,
+ key2: 0.0,
+ value: 0,
+ };
+ num_kv as usize
+ ];
+ assert_eq!(num_kv % 2, 0);
+ assert_eq!(num_kv / 2, list_len);
+ {
+ let (values_a, values_b) = values.split_at_mut(list_len as usize);
+ let mut thread_rng = rand::rng();
+ let max_value = list_len - 30; // limit the range to force duplicate values
+ for i in 0..list_len {
+ values_a[i as usize].key = thread_rng.random_range(0..max_value);
+ values_a[i as usize].key2 = i as f32 * 0.1;
+ values_a[i as usize].value = i;
+
+ values_b[i as usize].key = thread_rng.random_range(0..max_value);
+ values_b[i as usize].key2 = i as f32 * 0.1;
+ values_b[i as usize].value = list_len + i;
+
+ expected.push(values_a[i as usize]);
+ expected.push(values_b[i as usize]);
+ }
+ values_a.sort();
+ values_b.sort();
+ }
+
+ // Dispatch to GPU
+ let workgroups = UVec3::new(1, 1, 1);
+ let view = test.dispatch("test_calc_merge_path", num_kv, &values[..], workgroups);
+
+ // Calculate the expected result by doing the actual sort, and deriving all the
+ // merge paths from it.
+ expected.sort();
+ let total_path_len = list_len * 2;
+ let path_len = total_path_len.div_ceil(64);
+ let num_paths = total_path_len.div_ceil(path_len);
+ println!("path_len = {path_len}");
+ println!("num_paths = {num_paths}");
+ let mut paths: Vec<_> = (0..num_paths)
+ .map(|ipath| {
+ let start = (ipath * path_len) as usize;
+ let end = (start + path_len as usize).min(total_path_len as usize);
+ let slice = &expected[start..end];
+ let mut ia = 0;
+ for kv in slice {
+ if kv.value < list_len {
+ ia += 1;
+ }
+ }
+ ia
+ })
+ .collect();
+ for i in 1..paths.len() {
+ // The path at index #i is actually the cumulated path from start. Above we
+ // counted only the i_a within a cross-diagonal interval, but the GPU calculates
+ // the total i_a for the path starting at the beginning of the block up to the
+ // diagonal.
+ paths[i] += paths[i - 1];
+ }
+ //println!("EXPECTED:");
+ // for (i, exp_val) in paths.iter().enumerate() {
+ // let diag = (i as u32 + 1) * path_len;
+ // let i_a = *exp_val;
+ // let i_b = diag - i_a;
+ // println!("+ PATH #{i} : diag={diag} i_a={i_a} i_b={i_b}");
+ // let s: String = (0..path_len)
+ // .map(|idx| expected[idx as usize + (i * path_len as usize)])
+ // .fold("".to_string(), |acc, x| {
+ // format!(
+ // "{} {}[{},{},{}]",
+ // acc,
+ // if x.value < list_len { 'A' } else { 'B' },
+ // x.key,
+ // x.key2,
+ // x.value
+ // )
+ // });
+ // println!(" {s}");
+ // }
+
+ // Validate content
+ let view_slice: &[DualKeyValuePair] = cast_slice(&view[4..]);
+ assert_eq!(view_slice.len(), list_len as usize * 2);
+ assert!(view_slice.len() >= paths.len());
+ for (i, exp_val) in paths.iter().enumerate() {
+ // The test shader stores the resulting i_a[] into the 'value' of the first N
+ // entries of the sort buffer, and the diagonal value of the path into the 'key'
+ // field.
+
+ let calc_diag = view_slice[i].key;
+ let exp_diag = ((i as u32 + 1) * path_len).min(total_path_len);
+ assert_eq!(calc_diag, exp_diag);
+
+ let calc_ia = view_slice[i].value;
+ let exp_ia = *exp_val;
+ assert_eq!(calc_ia, exp_ia);
+
+ // println!(
+ // "-> [{}] diag={} a_i={} b_i={} [EXPECTED:{}]",
+ // i,
+ // view_slice[i].key,
+ // view_slice[i].value,
+ // view_slice[i].key - view_slice[i].value,
+ // *exp_val
+ // );
+ }
+ }
+
+ /// Calculate the effect index from a particle index using a binary search
+ /// of the base particle prefix sum.
+ #[test]
+ fn test_binary_search_prefix_sum() {
+ let mut test = SortTest::new();
+
+ let num_particle = 1024.min(test.max_block_size);
+
+ // We use the sort buffer as a generic test data I/O storage. The pairs array is
+ // exactly sized to the number of particles to test.
+ //
+ // Input:
+ // - count: number of effects
+ // - pairs:
+ // - key[..num_effects] : prefix sum
+ //
+ // Output:
+ // - pairs:
+ // - value[..num_particles] : index of the effect for the given particle
+ let effects = [0, 35, 399, 1000];
+ assert!((effects.len() as u32) < num_particle);
+ let values: Vec<_> = (0..num_particle as usize)
+ .map(|i| DualKeyValuePair {
+ key: effects.get(i).copied().unwrap_or(0xDEAD0000),
+ key2: i as f32 * 0.1, // unused
+ value: i as u32, // unused
+ })
+ .collect();
+
+ // Dispatch to GPU
+ let workgroups = UVec3::new(1, 1, 1);
+ let view = test.dispatch(
+ "test_find_effect_from_particle",
+ effects.len() as u32,
+ &values[..],
+ workgroups,
+ );
+
+ // Validate content
+ let view_slice: &[DualKeyValuePair] = cast_slice(&view[4..]);
+ for (i, kv) in view_slice.iter().enumerate() {
+ //println!("[#{}] k={} k2={} v={}", i, kv.key, kv.key2, kv.value);
+
+ // Do the binary search on CPU
+ let mut effect_index = usize::MAX;
+ for (idx, base_particle) in effects.iter().enumerate().rev() {
+ if i as u32 >= *base_particle {
+ effect_index = idx;
+ break;
+ }
+ }
+ assert!(effect_index <= effects.len());
+
+ // Validate the GPU result against the CPU one
+ assert_eq!(
+ effect_index as u32, kv.value,
+ "Test failed for particle {} : expected effect index {}, got {}",
+ i, effect_index, kv.value
+ );
+ }
+ }
+
+ /// Helper for all GPU sort tests.
+ struct SortTest {
+ #[allow(dead_code)]
+ pub renderer: MockRenderer,
+ pub device: RenderDevice,
+ pub queue: RenderQueue,
+ /// Max block size calculated from GPU device shared workgroup memory
+ /// limit.
+ pub max_block_size: u32,
+ }
+
+ impl SortTest {
+ /// Create a new GPU sort test instance.
+ fn new() -> SortTest {
+ let renderer = MockRenderer::new();
+ let device = renderer.device();
+ let queue = renderer.queue();
+
+ println!(
+ "max_compute_workgroup_storage_size = {}",
+ device.limits().max_compute_workgroup_storage_size
+ );
+
+ // SAFETY : for debugging only
+ #[allow(unsafe_code)]
+ unsafe {
+ device.wgpu_device().start_graphics_debugger_capture()
+ };
+
+ // Clamp max block size to the device's reported storage
+ let max_block_size = device.limits().max_compute_workgroup_storage_size
+ / (DualKeyValuePair::SHADER_SIZE.get() as u32);
+ println!("max_block_size = {}", max_block_size);
+
+ Self {
+ renderer,
+ device,
+ queue,
+ max_block_size,
+ }
+ }
+
+ /// Dispatch the sort test with the given sort buffer data.
+ ///
+ /// The `entry_point` is the compute shader entry point name to execute
+ /// (often a test-only entry point). The `count` and `pairs` are the
+ /// data of the sort buffer to upload to GPU before dispatching.
+ /// `workgroups` is the number of workgroups to dispatch.
+ ///
+ /// # Returns
+ ///
+ /// A view over the GPU buffer content, downloaded from GPU to CPU after
+ /// the GPU executed the sort shader test.
+ fn dispatch(
+ &mut self,
+ entry_point: &str,
+ count: u32,
+ pairs: &[DualKeyValuePair],
+ workgroups: UVec3,
+ ) -> BufferView {
+ // Allocate sort buffer
+ let byte_size = 4 + pairs.len() as u64 * DualKeyValuePair::SHADER_SIZE.get();
+ let sort_buffer = self.device.create_buffer(&BufferDescriptor {
+ label: Some("sort_buffer"),
+ size: byte_size,
+ usage: BufferUsages::STORAGE | BufferUsages::MAP_READ,
+ mapped_at_creation: true,
+ });
+ {
+ // Scope get_mapped_range_mut() to force a drop before unmap()
+ {
+ let mut mapped = sort_buffer
+ .slice(..)
+ .get_mapped_range_mut()
+ .expect("Buffer must be mapped for writing");
+ mapped.slice(..4).copy_from_slice(cast_slice(&[count]));
+ mapped.slice(4..).copy_from_slice(cast_slice(pairs));
+ }
+ sort_buffer.unmap();
+ }
+
+ // Create GPU resources
+ let bind_group_layout = self.device.create_bind_group_layout(
+ "bind_group_layout",
+ &BindGroupLayoutEntries::single(
+ ShaderStages::COMPUTE,
+ storage_buffer_sized(false, None),
+ ),
+ );
+ let bind_group = self.device.create_bind_group(
+ None,
+ &bind_group_layout,
+ &BindGroupEntries::single(sort_buffer.as_entire_binding()),
+ );
+ let pipeline_layout = self
+ .device
+ .create_pipeline_layout(&PipelineLayoutDescriptor {
+ label: Some("pipeline_layout"),
+ bind_group_layouts: &[Some(&bind_group_layout)],
+ immediate_size: 0,
+ });
+ let src = crate::test_utils::compile_wesl(
+ VFX_SORT_WESL.as_ref(),
+ &["HAS_DUAL_KEY", "TEST"],
+ &[],
+ )
+ .unwrap();
+ let shader_module =
+ self.device
+ .create_and_validate_shader_module(ShaderModuleDescriptor {
+ label: Some("vfx_sort"),
+ source: ShaderSource::Wgsl(src.into()),
+ });
+ let pipeline = self
+ .device
+ .create_compute_pipeline(&ComputePipelineDescriptor {
+ label: Some(entry_point),
+ layout: Some(&pipeline_layout),
+ module: &shader_module,
+ entry_point: Some(entry_point),
+ compilation_options: PipelineCompilationOptions {
+ constants: &[],
+ zero_initialize_workgroup_memory: false,
+ },
+ cache: None,
+ });
+
+ let mut encoder = self
+ .device
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("test"),
+ });
+
+ // Dispatch test
+ {
+ let mut compute_pass = encoder.begin_compute_pass(&ComputePassDescriptor {
+ label: Some(entry_point),
+ timestamp_writes: None,
+ });
+ compute_pass.set_pipeline(&pipeline);
+ compute_pass.set_bind_group(0, &bind_group, &[]);
+ compute_pass.dispatch_workgroups(workgroups.x, workgroups.y, workgroups.z);
+ }
+
+ // Submit command queue and wait for execution
+ println!("Executing pipeline...");
+ let command_buffer = encoder.finish();
+ self.queue.submit([command_buffer]);
+ let (tx, rx) = futures::channel::oneshot::channel();
+ self.queue.on_submitted_work_done(move || {
+ tx.send(()).unwrap();
+ });
+ let _ = self.device.poll(wgpu::PollType::Wait {
+ submission_index: None,
+ timeout: None,
+ });
+ let _ = futures::executor::block_on(rx);
+ println!("Pipeline executed");
+
+ // SAFETY : for debugging only
+ #[allow(unsafe_code)]
+ unsafe {
+ self.device.wgpu_device().stop_graphics_debugger_capture()
+ };
+
+ // Read back (GPU -> CPU)
+ println!("Downloading result buffer from GPU to CPU...");
+ let buffer_slice = sort_buffer.slice(..);
+ let (tx, rx) = futures::channel::oneshot::channel();
+ buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
+ tx.send(result).unwrap();
+ });
+ let _ = self.device.poll(wgpu::PollType::Wait {
+ submission_index: None,
+ timeout: None,
+ });
+ let _ = futures::executor::block_on(rx);
+ let view = buffer_slice
+ .get_mapped_range()
+ .expect("Buffer must be mapped for reading");
+ assert_eq!(view.len(), byte_size as usize);
+ println!("Result buffer downloaded to CPU");
+
+ view
+ }
+ }
+
+ #[test]
+ fn test_merge() {
+ let mut test = MergeTest::new();
+
+ // > 2 block sizes, but not exact
+ let num_particle = 3000;
+
+ // Each block of 1024 particles is sorted, but the total list is not
+ let mut values: Vec<_> = (0..num_particle)
+ .map(|i| DualKeyValuePair {
+ key: (i / 16) % 64,
+ key2: (i % 16) as f32 * 0.1,
+ value: i,
+ })
+ .collect();
+ let dummy = DualKeyValuePair {
+ key: u32::MAX,
+ key2: f32::INFINITY,
+ value: u32::MAX,
+ };
+ values.extend((0..num_particle).map(|_| dummy));
+
+ let num_passes = 2;
+ let merge_params = (0..num_passes)
+ .map(|i| GpuMergeParams {
+ max_list_size: 1024 << i,
+ source_buffer: i % 2,
+ })
+ .collect::<Vec<_>>();
+
+ // Dispatch to GPU
+ let workgroups = [UVec3::new(1, 1, 1); 2];
+ let view = test.dispatch(
+ "merge_sort",
+ num_particle,
+ &values[..],
+ &merge_params[..],
+ &workgroups,
+ );
+
+ // Validate that both ping-pong passes produced a globally sorted result
+ // in the first half of the buffer.
+ let view_slice: &[DualKeyValuePair] = cast_slice(&view[4..]);
+ let mut expected = values[..num_particle as usize].to_vec();
+ expected.sort();
+ let s = format_slice(&expected[..num_particle as usize]);
+ eprintln!("expected:\n{s}");
+ let s = format_slice(&view_slice[..num_particle as usize]);
+ eprintln!("actual:\n{s}");
+ let s = format_slice(&view_slice[num_particle as usize..]);
+ eprintln!("scratch:\n{s}");
+ assert_eq!(&view_slice[..num_particle as usize], expected.as_slice());
+ }
+
+ /// Helper for all GPU merge tests.
+ struct MergeTest {
+ #[allow(dead_code)]
+ pub renderer: MockRenderer,
+ pub device: RenderDevice,
+ pub queue: RenderQueue,
+ /// Max block size calculated from GPU device shared workgroup memory
+ /// limit.
+ #[allow(dead_code)]
+ pub max_block_size: u32,
+ }
+
+ impl MergeTest {
+ /// Create a new GPU sort test instance.
+ fn new() -> MergeTest {
+ let renderer = MockRenderer::new();
+ let device = renderer.device();
+ let queue = renderer.queue();
+
+ println!(
+ "max_compute_workgroup_storage_size = {}",
+ device.limits().max_compute_workgroup_storage_size
+ );
+
+ // SAFETY : for debugging only
+ #[allow(unsafe_code)]
+ unsafe {
+ device.wgpu_device().start_graphics_debugger_capture()
+ };
+
+ // Clamp max block size to the device's reported storage
+ let max_block_size = device.limits().max_compute_workgroup_storage_size
+ / (DualKeyValuePair::SHADER_SIZE.get() as u32);
+ println!("max_block_size = {}", max_block_size);
+
+ Self {
+ renderer,
+ device,
+ queue,
+ max_block_size,
+ }
+ }
+
+ /// Dispatch the merge test with the given sort buffer and merge params
+ /// data.
+ ///
+ /// The `entry_point` is the compute shader entry point name to execute
+ /// (often a test-only entry point). The `count` and `pairs` are the
+ /// data of the sort buffer to upload to GPU before dispatching. The
+ /// `merge` data is the merge params content. Each item in `workgroups`
+ /// is the number of workgroups to dispatch for its corresponding
+ /// merge pass.
+ ///
+ /// # Returns
+ ///
+ /// A view over the GPU buffer content, downloaded from GPU to CPU after
+ /// the GPU executed the sort shader test.
+ fn dispatch(
+ &mut self,
+ entry_point: &str,
+ count: u32,
+ pairs: &[DualKeyValuePair],
+ merge: &[GpuMergeParams],
+ workgroups: &[UVec3],
+ ) -> BufferView {
+ assert_eq!(merge.len(), workgroups.len());
+
+ // Allocate sort buffer
+ let sort_byte_size = 4 + pairs.len() as u64 * DualKeyValuePair::SHADER_SIZE.get();
+ let sort_buffer = self.device.create_buffer(&BufferDescriptor {
+ label: Some("sort_buffer"),
+ size: sort_byte_size,
+ usage: BufferUsages::STORAGE | BufferUsages::MAP_READ,
+ mapped_at_creation: true,
+ });
+ {
+ // Scope get_mapped_range_mut() to force a drop before unmap()
+ {
+ let mut mapped = sort_buffer
+ .slice(..)
+ .get_mapped_range_mut()
+ .expect("Buffer must be mapped for writing");
+ mapped.slice(..4).copy_from_slice(cast_slice(&[count]));
+ mapped.slice(4..).copy_from_slice(cast_slice(pairs));
+ }
+ sort_buffer.unmap();
+ }
+
+ // Allocate merge buffer
+ let merge_align = GpuMergeParams::aligned_size(
+ self.device.limits().min_storage_buffer_offset_alignment,
+ );
+ let mut merge_buffer = AlignedBufferVec::<GpuMergeParams>::new(
+ BufferUsages::STORAGE | BufferUsages::MAP_READ,
+ Some(merge_align),
+ Some("merge_buffer".to_string()),
+ );
+ for m in merge {
+ merge_buffer.push(*m);
+ }
+ assert!(merge_buffer.write_buffer(&self.device, &self.queue));
+
+ // Create GPU resources
+ let bind_group_layout = self.device.create_bind_group_layout(
+ "bind_group_layout",
+ &BindGroupLayoutEntries::sequential(
+ ShaderStages::COMPUTE,
+ (
+ storage_buffer_sized(false, None),
+ storage_buffer_read_only_sized(true, None),
+ ),
+ ),
+ );
+ let bind_group = self.device.create_bind_group(
+ None,
+ &bind_group_layout,
+ &BindGroupEntries::sequential((
+ sort_buffer.as_entire_binding(),
+ merge_buffer.range_binding(0, 1).unwrap(),
+ )),
+ );
+ let pipeline_layout = self
+ .device
+ .create_pipeline_layout(&PipelineLayoutDescriptor {
+ label: Some("pipeline_layout"),
+ bind_group_layouts: &[Some(&bind_group_layout)],
+ immediate_size: 0,
+ });
+ let src = crate::test_utils::compile_wesl(
+ VFX_SORT_MERGE_WESL.as_ref(),
+ &["HAS_DUAL_KEY", "TEST"],
+ &[],
+ )
+ .unwrap();
+ let shader_module =
+ self.device
+ .create_and_validate_shader_module(ShaderModuleDescriptor {
+ label: Some("vfx_sort_merge"),
+ source: ShaderSource::Wgsl(src.into()),
+ });
+ let pipeline = self
+ .device
+ .create_compute_pipeline(&ComputePipelineDescriptor {
+ label: Some(entry_point),
+ layout: Some(&pipeline_layout),
+ module: &shader_module,
+ entry_point: Some(entry_point),
+ compilation_options: PipelineCompilationOptions {
+ constants: &[],
+ zero_initialize_workgroup_memory: false,
+ },
+ cache: None,
+ });
+
+ let mut encoder = self
+ .device
+ .create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("test"),
+ });
+
+ // Each stage needs its own compute pass so the next ping-pong
+ // stage can observe storage-buffer writes from the previous one.
+ for (pass_index, workgroups) in workgroups.iter().enumerate() {
+ let mut compute_pass = encoder.begin_compute_pass(&ComputePassDescriptor {
+ label: Some(entry_point),
+ timestamp_writes: None,
+ });
+ compute_pass.set_pipeline(&pipeline);
+ let merge_offset = merge_buffer.dynamic_offset(pass_index);
+ compute_pass.set_bind_group(0, &bind_group, &[merge_offset]);
+ compute_pass.dispatch_workgroups(workgroups.x, workgroups.y, workgroups.z);
+ }
+
+ // Submit command queue and wait for execution
+ println!("Executing pipeline...");
+ let command_buffer = encoder.finish();
+ self.queue.submit([command_buffer]);
+ let (tx, rx) = futures::channel::oneshot::channel();
+ self.queue.on_submitted_work_done(move || {
+ tx.send(()).unwrap();
+ });
+ let _ = self.device.poll(wgpu::PollType::Wait {
+ submission_index: None,
+ timeout: None,
+ });
+ let _ = futures::executor::block_on(rx);
+ println!("Pipeline executed");
+
+ // SAFETY : for debugging only
+ #[allow(unsafe_code)]
+ unsafe {
+ self.device.wgpu_device().stop_graphics_debugger_capture()
+ };
+
+ // Read back (GPU -> CPU)
+ println!("Downloading result buffer from GPU to CPU...");
+ let buffer_slice = sort_buffer.slice(..);
+ let (tx, rx) = futures::channel::oneshot::channel();
+ buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
+ tx.send(result).unwrap();
+ });
+ let _ = self.device.poll(wgpu::PollType::Wait {
+ submission_index: None,
+ timeout: None,
+ });
+ let _ = futures::executor::block_on(rx);
+ let view = buffer_slice
+ .get_mapped_range()
+ .expect("Buffer must be mapped for reading");
+ assert_eq!(view.len(), sort_byte_size as usize);
+ println!("Result buffer downloaded to CPU");
+
+ view
+ }
+ }
+}
diff --git a/vendor/bevy_hanabi/src/render/vfx_common.wesl b/vendor/bevy_hanabi/src/render/vfx_common.wesl
new file mode 100644
index 00000000..c971edb5
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/vfx_common.wesl
@@ -0,0 +1,379 @@
+struct SimParams {
+ /// Frustum planes (xyz,d) of the main Hanabi camera, in world space.
+ frustum: array<vec4<f32>, 6>,
+ /// World space position of the main Hanabi camera.
+ camera_position: vec4<f32>,
+ /// Delta time in seconds since last simulation tick.
+ delta_time: f32,
+ /// Time in seconds since the start of simulation.
+ time: f32,
+ /// Virtual delta time in seconds since last simulation tick.
+ virtual_delta_time: f32,
+ /// Virtual time in seconds since the start of simulation.
+ virtual_time: f32,
+ /// Real delta time in seconds since last simulation tick.
+ real_delta_time: f32,
+ /// Real time in seconds since the start of simulation.
+ real_time: f32,
+ /// Total number of effects to update this frame. Used by the indirect
+ /// compute pipeline to cap the compute thread to the actual number of
+ /// effects to process.
+ num_effects: u32,
+}
+
+struct Spawner {
+ /// Compressed transform of the emitter.
+ transform: mat3x4<f32>, // transposed (row-major)
+ /// Inverse compressed transform of the emitter.
+ inverse_transform: mat3x4<f32>, // transposed (row-major)
+ /// Number of particles to spawn this frame, as calculated by the CPU Spawner.
+ ///
+ /// This is only used if the effect is not a child effect (driven by GPU events).
+ spawn: i32,
+ /// PRNG seed for this effect instance. Currently this can change each time the
+ /// effect is recompiled, and cannot be set deterministically (TODO).
+ seed: u32,
+ /// Index of the ping-pong buffer of particle indices to read particles from
+ /// during rendering. Cached from EffectMetadata::ping after it's swapped
+ /// in the indirect dispatch, because the EffectMetadata struct is used by GPU
+ /// as an indirect draw source so cannot also be bound as regular storage
+ /// buffer for reading.
+ render_indirect_read_index: u32,
+ /// Index of the [`EffectMetadata`] for this effect.
+ effect_metadata_index: u32,
+ /// Index of the [`DrawIndirectArgs`] or [`DrawIndexedIndirectArgs`] for this effect.
+ draw_indirect_index: u32,
+ /// Start offset of the particles and indirect indices into the effect's
+ /// slab, in number of particles (row index).
+ slab_offset: u32,
+ /// Start offset of the particles and indirect indices into the parent effect's
+ /// slab (if the effect has a parent effect), in number of particles (row index).
+ /// This is ignored if the effect has no parent.
+ parent_slab_offset: u32,
+
+ // Keep this field here separate from auto-padding below, so that the WGSL and Rust
+ // struct definitions match.
+ unused: u32,
+
+ {{SPAWNER_PADDING}}
+}
+
+const SPAWNER_OFFSET_PONG: u32 = 27u;
+
+/// Single row entry into an IndirectBuffer.
+///
+/// Each row corresponds to one row in the ParticleBuffer. The total number of rows in the
+/// IndirectBuffer is the capacity of the ParticleBuffer itself (that is, they have the same
+/// number of rows).
+struct IndirectEntry {
+ /// Ping-pong index into ParticleBuffer.
+ particle_index: array<u32, 2>,
+ /// Index into ParticleBuffer of a dead particle slot which can be recycled.
+ dead_index: u32,
+}
+
+/// Indirection buffer storing the indices of alive and dead particles as a contiguous
+/// range, to ensure we can dispatch a tight number of workgroups only for alive particles,
+/// and can find a dead one to recycle quickly.
+struct IndirectBuffer {
+ rows: array<IndirectEntry>,
+}
+
+/// A event emitted by another effect during its update pass, to trigger the spawning
+/// of one or more particle in this effect.
+struct SpawnEvent {
+ /// The particle index in the parent effect buffer of the source particle which
+ /// triggered the event. This is used to inherit attributes like position or velocity.
+ particle_index: u32,
+}
+
+/// Append buffer populated during the Update pass of the previous frame by a parent effect,
+/// and read back by its child effect(s) during the Init pass of the next frame.
+struct EventBuffer {
+ /// The spawn events themselves.
+ spawn_events: array<SpawnEvent>,
+}
+
+/// Info about a single child of a parent effect.
+struct ChildInfo {
+ /// Index of the effect's DispatchIndirectArgs entry in the global init indirect dispatch array.
+ init_indirect_dispatch_index: u32,
+ /// Number of events in the associated event buffer.
+ @if(CHILD_INFO_EVENT_COUNT_IS_ATOMIC)
+ event_count: atomic<i32>,
+ @if(!CHILD_INFO_EVENT_COUNT_IS_ATOMIC)
+ event_count: i32,
+}
+
+/// Buffer storing all the ChildInfo structs for several effects.
+struct ChildInfoBuffer {
+ /// The child info structs themselves.
+ rows: array<ChildInfo>,
+}
+
+/// Indirect compute dispatch struct for GPU-driven passes. The layout of this struct is dictated by WGSL.
+struct DispatchIndirectArgs {
+ /// Number of workgroups. Each workgroup has exactly 64 threads.
+ x: u32,
+ /// Unused; always 1.
+ y: u32,
+ /// Unused; always 1.
+ z: u32,
+}
+
+/// Indirect draw (non-indexed) dispatch struct for GPU-driven passes. The layout of this struct is dictated by WGSL.
+/// See https://docs.rs/wgpu/latest/wgpu/util/struct.DrawIndirectArgs.html.
+struct DrawIndirectArgs {
+ vertex_count: u32,
+ instance_count: atomic<u32>,
+ first_vertex: u32,
+ first_instance: u32,
+}
+
+/// Stride in u32 count (4 bytes) of the DrawIndirectArgs struct.
+const DRAW_INDIRECT_STRIDE: u32 = 4u;
+
+/// Indirect draw (non-indexed) dispatch struct for GPU-driven passes. The layout of this struct is dictated by WGSL.
+/// See https://docs.rs/wgpu/latest/wgpu/util/struct.DrawIndexedIndirectArgs.html.
+struct DrawIndexedIndirectArgs {
+ index_count: u32,
+ instance_count: atomic<u32>,
+ first_index: u32,
+ base_vertex: i32,
+ first_instance: u32,
+}
+
+/// Stride in u32 count (4 bytes) of the DrawIndexedIndirectArgs struct.
+const DRAW_INDEXED_INDIRECT_STRIDE: u32 = 5u;
+
+/// Shared info for a single batch (single shader invocation).
+struct BatchInfo {
+ /// Total number of CPU particles to spawn. This is the sum of all `spawn`
+ /// counts of all effect instances in this batch which spawn CPU-based
+ /// particles. This is uploaded from CPU each frame.
+ total_spawn_count: u32,
+ /// Total number of CPU particles to update. This is the sum of all
+ /// `alive_count` of all effect instances in this batch. This is calculated
+ /// on GPU each frame, between the init and update passes.
+ total_update_count: u32,
+ /// Start index of the slice of [`GpuSpawnerInfo`] for this batch, into the
+ /// [`EffectsMeta::spawner_buffer`]. The slice length is equal to the number
+ /// of effects instances batched together.
+ spawner_base: u32,
+ /// Offset to apply to the workgroup thread index to determine the global
+ /// particle index in the currently bound slab. This is often (and ideally)
+ /// zero, but may be > 0 if the entire slab cannot be processed with a
+ /// single invocation.
+ base_particle: u32,
+ /// Offset into the prefix sum buffer of the sum for the first effect of
+ /// this batch.
+ prefix_sum_offset: u32,
+ /// Number of active effects in the batch, and therefore number of
+ /// consecutive prefix sum values for effects of this batch.
+ prefix_sum_count: u32,
+
+ /// Padding for storage buffer alignment. This struct is sometimes bound as part
+ /// of an array, or sometimes individually as a single unit. In the later case,
+ /// we need it to be aligned to the GPU limits of the device. That limit is only
+ /// known at runtime when initializing the WebGPU device.
+ {{BATCH_INFO_PADDING}}
+}
+
+/// Metadata describing a single effect instance.
+///
+/// The metadata describes various effect settings, as well we the location in
+/// GPU buffers of the piece of data associated with that instance.
+struct EffectMetadata {
+ /// Total number of particles for this effect. This is the capacity of the effect,
+ /// in number of particles, which is used to sub-allocate various storages for this
+ /// effect, notably in the ParticleBuffer and the IndirectBuffer. This is constant
+ /// for the duration of the effect instance life.
+ capacity: u32,
+
+ /// Number of particles alive. Note that because particles can be simulated even
+ /// when off-screen, in theory this could be greater than instance_count. Currently
+ /// we don't have GPU culling, so in practice this remains strictly equal. But we
+ /// store it separately 1) because this could change in the future, and 2) because
+ /// the indirect render fields above (FIXME: not there anymore) should really be in
+ /// their own buffer, not here.
+ alive_count: atomic<u32>,
+ /// Maximum number of update threads to run. This is cached from `alive_count`
+ /// during the indirect dispatch, so that the update compute pass can cap its
+ /// thread count while also modifying the actual `alive_count` if some particle
+ /// dies during the update pass.
+ max_update: u32,
+ /// Maxmimum number of init threads to run on next frame. This is cached from
+ /// `capacity - alive_count` during the indirect dispatch of the previous frame,
+ /// so that the init compute pass can cap its thread count while also decrementing
+ /// the actual dead count (increment the `alive_count`) as particles are spawned.
+ max_spawn: atomic<u32>,
+
+ /// Write index into the ping-pong buffer for particle indices. The buffers
+ /// are swapped during the indirect dispatch (although the render pass still uses
+ /// the complement of this to write, so technically ignores that swap).
+ indirect_write_index: u32,
+ /// Index of the [`GpuRenderIndirect`] struct inside the global
+ /// [`EffectsMeta::render_group_dispatch_buffer`].
+ indirect_render_index: u32,
+ /// Offset (in u32 count) of the init indirect dispatch struct inside its
+ /// buffer. This avoids having to align those 16-byte structs to the GPU
+ /// alignment (at least 32 bytes, even 256 bytes on some).
+ init_indirect_dispatch_index: u32,
+ /// Offset (in u32 count) of the start of the property block for this
+ /// effect. This is ignored if the effect doesn't use properties.
+ properties_array_index: u32,
+ /// Index of this effect into its parent's ChildInfo array
+ /// ([`EffectChildren::effect_cache_ids`] and its associated GPU
+ /// array). This starts at zero for the first child of each effect, and is
+ /// only unique per parent, not globally. Only available if this effect is a
+ /// child of another effect (i.e. if it has a parent).
+ local_child_index: u32,
+ /// For children, global index of the ChildInfo into the shared array.
+ global_child_index: u32,
+ /// For parents, base index of the their first ChildInfo into the shared array.
+ base_child_index: u32,
+
+ /// Particle stride, in number of u32.
+ particle_stride: u32,
+ /// Offset from the particle start to the first sort key, in number of u32.
+ sort_key_offset: u32,
+ /// Offset from the particle start to the second sort key, in number of u32.
+ sort_key2_offset: u32,
+
+ /// Atomic counter incremented each time a particle spawns. Useful for
+ /// things like RIBBON_ID or any other use where a unique value is needed.
+ /// The value loops back after some time, but unless some particle lives
+ /// forever there's little chance of repetition.
+ particle_counter: atomic<u32>,
+}
+
+var<private> seed : u32 = 0u;
+
+const tau: f32 = 6.283185307179586476925286766559;
+
+// Rand: PCG
+// https://www.reedbeta.com/blog/hash-functions-for-gpu-rendering/
+fn pcg_hash(input: u32) -> u32 {
+ var state: u32 = input * 747796405u + 2891336453u;
+ var word: u32 = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;
+ return (word >> 22u) ^ word;
+}
+
+fn to_float01(u: u32) -> f32 {
+ // Note: could generate only 24 bits of randomness
+ return bitcast<f32>((u & 0x007fffffu) | 0x3f800000u) - 1.;
+}
+
+// Random floating-point number in [0:1]
+fn frand() -> f32 {
+ seed = pcg_hash(seed);
+ return to_float01(pcg_hash(seed));
+}
+
+// Random floating-point number in [0:1]^2
+fn frand2() -> vec2<f32> {
+ seed = pcg_hash(seed);
+ var x = to_float01(seed);
+ seed = pcg_hash(seed);
+ var y = to_float01(seed);
+ return vec2<f32>(x, y);
+}
+
+// Random floating-point number in [0:1]^3
+fn frand3() -> vec3<f32> {
+ seed = pcg_hash(seed);
+ var x = to_float01(seed);
+ seed = pcg_hash(seed);
+ var y = to_float01(seed);
+ seed = pcg_hash(seed);
+ var z = to_float01(seed);
+ return vec3<f32>(x, y, z);
+}
+
+// Random floating-point number in [0:1]^4
+fn frand4() -> vec4<f32> {
+ // Each rand() produces 32 bits, and we need 24 bits per component,
+ // so can get away with only 3 calls.
+ var r0 = pcg_hash(seed);
+ var r1 = pcg_hash(r0);
+ var r2 = pcg_hash(r1);
+ seed = r2;
+ var x = to_float01(r0);
+ var r01 = ((r0 & 0xff000000u) >> 8u) | (r1 & 0x0000ffffu);
+ var y = to_float01(r01);
+ var r12 = ((r1 & 0xffff0000u) >> 8u) | (r2 & 0x000000ffu);
+ var z = to_float01(r12);
+ var r22 = r2 >> 8u;
+ var w = to_float01(r22);
+ return vec4<f32>(x, y, z, w);
+}
+
+fn rand_uniform_f(a: f32, b: f32) -> f32 {
+ return a + frand() * (b - a);
+}
+
+fn rand_uniform_vec2(a: vec2<f32>, b: vec2<f32>) -> vec2<f32> {
+ return a + frand2() * (b - a);
+}
+
+fn rand_uniform_vec3(a: vec3<f32>, b: vec3<f32>) -> vec3<f32> {
+ return a + frand3() * (b - a);
+}
+
+fn rand_uniform_vec4(a: vec4<f32>, b: vec4<f32>) -> vec4<f32> {
+ return a + frand4() * (b - a);
+}
+
+// Normal distribution computed using Box-Muller transform
+fn rand_normal_f(mean: f32, std_dev: f32) -> f32 {
+ var u = frand();
+ var v = frand();
+ var r = sqrt(-2.0 * log(u));
+ return mean + std_dev * r * cos(tau * v);
+}
+
+fn rand_normal_vec2(mean: vec2f, std_dev: vec2f) -> vec2f {
+ var u = frand();
+ var v = frand2();
+ var r = sqrt(-2.0 * log(u));
+ return mean + std_dev * r * cos(tau * v);
+}
+
+fn rand_normal_vec3(mean: vec3f, std_dev: vec3f) -> vec3f {
+ var u = frand();
+ var v = frand3();
+ var r = sqrt(-2.0 * log(u));
+ return mean + std_dev * r * cos(tau * v);
+}
+
+fn rand_normal_vec4(mean: vec4f, std_dev: vec4f) -> vec4f {
+ var u = frand();
+ var v = frand4();
+ var r = sqrt(-2.0 * log(u));
+ return mean + std_dev * r * cos(tau * v);
+}
+
+fn proj(u: vec3<f32>, v: vec3<f32>) -> vec3<f32> {
+ return dot(v, u) / dot(u,u) * u;
+}
+
+/// Unpack a compressed transform stored in transposed row-major form.
+fn unpack_compressed_transform(compressed_transform: mat3x4<f32>) -> mat4x4<f32> {
+ return transpose(
+ mat4x4(
+ compressed_transform[0],
+ compressed_transform[1],
+ compressed_transform[2],
+ vec4<f32>(0.0, 0.0, 0.0, 1.0)
+ )
+ );
+}
+
+// Unpacks a compressed transform and transposes is.
+fn unpack_compressed_transform_3x3_transpose(compressed_transform: mat3x4<f32>) -> mat3x3<f32> {
+ return mat3x3(
+ compressed_transform[0].xyz,
+ compressed_transform[1].xyz,
+ compressed_transform[2].xyz,
+ );
+}
diff --git a/vendor/bevy_hanabi/src/render/vfx_indirect.wesl b/vendor/bevy_hanabi/src/render/vfx_indirect.wesl
new file mode 100644
index 00000000..9ea447f0
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/vfx_indirect.wesl
@@ -0,0 +1,83 @@
+import bevy_hanabi::render::vfx_common::{
+ ChildInfo, ChildInfoBuffer, DispatchIndirectArgs, EffectMetadata, SimParams, Spawner,
+ DRAW_INDEXED_INDIRECT_STRIDE,
+};
+
+@group(0) @binding(0) var<uniform> sim_params : SimParams;
+
+@group(1) @binding(0) var<storage, read_write> effect_metadatas : array<EffectMetadata>;
+// Tightly packed array of DrawIndexedIndirectArgs[], accessed as u32 array. This can contain
+// some DrawIndirectArgs[] instead, but in that case the stride is adjusted so all rows have
+// the same size. Since we access the instance_count, which is at the same position in both,
+// we ignore their size difference (the non-indexed one is padded).
+@group(1) @binding(1) var<storage, read_write> draw_indirect_buffer : array<u32>;
+
+@group(2) @binding(0) var<storage, read_write> spawner_buffer : array<Spawner>;
+@group(2) @binding(1) var<storage, read_write> prefix_sum : array<u32>;
+
+@if(HAS_GPU_SPAWN_EVENTS)
+@group(3) @binding(0) var<storage, read_write> child_info_buffer : ChildInfoBuffer;
+
+/// Perform per-instance update between the init and update passes.
+///
+/// This is invoked once per instance, with the global invocation ID indexing the list of spawners,
+/// which is re-uploaded each frame so is guaranteed to be a tightly packed array with exactly the
+/// number of
+@compute @workgroup_size(64)
+fn main(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
+ // Cap at maximum number of effects
+ let global_effect_index = global_invocation_id.x;
+ if (global_effect_index >= sim_params.num_effects) {
+ return;
+ }
+
+ // Clear any GPU event. The indexing is inconsistent here (indexing child info buffer with an
+ // effect instance), but is safe because there are always less child effects than there are effects
+ // in total, so the index will always cover the entire child info array. And we're only resetting
+ // a value so don't read anything, so only need to visit each entry once but the order doesn't matter.
+ @if(HAS_GPU_SPAWN_EVENTS)
+ if (global_effect_index < arrayLength(&child_info_buffer.rows)) {
+ child_info_buffer.rows[global_effect_index].event_count = 0;
+ }
+
+ let spawner = &spawner_buffer[global_effect_index];
+ let effect_metadata_index = (*spawner).effect_metadata_index;
+
+ // Clear the rendering instance count, which will be upgraded by the update pass
+ // with the particles actually alive at the end of their update (after aged).
+ let draw_indirect_index = (*spawner).draw_indirect_index;
+ let dri_base = DRAW_INDEXED_INDIRECT_STRIDE * draw_indirect_index;
+ draw_indirect_buffer[dri_base + 1u] = 0u;
+
+ let capacity = effect_metadatas[effect_metadata_index].capacity;
+ let alive_count = atomicLoad(&effect_metadatas[effect_metadata_index].alive_count); // atomic not needed
+ let dead_count = capacity - alive_count;
+
+ // Prepare to rebuild the prefix sum of active instances by storing in the prefix sum array
+ // the actual number of alive particles for each instance. We will build the prefix sum in
+ // the next pass (vfx_prefix_sum) once that's done.
+ // The prefix sums and spawners are allocated in sync, so are indexed with the same index value.
+ prefix_sum[global_effect_index] = alive_count;
+
+ // Update max_update from current value of alive_count, so that the
+ // update pass coming next can cap its threads to this value, while also
+ // atomically modifying alive_count itself for next frame.
+ effect_metadatas[effect_metadata_index].max_update = alive_count;
+
+ // Copy the number of dead particles to a constant location, so that the
+ // init pass on next frame can atomically modify alive_count in parallel
+ // yet still read its initial value at the beginning of the init pass,
+ // and limit the number of particles spawned to the number of dead
+ // particles to recycle.
+ atomicStore(&effect_metadatas[effect_metadata_index].max_spawn, dead_count); // atomic not needed
+
+ // Swap ping/pong buffers. The update pass always writes into ping, and both the update
+ // pass and the render pass always read from pong.
+ let ping = effect_metadatas[effect_metadata_index].indirect_write_index;
+ let pong = 1u - ping;
+ effect_metadatas[effect_metadata_index].indirect_write_index = pong;
+
+ // Copy the new pong into the spawner buffer, which will be used during rendering
+ // to determine where to read particle indices.
+ (*spawner).render_indirect_read_index = pong;
+}
diff --git a/vendor/bevy_hanabi/src/render/vfx_init.wesl b/vendor/bevy_hanabi/src/render/vfx_init.wesl
new file mode 100644
index 00000000..017dcea1
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/vfx_init.wesl
@@ -0,0 +1,202 @@
+import bevy_hanabi::render::vfx_common::{
+ ChildInfo, ChildInfoBuffer, EventBuffer, DispatchIndirectArgs, IndirectBuffer,
+ EffectMetadata, RenderGroupIndirect, SimParams, Spawner, BatchInfo,
+ seed, tau, pcg_hash, to_float01, frand, frand2, frand3, frand4,
+ rand_uniform_f, rand_uniform_vec2, rand_uniform_vec3, rand_uniform_vec4,
+ rand_normal_f, rand_normal_vec2, rand_normal_vec3, rand_normal_vec4, proj
+};
+
+struct Particle {
+{{ATTRIBUTES}}
+}
+
+struct ParticleBuffer {
+ particles: array<Particle>,
+}
+
+
+{{PARENT_PARTICLE}}
+
+@if(READ_PARENT_PARTICLE)
+struct ParentParticleBuffer {
+ particles: array<ParentParticle>,
+}
+
+
+{{PROPERTIES}}
+
+/// Location of an effect in a slab.
+struct EffectLocation {
+ /// Index of the effect in the global list of effects.
+ effect_index: u32,
+ /// Base particle index, that is index in the slab of the first particle for this instance.
+ base_particle: u32,
+ /// Index of this particle relative to its effect. Note that if there's an indirection
+ /// buffer then this is the linear index in [0:N[ of the particle to update, before the indirection.
+ update_index: u32,
+}
+
+/// Find the index of an effect from the index of a particle.
+///
+/// This uses a binary search on the slab_offset field of the spawners array, which
+/// represents a prefix sum of the particle count per effect (for previous effects;
+/// the value is actually the base particle so the first entry is always 0).
+///
+/// Requirements:
+/// - var<storage, read> batch_info : BatchInfo
+/// - var<storage, read> prefix_sum : array<u32>
+fn find_location_from_particle(update_particle_index: u32) -> EffectLocation {
+ var lo = batch_info.prefix_sum_offset;
+ var hi = lo + batch_info.prefix_sum_count;
+ var num_iter = 0; // avoid deadlocking the GPU by capping the iteration count
+ while (lo < hi) {
+ let mid = (hi + lo) >> 1u;
+ let base_particle = prefix_sum[mid];
+ if (update_particle_index >= base_particle) {
+ lo = mid + 1u;
+ } else if (update_particle_index < base_particle) {
+ hi = mid;
+ }
+ num_iter += 1;
+ if (num_iter >= 100) {
+ return EffectLocation(0xDEADBEEFu, 0xDEADBEEFu, 0xDEADBEEFu);
+ }
+ }
+ let base_index = prefix_sum[lo - 1u];
+ let update_index = update_particle_index - base_index;
+ let effect_index = lo - 1u - batch_info.prefix_sum_offset;
+ let base_particle = spawners[batch_info.spawner_base + effect_index].slab_offset;
+ return EffectLocation(effect_index, base_particle, update_index);
+}
+
+@group(0) @binding(0) var<uniform> sim_params : SimParams;
+
+// "particle" group @1
+@group(1) @binding(0) var<storage, read_write> particle_buffer : ParticleBuffer;
+@group(1) @binding(1) var<storage, read_write> indirect_buffer : IndirectBuffer;
+@if(READ_PARENT_PARTICLE)
+@group(1) @binding(2) var<storage, read> parent_particle_buffer : ParentParticleBuffer;
+
+// "spawner" group @2
+@group(2) @binding(0) var<storage, read> spawners : array<Spawner>;
+@group(2) @binding(1) var<storage, read> prefix_sum : array<u32>;
+@group(2) @binding(2) var<storage, read> batch_info : BatchInfo;
+{{PROPERTIES_BINDING}}
+{{MATERIAL_BINDINGS}}
+
+// "metadata" group @3
+@group(3) @binding(0) var<storage, read_write> effect_metadatas : array<EffectMetadata>;
+@if(CONSUME_GPU_SPAWN_EVENTS)
+@group(3) @binding(1) var<storage, read> child_info_buffer : ChildInfoBuffer;
+@if(CONSUME_GPU_SPAWN_EVENTS)
+@group(3) @binding(2) var<storage, read> event_buffer : EventBuffer;
+
+{{INIT_EXTRA}}
+
+var<private> effect_metadata_index: u32;
+var<private> properties_array_index: u32;
+
+@compute @workgroup_size(64)
+fn main(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
+ // Particle index in the packed init space of this batch.
+ let update_particle_index = global_invocation_id.x;
+ @if(!CONSUME_GPU_SPAWN_EVENTS)
+ if (update_particle_index >= batch_info.total_spawn_count) {
+ return;
+ }
+
+ // Find the index of the effect this particle is part of.
+ let location = find_location_from_particle(update_particle_index);
+ let spawner = &spawners[batch_info.spawner_base + location.effect_index];
+ effect_metadata_index = (*spawner).effect_metadata_index;
+ let base_particle = (*spawner).slab_offset;
+
+ // Cap to max number of dead particles, copied from (capacity - alive_count) at the end
+ // of the previous iteration, and constant during this pass (unlike alive_count).
+ let effect_metadata = &effect_metadatas[effect_metadata_index];
+ let max_spawn = atomicLoad(&(*effect_metadata).max_spawn); // Not atomic
+ if (location.update_index >= max_spawn) {
+ return;
+ }
+ properties_array_index = (*effect_metadata).properties_array_index;
+
+ // Cap to the actual number of spawning requested by CPU or GPU, since compute shaders run
+ // in workgroup_size(64) so more threads than needed are launched (rounded up to 64).
+ @if(CONSUME_GPU_SPAWN_EVENTS)
+ let event_index = location.update_index;
+ @if(CONSUME_GPU_SPAWN_EVENTS)
+ let global_child_index = (*effect_metadata).global_child_index;
+ @if(CONSUME_GPU_SPAWN_EVENTS)
+ let event_count = child_info_buffer.rows[global_child_index].event_count;
+ @if(CONSUME_GPU_SPAWN_EVENTS)
+ if (event_index >= u32(event_count)) {
+ return;
+ }
+ // Cap to the actual number of spawning requested by CPU (in the case of
+ // spawners) or the number of particles present in the source group (in the
+ // case of cloners).
+ @if(!CONSUME_GPU_SPAWN_EVENTS)
+ let spawn_count: u32 = u32((*spawner).spawn);
+ @if(!CONSUME_GPU_SPAWN_EVENTS)
+ if (location.update_index >= spawn_count) {
+ return;
+ }
+
+ // Count as alive, and recycle a dead particle slot to store the newly spawned particle
+ let alive_index = atomicAdd(&(*effect_metadata).alive_count, 1u);
+ let slab_particle_dead_index = indirect_buffer.rows[base_particle + alive_index].dead_index;
+ let particle_index = slab_particle_dead_index - base_particle;
+
+ // DEBUG
+ //indirect_buffer.rows[base_particle + alive_index].dead_index = 0xFFFFFFFFu;
+
+ // Bump the particle counter each time we allocate a particle. This generates a unique
+ // particle ID used for various purposes (but not directly by the simulation). We still
+ // store it in a variable, because the INIT_CODE might access it.
+ let particle_counter = atomicAdd(&(*effect_metadata).particle_counter, 1u);
+
+ // Initialize the PRNG seed
+ // raea: from the spawn's index in this frame's spawns (the spawner's seed moves on each frame), not from the
+ // dead slot it recycles, which threads take in an order that differs from run to run (raea #52)
+ seed = pcg_hash(location.update_index ^ (*spawner).seed);
+
+ // Spawner transform
+ let transform = transpose(
+ mat4x4(
+ (*spawner).transform[0],
+ (*spawner).transform[1],
+ (*spawner).transform[2],
+ vec4<f32>(0.0, 0.0, 0.0, 1.0)
+ )
+ );
+
+ // Fetch parent particle which triggered this spawn
+ @if(READ_PARENT_PARTICLE)
+ let parent_base_particle = (*spawner).parent_slab_offset;
+ @if(READ_PARENT_PARTICLE)
+ let parent_particle_index = event_buffer.spawn_events[event_index].particle_index;
+ @if(READ_PARENT_PARTICLE)
+ let parent_particle = parent_particle_buffer.particles[parent_base_particle + parent_particle_index];
+
+ // Initialize new particle
+ var particle = Particle();
+ {{INIT_CODE}}
+ @if(ATTRIBUTE_PREV)
+ particle.prev = 0xffffffffu;
+ @if(ATTRIBUTE_NEXT)
+ particle.next = 0xffffffffu;
+
+ // Only add emitter's transform to CPU-spawned particles. GPU-spawned particles
+ // don't have a CPU spawner to read from (they can read the parent particle
+ // transform, which is equivalent).
+ @if(!CONSUME_GPU_SPAWN_EVENTS) {
+ {{SIMULATION_SPACE_TRANSFORM_PARTICLE}}
+ }
+
+ // Append to alive list of indirect buffer.
+ let write_index = (*effect_metadata).indirect_write_index;
+ indirect_buffer.rows[base_particle + alive_index].particle_index[write_index] = particle_index;
+
+ // Write back new particle
+ particle_buffer.particles[base_particle + particle_index] = particle;
+}
diff --git a/vendor/bevy_hanabi/src/render/vfx_prefix_sum.wesl b/vendor/bevy_hanabi/src/render/vfx_prefix_sum.wesl
new file mode 100644
index 00000000..ba520349
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/vfx_prefix_sum.wesl
@@ -0,0 +1,43 @@
+import bevy_hanabi::render::vfx_common::{BatchInfo, DispatchIndirectArgs};
+
+@group(0) @binding(0) var<storage, read_write> batch_infos : array<BatchInfo>;
+@group(0) @binding(1) var<storage, read_write> prefix_sum : array<u32>;
+@group(0) @binding(2) var<storage, read_write> dispatch_indirect_buffer : array<DispatchIndirectArgs>;
+
+/// Compute the prefix sum of each effect batch.
+///
+/// This is invoked once per effect batch each frame, before the update pass, to recalculate
+/// the prefix sum of the alive particle counts per instance in that batch. Before this pass,
+/// the prefix sum buffer contains the number of alive particles for each instance. After it,
+/// it contains a prefix sum of that number.
+@compute @workgroup_size(64)
+fn main(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
+ // Get the batch to update
+ let batch_index = global_invocation_id.x;
+ let batch_count = arrayLength(&batch_infos);
+ if (batch_index >= batch_count) {
+ return;
+ }
+
+ // Find the slice of prefix sum to update inside the global shared buffer
+ let offset = batch_infos[batch_index].prefix_sum_offset;
+ let count = batch_infos[batch_index].prefix_sum_count;
+
+ // Calculate the prefix sum
+ let end = offset + count;
+ var sum = 0u;
+ for (var i = offset; i < end; i += 1u) {
+ let count = prefix_sum[i];
+ // Exclusive: store current sum before incrementing
+ prefix_sum[i] = sum;
+ sum = sum + count;
+ }
+
+ // Store the sum back into the batch
+ batch_infos[batch_index].total_update_count = sum;
+
+ // Update the dispatch indirect count
+ dispatch_indirect_buffer[batch_index].x = (sum + 63u) >> 6u;
+ dispatch_indirect_buffer[batch_index].y = 1u;
+ dispatch_indirect_buffer[batch_index].z = 1u;
+}
diff --git a/vendor/bevy_hanabi/src/render/vfx_render.wesl b/vendor/bevy_hanabi/src/render/vfx_render.wesl
new file mode 100644
index 00000000..5b05c760
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/vfx_render.wesl
@@ -0,0 +1,311 @@
+import bevy_render::view::View;
+import bevy_hanabi::render::vfx_common::{
+ IndirectBuffer, SimParams, Spawner, BatchInfo,
+ seed, tau, pcg_hash, to_float01, frand, frand2, frand3, frand4,
+ rand_uniform_f, rand_uniform_vec2, rand_uniform_vec3, rand_uniform_vec4,
+ rand_normal_f, rand_normal_vec2, rand_normal_vec3, rand_normal_vec4, proj,
+ unpack_compressed_transform, unpack_compressed_transform_3x3_transpose
+};
+
+struct Particle {
+{{ATTRIBUTES}}
+}
+
+{{PROPERTIES}}
+
+struct ParticleBuffer {
+ particles: array<Particle>,
+}
+
+struct VertexOutput {
+ @builtin(position) position: vec4<f32>,
+ @location(0) color: vec4<f32>,
+ @if(NEEDS_UV)
+ @location(1) uv: vec2<f32>,
+ @if(NEEDS_NORMAL)
+ @location(2) normal: vec3<f32>,
+ @if(NEEDS_PARTICLE_FRAGMENT)
+ @location(3) slab_particle_index: u32,
+}
+
+// Global bindings
+@group(0) @binding(0) var<uniform> view: View;
+@group(0) @binding(1) var<uniform> sim_params : SimParams;
+
+// Per-batch bindings
+@group(1) @binding(0) var<storage, read> particle_buffer : ParticleBuffer;
+@group(1) @binding(1) var<storage, read> indirect_buffer : IndirectBuffer;
+
+// Per-batch bindings
+@if(HAS_BATCHED_DRAW)
+@group(2) @binding(0) var<storage, read> spawners : array<Spawner>;
+@if(HAS_BATCHED_DRAW)
+@group(2) @binding(1) var<storage, read> prefix_sum : array<u32>;
+@if(HAS_BATCHED_DRAW)
+@group(2) @binding(2) var<storage, read> batch_info : BatchInfo;
+// Per-effect bindings
+@if(!HAS_BATCHED_DRAW)
+@group(2) @binding(0) var<storage, read> spawners : array<Spawner>;
+@if(!HAS_BATCHED_DRAW)
+@group(2) @binding(1) var<storage, read> batch_info : BatchInfo;
+{{PROPERTIES_BINDING}}
+{{MATERIAL_BINDINGS}}
+
+/// The resolved effect and particle location.
+///
+/// This is calculated at the start of the thread execution, and used after that
+/// in various functions.
+var<private> effect_location : EffectLocation;
+
+var<private> effect_metadata_index: u32;
+var<private> spawner_index: u32;
+// var<private> properties_offset: u32;
+
+fn get_camera_position_effect_space() -> vec3<f32> {
+ let view_pos = view.world_from_view[3].xyz;
+ @if(LOCAL_SPACE_SIMULATION)
+ let inverse_transform = unpack_compressed_transform(spawners[spawner_index].inverse_transform);
+ @if(LOCAL_SPACE_SIMULATION)
+ return (inverse_transform * vec4<f32>(view_pos, 1.0)).xyz;
+ @if(!LOCAL_SPACE_SIMULATION)
+ return view_pos;
+}
+
+fn get_camera_rotation_effect_space() -> mat3x3<f32> {
+ let view_rot = mat3x3(view.world_from_view[0].xyz, view.world_from_view[1].xyz, view.world_from_view[2].xyz);
+ @if(LOCAL_SPACE_SIMULATION)
+ let inverse_transform = transpose(
+ mat3x3(
+ spawners[spawner_index].inverse_transform[0].xyz,
+ spawners[spawner_index].inverse_transform[1].xyz,
+ spawners[spawner_index].inverse_transform[2].xyz,
+ )
+ );
+ @if(LOCAL_SPACE_SIMULATION)
+ return inverse_transform * view_rot;
+ @if(!LOCAL_SPACE_SIMULATION)
+ return view_rot;
+}
+
+/// Transform a simulation space position into a world space position.
+///
+/// The simulation space depends on the effect's SimulationSpace value, and is either
+/// the effect space (SimulationSpace::Local) or the world space (SimulationSpace::Global).
+fn transform_position_simulation_to_world(sim_position: vec3<f32>) -> vec4<f32> {
+ @if(LOCAL_SPACE_SIMULATION)
+ let transform = unpack_compressed_transform(spawners[spawner_index].transform);
+ @if(LOCAL_SPACE_SIMULATION)
+ return transform * vec4<f32>(sim_position, 1.0);
+ @if(!LOCAL_SPACE_SIMULATION)
+ return vec4<f32>(sim_position, 1.0);
+}
+
+fn transform_normal_simulation_to_world(sim_normal: vec3<f32>) -> vec3<f32> {
+ // We use the inverse transpose transform to transform normals.
+ // The inverse transpose is the same as the transposed inverse, so we can
+ // safely use the inverse transform.
+ @if(LOCAL_SPACE_SIMULATION)
+ let transform = unpack_compressed_transform_3x3_transpose(spawners[spawner_index].inverse_transform);
+ @if(LOCAL_SPACE_SIMULATION)
+ return transform * sim_normal;
+ @if(!LOCAL_SPACE_SIMULATION)
+ return sim_normal;
+}
+
+/// Transform a simulation space position into a clip space position.
+///
+/// The simulation space depends on the effect's SimulationSpace value, and is either
+/// the effect space (SimulationSpace::Local) or the world space (SimulationSpace::Global).
+/// The clip space is the final [-1:1]^3 space output from the vertex shader, before
+/// perspective divide and viewport transform are applied.
+fn transform_position_simulation_to_clip(sim_position: vec3<f32>) -> vec4<f32> {
+ return view.clip_from_world * transform_position_simulation_to_world(sim_position);
+}
+
+fn inverse_transpose_mat3(m: mat3x3<f32>) -> mat3x3<f32> {
+ let tmp0 = cross(m[1], m[2]);
+ let tmp1 = cross(m[2], m[0]);
+ let tmp2 = cross(m[0], m[1]);
+ let inv_det = 1.0 / dot(m[2], tmp2);
+ return mat3x3<f32>(tmp0 * inv_det, tmp1 * inv_det, tmp2 * inv_det);
+}
+
+{{RENDER_EXTRA}}
+
+/// Location of an effect in a slab.
+struct EffectLocation {
+ /// Index of the effect in the global list of effects.
+ effect_index: u32,
+ /// Base particle index, that is index in the slab of the first particle for this instance.
+ base_particle: u32,
+ /// Index of this particle relative to its effect. Note that if there's an indirection
+ /// buffer then this is the linear index in [0:N[ of the particle to update, before the indirection.
+ update_index: u32,
+}
+
+/// Find the index of an effect from the index of a particle.
+///
+/// This uses a binary search on the slab_offset field of the spawners array, which
+/// represents a prefix sum of the particle count per effect (for previous effects;
+/// the value is actually the base particle so the first entry is always 0).
+///
+/// Requirements:
+/// - var<storage, read> batch_info : BatchInfo
+/// - var<storage, read> prefix_sum : array<u32>
+@if(HAS_BATCHED_DRAW)
+fn find_location_from_particle(slab_particle_index: u32) -> EffectLocation {
+ var lo = batch_info.prefix_sum_offset;
+ var hi = lo + batch_info.prefix_sum_count;
+ var num_iter = 0; // avoid deadlocking the GPU by capping the iteration count
+ while (lo < hi) {
+ let mid = (hi + lo) >> 1u;
+ let base_particle = batch_info.base_particle + prefix_sum[mid];
+ if (slab_particle_index >= base_particle) {
+ lo = mid + 1u;
+ } else if (slab_particle_index < base_particle) {
+ hi = mid;
+ }
+ num_iter += 1;
+ if (num_iter >= 100) {
+ return EffectLocation(0xDEADBEEFu, 0xDEADBEEFu, 0xDEADBEEFu);
+ }
+ }
+ let effect_index = lo - 1u - batch_info.prefix_sum_offset;
+ let update_index = slab_particle_index - prefix_sum[lo - 1u];
+ let base_particle = spawners[batch_info.spawner_base + effect_offset + effect_index].slab_offset;
+ return EffectLocation(effect_index, base_particle, update_index);
+}
+
+@vertex
+fn vertex(
+ @builtin(instance_index) instance_index: u32,
+ @location(0) vertex_position: vec3<f32>,
+ @if(NEEDS_UV)
+ @location(1) vertex_uv: vec2<f32>,
+ @if(NEEDS_NORMAL)
+ @location(2) vertex_normal: vec3<f32>,
+ // @location(1) vertex_color: u32,
+ // @location(1) vertex_velocity: vec3<f32>,
+) -> VertexOutput {
+ // Find the index of the effect this particle is part of. Note that currently
+ // rendering is not yet batched, so this really derives into (effect_index = 0,
+ // base_particle = batch_info.base_particle), and the binary search is a bit useless
+ // until an actual batching is set up.
+ @if(HAS_BATCHED_DRAW)
+ effect_location = find_location_from_particle(instance_index);
+ @if(HAS_BATCHED_DRAW)
+ spawner_index = batch_info.spawner_base + effect_offset + effect_index;
+ @if(!HAS_BATCHED_DRAW)
+ effect_location.effect_index = 0u;
+ @if(!HAS_BATCHED_DRAW)
+ effect_location.base_particle = batch_info.base_particle;
+ @if(!HAS_BATCHED_DRAW)
+ effect_location.update_index = instance_index;
+ @if(!HAS_BATCHED_DRAW)
+ spawner_index = batch_info.spawner_base;
+ let spawner = &spawners[spawner_index];
+ effect_metadata_index = (*spawner).effect_metadata_index;
+ let base_particle = effect_location.base_particle;
+
+ // Fetch particle
+ let indirect_read_index = (*spawner).render_indirect_read_index;
+ let particle_index = indirect_buffer.rows[base_particle + instance_index].particle_index[indirect_read_index];
+ var particle = particle_buffer.particles[base_particle + particle_index];
+
+ var out: VertexOutput;
+
+ @if(NEEDS_PARTICLE_FRAGMENT)
+ out.slab_particle_index = base_particle + particle_index;
+
+ // Discard first instance; we draw from second one, and link to previous one
+ @if(RIBBONS)
+ if (instance_index == 0) {
+ out.position = vec4(0.0);
+ return out;
+ }
+
+ // Fetch previous particle
+ @if(RIBBONS)
+ let prev_index = indirect_buffer.rows[base_particle + instance_index - 1u].particle_index[indirect_read_index];
+ @if(RIBBONS)
+ let prev_particle = particle_buffer.particles[base_particle + prev_index];
+
+ // Discard this instance if previous one is from a different ribbon. Again,
+ // we draw from second one of each ribbon.
+ @if(RIBBONS)
+ if (prev_particle.ribbon_id != particle.ribbon_id) {
+ out.position = vec4(0.0);
+ return out;
+ }
+
+ // Compute UVs
+ @if(NEEDS_UV)
+ var uv = vertex_uv;
+ @if(NEEDS_UV && FLIPBOOK)
+ let row_count = {{FLIPBOOK_ROW_COUNT}};
+ @if(NEEDS_UV && FLIPBOOK)
+ let ij = vec2<f32>(f32(particle.sprite_index % row_count), f32(particle.sprite_index / row_count));
+ @if(NEEDS_UV && FLIPBOOK)
+ uv = (ij + uv) * {{FLIPBOOK_SCALE}};
+ @if(NEEDS_UV)
+ out.uv = uv;
+
+{{INPUTS}}
+
+{{VERTEX_MODIFIERS}}
+
+ @if(RIBBONS)
+ var delta = particle.position - prev_particle.position;
+
+ @if(RIBBONS)
+ axis_x = normalize(delta);
+ @if(RIBBONS)
+ axis_y = normalize(cross(axis_x, axis_z));
+ @if(RIBBONS)
+ axis_z = cross(axis_x, axis_y);
+
+ @if(RIBBONS)
+ position = mix(particle.position, prev_particle.position, 0.5);
+ @if(RIBBONS)
+ size = vec3(length(delta), size.y, 1.0);
+
+ // Expand particle mesh vertex based on particle position ("origin"), and local
+ // orientation and size of the particle mesh.
+ let vpos = vertex_position * size;
+ let sim_position = position + axis_x * vpos.x + axis_y * vpos.y + axis_z * vpos.z;
+ out.position = transform_position_simulation_to_clip(sim_position);
+
+ out.color = color;
+
+ @if(NEEDS_NORMAL)
+ let normal = inverse_transpose_mat3(mat3x3(axis_x, axis_y, axis_z)) * vertex_normal;
+ @if(NEEDS_NORMAL)
+ out.normal = transform_normal_simulation_to_world(normal);
+
+ return out;
+}
+
+@fragment
+fn fragment(in: VertexOutput) -> @location(0) vec4<f32> {
+ // Read fragment inputs
+ @if(USE_ALPHA_MASK)
+ var alpha_cutoff: f32 = {{ALPHA_CUTOFF}};
+ var color = in.color;
+ @if(NEEDS_UV)
+ var uv = in.uv;
+ @if(NEEDS_NORMAL)
+ var normal = in.normal;
+ @if(NEEDS_PARTICLE_FRAGMENT)
+ var particle = particle_buffer.particles[in.slab_particle_index];
+
+{{FRAGMENT_MODIFIERS}}
+
+ @if(USE_ALPHA_MASK)
+ if color.a >= alpha_cutoff {
+ color.a = 1.0;
+ } else {
+ discard;
+ }
+
+ return color;
+}
diff --git a/vendor/bevy_hanabi/src/render/vfx_sort.wesl b/vendor/bevy_hanabi/src/render/vfx_sort.wesl
new file mode 100644
index 00000000..863f7d77
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/vfx_sort.wesl
@@ -0,0 +1,474 @@
+/// Key-value pair to sort, with optional secondary key.
+///
+/// Sorting operates on the key (and the secondary key as discriminant, if present,
+/// and if the primary keys are equal). The value is carried over alongside the key(s),
+/// unmodified. It generally represents or indexes the payload associated with the key(s).
+struct KeyValuePair {
+ /// Sorting key.
+ key: u32,
+ /// Secondary sorting key. Used for values with equal primary key.
+ @if(HAS_DUAL_KEY)
+ key2: u32,
+ /// Value associated with the sort key(s), generally an index to some other data.
+ /// Copied as is and otherwise ignored by the sorting algorithm.
+ value: u32,
+}
+
+/// Buffer of key-value pairs to sort.
+struct SortBuffer {
+ /// Number of items in the buffer.
+ count: i32,
+ /// Pairs to sort. On output, contains the pairs in sorted order.
+ pairs: array<KeyValuePair>,
+}
+
+/// Check whether kv1 > kv2, comparing the key(s) of each pair.
+fn compare_greater(kv1: KeyValuePair, kv2: KeyValuePair) -> bool {
+ if (kv1.key > kv2.key) {
+ return true;
+ }
+ @if(HAS_DUAL_KEY)
+ if (kv1.key == kv2.key) {
+ return kv1.key2 > kv2.key2;
+ }
+ return false;
+}
+
+@group(0) @binding(0) var<storage, read_write> sort_buffer : SortBuffer;
+
+/// Number of items sorted per thread, serially.
+const numItemPerThread: u32 = 16u;
+
+/// Number of threads per workgroup (block).
+const numThreads: u32 = 64u;
+
+/// Size of a block of KeyValuePair in workgroup memory.
+const blockSize: u32 = numThreads * numItemPerThread; // 1024
+
+// Workgroup has at least 16kB memory (max_compute_workgroup_storage_size).
+// Note that Vulkan on Windows 11 report 16352, not 16384 (so, lower than
+// the default in the wgpu docs).
+var<workgroup> shared_pairs : array<KeyValuePair, blockSize>; // 12 kB
+
+/// Offset inside the sort buffer pairs of the source half to read unsorted pairs from.
+var<private> src: u32;
+
+/// Offset inside the sort buffer pairs of the destination half to write sorted pairs to.
+var<private> dst: u32;
+
+/// Sort locally inside a single block (workgroup), using workgroup-shared memory.
+///
+/// `tid` is the local thread ID inside the block (0..64). The `src` and `dst` offsets are
+/// the starts of blockSize-length memory blocks inside the sort buffer pairs, to read from
+/// and write to, respectively. `total_num_items` is the number of items in the block; this
+/// is typically equal to blockSize, except for the last block. `src == dst` is valid, and
+/// simply sort in-place inside the storage buffer.
+///
+/// https://moderngpu.github.io/mergesort.html#blocksort
+/// https://moderngpu.github.io/mergesort.html#sortnetworks
+fn block_sort(tid: u32, src: u32, dst: u32, total_num_items: u32) {
+
+ var pairs: array<KeyValuePair, numItemPerThread>;
+
+ // Each thread copies numItemPerThread into a local register array, then sort
+ // that array serially inside the thread, before copying the sorted result
+ // into shared workgroup memory for the block-level merge sort.
+ let num_threads = (total_num_items + numItemPerThread - 1) / numItemPerThread;
+ let begin = tid * numItemPerThread;
+ let end = min(total_num_items, begin + numItemPerThread);
+ if (tid < num_threads) {
+ // Copy pairs into register array
+ for (var i: u32 = begin; i < end; i += 1u) {
+ pairs[i - begin] = sort_buffer.pairs[src + i];
+ }
+
+ // Sort array serially inside this thread
+ let num = end - begin;
+ batcher_odd_even_mergesort(&pairs, num);
+
+ // Copy the data into shared workgroup memory
+ for (var i: u32 = begin; i < end; i += 1u) {
+ shared_pairs[i] = pairs[i - begin];
+ }
+ }
+
+ // Wait for all threads to have sorted their own thread-local values, and written
+ // them into their own slice of shared memory, before we read back shared memory below.
+ workgroupBarrier();
+
+ // shared_pairs[] contains a series of numItemPerThread-length sorted sub-arrays.
+ // Merge-sort in parallel all those sub-arrays into increasibly larger sub-arrays
+ // with increasngly more (= coop) threads collaborating to process each merge.
+ for (var coop: u32 = 2u; coop <= numThreads; coop = coop * 2u) {
+ let list = ~(coop - 1) & tid;
+ let diag = min(total_num_items, numItemPerThread * ((coop - 1) & tid));
+ let start = numItemPerThread * list;
+ let a0 = min(total_num_items, start);
+ let b0 = min(total_num_items, start + numItemPerThread * (coop / 2));
+ let b1 = min(total_num_items, start + numItemPerThread * coop);
+
+ let num_a = b0 - a0;
+ let num_b = b1 - b0;
+ let a_i = calc_merge_path(a0, b0, num_a, num_b, diag);
+
+ // Merge the 2 sorted lists
+ var ia = a0 + a_i;
+ var ib = b0 + diag - a_i;
+ for (var i: u32 = 0; i < numItemPerThread; i += 1u) {
+ if ((ib >= b1) || ((ia < b0) && !compare_greater(shared_pairs[ia], shared_pairs[ib]))) {
+ pairs[i] = shared_pairs[ia];
+ ia += 1u;
+ } else {
+ pairs[i] = shared_pairs[ib];
+ ib += 1u;
+ }
+ }
+
+ // We're about to write back exactly numItemPerThread elements into the shared array.
+ // However by design threads may read more values in either of the two merged lists,
+ // so we need to wait for all co-op threads to finish reading before we can write back.
+ workgroupBarrier();
+
+ // Copy back into shared memory for next iteration
+ for (var i: u32 = 0; i < numItemPerThread; i += 1u) {
+ shared_pairs[begin + i] = pairs[i];
+ }
+
+ // Next iteration (or the final write) need to read back from shared memory, so we need
+ // to wait for all threads to finish writing there.
+ workgroupBarrier();
+ }
+
+ // Copy sorted items from shared workgroup memory back into sort_buffer
+ if (tid < num_threads) {
+ for (var i: u32 = begin; i < end; i += 1u) {
+ sort_buffer.pairs[dst + i] = shared_pairs[i];
+ }
+ }
+}
+
+/// Calculate a single merge path for a subsequent parallel merge.
+///
+/// INPUTS:
+/// - Values A : var<workgroup> shared_pairs[num_a]
+/// - Values B : var<workgroup> arr1[num_b]
+/// - Index of diagonal constraint : diag
+///
+/// OUTPUT:
+/// Index in A of the merge path end. The index in B is ib = (diag - ia),
+/// since a merge path is always of length 'diag' so (ia + ib == diag).
+///
+/// The merge path is such that the merged sub-list [0..diag[ contains the
+/// first 'i_a' elements of A and the first 'i_b' elements of B. This means
+/// that we can load and merge in parallel exactly the elements between two
+/// consecutive diagonals, since we know exactly in advance which elements
+/// of the merged lists will be used, before we even start the actual merge.
+/// So calling calc_merge_path() N times sub-divides some merge lists into
+/// N+1 independent mergeable intervals. We can then recusrively merge down.
+///
+/// https://moderngpu.github.io/bulkinsert.html#mergepath
+fn calc_merge_path(offset_a: u32, offset_b: u32, num_a: u32, num_b: u32, diag: u32) -> u32 {
+ // Intersection of cross-diagonal with the X axis (alongside A) at the
+ // bottom of the merge matrix. This is the min A value to consider.
+ var begin = diag - min(diag, num_b); // == min(0, diag - num_b) >= 0
+ // Intersection of cross-diagonal with the X axis (alongside A) at the
+ // top of the merge matrix. This is the max A value to consider.
+ var end = min(diag, num_a);
+
+ // Binary search the cross-diagonal intersection with the merge path,
+ // which is the index where the values are sorted.
+ while (begin < end) {
+ let mid = (begin + end) >> 1u;
+ // Only if b < a do we move B, otherwise in case of equality we
+ // favor A, to ensure stability (since A is the first merge list,
+ // so its elements are originally located before those of B before
+ // we merge).
+ if (compare_greater(shared_pairs[offset_a + mid], shared_pairs[offset_b + diag - 1u - mid])) {
+ end = mid;
+ } else {
+ begin = mid + 1;
+ }
+ }
+
+ return begin;
+}
+
+/// Batcher's odd-even merge sort.
+///
+/// INPUTS:
+/// - Values A : var<workgroup> shared_pairs[]
+/// - Offset from the start of shared_pairs where the values to sort start : offset
+/// - Number of values to sort : n
+///
+/// OUTPUTS:
+/// - Values A in shared_pairs[], sorted
+///
+/// This is a sorting network. Not asymptotically optimal, but reasonably efficient.
+/// It's more of a reference implementation, from 1998. Not the fastest by today's
+/// standards. It's not stable.
+///
+/// https://en.wikipedia.org/wiki/Batcher_odd%E2%80%93even_mergesort
+fn batcher_odd_even_mergesort(data: ptr<function, array<KeyValuePair, numItemPerThread>>, num: u32) {
+ // Pad with elements which always compare greater, so they end up at the end
+ // of the array after all real elements, and when truncated we get back the
+ // sorted original array.
+ for (var i: u32 = num; i < numItemPerThread; i += 1u) {
+ data[i].key = 0xFFFFFFFFu;
+ @if(HAS_DUAL_KEY)
+ data[i].key2 = 0xFFFFFFFFu;
+ }
+
+ // Actual numItemPerThread-length sort
+ for (var p: u32 = 1; p < numItemPerThread; p += p) {
+ for (var k: u32 = p; k >= 1; k = k >> 1) {
+ for (var j: u32 = k % p; j + k < numItemPerThread; j += 2 * k) {
+ for (var i: u32 = 0; i < min(k, numItemPerThread - j - k); i += 1) {
+ let i0 = i + j;
+ let i1 = i + j + k;
+ let f0 = f32(i0) / f32(2 * p);
+ let f1 = f32(i1) / f32(2 * p);
+ // i0 < i1 < numItemPerThread - 1
+ if (floor(f0) == floor(f1)) {
+ let idx0 = i0;
+ let idx1 = i1;
+ if (compare_greater(data[idx0], data[idx1])) {
+ let kv = data[idx0];
+ data[idx0] = data[idx1];
+ data[idx1] = kv;
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+/// Find the index of an effect from the index of a particle.
+///
+/// This uses a binary search on the slab_offset field of the spawners array, which
+/// represents a prefix sum of the particle count per effect (for previous effects;
+/// the value is actually the base particle so the first entry is always 0).
+fn find_effect_from_particle(num_effects: u32, particle_index: u32) -> u32 {
+ var lo = 0u;
+ var hi = num_effects;
+ var nnn = 0;
+ while (lo < hi) {
+ let mid = (hi + lo) >> 1u;
+ let base_particle = shared_pairs[mid].key;
+ if (particle_index >= base_particle) {
+ lo = mid + 1u;
+ } else if (particle_index < base_particle) {
+ hi = mid;
+ }
+ nnn += 1;
+ if (nnn >= 100) {
+ return 0xDEADBEEFu;
+ }
+ }
+ return lo - 1u;
+}
+
+/// Get the number N such that log2(value) == N rounded up.
+fn find_log2(value: u32) -> u32 {
+ var num = 31u - countLeadingZeros(value);
+ if ((value & (value - 1u)) != 0u) { // not a power of 2
+ num += 1u;
+ }
+ return num;
+}
+
+/// Sort each block in parallel on a separate workgroup.
+@compute @workgroup_size(64)
+fn parallel_block_sort(@builtin(local_invocation_index) thread_id: u32, @builtin(workgroup_id) workgroup_id: vec3<u32>) {
+ let block_id = workgroup_id.x; // wgpu doesn't support @builtin(workgroup_index)
+ let total_num_items = u32(sort_buffer.count);
+
+ // Sort each block independently
+ let offset = block_id * blockSize;
+ let block_num = min(offset + blockSize, total_num_items) - offset;
+ let block_src = src + offset;
+ let block_dst = dst + offset;
+ block_sort(thread_id, block_src, block_dst, block_num);
+}
+
+fn parallel_merge_sort(thread_id: u32, block_id: u32) {
+ let total_num_items = u32(sort_buffer.count);
+ let num_blocks = (total_num_items + blockSize - 1) / blockSize;
+ let num_passes = find_log2(num_blocks);
+
+ // Sort each block independently
+ {
+ let offset = block_id * blockSize;
+ let block_num = min(offset + blockSize, total_num_items) - offset;
+ let block_src = src + offset;
+ let block_dst = dst + offset;
+ block_sort(thread_id, block_src, block_dst, block_num);
+ }
+
+ // Merge-sort blocks into storage buffer by recusrively merging pairs of adacent sorted lists of increasing size
+ src = 0u;
+ dst = total_num_items;
+ for (var ipass: u32 = 0u; ipass < num_passes; ipass += 1u) {
+ let coop = 2u << ipass;
+
+ let list = ~(coop - 1u) & block_id;
+ let diag = min(total_num_items, blockSize * ((coop - 1u) & block_id));
+ let start = blockSize * list;
+ let a0 = min(total_num_items, start);
+ let b0 = min(total_num_items, start + blockSize * (coop / 2u));
+ let b1 = min(total_num_items, start + blockSize * coop);
+
+ // TODO... calc merge path + do the ping-pong merge
+ }
+}
+
+
+/// Test for find_effect_from_particle().
+@if(TEST)
+@compute @workgroup_size(64)
+fn test_find_effect_from_particle(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
+ let tid = global_invocation_id.x;
+
+ // Read test data from sort buffer
+ let num_effects = u32(sort_buffer.count);
+ let num_particles = arrayLength(&sort_buffer.pairs);
+ if (tid < num_effects) {
+ shared_pairs[tid] = sort_buffer.pairs[tid];
+ }
+
+ workgroupBarrier();
+
+ // Execute the actual test
+ let particle_per_thread = (num_particles + 63u) >> 6u;
+ let first_particle = particle_per_thread * tid;
+ let last_particle = min(first_particle + particle_per_thread, num_particles);
+ for (var i = first_particle; i < last_particle; i += 1u) {
+ sort_buffer.pairs[i].value = find_effect_from_particle(num_effects, i);
+ }
+}
+
+/// Test for batcher_odd_even_mergesort().
+@if(TEST)
+@compute @workgroup_size(64)
+fn test_batcher_odd_even_mergesort(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
+ let tid = global_invocation_id.x;
+ let total_num_items = u32(sort_buffer.count);
+
+ // Threads copy all items into a local register array
+ var pairs: array<KeyValuePair, numItemPerThread>;
+ let base_item = tid * numItemPerThread;
+ let num_items = min(numItemPerThread, total_num_items - base_item);
+ for (var i: u32 = base_item; i < base_item + num_items; i += 1u) {
+ pairs[i - base_item] = sort_buffer.pairs[i];
+ }
+
+ workgroupBarrier();
+
+ // Sort all items in the local array
+ batcher_odd_even_mergesort(&pairs, numItemPerThread);
+
+ workgroupBarrier();
+
+ // Threads copy all items back into sort_buffer
+ for (var i: u32 = base_item; i < base_item + num_items; i += 1u) {
+ sort_buffer.pairs[i] = pairs[i - base_item];
+ }
+}
+
+/// Test for calc_merge_path().
+@if(TEST)
+@compute @workgroup_size(64)
+fn test_calc_merge_path(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
+ let tid = global_invocation_id.x;
+
+ // 64 threads copy all items into shared_pairs
+ let total_num_items = u32(sort_buffer.count) >> 1u;
+ let num_items_per_thread = (total_num_items + 63u) >> 6u;
+ let base_item = tid * num_items_per_thread;
+ let num_items = min(num_items_per_thread, total_num_items - base_item);
+ for (var i: u32 = base_item; i < base_item + num_items; i += 1u) {
+ // First half -> shared_pairs
+ shared_pairs[i] = sort_buffer.pairs[i];
+ // Second half -> shared_pairs
+ shared_pairs[total_num_items + i] = sort_buffer.pairs[total_num_items + i];
+ }
+
+ workgroupBarrier();
+
+ // The total path length is the sum of the lengths of the two lists, which here
+ // because they're of the same size is (total_num_items * 2u).
+ let total_path_len = total_num_items * 2u;
+
+ // Divide the entire merge into one interval per thread. The last interval can
+ // be shorter, which exercises the final partial merge tile.
+ let path_len = (total_path_len + 63u) / 64u;
+ let num_paths = (total_path_len + path_len - 1) / path_len;
+
+ // Calculate the merge path for each section
+ if (tid < num_paths) {
+ let diag = min((tid + 1u) * path_len, total_path_len);
+ let start_a = 0u;
+ let num_a = total_num_items;
+ let start_b = num_a;
+ let num_b = num_a; // merging 2 lists of same size
+ let a_i = calc_merge_path(start_a, start_b, num_a, num_b, diag);
+
+ // Copy results into sort_buffer
+ sort_buffer.pairs[tid].key = diag;
+ sort_buffer.pairs[tid].value = a_i;
+ }
+}
+
+/// Test for block_sort().
+@if(TEST)
+@compute @workgroup_size(64)
+fn test_block_sort(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
+ let tid = global_invocation_id.x;
+ let total_num_items = u32(sort_buffer.count);
+ block_sort(tid, 0u, 0u, total_num_items);
+}
+
+
+// GPU sorts
+// https://linebender.org/wiki/gpu/sorting/
+// https://moderngpu.github.io/mergesort.html
+// https://moderngpu.github.io/mergesort.html#blocksort
+// https://moderngpu.github.io/segsort.html
+
+/// Naive insertion sort. TODO: replace with something faster.
+// @compute @workgroup_size(64)
+// fn main(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
+// // Naive single-threaded sort
+// if (global_invocation_id.x != 0) {
+// return;
+// }
+
+// // Insertion sort
+// let num_items = sort_buffer.count;
+// for (var i: i32 = 1; i < num_items; i += 1) {
+// var kv = sort_buffer.pairs[i];
+// var j = i;
+// while (j > 0 && compare_greater(sort_buffer.pairs[j - 1], kv)) {
+// sort_buffer.pairs[j] = sort_buffer.pairs[j - 1];
+// j -= 1;
+// }
+// sort_buffer.pairs[j] = kv;
+// }
+
+// // Clear for next frame
+// sort_buffer.count = 0;
+// }
+
+/// Sort particles in blocks of 1024 per workgroup.
+///
+/// Larger inputs are merged by vfx_sort_merge.wesl in subsequent compute passes.
+@compute @workgroup_size(64)
+fn sort_blocks(@builtin(local_invocation_index) thread_id: u32, @builtin(workgroup_id) workgroup_id: vec3<u32>) {
+ let block_id = workgroup_id.x; // wgpu doesn't support @builtin(workgroup_index)
+
+ let total_num_items = u32(sort_buffer.count);
+
+ let offset = block_id * blockSize;
+ let count = min(offset + blockSize, total_num_items) - offset; // <= blockSize
+ block_sort(thread_id, offset, offset, count);
+}
diff --git a/vendor/bevy_hanabi/src/render/vfx_sort_copy.wesl b/vendor/bevy_hanabi/src/render/vfx_sort_copy.wesl
new file mode 100644
index 00000000..f7f815c8
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/vfx_sort_copy.wesl
@@ -0,0 +1,54 @@
+import bevy_hanabi::render::vfx_common::{EffectMetadata, Spawner};
+
+/// Key-value pair for sorting, with optional second sort key.
+struct KeyValuePair {
+ /// Sorting key.
+ key: u32,
+ /// Secondary sorting key. Sorts value with the same primary key.
+ key2: u32,
+ /// Value associated with the sort key(s), generally an index to some other data.
+ /// Copied as is and otherwise ignored by the sorting algorithm.
+ value: u32,
+}
+
+struct SortBuffer {
+ count: i32,
+ pairs: array<KeyValuePair>,
+}
+
+struct IndirectIndexBuffer {
+ data: array<u32>,
+}
+
+struct MergeParams {
+ max_list_size: u32,
+ source_buffer: u32,
+}
+
+@group(0) @binding(0) var<storage, read_write> indirect_index_buffer : IndirectIndexBuffer;
+@group(0) @binding(1) var<storage, read> sort_buffer : SortBuffer;
+// Technically read-only, but the type contains atomic<> fields and wasm is strict about it
+@group(0) @binding(2) var<storage, read_write> effect_metadatas : array<EffectMetadata>;
+@group(0) @binding(3) var<storage, read> spawner : Spawner;
+@group(0) @binding(4) var<storage, read> merge_params : MergeParams;
+
+/// Copy the sorted particle indices back into the effect index buffer.
+@compute @workgroup_size(64)
+fn sort_copy(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
+ let row_index = global_invocation_id.x;
+ let effect_metadata_index = spawner.effect_metadata_index;
+ let count = atomicLoad(&effect_metadatas[effect_metadata_index].alive_count); // TODO - atomic not needed
+ if (row_index >= count) {
+ return;
+ }
+
+ let base_particle = spawner.slab_offset;
+
+ // Write the particle index back into the same ping-pong column index we read it from
+ // in vfx_sort_fill. Sorting is optional and shouldn't influence that ping-pong logic.
+ let write_index = effect_metadatas[effect_metadata_index].indirect_write_index;
+
+ let source_offset = merge_params.source_buffer * u32(sort_buffer.count);
+ let particle_index = sort_buffer.pairs[source_offset + row_index].value;
+ indirect_index_buffer.data[(base_particle + row_index) * 3u + write_index] = particle_index;
+}
diff --git a/vendor/bevy_hanabi/src/render/vfx_sort_fill.wesl b/vendor/bevy_hanabi/src/render/vfx_sort_fill.wesl
new file mode 100644
index 00000000..97929896
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/vfx_sort_fill.wesl
@@ -0,0 +1,90 @@
+import bevy_hanabi::render::vfx_common::{EffectMetadata, Spawner};
+// raea: the main camera's frustum, and the effect's transform (#52)
+import bevy_hanabi::render::vfx_common::{SimParams, unpack_compressed_transform};
+
+/// Key-value pair for sorting, with optional second sort key.
+struct KeyValuePair {
+ /// Sorting key.
+ key: u32,
+ /// Secondary sorting key. Sorts value with the same primary key.
+ key2: u32,
+ /// Value associated with the sort key(s), generally an index to some other data.
+ /// Copied as is and otherwise ignored by the sorting algorithm.
+ value: u32,
+}
+
+struct SortBuffer {
+ count: atomic<i32>,
+ pairs: array<KeyValuePair>,
+}
+
+/// Particle buffer as an array of u32. This prevents having to specialize this shader
+/// for every single particle layout.
+struct RawParticleBuffer {
+ data: array<u32>,
+}
+
+@group(0) @binding(0) var<storage, read_write> sort_buffer : SortBuffer;
+@group(0) @binding(1) var<storage, read> particle_buffer : RawParticleBuffer;
+@group(0) @binding(2) var<storage, read> indirect_index_buffer : array<u32>;
+// Technically read-only, but the type contains atomic<> fields and wasm is strict about it
+@group(0) @binding(3) var<storage, read_write> effect_metadatas : array<EffectMetadata>;
+@group(0) @binding(4) var<storage, read> spawner : Spawner;
+// raea: (#52)
+@group(0) @binding(5) var<uniform> sim_params : SimParams;
+
+// raea: the flags on the sort key's offset (mod.rs's RAEA_SORT_BY_DISTANCE and RAEA_SORT_LOCAL, #52)
+const RAEA_SORT_BY_DISTANCE: u32 = 0x80000000u;
+const RAEA_SORT_LOCAL: u32 = 0x40000000u;
+
+/// Fill the sorting key-value pair buffer with data to prepare for actual sorting.
+@compute @workgroup_size(64)
+fn sort_fill(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
+ let thread_index = global_invocation_id.x;
+ let effect_metadata_index = spawner.effect_metadata_index;
+ let count = atomicLoad(&effect_metadatas[effect_metadata_index].alive_count); // TODO - atomic not needed
+ if (thread_index >= count) {
+ return;
+ }
+
+ let base_particle = spawner.slab_offset;
+
+ // Read the particle index from the ping-pong column index written this frame by vfx_update.
+ // After sorting we will write back into that same column, so that the sorting effectively
+ // sorted the column in-place (no ping-pong column swap here).
+ let read_index = effect_metadatas[effect_metadata_index].indirect_write_index;
+ let particle_index = indirect_index_buffer[(base_particle + thread_index) * 3u + read_index];
+
+ let particle_offset = (base_particle + particle_index) * effect_metadatas[effect_metadata_index].particle_stride;
+ let key_offset = particle_offset + effect_metadatas[effect_metadata_index].sort_key_offset;
+ let key2_offset = particle_offset + effect_metadatas[effect_metadata_index].sort_key2_offset;
+
+ let pair_index = atomicAdd(&sort_buffer.count, 1);
+ sort_buffer.pairs[pair_index].value = particle_index;
+
+ // raea: a blended effect's key is its particle's view depth from the main camera, as Bevy sorts its transparent
+ // phase: the distance in front of the near plane (frustum[4], its normal facing in), inverted so the sort's
+ // ascending order draws far first (a non-negative f32's bits order as a u32 does); AGE breaks ties, or 0 (#52)
+ let raea_flags = effect_metadatas[effect_metadata_index].sort_key_offset;
+ if ((raea_flags & RAEA_SORT_BY_DISTANCE) != 0u) {
+ let at = particle_offset + (raea_flags & ~(RAEA_SORT_BY_DISTANCE | RAEA_SORT_LOCAL));
+ var position = vec3<f32>(
+ bitcast<f32>(particle_buffer.data[at]),
+ bitcast<f32>(particle_buffer.data[at + 1u]),
+ bitcast<f32>(particle_buffer.data[at + 2u]),
+ );
+ if ((raea_flags & RAEA_SORT_LOCAL) != 0u) {
+ position = (unpack_compressed_transform(spawner.transform) * vec4<f32>(position, 1.0)).xyz;
+ }
+ let near = sim_params.frustum[4];
+ sort_buffer.pairs[pair_index].key = ~bitcast<u32>(max(dot(near.xyz, position) + near.w, 0.0));
+ let key2 = effect_metadatas[effect_metadata_index].sort_key2_offset;
+ sort_buffer.pairs[pair_index].key2 = 0u;
+ if (key2 != 0xFFFFFFFFu) {
+ sort_buffer.pairs[pair_index].key2 = particle_buffer.data[key2_offset];
+ }
+ } else {
+ sort_buffer.pairs[pair_index].key = particle_buffer.data[key_offset];
+ sort_buffer.pairs[pair_index].key2 = particle_buffer.data[key2_offset];
+ }
+}
diff --git a/vendor/bevy_hanabi/src/render/vfx_sort_merge.wesl b/vendor/bevy_hanabi/src/render/vfx_sort_merge.wesl
new file mode 100644
index 00000000..230f7191
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/vfx_sort_merge.wesl
@@ -0,0 +1,88 @@
+/// Key-value pair to sort, with optional secondary key.
+///
+/// Sorting operates on the key (and the secondary key as discriminant, if present,
+/// and if the primary keys are equal). The value is carried over alongside the key(s),
+/// unmodified. It generally represents or indexes the payload associated with the key(s).
+struct KeyValuePair {
+ /// Sorting key.
+ key: u32,
+ /// Secondary sorting key. Used for values with equal primary key.
+ @if(HAS_DUAL_KEY)
+ key2: u32,
+ /// Value associated with the sort key(s), generally an index to some other data.
+ /// Copied as is and otherwise ignored by the sorting algorithm.
+ value: u32,
+}
+
+/// Buffer of key-value pairs to sort.
+struct SortBuffer {
+ /// Number of items in the buffer.
+ count: i32,
+ /// Pairs to sort. On output, contains the pairs in sorted order.
+ pairs: array<KeyValuePair>,
+}
+
+/// Check whether kv1 > kv2, comparing the key(s) of each pair.
+fn compare_greater(kv1: KeyValuePair, kv2: KeyValuePair) -> bool {
+ if (kv1.key > kv2.key) {
+ return true;
+ }
+ @if(HAS_DUAL_KEY)
+ if (kv1.key == kv2.key) {
+ return kv1.key2 > kv2.key2;
+ }
+ return false;
+}
+
+struct MergeParams {
+ /// Maximum number of items per list for this pass.
+ max_list_size: u32,
+ /// Half of the ping-pong buffer to read from: 0 for the first half, 1 for
+ /// the second half.
+ source_buffer: u32,
+}
+
+@group(0) @binding(0) var<storage, read_write> sort_buffer : SortBuffer;
+@group(0) @binding(1) var<storage, read> merge_params : MergeParams;
+
+/// Merge two sorted lists [a..a+num_a) and [b..b+num_b) into a single sorted list.
+///
+/// The source elements are read from the sort buffer starting at offsets (src + a)
+/// and (src + b), and the merged list written starting at offset (dst + a).
+fn merge_lists_serial(a: u32, num_a: u32, b: u32, num_b: u32, src: u32, dst: u32) {
+ var ia = a;
+ var ib = b;
+ let a_end = a + num_a;
+ let b_end = b + num_b;
+ for (var i: u32 = 0u; i < num_a + num_b; i += 1u) {
+ if ((ib >= b_end) || ((ia < a_end) && !compare_greater(sort_buffer.pairs[src + ia], sort_buffer.pairs[src + ib]))) {
+ sort_buffer.pairs[dst + a + i] = sort_buffer.pairs[src + ia];
+ ia += 1u;
+ } else {
+ sort_buffer.pairs[dst + a + i] = sort_buffer.pairs[src + ib];
+ ib += 1u;
+ }
+ }
+}
+
+/// Sort each block in parallel on a separate workgroup.
+@compute @workgroup_size(64)
+fn merge_sort(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
+ let tid = global_invocation_id.x;
+ let total_num_items = u32(sort_buffer.count);
+ let list_size = merge_params.max_list_size;
+ let num_lists = (total_num_items + list_size - 1u) / list_size;
+ let num_merge_operations = (num_lists + 1u) / 2u;
+ if (tid < num_merge_operations) {
+ // We always merge 2 consecutive lists of up to list_size items. The last list may have
+ // less elements, if total_num_items is not a multiple of list_size (which is common).
+ // An unmatched last list is copied unchanged to the other ping-pong half.
+ let start_a = tid * list_size * 2u;
+ let start_b = start_a + list_size;
+ let num_a = min(list_size, total_num_items - start_a);
+ let num_b = min(list_size, total_num_items - min(start_b, total_num_items));
+ let src = merge_params.source_buffer * total_num_items;
+ let dst = (1u - merge_params.source_buffer) * total_num_items;
+ merge_lists_serial(start_a, num_a, start_b, num_b, src, dst);
+ }
+}
diff --git a/vendor/bevy_hanabi/src/render/vfx_update.wesl b/vendor/bevy_hanabi/src/render/vfx_update.wesl
new file mode 100644
index 00000000..e94091a4
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/vfx_update.wesl
@@ -0,0 +1,190 @@
+import bevy_hanabi::render::vfx_common::{
+ ChildInfo, ChildInfoBuffer, EventBuffer, DispatchIndirectArgs, IndirectBuffer,
+ EffectMetadata, RenderGroupIndirect, SimParams, Spawner, DrawIndexedIndirectArgs, BatchInfo,
+ seed, tau, pcg_hash, to_float01, frand, frand2, frand3, frand4,
+ rand_uniform_f, rand_uniform_vec2, rand_uniform_vec3, rand_uniform_vec4,
+ rand_normal_f, rand_normal_vec2, rand_normal_vec3, rand_normal_vec4, proj,
+ unpack_compressed_transform, unpack_compressed_transform_3x3_transpose
+};
+
+struct Particle {
+{{ATTRIBUTES}}
+}
+
+struct ParticleBuffer {
+ particles: array<Particle>,
+}
+
+
+{{PARENT_PARTICLE}}
+
+@if(READ_PARENT_PARTICLE)
+struct ParentParticleBuffer {
+ particles: array<ParentParticle>,
+}
+
+
+{{PROPERTIES}}
+
+/// Location of an effect in a slab.
+struct EffectLocation {
+ /// Index of the effect in the global list of effects.
+ effect_index: u32,
+ /// Base particle index, that is index in the slab of the first particle for this instance.
+ base_particle: u32,
+ /// Index of this particle relative to its effect. Note that if there's an indirection
+ /// buffer then this is the linear index in [0:N[ of the particle to update, before the indirection.
+ update_index: u32,
+}
+
+/// Find the index of an effect from the index of a particle.
+///
+/// This uses a binary search on the slab_offset field of the spawners array, which
+/// represents a prefix sum of the particle count per effect (for previous effects;
+/// the value is actually the base particle so the first entry is always 0).
+///
+/// Requirements:
+/// - var<storage, read> batch_info : BatchInfo
+/// - var<storage, read> prefix_sum : array<u32>
+fn find_location_from_particle(update_particle_index: u32) -> EffectLocation {
+ var lo = batch_info.prefix_sum_offset;
+ var hi = lo + batch_info.prefix_sum_count;
+ var num_iter = 0; // avoid deadlocking the GPU by capping the iteration count
+ while (lo < hi) {
+ let mid = (hi + lo) >> 1u;
+ let base_particle = prefix_sum[mid];
+ if (update_particle_index >= base_particle) {
+ lo = mid + 1u;
+ } else if (update_particle_index < base_particle) {
+ hi = mid;
+ }
+ num_iter += 1;
+ if (num_iter >= 100) {
+ return EffectLocation(0xDEADBEEFu, 0xDEADBEEFu, 0xDEADBEEFu);
+ }
+ }
+ let base_index = prefix_sum[lo - 1u];
+ let update_index = update_particle_index - base_index;
+ let effect_index = lo - 1u - batch_info.prefix_sum_offset;
+ let base_particle = spawners[batch_info.spawner_base + effect_index].slab_offset;
+ return EffectLocation(effect_index, base_particle, update_index);
+}
+
+/// Transform a simulation space position into a world space position.
+///
+/// The simulation space depends on the effect's SimulationSpace value, and is either
+/// the effect space (SimulationSpace::Local) or the world space (SimulationSpace::Global).
+fn transform_position_simulation_to_world(sim_position: vec3<f32>) -> vec4<f32> {
+ @if(LOCAL_SPACE_SIMULATION)
+ let transform = unpack_compressed_transform(spawners[spawner_index].transform);
+ @if(LOCAL_SPACE_SIMULATION)
+ return transform * vec4<f32>(sim_position, 1.0);
+ @if(!LOCAL_SPACE_SIMULATION)
+ return vec4<f32>(sim_position, 1.0);
+}
+
+fn transform_normal_simulation_to_world(sim_normal: vec3<f32>) -> vec3<f32> {
+ // We use the inverse transpose transform to transform normals.
+ // The inverse transpose is the same as the transposed inverse, so we can
+ // safely use the inverse transform.
+ @if(LOCAL_SPACE_SIMULATION)
+ let transform = unpack_compressed_transform_3x3_transpose(spawners[spawner_index].inverse_transform);
+ @if(LOCAL_SPACE_SIMULATION)
+ return transform * sim_normal;
+ @if(!LOCAL_SPACE_SIMULATION)
+ return sim_normal;
+}
+
+@group(0) @binding(0) var<uniform> sim_params : SimParams;
+@group(0) @binding(1) var<storage, read_write> draw_indirect_buffer : array<DrawIndexedIndirectArgs>;
+
+// "particle" group @1
+@group(1) @binding(0) var<storage, read_write> particle_buffer : ParticleBuffer;
+@group(1) @binding(1) var<storage, read_write> indirect_buffer : IndirectBuffer;
+@if(READ_PARENT_PARTICLE)
+@group(1) @binding(2) var<storage, read> parent_particle_buffer : ParentParticleBuffer;
+
+// "spawner" group @2
+@group(2) @binding(0) var<storage, read> spawners : array<Spawner>;
+@group(2) @binding(1) var<storage, read> prefix_sum : array<u32>;
+@group(2) @binding(2) var<storage, read> batch_info : BatchInfo;
+{{PROPERTIES_BINDING}}
+{{MATERIAL_BINDINGS}}
+
+// "metadata" group @3
+@group(3) @binding(0) var<storage, read_write> effect_metadatas : array<EffectMetadata>;
+{{EMIT_EVENT_BUFFER_BINDINGS}}
+
+{{UPDATE_EXTRA}}
+
+{{EMIT_EVENT_BUFFER_APPEND_FUNCS}}
+
+var<private> effect_metadata_index: u32;
+var<private> properties_array_index: u32;
+var<private> spawner_index: u32;
+
+@compute @workgroup_size(64)
+fn main(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
+ // Particle index in the packed update space of this batch.
+ let update_particle_index = global_invocation_id.x;
+ if (update_particle_index >= batch_info.total_update_count) {
+ return;
+ }
+
+ // Find the index of the effect this particle is part of.
+ let location = find_location_from_particle(update_particle_index);
+ spawner_index = batch_info.spawner_base + location.effect_index;
+ let spawner = &spawners[spawner_index];
+ effect_metadata_index = (*spawner).effect_metadata_index;
+ let base_particle = (*spawner).slab_offset;
+
+ // Cap at maximum number of alive particles for the current effect
+ let effect_metadata = &effect_metadatas[effect_metadata_index];
+ if (location.update_index >= (*effect_metadata).max_update) {
+ return;
+ }
+ properties_array_index = (*effect_metadata).properties_array_index;
+
+ let write_index = effect_metadata.indirect_write_index;
+ let read_index = 1u - write_index;
+
+ // This is the actual particle index, from the indirection buffer, addressing an
+ // actually alive particle.
+ let particle_index = indirect_buffer
+ .rows[base_particle + location.update_index]
+ .particle_index[read_index];
+
+ @if(READ_PARENT_PARTICLE)
+ let parent_base_particle = (*spawner).parent_slab_offset;
+
+ // Initialize the PRNG seed
+ seed = pcg_hash(particle_index ^ (*spawner).seed);
+
+ var particle: Particle = particle_buffer.particles[base_particle + particle_index];
+ {{AGE_CODE}}
+ {{REAP_CODE}}
+ {{UPDATE_CODE}}
+
+ {{WRITEBACK_CODE}}
+
+ // Check if alive
+ if (!is_alive) {
+ // Save dead index. Note that dead_index is a global slab index.
+ let alive_index = atomicSub(&((*effect_metadata).alive_count), 1u) - 1u;
+ indirect_buffer.rows[base_particle + alive_index].dead_index = base_particle + particle_index;
+
+ // DEBUG
+ //indirect_buffer.rows[base_particle + alive_index].particle_index[0] = 0xFFFFFFFFu;
+ //indirect_buffer.rows[base_particle + alive_index].particle_index[1] = 0xFFFFFFFFu;
+
+ // Also increment copy of dead count, which was updated in dispatch indirect
+ // pass just before, and need to remain correct after this pass. We wouldn't have
+ // to do that here if we had a per-effect pass between update and the next init.
+ atomicAdd(&((*effect_metadata).max_spawn), 1u);
+ } else {
+ // Increment visible particle count (in the absence of any GPU culling), and write
+ // the indirection index for later rendering.
+ let indirect_index = atomicAdd(&draw_indirect_buffer[(*effect_metadata).indirect_render_index].instance_count, 1u);
+ indirect_buffer.rows[base_particle + indirect_index].particle_index[write_index] = particle_index;
+ }
+}
diff --git a/vendor/bevy_hanabi/src/render/vfx_utils.wgsl b/vendor/bevy_hanabi/src/render/vfx_utils.wgsl
new file mode 100644
index 00000000..3700890d
--- /dev/null
+++ b/vendor/bevy_hanabi/src/render/vfx_utils.wgsl
@@ -0,0 +1,92 @@
+/// Arguments for a block operation on a buffer.
+struct BufferOperationArgs {
+ /// Offset, as u32 count, where the operation starts in the source buffer.
+ src_offset: u32,
+ /// Stride, as u32 count, between elements in the source buffer.
+ src_stride: u32,
+ /// Offset, as u32 count, where the operation starts in the destination buffer.
+ dst_offset: u32,
+ /// Stride, as u32 count, between elements in the destination buffer.
+ dst_stride: u32,
+ /// Number of u32 elements to process for this operation.
+ count: u32,
+ /// Thread group size.
+ thread_group_size: u32,
+}
+
+@group(0) @binding(0) var<uniform> args : BufferOperationArgs;
+@group(0) @binding(1) var<storage, read> src_buffer : array<u32>;
+@group(0) @binding(2) var<storage, read_write> dst_buffer : array<u32>;
+
+/// Clear a buffer to zero. Each thread clears a single u32.
+@compute @workgroup_size(64)
+fn zero_buffer(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
+ let thread_index = global_invocation_id.x;
+ if (thread_index >= args.count) {
+ return;
+ }
+ let dst = args.dst_offset + thread_index;
+ dst_buffer[dst] = 0u;
+}
+
+/// Copy a source buffer into a destination buffer. Each thread copies a single u32.
+@compute @workgroup_size(64)
+fn copy_buffer(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
+ let thread_index = global_invocation_id.x;
+ if (thread_index >= args.count) {
+ return;
+ }
+ let src = args.src_offset + thread_index * args.src_stride;
+ let dst = args.dst_offset + thread_index * args.dst_stride;
+ let value = src_buffer[src];
+ dst_buffer[dst] = value;
+}
+
+/// Calculate the number of workgroups to dispatch for a given number of threads.
+fn calc_workground_count(thread_count: u32) -> u32 {
+ // We assume a workgroup size of 64. This is currently the case everywhere in Hanabi,
+ // but would need to be adapted if we decided to vary the workgroup size.
+ let workgroup_count = (thread_count + 63u) >> 6u;
+ return workgroup_count;
+}
+
+/// Fill indirect dispatch arguments from a raw element count, by copying the element count
+/// and rounding it up to the number of thread per workgroup. Each thread copies a single u32.
+@compute @workgroup_size(64)
+fn fill_dispatch_args(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
+ let thread_index = global_invocation_id.x;
+ if (thread_index >= args.count) {
+ return;
+ }
+
+ let src = args.src_offset + thread_index * args.src_stride;
+ let dst = args.dst_offset + thread_index * args.dst_stride;
+ let thread_count = (src_buffer[src] + args.thread_group_size - 1) / args.thread_group_size;
+ let workgroup_count = calc_workground_count(thread_count);
+ dst_buffer[dst] = workgroup_count;
+ dst_buffer[dst + 1u] = 1u;
+ dst_buffer[dst + 2u] = 1u;
+}
+
+/// Fill indirect dispatch arguments from a raw element count, by copying the element count
+/// and rounding it up to the number of thread per workgroup. Each thread copies a single
+/// single u32. Same as fill_dispatch_args(), but both read and write are from the destination
+/// buffer. The source buffer is ignored (no binding).
+@compute @workgroup_size(64)
+fn fill_dispatch_args_self(@builtin(global_invocation_id) global_invocation_id: vec3<u32>) {
+ let thread_index = global_invocation_id.x;
+ if (thread_index >= args.count) {
+ return;
+ }
+ let src = args.src_offset + thread_index * args.src_stride;
+ // Note: we always assume 12-byte dispatch indirect structs, which is the canonical struct
+ // with its x/y/z values, without any extra field or padding.
+ let dst = args.dst_offset + thread_index * 3u;
+ // Note: only the dst_buffer is used
+ let thread_count = dst_buffer[src];
+ let workgroup_count = calc_workground_count(thread_count);
+ dst_buffer[dst] = workgroup_count;
+ dst_buffer[dst + 1u] = 1u;
+ dst_buffer[dst + 2u] = 1u;
+ // leave last entry untouched; sometimes it's used for unrelated things
+}
diff --git a/vendor/bevy_hanabi/src/spawn.rs b/vendor/bevy_hanabi/src/spawn.rs
new file mode 100644
index 00000000..538551d4
--- /dev/null
+++ b/vendor/bevy_hanabi/src/spawn.rs
@@ -0,0 +1,1491 @@
+use std::hash::{Hash, Hasher};
+
+use bevy::{ecs::resource::Resource, log::trace, math::FloatOrd, prelude::*, reflect::Reflect};
+use rand::{
+ distr::{uniform::SampleUniform, Distribution, Uniform},
+ SeedableRng,
+};
+use rand_pcg::Pcg32;
+use serde::{Deserialize, Serialize};
+use thiserror::Error;
+
+use crate::{
+ CompiledParticleEffect, EffectAsset, EffectSimulation, ParticleEffect, SimulationCondition,
+};
+
+/// An RNG to be used in the CPU for the particle system engine
+pub(crate) fn new_rng() -> Pcg32 {
+ let mut rng = rand::rng();
+ let mut seed = [0u8; 16];
+ seed.copy_from_slice(
+ &Uniform::new_inclusive(0, u128::MAX)
+ .unwrap()
+ .sample(&mut rng)
+ .to_le_bytes(),
+ );
+ Pcg32::from_seed(seed)
+}
+
+/// An RNG resource
+#[derive(Resource)]
+pub struct Random(pub Pcg32);
+
+/// Utility trait to help implementing [`std::hash::Hash`] for [`CpuValue`] of
+/// floating-point type.
+pub trait FloatHash: PartialEq {
+ fn hash_f32<H: Hasher>(&self, state: &mut H);
+}
+
+impl FloatHash for f32 {
+ fn hash_f32<H: Hasher>(&self, state: &mut H) {
+ FloatOrd(*self).hash(state);
+ }
+}
+
+impl FloatHash for Vec2 {
+ fn hash_f32<H: Hasher>(&self, state: &mut H) {
+ FloatOrd(self.x).hash(state);
+ FloatOrd(self.y).hash(state);
+ }
+}
+
+impl FloatHash for Vec3 {
+ fn hash_f32<H: Hasher>(&self, state: &mut H) {
+ FloatOrd(self.x).hash(state);
+ FloatOrd(self.y).hash(state);
+ FloatOrd(self.z).hash(state);
+ }
+}
+
+impl FloatHash for Vec4 {
+ fn hash_f32<H: Hasher>(&self, state: &mut H) {
+ FloatOrd(self.x).hash(state);
+ FloatOrd(self.y).hash(state);
+ FloatOrd(self.z).hash(state);
+ FloatOrd(self.w).hash(state);
+ }
+}
+
+/// A constant or random value evaluated on CPU.
+///
+/// This enum represents a value which is either constant, or randomly sampled
+/// according to a given probability distribution.
+///
+/// Not to be confused with [`graph::Value`]. This [`CpuValue`] is a legacy type
+/// that will be eventually replaced with a [`graph::Value`] once evaluation of
+/// the latter can be emulated on CPU, which is required for use
+/// with the [`SpawnerSettings`].
+///
+/// [`graph::Value`]: crate::graph::Value
+#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Reflect)]
+#[non_exhaustive]
+pub enum CpuValue<T: Copy + FromReflect> {
+ /// Single constant value.
+ Single(T),
+ /// Random value distributed uniformly between two inclusive bounds.
+ ///
+ /// The minimum bound must be less than or equal to the maximum one,
+ /// otherwise some methods like [`sample()`] will panic.
+ ///
+ /// [`sample()`]: crate::CpuValue::sample
+ Uniform((T, T)),
+}
+
+impl<T: Copy + FromReflect + Default> Default for CpuValue<T> {
+ fn default() -> Self {
+ Self::Single(T::default())
+ }
+}
+
+impl<T: Copy + FromReflect + SampleUniform> CpuValue<T> {
+ /// Sample the value.
+ /// - For [`CpuValue::Single`], always return the same single value.
+ /// - For [`CpuValue::Uniform`], use the given pseudo-random number
+ /// generator to generate a random sample.
+ pub fn sample(&self, rng: &mut Pcg32) -> T {
+ match self {
+ Self::Single(x) => *x,
+ Self::Uniform((a, b)) => Uniform::new_inclusive(*a, *b).unwrap().sample(rng),
+ }
+ }
+}
+
+impl<T: Copy + FromReflect + PartialOrd> CpuValue<T> {
+ /// Returns the range of allowable values in the form `[minimum, maximum]`.
+ /// For [`CpuValue::Single`], both values are the same.
+ pub fn range(&self) -> [T; 2] {
+ match self {
+ Self::Single(x) => [*x; 2],
+ Self::Uniform((a, b)) => {
+ if a <= b {
+ [*a, *b]
+ } else {
+ [*b, *a]
+ }
+ }
+ }
+ }
+}
+
+impl<T: Copy + FromReflect> From<T> for CpuValue<T> {
+ fn from(t: T) -> Self {
+ Self::Single(t)
+ }
+}
+
+impl<T: Copy + FromReflect> From<[T; 2]> for CpuValue<T> {
+ fn from(t: [T; 2]) -> Self {
+ Self::Uniform((t[0], t[1]))
+ }
+}
+
+impl<T: Copy + FromReflect> From<(T, T)> for CpuValue<T> {
+ fn from(t: (T, T)) -> Self {
+ Self::Uniform(t)
+ }
+}
+
+impl<T: Copy + FromReflect + FloatHash> Eq for CpuValue<T> {}
+
+impl<T: Copy + FromReflect + FloatHash> Hash for CpuValue<T> {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ match self {
+ CpuValue::Single(f) => {
+ 1_u8.hash(state);
+ f.hash_f32(state);
+ }
+ CpuValue::Uniform((a, b)) => {
+ 2_u8.hash(state);
+ a.hash_f32(state);
+ b.hash_f32(state);
+ }
+ }
+ }
+}
+
+/// Error type for [`SpawnerSettings::try_new()`].
+#[derive(Debug, Clone, Copy, Error)]
+pub enum SpawnerSettingsError {
+ #[error("Spawn period [{min}:{max}] is invalid")]
+ InvalidPeriod { min: f32, max: f32 },
+
+ #[error("Spawn period is infinite")]
+ InfinitePeriod,
+}
+
+/// Settings for an [`EffectSpawner`].
+///
+/// A [`SpawnerSettings`] represents the settings of an [`EffectSpawner`].
+///
+/// The spawning logic is based around the concept of _cycles_. A spawner
+/// defines a pattern of particle spawning as the repetition of a number of unit
+/// cycles. Each cycle is composed of a period of emission, followed by a period
+/// of rest (idling). Both periods can be of zero duration.
+///
+/// The settings are:
+///
+/// - `count` is the number of particles to spawn over a single cycle, during
+/// the emission period. It can evaluate to negative or zero random values, in
+/// which case no particle is spawned during the current cycle.
+/// - `spawn_duration` is the duration of the spawn part of a single cycle. If
+/// this is <= 0, then the particles spawn all at once exactly at the same
+/// instant at the beginning of the cycle.
+/// - `period` is the period of a cycle. If this is <= `spawn_duration`, then
+/// the spawner spawns a steady stream of particles. This is ignored if
+/// `cycle_count == 1`.
+/// - `cycle_count` is the number of cycles, that is the number of times this
+/// spawn-rest pattern occurs. Set this to `0` to repeat forever.
+///
+/// ```txt
+/// <----------- period ----------->
+/// <- spawn_duration ->
+/// |********************|-----------|
+/// spawn 'count' wait
+/// particles
+/// ```
+///
+/// Most settings are stored as a [`CpuValue`] to allow some randomizing. If
+/// using a random distribution, the value is resampled each cycle.
+///
+/// Note that the "burst" semantic here doesn't strictly mean a one-off
+/// emission, since that emission is spread over a number of simulation
+/// frames that total a duration of `spawn_duration`. If you want a strict
+/// single-frame burst, simply set the `spawn_duration` to zero; this is
+/// what [`once()`] does.
+///
+/// [`once()`]: Self::once
+#[derive(Debug, Clone, Copy, PartialEq, Reflect, Serialize, Deserialize)]
+#[reflect(Default)]
+pub struct SpawnerSettings {
+ /// Number of particles to spawn over [`spawn_duration`].
+ ///
+ /// [`spawn_duration`]: Self::spawn_duration
+ count: CpuValue<f32>,
+
+ /// Time over which to spawn [`count`], in seconds.
+ ///
+ /// [`count`]: Self::count
+ spawn_duration: CpuValue<f32>,
+
+ /// Time between bursts of the particle system, in seconds.
+ ///
+ /// If this is [`spawn_duration`] or less, the system spawns a steady stream
+ /// of particles.
+ ///
+ /// [`spawn_duration`]: Self::spawn_duration
+ period: CpuValue<f32>,
+
+ /// Number of cycles the spawner is active before completing.
+ ///
+ /// Each cycle lasts for `period`. A value of `0` means "infinite", that is
+ /// the spanwe emits particle forever as long as it's active.
+ cycle_count: u32,
+
+ /// Whether the [`EffectSpawner`] is active at startup.
+ ///
+ /// The value is used to initialize [`EffectSpawner::active`].
+ ///
+ /// [`EffectSpawner::active`]: crate::EffectSpawner::active
+ starts_active: bool,
+
+ /// Whether the [`EffectSpawner`] immediately starts emitting particles.
+ emit_on_start: bool,
+}
+
+impl Default for SpawnerSettings {
+ fn default() -> Self {
+ Self::once(1.0f32.into())
+ }
+}
+
+impl SpawnerSettings {
+ /// Create settings from individual values.
+ ///
+ /// This is the _raw_ constructor. In general you should prefer using one of
+ /// the utility constructors [`once()`], [`burst()`], or [`rate()`],
+ /// which will ensure the control parameters are set consistently relative
+ /// to each other.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `period` can produce a negative number (the sample range lower
+ /// bound is negative), unless the cycle count is exactly 1, in which case
+ /// `period` is ignored.
+ ///
+ /// Panics if `period` can only produce 0 (the sample range upper bound
+ /// is not strictly positive), unless the cycle count is exactly 1, in which
+ /// case `period` is ignored.
+ ///
+ /// Panics if any value is infinite.
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::SpawnerSettings;
+ /// // Spawn 32 particles over 3 seconds, then pause for 7 seconds (10 - 3),
+ /// // doing that 5 times in total.
+ /// let spawner = SpawnerSettings::new(32.0.into(), 3.0.into(), 10.0.into(), 5);
+ /// ```
+ ///
+ /// [`once()`]: Self::once
+ /// [`burst()`]: Self::burst
+ /// [`rate()`]: Self::rate
+ pub fn new(
+ count: CpuValue<f32>,
+ spawn_duration: CpuValue<f32>,
+ period: CpuValue<f32>,
+ cycle_count: u32,
+ ) -> Self {
+ match Self::try_new(count, spawn_duration, period, cycle_count) {
+ Ok(s) => s,
+ Err(err) => match err {
+ SpawnerSettingsError::InvalidPeriod { min, max } => {
+ if min < 0. {
+ panic!("`period` must not generate negative numbers (period.min was {min}, expected >= 0).");
+ } else {
+ panic!("`period` must be able to generate a positive number (period.max was {max}, expected > 0).");
+ }
+ }
+ SpawnerSettingsError::InfinitePeriod => panic!("`period` {period:?} has an infinite bound. If upgrading from a previous version, use `cycle_count = 1` instead for a single-cycle burst.",),
+ },
+ }
+ }
+
+ /// Try to create settings from individual values.
+ ///
+ /// Same as [`new()`], but fallible (returns an error) on invalid arugments
+ /// instead of panicking.
+ ///
+ /// [`new()`]: Self::new
+ pub fn try_new(
+ count: CpuValue<f32>,
+ spawn_duration: CpuValue<f32>,
+ period: CpuValue<f32>,
+ cycle_count: u32,
+ ) -> Result<Self, SpawnerSettingsError> {
+ let range = period.range();
+ if (cycle_count != 1) && (range[0] < 0. || range[1] <= 0.) {
+ return Err(SpawnerSettingsError::InvalidPeriod {
+ min: range[0],
+ max: range[1],
+ });
+ }
+ if !range[0].is_finite() || !range[1].is_finite() {
+ return Err(SpawnerSettingsError::InfinitePeriod);
+ }
+
+ Ok(Self {
+ count,
+ spawn_duration,
+ period,
+ cycle_count,
+ starts_active: true,
+ emit_on_start: true,
+ })
+ }
+
+ /// Set whether the [`EffectSpawner`] immediately starts to emit particle
+ /// when the [`ParticleEffect`] is spawned into the ECS world.
+ ///
+ /// If set to `false`, then [`EffectSpawner::has_completed()`] will return
+ /// `true` after spawning the component, and the spawner needs to be
+ /// [`EffectSpawner::reset()`] before it can spawn particles. This is
+ /// useful to spawn a particle effect instance immediately, but only start
+ /// emitting particles when an event occurs (collision, user input, any
+ /// other game logic...).
+ ///
+ /// Because a spawner repeating forever never completes, this has no effect
+ /// if [`is_forever()`] is `true`. To start/stop spawning with those
+ /// effects, use [`EffectSpawner::active`] instead.
+ ///
+ /// [`is_forever()`]: Self::is_forever
+ pub fn with_emit_on_start(mut self, emit_on_start: bool) -> Self {
+ self.emit_on_start = emit_on_start;
+ self
+ }
+
+ /// Set whether the [`EffectSpawner`] immediately starts to emit particle
+ /// when the [`ParticleEffect`] is spawned into the ECS world.
+ ///
+ /// See [with_emit_on_start()] for details.
+ ///
+ /// [with_emit_on_start()]: Self::with_emit_on_start
+ pub fn set_emit_on_start(&mut self, emit_on_start: bool) {
+ self.emit_on_start = emit_on_start;
+ }
+
+ /// Get whether the [`EffectSpawner`] immediately starts to emit particle
+ /// when the [`ParticleEffect`] is spawned into the ECS world.
+ ///
+ /// See [with_emit_on_start()] for details.
+ ///
+ /// [with_emit_on_start()]: Self::with_emit_on_start
+ pub fn emits_on_start(&self) -> bool {
+ self.emit_on_start
+ }
+
+ /// Create settings to spawn a burst of particles once.
+ ///
+ /// The burst of particles is spawned all at once in the same frame. After
+ /// that, the spawner idles, waiting to be manually reset via
+ /// [`EffectSpawner::reset()`].
+ ///
+ /// This is a convenience for:
+ ///
+ /// ```
+ /// # use bevy_hanabi::{SpawnerSettings, CpuValue};
+ /// # let count = CpuValue::Single(1.);
+ /// SpawnerSettings::new(count, 0.0.into(), 0.0.into(), 1);
+ /// ```
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::SpawnerSettings;
+ /// // Spawn 32 particles in a burst once immediately on creation.
+ /// let spawner = SpawnerSettings::once(32.0.into());
+ /// ```
+ pub fn once(count: CpuValue<f32>) -> Self {
+ Self::new(count, 0.0.into(), 0.0.into(), 1)
+ }
+
+ /// Get whether the spawner has a single cycle.
+ ///
+ /// This is true if the cycle count is exactly equal to 1.
+ pub fn is_once(&self) -> bool {
+ self.cycle_count == 1
+ }
+
+ /// Get whether the spawner has an infinite number of cycles.
+ ///
+ /// This is true if the cycle count is exactly equal to 0.
+ pub fn is_forever(&self) -> bool {
+ self.cycle_count == 0
+ }
+
+ /// Create settings to spawn a continuous stream of particles.
+ ///
+ /// The particle spawn `rate` is expressed in particles per second.
+ /// Fractional values are accumulated each frame.
+ ///
+ /// This is a convenience for:
+ ///
+ /// ```
+ /// # use bevy_hanabi::{SpawnerSettings, CpuValue};
+ /// # let rate = CpuValue::Single(1.);
+ /// SpawnerSettings::new(rate, 1.0.into(), 1.0.into(), 0);
+ /// ```
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::SpawnerSettings;
+ /// // Spawn 10 particles per second, indefinitely.
+ /// let spawner = SpawnerSettings::rate(10.0.into());
+ /// ```
+ pub fn rate(rate: CpuValue<f32>) -> Self {
+ Self::new(rate, 1.0.into(), 1.0.into(), 0)
+ }
+
+ /// Create settings to spawn particles in bursts.
+ ///
+ /// The settings define an infinite number of cycles where `count` particles
+ /// are spawned at the beginning of the cycle, then the spawner waits
+ /// `period` seconds, and repeats forever.
+ ///
+ /// This is a convenience for:
+ ///
+ /// ```
+ /// # use bevy_hanabi::{SpawnerSettings, CpuValue};
+ /// # let count = CpuValue::Single(1.);
+ /// # let period = CpuValue::Single(1.);
+ /// SpawnerSettings::new(count, 0.0.into(), period, 0);
+ /// ```
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use bevy_hanabi::SpawnerSettings;
+ /// // Spawn a burst of 5 particles every 3 seconds, indefinitely.
+ /// let spawner = SpawnerSettings::burst(5.0.into(), 3.0.into());
+ /// ```
+ pub fn burst(count: CpuValue<f32>, period: CpuValue<f32>) -> Self {
+ Self::new(count, 0.0.into(), period, 0)
+ }
+
+ /// Set the number of particles that are spawned each cycle.
+ pub fn with_count(mut self, count: CpuValue<f32>) -> Self {
+ self.count = count;
+ self
+ }
+
+ /// Set the number of particles that are spawned each cycle.
+ pub fn set_count(&mut self, count: CpuValue<f32>) {
+ self.count = count;
+ }
+
+ /// Get the number of particles that are spawned each cycle.
+ pub fn count(&self) -> CpuValue<f32> {
+ self.count
+ }
+
+ /// Set the duration, in seconds, of the spawn part each cycle.
+ pub fn with_spawn_duration(mut self, spawn_duration: CpuValue<f32>) -> Self {
+ self.spawn_duration = spawn_duration;
+ self
+ }
+
+ /// Set the duration, in seconds, of the spawn part each cycle.
+ pub fn set_spawn_duration(&mut self, spawn_duration: CpuValue<f32>) {
+ self.spawn_duration = spawn_duration;
+ }
+
+ /// Get the duration, in seconds, of the spawn part each cycle.
+ pub fn spawn_duration(&self) -> CpuValue<f32> {
+ self.spawn_duration
+ }
+
+ /// Set the duration of a single spawn cycle, in seconds.
+ ///
+ /// A spawn cycle includes the [`spawn_duration()`] value, and any extra
+ /// wait time (if larger than spawn time).
+ ///
+ /// # Panics
+ ///
+ /// Panics if the period is infinite.
+ ///
+ /// [`spawn_duration()`]: Self::spawn_duration
+ pub fn with_period(mut self, period: CpuValue<f32>) -> Self {
+ assert!(
+ period.range()[0].is_finite() && period.range()[1].is_finite(),
+ "`period` {:?} has an infinite bound. If upgrading from a previous version, use `cycle_count = 1` instead for a single-cycle burst.",
+ period
+ );
+ self.period = period;
+ self
+ }
+
+ /// Set the duration of a single spawn cycle, in seconds.
+ ///
+ /// A spawn cycle includes the [`spawn_duration()`] value, and any extra
+ /// wait time (if larger than spawn time).
+ ///
+ /// # Panics
+ ///
+ /// Panics if the period is infinite.
+ ///
+ /// [`spawn_duration()`]: Self::spawn_duration
+ pub fn set_period(&mut self, period: CpuValue<f32>) {
+ assert!(
+ period.range()[0].is_finite() && period.range()[1].is_finite(),
+ "`period` {:?} has an infinite bound. If upgrading from a previous version, use `cycle_count = 1` instead for a single-cycle burst.",
+ period
+ );
+ self.period = period;
+ }
+
+ /// Get the duration of a single spawn cycle, in seconds.
+ ///
+ /// A spawn cycle includes the [`spawn_duration()`] value, and any extra
+ /// wait time (if larger than spawn time).
+ ///
+ /// [`spawn_duration()`]: Self::spawn_duration
+ pub fn period(&self) -> CpuValue<f32> {
+ self.period
+ }
+
+ /// Set the number of cycles to spawn for.
+ ///
+ /// A spawn cycle includes the [`spawn_duration()`] value, and any extra
+ /// wait time (if larger than spawn time). It lasts for [`period()`].
+ ///
+ /// [`spawn_duration()`]: Self::spawn_duration
+ /// [`period()`]: Self::period
+ pub fn with_cycle_count(mut self, cycle_count: u32) -> Self {
+ self.cycle_count = cycle_count;
+ self
+ }
+
+ /// Set the number of cycles to spawn for.
+ ///
+ /// A spawn cycle includes the [`spawn_duration()`] value, and any extra
+ /// wait time (if larger than spawn time). It lasts for [`period()`].
+ ///
+ /// [`spawn_duration()`]: Self::spawn_duration
+ /// [`period()`]: Self::period
+ pub fn set_cycle_count(&mut self, cycle_count: u32) {
+ self.cycle_count = cycle_count;
+ }
+
+ /// Get the number of cycles to spawn for.
+ ///
+ /// A spawn cycle includes the [`spawn_duration()`] value, and any extra
+ /// wait time (if larger than spawn time). It lasts for [`period()`].
+ ///
+ /// [`spawn_duration()`]: Self::spawn_duration
+ /// [`period()`]: Self::period
+ pub fn cycle_count(&self) -> u32 {
+ self.cycle_count
+ }
+
+ /// Sets whether the spawner starts active when the effect is instantiated.
+ ///
+ /// This value will be transfered to the active state of the
+ /// [`EffectSpawner`] once it's instantiated. Inactive spawners do not spawn
+ /// any particle.
+ pub fn with_starts_active(mut self, starts_active: bool) -> Self {
+ self.starts_active = starts_active;
+ self
+ }
+
+ /// Set whether the spawner starts active when the effect is instantiated.
+ ///
+ /// This value will be transfered to the active state of the
+ /// [`EffectSpawner`] once it's instantiated. Inactive spawners do not spawn
+ /// any particle.
+ pub fn set_starts_active(&mut self, starts_active: bool) {
+ self.starts_active = starts_active;
+ }
+
+ /// Get whether the spawner starts active when the effect is instantiated.
+ ///
+ /// This value will be transfered to the active state of the
+ /// [`EffectSpawner`] once it's instantiated. Inactive spawners do not spawn
+ /// any particle.
+ pub fn starts_active(&self) -> bool {
+ self.starts_active
+ }
+}
+
+/// Runtime state machine for CPU particle spawning.
+///
+/// The spawner defines how new particles are emitted and when. Each time the
+/// spawner ticks, it calculates a number of particles to emit for this frame,
+/// based on its [`SpawnerSettings`]. This spawn count is passed to the GPU for
+/// the init compute pass to actually allocate the new particles and initialize
+/// them. The number of particles to spawn is stored as a floating-point number,
+/// and any remainder accumulates for the next tick.
+///
+/// Spawners are used to control from CPU when particles are spawned. To use GPU
+/// spawn events instead, and spawn particles based on events occurring on
+/// existing particles in other effects, see [`EffectParent`]. Those two
+/// mechanisms (CPU and GPU spawner) are mutually exclusive.
+///
+/// Once per frame the [`tick_spawners()`] system will add the [`EffectSpawner`]
+/// component if it's missing, cloning the [`SpawnerSettings`] from the source
+/// [`EffectAsset`] to initialize it. After that, it ticks the
+/// [`SpawnerSettings`] stored in the component. The resulting number of
+/// particles to spawn for the frame is then stored into
+/// [`EffectSpawner::spawn_count`]. You can override that value to manually
+/// control each frame how many particles are spawned, instead of using the
+/// logic of [`SpawnerSettings`].
+///
+/// [`EffectParent`]: crate::EffectParent
+#[derive(Debug, Default, Clone, Copy, PartialEq, Component, Reflect)]
+#[reflect(Component)]
+pub struct EffectSpawner {
+ /// The spawner settings extracted from the [`EffectAsset`], or directly
+ /// overriden by the user.
+ pub settings: SpawnerSettings,
+
+ /// Accumulated time for the current (partial) cycle, in seconds.
+ cycle_time: f32,
+
+ /// Number of cycles already completed.
+ completed_cycle_count: u32,
+
+ /// Sampled value of `spawn_duration` until `period` is reached. This is the
+ /// duration of the "active" period during which we spawn particles, as
+ /// opposed to the "wait" period during which we do nothing until the next
+ /// spawn cycle.
+ sampled_spawn_duration: f32,
+
+ /// Sampled value of the time period, in seconds, until the next spawn
+ /// cycle.
+ sampled_period: f32,
+
+ /// Sampled value of the number of particles to spawn per `spawn_duration`.
+ sampled_count: f32,
+
+ /// Number of particles to spawn this frame.
+ ///
+ /// This value is normally updated by calling [`tick()`], which
+ /// automatically happens once per frame when the [`tick_spawners()`]
+ /// system runs in the [`PostUpdate`] schedule.
+ ///
+ /// You can manually assign this value to override the one calculated by
+ /// [`tick()`]. Note in this case that you need to override the value after
+ /// the automated one was calculated, by ordering your system
+ /// after [`tick_spawners()`] or [`EffectSystems::TickSpawners`].
+ ///
+ /// [`tick()`]: crate::EffectSpawner::tick
+ /// [`EffectSystems::TickSpawners`]: crate::EffectSystems::TickSpawners
+ pub spawn_count: u32,
+
+ /// Fractional remainder of particle count to spawn.
+ ///
+ /// This is accumulated each tick, and the integral part is added to
+ /// `spawn_count`. The reminder gets saved for next frame.
+ spawn_remainder: f32,
+
+ /// Whether the spawner is active. Defaults to
+ /// [`SpawnerSettings::starts_active()`]. An inactive spawner
+ /// doesn't tick (no particle spawned, no internal state updated).
+ pub active: bool,
+}
+
+impl EffectSpawner {
+ /// Create a new spawner.
+ pub fn new(settings: &SpawnerSettings) -> Self {
+ Self {
+ settings: *settings,
+ cycle_time: 0.,
+ completed_cycle_count: if settings.emit_on_start || settings.is_forever() {
+ // Infinitely repeating effects always start at cycle #0.
+ 0
+ } else {
+ // Start at last cycle. This means has_completed() is true.
+ settings.cycle_count()
+ },
+ sampled_spawn_duration: 0.,
+ sampled_period: 0.,
+ sampled_count: 0.,
+ spawn_count: 0,
+ spawn_remainder: 0.,
+ active: settings.starts_active(),
+ }
+ }
+
+ /// Set whether the spawner is active.
+ ///
+ /// Inactive spawners do not tick, and therefore do not spawn any particle.
+ /// Their internal state do not update.
+ pub fn with_active(mut self, active: bool) -> Self {
+ self.active = active;
+ self
+ }
+
+ /// Get the time relative to the beginning of the current cycle.
+ #[inline]
+ pub fn cycle_time(&self) -> f32 {
+ self.cycle_time
+ }
+
+ /// Get the spawn duration for the current cycle.
+ ///
+ /// This value can change every cycle if [`SpawnerSettings::spawn_duration`]
+ /// is a randomly distributed value.
+ #[inline]
+ pub fn cycle_spawn_duration(&self) -> f32 {
+ self.sampled_spawn_duration
+ }
+
+ /// Get the period of the current cycle.
+ ///
+ /// This value can change every cycle if [`SpawnerSettings::period`] is a
+ /// randomly distributed value. If the effect spawns only once, and
+ /// therefore its cycle period is ignored, this returns `0`.
+ #[inline]
+ pub fn cycle_period(&self) -> f32 {
+ if self.settings.is_once() {
+ 0.
+ } else {
+ self.sampled_period
+ }
+ }
+
+ /// Get the progress ratio in 0..1 of the current cycle.
+ ///
+ /// This is the ratio of the [`cycle_time()`] over [`cycle_period()`]. If
+ /// the effect spawns only once, and therefore its cycle period is
+ /// ignored, this returns `0`.
+ ///
+ /// [`cycle_time()`]: Self::cycle_time
+ /// [`cycle_period()`]: Self::cycle_period
+ #[inline]
+ pub fn cycle_ratio(&self) -> f32 {
+ if self.settings.is_once() {
+ 0.
+ } else {
+ self.cycle_time / self.sampled_period
+ }
+ }
+
+ /// Get the number of particles to spawn during the current cycle
+ ///
+ /// This value can change every cycle if [`SpawnerSettings::count`] is a
+ /// randomly distributed value.
+ #[inline]
+ pub fn cycle_spawn_count(&self) -> f32 {
+ self.sampled_count
+ }
+
+ /// Get the number of completed cycles since last [`reset()`].
+ ///
+ /// The value loops back if the pattern repeats forever
+ /// ([`SpawnerSettings::is_forever()`] is `true`).
+ ///
+ /// [`reset()`]: Self::reset
+ #[inline]
+ pub fn completed_cycle_count(&self) -> u32 {
+ self.completed_cycle_count
+ }
+
+ /// Get whether the spawner has completed.
+ ///
+ /// A spawner has completed if it already ticked through its maximum number
+ /// of cycles. It can be reset back to its original state with [`reset()`].
+ /// A spawner repeating forever never completes.
+ ///
+ /// [`reset()`]: Self::reset
+ #[inline]
+ pub fn has_completed(&self) -> bool {
+ !self.settings.is_forever() && (self.completed_cycle_count >= self.settings.cycle_count())
+ }
+
+ /// Reset the spawner state.
+ ///
+ /// This resets the internal spawner time and cycle count to zero.
+ ///
+ /// Use this, for example, to immediately spawn some particles in a spawner
+ /// constructed with [`SpawnerSettings::once`].
+ ///
+ /// [`SpawnerSettings::once`]: crate::SpawnerSettings::once
+ pub fn reset(&mut self) {
+ self.cycle_time = 0.;
+ self.completed_cycle_count = 0;
+ self.sampled_spawn_duration = 0.;
+ self.sampled_period = 0.;
+ self.sampled_count = 0.;
+ self.spawn_count = 0;
+ self.spawn_remainder = 0.;
+ }
+
+ /// Tick the spawner to calculate the number of particles to spawn this
+ /// frame.
+ ///
+ /// The frame delta time `dt` is added to the current spawner time, before
+ /// the spawner calculates the number of particles to spawn.
+ ///
+ /// This method is called automatically by [`tick_spawners()`] during the
+ /// [`PostUpdate`], so you normally don't have to call it yourself
+ /// manually.
+ ///
+ /// # Returns
+ ///
+ /// The integral number of particles to spawn this frame. Any fractional
+ /// remainder is saved for the next call.
+ pub fn tick(&mut self, mut dt: f32, rng: &mut Pcg32) -> u32 {
+ // If inactive, or if the finite number of cycles has been completed, then we're
+ // done.
+ if !self.active
+ || (!self.settings.is_forever()
+ && (self.completed_cycle_count >= self.settings.cycle_count()))
+ {
+ self.spawn_count = 0;
+ return 0;
+ }
+
+ // Use a loop in case the timestep dt spans multiple cycles
+ loop {
+ // Check if this is a new cycle which needs resampling
+ if self.sampled_period == 0.0 {
+ if self.settings.is_once() {
+ self.sampled_spawn_duration = self.settings.spawn_duration.sample(rng);
+ // Period is unchecked, should be ignored (could sample to <= 0). Use the spawn
+ // duration, but ensure we have something > 0 as a marker that we've resampled.
+ self.sampled_period = self.sampled_spawn_duration.max(1e-12);
+ } else {
+ self.sampled_period = self.settings.period.sample(rng);
+ assert!(self.sampled_period > 0.);
+ self.sampled_spawn_duration = self
+ .settings
+ .spawn_duration
+ .sample(rng)
+ .clamp(0., self.sampled_period);
+ }
+ self.sampled_spawn_duration = self.settings.spawn_duration.sample(rng);
+ self.sampled_count = self.settings.count.sample(rng).max(0.);
+ }
+
+ let new_time = self.cycle_time + dt;
+
+ // If inside the spawn period, accumulate some particle spawn count
+ if self.cycle_time <= self.sampled_spawn_duration {
+ // If the spawn time is very small, close to zero, spawn all particles
+ // immediately in one burst over a single frame.
+ self.spawn_remainder += if self.sampled_spawn_duration < 1e-5f32.max(dt / 100.0) {
+ self.sampled_count
+ } else {
+ // Spawn an amount of particles equal to the fraction of time the current frame
+ // spans compared to the total burst duration.
+ let ratio = ((new_time.min(self.sampled_spawn_duration) - self.cycle_time)
+ / self.sampled_spawn_duration)
+ .clamp(0., 1.);
+ self.sampled_count * ratio
+ };
+ }
+
+ // Increment current time
+ self.cycle_time = new_time;
+
+ // Check for cycle completion
+ if self.cycle_time >= self.sampled_period {
+ dt = self.cycle_time - self.sampled_period;
+ self.cycle_time = 0.0;
+ self.completed_cycle_count += 1;
+
+ // Mark as "need resampling"
+ self.sampled_period = 0.0;
+
+ // If this was the last cycle, we're done
+ if !self.settings.is_forever()
+ && (self.completed_cycle_count >= self.settings.cycle_count())
+ {
+ // Don't deactivate quite yet, otherwise we'll miss the spawns for this frame
+ break;
+ }
+ } else {
+ // We're done for this frame
+ break;
+ }
+ }
+
+ // Extract integral number of particles to spawn this frame, keep remainder for
+ // next one
+ let count = self.spawn_remainder.floor();
+ self.spawn_remainder -= count;
+ self.spawn_count = count as u32;
+
+ self.spawn_count
+ }
+}
+
+/// Tick all the [`EffectSpawner`] components.
+///
+/// This system runs in the [`PostUpdate`] stage, after the visibility system
+/// has updated the [`InheritedVisibility`] of each effect instance (see
+/// [`VisibilitySystems::VisibilityPropagate`]). Hidden instances are not
+/// updated, unless the [`EffectAsset::simulation_condition`]
+/// is set to [`SimulationCondition::Always`]. If no [`InheritedVisibility`] is
+/// present, the effect is assumed to be visible.
+///
+/// Note that by that point the [`ViewVisibility`] is not yet calculated, and it
+/// may happen that spawners are ticked but no effect is visible in any view
+/// even though some are "visible" (active) in the [`World`]. The actual
+/// per-view culling of invisible (not in view) effects is performed later on
+/// the render world.
+///
+/// Once the system determined that the effect instance needs to be simulated
+/// this frame, it ticks the effect's spawner by calling
+/// [`EffectSpawner::tick()`], adding a new [`EffectSpawner`] component if it
+/// doesn't already exist on the same entity as the [`ParticleEffect`].
+///
+/// [`VisibilitySystems::VisibilityPropagate`]: bevy::camera::visibility::VisibilitySystems::VisibilityPropagate
+/// [`EffectAsset::simulation_condition`]: crate::EffectAsset::simulation_condition
+pub fn tick_spawners(
+ mut commands: Commands,
+ time: Res<Time<EffectSimulation>>,
+ effects: Res<Assets<EffectAsset>>,
+ mut rng: ResMut<Random>,
+ mut query: Query<(
+ Entity,
+ &ParticleEffect,
+ &CompiledParticleEffect,
+ &InheritedVisibility,
+ Option<&mut EffectSpawner>,
+ )>,
+) {
+ #[cfg(feature = "trace")]
+ let _span = bevy::log::info_span!("tick_spawners").entered();
+ trace!("tick_spawners()");
+
+ let dt = time.delta_secs();
+
+ for (entity, effect, compiled_effect, inherited_visibility, maybe_spawner) in query.iter_mut() {
+ // Skip effect which are not ready; this prevents ticking the spawner for an
+ // effect not ready to consume those spawn commands.
+ let mut can_tick = if compiled_effect.is_ready() {
+ true
+ } else {
+ trace!("[Effect {entity:?}] Not ready; skipped spawner tick.");
+ false
+ };
+
+ let Some(asset) = effects.get(&effect.handle) else {
+ trace!(
+ "Effect asset with handle {:?} is not available; skipped initializers tick.",
+ effect.handle
+ );
+ continue;
+ };
+
+ if asset.simulation_condition == SimulationCondition::WhenVisible
+ && !inherited_visibility.get()
+ {
+ trace!(
+ "Effect asset with handle {:?} is not visible, and simulates only WhenVisible; skipped initializers tick.",
+ effect.handle
+ );
+ can_tick = false;
+ }
+
+ if let Some(mut effect_spawner) = maybe_spawner {
+ if can_tick {
+ effect_spawner.tick(dt, &mut rng.0);
+ }
+ } else {
+ let mut effect_spawner = EffectSpawner::new(&asset.spawner);
+ if can_tick {
+ effect_spawner.tick(dt, &mut rng.0);
+ }
+ commands.entity(entity).insert(effect_spawner);
+ }
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use std::time::Duration;
+
+ use bevy::{
+ asset::{
+ io::{
+ memory::{Dir, MemoryAssetReader},
+ AssetSourceBuilder, AssetSourceBuilders, AssetSourceId,
+ },
+ AssetServerMode, UnapprovedPathMode,
+ },
+ camera::visibility::{VisibilityPlugin, VisibilitySystems},
+ tasks::{IoTaskPool, TaskPoolBuilder},
+ };
+
+ use super::*;
+ use crate::Module;
+
+ #[test]
+ fn test_range_single() {
+ let value = CpuValue::Single(1.0);
+ assert_eq!(value.range(), [1.0, 1.0]);
+ }
+
+ #[test]
+ fn test_range_uniform() {
+ let value = CpuValue::Uniform((1.0, 3.0));
+ assert_eq!(value.range(), [1.0, 3.0]);
+ }
+
+ #[test]
+ fn test_range_uniform_reverse() {
+ let value = CpuValue::Uniform((3.0, 1.0));
+ assert_eq!(value.range(), [1.0, 3.0]);
+ }
+
+ #[test]
+ fn test_new() {
+ let rng = &mut new_rng();
+ // 3 particles over 3 seconds, pause 7 seconds (total 10 seconds period). 2
+ // cycles.
+ let spawner = SpawnerSettings::new(3.0.into(), 3.0.into(), 10.0.into(), 2);
+ let mut spawner = EffectSpawner::new(&spawner);
+ let count = spawner.tick(2., rng); // t = 2s
+ assert_eq!(count, 2);
+ assert!(spawner.active);
+ assert_eq!(spawner.cycle_time(), 2.);
+ assert_eq!(spawner.cycle_spawn_duration(), 3.);
+ assert_eq!(spawner.cycle_period(), 10.);
+ assert_eq!(spawner.cycle_ratio(), 0.2); // 2s / 10s
+ assert_eq!(spawner.cycle_spawn_count(), 3.);
+ assert_eq!(spawner.completed_cycle_count(), 0);
+ let count = spawner.tick(5., rng); // t = 7s
+ assert_eq!(count, 1);
+ assert!(spawner.active);
+ assert_eq!(spawner.cycle_time(), 7.);
+ assert_eq!(spawner.cycle_spawn_duration(), 3.);
+ assert_eq!(spawner.cycle_period(), 10.);
+ assert_eq!(spawner.cycle_ratio(), 0.7); // 7s / 10s
+ assert_eq!(spawner.cycle_spawn_count(), 3.);
+ assert_eq!(spawner.completed_cycle_count(), 0);
+ let count = spawner.tick(8., rng); // t = 15s
+ assert_eq!(count, 3);
+ assert!(spawner.active);
+ assert_eq!(spawner.cycle_time(), 5.); // 15. mod 10.
+ assert_eq!(spawner.cycle_spawn_duration(), 3.);
+ assert_eq!(spawner.cycle_period(), 10.);
+ assert_eq!(spawner.cycle_ratio(), 0.5); // 5s / 10s
+ assert_eq!(spawner.cycle_spawn_count(), 3.);
+ assert_eq!(spawner.completed_cycle_count(), 1);
+ let count = spawner.tick(10., rng); // t = 25s
+ assert_eq!(count, 0);
+ assert!(spawner.active);
+ assert_eq!(spawner.completed_cycle_count(), 2);
+ let count = spawner.tick(0.1, rng); // t = 25.1s
+ assert_eq!(count, 0);
+ assert!(spawner.active);
+ assert_eq!(spawner.completed_cycle_count(), 2);
+ }
+
+ #[test]
+ #[should_panic]
+ fn test_new_panic_negative_period() {
+ let _ = SpawnerSettings::new(3.0.into(), 1.0.into(), CpuValue::Uniform((-1., 1.)), 0);
+ }
+
+ #[test]
+ #[should_panic]
+ fn test_new_panic_zero_period() {
+ let _ = SpawnerSettings::new(3.0.into(), 1.0.into(), CpuValue::Uniform((0., 0.)), 0);
+ }
+
+ #[test]
+ #[should_panic]
+ fn test_new_panic_infinite_period() {
+ let _ = SpawnerSettings::new(
+ 3.0.into(),
+ 1.0.into(),
+ CpuValue::Uniform((0., f32::INFINITY)),
+ 0,
+ );
+ }
+
+ #[test]
+ fn test_try_new_negative_period() {
+ assert!(matches!(
+ SpawnerSettings::try_new(3.0.into(), 1.0.into(), CpuValue::Uniform((-1., 1.)), 0),
+ Err(SpawnerSettingsError::InvalidPeriod { min: -1., max: 1. })
+ ));
+ }
+
+ #[test]
+ fn test_try_new_zero_period() {
+ assert!(matches!(
+ SpawnerSettings::try_new(3.0.into(), 1.0.into(), CpuValue::Uniform((0., 0.)), 0),
+ Err(SpawnerSettingsError::InvalidPeriod { min: 0., max: 0. })
+ ));
+ }
+
+ #[test]
+ fn test_try_new_infitie_period() {
+ assert!(matches!(
+ SpawnerSettings::try_new(
+ 3.0.into(),
+ 1.0.into(),
+ CpuValue::Uniform((0., f32::INFINITY)),
+ 0
+ ),
+ Err(SpawnerSettingsError::InfinitePeriod)
+ ));
+ assert!(matches!(
+ SpawnerSettings::try_new(
+ 3.0.into(),
+ 1.0.into(),
+ CpuValue::Uniform((f32::INFINITY, f32::INFINITY)),
+ 0
+ ),
+ Err(SpawnerSettingsError::InfinitePeriod)
+ ));
+ }
+
+ #[test]
+ fn test_once() {
+ let rng = &mut new_rng();
+ let spawner = SpawnerSettings::once(5.0.into());
+ assert!(spawner.is_once());
+ let mut spawner = EffectSpawner::new(&spawner);
+ assert!(spawner.active);
+ let count = spawner.tick(0.001, rng);
+ assert_eq!(count, 5);
+ let count = spawner.tick(100.0, rng);
+ assert_eq!(count, 0);
+ }
+
+ #[test]
+ fn test_once_reset() {
+ let rng = &mut new_rng();
+ let spawner = SpawnerSettings::once(5.0.into());
+ assert!(spawner.is_once());
+ assert!(spawner.starts_active());
+ let mut spawner = EffectSpawner::new(&spawner);
+ spawner.tick(1.0, rng);
+ spawner.reset();
+ let count = spawner.tick(1.0, rng);
+ assert_eq!(count, 5);
+ }
+
+ #[test]
+ fn test_once_start_inactive() {
+ let rng = &mut new_rng();
+
+ let spawner = SpawnerSettings::once(5.0.into()).with_starts_active(false);
+ assert!(spawner.is_once());
+ assert!(!spawner.starts_active());
+ let mut spawner = EffectSpawner::new(&spawner);
+ assert!(!spawner.has_completed());
+
+ // Inactive; no-op
+ let count = spawner.tick(1.0, rng);
+ assert_eq!(count, 0);
+ assert!(!spawner.has_completed());
+
+ spawner.active = true;
+
+ // Active; spawns
+ let count = spawner.tick(1.0, rng);
+ assert_eq!(count, 5);
+ assert!(spawner.active);
+ assert!(spawner.has_completed()); // once(), so completes on first tick()
+
+ // Completed; no-op
+ let count = spawner.tick(1.0, rng);
+ assert_eq!(count, 0);
+ assert!(spawner.active);
+ assert!(spawner.has_completed());
+
+ // Reset internal state, still active
+ spawner.reset();
+ assert!(spawner.active);
+ assert!(!spawner.has_completed());
+
+ let count = spawner.tick(1.0, rng);
+ assert_eq!(count, 5);
+ assert!(spawner.active);
+ assert!(spawner.has_completed());
+ }
+
+ #[test]
+ fn test_rate() {
+ let rng = &mut new_rng();
+ let spawner = SpawnerSettings::rate(5.0.into());
+ assert!(!spawner.is_once());
+ assert!(spawner.is_forever());
+ let mut spawner = EffectSpawner::new(&spawner);
+ // Slightly over 1.0 to avoid edge case
+ let count = spawner.tick(1.01, rng);
+ assert_eq!(count, 5);
+ let count = spawner.tick(0.4, rng);
+ assert_eq!(count, 2);
+ }
+
+ #[test]
+ fn test_rate_active() {
+ let rng = &mut new_rng();
+ let spawner = SpawnerSettings::rate(5.0.into());
+ assert!(!spawner.is_once());
+ let mut spawner = EffectSpawner::new(&spawner);
+ spawner.tick(1.01, rng);
+ spawner.active = false;
+ assert!(!spawner.active);
+ let count = spawner.tick(0.4, rng);
+ assert_eq!(count, 0);
+ spawner.active = true;
+ assert!(spawner.active);
+ let count = spawner.tick(0.4, rng);
+ assert_eq!(count, 2);
+ }
+
+ #[test]
+ fn test_rate_accumulate() {
+ let rng = &mut new_rng();
+ let spawner = SpawnerSettings::rate(5.0.into());
+ assert!(!spawner.is_once());
+ let mut spawner = EffectSpawner::new(&spawner);
+ // 13 ticks instead of 12 to avoid edge case
+ let count = (0..13).map(|_| spawner.tick(1.0 / 60.0, rng)).sum::<u32>();
+ assert_eq!(count, 1);
+ }
+
+ #[test]
+ fn test_burst() {
+ let rng = &mut new_rng();
+ let spawner = SpawnerSettings::burst(5.0.into(), 2.0.into());
+ assert!(!spawner.is_once());
+ assert!(spawner.is_forever());
+ let mut spawner = EffectSpawner::new(&spawner);
+ let count = spawner.tick(1.0, rng);
+ assert_eq!(count, 5);
+ let count = spawner.tick(4.0, rng);
+ assert_eq!(count, 10);
+ let count = spawner.tick(0.1, rng);
+ assert_eq!(count, 0);
+ }
+
+ #[test]
+ fn test_with_active() {
+ let rng = &mut new_rng();
+ let spawner = SpawnerSettings::rate(5.0.into()).with_starts_active(false);
+ let mut spawner = EffectSpawner::new(&spawner);
+ assert!(!spawner.active);
+ let count = spawner.tick(1., rng);
+ assert_eq!(count, 0);
+ spawner.active = false; // no-op
+ let count = spawner.tick(1., rng);
+ assert_eq!(count, 0);
+ spawner.active = true;
+ assert!(spawner.active);
+ let count = spawner.tick(1., rng);
+ assert_eq!(count, 5);
+ }
+
+ fn make_test_app() -> App {
+ IoTaskPool::get_or_init(|| {
+ TaskPoolBuilder::default()
+ .num_threads(1)
+ .thread_name("Hanabi test IO Task Pool".to_string())
+ .build()
+ });
+
+ let mut app = App::new();
+
+ let watch_for_changes = false;
+ let mut builders = app
+ .world_mut()
+ .get_resource_or_insert_with::<AssetSourceBuilders>(Default::default);
+ let dir = Dir::default();
+ let dummy_builder =
+ AssetSourceBuilder::new(move || Box::new(MemoryAssetReader { root: dir.clone() }));
+ builders.insert(AssetSourceId::Default, dummy_builder);
+ let sources = builders.build_sources(watch_for_changes, false);
+ let asset_server = AssetServer::new(
+ sources.into(),
+ AssetServerMode::Unprocessed,
+ watch_for_changes,
+ UnapprovedPathMode::Forbid,
+ );
+
+ app.insert_resource(asset_server);
+ // app.add_plugins(DefaultPlugins);
+ app.init_asset::<Mesh>();
+ app.init_asset::<bevy::mesh::skinning::SkinnedMeshInverseBindposes>();
+ app.add_plugins(VisibilityPlugin);
+ app.init_resource::<Time<EffectSimulation>>();
+ app.insert_resource(Random(new_rng()));
+ app.init_asset::<EffectAsset>();
+ app.add_systems(
+ PostUpdate,
+ tick_spawners.after(VisibilitySystems::CheckVisibility),
+ );
+
+ app
+ }
+
+ /// Test case for `tick_spawners()`.
+ struct TestCase {
+ /// Initial entity visibility on spawn. If `None`, do not add a
+ /// [`Visibility`] component.
+ visibility: Option<Visibility>,
+
+ /// Spawner settings assigned to the `EffectAsset`.
+ asset_spawner: SpawnerSettings,
+ }
+
+ impl TestCase {
+ fn new(visibility: Option<Visibility>, asset_spawner: SpawnerSettings) -> Self {
+ Self {
+ visibility,
+ asset_spawner,
+ }
+ }
+ }
+
+ #[test]
+ fn test_tick_spawners() {
+ let asset_spawner = SpawnerSettings::once(32.0.into());
+
+ for test_case in &[
+ TestCase::new(None, asset_spawner),
+ TestCase::new(Some(Visibility::Hidden), asset_spawner),
+ TestCase::new(Some(Visibility::Visible), asset_spawner),
+ ] {
+ let mut app = make_test_app();
+
+ let (effect_entity, handle) = {
+ let world = app.world_mut();
+
+ // Add effect asset
+ let mut assets = world.resource_mut::<Assets<EffectAsset>>();
+ let mut asset = EffectAsset::new(64, test_case.asset_spawner, Module::default());
+ asset.simulation_condition = if test_case.visibility.is_some() {
+ SimulationCondition::WhenVisible
+ } else {
+ SimulationCondition::Always
+ };
+ let handle = assets.add(asset);
+
+ // Spawn particle effect
+ let entity = if let Some(visibility) = test_case.visibility {
+ world
+ .spawn((
+ visibility,
+ InheritedVisibility::default(),
+ ParticleEffect {
+ handle: handle.clone(),
+ ..default()
+ },
+ // Force-ready the effect as those tests don't initialize the render
+ // world (headless), so the effect would never get ready otherwise.
+ CompiledParticleEffect::default().with_ready_for_tests(),
+ ))
+ .id()
+ } else {
+ world
+ .spawn((
+ ParticleEffect {
+ handle: handle.clone(),
+ ..default()
+ },
+ // Force-ready the effect as those tests don't initialize the render
+ // world (headless), so the effect would never get ready otherwise.
+ CompiledParticleEffect::default().with_ready_for_tests(),
+ ))
+ .id()
+ };
+
+ // Spawn a camera, otherwise ComputedVisibility stays at HIDDEN
+ world.spawn(Camera3d::default());
+
+ (entity, handle)
+ };
+
+ // Tick once
+ let _cur_time = {
+ // Make sure to increment the current time so that the spawners spawn something.
+ // Note that `Time` has this weird behavior where the common quantities like
+ // `Time::delta_secs()` only update after the *second* update. So we tick the
+ // `Time` twice here to enforce this.
+ let mut time = app.world_mut().resource_mut::<Time<EffectSimulation>>();
+ time.advance_by(Duration::from_millis(16));
+ time.elapsed()
+ };
+ app.update();
+
+ let world = app.world_mut();
+
+ // Check the state of the components after `tick_spawners()` ran
+ if let Some(test_visibility) = test_case.visibility {
+ // Simulated-when-visible effect (SimulationCondition::WhenVisible)
+
+ let (entity, visibility, inherited_visibility, particle_effect, effect_spawner) =
+ world
+ .query::<(
+ Entity,
+ &Visibility,
+ &InheritedVisibility,
+ &ParticleEffect,
+ Option<&EffectSpawner>,
+ )>()
+ .iter(world)
+ .next()
+ .unwrap();
+ assert_eq!(entity, effect_entity);
+ assert_eq!(visibility, test_visibility);
+ assert_eq!(
+ inherited_visibility.get(),
+ test_visibility == Visibility::Visible
+ );
+ assert_eq!(particle_effect.handle, handle);
+
+ // The EffectSpawner component is always spawned, even if not visible.
+ assert!(effect_spawner.is_some());
+ let effect_spawner = effect_spawner.unwrap();
+ let actual_spawner = effect_spawner.settings;
+ assert_eq!(actual_spawner, test_case.asset_spawner);
+ assert!(effect_spawner.active);
+ assert_eq!(effect_spawner.spawn_remainder, 0.);
+ assert_eq!(effect_spawner.cycle_time, 0.);
+
+ if inherited_visibility.get() {
+ // Check the spawner ticked
+ assert_eq!(effect_spawner.completed_cycle_count, 1);
+ assert_eq!(effect_spawner.spawn_count, 32);
+ } else {
+ // Didn't tick
+ assert_eq!(effect_spawner.completed_cycle_count, 0);
+ assert_eq!(effect_spawner.spawn_count, 0);
+ }
+ } else {
+ // Always-simulated effect (SimulationCondition::Always)
+
+ let (entity, particle_effect, effect_spawners) = world
+ .query::<(Entity, &ParticleEffect, Option<&EffectSpawner>)>()
+ .iter(world)
+ .next()
+ .unwrap();
+ assert_eq!(entity, effect_entity);
+ assert_eq!(particle_effect.handle, handle);
+
+ assert!(effect_spawners.is_some());
+ let effect_spawner = effect_spawners.unwrap();
+ let actual_spawner = effect_spawner.settings;
+
+ // Check the spawner ticked
+ assert!(effect_spawner.active); // will get deactivated next tick()
+ assert_eq!(effect_spawner.spawn_remainder, 0.);
+ assert_eq!(effect_spawner.cycle_time, 0.);
+ assert_eq!(effect_spawner.completed_cycle_count, 1);
+ assert_eq!(effect_spawner.spawn_count, 32);
+
+ assert_eq!(actual_spawner, test_case.asset_spawner);
+ }
+ }
+ }
+}
diff --git a/vendor/bevy_hanabi/src/test_utils.rs b/vendor/bevy_hanabi/src/test_utils.rs
new file mode 100644
index 00000000..eaa4787c
--- /dev/null
+++ b/vendor/bevy_hanabi/src/test_utils.rs
@@ -0,0 +1,228 @@
+use std::ops::Sub;
+
+use bevy::prelude::{Quat, Vec2, Vec3, Vec4};
+#[cfg(feature = "gpu_tests")]
+use bevy::render::renderer::{RenderDevice, RenderQueue};
+
+/// Utility trait to compare floating-point values with a tolerance.
+pub(crate) trait AbsDiffEq {
+ /// Calculate the absolute value of the difference between two
+ /// floating-point quantities. For non-scalar quantities, the maximum
+ /// absolute difference for all components is returned.
+ fn abs_diff(a: &Self, b: &Self) -> f32;
+
+ /// Check if two floating-point quantities are approximately equal within a
+ /// given tolerance. Non-scalar values are checked component-wise.
+ fn abs_diff_eq(a: &Self, b: &Self, tol: f32) -> bool;
+}
+
+impl AbsDiffEq for f32 {
+ fn abs_diff(a: &f32, b: &f32) -> f32 {
+ (a - b).abs()
+ }
+
+ fn abs_diff_eq(a: &f32, b: &f32, tol: f32) -> bool {
+ (a - b).abs() < tol
+ }
+}
+
+impl AbsDiffEq for f64 {
+ fn abs_diff(a: &f64, b: &f64) -> f32 {
+ (a - b).abs() as f32
+ }
+
+ fn abs_diff_eq(a: &f64, b: &f64, tol: f32) -> bool {
+ (a - b).abs() < tol as f64
+ }
+}
+
+impl AbsDiffEq for Vec2 {
+ fn abs_diff(a: &Vec2, b: &Vec2) -> f32 {
+ a.sub(*b).abs().max_element()
+ }
+
+ fn abs_diff_eq(a: &Vec2, b: &Vec2, tol: f32) -> bool {
+ a.abs_diff_eq(*b, tol)
+ }
+}
+
+impl AbsDiffEq for Vec3 {
+ fn abs_diff(a: &Vec3, b: &Vec3) -> f32 {
+ a.sub(*b).abs().max_element()
+ }
+
+ fn abs_diff_eq(a: &Vec3, b: &Vec3, tol: f32) -> bool {
+ a.abs_diff_eq(*b, tol)
+ }
+}
+
+impl AbsDiffEq for Vec4 {
+ fn abs_diff(a: &Vec4, b: &Vec4) -> f32 {
+ a.sub(*b).abs().max_element()
+ }
+
+ fn abs_diff_eq(a: &Vec4, b: &Vec4, tol: f32) -> bool {
+ a.abs_diff_eq(*b, tol)
+ }
+}
+
+impl AbsDiffEq for Quat {
+ fn abs_diff(a: &Quat, b: &Quat) -> f32 {
+ Vec4::from(*a).sub(Vec4::from(*b)).abs().max_element()
+ }
+
+ fn abs_diff_eq(a: &Quat, b: &Quat, tol: f32) -> bool {
+ a.abs_diff_eq(*b, tol)
+ }
+}
+
+/// Assert that two floating-point quantities are approximately equal.
+///
+/// This macro asserts that the absolute difference between the two first
+/// arguments is strictly less than a tolerance factor, which can be explicitly
+/// passed as third argument or implicitly defaults to `1e-5`.
+///
+/// The two quantities must implement the [`AbsDiffEq`] helper trait. This trait
+/// is implemented for common floating-point quantities like `f32` or `f64`, or
+/// associated vector math types like `Vec3` or `Quat`.
+///
+/// # Usage
+///
+/// ```
+/// let x = 3.500009;
+/// assert_approx_eq!(x, 3.5); // default tolerance 1e-5
+///
+/// let x = 3.509;
+/// assert_approx_eq!(x, 3.5, 0.01); // explicit tolerance
+/// ```
+macro_rules! assert_approx_eq {
+ ($left:expr, $right:expr $(,)?) => {
+ match (&$left, &$right) {
+ (left_val, right_val) => {
+ assert!(
+ crate::test_utils::AbsDiffEq::abs_diff_eq(left_val, right_val, 1e-5),
+ "assertion failed: expected={} actual={} delta={} tol=1e-5(default)",
+ left_val,
+ right_val,
+ crate::test_utils::AbsDiffEq::abs_diff(left_val, right_val),
+ );
+ }
+ }
+ };
+ ($left:expr, $right:expr, $tol:expr $(,)?) => {
+ match (&$left, &$right, &$tol) {
+ (left_val, right_val, tol_val) => {
+ assert!(
+ crate::test_utils::AbsDiffEq::abs_diff_eq(left_val, right_val, *tol_val),
+ "assertion failed: expected={} actual={} delta={} tol={}",
+ left_val,
+ right_val,
+ crate::test_utils::AbsDiffEq::abs_diff(left_val, right_val),
+ tol_val
+ );
+ }
+ }
+ };
+}
+
+pub(crate) use assert_approx_eq;
+
+/// Mock renderer backed by any available WGPU backend, and simulating the real
+/// Bevy backend to enable testing rendering-related features.
+#[cfg(feature = "gpu_tests")]
+#[allow(dead_code)]
+pub(crate) struct MockRenderer {
+ /// WGPU instance backed by any available backend.
+ instance: wgpu::Instance,
+ /// Default WGPU adapter for the configured instance.
+ adapter: wgpu::Adapter,
+ /// Bevy render device abstracting the WGPU backend.
+ device: RenderDevice,
+ /// Bevy render queue sending commands to the render device.
+ queue: RenderQueue,
+}
+
+#[cfg(feature = "gpu_tests")]
+impl MockRenderer {
+ /// Create a new mock renderer with a default backend and adapter.
+ pub fn new() -> Self {
+ #[cfg(debug_assertions)]
+ let flags = wgpu::InstanceFlags::DEBUG | wgpu::InstanceFlags::VALIDATION;
+ #[cfg(not(debug_assertions))]
+ let flags = wgpu::InstanceFlags::empty();
+
+ // Create the WGPU adapter. Use PRIMARY backends (Vulkan, Metal, DX12,
+ // Browser+WebGPU) to ensure we get a backend that supports compute and other
+ // modern features we might need.
+ let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
+ backends: wgpu::Backends::PRIMARY,
+ flags,
+ backend_options: wgpu::BackendOptions::default(),
+ memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
+ display: None,
+ });
+ let adapter =
+ futures::executor::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
+ power_preference: wgpu::PowerPreference::default(),
+ force_fallback_adapter: false,
+ compatible_surface: None,
+ ..Default::default()
+ }))
+ .expect("Failed to find an appropriate adapter");
+
+ // Create the logical device and command queue
+ let (device, queue) =
+ futures::executor::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
+ // Request MAPPABLE_PRIMARY_BUFFERS to allow MAP_WRITE|COPY_DST.
+ // FIXME - Should use a separate buffer from primary to support more platforms.
+ required_features: wgpu::Features::MAPPABLE_PRIMARY_BUFFERS,
+ required_limits: wgpu::Limits::defaults(),
+ ..Default::default()
+ }))
+ .expect("Failed to create device");
+
+ // Turn into Bevy objects
+ let device = RenderDevice::from(device);
+ let queue = RenderQueue::new(queue);
+
+ Self {
+ instance,
+ adapter,
+ device,
+ queue,
+ }
+ }
+
+ /// Get the Bevy render device of the mock renderer.
+ pub fn device(&self) -> RenderDevice {
+ self.device.clone()
+ }
+
+ /// Get the Bevy render queue of the mock renderer.
+ pub fn queue(&self) -> RenderQueue {
+ self.queue.clone()
+ }
+}
+
+/// Compile shader tests with the same conditional-translation defaults as Bevy.
+pub(crate) fn compile_wesl(
+ source: &str,
+ features: &[&str],
+ modules: &[(&str, &str)],
+) -> Result<String, wesl::Error> {
+ let mut resolver = wesl::resolver::VirtualResolver::new();
+ let path = "package::test".parse().unwrap();
+ resolver.add_module(path, source.into());
+ for (path, source) in modules {
+ resolver.add_module(path.parse().unwrap(), (*source).into());
+ }
+ let mut options = wesl::CompileOptions {
+ visibility: false,
+ ..Default::default()
+ };
+ for feature in features {
+ options.features.set(feature, true);
+ }
+ wesl::compile(&"package::test".parse().unwrap(), &options, &resolver)
+ .map(|result| result.to_string())
+}
diff --git a/vendor/bevy_hanabi/src/time.rs b/vendor/bevy_hanabi/src/time.rs
new file mode 100644
index 00000000..ad23af27
--- /dev/null
+++ b/vendor/bevy_hanabi/src/time.rs
@@ -0,0 +1,255 @@
+use bevy::prelude::*;
+
+/// The effect simulation clock.
+///
+/// This is a specialization of the [`Time`] structure and uses the virtual
+/// clock [`Time<Virtual>`](Virtual) as its base.
+///
+/// The speed of this clock is therefore the product of the speed of the virtual
+/// clock and the speed of this clock itself. To change the speed of the entire
+/// app (including the effects), use [`Time<Virtual>`](Virtual). To influence
+/// only the speed of the effects, use
+/// [`Time<EffectSimulation>`](EffectSimulation).
+///
+/// # Example
+///
+/// ```
+/// # use bevy_hanabi::*;
+/// # use bevy::prelude::*;
+/// fn my_system(mut time: ResMut<Time<EffectSimulation>>) {
+/// // Pause the effects
+/// time.pause();
+///
+/// // Unpause the effects
+/// time.unpause();
+///
+/// // Set the speed to 2.0
+/// time.set_relative_speed(2.0);
+/// }
+/// ```
+#[derive(Debug, Copy, Clone, Reflect)]
+pub struct EffectSimulation {
+ paused: bool,
+ relative_speed: f64,
+ effective_speed: f64,
+}
+
+impl Default for EffectSimulation {
+ fn default() -> Self {
+ Self {
+ paused: false,
+ relative_speed: 1.0,
+ effective_speed: 1.0,
+ }
+ }
+}
+
+/// All methods for the [`Time<EffectSimulation>`](EffectSimulation) clock.
+pub trait EffectSimulationTime {
+ /// Returns the speed the clock advances relative to the virtual clock, as
+ /// [`f32`].
+ fn relative_speed(&self) -> f32;
+
+ /// Returns the speed the clock advances relative to the virtual clock, as
+ /// [`f64`].
+ fn relative_speed_f64(&self) -> f64;
+
+ /// Returns the speed the clock advanced relative to your system clock in
+ /// this update, as [`f32`].
+ ///
+ /// Returns `0.0` if either the [`Time<Virtual>`](Virtual) or the
+ /// [`Time<EffectSimulationTime>`](EffectSimulationTime) was paused
+ /// and otherwise the product of the `relative_speed` of the clocks at the
+ /// start of the update.
+ fn effective_speed(&self) -> f32;
+
+ /// Returns the speed the clock advanced relative to your system clock in
+ /// this update, as [`f64`].
+ ///
+ /// Returns `0.0` if either the [`Time<Virtual>`](Virtual) or the
+ /// [`Time<EffectSimulationTime>`](EffectSimulationTime) was paused
+ /// and otherwise the product of the `relative_speed` of the clocks at the
+ /// start of the update.
+ fn effective_speed_f64(&self) -> f64;
+
+ /// Sets the speed the clock advances relative to the virtual clock, given
+ /// as an [`f32`].
+ ///
+ /// For example, setting this to `2.0` will make the clock advance twice as
+ /// fast as the virtual clock.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `ratio` is negative or not finite.
+ fn set_relative_speed(&mut self, ratio: f32);
+
+ /// Sets the speed the clock advances relative to the virtual clock, given
+ /// as an [`f64`].
+ ///
+ /// For example, setting this to `2.0` will make the clock advance twice as
+ /// fast as the virtual clock.
+ ///
+ /// # Panics
+ ///
+ /// Panics if `ratio` is negative or not finite.
+ fn set_relative_speed_f64(&mut self, ratio: f64);
+
+ /// Stops the clock, preventing it from advancing until resumed.
+ fn pause(&mut self);
+
+ /// Resumes the clock if paused.
+ fn unpause(&mut self);
+
+ /// Returns `true` if the clock is currently paused.
+ fn is_paused(&self) -> bool;
+
+ /// Returns `true` if the clock was paused at the start of this update.
+ fn was_paused(&self) -> bool;
+}
+
+impl EffectSimulationTime for Time<EffectSimulation> {
+ #[inline]
+ fn relative_speed(&self) -> f32 {
+ self.relative_speed_f64() as f32
+ }
+
+ #[inline]
+ fn relative_speed_f64(&self) -> f64 {
+ self.context().relative_speed
+ }
+
+ #[inline]
+ fn effective_speed(&self) -> f32 {
+ self.context().effective_speed as f32
+ }
+
+ #[inline]
+ fn effective_speed_f64(&self) -> f64 {
+ self.context().effective_speed
+ }
+
+ #[inline]
+ fn set_relative_speed(&mut self, ratio: f32) {
+ self.set_relative_speed_f64(ratio as f64);
+ }
+
+ #[inline]
+ fn set_relative_speed_f64(&mut self, ratio: f64) {
+ assert!(ratio.is_finite(), "tried to go infinitely fast");
+ assert!(ratio >= 0.0, "tried to go back in time");
+ self.context_mut().relative_speed = ratio;
+ }
+
+ #[inline]
+ fn pause(&mut self) {
+ self.context_mut().paused = true;
+ }
+
+ #[inline]
+ fn unpause(&mut self) {
+ self.context_mut().paused = false;
+ }
+
+ #[inline]
+ fn is_paused(&self) -> bool {
+ self.context().paused
+ }
+
+ #[inline]
+ fn was_paused(&self) -> bool {
+ self.context().effective_speed == 0.0
+ }
+}
+
+pub(crate) fn effect_simulation_time_system(
+ virt: Res<Time<Virtual>>,
+ mut effect_simulation: ResMut<Time<EffectSimulation>>,
+) {
+ let virt_delta = virt.delta();
+ let effective_speed = if effect_simulation.context().paused {
+ 0.0
+ } else {
+ effect_simulation.context().relative_speed
+ };
+ let delta = if effective_speed != 1.0 {
+ virt_delta.mul_f64(effective_speed)
+ } else {
+ // avoid rounding when at normal speed
+ virt_delta
+ };
+ effect_simulation.context_mut().effective_speed = effective_speed * virt.effective_speed_f64();
+ effect_simulation.advance_by(delta);
+}
+
+#[cfg(test)]
+mod tests {
+ use std::{thread::sleep, time::Duration};
+
+ use bevy::time::{time_system, TimePlugin, TimeSystems};
+
+ use super::*;
+
+ fn make_test_app() -> App {
+ let mut app = App::new();
+
+ app.add_plugins(TimePlugin);
+ app.init_resource::<Time<EffectSimulation>>();
+ app.add_systems(
+ First,
+ effect_simulation_time_system
+ .after(time_system)
+ .in_set(TimeSystems),
+ );
+
+ app
+ }
+
+ #[test]
+ #[allow(clippy::suboptimal_flops)]
+ fn test_effect_simulation_time() {
+ // This is only used for floating point comparisons, inaccurate sleep times are
+ // always fine, as we only test for the relative values between the
+ // clocks.
+ const EPSILON: f32 = 0.000001;
+
+ let mut app = make_test_app();
+ app.update();
+
+ // Update with default speed
+ sleep(Duration::from_millis(1));
+ app.update();
+ let real = app.world().resource::<Time<Real>>();
+ let virt = app.world().resource::<Time<Virtual>>();
+ let effect_simulation = app.world().resource::<Time<EffectSimulation>>();
+ assert!(f32::abs(virt.delta_secs() - real.delta_secs()) < EPSILON);
+ assert!(f32::abs(effect_simulation.delta_secs() - real.delta_secs()) < EPSILON);
+
+ // Update with virtual speed 2.0
+ app.world_mut()
+ .resource_mut::<Time<Virtual>>()
+ .set_relative_speed(2.0);
+ sleep(Duration::from_millis(1));
+ app.update();
+ let real = app.world().resource::<Time<Real>>();
+ let virt = app.world().resource::<Time<Virtual>>();
+ let effect_simulation = app.world().resource::<Time<EffectSimulation>>();
+ assert!(f32::abs(virt.delta_secs() - 2.0 * real.delta_secs()) < EPSILON);
+ assert!(f32::abs(effect_simulation.delta_secs() - 2.0 * real.delta_secs()) < EPSILON);
+ assert!(f32::abs(virt.effective_speed() - 2.0) < EPSILON);
+ assert!(f32::abs(effect_simulation.effective_speed() - 2.0) < EPSILON);
+
+ // Update with virtual speed 2.0 and effect speed 3.0
+ app.world_mut()
+ .resource_mut::<Time<EffectSimulation>>()
+ .set_relative_speed(3.0);
+ sleep(Duration::from_millis(1));
+ app.update();
+ let real = app.world().resource::<Time<Real>>();
+ let virt = app.world().resource::<Time<Virtual>>();
+ let effect_simulation = app.world().resource::<Time<EffectSimulation>>();
+ assert!(f32::abs(virt.delta_secs() - 2.0 * real.delta_secs()) < EPSILON);
+ assert!(f32::abs(effect_simulation.delta_secs() - 6.0 * real.delta_secs()) < EPSILON);
+ assert!(f32::abs(virt.effective_speed() - 2.0) < EPSILON);
+ assert!(f32::abs(effect_simulation.effective_speed() - 6.0) < EPSILON);
+ }
+}
diff --git a/vendor/vendor.toml b/vendor/vendor.toml
index 30a2a4b3..0782c735 100644
--- a/vendor/vendor.toml
+++ b/vendor/vendor.toml
@@ -157,3 +157,10 @@ upstream = "git:github.com/anomalyco/rune@7ead7d63fcf6f9dd9669385a8b90e2ae80015d
kind = "patch"
reason = "taffy's flexbox_balance is on (Blitz turns it on and features unify in one build), so encode_wrap maps FlexWrap::Balance and BalanceReverse; upstream's match isn't exhaustive with that feature"
exit = "a Rune release whose rune-taffy handles taffy's flexbox_balance"
+
+[bevy_hanabi]
+path = "vendor/bevy_hanabi"
+upstream = "git:github.com/djeedai/bevy_hanabi@77630ff1eed8b104f34e91d23e9440428dc5ab01:."
+kind = "patch"
+reason = "frame-pure particles (raea #52): a new particle seeded by its spawn index, not the dead slot it recycles (vfx_init.wesl), and blended effects sorted by view depth from the main camera, far first as Bevy sorts its transparent phase, through the ribbons' sort pass (mod.rs, sort.rs, vfx_sort_fill.wesl); examples and GPU tests dropped"
+exit = "a hanabi with a deterministic mode (both changes offered upstream); then back to the git dependency and drop the copy"