bevy_asset 0.19.0

Provides asset 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
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
//! In the context of game development, an "asset" is a piece of content that is loaded from disk and displayed in the game.
//! Typically, these are authored by artists and designers (in contrast to code),
//! are relatively large in size, and include everything from textures and models to sounds and music to levels and scripts.
//!
//! This presents two main challenges:
//! - Assets take up a lot of memory; simply storing a copy for each instance of an asset in the game would be prohibitively expensive.
//! - Loading assets from disk is slow, and can cause long load times and delays.
//!
//! These problems play into each other, for if assets are expensive to store in memory,
//! then larger game worlds will need to load them from disk as needed, ideally without a loading screen.
//!
//! As is common in Rust, non-blocking asset loading is done using `async`, with background tasks used to load assets while the game is running.
//! Bevy coordinates these tasks using the [`AssetServer`] resource, storing each loaded asset in a strongly-typed [`Assets<T>`] collection (also a resource).
//! [`Handle`]s serve as an id-based reference to entries in the [`Assets`] collection, allowing them to be cheaply shared between systems,
//! and providing a way to initialize objects (generally entities) before the required assets are loaded.
//! In short: [`Handle`]s are not the assets themselves, they just tell how to look them up!
//!
//! ## Loading assets
//!
//! The [`AssetServer`] is the main entry point for loading assets.
//! Typically, you'll use the [`AssetServer::load`] method to load an asset from disk, which returns a [`Handle`].
//! Note that this method does not attempt to reload the asset if it has already been loaded: as long as at least one handle has not been dropped,
//! calling [`AssetServer::load`] on the same path will return the same handle.
//! The handle that's returned can be used to instantiate various [`Component`]s that require asset data to function,
//! which will then be spawned into the world as part of an entity.
//!
//! To avoid assets "popping" into existence, you may want to check that all of the required assets are loaded before transitioning to a new scene.
//! This can be done by checking the [`LoadState`] of the asset handle using [`AssetServer::is_loaded_with_dependencies`],
//! which will be `true` when the asset is ready to use.
//!
//! Keep track of what you're waiting on by using a [`HashSet`] of asset handles or similar data structure,
//! which iterate over and poll in your update loop, and transition to the new scene once all assets are loaded.
//! Bevy's built-in states system can be very helpful for this!
//!
//! # Modifying entities that use assets
//!
//! If we later want to change the asset data a given component uses (such as changing an entity's material), we have three options:
//!
//! 1. Change the handle stored on the responsible component to the handle of a different asset
//! 2. Despawn the entity and spawn a new one with the new asset data.
//! 3. Use the [`Assets`] collection to directly modify the current handle's asset data
//!
//! The first option is the most common: just query for the component that holds the handle, and mutate it, pointing to the new asset.
//! Check how the handle was passed in to the entity when it was spawned: if a mesh-related component required a handle to a mesh asset,
//! you'll need to find that component via a query and change the handle to the new mesh asset.
//! This is so commonly done that you should think about strategies for how to store and swap handles in your game.
//!
//! The second option is the simplest, but can be slow if done frequently,
//! and can lead to frustrating bugs as references to the old entity (such as what is targeting it) and other data on the entity are lost.
//! Generally, this isn't a great strategy.
//!
//! The third option has different semantics: rather than modifying the asset data for a single entity, it modifies the asset data for *all* entities using this handle.
//! While this might be what you want, it generally isn't!
//!
//! # Hot reloading assets
//!
//! Bevy supports asset hot reloading, allowing you to change assets on disk and see the changes reflected in your game without restarting.
//! When enabled, any changes to the underlying asset file will be detected by the [`AssetServer`], which will then reload the asset,
//! mutating the asset data in the [`Assets`] collection and thus updating all entities that use the asset.
//! While it has limited uses in published games, it is very useful when developing, as it allows you to iterate quickly.
//!
//! To enable asset hot reloading on desktop platforms, enable `bevy`'s `file_watcher` cargo feature.
//! To toggle it at runtime, you can use the `watch_for_changes_override` field in the [`AssetPlugin`] to enable or disable hot reloading.
//!
//! # Procedural asset creation
//!
//! Not all assets are loaded from disk: some are generated at runtime, such as procedural materials, sounds or even levels.
//! After creating an item of a type that implements [`Asset`], you can add it to the [`Assets`] collection using [`Assets::add`].
//! Once in the asset collection, this data can be operated on like any other asset.
//!
//! Note that, unlike assets loaded from a file path, no general mechanism currently exists to deduplicate procedural assets:
//! calling [`Assets::add`] for every entity that needs the asset will create a new copy of the asset for each entity,
//! quickly consuming memory.
//!
//! ## Handles and reference counting
//!
//! [`Handle`] (or their untyped counterpart [`UntypedHandle`]) are used to reference assets in the [`Assets`] collection,
//! and are the primary way to interact with assets in Bevy.
//! As a user, you'll be working with handles a lot!
//!
//! The most important thing to know about handles is that they are reference counted: when you clone a handle, you're incrementing a reference count.
//! When the object holding the handle is dropped (generally because an entity was despawned), the reference count is decremented.
//! When the reference count hits zero, the asset it references is removed from the [`Assets`] collection.
//!
//! This reference counting is a simple, largely automatic way to avoid holding onto memory for game objects that are no longer in use.
//! However, it can lead to surprising behavior if you're not careful!
//!
//! There are two categories of problems to watch out for:
//! - never dropping a handle, causing the asset to never be removed from memory
//! - dropping a handle too early, causing the asset to be removed from memory while it's still in use
//!
//! The first problem is less critical for beginners, as for tiny games, you can often get away with simply storing all of the assets in memory at once,
//! and loading them all at the start of the game.
//! As your game grows, you'll need to be more careful about when you load and unload assets,
//! segmenting them by level or area, and loading them on-demand.
//! This problem generally arises when handles are stored in a persistent "collection" or "manifest" of possible objects (generally in a resource),
//! which is convenient for easy access and zero-latency spawning, but can result in high but stable memory usage.
//!
//! The second problem is more concerning, and looks like your models or textures suddenly disappearing from the game.
//! Debugging reveals that the *entities* are still there, but nothing is rendering!
//! This is because the assets were removed from memory while they were still in use.
//! You were probably too aggressive with the use of weak handles (which don't increment the reference count of the asset): think through the lifecycle of your assets carefully!
//! As soon as an asset is loaded, you must ensure that at least one strong handle is held to it until all matching entities are out of sight of the player.
//!
//! # Asset dependencies
//!
//! Some assets depend on other assets to be loaded before they can be loaded themselves.
//! For example, a 3D model might require both textures and meshes to be loaded,
//! or a 2D level might require a tileset to be loaded.
//!
//! The assets that are required to load another asset are called "dependencies".
//! An asset is only considered fully loaded when it and all of its dependencies are loaded.
//! Asset dependencies can be declared when implementing the [`Asset`] trait by implementing the [`VisitAssetDependencies`] trait,
//! and the `#[dependency]` attribute can be used to automatically derive this implementation.
//!
//! # Custom asset types
//!
//! While Bevy comes with implementations for a large number of common game-oriented asset types (often behind off-by-default feature flags!),
//! implementing a custom asset type can be useful when dealing with unusual, game-specific, or proprietary formats.
//!
//! Defining a new asset type is as simple as implementing the [`Asset`] trait.
//! This requires [`TypePath`] for metadata about the asset type,
//! and [`VisitAssetDependencies`] to track asset dependencies.
//! In simple cases, you can derive [`Asset`] and [`Reflect`] and be done with it: the required supertraits will be implemented for you.
//!
//! With a new asset type in place, we now need to figure out how to load it.
//! While [`AssetReader`](io::AssetReader) describes strategies to read asset bytes from various sources,
//! [`AssetLoader`] is the trait that actually turns those into your desired in-memory format.
//! Generally, (only) [`AssetLoader`] needs to be implemented for custom assets, as the [`AssetReader`](io::AssetReader) implementations are provided by Bevy.
//!
//! However, [`AssetLoader`] shouldn't be implemented for your asset type directly: instead, this is implemented for a "loader" type
//! that can store settings and any additional data required to load your asset, while your asset type is used as the [`AssetLoader::Asset`] associated type.
//! As the trait documentation explains, this allows various [`AssetLoader::Settings`] to be used to configure the loader.
//!
//! After the loader is implemented, it needs to be registered with the [`AssetServer`] using [`App::register_asset_loader`](AssetApp::register_asset_loader).
//! Once your asset type is loaded, you can use it in your game like any other asset type!
//!

#![expect(missing_docs, reason = "Not all docs are written yet, see #3492.")]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(
    html_logo_url = "https://bevy.org/assets/icon.png",
    html_favicon_url = "https://bevy.org/assets/icon.png"
)]
#![no_std]

extern crate alloc;
extern crate std;

// Required to make proc macros work in bevy itself.
extern crate self as bevy_asset;

pub mod io;
pub mod meta;
pub mod processor;
pub mod saver;
pub mod transformer;

/// The asset prelude.
///
/// This includes the most common types in this crate, re-exported for your convenience.
pub mod prelude {
    #[doc(hidden)]
    pub use crate::asset_changed::AssetChanged;

    #[doc(hidden)]
    pub use crate::{
        asset_value, Asset, AssetApp, AssetEvent, AssetId, AssetMode, AssetPlugin, AssetServer,
        Assets, DirectAssetAccessExt, Handle, UntypedHandle,
    };
}

mod asset_changed;
mod assets;
mod direct_access_ext;
mod event;
mod folder;
mod handle;
mod id;
mod loader;
mod loader_builders;
mod path;
mod reflect;
mod render_asset;
mod server;

pub use assets::*;
pub use bevy_asset_macros::{Asset, VisitAssetDependencies};
use bevy_diagnostic::{Diagnostic, DiagnosticsStore, RegisterDiagnostic};
pub use direct_access_ext::DirectAssetAccessExt;
pub use event::*;
pub use folder::*;
pub use futures_lite::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
pub use handle::*;
pub use id::*;
pub use loader::*;
pub use loader_builders::NestedLoadBuilder;
pub use path::*;
pub use reflect::*;
pub use render_asset::*;
pub use server::*;

pub use uuid;

use crate::{
    io::{embedded::EmbeddedAssetRegistry, AssetSourceBuilder, AssetSourceBuilders, AssetSourceId},
    processor::{AssetProcessor, Process},
};
use alloc::{
    string::{String, ToString},
    sync::Arc,
    vec::Vec,
};
use bevy_app::{App, Plugin, PostUpdate, PreUpdate};
use bevy_ecs::{prelude::Component, schedule::common_conditions::resource_exists};
use bevy_ecs::{
    reflect::AppTypeRegistry,
    schedule::{IntoScheduleConfigs, SystemSet},
    world::FromWorld,
};
use bevy_platform::collections::{HashMap, HashSet};
use bevy_reflect::{FromReflect, GetTypeRegistration, Reflect, TypePath};
use core::any::TypeId;
use tracing::error;

/// Provides "asset" loading and processing functionality. An [`Asset`] is a "runtime value" that is loaded from an [`AssetSource`],
/// which can be something like a filesystem, a network, etc.
///
/// Supports flexible "modes", such as [`AssetMode::Processed`] and
/// [`AssetMode::Unprocessed`] that enable using the asset workflow that best suits your project.
///
/// [`AssetSource`]: io::AssetSource
pub struct AssetPlugin {
    /// The default file path to use (relative to the project root) for unprocessed assets.
    pub file_path: String,
    /// The default file path to use (relative to the project root) for processed assets.
    pub processed_file_path: String,
    /// If set, will override the default "watch for changes" setting. By default "watch for changes" will be `false` unless
    /// the `watch` cargo feature is set. `watch` can be enabled manually, or it will be automatically enabled if a specific watcher
    /// like `file_watcher` is enabled.
    ///
    /// Most use cases should leave this set to [`None`] and enable a specific watcher feature such as `file_watcher` to enable
    /// watching for dev-scenarios.
    pub watch_for_changes_override: Option<bool>,
    /// If set, will override the default "use asset processor" setting. By default "use asset
    /// processor" will be `false` unless the `asset_processor` cargo feature is set.
    ///
    /// Most use cases should leave this set to [`None`] and enable the `asset_processor` cargo
    /// feature.
    pub use_asset_processor_override: Option<bool>,
    /// The [`AssetMode`] to use for this server.
    pub mode: AssetMode,
    /// How/If asset meta files should be checked.
    pub meta_check: AssetMetaCheck,
    /// How to handle load requests of files that are outside the approved directories.
    ///
    /// Approved folders are [`AssetPlugin::file_path`] and the folder of each
    /// [`AssetSource`](io::AssetSource). Subfolders within these folders are also valid.
    pub unapproved_path_mode: UnapprovedPathMode,
}

/// Determines how to react to attempts to load assets not inside the approved folders.
///
/// Approved folders are [`AssetPlugin::file_path`] and the folder of each
/// [`AssetSource`](io::AssetSource). Subfolders within these folders are also valid.
///
/// It is strongly discouraged to use [`Allow`](UnapprovedPathMode::Allow) if your
/// app will include scripts or modding support, as it could allow arbitrary file
/// access for malicious code.
///
/// The default value is [`Forbid`](UnapprovedPathMode::Forbid).
///
/// See [`AssetPath::is_unapproved`](crate::AssetPath::is_unapproved)
#[derive(Clone, Default)]
pub enum UnapprovedPathMode {
    /// Unapproved asset loading is allowed. This is strongly discouraged.
    Allow,
    /// Fails to load any asset that is unapproved, unless [`LoadBuilder::override_unapproved`] is
    /// used.
    Deny,
    /// Fails to load any asset that is unapproved.
    #[default]
    Forbid,
}

/// Controls whether or not assets are pre-processed before being loaded.
///
/// This setting is controlled by setting [`AssetPlugin::mode`].
///
/// When building on web, asset preprocessing can cause problems due to the lack of filesystem access.
/// See [bevy#10157](https://github.com/bevyengine/bevy/issues/10157) for context.
#[derive(Debug)]
pub enum AssetMode {
    /// Loads assets from their [`AssetSource`]'s default [`AssetReader`] without any "preprocessing".
    ///
    /// [`AssetReader`]: io::AssetReader
    /// [`AssetSource`]: io::AssetSource
    Unprocessed,
    /// Assets will be "pre-processed". This enables assets to be imported / converted / optimized ahead of time.
    ///
    /// Assets will be read from their unprocessed [`AssetSource`] (defaults to the `assets` folder),
    /// processed according to their [`AssetMeta`], and written to their processed [`AssetSource`] (defaults to the `imported_assets/Default` folder).
    ///
    /// By default, this assumes the processor _has already been run_. It will load assets from their final processed [`AssetReader`].
    ///
    /// When developing an app, you should enable the `asset_processor` cargo feature, which will run the asset processor at startup. This should generally
    /// be used in combination with the `file_watcher` cargo feature, which enables hot-reloading of assets that have changed. When both features are enabled,
    /// changes to "original/source assets" will be detected, the asset will be re-processed, and then the final processed asset will be hot-reloaded in the app.
    ///
    /// [`AssetMeta`]: meta::AssetMeta
    /// [`AssetSource`]: io::AssetSource
    /// [`AssetReader`]: io::AssetReader
    Processed,
}

/// Configures how / if meta files will be checked. If an asset's meta file is not checked, the default meta for the asset
/// will be used.
#[derive(Debug, Default, Clone)]
pub enum AssetMetaCheck {
    /// Always check if assets have meta files. If the meta does not exist, the default meta will be used.
    #[default]
    Always,
    /// Only look up meta files for the provided paths. The default meta will be used for any paths not contained in this set.
    Paths(HashSet<AssetPath<'static>>),
    /// Never check if assets have meta files and always use the default meta. If meta files exist, they will be ignored and the default meta will be used.
    Never,
}

impl Default for AssetPlugin {
    fn default() -> Self {
        Self {
            mode: AssetMode::Unprocessed,
            file_path: Self::DEFAULT_UNPROCESSED_FILE_PATH.to_string(),
            processed_file_path: Self::DEFAULT_PROCESSED_FILE_PATH.to_string(),
            watch_for_changes_override: None,
            use_asset_processor_override: None,
            meta_check: AssetMetaCheck::default(),
            unapproved_path_mode: UnapprovedPathMode::default(),
        }
    }
}

impl AssetPlugin {
    const DEFAULT_UNPROCESSED_FILE_PATH: &'static str = "assets";
    /// NOTE: this is in the Default sub-folder to make this forward compatible with "import profiles"
    /// and to allow us to put the "processor transaction log" at `imported_assets/log`
    const DEFAULT_PROCESSED_FILE_PATH: &'static str = "imported_assets/Default";
}

impl Plugin for AssetPlugin {
    fn build(&self, app: &mut App) {
        let embedded = EmbeddedAssetRegistry::default();
        {
            let mut sources = app
                .world_mut()
                .get_resource_or_init::<AssetSourceBuilders>();
            sources.init_default_source(
                &self.file_path,
                (!matches!(self.mode, AssetMode::Unprocessed))
                    .then_some(self.processed_file_path.as_str()),
            );
            embedded.register_source(&mut sources);
        }
        {
            let watch = self
                .watch_for_changes_override
                .unwrap_or(cfg!(feature = "watch"));
            match self.mode {
                AssetMode::Unprocessed => {
                    let mut builders = app.world_mut().resource_mut::<AssetSourceBuilders>();
                    let sources = builders.build_sources(watch, false);

                    app.insert_resource(AssetServer::new_with_meta_check(
                        Arc::new(sources),
                        AssetServerMode::Unprocessed,
                        self.meta_check.clone(),
                        watch,
                        self.unapproved_path_mode.clone(),
                    ));
                }
                AssetMode::Processed => {
                    let use_asset_processor = self
                        .use_asset_processor_override
                        .unwrap_or(cfg!(feature = "asset_processor"));
                    if use_asset_processor {
                        let mut builders = app.world_mut().resource_mut::<AssetSourceBuilders>();
                        let (processor, sources) = AssetProcessor::new(&mut builders, watch);
                        // the main asset server shares loaders with the processor asset server
                        app.insert_resource(AssetServer::new_with_loaders(
                            sources,
                            processor.server().data.loaders.clone(),
                            AssetServerMode::Processed,
                            AssetMetaCheck::Always,
                            watch,
                            self.unapproved_path_mode.clone(),
                        ))
                        .insert_resource(processor)
                        .add_systems(bevy_app::Startup, AssetProcessor::start);
                    } else {
                        let mut builders = app.world_mut().resource_mut::<AssetSourceBuilders>();
                        let sources = builders.build_sources(false, watch);
                        app.insert_resource(AssetServer::new_with_meta_check(
                            Arc::new(sources),
                            AssetServerMode::Processed,
                            AssetMetaCheck::Always,
                            watch,
                            self.unapproved_path_mode.clone(),
                        ));
                    }
                }
            }
        }
        app.insert_resource(embedded)
            .init_asset::<LoadedFolder>()
            .init_asset::<LoadedUntypedAsset>()
            .init_asset::<()>()
            .add_message::<UntypedAssetLoadFailedEvent>()
            .configure_sets(
                PreUpdate,
                AssetTrackingSystems.after(handle_internal_asset_events),
            )
            // `handle_internal_asset_events` requires the use of `&mut World`,
            // and as a result has ambiguous system ordering with all other systems in `PreUpdate`.
            // This is virtually never a real problem: asset loading is async and so anything that interacts directly with it
            // needs to be robust to stochastic delays anyways.
            .add_systems(
                PreUpdate,
                (
                    handle_internal_asset_events.ambiguous_with_all(),
                    // TODO: Remove the run condition and use `If` once
                    // https://github.com/bevyengine/bevy/issues/21549 is resolved.
                    publish_asset_server_diagnostics.run_if(resource_exists::<DiagnosticsStore>),
                )
                    .chain(),
            )
            .register_diagnostic(Diagnostic::new(AssetServer::STARTED_LOAD_COUNT));
    }
}

/// Declares that this type is an asset,
/// which can be loaded and managed by the [`AssetServer`] and stored in [`Assets`] collections.
///
/// Generally, assets are large, complex, and/or expensive to load from disk, and are often authored by artists or designers.
///
/// [`TypePath`] is largely used for diagnostic purposes, and should almost always be implemented by deriving [`Reflect`] on your type.
/// [`VisitAssetDependencies`] is used to track asset dependencies, and an implementation is automatically generated when deriving [`Asset`].
#[diagnostic::on_unimplemented(
    message = "`{Self}` is not an `Asset`",
    label = "invalid `Asset`",
    note = "consider annotating `{Self}` with `#[derive(Asset)]`"
)]
pub trait Asset: VisitAssetDependencies + TypePath + Send + Sync + 'static {}

/// A trait for components that can be used as asset identifiers, e.g. handle wrappers.
pub trait AsAssetId: Component {
    /// The underlying asset type.
    type Asset: Asset;

    /// Retrieves the asset id from this component.
    fn as_asset_id(&self) -> AssetId<Self::Asset>;
}

/// This trait defines how to visit the dependencies of an asset.
/// For example, a 3D model might require both textures and meshes to be loaded.
///
/// Note that this trait is automatically implemented when deriving [`Asset`].
pub trait VisitAssetDependencies {
    fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId));
}

impl<A: Asset> VisitAssetDependencies for Handle<A> {
    fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
        visit(self.id().untyped());
    }
}

impl<A: Asset> VisitAssetDependencies for Option<Handle<A>> {
    fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
        if let Some(handle) = self {
            visit(handle.id().untyped());
        }
    }
}

impl VisitAssetDependencies for UntypedHandle {
    fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
        visit(self.id());
    }
}

impl VisitAssetDependencies for Option<UntypedHandle> {
    fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
        if let Some(handle) = self {
            visit(handle.id());
        }
    }
}

impl VisitAssetDependencies for UntypedAssetId {
    fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
        visit(*self);
    }
}

impl<A: Asset, const N: usize> VisitAssetDependencies for [Handle<A>; N] {
    fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
        for dependency in self {
            visit(dependency.id().untyped());
        }
    }
}

impl<const N: usize> VisitAssetDependencies for [UntypedHandle; N] {
    fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
        for dependency in self {
            visit(dependency.id());
        }
    }
}

impl<V: VisitAssetDependencies> VisitAssetDependencies for Vec<V> {
    fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
        for dependency in self {
            dependency.visit_dependencies(visit);
        }
    }
}

impl<V: VisitAssetDependencies> VisitAssetDependencies for HashSet<V> {
    fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
        for dependency in self {
            dependency.visit_dependencies(visit);
        }
    }
}

impl<A: Asset, K> VisitAssetDependencies for HashMap<K, Handle<A>> {
    fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
        for dependency in self.values() {
            visit(dependency.id().untyped());
        }
    }
}

impl<K> VisitAssetDependencies for HashMap<K, UntypedHandle> {
    fn visit_dependencies(&self, visit: &mut impl FnMut(UntypedAssetId)) {
        for dependency in self.values() {
            visit(dependency.id());
        }
    }
}

/// Adds asset-related builder methods to [`App`].
pub trait AssetApp {
    /// Registers the given `loader` in the [`App`]'s [`AssetServer`].
    fn register_asset_loader<L: AssetLoader>(&mut self, loader: L) -> &mut Self;
    /// Registers the given `processor` in the [`App`]'s [`AssetProcessor`].
    fn register_asset_processor<P: Process>(&mut self, processor: P) -> &mut Self;
    /// Registers the given [`AssetSourceBuilder`] with the given `id`.
    ///
    /// Note that asset sources must be registered before adding [`AssetPlugin`] to your application,
    /// since registered asset sources are built at that point and not after.
    fn register_asset_source(
        &mut self,
        id: impl Into<AssetSourceId<'static>>,
        source: AssetSourceBuilder,
    ) -> &mut Self;
    /// Sets the default asset processor for the given `extension`.
    fn set_default_asset_processor<P: Process>(&mut self, extension: &str) -> &mut Self;
    /// Initializes the given loader in the [`App`]'s [`AssetServer`].
    fn init_asset_loader<L: AssetLoader + FromWorld>(&mut self) -> &mut Self;
    /// Initializes the given [`Asset`] in the [`App`] by:
    /// * Registering the [`Asset`] in the [`AssetServer`]
    /// * Initializing the [`AssetEvent`] resource for the [`Asset`]
    /// * Adding other relevant systems and resources for the [`Asset`]
    /// * Ignoring schedule ambiguities in [`Assets`] resource. Any time a system takes
    ///   mutable access to this resource this causes a conflict, but they rarely actually
    ///   modify the same underlying asset.
    fn init_asset<A: Asset>(&mut self) -> &mut Self;
    /// Registers the asset type `T` using `[App::register]`,
    /// and adds [`ReflectAsset`] type data to `T` and [`ReflectHandle`] type data to [`Handle<T>`] in the type registry.
    ///
    /// This enables reflection code to access assets. For detailed information, see the docs on [`ReflectAsset`] and [`ReflectHandle`].
    fn register_asset_reflect<A>(&mut self) -> &mut Self
    where
        A: Asset + Reflect + FromReflect + GetTypeRegistration;
    /// Preregisters a loader for the given extensions, that will block asset loads until a real loader
    /// is registered.
    fn preregister_asset_loader<L: AssetLoader>(&mut self, extensions: &[&str]) -> &mut Self;
}

impl AssetApp for App {
    fn register_asset_loader<L: AssetLoader>(&mut self, loader: L) -> &mut Self {
        self.world()
            .resource::<AssetServer>()
            .register_loader(loader);
        self
    }

    fn register_asset_processor<P: Process>(&mut self, processor: P) -> &mut Self {
        if let Some(asset_processor) = self.world().get_resource::<AssetProcessor>() {
            asset_processor.register_processor(processor);
        }
        self
    }

    fn register_asset_source(
        &mut self,
        id: impl Into<AssetSourceId<'static>>,
        source: AssetSourceBuilder,
    ) -> &mut Self {
        let id = id.into();
        if self.world().get_resource::<AssetServer>().is_some() {
            error!("{} must be registered before `AssetPlugin` (typically added as part of `DefaultPlugins`)", id);
        }

        {
            let mut sources = self
                .world_mut()
                .get_resource_or_init::<AssetSourceBuilders>();
            sources.insert(id, source);
        }

        self
    }

    fn set_default_asset_processor<P: Process>(&mut self, extension: &str) -> &mut Self {
        if let Some(asset_processor) = self.world().get_resource::<AssetProcessor>() {
            asset_processor.set_default_processor::<P>(extension);
        }
        self
    }

    fn init_asset_loader<L: AssetLoader + FromWorld>(&mut self) -> &mut Self {
        let loader = L::from_world(self.world_mut());
        self.register_asset_loader(loader)
    }

    fn init_asset<A: Asset>(&mut self) -> &mut Self {
        let assets = Assets::<A>::default();
        self.world()
            .resource::<AssetServer>()
            .register_asset(&assets);
        if self.world().contains_resource::<AssetProcessor>() {
            let processor = self.world().resource::<AssetProcessor>();
            // The processor should have its own handle provider separate from the Asset storage
            // to ensure the id spaces are entirely separate. Not _strictly_ necessary, but
            // desirable.
            processor
                .server()
                .register_handle_provider(AssetHandleProvider::new(
                    TypeId::of::<A>(),
                    Arc::new(AssetIndexAllocator::default()),
                ));
        }
        self.insert_resource(assets)
            .allow_ambiguous_resource::<Assets<A>>()
            .add_message::<AssetEvent<A>>()
            .add_message::<AssetLoadFailedEvent<A>>()
            .register_type::<Handle<A>>()
            .add_systems(
                PostUpdate,
                Assets::<A>::asset_events
                    .run_if(Assets::<A>::asset_events_condition)
                    .in_set(AssetEventSystems),
            )
            .add_systems(
                PreUpdate,
                Assets::<A>::track_assets.in_set(AssetTrackingSystems),
            )
    }

    fn register_asset_reflect<A>(&mut self) -> &mut Self
    where
        A: Asset + Reflect + FromReflect + GetTypeRegistration,
    {
        let type_registry = self.world().resource::<AppTypeRegistry>();
        {
            let mut type_registry = type_registry.write();

            type_registry.register::<A>();
            type_registry.register::<Handle<A>>();
            type_registry.register::<HandleTemplate<A>>();
            type_registry.register_type_data::<A, ReflectAsset>();
            type_registry.register_type_data::<Handle<A>, ReflectHandle>();
            type_registry
                .register_type_conversion::<String, HandleTemplate<A>, _>(|s| Ok(s.into()));
        }

        self
    }

    fn preregister_asset_loader<L: AssetLoader>(&mut self, extensions: &[&str]) -> &mut Self {
        self.world_mut()
            .resource_mut::<AssetServer>()
            .preregister_loader::<L>(extensions);
        self
    }
}

/// A system set that holds all "track asset" operations.
#[derive(SystemSet, Hash, Debug, PartialEq, Eq, Clone)]
pub struct AssetTrackingSystems;

/// A system set where events accumulated in [`Assets`] are applied to the [`AssetEvent`] [`Messages`] resource.
///
/// [`Messages`]: bevy_ecs::message::Messages
#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]
pub struct AssetEventSystems;

#[cfg(test)]
mod tests {
    use crate::{
        folder::LoadedFolder,
        handle::Handle,
        io::{
            gated::{GateOpener, GatedReader},
            memory::{Dir, MemoryAssetReader, MemoryAssetWriter},
            AssetReader, AssetReaderError, AssetSourceBuilder, AssetSourceEvent, AssetSourceId,
            AssetWatcher, Reader,
        },
        loader::{AssetLoader, LoadContext},
        Asset, AssetApp, AssetEvent, AssetId, AssetLoadError, AssetLoadFailedEvent, AssetPath,
        AssetPlugin, AssetServer, Assets, InvalidGenerationError, LoadState, LoadedAsset,
        UnapprovedPathMode, UntypedHandle, VisitAssetDependencies, WriteDefaultMetaError,
    };
    use alloc::{
        boxed::Box,
        format,
        string::{String, ToString},
        sync::Arc,
        vec,
        vec::Vec,
    };
    use async_channel::{Receiver, Sender};
    use bevy_app::{App, TaskPoolPlugin, Update};
    use bevy_diagnostic::{DiagnosticsPlugin, DiagnosticsStore};
    use bevy_ecs::{
        message::MessageCursor,
        prelude::*,
        schedule::{LogLevel, ScheduleBuildSettings},
    };
    use bevy_platform::{
        collections::{HashMap, HashSet},
        sync::Mutex,
    };
    use bevy_reflect::{Reflect, TypePath};
    use bevy_tasks::block_on;
    use core::{any::TypeId, time::Duration};
    use futures_lite::AsyncReadExt;
    use ron::ser::PrettyConfig;
    use serde::{Deserialize, Serialize};
    use std::path::{Path, PathBuf};
    use thiserror::Error;

    #[derive(Asset, Debug, Default, Reflect)]
    pub struct CoolText {
        pub text: String,
        pub embedded: String,
        #[dependency]
        pub dependencies: Vec<Handle<CoolText>>,
        #[dependency]
        pub sub_texts: Vec<Handle<SubText>>,
    }

    #[derive(Asset, TypePath, Debug)]
    pub struct SubText {
        pub text: String,
    }

    #[derive(Serialize, Deserialize, Default)]
    pub struct CoolTextRon {
        pub text: String,
        pub dependencies: Vec<String>,
        pub embedded_dependencies: Vec<String>,
        pub sub_texts: Vec<String>,
    }

    #[derive(Default, TypePath)]
    pub struct CoolTextLoader;

    #[derive(Error, Debug)]
    pub enum CoolTextLoaderError {
        #[error("Could not load dependency: {dependency}")]
        CannotLoadDependency { dependency: AssetPath<'static> },
        #[error("A RON error occurred during loading")]
        RonSpannedError(#[from] ron::error::SpannedError),
        #[error("An IO error occurred during loading")]
        Io(#[from] std::io::Error),
    }

    impl AssetLoader for CoolTextLoader {
        type Asset = CoolText;

        type Settings = ();

        type Error = CoolTextLoaderError;

        async fn load(
            &self,
            reader: &mut dyn Reader,
            _settings: &Self::Settings,
            load_context: &mut LoadContext<'_>,
        ) -> Result<Self::Asset, Self::Error> {
            let mut bytes = Vec::new();
            reader.read_to_end(&mut bytes).await?;
            let mut ron: CoolTextRon = ron::de::from_bytes(&bytes)?;
            let mut embedded = String::new();
            for dep in ron.embedded_dependencies {
                let loaded = load_context
                    .load_builder()
                    .load_value::<CoolText>(&dep)
                    .await
                    .map_err(|_| Self::Error::CannotLoadDependency {
                        dependency: dep.into(),
                    })?;
                let cool = loaded.get();
                embedded.push_str(&cool.text);
            }
            Ok(CoolText {
                text: ron.text,
                embedded,
                dependencies: ron
                    .dependencies
                    .iter()
                    .map(|p| load_context.load(p))
                    .collect(),
                sub_texts: ron
                    .sub_texts
                    .drain(..)
                    .map(|text| load_context.add_labeled_asset(text.clone(), SubText { text }))
                    .collect(),
            })
        }

        fn extensions(&self) -> &[&str] {
            &["cool.ron"]
        }
    }

    /// A dummy [`CoolText`] asset reader that only succeeds after `failure_count` times it's read from for each asset.
    #[derive(Default, Clone)]
    pub struct UnstableMemoryAssetReader {
        pub attempt_counters: Arc<Mutex<HashMap<Box<Path>, usize>>>,
        pub load_delay: Duration,
        memory_reader: MemoryAssetReader,
        failure_count: usize,
    }

    impl UnstableMemoryAssetReader {
        pub fn new(root: Dir, failure_count: usize) -> Self {
            Self {
                load_delay: Duration::from_millis(10),
                memory_reader: MemoryAssetReader { root },
                attempt_counters: Default::default(),
                failure_count,
            }
        }
    }

    impl AssetReader for UnstableMemoryAssetReader {
        async fn is_directory<'a>(&'a self, path: &'a Path) -> Result<bool, AssetReaderError> {
            self.memory_reader.is_directory(path).await
        }
        async fn read_directory<'a>(
            &'a self,
            path: &'a Path,
        ) -> Result<Box<bevy_asset::io::PathStream>, AssetReaderError> {
            self.memory_reader.read_directory(path).await
        }
        async fn read_meta<'a>(
            &'a self,
            path: &'a Path,
        ) -> Result<impl Reader + 'a, AssetReaderError> {
            self.memory_reader.read_meta(path).await
        }
        async fn read<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
            let attempt_number = {
                let mut attempt_counters = self.attempt_counters.lock().unwrap();
                if let Some(existing) = attempt_counters.get_mut(path) {
                    *existing += 1;
                    *existing
                } else {
                    attempt_counters.insert(path.into(), 1);
                    1
                }
            };

            if attempt_number <= self.failure_count {
                let io_error = std::io::Error::new(
                    std::io::ErrorKind::ConnectionRefused,
                    format!(
                        "Simulated failure {attempt_number} of {}",
                        self.failure_count
                    ),
                );
                let wait = self.load_delay;
                return async move {
                    std::thread::sleep(wait);
                    Err(AssetReaderError::Io(io_error.into()))
                }
                .await;
            }

            self.memory_reader.read(path).await
        }
    }

    /// Creates a basic asset app and an in-memory file system.
    pub(crate) fn create_app() -> (App, Dir) {
        let mut app = App::new();
        let dir = Dir::default();
        let dir_clone = dir.clone();
        let dir_clone2 = dir.clone();
        app.register_asset_source(
            AssetSourceId::Default,
            AssetSourceBuilder::new(move || {
                Box::new(MemoryAssetReader {
                    root: dir_clone.clone(),
                })
            })
            .with_writer(move |_| {
                Some(Box::new(MemoryAssetWriter {
                    root: dir_clone2.clone(),
                }))
            }),
        )
        .add_plugins((
            TaskPoolPlugin::default(),
            AssetPlugin {
                watch_for_changes_override: Some(false),
                use_asset_processor_override: Some(false),
                ..Default::default()
            },
            DiagnosticsPlugin,
        ));
        (app, dir)
    }

    fn create_app_with_gate(dir: Dir) -> (App, GateOpener) {
        let mut app = App::new();
        let (gated_memory_reader, gate_opener) = GatedReader::new(MemoryAssetReader { root: dir });
        app.register_asset_source(
            AssetSourceId::Default,
            AssetSourceBuilder::new(move || Box::new(gated_memory_reader.clone())),
        )
        .add_plugins((
            TaskPoolPlugin::default(),
            AssetPlugin {
                watch_for_changes_override: Some(false),
                use_asset_processor_override: Some(false),
                ..Default::default()
            },
            DiagnosticsPlugin,
        ));
        (app, gate_opener)
    }

    pub fn run_app_until(app: &mut App, mut predicate: impl FnMut(&mut World) -> Option<()>) {
        for _ in 0..LARGE_ITERATION_COUNT {
            app.update();
            if predicate(app.world_mut()).is_some() {
                return;
            }
        }

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

    const LARGE_ITERATION_COUNT: usize = 10000;

    fn get<A: Asset>(world: &World, id: AssetId<A>) -> Option<&A> {
        world.resource::<Assets<A>>().get(id)
    }

    fn get_started_load_count(world: &World) -> usize {
        world
            .resource::<DiagnosticsStore>()
            .get_measurement(&AssetServer::STARTED_LOAD_COUNT)
            .map(|measurement| measurement.value as _)
            .unwrap_or_default()
    }

    #[derive(Resource, Default)]
    struct StoredEvents(Vec<AssetEvent<CoolText>>);

    fn store_asset_events(
        mut reader: MessageReader<AssetEvent<CoolText>>,
        mut storage: ResMut<StoredEvents>,
    ) {
        storage.0.extend(reader.read().cloned());
    }

    /// Serializes `text` into a `CoolText` that can be loaded.
    ///
    /// This doesn't support all the features of `CoolText`, so more complex scenarios may require
    /// doing this manually.
    pub(crate) fn serialize_as_cool_text(text: &str) -> String {
        let cool_text_ron = CoolTextRon {
            text: text.into(),
            dependencies: vec![],
            embedded_dependencies: vec![],
            sub_texts: vec![],
        };
        ron::ser::to_string_pretty(&cool_text_ron, PrettyConfig::new().new_line("\n")).unwrap()
    }

    #[test]
    fn load_dependencies() {
        let dir = Dir::default();

        let a_path = "a.cool.ron";
        let a_ron = r#"
(
    text: "a",
    dependencies: [
        "foo/b.cool.ron",
        "c.cool.ron",
    ],
    embedded_dependencies: [],
    sub_texts: [],
)"#;
        let b_path = "foo/b.cool.ron";
        let b_ron = r#"
(
    text: "b",
    dependencies: [],
    embedded_dependencies: [],
    sub_texts: [],
)"#;

        let c_path = "c.cool.ron";
        let c_ron = r#"
(
    text: "c",
    dependencies: [
        "d.cool.ron",
    ],
    embedded_dependencies: ["a.cool.ron", "foo/b.cool.ron"],
    sub_texts: ["hello"],
)"#;

        let d_path = "d.cool.ron";
        let d_ron = r#"
(
    text: "d",
    dependencies: [],
    embedded_dependencies: [],
    sub_texts: [],
)"#;

        dir.insert_asset_text(Path::new(a_path), a_ron);
        dir.insert_asset_text(Path::new(b_path), b_ron);
        dir.insert_asset_text(Path::new(c_path), c_ron);
        dir.insert_asset_text(Path::new(d_path), d_ron);

        #[derive(Resource)]
        struct IdResults {
            b_id: AssetId<CoolText>,
            c_id: AssetId<CoolText>,
            d_id: AssetId<CoolText>,
        }

        let (mut app, gate_opener) = create_app_with_gate(dir);
        app.init_asset::<CoolText>()
            .init_asset::<SubText>()
            .init_resource::<StoredEvents>()
            .register_asset_loader(CoolTextLoader)
            .add_systems(Update, store_asset_events);
        let asset_server = app.world().resource::<AssetServer>().clone();
        let handle: Handle<CoolText> = asset_server.load(a_path);
        let a_id = handle.id();
        app.update();
        assert_eq!(get_started_load_count(app.world()), 1);

        {
            let a_text = get::<CoolText>(app.world(), a_id);
            let (a_load, a_deps, a_rec_deps) = asset_server.get_load_states(a_id).unwrap();
            assert!(a_text.is_none(), "a's asset should not exist yet");
            assert!(a_load.is_loading());
            assert!(a_deps.is_loading());
            assert!(a_rec_deps.is_loading());
        }

        // Allow "a" to load ... wait for it to finish loading and validate results
        // Dependencies are still gated so they should not be loaded yet
        gate_opener.open(a_path);
        run_app_until(&mut app, |world| {
            let a_text = get::<CoolText>(world, a_id)?;
            let (a_load, a_deps, a_rec_deps) = asset_server.get_load_states(a_id).unwrap();
            assert_eq!(a_text.text, "a");
            assert_eq!(a_text.dependencies.len(), 2);
            assert!(a_load.is_loaded());
            assert!(a_deps.is_loading());
            assert!(a_rec_deps.is_loading());

            let b_id = a_text.dependencies[0].id();
            let b_text = get::<CoolText>(world, b_id);
            let (b_load, b_deps, b_rec_deps) = asset_server.get_load_states(b_id).unwrap();
            assert!(b_text.is_none(), "b component should not exist yet");
            assert!(b_load.is_loading());
            assert!(b_deps.is_loading());
            assert!(b_rec_deps.is_loading());

            let c_id = a_text.dependencies[1].id();
            let c_text = get::<CoolText>(world, c_id);
            let (c_load, c_deps, c_rec_deps) = asset_server.get_load_states(c_id).unwrap();
            assert!(c_text.is_none(), "c component should not exist yet");
            assert!(c_load.is_loading());
            assert!(c_deps.is_loading());
            assert!(c_rec_deps.is_loading());
            Some(())
        });
        assert_eq!(get_started_load_count(app.world()), 3);

        // Allow "b" to load ... wait for it to finish loading and validate results
        // "c" should not be loaded yet
        gate_opener.open(b_path);
        run_app_until(&mut app, |world| {
            let a_text = get::<CoolText>(world, a_id)?;
            let (a_load, a_deps, a_rec_deps) = asset_server.get_load_states(a_id).unwrap();
            assert_eq!(a_text.text, "a");
            assert_eq!(a_text.dependencies.len(), 2);
            assert!(a_load.is_loaded());
            assert!(a_deps.is_loading());
            assert!(a_rec_deps.is_loading());

            let b_id = a_text.dependencies[0].id();
            let b_text = get::<CoolText>(world, b_id)?;
            let (b_load, b_deps, b_rec_deps) = asset_server.get_load_states(b_id).unwrap();
            assert_eq!(b_text.text, "b");
            assert!(b_load.is_loaded());
            assert!(b_deps.is_loaded());
            assert!(b_rec_deps.is_loaded());

            let c_id = a_text.dependencies[1].id();
            let c_text = get::<CoolText>(world, c_id);
            let (c_load, c_deps, c_rec_deps) = asset_server.get_load_states(c_id).unwrap();
            assert!(c_text.is_none(), "c component should not exist yet");
            assert!(c_load.is_loading());
            assert!(c_deps.is_loading());
            assert!(c_rec_deps.is_loading());
            Some(())
        });
        assert_eq!(get_started_load_count(app.world()), 3);

        // Allow "c" to load ... wait for it to finish loading and validate results
        // all "a" dependencies should be loaded now
        gate_opener.open(c_path);

        // Re-open a and b gates to allow c to load embedded deps (gates are closed after each load)
        gate_opener.open(a_path);
        gate_opener.open(b_path);
        run_app_until(&mut app, |world| {
            let a_text = get::<CoolText>(world, a_id)?;
            let (a_load, a_deps, a_rec_deps) = asset_server.get_load_states(a_id).unwrap();
            assert_eq!(a_text.text, "a");
            assert_eq!(a_text.embedded, "");
            assert_eq!(a_text.dependencies.len(), 2);
            assert!(a_load.is_loaded());

            let b_id = a_text.dependencies[0].id();
            let b_text = get::<CoolText>(world, b_id)?;
            let (b_load, b_deps, b_rec_deps) = asset_server.get_load_states(b_id).unwrap();
            assert_eq!(b_text.text, "b");
            assert_eq!(b_text.embedded, "");
            assert!(b_load.is_loaded());
            assert!(b_deps.is_loaded());
            assert!(b_rec_deps.is_loaded());

            let c_id = a_text.dependencies[1].id();
            let c_text = get::<CoolText>(world, c_id)?;
            let (c_load, c_deps, c_rec_deps) = asset_server.get_load_states(c_id).unwrap();
            assert_eq!(c_text.text, "c");
            assert_eq!(c_text.embedded, "ab");
            assert!(c_load.is_loaded());
            assert!(
                c_deps.is_loading(),
                "c deps should not be loaded yet because d has not loaded"
            );
            assert!(
                c_rec_deps.is_loading(),
                "c rec deps should not be loaded yet because d has not loaded"
            );

            let sub_text_id = c_text.sub_texts[0].id();
            let sub_text = get::<SubText>(world, sub_text_id)
                .expect("subtext should exist if c exists. it came from the same loader");
            assert_eq!(sub_text.text, "hello");
            let (sub_text_load, sub_text_deps, sub_text_rec_deps) =
                asset_server.get_load_states(sub_text_id).unwrap();
            assert!(sub_text_load.is_loaded());
            assert!(sub_text_deps.is_loaded());
            assert!(sub_text_rec_deps.is_loaded());

            let d_id = c_text.dependencies[0].id();
            let d_text = get::<CoolText>(world, d_id);
            let (d_load, d_deps, d_rec_deps) = asset_server.get_load_states(d_id).unwrap();
            assert!(d_text.is_none(), "d component should not exist yet");
            assert!(d_load.is_loading());
            assert!(d_deps.is_loading());
            assert!(d_rec_deps.is_loading());

            assert!(
                a_deps.is_loaded(),
                "If c has been loaded, the a deps should all be considered loaded"
            );
            assert!(
                a_rec_deps.is_loading(),
                "d is not loaded, so a's recursive deps should still be loading"
            );
            world.insert_resource(IdResults { b_id, c_id, d_id });
            Some(())
        });
        assert_eq!(get_started_load_count(app.world()), 6);

        gate_opener.open(d_path);
        run_app_until(&mut app, |world| {
            let a_text = get::<CoolText>(world, a_id)?;
            let (_a_load, _a_deps, a_rec_deps) = asset_server.get_load_states(a_id).unwrap();
            let c_id = a_text.dependencies[1].id();
            let c_text = get::<CoolText>(world, c_id)?;
            let (c_load, c_deps, c_rec_deps) = asset_server.get_load_states(c_id).unwrap();
            assert_eq!(c_text.text, "c");
            assert_eq!(c_text.embedded, "ab");

            let d_id = c_text.dependencies[0].id();
            let d_text = get::<CoolText>(world, d_id)?;
            let (d_load, d_deps, d_rec_deps) = asset_server.get_load_states(d_id).unwrap();
            assert_eq!(d_text.text, "d");
            assert_eq!(d_text.embedded, "");

            assert!(c_load.is_loaded());
            assert!(c_deps.is_loaded());
            assert!(c_rec_deps.is_loaded());

            assert!(d_load.is_loaded());
            assert!(d_deps.is_loaded());
            assert!(d_rec_deps.is_loaded());

            assert!(
                a_rec_deps.is_loaded(),
                "d is loaded, so a's recursive deps should be loaded"
            );
            Some(())
        });

        assert_eq!(get_started_load_count(app.world()), 6);

        {
            let mut texts = app.world_mut().resource_mut::<Assets<CoolText>>();
            let mut a = texts.get_mut(a_id).unwrap();
            a.text = "Changed".to_string();
        }

        drop(handle);

        app.update();
        assert_eq!(
            app.world().resource::<Assets<CoolText>>().len(),
            0,
            "CoolText asset entities should be despawned when no more handles exist"
        );
        app.update();
        // this requires a second update because the parent asset was freed in the previous app.update()
        assert_eq!(
            app.world().resource::<Assets<SubText>>().len(),
            0,
            "SubText asset entities should be despawned when no more handles exist"
        );
        let events = app.world_mut().remove_resource::<StoredEvents>().unwrap();
        let id_results = app.world_mut().remove_resource::<IdResults>().unwrap();
        let expected_events = vec![
            AssetEvent::Added { id: a_id },
            AssetEvent::LoadedWithDependencies {
                id: id_results.b_id,
            },
            AssetEvent::Added {
                id: id_results.b_id,
            },
            AssetEvent::Added {
                id: id_results.c_id,
            },
            AssetEvent::LoadedWithDependencies {
                id: id_results.d_id,
            },
            AssetEvent::LoadedWithDependencies {
                id: id_results.c_id,
            },
            AssetEvent::LoadedWithDependencies { id: a_id },
            AssetEvent::Added {
                id: id_results.d_id,
            },
            AssetEvent::Modified { id: a_id },
            AssetEvent::Unused { id: a_id },
            AssetEvent::Removed { id: a_id },
            AssetEvent::Unused {
                id: id_results.b_id,
            },
            AssetEvent::Removed {
                id: id_results.b_id,
            },
            AssetEvent::Unused {
                id: id_results.c_id,
            },
            AssetEvent::Removed {
                id: id_results.c_id,
            },
            AssetEvent::Unused {
                id: id_results.d_id,
            },
            AssetEvent::Removed {
                id: id_results.d_id,
            },
        ];
        assert_eq!(events.0, expected_events);
    }

    #[test]
    fn failure_load_states() {
        let dir = Dir::default();

        let a_path = "a.cool.ron";
        let a_ron = r#"
(
    text: "a",
    dependencies: [
        "b.cool.ron",
        "c.cool.ron",
    ],
    embedded_dependencies: [],
    sub_texts: []
)"#;
        let b_path = "b.cool.ron";
        let b_ron = r#"
(
    text: "b",
    dependencies: [],
    embedded_dependencies: [],
    sub_texts: []
)"#;

        let c_path = "c.cool.ron";
        let c_ron = r#"
(
    text: "c",
    dependencies: [
        "d.cool.ron",
    ],
    embedded_dependencies: [],
    sub_texts: []
)"#;

        let d_path = "d.cool.ron";
        let d_ron = r#"
(
    text: "d",
    dependencies: [],
    OH NO THIS ASSET IS MALFORMED
    embedded_dependencies: [],
    sub_texts: []
)"#;

        dir.insert_asset_text(Path::new(a_path), a_ron);
        dir.insert_asset_text(Path::new(b_path), b_ron);
        dir.insert_asset_text(Path::new(c_path), c_ron);
        dir.insert_asset_text(Path::new(d_path), d_ron);

        let (mut app, gate_opener) = create_app_with_gate(dir);
        app.init_asset::<CoolText>()
            .register_asset_loader(CoolTextLoader);
        let asset_server = app.world().resource::<AssetServer>().clone();
        let handle: Handle<CoolText> = asset_server.load(a_path);
        let a_id = handle.id();

        app.update();
        assert_eq!(get_started_load_count(app.world()), 1);
        {
            let other_handle: Handle<CoolText> = asset_server.load(a_path);
            assert_eq!(
                other_handle, handle,
                "handles from consecutive load calls should be equal"
            );
            assert_eq!(
                other_handle.id(),
                handle.id(),
                "handle ids from consecutive load calls should be equal"
            );

            app.update();
            // Only one load still!
            assert_eq!(get_started_load_count(app.world()), 1);
        }

        gate_opener.open(a_path);
        gate_opener.open(b_path);
        gate_opener.open(c_path);
        gate_opener.open(d_path);

        run_app_until(&mut app, |world| {
            let a_text = get::<CoolText>(world, a_id)?;
            let (a_load, a_deps, a_rec_deps) = asset_server.get_load_states(a_id).unwrap();

            let b_id = a_text.dependencies[0].id();
            let b_text = get::<CoolText>(world, b_id)?;
            let (b_load, b_deps, b_rec_deps) = asset_server.get_load_states(b_id).unwrap();

            let c_id = a_text.dependencies[1].id();
            let c_text = get::<CoolText>(world, c_id)?;
            let (c_load, c_deps, c_rec_deps) = asset_server.get_load_states(c_id).unwrap();

            let d_id = c_text.dependencies[0].id();
            let d_text = get::<CoolText>(world, d_id);
            let (d_load, d_deps, d_rec_deps) = asset_server.get_load_states(d_id).unwrap();

            if !d_load.is_failed() {
                // wait until d has exited the loading state
                return None;
            }

            assert!(d_text.is_none());
            assert!(d_load.is_failed());
            assert!(d_deps.is_failed());
            assert!(d_rec_deps.is_failed());

            assert_eq!(a_text.text, "a");
            assert!(a_load.is_loaded());
            assert!(a_deps.is_loaded());
            assert!(a_rec_deps.is_failed());

            assert_eq!(b_text.text, "b");
            assert!(b_load.is_loaded());
            assert!(b_deps.is_loaded());
            assert!(b_rec_deps.is_loaded());

            assert_eq!(c_text.text, "c");
            assert!(c_load.is_loaded());
            assert!(c_deps.is_failed());
            assert!(c_rec_deps.is_failed());

            assert!(asset_server.load_state(a_id).is_loaded());
            assert!(asset_server.dependency_load_state(a_id).is_loaded());
            assert!(asset_server
                .recursive_dependency_load_state(a_id)
                .is_failed());

            assert!(asset_server.is_loaded(a_id));
            assert!(asset_server.is_loaded_with_direct_dependencies(a_id));
            assert!(!asset_server.is_loaded_with_dependencies(a_id));

            Some(())
        });

        assert_eq!(get_started_load_count(app.world()), 4);
    }

    #[test]
    fn dependency_load_states() {
        let a_path = "a.cool.ron";
        let a_ron = r#"
(
    text: "a",
    dependencies: [
        "b.cool.ron",
        "c.cool.ron",
    ],
    embedded_dependencies: [],
    sub_texts: []
)"#;
        let b_path = "b.cool.ron";
        let b_ron = r#"
(
    text: "b",
    dependencies: [],
    MALFORMED
    embedded_dependencies: [],
    sub_texts: []
)"#;

        let c_path = "c.cool.ron";
        let c_ron = r#"
(
    text: "c",
    dependencies: [],
    embedded_dependencies: [],
    sub_texts: []
)"#;

        let dir = Dir::default();
        dir.insert_asset_text(Path::new(a_path), a_ron);
        dir.insert_asset_text(Path::new(b_path), b_ron);
        dir.insert_asset_text(Path::new(c_path), c_ron);

        let (mut app, gate_opener) = create_app_with_gate(dir);
        app.init_asset::<CoolText>()
            .register_asset_loader(CoolTextLoader);
        let asset_server = app.world().resource::<AssetServer>().clone();
        let handle: Handle<CoolText> = asset_server.load(a_path);
        let a_id = handle.id();

        app.update();
        assert_eq!(get_started_load_count(app.world()), 1);

        gate_opener.open(a_path);
        run_app_until(&mut app, |world| {
            let _a_text = get::<CoolText>(world, a_id)?;
            let (a_load, a_deps, a_rec_deps) = asset_server.get_load_states(a_id).unwrap();
            assert!(a_load.is_loaded());
            assert!(a_deps.is_loading());
            assert!(a_rec_deps.is_loading());
            Some(())
        });

        assert_eq!(get_started_load_count(app.world()), 3);

        gate_opener.open(b_path);
        run_app_until(&mut app, |world| {
            let a_text = get::<CoolText>(world, a_id)?;
            let b_id = a_text.dependencies[0].id();

            let (b_load, _b_deps, _b_rec_deps) = asset_server.get_load_states(b_id).unwrap();
            if !b_load.is_failed() {
                // wait until b fails
                return None;
            }

            let (a_load, a_deps, a_rec_deps) = asset_server.get_load_states(a_id).unwrap();
            assert!(a_load.is_loaded());
            assert!(a_deps.is_failed());
            assert!(a_rec_deps.is_failed());
            Some(())
        });

        assert_eq!(get_started_load_count(app.world()), 3);

        gate_opener.open(c_path);
        run_app_until(&mut app, |world| {
            let a_text = get::<CoolText>(world, a_id)?;
            let c_id = a_text.dependencies[1].id();
            // wait until c loads
            let _c_text = get::<CoolText>(world, c_id)?;

            let (a_load, a_deps, a_rec_deps) = asset_server.get_load_states(a_id).unwrap();
            assert!(a_load.is_loaded());
            assert!(
                a_deps.is_failed(),
                "Successful dependency load should not overwrite a previous failure"
            );
            assert!(
                a_rec_deps.is_failed(),
                "Successful dependency load should not overwrite a previous failure"
            );
            Some(())
        });

        assert_eq!(get_started_load_count(app.world()), 3);
    }

    const SIMPLE_TEXT: &str = r#"
(
    text: "dep",
    dependencies: [],
    embedded_dependencies: [],
    sub_texts: [],
)"#;
    #[test]
    fn keep_gotten_strong_handles() {
        let dir = Dir::default();
        dir.insert_asset_text(Path::new("dep.cool.ron"), SIMPLE_TEXT);

        let (mut app, _) = create_app_with_gate(dir);
        app.init_asset::<CoolText>()
            .init_asset::<SubText>()
            .init_resource::<StoredEvents>()
            .register_asset_loader(CoolTextLoader)
            .add_systems(Update, store_asset_events);

        let id = {
            let handle = {
                let mut texts = app.world_mut().resource_mut::<Assets<CoolText>>();
                let handle = texts.add(CoolText::default());
                texts.get_strong_handle(handle.id()).unwrap()
            };

            app.update();

            {
                let text = app.world().resource::<Assets<CoolText>>().get(&handle);
                assert!(text.is_some());
            }
            handle.id()
        };
        // handle is dropped
        app.update();
        assert!(
            app.world().resource::<Assets<CoolText>>().get(id).is_none(),
            "asset has no handles, so it should have been dropped last update"
        );
    }

    #[test]
    fn manual_asset_management() {
        let dir = Dir::default();
        let dep_path = "dep.cool.ron";

        dir.insert_asset_text(Path::new(dep_path), SIMPLE_TEXT);

        let (mut app, gate_opener) = create_app_with_gate(dir);
        app.init_asset::<CoolText>()
            .init_asset::<SubText>()
            .init_resource::<StoredEvents>()
            .register_asset_loader(CoolTextLoader)
            .add_systems(Update, store_asset_events);

        let hello = "hello".to_string();
        let empty = "".to_string();

        let id = {
            let handle = {
                let mut texts = app.world_mut().resource_mut::<Assets<CoolText>>();
                texts.add(CoolText {
                    text: hello.clone(),
                    embedded: empty.clone(),
                    dependencies: vec![],
                    sub_texts: Vec::new(),
                })
            };

            app.update();

            {
                let text = app
                    .world()
                    .resource::<Assets<CoolText>>()
                    .get(&handle)
                    .unwrap();
                assert_eq!(text.text, hello);
            }
            handle.id()
        };
        // handle is dropped
        app.update();
        assert!(
            app.world().resource::<Assets<CoolText>>().get(id).is_none(),
            "asset has no handles, so it should have been dropped last update"
        );
        // remove event is emitted
        app.update();
        let events = core::mem::take(&mut app.world_mut().resource_mut::<StoredEvents>().0);
        let expected_events = vec![
            AssetEvent::Added { id },
            AssetEvent::Unused { id },
            AssetEvent::Removed { id },
        ];

        // No loads have occurred yet.
        assert_eq!(get_started_load_count(app.world()), 0);

        assert_eq!(events, expected_events);

        let dep_handle = app.world().resource::<AssetServer>().load(dep_path);

        app.update();
        assert_eq!(get_started_load_count(app.world()), 1);

        let a = CoolText {
            text: "a".to_string(),
            embedded: empty,
            // this dependency is behind a manual load gate, which should prevent 'a' from emitting a LoadedWithDependencies event
            dependencies: vec![dep_handle.clone()],
            sub_texts: Vec::new(),
        };
        let a_handle = app.world().resource::<AssetServer>().load_asset(a);

        // load_asset does not count as a load.
        assert_eq!(get_started_load_count(app.world()), 1);

        app.update();
        // TODO: ideally it doesn't take two updates for the added event to emit
        app.update();

        let events = core::mem::take(&mut app.world_mut().resource_mut::<StoredEvents>().0);
        let expected_events = vec![AssetEvent::Added { id: a_handle.id() }];
        assert_eq!(events, expected_events);

        gate_opener.open(dep_path);
        loop {
            app.update();
            let events = core::mem::take(&mut app.world_mut().resource_mut::<StoredEvents>().0);
            if events.is_empty() {
                continue;
            }
            let expected_events = vec![
                AssetEvent::LoadedWithDependencies {
                    id: dep_handle.id(),
                },
                AssetEvent::LoadedWithDependencies { id: a_handle.id() },
            ];
            assert_eq!(events, expected_events);
            break;
        }

        assert_eq!(get_started_load_count(app.world()), 1);

        app.update();
        let events = core::mem::take(&mut app.world_mut().resource_mut::<StoredEvents>().0);
        let expected_events = vec![AssetEvent::Added {
            id: dep_handle.id(),
        }];
        assert_eq!(events, expected_events);
    }

    #[test]
    fn load_folder() {
        let dir = Dir::default();

        let a_path = "text/a.cool.ron";
        let a_ron = r#"
(
    text: "a",
    dependencies: [
        "b.cool.ron",
    ],
    embedded_dependencies: [],
    sub_texts: [],
)"#;
        let b_path = "b.cool.ron";
        let b_ron = r#"
(
    text: "b",
    dependencies: [],
    embedded_dependencies: [],
    sub_texts: [],
)"#;

        let c_path = "text/c.cool.ron";
        let c_ron = r#"
(
    text: "c",
    dependencies: [
    ],
    embedded_dependencies: [],
    sub_texts: [],
)"#;
        dir.insert_asset_text(Path::new(a_path), a_ron);
        dir.insert_asset_text(Path::new(b_path), b_ron);
        dir.insert_asset_text(Path::new(c_path), c_ron);

        let (mut app, gate_opener) = create_app_with_gate(dir);
        app.init_asset::<CoolText>()
            .init_asset::<SubText>()
            .register_asset_loader(CoolTextLoader);
        let asset_server = app.world().resource::<AssetServer>().clone();
        let handle: Handle<LoadedFolder> = asset_server.load_folder("text");

        // The folder started loading. The task will also try to start loading the first asset in
        // the folder. With the multi_threaded feature this check is racing with the first load, so
        // allow 1 or 2 load tasks to start.
        app.update();
        let started_load_tasks = get_started_load_count(app.world());
        assert!((1..=2).contains(&started_load_tasks));

        gate_opener.open(a_path);
        gate_opener.open(b_path);
        gate_opener.open(c_path);

        let mut cursor = MessageCursor::default();
        run_app_until(&mut app, |world| {
            let events = world.resource::<Messages<AssetEvent<LoadedFolder>>>();
            let asset_server = world.resource::<AssetServer>();
            let loaded_folders = world.resource::<Assets<LoadedFolder>>();
            let cool_texts = world.resource::<Assets<CoolText>>();
            for event in cursor.read(events) {
                if let AssetEvent::LoadedWithDependencies { id } = event
                    && *id == handle.id()
                {
                    let loaded_folder = loaded_folders.get(&handle).unwrap();
                    let a_handle: Handle<CoolText> =
                        asset_server.get_handle("text/a.cool.ron").unwrap();
                    let c_handle: Handle<CoolText> =
                        asset_server.get_handle("text/c.cool.ron").unwrap();

                    let mut found_a = false;
                    let mut found_c = false;
                    for asset_handle in &loaded_folder.handles {
                        if asset_handle.id() == a_handle.id().untyped() {
                            found_a = true;
                        } else if asset_handle.id() == c_handle.id().untyped() {
                            found_c = true;
                        }
                    }
                    assert!(found_a);
                    assert!(found_c);
                    assert_eq!(loaded_folder.handles.len(), 2);

                    let a_text = cool_texts.get(&a_handle).unwrap();
                    let b_text = cool_texts.get(&a_text.dependencies[0]).unwrap();
                    let c_text = cool_texts.get(&c_handle).unwrap();

                    assert_eq!("a", a_text.text);
                    assert_eq!("b", b_text.text);
                    assert_eq!("c", c_text.text);

                    return Some(());
                }
            }
            None
        });
        assert_eq!(get_started_load_count(app.world()), 4);
    }

    /// Tests that `AssetLoadFailedEvent<A>` events are emitted and can be used to retry failed assets.
    #[test]
    fn load_error_events() {
        #[derive(Resource, Default)]
        struct ErrorTracker {
            tick: u64,
            failures: usize,
            queued_retries: Vec<(AssetPath<'static>, AssetId<CoolText>, u64)>,
            finished_asset: Option<AssetId<CoolText>>,
        }

        fn asset_event_handler(
            mut events: MessageReader<AssetEvent<CoolText>>,
            mut tracker: ResMut<ErrorTracker>,
        ) {
            for event in events.read() {
                if let AssetEvent::LoadedWithDependencies { id } = event {
                    tracker.finished_asset = Some(*id);
                }
            }
        }

        fn asset_load_error_event_handler(
            server: Res<AssetServer>,
            mut errors: MessageReader<AssetLoadFailedEvent<CoolText>>,
            mut tracker: ResMut<ErrorTracker>,
        ) {
            // In the real world, this would refer to time (not ticks)
            tracker.tick += 1;

            // Retry loading past failed items
            let now = tracker.tick;
            tracker
                .queued_retries
                .retain(|(path, old_id, retry_after)| {
                    if now > *retry_after {
                        let new_handle = server.load::<CoolText>(path);
                        assert_eq!(&new_handle.id(), old_id);
                        false
                    } else {
                        true
                    }
                });

            // Check what just failed
            for error in errors.read() {
                let (load_state, _, _) = server.get_load_states(error.id).unwrap();
                assert!(load_state.is_failed());
                assert_eq!(*error.path.source(), AssetSourceId::Name("unstable".into()));
                match &error.error {
                    AssetLoadError::AssetReaderError(read_error) => match read_error {
                        AssetReaderError::Io(_) => {
                            tracker.failures += 1;
                            if tracker.failures <= 2 {
                                // Retry in 10 ticks
                                tracker.queued_retries.push((
                                    error.path.clone(),
                                    error.id,
                                    now + 10,
                                ));
                            } else {
                                panic!(
                                    "Unexpected failure #{} (expected only 2)",
                                    tracker.failures
                                );
                            }
                        }
                        _ => panic!("Unexpected error type {}", read_error),
                    },
                    _ => panic!("Unexpected error type {}", error.error),
                }
            }
        }

        let a_path = "text/a.cool.ron";
        let a_ron = r#"
(
    text: "a",
    dependencies: [],
    embedded_dependencies: [],
    sub_texts: [],
)"#;

        let dir = Dir::default();
        dir.insert_asset_text(Path::new(a_path), a_ron);
        let unstable_reader = UnstableMemoryAssetReader::new(dir, 2);

        let mut app = App::new();
        app.register_asset_source(
            AssetSourceId::Default,
            AssetSourceBuilder::new(move || {
                // This reader is unused, but we set it here so we don't accidentally use the
                // filesystem.
                Box::new(MemoryAssetReader {
                    root: Dir::default(),
                })
            }),
        )
        .register_asset_source(
            "unstable",
            AssetSourceBuilder::new(move || Box::new(unstable_reader.clone())),
        )
        .add_plugins((
            TaskPoolPlugin::default(),
            AssetPlugin {
                watch_for_changes_override: Some(false),
                use_asset_processor_override: Some(false),
                ..Default::default()
            },
        ))
        .init_asset::<CoolText>()
        .register_asset_loader(CoolTextLoader)
        .init_resource::<ErrorTracker>()
        .add_systems(
            Update,
            (asset_event_handler, asset_load_error_event_handler).chain(),
        );

        let asset_server = app.world().resource::<AssetServer>().clone();
        let a_path = format!("unstable://{a_path}");
        let a_handle: Handle<CoolText> = asset_server.load(a_path);
        let a_id = a_handle.id();

        run_app_until(&mut app, |world| {
            let tracker = world.resource::<ErrorTracker>();
            match tracker.finished_asset {
                Some(asset_id) => {
                    assert_eq!(asset_id, a_id);
                    let assets = world.resource::<Assets<CoolText>>();
                    let result = assets.get(asset_id).unwrap();
                    assert_eq!(result.text, "a");
                    Some(())
                }
                None => None,
            }
        });
    }

    #[test]
    fn ignore_system_ambiguities_on_assets() {
        let mut app = create_app().0;
        app.init_asset::<CoolText>();

        fn uses_assets(_asset: ResMut<Assets<CoolText>>) {}
        app.add_systems(Update, (uses_assets, uses_assets));
        app.edit_schedule(Update, |s| {
            s.set_build_settings(ScheduleBuildSettings {
                ambiguity_detection: LogLevel::Error,
                ..Default::default()
            });
        });

        // running schedule does not error on ambiguity between the 2 uses_assets systems
        app.world_mut().run_schedule(Update);
    }

    // This test is not checking a requirement, but documenting a current limitation. We simply are
    // not capable of loading subassets when doing nested immediate loads.
    #[test]
    fn error_on_nested_immediate_load_of_subasset() {
        let (mut app, dir) = create_app();
        dir.insert_asset_text(
            Path::new("a.cool.ron"),
            r#"(
    text: "b",
    dependencies: [],
    embedded_dependencies: [],
    sub_texts: ["A"],
)"#,
        );
        dir.insert_asset_text(Path::new("empty.txt"), "");

        app.init_asset::<CoolText>()
            .init_asset::<SubText>()
            .register_asset_loader(CoolTextLoader);

        #[derive(TypePath)]
        struct NestedLoadOfSubassetLoader;

        impl AssetLoader for NestedLoadOfSubassetLoader {
            type Asset = TestAsset;
            type Error = crate::loader::LoadDirectError;
            type Settings = ();

            async fn load(
                &self,
                _: &mut dyn Reader,
                _: &Self::Settings,
                load_context: &mut LoadContext<'_>,
            ) -> Result<Self::Asset, Self::Error> {
                // We expect this load to fail.
                load_context
                    .load_builder()
                    .load_value::<SubText>("a.cool.ron#A")
                    .await?;
                Ok(TestAsset)
            }

            fn extensions(&self) -> &[&str] {
                &["txt"]
            }
        }

        app.init_asset::<TestAsset>()
            .register_asset_loader(NestedLoadOfSubassetLoader);

        let asset_server = app.world().resource::<AssetServer>().clone();
        let handle = asset_server.load::<TestAsset>("empty.txt");

        run_app_until(&mut app, |_world| match asset_server.load_state(&handle) {
            LoadState::Loading => None,
            LoadState::Failed(err) => {
                let error_message = format!("{err}");
                assert!(error_message.contains("Requested to load an asset path (a.cool.ron#A) with a subasset, but this is unsupported"), "what? \"{error_message}\"");
                Some(())
            }
            state => panic!("Unexpected asset state: {state:?}"),
        });
    }

    // validate the Asset derive macro for various asset types
    #[derive(Asset, TypePath)]
    pub struct TestAsset;

    // Test that `VisitAssetDependencies` can be derived without deriving
    // `Asset`, and that the type can be used as a `#[dependency]` within an
    // asset.
    #[derive(VisitAssetDependencies)]
    pub struct TestNonAssetType(#[dependency] Handle<TestAsset>);

    #[derive(Asset, TypePath)]
    #[expect(
        dead_code,
        reason = "This exists to ensure that `#[derive(Asset)]` works on enums. The inner variants are known not to be used."
    )]
    pub enum EnumTestAsset {
        Unnamed(#[dependency] Handle<TestAsset>),
        Named {
            #[dependency]
            handle: Handle<TestAsset>,
            #[dependency]
            vec_handles: Vec<Handle<TestAsset>>,
            #[dependency]
            embedded: TestAsset,
            #[dependency]
            set_handles: HashSet<Handle<TestAsset>>,
            #[dependency]
            untyped_set_handles: HashSet<UntypedHandle>,
            #[dependency]
            map_handles: HashMap<String, Handle<TestAsset>>,
            #[dependency]
            untyped_map_handles: HashMap<String, UntypedHandle>,
            #[dependency]
            non_asset_type: TestNonAssetType,
        },
        StructStyle(#[dependency] TestAsset),
        Empty,
    }

    #[expect(
        dead_code,
        reason = "This struct is used as a compilation test to test the derive macros, and as such is intentionally never constructed."
    )]
    #[derive(Asset, TypePath)]
    pub struct StructTestAsset {
        #[dependency]
        handle: Handle<TestAsset>,
        #[dependency]
        embedded: TestAsset,
        #[dependency]
        array_handles: [Handle<TestAsset>; 5],
        #[dependency]
        untyped_array_handles: [UntypedHandle; 5],
        #[dependency]
        set_handles: HashSet<Handle<TestAsset>>,
        #[dependency]
        untyped_set_handles: HashSet<UntypedHandle>,
        #[dependency]
        map_handles: HashMap<String, Handle<TestAsset>>,
        #[dependency]
        untyped_map_handles: HashMap<String, UntypedHandle>,
        #[dependency]
        non_asset_type: TestNonAssetType,
    }

    #[expect(
        dead_code,
        reason = "This struct is used as a compilation test to test the derive macros, and as such is intentionally never constructed."
    )]
    #[derive(Asset, TypePath)]
    pub struct TupleTestAsset(#[dependency] Handle<TestAsset>);

    fn unapproved_path_setup(mode: UnapprovedPathMode) -> App {
        let dir = Dir::default();
        let a_path = "../a.cool.ron";
        let a_ron = r#"
(
    text: "a",
    dependencies: [],
    embedded_dependencies: [],
    sub_texts: [],
)"#;

        dir.insert_asset_text(Path::new(a_path), a_ron);

        let mut app = App::new();
        let memory_reader = MemoryAssetReader { root: dir };
        app.register_asset_source(
            AssetSourceId::Default,
            AssetSourceBuilder::new(move || Box::new(memory_reader.clone())),
        )
        .add_plugins((
            TaskPoolPlugin::default(),
            AssetPlugin {
                unapproved_path_mode: mode,
                watch_for_changes_override: Some(false),
                use_asset_processor_override: Some(false),
                ..Default::default()
            },
        ));
        app.init_asset::<CoolText>()
            .register_asset_loader(CoolTextLoader);

        app
    }

    #[test]
    fn unapproved_path_forbid_does_not_load_even_with_override() {
        let app = unapproved_path_setup(UnapprovedPathMode::Forbid);

        let asset_server = app.world().resource::<AssetServer>().clone();
        assert_eq!(
            asset_server
                .load_builder()
                .override_unapproved()
                .load::<CoolText>("../a.cool.ron"),
            Handle::default()
        );
    }

    #[test]
    fn unapproved_path_deny_does_not_load() {
        let app = unapproved_path_setup(UnapprovedPathMode::Deny);

        let asset_server = app.world().resource::<AssetServer>().clone();
        assert_eq!(
            asset_server.load::<CoolText>("../a.cool.ron"),
            Handle::default()
        );
    }

    #[test]
    fn unapproved_path_deny_loads_with_override() {
        let mut app = unapproved_path_setup(UnapprovedPathMode::Deny);

        let asset_server = app.world().resource::<AssetServer>().clone();
        let handle = asset_server
            .load_builder()
            .override_unapproved()
            .load::<CoolText>("../a.cool.ron");
        assert_ne!(handle, Handle::default());

        // Make sure this asset actually loads.
        run_app_until(&mut app, |_| asset_server.is_loaded(&handle).then_some(()));
    }

    #[test]
    fn unapproved_path_allow_loads() {
        let mut app = unapproved_path_setup(UnapprovedPathMode::Allow);

        let asset_server = app.world().resource::<AssetServer>().clone();
        let handle = asset_server.load::<CoolText>("../a.cool.ron");
        assert_ne!(handle, Handle::default());

        // Make sure this asset actually loads.
        run_app_until(&mut app, |_| asset_server.is_loaded(&handle).then_some(()));
    }

    #[test]
    fn insert_dropped_handle_returns_error() {
        let mut app = create_app().0;

        app.init_asset::<TestAsset>();

        let handle = app.world().resource::<Assets<TestAsset>>().reserve_handle();
        // We still have the asset ID, but we've dropped the handle so the asset is no longer live.
        let asset_id = handle.id();
        drop(handle);

        // Allow `Assets` to detect the dropped handle.
        app.world_mut()
            .run_system_cached(Assets::<TestAsset>::track_assets)
            .unwrap();

        let AssetId::Index { index, .. } = asset_id else {
            unreachable!("Reserving a handle always produces an index");
        };

        // Try to insert an asset into the dropped handle's spot. This should not panic.
        assert_eq!(
            app.world_mut()
                .resource_mut::<Assets<TestAsset>>()
                .insert(asset_id, TestAsset),
            Err(InvalidGenerationError::Removed { index })
        );
    }

    /// A loader that notifies a sender when the loader has started, and blocks on a receiver to
    /// simulate a long asset loader.
    // Note: we can't just use the GatedReader, since currently we hold the handle until after
    // we've selected the reader. The GatedReader blocks this process, so we need to wait until
    // we gate in the loader instead.
    #[derive(TypePath)]
    struct GatedLoader {
        in_loader_sender: Sender<()>,
        gate_receiver: Receiver<()>,
    }

    impl AssetLoader for GatedLoader {
        type Asset = TestAsset;
        type Error = std::io::Error;
        type Settings = ();

        async fn load(
            &self,
            _reader: &mut dyn Reader,
            _settings: &Self::Settings,
            _load_context: &mut LoadContext<'_>,
        ) -> Result<Self::Asset, Self::Error> {
            self.in_loader_sender.send_blocking(()).unwrap();
            let _ = self.gate_receiver.recv().await;
            Ok(TestAsset)
        }

        fn extensions(&self) -> &[&str] {
            &["ron"]
        }
    }

    #[test]
    fn dropping_handle_while_loading_cancels_load() {
        let (mut app, dir) = create_app();

        let (in_loader_sender, in_loader_receiver) = async_channel::bounded(1);
        let (gate_sender, gate_receiver) = async_channel::bounded(1);

        app.init_asset::<TestAsset>()
            .register_asset_loader(GatedLoader {
                in_loader_sender,
                gate_receiver,
            });

        let path = Path::new("abc.ron");
        dir.insert_asset_text(path, "blah");

        let asset_server = app.world().resource::<AssetServer>().clone();

        // Start loading the asset. This load will get blocked by the gate.
        let handle = asset_server.load::<TestAsset>(path);
        assert!(asset_server.get_load_state(&handle).unwrap().is_loading());
        app.update();

        // Make sure we are inside the loader before continuing.
        in_loader_receiver.recv_blocking().unwrap();

        let asset_id = handle.id();
        // Dropping the handle and doing another update should result in the load being cancelled.
        drop(handle);
        app.update();
        assert!(asset_server.get_load_state(asset_id).is_none());

        // Unblock the loader and then update a few times, showing that the asset never loads.
        gate_sender.send_blocking(()).unwrap();
        for _ in 0..10 {
            app.update();
            for message in app
                .world()
                .resource::<Messages<AssetEvent<TestAsset>>>()
                .iter_current_update_messages()
            {
                match message {
                    AssetEvent::Unused { .. } => {}
                    message => panic!("No asset events are allowed: {message:?}"),
                }
            }
        }
    }

    #[test]
    fn dropping_subasset_handle_while_loading_cancels_load() {
        let (mut app, dir) = create_app();

        let (in_loader_sender, in_loader_receiver) = async_channel::bounded(1);
        let (gate_sender, gate_receiver) = async_channel::bounded(1);

        app.init_asset::<TestAsset>()
            .register_asset_loader(GatedLoader {
                in_loader_sender,
                gate_receiver,
            });

        let path = Path::new("abc.ron");
        dir.insert_asset_text(path, "blah");

        let asset_server = app.world().resource::<AssetServer>().clone();

        // Start loading the subasset. This load will get blocked by the gate.
        // Note: it doesn't matter that the subasset doesn't actually end up existing, since the
        // asset system doesn't know that until after the load completes, which we cancel anyway.
        let handle = asset_server.load::<TestAsset>("abc.ron#sub");
        assert!(asset_server.get_load_state(&handle).unwrap().is_loading());
        app.update();

        // Make sure we are inside the loader before continuing.
        in_loader_receiver.recv_blocking().unwrap();

        let asset_id = handle.id();
        // Dropping the handle and doing another update should result in the load being cancelled.
        drop(handle);
        app.update();
        assert!(asset_server.get_load_state(asset_id).is_none());

        // Unblock the loader and then update a few times, showing that the asset never loads.
        gate_sender.send_blocking(()).unwrap();
        for _ in 0..10 {
            app.update();
            for message in app
                .world()
                .resource::<Messages<AssetEvent<TestAsset>>>()
                .iter_current_update_messages()
            {
                match message {
                    AssetEvent::Unused { .. } => {}
                    message => panic!("No asset events are allowed: {message:?}"),
                }
            }
        }
    }

    // Creates a basic app with the default asset source engineered to get back the asset event
    // sender.
    fn create_app_with_source_event_sender() -> (App, Dir, Sender<AssetSourceEvent>) {
        let mut app = App::new();
        let dir = Dir::default();
        let memory_reader = MemoryAssetReader { root: dir.clone() };

        // Create a channel to pass the source event sender back to us.
        let (sender_sender, sender_receiver) = crossbeam_channel::bounded(1);

        struct FakeWatcher;
        impl AssetWatcher for FakeWatcher {}

        app.register_asset_source(
            AssetSourceId::Default,
            AssetSourceBuilder::new(move || Box::new(memory_reader.clone())).with_watcher(
                move |sender| {
                    sender_sender.send(sender).unwrap();
                    Some(Box::new(FakeWatcher))
                },
            ),
        )
        .add_plugins((
            TaskPoolPlugin::default(),
            AssetPlugin {
                watch_for_changes_override: Some(true),
                use_asset_processor_override: Some(false),
                ..Default::default()
            },
        ));

        let sender = sender_receiver.try_recv().unwrap();

        (app, dir, sender)
    }

    fn collect_asset_events<A: Asset>(world: &mut World) -> Vec<AssetEvent<A>> {
        world
            .resource_mut::<Messages<AssetEvent<A>>>()
            .drain()
            .collect()
    }

    fn collect_asset_load_failed_events<A: Asset>(
        world: &mut World,
    ) -> Vec<AssetLoadFailedEvent<A>> {
        world
            .resource_mut::<Messages<AssetLoadFailedEvent<A>>>()
            .drain()
            .collect()
    }

    #[test]
    fn reloads_asset_after_source_event() {
        let (mut app, dir, source_events) = create_app_with_source_event_sender();
        let asset_server = app.world().resource::<AssetServer>().clone();

        dir.insert_asset_text(
            Path::new("abc.cool.ron"),
            r#"(
    text: "a",
    dependencies: [],
    embedded_dependencies: [],
    sub_texts: [],
)"#,
        );

        app.init_asset::<CoolText>()
            .init_asset::<SubText>()
            .register_asset_loader(CoolTextLoader);

        let handle: Handle<CoolText> = asset_server.load("abc.cool.ron");
        run_app_until(&mut app, |world| {
            let messages = collect_asset_events(world);
            if messages.is_empty() {
                return None;
            }
            assert_eq!(
                messages,
                [
                    AssetEvent::LoadedWithDependencies { id: handle.id() },
                    AssetEvent::Added { id: handle.id() },
                ]
            );
            Some(())
        });

        // Sending an asset event should result in the asset being reloaded - resulting in a
        // "Modified" message.
        source_events
            .send_blocking(AssetSourceEvent::ModifiedAsset(PathBuf::from(
                "abc.cool.ron",
            )))
            .unwrap();

        run_app_until(&mut app, |world| {
            let messages = collect_asset_events(world);
            if messages.is_empty() {
                return None;
            }
            assert_eq!(
                messages,
                [
                    AssetEvent::LoadedWithDependencies { id: handle.id() },
                    AssetEvent::Modified { id: handle.id() }
                ]
            );
            Some(())
        });
    }

    #[test]
    fn added_asset_reloads_previously_missing_asset() {
        let (mut app, dir, source_events) = create_app_with_source_event_sender();
        let asset_server = app.world().resource::<AssetServer>().clone();

        app.init_asset::<CoolText>()
            .init_asset::<SubText>()
            .register_asset_loader(CoolTextLoader);

        let handle: Handle<CoolText> = asset_server.load("abc.cool.ron");
        run_app_until(&mut app, |world| {
            let failed_ids = collect_asset_load_failed_events(world)
                .drain(..)
                .map(|event| event.id)
                .collect::<Vec<_>>();
            if failed_ids.is_empty() {
                return None;
            }
            assert_eq!(failed_ids, [handle.id()]);
            Some(())
        });

        // The asset has already been considered as failed to load. Now we add the asset data, and
        // send an AddedAsset event.
        dir.insert_asset_text(
            Path::new("abc.cool.ron"),
            r#"(
    text: "a",
    dependencies: [],
    embedded_dependencies: [],
    sub_texts: [],
)"#,
        );
        source_events
            .send_blocking(AssetSourceEvent::AddedAsset(PathBuf::from("abc.cool.ron")))
            .unwrap();

        run_app_until(&mut app, |world| {
            let messages = collect_asset_events(world);
            if messages.is_empty() {
                return None;
            }
            assert_eq!(
                messages,
                [
                    AssetEvent::LoadedWithDependencies { id: handle.id() },
                    AssetEvent::Added { id: handle.id() }
                ]
            );
            Some(())
        });
    }

    #[test]
    fn same_asset_different_settings() {
        // Test loading the same asset twice with different settings. This should
        // produce two distinct assets.

        // First, implement an asset that's a single u8, whose value is copied from
        // the loader settings.

        #[derive(Asset, TypePath)]
        struct U8Asset(u8);

        #[derive(Serialize, Deserialize, Default)]
        struct U8LoaderSettings(u8);

        #[derive(TypePath)]
        struct U8Loader;

        impl AssetLoader for U8Loader {
            type Asset = U8Asset;
            type Settings = U8LoaderSettings;
            type Error = crate::loader::LoadDirectError;

            async fn load(
                &self,
                _: &mut dyn Reader,
                settings: &Self::Settings,
                _: &mut LoadContext<'_>,
            ) -> Result<Self::Asset, Self::Error> {
                Ok(U8Asset(settings.0))
            }

            fn extensions(&self) -> &[&str] {
                &["u8"]
            }
        }

        // Create a test asset and setup the app.

        let (mut app, dir) = create_app();
        dir.insert_asset(Path::new("test.u8"), &[]);

        app.init_asset::<U8Asset>().register_asset_loader(U8Loader);

        let asset_server = app.world().resource::<AssetServer>();

        // Load the test asset twice but with different settings.

        fn load(asset_server: &AssetServer, path: &'static str, value: u8) -> Handle<U8Asset> {
            asset_server
                .load_builder()
                .with_settings(move |s: &mut U8LoaderSettings| s.0 = value)
                .load::<U8Asset>(path)
        }

        let handle_1 = load(asset_server, "test.u8", 1);
        let handle_2 = load(asset_server, "test.u8", 2);

        // Handles should be different.

        // These handles should be different, but due to
        // https://github.com/bevyengine/bevy/pull/21564, they are not. Once 21564 is fixed, we
        // should replace these expects.
        //
        // assert_ne!(handle_1, handle_2);
        assert_eq!(handle_1, handle_2);

        run_app_until(&mut app, |world| {
            let (Some(asset_1), Some(asset_2)) = (
                world.resource::<Assets<U8Asset>>().get(&handle_1),
                world.resource::<Assets<U8Asset>>().get(&handle_2),
            ) else {
                return None;
            };

            // Values should match the settings.

            // These values should be different, but due to
            // https://github.com/bevyengine/bevy/pull/21564, they are not. Once 21564 is fixed, we
            // should replace these expects.
            //
            // assert_eq!(asset_1.0, 1);
            // assert_eq!(asset_2.0, 2);
            assert_eq!(asset_1.0, asset_2.0);

            Some(())
        });
    }

    #[test]
    fn loading_two_subassets_does_not_start_two_loads() {
        let (mut app, dir) = create_app();
        dir.insert_asset(Path::new("test.txt"), &[]);

        #[derive(TypePath)]
        struct TwoSubassetLoader;

        impl AssetLoader for TwoSubassetLoader {
            type Asset = TestAsset;
            type Settings = ();
            type Error = std::io::Error;

            async fn load(
                &self,
                _reader: &mut dyn Reader,
                _settings: &Self::Settings,
                load_context: &mut LoadContext<'_>,
            ) -> Result<Self::Asset, Self::Error> {
                load_context.add_labeled_asset("A", TestAsset);
                load_context.add_labeled_asset("B", TestAsset);
                Ok(TestAsset)
            }

            fn extensions(&self) -> &[&str] {
                &["txt"]
            }
        }

        app.init_asset::<TestAsset>()
            .register_asset_loader(TwoSubassetLoader);

        let asset_server = app.world().resource::<AssetServer>().clone();
        let _subasset_1: Handle<TestAsset> = asset_server.load("test.txt#A");
        let _subasset_2: Handle<TestAsset> = asset_server.load("test.txt#B");

        app.update();

        // Due to https://github.com/bevyengine/bevy/issues/12756, this expectation fails. Once
        // #12756 is fixed, we should swap these asserts.
        //
        // assert_eq!(get_started_load_count(app.world()), 1);
        assert_eq!(get_started_load_count(app.world()), 2);
    }

    /// A loader that immediately returns a [`TestAsset`].
    #[derive(TypePath)]
    struct TrivialLoader;

    impl AssetLoader for TrivialLoader {
        type Asset = TestAsset;
        type Settings = ();
        type Error = std::io::Error;

        async fn load(
            &self,
            _reader: &mut dyn Reader,
            _settings: &Self::Settings,
            _load_context: &mut LoadContext<'_>,
        ) -> Result<Self::Asset, Self::Error> {
            Ok(TestAsset)
        }

        fn extensions(&self) -> &[&str] {
            &["txt"]
        }
    }

    #[test]
    fn get_strong_handle_prevents_reload_when_asset_still_alive() {
        let (mut app, dir) = create_app();
        dir.insert_asset(Path::new("test.txt"), &[]);

        app.init_asset::<TestAsset>()
            .register_asset_loader(TrivialLoader);

        let asset_server = app.world().resource::<AssetServer>().clone();
        let original_handle: Handle<TestAsset> = asset_server.load("test.txt");

        // Wait for the asset to load.
        run_app_until(&mut app, |world| {
            world
                .resource::<Assets<TestAsset>>()
                .get(&original_handle)
                .map(|_| ())
        });

        assert_eq!(get_started_load_count(app.world()), 1);

        // Get a new strong handle from the original handle's ID.
        let new_handle = app
            .world_mut()
            .resource_mut::<Assets<TestAsset>>()
            .get_strong_handle(original_handle.id())
            .unwrap();

        // Drop the original handle. This should still leave the asset alive.
        drop(original_handle);

        app.update();
        assert!(app
            .world()
            .resource::<Assets<TestAsset>>()
            .get(&new_handle)
            .is_some());

        let _other_handle: Handle<TestAsset> = asset_server.load("test.txt");
        app.update();
        // The asset server should **not** have started a new load, since the asset is still alive.

        // Due to https://github.com/bevyengine/bevy/issues/20651, we do get a second load. Once
        // #20651 is fixed, we should swap these asserts.
        //
        // assert_eq!(get_started_load_count(app.world()), 1);
        assert_eq!(get_started_load_count(app.world()), 2);
    }

    #[test]
    fn immediate_nested_asset_loads_dependency() {
        let (mut app, dir) = create_app();

        /// This asset holds a handle to its dependency.
        #[derive(Asset, TypePath)]
        struct DeferredNested(Handle<TestAsset>);

        #[derive(TypePath)]
        struct DeferredNestedLoader;

        impl AssetLoader for DeferredNestedLoader {
            type Asset = DeferredNested;
            type Settings = ();
            type Error = std::io::Error;

            async fn load(
                &self,
                reader: &mut dyn Reader,
                _: &Self::Settings,
                load_context: &mut LoadContext<'_>,
            ) -> Result<Self::Asset, Self::Error> {
                let mut nested_path = String::new();
                reader.read_to_string(&mut nested_path).await?;
                Ok(DeferredNested(load_context.load(nested_path)))
            }

            fn extensions(&self) -> &[&str] {
                &["defer"]
            }
        }

        /// This asset holds a handle a dependency of one of its dependencies.
        #[derive(Asset, TypePath)]
        struct ImmediateNested(Handle<TestAsset>);

        #[derive(TypePath)]
        struct ImmediateNestedLoader;

        impl AssetLoader for ImmediateNestedLoader {
            type Asset = ImmediateNested;
            type Settings = ();
            type Error = std::io::Error;

            async fn load(
                &self,
                reader: &mut dyn Reader,
                _: &Self::Settings,
                load_context: &mut LoadContext<'_>,
            ) -> Result<Self::Asset, Self::Error> {
                let mut nested_path = String::new();
                reader.read_to_string(&mut nested_path).await?;
                let deferred_nested: LoadedAsset<DeferredNested> = load_context
                    .load_builder()
                    .load_value(nested_path)
                    .await
                    .unwrap();
                Ok(ImmediateNested(deferred_nested.get().0.clone()))
            }

            fn extensions(&self) -> &[&str] {
                &["immediate"]
            }
        }

        app.init_asset::<TestAsset>()
            .init_asset::<DeferredNested>()
            .init_asset::<ImmediateNested>()
            .register_asset_loader(TrivialLoader)
            .register_asset_loader(DeferredNestedLoader)
            .register_asset_loader(ImmediateNestedLoader);

        dir.insert_asset_text(Path::new("a.immediate"), "b.defer");
        dir.insert_asset_text(Path::new("b.defer"), "c.txt");
        dir.insert_asset_text(Path::new("c.txt"), "hiya");

        let server = app.world().resource::<AssetServer>().clone();
        let immediate_handle: Handle<ImmediateNested> = server.load("a.immediate");

        run_app_until(&mut app, |world| {
            let immediate_assets = world.resource::<Assets<ImmediateNested>>();
            let immediate = immediate_assets.get(&immediate_handle)?;

            let test_asset_handle = immediate.0.clone();
            world
                .resource::<Assets<TestAsset>>()
                .get(&test_asset_handle)?;

            // The immediate asset is loaded, and the asset it got from its immediate load is also
            // loaded.
            Some(())
        });
    }

    pub(crate) fn read_asset_as_string(dir: &Dir, path: &Path) -> String {
        let bytes = dir.get_asset(path).unwrap();
        str::from_utf8(bytes.value()).unwrap().to_string()
    }

    pub(crate) fn read_meta_as_string(dir: &Dir, path: &Path) -> String {
        let bytes = dir.get_metadata(path).unwrap();
        str::from_utf8(bytes.value()).unwrap().to_string()
    }

    #[test]
    fn writes_default_meta_for_loader() {
        let (mut app, source) = create_app();

        app.register_asset_loader(CoolTextLoader);

        const ASSET_PATH: &str = "abc.cool.ron";
        source.insert_asset_text(Path::new(ASSET_PATH), "blah");

        let asset_server = app.world().resource::<AssetServer>().clone();
        block_on(asset_server.write_default_loader_meta_file_for_path(ASSET_PATH)).unwrap();

        assert_eq!(
            read_meta_as_string(&source, Path::new(ASSET_PATH)),
            r#"(
    meta_format_version: "1.0",
    asset: Load(
        loader: "bevy_asset::tests::CoolTextLoader",
        settings: (),
    ),
)"#
        );
    }

    #[test]
    fn write_default_meta_does_not_overwrite() {
        let (mut app, source) = create_app();

        app.register_asset_loader(CoolTextLoader);

        const ASSET_PATH: &str = "abc.cool.ron";
        source.insert_asset_text(Path::new(ASSET_PATH), "blah");
        const META_TEXT: &str = "hey i'm walkin here!";
        source.insert_meta_text(Path::new(ASSET_PATH), META_TEXT);

        let asset_server = app.world().resource::<AssetServer>().clone();
        assert!(matches!(
            block_on(asset_server.write_default_loader_meta_file_for_path(ASSET_PATH)),
            Err(WriteDefaultMetaError::MetaAlreadyExists)
        ));

        assert_eq!(
            read_meta_as_string(&source, Path::new(ASSET_PATH)),
            META_TEXT
        );
    }

    #[test]
    fn asset_dependency_is_tracked_when_not_loaded() {
        let (mut app, dir) = create_app();

        #[derive(Asset, TypePath)]
        struct AssetWithDep {
            #[dependency]
            dep: Handle<TestAsset>,
        }

        #[derive(TypePath)]
        struct AssetWithDepLoader;

        impl AssetLoader for AssetWithDepLoader {
            type Asset = TestAsset;
            type Settings = ();
            type Error = std::io::Error;

            async fn load(
                &self,
                _reader: &mut dyn Reader,
                _settings: &Self::Settings,
                load_context: &mut LoadContext<'_>,
            ) -> Result<Self::Asset, Self::Error> {
                // Load the asset in the root context, but then put the handle in the subasset. So
                // the subasset's (internal) load context never loaded `dep`.
                let dep = load_context.load::<TestAsset>("abc.ron");
                load_context.add_labeled_asset("subasset", AssetWithDep { dep });
                Ok(TestAsset)
            }

            fn extensions(&self) -> &[&str] {
                &["with_deps"]
            }
        }

        // Write some data so the loaders have something to load (even though they don't use the
        // data).
        dir.insert_asset_text(Path::new("abc.ron"), "");
        dir.insert_asset_text(Path::new("blah.with_deps"), "");

        let (in_loader_sender, in_loader_receiver) = async_channel::bounded(1);
        let (gate_sender, gate_receiver) = async_channel::bounded(1);
        app.init_asset::<TestAsset>()
            .init_asset::<AssetWithDep>()
            .register_asset_loader(GatedLoader {
                in_loader_sender,
                gate_receiver,
            })
            .register_asset_loader(AssetWithDepLoader);

        let asset_server = app.world().resource::<AssetServer>().clone();
        let subasset_handle: Handle<AssetWithDep> = asset_server.load("blah.with_deps#subasset");

        run_app_until(&mut app, |_| {
            asset_server.is_loaded(&subasset_handle).then_some(())
        });
        // Even though the subasset is loaded, and its load context never loaded its dependency, it
        // still depends on its dependency, so that is tracked correctly here.
        assert!(!asset_server.is_loaded_with_dependencies(&subasset_handle));

        let dep_handle: Handle<TestAsset> = app
            .world()
            .resource::<Assets<AssetWithDep>>()
            .get(&subasset_handle)
            .unwrap()
            .dep
            .clone();

        // Pass the gate in the dependency loader.
        in_loader_receiver.recv_blocking().unwrap();
        gate_sender.send_blocking(()).unwrap();

        run_app_until(&mut app, |_| {
            asset_server.is_loaded(&dep_handle).then_some(())
        });
        // Now that the dependency is loaded, the subasset is counted as loaded with dependencies!
        assert!(asset_server.is_loaded_with_dependencies(&subasset_handle));
    }

    // A simplified version of `LoadState` for easier comparison.
    #[derive(Debug, PartialEq, Eq)]
    enum TestLoadState {
        NotLoaded,
        Loading,
        Loaded,
        Failed(TestAssetLoadError),
    }

    // A simplified subset of `AssetLoadError` for easier comparison.
    #[derive(Debug, PartialEq, Eq)]
    enum TestAssetLoadError {
        RequestedHandleTypeMismatch {
            requested: TypeId,
            actual_asset_name: &'static str,
        },
        MissingAssetLoader,
        AssetReaderErrorNotFound,
        AssetLoaderError,
        MissingLabel,
    }

    impl From<LoadState> for TestLoadState {
        fn from(value: LoadState) -> Self {
            match value {
                LoadState::NotLoaded => Self::NotLoaded,
                LoadState::Loading => Self::Loading,
                LoadState::Loaded => Self::Loaded,
                LoadState::Failed(err) => Self::Failed((&*err).into()),
            }
        }
    }

    impl From<&AssetLoadError> for TestAssetLoadError {
        fn from(value: &AssetLoadError) -> TestAssetLoadError {
            match value {
                AssetLoadError::RequestedHandleTypeMismatch {
                    requested,
                    actual_asset_name,
                    ..
                } => Self::RequestedHandleTypeMismatch {
                    requested: *requested,
                    actual_asset_name,
                },
                AssetLoadError::MissingAssetLoader { .. } => Self::MissingAssetLoader,
                AssetLoadError::AssetReaderError(AssetReaderError::NotFound(_)) => {
                    Self::AssetReaderErrorNotFound
                }
                AssetLoadError::AssetLoaderError { .. } => Self::AssetLoaderError,
                AssetLoadError::MissingLabel { .. } => Self::MissingLabel,
                _ => panic!("TestAssetLoadError's From<&AssetLoaderError> is missing a case for AssetLoadError \"{:?}\".", value),
            }
        }
    }

    // An asset type that doesn't have a registered loader.
    #[derive(Asset, TypePath)]
    struct LoaderlessAsset;

    // Load the given path and test that `AssetServer::get_load_state` returns
    // the given state.
    fn test_load_state<A: Asset>(
        label: &'static str,
        path: &'static str,
        expected_load_state: TestLoadState,
    ) {
        let (mut app, dir) = create_app();

        app.init_asset::<CoolText>()
            .init_asset::<SubText>()
            .init_asset::<LoaderlessAsset>()
            .register_asset_loader(CoolTextLoader);

        dir.insert_asset_text(
            Path::new("test.cool.ron"),
            r#"
(
    text: "test",
    dependencies: [],
    embedded_dependencies: [],
    sub_texts: ["subasset"],
)"#,
        );

        dir.insert_asset_text(Path::new("malformed.cool.ron"), "MALFORMED");

        let asset_server = app.world().resource::<AssetServer>().clone();
        let handle = asset_server.load::<A>(path);
        let mut load_state = TestLoadState::NotLoaded;

        for _ in 0..LARGE_ITERATION_COUNT {
            app.update();
            load_state = asset_server.get_load_state(&handle).unwrap().into();
            if load_state == expected_load_state {
                break;
            }
        }

        assert!(
            load_state == expected_load_state,
            "For test \"{}\", expected {:?} but got {:?}.",
            label,
            expected_load_state,
            load_state,
        );
    }

    // Tests that `AssetServer::get_load_state` returns the correct state after
    // various loads, some of which trigger errors.
    #[test]
    fn load_failure() {
        test_load_state::<CoolText>("root asset exists", "test.cool.ron", TestLoadState::Loaded);

        test_load_state::<SubText>(
            "sub-asset exists",
            "test.cool.ron#subasset",
            TestLoadState::Loaded,
        );

        test_load_state::<CoolText>(
            "root asset does not exist",
            "does_not_exist.cool.ron",
            TestLoadState::Failed(TestAssetLoadError::AssetReaderErrorNotFound),
        );

        test_load_state::<CoolText>(
            "sub-asset of root asset that does not exist",
            "does_not_exist.cool.ron#subasset",
            TestLoadState::Failed(TestAssetLoadError::AssetReaderErrorNotFound),
        );

        test_load_state::<SubText>(
            "sub-asset does not exist",
            "test.cool.ron#does_not_exist",
            TestLoadState::Failed(TestAssetLoadError::MissingLabel),
        );

        test_load_state::<CoolText>(
            "sub-asset is not requested type",
            "test.cool.ron#subasset",
            TestLoadState::Failed(TestAssetLoadError::RequestedHandleTypeMismatch {
                requested: TypeId::of::<CoolText>(),
                actual_asset_name: "bevy_asset::tests::SubText",
            }),
        );

        test_load_state::<CoolText>(
            "malformed root asset",
            "malformed.cool.ron",
            TestLoadState::Failed(TestAssetLoadError::AssetLoaderError),
        );

        test_load_state::<CoolText>(
            "sub-asset of malformed root asset",
            "malformed.cool.ron#subasset",
            TestLoadState::Failed(TestAssetLoadError::AssetLoaderError),
        );

        test_load_state::<LoaderlessAsset>(
            "root asset has no loader",
            "loaderless",
            TestLoadState::Failed(TestAssetLoadError::MissingAssetLoader),
        );
    }

    #[test]
    fn load_empty_path_returns_default() {
        let mut app = create_app().0;

        // Not necessary but better to make things more realistic to ensure we hit the right error
        // case.
        app.init_asset::<TestAsset>()
            .register_asset_loader(TrivialLoader);

        const TYPE_ID: TypeId = TypeId::of::<TestAsset>();

        fn boring_settings(_: &mut ()) {}

        let asset_server = app.world().resource::<AssetServer>().clone();

        for path in ["", "no_path://#WithALabel"] {
            // TODO: We have way too many "load" variants. We **need** to simplify this.
            assert_eq!(asset_server.load(path), Handle::<TestAsset>::default());
            assert_eq!(
                asset_server.load_builder().with_guard(()).load(path),
                Handle::<TestAsset>::default()
            );
            assert_eq!(
                asset_server
                    .load_builder()
                    .with_guard(())
                    .override_unapproved()
                    .load(path),
                Handle::<TestAsset>::default()
            );
            assert_eq!(
                asset_server
                    .load_builder()
                    .with_guard(())
                    .with_settings(boring_settings)
                    .load(path),
                Handle::<TestAsset>::default()
            );
            assert_eq!(
                asset_server.load_builder().load_erased(TYPE_ID, path),
                Handle::<TestAsset>::default()
            );
            assert_eq!(
                asset_server.load_builder().override_unapproved().load(path),
                Handle::<TestAsset>::default()
            );
            assert_eq!(
                asset_server.load_builder().load_untyped(path),
                Handle::default()
            );
            assert!(matches!(
                block_on(asset_server.load_builder().load_untyped_async(path)),
                Err(AssetLoadError::EmptyPath(reported_path)) if AssetPath::from(path) == reported_path
            ));
            assert_eq!(
                asset_server
                    .load_builder()
                    .with_settings(|_: &mut ()| {})
                    .load(path),
                Handle::<TestAsset>::default()
            );
            assert_eq!(
                asset_server
                    .load_builder()
                    .with_settings(|_: &mut ()| {})
                    .override_unapproved()
                    .load(path),
                Handle::<TestAsset>::default()
            );
        }
    }

    #[test]
    fn resource_are_dependencies_loaded() {
        let (mut app, dir) = create_app();
        dir.insert_asset_text(Path::new("abc.txt"), "");
        dir.insert_asset_text(Path::new("def.txt"), "");
        dir.insert_asset_text(Path::new("ghi.txt"), "");

        app.init_asset::<TestAsset>()
            .register_asset_loader(TrivialLoader);

        let asset_server = app.world().resource::<AssetServer>().clone();

        #[derive(Resource, VisitAssetDependencies)]
        struct MyAssetHolder {
            #[dependency]
            abc: Handle<TestAsset>,
            #[dependency]
            def: Handle<TestAsset>,
            #[dependency]
            ghi: Handle<TestAsset>,
        }

        app.insert_resource(MyAssetHolder {
            abc: asset_server.load("abc.txt"),
            def: asset_server.load("def.txt"),
            ghi: asset_server.load("ghi.txt"),
        });

        assert!(!asset_server.are_dependencies_loaded(app.world().resource::<MyAssetHolder>()));
        assert!(
            !asset_server.are_direct_dependencies_loaded(app.world().resource::<MyAssetHolder>())
        );

        run_app_until(&mut app, |world| {
            asset_server
                .are_dependencies_loaded(world.resource::<MyAssetHolder>())
                .then_some(())
        });
        assert!(
            asset_server.are_direct_dependencies_loaded(app.world().resource::<MyAssetHolder>())
        );
    }

    #[test]
    fn hot_reload_folder() {
        let (mut app, dir, event_sender) = create_app_with_source_event_sender();

        app.init_asset::<CoolText>()
            .init_asset::<SubText>()
            .register_asset_loader(CoolTextLoader);

        let abc_path = Path::new("dir/abc.cool.ron");
        let def_path = Path::new("dir/def.cool.ron");
        dir.insert_asset_text(abc_path, &serialize_as_cool_text("abc"));
        dir.insert_asset_text(def_path, &serialize_as_cool_text("def"));

        let asset_server = app.world().resource::<AssetServer>().clone();

        let folder_handle = asset_server.load_folder("dir");
        run_app_until(&mut app, |_| {
            asset_server
                .is_loaded_with_dependencies(&folder_handle)
                .then_some(())
        });

        let folder = app
            .world()
            .resource::<Assets<LoadedFolder>>()
            .get(&folder_handle)
            .unwrap();
        assert_eq!(folder.handles.len(), 2);
        let mut handles = folder
            .handles
            .iter()
            .cloned()
            .map(UntypedHandle::typed::<CoolText>)
            .collect::<Vec<_>>();
        // Sort the handles so we know abc is first and def is second.
        handles.sort_by_key(|handle| handle.path().unwrap().path().to_path_buf());

        let abc_handle = handles[0].clone();
        let def_handle = handles[1].clone();

        let cool_texts = app.world().resource::<Assets<CoolText>>();
        assert_eq!(cool_texts.get(&abc_handle).unwrap().text, "abc");
        assert_eq!(cool_texts.get(&def_handle).unwrap().text, "def");

        // Before doing any hot reloading stuff, clear out any AssetEvent messages.
        app.world_mut()
            .resource_mut::<Messages<AssetEvent<LoadedFolder>>>()
            .clear();

        // Add a new asset to the folder, and send an event to trigger hot-reloading.
        let ghi_path = Path::new("dir/ghi.cool.ron");
        dir.insert_asset_text(ghi_path, &serialize_as_cool_text("ghi"));
        event_sender
            .send_blocking(AssetSourceEvent::AddedAsset(ghi_path.to_path_buf()))
            .unwrap();

        run_app_until(&mut app, |world| {
            for event in world
                .resource_mut::<Messages<AssetEvent<LoadedFolder>>>()
                .drain()
            {
                if let AssetEvent::LoadedWithDependencies { id } = event
                    && id == folder_handle.id()
                {
                    return Some(());
                }
            }
            None
        });

        let folder = app
            .world()
            .resource::<Assets<LoadedFolder>>()
            .get(&folder_handle)
            .unwrap();
        assert_eq!(folder.handles.len(), 3);
        let mut handles = folder
            .handles
            .iter()
            .cloned()
            .map(UntypedHandle::typed::<CoolText>)
            .collect::<Vec<_>>();
        // Sort the handles so we know the order is abc, def, and ghi.
        handles.sort_by_key(|handle| handle.path().unwrap().path().to_path_buf());

        let new_abc_handle = handles[0].clone();
        let new_def_handle = handles[1].clone();
        let new_ghi_handle = handles[2].clone();

        assert_eq!(new_abc_handle, abc_handle);
        assert_eq!(new_def_handle, def_handle);

        let cool_texts = app.world().resource::<Assets<CoolText>>();
        assert_eq!(cool_texts.get(&new_abc_handle).unwrap().text, "abc");
        assert_eq!(cool_texts.get(&new_def_handle).unwrap().text, "def");
        assert_eq!(cool_texts.get(&new_ghi_handle).unwrap().text, "ghi");
    }
}