bevy_mesh 0.19.1

Provides mesh types 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
use bevy_transform::components::Transform;
pub use wgpu_types::PrimitiveTopology;

use super::{
    skinning::{SkinnedMeshBounds, SkinnedMeshBoundsError},
    triangle_area_normal, triangle_normal, FourIterators, Indices, MeshAttributeData,
    MeshTrianglesError, MeshVertexAttribute, MeshVertexAttributeId, MeshVertexBufferLayout,
    MeshVertexBufferLayoutRef, MeshVertexBufferLayouts, MeshWindingInvertError,
    VertexAttributeValues, VertexBufferLayout,
};
#[cfg(feature = "morph")]
use crate::morph::MorphAttributes;
#[cfg(feature = "serialize")]
use crate::SerializedMeshAttributeData;
use alloc::collections::BTreeMap;
use bevy_asset::{Asset, RenderAssetUsages};
use bevy_math::{bounding::Aabb3d, primitives::Triangle3d, *};
use bevy_platform::collections::{hash_map, HashMap};
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
use bytemuck::cast_slice;
use core::hash::{Hash, Hasher};
use core::ptr;
#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tracing::warn;
use wgpu_types::{VertexAttribute, VertexFormat, VertexStepMode, WriteOnly};

pub const INDEX_BUFFER_ASSET_INDEX: u64 = 0;
pub const VERTEX_ATTRIBUTE_BUFFER_ID: u64 = 10;

/// Error from accessing mesh vertex attributes or indices
#[derive(Error, Debug, Clone)]
pub enum MeshAccessError {
    #[error("The mesh vertex/index data has been extracted to the RenderWorld (via `Mesh::asset_usage`)")]
    ExtractedToRenderWorld,
    #[error("The requested mesh data wasn't found in this mesh")]
    NotFound,
}

const MESH_EXTRACTED_ERROR: &str = "Mesh has been extracted to RenderWorld. To access vertex attributes, the mesh `asset_usage` must include `MAIN_WORLD`";

// storage for extractable data with access methods which return errors if the
// contents have already been extracted
#[derive(Debug, Clone, PartialEq, Reflect, Default)]
enum MeshExtractableData<T> {
    Data(T),
    #[default]
    NoData,
    ExtractedToRenderWorld,
}

impl<T> MeshExtractableData<T> {
    // get a reference to internal data. returns error if data has been extracted, or if no
    // data exists
    fn as_ref(&self) -> Result<&T, MeshAccessError> {
        match self {
            MeshExtractableData::Data(data) => Ok(data),
            MeshExtractableData::NoData => Err(MeshAccessError::NotFound),
            MeshExtractableData::ExtractedToRenderWorld => {
                Err(MeshAccessError::ExtractedToRenderWorld)
            }
        }
    }

    // get an optional reference to internal data. returns error if data has been extracted
    fn as_ref_option(&self) -> Result<Option<&T>, MeshAccessError> {
        match self {
            MeshExtractableData::Data(data) => Ok(Some(data)),
            MeshExtractableData::NoData => Ok(None),
            MeshExtractableData::ExtractedToRenderWorld => {
                Err(MeshAccessError::ExtractedToRenderWorld)
            }
        }
    }

    // get a mutable reference to internal data. returns error if data has been extracted,
    // or if no data exists
    fn as_mut(&mut self) -> Result<&mut T, MeshAccessError> {
        match self {
            MeshExtractableData::Data(data) => Ok(data),
            MeshExtractableData::NoData => Err(MeshAccessError::NotFound),
            MeshExtractableData::ExtractedToRenderWorld => {
                Err(MeshAccessError::ExtractedToRenderWorld)
            }
        }
    }

    // get an optional mutable reference to internal data. returns error if data has been extracted
    fn as_mut_option(&mut self) -> Result<Option<&mut T>, MeshAccessError> {
        match self {
            MeshExtractableData::Data(data) => Ok(Some(data)),
            MeshExtractableData::NoData => Ok(None),
            MeshExtractableData::ExtractedToRenderWorld => {
                Err(MeshAccessError::ExtractedToRenderWorld)
            }
        }
    }

    // extract data and replace self with `ExtractedToRenderWorld`. returns error if
    // data has been extracted
    fn extract(&mut self) -> Result<MeshExtractableData<T>, MeshAccessError> {
        match core::mem::replace(self, MeshExtractableData::ExtractedToRenderWorld) {
            MeshExtractableData::ExtractedToRenderWorld => {
                Err(MeshAccessError::ExtractedToRenderWorld)
            }
            not_extracted => Ok(not_extracted),
        }
    }

    // replace internal data. returns the existing data, or an error if data has been extracted
    fn replace(
        &mut self,
        data: impl Into<MeshExtractableData<T>>,
    ) -> Result<Option<T>, MeshAccessError> {
        match core::mem::replace(self, data.into()) {
            MeshExtractableData::ExtractedToRenderWorld => {
                *self = MeshExtractableData::ExtractedToRenderWorld;
                Err(MeshAccessError::ExtractedToRenderWorld)
            }
            MeshExtractableData::Data(t) => Ok(Some(t)),
            MeshExtractableData::NoData => Ok(None),
        }
    }
}

impl<T> From<Option<T>> for MeshExtractableData<T> {
    fn from(value: Option<T>) -> Self {
        match value {
            Some(data) => MeshExtractableData::Data(data),
            None => MeshExtractableData::NoData,
        }
    }
}

/// A 3D object made out of vertices representing triangles, lines, or points,
/// with "attribute" values for each vertex.
///
/// Meshes can be automatically generated by a bevy `AssetLoader` (generally by loading a `Gltf` file),
/// or by converting a [primitive](bevy_math::primitives) using [`into`](Into).
/// It is also possible to create one manually. They can be edited after creation.
///
/// Meshes can be rendered with a [`Mesh2d`](crate::Mesh2d) and `MeshMaterial2d`
/// or [`Mesh3d`](crate::Mesh3d) and `MeshMaterial3d` for 2D and 3D respectively.
///
/// A [`Mesh`] in Bevy is equivalent to a "primitive" in the glTF format, for a
/// glTF Mesh representation, see `GltfMesh`.
///
/// ## Manual creation
///
/// The following function will construct a flat mesh, to be rendered with a
/// `StandardMaterial` or `ColorMaterial`:
///
/// ```
/// # use bevy_mesh::{Mesh, Indices, PrimitiveTopology};
/// # use bevy_asset::RenderAssetUsages;
/// fn create_simple_parallelogram() -> Mesh {
///     // Create a new mesh using a triangle list topology, where each set of 3 vertices composes a triangle.
///     Mesh::new(PrimitiveTopology::TriangleList, RenderAssetUsages::default())
///         // Add 4 vertices, each with its own position attribute (coordinate in
///         // 3D space), for each of the corners of the parallelogram.
///         .with_inserted_attribute(
///             Mesh::ATTRIBUTE_POSITION,
///             vec![[0.0, 0.0, 0.0], [1.0, 2.0, 0.0], [2.0, 2.0, 0.0], [1.0, 0.0, 0.0]]
///         )
///         // Assign a UV coordinate to each vertex.
///         .with_inserted_attribute(
///             Mesh::ATTRIBUTE_UV_0,
///             vec![[0.0, 1.0], [0.5, 0.0], [1.0, 0.0], [0.5, 1.0]]
///         )
///         // Assign normals (everything points outwards)
///         .with_inserted_attribute(
///             Mesh::ATTRIBUTE_NORMAL,
///             vec![[0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]]
///         )
///         // After defining all the vertices and their attributes, build each triangle using the
///         // indices of the vertices that make it up in a counter-clockwise order.
///         .with_inserted_indices(Indices::U32(vec![
///             // First triangle
///             0, 3, 1,
///             // Second triangle
///             1, 3, 2
///         ]))
/// }
/// ```
///
/// You can see how it looks like [here](https://github.com/bevyengine/bevy/blob/main/assets/docs/Mesh.png),
/// used in a [`Mesh3d`](crate::Mesh3d) with a square bevy logo texture, with added axis, points,
/// lines and text for clarity.
///
/// ## Other examples
///
/// For further visualization, explanation, and examples, see the built-in Bevy examples,
/// and the [implementation of the built-in shapes](https://github.com/bevyengine/bevy/tree/main/crates/bevy_mesh/src/primitives).
/// In particular, [generate_custom_mesh](https://github.com/bevyengine/bevy/blob/main/examples/3d/generate_custom_mesh.rs)
/// teaches you to access and modify the attributes of a [`Mesh`] after creating it.
///
/// ## Common points of confusion
///
/// - UV maps in Bevy start at the top-left, see [`ATTRIBUTE_UV_0`](Mesh::ATTRIBUTE_UV_0),
///   other APIs can have other conventions, `OpenGL` starts at bottom-left.
/// - It is possible and sometimes useful for multiple vertices to have the same
///   [position attribute](Mesh::ATTRIBUTE_POSITION) value,
///   it's a common technique in 3D modeling for complex UV mapping or other calculations.
/// - Bevy performs frustum culling based on the `Aabb` of meshes, which is calculated
///   and added automatically for new meshes only. If a mesh is modified, the entity's `Aabb`
///   needs to be updated manually or deleted so that it is re-calculated.
///
/// ## Use with `StandardMaterial`
///
/// To render correctly with `StandardMaterial`, a mesh needs to have properly defined:
/// - [`UVs`](Mesh::ATTRIBUTE_UV_0): Bevy needs to know how to map a texture onto the mesh
///   (also true for `ColorMaterial`).
/// - [`Normals`](Mesh::ATTRIBUTE_NORMAL): Bevy needs to know how light interacts with your mesh.
///   [0.0, 0.0, 1.0] is very common for simple flat meshes on the XY plane,
///   because simple meshes are smooth and they don't require complex light calculations.
/// - Vertex winding order: by default, `StandardMaterial.cull_mode` is `Some(Face::Back)`,
///   which means that Bevy would *only* render the "front" of each triangle, which
///   is the side of the triangle from where the vertices appear in a *counter-clockwise* order.
///
/// ## Remote Inspection
///
/// To transmit a [`Mesh`] between two running Bevy apps, e.g. through BRP, use [`SerializedMesh`].
/// This type is only meant for short-term transmission between same versions and should not be stored anywhere.
#[derive(Asset, Debug, Clone, Reflect, PartialEq)]
#[reflect(Clone)]
pub struct Mesh {
    #[reflect(ignore, clone)]
    primitive_topology: PrimitiveTopology,
    /// `std::collections::BTreeMap` with all defined vertex attributes (Positions, Normals, ...)
    /// for this mesh. Attribute ids to attribute values.
    /// Uses a [`BTreeMap`] because, unlike `HashMap`, it has a defined iteration order,
    /// which allows easy stable `VertexBuffers` (i.e. same buffer order)
    #[reflect(ignore, clone)]
    attributes: MeshExtractableData<BTreeMap<MeshVertexAttributeId, MeshAttributeData>>,
    indices: MeshExtractableData<Indices>,
    #[cfg(feature = "morph")]
    morph_targets: MeshExtractableData<Vec<MorphAttributes>>,
    #[cfg(feature = "morph")]
    morph_target_names: MeshExtractableData<Vec<String>>,
    pub asset_usage: RenderAssetUsages,
    /// Whether or not to build a BLAS for use with `bevy_solari` raytracing.
    ///
    /// Note that this is _not_ whether the mesh is _compatible_ with `bevy_solari` raytracing.
    /// This field just controls whether or not a BLAS gets built for this mesh, assuming that
    /// the mesh is compatible.
    ///
    /// The use case for this field is using lower-resolution proxy meshes for raytracing (to save on BLAS memory usage),
    /// while using higher-resolution meshes for raster. You can set this field to true for the lower-resolution proxy mesh,
    /// and to false for the high-resolution raster mesh.
    ///
    /// Alternatively, you can use the same mesh for both raster and raytracing, with this field set to true.
    ///
    /// Does nothing if not used with `bevy_solari`, or if the mesh is not compatible
    /// with `bevy_solari` (see `bevy_solari`'s docs).
    pub enable_raytracing: bool,
    /// Precomputed min and max extents of the mesh position data. Used mainly for constructing `Aabb`s for frustum culling.
    /// This data will be set if/when a mesh is extracted to the GPU
    pub final_aabb: Option<Aabb3d>,
    skinned_mesh_bounds: Option<SkinnedMeshBounds>,
}

impl Mesh {
    /// Where the vertex is located in space. Use in conjunction with [`Mesh::insert_attribute`]
    /// or [`Mesh::with_inserted_attribute`].
    ///
    /// The format of this attribute is [`VertexFormat::Float32x3`].
    pub const ATTRIBUTE_POSITION: MeshVertexAttribute =
        MeshVertexAttribute::new("Vertex_Position", 0, VertexFormat::Float32x3);

    /// The direction the vertex normal is facing in.
    /// Use in conjunction with [`Mesh::insert_attribute`] or [`Mesh::with_inserted_attribute`].
    ///
    /// The format of this attribute is [`VertexFormat::Float32x3`].
    pub const ATTRIBUTE_NORMAL: MeshVertexAttribute =
        MeshVertexAttribute::new("Vertex_Normal", 1, VertexFormat::Float32x3);

    /// Texture coordinates for the vertex. Use in conjunction with [`Mesh::insert_attribute`]
    /// or [`Mesh::with_inserted_attribute`].
    ///
    /// Generally `[0.,0.]` is mapped to the top left of the texture, and `[1.,1.]` to the bottom-right.
    ///
    /// By default values outside will be clamped per pixel not for the vertex,
    /// "stretching" the borders of the texture.
    /// This behavior can be useful in some cases, usually when the borders have only
    /// one color, for example a logo, and you want to "extend" those borders.
    ///
    /// For different mapping outside of `0..=1` range,
    /// see [`ImageAddressMode`](https://docs.rs/bevy_image/latest/bevy_image/enum.ImageAddressMode.html).
    ///
    /// The format of this attribute is [`VertexFormat::Float32x2`].
    pub const ATTRIBUTE_UV_0: MeshVertexAttribute =
        MeshVertexAttribute::new("Vertex_Uv", 2, VertexFormat::Float32x2);

    /// Alternate texture coordinates for the vertex. Use in conjunction with
    /// [`Mesh::insert_attribute`] or [`Mesh::with_inserted_attribute`].
    ///
    /// Typically, these are used for lightmaps, textures that provide
    /// precomputed illumination.
    ///
    /// The format of this attribute is [`VertexFormat::Float32x2`].
    pub const ATTRIBUTE_UV_1: MeshVertexAttribute =
        MeshVertexAttribute::new("Vertex_Uv_1", 3, VertexFormat::Float32x2);

    /// The direction of the vertex tangent. Used for normal mapping.
    /// Usually generated with [`generate_tangents`](Mesh::generate_tangents) or
    /// [`with_generated_tangents`](Mesh::with_generated_tangents).
    ///
    /// The format of this attribute is [`VertexFormat::Float32x4`].
    pub const ATTRIBUTE_TANGENT: MeshVertexAttribute =
        MeshVertexAttribute::new("Vertex_Tangent", 4, VertexFormat::Float32x4);

    /// Per vertex coloring. Use in conjunction with [`Mesh::insert_attribute`]
    /// or [`Mesh::with_inserted_attribute`].
    ///
    /// The format of this attribute is [`VertexFormat::Float32x4`].
    pub const ATTRIBUTE_COLOR: MeshVertexAttribute =
        MeshVertexAttribute::new("Vertex_Color", 5, VertexFormat::Float32x4);

    /// Per vertex joint transform matrix weight. Use in conjunction with [`Mesh::insert_attribute`]
    /// or [`Mesh::with_inserted_attribute`].
    ///
    /// The format of this attribute is [`VertexFormat::Float32x4`].
    pub const ATTRIBUTE_JOINT_WEIGHT: MeshVertexAttribute =
        MeshVertexAttribute::new("Vertex_JointWeight", 6, VertexFormat::Float32x4);

    /// Per vertex joint transform matrix index. Use in conjunction with [`Mesh::insert_attribute`]
    /// or [`Mesh::with_inserted_attribute`].
    ///
    /// The format of this attribute is [`VertexFormat::Uint16x4`].
    pub const ATTRIBUTE_JOINT_INDEX: MeshVertexAttribute =
        MeshVertexAttribute::new("Vertex_JointIndex", 7, VertexFormat::Uint16x4);

    /// The first index that can be used for custom vertex attributes.
    /// Only the attributes with an index below this are used by Bevy.
    pub const FIRST_AVAILABLE_CUSTOM_ATTRIBUTE: u64 = 8;

    /// Construct a new mesh. You need to provide a [`PrimitiveTopology`] so that the
    /// renderer knows how to treat the vertex data. Most of the time this will be
    /// [`PrimitiveTopology::TriangleList`].
    pub fn new(primitive_topology: PrimitiveTopology, asset_usage: RenderAssetUsages) -> Self {
        Mesh {
            primitive_topology,
            attributes: MeshExtractableData::Data(Default::default()),
            indices: MeshExtractableData::NoData,
            #[cfg(feature = "morph")]
            morph_targets: MeshExtractableData::NoData,
            #[cfg(feature = "morph")]
            morph_target_names: MeshExtractableData::NoData,
            asset_usage,
            enable_raytracing: true,
            final_aabb: None,
            skinned_mesh_bounds: None,
        }
    }

    /// Returns the topology of the mesh.
    pub fn primitive_topology(&self) -> PrimitiveTopology {
        self.primitive_topology
    }

    /// Sets the data for a vertex attribute (position, normal, etc.). The name will
    /// often be one of the associated constants such as [`Mesh::ATTRIBUTE_POSITION`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    ///
    /// # Panics
    /// Panics when the format of the values does not match the attribute's format.
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_insert_attribute`]
    #[inline]
    pub fn insert_attribute(
        &mut self,
        attribute: MeshVertexAttribute,
        values: impl Into<VertexAttributeValues>,
    ) {
        self.try_insert_attribute(attribute, values)
            .expect(MESH_EXTRACTED_ERROR);
    }

    /// Sets the data for a vertex attribute (position, normal, etc.). The name will
    /// often be one of the associated constants such as [`Mesh::ATTRIBUTE_POSITION`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    ///
    /// # Panics
    /// Panics when the format of the values does not match the attribute's format.
    #[inline]
    pub fn try_insert_attribute(
        &mut self,
        attribute: MeshVertexAttribute,
        values: impl Into<VertexAttributeValues>,
    ) -> Result<(), MeshAccessError> {
        let values = values.into();
        let values_format = VertexFormat::from(&values);
        if values_format != attribute.format {
            panic!(
                "Failed to insert attribute. Invalid attribute format for {}. Given format is {values_format:?} but expected {:?}",
                attribute.name, attribute.format
            );
        }

        self.attributes
            .as_mut()?
            .insert(attribute.id, MeshAttributeData { attribute, values });
        Ok(())
    }

    /// Consumes the mesh and returns a mesh with data set for a vertex attribute (position, normal, etc.).
    /// The name will often be one of the associated constants such as [`Mesh::ATTRIBUTE_POSITION`].
    ///
    /// (Alternatively, you can use [`Mesh::insert_attribute`] to mutate an existing mesh in-place)
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    ///
    /// # Panics
    /// Panics when the format of the values does not match the attribute's format.
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_with_inserted_attribute`]
    #[must_use]
    #[inline]
    pub fn with_inserted_attribute(
        mut self,
        attribute: MeshVertexAttribute,
        values: impl Into<VertexAttributeValues>,
    ) -> Self {
        self.insert_attribute(attribute, values);
        self
    }

    /// Consumes the mesh and returns a mesh with data set for a vertex attribute (position, normal, etc.).
    /// The name will often be one of the associated constants such as [`Mesh::ATTRIBUTE_POSITION`].
    ///
    /// (Alternatively, you can use [`Mesh::insert_attribute`] to mutate an existing mesh in-place)
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    #[inline]
    pub fn try_with_inserted_attribute(
        mut self,
        attribute: MeshVertexAttribute,
        values: impl Into<VertexAttributeValues>,
    ) -> Result<Self, MeshAccessError> {
        self.try_insert_attribute(attribute, values)?;
        Ok(self)
    }

    /// Removes the data for a vertex attribute
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_remove_attribute`]
    pub fn remove_attribute(
        &mut self,
        attribute: impl Into<MeshVertexAttributeId>,
    ) -> Option<VertexAttributeValues> {
        self.attributes
            .as_mut()
            .expect(MESH_EXTRACTED_ERROR)
            .remove(&attribute.into())
            .map(|data| data.values)
    }

    /// Removes the data for a vertex attribute
    /// Returns an error if the mesh data has been extracted to `RenderWorld`or
    /// if the attribute does not exist.
    pub fn try_remove_attribute(
        &mut self,
        attribute: impl Into<MeshVertexAttributeId>,
    ) -> Result<VertexAttributeValues, MeshAccessError> {
        Ok(self
            .attributes
            .as_mut()?
            .remove(&attribute.into())
            .ok_or(MeshAccessError::NotFound)?
            .values)
    }

    /// Consumes the mesh and returns a mesh without the data for a vertex attribute
    ///
    /// (Alternatively, you can use [`Mesh::remove_attribute`] to mutate an existing mesh in-place)
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_with_removed_attribute`]
    #[must_use]
    pub fn with_removed_attribute(mut self, attribute: impl Into<MeshVertexAttributeId>) -> Self {
        self.remove_attribute(attribute);
        self
    }

    /// Consumes the mesh and returns a mesh without the data for a vertex attribute
    ///
    /// (Alternatively, you can use [`Mesh::remove_attribute`] to mutate an existing mesh in-place)
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`or
    /// if the attribute does not exist.
    pub fn try_with_removed_attribute(
        mut self,
        attribute: impl Into<MeshVertexAttributeId>,
    ) -> Result<Self, MeshAccessError> {
        self.try_remove_attribute(attribute)?;
        Ok(self)
    }

    /// Returns a bool indicating if the attribute is present in this mesh's vertex data.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_contains_attribute`]
    #[inline]
    pub fn contains_attribute(&self, id: impl Into<MeshVertexAttributeId>) -> bool {
        self.attributes
            .as_ref()
            .expect(MESH_EXTRACTED_ERROR)
            .contains_key(&id.into())
    }

    /// Returns a bool indicating if the attribute is present in this mesh's vertex data.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    #[inline]
    pub fn try_contains_attribute(
        &self,
        id: impl Into<MeshVertexAttributeId>,
    ) -> Result<bool, MeshAccessError> {
        Ok(self.attributes.as_ref()?.contains_key(&id.into()))
    }

    /// Retrieves the data currently set to the vertex attribute with the specified [`MeshVertexAttributeId`].
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_attribute`] or [`Mesh::try_attribute_option`]
    #[inline]
    pub fn attribute(
        &self,
        id: impl Into<MeshVertexAttributeId>,
    ) -> Option<&VertexAttributeValues> {
        self.try_attribute_option(id).expect(MESH_EXTRACTED_ERROR)
    }

    /// Retrieves the data currently set to the vertex attribute with the specified [`MeshVertexAttributeId`].
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`or
    /// if the attribute does not exist.
    #[inline]
    pub fn try_attribute(
        &self,
        id: impl Into<MeshVertexAttributeId>,
    ) -> Result<&VertexAttributeValues, MeshAccessError> {
        self.try_attribute_option(id)?
            .ok_or(MeshAccessError::NotFound)
    }

    /// Retrieves the data currently set to the vertex attribute with the specified [`MeshVertexAttributeId`].
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    #[inline]
    pub fn try_attribute_option(
        &self,
        id: impl Into<MeshVertexAttributeId>,
    ) -> Result<Option<&VertexAttributeValues>, MeshAccessError> {
        Ok(self
            .attributes
            .as_ref()?
            .get(&id.into())
            .map(|data| &data.values))
    }

    /// Retrieves the full data currently set to the vertex attribute with the specified [`MeshVertexAttributeId`].
    #[inline]
    pub(crate) fn try_attribute_data(
        &self,
        id: impl Into<MeshVertexAttributeId>,
    ) -> Result<Option<&MeshAttributeData>, MeshAccessError> {
        Ok(self.attributes.as_ref()?.get(&id.into()))
    }

    /// Retrieves the data currently set to the vertex attribute with the specified `name` mutably.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_attribute_mut`]
    #[inline]
    pub fn attribute_mut(
        &mut self,
        id: impl Into<MeshVertexAttributeId>,
    ) -> Option<&mut VertexAttributeValues> {
        self.try_attribute_mut_option(id)
            .expect(MESH_EXTRACTED_ERROR)
    }

    /// Retrieves the data currently set to the vertex attribute with the specified `name` mutably.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`or
    /// if the attribute does not exist.
    #[inline]
    pub fn try_attribute_mut(
        &mut self,
        id: impl Into<MeshVertexAttributeId>,
    ) -> Result<&mut VertexAttributeValues, MeshAccessError> {
        self.try_attribute_mut_option(id)?
            .ok_or(MeshAccessError::NotFound)
    }

    /// Retrieves the data currently set to the vertex attribute with the specified `name` mutably.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    #[inline]
    pub fn try_attribute_mut_option(
        &mut self,
        id: impl Into<MeshVertexAttributeId>,
    ) -> Result<Option<&mut VertexAttributeValues>, MeshAccessError> {
        Ok(self
            .attributes
            .as_mut()?
            .get_mut(&id.into())
            .map(|data| &mut data.values))
    }

    /// Returns an iterator that yields references to the data of each vertex attribute.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_attributes`]
    pub fn attributes(
        &self,
    ) -> impl Iterator<Item = (&MeshVertexAttribute, &VertexAttributeValues)> {
        self.try_attributes().expect(MESH_EXTRACTED_ERROR)
    }

    /// Returns an iterator that yields references to the data of each vertex attribute.
    /// Returns an error if data has been extracted to `RenderWorld`
    pub fn try_attributes(
        &self,
    ) -> Result<impl Iterator<Item = (&MeshVertexAttribute, &VertexAttributeValues)>, MeshAccessError>
    {
        Ok(self
            .attributes
            .as_ref()?
            .values()
            .map(|data| (&data.attribute, &data.values)))
    }

    /// Returns an iterator that yields mutable references to the data of each vertex attribute.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_attributes_mut`]
    pub fn attributes_mut(
        &mut self,
    ) -> impl Iterator<Item = (&MeshVertexAttribute, &mut VertexAttributeValues)> {
        self.try_attributes_mut().expect(MESH_EXTRACTED_ERROR)
    }

    /// Returns an iterator that yields mutable references to the data of each vertex attribute.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    pub fn try_attributes_mut(
        &mut self,
    ) -> Result<
        impl Iterator<Item = (&MeshVertexAttribute, &mut VertexAttributeValues)>,
        MeshAccessError,
    > {
        Ok(self
            .attributes
            .as_mut()?
            .values_mut()
            .map(|data| (&data.attribute, &mut data.values)))
    }

    /// Sets the vertex indices of the mesh. They describe how triangles are constructed out of the
    /// vertex attributes and are therefore only useful for the [`PrimitiveTopology`] variants
    /// that use triangles.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_insert_indices`]
    #[inline]
    pub fn insert_indices(&mut self, indices: Indices) {
        self.indices
            .replace(Some(indices))
            .expect(MESH_EXTRACTED_ERROR);
    }

    /// Sets the vertex indices of the mesh. They describe how triangles are constructed out of the
    /// vertex attributes and are therefore only useful for the [`PrimitiveTopology`] variants
    /// that use triangles.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    #[inline]
    pub fn try_insert_indices(&mut self, indices: Indices) -> Result<(), MeshAccessError> {
        self.indices.replace(Some(indices))?;
        Ok(())
    }

    /// Consumes the mesh and returns a mesh with the given vertex indices. They describe how triangles
    /// are constructed out of the vertex attributes and are therefore only useful for the
    /// [`PrimitiveTopology`] variants that use triangles.
    ///
    /// (Alternatively, you can use [`Mesh::insert_indices`] to mutate an existing mesh in-place)
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_with_inserted_indices`]
    #[must_use]
    #[inline]
    pub fn with_inserted_indices(mut self, indices: Indices) -> Self {
        self.insert_indices(indices);
        self
    }

    /// Consumes the mesh and returns a mesh with the given vertex indices. They describe how triangles
    /// are constructed out of the vertex attributes and are therefore only useful for the
    /// [`PrimitiveTopology`] variants that use triangles.
    ///
    /// (Alternatively, you can use [`Mesh::try_insert_indices`] to mutate an existing mesh in-place)
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    #[inline]
    pub fn try_with_inserted_indices(mut self, indices: Indices) -> Result<Self, MeshAccessError> {
        self.try_insert_indices(indices)?;
        Ok(self)
    }

    /// Retrieves the vertex `indices` of the mesh, returns None if not found.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_indices`]
    #[inline]
    pub fn indices(&self) -> Option<&Indices> {
        self.indices.as_ref_option().expect(MESH_EXTRACTED_ERROR)
    }

    /// Retrieves the vertex `indices` of the mesh.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`or
    /// if the attribute does not exist.
    #[inline]
    pub fn try_indices(&self) -> Result<&Indices, MeshAccessError> {
        self.indices.as_ref()
    }

    /// Retrieves the vertex `indices` of the mesh, returns None if not found.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    #[inline]
    pub fn try_indices_option(&self) -> Result<Option<&Indices>, MeshAccessError> {
        self.indices.as_ref_option()
    }

    /// Retrieves the vertex `indices` of the mesh mutably.
    #[inline]
    pub fn indices_mut(&mut self) -> Option<&mut Indices> {
        self.try_indices_mut_option().expect(MESH_EXTRACTED_ERROR)
    }

    /// Retrieves the vertex `indices` of the mesh mutably.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    #[inline]
    pub fn try_indices_mut(&mut self) -> Result<&mut Indices, MeshAccessError> {
        self.indices.as_mut()
    }

    /// Retrieves the vertex `indices` of the mesh mutably.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    #[inline]
    pub fn try_indices_mut_option(&mut self) -> Result<Option<&mut Indices>, MeshAccessError> {
        self.indices.as_mut_option()
    }

    /// Removes the vertex `indices` from the mesh and returns them.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_remove_indices`]
    #[inline]
    pub fn remove_indices(&mut self) -> Option<Indices> {
        self.try_remove_indices().expect(MESH_EXTRACTED_ERROR)
    }

    /// Removes the vertex `indices` from the mesh and returns them.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    #[inline]
    pub fn try_remove_indices(&mut self) -> Result<Option<Indices>, MeshAccessError> {
        self.indices.replace(None)
    }

    /// Consumes the mesh and returns a mesh without the vertex `indices` of the mesh.
    ///
    /// (Alternatively, you can use [`Mesh::remove_indices`] to mutate an existing mesh in-place)
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_with_removed_indices`]
    #[must_use]
    pub fn with_removed_indices(mut self) -> Self {
        self.remove_indices();
        self
    }

    /// Consumes the mesh and returns a mesh without the vertex `indices` of the mesh.
    ///
    /// (Alternatively, you can use [`Mesh::try_remove_indices`] to mutate an existing mesh in-place)
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    pub fn try_with_removed_indices(mut self) -> Result<Self, MeshAccessError> {
        self.try_remove_indices()?;
        Ok(self)
    }

    /// Returns the size of a vertex in bytes.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`.
    pub fn get_vertex_size(&self) -> u64 {
        self.attributes
            .as_ref()
            .expect(MESH_EXTRACTED_ERROR)
            .values()
            .map(|data| data.attribute.format.size())
            .sum()
    }

    /// Returns the size required for the vertex buffer in bytes.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`.
    pub fn get_vertex_buffer_size(&self) -> usize {
        let vertex_size = self.get_vertex_size() as usize;
        let vertex_count = self.count_vertices();
        vertex_count * vertex_size
    }

    /// Computes and returns the index data of the mesh as bytes.
    /// This is used to transform the index data into a GPU friendly format.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`.
    pub fn get_index_buffer_bytes(&self) -> Option<&[u8]> {
        let mesh_indices = self.indices.as_ref_option().expect(MESH_EXTRACTED_ERROR);

        mesh_indices.as_ref().map(|indices| match &indices {
            Indices::U16(indices) => cast_slice(&indices[..]),
            Indices::U32(indices) => cast_slice(&indices[..]),
        })
    }

    /// If any morph displacements are present, returns them as a
    /// [`MorphAttributes`] array.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to the render
    /// world.
    #[cfg(feature = "morph")]
    pub fn get_morph_targets(&self) -> Option<&[MorphAttributes]> {
        self.morph_targets
            .as_ref_option()
            .expect(MESH_EXTRACTED_ERROR)
            .map(|morph_attributes| &morph_attributes[..])
    }

    /// Get this `Mesh`'s [`MeshVertexBufferLayout`], used in `SpecializedMeshPipeline`.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`.
    pub fn get_mesh_vertex_buffer_layout(
        &self,
        mesh_vertex_buffer_layouts: &mut MeshVertexBufferLayouts,
    ) -> MeshVertexBufferLayoutRef {
        let mesh_attributes = self.attributes.as_ref().expect(MESH_EXTRACTED_ERROR);

        let mut attributes = Vec::with_capacity(mesh_attributes.len());
        let mut attribute_ids = Vec::with_capacity(mesh_attributes.len());
        let mut accumulated_offset = 0;
        for (index, data) in mesh_attributes.values().enumerate() {
            attribute_ids.push(data.attribute.id);
            attributes.push(VertexAttribute {
                offset: accumulated_offset,
                format: data.attribute.format,
                shader_location: index as u32,
            });
            accumulated_offset += data.attribute.format.size();
        }

        let layout = MeshVertexBufferLayout {
            layout: VertexBufferLayout {
                array_stride: accumulated_offset,
                step_mode: VertexStepMode::Vertex,
                attributes,
            },
            attribute_ids,
        };
        mesh_vertex_buffer_layouts.insert(layout)
    }

    /// Counts all vertices of the mesh.
    ///
    /// If the attributes have different vertex counts, the smallest is returned.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`.
    pub fn count_vertices(&self) -> usize {
        let mut vertex_count: Option<usize> = None;
        let mesh_attributes = self.attributes.as_ref().expect(MESH_EXTRACTED_ERROR);

        for (attribute_id, attribute_data) in mesh_attributes {
            let attribute_len = attribute_data.values.len();
            if let Some(previous_vertex_count) = vertex_count {
                if previous_vertex_count != attribute_len {
                    let name = mesh_attributes
                        .get(attribute_id)
                        .map(|data| data.attribute.name.to_string())
                        .unwrap_or_else(|| format!("{attribute_id:?}"));

                    warn!("{name} has a different vertex count ({attribute_len}) than other attributes ({previous_vertex_count}) in this mesh, \
                        all attributes will be truncated to match the smallest.");
                    vertex_count = Some(core::cmp::min(previous_vertex_count, attribute_len));
                }
            } else {
                vertex_count = Some(attribute_len);
            }
        }

        vertex_count.unwrap_or(0)
    }

    /// Computes and returns the vertex data of the mesh as bytes.
    /// Therefore the attributes are located in the order of their [`MeshVertexAttribute::id`].
    /// This is used to transform the vertex data into a GPU friendly format.
    ///
    /// If the vertex attributes have different lengths, they are all truncated to
    /// the length of the smallest.
    ///
    /// This is a convenience method which allocates a Vec.
    /// Prefer pre-allocating and using [`Mesh::write_packed_vertex_buffer_data`] when possible.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`.
    pub fn create_packed_vertex_buffer_data(&self) -> Vec<u8> {
        let mut attributes_interleaved_buffer = vec![0; self.get_vertex_buffer_size()];
        self.write_packed_vertex_buffer_data(WriteOnly::from_mut(
            &mut attributes_interleaved_buffer,
        ));
        attributes_interleaved_buffer
    }

    /// Computes and write the vertex data of the mesh into a mutable byte slice.
    /// The attributes are located in the order of their [`MeshVertexAttribute::id`].
    /// This is used to transform the vertex data into a GPU friendly format.
    ///
    /// If the vertex attributes have different lengths, they are all truncated to
    /// the length of the smallest.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`.
    pub fn write_packed_vertex_buffer_data(&self, mut slice: WriteOnly<'_, [u8]>) {
        let mesh_attributes = self.attributes.as_ref().expect(MESH_EXTRACTED_ERROR);

        let vertex_size = self.get_vertex_size() as usize;
        let vertex_count = self.count_vertices();
        // bundle into interleaved buffers
        let mut attribute_offset = 0;
        for attribute_data in mesh_attributes.values() {
            let attribute_size = attribute_data.attribute.format.size() as usize;
            let attributes_bytes = attribute_data.values.get_bytes();
            for (vertex_index, attribute_bytes) in attributes_bytes
                .chunks_exact(attribute_size)
                .take(vertex_count)
                .enumerate()
            {
                let offset = vertex_index * vertex_size + attribute_offset;
                slice
                    .slice(offset..offset + attribute_size)
                    .copy_from_slice(attribute_bytes);
            }

            attribute_offset += attribute_size;
        }
    }

    /// Duplicates the vertex attributes so that no vertices are shared.
    ///
    /// This can dramatically increase the vertex count, so make sure this is what you want.
    /// Does nothing if no [Indices] are set.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_duplicate_vertices`]
    pub fn duplicate_vertices(&mut self) {
        self.try_duplicate_vertices().expect(MESH_EXTRACTED_ERROR);
    }

    /// Duplicates the vertex attributes so that no vertices are shared.
    ///
    /// This can dramatically increase the vertex count, so make sure this is what you want.
    /// Does nothing if no [Indices] are set.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    pub fn try_duplicate_vertices(&mut self) -> Result<(), MeshAccessError> {
        fn duplicate<T: Copy>(values: &[T], indices: impl Iterator<Item = usize>) -> Vec<T> {
            indices.map(|i| values[i]).collect()
        }

        let Some(indices) = self.indices.replace(None)? else {
            return Ok(());
        };

        let mesh_attributes = self.attributes.as_mut()?;

        for attributes in mesh_attributes.values_mut() {
            let indices = indices.iter();
            #[expect(
                clippy::match_same_arms,
                reason = "Although the `vec` binding on some match arms may have different types, each variant has different semantics; thus it's not guaranteed that they will use the same type forever."
            )]
            match &mut attributes.values {
                VertexAttributeValues::Float32(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Sint32(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Uint32(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Float32x2(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Sint32x2(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Uint32x2(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Float32x3(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Sint32x3(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Uint32x3(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Sint32x4(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Uint32x4(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Float32x4(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Sint16x2(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Snorm16x2(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Uint16x2(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Unorm16x2(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Sint16x4(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Snorm16x4(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Uint16x4(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Unorm16x4(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Sint8x2(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Snorm8x2(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Uint8x2(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Unorm8x2(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Sint8x4(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Snorm8x4(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Uint8x4(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Unorm8x4(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Uint8(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Sint8(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Unorm8(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Snorm8(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Uint16(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Sint16(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Unorm16(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Snorm16(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Float16(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Float16x2(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Float16x4(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Float64(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Float64x2(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Float64x3(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Float64x4(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Unorm10_10_10_2(vec) => *vec = duplicate(vec, indices),
                VertexAttributeValues::Unorm8x4Bgra(vec) => *vec = duplicate(vec, indices),
            }
        }

        Ok(())
    }

    /// Consumes the mesh and returns a mesh with no shared vertices.
    ///
    /// This can dramatically increase the vertex count, so make sure this is what you want.
    /// Does nothing if no [`Indices`] are set.
    ///
    /// (Alternatively, you can use [`Mesh::duplicate_vertices`] to mutate an existing mesh in-place)
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_with_duplicated_vertices`]
    #[must_use]
    pub fn with_duplicated_vertices(mut self) -> Self {
        self.duplicate_vertices();
        self
    }

    /// Consumes the mesh and returns a mesh with no shared vertices.
    ///
    /// This can dramatically increase the vertex count, so make sure this is what you want.
    /// Does nothing if no [`Indices`] are set.
    ///
    /// (Alternatively, you can use [`Mesh::try_duplicate_vertices`] to mutate an existing mesh in-place)
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    pub fn try_with_duplicated_vertices(mut self) -> Result<Self, MeshAccessError> {
        self.try_duplicate_vertices()?;
        Ok(self)
    }

    /// Remove duplicate vertices and create the index pointing to the unique vertices.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    /// Returns an error if the mesh already has [`Indices`] set, even if there
    /// are duplicate vertices. If deduplication is needed with indices already set,
    /// consider calling [`Mesh::duplicate_vertices`] and then this function.
    pub fn merge_duplicate_vertices(&mut self) -> Result<(), MeshMergeDuplicateVerticesError> {
        match self.try_indices() {
            Ok(_) => return Err(MeshMergeDuplicateVerticesError::IndicesAlreadySet),
            Err(err) => match err {
                MeshAccessError::ExtractedToRenderWorld => return Err(err.into()),
                MeshAccessError::NotFound => (),
            },
        }

        #[derive(Copy, Clone)]
        struct VertexRef<'a> {
            mesh_attributes: &'a BTreeMap<MeshVertexAttributeId, MeshAttributeData>,
            i: usize,
        }
        impl<'a> VertexRef<'a> {
            fn push_to(&self, target: &mut BTreeMap<MeshVertexAttributeId, MeshAttributeData>) {
                for (key, this_attribute_data) in self.mesh_attributes.iter() {
                    let target_attribute_data = target.get_mut(key).unwrap(); // ok to unwrap, all keys added to new_attributes below
                    target_attribute_data
                        .values
                        .push_from(&this_attribute_data.values, self.i);
                }
            }
        }
        impl<'a> PartialEq for VertexRef<'a> {
            fn eq(&self, other: &Self) -> bool {
                assert!(ptr::eq(self.mesh_attributes, other.mesh_attributes));
                for values in self.mesh_attributes.values() {
                    if values.values.get_bytes_at(self.i) != values.values.get_bytes_at(other.i) {
                        return false;
                    }
                }
                true
            }
        }
        impl<'a> Eq for VertexRef<'a> {}
        impl<'a> Hash for VertexRef<'a> {
            fn hash<H: Hasher>(&self, state: &mut H) {
                for values in self.mesh_attributes.values() {
                    values.values.get_bytes_at(self.i).hash(state);
                }
            }
        }

        let old_attributes = self.attributes.as_ref()?;

        let mut new_attributes: BTreeMap<MeshVertexAttributeId, MeshAttributeData> = self
            .attributes
            .as_ref()?
            .iter()
            .map(|(k, v)| {
                (
                    *k,
                    MeshAttributeData {
                        attribute: v.attribute,
                        values: VertexAttributeValues::new(VertexFormat::from(&v.values)),
                    },
                )
            })
            .collect();

        let mut vertex_to_new_index: HashMap<VertexRef, u32> = HashMap::new();
        let mut indices = Vec::with_capacity(self.count_vertices());
        for i in 0..self.count_vertices() {
            let len: u32 = vertex_to_new_index
                .len()
                .try_into()
                .expect("The number of vertices exceeds u32::MAX");
            let vertex_ref = VertexRef {
                mesh_attributes: old_attributes,
                i,
            };
            let j = match vertex_to_new_index.entry(vertex_ref) {
                hash_map::Entry::Occupied(e) => *e.get(),
                hash_map::Entry::Vacant(e) => {
                    e.insert(len);
                    vertex_ref.push_to(&mut new_attributes);
                    len
                }
            };
            indices.push(j);
        }
        drop(vertex_to_new_index);

        for v in new_attributes.values_mut() {
            v.values.shrink_to_fit();
        }

        self.attributes = MeshExtractableData::Data(new_attributes);
        self.indices = MeshExtractableData::Data(Indices::U32(indices));

        Ok(())
    }

    /// Consumes the mesh and returns a mesh with merged vertices.
    ///
    /// (Alternatively, you can use [`Mesh::merge_duplicate_vertices`] to mutate an existing mesh in-place)
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    /// Returns an error if the mesh already has [`Indices`] set, even if there
    /// are duplicate vertices. If deduplication is needed with indices already set,
    /// consider calling [`Mesh::duplicate_vertices`] and then this function.
    pub fn with_merge_duplicate_vertices(
        mut self,
    ) -> Result<Self, MeshMergeDuplicateVerticesError> {
        self.merge_duplicate_vertices()?;
        Ok(self)
    }

    /// Inverts the winding of the indices such that all counter-clockwise triangles are now
    /// clockwise and vice versa.
    /// For lines, their start and end indices are flipped.
    ///
    /// Does nothing if no [`Indices`] are set.
    /// If this operation succeeded, an [`Ok`] result is returned.
    pub fn invert_winding(&mut self) -> Result<(), MeshWindingInvertError> {
        fn invert<I>(
            indices: &mut [I],
            topology: PrimitiveTopology,
        ) -> Result<(), MeshWindingInvertError> {
            match topology {
                PrimitiveTopology::TriangleList => {
                    let (chunks, []) = indices.as_chunks_mut() else {
                        // Early return if the index count doesn't match
                        return Err(MeshWindingInvertError::AbruptIndicesEnd);
                    };

                    for [_, b, c] in chunks {
                        core::mem::swap(b, c);
                    }
                    Ok(())
                }
                PrimitiveTopology::LineList => {
                    // Early return if the index count doesn't match
                    if !indices.len().is_multiple_of(2) {
                        return Err(MeshWindingInvertError::AbruptIndicesEnd);
                    }
                    indices.reverse();
                    Ok(())
                }
                PrimitiveTopology::TriangleStrip | PrimitiveTopology::LineStrip => {
                    indices.reverse();
                    Ok(())
                }
                _ => Err(MeshWindingInvertError::WrongTopology),
            }
        }

        let mesh_indices = self.indices.as_mut_option()?;

        match mesh_indices {
            Some(Indices::U16(vec)) => invert(vec, self.primitive_topology),
            Some(Indices::U32(vec)) => invert(vec, self.primitive_topology),
            None => Ok(()),
        }
    }

    /// Consumes the mesh and returns a mesh with inverted winding of the indices such
    /// that all counter-clockwise triangles are now clockwise and vice versa.
    ///
    /// Does nothing if no [`Indices`] are set.
    pub fn with_inverted_winding(mut self) -> Result<Self, MeshWindingInvertError> {
        self.invert_winding().map(|_| self)
    }

    /// Calculates the [`Mesh::ATTRIBUTE_NORMAL`] of a mesh.
    /// If the mesh is indexed, this defaults to smooth normals. Otherwise, it defaults to flat
    /// normals.
    ///
    /// # Panics
    /// Panics if [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].=
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_compute_normals`]
    pub fn compute_normals(&mut self) {
        self.try_compute_normals().expect(MESH_EXTRACTED_ERROR);
    }

    /// Calculates the [`Mesh::ATTRIBUTE_NORMAL`] of a mesh.
    /// If the mesh is indexed, this defaults to smooth normals. Otherwise, it defaults to flat
    /// normals.
    ///
    /// # Panics
    /// Panics if [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].=
    pub fn try_compute_normals(&mut self) -> Result<(), MeshAccessError> {
        assert!(
            matches!(self.primitive_topology, PrimitiveTopology::TriangleList),
            "`compute_normals` can only work on `TriangleList`s"
        );
        if self.try_indices_option()?.is_none() {
            self.try_compute_flat_normals()
        } else {
            self.try_compute_smooth_normals()
        }
    }

    /// Calculates the [`Mesh::ATTRIBUTE_NORMAL`] of a mesh.
    ///
    /// # Panics
    /// Panics if [`Indices`] are set or [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].
    /// Consider calling [`Mesh::duplicate_vertices`] or exporting your mesh with normal
    /// attributes.
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_compute_flat_normals`]
    ///
    /// FIXME: This should handle more cases since this is called as a part of gltf
    /// mesh loading where we can't really blame users for loading meshes that might
    /// not conform to the limitations here!
    pub fn compute_flat_normals(&mut self) {
        self.try_compute_flat_normals().expect(MESH_EXTRACTED_ERROR);
    }

    /// Calculates the [`Mesh::ATTRIBUTE_NORMAL`] of a mesh.
    ///
    /// # Panics
    /// Panics if [`Indices`] are set or [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].
    /// Consider calling [`Mesh::duplicate_vertices`] or exporting your mesh with normal
    /// attributes.
    ///
    /// FIXME: This should handle more cases since this is called as a part of gltf
    /// mesh loading where we can't really blame users for loading meshes that might
    /// not conform to the limitations here!
    pub fn try_compute_flat_normals(&mut self) -> Result<(), MeshAccessError> {
        assert!(
            self.try_indices_option()?.is_none(),
            "`compute_flat_normals` can't work on indexed geometry. Consider calling either `Mesh::compute_smooth_normals` or `Mesh::duplicate_vertices` followed by `Mesh::compute_flat_normals`."
        );
        assert!(
            matches!(self.primitive_topology, PrimitiveTopology::TriangleList),
            "`compute_flat_normals` can only work on `TriangleList`s"
        );

        let positions = self
            .try_attribute(Mesh::ATTRIBUTE_POSITION)?
            .as_float3()
            .expect("`Mesh::ATTRIBUTE_POSITION` vertex attributes should be of type `float3`");

        let normals: Vec<_> = positions
            .as_chunks()
            .0
            .iter()
            .flat_map(|&[a, b, c]| [triangle_normal(a, b, c); 3])
            .collect();

        self.try_insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
    }

    /// Calculates the [`Mesh::ATTRIBUTE_NORMAL`] of an indexed mesh, smoothing normals for shared
    /// vertices.
    ///
    /// This method weights normals by the angles of the corners of connected triangles, thus
    /// eliminating triangle area and count as factors in the final normal. This does make it
    /// somewhat slower than [`Mesh::compute_area_weighted_normals`] which does not need to
    /// greedily normalize each triangle's normal or calculate corner angles.
    ///
    /// If you would rather have the computed normals be weighted by triangle area, see
    /// [`Mesh::compute_area_weighted_normals`] instead. If you need to weight them in some other
    /// way, see [`Mesh::compute_custom_smooth_normals`].
    ///
    /// # Panics
    /// Panics if [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].
    /// Panics if the mesh does not have indices defined.
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_compute_smooth_normals`]
    pub fn compute_smooth_normals(&mut self) {
        self.try_compute_smooth_normals()
            .expect(MESH_EXTRACTED_ERROR);
    }

    /// Calculates the [`Mesh::ATTRIBUTE_NORMAL`] of an indexed mesh, smoothing normals for shared
    /// vertices.
    ///
    /// This method weights normals by the angles of the corners of connected triangles, thus
    /// eliminating triangle area and count as factors in the final normal. This does make it
    /// somewhat slower than [`Mesh::compute_area_weighted_normals`] which does not need to
    /// greedily normalize each triangle's normal or calculate corner angles.
    ///
    /// If you would rather have the computed normals be weighted by triangle area, see
    /// [`Mesh::compute_area_weighted_normals`] instead. If you need to weight them in some other
    /// way, see [`Mesh::compute_custom_smooth_normals`].
    ///
    /// # Panics
    /// Panics if [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].
    /// Panics if the mesh does not have indices defined.
    pub fn try_compute_smooth_normals(&mut self) -> Result<(), MeshAccessError> {
        self.try_compute_custom_smooth_normals(|[a, b, c], positions, normals| {
            let pa = Vec3::from(positions[a]);
            let pb = Vec3::from(positions[b]);
            let pc = Vec3::from(positions[c]);

            let ab = pb - pa;
            let ba = pa - pb;
            let bc = pc - pb;
            let cb = pb - pc;
            let ca = pa - pc;
            let ac = pc - pa;

            const EPS: f32 = f32::EPSILON;
            let weight_a = if ab.length_squared() * ac.length_squared() > EPS {
                ab.angle_between(ac)
            } else {
                0.0
            };
            let weight_b = if ba.length_squared() * bc.length_squared() > EPS {
                ba.angle_between(bc)
            } else {
                0.0
            };
            let weight_c = if ca.length_squared() * cb.length_squared() > EPS {
                ca.angle_between(cb)
            } else {
                0.0
            };

            let normal = Vec3::from(triangle_normal(positions[a], positions[b], positions[c]));

            normals[a] += normal * weight_a;
            normals[b] += normal * weight_b;
            normals[c] += normal * weight_c;
        })
    }

    /// Calculates the [`Mesh::ATTRIBUTE_NORMAL`] of an indexed mesh, smoothing normals for shared
    /// vertices.
    ///
    /// This method weights normals by the area of each triangle containing the vertex. Thus,
    /// larger triangles will skew the normals of their vertices towards their own normal more
    /// than smaller triangles will.
    ///
    /// This method is actually somewhat faster than [`Mesh::compute_smooth_normals`] because an
    /// intermediate result of triangle normal calculation is already scaled by the triangle's area.
    ///
    /// If you would rather have the computed normals be influenced only by the angles of connected
    /// edges, see [`Mesh::compute_smooth_normals`] instead. If you need to weight them in some
    /// other way, see [`Mesh::compute_custom_smooth_normals`].
    ///
    /// # Panics
    /// Panics if [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].
    /// Panics if the mesh does not have indices defined.
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_compute_area_weighted_normals`]
    pub fn compute_area_weighted_normals(&mut self) {
        self.try_compute_area_weighted_normals()
            .expect(MESH_EXTRACTED_ERROR);
    }

    /// Calculates the [`Mesh::ATTRIBUTE_NORMAL`] of an indexed mesh, smoothing normals for shared
    /// vertices.
    ///
    /// This method weights normals by the area of each triangle containing the vertex. Thus,
    /// larger triangles will skew the normals of their vertices towards their own normal more
    /// than smaller triangles will.
    ///
    /// This method is actually somewhat faster than [`Mesh::compute_smooth_normals`] because an
    /// intermediate result of triangle normal calculation is already scaled by the triangle's area.
    ///
    /// If you would rather have the computed normals be influenced only by the angles of connected
    /// edges, see [`Mesh::compute_smooth_normals`] instead. If you need to weight them in some
    /// other way, see [`Mesh::compute_custom_smooth_normals`].
    ///
    /// # Panics
    /// Panics if [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].
    /// Panics if the mesh does not have indices defined.
    pub fn try_compute_area_weighted_normals(&mut self) -> Result<(), MeshAccessError> {
        self.try_compute_custom_smooth_normals(|[a, b, c], positions, normals| {
            let normal = Vec3::from(triangle_area_normal(
                positions[a],
                positions[b],
                positions[c],
            ));
            [a, b, c].into_iter().for_each(|pos| {
                normals[pos] += normal;
            });
        })
    }

    /// Calculates the [`Mesh::ATTRIBUTE_NORMAL`] of an indexed mesh, smoothing normals for shared
    /// vertices.
    ///
    /// This method allows you to customize how normals are weighted via the `per_triangle` parameter,
    /// which must be a function or closure that accepts 3 parameters:
    /// - The indices of the three vertices of the triangle as a `[usize; 3]`.
    /// - A reference to the values of the [`Mesh::ATTRIBUTE_POSITION`] of the mesh (`&[[f32; 3]]`).
    /// - A mutable reference to the sums of all normals so far.
    ///
    /// See also the standard methods included in Bevy for calculating smooth normals:
    /// - [`Mesh::compute_smooth_normals`]
    /// - [`Mesh::compute_area_weighted_normals`]
    ///
    /// An example that would weight each connected triangle's normal equally, thus skewing normals
    /// towards the planes divided into the most triangles:
    /// ```
    /// # use bevy_asset::RenderAssetUsages;
    /// # use bevy_mesh::{Mesh, PrimitiveTopology, Meshable, MeshBuilder};
    /// # use bevy_math::{Vec3, primitives::Cuboid};
    /// # let mut mesh = Cuboid::default().mesh().build();
    /// mesh.compute_custom_smooth_normals(|[a, b, c], positions, normals| {
    ///     let normal = Vec3::from(bevy_mesh::triangle_normal(positions[a], positions[b], positions[c]));
    ///     for idx in [a, b, c] {
    ///         normals[idx] += normal;
    ///     }
    /// });
    /// ```
    ///
    /// # Panics
    /// Panics if [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].
    /// Panics if the mesh does not have indices defined.
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_compute_custom_smooth_normals`]
    //
    // FIXME: This should handle more cases since this is called as a part of gltf
    // mesh loading where we can't really blame users for loading meshes that might
    // not conform to the limitations here!
    //
    // When fixed, also update "Panics" sections of
    // - [Mesh::compute_smooth_normals]
    // - [Mesh::with_computed_smooth_normals]
    // - [Mesh::compute_area_weighted_normals]
    // - [Mesh::with_computed_area_weighted_normals]
    pub fn compute_custom_smooth_normals(
        &mut self,
        per_triangle: impl FnMut([usize; 3], &[[f32; 3]], &mut [Vec3]),
    ) {
        self.try_compute_custom_smooth_normals(per_triangle)
            .expect(MESH_EXTRACTED_ERROR);
    }

    /// Calculates the [`Mesh::ATTRIBUTE_NORMAL`] of an indexed mesh, smoothing normals for shared
    /// vertices.
    ///
    /// This method allows you to customize how normals are weighted via the `per_triangle` parameter,
    /// which must be a function or closure that accepts 3 parameters:
    /// - The indices of the three vertices of the triangle as a `[usize; 3]`.
    /// - A reference to the values of the [`Mesh::ATTRIBUTE_POSITION`] of the mesh (`&[[f32; 3]]`).
    /// - A mutable reference to the sums of all normals so far.
    ///
    /// See also the standard methods included in Bevy for calculating smooth normals:
    /// - [`Mesh::compute_smooth_normals`]
    /// - [`Mesh::compute_area_weighted_normals`]
    ///
    /// An example that would weight each connected triangle's normal equally, thus skewing normals
    /// towards the planes divided into the most triangles:
    /// ```
    /// # use bevy_asset::RenderAssetUsages;
    /// # use bevy_mesh::{Mesh, PrimitiveTopology, Meshable, MeshBuilder};
    /// # use bevy_math::{Vec3, primitives::Cuboid};
    /// # let mut mesh = Cuboid::default().mesh().build();
    /// mesh.compute_custom_smooth_normals(|[a, b, c], positions, normals| {
    ///     let normal = Vec3::from(bevy_mesh::triangle_normal(positions[a], positions[b], positions[c]));
    ///     for idx in [a, b, c] {
    ///         normals[idx] += normal;
    ///     }
    /// });
    /// ```
    ///
    /// # Panics
    /// Panics if [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].
    /// Panics if the mesh does not have indices defined.
    //
    // FIXME: This should handle more cases since this is called as a part of gltf
    // mesh loading where we can't really blame users for loading meshes that might
    // not conform to the limitations here!
    //
    // When fixed, also update "Panics" sections of
    // - [Mesh::compute_smooth_normals]
    // - [Mesh::with_computed_smooth_normals]
    // - [Mesh::compute_area_weighted_normals]
    // - [Mesh::with_computed_area_weighted_normals]
    pub fn try_compute_custom_smooth_normals(
        &mut self,
        mut per_triangle: impl FnMut([usize; 3], &[[f32; 3]], &mut [Vec3]),
    ) -> Result<(), MeshAccessError> {
        assert!(
            matches!(self.primitive_topology, PrimitiveTopology::TriangleList),
            "smooth normals can only be computed on `TriangleList`s"
        );
        assert!(
            self.try_indices_option()?.is_some(),
            "smooth normals can only be computed on indexed meshes"
        );

        let positions = self
            .try_attribute(Mesh::ATTRIBUTE_POSITION)?
            .as_float3()
            .expect("`Mesh::ATTRIBUTE_POSITION` vertex attributes should be of type `float3`");

        let mut normals = vec![Vec3::ZERO; positions.len()];

        match self.try_indices()? {
            Indices::U16(vec) => vec.as_chunks().0.iter().for_each(|&chunk| {
                per_triangle(chunk.map(|i| i as usize), positions, &mut normals);
            }),
            Indices::U32(vec) => vec.as_chunks().0.iter().for_each(|&chunk| {
                per_triangle(chunk.map(|i| i as usize), positions, &mut normals);
            }),
        }

        for normal in &mut normals {
            *normal = normal.try_normalize().unwrap_or(Vec3::ZERO);
        }

        self.try_insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
    }

    /// Consumes the mesh and returns a mesh with calculated [`Mesh::ATTRIBUTE_NORMAL`].
    /// If the mesh is indexed, this defaults to smooth normals. Otherwise, it defaults to flat
    /// normals.
    ///
    /// (Alternatively, you can use [`Mesh::compute_normals`] to mutate an existing mesh in-place)
    ///
    /// # Panics
    /// Panics if [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_with_computed_normals`]
    #[must_use]
    pub fn with_computed_normals(self) -> Self {
        self.try_with_computed_normals()
            .expect(MESH_EXTRACTED_ERROR)
    }

    /// Consumes the mesh and returns a mesh with calculated [`Mesh::ATTRIBUTE_NORMAL`].
    /// If the mesh is indexed, this defaults to smooth normals. Otherwise, it defaults to flat
    /// normals.
    ///
    /// (Alternatively, you can use [`Mesh::compute_normals`] to mutate an existing mesh in-place)
    ///
    /// # Panics
    /// Panics if [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].
    pub fn try_with_computed_normals(mut self) -> Result<Self, MeshAccessError> {
        self.try_compute_normals()?;
        Ok(self)
    }

    /// Consumes the mesh and returns a mesh with calculated [`Mesh::ATTRIBUTE_NORMAL`].
    ///
    /// (Alternatively, you can use [`Mesh::compute_flat_normals`] to mutate an existing mesh in-place)
    ///
    /// # Panics
    /// Panics if [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].
    /// Panics if the mesh has indices defined
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_with_computed_flat_normals`]
    pub fn with_computed_flat_normals(mut self) -> Self {
        self.compute_flat_normals();
        self
    }

    /// Consumes the mesh and returns a mesh with calculated [`Mesh::ATTRIBUTE_NORMAL`].
    ///
    /// (Alternatively, you can use [`Mesh::compute_flat_normals`] to mutate an existing mesh in-place)
    ///
    /// # Panics
    /// Panics if [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].
    /// Panics if the mesh has indices defined
    pub fn try_with_computed_flat_normals(mut self) -> Result<Self, MeshAccessError> {
        self.try_compute_flat_normals()?;
        Ok(self)
    }

    /// Consumes the mesh and returns a mesh with calculated [`Mesh::ATTRIBUTE_NORMAL`].
    ///
    /// (Alternatively, you can use [`Mesh::compute_smooth_normals`] to mutate an existing mesh in-place)
    ///
    /// This method weights normals by the angles of triangle corners connected to each vertex. If
    /// you would rather have the computed normals be weighted by triangle area, see
    /// [`Mesh::with_computed_area_weighted_normals`] instead.
    ///
    /// # Panics
    /// Panics if [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].
    /// Panics if the mesh does not have indices defined.
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_with_computed_smooth_normals`]
    pub fn with_computed_smooth_normals(mut self) -> Self {
        self.compute_smooth_normals();
        self
    }
    /// Consumes the mesh and returns a mesh with calculated [`Mesh::ATTRIBUTE_NORMAL`].
    ///
    /// (Alternatively, you can use [`Mesh::compute_smooth_normals`] to mutate an existing mesh in-place)
    ///
    /// This method weights normals by the angles of triangle corners connected to each vertex. If
    /// you would rather have the computed normals be weighted by triangle area, see
    /// [`Mesh::with_computed_area_weighted_normals`] instead.
    ///
    /// # Panics
    /// Panics if [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].
    /// Panics if the mesh does not have indices defined.
    pub fn try_with_computed_smooth_normals(mut self) -> Result<Self, MeshAccessError> {
        self.try_compute_smooth_normals()?;
        Ok(self)
    }

    /// Consumes the mesh and returns a mesh with calculated [`Mesh::ATTRIBUTE_NORMAL`].
    ///
    /// (Alternatively, you can use [`Mesh::compute_area_weighted_normals`] to mutate an existing mesh in-place)
    ///
    /// This method weights normals by the area of each triangle containing the vertex. Thus,
    /// larger triangles will skew the normals of their vertices towards their own normal more
    /// than smaller triangles will. If you would rather have the computed normals be influenced
    /// only by the angles of connected edges, see [`Mesh::with_computed_smooth_normals`] instead.
    ///
    /// # Panics
    /// Panics if [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].
    /// Panics if the mesh does not have indices defined.
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_with_computed_area_weighted_normals`]
    pub fn with_computed_area_weighted_normals(mut self) -> Self {
        self.compute_area_weighted_normals();
        self
    }

    /// Consumes the mesh and returns a mesh with calculated [`Mesh::ATTRIBUTE_NORMAL`].
    ///
    /// (Alternatively, you can use [`Mesh::compute_area_weighted_normals`] to mutate an existing mesh in-place)
    ///
    /// This method weights normals by the area of each triangle containing the vertex. Thus,
    /// larger triangles will skew the normals of their vertices towards their own normal more
    /// than smaller triangles will. If you would rather have the computed normals be influenced
    /// only by the angles of connected edges, see [`Mesh::with_computed_smooth_normals`] instead.
    ///
    /// # Panics
    /// Panics if [`Mesh::ATTRIBUTE_POSITION`] is not of type `float3`.
    /// Panics if the mesh has any other topology than [`PrimitiveTopology::TriangleList`].
    /// Panics if the mesh does not have indices defined.
    pub fn try_with_computed_area_weighted_normals(mut self) -> Result<Self, MeshAccessError> {
        self.try_compute_area_weighted_normals()?;
        Ok(self)
    }

    /// Generate tangents for the mesh using the `mikktspace` algorithm.
    ///
    /// Sets the [`Mesh::ATTRIBUTE_TANGENT`] attribute if successful.
    /// Requires a [`PrimitiveTopology::TriangleList`] topology and the [`Mesh::ATTRIBUTE_POSITION`], [`Mesh::ATTRIBUTE_NORMAL`] and [`Mesh::ATTRIBUTE_UV_0`] attributes set.
    #[cfg(feature = "bevy_mikktspace")]
    pub fn generate_tangents(&mut self) -> Result<(), super::GenerateTangentsError> {
        let tangents = super::generate_tangents_for_mesh(self)?;
        self.try_insert_attribute(Mesh::ATTRIBUTE_TANGENT, tangents)?;
        Ok(())
    }

    /// Consumes the mesh and returns a mesh with tangents generated using the `mikktspace` algorithm.
    ///
    /// The resulting mesh will have the [`Mesh::ATTRIBUTE_TANGENT`] attribute if successful.
    ///
    /// (Alternatively, you can use [`Mesh::generate_tangents`] to mutate an existing mesh in-place)
    ///
    /// Requires a [`PrimitiveTopology::TriangleList`] topology and the [`Mesh::ATTRIBUTE_POSITION`], [`Mesh::ATTRIBUTE_NORMAL`] and [`Mesh::ATTRIBUTE_UV_0`] attributes set.
    #[cfg(feature = "bevy_mikktspace")]
    pub fn with_generated_tangents(mut self) -> Result<Mesh, super::GenerateTangentsError> {
        self.generate_tangents()?;
        Ok(self)
    }

    /// Merges the [`Mesh`] data of `other` with `self`. The attributes and indices of `other` will be appended to `self`.
    ///
    /// Note that attributes of `other` that don't exist on `self` will be ignored.
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    ///
    /// # Errors
    ///
    /// If any of the following conditions are not met, this function errors:
    /// * All of the vertex attributes that have the same attribute id, must also
    ///   have the same attribute type.
    ///   For example two attributes with the same id, but where one is a
    ///   [`VertexAttributeValues::Float32`] and the other is a
    ///   [`VertexAttributeValues::Float32x3`], would be invalid.
    /// * Both meshes must have the same primitive topology.
    pub fn merge(&mut self, other: &Mesh) -> Result<(), MeshMergeError> {
        use VertexAttributeValues::*;

        // Check if the meshes `primitive_topology` field is the same,
        // as if that is not the case, the resulting mesh could (and most likely would)
        // be invalid.
        if self.primitive_topology != other.primitive_topology {
            return Err(MeshMergeError::IncompatiblePrimitiveTopology {
                self_primitive_topology: self.primitive_topology,
                other_primitive_topology: other.primitive_topology,
            });
        }

        // The indices of `other` should start after the last vertex of `self`.
        let index_offset = self.count_vertices();

        // Extend attributes of `self` with attributes of `other`.
        for (attribute, values) in self.try_attributes_mut()? {
            if let Some(other_values) = other.try_attribute_option(attribute.id)? {
                #[expect(
                    clippy::match_same_arms,
                    reason = "Although the bindings on some match arms may have different types, each variant has different semantics; thus it's not guaranteed that they will use the same type forever."
                )]
                match (values, other_values) {
                    (Float32(vec1), Float32(vec2)) => vec1.extend(vec2),
                    (Sint32(vec1), Sint32(vec2)) => vec1.extend(vec2),
                    (Uint32(vec1), Uint32(vec2)) => vec1.extend(vec2),
                    (Float32x2(vec1), Float32x2(vec2)) => vec1.extend(vec2),
                    (Sint32x2(vec1), Sint32x2(vec2)) => vec1.extend(vec2),
                    (Uint32x2(vec1), Uint32x2(vec2)) => vec1.extend(vec2),
                    (Float32x3(vec1), Float32x3(vec2)) => vec1.extend(vec2),
                    (Sint32x3(vec1), Sint32x3(vec2)) => vec1.extend(vec2),
                    (Uint32x3(vec1), Uint32x3(vec2)) => vec1.extend(vec2),
                    (Sint32x4(vec1), Sint32x4(vec2)) => vec1.extend(vec2),
                    (Uint32x4(vec1), Uint32x4(vec2)) => vec1.extend(vec2),
                    (Float32x4(vec1), Float32x4(vec2)) => vec1.extend(vec2),
                    (Sint16x2(vec1), Sint16x2(vec2)) => vec1.extend(vec2),
                    (Snorm16x2(vec1), Snorm16x2(vec2)) => vec1.extend(vec2),
                    (Uint16x2(vec1), Uint16x2(vec2)) => vec1.extend(vec2),
                    (Unorm16x2(vec1), Unorm16x2(vec2)) => vec1.extend(vec2),
                    (Sint16x4(vec1), Sint16x4(vec2)) => vec1.extend(vec2),
                    (Snorm16x4(vec1), Snorm16x4(vec2)) => vec1.extend(vec2),
                    (Uint16x4(vec1), Uint16x4(vec2)) => vec1.extend(vec2),
                    (Unorm16x4(vec1), Unorm16x4(vec2)) => vec1.extend(vec2),
                    (Sint8x2(vec1), Sint8x2(vec2)) => vec1.extend(vec2),
                    (Snorm8x2(vec1), Snorm8x2(vec2)) => vec1.extend(vec2),
                    (Uint8x2(vec1), Uint8x2(vec2)) => vec1.extend(vec2),
                    (Unorm8x2(vec1), Unorm8x2(vec2)) => vec1.extend(vec2),
                    (Sint8x4(vec1), Sint8x4(vec2)) => vec1.extend(vec2),
                    (Snorm8x4(vec1), Snorm8x4(vec2)) => vec1.extend(vec2),
                    (Uint8x4(vec1), Uint8x4(vec2)) => vec1.extend(vec2),
                    (Unorm8x4(vec1), Unorm8x4(vec2)) => vec1.extend(vec2),
                    _ => {
                        return Err(MeshMergeError::IncompatibleVertexAttributes {
                            self_attribute: *attribute,
                            other_attribute: other
                                .try_attribute_data(attribute.id)?
                                .map(|data| data.attribute),
                        })
                    }
                }
            }
        }

        // Extend indices of `self` with indices of `other`.
        if let (Some(indices), Some(other_indices)) =
            (self.try_indices_mut_option()?, other.try_indices_option()?)
        {
            indices.extend(other_indices.iter().map(|i| (i + index_offset) as u32));
        }
        Ok(())
    }

    /// Transforms the vertex positions, normals, and tangents of the mesh by the given [`Transform`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_transformed_by`]
    pub fn transformed_by(mut self, transform: Transform) -> Self {
        self.transform_by(transform);
        self
    }

    /// Transforms the vertex positions, normals, and tangents of the mesh by the given [`Transform`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    pub fn try_transformed_by(mut self, transform: Transform) -> Result<Self, MeshAccessError> {
        self.try_transform_by(transform)?;
        Ok(self)
    }

    /// Transforms the vertex positions, normals, and tangents of the mesh in place by the given [`Transform`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_transform_by`]
    pub fn transform_by(&mut self, transform: Transform) {
        self.try_transform_by(transform)
            .expect(MESH_EXTRACTED_ERROR);
    }

    /// Transforms the vertex positions, normals, and tangents of the mesh in place by the given [`Transform`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    pub fn try_transform_by(&mut self, transform: Transform) -> Result<(), MeshAccessError> {
        // Needed when transforming normals and tangents
        let scale_recip = 1. / transform.scale;
        debug_assert!(
            transform.scale.yzx() * transform.scale.zxy() != Vec3::ZERO,
            "mesh transform scale cannot be zero on more than one axis"
        );

        if let Some(VertexAttributeValues::Float32x3(positions)) =
            self.try_attribute_mut_option(Mesh::ATTRIBUTE_POSITION)?
        {
            // Apply scale, rotation, and translation to vertex positions
            positions
                .iter_mut()
                .for_each(|pos| *pos = transform.transform_point(Vec3::from_slice(pos)).to_array());
        }

        // No need to transform normals or tangents if rotation is near identity and scale is uniform
        if transform.rotation.is_near_identity()
            && transform.scale.x == transform.scale.y
            && transform.scale.y == transform.scale.z
        {
            return Ok(());
        }

        if let Some(VertexAttributeValues::Float32x3(normals)) =
            self.try_attribute_mut_option(Mesh::ATTRIBUTE_NORMAL)?
        {
            // Transform normals, taking into account non-uniform scaling and rotation
            normals.iter_mut().for_each(|normal| {
                *normal = (transform.rotation
                    * scale_normal(Vec3::from_array(*normal), scale_recip))
                .to_array();
            });
        }

        if let Some(VertexAttributeValues::Float32x4(tangents)) =
            self.try_attribute_mut_option(Mesh::ATTRIBUTE_TANGENT)?
        {
            // Transform tangents, taking into account non-uniform scaling and rotation
            tangents.iter_mut().for_each(|tangent| {
                let handedness = tangent[3];
                let scaled_tangent = Vec3::from_slice(tangent) * transform.scale;
                *tangent = (transform.rotation * scaled_tangent.normalize_or_zero())
                    .extend(handedness)
                    .to_array();
            });
        }

        Ok(())
    }

    /// Translates the vertex positions of the mesh by the given [`Vec3`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_translated_by`]
    pub fn translated_by(mut self, translation: Vec3) -> Self {
        self.translate_by(translation);
        self
    }

    /// Translates the vertex positions of the mesh by the given [`Vec3`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    pub fn try_translated_by(mut self, translation: Vec3) -> Result<Self, MeshAccessError> {
        self.try_translate_by(translation)?;
        Ok(self)
    }

    /// Translates the vertex positions of the mesh in place by the given [`Vec3`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_translate_by`]
    pub fn translate_by(&mut self, translation: Vec3) {
        self.try_translate_by(translation)
            .expect(MESH_EXTRACTED_ERROR);
    }

    /// Translates the vertex positions of the mesh in place by the given [`Vec3`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    pub fn try_translate_by(&mut self, translation: Vec3) -> Result<(), MeshAccessError> {
        if translation == Vec3::ZERO {
            return Ok(());
        }

        if let Some(VertexAttributeValues::Float32x3(positions)) =
            self.try_attribute_mut_option(Mesh::ATTRIBUTE_POSITION)?
        {
            // Apply translation to vertex positions
            positions
                .iter_mut()
                .for_each(|pos| *pos = (Vec3::from_slice(pos) + translation).to_array());
        }

        Ok(())
    }

    /// Rotates the vertex positions, normals, and tangents of the mesh by the given [`Quat`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_rotated_by`]
    pub fn rotated_by(mut self, rotation: Quat) -> Self {
        self.try_rotate_by(rotation).expect(MESH_EXTRACTED_ERROR);
        self
    }

    /// Rotates the vertex positions, normals, and tangents of the mesh by the given [`Quat`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    pub fn try_rotated_by(mut self, rotation: Quat) -> Result<Self, MeshAccessError> {
        self.try_rotate_by(rotation)?;
        Ok(self)
    }

    /// Rotates the vertex positions, normals, and tangents of the mesh in place by the given [`Quat`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_rotate_by`]
    pub fn rotate_by(&mut self, rotation: Quat) {
        self.try_rotate_by(rotation).expect(MESH_EXTRACTED_ERROR);
    }

    /// Rotates the vertex positions, normals, and tangents of the mesh in place by the given [`Quat`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    pub fn try_rotate_by(&mut self, rotation: Quat) -> Result<(), MeshAccessError> {
        if let Some(VertexAttributeValues::Float32x3(positions)) =
            self.try_attribute_mut_option(Mesh::ATTRIBUTE_POSITION)?
        {
            // Apply rotation to vertex positions
            positions
                .iter_mut()
                .for_each(|pos| *pos = (rotation * Vec3::from_slice(pos)).to_array());
        }

        // No need to transform normals or tangents if rotation is near identity
        if rotation.is_near_identity() {
            return Ok(());
        }

        if let Some(VertexAttributeValues::Float32x3(normals)) =
            self.try_attribute_mut_option(Mesh::ATTRIBUTE_NORMAL)?
        {
            // Transform normals
            normals.iter_mut().for_each(|normal| {
                *normal = (rotation * Vec3::from_slice(normal).normalize_or_zero()).to_array();
            });
        }

        if let Some(VertexAttributeValues::Float32x4(tangents)) =
            self.try_attribute_mut_option(Mesh::ATTRIBUTE_TANGENT)?
        {
            // Transform tangents
            tangents.iter_mut().for_each(|tangent| {
                let handedness = tangent[3];
                *tangent = (rotation * Vec3::from_slice(tangent).normalize_or_zero())
                    .extend(handedness)
                    .to_array();
            });
        }

        Ok(())
    }

    /// Scales the vertex positions, normals, and tangents of the mesh by the given [`Vec3`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_scaled_by`]
    pub fn scaled_by(mut self, scale: Vec3) -> Self {
        self.scale_by(scale);
        self
    }

    /// Scales the vertex positions, normals, and tangents of the mesh by the given [`Vec3`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    pub fn try_scaled_by(mut self, scale: Vec3) -> Result<Self, MeshAccessError> {
        self.try_scale_by(scale)?;
        Ok(self)
    }

    /// Scales the vertex positions, normals, and tangents of the mesh in place by the given [`Vec3`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_scale_by`]
    pub fn scale_by(&mut self, scale: Vec3) {
        self.try_scale_by(scale).expect(MESH_EXTRACTED_ERROR);
    }

    /// Scales the vertex positions, normals, and tangents of the mesh in place by the given [`Vec3`].
    ///
    /// `Aabb` of entities with modified mesh are not updated automatically.
    pub fn try_scale_by(&mut self, scale: Vec3) -> Result<(), MeshAccessError> {
        // Needed when transforming normals and tangents
        let scale_recip = 1. / scale;
        debug_assert!(
            scale.yzx() * scale.zxy() != Vec3::ZERO,
            "mesh transform scale cannot be zero on more than one axis"
        );

        if let Some(VertexAttributeValues::Float32x3(positions)) =
            self.try_attribute_mut_option(Mesh::ATTRIBUTE_POSITION)?
        {
            // Apply scale to vertex positions
            positions
                .iter_mut()
                .for_each(|pos| *pos = (scale * Vec3::from_slice(pos)).to_array());
        }

        // No need to transform normals or tangents if scale is uniform
        if scale.x == scale.y && scale.y == scale.z {
            return Ok(());
        }

        if let Some(VertexAttributeValues::Float32x3(normals)) =
            self.try_attribute_mut_option(Mesh::ATTRIBUTE_NORMAL)?
        {
            // Transform normals, taking into account non-uniform scaling
            normals.iter_mut().for_each(|normal| {
                *normal = scale_normal(Vec3::from_array(*normal), scale_recip).to_array();
            });
        }

        if let Some(VertexAttributeValues::Float32x4(tangents)) =
            self.try_attribute_mut_option(Mesh::ATTRIBUTE_TANGENT)?
        {
            // Transform tangents, taking into account non-uniform scaling
            tangents.iter_mut().for_each(|tangent| {
                let handedness = tangent[3];
                let scaled_tangent = Vec3::from_slice(tangent) * scale;
                *tangent = scaled_tangent
                    .normalize_or_zero()
                    .extend(handedness)
                    .to_array();
            });
        }

        Ok(())
    }

    /// Normalize joint weights so they sum to 1.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_normalize_joint_weights`]
    pub fn normalize_joint_weights(&mut self) {
        self.try_normalize_joint_weights()
            .expect(MESH_EXTRACTED_ERROR);
    }

    /// Normalize joint weights so they sum to 1.
    pub fn try_normalize_joint_weights(&mut self) -> Result<(), MeshAccessError> {
        if let Some(VertexAttributeValues::Float32x4(joints)) =
            self.try_attribute_mut_option(Self::ATTRIBUTE_JOINT_WEIGHT)?
        {
            for weights in joints.iter_mut() {
                // force negative weights to zero
                weights.iter_mut().for_each(|w| *w = w.max(0.0));

                let sum: f32 = weights.iter().sum();
                if sum == 0.0 {
                    // all-zero weights are invalid
                    weights[0] = 1.0;
                } else {
                    let recip = sum.recip();
                    for weight in weights.iter_mut() {
                        *weight *= recip;
                    }
                }
            }
        }

        Ok(())
    }

    /// Get a list of this Mesh's [triangles] as an iterator if possible.
    ///
    /// Returns an error if any of the following conditions are met (see [`MeshTrianglesError`]):
    /// * The Mesh's [primitive topology] is not `TriangleList` or `TriangleStrip`.
    /// * The Mesh is missing position or index data.
    /// * The Mesh's position data has the wrong format (not `Float32x3`).
    ///
    /// [primitive topology]: PrimitiveTopology
    /// [triangles]: Triangle3d
    pub fn triangles(&self) -> Result<impl Iterator<Item = Triangle3d> + '_, MeshTrianglesError> {
        fn indices_to_triangle<T: TryInto<usize> + Copy>(
            vertices: &[[f32; 3]],
            indices: &[T; 3],
        ) -> Option<Triangle3d> {
            let vert0 = Vec3::from(*vertices.get(indices[0].try_into().ok()?)?);
            let vert1 = Vec3::from(*vertices.get(indices[1].try_into().ok()?)?);
            let vert2 = Vec3::from(*vertices.get(indices[2].try_into().ok()?)?);
            Some(Triangle3d {
                vertices: [vert0, vert1, vert2],
            })
        }

        let position_data = self.try_attribute(Mesh::ATTRIBUTE_POSITION)?;

        let Some(vertices) = position_data.as_float3() else {
            return Err(MeshTrianglesError::PositionsFormat);
        };

        let indices = self.try_indices()?;

        match self.primitive_topology {
            PrimitiveTopology::TriangleList => {
                // When indices reference out-of-bounds vertex data, the triangle is omitted.
                // This implicitly truncates the indices to a multiple of 3.
                let iterator = match indices {
                    Indices::U16(vec) => FourIterators::First(
                        vec.as_chunks()
                            .0
                            .iter()
                            .flat_map(|indices| indices_to_triangle(vertices, indices)),
                    ),
                    Indices::U32(vec) => FourIterators::Second(
                        vec.as_chunks()
                            .0
                            .iter()
                            .flat_map(|indices| indices_to_triangle(vertices, indices)),
                    ),
                };

                Ok(iterator)
            }
            PrimitiveTopology::TriangleStrip => {
                // When indices reference out-of-bounds vertex data, the triangle is omitted.
                // If there aren't enough indices to make a triangle, then an empty vector will be
                // returned.
                let iterator = match indices {
                    Indices::U16(vec) => {
                        FourIterators::Third(vec.array_windows().enumerate().flat_map(
                            |(i, indices @ &[idx0, idx1, idx2])| {
                                if i % 2 == 0 {
                                    indices_to_triangle(vertices, indices)
                                } else {
                                    indices_to_triangle(vertices, &[idx1, idx0, idx2])
                                }
                            },
                        ))
                    }
                    Indices::U32(vec) => {
                        FourIterators::Fourth(vec.array_windows().enumerate().flat_map(
                            |(i, indices @ &[idx0, idx1, idx2])| {
                                if i % 2 == 0 {
                                    indices_to_triangle(vertices, indices)
                                } else {
                                    indices_to_triangle(vertices, &[idx1, idx0, idx2])
                                }
                            },
                        ))
                    }
                };

                Ok(iterator)
            }
            _ => Err(MeshTrianglesError::WrongTopology),
        }
    }

    /// Extracts the mesh vertex, index and morph target data for GPU upload.
    /// This function is called internally in render world extraction, it is
    /// unlikely to be useful outside of that context.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    pub fn take_gpu_data(&mut self) -> Result<Self, MeshAccessError> {
        let attributes = self.attributes.extract()?;
        let indices = self.indices.extract()?;
        #[cfg(feature = "morph")]
        let morph_targets = self.morph_targets.extract()?;
        #[cfg(feature = "morph")]
        let morph_target_names = self.morph_target_names.extract()?;

        // store the aabb extents as they cannot be computed after extraction
        if let Some(MeshAttributeData {
            values: VertexAttributeValues::Float32x3(position_values),
            ..
        }) = attributes
            .as_ref_option()?
            .and_then(|attrs| attrs.get(&Self::ATTRIBUTE_POSITION.id))
            && !position_values.is_empty()
        {
            let mut iter = position_values.iter().map(|p| Vec3::from_slice(p));
            let mut min = iter.next().unwrap();
            let mut max = min;
            for v in iter {
                min = Vec3::min(min, v);
                max = Vec3::max(max, v);
            }
            self.final_aabb = Some(Aabb3d::from_min_max(min, max));
        }

        Ok(Self {
            attributes,
            indices,
            #[cfg(feature = "morph")]
            morph_targets,
            #[cfg(feature = "morph")]
            morph_target_names,
            ..self.clone()
        })
    }

    /// Get this mesh's [`SkinnedMeshBounds`].
    pub fn skinned_mesh_bounds(&self) -> Option<&SkinnedMeshBounds> {
        self.skinned_mesh_bounds.as_ref()
    }

    /// Set this mesh's [`SkinnedMeshBounds`].
    pub fn set_skinned_mesh_bounds(&mut self, skinned_mesh_bounds: Option<SkinnedMeshBounds>) {
        self.skinned_mesh_bounds = skinned_mesh_bounds;
    }

    /// Consumes the mesh and returns a mesh with the given [`SkinnedMeshBounds`].
    pub fn with_skinned_mesh_bounds(
        mut self,
        skinned_mesh_bounds: Option<SkinnedMeshBounds>,
    ) -> Self {
        self.set_skinned_mesh_bounds(skinned_mesh_bounds);
        self
    }

    /// Generate [`SkinnedMeshBounds`] for this mesh.
    pub fn generate_skinned_mesh_bounds(&mut self) -> Result<(), SkinnedMeshBoundsError> {
        self.skinned_mesh_bounds = Some(SkinnedMeshBounds::from_mesh(self)?);
        Ok(())
    }

    /// Consumes the mesh and returns a mesh with generated [`SkinnedMeshBounds`].
    pub fn with_generated_skinned_mesh_bounds(mut self) -> Result<Self, SkinnedMeshBoundsError> {
        self.generate_skinned_mesh_bounds()?;
        Ok(self)
    }
}

#[cfg(feature = "morph")]
impl Mesh {
    /// Whether this mesh has morph targets.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_has_morph_targets`]
    pub fn has_morph_targets(&self) -> bool {
        self.try_has_morph_targets().expect(MESH_EXTRACTED_ERROR)
    }

    /// Whether this mesh has morph targets.
    pub fn try_has_morph_targets(&self) -> Result<bool, MeshAccessError> {
        Ok(self.morph_targets.as_ref_option()?.is_some())
    }

    /// Set the [morph target] displacements for this mesh.
    ///
    /// [morph target]: https://en.wikipedia.org/wiki/Morph_target_animation
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_set_morph_targets`]
    #[cfg(feature = "morph")]
    pub fn set_morph_targets(&mut self, morph_targets: Vec<MorphAttributes>) {
        self.try_set_morph_targets(morph_targets)
            .expect(MESH_EXTRACTED_ERROR);
    }

    /// Set the [morph target] displacements for this mesh.
    ///
    /// [morph targets]: https://en.wikipedia.org/wiki/Morph_target_animation
    #[cfg(feature = "morph")]
    pub fn try_set_morph_targets(
        &mut self,
        morph_targets: Vec<MorphAttributes>,
    ) -> Result<(), MeshAccessError> {
        self.morph_targets.replace(Some(morph_targets))?;
        Ok(())
    }

    /// Retrieve the morph target displacements for this mesh, or None if there
    /// are no morph targets.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_morph_targets`]
    #[cfg(feature = "morph")]
    pub fn morph_targets(&self) -> Option<&Vec<MorphAttributes>> {
        self.morph_targets
            .as_ref_option()
            .expect(MESH_EXTRACTED_ERROR)
    }

    /// Retrieve the morph displacements for this mesh, or None if there are no
    /// morph targets.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`or
    /// if the morph targets do not exist.
    #[cfg(feature = "morph")]
    pub fn try_morph_targets(&self) -> Result<&Vec<MorphAttributes>, MeshAccessError> {
        self.morph_targets.as_ref()
    }

    /// Consumes the mesh and returns a mesh with the given [morph target]
    /// displacements.
    ///
    /// (Alternatively, you can use [`Mesh::set_morph_targets`] to mutate an existing mesh in-place)
    ///
    /// [morph target]: https://en.wikipedia.org/wiki/Morph_target_animation
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_with_morph_targets`]
    #[must_use]
    #[cfg(feature = "morph")]
    pub fn with_morph_targets(mut self, morph_targets: Vec<MorphAttributes>) -> Self {
        self.set_morph_targets(morph_targets);
        self
    }

    /// Consumes the mesh and returns a mesh with the given [morph targets].
    ///
    /// (Alternatively, you can use [`Mesh::set_morph_targets`] to mutate an existing mesh in-place)
    ///
    /// [morph targets]: https://en.wikipedia.org/wiki/Morph_target_animation
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    #[cfg(feature = "morph")]
    pub fn try_with_morph_targets(
        mut self,
        morph_targets: Vec<MorphAttributes>,
    ) -> Result<Self, MeshAccessError> {
        self.try_set_morph_targets(morph_targets)?;
        Ok(self)
    }

    /// Sets the names of each morph target. This should correspond to the order of the morph targets in `set_morph_targets`.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_set_morph_target_names`]
    pub fn set_morph_target_names(&mut self, names: Vec<String>) {
        self.try_set_morph_target_names(names)
            .expect(MESH_EXTRACTED_ERROR);
    }

    /// Sets the names of each morph target. This should correspond to the order of the morph targets in `set_morph_targets`.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    pub fn try_set_morph_target_names(
        &mut self,
        names: Vec<String>,
    ) -> Result<(), MeshAccessError> {
        self.morph_target_names.replace(Some(names))?;
        Ok(())
    }

    /// Consumes the mesh and returns a mesh with morph target names.
    /// Names should correspond to the order of the morph targets in `set_morph_targets`.
    ///
    /// (Alternatively, you can use [`Mesh::set_morph_target_names`] to mutate an existing mesh in-place)
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_set_morph_target_names`]
    #[must_use]
    pub fn with_morph_target_names(self, names: Vec<String>) -> Self {
        self.try_with_morph_target_names(names)
            .expect(MESH_EXTRACTED_ERROR)
    }

    /// Consumes the mesh and returns a mesh with morph target names.
    /// Names should correspond to the order of the morph targets in `set_morph_targets`.
    ///
    /// (Alternatively, you can use [`Mesh::set_morph_target_names`] to mutate an existing mesh in-place)
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`.
    pub fn try_with_morph_target_names(
        mut self,
        names: Vec<String>,
    ) -> Result<Self, MeshAccessError> {
        self.try_set_morph_target_names(names)?;
        Ok(self)
    }

    /// Gets a list of all morph target names, if they exist.
    ///
    /// # Panics
    /// Panics when the mesh data has already been extracted to `RenderWorld`. To handle
    /// this as an error use [`Mesh::try_morph_target_names`]
    pub fn morph_target_names(&self) -> Option<&[String]> {
        self.try_morph_target_names().expect(MESH_EXTRACTED_ERROR)
    }

    /// Gets a list of all morph target names, if they exist.
    ///
    /// Returns an error if the mesh data has been extracted to `RenderWorld`or
    /// if the morph targets do not exist.
    pub fn try_morph_target_names(&self) -> Result<Option<&[String]>, MeshAccessError> {
        Ok(self
            .morph_target_names
            .as_ref_option()?
            .map(core::ops::Deref::deref))
    }
}

/// An enum to define which UV attribute to use for a texture.
///
/// It only supports two UV attributes, [`Mesh::ATTRIBUTE_UV_0`] and
/// [`Mesh::ATTRIBUTE_UV_1`].
/// The default is [`UvChannel::Uv0`].
#[derive(Reflect, Default, Debug, Clone, PartialEq, Eq)]
#[reflect(Default, Debug, Clone, PartialEq)]
pub enum UvChannel {
    #[default]
    Uv0,
    Uv1,
}

/// Correctly scales and renormalizes an already normalized `normal` by the scale determined by its reciprocal `scale_recip`
pub(crate) fn scale_normal(normal: Vec3, scale_recip: Vec3) -> Vec3 {
    // This is basically just `normal * scale_recip` but with the added rule that `0. * anything == 0.`
    // This is necessary because components of `scale_recip` may be infinities, which do not multiply to zero
    let n = Vec3::select(normal.cmpeq(Vec3::ZERO), Vec3::ZERO, normal * scale_recip);

    // If n is finite, no component of `scale_recip` was infinite or the normal was perpendicular to the scale
    // else the scale had at least one zero-component and the normal needs to point along the direction of that component
    if n.is_finite() {
        n.normalize_or_zero()
    } else {
        Vec3::select(n.abs().cmpeq(Vec3::INFINITY), n.signum(), Vec3::ZERO).normalize()
    }
}

impl core::ops::Mul<Mesh> for Transform {
    type Output = Mesh;

    fn mul(self, rhs: Mesh) -> Self::Output {
        rhs.transformed_by(self)
    }
}

/// A version of [`Mesh`] suitable for serializing for short-term transfer.
///
/// [`Mesh`] does not implement [`Serialize`] / [`Deserialize`] because it is made with the renderer in mind.
/// It is not a general-purpose mesh implementation, and its internals are subject to frequent change.
/// As such, storing a [`Mesh`] on disk is highly discouraged.
///
/// But there are still some valid use cases for serializing a [`Mesh`], namely transferring meshes between processes.
/// To support this, you can create a [`SerializedMesh`] from a [`Mesh`] with [`SerializedMesh::from_mesh`],
/// and then deserialize it with [`SerializedMesh::deserialize`]. The caveats are:
/// - The mesh representation is not valid across different versions of Bevy.
/// - This conversion is lossy. Only the following information is preserved:
///   - Primitive topology
///   - Vertex attributes
///   - Indices
/// - Custom attributes that were not specified with [`MeshDeserializer::add_custom_vertex_attribute`] will be ignored while deserializing.
#[cfg(feature = "serialize")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SerializedMesh {
    primitive_topology: PrimitiveTopology,
    attributes: Vec<(MeshVertexAttributeId, SerializedMeshAttributeData)>,
    indices: Option<Indices>,
}

#[cfg(feature = "serialize")]
impl SerializedMesh {
    /// Create a [`SerializedMesh`] from a [`Mesh`]. See the documentation for [`SerializedMesh`] for caveats.
    pub fn from_mesh(mut mesh: Mesh) -> Self {
        Self {
            primitive_topology: mesh.primitive_topology,
            attributes: mesh
                .attributes
                .replace(None)
                .expect(MESH_EXTRACTED_ERROR)
                .unwrap()
                .into_iter()
                .map(|(id, data)| {
                    (
                        id,
                        SerializedMeshAttributeData::from_mesh_attribute_data(data),
                    )
                })
                .collect(),
            indices: mesh.indices.replace(None).expect(MESH_EXTRACTED_ERROR),
        }
    }

    /// Create a [`Mesh`] from a [`SerializedMesh`]. See the documentation for [`SerializedMesh`] for caveats.
    ///
    /// Use [`MeshDeserializer`] if you need to pass extra options to the deserialization process, such as specifying custom vertex attributes.
    pub fn into_mesh(self) -> Mesh {
        MeshDeserializer::default().deserialize(self)
    }
}

/// Use to specify extra options when deserializing a [`SerializedMesh`] into a [`Mesh`].
#[cfg(feature = "serialize")]
pub struct MeshDeserializer {
    custom_vertex_attributes: HashMap<Box<str>, MeshVertexAttribute>,
}

#[cfg(feature = "serialize")]
impl Default for MeshDeserializer {
    fn default() -> Self {
        // Written like this so that the compiler can validate that we use all the built-in attributes.
        // If you just added a new attribute and got a compile error, please add it to this list :)
        const BUILTINS: [MeshVertexAttribute; Mesh::FIRST_AVAILABLE_CUSTOM_ATTRIBUTE as usize] = [
            Mesh::ATTRIBUTE_POSITION,
            Mesh::ATTRIBUTE_NORMAL,
            Mesh::ATTRIBUTE_UV_0,
            Mesh::ATTRIBUTE_UV_1,
            Mesh::ATTRIBUTE_TANGENT,
            Mesh::ATTRIBUTE_COLOR,
            Mesh::ATTRIBUTE_JOINT_WEIGHT,
            Mesh::ATTRIBUTE_JOINT_INDEX,
        ];
        Self {
            custom_vertex_attributes: BUILTINS
                .into_iter()
                .map(|attribute| (attribute.name.into(), attribute))
                .collect(),
        }
    }
}

#[cfg(feature = "serialize")]
impl MeshDeserializer {
    /// Create a new [`MeshDeserializer`].
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a custom vertex attribute to the deserializer. Custom vertex attributes that were not added with this method will be ignored while deserializing.
    pub fn add_custom_vertex_attribute(
        &mut self,
        name: &str,
        attribute: MeshVertexAttribute,
    ) -> &mut Self {
        self.custom_vertex_attributes.insert(name.into(), attribute);
        self
    }

    /// Deserialize a [`SerializedMesh`] into a [`Mesh`].
    ///
    /// See the documentation for [`SerializedMesh`] for caveats.
    pub fn deserialize(&self, serialized_mesh: SerializedMesh) -> Mesh {
        Mesh {
            attributes: MeshExtractableData::Data(
                serialized_mesh
                .attributes
                .into_iter()
                .filter_map(|(id, data)| {
                    let attribute = data.attribute.clone();
                    let Some(data) =
                        data.try_into_mesh_attribute_data(&self.custom_vertex_attributes)
                    else {
                        warn!(
                            "Deserialized mesh contains custom vertex attribute {attribute:?} that \
                            was not specified with `MeshDeserializer::add_custom_vertex_attribute`. Ignoring."
                        );
                        return None;
                    };
                    Some((id, data))
                })
                .collect()),
            indices: serialized_mesh.indices.into(),
            ..Mesh::new(serialized_mesh.primitive_topology, RenderAssetUsages::default())
        }
    }
}

/// Error that can occur when calling [`Mesh::merge_duplicate_vertices`]
#[derive(Error, Debug, Clone)]
pub enum MeshMergeDuplicateVerticesError {
    #[error("Index attribute already set.")]
    IndicesAlreadySet,
    #[error("Mesh access error: {0}")]
    MeshAccessError(#[from] MeshAccessError),
}

/// Error that can occur when calling [`Mesh::merge`].
#[derive(Error, Debug, Clone)]
pub enum MeshMergeError {
    #[error("Incompatible vertex attribute types: {} and {}", self_attribute.name, other_attribute.map(|a| a.name).unwrap_or("None"))]
    IncompatibleVertexAttributes {
        self_attribute: MeshVertexAttribute,
        other_attribute: Option<MeshVertexAttribute>,
    },
    #[error(
        "Incompatible primitive topologies: {:?} and {:?}",
        self_primitive_topology,
        other_primitive_topology
    )]
    IncompatiblePrimitiveTopology {
        self_primitive_topology: PrimitiveTopology,
        other_primitive_topology: PrimitiveTopology,
    },
    #[error("Mesh access error: {0}")]
    MeshAccessError(#[from] MeshAccessError),
}

#[cfg(test)]
mod tests {
    use super::Mesh;
    #[cfg(feature = "serialize")]
    use super::SerializedMesh;
    use crate::mesh::{Indices, MeshWindingInvertError, VertexAttributeValues};
    use crate::PrimitiveTopology;
    use bevy_asset::RenderAssetUsages;
    use bevy_math::bounding::Aabb3d;
    use bevy_math::primitives::Triangle3d;
    use bevy_math::Vec3;
    use bevy_transform::components::Transform;

    #[test]
    #[should_panic]
    fn panic_invalid_format() {
        let _mesh = Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        )
        .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, vec![[0.0, 0.0, 0.0]]);
    }

    #[test]
    fn transform_mesh() {
        let mesh = Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        )
        .with_inserted_attribute(
            Mesh::ATTRIBUTE_POSITION,
            vec![[-1., -1., 2.], [1., -1., 2.], [0., 1., 2.]],
        )
        .with_inserted_attribute(
            Mesh::ATTRIBUTE_NORMAL,
            vec![
                Vec3::new(-1., -1., 1.).normalize().to_array(),
                Vec3::new(1., -1., 1.).normalize().to_array(),
                [0., 0., 1.],
            ],
        )
        .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, vec![[0., 0.], [1., 0.], [0.5, 1.]]);

        let mesh = mesh.transformed_by(
            Transform::from_translation(Vec3::splat(-2.)).with_scale(Vec3::new(2., 0., -1.)),
        );

        if let Some(VertexAttributeValues::Float32x3(positions)) =
            mesh.attribute(Mesh::ATTRIBUTE_POSITION)
        {
            // All positions are first scaled resulting in `vec![[-2, 0., -2.], [2., 0., -2.], [0., 0., -2.]]`
            // and then shifted by `-2.` along each axis
            assert_eq!(
                positions,
                &vec![[-4.0, -2.0, -4.0], [0.0, -2.0, -4.0], [-2.0, -2.0, -4.0]]
            );
        } else {
            panic!("Mesh does not have a position attribute");
        }

        if let Some(VertexAttributeValues::Float32x3(normals)) =
            mesh.attribute(Mesh::ATTRIBUTE_NORMAL)
        {
            assert_eq!(normals, &vec![[0., -1., 0.], [0., -1., 0.], [0., 0., -1.]]);
        } else {
            panic!("Mesh does not have a normal attribute");
        }

        if let Some(VertexAttributeValues::Float32x2(uvs)) = mesh.attribute(Mesh::ATTRIBUTE_UV_0) {
            assert_eq!(uvs, &vec![[0., 0.], [1., 0.], [0.5, 1.]]);
        } else {
            panic!("Mesh does not have a uv attribute");
        }
    }

    #[test]
    fn point_list_mesh_invert_winding() {
        let mesh = Mesh::new(PrimitiveTopology::PointList, RenderAssetUsages::default())
            .with_inserted_indices(Indices::U32(vec![]));
        assert!(matches!(
            mesh.with_inverted_winding(),
            Err(MeshWindingInvertError::WrongTopology)
        ));
    }

    #[test]
    fn line_list_mesh_invert_winding() {
        let mesh = Mesh::new(PrimitiveTopology::LineList, RenderAssetUsages::default())
            .with_inserted_indices(Indices::U32(vec![0, 1, 1, 2, 2, 3]));
        let mesh = mesh.with_inverted_winding().unwrap();
        assert_eq!(
            mesh.indices().unwrap().iter().collect::<Vec<usize>>(),
            vec![3, 2, 2, 1, 1, 0]
        );
    }

    #[test]
    fn line_list_mesh_invert_winding_fail() {
        let mesh = Mesh::new(PrimitiveTopology::LineList, RenderAssetUsages::default())
            .with_inserted_indices(Indices::U32(vec![0, 1, 1]));
        assert!(matches!(
            mesh.with_inverted_winding(),
            Err(MeshWindingInvertError::AbruptIndicesEnd)
        ));
    }

    #[test]
    fn line_strip_mesh_invert_winding() {
        let mesh = Mesh::new(PrimitiveTopology::LineStrip, RenderAssetUsages::default())
            .with_inserted_indices(Indices::U32(vec![0, 1, 2, 3]));
        let mesh = mesh.with_inverted_winding().unwrap();
        assert_eq!(
            mesh.indices().unwrap().iter().collect::<Vec<usize>>(),
            vec![3, 2, 1, 0]
        );
    }

    #[test]
    fn triangle_list_mesh_invert_winding() {
        let mesh = Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        )
        .with_inserted_indices(Indices::U32(vec![
            0, 3, 1, // First triangle
            1, 3, 2, // Second triangle
        ]));
        let mesh = mesh.with_inverted_winding().unwrap();
        assert_eq!(
            mesh.indices().unwrap().iter().collect::<Vec<usize>>(),
            vec![
                0, 1, 3, // First triangle
                1, 2, 3, // Second triangle
            ]
        );
    }

    #[test]
    fn triangle_list_mesh_invert_winding_fail() {
        let mesh = Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        )
        .with_inserted_indices(Indices::U32(vec![0, 3, 1, 2]));
        assert!(matches!(
            mesh.with_inverted_winding(),
            Err(MeshWindingInvertError::AbruptIndicesEnd)
        ));
    }

    #[test]
    fn triangle_strip_mesh_invert_winding() {
        let mesh = Mesh::new(
            PrimitiveTopology::TriangleStrip,
            RenderAssetUsages::default(),
        )
        .with_inserted_indices(Indices::U32(vec![0, 1, 2, 3]));
        let mesh = mesh.with_inverted_winding().unwrap();
        assert_eq!(
            mesh.indices().unwrap().iter().collect::<Vec<usize>>(),
            vec![3, 2, 1, 0]
        );
    }

    #[test]
    fn compute_area_weighted_normals() {
        let mut mesh = Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        );

        //  z      y
        //  |    /
        //  3---2
        //  | /  \
        //  0-----1--x

        mesh.insert_attribute(
            Mesh::ATTRIBUTE_POSITION,
            vec![[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [0., 0., 1.]],
        );
        mesh.insert_indices(Indices::U16(vec![0, 1, 2, 0, 2, 3]));
        mesh.compute_area_weighted_normals();
        let normals = mesh
            .attribute(Mesh::ATTRIBUTE_NORMAL)
            .unwrap()
            .as_float3()
            .unwrap();
        assert_eq!(4, normals.len());
        // 0
        assert_eq!(Vec3::new(1., 0., 1.).normalize().to_array(), normals[0]);
        // 1
        assert_eq!([0., 0., 1.], normals[1]);
        // 2
        assert_eq!(Vec3::new(1., 0., 1.).normalize().to_array(), normals[2]);
        // 3
        assert_eq!([1., 0., 0.], normals[3]);
    }

    #[test]
    fn compute_area_weighted_normals_proportionate() {
        let mut mesh = Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        );

        //  z      y
        //  |    /
        //  3---2..
        //  | /    \
        //  0-------1---x

        mesh.insert_attribute(
            Mesh::ATTRIBUTE_POSITION,
            vec![[0., 0., 0.], [2., 0., 0.], [0., 1., 0.], [0., 0., 1.]],
        );
        mesh.insert_indices(Indices::U16(vec![0, 1, 2, 0, 2, 3]));
        mesh.compute_area_weighted_normals();
        let normals = mesh
            .attribute(Mesh::ATTRIBUTE_NORMAL)
            .unwrap()
            .as_float3()
            .unwrap();
        assert_eq!(4, normals.len());
        // 0
        assert_eq!(Vec3::new(1., 0., 2.).normalize().to_array(), normals[0]);
        // 1
        assert_eq!([0., 0., 1.], normals[1]);
        // 2
        assert_eq!(Vec3::new(1., 0., 2.).normalize().to_array(), normals[2]);
        // 3
        assert_eq!([1., 0., 0.], normals[3]);
    }

    #[test]
    fn compute_angle_weighted_normals() {
        // CuboidMeshBuilder duplicates vertices (even though it is indexed)

        //   5---------4
        //  /|        /|
        // 1-+-------0 |
        // | 6-------|-7
        // |/        |/
        // 2---------3
        let verts = vec![
            [1.0, 1.0, 1.0],
            [-1.0, 1.0, 1.0],
            [-1.0, -1.0, 1.0],
            [1.0, -1.0, 1.0],
            [1.0, 1.0, -1.0],
            [-1.0, 1.0, -1.0],
            [-1.0, -1.0, -1.0],
            [1.0, -1.0, -1.0],
        ];

        let indices = Indices::U16(vec![
            0, 1, 2, 2, 3, 0, // front
            5, 4, 7, 7, 6, 5, // back
            1, 5, 6, 6, 2, 1, // left
            4, 0, 3, 3, 7, 4, // right
            4, 5, 1, 1, 0, 4, // top
            3, 2, 6, 6, 7, 3, // bottom
        ]);
        let mut mesh = Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        );
        mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, verts);
        mesh.insert_indices(indices);
        mesh.compute_smooth_normals();

        let normals = mesh
            .attribute(Mesh::ATTRIBUTE_NORMAL)
            .unwrap()
            .as_float3()
            .unwrap();

        for new in normals.iter().copied().flatten() {
            // std impl is unstable
            const FRAC_1_SQRT_3: f32 = 0.57735026;
            const MIN: f32 = FRAC_1_SQRT_3 - f32::EPSILON;
            const MAX: f32 = FRAC_1_SQRT_3 + f32::EPSILON;
            assert!(new.abs() >= MIN, "{new} < {MIN}");
            assert!(new.abs() <= MAX, "{new} > {MAX}");
        }
    }

    #[test]
    fn triangles_from_triangle_list() {
        let mut mesh = Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        );
        mesh.insert_attribute(
            Mesh::ATTRIBUTE_POSITION,
            vec![[0., 0., 0.], [1., 0., 0.], [1., 1., 0.], [0., 1., 0.]],
        );
        mesh.insert_indices(Indices::U32(vec![0, 1, 2, 2, 3, 0]));
        assert_eq!(
            vec![
                Triangle3d {
                    vertices: [
                        Vec3::new(0., 0., 0.),
                        Vec3::new(1., 0., 0.),
                        Vec3::new(1., 1., 0.),
                    ]
                },
                Triangle3d {
                    vertices: [
                        Vec3::new(1., 1., 0.),
                        Vec3::new(0., 1., 0.),
                        Vec3::new(0., 0., 0.),
                    ]
                }
            ],
            mesh.triangles().unwrap().collect::<Vec<Triangle3d>>()
        );
    }

    #[test]
    fn triangles_from_triangle_strip() {
        let mut mesh = Mesh::new(
            PrimitiveTopology::TriangleStrip,
            RenderAssetUsages::default(),
        );
        // Triangles: (0, 1, 2), (2, 1, 3), (2, 3, 4), (4, 3, 5)
        //
        // 4 - 5
        // | \ |
        // 2 - 3
        // | \ |
        // 0 - 1
        let positions: Vec<Vec3> = [
            [0., 0., 0.],
            [1., 0., 0.],
            [0., 1., 0.],
            [1., 1., 0.],
            [0., 2., 0.],
            [1., 2., 0.],
        ]
        .into_iter()
        .map(Vec3::from_array)
        .collect();
        mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions.clone());
        mesh.insert_indices(Indices::U32(vec![0, 1, 2, 3, 4, 5]));
        assert_eq!(
            vec![
                Triangle3d {
                    vertices: [positions[0], positions[1], positions[2]]
                },
                Triangle3d {
                    vertices: [positions[2], positions[1], positions[3]]
                },
                Triangle3d {
                    vertices: [positions[2], positions[3], positions[4]]
                },
                Triangle3d {
                    vertices: [positions[4], positions[3], positions[5]]
                },
            ],
            mesh.triangles().unwrap().collect::<Vec<Triangle3d>>()
        );
    }

    #[test]
    fn take_gpu_data_calculates_aabb() {
        let mut mesh = Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        );
        mesh.insert_attribute(
            Mesh::ATTRIBUTE_POSITION,
            vec![
                [-0.5, 0., 0.],
                [-1., 0., 0.],
                [-1., -1., 0.],
                [-0.5, -1., 0.],
            ],
        );
        mesh.insert_indices(Indices::U32(vec![0, 1, 2, 2, 3, 0]));
        mesh = mesh.take_gpu_data().unwrap();
        assert_eq!(
            mesh.final_aabb,
            Some(Aabb3d::from_min_max([-1., -1., 0.], [-0.5, 0., 0.]))
        );
    }

    #[cfg(feature = "serialize")]
    #[test]
    fn serialize_deserialize_mesh() {
        let mut mesh = Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        );

        mesh.insert_attribute(
            Mesh::ATTRIBUTE_POSITION,
            vec![[0., 0., 0.], [2., 0., 0.], [0., 1., 0.], [0., 0., 1.]],
        );
        mesh.insert_indices(Indices::U16(vec![0, 1, 2, 0, 2, 3]));

        let serialized_mesh = SerializedMesh::from_mesh(mesh.clone());
        let serialized_string = serde_json::to_string(&serialized_mesh).unwrap();
        let serialized_mesh_from_string: SerializedMesh =
            serde_json::from_str(&serialized_string).unwrap();
        let deserialized_mesh = serialized_mesh_from_string.into_mesh();
        assert_eq!(mesh, deserialized_mesh);
    }

    #[test]
    fn merge_duplicate_vertices() {
        let mut mesh = Mesh::new(
            PrimitiveTopology::TriangleList,
            RenderAssetUsages::default(),
        );
        // Quad made of two triangles.
        let positions = vec![
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [1.0, 1.0, 0.0],
            // This will be deduplicated.
            [1.0, 1.0, 0.0],
            [0.0, 1.0, 0.0],
            // Position is equal to the first one but UV is different so it won't be deduplicated.
            [0.0, 0.0, 0.0],
        ];
        let uvs = vec![
            [0.0, 0.0],
            [1.0, 0.0],
            [1.0, 1.0],
            // This will be deduplicated.
            [1.0, 1.0],
            [0.0, 1.0],
            // Use different UV here so it won't be deduplicated.
            [0.0, 0.5],
        ];
        mesh.insert_attribute(
            Mesh::ATTRIBUTE_POSITION,
            VertexAttributeValues::Float32x3(positions.clone()),
        );
        mesh.insert_attribute(
            Mesh::ATTRIBUTE_UV_0,
            VertexAttributeValues::Float32x2(uvs.clone()),
        );

        let res = mesh.merge_duplicate_vertices();
        assert!(res.is_ok());
        assert_eq!(6, mesh.indices().unwrap().len());
        // Note we have 5 unique vertices, not 6.
        assert_eq!(5, mesh.attribute(Mesh::ATTRIBUTE_POSITION).unwrap().len());
        assert_eq!(5, mesh.attribute(Mesh::ATTRIBUTE_UV_0).unwrap().len());

        // Duplicate back.
        mesh.duplicate_vertices();
        assert!(mesh.indices().is_none());
        let VertexAttributeValues::Float32x3(new_positions) =
            mesh.attribute(Mesh::ATTRIBUTE_POSITION).unwrap()
        else {
            panic!("Unexpected attribute type")
        };
        let VertexAttributeValues::Float32x2(new_uvs) =
            mesh.attribute(Mesh::ATTRIBUTE_UV_0).unwrap()
        else {
            panic!("Unexpected attribute type")
        };
        assert_eq!(&positions, new_positions);
        assert_eq!(&uvs, new_uvs);
    }
}