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
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
//! Expression API
//!
//! This module contains the low-level _Expression API_, designed to produce
//! highly customizable modifier behaviors through a code-first API focused on
//! runtime and serialization. For asset editing, the higher-level [Node API]
//! offers an easier-to-use abstraction built on top of the Expression API.
//!
//! # Modules and expressions
//!
//! A particle effect is composed of a series [`Modifier`]s decribing how to
//! initialize and update (simulate) the particles of the effect. Choosing which
//! modifier to add to an effect provides the user some limited level of
//! customizing. However modifiers alone cannot provide enough customizing to
//! build visual effects. For this reason, modifier inputs can be further
//! customized with _expressions_. An expression produces a value which is
//! assigned to the input. That value can be constant, in which case it will be
//! hard-coded into the generated WGSL shader, for performance reasons.
//! Alternatively, that value can vary based on other quantities, like an effect
//! property, a particle attribute, or some built-in simulation variable like
//! the simulation time.
//!
//! An expression is represented by the [`Expr`] enum. Expressions can be
//! combined together to form more complex expression; for example, the Add
//! expression computes the sum between two other expressions. [`Expr`]
//! represents a form of abstraction over the actual WGSL shader code, and is
//! generally closely related to the actual expressions of the WGSL language
//! itself.
//!
//! An expression often refers to other expressions. However, [`Expr`] as an
//! enum cannot directly contain other [`Expr`], otherwise the type would become
//! infinitely recursive. Instead, each expression is stored into a [`Module`]
//! and indexed by an [`ExprHandle`], a non-zero index referencing the
//! expression inside the module. This indirection avoids the recursion issue.
//! This means all expressions are implicitly associated with a unique module,
//! and care must be taken to not mix exressions from different modules.
//!
//! Each [`EffectAsset`] contains a single [`Module`] storing all the [`Expr`]
//! used in all its modifiers.
//!
//! # Kinds of expressions
//!
//! Expressions can be grouped into various kinds, for the sake of
//! comprehension:
//! - Literal expressions represent a constant, which will be hard-coded into
//!   the final WGSL shader code. Expressions like `1.42` or `vec3<f32>(0.)` are
//!   literal expressions in WGSL, and are represented by a [`LiteralExpr`].
//! - Built-in expressions represent specific built-in values provided by the
//!   simulation context. For example, the current simulation time is a built-in
//!   expression accessible from the shader code of any visual effect to animate
//!   it. A built-in expression is represented by a [`BuiltInExpr`].
//! - Attribute expressions represent the value of an attribute of a particle. A
//!   typical example is the particle position, represented by
//!   [`Attribute::POSITION`], which can be obtained as an expression through an
//!   [`AttributeExpr`].
//! - Property expressions represent the value of a visual effect property, a
//!   quantity assigned by the user on the CPU side and uploaded each frame into
//!   the GPU for precise per-frame control over an effect. It's represented by
//!   a [`PropertyExpr`].
//! - Unary and binary operations are expressions taking one or two operand
//!   expressions and transforming them. A typical example is the Add operator,
//!   which takes two operand expressions and produces their sum.
//!
//! # Building expressions
//!
//! The fundamental way to build expressions is to directly write them into a
//! [`Module`] itself. The [`Module`] type contains various methods to create
//! new expressions and immediately write them.
//!
//! ```
//! # use bevy_hanabi::*;
//! let mut module = Module::default();
//!
//! // Build and write a literal expression into the module.
//! let expr = module.lit(3.42);
//! ```
//!
//! Due to the code-first nature of the Expression API however, that approach
//! can be very verbose. Instead, users are encouraged to use an [`ExprWriter`],
//! a simple utility to build expressions with a shortened syntax. Once an
//! expression is built, it can be written into the underlying [`Module`]. This
//! approach generally makes the code more readable, and is therefore highly
//! encouraged, but is not mandatory.
//!
//! ```
//! # use bevy_hanabi::*;
//! // Create a writer owning a new Module
//! let mut w = ExprWriter::new();
//!
//! // Build a complex expression: max(3.42, properties.my_prop)
//! let prop = w.add_property("my_property", 3.0.into());
//! let expr = w.lit(3.42).max(w.prop(prop));
//!
//! // Finalize the expression and write it into the Module. The returned handle can
//! // be assign to a modifier input.
//! let handle = expr.expr();
//!
//! // Finish using the writer and recover the Module with all written expressions
//! let module = w.finish();
//! ```
//!
//! [Node API]: crate::graph::node
//! [`Modifier`]: crate::Modifier
//! [`EffectAsset`]: crate::EffectAsset

use std::{cell::RefCell, num::NonZeroU32, rc::Rc};

use bevy::{
    platform::collections::HashSet,
    prelude::default,
    reflect::{Reflect, ReflectDeserialize, ReflectSerialize},
};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use super::Value;
use crate::{
    Attribute, ModifierContext, ParticleLayout, Property, PropertyLayout, ScalarType,
    TextureLayout, TextureSlot, ToWgslString, ValueType, VectorType,
};

/// A one-based ID into a collection of a [`Module`].
type Id = NonZeroU32;

/// Handle of an expression inside a given [`Module`].
///
/// A handle uniquely references an [`Expr`] stored inside a [`Module`]. It's a
/// lightweight representation, similar to a simple array index. For this
/// reason, it's easily copyable. However it's also lacking any kind of error
/// checking, and mixing handles to different modules produces undefined
/// behaviors (like an index does when indexing the wrong array).
///
/// # Serialization
///
/// [`ExprHandle`] is serialized as a string `#<id>`, where `<id>` is the
/// 1-based integer index of the expression in the implicitly associated
/// [`Module`]'s expression array. Valid `<id>` values are in the range
/// `1..=u32::MAX`.
///
/// Note that during deserialization, there is no validation that the index
/// actually refers to a valid entry in the expression array.
///
/// Examples of valid values:
/// - `"#1"`
/// - `"#42"`
/// - `"#4000"` -- deserializes OK, but unlikely there are 4000 expressions in
///   the Module
///
/// Examples of **invalid** values:
/// - `"#0"` -- 0 is a reserved value
/// - `"#-1"` -- must be positive
/// - `"#4294967296"` -- out of bounds (> u32::MAX)
/// - `33` -- not a string
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect)]
#[reflect(Serialize, Deserialize)]
#[repr(transparent)]
pub struct ExprHandle {
    id: Id,
}

impl serde::Serialize for ExprHandle {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&format!("#{}", self.id.get()))
    }
}

impl<'de> serde::Deserialize<'de> for ExprHandle {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct IdVisitor;

        impl<'de2> serde::de::Visitor<'de2> for IdVisitor {
            type Value = ExprHandle;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str(
                    "a string of the form \"#<N>\" where <N> is a non-zero expression index",
                )
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                if v.len() > 1 && v.chars().nth(0) == Some('#') {
                    let id = v[1..]
                        .parse::<u32>()
                        .map_err(|_| serde::de::Error::custom("Failed to parse ID value"))?;
                    NonZeroU32::try_from(id)
                        .map(|id| ExprHandle { id })
                        .map_err(|_| serde::de::Error::custom("Invalid ID value"))
                } else {
                    Err(serde::de::Error::custom(
                        "Invalid ID format (expected '#N')",
                    ))
                }
            }

            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                self.visit_str(&v[..])
            }
        }

        deserializer.deserialize_any(IdVisitor)
    }
}

impl ExprHandle {
    /// Create a new handle from a 1-based [`Id`].
    #[allow(dead_code)]
    fn new(id: Id) -> Self {
        Self { id }
    }

    /// Create a new handle from a 1-based [`Id`] as a `usize`, for cases where
    /// the index is known to be non-zero already.
    #[allow(unsafe_code)]
    unsafe fn new_unchecked(id: usize) -> Self {
        debug_assert!(id != 0);
        Self {
            id: NonZeroU32::new_unchecked(id as u32),
        }
    }

    /// Get the zero-based index into the array of the module.
    pub fn index(&self) -> usize {
        (self.id.get() - 1) as usize
    }
}

/// Handle of a property inside a given [`Module`].
///
/// A handle uniquely references a [`Property`] stored inside a [`Module`]. It's
/// a lightweight representation, similar to a simple array index. For this
/// reason, it's easily copyable. However it's also lacking any kind of error
/// checking, and mixing handles to different modules produces undefined
/// behaviors (like an index does when indexing the wrong array).
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect, Serialize, Deserialize,
)]
#[repr(transparent)]
#[serde(transparent)]
pub struct PropertyHandle {
    id: Id,
}

impl PropertyHandle {
    /// Create a new handle from a 1-based [`Id`].
    #[allow(dead_code)]
    fn new(id: Id) -> Self {
        Self { id }
    }

    /// Create a new handle from a 1-based [`Id`] as a `usize`, for cases where
    /// the index is known to be non-zero already.
    #[allow(unsafe_code)]
    unsafe fn new_unchecked(id: usize) -> Self {
        debug_assert!(id != 0);
        Self {
            id: NonZeroU32::new_unchecked(id as u32),
        }
    }

    /// Get the zero-based index into the array of the module.
    pub fn index(&self) -> usize {
        (self.id.get() - 1) as usize
    }
}

/// Handle of a texture inside a given [`Module`].
///
/// A handle uniquely references a [`TextureSlot`] stored inside a [`Module`].
/// It's a lightweight representation, similar to a simple array index. For this
/// reason, it's easily copyable. However it's also lacking any kind of error
/// checking, and mixing handles to different modules produces undefined
/// behaviors (like an index does when indexing the wrong array).
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect, Serialize, Deserialize,
)]
#[repr(transparent)]
#[serde(transparent)]
pub struct TextureHandle {
    id: Id,
}

impl TextureHandle {
    /// Create a new handle from a 1-based [`Id`].
    #[allow(dead_code)]
    fn new(id: Id) -> Self {
        Self { id }
    }

    /// Create a new handle from a 1-based [`Id`] as a `usize`, for cases where
    /// the index is known to be non-zero already.
    #[allow(unsafe_code)]
    unsafe fn new_unchecked(id: usize) -> Self {
        debug_assert!(id != 0);
        Self {
            id: NonZeroU32::new_unchecked(id as u32),
        }
    }

    /// Get the zero-based index into the array of the module.
    #[allow(dead_code)]
    fn index(&self) -> usize {
        (self.id.get() - 1) as usize
    }
}

/// Container for expressions.
///
/// A module represents a storage for a set of expressions used in a single
/// [`EffectAsset`]. Modules are not reusable accross effect assets; each effect
/// asset owns a single module, containing all the expressions used in all the
/// modifiers attached to that asset. However, for convenience, a module can be
/// cloned into an unrelated module, and the clone can be assigned to another
/// effect asset.
///
/// Modules are built incrementally. Expressions are written into the module
/// through convenience helpers like [`lit()`] or [`attr()`]. Alternatively, an
/// [`ExprWriter`] can be used to populate a new or existing module. Either way,
/// once an expression is written into a module, it cannot be modified or
/// deleted. Modules are not designed to be used as editing structures, but as
/// storage and serialization ones.
///
/// [`EffectAsset`]: crate::EffectAsset
/// [`lit()`]: Module::lit
/// [`attr()`]: Module::attr
#[derive(Debug, Default, Clone, PartialEq, Hash, Reflect, Serialize, Deserialize)]
pub struct Module {
    /// Expressions defined in the module.
    expressions: Vec<Expr>,
    /// Properties used as part of a [`PropertyExpr`].
    properties: Vec<Property>,
    /// Texture layout.
    texture_layout: TextureLayout,
}

macro_rules! impl_module_unary {
    ($t: ident, $T: ident) => {
        #[doc = concat!("Build a [`UnaryOperator::", stringify!($T), "`](crate::graph::expr::UnaryOperator::", stringify!($T),") unary expression and append it to the module.\n\nThis is a shortcut for [`unary(UnaryOperator::", stringify!($T), ", inner)`](crate::graph::expr::Module::unary).")]
        #[inline]
        pub fn $t(&mut self, inner: ExprHandle) -> ExprHandle {
            self.unary(UnaryOperator::$T, inner)
        }
    };
}

macro_rules! impl_module_binary {
    ($t: ident, $T: ident) => {
        #[doc = concat!("Build a [`BinaryOperator::", stringify!($T), "`](crate::graph::expr::BinaryOperator::", stringify!($T),") binary expression and append it to the module.\n\nThis is a shortcut for [`binary(BinaryOperator::", stringify!($T), ", left, right)`](crate::graph::expr::Module::binary).")]
        #[inline]
        pub fn $t(&mut self, left: ExprHandle, right: ExprHandle) -> ExprHandle {
            self.binary(BinaryOperator::$T, left, right)
        }
    };
}

macro_rules! impl_module_ternary {
    ($t: ident, $T: ident) => {
        #[doc = concat!("Build a [`TernaryOperator::", stringify!($T), "`](crate::graph::expr::TernaryOperator::", stringify!($T),") ternary expression and append it to the module.\n\nThis is a shortcut for [`ternary(TernaryOperator::", stringify!($T), ", first, second, third)`](crate::graph::expr::Module::ternary).")]
        #[inline]
        pub fn $t(&mut self, first: ExprHandle, second: ExprHandle, third: ExprHandle) -> ExprHandle {
            self.ternary(TernaryOperator::$T, first, second, third)
        }
    };
}

impl Module {
    /// Create a new module from an existing collection of expressions.
    pub fn from_raw(expr: Vec<Expr>) -> Self {
        Self {
            expressions: expr,
            properties: vec![],
            texture_layout: default(),
        }
    }

    /// Get all the expressions in this module.
    pub fn expressions(&self) -> impl Iterator<Item = (ExprHandle, &Expr)> {
        self.expressions.iter().enumerate().map(|(index, expr)| {
            (
                // SAFETY - We directly iterate over the array with enumerate() so all indices are
                // valid by design.
                #[allow(unsafe_code)]
                unsafe {
                    ExprHandle::new_unchecked(index + 1)
                },
                expr,
            )
        })
    }

    /// Append a new expression to the module.
    pub fn add_expr(&mut self, expr: impl Into<Expr>) -> ExprHandle {
        self.expressions.push(expr.into());
        #[allow(unsafe_code)]
        unsafe {
            ExprHandle::new_unchecked(self.expressions.len())
        }
    }

    /// Add a new property to the module.
    ///
    /// See [`Property`] for more details on what effect properties are.
    ///
    /// # Panics
    ///
    /// Panics if a property with the same name already exists.
    pub fn add_property(
        &mut self,
        name: impl Into<String>,
        default_value: Value,
    ) -> PropertyHandle {
        let name = name.into();
        assert!(!self.properties.iter().any(|p| p.name() == name));
        self.properties.push(Property::new(name, default_value));
        // SAFETY - We just pushed a new property into the array, so its length is
        // non-zero.
        #[allow(unsafe_code)]
        unsafe {
            PropertyHandle::new_unchecked(self.properties.len())
        }
    }

    /// Get an existing property by handle.
    ///
    /// Existing properties are properties previously created with
    /// [`add_property()`].
    ///
    /// [`add_property()`]: crate::Module::add_property
    pub fn get_property(&self, property: PropertyHandle) -> Option<&Property> {
        self.properties.get(property.index())
    }

    /// Get an existing property by name.
    ///
    /// Existing properties are properties previously created with
    /// [`add_property()`].
    ///
    /// [`add_property()`]: crate::Module::add_property
    pub fn get_property_by_name(&self, name: &str) -> Option<PropertyHandle> {
        self.properties
            .iter()
            .enumerate()
            .find(|(_, prop)| prop.name() == name)
            .map(|(index, _)| PropertyHandle::new(NonZeroU32::new(index as u32 + 1).unwrap()))
    }

    /// Get the list of existing properties.
    pub fn properties(&self) -> &[Property] {
        &self.properties
    }

    /// Add a new texture slot to the module.
    ///
    /// The `name` parameter defines a new [`TextureSlot`] associated with this
    /// module, and must be unique inside this module. A unique index is also
    /// associated with the slot, corresponding to the value returned by
    /// [`TextureLayout::get_slot_by_name()`].
    ///
    /// Once a slot is added, an actual texture resource, defined by its
    /// `Handle<Image>`, is bound to that slot through the
    /// [`EffectMaterial`] component. Expressions like [`TextureSampleExpr`] can
    /// be used to sample the texture using the returned [`TextureHandle`].
    ///
    /// # Returns
    ///
    /// The handle of the texture inside this module. This handle is used in
    /// expressions like the [`TextureSampleExpr`] to reference this texture
    /// slot.
    ///
    /// # Panics
    ///
    /// Panics if a texture slot with the same name already exists inside this
    /// module. Different effect asset (different modules) can have the same
    /// slot name.
    ///
    /// [`EffectMaterial`]: crate::EffectMaterial
    pub fn add_texture_slot(&mut self, name: impl Into<String>) -> TextureHandle {
        let name = name.into();
        assert!(!self.texture_layout.layout.iter().any(|t| t.name == name));
        self.texture_layout.layout.push(TextureSlot { name });
        // SAFETY - We just pushed a new slot into the array, so its length is non-zero.
        #[allow(unsafe_code)]
        unsafe {
            TextureHandle::new_unchecked(self.texture_layout.layout.len())
        }
    }

    /// Insert into the given set all attributes referenced by any
    /// [`AttributeExpr`] present in the module.
    ///
    /// Note that this **excludes** the attributes from an
    /// [`Expr::ParentAttribute`] expression.
    pub fn gather_attributes(&self, set: &mut HashSet<Attribute>) {
        for expr in &self.expressions {
            if let Expr::Attribute(attr) = expr {
                set.insert(attr.attr);
            }
        }
    }

    /// Build a literal expression and append it to the module.
    #[inline]
    pub fn lit<V>(&mut self, value: V) -> ExprHandle
    where
        Value: From<V>,
    {
        self.add_expr(Expr::Literal(LiteralExpr::new(value)))
    }

    /// Build an attribute expression and append it to the module.
    #[inline]
    pub fn attr(&mut self, attr: Attribute) -> ExprHandle {
        self.add_expr(Expr::Attribute(AttributeExpr::new(attr)))
    }

    /// Build a parent attribute expression and append it to the module.
    #[inline]
    pub fn parent_attr(&mut self, attr: Attribute) -> ExprHandle {
        self.add_expr(Expr::ParentAttribute(AttributeExpr::new(attr)))
    }

    /// Build a property expression and append it to the module.
    ///
    /// A property expression retrieves the value of the given property.
    #[inline]
    pub fn prop(&mut self, property: PropertyHandle) -> ExprHandle {
        self.add_expr(Expr::Property(PropertyExpr::new(property)))
    }

    /// Build a built-in expression and append it to the module.
    #[inline]
    pub fn builtin(&mut self, op: BuiltInOperator) -> ExprHandle {
        self.add_expr(Expr::BuiltIn(BuiltInExpr::new(op)))
    }

    /// Build a unary expression and append it to the module.
    ///
    /// The handle to the expression representing the operand of the unary
    /// operation must be valid, that is reference an expression
    /// contained in the current [`Module`].
    ///
    /// # Panics
    ///
    /// Panics in some cases if the operand handle do not reference an existing
    /// expression in the current module. Note however that this check can
    /// miss some invalid handles (false negative), so only represents an
    /// extra safety net that users shouldn't rely exclusively on
    /// to ensure the operand handles are valid. Instead, it's the
    /// responsibility of the user to ensure the operand handle references an
    /// existing expression in the current [`Module`].
    #[inline]
    pub fn unary(&mut self, op: UnaryOperator, inner: ExprHandle) -> ExprHandle {
        assert!(inner.index() < self.expressions.len());
        self.add_expr(Expr::Unary { op, expr: inner })
    }

    impl_module_unary!(abs, Abs);
    impl_module_unary!(acos, Acos);
    impl_module_unary!(asin, Asin);
    impl_module_unary!(atan, Atan);
    impl_module_unary!(all, All);
    impl_module_unary!(any, Any);
    impl_module_unary!(ceil, Ceil);
    impl_module_unary!(cos, Cos);
    impl_module_unary!(exp, Exp);
    impl_module_unary!(exp2, Exp2);
    impl_module_unary!(floor, Floor);
    impl_module_unary!(fract, Fract);
    impl_module_unary!(inverse_sqrt, InvSqrt);
    impl_module_unary!(length, Length);
    impl_module_unary!(log, Log);
    impl_module_unary!(log2, Log2);
    impl_module_unary!(normalize, Normalize);
    impl_module_unary!(pack4x8snorm, Pack4x8snorm);
    impl_module_unary!(pack4x8unorm, Pack4x8unorm);
    impl_module_unary!(round, Round);
    impl_module_unary!(saturate, Saturate);
    impl_module_unary!(sign, Sign);
    impl_module_unary!(sin, Sin);
    impl_module_unary!(sqrt, Sqrt);
    impl_module_unary!(tan, Tan);
    impl_module_unary!(unpack4x8snorm, Unpack4x8snorm);
    impl_module_unary!(unpack4x8unorm, Unpack4x8unorm);
    impl_module_unary!(w, W);
    impl_module_unary!(x, X);
    impl_module_unary!(y, Y);
    impl_module_unary!(z, Z);

    /// Build a binary expression and append it to the module.
    ///
    /// The handles to the expressions representing the left and right operands
    /// of the binary operation must be valid, that is reference expressions
    /// contained in the current [`Module`].
    ///
    /// # Panics
    ///
    /// Panics in some cases if either of the left or right operand handles do
    /// not reference existing expressions in the current module. Note however
    /// that this check can miss some invalid handles (false negative), so only
    /// represents an extra safety net that users shouldn't rely exclusively on
    /// to ensure the operand handles are valid. Instead, it's the
    /// responsibility of the user to ensure handles reference existing
    /// expressions in the current [`Module`].
    #[inline]
    pub fn binary(
        &mut self,
        op: BinaryOperator,
        left: ExprHandle,
        right: ExprHandle,
    ) -> ExprHandle {
        assert!(left.index() < self.expressions.len());
        assert!(right.index() < self.expressions.len());
        self.add_expr(Expr::Binary { op, left, right })
    }

    impl_module_binary!(add, Add);
    impl_module_binary!(atan2, Atan2);
    impl_module_binary!(cross, Cross);
    impl_module_binary!(distance, Distance);
    impl_module_binary!(div, Div);
    impl_module_binary!(dot, Dot);
    impl_module_binary!(ge, GreaterThanOrEqual);
    impl_module_binary!(gt, GreaterThan);
    impl_module_binary!(le, LessThanOrEqual);
    impl_module_binary!(lt, LessThan);
    impl_module_binary!(max, Max);
    impl_module_binary!(min, Min);
    impl_module_binary!(mul, Mul);
    impl_module_binary!(rem, Remainder);
    impl_module_binary!(step, Step);
    impl_module_binary!(sub, Sub);
    impl_module_binary!(uniform, UniformRand);
    impl_module_binary!(normal, NormalRand);
    impl_module_binary!(vec2, Vec2);
    impl_module_binary!(vec4_xyz_w, Vec4XyzW);

    /// Build a ternary expression and append it to the module.
    ///
    /// The handles to the expressions representing the three operands of the
    /// ternary operation must be valid, that is reference expressions
    /// contained in the current [`Module`].
    ///
    /// # Panics
    ///
    /// Panics in some cases if any of the operand handles do not reference
    /// existing expressions in the current module. Note however
    /// that this check can miss some invalid handles (false negative), so only
    /// represents an extra safety net that users shouldn't rely exclusively on
    /// to ensure the operand handles are valid. Instead, it's the
    /// responsibility of the user to ensure handles reference existing
    /// expressions in the current [`Module`].
    #[inline]
    pub fn ternary(
        &mut self,
        op: TernaryOperator,
        first: ExprHandle,
        second: ExprHandle,
        third: ExprHandle,
    ) -> ExprHandle {
        assert!(first.index() < self.expressions.len());
        assert!(second.index() < self.expressions.len());
        assert!(third.index() < self.expressions.len());
        self.add_expr(Expr::Ternary {
            op,
            first,
            second,
            third,
        })
    }

    impl_module_ternary!(mix, Mix);
    impl_module_ternary!(clamp, Clamp);
    impl_module_ternary!(smoothstep, SmoothStep);
    impl_module_ternary!(vec3, Vec3);

    /// Build a cast expression and append it to the module.
    ///
    /// The handle to the expressions representing the operand of the cast
    /// operation must be valid, that is reference expressions contained in
    /// the current [`Module`].
    ///
    /// # Panics
    ///
    /// Panics in some cases if the operand handle does not reference existing
    /// expressions in the current module. Note however that this check can
    /// miss some invalid handles (false negative), so only represents an
    /// extra safety net that users shouldn't rely exclusively on
    /// to ensure the operand handles are valid. Instead, it's the
    /// responsibility of the user to ensure handles reference existing
    /// expressions in the current [`Module`].
    ///
    /// Panics if the resulting cast expression is not valid. See
    /// [`CastExpr::is_valid()`] for the exact meaning.
    pub fn cast(&mut self, expr: ExprHandle, target: impl Into<ValueType>) -> ExprHandle {
        assert!(expr.index() < self.expressions.len());
        let target = target.into();
        let expr = CastExpr::new(expr, target);
        if let Some(valid) = expr.is_valid(self) {
            assert!(valid);
        }
        self.add_expr(Expr::Cast(expr))
    }

    /// Get an existing expression from its handle.
    #[inline]
    pub fn get(&self, expr: ExprHandle) -> Option<&Expr> {
        let index = expr.index();
        self.expressions.get(index)
    }

    /// Get an existing expression from its handle.
    #[inline]
    pub fn get_mut(&mut self, expr: ExprHandle) -> Option<&mut Expr> {
        let index = expr.index();
        self.expressions.get_mut(index)
    }

    /// Get an existing expression from its handle.
    #[inline]
    pub fn try_get(&self, expr: ExprHandle) -> Result<&Expr, ExprError> {
        let index = expr.index();
        self.expressions
            .get(index)
            .ok_or(ExprError::InvalidExprHandleError(format!(
                "Cannot find expression with handle {:?} in the current module. Check that the Module used to build the expression was the same used in the EvalContext or the original EffectAsset.", expr)))
    }

    /// Get an existing expression from its handle.
    #[inline]
    pub fn try_get_mut(&mut self, expr: ExprHandle) -> Result<&mut Expr, ExprError> {
        let index = expr.index();
        self.expressions
            .get_mut(index)
            .ok_or(ExprError::InvalidExprHandleError(format!(
                "Cannot find expression with handle {:?} in the current module. Check that the Module used to build the expression was the same used in the EvalContext or the original EffectAsset.", expr)))
    }

    /// Is the expression resulting in a compile-time constant which can be
    /// hard-coded into a shader's code?
    ///
    /// # Panics
    ///
    /// Panics if `expr` doesn't refer to an expression of this module.
    #[inline]
    pub fn is_const(&self, expr: ExprHandle) -> bool {
        let expr = self.get(expr).unwrap();
        expr.is_const(self)
    }

    /// Has the expression any side-effect?
    ///
    /// Expressions with side-effect need to be stored into temporary variables
    /// when the shader code is emitted, so that the side effect is only applied
    /// once when the expression is reused in multiple locations.
    ///
    /// # Panics
    ///
    /// Panics if `expr` doesn't refer to an expression of this module.
    pub fn has_side_effect(&self, expr: ExprHandle) -> bool {
        let expr = self.get(expr).unwrap();
        expr.has_side_effect(self)
    }

    /// Get the texture layout of this module.
    pub fn texture_layout(&self) -> TextureLayout {
        self.texture_layout.clone()
    }
}

/// Errors raised when manipulating expressions [`Expr`] and node graphs
/// [`Graph`].
///
/// [`Graph`]: crate::graph::Graph
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum ExprError {
    /// Expression type error.
    ///
    /// Generally used for invalid type conversion (casting).
    #[error("Type error: {0}")]
    TypeError(String),

    /// Expression syntax error.
    #[error("Syntax error: {0}")]
    SyntaxError(String),

    /// Generic graph evaluation error.
    #[error("Graph evaluation error: {0}")]
    GraphEvalError(String),

    /// Error resolving a property.
    ///
    /// An unknown property was not defined in the evaluation context, which
    /// usually means that the property was not defined with
    /// [`Module::add_property()`].
    #[error("Property error: {0}")]
    PropertyError(String),

    /// Invalid expression handle not referencing any existing [`Expr`] in the
    /// evaluation [`Module`].
    ///
    /// This error is commonly raised when using an [`ExprWriter`] and
    /// forgetting to transfer the underlying [`Module`] where the expressions
    /// are written to the [`EffectAsset`]. See [`ExprWriter`] for details.
    ///
    /// [`EffectAsset`]: crate::EffectAsset
    #[error("Invalid expression handle: {0}")]
    InvalidExprHandleError(String),

    /// Invalid modifier context.
    ///
    /// The operation was expecting a given [`ModifierContext`], but instead
    /// another [`ModifierContext`] was available.
    #[error("Invalid modifier context {0}, expected {1} instead.")]
    InvalidModifierContext(ModifierContext, ModifierContext),
}

/// Evaluation context for transforming expressions into WGSL code.
///
/// The evaluation context references a [`Module`] storing all [`Expr`] in use,
/// as well as a [`ParticleLayout`] defining the existing attributes of each
/// particle and their layout in memory, and a [`PropertyLayout`] defining
/// existing properties and their layout in memory. These together define the
/// context within which expressions are evaluated.
///
/// A same expression can be valid in one context and invalid in another. The
/// most obvious example is a [`PropertyExpr`] which is only valid if the
/// property is actually defined in the property layout of the evaluation
/// context.
pub trait EvalContext {
    /// Get the modifier context of the evaluation.
    fn modifier_context(&self) -> ModifierContext;

    /// Get the particle layout of the effect.
    fn particle_layout(&self) -> &ParticleLayout;

    /// Get the property layout of the effect.
    fn property_layout(&self) -> &PropertyLayout;

    /// Evaluate an expression, returning its WGSL shader code.
    ///
    /// The evaluation is guaranteed to be unique. Calling `eval()` multiple
    /// times with the same handle will return the same result. If the
    /// expression referenced by `handle` has side effects, it's evaluated only
    /// once on first call, stored in a local variable, and the variable cached
    /// and returned on subsequent calls.
    fn eval(&mut self, module: &Module, handle: ExprHandle) -> Result<String, ExprError>;

    /// Generate a unique local variable name.
    ///
    /// Each time this function is called, a new unique name is generated. The
    /// name is guaranteed to be unique within the current evaluation context
    /// only. Do not use for global top-level identifiers.
    ///
    /// The variable name is not registered automatically in the [`Module`]. If
    /// you call `make_local_var()` but doesn't use the returned name, it won't
    /// appear in the shader.
    fn make_local_var(&mut self) -> String;

    /// Push an intermediate statement during an evaluation.
    ///
    /// Intermediate statements are inserted before the expression evaluation
    /// which produced them. They're generally used to define temporary local
    /// variables, for example to store the result of expressions with side
    /// effects.
    fn push_stmt(&mut self, stmt: &str);

    /// Create a function.
    ///
    /// Create a new function with the given `func_name` inside the given
    /// [`Module`]. The function takes a list of arguments `args`, which are
    /// copied verbatim into the shader code without any validation. The body of
    /// the function is generated by invoking the given closure once with the
    /// input `module` and a temporary [`EvalContext`] local to the function.
    /// The closure must return the generated shader code of the function
    /// body. Any statement pushed to the temporary function context with
    /// [`EvalContext::push_stmt()`] is emitted inside the function body before
    /// the returned code. The function can subsequently be called from the
    /// parent context by generating code to call `func_name`, with the correct
    /// arguments.
    fn make_fn(
        &mut self,
        func_name: &str,
        args: &str,
        module: &mut Module,
        f: &mut dyn FnMut(&mut Module, &mut dyn EvalContext) -> Result<String, ExprError>,
    ) -> Result<(), ExprError>;

    /// Check if the particle attribute struct is a pointer?
    ///
    /// In some context the attribute struct (named 'particle' in WGSL code) is
    /// a pointer instead of being a struct instance. This happens in particular
    /// when defining a function for a modifier, and passing the attribute
    /// struct to be modified. In that case the generated code needs to emit
    /// a pointer indirection code to access the fields of the struct.
    fn is_attribute_pointer(&self) -> bool;
}

/// Language expression producing a value.
#[derive(Debug, Clone, Copy, PartialEq, Hash, Reflect, Serialize, Deserialize)]
pub enum Expr {
    /// Built-in expression ([`BuiltInExpr`]).
    ///
    /// A built-in expression provides access to some internal
    /// quantities like the simulation time.
    BuiltIn(BuiltInExpr),

    /// Literal expression ([`LiteralExpr`]).
    ///
    /// A literal expression represents a shader constants.
    Literal(LiteralExpr),

    /// Property expression ([`PropertyExpr`]).
    ///
    /// A property expression represents the value of an [`EffectAsset`]'s
    /// property.
    ///
    /// [`EffectAsset`]: crate::EffectAsset
    Property(PropertyExpr),

    /// Attribute expression ([`AttributeExpr`]).
    ///
    /// An attribute expression represents the value of an attribute for a
    /// particle, like its position or velocity.
    Attribute(AttributeExpr),

    /// Attribute expression ([`AttributeExpr`]) from a parent effect.
    ///
    /// An attribute expression represents the value of an attribute for a
    /// particle, like its position or velocity. This attribute however refers
    /// to the parent particle which spawned this one, via GPU events.
    ///
    /// This attribute is only valid when used in init modifiers, from an effect
    /// with a parent effect (an effect which has an [`EffectParent`]
    /// component).
    ///
    /// [`EffectParent`]: crate::EffectParent
    ParentAttribute(AttributeExpr),

    /// Unary operation expression.
    ///
    /// A unary operation transforms an expression into another expression.
    Unary {
        /// Unary operator.
        op: UnaryOperator,
        /// Operand the unary operation applies to.
        expr: ExprHandle,
    },

    /// Binary operation expression.
    ///
    /// A binary operation composes two expressions into a third one.
    Binary {
        /// Binary operator.
        op: BinaryOperator,
        /// Left-hand side operand the binary operation applies to.
        left: ExprHandle,
        /// Right-hand side operand the binary operation applies to.
        right: ExprHandle,
    },

    /// Ternary operation expression.
    ///
    /// A ternary operation composes three expressions into a fourth one.
    Ternary {
        /// Ternary operator.
        op: TernaryOperator,
        /// First operand the ternary operation applies to.
        first: ExprHandle,
        /// Second operand the ternary operation applies to.
        second: ExprHandle,
        /// Third operand the ternary operation applies to.
        third: ExprHandle,
    },

    /// Cast expression.
    ///
    /// An expression to cast an expression to another type.
    Cast(CastExpr),

    /// Access to textures.
    ///
    /// An expression to sample a texture from the effect's material. Currently
    /// only color textures (returning a `vec4<f32>`) are supported.
    TextureSample(TextureSampleExpr),
}

impl Expr {
    /// Is the expression resulting in a compile-time constant which can be
    /// hard-coded into a shader's code?
    ///
    /// The [`Module`] passed as argument is the owning module of the
    /// expression, which is used to recursively evaluate the const-ness of the
    /// entire expression. For some expressions like literals or attributes or
    /// properties their const-ness is intrinsic to the expression type, but for
    /// other expressions like binary operations (addition, ...) their
    /// const-ness depends in turn on the const-ness of their sub-expressions
    /// (left and right operands), which requires a [`Module`] to be retrieved
    /// and evaluated.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # let mut module = Module::default();
    /// // Literals are always constant by definition.
    /// assert!(Expr::Literal(LiteralExpr::new(1.)).is_const(&module));
    ///
    /// // Properties and attributes are never constant, since they're by definition used
    /// // to provide runtime customization.
    /// let prop = module.add_property("my_property", 3.0.into());
    /// assert!(!Expr::Property(PropertyExpr::new(prop)).is_const(&module));
    /// assert!(!Expr::Attribute(AttributeExpr::new(Attribute::POSITION)).is_const(&module));
    /// ```
    pub fn is_const(&self, module: &Module) -> bool {
        match self {
            Expr::BuiltIn(expr) => expr.is_const(),
            Expr::Literal(expr) => expr.is_const(),
            Expr::Property(expr) => expr.is_const(),
            Expr::Attribute(expr) => expr.is_const(),
            Expr::ParentAttribute(expr) => expr.is_const(),
            Expr::Unary { expr, .. } => module.is_const(*expr),
            Expr::Binary { left, right, .. } => module.is_const(*left) && module.is_const(*right),
            Expr::Ternary {
                first,
                second,
                third,
                ..
            } => module.is_const(*first) && module.is_const(*second) && module.is_const(*third),
            Expr::Cast(expr) => module.is_const(expr.inner),
            Expr::TextureSample(_) => false,
        }
    }

    /// Has the expression any side-effect?
    ///
    /// Expressions with side-effect need to be stored into temporary variables
    /// when the shader code is emitted, so that the side effect is only applied
    /// once when the expression is reused in multiple locations.
    pub fn has_side_effect(&self, _: &Module) -> bool {
        match self {
            Expr::BuiltIn(expr) => expr.has_side_effect(),
            Expr::Literal(_) => false,
            Expr::Property(_) => false,
            Expr::Attribute(_) => false,
            Expr::ParentAttribute(_) => false,
            Expr::Unary { .. } => false,
            Expr::Binary { op, .. } => {
                *op == BinaryOperator::UniformRand || *op == BinaryOperator::NormalRand
            }
            Expr::Ternary { .. } => false,
            Expr::Cast(_) => false,
            Expr::TextureSample(_) => false,
        }
    }

    /// The type of the value produced by the expression.
    ///
    /// If the type is variable and depends on the runtime evaluation context,
    /// this returns `None`. In that case the type needs to be obtained by
    /// evaluating the expression with [`eval()`].
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// // Literal expressions always have a constant, build-time value type.
    /// let expr = Expr::Literal(LiteralExpr::new(1.));
    /// assert_eq!(
    ///     expr.value_type(),
    ///     Some(ValueType::Scalar(ScalarType::Float))
    /// );
    /// ```
    ///
    /// [`eval()`]: crate::graph::Expr::eval
    pub fn value_type(&self) -> Option<ValueType> {
        match self {
            Expr::BuiltIn(expr) => Some(expr.value_type()),
            Expr::Literal(expr) => Some(expr.value_type()),
            Expr::Property(_) => None,
            Expr::Attribute(expr) => Some(expr.value_type()),
            Expr::ParentAttribute(expr) => Some(expr.value_type()),
            Expr::Unary { .. } => None,
            Expr::Binary { .. } => None,
            Expr::Ternary { .. } => None,
            Expr::Cast(expr) => Some(expr.value_type()),
            Expr::TextureSample(expr) => Some(expr.value_type()),
        }
    }

    /// Evaluate the expression in the given context.
    ///
    /// Evaluate the full expression as part of the given evaluation context,
    /// returning the WGSL string representation of the expression on success.
    ///
    /// The evaluation context is used to resolve some quantities related to the
    /// effect asset, like its properties. It also holds the [`Module`] that the
    /// expression is part of, to allow resolving sub-expressions of operators.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// let mut module = Module::default();
    /// # let pl = PropertyLayout::empty();
    /// # let pal = ParticleLayout::default();
    /// # let mut context = ShaderWriter::new(ModifierContext::Update, &pl, &pal);
    /// let handle = module.lit(1.);
    /// let expr = module.get(handle).unwrap();
    /// assert_eq!(Ok("1.".to_string()), expr.eval(&module, &mut context));
    /// ```
    pub fn eval(
        &self,
        module: &Module,
        context: &mut dyn EvalContext,
    ) -> Result<String, ExprError> {
        match self {
            Expr::BuiltIn(expr) => expr.eval(context),
            Expr::Literal(expr) => expr.eval(context),
            Expr::Property(expr) => expr.eval(module, context),
            Expr::Attribute(expr) => expr.eval(context, false),
            Expr::ParentAttribute(expr) => expr.eval(context, true),
            Expr::Unary { op, expr } => {
                // Recursively evaluate child expressions throught the context to ensure caching
                let expr = context.eval(module, *expr)?;

                // if expr.value_type() != self.value_type() {
                //     return Err(ExprError::TypeError(format!(
                //         "Cannot apply normalize() function to non-vector expression: {}",
                //         expr.unwrap_or("(error evaluating expression)".to_string())
                //     )));
                // }

                Ok(if op.is_functional() {
                    format!("{}({})", op.to_wgsl_string(), expr)
                } else {
                    format!("{}.{}", expr, op.to_wgsl_string())
                })
            }
            Expr::Binary { op, left, right } => {
                // Recursively evaluate child expressions throught the context to ensure caching
                let compiled_left = context.eval(module, *left)?;
                let compiled_right = context.eval(module, *right)?;

                // if !self.input.value_type().is_vector() {
                //     return Err(ExprError::TypeError(format!(
                //         "Cannot apply normalize() function to non-vector expression: {}",
                //         expr.unwrap_or("(error evaluating expression)".to_string())
                //     )));
                // }

                let body = if op.is_functional() {
                    if op.needs_type_suffix() {
                        let lhs_type = module.get(*left).and_then(|arg| arg.value_type());
                        let rhs_type = module.get(*right).and_then(|arg| arg.value_type());
                        if lhs_type.is_none() || rhs_type.is_none() {
                            return Err(ExprError::TypeError(
                                "Can't determine the type of the operand".to_string(),
                            ));
                        }
                        if lhs_type != rhs_type {
                            return Err(ExprError::TypeError("Mismatched types".to_string()));
                        }
                        let value_type = lhs_type.unwrap();
                        let suffix = match value_type {
                            ValueType::Scalar(ScalarType::Float) => "f",
                            ValueType::Vector(vector_type)
                                if vector_type.elem_type() == ScalarType::Float =>
                            {
                                match vector_type.count() {
                                    2 => "vec2",
                                    3 => "vec3",
                                    4 => "vec4",
                                    _ => unreachable!(),
                                }
                            }
                            _ => {
                                // Add more types here as needed.
                                return Err(ExprError::TypeError("Unsupported type".to_string()));
                            }
                        };

                        Ok(format!(
                            "{}_{}({}, {})",
                            op.to_wgsl_string(),
                            suffix,
                            compiled_left,
                            compiled_right
                        ))
                    } else {
                        Ok(format!(
                            "{}({}, {})",
                            op.to_wgsl_string(),
                            compiled_left,
                            compiled_right
                        ))
                    }
                } else {
                    Ok(format!(
                        "({}) {} ({})",
                        compiled_left,
                        op.to_wgsl_string(),
                        compiled_right
                    ))
                };

                body.map(|body| {
                    check_side_effects_and_create_local_if_needed(
                        context,
                        body,
                        self.has_side_effect(module),
                    )
                })
            }
            Expr::Ternary {
                op,
                first,
                second,
                third,
            } => {
                // Recursively evaluate child expressions throught the context to ensure caching
                let first = context.eval(module, *first)?;
                let second = context.eval(module, *second)?;
                let third = context.eval(module, *third)?;

                // if !self.input.value_type().is_vector() {
                //     return Err(ExprError::TypeError(format!(
                //         "Cannot apply normalize() function to non-vector expression: {}",
                //         expr.unwrap_or("(error evaluating expression)".to_string())
                //     )));
                // }

                Ok(format!(
                    "{}({}, {}, {})",
                    op.to_wgsl_string(),
                    first,
                    second,
                    third
                ))
            }
            Expr::Cast(expr) => {
                // Recursively evaluate child expressions throught the context to ensure caching
                let inner = context.eval(module, expr.inner)?;

                Ok(format!("{}({})", expr.target.to_wgsl_string(), inner))
            }
            Expr::TextureSample(expr) => expr.eval(module, context),
        }
    }
}

/// A literal constant expression like `3.0` or `vec3<f32>(1.0, 2.0, 3.0)`.
///
/// Literal expression are compile-time constants. They are always constant
/// ([`is_const()`] is `true`) and have a value type equal to the type of the
/// constant itself.
///
/// [`is_const()`]: LiteralExpr::is_const
#[derive(Debug, Clone, Copy, PartialEq, Hash, Reflect, Serialize, Deserialize)]
#[serde(transparent)]
pub struct LiteralExpr {
    /// The literal value of this expression.
    pub value: Value,
}

impl LiteralExpr {
    /// Create a new literal expression from a [`Value`].
    pub fn new<V>(value: V) -> Self
    where
        Value: From<V>,
    {
        Self {
            value: value.into(),
        }
    }

    /// Is the expression resulting in a compile-time constant which can be
    /// hard-coded into a shader's code?
    pub fn is_const(&self) -> bool {
        true
    }

    /// Get the value type of the expression.
    pub fn value_type(&self) -> ValueType {
        self.value.value_type()
    }

    /// Evaluate the expression in the given context.
    pub fn eval(&self, _context: &dyn EvalContext) -> Result<String, ExprError> {
        Ok(self.value.to_wgsl_string())
    }
}

impl ToWgslString for LiteralExpr {
    fn to_wgsl_string(&self) -> String {
        self.value.to_wgsl_string()
    }
}

impl From<&Value> for LiteralExpr {
    fn from(value: &Value) -> Self {
        Self { value: *value }
    }
}

impl<T: Into<Value>> From<T> for LiteralExpr {
    fn from(value: T) -> Self {
        Self {
            value: value.into(),
        }
    }
}

/// Expression representing the value of an attribute of a particle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
pub struct AttributeExpr {
    /// The attribute this expression represents.
    ///
    /// The expression evaluates to the value of this attribute at the time of
    /// evaluation.
    pub attr: Attribute,
}

impl AttributeExpr {
    /// Create a new attribute expression.
    #[inline]
    pub fn new(attr: Attribute) -> Self {
        Self { attr }
    }

    /// Is the expression resulting in a compile-time constant which can be
    /// hard-coded into a shader's code?
    pub fn is_const(&self) -> bool {
        false
    }

    /// Get the value type of the expression.
    pub fn value_type(&self) -> ValueType {
        self.attr.value_type()
    }

    /// Evaluate the expression in the given context.
    pub fn eval(&self, context: &dyn EvalContext, parent: bool) -> Result<String, ExprError> {
        if self.attr == Attribute::ID {
            // Pseudo-attribute, not stored in the particle buffer
            Ok(if parent {
                "parent_particle_index"
            } else {
                "particle_index"
            }
            .to_string())
        } else if self.attr == Attribute::PARTICLE_COUNTER {
            // Pseudo-attribute, not stored in the particle buffer
            Ok("particle_counter".to_string())
        } else {
            let owner = if parent {
                "parent_particle"
            } else {
                "particle"
            };
            if context.is_attribute_pointer() {
                Ok(format!("(*{}).{}", owner, self.attr.name()))
            } else {
                Ok(format!("{}.{}", owner, self.attr.name()))
            }
        }
    }
}

impl ToWgslString for AttributeExpr {
    fn to_wgsl_string(&self) -> String {
        format!("particle.{}", self.attr.name())
    }
}

impl From<Attribute> for AttributeExpr {
    fn from(value: Attribute) -> Self {
        AttributeExpr::new(value)
    }
}

/// Expression representing the value of a property of an effect.
///
/// A property expression represents the value of the property at the time the
/// expression appears. In shader, the expression yields a read from the
/// property memory location.
///
/// To create a property to reference with an expression, use
/// [`Module::add_property()`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
#[repr(transparent)]
#[serde(transparent)]
pub struct PropertyExpr {
    /// The property this expression represents.
    ///
    /// The expression evaluates to the value of this property at the time of
    /// evaluation.
    pub property: PropertyHandle,
}

impl PropertyExpr {
    /// Create a new property expression.
    #[inline]
    pub fn new(property: PropertyHandle) -> Self {
        Self { property }
    }

    /// Is the expression resulting in a compile-time constant which can be
    /// hard-coded into a shader's code?
    pub fn is_const(&self) -> bool {
        false
    }

    /// Evaluate the expression in the given context.
    pub fn eval(&self, module: &Module, context: &dyn EvalContext) -> Result<String, ExprError> {
        let prop = module
            .get_property(self.property)
            .ok_or(ExprError::PropertyError(format!(
                "Unknown property handle {:?} in evaluation module.",
                self.property
            )))?;
        if !context.property_layout().contains(prop.name()) {
            return Err(ExprError::PropertyError(format!(
                "Unknown property '{}' in evaluation layout.",
                prop.name()
            )));
        }

        Ok(prop.to_wgsl_string())
    }
}

/// Expression to cast an expression to another type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
pub struct CastExpr {
    /// The operand expression to cast.
    pub inner: ExprHandle,
    /// The target type to cast to.
    pub target: ValueType,
}

impl CastExpr {
    /// Create a new cast expression.
    #[inline]
    pub fn new(inner: ExprHandle, target: impl Into<ValueType>) -> Self {
        Self {
            inner,
            target: target.into(),
        }
    }

    /// Get the value type of the expression.
    ///
    /// This is the target type the cast converts to.
    pub fn value_type(&self) -> ValueType {
        self.target
    }

    /// Try to evaluate if the cast expression is valid.
    ///
    /// The evaluation fails if the value type of the operand cannot be
    /// determined. In that case, the function returns `None`. This doesn't mean
    /// the cast expression is invalid, but rather that we cannot currently
    /// evaluate it, as it likely depends on the runtime context in which it's
    /// used.
    ///
    /// Valid cast expressions are:
    /// - scalar to scalar
    /// - scalar to vector
    /// - vector to vector
    /// - matrix to matrix
    ///
    /// # Returns
    ///
    /// - `Some(is_valid)` if the evaluation was successful in determining
    ///   whether the expression is valid or not.
    /// - `None` if the expression couldn't be evaluated, and so couldn't be
    ///   validated. This generally happens when the inner expression has a
    ///   value type unknown statically (depends on runtime context), which
    ///   prevents evaluating whether the cast expression is valid.
    pub fn is_valid(&self, module: &Module) -> Option<bool> {
        let Some(inner) = module.get(self.inner) else {
            return Some(false);
        };
        if let Some(inner_type) = inner.value_type() {
            match self.target {
                ValueType::Scalar(_) => {
                    // scalar -> scalar only
                    Some(matches!(inner_type, ValueType::Scalar(_)))
                }
                ValueType::Vector(_) => {
                    // {scalar, vector} -> vector
                    Some(!matches!(inner_type, ValueType::Matrix(_)))
                }
                ValueType::Matrix(_) => {
                    // matrix -> matrix only
                    Some(matches!(inner_type, ValueType::Matrix(_)))
                }
            }
        } else {
            None
        }
    }
}

/// Expression to sample a texture from the effect's material.
///
/// This currently supports only 4-component textures sampled with [the WGSL
/// `textureSample()` function], that is all textures which return a `vec4<f32>`
/// when sampled. This is the case of most color textures, including
/// single-channel (e.g. red) textures which return zero for missing components,
/// but excludes depth textures.
///
/// [the WGSL `textureSample()` function]: https://www.w3.org/TR/WGSL/#texturesample
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
pub struct TextureSampleExpr {
    /// The index of the image to sample. This is the texture slot defined in
    /// the [`Module`]. The texture bound to the slot is defined in the
    /// [`EffectMaterial`] component.
    ///
    /// [`EffectMaterial`]: crate::EffectMaterial
    pub image: ExprHandle,
    /// The coordinates to sample at.
    pub coordinates: ExprHandle,
}

impl TextureSampleExpr {
    /// Create a new texture sample expression.
    #[inline]
    pub fn new(image: ExprHandle, coordinates: ExprHandle) -> Self {
        Self { image, coordinates }
    }

    /// Get the value type of the expression.
    pub fn value_type(&self) -> ValueType {
        // FIXME - depth textures return a single f32 when sampled
        ValueType::Vector(VectorType::VEC4F)
    }

    /// Try to evaluate if the texture sample expression is valid.
    ///
    /// This only checks that the expressions exist in the module.
    pub fn is_valid(&self, module: &Module) -> Option<bool> {
        let Some(_image) = module.get(self.image) else {
            return Some(false);
        };
        let Some(_coordinates) = module.get(self.coordinates) else {
            return Some(false);
        };
        Some(true)
    }

    /// Evaluate the expression in the given context.
    pub fn eval(
        &self,
        module: &Module,
        context: &mut dyn EvalContext,
    ) -> Result<String, ExprError> {
        let image = module.try_get(self.image)?;
        let image = image.eval(module, context)?;
        let coordinates = module.try_get(self.coordinates)?;
        let coordinates = coordinates.eval(module, context)?;
        Ok(format!(
            "textureSample(material_texture_{image}, material_sampler_{image}, {coordinates})",
        ))
    }
}

/// Built-in operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
pub enum BuiltInOperator {
    /// Current effect system simulation time since startup, in seconds.
    ///
    /// This is based on the
    /// [`Time<EffectSimulation>`](crate::time::EffectSimulation) clock.
    ///
    /// Type: `f32`
    Time,
    /// Delta time, in seconds, since last effect system update.
    ///
    /// Type: `f32`
    DeltaTime,
    /// Current virtual time since startup, in seconds.
    ///
    /// This is based on the [`Time<Virtual>`](bevy::time::Virtual) clock.
    ///
    /// Type: `f32`
    VirtualTime,
    /// Virtual delta time, in seconds, since last effect system update.
    ///
    /// Type: `f32`
    VirtualDeltaTime,
    /// Current real time since startup, in seconds.
    ///
    /// This is based on the [`Time<Time>`](bevy::time::Real) clock.
    ///
    /// Type: `f32`
    RealTime,
    /// Real delta time, in seconds, since last effect system update.
    ///
    /// Type: `f32`
    RealDeltaTime,
    /// Random unit value of the given type.
    ///
    /// The type can be any scalar or vector type. Matrix types are not
    /// supported. The random values generated are uniformly distributed in
    /// `[0:1]`. For vectors, each component is sampled separately.
    ///
    /// The random number generator is from [the PCG family] of PRNGs, and is
    /// implemented directly inside the shader, and running on the GPU
    /// exclusively. It's seeded by the [`SpawnerSettings`].
    ///
    /// Type: Same as its [`ValueType`].
    ///
    /// [the PCG family]: https://www.pcg-random.org/
    /// [`SpawnerSettings`]: crate::SpawnerSettings
    Rand(ValueType),
    /// Value of the alpha cutoff for alpha masking.
    ///
    /// This value is only available in the render context. It represents the
    /// current threshold, generally in \[0:1\], which the particle's fragment
    /// alpha value will be compared against to determine alpha masking.
    ///
    /// The value is initalized at the beginning of the fragment shader to the
    /// expression stored in [`AlphaMode::Mask`].
    ///
    /// Type: `f32`
    ///
    /// [`AlphaMode::Mask`]: crate::AlphaMode::Mask
    AlphaCutoff,
    /// Alive flag for the particle.
    ///
    /// The alive flag is initialized at the beginning of the update pass:
    /// - If the particle has both the [`Attribute::AGE`] and
    ///   [`Attribute::LIFETIME`], then the initial value at the beginning of
    ///   the update pass is `age < lifetime`.
    /// - Otherwise, the initial value is `true`.
    ///
    /// At the end of the update pass, if the particle has both the
    /// [`Attribute::AGE`] and [`Attribute::LIFETIME`], then the flag is
    /// re-evaluated as:
    ///
    /// ```wgsl
    /// is_alive = is_alive && (particle.age < particle.lifetime);
    /// ```
    ///
    /// If the flag is `false` after that, the particle is considered dead and
    /// it's deallocated.
    ///
    /// This flag is only available in the update pass. Attempting to use it
    /// inside either the init or render passes will generate an invalid shader.
    ///
    /// Type: `bool`
    IsAlive,
}

impl BuiltInOperator {
    /// Get the operator name.
    pub fn name(&self) -> &str {
        match self {
            BuiltInOperator::Time => "time",
            BuiltInOperator::DeltaTime => "delta_time",
            BuiltInOperator::VirtualTime => "virtual_time",
            BuiltInOperator::VirtualDeltaTime => "virtual_delta_time",
            BuiltInOperator::RealTime => "real_time",
            BuiltInOperator::RealDeltaTime => "real_delta_time",
            BuiltInOperator::Rand(value_type) => match value_type {
                ValueType::Scalar(s) => match s {
                    ScalarType::Bool => "brand",
                    ScalarType::Float => "frand",
                    ScalarType::Int => "irand",
                    ScalarType::Uint => "urand",
                },
                ValueType::Vector(vector_type) => {
                    match (vector_type.elem_type(), vector_type.count()) {
                        (ScalarType::Bool, 2) => "brand2",
                        (ScalarType::Bool, 3) => "brand3",
                        (ScalarType::Bool, 4) => "brand4",
                        (ScalarType::Float, 2) => "frand2",
                        (ScalarType::Float, 3) => "frand3",
                        (ScalarType::Float, 4) => "frand4",
                        (ScalarType::Int, 2) => "irand2",
                        (ScalarType::Int, 3) => "irand3",
                        (ScalarType::Int, 4) => "irand4",
                        (ScalarType::Uint, 2) => "urand2",
                        (ScalarType::Uint, 3) => "urand3",
                        (ScalarType::Uint, 4) => "urand4",
                        _ => panic!("Invalid vector type {:?}", vector_type),
                    }
                }
                ValueType::Matrix(_) => panic!("Invalid BuiltInOperator::Rand(ValueType::Matrix)."),
            },
            BuiltInOperator::AlphaCutoff => "alpha_cutoff",
            BuiltInOperator::IsAlive => "is_alive",
        }
    }

    /// Get the type of the value of a built-in operator.
    pub fn value_type(&self) -> ValueType {
        match self {
            BuiltInOperator::Time => ValueType::Scalar(ScalarType::Float),
            BuiltInOperator::DeltaTime => ValueType::Scalar(ScalarType::Float),
            BuiltInOperator::VirtualTime => ValueType::Scalar(ScalarType::Float),
            BuiltInOperator::VirtualDeltaTime => ValueType::Scalar(ScalarType::Float),
            BuiltInOperator::RealTime => ValueType::Scalar(ScalarType::Float),
            BuiltInOperator::RealDeltaTime => ValueType::Scalar(ScalarType::Float),
            BuiltInOperator::Rand(value_type) => *value_type,
            BuiltInOperator::AlphaCutoff => ValueType::Scalar(ScalarType::Float),
            BuiltInOperator::IsAlive => ValueType::Scalar(ScalarType::Bool),
        }
    }

    // /// Evaluate the result of the operator as an expression.
    // pub fn eval(&self, _context: &dyn EvalContext) -> Result<String, ExprError> {
    //     match self {
    //         BuiltInOperator::Time => Value::Scalar(Scal)
    //     }
    // }
}

impl ToWgslString for BuiltInOperator {
    fn to_wgsl_string(&self) -> String {
        match self {
            BuiltInOperator::Rand(_) => format!("{}()", self.name()),
            BuiltInOperator::IsAlive => "is_alive".to_string(),
            _ => format!("sim_params.{}", self.name()),
        }
    }
}

/// Expression for getting built-in quantities related to the effect system.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
pub struct BuiltInExpr {
    /// The built-in operator this expression represents.
    ///
    /// The expression evaluates to the value of this built-in operator at the
    /// time of evaluation.
    pub operator: BuiltInOperator,
}

impl BuiltInExpr {
    /// Create a new built-in operator expression.
    ///
    /// # Panics
    ///
    /// Panics on invalid [`BuiltInOperator`], like `Rand(MatrixType)`. See
    /// each [`BuiltInOperator`] variant for more details.
    #[inline]
    pub fn new(operator: BuiltInOperator) -> Self {
        if let BuiltInOperator::Rand(value_type) = operator {
            assert!(!matches!(value_type, ValueType::Matrix(_)));
        }
        Self { operator }
    }

    /// Is the expression resulting in a compile-time constant?
    ///
    /// Constant expressions can be hard-coded into a shader's code, making them
    /// more efficient and open to shader compiler optimizing.
    pub fn is_const(&self) -> bool {
        false
    }

    /// Has the expression any side-effect?
    ///
    /// Expressions with side-effect need to be stored into temporary variables
    /// when the shader code is emitted, so that the side effect is only applied
    /// once when the expression is reused in multiple locations.
    pub fn has_side_effect(&self) -> bool {
        matches!(self.operator, BuiltInOperator::Rand(_))
    }

    /// Get the value type of the expression.
    ///
    /// The value type of the expression is the type of the value(s) that an
    /// expression produces.
    pub fn value_type(&self) -> ValueType {
        self.operator.value_type()
    }

    /// Evaluate the expression in the given context.
    pub fn eval(&self, context: &mut dyn EvalContext) -> Result<String, ExprError> {
        Ok(check_side_effects_and_create_local_if_needed(
            context,
            self.to_wgsl_string(),
            self.has_side_effect(),
        ))
    }
}

impl ToWgslString for BuiltInExpr {
    fn to_wgsl_string(&self) -> String {
        self.operator.to_wgsl_string()
    }
}

/// Creates a local variable if necessary to avoid evaluating side-effecting
/// expressions multiple times.
///
/// If `has_side_effect` is true, this function creates a local variable within
/// the [`EvalContext`] and stores the `compiled_code` there. Otherwise, it
/// simply returns `compiled_code` unchanged.
fn check_side_effects_and_create_local_if_needed(
    context: &mut dyn EvalContext,
    compiled_code: String,
    has_side_effect: bool,
) -> String {
    if has_side_effect {
        let var_name = context.make_local_var();
        context.push_stmt(&format!("let {} = {};", var_name, compiled_code));
        var_name
    } else {
        compiled_code
    }
}

/// Unary operator.
///
/// Operator applied to a single operand to produce another value. The type of
/// the operand and the result are not necessarily the same. Valid operand types
/// depend on the operator itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
pub enum UnaryOperator {
    /// Absolute value operator.
    ///
    /// Return the absolute value of the operand, component-wise for vectors.
    /// Only valid for numeric operands.
    Abs,

    /// Inverse cosine operator.
    ///
    /// Return the inverse cosine of the operand, component-wise for vectors.
    /// Only valid for floating-point operands.
    Acos,

    /// Inverse sine operator.
    ///
    /// Return the inverse sine of the operand, component-wise for vectors.
    /// Only valid for floating-point operands.
    Asin,

    /// Inverse tangent operator.
    ///
    /// Return the inverse tangent of the operand, component-wise for vectors.
    /// Only valid for floating-point operands.
    Atan,

    /// Logical ALL operator for bool vectors.
    ///
    /// Return `true` if all the components of the bool vector operand are
    /// `true`. Invalid for any other type of operand.
    All,

    /// Logical ANY operator for bool vectors.
    ///
    /// Return `true` if any component of the bool vector operand is `true`.
    /// Invalid for any other type of operand.
    Any,

    /// Ceiling operator.
    ///
    /// Return the unique integral number `k` such that `k-1 < x <= k`, where
    /// `x` is the operand which the operator applies to.
    Ceil,

    /// Cosine operator.
    Cos,

    /// Natural exponent operator.
    ///
    /// Return the natural exponentiation of the operand (`e^x`), component-wise
    /// for vectors.
    Exp,

    /// Base-2 exponent operator.
    ///
    /// Return two raised to the power of the operand (`2^x`), component-wise
    /// for vectors.
    Exp2,

    /// Floor operator.
    ///
    /// Return the unique integral number `k` such that `k <= x < k+1`, where
    /// `x` is the operand which the operator applies to.
    Floor,

    /// Fractional part operator.
    ///
    /// Return the fractional part of the operand, which is equal to `x -
    /// floor(x)`, component-wise for vectors.
    Fract,

    /// Inverse square root operator.
    ///
    /// Return the inverse square root of the floating-point operand (`1.0 /
    /// sqrt(x)`), component-wise for vectors.
    InvSqrt,

    /// Length operator.
    ///
    /// Return the length of a floating point scalar or vector. The "length" of
    /// a scalar is taken as its absolute value. The length of a vector is the
    /// Euclidian distance `sqrt(x^2 + ...)` (square root of the sum of the
    /// squared components).
    ///
    /// The output is always a floating point scalar.
    Length,

    /// Natural logarithm operator.
    ///
    /// Return the natural logarithm of the operand (`log(x)`), component-wise
    /// for vectors.
    Log,

    /// Base-2 logarithm operator.
    ///
    /// Return the base-2 logarithm of the operand (`log2(x)`), component-wise
    /// for vectors.
    Log2,

    /// Vector normalizing operator.
    ///
    /// Normalize the given numeric vector. Only valid for numeric vector
    /// operands.
    Normalize,

    /// Packing operator from `vec4<f32>` to `u32` (signed normalized).
    ///
    /// Convert the four components of a signed normalized floating point vector
    /// into a signed integral `i8` value in `[-128:127]`, then pack those
    /// four values into a single `u32`. Each vector component should be in
    /// `[-1:1]` before packing; values outside this range are clamped.
    Pack4x8snorm,

    /// Packing operator from `vec4<f32>` to `u32` (unsigned normalized).
    ///
    /// Convert the four components of an unsigned normalized floating point
    /// vector into an unsigned integral `u8` value in `[0:255]`, then pack
    /// those four values into a single `u32`. Each vector component should
    /// be in `[0:1]` before packing; values outside this range are clamped.
    Pack4x8unorm,

    /// Rounding operator.
    ///
    /// Round the given scalar of vector float to the nearest integer, returned
    /// as a float value.
    Round,

    /// Saturate operator.
    ///
    /// Clamp the value of the operand to the \[0:1\] range, component-wise for
    /// vectors.
    Saturate,

    /// Sign operator.
    ///
    /// Return a value representing the sign of a floating point scalar or
    /// vector input:
    /// - `1.` if the operand is > 0
    /// - `0.` if the operand is = 0
    /// - `-1.` if the operand is < 0
    ///
    /// Applies component-wise for vectors.
    Sign,

    /// Sine operator.
    Sin,

    /// Square root operator.
    ///
    /// Return the square root of the floating-point operand, component-wise for
    /// vectors.
    Sqrt,

    /// Tangent operator.
    Tan,

    /// Unpacking operator from `u32` to `vec4<f32>` (signed normalized).
    ///
    /// Unpack the `u32` into four signed integral `i8` value in `[-128:127]`,
    /// then convert each value to a signed normalized `f32` value in `[-1:1]`.
    Unpack4x8snorm,

    /// Unpacking operator from `u32` to `vec4<f32>` (unsigned normalized).
    ///
    /// Unpack the `u32` into four unsigned integral `u8` value in `[0:255]`,
    /// then convert each value to an unsigned normalized `f32` value in
    /// `[0:1]`.
    Unpack4x8unorm,

    /// Get the fourth component of a vector.
    ///
    /// This is only valid for vectors of rank 4.
    W,

    /// Get the first component of a scalar or vector.
    ///
    /// For scalar, return the value itself. For vectors, return the first
    /// component.
    X,

    /// Get the second component of a vector.
    Y,

    /// Get the third component of a vector.
    ///
    /// This is only valid for vectors of rank 3 or more.
    Z,
}

impl UnaryOperator {
    /// Check if a unary operator is called via a functional-style call.
    ///
    /// Functional-style calls are in the form `op(inner)`, like `abs(x)` for
    /// example, while non-functional ones are in the form `inner.op`,
    /// like `v.x` for example. This check is used for formatting the WGSL
    /// code emitted during evaluation of a binary operation expression.
    pub fn is_functional(&self) -> bool {
        !matches!(
            *self,
            UnaryOperator::X | UnaryOperator::Y | UnaryOperator::Z | UnaryOperator::W
        )
    }
}

impl ToWgslString for UnaryOperator {
    fn to_wgsl_string(&self) -> String {
        match *self {
            UnaryOperator::Abs => "abs".to_string(),
            UnaryOperator::Acos => "acos".to_string(),
            UnaryOperator::Asin => "asin".to_string(),
            UnaryOperator::Atan => "atan".to_string(),
            UnaryOperator::All => "all".to_string(),
            UnaryOperator::Any => "any".to_string(),
            UnaryOperator::Ceil => "ceil".to_string(),
            UnaryOperator::Cos => "cos".to_string(),
            UnaryOperator::Exp => "exp".to_string(),
            UnaryOperator::Exp2 => "exp2".to_string(),
            UnaryOperator::Floor => "floor".to_string(),
            UnaryOperator::Fract => "fract".to_string(),
            UnaryOperator::InvSqrt => "inverseSqrt".to_string(),
            UnaryOperator::Length => "length".to_string(),
            UnaryOperator::Log => "log".to_string(),
            UnaryOperator::Log2 => "log2".to_string(),
            UnaryOperator::Normalize => "normalize".to_string(),
            UnaryOperator::Pack4x8snorm => "pack4x8snorm".to_string(),
            UnaryOperator::Pack4x8unorm => "pack4x8unorm".to_string(),
            UnaryOperator::Round => "round".to_string(),
            UnaryOperator::Saturate => "saturate".to_string(),
            UnaryOperator::Sign => "sign".to_string(),
            UnaryOperator::Sin => "sin".to_string(),
            UnaryOperator::Sqrt => "sqrt".to_string(),
            UnaryOperator::Tan => "tan".to_string(),
            UnaryOperator::Unpack4x8snorm => "unpack4x8snorm".to_string(),
            UnaryOperator::Unpack4x8unorm => "unpack4x8unorm".to_string(),
            UnaryOperator::W => "w".to_string(),
            UnaryOperator::X => "x".to_string(),
            UnaryOperator::Y => "y".to_string(),
            UnaryOperator::Z => "z".to_string(),
        }
    }
}

/// Binary operator.
///
/// Operator applied between two operands, generally denoted "left" and "right".
/// The type of the operands and the result are not necessarily the same. Valid
/// operand types depend on the operator itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
pub enum BinaryOperator {
    /// Addition operator.
    ///
    /// Returns the sum of its operands. Only valid for numeric operands.
    Add,

    /// Inverse tangent operator with 2 arguments.
    ///
    /// Returns the arctangent (inverse tangent) of the ratio of the first
    /// argument divided by the second argument.
    Atan2,

    /// Cross product operator.
    ///
    /// Returns the cross product of the left and right operands. Only valid for
    /// vector type operands of size 3. Always produce a vector result of the
    /// same size.
    Cross,

    /// Distance operator.
    ///
    /// Returns the distance between two floating point scalar or vectors, that
    /// is `length(right - left)`.
    Distance,

    /// Division operator.
    ///
    /// Returns the left operand divided by the right operand. Only valid for
    /// numeric operands.
    Div,

    /// Dot product operator.
    ///
    /// Returns the dot product of the left and right operands. Only valid for
    /// vector type operands. Always produce a scalar floating-point result.
    Dot,

    /// Greater-than operator.
    ///
    /// Returns `true` if the left operand is strictly greater than the right
    /// operand. Only valid for numeric types. If the operands are vectors,
    /// they must be of the same rank, and the result is a bool vector of
    /// that rank.
    GreaterThan,

    /// Greater-than-or-equal operator.
    ///
    /// Returns `true` if the left operand is greater than or equal to the right
    /// operand. Only valid for numeric types. If the operands are vectors,
    /// they must be of the same rank, and the result is a bool vector of
    /// that rank.
    GreaterThanOrEqual,

    /// Less-than operator.
    ///
    /// Returns `true` if the left operand is strictly less than the right
    /// operand. Only valid for numeric types. If the operands are vectors,
    /// they must be of the same rank, and the result is a bool vector of
    /// that rank.
    LessThan,

    /// Less-than-or-equal operator.
    ///
    /// Returns `true` if the left operand is less than or equal to the right
    /// operand. Only valid for numeric types. If the operands are vectors,
    /// they must be of the same rank, and the result is a bool vector of
    /// that rank.
    LessThanOrEqual,

    /// Maximum operator.
    ///
    /// Returns the maximum value of its left and right operands. Only valid for
    /// numeric types. If the operands are vectors, they must be of the same
    /// rank, and the result is a vector of that rank and same element
    /// scalar type.
    Max,

    /// Minimum operator.
    ///
    /// Returns the minimum value of its left and right operands. Only valid for
    /// numeric types. If the operands are vectors, they must be of the same
    /// rank, and the result is a vector of that rank and same element
    /// scalar type.
    Min,

    /// Multiply operator.
    ///
    /// Returns the product of its operands. Only valid for numeric operands.
    Mul,

    /// Remainder operator.
    ///
    /// Returns the remainder of the division of the first operand by the
    /// second. Only valid for numeric types. If the operands are vectors,
    /// they must be of the same rank, and the result is a vector of that
    /// rank and same element scalar type.
    Remainder,

    /// Stepping operator.
    ///
    /// Returns `1.0` if the left operand is less than or equal to the right
    /// operand, or `0.0` otherwise. Only valid for floating scalar or vectors
    /// of the same rank, and applied component-wise for vectors.
    Step,

    /// Subtraction operator.
    ///
    /// Returns the difference between its left and right operands. Only valid
    /// for numeric operands.
    Sub,

    /// Uniform random number operator.
    ///
    /// Returns a value generated by a fast non-cryptographically-secure
    /// pseudo-random number generator (PRNG) whose statistical characteristics
    /// are undefined and generally focused around speed. The random value is
    /// uniformly distributed between the left and right operands, which must be
    /// numeric types. If the operands are vectors, they must be of the same
    /// rank, and the result is a vector of that rank and same element
    /// scalar type.
    UniformRand,

    /// Normal distribution random number operator.
    ///
    /// Returns a value generated by a fast non-cryptographically-secure
    /// pseudo-random number generator (PRNG) whose statistical characteristics
    /// are undefined and generally focused around speed. The random value is
    /// normally distributed with mean given by the first operand and standard
    /// deviation by the second, which must be numeric types. If the operands
    /// are vectors, they must be of the same rank, and the result is a vector
    /// of that rank and same element scalar type.
    NormalRand,

    /// Constructor for 2-element vectors.
    ///
    /// Given two scalar elements `x` and `y`, returns the vector consisting of
    /// those two elements `(x, y)`.
    Vec2,

    /// Constructor for a 4-element vector.
    ///
    /// Given a 3-element vector `xyz` and a scalar value `w`, returns the
    /// vector `vec4(xyz, w)`.
    Vec4XyzW,
}

impl BinaryOperator {
    /// Check if a binary operator is called via a functional-style call.
    ///
    /// Functional-style calls are in the form `op(lhs, rhs)`, like `min(a,
    /// b)` for example, while non-functional ones are in the form `lhs op rhs`,
    /// like `a + b` for example. This check is used for formatting the WGSL
    /// code emitted during evaluation of a binary operation expression.
    pub fn is_functional(&self) -> bool {
        match *self {
            BinaryOperator::Add
            | BinaryOperator::Div
            | BinaryOperator::GreaterThan
            | BinaryOperator::GreaterThanOrEqual
            | BinaryOperator::LessThan
            | BinaryOperator::LessThanOrEqual
            | BinaryOperator::Mul
            | BinaryOperator::Remainder
            | BinaryOperator::Sub => false,
            BinaryOperator::Atan2
            | BinaryOperator::Cross
            | BinaryOperator::Distance
            | BinaryOperator::Dot
            | BinaryOperator::Max
            | BinaryOperator::Min
            | BinaryOperator::Step
            | BinaryOperator::UniformRand
            | BinaryOperator::NormalRand
            | BinaryOperator::Vec2
            | BinaryOperator::Vec4XyzW => true,
        }
    }

    /// Check if a binary operator needs a type suffix.
    ///
    /// This is currently just for `rand_uniform`
    /// (`BinaryOperator::UniformRand`) and `rand_normal`
    /// (`BinaryOperator::NormalRand`), which are functions we define ourselves.
    /// WGSL doesn't support user-defined function overloading, so we need a
    /// suffix to disambiguate the types.
    pub fn needs_type_suffix(&self) -> bool {
        matches!(
            *self,
            BinaryOperator::UniformRand | BinaryOperator::NormalRand
        )
    }
}

impl ToWgslString for BinaryOperator {
    fn to_wgsl_string(&self) -> String {
        match *self {
            BinaryOperator::Add => "+".to_string(),
            BinaryOperator::Atan2 => "atan2".to_string(),
            BinaryOperator::Cross => "cross".to_string(),
            BinaryOperator::Distance => "distance".to_string(),
            BinaryOperator::Div => "/".to_string(),
            BinaryOperator::Dot => "dot".to_string(),
            BinaryOperator::GreaterThan => ">".to_string(),
            BinaryOperator::GreaterThanOrEqual => ">=".to_string(),
            BinaryOperator::LessThan => "<".to_string(),
            BinaryOperator::LessThanOrEqual => "<=".to_string(),
            BinaryOperator::Max => "max".to_string(),
            BinaryOperator::Min => "min".to_string(),
            BinaryOperator::Mul => "*".to_string(),
            BinaryOperator::Remainder => "%".to_string(),
            BinaryOperator::Step => "step".to_string(),
            BinaryOperator::Sub => "-".to_string(),
            BinaryOperator::UniformRand => "rand_uniform".to_string(),
            BinaryOperator::NormalRand => "rand_normal".to_string(),
            BinaryOperator::Vec2 => "vec2".to_string(),
            BinaryOperator::Vec4XyzW => "vec4".to_string(),
        }
    }
}

/// Ternary operator.
///
/// Operator applied between three operands. The type of the operands and the
/// result are not necessarily the same. Valid operand types depend on the
/// operator itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
pub enum TernaryOperator {
    /// Linear blend ("mix") operator.
    ///
    /// Returns the linear blend between the first and second argument, based on
    /// the fraction of the third argument. If the operands are vectors, they
    /// must be of the same rank, and the result is a vector of that rank
    /// and same element scalar type.
    ///
    /// The linear blend of `x` and `y` with fraction `t` is equivalent to `x *
    /// (1 - t) + y * t`.
    Mix,

    /// Clamp operator.
    ///
    /// Returns the first argument clamped to the range defined by the second
    /// and third arguments. If the operands are vectors, they must be of
    /// the same rank, and the result is a vector of that rank
    /// and same element scalar type.
    ///
    /// The expression `clamp(x, low, high)` is equivalent to `min(max(x, low),
    /// high)`.
    Clamp,

    /// Smooth stepping operator.
    ///
    /// Returns the smooth Hermitian interpolation between the first and second
    /// argument, calculated at the third argument. If the operands are vectors,
    /// they must be of the same rank, and the result is a vector of that
    /// rank and same element scalar type.
    ///
    /// The smooth stepping of `low` and `high` at position `x` is equivalent to
    /// `t * t * (3. - 2. * t)` where `t = clamp((x - low) / (high - low))`
    /// represents the fractional position of `x` between `low` and `high`.
    ///
    /// The result is always a floating point scalar in \[0:1\].
    SmoothStep,

    /// Constructor for 3-element vectors.
    ///
    /// Given three scalar elements `x`, `y`, and `z`, returns the vector
    /// consisting of those three elements `(x, y, z)`.
    Vec3,
}

impl ToWgslString for TernaryOperator {
    fn to_wgsl_string(&self) -> String {
        match *self {
            TernaryOperator::Mix => "mix".to_string(),
            TernaryOperator::Clamp => "clamp".to_string(),
            TernaryOperator::SmoothStep => "smoothstep".to_string(),
            TernaryOperator::Vec3 => "vec3".to_string(),
        }
    }
}

/// Expression writer.
///
/// Utility to write expressions with a simple functional syntax. Expressions
/// created with the writer are gatherned into a [`Module`] which can be
/// transfered once [`finish()`]ed to initialize an [`EffectAsset`].
///
/// Because an [`EffectAsset`] contains a single [`Module`], you generally want
/// to keep using the same [`ExprWriter`] to write all the expressions used by
/// all the [`Modifer`]s assigned to a given [`EffectAsset`], and only then once
/// done call [`finish()`] to recover the [`ExprWriter`]'s underlying [`Module`]
/// to assign it to the [`EffectAsset`].
///
/// # Example
///
/// ```
/// # use bevy_hanabi::*;
/// # use bevy::prelude::*;
/// // Create a writer
/// let w = ExprWriter::new();
///
/// // Create a new expression: max(5. + particle.position, properties.my_prop)
/// let prop = w.add_property("my_property", Vec3::ONE.into());
/// let expr = (w.lit(5.) + w.attr(Attribute::POSITION)).max(w.prop(prop));
///
/// // Finalize the expression and write it down into the `Module` as an `Expr`
/// let expr: ExprHandle = expr.expr();
///
/// // Create a modifier and assign the expression to one of its input(s)
/// let init_modifier = SetAttributeModifier::new(Attribute::LIFETIME, expr);
///
/// // Create an EffectAsset with the modifier and the Module from the writer
/// let effect = EffectAsset::new(1024, SpawnerSettings::rate(32_f32.into()), w.finish())
///     .init(init_modifier);
/// ```
///
/// [`finish()`]: ExprWriter::finish
/// [`EffectAsset`]: crate::EffectAsset
/// [`Modifer`]: crate::Modifier
#[derive(Debug, Default, Clone)]
pub struct ExprWriter {
    module: Rc<RefCell<Module>>,
}

#[allow(dead_code)]
impl ExprWriter {
    /// Create a new writer.
    ///
    /// The writer owns a new [`Module`] internally, and write all expressions
    /// to it. The module can be released to the user with [`finish()`] once
    /// done using the writer.
    ///
    /// [`finish()`]: ExprWriter::finish
    pub fn new() -> Self {
        Self {
            module: Rc::new(RefCell::new(Module::default())),
        }
    }

    /// Create a new writer from an existing module.
    ///
    /// This is an advanced use entry point to write expressions into an
    /// existing [`Module`]. In general, users should prefer using
    /// [`ExprWriter::new()`] to create a new [`Module`], and keep using the
    /// same [`ExprWriter`] to write all expressions of the same
    /// [`EffectAsset`].
    ///
    /// [`EffectAsset`]: crate::EffectAsset
    pub fn from_module(module: Rc<RefCell<Module>>) -> Self {
        Self { module }
    }

    /// Add a new property.
    ///
    /// See [`Property`] for more details on what effect properties are.
    ///
    /// # Panics
    ///
    /// Panics if a property with the same name already exists.
    pub fn add_property(&self, name: impl Into<String>, default_value: Value) -> PropertyHandle {
        self.module.borrow_mut().add_property(name, default_value)
    }

    /// Push a new expression into the writer.
    pub fn push(&self, expr: impl Into<Expr>) -> WriterExpr {
        let expr = {
            let mut m = self.module.borrow_mut();
            m.add_expr(expr.into())
        };
        WriterExpr {
            expr,
            module: Rc::clone(&self.module),
        }
    }

    /// Create a new writer expression from a literal constant.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// let mut w = ExprWriter::new();
    /// let x = w.lit(-3.5); // x = -3.5;
    /// ```
    pub fn lit(&self, value: impl Into<Value>) -> WriterExpr {
        self.push(Expr::Literal(LiteralExpr {
            value: value.into(),
        }))
    }

    /// Create a new writer expression from an attribute.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// let mut w = ExprWriter::new();
    /// let x = w.attr(Attribute::POSITION); // x = particle.position;
    /// ```
    pub fn attr(&self, attr: Attribute) -> WriterExpr {
        self.push(Expr::Attribute(AttributeExpr::new(attr)))
    }

    /// Create a new writer expression from an attribute on a parent effect.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// let mut w = ExprWriter::new();
    /// let x = w.parent_attr(Attribute::POSITION); // x = parent_particle.position;
    /// ```
    pub fn parent_attr(&self, attr: Attribute) -> WriterExpr {
        self.push(Expr::ParentAttribute(AttributeExpr::new(attr)))
    }

    /// Create a new writer expression from a property.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// let mut w = ExprWriter::new();
    /// let prop = w.add_property("my_prop", 3.0.into());
    /// let x = w.prop(prop); // x = properties.my_prop;
    /// ```
    pub fn prop(&self, handle: PropertyHandle) -> WriterExpr {
        self.push(Expr::Property(PropertyExpr::new(handle)))
    }

    /// Create a new writer expression representing the current simulation time.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// let mut w = ExprWriter::new();
    /// let x = w.time(); // x = sim_params.time;
    /// ```
    pub fn time(&self) -> WriterExpr {
        self.push(Expr::BuiltIn(BuiltInExpr::new(BuiltInOperator::Time)))
    }

    /// Create a new writer expression representing the simulation delta time
    /// since last frame.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// let mut w = ExprWriter::new();
    /// let x = w.delta_time(); // x = sim_params.delta_time;
    /// ```
    pub fn delta_time(&self) -> WriterExpr {
        self.push(Expr::BuiltIn(BuiltInExpr::new(BuiltInOperator::DeltaTime)))
    }

    /// Create a new writer expression representing a random value of the given
    /// type.
    ///
    /// The type can be any scalar or vector type. Matrix types are not
    /// supported. The random values generated are uniformly distributed in
    /// `[0:1]`. For vectors, each component is sampled separately.
    ///
    /// # Panics
    ///
    /// Panics in the same cases as [`BuiltInExpr::new()`] does.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// let mut w = ExprWriter::new();
    /// let x = w.rand(VectorType::VEC3F); // x = frand3();
    /// ```
    pub fn rand(&self, value_type: impl Into<ValueType>) -> WriterExpr {
        self.push(Expr::BuiltIn(BuiltInExpr::new(BuiltInOperator::Rand(
            value_type.into(),
        ))))
    }

    /// Create a new writer expression representing the alpha cutoff value used
    /// for alpha masking.
    ///
    /// This expression is only valid when used in the context of the fragment
    /// shader, in the render context.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// let mut w = ExprWriter::new();
    /// let x = w.alpha_cutoff(); // x = alpha_cutoff;
    /// ```
    pub fn alpha_cutoff(&self) -> WriterExpr {
        self.push(Expr::BuiltIn(BuiltInExpr::new(
            BuiltInOperator::AlphaCutoff,
        )))
    }

    /// Finish using the writer, and recover the [`Module`] where all [`Expr`]
    /// were written by the writer.
    ///
    /// This module is typically passed to [`EffectAsset::new()`] before adding
    /// to that effect the modifiers which use the expressions created by this
    /// writer.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # let spawner = SpawnerSettings::default();
    /// let mut w = ExprWriter::new();
    /// // [...]
    /// let module = w.finish();
    /// let asset = EffectAsset::new(256, spawner, module);
    /// ```
    ///
    /// [`EffectAsset::new()`]: crate::EffectAsset::new()
    pub fn finish(self) -> Module {
        self.module.take()
    }
}

/// Intermediate expression from an [`ExprWriter`].
///
/// A writer expression [`WriterExpr`] is equivalent to an [`ExprHandle`], but
/// retains a reference to the underlying [`Module`] and therefore can easily be
/// chained with other [`WriterExpr`] via a concise syntax, at the expense of
/// being more heavyweight and locking the underlying [`Module`] under a
/// ref-counted interior mutability (`Rc<RefCell<Module>>`). [`ExprHandle`] by
/// opposition is a very lightweight type, similar to a simple index. And like
/// an array index, [`ExprHandle`] doesn't explicitly reference its associated
/// storage ([`Module`]) which needs to be remembered by the user explicitly.
///
/// In addition, [`WriterExpr`] implements several numerical operators like the
/// [`std::ops::Add`] trait, making it simpler to combine it with another
/// [`WriterExpr`].
///
/// ```
/// # use bevy_hanabi::*;
/// let mut w = ExprWriter::new();
/// let x = w.lit(-3.5);
/// let y = w.lit(78.);
/// let z = x + y; // == 74.5
/// ```
///
/// In general the [`WriterExpr`] type is not used directly, but inferred from
/// calling [`ExprWriter`] methods and combining [`WriterExpr`] together.
///
/// ```
/// # use bevy_hanabi::*;
/// let mut w = ExprWriter::new();
/// let my_prop = w.add_property("my_prop", 3.0.into());
///
/// // x = max(-3.5 + 1., properties.my_prop) * 0.5 - particle.position;
/// let x = (w.lit(-3.5) + w.lit(1.))
///     .max(w.prop(my_prop))
///     .mul(w.lit(0.5))
///     .sub(w.attr(Attribute::POSITION));
///
/// let handle: ExprHandle = x.expr();
/// ```
#[derive(Debug, Clone)]
pub struct WriterExpr {
    expr: ExprHandle,
    module: Rc<RefCell<Module>>,
}

impl WriterExpr {
    fn unary_op(self, op: UnaryOperator) -> Self {
        let expr = self.module.borrow_mut().add_expr(Expr::Unary {
            op,
            expr: self.expr,
        });
        WriterExpr {
            expr,
            module: self.module,
        }
    }

    /// Take the absolute value of the current expression.
    ///
    /// This is a unary operator, which applies component-wise to vector and
    /// matrix operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = -3.5;`.
    /// let x = w.lit(-3.5);
    ///
    /// // The absolute value `y = abs(x);`.
    /// let y = x.abs(); // == 3.5
    /// ```
    #[inline]
    pub fn abs(self) -> Self {
        self.unary_op(UnaryOperator::Abs)
    }

    /// Apply the logical operator "all" to the current bool vector expression.
    ///
    /// This is a unary operator, which applies to vector operand expressions to
    /// produce a scalar boolean.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::BVec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<bool>(true, false, true);`.
    /// let x = w.lit(BVec3::new(true, false, true));
    ///
    /// // Check if all components are true `y = all(x);`.
    /// let y = x.all(); // == false
    /// ```
    #[inline]
    pub fn all(self) -> Self {
        self.unary_op(UnaryOperator::All)
    }

    /// Apply the logical operator "any" to the current bool vector expression.
    ///
    /// This is a unary operator, which applies to vector operand expressions to
    /// produce a scalar boolean.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::BVec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<bool>(true, false, true);`.
    /// let x = w.lit(BVec3::new(true, false, true));
    ///
    /// // Check if any components is true `y = any(x);`.
    /// let y = x.any(); // == true
    /// ```
    #[inline]
    pub fn any(self) -> Self {
        self.unary_op(UnaryOperator::Any)
    }

    /// Apply the "acos" (inverse cosine) operator to the current float scalar
    /// or vector expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions. The return value lies in
    /// the 0 ≤ x ≤ π range.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Acos: `y = acos(x);`
    /// let y = x.acos();
    /// ```
    #[inline]
    pub fn acos(self) -> Self {
        self.unary_op(UnaryOperator::Acos)
    }

    /// Apply the "asin" (inverse sine) operator to the current float scalar or
    /// vector expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions. The return value lies in
    /// the -π/2 ≤ x ≤ π/2 range.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Asin: `y = asin(x);`
    /// let y = x.asin();
    /// ```
    #[inline]
    pub fn asin(self) -> Self {
        self.unary_op(UnaryOperator::Asin)
    }

    /// Apply the "atan" (inverse tangent) operator to the current float scalar
    /// or vector expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions. The return value lies in
    /// the -π/2 ≤ x ≤ π/2 range.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Atan: `y = atan(x);`
    /// let y = x.atan();
    /// ```
    #[inline]
    pub fn atan(self) -> Self {
        self.unary_op(UnaryOperator::Atan)
    }

    /// Apply the "ceil" operator to the current float scalar or vector
    /// expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Ceil: `y = ceil(x);`
    /// let y = x.ceil();
    /// ```
    #[inline]
    pub fn ceil(self) -> Self {
        self.unary_op(UnaryOperator::Ceil)
    }

    /// Apply the "cos" operator to the current float scalar or vector
    /// expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Cos: `y = cos(x);`
    /// let y = x.cos();
    /// ```
    #[inline]
    pub fn cos(self) -> Self {
        self.unary_op(UnaryOperator::Cos)
    }

    /// Apply the "exp" operator to the current float scalar or vector
    /// expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Exp: `y = exp(x);`
    /// let y = x.exp();
    /// ```
    #[inline]
    pub fn exp(self) -> Self {
        self.unary_op(UnaryOperator::Exp)
    }

    /// Apply the "exp2" operator to the current float scalar or vector
    /// expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Exp2: `y = exp2(x);`
    /// let y = x.exp2();
    /// ```
    #[inline]
    pub fn exp2(self) -> Self {
        self.unary_op(UnaryOperator::Exp2)
    }

    /// Apply the "floor" operator to the current float scalar or vector
    /// expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Floor: `y = floor(x);`
    /// let y = x.floor();
    /// ```
    #[inline]
    pub fn floor(self) -> Self {
        self.unary_op(UnaryOperator::Floor)
    }

    /// Apply the "fract" operator to the current float scalar or vector
    /// expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Fract: `y = fract(x);`
    /// let y = x.fract();
    /// ```
    #[inline]
    pub fn fract(self) -> Self {
        self.unary_op(UnaryOperator::Fract)
    }

    /// Apply the "inverseSqrt" (inverse square root) operator to the current
    /// float scalar or vector expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Inverse square root: `y = inverseSqrt(x) = 1.0 / sqrt(x);`
    /// let y = x.inverse_sqrt();
    /// ```
    #[inline]
    pub fn inverse_sqrt(self) -> Self {
        self.unary_op(UnaryOperator::InvSqrt)
    }

    /// Apply the "length" operator to the current float scalar or vector
    /// expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Length: `y = length(x);`
    /// let y = x.length();
    /// ```
    #[inline]
    pub fn length(self) -> Self {
        self.unary_op(UnaryOperator::Length)
    }

    /// Apply the "log" operator to the current float scalar or vector
    /// expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Log: `y = log(x);`
    /// let y = x.log();
    /// ```
    #[inline]
    pub fn log(self) -> Self {
        self.unary_op(UnaryOperator::Log)
    }

    /// Apply the "log2" operator to the current float scalar or vector
    /// expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Log2: `y = log2(x);`
    /// let y = x.log2();
    /// ```
    #[inline]
    pub fn log2(self) -> Self {
        self.unary_op(UnaryOperator::Log2)
    }

    /// Apply the "normalize" operator to the current float vector expression.
    ///
    /// This is a unary operator, which applies to float vector operand
    /// expressions to produce another float vector with unit length
    /// (normalized).
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Normalize: `y = normalize(x);`
    /// let y = x.normalized();
    /// ```
    #[inline]
    pub fn normalized(self) -> Self {
        self.unary_op(UnaryOperator::Normalize)
    }

    /// Apply the "pack4x8snorm" operator to the current 4-component float
    /// vector expression.
    ///
    /// This is a unary operator, which applies to 4-component float vector
    /// operand expressions to produce a single `u32` scalar expression.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec4;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec4<f32>(-1., 1., 0., 7.2);`.
    /// let x = w.lit(Vec4::new(-1., 1., 0., 7.2));
    ///
    /// // Pack: `y = pack4x8snorm(x);`
    /// let y = x.pack4x8snorm(); // 0x7F007FFFu32
    /// ```
    #[inline]
    pub fn pack4x8snorm(self) -> Self {
        self.unary_op(UnaryOperator::Pack4x8snorm)
    }

    /// Apply the "pack4x8unorm" operator to the current 4-component float
    /// vector expression.
    ///
    /// This is a unary operator, which applies to 4-component float vector
    /// operand expressions to produce a single `u32` scalar expression.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec4;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec4<f32>(-1., 1., 0., 7.2);`.
    /// let x = w.lit(Vec4::new(-1., 1., 0., 7.2));
    ///
    /// // Pack: `y = pack4x8unorm(x);`
    /// let y = x.pack4x8unorm(); // 0xFF00FF00u32
    /// ```
    #[inline]
    pub fn pack4x8unorm(self) -> Self {
        self.unary_op(UnaryOperator::Pack4x8unorm)
    }

    /// Apply the "round" operator to the current float scalar or vector
    /// expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1.5, -3.2, 0.75);`.
    /// let x = w.lit(Vec3::new(1.5, -3.2, 0.75));
    ///
    /// // Sign: `y = round(x);`
    /// let y = x.round();
    /// ```
    #[inline]
    pub fn round(self) -> Self {
        self.unary_op(UnaryOperator::Round)
    }

    /// Apply the "sign" operator to the current float scalar or vector
    /// expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Sign: `y = sign(x);`
    /// let y = x.sign();
    /// ```
    #[inline]
    pub fn sign(self) -> Self {
        self.unary_op(UnaryOperator::Sign)
    }

    /// Apply the "sin" operator to the current float scalar or vector
    /// expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Sin: `y = sin(x);`
    /// let y = x.sin();
    /// ```
    #[inline]
    pub fn sin(self) -> Self {
        self.unary_op(UnaryOperator::Sin)
    }

    /// Apply the "sqrt" (square root) operator to the current float scalar or
    /// vector expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Square root: `y = sqrt(x);`
    /// let y = x.sqrt();
    /// ```
    #[inline]
    pub fn sqrt(self) -> Self {
        self.unary_op(UnaryOperator::Sqrt)
    }

    /// Apply the "tan" operator to the current float scalar or vector
    /// expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Tan: `y = tan(x);`
    /// let y = x.tan();
    /// ```
    #[inline]
    pub fn tan(self) -> Self {
        self.unary_op(UnaryOperator::Tan)
    }

    /// Apply the "unpack4x8snorm" operator to the current `u32` scalar
    /// expression.
    ///
    /// This is a unary operator, which applies to `u32` scalar operand
    /// expressions to produce a 4-component floating point vector of signed
    /// normalized components in `[-1:1]`.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `y = 0x7F007FFFu32;`.
    /// let y = w.lit(0x7F007FFFu32);
    ///
    /// // Unpack: `x = unpack4x8snorm(y);`
    /// let x = y.unpack4x8snorm(); // vec4<f32>(-1., 1., 0., 7.2)
    /// ```
    #[inline]
    pub fn unpack4x8snorm(self) -> Self {
        self.unary_op(UnaryOperator::Unpack4x8snorm)
    }

    /// Apply the "unpack4x8unorm" operator to the current `u32` scalar
    /// expression.
    ///
    /// This is a unary operator, which applies to `u32` scalar operand
    /// expressions to produce a 4-component floating point vector of unsigned
    /// normalized components in `[0:1]`.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `y = 0xFF00FF00u32;`.
    /// let y = w.lit(0xFF00FF00u32);
    ///
    /// // Unpack: `x = unpack4x8unorm(y);`
    /// let x = y.unpack4x8unorm(); // vec4<f32>(-1., 1., 0., 7.2)
    /// ```
    #[inline]
    pub fn unpack4x8unorm(self) -> Self {
        self.unary_op(UnaryOperator::Unpack4x8unorm)
    }

    /// Apply the "saturate" operator to the current float scalar or vector
    /// expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(1., 1., 1.);`.
    /// let x = w.lit(Vec3::ONE);
    ///
    /// // Saturate: `y = saturate(x);`
    /// let y = x.saturate();
    /// ```
    #[inline]
    pub fn saturate(self) -> Self {
        self.unary_op(UnaryOperator::Saturate)
    }

    /// Get the first component of a scalar or vector.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `v = vec3<f32>(1., 1., 1.);`.
    /// let v = w.lit(Vec3::ONE);
    ///
    /// // f = v.x;`
    /// let f = v.x();
    /// ```
    #[inline]
    pub fn x(self) -> Self {
        self.unary_op(UnaryOperator::X)
    }

    /// Get the second component of a vector.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `v = vec3<f32>(1., 1., 1.);`.
    /// let v = w.lit(Vec3::ONE);
    ///
    /// // f = v.y;`
    /// let f = v.y();
    /// ```
    #[inline]
    pub fn y(self) -> Self {
        self.unary_op(UnaryOperator::Y)
    }

    /// Get the third component of a vector.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `v = vec3<f32>(1., 1., 1.);`.
    /// let v = w.lit(Vec3::ONE);
    ///
    /// // f = v.z;`
    /// let f = v.z();
    /// ```
    #[inline]
    pub fn z(self) -> Self {
        self.unary_op(UnaryOperator::Z)
    }

    /// Get the fourth component of a vector.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `v = vec3<f32>(1., 1., 1.);`.
    /// let v = w.lit(Vec3::ONE);
    ///
    /// // f = v.w;`
    /// let f = v.w();
    /// ```
    #[inline]
    pub fn w(self) -> Self {
        self.unary_op(UnaryOperator::W)
    }

    fn binary_op(self, other: Self, op: BinaryOperator) -> Self {
        assert_eq!(self.module, other.module);
        let left = self.expr;
        let right = other.expr;
        let expr = self
            .module
            .borrow_mut()
            .add_expr(Expr::Binary { op, left, right });
        WriterExpr {
            expr,
            module: self.module,
        }
    }

    /// Add the current expression with another expression.
    ///
    /// This is a binary operator, which applies component-wise to vector
    /// operand expressions.
    ///
    /// You can also use the [`std::ops::Add`] trait directly, via the `+`
    /// symbol, as an alternative to calling this method directly.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec2;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec2<f32>(3., -2.);`.
    /// let x = w.lit(Vec2::new(3., -2.));
    ///
    /// // Another literal expression `y = vec2<f32>(1., 5.);`.
    /// let y = w.lit(Vec2::new(1., 5.));
    ///
    /// // The sum of both vectors `z = x + y;`.
    /// let z = x.add(y); // == vec2<f32>(4., 3.)
    ///                   // -OR-
    ///                   // let z = x + y;
    /// ```
    #[allow(clippy::should_implement_trait)]
    #[inline]
    pub fn add(self, other: Self) -> Self {
        self.binary_op(other, BinaryOperator::Add)
    }

    /// Apply the "atan2" (inverse tangent with 2 arguments) operator to the
    /// current float scalar or vector expression.
    ///
    /// This is a unary operator, which applies to float scalar or vector
    /// operand expressions to produce a float scalar or vector. It applies
    /// component-wise to vector operand expressions. The return value lies in
    /// the -π ≤ x ≤ π range, and represents a value whose tangent is equal to
    /// y over x (`z = atan2(y, x)` <=> `tan(z) = y / x`).
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // Two literal expressions `x` and `y`.
    /// let x = w.lit(Vec3::new(1., 0., -1.));
    /// let y = w.lit(Vec3::ONE);
    ///
    /// // Atan: `z = atan2(y, x);`
    /// let z = y.atan2(x);
    /// ```
    #[inline]
    pub fn atan2(self, other: Self) -> Self {
        self.binary_op(other, BinaryOperator::Atan2)
    }

    /// Calculate the cross product of the current expression by another
    /// expression.
    ///
    /// This is a binary operator, which applies to vector operands of size 3
    /// only, and always produces a vector of the same size.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(3., -2., 1.);`.
    /// let x = w.lit(Vec3::new(3., -2., 1.));
    ///
    /// // Another literal expression `y = vec3<f32>(1., 5., 0.);`.
    /// let y = w.lit(Vec3::new(1., 5., 0.));
    ///
    /// // The cross product of both vectors `z = cross(x, y);`.
    /// let z = x.cross(y);
    /// ```
    #[inline]
    pub fn cross(self, other: Self) -> Self {
        self.binary_op(other, BinaryOperator::Cross)
    }

    /// Calculate the dot product of the current expression by another
    /// expression.
    ///
    /// This is a binary operator, which applies to vector operands of same size
    /// only, and always produces a floating point scalar.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec2;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec2<f32>(3., -2.);`.
    /// let x = w.lit(Vec2::new(3., -2.));
    ///
    /// // Another literal expression `y = vec2<f32>(1., 5.);`.
    /// let y = w.lit(Vec2::new(1., 5.));
    ///
    /// // The dot product of both vectors `z = dot(x, y);`.
    /// let z = x.dot(y);
    /// ```
    #[inline]
    pub fn dot(self, other: Self) -> Self {
        self.binary_op(other, BinaryOperator::Dot)
    }

    /// Calculate the distance between the current expression and another
    /// expression.
    ///
    /// This is a binary operator.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(3., -2., 1.);`.
    /// let x = w.lit(Vec3::new(3., -2., 1.));
    ///
    /// // Another literal expression `y = vec3<f32>(1., 5., 0.);`.
    /// let y = w.lit(Vec3::new(1., 5., 0.));
    ///
    /// // The distance between the vectors `z = distance(x, y);`.
    /// let z = x.distance(y);
    /// ```
    #[inline]
    pub fn distance(self, other: Self) -> Self {
        self.binary_op(other, BinaryOperator::Distance)
    }

    /// Divide the current expression by another expression.
    ///
    /// This is a binary operator, which applies component-wise to vector
    /// operand expressions.
    ///
    /// You can also use the [`std::ops::Div`] trait directly, via the `/`
    /// symbol, as an alternative to calling this method directly.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec2;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec2<f32>(3., -2.);`.
    /// let x = w.lit(Vec2::new(3., -2.));
    ///
    /// // Another literal expression `y = vec2<f32>(1., 5.);`.
    /// let y = w.lit(Vec2::new(1., 5.));
    ///
    /// // The quotient of both vectors `z = x / y;`.
    /// let z = x.div(y); // == vec2<f32>(3., -0.4)
    ///                   // -OR-
    ///                   // let z = x / y;
    /// ```
    #[allow(clippy::should_implement_trait)]
    #[inline]
    pub fn div(self, other: Self) -> Self {
        self.binary_op(other, BinaryOperator::Div)
    }

    /// Apply the logical operator "greater than or equal" to this expression
    /// and another expression.
    ///
    /// This is a binary operator, which applies component-wise to vector
    /// operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(3., -2., 7.);`.
    /// let x = w.lit(Vec3::new(3., -2., 7.));
    ///
    /// // Another literal expression `y = vec3<f32>(1., 5., 7.);`.
    /// let y = w.lit(Vec3::new(1., 5., 7.));
    ///
    /// // The boolean result of the greater than or equal operation `z = (x >= y);`.
    /// let z = x.ge(y); // == vec3<bool>(true, false, true)
    /// ```
    #[inline]
    pub fn ge(self, other: Self) -> Self {
        self.binary_op(other, BinaryOperator::GreaterThanOrEqual)
    }

    /// Apply the logical operator "greater than" to this expression and another
    /// expression.
    ///
    /// This is a binary operator, which applies component-wise to vector
    /// operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(3., -2., 7.);`.
    /// let x = w.lit(Vec3::new(3., -2., 7.));
    ///
    /// // Another literal expression `y = vec3<f32>(1., 5., 7.);`.
    /// let y = w.lit(Vec3::new(1., 5., 7.));
    ///
    /// // The boolean result of the greater than operation `z = (x > y);`.
    /// let z = x.gt(y); // == vec3<bool>(true, false, false)
    /// ```
    #[inline]
    pub fn gt(self, other: Self) -> Self {
        self.binary_op(other, BinaryOperator::GreaterThan)
    }

    /// Apply the logical operator "less than or equal" to this expression and
    /// another expression.
    ///
    /// This is a binary operator, which applies component-wise to vector
    /// operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(3., -2., 7.);`.
    /// let x = w.lit(Vec3::new(3., -2., 7.));
    ///
    /// // Another literal expression `y = vec3<f32>(1., 5., 7.);`.
    /// let y = w.lit(Vec3::new(1., 5., 7.));
    ///
    /// // The boolean result of the less than or equal operation `z = (x <= y);`.
    /// let z = x.le(y); // == vec3<bool>(false, true, true)
    /// ```
    #[inline]
    pub fn le(self, other: Self) -> Self {
        self.binary_op(other, BinaryOperator::LessThanOrEqual)
    }

    /// Apply the logical operator "less than" to this expression and another
    /// expression.
    ///
    /// This is a binary operator, which applies component-wise to vector
    /// operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(3., -2., 7.);`.
    /// let x = w.lit(Vec3::new(3., -2., 7.));
    ///
    /// // Another literal expression `y = vec3<f32>(1., 5., 7.);`.
    /// let y = w.lit(Vec3::new(1., 5., 7.));
    ///
    /// // The boolean result of the less than operation `z = (x < y);`.
    /// let z = x.lt(y); // == vec3<bool>(false, true, false)
    /// ```
    #[inline]
    pub fn lt(self, other: Self) -> Self {
        self.binary_op(other, BinaryOperator::LessThan)
    }

    /// Take the maximum value of the current expression and another expression.
    ///
    /// This is a binary operator, which applies component-wise to vector
    /// operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec2;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec2<f32>(3., -2.);`.
    /// let x = w.lit(Vec2::new(3., -2.));
    ///
    /// // Another literal expression `y = vec2<f32>(1., 5.);`.
    /// let y = w.lit(Vec2::new(1., 5.));
    ///
    /// // The maximum of both vectors `z = max(x, y);`.
    /// let z = x.max(y); // == vec2<f32>(3., 5.)
    /// ```
    #[inline]
    pub fn max(self, other: Self) -> Self {
        self.binary_op(other, BinaryOperator::Max)
    }

    /// Take the minimum value of the current expression and another expression.
    ///
    /// This is a binary operator, which applies component-wise to vector
    /// operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec2;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec2<f32>(3., -2.);`.
    /// let x = w.lit(Vec2::new(3., -2.));
    ///
    /// // Another literal expression `y = vec2<f32>(1., 5.);`.
    /// let y = w.lit(Vec2::new(1., 5.));
    ///
    /// // The minimum of both vectors `z = min(x, y);`.
    /// let z = x.min(y); // == vec2<f32>(1., -2.)
    /// ```
    #[inline]
    pub fn min(self, other: Self) -> Self {
        self.binary_op(other, BinaryOperator::Min)
    }

    /// Multiply the current expression with another expression.
    ///
    /// This is a binary operator, which applies component-wise to vector
    /// operand expressions.
    ///
    /// You can also use the [`std::ops::Mul`] trait directly, via the `*`
    /// symbol, as an alternative to calling this method directly.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec2;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec2<f32>(3., -2.);`.
    /// let x = w.lit(Vec2::new(3., -2.));
    ///
    /// // Another literal expression `y = vec2<f32>(1., 5.);`.
    /// let y = w.lit(Vec2::new(1., 5.));
    ///
    /// // The product of both vectors `z = x * y;`.
    /// let z = x.mul(y); // == vec2<f32>(3., -10.)
    ///                   // -OR-
    ///                   // let z = x * y;
    /// ```
    #[allow(clippy::should_implement_trait)]
    #[inline]
    pub fn mul(self, other: Self) -> Self {
        self.binary_op(other, BinaryOperator::Mul)
    }

    /// Apply the logical operator "normal" to this expression and another
    /// expression.
    ///
    /// This is a binary operator, which applies component-wise to vector
    /// operand expressions. That is, for vectors, this produces a vector of
    /// random values where each component is normally distributed with a mean
    /// of the corresponding component of the first operand and a standard
    /// deviation of the corresponding component of the second operand.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(3., -2., 7.);`.
    /// let x = w.lit(Vec3::new(3., -2., 7.));
    ///
    /// // Another literal expression `y = vec3<f32>(1., 5., 7.);`.
    /// let y = w.lit(Vec3::new(1., 5., 7.));
    ///
    /// // A random variable normally distributed in [1:3]x[-2:5]x[7:7].
    /// let z = x.normal(y);
    /// ```
    #[inline]
    pub fn normal(self, other: Self) -> Self {
        self.binary_op(other, BinaryOperator::NormalRand)
    }

    /// Calculate the remainder of the division of the current expression by
    /// another expression.
    ///
    /// This is a binary operator.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(3., -2., 1.);`.
    /// let x = w.lit(Vec3::new(3., -2., 1.));
    ///
    /// // Another literal expression `y = vec3<f32>(1., 5., 0.);`.
    /// let y = w.lit(Vec3::new(1., 5., 0.));
    ///
    /// // The remainder of the division `z = x % y;`.
    /// let z = x.rem(y);
    /// ```
    #[allow(clippy::should_implement_trait)]
    #[inline]
    pub fn rem(self, other: Self) -> Self {
        self.binary_op(other, BinaryOperator::Remainder)
    }

    /// Calculate the step of a value with respect to a reference.
    ///
    /// This is a binary operator, which applies component-wise to vector
    /// operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(3., -2.);`.
    /// let x = w.lit(Vec3::new(3., -2., 8.));
    ///
    /// // An edge reference `e = vec3<f32>(1., 5.);`.
    /// let e = w.lit(Vec3::new(1., 5., 8.));
    ///
    /// // The step value
    /// let s = x.step(e); // == vec3<f32>(1., 0., 1.)
    /// ```
    #[allow(clippy::should_implement_trait)]
    #[inline]
    pub fn step(self, edge: Self) -> Self {
        // Note: order is step(edge, x) but x.step(edge)
        edge.binary_op(self, BinaryOperator::Step)
    }

    /// Subtract another expression from the current expression.
    ///
    /// This is a binary operator, which applies component-wise to vector
    /// operand expressions.
    ///
    /// You can also use the [`std::ops::Sub`] trait directly, via the `-`
    /// symbol, as an alternative to calling this method directly.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec2;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec2<f32>(3., -2.);`.
    /// let x = w.lit(Vec2::new(3., -2.));
    ///
    /// // Another literal expression `y = vec2<f32>(1., 5.);`.
    /// let y = w.lit(Vec2::new(1., 5.));
    ///
    /// // The difference of both vectors `z = x - y;`.
    /// let z = x.sub(y); // == vec2<f32>(2., -7.)
    ///                   // -OR-
    ///                   // let z = x - y;
    /// ```
    #[allow(clippy::should_implement_trait)]
    #[inline]
    pub fn sub(self, other: Self) -> Self {
        self.binary_op(other, BinaryOperator::Sub)
    }

    /// Apply the logical operator "uniform" to this expression and another
    /// expression.
    ///
    /// This is a binary operator, which applies component-wise to vector
    /// operand expressions. That is, for vectors, this produces a vector of
    /// random values where each component is uniformly distributed within the
    /// bounds of the related component of both operands.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec3;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec3<f32>(3., -2., 7.);`.
    /// let x = w.lit(Vec3::new(3., -2., 7.));
    ///
    /// // Another literal expression `y = vec3<f32>(1., 5., 7.);`.
    /// let y = w.lit(Vec3::new(1., 5., 7.));
    ///
    /// // A random variable uniformly distributed in [1:3]x[-2:5]x[7:7].
    /// let z = x.uniform(y);
    /// ```
    #[inline]
    pub fn uniform(self, other: Self) -> Self {
        self.binary_op(other, BinaryOperator::UniformRand)
    }

    fn ternary_op(self, second: Self, third: Self, op: TernaryOperator) -> Self {
        assert_eq!(self.module, second.module);
        assert_eq!(self.module, third.module);
        let first = self.expr;
        let second = second.expr;
        let third = third.expr;
        let expr = self.module.borrow_mut().add_expr(Expr::Ternary {
            op,
            first,
            second,
            third,
        });
        WriterExpr {
            expr,
            module: self.module,
        }
    }

    /// Blending linearly ("mix") two expressions with the fraction provided by
    /// a third expression.
    ///
    /// This is a ternary operator, which applies component-wise to vector
    /// operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec2;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec2<f32>(3., -2.);`.
    /// let x = w.lit(Vec2::new(3., -2.));
    ///
    /// // Another literal expression `y = vec2<f32>(1., 4.);`.
    /// let y = w.lit(Vec2::new(1., 4.));
    ///
    /// // A fraction `t = 0.5;`.
    /// let t = w.lit(0.25);
    ///
    /// // The linear blend of x and y via t: z = (1 - t) * x + y * t
    /// let z = x.mix(y, t); // == vec2<f32>(2.5, -0.5)
    /// ```
    #[inline]
    pub fn mix(self, other: Self, fraction: Self) -> Self {
        self.ternary_op(other, fraction, TernaryOperator::Mix)
    }

    /// Clamp an expression between the bounds defined by two other expressions.
    ///
    /// This is a ternary operator, which applies component-wise to vector
    /// operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec2;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = vec2<f32>(1., -2.);`.
    /// let x = w.lit(Vec2::new(1., -2.));
    ///
    /// // A literal expression `lo = vec2<f32>(3., -3.);`.
    /// let lo = w.lit(Vec2::new(3., -3.));
    ///
    /// // A literal expression `hi = vec2<f32>(5., 1.);`.
    /// let hi = w.lit(Vec2::new(5., 1.));
    ///
    /// // Clamp x in [lo:hi]
    /// let z = x.clamp(lo, hi); // == vec2<f32>(3., -2.)
    /// ```
    #[inline]
    pub fn clamp(self, lo: Self, hi: Self) -> Self {
        self.ternary_op(lo, hi, TernaryOperator::Clamp)
    }

    /// Calculate the smooth Hermite interpolation in \[0:1\] of the current
    /// value taken between the given bounds.
    ///
    /// This is a ternary operator, which applies component-wise to vector
    /// operand expressions.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec2;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `low = vec2<f32>(3., -2.);`.
    /// let low = w.lit(Vec2::new(3., -2.));
    ///
    /// // Another literal expression `high = vec2<f32>(1., 4.);`.
    /// let high = w.lit(Vec2::new(1., 4.));
    ///
    /// // A point `x = vec2<f32>(2., 1.);` between `low` and `high`.
    /// let x = w.lit(Vec2::new(2., 1.));
    ///
    /// // The smooth Hermite interpolation: `t = smoothstep(low, high, x)`
    /// let t = x.smoothstep(low, high); // == 0.5
    /// ```
    #[inline]
    pub fn smoothstep(self, low: Self, high: Self) -> Self {
        // Note: order is smoothstep(low, high, x) but x.smoothstep(low, high)
        low.ternary_op(high, self, TernaryOperator::SmoothStep)
    }

    /// Construct a `Vec2` from two scalars.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # let mut w = ExprWriter::new();
    /// let theta = w.add_property("theta", 0.0.into());
    /// // Convert the angular property `theta` to a 2D vector.
    /// let (cos_theta, sin_theta) = (w.prop(theta).cos(), w.prop(theta).sin());
    /// let circle_pos = cos_theta.vec2(sin_theta);
    /// ```
    #[inline]
    pub fn vec2(self, y: Self) -> Self {
        self.binary_op(y, BinaryOperator::Vec2)
    }

    /// Construct a `Vec3` from two scalars.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # let mut w = ExprWriter::new();
    /// let theta = w.add_property("theta", 0.0.into());
    /// // Convert the angular property `theta` to a 3D vector in a flat plane.
    /// let (cos_theta, sin_theta) = (w.prop(theta).cos(), w.prop(theta).sin());
    /// let circle_pos = cos_theta.vec3(w.lit(0.0), sin_theta);
    /// ```
    #[inline]
    pub fn vec3(self, y: Self, z: Self) -> Self {
        self.ternary_op(y, z, TernaryOperator::Vec3)
    }

    /// Construct a `Vec4` from a vector XYZ and a scalar W.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # let mut w = ExprWriter::new();
    /// let rgb = w.rand(VectorType::VEC3F);
    /// let a = w.lit(1.);
    /// // Build vec4<f32>(R, G, B, A) and convert to 0xAABBGGRR
    /// let col = rgb.vec4_xyz_w(a).pack4x8unorm();
    /// ```
    #[inline]
    pub fn vec4_xyz_w(self, w: Self) -> Self {
        self.binary_op(w, BinaryOperator::Vec4XyzW)
    }

    /// Cast an expression to a different type.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # use bevy::math::Vec2;
    /// # let mut w = ExprWriter::new();
    /// let x = w.lit(Vec2::new(3., -2.));
    /// let y = x.cast(VectorType::VEC3I); // x = vec3<i32>(particle.position);
    /// ```
    pub fn cast(self, target: impl Into<ValueType>) -> Self {
        let target = target.into();
        let expr = self
            .module
            .borrow_mut()
            .add_expr(Expr::Cast(CastExpr::new(self.expr, target)));
        WriterExpr {
            expr,
            module: self.module,
        }
    }

    /// Finalize an expression chain and return the accumulated expression.
    ///
    /// The returned handle indexes the [`Module`] owned by the [`ExprWriter`]
    /// this intermediate expression was built from.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_hanabi::*;
    /// # let mut w = ExprWriter::new();
    /// // A literal expression `x = -3.5;`.
    /// let x = w.lit(-3.5);
    ///
    /// // Retrieve the ExprHandle for that expression.
    /// let handle = x.expr();
    /// ```
    #[inline]
    pub fn expr(self) -> ExprHandle {
        self.expr
    }
}

impl std::ops::Add<WriterExpr> for WriterExpr {
    type Output = WriterExpr;

    #[inline]
    fn add(self, rhs: WriterExpr) -> Self::Output {
        self.add(rhs)
    }
}

impl std::ops::Sub<WriterExpr> for WriterExpr {
    type Output = WriterExpr;

    #[inline]
    fn sub(self, rhs: WriterExpr) -> Self::Output {
        self.sub(rhs)
    }
}

impl std::ops::Mul<WriterExpr> for WriterExpr {
    type Output = WriterExpr;

    #[inline]
    fn mul(self, rhs: WriterExpr) -> Self::Output {
        self.mul(rhs)
    }
}

impl std::ops::Div<WriterExpr> for WriterExpr {
    type Output = WriterExpr;

    #[inline]
    fn div(self, rhs: WriterExpr) -> Self::Output {
        self.div(rhs)
    }
}

impl std::ops::Rem<WriterExpr> for WriterExpr {
    type Output = WriterExpr;

    #[inline]
    fn rem(self, rhs: WriterExpr) -> Self::Output {
        self.rem(rhs)
    }
}

#[cfg(test)]
mod tests {
    use bevy::{platform::collections::HashSet, prelude::*};
    use ron::ser::PrettyConfig;

    use super::*;
    use crate::{MatrixType, ScalarValue, ShaderWriter, VectorType};

    #[test]
    fn module() {
        let mut m = Module::default();

        #[allow(unsafe_code)]
        let unknown = unsafe { ExprHandle::new_unchecked(1) };
        assert!(m.get(unknown).is_none());
        assert!(m.get_mut(unknown).is_none());
        assert!(matches!(
            m.try_get(unknown),
            Err(ExprError::InvalidExprHandleError(_))
        ));
        assert!(matches!(
            m.try_get_mut(unknown),
            Err(ExprError::InvalidExprHandleError(_))
        ));

        let x = m.lit(5.);
        let mut expected = Expr::Literal(LiteralExpr::new(5.));
        assert_eq!(m.get(x), Some(&expected));
        assert_eq!(m.get_mut(x), Some(&mut expected));
        assert_eq!(m.try_get(x), Ok(&expected));
        assert_eq!(m.try_get_mut(x), Ok(&mut expected));
    }

    #[test]
    fn local_var() {
        let property_layout = PropertyLayout::default();
        let particle_layout = ParticleLayout::default();
        let mut ctx =
            ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);
        let mut h = HashSet::new();
        for _ in 0..100 {
            let v = ctx.make_local_var();
            assert!(h.insert(v));
        }
    }

    #[test]
    fn make_fn() {
        let property_layout = PropertyLayout::default();
        let particle_layout = ParticleLayout::default();
        let mut ctx =
            ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);
        let mut module = Module::default();

        // Make a function
        let func_name = "my_func";
        let args = "arg0: i32, arg1: f32";
        assert!(ctx
            .make_fn(func_name, args, &mut module, &mut |m, ctx| {
                m.lit(3.);
                let v = ctx.make_local_var();
                assert_eq!(v, "var0");
                let code = String::new();
                Ok(code)
            })
            .is_ok());

        // The local function context doesn't influence the outer caller context
        let v = ctx.make_local_var();
        assert_eq!(v, "var0");

        // However the module is common to the outer caller and the function
        assert!(!module.expressions.is_empty());
    }

    #[test]
    fn property() {
        let mut m = Module::default();

        let _my_prop = m.add_property("my_prop", Value::Scalar(345_u32.into()));
        let _other_prop = m.add_property(
            "other_prop",
            Value::Vector(Vec3::new(3., -7.5, 42.42).into()),
        );

        assert!(m.properties().iter().any(|p| p.name() == "my_prop"));
        assert!(m.properties().iter().any(|p| p.name() == "other_prop"));
        assert!(!m.properties().iter().any(|p| p.name() == "do_not_exist"));
    }

    #[test]
    fn writer() {
        // Get a module and its writer
        let w = ExprWriter::new();
        let my_prop = w.add_property("my_prop", 3.0.into());

        // Build some expression
        let x = w.lit(3.).abs().max(w.attr(Attribute::POSITION) * w.lit(2.))
            + w.lit(-4.).min(w.prop(my_prop));
        let x = x.expr();

        // Create an evaluation context
        let property_layout =
            PropertyLayout::new(&[Property::new("my_prop", ScalarValue::Float(3.))]);
        let particle_layout = ParticleLayout::default();
        let m = w.finish();
        let mut context =
            ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);

        // Evaluate the expression
        let x = m.try_get(x).unwrap();
        let s = x.eval(&m, &mut context).unwrap();
        assert_eq!(
            "(max(abs(3.), (particle.position) * (2.))) + (min(-4., properties[properties_array_index].my_prop))"
                .to_string(),
            s
        );
    }

    #[test]
    fn type_error() {
        let l = Value::Scalar(3.5_f32.into());
        let r: Result<Vec2, ExprError> = l.try_into();
        assert!(r.is_err());
        assert!(matches!(r, Err(ExprError::TypeError(_))));
    }

    #[test]
    fn math_expr() {
        let mut m = Module::default();

        let x = m.attr(Attribute::POSITION);
        let y = m.lit(Vec3::ONE);

        let add = m.add(x, y);
        let sub = m.sub(x, y);
        let mul = m.mul(x, y);
        let div = m.div(x, y);
        let rem = m.rem(x, y);
        let lt = m.lt(x, y);
        let le = m.le(x, y);
        let gt = m.gt(x, y);
        let ge = m.ge(x, y);

        let property_layout = PropertyLayout::default();
        let particle_layout = ParticleLayout::default();
        let mut ctx =
            ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);

        for (expr, op) in [
            (add, "+"),
            (sub, "-"),
            (mul, "*"),
            (div, "/"),
            (rem, "%"),
            (lt, "<"),
            (le, "<="),
            (gt, ">"),
            (ge, ">="),
        ] {
            let expr = ctx.eval(&m, expr);
            assert!(expr.is_ok());
            let expr = expr.unwrap();
            assert_eq!(
                expr,
                format!(
                    "(particle.{}) {} (vec3<f32>(1.,1.,1.))",
                    Attribute::POSITION.name(),
                    op,
                )
            );
        }
    }

    #[test]
    fn builtin_expr() {
        let mut m = Module::default();

        // Simulation parameters
        let builtin_ops = [
            BuiltInOperator::Time,
            BuiltInOperator::DeltaTime,
            BuiltInOperator::VirtualTime,
            BuiltInOperator::VirtualDeltaTime,
            BuiltInOperator::RealTime,
            BuiltInOperator::RealDeltaTime,
        ];
        for op in builtin_ops {
            let handle = m.builtin(op);

            {
                let expr = m.get(handle);
                assert!(expr.is_some());
                let expr = expr.unwrap();
                assert!(matches!(*expr, Expr::BuiltIn(_)));
                if let Expr::BuiltIn(op) = expr {
                    assert!(builtin_ops.contains(&op.operator));
                }
            }

            let property_layout = PropertyLayout::default();
            let particle_layout = ParticleLayout::default();
            let mut ctx =
                ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);

            let expr = ctx.eval(&m, handle);
            assert!(expr.is_ok());
            let expr = expr.unwrap();
            assert_eq!(expr, format!("sim_params.{}", op.name()));
        }

        // Exercise the expression introspection
        for (handle, expr) in m.expressions() {
            assert!(handle.index() < m.expressions.len());
            assert!(matches!(*expr, Expr::BuiltIn(_)));
            if let Expr::BuiltIn(op) = expr {
                assert!(builtin_ops.contains(&op.operator));
            }
        }

        // is_alive
        {
            let value = m.builtin(BuiltInOperator::IsAlive);

            let property_layout = PropertyLayout::default();
            let particle_layout = ParticleLayout::default();
            let mut ctx =
                ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);

            let expr = ctx.eval(&m, value);
            assert!(expr.is_ok());
            let expr = expr.unwrap();
            assert_eq!(expr, "is_alive");
        }

        // BuiltInOperator::Rand (which has side effect)
        for (scalar_type, prefix) in [
            (ScalarType::Bool, "b"),
            (ScalarType::Float, "f"),
            (ScalarType::Int, "i"),
            (ScalarType::Uint, "u"),
        ] {
            let value = m.builtin(BuiltInOperator::Rand(scalar_type.into()));

            // Scalar form
            {
                let property_layout = PropertyLayout::default();
                let particle_layout = ParticleLayout::default();
                let mut ctx =
                    ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);

                let expr = ctx.eval(&m, value);
                assert!(expr.is_ok());
                let expr = expr.unwrap();
                assert_eq!(expr, "var0");
                assert_eq!(ctx.main_code, format!("let var0 = {}rand();\n", prefix));
            }

            // Vector form
            for count in 2..=4 {
                let vec = m.builtin(BuiltInOperator::Rand(
                    VectorType::new(scalar_type, count).into(),
                ));

                let property_layout = PropertyLayout::default();
                let particle_layout = ParticleLayout::default();
                let mut ctx =
                    ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);

                let expr = ctx.eval(&m, vec);
                assert!(expr.is_ok());
                let expr = expr.unwrap();
                assert_eq!(expr, "var0");
                assert_eq!(
                    ctx.main_code,
                    format!("let var0 = {}rand{}();\n", prefix, count)
                );
            }
        }
    }

    #[test]
    fn unary_expr() {
        let mut m = Module::default();

        let x = m.attr(Attribute::POSITION);
        let y = m.lit(Vec3::new(1., -3.1, 6.99));
        let z = m.lit(BVec3::new(false, true, false));
        let w = m.lit(Vec4::W);
        let v = m.lit(Vec4::new(-1., 1., 0., 7.2));
        let us = m.lit(0x0u32);
        let uu = m.lit(0x0u32);

        let abs = m.abs(x);
        let acos = m.acos(w);
        let all = m.all(z);
        let any = m.any(z);
        let asin = m.asin(w);
        let atan = m.atan(w);
        let ceil = m.ceil(y);
        let cos = m.cos(y);
        let exp = m.exp(y);
        let exp2 = m.exp2(y);
        let floor = m.floor(y);
        let fract = m.fract(y);
        let inv_sqrt = m.inverse_sqrt(y);
        let length = m.length(y);
        let log = m.log(y);
        let log2 = m.log2(y);
        let norm = m.normalize(y);
        let pack4x8snorm = m.pack4x8snorm(v);
        let pack4x8unorm = m.pack4x8unorm(v);
        let round = m.round(y);
        let saturate = m.saturate(y);
        let sign = m.sign(y);
        let sin = m.sin(y);
        let sqrt = m.sqrt(y);
        let tan = m.tan(y);
        let unpack4x8snorm = m.unpack4x8snorm(us);
        let unpack4x8unorm = m.unpack4x8unorm(uu);
        let comp_x = m.x(w);
        let comp_y = m.y(w);
        let comp_z = m.z(w);
        let comp_w = m.w(w);

        let property_layout = PropertyLayout::default();
        let particle_layout = ParticleLayout::default();
        let mut ctx =
            ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);

        for (expr, op, inner) in [
            (
                abs,
                "abs",
                &format!("particle.{}", Attribute::POSITION.name())[..],
            ),
            (acos, "acos", "vec4<f32>(0.,0.,0.,1.)"),
            (all, "all", "vec3<bool>(false,true,false)"),
            (any, "any", "vec3<bool>(false,true,false)"),
            (asin, "asin", "vec4<f32>(0.,0.,0.,1.)"),
            (atan, "atan", "vec4<f32>(0.,0.,0.,1.)"),
            (ceil, "ceil", "vec3<f32>(1.,-3.1,6.99)"),
            (cos, "cos", "vec3<f32>(1.,-3.1,6.99)"),
            (exp, "exp", "vec3<f32>(1.,-3.1,6.99)"),
            (exp2, "exp2", "vec3<f32>(1.,-3.1,6.99)"),
            (floor, "floor", "vec3<f32>(1.,-3.1,6.99)"),
            (fract, "fract", "vec3<f32>(1.,-3.1,6.99)"),
            (inv_sqrt, "inverseSqrt", "vec3<f32>(1.,-3.1,6.99)"),
            (length, "length", "vec3<f32>(1.,-3.1,6.99)"),
            (log, "log", "vec3<f32>(1.,-3.1,6.99)"),
            (log2, "log2", "vec3<f32>(1.,-3.1,6.99)"),
            (norm, "normalize", "vec3<f32>(1.,-3.1,6.99)"),
            (pack4x8snorm, "pack4x8snorm", "vec4<f32>(-1.,1.,0.,7.2)"),
            (pack4x8unorm, "pack4x8unorm", "vec4<f32>(-1.,1.,0.,7.2)"),
            (round, "round", "vec3<f32>(1.,-3.1,6.99)"),
            (saturate, "saturate", "vec3<f32>(1.,-3.1,6.99)"),
            (sign, "sign", "vec3<f32>(1.,-3.1,6.99)"),
            (sin, "sin", "vec3<f32>(1.,-3.1,6.99)"),
            (sqrt, "sqrt", "vec3<f32>(1.,-3.1,6.99)"),
            (tan, "tan", "vec3<f32>(1.,-3.1,6.99)"),
            (unpack4x8snorm, "unpack4x8snorm", "0u"),
            (unpack4x8unorm, "unpack4x8unorm", "0u"),
        ] {
            let expr = ctx.eval(&m, expr);
            assert!(expr.is_ok());
            let expr = expr.unwrap();
            assert_eq!(expr, format!("{}({})", op, inner));
        }

        for (expr, op, inner) in [
            (comp_x, "x", "vec4<f32>(0.,0.,0.,1.)"),
            (comp_y, "y", "vec4<f32>(0.,0.,0.,1.)"),
            (comp_z, "z", "vec4<f32>(0.,0.,0.,1.)"),
            (comp_w, "w", "vec4<f32>(0.,0.,0.,1.)"),
        ] {
            let expr = ctx.eval(&m, expr);
            assert!(expr.is_ok());
            let expr = expr.unwrap();
            assert_eq!(expr, format!("{}.{}", inner, op));
        }
    }

    #[test]
    fn binary_expr() {
        let mut m = Module::default();

        let x = m.attr(Attribute::POSITION);
        let y = m.lit(Vec3::ONE);
        let z = m.lit(1.45);

        let atan2 = m.atan2(x, y);
        let cross = m.cross(x, y);
        let dist = m.distance(x, y);
        let dot = m.dot(x, y);
        let min = m.min(x, y);
        let max = m.max(x, y);
        let step = m.step(x, y);
        let vec4_xyz_w = m.vec4_xyz_w(x, z);

        let property_layout = PropertyLayout::default();
        let particle_layout = ParticleLayout::default();
        let mut ctx =
            ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);

        for (expr, op) in [
            (atan2, "atan2"),
            (cross, "cross"),
            (dist, "distance"),
            (dot, "dot"),
            (min, "min"),
            (max, "max"),
            (step, "step"),
        ] {
            let expr = ctx.eval(&m, expr);
            assert!(expr.is_ok());
            let expr = expr.unwrap();
            assert_eq!(
                expr,
                format!(
                    "{}(particle.{}, vec3<f32>(1.,1.,1.))",
                    op,
                    Attribute::POSITION.name(),
                )
            );
        }

        {
            let expr = ctx.eval(&m, vec4_xyz_w);
            assert!(expr.is_ok());
            let expr = expr.unwrap();
            let z = ctx.eval(&m, z).unwrap();
            assert_eq!(
                expr,
                format!("vec4(particle.{}, {})", Attribute::POSITION.name(), z)
            );
        }
    }

    #[test]
    fn ternary_expr() {
        let mut m = Module::default();

        let x = m.attr(Attribute::POSITION);
        let y = m.lit(Vec3::ONE);
        let z = m.lit(Vec3::splat(2.));
        let t = m.lit(0.3);
        let a = m.lit(-4.2);
        let b = m.lit(53.09);

        let mix = m.mix(x, y, t);
        let clamp = m.clamp(x, y, z);
        let smoothstep = m.smoothstep(x, y, x);
        let vecthree = m.vec3(a, b, t);

        let property_layout = PropertyLayout::default();
        let particle_layout = ParticleLayout::default();
        let mut ctx =
            ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);

        for (expr, op, third) in [
            (mix, "mix", t),
            (clamp, "clamp", z),
            (smoothstep, "smoothstep", x),
        ] {
            let expr = ctx.eval(&m, expr);
            assert!(expr.is_ok());
            let expr = expr.unwrap();
            let third = ctx.eval(&m, third).unwrap();
            assert_eq!(
                expr,
                format!(
                    "{}(particle.{}, vec3<f32>(1.,1.,1.), {})",
                    op,
                    Attribute::POSITION.name(),
                    third
                )
            );
        }

        {
            let expr = ctx.eval(&m, vecthree);
            assert!(expr.is_ok());
            let expr = expr.unwrap();
            let a = ctx.eval(&m, a).unwrap();
            let b = ctx.eval(&m, b).unwrap();
            let t = ctx.eval(&m, t).unwrap();
            assert_eq!(expr, format!("vec3({}, {}, {})", a, b, t));
        }
    }

    #[test]
    fn cast_expr() {
        let mut m = Module::default();

        let x = m.attr(Attribute::POSITION);
        let y = m.lit(IVec2::ONE);
        let z = m.lit(0.3);
        let w = m.lit(false);

        let cx = m.cast(x, VectorType::VEC3I);
        let cy = m.cast(y, VectorType::VEC2U);
        let cz = m.cast(z, ScalarType::Int);
        let cw = m.cast(w, ScalarType::Uint);

        let property_layout = PropertyLayout::default();
        let particle_layout = ParticleLayout::default();
        let mut ctx =
            ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);

        for (expr, cast, target) in [
            (x, cx, ValueType::Vector(VectorType::VEC3I)),
            (y, cy, VectorType::VEC2U.into()),
            (z, cz, ScalarType::Int.into()),
            (w, cw, ScalarType::Uint.into()),
        ] {
            let expr = ctx.eval(&m, expr);
            assert!(expr.is_ok());
            let expr = expr.unwrap();
            let cast = ctx.eval(&m, cast);
            assert!(cast.is_ok());
            let cast = cast.unwrap();
            assert_eq!(cast, format!("{}({})", target.to_wgsl_string(), expr));
        }
    }

    #[test]
    fn attribute_pointer() {
        let mut m = Module::default();
        let x = m.attr(Attribute::POSITION);

        let property_layout = PropertyLayout::default();
        let particle_layout = ParticleLayout::default();
        let mut ctx =
            ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);

        let res = ctx.eval(&m, x);
        assert!(res.is_ok());
        let xx = res.ok().unwrap();
        assert_eq!(xx, format!("particle.{}", Attribute::POSITION.name()));

        // Use a different context; it's invalid to reuse a mutated context, as the
        // expression cache will have been generated with the wrong context.
        let mut ctx =
            ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout)
                .with_attribute_pointer();

        let res = ctx.eval(&m, x);
        assert!(res.is_ok());
        let xx = res.ok().unwrap();
        assert_eq!(xx, format!("(*particle).{}", Attribute::POSITION.name()));
    }

    #[test]
    #[should_panic]
    fn invalid_cast_vector_to_scalar() {
        let mut m = Module::default();
        let x = m.lit(Vec2::ONE);
        let _ = m.cast(x, ScalarType::Float);
    }

    #[test]
    #[should_panic]
    fn invalid_cast_matrix_to_scalar() {
        let mut m = Module::default();
        let x = m.lit(Value::Matrix(Mat4::ZERO.into()));
        let _ = m.cast(x, ScalarType::Float);
    }

    #[test]
    #[should_panic]
    fn invalid_cast_matrix_to_vector() {
        let mut m = Module::default();
        let x = m.lit(Value::Matrix(Mat4::ZERO.into()));
        let _ = m.cast(x, VectorType::VEC4F);
    }

    #[test]
    #[should_panic]
    fn invalid_cast_scalar_to_matrix() {
        let mut m = Module::default();
        let x = m.lit(3.);
        let _ = m.cast(x, MatrixType::MAT3X3F);
    }

    #[test]
    #[should_panic]
    fn invalid_cast_vector_to_matrix() {
        let mut m = Module::default();
        let x = m.lit(Vec3::ZERO);
        let _ = m.cast(x, MatrixType::MAT2X4F);
    }

    #[test]
    fn cast_expr_new() {
        let mut m = Module::default();

        let x = m.attr(Attribute::POSITION);
        let c = CastExpr::new(x, VectorType::VEC3F);
        assert_eq!(c.value_type(), ValueType::Vector(VectorType::VEC3F));
        assert_eq!(c.is_valid(&m), Some(true));

        let x = m.attr(Attribute::POSITION);
        let c = CastExpr::new(x, ScalarType::Bool);
        assert_eq!(c.value_type(), ValueType::Scalar(ScalarType::Bool));
        assert_eq!(c.is_valid(&m), Some(false)); // invalid cast vector -> scalar

        let p = m.add_property("my_prop", 3.0.into());
        let y = m.prop(p);
        let c = CastExpr::new(y, MatrixType::MAT2X3F);
        assert_eq!(c.value_type(), ValueType::Matrix(MatrixType::MAT2X3F));
        assert_eq!(c.is_valid(&m), None); // properties' value_type() is unknown
    }

    #[test]
    fn side_effect() {
        let mut m = Module::default();

        // Adding the same cloned expression with side effect to itself should yield
        // twice the value, and not two separate evaluations of the expression.
        // CORRECT:
        //   let r = frand();
        //   r + r
        // INCORRECT:
        //   frand() + frand()

        let r = m.builtin(BuiltInOperator::Rand(ScalarType::Float.into()));
        let r2 = r;
        let r3 = r2;
        let a = m.add(r, r2);
        let b = m.mix(r, r2, r3);
        let c = m.abs(a);

        {
            let property_layout = PropertyLayout::default();
            let particle_layout = ParticleLayout::default();
            let mut ctx =
                ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);
            let value = ctx.eval(&m, a).unwrap();
            assert_eq!(value, "(var0) + (var0)");
            assert_eq!(ctx.main_code, "let var0 = frand();\n");
        }

        {
            let property_layout = PropertyLayout::default();
            let particle_layout = ParticleLayout::default();
            let mut ctx =
                ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);
            let value = ctx.eval(&m, b).unwrap();
            assert_eq!(value, "mix(var0, var0, var0)");
            assert_eq!(ctx.main_code, "let var0 = frand();\n");
        }

        {
            let property_layout = PropertyLayout::default();
            let particle_layout = ParticleLayout::default();
            let mut ctx =
                ShaderWriter::new(ModifierContext::Update, &property_layout, &particle_layout);
            let value = ctx.eval(&m, c).unwrap();
            assert_eq!(value, "abs((var0) + (var0))");
            assert_eq!(ctx.main_code, "let var0 = frand();\n");
        }
    }

    // #[test]
    // fn serde() {
    //     let v = Value::Scalar(3.0_f32.into());
    //     let l: LiteralExpr = v.into();
    //     assert_eq!(Ok(v), l.eval());
    //     let s = ron::to_string(&l).unwrap();
    //     println!("literal: {:?}", s);
    //     let l_serde: LiteralExpr = ron::from_str(&s).unwrap();
    //     assert_eq!(l_serde, l);

    //     let b: ExprHandle = Box::new(l);
    //     let s = ron::to_string(&b).unwrap();
    //     println!("boxed literal: {:?}", s);
    //     let b_serde: ExprHandle = ron::from_str(&s).unwrap();
    //     assert!(b_serde.is_const());
    //     assert_eq!(b_serde.to_wgsl_string(), b.to_wgsl_string());

    //     let v0 = Value::Scalar(3.0_f32.into());
    //     let v1 = Value::Scalar(2.5_f32.into());
    //     let l0: LiteralExpr = v0.into();
    //     let l1: LiteralExpr = v1.into();
    //     let a = l0 + l1;
    //     assert!(a.is_const());
    //     assert_eq!(Ok(Value::Scalar(5.5_f32.into())), a.eval());
    //     let s = ron::to_string(&a).unwrap();
    //     println!("add: {:?}", s);
    //     let a_serde: AddExpr = ron::from_str(&s).unwrap();
    //     println!("a_serde: {:?}", a_serde);
    //     assert_eq!(a_serde.left.to_wgsl_string(), l0.to_wgsl_string());
    //     assert_eq!(a_serde.right.to_wgsl_string(), l1.to_wgsl_string());
    // }

    #[test]
    fn expr_handle_serde() {
        let handle = ExprHandle {
            id: NonZeroU32::new(42).unwrap(),
        };

        // ser
        let s = ron::ser::to_string_pretty(&handle, PrettyConfig::default()).unwrap();
        eprintln!("{}", s);

        // de
        {
            let mut de = ron::de::Deserializer::from_str(&s).unwrap();
            let serde_handle = ExprHandle::deserialize(&mut de).unwrap();
            assert_eq!(handle, serde_handle);
        }

        // de -- literatl string
        {
            let mut de = ron::de::Deserializer::from_str("\"#42\"").unwrap();
            let serde_handle = ExprHandle::deserialize(&mut de).unwrap();
            assert_eq!(handle, serde_handle);
        }

        // de -- invalid string
        {
            let mut de = ron::de::Deserializer::from_str("\"invalid\"").unwrap();
            let ret = ExprHandle::deserialize(&mut de);
            assert!(ret.is_err());
        }

        // de -- literal (not supported)
        {
            let mut de = ron::de::Deserializer::from_str("33").unwrap();
            let ret = ExprHandle::deserialize(&mut de);
            assert!(ret.is_err());
        }

        // de -- invalid ID (zero)
        {
            let mut de = ron::de::Deserializer::from_str("\"#0\"").unwrap();
            let ret = ExprHandle::deserialize(&mut de);
            assert!(ret.is_err());
        }

        // de -- invalid ID (negative)
        {
            let mut de = ron::de::Deserializer::from_str("\"#-5\"").unwrap();
            let ret = ExprHandle::deserialize(&mut de);
            assert!(ret.is_err());
        }

        // de -- valid ID (u32::MAX)
        {
            let mut de = ron::de::Deserializer::from_str("\"#4294967295\"").unwrap();
            let serde_handle = ExprHandle::deserialize(&mut de).unwrap();
            assert_eq!(serde_handle.id.get(), u32::MAX);
        }

        // de -- invalid ID (u32::MAX + 1; out of bounds)
        {
            let mut de = ron::de::Deserializer::from_str("\"#4294967296\"").unwrap();
            let ret = ExprHandle::deserialize(&mut de);
            assert!(ret.is_err());
        }
    }
}