forked from djeedai/bevy_hanabi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
2130 lines (1940 loc) Β· 78.2 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![deny(
warnings,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
missing_docs,
unsafe_code,
unstable_features,
unused_import_braces,
unused_qualifications,
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.
//!
//! _Note: This library 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) via WebGPU is only available in Bevy in general since
//! the newly-released Bevy v0.11, and is not yet available in this library.
//! See [#41](https://github.com/djeedai/bevy_hanabi/issues/41) for details on
//! progress._
//!
//! # 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.
//!
//! ```toml
//! # Example: enable only 3D integration
//! bevy_hanabi = { version = "0.6", 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 = 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(0.05),
//! 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
//! vec![32768],
//! // Spawn at a rate of 5 particles per second
//! Spawner::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 });
//!
//! // 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. The simplest way is
//! to use the [`ParticleEffectBundle`] to ensure all required components are
//! spawned together.
//!
//! ```
//! # use bevy::prelude::*;
//! # use bevy_hanabi::prelude::*;
//! # fn spawn_effect(mut commands: Commands) {
//! # let effect_asset = Handle::<EffectAsset>::default();
//! commands.spawn(ParticleEffectBundle {
//! effect: ParticleEffect::new(effect_asset),
//! transform: Transform::from_translation(Vec3::Y),
//! ..Default::default()
//! });
//! # }
//! ```
//!
//! # 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 (or use the
//! [`ParticleEffectBundle`] for simplicity). 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. Also spawn an [`EffectProperties`] component on the same entity. This is
//! required even if the effect doesn't use properties. See [properties] for
//! more details.
//! 4. If actually using properties, update them through the
//! [`EffectProperties`] 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.
use std::fmt::Write as _;
#[cfg(feature = "2d")]
use bevy::utils::FloatOrd;
use bevy::{
prelude::*,
utils::{thiserror::Error, HashSet},
};
use serde::{Deserialize, Serialize};
mod asset;
pub mod attributes;
mod bundle;
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, EffectAsset, MotionIntegration, SimulationCondition};
pub use attributes::*;
pub use bundle::ParticleEffectBundle;
pub use gradient::{Gradient, GradientKey};
pub use graph::*;
pub use modifier::*;
pub use plugin::{EffectSystems, HanabiPlugin};
pub use properties::*;
pub use render::{LayoutFlags, ShaderCache};
pub use spawn::{tick_spawners, CpuValue, EffectSpawner, Random, Spawner};
pub use time::{EffectSimulation, EffectSimulationTime};
#[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."
);
/// Get the smallest multiple of align greater than or equal to value, where
/// `align` must be a power of two.
///
/// # Panics
///
/// Panics if `align` is not a power of two.
// TODO - filler for usize.next_multiple_of()
// https://github.com/rust-lang/rust/issues/88581
pub(crate) fn next_multiple_of(value: usize, align: usize) -> usize {
assert!(align & (align - 1) == 0); // power of 2
let count = (value + align - 1) / align;
count * align
}
/// 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 [`Transform`] 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 [`Transform`] of the
/// [`ParticleEffect`] component being simulated. Particles simulated in
/// local effect space are "attached" to the effect, and will be affected by
/// its [`Transform`]. The particle's [`Attribute::POSITION`] is the
/// position of the particle relative to the effect's [`Transform`].
Local,
}
impl SimulationSpace {
/// Evaluate the simulation space expression.
///
/// - In the init and udpate contexts, this expression transforms the
/// particle's position from simulation space to storage 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 | ModifierContext::Update => 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())));
}
Ok(format!(
"particle.{} += transform[3].xyz;", // TODO: get_view_position()
Attribute::POSITION.name()
))
}
SimulationSpace::Local => Ok("".to_string()),
},
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,
}
}
}
/// Visual effect made of particles.
///
/// The particle effect component represent 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 [`Transform`] 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.
///
/// # Dependencies
///
/// This component must always be paired with a [`CompiledParticleEffect`]
/// component. Failure to do so will prevent the effect instance from working.
///
/// When spawning a new [`ParticleEffect`], consider using the
/// [`ParticleEffectBundle`] to ensure all the necessary components are present
/// on the entity for the effect to render correctly.
///
/// # 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)]
pub struct ParticleEffect {
/// Handle of the effect to instantiate.
pub handle: Handle<EffectAsset>,
/// For 2D rendering, override the value of the Z coordinate of the layer at
/// which the particles are rendered.
///
/// 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.
///
/// Note that this value is shared by all particles of the effect instance.
///
/// This is only available with the `2d` feature.
#[cfg(feature = "2d")]
pub z_layer_2d: Option<f32>,
}
impl ParticleEffect {
/// Create a new particle effect without a spawner or any modifier.
pub fn new(handle: Handle<EffectAsset>) -> Self {
Self {
handle,
#[cfg(feature = "2d")]
z_layer_2d: None,
}
}
/// Set the value of the Z layer used when rendering in 2D mode.
///
/// In 2D mode, the Bevy renderer sorts all render items according to their
/// Z layer value, from back (negative) to front (positive). This
/// function sets the value assigned to the current particle effect, to
/// order it relative to any other 2D render item (including non-effects).
/// Setting the value to `None` reverts to the default sorting and put the
/// effect back into the default layer.
///
/// This function has no effect when rendering in 3D mode.
///
/// # Example
///
/// ```
/// # use bevy_hanabi::*;
/// # use bevy::asset::Handle;
/// # let asset = Handle::<EffectAsset>::default();
/// // Always render the effect in front of the default layer (z=0)
/// let effect = ParticleEffect::new(asset).with_z_layer_2d(Some(0.1));
/// ```
#[cfg(feature = "2d")]
pub fn with_z_layer_2d(mut self, z_layer_2d: Option<f32>) -> Self {
self.z_layer_2d = z_layer_2d;
self
}
}
/// Effect shader.
///
/// Contains the configured shaders for the init, update, and render passes.
#[derive(Debug, Default, Clone)]
pub(crate) struct EffectShader {
pub init: Handle<Shader>,
pub update: Vec<Handle<Shader>>,
pub render: Vec<Handle<Shader>>,
}
/// Source code (WGSL) 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 by the relevant WGSL code) but is not
/// specialized (the conditional directives like `#if` are still present).
#[derive(Debug)]
struct EffectShaderSource {
pub init: String,
pub update: Vec<String>,
pub render: Vec<String>,
pub layout_flags: LayoutFlags,
pub particle_texture: Option<Handle<Image>>,
}
/// Error resulting from the generating of the WGSL shader code of an
/// [`EffectAsset`].
#[derive(Debug, Error)]
enum ShaderGenerateError {
#[error("Expression error: {0:?}")]
Expr(ExprError),
#[error("Validation error: {0:?}")]
Validate(String),
}
impl EffectShaderSource {
/// 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) -> Result<EffectShaderSource, ShaderGenerateError> {
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
)));
}
// 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()
)));
}
// Generate the WGSL code declaring all the attributes inside the Particle
// struct.
let attributes_code = particle_layout.generate_code();
// 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 = vec2<f32>(particle.{0}, particle.{0});\n",
Attribute::SIZE.name()
);
has_size = true;
} else {
warn!("Attribute SIZE conflicts with another size attribute; ignored.");
}
} else if attr == Attribute::SIZE2 {
if !has_size {
inputs_code += &format!("var size = particle.{0};\n", Attribute::SIZE2.name());
has_size = true;
} else {
warn!("Attribute SIZE2 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;
} 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;
} 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::SIZE2.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_code();
let properties_binding_code = if property_layout.is_empty() {
"// (no properties)".to_string()
} else {
"@group(1) @binding(3) var<storage, read> properties : Properties;".to_string()
};
// 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();
// Generate the shader code for the initializing shader
let (init_code, init_extra, init_sim_space_transform_code) = {
let mut init_context =
ShaderWriter::new(ModifierContext::Init, &property_layout, &particle_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: {:?}", err);
return Err(ShaderGenerateError::Expr(err));
}
}
// If there are linked list attributes, clear them out.
// Not doing this is always a bug, so we might as well save the user
// some trouble.
for attribute in [Attribute::PREV, Attribute::NEXT] {
if particle_layout.contains(attribute) {
init_context
.main_code
.push_str(&format!("particle.{} = 0xffffffffu;", attribute.name()));
}
}
let sim_space_transform_code = match asset.simulation_space.eval(&init_context) {
Ok(s) => s,
Err(err) => {
error!("Failed to compile effect's simulation space: {:?}", err);
return Err(ShaderGenerateError::Expr(err));
}
};
(
init_context.main_code,
init_context.extra_code,
sim_space_transform_code,
)
};
// Configure the init shader template, and make sure a corresponding shader
// asset exists
let init_shader_source = PARTICLES_INIT_SHADER_TEMPLATE
.replace("{{ATTRIBUTES}}", &attributes_code)
.replace("{{INIT_CODE}}", &init_code)
.replace("{{INIT_EXTRA}}", &init_extra)
.replace("{{PROPERTIES}}", &properties_code)
.replace("{{PROPERTIES_BINDING}}", &properties_binding_code)
.replace(
"{{SIMULATION_SPACE_TRANSFORM_PARTICLE}}",
&init_sim_space_transform_code,
);
trace!("Configured init shader:\n{}", init_shader_source);
let mut layout_flags = LayoutFlags::NONE;
if asset.simulation_space == SimulationSpace::Local {
layout_flags |= LayoutFlags::LOCAL_SPACE_SIMULATION;
}
if let AlphaMode::Mask(_) = &asset.alpha_mode {
layout_flags |= LayoutFlags::USE_ALPHA_MASK;
}
let mut effect_particle_texture = None;
let (mut update_shader_sources, mut render_shader_sources) = (vec![], vec![]);
for group_index in 0..(asset.capacities().len() as u32) {
// Generate the shader code for the update shader
let (mut update_code, update_extra) = {
let mut update_context =
ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);
for m in asset.update_modifiers_for_group(group_index) {
if let Err(err) = m.apply(&mut module, &mut update_context) {
error!(
"Failed to compile effect, error in update context: {:?}",
err
);
return Err(ShaderGenerateError::Expr(err));
}
}
(update_context.main_code, update_context.extra_code)
};
// 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 {}.",
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,
image_sample_mapping_code,
) = {
let mut render_context = RenderContext::new(&property_layout, &particle_layout);
for m in asset.render_modifiers_for_group(group_index) {
m.apply_render(&mut module, &mut render_context);
}
if render_context.needs_uv {
layout_flags |= LayoutFlags::NEEDS_UV;
}
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 {
String::new()
};
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 {
(String::new(), String::new())
};
// FIXME: What about multiple textures?
if let Some(particle_texture) = render_context.particle_texture {
effect_particle_texture = Some(particle_texture);
}
(
render_context.vertex_code,
render_context.fragment_code,
render_context.render_extra,
alpha_cutoff_code,
flipbook_scale_code,
flipbook_row_count_code,
render_context.image_sample_mapping_code,
)
};
// Configure aging code