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
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
#![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, 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};

#[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.
    ///
    /// - 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,
        }
    }
}

/// The [`VisibilityClass`] used for all particle effects.
#[derive(Default, Clone, Copy, Component, ExtractComponent)]
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>>,
}

/// Texture slot of a [`Module`].
///
/// A texture slot defines a named bind point where a texture can be attached
/// and 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 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)
    }
}

/// 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 (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 with the relevant WGSL code) but is not
/// _specialized_ (the conditional directives 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 {
    /// WGSL source code for the init compute shader.
    pub init_shader_source: String,
    /// WGSL source code for the update compute shader.
    pub update_shader_source: String,
    /// WGSL 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_attributes_code = parent_layout
            .map(|layout| 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()
        };

        // 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(
            "@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!(
                "@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.
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);
            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_ATTRIBUTES}}", &parent_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 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);
            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,
            material_bindings_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 {
                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())
            };

            trace!(
                "Generating material bindings code for layout: {:?}",
                texture_layout
            );
            let mut material_bindings_code = String::new();
            let mut bind_index = 0;
            for (slot, _) in texture_layout.layout.iter().enumerate() {
                let tex_index = bind_index;
                let sampler_index = bind_index + 1;
                material_bindings_code.push_str(&format!(
                    "@group(3) @binding({tex_index}) var material_texture_{slot}: texture_2d<f32>;
@group(3) @binding({sampler_index}) var material_sampler_{slot}: sampler;
"
                ));
                bind_index += 2;
            }

            (
                render_context.vertex_code,
                render_context.fragment_code,
                render_context.render_extra,
                alpha_cutoff_code,
                flipbook_scale_code,
                flipbook_row_count_code,
                material_bindings_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_ATTRIBUTES}}", &parent_attributes_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(
                "{{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.wgsl");
const PARTICLES_UPDATE_SHADER_TEMPLATE: &str = include_str!("render/vfx_update.wgsl");
const PARTICLES_RENDER_SHADER_TEMPLATE: &str = include_str!("render/vfx_render.wgsl");

/// 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},
        shader::ShaderLoader,
        tasks::{IoTaskPool, TaskPoolBuilder},
    };
    use naga_oil::compose::{Composer, NagaModuleDescriptor, ShaderDefValue};

    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();
        {
            // Local is always available
            let ctx =
                ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);
            assert!(SimulationSpace::Local.eval(&ctx).is_ok());
            assert!(SimulationSpace::Global.eval(&ctx).is_err());

            // Global requires storing the particle's position
            let particle_layout = ParticleLayout::new().append(Attribute::POSITION).build();
            let ctx =
                ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);
            assert!(SimulationSpace::Local.eval(&ctx).is_ok());
            assert!(SimulationSpace::Global.eval(&ctx).is_ok());
        }
        {
            // Local is always available
            let ctx =
                ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);
            assert!(SimulationSpace::Local.eval(&ctx).is_ok());
            assert!(SimulationSpace::Global.eval(&ctx).is_err());

            // Global requires storing the particle's position
            let particle_layout = ParticleLayout::new().append(Attribute::POSITION).build();
            let ctx =
                ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);
            assert!(SimulationSpace::Local.eval(&ctx).is_ok());
            assert!(SimulationSpace::Global.eval(&ctx).is_ok());
        }
        {
            // 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());
        }
    }

    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 shader_defs = std::collections::HashMap::<String, ShaderDefValue>::new();
            shader_defs.insert("LOCAL_SPACE_SIMULATION".into(), ShaderDefValue::Bool(true));
            shader_defs.insert("NEEDS_UV".into(), ShaderDefValue::Bool(true));
            shader_defs.insert("NEEDS_NORMAL".into(), ShaderDefValue::Bool(false));
            shader_defs.insert(
                "NEEDS_PARTICLE_FRAGMENT".into(),
                ShaderDefValue::Bool(false),
            );
            shader_defs.insert(
                "PARTICLE_SCREEN_SPACE_SIZE".into(),
                ShaderDefValue::Bool(true),
            );
            if name == "Update" {
                shader_defs.insert("EM_MAX_SPAWN_ATOMIC".into(), ShaderDefValue::Bool(true));
            }
            let mut composer = Composer::default();

            // Import bevy_render::view for the render shader
            {
                // It's reasonably hard to retrieve the source code for view.wgsl in
                // bevy_render. We use a few tricks to get a Shader that we can
                // then convert into a composable module (which is how imports work in Bevy
                // itself).
                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
                    .init_asset::<Shader>()
                    .init_asset_loader::<ShaderLoader>();
                dummy_app.add_plugins(bevy::render::view::ViewPlugin);
                let asset_server = dummy_app.world().resource::<AssetServer>();
                let view_shader_handle =
                    asset_server.load::<Shader>("embedded://bevy_render/view/view.wgsl");

                // 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.update();

                    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();
                for (id, shader) in shaders.iter() {
                    println!("[{id:?}] {shader:?}");
                }
                let view_shader = shaders.get(&view_shader_handle).unwrap();

                let res = composer.add_composable_module(view_shader.into());
                assert!(res.is_ok());
            }

            // Import bevy_hanabi::vfx_common
            {
                let min_storage_buffer_offset_alignment = 256;
                let common_shader =
                    HanabiPlugin::make_common_shader(min_storage_buffer_offset_alignment);
                let res = composer.add_composable_module((&common_shader).into());
                assert!(res.is_ok());
            }

            match composer.make_naga_module(NagaModuleDescriptor {
                source: &code[..],
                file_path: &format!("{}.wgsl", name),
                shader_defs,
                ..Default::default()
            }) {
                Ok(module) => {
                    // println!("shader: {:#?}", module);
                    let info = naga::valid::Validator::new(
                        naga::valid::ValidationFlags::all(),
                        naga::valid::Capabilities::default(),
                    )
                    .validate(&module)
                    .unwrap();
                    let wgsl = naga::back::wgsl::write_string(
                        &module,
                        &info,
                        naga::back::wgsl::WriterFlags::EXPLICIT_TYPES,
                    )
                    .unwrap();
                    println!("Final wgsl from naga:\n\n{}", wgsl);
                    // Ok(module)
                }
                Err(e) => {
                    panic!("{}", e.emit_to_string(&composer));
                    // Err(e)
                }
            }

            // let mut frontend = Frontend::new();
            // let res = frontend.parse(code);
            // if let Err(err) = &res {
            //     println!("{} code: {}", name, code);
            //     println!("Err: {:?}", err);
            // }
            // assert!(res.is_ok());
        }
    }

    // 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());
            }
        }
    }
}