bevy_hanabi 0.19.0

Hanabi GPU particle system for the Bevy game engine
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
//! 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,
    /// 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,
    ) -> Self {
        Self {
            main_code: String::new(),
            extra_code: String::new(),
            property_layout,
            particle_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 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,
        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,
        )
        .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
        self.extra_code += &format!(
            r##"fn {0}({1}) {{
{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 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,
        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
        self.render_extra += &format!(
            r##"fn {0}({1}) {{
            {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();

        // 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>();
        // 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>();
        // 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, |module| {
        let slot = module.lit(0u32);
        Box::new(ParticleTextureModifier::new(slot))
    });
    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,
        })
    });

    // 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 mut context =
                ShaderWriter::new(ModifierContext::Init, &property_layout, &particle_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();
    var transform: mat4x4<f32> = mat4x4<f32>();
{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 mut context =
                ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_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 transform: mat4x4<f32> = mat4x4<f32>();
    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 mut base_module = Module::default();
        let slot_zero = base_module.lit(0u32);
        let modifiers: &[&dyn RenderModifier] = &[
            &ParticleTextureModifier::new(slot_zero),
            &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();
            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)
                .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;

{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: {:?}",
                    modifier.get_represented_type_info().unwrap().type_path()
                );
                println!("Code: {:?}", code);
                println!("Err: {:?}", 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 x = module.builtin(BuiltInOperator::Rand(ScalarType::Float.into()));
        let texture_layout = module.texture_layout();
        let init: &mut dyn EvalContext =
            &mut ShaderWriter::new(ModifierContext::Init, &property_layout, &particle_layout);
        let update: &mut dyn EvalContext =
            &mut ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_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);
        }
    }
}