bevy_scene 0.19.0

Provides scene functionality for Bevy 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
#![expect(unsafe_code, reason = "Unsafe code is used to improve performance.")]
//! Composable scene authoring for Bevy, defined using the Bevy Scene Notation (BSN) format.
//!
//! Game entities rarely exist in isolation.
//! A 3D level might be made up of walls, floors, props and enemies.
//! A 2D character might need a distinct sprite entity for weapon, hat and boots.
//! A UI popup might need text and multiple buttons for accept, cancel, minimize and close actions.
//! Spawning these collections as individual, disjointed entities is tedious, error-prone, and hard to reuse.
//! A **scene** lets you describe a conceptual **object**, made of an entity, its components, children, and assets, once
//! and spawn it wherever you need it.
//!
//! Any scene system must overcome three challenges:
//!
//! - **Composability**: combining smaller scenes into larger ones without
//!   duplicating shared constants and setup code.
//! - **Granular overrides**: when reusing a scene, overriding *individual fields*
//!   on a component (like changing just a button's width) without having to respecify
//!   every other field on that component.
//! - **Asset integration**: referencing assets (meshes, textures, sounds) from within
//!   scenes without manually wiring up asset handles.
//!
//! This crate tackles all three, via [`Scene`] composition, [`Template`]-based
//! field-level patching, and automatic string-to-asset-handle resolution.
//!
//! The [`bsn!`] macro exposes these ideas, and makes the process of scene-authoring pleasant
//! by providing a terse syntax for defining [`Scene`]s inline.
//! This brevity is essential: making it easier to review and understand scenes at a glance,
//! resolve merge conflicts and keep file sizes under control.
//! The macro includes best-effort Rust-Analyzer support. Autocomplete, go-to-definition, and hover docs
//! should work inside the macros, and this effort should transfer over correctly to other LSPs!
//!
//! ## BSN syntax reference
//!
//! For a quick rundown on how to read and write BSN syntax, see the docs for [`bsn!`].
//!
//! ## Quick Start
//!
//! Spawn entities in a [`Scene`] by calling [`World::spawn_scene`],
//! wrapping a call to the [`bsn!`] macro.
//!
//! ```
//! # use bevy_app::App;
//! # use bevy_scene::{prelude::*, ScenePlugin};
//! # use bevy_ecs::prelude::*;
//! # use bevy_asset::AssetPlugin;
//! # use bevy_app::TaskPoolPlugin;
//! # let mut app = App::new();
//! # app.add_plugins((
//! #     TaskPoolPlugin::default(),
//! #     AssetPlugin::default(),
//! #     ScenePlugin::default(),
//! # ));
//! # let world = app.world_mut();
//! #[derive(Component, Default, Clone)]
//! struct Score(usize);
//!
//! #[derive(Component, Default, Clone)]
//! struct Sword;
//!
//! #[derive(Component, Default, Clone)]
//! struct Shield;
//!
//! // #Player adds a `Name("Player")` component to the root entity.
//! // Children spawns two child entities: one with Sword, one with Shield.
//! world.spawn_scene(bsn! {
//!     #Player // This names the entity "Player"
//!     Score(0)
//!     Children [
//!         Sword,
//!         Shield,
//!     ]
//! });
//! ```
//!
//! ## Core Concepts
//!
//! - **[`Scene`]**: Describes what a spawned [`Entity`] should look like, created using [`bsn!`] or,
//!   in the future, `.bsn` asset files. Conceptually, a [`Scene`] contains a list of "entries" to apply to an [`Entity`].
//! - **[`SceneList`]**: A list of scenes, returned by [`bsn_list!`].
//!   Each [`Scene`] in the list produces one [`Entity`].
//! - **Scene Composition**: Composition works by including scenes in other scenes. The included scenes "entries" will be
//!   treated as if they were written in the outer scene.
//! - **[`Template`]**: A [`Template`] is something that, given a spawn context (target [`Entity`], [`World`], etc), can produce some output. Think of it
//!   as a "superpowered ECS-aware constructor" for a type. In the context of scenes, [`Template`]s are used to produce [`Component`]s and [`Bundle`]s. This
//!   enables defining scenes without needing to pass in a bunch of their dependencies (such as assets). The [`FromTemplate`] trait is used to associate some
//!   final output type (ex: a [`Component`]) with a canonical [`Template`] that produces it. [`FromTemplate`] / [`Template`] is automatically implemented for
//!   types that implement [`Default`] + [`Clone`], which is generally preferred. You should manually derive [`FromTemplate`] when a type needs custom template logic
//!   (ex: one of its fields is an "asset handle", which has custom template logic).
//! - **[`RelatedScenes`]**: These add a [`SceneList`] as related to this [`Scene`] by a specific [`relationship`](bevy_ecs::relationship::Relationship).
//!   This kind of change is added to the [`Scene`] by specifying a [`RelationshipTarget`] component like [`Children`], followed by a [`SceneList`].
//!
//! ## Spawning Scenes
//!
//! There are two approaches to spawning scenes:
//!
//! - **Immediate**: [`World::spawn_scene`] and [`Commands::spawn_scene`]
//!   resolve and spawn in one step.
//!   Returns an error if any asset dependencies are not yet loaded.
//! - **Queued**: [`World::queue_spawn_scene`] and [`Commands::queue_spawn_scene`]
//!   register the scene's dependencies and wait for them to load before resolving and spawning.
//!   When the dependencies are loaded (or there are no dependencies), the scene will spawn during
//!   that frame's [`SpawnScene`] schedule, between [`Update`](bevy_app::Update) and
//!   [`PostUpdate`](bevy_app::PostUpdate).
//!
//! In all cases, your `*_spawn_scene` method call should wrap an invocation of the [`bsn!`] macro,
//! or call a function which returns a [`Scene`].
//!
//! See the [`WorldSceneExt`], [`CommandsSceneExt`], [`EntityWorldMutSceneExt`], and
//! [`EntityCommandsSceneExt`] extension traits for the full set of scene-spawning APIs.
//!
//! ## Entity Hierarchies and Relationships
//!
//! Use `Children [scene1, scene2]` inside [`bsn!`] to spawn child entities.
//! [`Children`] (and entities within [`bsn_list!`]) are separated by commas;
//! add multiple components to the same entity by listing them without a comma:
//!
//! ```ignore
//! // Spawns one child entity with components A, B and C
//! bsn! { #Parent Children [A B C] }
//!
//! // Spawns two child entities, one with A and B, the other with C, due to the added comma
//! bsn! { #Parent Children [A B, C] }
//!
//! // Spawns two child entities, but more clearly separated due to parentheses.
//! bsn! { #Parent Children [(A B), C] }
//! ```
//!
//! These invocations can be nested to build deeper hierarchies.
//!
//! ```ignore
//! bsn! {
//!   #Parent
//!   Children [
//!     #Child1 SomeComponent,
//!     #Child2
//!     SomeComponent
//!     Children [
//!        #GrandChild1 SomeComponent,
//!        #GrandChild2
//!     ]
//!   ]
//! }
//! ```
//!
//! We can improve clarity at the cost of compactness through the careful use of newlines, parentheses and indentation:
//!
//! ```ignore
//! bsn! {
//!   #Parent
//!   Children [
//!      (
//!        #Child1
//!        SomeComponent
//!      ),
//!      (
//!        #Child2
//!        Children [
//!           (
//!             #GrandChild1
//!             SomeComponent
//!           ),
//!           (
//!             #GrandChild2
//!           )
//!        ]
//!      ),
//!   ]
//! }
//! ```
//!
//! This is fundamentally a stylistic choice: white space, Rust comments (`//` and `/* */`), and parentheses used in this way are ignored.
//!
//! The tools discussed here are not limited to [`Children`]: any [`RelationshipTarget`] type can be used the same way.
//!
//! ## Named Entity References
//!
//! The `#Name` syntax assigns a [`Name`] to an entity and registers it for cross-referencing within the same macro invocation.
//! Within the same bsn! invocation / scope, it is possible to reference an entity by its `#Name`, generating an [`EntityTemplate`] which ultimately resolves to an [`Entity`]:
//!
//! ```ignore
//! bsn! {
//!     #Name
//!     my_scene(#Name)
//!     ComponentA(#Name)
//!     ComponentB { entity: #Name }
//!     Children [
//!         ComponentC(#Name)
//!     ]
//! }
//! ```
//!
//! Notice that the "child entity" was able to access the parent entity via `#Name`. It is also possible for ancestors to access
//! their descendants:
//!
//! ```ignore
//! bsn! {
//!     #Root
//!     Children [
//!         Reference(#Root)
//!     ]
//! }
//! ```
//!
//! Using `#Name` as a value in [`bsn!`] will result in an [`EntityTemplate`], which is a [`Template`] that resolves to an [`Entity`]
//! [`Component`]s with [`Entity`] fields should generally derive [`FromTemplate`], because [`Entity`] uses [`FromTemplate`] to map to [`EntityTemplate`].
//!
//! ### Scope rules
//!
//! Each [`bsn!`] invocation creates its own name scope. A name is visible to the root
//! entity, its children, and any deeper descendants in the same call. The reverse is also
//! true: descendants can "look up" the hierarchy.
//! Composed scenes (via `my_scene(#Name)`) or [`SceneComponents`](SceneComponent)
//! each contain their own [`bsn!`] invocation and therefore their own scope,
//! so re-using the same name across multiple different scenes is fine.
//! However, the results of a named entity reference, the [`EntityTemplate`],
//! can be passed to other scenes. It is valid only during the spawning of a scene.
//! That means [`Components`](Component) should never store [`EntityTemplate`] fields,
//! they should store the resolved [`Entity`] instead and
//! derive [`FromTemplate`] to convert [`EntityTemplate`] automatically.
//!
//! If both a parent and a composed child define the same name (e.g. both use `#X`),
//! each scope's `#X` resolves to its own entity, avoiding conflicts or potentially unintuitive shadowing.
//!
//! In a [`bsn_list!`], all root entities share a single name scope, so sibling scenes
//! can reference each other by name. This is useful for wiring up relationships between
//! entities that are spawned together. For example, a group of UI panels where each
//! panel needs a relationship to its neighbor:
//!
//! ```ignore
//! fn linked_pair() -> impl SceneList {
//!     bsn_list![
//!         (#Left  Link(#Right)),
//!         (#Right Link(#Left)),
//!     ]
//! }
//! ```
//!
//! ### Dynamic Name Values and Entity References
//!
//! `#SomeName` syntax will set the value of the [`Name`] component to `Name("SomeName")`, and  make the entity reference-able in [`bsn!`]. `#Name` syntax is _always_ scoped and
//! doesn't support "dynamic" names. If you would like to _both_ reference an entity in [`bsn!`] _and_ provide a dynamic name, you can do this:
//!
//! ```ignore
//! let i = 0;
//! bsn! {
//!   #Root
//!   Name({format!("Entity {i}")})
//!   Children [
//!     Reference(#Root)
//!   ]
//! }
//! ```
//! Adding `Name("desired name")` after the `#SomeName` reference will patch over the `Name` component created by the reference to give it a custom name.
//!
//! ## Patching
//!
//! When you insert a component into an [`Entity`] in normal ECS code, the entire pre-existing value is replaced.
//! If a scene sets `Button { width: 100, height: 300 }` and a caller wants to
//! change just `width`, ordinary component insertion would force them to respecify `height` too.
//!
//! **Patching** avoids this. When you write `Button { width: 200 }` in [`bsn!`], it creates
//! a *patch* that sets only the `width` field. Unmentioned fields keep their existing values
//! (from a included scene, an earlier patch, or the type's defaults). Multiple patches to the
//! same component and its values are applied in order, only overwriting the fields they changed.
//!
//! The following scenes all end up with a button which is 200 wide and 300 high.
//! ```ignore
//! impl Default for Button {
//!     fn default() -> Self {
//!         Button { width: 100, height: 300 }
//!     }
//! }
//!
//! bsn! { Button { width: 200, height: 300 } } // fully specified
//! bsn! { Button { width: 200 } }              // only changing width, height defaults to 300
//!
//! bsn! {
//!     Button                 // inserts defaults
//!     Button { width: 200 }  // changes width
//!     Button { height: 300 } // changes height
//! }
//! ```
//!
//! ### Required Traits
//!
//! To make a component available in [`bsn!`], derive either [`Default`] + [`Clone`], or [`FromTemplate`].
//! Both support patching: unmentioned fields keep their values from earlier patches or the
//! type's defaults, and multiple patches merge rather than overwrite.
//!
//! The distinction is about what values a field can hold at spawn time:
//!
//! - **[`Clone`] + [`Default`]** (e.g. `#[derive(Component, Default, Clone)]`): covers the simple case, and should be your default choice.
//! - **[`FromTemplate`]** (e.g. `#[derive(Component, FromTemplate)]`) is needed when a field requires spawn-time context.
//!   Examples include [`Handle<T>`] fields which need [`AssetServer`] to resolve asset paths, or [`Entity`]
//!   fields which resolve [`EntityTemplate`]s from named entity references. If any of your fields' types
//!   implement [`FromTemplate`] manually / have custom template logic, you should derive it for the parent type as well if you want your type
//!   to use that logic.
//!
//! Deriving [`FromTemplate`] and [`Default`] on the same type is not allowed, as both would supply a [`FromTemplate`] impl and conflict.
//! [`FromTemplate`] derivers still have access to a default constructor of sorts though: the derive generates a companion struct
//! for `YourType` named `YourTypeTemplate` which implements `Default`, so `YourTypeTemplate::default()` serves the same purpose.
//!
//! #### Enums in bsn
//!
//! Enums are special-cased to allow for better implicit defaults: [`bsn!`] requires that enums have defaults for all variant arms, not just the type as a whole.
//!
//! When [`bsn!`] encounters a Enum, it will try to get the default value for the variant using static methods like `default_{variant_lower}`.
//! To help with setting up these methods, theres a pseudo-`derive` called [`VariantDefaults`](bevy_ecs::VariantDefaults).
//! It works like a normal `derive` macro, but without a matching Trait. It just generates a impl block with the `default_{variant_lower}` static methods.
//!
//! Deriving [`FromTemplate`] also implies/works like [`VariantDefaults`](bevy_ecs::VariantDefaults).
//!
//! ## Composition
//!
//! Composition relies on patching to work nicely, allowing you to include other scenes in the current ones.
//! All of their patches will be applied at the position they're included.
//!
//! Example:
//!
//! ```
//! # use bevy_app::App;
//! # use bevy_scene::{prelude::*, ScenePlugin};
//! # use bevy_ecs::prelude::*;
//! # use bevy_asset::AssetPlugin;
//! # use bevy_app::TaskPoolPlugin;
//! # let mut app = App::new();
//! # app.add_plugins((
//! #     TaskPoolPlugin::default(),
//! #     AssetPlugin::default(),
//! #     ScenePlugin::default(),
//! # ));
//! # let world = app.world_mut();
//! #[derive(Component, FromTemplate)]
//! struct Health {
//!  current: u32,
//!  max: u32
//! }
//!
//! fn enemy() -> impl Scene {
//!     bsn! { Health { current: 100, max: 100 } }
//! }
//!
//! // Include `enemy()` and patch just the `max` field:
//! world.spawn_scene(bsn! {
//!     enemy()
//!     Health { max: 200 }
//! });
//! ```
//!
//! The spawned entity has `Health { current: 100, max: 200 }`: the `max` field is overridden
//! while `current` retains the value from `enemy()`. Tuples of [`Scene`]s also implement
//! [`Scene`], so patches from multiple sources merge into a single [`ResolvedScene`].
//!
//! For programmatic patching outside of [`bsn!`], see the [`PatchFromTemplate`] and
//! [`PatchTemplate`] traits.
//!
//! ## Scene Caching
//!
//! <div class="warning">
//!
//! Note: Caching is currently only implemented for scene assets. It hasn't yet been wired up for "function scenes" or [`SceneComponent`]s. Attempting to use
//! it in those cases will result in a compile error.
//!
//! </div>
//!
//! Scenes can be cached, improving performance. Since this can change the semantics in some cases, this requires an explicit opt-in.
//! Caching works by resolving the included scene and storing the resulting [`ResolvedScene`] for future use. When the outer scene is spawned again,
//! it will not need to resolve the included scene again, instead patching on top of the cached version (using copy-on-write semantics for each [`Template`]).
//! This means caching can only be used if the scene is the first scene entry.
//!
//! This scene includes an uncached "enemy" scene:
//! ```ignore
//! bsn! {
//!     enemy()
//!     Health { max: 200 }
//! }
//! ```
//!
//! This scene caches the "enemy" scene by adding the  `:` prefix (however caching scene functions like this is not currently supported)
//! ```ignore
//! bsn! {
//!     :enemy
//!     Health { max: 200 }
//! }
//! ```
//!
//! Scene assets always need to be cached using the `:` prefix.
//! Note that the `.bsn` file format is not yet released. (This already works, assuming theres a loader for the asset format)
//! ```ignore
//! bsn! {
//!    :"enemy.bsn"
//!    Health { max: 200 }
//! }
//! ```
//!
//! ## Loading Assets into Scenes
//!
//! Without the use of scenes, loading an asset requires referencing the [`AssetServer`] explicitly:
//!
//! ```ignore
//! let handle: Handle<Image> = asset_server.load("player.png");
//! commands.spawn(Sprite { image: handle, ..default() });
//! ```
//!
//! This can be particularly frustrating when defining helper functions for spawning entities,
//! which require you to pass [`AssetServer`] or handles through multiple layers of function calls.
//!
//! In [`bsn!`], asset paths work directly as field values. When a component field is a
//! [`Handle<T>`], the [`bsn!`] macro accepts a string literal in its place. Under the hood,
//! this creates a [`HandleTemplate`] that calls [`AssetServer::load`] at resolve time.
//! If the asset has already been loaded, this returns the existing handle rather than
//! loading it again.
//!
//! ```ignore
//! commands.spawn_scene(bsn! {
//!     Sprite { image: "player.png" }
//! });
//! ```
//!
//! A [`Component`] must also derive [`FromTemplate`] to accept asset paths:
//!
//! ```ignore
//! #[derive(Component, FromTemplate)]
//! struct Icon {
//!     image: Handle<Image>,
//!     tint: Color,
//! }
//!
//! // "icon.png" is converted to a HandleTemplate<Image> via implicit .into()
//! commands.spawn_scene(bsn! {
//!     Icon { image: "icon.png", tint: Color::WHITE }
//! });
//! ```
//!
//! [`AssetServer`]: bevy_asset::AssetServer
//! [`AssetServer::load`]: bevy_asset::AssetServer::load
//! [`HandleTemplate`]: bevy_asset::HandleTemplate
//! [`Handle<T>`]: bevy_asset::Handle
//!
//! ## Observers
//!
//! Use [`on()`](on) inside [`bsn!`] to attach an entity [`Observer`]. Entity observers are closures or
//! functions which fire when a given [`EntityEvent`] is triggered and targets this entity.
//! The first parameter's type determines which event is observed. Multiple observers can be added to
//! the same entity, and the observer has full access to the ECS via [system parameters](bevy_ecs::system#system-parameter-list):
//!
//! ```ignore
//! #[derive(EntityEvent)]
//! struct Damage {
//!     entity: Entity,
//!     amount: u32,
//! }
//!
//! #[derive(EntityEvent)]
//! struct Heal {
//!     entity: Entity,
//!     amount: u32,
//! }
//!
//! fn player() -> impl Scene {
//!     bsn! {
//!         Health { max: 100, current: 100 }
//!         // Each `on(...)` attaches a separate observer.
//!         on(|damage: On<Damage>, mut query: Query<&mut Health>| {
//!             let mut health = query.get_mut(damage.entity).unwrap();
//!             health.current = health.current.saturating_sub(damage.amount);
//!         })
//!         on(on_heal)
//!     }
//! }
//!
//! fn on_heal(heal: On<Heal>, query: Query<&mut Health>){
//!     let mut health = query.get_mut(heal.entity).unwrap();
//!     health.current = (health.current + heal.amount).min(health.max);
//! }
//! ```
//!
//! This is useful for self-contained logic like click handlers, damage reactions,
//! or scripting-style triggers.
//! Closures passed to [`on`] work like any Rust closure:
//! you can use [`move`](https://doc.rust-lang.org/std/keyword.move.html) and capture variables from the enclosing scope normally.
//!
//! ## Using Dynamic Expressions in Scenes
//!
//! The [`bsn!`] macro is not limited to static data. Because scene functions are plain
//! Rust functions, you can accept parameters and capture variables from the enclosing scope.
//! Use `{...}` (curly braces) anywhere a value is expected to embed an arbitrary Rust expression:
//!
//! ```ignore
//! fn enemy(hp: u32, name: &str) -> impl Scene {
//!     let name_string = name.to_string();
//!     bsn! {
//!         #{name}
//!         Health { current: {hp / 2}, max: hp }
//!         Sprite { image: {name_string + ".png"} }
//!     }
//! }
//!
//! // Call it like an ordinary Rust function
//! commands.spawn_scene(bsn! { enemy(200, "goblin") });
//! ```
//!
//! Braces are required when the macro would otherwise misparse the expression
//! and for complex expressions like `{hp * 2}`.
//!
//! ### Dynamic template values
//!
//! A [`Template`] value, such as an instance of a Component, cannot be directly passed in to a `bsn!` block, as `bsn!`
//! expects "scene variables" in that position. Instead use `template_value(...)` which accepts a given component [`Template`] value
//! and returns a [`Scene`] implementation for it.
//!
//! ```ignore
//! fn enemy(translation: Vec3){
//!     let transform = Transform::from_translation(translation);
//!     bsn! {
//!         #Foo
//!         template_value(transform)
//!     }
//!
//! }
//! ```
//!
//! ### Ad-hoc template functions
//!
//! Sometimes you need custom behavior or world access to create a [`Template`].
//! If this is the case, you can use [`template`](fn@template) instead of a custom [`FromTemplate`] or [`Template`] implementation.
//! In [`template`](fn@template) you get access to a [`TemplateContext`](bevy_ecs::template::TemplateContext) which
//! contains the [`EntityWorldMut`] and a collection of named entity references.
//!
//! ```ignore
//! bsn! {
//!     #Foo
//!     template(|ctx| {
//!         Foo(ctx.resource::<MyAssetCollection>().get("generated_asset_name"))
//!     })
//! }
//! ```
//!
//! ### Expressions as scenes
//!
//! You can insert a [`Scene`] or [`SceneList`] in another Scene using curly-bracketed expressions:
//!
//! ```ignore
//! fn container(contents: impl SceneList) -> impl Scene {
//!     bsn! {
//!         Children [
//!             #Header,
//!             {contents},
//!             #Footer,
//!         ]
//!     }
//! }
//!
//! let items = bsn_list![#A, #B, #C]; // or bsn! if container takes a `impl Scene`
//! commands.spawn_scene(container(items));
//! ```
//!
//! ### Conditional values
//!
//! There is no `if`/`match` syntax inside the [`bsn!`] grammar (yet!), but you can embed
//! conditionals via `{...}` blocks or handle them outside the macro:
//!
//! ```ignore
//! fn unit(is_boss: bool) -> impl Scene {
//!     let hp = if is_boss { 500 } else { 100 };
//!     bsn! { Health { current: hp, max: hp } }
//! }
//! ```
//! One way to achieve conditional scenes is using a [`Box<dyn Scene>`] to store different scenes in one variable.
//! ```ignore
//! fn unit(is_boss: bool, level: u32) -> impl Scene {
//!     let scene: Box<dyn Scene> = if is_boss {
//!         Box::new(bsn! {
//!             Boss
//!             Followers [ // the boss is followed by some grunts
//!                 :unit(false, level - 1) #Grunt1,
//!                 :unit(false, level - 2) #Grunt2
//!             ]
//!         })
//!     } else {
//!         Box::new(bsn! { Grunt })
//!     };
//!     bsn! {
//!         Level(level)
//!         {scene}
//!     }
//! }
//! ```
//!
//! We plan on making "conditional scenes" easier to define in future releases.
//!
//! ## Scene Components
//!
//! A [`SceneComponent`] is a specialized type of [`Component`] that has an associated [`Scene`]:
//!
//! ```
//! # use bevy_scene::prelude::*;
//! # use bevy_ecs::prelude::*;
//! # #[derive(Component, Default, Clone)]
//! # struct Sword;
//! # #[derive(Component, Default, Clone)]
//! # struct Shield;
//! #[derive(SceneComponent, Default, Clone)]
//! struct Player {
//!     score: usize
//! }
//!
//! impl Player {
//!     fn scene() -> impl Scene {
//!         bsn! {
//!             #Player
//!             Children [
//!                 #RightHand Sword,
//!                 #LeftHand Shield,
//!             ]
//!         }
//!     }
//! }
//! ```
//!
//! This enables including the [`SceneComponent`] as a scene, using the following syntax:
//!
//! ```no_run
//! # use bevy_scene::prelude::*;
//! # use bevy_ecs::prelude::*;
//! # #[derive(SceneComponent, Default, Clone)]
//! # struct Player {
//! #    score: usize
//! # }
//! # impl Player {
//! #   fn scene() -> impl Scene {}
//! # }
//! # let mut world = World::new();
//! world.spawn_scene(bsn! {
//!  @Player { score: 0 }
//! });
//! ```
//!
//! This will spawn the `Player` component _and_ the entire scene with it. This means that you write
//! systems that query for the `Player` component, they can generally assume the rest of the scene will be there
//! too!
//!
//! [`SceneComponent`]s can only be spawned using scene APIs like [`World::spawn_scene`]. Spawning
//! them using [`World::spawn`] will log an error.
//!
//! ### Custom Scene Functions
//!
//! When deriving [`SceneComponent`], it defaults to using `Self::scene` as the "scene function".
//! Scene functions can also be manually specified:
//!
//! ```
//! # use bevy_scene::prelude::*;
//! # use bevy_ecs::prelude::*;
//! #[derive(SceneComponent, Default, Clone)]
//! #[scene(player)]
//! struct Player;
//!
//! fn player() -> impl Scene {
//!    bsn! { /* scene here */}
//! }
//! ```
//!
//! ### `SceneComponent` Asset Paths
//!
//! Note: Currently, Bevy does not include a `.bsn` asset format. These docs exist to help you understand what is planned, and what is currently possible
//! with third-party asset formats.
//!
//! Alternatively, a scene asset path can be specified:
//!
//! ```
//! # use bevy_scene::prelude::*;
//! # use bevy_ecs::prelude::*;
//! #[derive(SceneComponent, Default, Clone)]
//! #[scene("player.bsn")]
//! struct Player {
//!     score: usize
//! }
//! ```
//!
//!
//! ### Scene Components are Template-able
//!
//! Just like other [`Component`]s, [`SceneComponent`]s are "template-able"
//!
//! ```no_run
//! # use bevy_scene::prelude::*;
//! # use bevy_ecs::{prelude::*, template::TemplateContext};
//! # let mut world = World::new();
//! # struct Handle<T>(std::marker::PhantomData<T>);
//! # struct HandleTemplate<T>(String, std::marker::PhantomData<T>);
//! # impl<'a, T> From<&'a str> for HandleTemplate<T> {
//! #   fn from(value: &'a str) -> Self { todo!() }
//! # }
//! # impl<T> Default for HandleTemplate<T> {
//! #   fn default() -> Self { todo!() }
//! # }
//! # struct Image;
//! # impl<T> Template for HandleTemplate<T> {
//! #   type Output = Handle<T>;
//! #   fn build_template(&self, context: &mut TemplateContext) -> Result<Handle<T>> { todo!() }
//! #   fn clone_template(&self) -> Self { todo!() }
//! # }
//! # impl<T> FromTemplate for Handle<T> {
//! #   type Template = HandleTemplate<T>;
//! # }
//! #[derive(SceneComponent, FromTemplate)]
//! struct Player {
//!     image: Handle<Image>,
//! }
//!
//! impl Player {
//!     fn scene() -> impl Scene {
//!         bsn! { /* scene here */}
//!     }
//! }
//!
//! world.spawn_scene(bsn! {
//!    @Player { image: "player.png" }
//! });
//! ```
//!
//! ### `SceneComponent` Props
//!
//! Sometimes it is desirable to "parameterize" a scene: pass in values to the scene which determine
//! what the scene outputs are. The answer to this in BSN is "scene props":
//!
//! ```no_run
//! # use bevy_scene::prelude::*;
//! # use bevy_ecs::prelude::*;
//! # #[derive(Component, Default, Clone)]
//! # struct Node;
//! # #[derive(Component, Default, Clone)]
//! # struct Text(String);
//! # let mut world = World::new();
//! /// A UI widget that repeats "hello" text a given number of times.
//! #[derive(SceneComponent, Default, Clone)]
//! #[scene(HelloRepeaterProps)]
//! struct HelloRepeater;
//!
//! #[derive(Default)]
//! struct HelloRepeaterProps {
//!     repeat: usize,
//! }
//!
//! impl HelloRepeater {
//!     fn scene(props: HelloRepeaterProps) -> impl Scene {
//!         let hellos = (0..props.repeat)
//!             .map(|_| bsn! { Text("hello") })
//!             .collect::<Vec<_>>();
//!         bsn! {
//!             Node
//!             Children [
//!                 {hellos}
//!             ]
//!         }
//!     }
//! }
//!
//! world.spawn_scene(bsn! {
//!    @HelloRepeater {
//!        @repeat: 5
//!    }
//! });
//! ```
//!
//! Notice the `@field` syntax, which specifies that a prop is being set instead of a field.
//! Props are evaluated "immediately" when the scene is included in another scene.
//! This means that they are not "patchable", as at that point they have already been evaluated,
//! and they _produce_ "patchable" outputs.
//!
//! You can set _both_ props and normal fields at the same time:
//! ```no_run
//! # use bevy_scene::prelude::*;
//! # use bevy_ecs::prelude::*;
//! # let mut world = World::new();
//! # impl Widget {
//! #   fn scene(props: WidgetProps) -> impl Scene {}
//! # }
//! #[derive(SceneComponent, Default, Clone)]
//! #[scene(WidgetProps)]
//! struct Widget {
//!     value: usize
//! }
//!
//! #[derive(Default)]
//! struct WidgetProps {
//!     border: bool,
//! }
//!
//! world.spawn_scene(bsn! {
//!    @Widget {
//!        @border: true,
//!        value: 10,
//!    }
//! });
//! ```
//!
//! ### The Scene Component is Always Added
//!
//! Specifying the scene component manually in the scene function is not necessary. It will be added
//! automatically:
//!
//! ```
//! # use bevy_scene::prelude::*;
//! #[derive(SceneComponent, Default, Clone)]
//! struct Player;
//!
//! impl Player {
//!     fn scene() -> impl Scene {
//!         bsn! {
//!             // No need to specify a Player component here.
//!             // It is implied!
//!         }
//!     }
//! }
//! ```
//! However you _can_ patch the scene component in the scene if you would like. This comes in handy
//! if you would like props to contribute to the scene component's fields:
//!
//! ```
//! # use bevy_scene::prelude::*;
//! # #[derive(Default)]
//! # struct PlayerProps { size_in_millimeters: f32 };
//! # #[derive(SceneComponent, Default, Clone)]
//! # #[scene(PlayerProps)]
//! # struct Player { size_in_meters: f32 }
//! impl Player {
//!     fn scene(props: PlayerProps) -> impl Scene {
//!         bsn! {
//!             Player {
//!                 size_in_meters: {props.size_in_millimeters / 1000. }
//!             }
//!         }
//!     }
//! }
//! ```
//!
//! ### Scene Components vs Required Components
//!
//! At first glance, Scene Components and [Required Components](bevy_ecs::component::Component) solve
//! similar problems. They both provide a mechanism to initialize components with other components.
//!
//! They are functionally quite different however. It is worth understanding the differences and
//! tradeoffs:
//!
//! - **Required Components**: Context-less (ex: Default constructors), non-hierarchical, can always
//!   be applied immediately, not dependency aware, automatically enforced at runtime as components
//!   are added, not patchable, pretty low overhead, not a lot of features / functionality
//! - **Scene Components**: Require context (ex: World access and "Entity Spawn Context", such as
//!   entity references), hierarchical (spawn children), cannot always be applied immediately
//!   (can have dependencies that aren't loaded yet), dependency aware, only enforced at spawn
//!   time, patchable, more dynamic / higher overhead, many features.
//!
//! Some good rules of thumb:
//!
//! - Are you building something "hierarchical" / with related entities? Use [`SceneComponent`].
//! - Do you want or need the full capabilities of the scene system? Use [`SceneComponent`].
//! - Are you spawning something that has dependencies / needs World access? use [`SceneComponent`].
//! - Are you defining "flat" components that aren't really scenes on their own? Use required components.
//! - Do you need the "required" components to be automatically added in non-scene contexts?  Use required components.
//! - Is spawn performance a very high priority? Use required components.
//!
//! ## .bsn Asset Format
//!
//! Bevy does not currently have support for `.bsn` files,
//! but intends to offer a `.bsn` asset format in future releases.
//!
//! This would allow you to define your scenes on disk,
//! creating/modifying them in various authoring tools and using asset hot-reloading.
//!
//! This format is intended to have broad syntactic compatibility with the `bsn!` macro,
//! making it easy to port your content between both the macro and the asset form.
//!
//! When planning your future use of `.bsn` asset files (which are not currently shipped), be aware that
//! unlike `bsn!` macro calls `.bsn` assets will not support expressions or other dynamic features directly.
//!
//! For now, you should use existing non-Bevy asset formats like glTF,
//! search for ecosystem implementations or stick to `bsn!` macro calls.
//!
//! Note that the architecture to support an asset format already exists,
//! allowing community implementations/experimentation until an official version exists. An example of how to go about this
//! can be found in the [scene benchmarks](<https://github.com/bevyengine/bevy/blob/v0.19.0/benches/benches/bevy_scene/spawn.rs#L414>)
//!
//! [`Template`]: bevy_ecs::template::Template
//! [`FromTemplate`]: bevy_ecs::template::FromTemplate
//! [`Asset`]: bevy_asset::Asset
//! [`Entity`]: bevy_ecs::entity::Entity
//! [`EntityTemplate`]: bevy_ecs::template::EntityTemplate
//! [`RelationshipTarget`]: bevy_ecs::relationship::RelationshipTarget
//! [`EntityEvent`]: bevy_ecs::event::EntityEvent
//! [`Name`]: bevy_ecs::name::Name
//! [`World::spawn_scene`]: crate::WorldSceneExt::spawn_scene
//! [`Commands::spawn_scene`]: crate::CommandsSceneExt::spawn_scene
//! [`World::queue_spawn_scene`]: crate::WorldSceneExt::queue_spawn_scene
//! [`Commands::queue_spawn_scene`]: crate::CommandsSceneExt::queue_spawn_scene

/// The Bevy Scene prelude.
///
/// This includes the most common types in this crate, re-exported for your convenience.
pub mod prelude {
    pub use crate::{
        bsn, bsn_list, on, template_value, CommandsSceneExt, EntityCommandsSceneExt,
        EntityWorldMutSceneExt, PatchFromTemplate, PatchTemplate, Scene, SceneComponent, SceneList,
        ScenePatchInstance, SpawnListSystem, SpawnSystem, WorldSceneExt,
    };
}

/// Functionality used by the [`bsn!`] macro.
pub mod macro_utils;

extern crate alloc;

mod resolved_scene;
mod scene;
mod scene_component;
mod scene_list;
mod scene_patch;
mod spawn;
mod spawn_system;

pub use resolved_scene::*;
pub use scene::*;
pub use scene_component::*;
pub use scene_list::*;
pub use scene_patch::*;
pub use spawn::*;
pub use spawn_system::*;

use bevy_app::{App, Plugin, SceneSpawnerSystems, SpawnScene};
use bevy_asset::AssetApp;
use bevy_ecs::prelude::*;

/// Creates a `Scene` using BSN (Bevy Scene Notation) syntax.
///
/// These docs primarily contain syntax
/// See [`bevy_scene`](crate) module-level docs for in-depth details about usage and interactions.
///
///
/// ## Syntax Reference
///
/// The syntax consists of scene entries which are listed below, which all act on the scene in some way.
/// Often, this is by inserting/patching a component or its values or including other scenes.
/// Scene entries can have prefix characters which specify/disambiguate the following entry.
///
/// ```text
/// bsn! {
///     <scene entry>
///     :<cached scene include>
///     #<name>
///     @<SceneComponent>
///     ~<custom Template>
/// }
/// ```
///
/// ### Scene entries
/// | Examples                                   | Explanation                                                                                                    |
/// | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------- |
/// | `CompA`                                    | A unit or default component. Fields, if any exist, will be default                                             |
/// | `CompA(val)`<br>`CompA(val, val)`          | Tuple Component with some fields specified. Unspecified fields will be default, see [patching](self#patching)  |
/// | `CompA { name: val }`                      | Component with some fields specified. Unspecified fields will be default, see [patching](self#patching)        |
/// | `mymodule::CompA { name: val }`            | Same as above, but referring to the component by module path                                                   |
/// | `CompA { name }`                           | Component with Rust's "field assignment shorthand". Evaluates to `CompA { name: name.into() }`                 |
/// | `MyEnum::Variant`                          | Enum Component `MyEnum` with the `Variant` variant                                                             |
/// | `template_value(component)`                | Insert the component value from a variable `component`                                                         |
/// | `template_value(CompA::from_str("foo"))`   | Insert the component value by immediately calling the constructor                                              |
/// | `template(|context| { ... })`              | Register a function/closure returning a Template (eg. Component). Its passed [`context`] allowing World access |
/// | `~MyType`<br>`~MyType {name: var}`         | Type implementing [`Template`], the prefix is used to distinguish it from Components which use [`FromTemplate`]|
/// | **Including Scenes**                       |                                                                                                                |
/// | `scene()`<br>`scene(val)`                  | Include the result of a `impl `[`Scene`] function                                                              |
/// | `{ expr }`                                 | Include the result of `expr`, which should be a [`Scene`]                                                      |
/// | `@MySceneComp`                             | Include a [`SceneComponent`]. Fields, if any exist, will be default                                            |
/// | `@MySceneComp { @prop: val }`              | Include a [`SceneComponent`] with a `prop` field, passed to this components scene function                     |
/// | `@MySceneComp { name: val }`               | Include a [`SceneComponent`] with a normal field, works the same as it does for normal components              |
/// | `@MySceneComp { @prop: val1, name: val2 }` | Include a [`SceneComponent`] with both a `prop` and a field                                                    |
/// | `:"scene.bsn"`                             | <div class="warning">Asset format not yet implemented!</div> Include a cached scene asset file                  |
/// | `:scene()`<br>`:@MySceneComp`              | <div class="warning">Caching for scene includes not yet implemented!</div> Include a cached scene function     |
/// | **Named entity references**                |                                                                                                                |
/// | `#MyName`                                  | Becomes `Name("MyName")` when used as a `part` of a scene                                                      |
/// | `CompA(#MyName)`<br>`scene(#MyName)`       | Referring to the entity which was named `MyName` in this scope, results in an [`EntityTemplate`] being passed  |
/// | `Name("Foo")`                              | Manually sets the Name component, can be put after a `#MyName` to use a custom name while allowing references  |
/// | **Observers**                              |                                                                                                                |
/// | `on(\|ev: On<Ev>\| { … })`                 | Attaches an entity [`observer`] for the [`EntityEvent`] `Ev` to this entity. In this example, using a closure  |
/// | `on(my_observer)`                          | Attaches an entity [`observer`] for the [`EntityEvent`] `Ev` to this entity. In this example, using a function |
/// | **Relationships**                          |                                                                                                                |
/// | `Children []`                              | Spawns each entry as a child of this entity, see **Scene Lists** below for details                             |
/// | `ChildOf(entity)`                          | Makes **this** entity a child of `entity`, accepts an [`Entity`] or a `#Name` reference ([`EntityTemplate`])    |
/// | `MyRel []`                                 | Like `Children`, but uses any `RelationshipTarget` component                                                   |
///
/// [`context`]: bevy_ecs::template::TemplateContext
/// [`EntityTemplate`]: bevy_ecs::template::EntityTemplate
/// ### Scene Lists
///
/// In `bsn_list!` and Relationships a list of scenes delimited by `[]` is allowed.
/// Unlike parts of a scene, which are whitespace-separated, the scenes in a scene list are comma-separated.
///
/// Note: examples are part of a relationship like `Children [<example here>]` or a list macro like `bsn_list![<example here>]`
///
/// | Example                      | Meaning                                                                                                               |
/// | ---------------------------- | --------------------------------------------------------------------------------------------------------------------- |
/// | `[ #Child1 CompA, #Child2 ]`     | Spawns 2 children, one with `(Name("Child1"), CompA::default())` and the other with `Name("Child2")`              |
/// | `[ (#Child1 CompA), (#Child2) ]` | Same as above, with explicit parentheses                                                                          |
/// | `[ #First, { expr }, #Last ]`   | Spawns an entity with name `First`, then every entity from the `SceneList` returned by expr, then one named `Last` |
/// | `[ #First, ({ expr }), #Last ]` | Same as above, but the `expr` should result in a `Scene` and will only spawn one entity using it                   |
///
/// ### Values
///
/// Values in BSN (as in `val`,`val1` etc used above) are generally any literal Rust values, plus a few bsn-specific quirks.
///
///
/// | Example                          | Meaning       | Explanation                                                                             |
/// | -------------------------------- | ------------- | --------------------------------------------------------------------------------------- |
/// | `1`                              | Unsigned int  | Positive number, common types: [`usize`], [`u8`], [`u32`], [`u64`]                      |
/// | `1` or `-1`                      | Signed int    | Positive or negative number, common types: `i32`, `i64`                                 |
/// | `1.1` or `-0.1` or `1.` or `-2.` | Float         | Floating point number, common types: `f32`, `f64`                                       |
/// | `true` or `false`                | Bool          | Boolean, type: [`bool`]                                                                 |
/// | `"somename"`                     | String        | Text, types: `String` or `&'static str`                                                 |
/// | `"mypicture.png"`                | Asset path    | Asset, when used in a field which expects a [`Handle`] to the matching `Asset` type     |
/// | `some_function(1)`                        | Function call | Calls a function with the provided arguments                                            |
/// | `GREEN`                          | Constant      | Fixed value, must be in scope                                                           |
/// | `std::f32::consts::PI`           | Constant      | Fixed value, uses full path so doesn't need to be in scope                              |
/// | **Expression syntax**            |               |                                                                                         |
/// | `{ 1 + 2 }`                      | Expression    | Any rust expression works in `{}`, in this case addition of 2 integers                  |
/// | `{ vec![true, false] }`          | Vector        | An expression returning a [`Vec`], a collection of multiple items of one specific type. |
/// | `{ bsn!{ Text("foo") Style } }`  | Scene         | Sometimes, you may need to pass a small `Scene` as a value to something else            |
///
/// ### Other Rust syntax
///
/// If you're new to Rust, you might struggle with some of its syntax when you see it in or around BSN.
/// Here are some syntax snippets which haven't been shown so far:
///
/// | Syntax            | Meaning       | Explanation                                                     |
/// | ----------------- | ------------- | --------------------------------------------------------------- |
/// | `\|param\| { … }` | Closure       | A closure; effectively an unnamed function                      |
/// | `Vec<T>`          | Generic type  | A type with a generic type parameter `T`                        |
/// | `//`              | Comment       | Line comment; all text after `//` on the same line is ignored   |
/// | `/* */`           | Block comment | Standard Rust block comment; all text inside `/* */` is ignored |
/// | `bsn! { … }`      | Macro call    | Calls a macro on the value inside of the braces                 |
///
/// ### Syntax example
// Note: the actual syntax example comes from the original bevy_scene_macros::bsn docs.
// rustdoc appends these #[doc(inline)] docs before those
// rust-analyzer ignores these docs and only shows the original ones, see https://github.com/rust-lang/rust-analyzer/issues/14079
// despite those being #[doc(hidden)]
//
#[doc(inline)]
pub use bevy_scene_macros::bsn;

/// Creates a `SceneList` using BSN (Bevy Scene Notation) syntax.
///
/// This is useful when you want multiple root entities in your scene
/// that do not share a common parent, or if you want to create multiple scenes at once.
///
/// Like in [`bsn!`], commas separate entities,
/// while whitespace separates components on the same entity.
///
/// All root entries in a [`bsn_list!`] share a single name scope, so sibling root entities
/// can cross-reference each other by `#Name`.
/// This is not possible with separate [`bsn!`] calls, and is a key motivation for using [`bsn_list!`].
///
/// See [`bsn!`] for more details on syntax.
/// See the `bevy_scene` crate docs for a high-level overview of the key concepts.
#[doc(inline)]
pub use bevy_scene_macros::bsn_list;
pub use bevy_scene_macros::SceneComponent;

/// Adds support for spawning Bevy Scenes. See [`Scene`], [`SceneList`], [`ScenePatch`], and the [`bsn!`] macro for more information.
#[derive(Default)]
pub struct ScenePlugin;

impl Plugin for ScenePlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<QueuedScenes>()
            .init_resource::<WaitingScenes>()
            .init_asset::<ScenePatch>()
            .init_asset::<SceneListPatch>()
            .add_systems(
                SpawnScene,
                (resolve_scene_patches, spawn_queued)
                    .chain()
                    .in_set(SceneSpawnerSystems::SceneSpawn)
                    .after(SceneSpawnerSystems::WorldInstanceSpawn),
            )
            .add_observer(on_add_scene_patch_instance);
    }
}

#[cfg(test)]
mod tests {
    use crate::{self as bevy_scene, ScenePlugin};
    use crate::{prelude::*, ScenePatch};
    use alloc::sync::Arc;
    use bevy_app::{App, TaskPoolPlugin};
    use bevy_asset::io::memory::{Dir, MemoryAssetReader};
    use bevy_asset::io::{AssetSourceBuilder, AssetSourceId};
    use bevy_asset::{Asset, AssetApp, AssetLoader, AssetPlugin, AssetServer, Assets, Handle};
    use bevy_ecs::lifecycle::HookContext;
    use bevy_ecs::name::Name;
    use bevy_ecs::prelude::*;
    use bevy_ecs::relationship::Relationship;
    use bevy_ecs::system::{system_value, SystemHandle};
    use bevy_ecs::world::DeferredWorld;
    use bevy_reflect::TypePath;
    use bevy_scene_macros::SceneComponent;
    use std::path::Path;
    use std::sync::Mutex;

    fn test_app() -> App {
        let mut app = App::new();
        app.add_plugins((
            TaskPoolPlugin::default(),
            AssetPlugin::default(),
            ScenePlugin,
        ));
        app
    }

    #[test]
    fn cached_patching() {
        let mut app = test_app();
        let world = app.world_mut();

        #[derive(Component, FromTemplate)]
        struct Position {
            x: f32,
            y: f32,
            z: f32,
        }

        fn b() -> impl Scene {
            bsn! {
                a()
                Position { x: 1. }
                Children [ #Y ]
            }
        }

        fn a() -> impl Scene {
            bsn! {
                Position { y: 2. }
                Children [ #X ]
            }
        }

        let id = world.spawn_scene(b()).unwrap().id();
        let root = world.entity(id);

        let position = root.get::<Position>().unwrap();
        assert_eq!(position.x, 1.);
        assert_eq!(position.y, 2.);
        assert_eq!(position.z, 0.);

        let children = root.get::<Children>().unwrap();
        assert_eq!(children.len(), 2);

        let x = world.entity(children[0]);
        let name = x.get::<Name>().unwrap();
        assert_eq!(name.as_str(), "X");

        let y = world.entity(children[1]);
        let name = y.get::<Name>().unwrap();
        assert_eq!(name.as_str(), "Y");
    }

    #[test]
    fn cached_patching_order() {
        let mut app = test_app();
        let world = app.world_mut();

        #[derive(Component, FromTemplate)]
        struct Position {
            x: f32,
            y: f32,
            z: f32,
        }

        fn a() -> impl Scene {
            bsn! {
                Position { x: 2. }
            }
        }

        fn b() -> impl Scene {
            bsn! {
                Position { x: 1., y: 1., z: 1. }
                a()
            }
        }

        let root = world.spawn_scene(b()).unwrap();
        let position = root.get::<Position>().unwrap();
        // Overridden by a
        assert_eq!(position.x, 2.);
        // Remains from b
        assert_eq!(position.y, 1.);
        assert_eq!(position.z, 1.);
    }

    #[test]
    fn loaded_asset_cached_patching() {
        #[derive(Component, FromTemplate)]
        struct Position {
            x: f32,
            y: f32,
            z: f32,
        }

        fn b() -> impl Scene {
            bsn! {
                :"a.bsn"
                Position { x: 1. }
                Children [ #Y ]
            }
        }

        fn a() -> impl Scene {
            bsn! {
                Position { y: 2. }
                Children [ #X ]
            }
        }

        #[derive(SceneComponent, Default, Clone)]
        #[scene("a.bsn")]
        struct AWidget {
            value: usize,
        }

        let mut app = App::new();
        let dir = Dir::default();
        let dir_clone = dir.clone();
        app.register_asset_source(
            AssetSourceId::Default,
            AssetSourceBuilder::new(move || {
                Box::new(MemoryAssetReader {
                    root: dir_clone.clone(),
                })
            }),
        );
        app.add_plugins((
            TaskPoolPlugin::default(),
            AssetPlugin::default(),
            ScenePlugin,
        ));

        app.finish();
        app.cleanup();
        // Create a fake loader to act as a ScenePatch loaded from a file.
        app.register_asset_loader(FakeSceneLoader);

        #[derive(TypePath)]
        struct FakeSceneLoader;

        impl AssetLoader for FakeSceneLoader {
            type Asset = ScenePatch;
            type Error = std::io::Error;
            type Settings = ();

            async fn load(
                &self,
                _reader: &mut dyn bevy_asset::io::Reader,
                _settings: &Self::Settings,
                load_context: &mut bevy_asset::LoadContext<'_>,
            ) -> Result<Self::Asset, Self::Error> {
                Ok(ScenePatch::load_with(load_context, a()))
            }
        }

        // Insert an asset that the fake loader can fake read.
        dir.insert_asset_text(Path::new("a.bsn"), "");
        let asset_server = app.world().resource::<AssetServer>().clone();
        let handle = asset_server.load("a.bsn");
        assert!(app.world().get_resource::<Assets<ScenePatch>>().is_some());
        run_app_until(&mut app, || asset_server.is_loaded(&handle));
        let patch = app
            .world()
            .resource::<Assets<ScenePatch>>()
            .get(&handle)
            .unwrap();
        assert!(patch.resolved.is_some());

        let world = app.world_mut();
        let id = world.spawn_scene(b()).unwrap().id();
        let root = world.entity(id);

        let position = root.get::<Position>().unwrap();
        assert_eq!(position.x, 1.);
        assert_eq!(position.y, 2.);
        assert_eq!(position.z, 0.);

        let children = root.get::<Children>().unwrap();
        assert_eq!(children.len(), 2);

        let x = world.entity(children[0]);
        let name = x.get::<Name>().unwrap();
        assert_eq!(name.as_str(), "X");

        let y = world.entity(children[1]);
        let name = y.get::<Name>().unwrap();
        assert_eq!(name.as_str(), "Y");

        // "a.bsn" as AWidget's "component scene"
        let id = world
            .spawn_scene(bsn! {@AWidget { value: 2 }})
            .unwrap()
            .id();
        let root = world.entity(id);

        let a_widget = root.get::<AWidget>().unwrap();
        assert_eq!(a_widget.value, 2);
        let position = root.get::<Position>().unwrap();
        assert_eq!(position.x, 0.);
        assert_eq!(position.y, 2.);
        assert_eq!(position.z, 0.);

        let children = root.get::<Children>().unwrap();
        assert_eq!(children.len(), 1);

        let x = world.entity(children[0]);
        let name = x.get::<Name>().unwrap();
        assert_eq!(name.as_str(), "X");
    }

    #[test]
    fn inline_scene_patching() {
        let mut app = test_app();
        let world = app.world_mut();

        #[derive(Component, FromTemplate)]
        struct Position {
            x: f32,
            y: f32,
            z: f32,
        }

        fn b() -> impl Scene {
            bsn! {
                a()
                Position { x: 1. }
                Children [ #Y ]
            }
        }

        fn a() -> impl Scene {
            bsn! {
                Position { y: 2. }
                Children [ #X ]
            }
        }

        let id = world.spawn_scene(b()).unwrap().id();
        let root = world.entity(id);

        let position = root.get::<Position>().unwrap();
        assert_eq!(position.x, 1.);
        assert_eq!(position.y, 2.);
        assert_eq!(position.z, 0.);

        let children = root.get::<Children>().unwrap();
        assert_eq!(children.len(), 2);

        let x = world.entity(children[0]);
        let name = x.get::<Name>().unwrap();
        assert_eq!(name.as_str(), "X");

        let y = world.entity(children[1]);
        let name = y.get::<Name>().unwrap();
        assert_eq!(name.as_str(), "Y");
    }

    #[test]
    fn hierarchy() {
        let mut app = test_app();
        let world = app.world_mut();

        fn scene() -> impl Scene {
            bsn! {
                #A
                Children [
                    (
                        #B
                        Children [
                            #X
                        ]
                    ),
                    (
                        #C
                        Children [
                            #Y
                        ]
                    )
                ]
            }
        }

        let id = world.spawn_scene(scene()).unwrap().id();

        let a = world.entity(id);
        let name = a.get::<Name>().unwrap();
        assert_eq!(name.as_str(), "A");

        let children = a.get::<Children>().unwrap();
        assert_eq!(children.len(), 2);

        let b = world.entity(children[0]);
        let c = world.entity(children[1]);

        let name = b.get::<Name>().unwrap();
        assert_eq!(name.as_str(), "B");

        let name = c.get::<Name>().unwrap();
        assert_eq!(name.as_str(), "C");

        let children = b.get::<Children>().unwrap();
        assert_eq!(children.len(), 1);
        let x = world.entity(children[0]);
        let name = x.get::<Name>().unwrap();
        assert_eq!(name.as_str(), "X");

        let children = c.get::<Children>().unwrap();
        assert_eq!(children.len(), 1);
        let y = world.entity(children[0]);
        let name = y.get::<Name>().unwrap();
        assert_eq!(name.as_str(), "Y");
    }

    #[test]
    fn constant_values() {
        let mut app = test_app();
        let world = app.world_mut();

        const X_AXIS: usize = 1;
        const XAXIS: usize = 2;

        #[derive(Component, FromTemplate)]
        struct Value(usize);

        fn x_axis() -> impl Scene {
            bsn! {Value(X_AXIS)}
        }

        fn xaxis() -> impl Scene {
            bsn! {Value(XAXIS)}
        }

        let entity = world.spawn_scene(x_axis()).unwrap();
        assert_eq!(entity.get::<Value>().unwrap().0, 1);

        let entity = world.spawn_scene(xaxis()).unwrap();
        assert_eq!(entity.get::<Value>().unwrap().0, 2);
    }

    #[derive(Component, FromTemplate)]
    struct Reference(Entity);

    #[test]
    fn bsn_name_references() {
        let mut app = test_app();
        let world = app.world_mut();
        fn a() -> impl Scene {
            bsn! {
                #X
                Children [
                    (b() Reference(#X))
                ]
            }
        }

        fn b() -> impl Scene {
            let inline = bsn! {#Y Reference(#Y) Children [ Reference(#Y)] };
            bsn! {
                #X
                Children [
                    Reference(#X),
                    (inline Reference(#X)),
                ]
            }
        }

        let id = world.spawn_scene(a()).unwrap().id();

        let a = world.entity(id);
        let name = a.get::<Name>().unwrap();
        assert_eq!(name.as_str(), "X");

        let children = a.get::<Children>().unwrap();
        assert_eq!(children.len(), 1);

        let b = world.entity(children[0]);
        let reference = b.get::<Reference>().unwrap();
        assert_eq!(reference.0, id);

        let b_name = b.get::<Name>().unwrap();
        assert_eq!(b_name.as_str(), "X");

        let grandchildren = b.get::<Children>().unwrap();
        assert_eq!(grandchildren.len(), 2);

        let grandchild = world.entity(grandchildren[0]);
        assert_eq!(grandchild.get::<Reference>().unwrap().0, b.id());

        let grandchild = world.entity(grandchildren[1]);
        assert_eq!(grandchild.get::<Reference>().unwrap().0, b.id());
        assert_eq!(grandchild.get::<Name>().unwrap().as_str(), "Y");

        assert_eq!(
            grandchild.id(),
            world
                .entity(grandchild.get::<Children>().unwrap()[0])
                .get::<Reference>()
                .unwrap()
                .0
        );
    }
    #[test]
    fn bsn_reverse_reference() {
        let mut app = test_app();
        let world = app.world_mut();

        fn a() -> impl Scene {
            bsn! {
                Reference(#Last)
                Children [
                    #First,
                    #Second,
                    #Last
                ]
            }
        }
        let id = world.spawn_scene(a()).unwrap().id();
        let ref_id = world.entity(id).get::<Reference>().unwrap();

        let children = world.entity(id).get::<Children>().unwrap();
        assert_eq!(children[2], ref_id.0);

        let name = world.entity(ref_id.0).get::<Name>().unwrap();
        assert_eq!(name.as_str(), "Last");
    }

    #[test]
    fn bsn_list_name_references() {
        let mut app = test_app();
        let world = app.world_mut();

        fn b() -> impl Scene {
            bsn! {
                #Z
                Children [
                    Reference(#Z)
                ]
            }
        }

        fn a() -> impl SceneList {
            bsn_list![
                (
                    #X
                    Reference(#Y)
                    Children [
                        (#Z Reference(#X))
                    ]

                ),
                (
                    #Y
                    Reference(#X)
                    Children [
                        Reference(#Y)
                    ]
                ),
                (b() #Z)
            ]
        }

        let ids = world.spawn_scene_list(a()).unwrap();
        assert_eq!(ids.len(), 3);

        let e0 = world.entity(ids[0]);
        let name = e0.get::<Name>().unwrap();
        assert_eq!(name.as_str(), "X");
        let reference = e0.get::<Reference>().unwrap();
        assert_eq!(reference.0, ids[1]);

        let child0 = e0.get::<Children>().unwrap()[0];
        let reference = world.entity(child0).get::<Reference>().unwrap();
        assert_eq!(reference.0, ids[0]);

        let e1 = world.entity(ids[1]);
        let name = e1.get::<Name>().unwrap();
        assert_eq!(name.as_str(), "Y");

        let reference = e1.get::<Reference>().unwrap();
        assert_eq!(reference.0, ids[0]);

        let child0 = e1.get::<Children>().unwrap()[0];
        let reference = world.entity(child0).get::<Reference>().unwrap();
        assert_eq!(reference.0, ids[1]);

        let e2 = world.entity(ids[2]);
        let name = e2.get::<Name>().unwrap();
        assert_eq!(name.as_str(), "Z");
        let child0 = e2.get::<Children>().unwrap()[0];
        let reference = world.entity(child0).get::<Reference>().unwrap();
        assert_eq!(reference.0, ids[2]);
    }

    #[test]
    fn on_template() {
        #[derive(Resource)]
        struct Exploded(Option<Entity>);

        #[derive(EntityEvent)]
        struct Explode(Entity);

        let mut app = test_app();
        let world = app.world_mut();
        world.insert_resource(Exploded(None));

        fn scene() -> impl Scene {
            bsn! {
                on(|explode: On<Explode>, mut exploded: ResMut<Exploded>|{
                    exploded.0 = Some(explode.0);
                })
            }
        }

        let id = world.spawn_scene(scene()).unwrap().id();
        world.trigger(Explode(id));
        let exploded = world.resource::<Exploded>();
        assert_eq!(exploded.0, Some(id));
    }
    #[test]
    fn primitive_literals() {
        #![allow(dead_code, reason = "test")]
        // test that bsn compiles and doesn't fail to spawn a scene with all sorts of literal values
        macro_rules! types_fields {
            (def $name:ident, $($typ:ident),*) => {
                #[derive(Component, FromTemplate)]
                struct $name {
                    $(
                        $typ: $typ,
                    )*
                }
            };
            ($world:ident, $name:ident($a:expr, $b:expr, $c:expr, $d:expr, $e:expr), $($typ:ident),*) => {
                types_fields!($world, $name($a, $b, $c, $d), $($typ),*);
                types_fields!(val $world, $e, $name, $($typ),*);
            };
            ($world:ident, $name:ident($a:expr, $b:expr, $c:expr, $d:expr), $($typ:ident),*) => {
                types_fields!($world, $name($a, $b, $c), $($typ),*);
                types_fields!(val $world, $d, $name, $($typ),*);
            };
            ($world:ident, $name:ident($a:expr, $b:expr, $c:expr), $($typ:ident),*) => {
                types_fields!($world, $name($a, $b), $($typ),*);
                types_fields!(val $world, $c, $name, $($typ),*);

            };
            ($world:ident, $name:ident($a:expr, $b:expr), $($typ:ident),*) => {
                types_fields!($world, $name($a), $($typ),*);
                types_fields!(val $world, $b, $name, $($typ),*);
            };
            ($world:ident, $name:ident($a:expr), $($typ:ident),*) => {
                types_fields!(def $name, $($typ),*);
                types_fields!(val $world, $a, $name, $($typ),*);
            };
            (val $world:ident, $a:expr, $name:ident, $($typ:ident),*) => {
                let v = bsn!{ $name {
                    $(
                        $typ: $a,
                    )*
                }};
                $world.spawn_scene(v).unwrap();
            };
        }
        let mut app = test_app();
        let world = app.world_mut();
        types_fields!(world, Unsigned(0, 1), usize, u8, u16, u32, u64, u128);
        types_fields!(world, Signed(-1, 0, 1), isize, i8, i16, i32, i64, i128);
        types_fields!(
            world,
            Float(-1.0, 0.0, 1.0, core::f32::consts::PI, -1.),
            f32,
            f64
        );
        types_fields!(world, Bool(true, false), bool);
        #[derive(Component, FromTemplate)]
        struct Random {
            str: &'static str,
            string: String,
            vec: Vec<u8>,
            array: [u8; 4],
        }
        let scene = bsn! {
            Random{
                str: "test",
                string: "test",
                vec: {vec![0, 1]},
                array: {[0, 1, 2, 3]}
            }
        };
        world.spawn_scene(scene).unwrap();
    }
    #[test]
    fn children_list_expr() {
        fn container(items: impl SceneList) -> impl Scene {
            bsn! {
                #Root
                Children [
                    #First,
                    {items},
                    #Last
                ]
            }
        }
        let mut app = test_app();
        let world = app.world_mut();
        let items = bsn_list![
            #Second,
            #Third
        ];
        let id = world.spawn_scene(container(items)).unwrap().id();
        let children = world.entity(id).get::<Children>().unwrap();
        let names: Vec<_> = children
            .iter()
            .map(|id| world.entity(id).get::<Name>().unwrap().as_str())
            .collect();
        assert_eq!(&names, &["First", "Second", "Third", "Last"]);
    }
    #[test]
    fn children_single_expr() {
        fn container(item: impl Scene) -> impl Scene {
            bsn! {
                #Root
                Children [
                    #First,
                    ({item}),
                    #Last
                ]
            }
        }
        let mut app = test_app();
        let world = app.world_mut();
        let items = bsn![
            #Second
        ];
        let id = world.spawn_scene(container(items)).unwrap().id();
        let children = world.entity(id).get::<Children>().unwrap();
        let names: Vec<_> = children
            .iter()
            .map(|id| world.entity(id).get::<Name>().unwrap().as_str())
            .collect();
        assert_eq!(&names, &["First", "Second", "Last"]);
    }
    #[test]
    fn conditional_scene() {
        #[derive(Component, Clone, Default)]
        struct Grunt;
        #[derive(Component, Clone, Default)]
        struct Boss;
        #[derive(Component, Clone, Default, PartialEq, Eq)]
        struct Level(u32);

        fn unit(is_boss: bool, level: u32) -> impl Scene {
            let scene: Box<dyn Scene> = if is_boss {
                Box::new(bsn! {
                    Boss
                    Children [ unit(false, level - 1) #Grunt1, unit(false, level - 1) #Grunt2]
                })
            } else {
                Box::new(bsn! { Grunt })
            };
            bsn! {
                Level(level)
                {scene}
            }
        }
        let mut app = test_app();
        let world = app.world_mut();

        let id = world.spawn_scene(unit(true, 10)).unwrap().id();
        let children = world.entity(id).get::<Children>().unwrap();
        let names: Vec<_> = children
            .iter()
            .map(|id| world.entity(id).get::<Name>().unwrap().as_str())
            .collect();
        assert_eq!(&names, &["Grunt1", "Grunt2"]);
        let names: Vec<_> = children
            .iter()
            .map(|id| world.entity(id).get::<Level>().unwrap().0)
            .collect();
        assert_eq!(&names, &[9, 9]);
    }
    #[test]
    fn partial_tuple_struct() {
        // Tests that only part of a tuple struct can be patched,
        // since its different to named fields
        let mut app = test_app();
        let world = app.world_mut();
        #[derive(Component, Default, Clone)]
        struct TupleStruct(f32, u32);

        fn a() -> impl Scene {
            bsn! {
                TupleStruct(0.1)
            }
        }
        let id = world.spawn_scene(a()).unwrap().id();
        let root = world.entity(id);

        let foo = root.get::<TupleStruct>().unwrap();
        assert_eq!(foo.0, 0.1);
        assert_eq!(foo.1, 0);
    }

    #[test]
    fn scene_expression_passing_pointless() {
        // This test exists mostly to ensure that the practice of not passing `impl Scene` into a scene
        // is the same as the preferred option, using patching.
        #[derive(Component, Default, Clone)]
        struct Health {
            current: u8,
            max: u8,
        }
        #[derive(Component, Default, Clone)]
        struct Armor(u8);

        fn unit_with_armor(unit_base: impl Scene) -> impl Scene {
            bsn! {
                {unit_base}
                Armor(50)
            }
        }
        fn armor() -> impl Scene {
            bsn! {
                Armor(50)
            }
        }
        let mut app = test_app();
        let world = app.world_mut();
        let inner = bsn! { Health { current: 100, max: 100 } };
        let ida = world.spawn_scene(unit_with_armor(inner)).unwrap().id();

        // inheritance is the same!
        let entity_b = bsn! {
            armor()
            Health { current: 100, max: 100 }
        };
        let idb = world.spawn_scene(entity_b).unwrap().id();

        assert_eq!(
            world.entity(ida).archetype().components(),
            world.entity(idb).archetype().components()
        );
    }

    #[test]
    fn enum_patching() {
        let mut app = test_app();
        let world = app.world_mut();

        #[derive(Component, FromTemplate, PartialEq, Eq, Debug)]
        enum Foo {
            #[default]
            Bar {
                x: u32,
                y: u32,
                z: u32,
            },
            Baz(usize),
            Qux,
        }

        fn a() -> impl Scene {
            bsn! {
                Foo::Baz(10)
            }
        }

        fn b() -> impl Scene {
            bsn! {
                a()
                Foo::Bar { x: 1 }
            }
        }

        fn c() -> impl Scene {
            bsn! {
                b()
                Foo::Bar { y: 2 }
            }
        }

        fn d() -> impl Scene {
            bsn! {
                c()
                Foo::Qux
            }
        }

        let id = world.spawn_scene(c()).unwrap().id();
        let root = world.entity(id);

        let foo = root.get::<Foo>().unwrap();
        assert_eq!(Foo::Bar { x: 1, y: 2, z: 0 }, *foo);

        let id = world.spawn_scene(a()).unwrap().id();
        let root = world.entity(id);

        let foo = root.get::<Foo>().unwrap();
        assert_eq!(Foo::Baz(10), *foo);

        let id = world.spawn_scene(d()).unwrap().id();
        let root = world.entity(id);
        let foo = root.get::<Foo>().unwrap();
        assert_eq!(Foo::Qux, *foo);
    }

    #[test]
    fn struct_patching() {
        let mut app = test_app();
        let world = app.world_mut();

        #[derive(Component, FromTemplate, PartialEq, Eq, Debug)]
        struct Foo {
            x: u32,
            y: u32,
            z: u32,
            nested: Bar,
        }

        #[derive(Component, FromTemplate, PartialEq, Eq, Debug)]
        struct Bar(usize, usize, usize);

        fn a() -> impl Scene {
            bsn! {
                Foo {
                    x: 1,
                    nested: Bar(1, 1),
                }
            }
        }

        fn b() -> impl Scene {
            bsn! {
                a()
                Foo {
                    y: 2,
                    nested: Bar(2),
                }
            }
        }

        let id = world.spawn_scene(b()).unwrap().id();
        let root = world.entity(id);

        let foo = root.get::<Foo>().unwrap();
        assert_eq!(
            *foo,
            Foo {
                x: 1,
                y: 2,
                z: 0,
                nested: Bar(2, 1, 0)
            }
        );
    }

    #[test]
    fn field_patching_with_default() {
        let mut app = test_app();
        let world = app.world_mut();

        #[derive(Component, Clone, Default, PartialEq, Eq, Debug)]
        struct Foo {
            x: u32,
            y: u32,
            z: u32,
            nested: Bar,
        }

        #[derive(Component, Clone, Default, PartialEq, Eq, Debug)]
        struct Bar(usize, usize, usize);

        fn a() -> impl Scene {
            bsn! {
                Foo {
                    x: 1,
                    nested: Bar(1, 1),
                }
            }
        }

        fn b() -> impl Scene {
            bsn! {
                a()
                Foo {
                    y: 2,
                    nested: Bar(2),
                }
            }
        }

        let id = world.spawn_scene(b()).unwrap().id();
        let root = world.entity(id);

        let foo = root.get::<Foo>().unwrap();
        assert_eq!(
            *foo,
            Foo {
                x: 1,
                y: 2,
                z: 0,
                nested: Bar(2, 1, 0)
            }
        );
    }

    #[test]
    fn handle_template() {
        let mut app = test_app();
        app.init_asset::<Image>();

        #[derive(Asset, TypePath)]
        struct Image;

        let handle = app.world().resource::<AssetServer>().load("image.png");
        let world = app.world_mut();

        #[derive(Component, FromTemplate, PartialEq, Eq, Debug)]
        struct Sprite(Handle<Image>);

        fn scene() -> impl Scene {
            bsn! {
                Sprite("image.png")
            }
        }

        let id = world.spawn_scene(scene()).unwrap().id();
        let root = world.entity(id);

        let sprite = root.get::<Sprite>().unwrap();
        assert_eq!(sprite.0, handle);
    }

    #[test]
    fn child_of_template() {
        let mut app = test_app();

        let world = app.world_mut();

        fn scene(root: Entity) -> impl SceneList {
            bsn_list! {
                ( #Child1 ChildOf(root) ),
                ( #Child2 ChildOf(#Child1) ),
            }
        }

        let root = world.spawn_empty().id();

        let ids = world.spawn_scene_list(scene(root)).unwrap();
        assert_eq!(ids.len(), 2);

        let [a, b] = world.entity(&*ids)[..] else {
            unreachable!()
        };
        assert_eq!(a.get::<Name>().unwrap().as_str(), "Child1");
        assert_eq!(a.get::<ChildOf>().unwrap().get(), root);

        assert_eq!(b.get::<Name>().unwrap().as_str(), "Child2");
        assert_eq!(b.get::<ChildOf>().unwrap().get(), a.id());
    }

    #[test]
    fn scene_list_children() {
        let mut app = test_app();
        let world = app.world_mut();

        fn root(children: impl SceneList) -> impl Scene {
            bsn! {
                Children [
                    #A,
                    {children},
                    #D
                ]
            }
        }

        let children = bsn_list! [
            #B,
            #C,
        ];

        let id = world.spawn_scene(root(children)).unwrap().id();
        let root = world.entity(id);
        let children = root.get::<Children>().unwrap();
        let a = world.entity(children[0]).get::<Name>().unwrap();
        let b = world.entity(children[1]).get::<Name>().unwrap();
        let c = world.entity(children[2]).get::<Name>().unwrap();
        let d = world.entity(children[3]).get::<Name>().unwrap();
        assert_eq!(a.as_str(), "A");
        assert_eq!(b.as_str(), "B");
        assert_eq!(c.as_str(), "C");
        assert_eq!(d.as_str(), "D");
    }

    #[test]
    fn generic_patching() {
        let mut app = test_app();
        let world = app.world_mut();

        #[derive(Component, FromTemplate, PartialEq, Eq, Debug)]
        struct Foo<T: FromTemplate<Template: Default + Template<Output = T>>> {
            value: T,
            number: u32,
        }

        #[derive(Component, FromTemplate, PartialEq, Eq, Debug)]
        struct Position {
            x: u32,
            y: u32,
            z: u32,
        }

        fn a() -> impl Scene {
            bsn! {
                Foo::<Position> {
                    value: Position { x: 1 }
                }
            }
        }

        fn b() -> impl Scene {
            bsn! {
                a()
                Foo::<Position> {
                    value: Position { y: 2 },
                    number: 10,
                }
            }
        }

        let id = world.spawn_scene(b()).unwrap().id();
        let root = world.entity(id);

        let foo = root.get::<Foo<Position>>().unwrap();
        assert_eq!(
            *foo,
            Foo {
                value: Position { x: 1, y: 2, z: 0 },
                number: 10
            }
        );
    }

    #[test]
    fn empty_scene_expressions() {
        let mut app = test_app();
        let world = app.world_mut();
        fn a() -> impl Scene {
            bsn! {
                {}
            }
        }
        world.spawn_scene(a()).unwrap();
    }

    #[test]
    fn closures_in_bsn() {
        #[derive(Resource, Default)]
        struct TotalHealed(u32);

        #[derive(EntityEvent)]
        struct Heal(Entity);

        let mut app = test_app();
        let world = app.world_mut();
        world.init_resource::<TotalHealed>();

        fn non_move_scene() -> impl Scene {
            bsn! {
                on(|_: On<Heal>, mut healed: ResMut<TotalHealed>| {
                    healed.0 += 1;
                })
            }
        }

        let id = world.spawn_scene(non_move_scene()).unwrap().id();
        world.trigger(Heal(id));
        assert_eq!(world.resource::<TotalHealed>().0, 1);
        world.resource_mut::<TotalHealed>().0 = 0;
        fn on_heal(_: On<Heal>, mut healed: ResMut<TotalHealed>) {
            healed.0 += 2;
        }
        fn function_scene() -> impl Scene {
            bsn! {
                on(on_heal)
            }
        }

        let id = world.spawn_scene(function_scene()).unwrap().id();
        world.trigger(Heal(id));
        assert_eq!(world.resource::<TotalHealed>().0, 2);
        world.resource_mut::<TotalHealed>().0 = 0;

        fn move_scene(bonus: u32) -> impl Scene {
            bsn! {
                on(move |_: On<Heal>, mut healed: ResMut<TotalHealed>| {
                    healed.0 += bonus;
                })
            }
        }

        let id = world.spawn_scene(move_scene(42)).unwrap().id();
        world.trigger(Heal(id));
        assert_eq!(world.resource::<TotalHealed>().0, 42);
    }

    #[test]
    fn comments_in_bsn() {
        let mut app = test_app();
        let world = app.world_mut();

        #[derive(Component, Clone, Default)]
        struct Marker;

        fn yappy() -> impl Scene {
            bsn! {
                // Look ma, a comment!
                #MyName
                /*
                   Wow, a block comment now?
                */
                Marker
            }
        }
        world.spawn_scene(yappy()).unwrap();
    }

    #[test]
    fn bsn_entry_can_surpass_tuple_limit() {
        let _ = bsn! {
            Name
            Name
            Name
            Name
            Name
            Name
            Name
            Name
            Name
            Name
            Name
            Name
            Name
            Name
        };
    }

    #[derive(Component, Default)]
    struct Fail;
    impl FromTemplate for Fail {
        type Template = Fail;
    }
    impl Template for Fail {
        type Output = Fail;

        fn build_template(
            &self,
            _context: &mut bevy_ecs::template::TemplateContext,
        ) -> Result<Self::Output> {
            Err(BevyError::error("fail!"))
        }

        fn clone_template(&self) -> Self {
            todo!()
        }
    }

    #[test]
    fn queue_spawn_scene_during_spawn() {
        #[derive(Component, Default, Clone)]
        #[component(on_insert)]
        struct SpawnOnInsert;

        impl SpawnOnInsert {
            fn on_insert(mut world: DeferredWorld, _context: HookContext) {
                world.commands().queue_spawn_scene(scene2());
            }
        }

        fn scene1() -> impl Scene {
            bsn!(SpawnOnInsert)
        }

        fn scene2() -> impl Scene {
            bsn!(#Name)
        }

        let mut app = test_app();
        let world = app.world_mut();
        world.queue_spawn_scene(scene1());

        app.update();
    }

    #[test]
    fn component_scene() {
        #[derive(SceneComponent, Default, Clone)]
        struct Widget;

        impl Widget {
            fn scene() -> impl Scene {
                bsn! {Name("widget")}
            }
        }

        let mut app = test_app();
        let world = app.world_mut();
        let entity = world.spawn_scene(bsn! {@Widget}).unwrap();
        assert_eq!(entity.get::<Name>().unwrap().as_str(), "widget");
        assert!(entity.contains::<Widget>());

        #[derive(SceneComponent, Default, Clone)]
        #[scene(Widget::scene)]
        struct OtherWidget;
        let entity = world.spawn_scene(bsn! {@OtherWidget}).unwrap();
        assert_eq!(entity.get::<Name>().unwrap().as_str(), "widget");
        assert!(entity.contains::<OtherWidget>());
        assert!(
            !entity.contains::<Widget>(),
            "This reuses the Widget::scene function, but that scene does not explicitly add Widget"
        );
    }

    #[test]
    fn component_scene_props() {
        #[derive(SceneComponent, Default, Clone)]
        #[scene(WidgetProps)]
        struct Widget {
            value: usize,
        }

        #[derive(Default)]
        struct WidgetProps {
            children: usize,
        }

        impl Widget {
            fn scene(props: WidgetProps) -> impl Scene {
                let children = (0..props.children)
                    .map(|i| {
                        bsn! {
                            Name({format!("Child{i}")})
                        }
                    })
                    .collect::<Vec<_>>();
                bsn! {
                    Children [
                        {children}
                    ]
                }
            }
        }

        let mut app = test_app();
        let world = app.world_mut();
        let entity = world
            .spawn_scene(bsn! {@Widget {
                @children: 2,
                value: 10,
            }})
            .unwrap();
        assert_eq!(entity.get::<Widget>().unwrap().value, 10);
        assert_eq!(entity.get::<Children>().unwrap().len(), 2);

        #[derive(SceneComponent, Default, Clone)]
        #[scene(Widget::scene(WidgetProps))]
        struct OtherWidget {
            value: usize,
        }

        let entity = world
            .spawn_scene(bsn! {@OtherWidget {
                @children: 2,
                value: 10,
            }})
            .unwrap();
        assert_eq!(entity.get::<OtherWidget>().unwrap().value, 10);
        assert_eq!(entity.get::<Children>().unwrap().len(), 2);

        fn const_val<const N: usize>() -> impl Scene {
            bsn! {
                @Widget {
                    @children: N
                }
            }
        }
        #[derive(SceneComponent, Clone, Default)]
        #[scene(const_val::<5>)]
        struct SpecificWidget;
        let entity = world.spawn_scene(bsn! { @SpecificWidget }).unwrap();
        assert_eq!(entity.get::<Children>().unwrap().len(), 5);
    }

    #[test]
    fn scene_without_explicit_component_still_spawns_component() {
        #[derive(SceneComponent, Default, Clone)]
        struct Widget;

        impl Widget {
            fn scene() -> impl Scene {
                bsn! {}
            }
        }

        let mut app = test_app();
        let world = app.world_mut();
        let entity = world.spawn_scene(bsn! {@Widget}).unwrap();
        assert!(entity.contains::<Widget>());
    }

    #[test]
    fn tuple_scene_component_name_reference() {
        #[derive(SceneComponent, FromTemplate)]
        struct Widget(pub Entity);

        impl Widget {
            fn scene() -> impl Scene {
                bsn! {}
            }
        }

        let scene = bsn! {
            #Name
            Children [
                @Widget(#Name)
            ]
        };

        let mut app = test_app();
        let world = app.world_mut();
        let entity = world.spawn_scene(scene).unwrap().id();
        let root = world.entity(entity);
        let children = root.get::<Children>().unwrap();
        let child_widget = world.entity(children[0]).get::<Widget>().unwrap();
        assert_eq!(child_widget.0, entity);
    }

    #[test]
    fn named_scene_component_name_reference() {
        #[derive(SceneComponent, FromTemplate)]
        struct Widget {
            entity: Entity,
        }

        impl Widget {
            fn scene() -> impl Scene {
                bsn! {}
            }
        }

        let scene = bsn! {
            #Name
            Children [
                @Widget{
                    entity: #Name
                }
            ]
        };

        let mut app = test_app();
        let world = app.world_mut();
        let entity = world.spawn_scene(scene).unwrap().id();
        let root = world.entity(entity);
        let children = root.get::<Children>().unwrap();
        let child_widget = world.entity(children[0]).get::<Widget>().unwrap();
        assert_eq!(child_widget.entity, entity);
    }

    #[test]
    fn scene_function_name_reference() {
        use bevy_ecs::template::EntityTemplate;
        #[derive(Component, FromTemplate)]
        struct Reference(Entity);
        fn widget(entity: EntityTemplate) -> impl Scene {
            bsn! {
                Reference(entity)
            }
        }
        let mut app = test_app();
        let world = app.world_mut();

        let pass_expr = bsn! {
            #Name
            Children [
                widget(Entity::PLACEHOLDER.into())
            ]
        };
        let entity = world.spawn_scene(pass_expr).unwrap().id();
        let root = world.entity(entity);
        let children = root.get::<Children>().unwrap();
        let child_widget = world.entity(children[0]).get::<Reference>().unwrap();
        assert_eq!(child_widget.0, Entity::PLACEHOLDER);

        let pass_name = bsn! {
            #Name
            Children [
                widget(#Name)
            ]
        };
        let entity = world.spawn_scene(pass_name).unwrap().id();
        let root = world.entity(entity);
        let children = root.get::<Children>().unwrap();
        let child_widget = world.entity(children[0]).get::<Reference>().unwrap();
        assert_eq!(child_widget.0, entity);

        // This allows both passing entity id by name reference and a custom dynamic name
        let i = 5;
        let pass_name_expr = bsn! {
            #Root
            Name({format!("Foo{i}")})
            Children [
                #Name
                widget(#Root)
            ]
        };
        let entity = world.spawn_scene(pass_name_expr).unwrap().id();
        let root = world.entity(entity);
        let children = root.get::<Children>().unwrap();
        let child_widget = world.entity(children[0]).get::<Reference>().unwrap();
        assert_eq!(child_widget.0, entity);
        let name = root.get::<Name>().unwrap();
        assert_eq!(name.as_str(), "Foo5");
    }

    #[test]
    fn scene_component_prop_name_reference() {
        use bevy_ecs::template::EntityTemplate;
        #[derive(Component, FromTemplate)]
        struct Reference(Entity);

        #[derive(SceneComponent, Clone, Default)]
        #[scene(WidgetProps)]
        struct Widget;

        #[derive(Default)]
        struct WidgetProps {
            entity: EntityTemplate,
        }

        impl Widget {
            fn scene(props: WidgetProps) -> impl Scene {
                bsn! {
                    Reference({props.entity})
                }
            }
        }
        let mut app = test_app();
        let world = app.world_mut();

        let prop_expr = bsn! {
            Children [
                @Widget {
                    @entity: Entity::PLACEHOLDER
                }
            ]
        };
        let entity = world.spawn_scene(prop_expr).unwrap().id();
        let root = world.entity(entity);
        let children = root.get::<Children>().unwrap();
        let child_widget = world.entity(children[0]).get::<Reference>().unwrap();
        assert_eq!(child_widget.0, Entity::PLACEHOLDER);
        let scene_prop = bsn! {
            #Name
            Children [
                @Widget {
                    @entity: #Name
                }
            ]
        };
        let entity = world.spawn_scene(scene_prop).unwrap().id();
        let root = world.entity(entity);
        let children = root.get::<Children>().unwrap();
        let child_widget = world.entity(children[0]).get::<Reference>().unwrap();
        assert_eq!(child_widget.0, entity);
    }

    #[test]
    fn repeated_call_entity_reference() {
        let scenes = (0..6).map(|_: u32| bsn! { #Name }).collect::<Vec<_>>();
        let scenes_len = scenes.len();
        let mut app = test_app();
        let world = app.world_mut();
        world.spawn_scene_list(scenes).unwrap();
        assert_eq!(world.query::<&Name>().query(world).count(), scenes_len);
    }

    #[test]
    fn drop_is_called_for_uninserted_components() {
        #[derive(Component, FromTemplate)]
        struct DropTracker(Option<Arc<Mutex<usize>>>);

        impl Drop for DropTracker {
            fn drop(&mut self) {
                if let Some(count) = &mut self.0 {
                    *count.lock().unwrap() += 1;
                }
            }
        }

        let mut app = test_app();
        let world = app.world_mut();
        let count_arc = Arc::new(Mutex::new(0));
        let count = Some(count_arc.clone());
        let scene = bsn! {
            DropTracker({count.clone()})
            Fail
        };
        let result = world.spawn_scene(scene);
        assert!(result.is_err());
        assert_eq!(1, *count_arc.lock().unwrap());
    }

    #[test]
    fn despawn_on_failed_spawn() {
        let mut app = test_app();
        let world = app.world_mut();
        let current_entities = world.entities().len();
        let result = world.spawn_scene(bsn! {
           Fail
        });
        assert!(result.is_err());
        assert_eq!(current_entities, world.entities().len());
    }

    fn run_app_until(app: &mut App, mut predicate: impl FnMut() -> bool) {
        const LARGE_ITERATION_COUNT: usize = 10000;
        for _ in 0..LARGE_ITERATION_COUNT {
            app.update();
            if predicate() {
                return;
            }
        }

        panic!("Ran out of loops to return `Some` from `predicate`");
    }

    // NOTE: function scene caching is not yet implemented
    // #[test]
    // fn caching_with_generics() {
    //     #[derive(Component, FromTemplate, PartialEq, Eq, Debug)]
    //     struct Foo<T: FromTemplate<Template: Default + Template<Output = T>>> {
    //         value: T,
    //         number: u32,
    //     }

    //     fn b() -> impl Scene {
    //         bsn! {
    //             :a::<0, i32>
    //             Children [ #Y ]
    //         }
    //     }

    //     fn a<
    //         const A: u32,
    //         T: 'static
    //             + Send
    //             + Sync
    //             + FromTemplate<Template: Send + Sync + Default + Template<Output = T>>,
    //     >() -> impl Scene {
    //         bsn! {
    //             Foo<T>{
    //                 number: A
    //             }
    //         }
    //     }

    //     b();
    // }

    #[test]
    fn scene_with_blocks() {
        #[derive(Component, Clone, Default)]
        struct Holder {
            const_block: i32,
            unsafe_block: i32,
        }

        fn func() -> impl Scene {
            bsn! {
                Holder {
                    const_block: const {0},
                    unsafe_block: unsafe {0},
                }
            }
        }

        func();
    }
    #[test]
    fn macro_doc_test() {
        #![allow(unused, reason = "test")]
        #![allow(dead_code, reason = "test")]

        fn some_scene() -> impl Scene {}
        #[derive(Component, Default, Clone)]
        struct ComponentA;
        #[derive(Component, Default, Clone)]
        struct ComponentB(f32, u8);
        #[derive(Component, Default, Clone)]
        struct Node {
            height: f32,
            width: f32,
        }
        fn px(v: f32) -> f32 {
            v
        }
        #[derive(EntityEvent)]
        struct MyEntityEvent {
            entity: Entity,
            value: f32,
        }
        fn other_scene() -> impl Scene {}
        #[derive(Component, FromTemplate)]
        struct Link(Entity);
        #[derive(SceneComponent, FromTemplate)]
        #[scene(scenecomponentscene(Props))]
        struct MySceneComponent {
            normal_field: u8,
        }
        #[derive(Default)]
        struct Props {
            some_prop: u8,
        }
        fn scenecomponentscene(props: Props) -> impl Scene {}
        let some_var: f32 = 0.;
        #[derive(SceneComponent, FromTemplate)]
        #[scene(scenecomponentscene2(Props2))]
        struct Container;
        struct Props2 {
            items: Box<dyn SceneList>,
        }
        impl Default for Props2 {
            fn default() -> Self {
                Self {
                    items: Box::new(bsn_list!()),
                }
            }
        }
        fn scenecomponentscene2(props: Props2) -> impl Scene {}
        #[derive(Component, Default, Clone)]
        struct SomeComponent;
        // Copy of the macro from bevy_scene/macros/src/lib.rs
        // why? because it should be tested
        // why not doctests? because the macro can't depend on this crate
        // why not include! it here and include_str! it in the docs? because rust-analyzer ignores #[doc = include_str!()] and this is mostly a showcase for rust-analyzer
        let scene = bsn! {
            some_scene()        // include a scene function
            #SomeName           // entity name, will insert Name("SomeName")
            ComponentA          // component without a value will use default
            ComponentB(0.0)     // passing a value, other fields will use default
            Node {
                height: px(0.1) // same with named fields, unmentioned ones stay default
            }
            on(|evt: On<MyEntityEvent>, mut query: Query<&mut ComponentB>| {  // add an observer
                let mut b = query.get_mut(evt.entity).unwrap();
                b.0 += evt.value;
            })
            Children [                   // spawning multiple related entities using a RelationshipTarget component
                #Child1 ComponentA       // whitespace doesn't have to be newlines
                ,                        // entities are comma-separated
                (other_scene() #Child3), // parentheses around a single entity are optional
                Link(#SomeName),         // passing a entity reference to a component as `Entity`, component has to implement FromTemplate
                @MySceneComponent {      // components which derive SceneComponent have scenes and can be inherited from
                    @some_prop: 3,       // props, look like fields prefixed with @ but end up passed to the components scene as arguments
                    normal_field: 5      // while normal fields are the actual fields of the component
                },
                Node {
                    width: some_var      // you can directly use variables without {}
                }
                ComponentB({some_var + 3.})  // values can be expressions, when wrapped in {}
                @Container {
                    @items: {
                        bsn_list![                // sometimes you may need to nest macro calls
                            #item1 SomeComponent, // note: the name #item1 here is in its own scope
                            some_scene() #item2
                        ]
                    }
                }
            ]
        };
        // just checking it spawns correctly
        let mut app = test_app();
        let world = app.world_mut();
        let entity = world.spawn_scene(scene).unwrap().id();
    }

    #[test]
    fn scene_with_oneshot_system() {
        #[derive(Component, FromTemplate)]
        struct Callback {
            callback: SystemHandle<(), ()>,
        }

        fn my_system() {}

        let mut app = test_app();
        let world = app.world_mut();

        let direct = bsn! {
            Callback {
                callback: system_value(my_system)
            }
        };
        let direct_ent = world.spawn_scene(direct).unwrap();
        assert!(direct_ent.get::<Callback>().is_some());

        let id = world.register_tracked_system(my_system);
        let id2 = id.clone();

        let indirect = bsn! {
            Callback {
                callback: id
            }
        };
        let indirect_ent = world.spawn_scene(indirect).unwrap();
        assert!(indirect_ent.get::<Callback>().unwrap().callback == id2);
    }

    #[test]
    fn direct_macro_values_in_bsn() {
        let mut app = test_app();
        let world = app.world_mut();

        #[derive(Component, Default, Clone)]
        struct Foo {
            value: Vec<usize>,
        }
        let entity = world
            .spawn_scene(bsn! {
                Foo {
                    value: vec! [ 10 ],
                }
            })
            .unwrap();
        assert_eq!(entity.get::<Foo>().unwrap().value, vec![10]);
    }

    #[test]
    fn enum_variant_field_values_use_implicit_into() {
        let mut app = test_app();
        let world = app.world_mut();

        #[derive(Component, Default, Clone)]
        struct TextFont {
            font_size: FontSize,
        }

        #[derive(Default, Clone, Debug, PartialEq, Eq)]
        struct FontSize(u32);

        enum TextSize {
            Large,
        }

        impl From<TextSize> for FontSize {
            fn from(value: TextSize) -> Self {
                match value {
                    TextSize::Large => FontSize(24),
                }
            }
        }

        let entity = world
            .spawn_scene(bsn! {
                TextFont {
                    font_size: TextSize::Large,
                }
            })
            .unwrap();

        assert_eq!(entity.get::<TextFont>().unwrap().font_size, FontSize(24));
    }

    #[test]
    fn field_name_shorthand() {
        let mut app = test_app();
        let world = app.world_mut();

        #[derive(Component, Default, Clone)]
        struct Foo {
            value: usize,
        }
        let value = 10usize;
        let entity = world.spawn_scene(bsn! { Foo { value } }).unwrap();
        assert_eq!(entity.get::<Foo>().unwrap().value, 10);

        #[derive(SceneComponent, Default, Clone)]
        #[scene(BarProps)]
        struct Bar {
            value: usize,
        }

        #[derive(Default)]
        struct BarProps {
            value: usize,
        }

        impl Bar {
            fn scene(props: BarProps) -> impl Scene {
                bsn! {Bar {
                    value: {props.value}
                }}
            }
        }

        let value = 10usize;
        let entity = world.spawn_scene(bsn! { @Bar { @value } }).unwrap();
        assert_eq!(entity.get::<Bar>().unwrap().value, 10);

        #[derive(Component, Default, Clone)]
        struct Baz {
            value: X,
        }

        #[derive(Default, Clone)]
        struct X;

        #[derive(Default, Clone)]
        struct Y;

        impl From<Y> for X {
            fn from(_: Y) -> Self {
                X
            }
        }

        let value = Y;
        // ensure implicit Into works
        let _ = world.spawn_scene(bsn! { Baz { value } }).unwrap();
    }

    #[test]
    fn scene_with_optional_components() {
        let mut app = test_app();
        let world = app.world_mut();

        #[derive(Component, Default, Clone)]
        struct Foo;

        let optional_component = Some(bsn! {
            Foo
        });

        let entity = world
            .spawn_scene(bsn! {
                #MaybeFoo
                {optional_component}
            })
            .unwrap();
        assert!(entity.get::<Foo>().is_some());
    }
}