draco-io 0.5.1

OBJ, PLY, STL and FBX mesh readers and writers for the Draco geometry model
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
//! PLY format reader for meshes and point clouds.
//!
//! Reads positions, triangle/polygon faces, normals, colors, and per-vertex
//! texture coordinates from ASCII and binary PLY files. Polygon faces are
//! triangulated with a fan.

use crate::raw_attribute::{make_f32x2_attribute, make_f32x3_attribute};
use crate::traits::finalize_mesh;
use byteorder::{BigEndian, LittleEndian, ReadBytesExt};
use std::fs;
use std::io::{self, Cursor, Write};
use std::path::Path;

use draco_core::draco_types::DataType;
use draco_core::geometry_attribute::{GeometryAttributeType, PointAttribute};
use draco_core::mesh::Mesh;

pub use crate::ply_format::PlyFormat;
use crate::traits::{PointCloudReader, ReadFromBytes, Reader};

#[derive(Debug)]
struct ParsedPlyColorData {
    num_components: u8,
    values: Vec<[u8; 4]>,
}

#[derive(Debug)]
struct ParsedPlyData {
    positions: ParsedPlyPositionData,
    faces: Vec<[u32; 3]>,
    normals: Option<Vec<[f32; 3]>>,
    colors: Option<ParsedPlyColorData>,
    texcoords: Option<Vec<[f32; 2]>>,
    generic: Vec<ParsedGenericProperty>,
}

/// One vertex property carried through as a generic attribute.
///
/// Values are held as `f64` whatever the file declared, which is exact for
/// every scalar type PLY has — the widest are `int32`, `uint32` and `float64`,
/// and `f64` represents all three without loss. The declared type is kept
/// beside them so the attribute is built in the file's own width rather than
/// widened to the one used for transport.
#[derive(Debug)]
struct ParsedGenericProperty {
    name: String,
    data_type: DataType,
    values: Vec<f64>,
}

#[derive(Debug)]
enum ParsedPlyPositionData {
    Float32(Vec<[f32; 3]>),
    Int32(Vec<[i32; 3]>),
}

impl ParsedPlyPositionData {
    fn len(&self) -> usize {
        match self {
            ParsedPlyPositionData::Float32(values) => values.len(),
            ParsedPlyPositionData::Int32(values) => values.len(),
        }
    }

    fn to_f32_positions(&self) -> Vec<[f32; 3]> {
        match self {
            ParsedPlyPositionData::Float32(values) => values.clone(),
            ParsedPlyPositionData::Int32(values) => values
                .iter()
                .map(|value| [value[0] as f32, value[1] as f32, value[2] as f32])
                .collect(),
        }
    }
}

#[derive(Debug, Clone)]
enum PlyPropertyKind {
    Scalar(DataType),
    List {
        count_type: DataType,
        item_type: DataType,
    },
}

#[derive(Debug, Clone)]
struct PlyPropertyDef {
    name: String,
    kind: PlyPropertyKind,
}

impl PlyPropertyDef {
    fn scalar_type(&self) -> Option<DataType> {
        match self.kind {
            PlyPropertyKind::Scalar(data_type) => Some(data_type),
            PlyPropertyKind::List { .. } => None,
        }
    }
}

#[derive(Debug, Clone)]
struct PlyHeader {
    format: PlyFormat,
    vertex_count: usize,
    face_count: usize,
    elements: Vec<PlyElementDef>,
    vertex_properties: Vec<PlyPropertyDef>,
    face_properties: Vec<PlyPropertyDef>,
}

#[derive(Debug, Clone)]
struct PlyElementDef {
    name: String,
    count: usize,
    properties: Vec<PlyPropertyDef>,
}

#[derive(Debug, Clone, Copy)]
struct PlyReadSchema {
    position_data_type: DataType,
    has_normals: bool,
    color_components: u8,
    texcoord_pair: Option<TexcoordPropertyPair>,
}

#[derive(Debug, Clone, Copy)]
struct TexcoordPropertyPair {
    u: &'static str,
    v: &'static str,
}

fn parse_ply_scalar_type(token: &str) -> Option<DataType> {
    match token {
        "char" | "int8" => Some(DataType::Int8),
        "uchar" | "uint8" => Some(DataType::Uint8),
        "short" | "int16" => Some(DataType::Int16),
        "ushort" | "uint16" => Some(DataType::Uint16),
        "int" | "int32" => Some(DataType::Int32),
        "uint" | "uint32" => Some(DataType::Uint32),
        "float" | "float32" => Some(DataType::Float32),
        "double" | "float64" => Some(DataType::Float64),
        _ => None,
    }
}

/// One thing a PLY file declares that a read does not carry into the mesh.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PlyDroppedItem {
    /// A vertex property with no attribute to land in.
    ///
    /// `data_type` is `None` for a list property, which the vertex element has
    /// no reading for at all.
    VertexProperty {
        /// The property name as the header spells it.
        name: String,
        /// The declared scalar type, or `None` for a list.
        data_type: Option<DataType>,
    },
    /// `nx`/`ny`/`nz` are declared, but not all three as `float32`, which is
    /// the only form the normal attribute is built from.
    Normals,
    /// A face property other than the corner-index list — per-corner texture
    /// coordinates, most often.
    FaceProperty {
        /// The property name as the header spells it.
        name: String,
    },
    /// A whole element other than `vertex` and `face`, skipped with everything
    /// declared on it.
    Element {
        /// The element name as the header spells it.
        name: String,
        /// How many of them the header declares.
        count: usize,
    },
}

impl std::fmt::Display for PlyDroppedItem {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PlyDroppedItem::VertexProperty { name, data_type } => match data_type {
                Some(data_type) => write!(
                    formatter,
                    "vertex property {name:?} ({data_type:?}) has no attribute to read it into"
                ),
                None => write!(
                    formatter,
                    "vertex property {name:?} is a list, which the vertex element has no reading for"
                ),
            },
            PlyDroppedItem::Normals => write!(
                formatter,
                "normals are declared but not as three float32 components, so they are not read"
            ),
            PlyDroppedItem::FaceProperty { name } => write!(
                formatter,
                "face property {name:?} is not the corner-index list and is skipped"
            ),
            PlyDroppedItem::Element { name, count } => write!(
                formatter,
                "element {name:?} and its {count} entries are skipped entirely"
            ),
        }
    }
}

/// What a read of a PLY file leaves behind.
///
/// The reader maps a fixed set of property names onto Draco's attribute types
/// and ignores the rest without failing, so a file whose payload lives in
/// custom per-vertex properties — a Gaussian-splat PLY, say, where everything
/// but the position sits in `f_dc_*`, `f_rest_*`, `opacity`, `scale_*` and
/// `rot_*` — reads back as a bare point cloud and reports no error. This says
/// what went missing.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PlyLossReport {
    dropped: Vec<PlyDroppedItem>,
}

impl PlyLossReport {
    /// Everything the read does not carry, in header declaration order.
    pub fn dropped(&self) -> &[PlyDroppedItem] {
        &self.dropped
    }

    /// Whether the read carries the file's whole declared content.
    pub fn is_lossless(&self) -> bool {
        self.dropped.is_empty()
    }
}

/// PLY format reader.
///
/// Reads vertex positions from ASCII and little-endian binary PLY files.
#[derive(Debug)]
pub struct PlyReader {
    source: PlyReaderSource,
    carry_generics: bool,
}

#[derive(Debug, Clone)]
enum PlyReaderSource {
    Path(std::path::PathBuf),
    Bytes(Vec<u8>),
}

impl PlyReader {
    /// Open a PLY file for reading.
    pub fn open<P: AsRef<Path>>(path: P) -> io::Result<Self> {
        let path = path.as_ref().to_path_buf();
        if !path.exists() {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                format!("File not found: {}", path.display()),
            ));
        }
        Ok(Self {
            source: PlyReaderSource::Path(path),
            carry_generics: false,
        })
    }

    /// Create a PLY reader from in-memory bytes.
    pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Self {
        Self {
            source: PlyReaderSource::Bytes(bytes.into()),
            carry_generics: false,
        }
    }

    /// Carry vertex properties with no attribute of their own as `Generic`
    /// attributes, one per property, named after the property.
    ///
    /// Off by default, because it changes what a read produces: a file with
    /// custom properties gains attributes that callers reading by index do not
    /// expect. On, a Gaussian-splat PLY arrives whole rather than as bare
    /// positions.
    ///
    /// Each attribute keeps the type the file declared, and its name is stored
    /// as a `"name"` entry in the attribute's metadata, which is the key
    /// upstream Draco writes and reads. List properties stay behind — an
    /// attribute has one width per point and a list does not — and remain in
    /// the loss report, which never names anything this carries.
    ///
    /// The writing half is
    /// [`PlyWriter::with_generic_attributes`](crate::PlyWriter::with_generic_attributes).
    pub fn with_generic_attributes(mut self, enabled: bool) -> Self {
        self.carry_generics = enabled;
        self
    }

    /// The mutable form of [`with_generic_attributes`](Self::with_generic_attributes).
    pub fn set_generic_attributes(&mut self, enabled: bool) -> &mut Self {
        self.carry_generics = enabled;
        self
    }

    /// Read a mesh directly from in-memory bytes.
    pub fn read_from_bytes(bytes: &[u8]) -> io::Result<Mesh> {
        let mut reader = Self::from_bytes(bytes.to_vec());
        reader.read_mesh()
    }

    /// Report what a read of this file would not carry into the mesh.
    ///
    /// Reads and validates the header only, so it answers for the same file a
    /// following [`read_mesh`](Self::read_mesh) would parse, and fails on the
    /// headers that one rejects.
    pub fn loss_report(&mut self) -> io::Result<PlyLossReport> {
        let bytes = match &self.source {
            PlyReaderSource::Path(path) => std::borrow::Cow::Owned(fs::read(path)?),
            PlyReaderSource::Bytes(bytes) => std::borrow::Cow::Borrowed(bytes.as_slice()),
        };
        let (header, _) = parse_ply_header(&bytes)?;
        let schema = build_read_schema(&header)?;
        let plan = GenericPlan::build(&header, &schema, self.carry_generics);
        Ok(build_loss_report(&header, &schema, !plan.is_empty()))
    }

    /// Read all positions from the PLY file.
    pub fn read_positions(&mut self) -> io::Result<Vec<[f32; 3]>> {
        Ok(read_ply_source(&self.source)?.positions.to_f32_positions())
    }

    /// Read a mesh with positions (and faces if present).
    pub fn read_mesh(&mut self) -> io::Result<Mesh> {
        Ok(self.read_mesh_reporting_loss()?.0)
    }

    /// Read a mesh, and what the read did not carry into it.
    ///
    /// The report answers for the bytes this mesh came from.
    /// [`loss_report`](Self::loss_report) parses on its own, so for a reader
    /// opened on a path the two calls can land either side of a write to that
    /// file; this one cannot.
    pub fn read_mesh_reporting_loss(&mut self) -> io::Result<(Mesh, PlyLossReport)> {
        let (parsed, report) = read_ply_source_reporting(&self.source, self.carry_generics)?;
        Ok((mesh_from_parsed(parsed)?, report))
    }
}

/// Build the mesh a parsed PLY describes.
///
/// Shared so that reading with a loss report and reading without one cannot
/// disagree about the mesh.
fn mesh_from_parsed(parsed: ParsedPlyData) -> io::Result<Mesh> {
    let mut mesh = Mesh::new();

    if parsed.positions.len() == 0 {
        return Ok(mesh);
    }

    mesh.set_num_points(parsed.positions.len());
    mesh.set_num_faces(parsed.faces.len());

    // Create position attribute
    match &parsed.positions {
        ParsedPlyPositionData::Float32(values) => {
            mesh.add_attribute(make_f32x3_attribute(
                GeometryAttributeType::Position,
                values,
            ));
        }
        ParsedPlyPositionData::Int32(values) => {
            mesh.add_attribute(make_i32x3_attribute(
                GeometryAttributeType::Position,
                values,
            ));
        }
    }

    if let Some(normals) = parsed.normals.as_ref() {
        mesh.add_attribute(make_f32x3_attribute(GeometryAttributeType::Normal, normals));
    }

    if let Some(colors) = parsed.colors.as_ref() {
        mesh.add_attribute(make_u8_attribute(
            GeometryAttributeType::Color,
            colors.num_components,
            true,
            &colors.values,
        ));
    }

    if let Some(texcoords) = parsed.texcoords.as_ref() {
        mesh.add_attribute(make_f32x2_attribute(
            GeometryAttributeType::TexCoord,
            texcoords,
        ));
    }

    for property in &parsed.generic {
        // A property short of a value for every point would make an attribute
        // whose tail is whatever the buffer was initialised to, which is worse
        // than not carrying it: the values would look real. The body reader
        // already fails on a truncated vertex, so this guards the case where a
        // header declares a property the body never supplies.
        if property.values.len() != mesh.num_points() {
            continue;
        }
        let attribute_id = mesh.add_attribute(make_generic_attribute(property));
        let unique_id = mesh.attribute(attribute_id).unique_id();
        let mut metadata = draco_core::metadata::Metadata::new();
        // `"name"` is upstream Draco's key for this: `obj_decoder.cc` writes it
        // onto a generic attribute and `obj_encoder.cc` reads it back.
        metadata
            .set_string("name", property.name.clone())
            .map_err(|error| invalid_ply(format!("Cannot name attribute: {error:?}")))?;
        mesh.metadata_or_insert()
            .set_attribute_metadata(unique_id, metadata);
    }

    for (i, face) in parsed.faces.iter().enumerate() {
        mesh.set_face(
            draco_core::geometry_indices::FaceIndex(i as u32),
            [
                draco_core::geometry_indices::PointIndex(face[0]),
                draco_core::geometry_indices::PointIndex(face[1]),
                draco_core::geometry_indices::PointIndex(face[2]),
            ],
        );
    }

    // Upstream's PLY reader guards this on there being faces at all: a
    // point cloud has nothing whose connectivity could change.
    if mesh.num_faces() > 0 {
        finalize_mesh(&mut mesh)?;
    }

    Ok(mesh)
}

impl Reader for PlyReader {
    fn open<P: AsRef<Path>>(path: P) -> io::Result<Self> {
        PlyReader::open(path)
    }

    fn read_meshes(&mut self) -> io::Result<Vec<Mesh>> {
        let m = self.read_mesh()?;
        Ok(vec![m])
    }
}

impl ReadFromBytes for PlyReader {
    fn from_bytes(bytes: &[u8]) -> io::Result<Self> {
        Ok(Self::from_bytes(bytes.to_vec()))
    }
}

impl PointCloudReader for PlyReader {
    fn read_points(&mut self) -> io::Result<Vec<[f32; 3]>> {
        self.read_positions()
    }
}

// ============================================================================
// Convenience Functions (for backward compatibility)
// ============================================================================

/// Parse point positions from an ASCII or binary little-endian PLY file.
/// Returns a vec of [x, y, z] positions.
pub fn read_ply_positions<P: AsRef<Path>>(path: P) -> io::Result<Vec<[f32; 3]>> {
    Ok(read_ply(path)?.positions.to_f32_positions())
}

/// Build a one-component `Generic` attribute in the type the file declared.
///
/// Values arrive as `f64`, which held every PLY scalar exactly on the way in,
/// and are narrowed here to the declared type. The narrowing is the file's own
/// width rather than a choice: a `uchar` property that came in as `uchar` goes
/// back out as one byte per point.
fn make_generic_attribute(property: &ParsedGenericProperty) -> PointAttribute {
    let mut attribute = PointAttribute::new();
    attribute.init(
        GeometryAttributeType::Generic,
        1,
        property.data_type,
        false,
        property.values.len(),
    );

    let buffer = attribute.buffer_mut();
    let width = property.data_type.byte_length();
    for (index, value) in property.values.iter().enumerate() {
        let value = *value;
        let bytes: [u8; 8] = match property.data_type {
            DataType::Int8 => pad(&(value as i8).to_le_bytes()),
            DataType::Uint8 => pad(&(value as u8).to_le_bytes()),
            DataType::Int16 => pad(&(value as i16).to_le_bytes()),
            DataType::Uint16 => pad(&(value as u16).to_le_bytes()),
            DataType::Int32 => pad(&(value as i32).to_le_bytes()),
            DataType::Uint32 => pad(&(value as u32).to_le_bytes()),
            DataType::Float64 => value.to_le_bytes(),
            // Float32 and anything a header could not have declared.
            _ => pad(&(value as f32).to_le_bytes()),
        };
        buffer.write(index * width, &bytes[..width]);
    }
    attribute
}

/// Widen a little-endian encoding to eight bytes so one array type serves every
/// branch above; only the declared width is ever written.
fn pad(bytes: &[u8]) -> [u8; 8] {
    let mut padded = [0u8; 8];
    padded[..bytes.len()].copy_from_slice(bytes);
    padded
}

fn make_i32x3_attribute(
    attribute_type: GeometryAttributeType,
    values: &[[i32; 3]],
) -> PointAttribute {
    let mut attribute = PointAttribute::new();
    attribute.init(attribute_type, 3, DataType::Int32, false, values.len());

    let buffer = attribute.buffer_mut();
    for (i, value) in values.iter().enumerate() {
        let bytes: Vec<u8> = value
            .iter()
            .flat_map(|component| component.to_le_bytes())
            .collect();
        buffer.write(i * 12, &bytes);
    }

    attribute
}

fn make_u8_attribute(
    attribute_type: GeometryAttributeType,
    num_components: u8,
    normalized: bool,
    values: &[[u8; 4]],
) -> PointAttribute {
    let mut attribute = PointAttribute::new();
    attribute.init(
        attribute_type,
        num_components,
        DataType::Uint8,
        normalized,
        values.len(),
    );

    let buffer = attribute.buffer_mut();
    for (i, value) in values.iter().enumerate() {
        let end = num_components as usize;
        buffer.write(i * end, &value[..end]);
    }

    attribute
}

fn invalid_ply(message: impl Into<String>) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, message.into())
}

fn parse_ply_property(parts: &[&str]) -> io::Result<PlyPropertyDef> {
    if parts.len() < 3 {
        return Err(invalid_ply("Malformed property declaration"));
    }

    if parts[1] == "list" {
        if parts.len() < 5 {
            return Err(invalid_ply("Malformed list property declaration"));
        }
        let count_type = parse_ply_scalar_type(parts[2])
            .ok_or_else(|| invalid_ply(format!("Unsupported PLY scalar type: {}", parts[2])))?;
        let item_type = parse_ply_scalar_type(parts[3])
            .ok_or_else(|| invalid_ply(format!("Unsupported PLY scalar type: {}", parts[3])))?;
        Ok(PlyPropertyDef {
            name: parts[4].to_string(),
            kind: PlyPropertyKind::List {
                count_type,
                item_type,
            },
        })
    } else {
        let data_type = parse_ply_scalar_type(parts[1])
            .ok_or_else(|| invalid_ply(format!("Unsupported PLY scalar type: {}", parts[1])))?;
        Ok(PlyPropertyDef {
            name: parts[2].to_string(),
            kind: PlyPropertyKind::Scalar(data_type),
        })
    }
}

fn parse_ply_header(bytes: &[u8]) -> io::Result<(PlyHeader, usize)> {
    if bytes.is_empty() {
        return Err(invalid_ply("Empty PLY file"));
    }

    let mut body_offset = None;
    let mut offset = 0usize;
    while offset < bytes.len() {
        let line_end = bytes[offset..]
            .iter()
            .position(|byte| matches!(*byte, b'\n' | b'\r'))
            .map(|idx| offset + idx);
        match line_end {
            Some(end) => {
                let line_bytes = &bytes[offset..end];
                let line = std::str::from_utf8(line_bytes)
                    .map_err(|_| invalid_ply("PLY header must be valid UTF-8/ASCII"))?;
                offset = end + 1;
                if bytes[end] == b'\r' && bytes.get(offset) == Some(&b'\n') {
                    offset += 1;
                }
                if line.trim() == "end_header" {
                    body_offset = Some(offset);
                    break;
                }
            }
            None => {
                let line = std::str::from_utf8(&bytes[offset..])
                    .map_err(|_| invalid_ply("PLY header must be valid UTF-8/ASCII"))?;
                if line.trim() == "end_header" {
                    body_offset = Some(bytes.len());
                    break;
                }
                break;
            }
        }
    }

    let body_offset = body_offset.ok_or_else(|| invalid_ply("No end_header found"))?;
    let header_text = std::str::from_utf8(&bytes[..body_offset])
        .map_err(|_| invalid_ply("PLY header must be valid UTF-8/ASCII"))?;

    // PLY writers in the wild use LF, CRLF, and (notably Rhino) CR-only
    // header lines. `str::lines` does not split CR-only input.
    let mut lines = header_text.split(['\n', '\r']);
    let first_line = lines.next().ok_or_else(|| invalid_ply("Empty PLY file"))?;
    if first_line.trim() != "ply" {
        return Err(invalid_ply("Missing PLY header"));
    }

    let mut format = None;
    let mut vertex_count = 0usize;
    let mut face_count = 0usize;
    let mut elements: Vec<PlyElementDef> = Vec::new();

    for line in lines {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed == "end_header" {
            continue;
        }

        let parts: Vec<&str> = trimmed.split_whitespace().collect();
        if parts.is_empty() {
            continue;
        }

        match parts[0] {
            "comment" | "obj_info" => {}
            "format" => {
                if parts.len() < 2 {
                    return Err(invalid_ply("Malformed format declaration"));
                }
                format = Some(match parts[1] {
                    "ascii" => PlyFormat::Ascii,
                    "binary_little_endian" => PlyFormat::BinaryLittleEndian,
                    "binary_big_endian" => PlyFormat::BinaryBigEndian,
                    other => {
                        return Err(invalid_ply(format!("Unsupported PLY format: {other}")));
                    }
                });
            }
            "element" => {
                if parts.len() < 3 {
                    return Err(invalid_ply("Malformed element declaration"));
                }
                let count = parts[2]
                    .parse()
                    .map_err(|_| invalid_ply("Invalid element count"))?;
                elements.push(PlyElementDef {
                    name: parts[1].to_string(),
                    count,
                    properties: Vec::new(),
                });
                match parts[1] {
                    "vertex" => {
                        vertex_count = count;
                    }
                    "face" => {
                        face_count = count;
                    }
                    _ => {}
                }
            }
            "property" => {
                let property = parse_ply_property(&parts)?;
                let Some(element) = elements.last_mut() else {
                    return Err(invalid_ply("Property declared before element"));
                };
                element.properties.push(property);
            }
            _ => {}
        }
    }

    let mut vertex_properties = Vec::new();
    let mut face_properties = Vec::new();
    for element in &elements {
        match element.name.as_str() {
            "vertex" => vertex_properties = element.properties.clone(),
            "face" => face_properties = element.properties.clone(),
            _ => {}
        }
    }

    Ok((
        PlyHeader {
            format: format.ok_or_else(|| invalid_ply("Missing PLY format declaration"))?,
            vertex_count,
            face_count,
            elements,
            vertex_properties,
            face_properties,
        },
        body_offset,
    ))
}

/// Consumes `count` lines, stopping at the end of the text.
///
/// The count comes from an `element` header line, so it is file-controlled and
/// unrelated to how many lines actually follow: a 130-byte file declaring four
/// billion elements spun this loop for seven seconds before the reader had read
/// a single vertex. Stopping when the iterator is exhausted makes the work
/// proportional to the file rather than to a number printed in it.
fn skip_ascii_element_lines(lines: &mut std::str::Lines<'_>, count: usize) {
    for _ in 0..count {
        if lines.next().is_none() {
            return;
        }
    }
}

fn ascii_scalar_token_count(data_type: DataType) -> usize {
    if data_type == DataType::Invalid {
        0
    } else {
        1
    }
}

fn split_ascii_vertex_lines<'a>(
    header: &PlyHeader,
    body_text: &'a str,
) -> io::Result<(Vec<&'a str>, Vec<&'a str>)> {
    let mut lines = body_text.lines();
    let mut vertex_lines = Vec::new();
    let mut face_lines = Vec::new();

    for element in &header.elements {
        match element.name.as_str() {
            // Each `count` comes from the header and is unrelated to how many
            // lines follow, so the loop has to end with the text rather than
            // with the number: a file declaring four billion elements spun here
            // for seconds without a body to match.
            "vertex" => {
                for _ in 0..element.count {
                    let Some(line) = lines.next() else { break };
                    vertex_lines.push(line);
                }
            }
            "face" => {
                for _ in 0..element.count {
                    let Some(line) = lines.next() else { break };
                    face_lines.push(line);
                }
            }
            _ => skip_ascii_element_lines(&mut lines, element.count),
        }
    }

    Ok((vertex_lines, face_lines))
}

fn position_data_type_for_scalar(data_type: DataType) -> DataType {
    match data_type {
        DataType::Int32 => DataType::Int32,
        _ => DataType::Float32,
    }
}

fn scalar_property_type(header: &PlyHeader, name: &str) -> Option<DataType> {
    header.vertex_properties.iter().find_map(|property| {
        (property.name == name)
            .then(|| property.scalar_type())
            .flatten()
    })
}

/// The texture-coordinate pair a file carries, if it carries one.
///
/// A pair counts only when both halves are declared and both are `float`.
/// Anything short of that is not a malformed texture coordinate but an
/// ordinary property that happens to share a name -- carried as a generic
/// attribute when asked, reported as dropped otherwise. The PLY format gives
/// these names no meaning; upstream Draco reads no texture coordinates from a
/// PLY at all; and a lone `t` is as often a timestamp as half of anything.
/// Refusing the file over it, as this once did, turned away a valid file that
/// both upstream and `plyfile` read.
///
/// When more than one spelling is complete, the first in this order wins, and
/// the others are ordinary properties too.
fn detect_texcoord_pair(header: &PlyHeader) -> Option<TexcoordPropertyPair> {
    const PAIRS: [TexcoordPropertyPair; 3] = [
        TexcoordPropertyPair {
            u: "texture_u",
            v: "texture_v",
        },
        TexcoordPropertyPair { u: "u", v: "v" },
        TexcoordPropertyPair { u: "s", v: "t" },
    ];

    PAIRS.into_iter().find(|pair| {
        scalar_property_type(header, pair.u) == Some(DataType::Float32)
            && scalar_property_type(header, pair.v) == Some(DataType::Float32)
    })
}

fn build_read_schema(header: &PlyHeader) -> io::Result<PlyReadSchema> {
    let mut has_x = false;
    let mut has_y = false;
    let mut has_z = false;
    let mut position_data_type = DataType::Float32;
    let mut prop_nx_type = None;
    let mut prop_ny_type = None;
    let mut prop_nz_type = None;
    let mut prop_r_type = None;
    let mut prop_g_type = None;
    let mut prop_b_type = None;
    let mut prop_a_type = None;

    for property in &header.vertex_properties {
        let Some(data_type) = property.scalar_type() else {
            continue;
        };

        match property.name.as_str() {
            "x" => {
                has_x = true;
                position_data_type = position_data_type_for_scalar(data_type);
            }
            "y" => {
                has_y = true;
                position_data_type = position_data_type_for_scalar(data_type);
            }
            "z" => {
                has_z = true;
                position_data_type = position_data_type_for_scalar(data_type);
            }
            "nx" => prop_nx_type = Some(data_type),
            "ny" => prop_ny_type = Some(data_type),
            "nz" => prop_nz_type = Some(data_type),
            "red" => prop_r_type = Some(data_type),
            "green" => prop_g_type = Some(data_type),
            "blue" => prop_b_type = Some(data_type),
            "alpha" => prop_a_type = Some(data_type),
            _ => {}
        }
    }

    if !has_x {
        return Err(invalid_ply("No x property"));
    }
    if !has_y {
        return Err(invalid_ply("No y property"));
    }
    if !has_z {
        return Err(invalid_ply("No z property"));
    }

    let has_normals = prop_nx_type == Some(DataType::Float32)
        && prop_ny_type == Some(DataType::Float32)
        && prop_nz_type == Some(DataType::Float32);

    let color_types = [prop_r_type, prop_g_type, prop_b_type, prop_a_type];
    let color_components = color_types.iter().flatten().count() as u8;
    if color_components > 0 {
        for color_type in color_types.into_iter().flatten() {
            if color_type != DataType::Uint8 {
                return Err(invalid_ply("Color properties must be uint8"));
            }
        }
    }

    Ok(PlyReadSchema {
        position_data_type,
        has_normals,
        color_components,
        texcoord_pair: detect_texcoord_pair(header),
    })
}

/// Diff what the header declares against what the schema reads.
///
/// The two have to be derived from one header: the schema is what decides
/// whether a declared property is consumed or ignored, so asking the names
/// alone would call a non-`float32` `nx` supported and a second texture
/// coordinate pair read.
const NORMAL_NAMES: [&str; 3] = ["nx", "ny", "nz"];
const COLOR_NAMES: [&str; 4] = ["red", "green", "blue", "alpha"];

/// Whether a read takes this vertex property into a built-in attribute.
///
/// One answer for three callers that must not disagree: the body readers,
/// which carry a property as a generic attribute only when nothing else
/// claimed it; the loss report, which must not name a property that was read;
/// and the schema, whose match arms this mirrors. Keeping it in one place is
/// what stops a spelling learned in one of them from being missed by another.
fn consumes_vertex_property(schema: &PlyReadSchema, name: &str) -> bool {
    matches!(name, "x" | "y" | "z")
        || NORMAL_NAMES.contains(&name)
        || COLOR_NAMES.contains(&name)
        || schema
            .texcoord_pair
            .is_some_and(|pair| name == pair.u || name == pair.v)
}

/// Which vertex properties a read carries through as generic attributes.
///
/// Built once per file from the header and the schema, so the two body readers
/// and the attribute builder all agree on the set and its order without each
/// re-deriving it.
#[derive(Debug, Default)]
struct GenericPlan {
    /// Header property index -> column, for the properties being carried.
    columns: Vec<Option<usize>>,
    /// Name and declared type per column, in header order.
    properties: Vec<(String, DataType)>,
}

impl GenericPlan {
    /// Empty when the option is off, so the body readers pay nothing for it.
    fn build(header: &PlyHeader, schema: &PlyReadSchema, enabled: bool) -> Self {
        let mut plan = Self::default();
        if !enabled {
            return plan;
        }
        plan.columns = vec![None; header.vertex_properties.len()];
        for (index, property) in header.vertex_properties.iter().enumerate() {
            // A list has no fixed width, so it cannot become an attribute and
            // stays in the loss report instead.
            let Some(data_type) = property.scalar_type() else {
                continue;
            };
            if consumes_vertex_property(schema, &property.name) {
                continue;
            }
            plan.columns[index] = Some(plan.properties.len());
            plan.properties.push((property.name.clone(), data_type));
        }
        plan
    }

    fn column_for(&self, property_index: usize) -> Option<usize> {
        self.columns.get(property_index).copied().flatten()
    }

    fn is_empty(&self) -> bool {
        self.properties.is_empty()
    }

    /// Fresh per-column accumulators sized for the vertices expected.
    fn new_values(&self, capacity: usize) -> Vec<Vec<f64>> {
        self.properties
            .iter()
            .map(|_| Vec::with_capacity(capacity))
            .collect()
    }

    /// Pair the accumulated columns with their names and declared types.
    fn finish(&self, values: Vec<Vec<f64>>) -> Vec<ParsedGenericProperty> {
        self.properties
            .iter()
            .zip(values)
            .map(|((name, data_type), values)| ParsedGenericProperty {
                name: name.clone(),
                data_type: *data_type,
                values,
            })
            .collect()
    }
}

fn build_loss_report(
    header: &PlyHeader,
    schema: &PlyReadSchema,
    carried_generics: bool,
) -> PlyLossReport {
    let mut dropped = Vec::new();

    let declares_normals = header
        .vertex_properties
        .iter()
        .any(|property| NORMAL_NAMES.contains(&property.name.as_str()));
    if declares_normals && !schema.has_normals {
        dropped.push(PlyDroppedItem::Normals);
    }

    for property in &header.vertex_properties {
        let name = property.name.as_str();
        let consumed = consumes_vertex_property(schema, name);
        // A property carried into a generic attribute is not lost, so naming it
        // here would name a non-problem -- and a report that does that stops
        // being read. Lists are the exception: an attribute has one width and
        // a list does not, so they are dropped whatever the option says.
        let carried = carried_generics && property.scalar_type().is_some();
        if !consumed && !carried {
            dropped.push(PlyDroppedItem::VertexProperty {
                name: property.name.clone(),
                data_type: property.scalar_type(),
            });
        }
    }

    let face_index = face_index_property(&header.face_properties);
    for (index, property) in header.face_properties.iter().enumerate() {
        if Some(index) != face_index {
            dropped.push(PlyDroppedItem::FaceProperty {
                name: property.name.clone(),
            });
        }
    }

    for element in &header.elements {
        if !matches!(element.name.as_str(), "vertex" | "face") {
            dropped.push(PlyDroppedItem::Element {
                name: element.name.clone(),
                count: element.count,
            });
        }
    }

    PlyLossReport { dropped }
}

fn triangulate_vertex_indices(indices: &[u32], faces: &mut Vec<[u32; 3]>) {
    if indices.len() < 3 {
        return;
    }

    for j in 1..indices.len() - 1 {
        faces.push([indices[0], indices[j], indices[j + 1]]);
    }
}

/// Which face property carries the polygon's corner indices.
///
/// `vertex_indices` when the file names it, and otherwise the first list on the
/// element, which is what a file spelling it `vertex_index` leaves behind. Every
/// other list there describes the face rather than being it — per-corner
/// texture coordinates, most often, which Draco's own encoder writes next to the
/// indices — so it is skipped whatever scalar type it declares. Choosing the
/// property before the values are read is the point: reading each list in turn
/// and keeping the first one made the choice depend on the declaration order,
/// and made a float list next to the indices a parse error.
fn face_index_property(properties: &[PlyPropertyDef]) -> Option<usize> {
    let lists = || {
        properties
            .iter()
            .enumerate()
            .filter(|(_, property)| matches!(property.kind, PlyPropertyKind::List { .. }))
    };
    lists()
        .find(|(_, property)| property.name == "vertex_indices")
        .or_else(|| lists().next())
        .map(|(index, _)| index)
}

fn parse_ascii_face_line(
    header: &PlyHeader,
    line: &str,
    faces: &mut Vec<[u32; 3]>,
) -> io::Result<()> {
    let parts: Vec<&str> = line.split_whitespace().collect();
    if parts.is_empty() {
        return Ok(());
    }

    if header.face_properties.is_empty() {
        let indices: Vec<u32> = parts
            .iter()
            .map(|part| {
                part.parse::<u32>()
                    .map_err(|_| invalid_ply("Bad face index value"))
            })
            .collect::<io::Result<Vec<u32>>>()?;

        if indices.is_empty() {
            return Ok(());
        }

        let polygon_size = indices[0] as usize;
        // `polygon_size` is a file-controlled `u32`, and `usize` is 32 bits on
        // the wasm32 target this ships to, where the leading count's own slot
        // pushes it past the end.
        let Some(end) = polygon_size.checked_add(1) else {
            return Ok(());
        };
        if polygon_size < 3 || indices.len() < end {
            return Ok(());
        }

        triangulate_vertex_indices(&indices[1..end], faces);
        return Ok(());
    }

    let index_property = face_index_property(&header.face_properties);
    let mut cursor = 0usize;
    let mut polygon_indices: Option<Vec<u32>> = None;

    for (position, property) in header.face_properties.iter().enumerate() {
        match property.kind {
            PlyPropertyKind::Scalar(_) => {
                if cursor >= parts.len() {
                    return Ok(());
                }
                cursor += 1;
            }
            PlyPropertyKind::List { .. } => {
                if cursor >= parts.len() {
                    return Ok(());
                }
                let count: usize = parts[cursor]
                    .parse()
                    .map_err(|_| invalid_ply("Bad face list size"))?;
                cursor += 1;
                // The count is whatever the line says. Added to the cursor it
                // leaves `usize` -- and the sum, having wrapped, then passes
                // for a length this line does hold.
                let Some(end) = cursor.checked_add(count) else {
                    return Ok(());
                };
                if parts.len() < end {
                    return Ok(());
                }

                if index_property == Some(position) {
                    polygon_indices = Some(
                        parts[cursor..end]
                            .iter()
                            .map(|part| {
                                part.parse::<u32>()
                                    .map_err(|_| invalid_ply("Bad face index value"))
                            })
                            .collect::<io::Result<Vec<u32>>>()?,
                    );
                }
                cursor = end;
            }
        }
    }

    if let Some(indices) = polygon_indices {
        triangulate_vertex_indices(&indices, faces);
    }

    Ok(())
}

fn parse_ascii_f32(token: &str, label: &str) -> io::Result<f32> {
    token
        .parse()
        .map_err(|_| invalid_ply(format!("Bad {label} value")))
}

/// Parse a carried property's value.
///
/// `f64` for every declared type: it represents `int32`, `uint32` and
/// `float64` exactly, and those are the widest PLY has, so the transport is
/// lossless whatever the attribute is later built as.
fn parse_ascii_f64(token: &str, label: &str) -> io::Result<f64> {
    token
        .parse()
        .map_err(|_| invalid_ply(format!("Bad {label} value")))
}

fn parse_ascii_i32(token: &str, label: &str) -> io::Result<i32> {
    token
        .parse()
        .map_err(|_| invalid_ply(format!("Bad {label} value")))
}

fn parse_ascii_u8(token: &str) -> io::Result<u8> {
    token
        .parse()
        .map_err(|_| invalid_ply("Bad color component value"))
}

/// A capacity to reserve for `declared` items, given that the body left to read
/// is `available_bytes` long and each item costs at least `min_bytes_per_item`.
///
/// The counts in a PLY header are file-controlled and unrelated to what
/// follows: a 130-byte file may declare four billion vertices, and reserving
/// from that number alone asks for tens of gigabytes before a single body byte
/// has been read. Reserving from what the body could actually hold keeps the
/// fast path - a well-formed file reserves exactly its own count - while a
/// header that outruns its body reserves what the body can support and then
/// fails on the missing data, which is where it should fail.
fn body_bounded_capacity(
    declared: usize,
    available_bytes: usize,
    min_bytes_per_item: usize,
) -> usize {
    declared.min(available_bytes / min_bytes_per_item.max(1))
}

fn read_ply_ascii_body(
    header: &PlyHeader,
    schema: &PlyReadSchema,
    generic_plan: &GenericPlan,
    body: &[u8],
) -> io::Result<ParsedPlyData> {
    let body_text = std::str::from_utf8(body)
        .map_err(|_| invalid_ply("ASCII PLY payload must be valid UTF-8/ASCII"))?;
    let (vertex_lines, face_lines) = split_ascii_vertex_lines(header, body_text)?;
    // The lines have already been split, so the exact count is known here and
    // the declared one is only an upper bound on it.
    let vertex_capacity = header.vertex_count.min(vertex_lines.len());

    let mut float_positions = matches!(schema.position_data_type, DataType::Float32)
        .then(|| Vec::with_capacity(vertex_capacity));
    let mut int_positions = matches!(schema.position_data_type, DataType::Int32)
        .then(|| Vec::with_capacity(vertex_capacity));
    let mut normals = schema
        .has_normals
        .then(|| Vec::with_capacity(vertex_capacity));
    let mut colors = (schema.color_components > 0).then(|| ParsedPlyColorData {
        num_components: schema.color_components,
        values: Vec::with_capacity(vertex_capacity),
    });
    let mut texcoords = schema
        .texcoord_pair
        .is_some()
        .then(|| Vec::with_capacity(vertex_capacity));
    let mut generic_values = generic_plan.new_values(vertex_capacity);

    for line in vertex_lines {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }

        let parts: Vec<&str> = trimmed.split_whitespace().collect();
        let mut float_position = [0.0f32; 3];
        let mut int_position = [0i32; 3];
        let mut normal = [0.0f32; 3];
        let mut color = [0u8; 4];
        let mut texcoord = [0.0f32; 2];
        let mut color_component = 0usize;
        let mut cursor = 0usize;

        for (property_index, property) in header.vertex_properties.iter().enumerate() {
            let Some(data_type) = property.scalar_type() else {
                if cursor >= parts.len() {
                    break;
                }
                let count: usize = parts[cursor]
                    .parse()
                    .map_err(|_| invalid_ply("Bad vertex list size"))?;
                cursor = cursor
                    .checked_add(1 + count)
                    .ok_or_else(|| invalid_ply("ASCII PLY line is too large"))?;
                continue;
            };
            if cursor >= parts.len() {
                break;
            }
            let token = parts[cursor];
            cursor += ascii_scalar_token_count(data_type);

            match property.name.as_str() {
                "x" => match schema.position_data_type {
                    DataType::Int32 => int_position[0] = parse_ascii_i32(token, "x")?,
                    _ => float_position[0] = parse_ascii_f32(token, "x")?,
                },
                "y" => match schema.position_data_type {
                    DataType::Int32 => int_position[1] = parse_ascii_i32(token, "y")?,
                    _ => float_position[1] = parse_ascii_f32(token, "y")?,
                },
                "z" => match schema.position_data_type {
                    DataType::Int32 => int_position[2] = parse_ascii_i32(token, "z")?,
                    _ => float_position[2] = parse_ascii_f32(token, "z")?,
                },
                "nx" if schema.has_normals => normal[0] = parse_ascii_f32(token, "nx")?,
                "ny" if schema.has_normals => normal[1] = parse_ascii_f32(token, "ny")?,
                "nz" if schema.has_normals => normal[2] = parse_ascii_f32(token, "nz")?,
                // A header may name more colour properties than a colour has
                // channels - the same one twice, say - and the count comes from
                // the file. Extra channels are read and dropped rather than
                // written past the end of the array.
                "red" | "green" | "blue" | "alpha" if schema.color_components > 0 => {
                    let value = parse_ascii_u8(token)?;
                    if let Some(slot) = color.get_mut(color_component) {
                        *slot = value;
                    }
                    color_component += 1;
                }
                name if schema.texcoord_pair.is_some_and(|pair| name == pair.u) => {
                    texcoord[0] = parse_ascii_f32(token, name)?;
                }
                name if schema.texcoord_pair.is_some_and(|pair| name == pair.v) => {
                    texcoord[1] = parse_ascii_f32(token, name)?;
                }
                name => {
                    if let Some(column) = generic_plan.column_for(property_index) {
                        generic_values[column].push(parse_ascii_f64(token, name)?);
                    }
                }
            }
        }

        match schema.position_data_type {
            DataType::Int32 => int_positions.as_mut().unwrap().push(int_position),
            _ => float_positions.as_mut().unwrap().push(float_position),
        }

        if let Some(normals) = normals.as_mut() {
            normals.push(normal);
        }

        if let Some(colors) = colors.as_mut() {
            colors.values.push(color);
        }

        if let Some(texcoords) = texcoords.as_mut() {
            texcoords.push(texcoord);
        }
    }

    let mut faces = Vec::with_capacity(header.face_count.min(face_lines.len()));
    for line in face_lines {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        parse_ascii_face_line(header, trimmed, &mut faces)?;
    }

    Ok(ParsedPlyData {
        positions: match schema.position_data_type {
            DataType::Int32 => ParsedPlyPositionData::Int32(int_positions.unwrap_or_default()),
            _ => ParsedPlyPositionData::Float32(float_positions.unwrap_or_default()),
        },
        faces,
        normals,
        colors,
        texcoords,
        generic: generic_plan.finish(generic_values),
    })
}

fn ensure_remaining(cursor: &Cursor<&[u8]>, bytes_needed: usize) -> io::Result<()> {
    let position = cursor.position() as usize;
    let end = position
        .checked_add(bytes_needed)
        .ok_or_else(|| invalid_ply("PLY payload is too large"))?;
    if end > cursor.get_ref().len() {
        return Err(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "Unexpected end of binary PLY payload",
        ));
    }
    Ok(())
}

fn skip_binary_scalar(cursor: &mut Cursor<&[u8]>, data_type: DataType) -> io::Result<()> {
    ensure_remaining(cursor, data_type.byte_length())?;
    cursor.set_position(cursor.position() + data_type.byte_length() as u64);
    Ok(())
}

#[derive(Debug, Clone, Copy)]
enum BinaryEndian {
    Little,
    Big,
}

/// Read a carried property's value, whatever width the file declared it at.
///
/// `f64` because it is the only type that holds every PLY scalar exactly:
/// `int32` and `uint32` need more than `f32`'s 24 bits of mantissa, and a
/// carried value that a widening step has already rounded cannot be narrowed
/// back to what the file said.
fn read_binary_scalar_as_f64(
    cursor: &mut Cursor<&[u8]>,
    data_type: DataType,
    endian: BinaryEndian,
) -> io::Result<f64> {
    ensure_remaining(cursor, data_type.byte_length())?;
    let value = match data_type {
        DataType::Int8 => cursor.read_i8()? as f64,
        DataType::Uint8 => cursor.read_u8()? as f64,
        DataType::Int16 => match endian {
            BinaryEndian::Little => cursor.read_i16::<LittleEndian>()? as f64,
            BinaryEndian::Big => cursor.read_i16::<BigEndian>()? as f64,
        },
        DataType::Uint16 => match endian {
            BinaryEndian::Little => cursor.read_u16::<LittleEndian>()? as f64,
            BinaryEndian::Big => cursor.read_u16::<BigEndian>()? as f64,
        },
        DataType::Int32 => match endian {
            BinaryEndian::Little => cursor.read_i32::<LittleEndian>()? as f64,
            BinaryEndian::Big => cursor.read_i32::<BigEndian>()? as f64,
        },
        DataType::Uint32 => match endian {
            BinaryEndian::Little => cursor.read_u32::<LittleEndian>()? as f64,
            BinaryEndian::Big => cursor.read_u32::<BigEndian>()? as f64,
        },
        DataType::Float32 => match endian {
            BinaryEndian::Little => cursor.read_f32::<LittleEndian>()? as f64,
            BinaryEndian::Big => cursor.read_f32::<BigEndian>()? as f64,
        },
        DataType::Float64 => match endian {
            BinaryEndian::Little => cursor.read_f64::<LittleEndian>()?,
            BinaryEndian::Big => cursor.read_f64::<BigEndian>()?,
        },
        other => {
            return Err(invalid_ply(format!(
                "Vertex property type {other:?} cannot be carried"
            )))
        }
    };
    Ok(value)
}

fn read_binary_scalar_as_f32(
    cursor: &mut Cursor<&[u8]>,
    data_type: DataType,
    endian: BinaryEndian,
) -> io::Result<f32> {
    ensure_remaining(cursor, data_type.byte_length())?;
    match data_type {
        DataType::Int8 => cursor.read_i8().map(|value| value as f32),
        DataType::Uint8 => cursor.read_u8().map(|value| value as f32),
        DataType::Int16 => match endian {
            BinaryEndian::Little => cursor.read_i16::<LittleEndian>().map(|value| value as f32),
            BinaryEndian::Big => cursor.read_i16::<BigEndian>().map(|value| value as f32),
        },
        DataType::Uint16 => match endian {
            BinaryEndian::Little => cursor.read_u16::<LittleEndian>().map(|value| value as f32),
            BinaryEndian::Big => cursor.read_u16::<BigEndian>().map(|value| value as f32),
        },
        DataType::Int32 => match endian {
            BinaryEndian::Little => cursor.read_i32::<LittleEndian>().map(|value| value as f32),
            BinaryEndian::Big => cursor.read_i32::<BigEndian>().map(|value| value as f32),
        },
        DataType::Uint32 => match endian {
            BinaryEndian::Little => cursor.read_u32::<LittleEndian>().map(|value| value as f32),
            BinaryEndian::Big => cursor.read_u32::<BigEndian>().map(|value| value as f32),
        },
        DataType::Int64 => match endian {
            BinaryEndian::Little => cursor.read_i64::<LittleEndian>().map(|value| value as f32),
            BinaryEndian::Big => cursor.read_i64::<BigEndian>().map(|value| value as f32),
        },
        DataType::Uint64 => match endian {
            BinaryEndian::Little => cursor.read_u64::<LittleEndian>().map(|value| value as f32),
            BinaryEndian::Big => cursor.read_u64::<BigEndian>().map(|value| value as f32),
        },
        DataType::Float32 => match endian {
            BinaryEndian::Little => cursor.read_f32::<LittleEndian>(),
            BinaryEndian::Big => cursor.read_f32::<BigEndian>(),
        },
        DataType::Float64 => match endian {
            BinaryEndian::Little => cursor.read_f64::<LittleEndian>().map(|value| value as f32),
            BinaryEndian::Big => cursor.read_f64::<BigEndian>().map(|value| value as f32),
        },
        _ => Err(invalid_ply("Unsupported binary scalar type")),
    }
}

fn read_binary_scalar_as_i32(
    cursor: &mut Cursor<&[u8]>,
    data_type: DataType,
    endian: BinaryEndian,
) -> io::Result<i32> {
    ensure_remaining(cursor, data_type.byte_length())?;
    match data_type {
        DataType::Int8 => cursor.read_i8().map(|value| value as i32),
        DataType::Uint8 => cursor.read_u8().map(|value| value as i32),
        DataType::Int16 => match endian {
            BinaryEndian::Little => cursor.read_i16::<LittleEndian>().map(|value| value as i32),
            BinaryEndian::Big => cursor.read_i16::<BigEndian>().map(|value| value as i32),
        },
        DataType::Uint16 => match endian {
            BinaryEndian::Little => cursor.read_u16::<LittleEndian>().map(|value| value as i32),
            BinaryEndian::Big => cursor.read_u16::<BigEndian>().map(|value| value as i32),
        },
        DataType::Int32 => match endian {
            BinaryEndian::Little => cursor.read_i32::<LittleEndian>(),
            BinaryEndian::Big => cursor.read_i32::<BigEndian>(),
        },
        DataType::Uint32 => {
            let value = match endian {
                BinaryEndian::Little => cursor.read_u32::<LittleEndian>()?,
                BinaryEndian::Big => cursor.read_u32::<BigEndian>()?,
            };
            i32::try_from(value).map_err(|_| invalid_ply("Binary PLY value does not fit in int32"))
        }
        _ => Err(invalid_ply("Unsupported binary int32 scalar type")),
    }
}

fn read_binary_scalar_as_u8(cursor: &mut Cursor<&[u8]>, data_type: DataType) -> io::Result<u8> {
    ensure_remaining(cursor, data_type.byte_length())?;
    match data_type {
        DataType::Uint8 => cursor.read_u8(),
        DataType::Int8 => {
            let value = cursor.read_i8()?;
            u8::try_from(value).map_err(|_| invalid_ply("Negative color component value"))
        }
        _ => Err(invalid_ply("Color properties must be uint8")),
    }
}

fn read_binary_scalar_as_u32(
    cursor: &mut Cursor<&[u8]>,
    data_type: DataType,
    endian: BinaryEndian,
) -> io::Result<u32> {
    ensure_remaining(cursor, data_type.byte_length())?;
    match data_type {
        DataType::Uint8 => cursor.read_u8().map(|value| value as u32),
        DataType::Int8 => {
            let value = cursor.read_i8()?;
            u32::try_from(value).map_err(|_| invalid_ply("Negative face index value"))
        }
        DataType::Uint16 => match endian {
            BinaryEndian::Little => cursor.read_u16::<LittleEndian>().map(|value| value as u32),
            BinaryEndian::Big => cursor.read_u16::<BigEndian>().map(|value| value as u32),
        },
        DataType::Int16 => {
            let value = match endian {
                BinaryEndian::Little => cursor.read_i16::<LittleEndian>()?,
                BinaryEndian::Big => cursor.read_i16::<BigEndian>()?,
            };
            u32::try_from(value).map_err(|_| invalid_ply("Negative face index value"))
        }
        DataType::Uint32 => match endian {
            BinaryEndian::Little => cursor.read_u32::<LittleEndian>(),
            BinaryEndian::Big => cursor.read_u32::<BigEndian>(),
        },
        DataType::Int32 => {
            let value = match endian {
                BinaryEndian::Little => cursor.read_i32::<LittleEndian>()?,
                BinaryEndian::Big => cursor.read_i32::<BigEndian>()?,
            };
            u32::try_from(value).map_err(|_| invalid_ply("Negative face index value"))
        }
        _ => Err(invalid_ply("Unsupported face index scalar type")),
    }
}

fn read_binary_scalar_as_usize(
    cursor: &mut Cursor<&[u8]>,
    data_type: DataType,
    endian: BinaryEndian,
) -> io::Result<usize> {
    let value = read_binary_scalar_as_u32(cursor, data_type, endian)?;
    usize::try_from(value).map_err(|_| invalid_ply("Binary list size is too large"))
}

fn skip_binary_element(
    cursor: &mut Cursor<&[u8]>,
    element: &PlyElementDef,
    endian: BinaryEndian,
) -> io::Result<()> {
    for _ in 0..element.count {
        for property in &element.properties {
            match property.kind {
                PlyPropertyKind::Scalar(data_type) => skip_binary_scalar(cursor, data_type)?,
                PlyPropertyKind::List {
                    count_type,
                    item_type,
                } => {
                    let count = read_binary_scalar_as_usize(cursor, count_type, endian)?;
                    for _ in 0..count {
                        skip_binary_scalar(cursor, item_type)?;
                    }
                }
            }
        }
    }
    Ok(())
}

fn read_ply_binary_body(
    header: &PlyHeader,
    schema: &PlyReadSchema,
    generic_plan: &GenericPlan,
    body: &[u8],
    endian: BinaryEndian,
) -> io::Result<ParsedPlyData> {
    let mut cursor = Cursor::new(body);
    let vertex_element_index = header
        .elements
        .iter()
        .position(|element| element.name == "vertex")
        .ok_or_else(|| invalid_ply("Missing vertex element"))?;
    for element in &header.elements[..vertex_element_index] {
        skip_binary_element(&mut cursor, element, endian)?;
    }

    // A binary vertex occupies at least one byte, so the bytes left after the
    // preceding elements bound how many of the declared vertices can be there.
    let vertex_capacity = body_bounded_capacity(
        header.vertex_count,
        body.len().saturating_sub(cursor.position() as usize),
        1,
    );

    let mut float_positions = matches!(schema.position_data_type, DataType::Float32)
        .then(|| Vec::with_capacity(vertex_capacity));
    let mut int_positions = matches!(schema.position_data_type, DataType::Int32)
        .then(|| Vec::with_capacity(vertex_capacity));
    let mut normals = schema
        .has_normals
        .then(|| Vec::with_capacity(vertex_capacity));
    let mut colors = (schema.color_components > 0).then(|| ParsedPlyColorData {
        num_components: schema.color_components,
        values: Vec::with_capacity(vertex_capacity),
    });
    let mut texcoords = schema
        .texcoord_pair
        .is_some()
        .then(|| Vec::with_capacity(vertex_capacity));
    let mut generic_values = generic_plan.new_values(vertex_capacity);

    for _ in 0..header.vertex_count {
        let mut float_position = [0.0f32; 3];
        let mut int_position = [0i32; 3];
        let mut normal = [0.0f32; 3];
        let mut color = [0u8; 4];
        let mut texcoord = [0.0f32; 2];
        let mut color_component = 0usize;

        for (property_index, property) in header.vertex_properties.iter().enumerate() {
            match property.kind {
                PlyPropertyKind::Scalar(data_type) => match property.name.as_str() {
                    "x" => match schema.position_data_type {
                        DataType::Int32 => {
                            int_position[0] =
                                read_binary_scalar_as_i32(&mut cursor, data_type, endian)?
                        }
                        _ => {
                            float_position[0] =
                                read_binary_scalar_as_f32(&mut cursor, data_type, endian)?
                        }
                    },
                    "y" => match schema.position_data_type {
                        DataType::Int32 => {
                            int_position[1] =
                                read_binary_scalar_as_i32(&mut cursor, data_type, endian)?
                        }
                        _ => {
                            float_position[1] =
                                read_binary_scalar_as_f32(&mut cursor, data_type, endian)?
                        }
                    },
                    "z" => match schema.position_data_type {
                        DataType::Int32 => {
                            int_position[2] =
                                read_binary_scalar_as_i32(&mut cursor, data_type, endian)?
                        }
                        _ => {
                            float_position[2] =
                                read_binary_scalar_as_f32(&mut cursor, data_type, endian)?
                        }
                    },
                    "nx" if schema.has_normals => {
                        normal[0] = read_binary_scalar_as_f32(&mut cursor, data_type, endian)?
                    }
                    "ny" if schema.has_normals => {
                        normal[1] = read_binary_scalar_as_f32(&mut cursor, data_type, endian)?
                    }
                    "nz" if schema.has_normals => {
                        normal[2] = read_binary_scalar_as_f32(&mut cursor, data_type, endian)?
                    }
                    // As in the ASCII path: a header naming more colour
                    // properties than a colour has channels must not write past
                    // the array.
                    "red" | "green" | "blue" | "alpha" if schema.color_components > 0 => {
                        let value = read_binary_scalar_as_u8(&mut cursor, data_type)?;
                        if let Some(slot) = color.get_mut(color_component) {
                            *slot = value;
                        }
                        color_component += 1;
                    }
                    name if schema.texcoord_pair.is_some_and(|pair| name == pair.u) => {
                        texcoord[0] = read_binary_scalar_as_f32(&mut cursor, data_type, endian)?
                    }
                    name if schema.texcoord_pair.is_some_and(|pair| name == pair.v) => {
                        texcoord[1] = read_binary_scalar_as_f32(&mut cursor, data_type, endian)?
                    }
                    _ => match generic_plan.column_for(property_index) {
                        Some(column) => generic_values[column].push(read_binary_scalar_as_f64(
                            &mut cursor,
                            data_type,
                            endian,
                        )?),
                        None => skip_binary_scalar(&mut cursor, data_type)?,
                    },
                },
                PlyPropertyKind::List {
                    count_type,
                    item_type,
                } => {
                    let count = read_binary_scalar_as_usize(&mut cursor, count_type, endian)?;
                    for _ in 0..count {
                        skip_binary_scalar(&mut cursor, item_type)?;
                    }
                }
            }
        }

        match schema.position_data_type {
            DataType::Int32 => int_positions.as_mut().unwrap().push(int_position),
            _ => float_positions.as_mut().unwrap().push(float_position),
        }

        if let Some(normals) = normals.as_mut() {
            normals.push(normal);
        }

        if let Some(colors) = colors.as_mut() {
            colors.values.push(color);
        }

        if let Some(texcoords) = texcoords.as_mut() {
            texcoords.push(texcoord);
        }
    }

    let face_element_index = header
        .elements
        .iter()
        .position(|element| element.name == "face");
    if let Some(face_element_index) = face_element_index {
        if face_element_index < vertex_element_index {
            return Err(invalid_ply(
                "PLY face element before vertex element is not supported",
            ));
        }
        for element in &header.elements[vertex_element_index + 1..face_element_index] {
            skip_binary_element(&mut cursor, element, endian)?;
        }
    }

    if header.face_count > 0 && header.face_properties.is_empty() {
        return Err(invalid_ply(
            "Binary PLY faces require a face property declaration",
        ));
    }

    let index_property = face_index_property(&header.face_properties);
    let mut faces = Vec::with_capacity(body_bounded_capacity(
        header.face_count,
        body.len().saturating_sub(cursor.position() as usize),
        1,
    ));
    for _ in 0..header.face_count {
        let mut polygon_indices: Option<Vec<u32>> = None;

        for (position, property) in header.face_properties.iter().enumerate() {
            match property.kind {
                PlyPropertyKind::Scalar(data_type) => skip_binary_scalar(&mut cursor, data_type)?,
                PlyPropertyKind::List {
                    count_type,
                    item_type,
                } => {
                    let count = read_binary_scalar_as_usize(&mut cursor, count_type, endian)?;
                    if index_property == Some(position) {
                        // The count is a number in the payload, and each index
                        // behind it is a fixed width, so the bytes left bound
                        // how many of them can be there. Reserving from the
                        // count alone let a 460-byte file ask for 6.5 GB in one
                        // allocation before the read that fails on the missing
                        // data.
                        let mut values = Vec::with_capacity(body_bounded_capacity(
                            count,
                            body.len().saturating_sub(cursor.position() as usize),
                            item_type.byte_length(),
                        ));
                        for _ in 0..count {
                            values.push(read_binary_scalar_as_u32(&mut cursor, item_type, endian)?);
                        }
                        polygon_indices = Some(values);
                    } else {
                        for _ in 0..count {
                            skip_binary_scalar(&mut cursor, item_type)?;
                        }
                    }
                }
            }
        }

        if let Some(indices) = polygon_indices {
            triangulate_vertex_indices(&indices, &mut faces);
        }
    }

    Ok(ParsedPlyData {
        positions: match schema.position_data_type {
            DataType::Int32 => ParsedPlyPositionData::Int32(int_positions.unwrap_or_default()),
            _ => ParsedPlyPositionData::Float32(float_positions.unwrap_or_default()),
        },
        faces,
        normals,
        colors,
        texcoords,
        generic: generic_plan.finish(generic_values),
    })
}

fn read_ply<P: AsRef<Path>>(path: P) -> io::Result<ParsedPlyData> {
    let bytes = fs::read(path)?;
    read_ply_bytes(&bytes)
}

fn read_ply_source(source: &PlyReaderSource) -> io::Result<ParsedPlyData> {
    match source {
        PlyReaderSource::Path(path) => read_ply(path),
        PlyReaderSource::Bytes(bytes) => read_ply_bytes(bytes),
    }
}

fn read_ply_source_reporting(
    source: &PlyReaderSource,
    carry_generics: bool,
) -> io::Result<(ParsedPlyData, PlyLossReport)> {
    match source {
        PlyReaderSource::Path(path) => read_ply_bytes_reporting(&fs::read(path)?, carry_generics),
        PlyReaderSource::Bytes(bytes) => read_ply_bytes_reporting(bytes, carry_generics),
    }
}

fn read_ply_bytes(bytes: &[u8]) -> io::Result<ParsedPlyData> {
    Ok(read_ply_bytes_reporting(bytes, false)?.0)
}

/// Parse a PLY, and say in the same pass what the parse did not carry.
///
/// One header, one schema, one report: asking separately would answer for a
/// second read of the file, which for a path source is not necessarily the
/// same bytes.
fn read_ply_bytes_reporting(
    bytes: &[u8],
    carry_generics: bool,
) -> io::Result<(ParsedPlyData, PlyLossReport)> {
    let (header, body_offset) = parse_ply_header(bytes)?;
    let schema = build_read_schema(&header)?;
    let plan = GenericPlan::build(&header, &schema, carry_generics);
    let report = build_loss_report(&header, &schema, !plan.is_empty());
    let body = &bytes[body_offset..];

    let parsed = match header.format {
        PlyFormat::Ascii => read_ply_ascii_body(&header, &schema, &plan, body)?,
        PlyFormat::BinaryLittleEndian => {
            read_ply_binary_body(&header, &schema, &plan, body, BinaryEndian::Little)?
        }
        PlyFormat::BinaryBigEndian => {
            read_ply_binary_body(&header, &schema, &plan, body, BinaryEndian::Big)?
        }
    };
    Ok((parsed, report))
}

/// Write point positions to an ASCII PLY file.
pub fn write_ply_positions<P: AsRef<Path>>(path: P, points: &[[f32; 3]]) -> io::Result<()> {
    let mut file = fs::File::create(path)?;

    writeln!(file, "ply")?;
    writeln!(file, "format ascii 1.0")?;
    writeln!(file, "element vertex {}", points.len())?;
    writeln!(file, "property float x")?;
    writeln!(file, "property float y")?;
    writeln!(file, "property float z")?;
    writeln!(file, "end_header")?;

    for p in points {
        writeln!(file, "{:.6} {:.6} {:.6}", p[0], p[1], p[2])?;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use draco_core::geometry_attribute::GeometryAttributeType;
    use tempfile::NamedTempFile;

    #[test]
    fn test_read_write_ply() {
        let expected = vec![
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            [0.0, 0.0, 1.0],
            [-1.0, -1.0, -1.0],
        ];

        let file = NamedTempFile::new().unwrap();
        write_ply_positions(file.path(), &expected).unwrap();

        let positions = read_ply_positions(file.path()).unwrap();
        assert_eq!(positions.len(), expected.len());

        for (i, (a, b)) in positions.iter().zip(expected.iter()).enumerate() {
            let diff = (a[0] - b[0]).abs() + (a[1] - b[1]).abs() + (a[2] - b[2]).abs();
            assert!(
                diff < 1e-5,
                "Position mismatch at index {i}: {a:?} vs {b:?}"
            );
        }
    }

    #[test]
    fn test_read_mesh_parses_and_triangulates_faces() {
        let file = NamedTempFile::new().unwrap();
        let ply = r#"ply
format ascii 1.0
element vertex 4
property float x
property float y
property float z
element face 2
property list uchar int vertex_indices
end_header
0 0 0
1 0 0
1 1 0
0 1 0
3 0 1 2
4 0 1 2 3
"#;

        std::fs::write(file.path(), ply).unwrap();

        let mut reader = PlyReader::open(file.path()).unwrap();
        let mesh = reader.read_mesh().unwrap();

        assert_eq!(mesh.num_points(), 4);
        assert_eq!(mesh.num_faces(), 3);
        assert_eq!(
            mesh.face(draco_core::geometry_indices::FaceIndex(0)),
            [0u32.into(), 1u32.into(), 2u32.into()]
        );
        assert_eq!(
            mesh.face(draco_core::geometry_indices::FaceIndex(1)),
            [0u32.into(), 1u32.into(), 2u32.into()]
        );
        assert_eq!(
            mesh.face(draco_core::geometry_indices::FaceIndex(2)),
            [0u32.into(), 2u32.into(), 3u32.into()]
        );
    }

    #[test]
    fn test_read_mesh_parses_normals_and_colors() {
        let file = NamedTempFile::new().unwrap();
        let ply = r#"ply
format ascii 1.0
element vertex 2
property float x
property float y
property float z
property float nx
property float ny
property float nz
property uchar red
property uchar green
property uchar blue
property uchar alpha
end_header
0 0 0 0 0 1 10 20 30 40
1 0 0 0 1 0 50 60 70 80
"#;

        std::fs::write(file.path(), ply).unwrap();

        let mut reader = PlyReader::open(file.path()).unwrap();
        let mesh = reader.read_mesh().unwrap();

        assert_eq!(mesh.num_points(), 2);
        assert_eq!(mesh.num_faces(), 0);
        assert_eq!(mesh.num_attributes(), 3);

        let normal_att = mesh.named_attribute(GeometryAttributeType::Normal).unwrap();
        assert_eq!(normal_att.data_type(), DataType::Float32);
        assert_eq!(normal_att.num_components(), 3);
        assert!(!normal_att.normalized());

        let normal_data = normal_att.buffer().data();
        let first_normal = [
            f32::from_le_bytes(normal_data[0..4].try_into().unwrap()),
            f32::from_le_bytes(normal_data[4..8].try_into().unwrap()),
            f32::from_le_bytes(normal_data[8..12].try_into().unwrap()),
        ];
        assert_eq!(first_normal, [0.0, 0.0, 1.0]);

        let color_att = mesh.named_attribute(GeometryAttributeType::Color).unwrap();
        assert_eq!(color_att.data_type(), DataType::Uint8);
        assert_eq!(color_att.num_components(), 4);
        assert!(color_att.normalized());
        assert_eq!(color_att.buffer().data(), &[10, 20, 30, 40, 50, 60, 70, 80]);
    }

    #[test]
    fn test_read_mesh_preserves_int32_positions() {
        let file = NamedTempFile::new().unwrap();
        let ply = r#"ply
format ascii 1.0
element vertex 2
property int x
property int y
property int z
end_header
1 2 3
4 5 6
"#;

        std::fs::write(file.path(), ply).unwrap();

        let mut reader = PlyReader::open(file.path()).unwrap();
        let mesh = reader.read_mesh().unwrap();

        let position_att = mesh
            .named_attribute(GeometryAttributeType::Position)
            .unwrap();
        assert_eq!(position_att.data_type(), DataType::Int32);
        assert_eq!(position_att.num_components(), 3);
        assert!(!position_att.normalized());

        let position_data = position_att.buffer().data();
        let first_position = [
            i32::from_le_bytes(position_data[0..4].try_into().unwrap()),
            i32::from_le_bytes(position_data[4..8].try_into().unwrap()),
            i32::from_le_bytes(position_data[8..12].try_into().unwrap()),
        ];
        assert_eq!(first_position, [1, 2, 3]);
    }

    #[test]
    fn test_read_mesh_ignores_non_float_normals() {
        let file = NamedTempFile::new().unwrap();
        let ply = r#"ply
format ascii 1.0
element vertex 1
property float x
property float y
property float z
property int nx
property int ny
property int nz
end_header
0 0 0 0 0 1
"#;

        std::fs::write(file.path(), ply).unwrap();

        let mut reader = PlyReader::open(file.path()).unwrap();
        let mesh = reader.read_mesh().unwrap();

        assert_eq!(mesh.named_attribute_id(GeometryAttributeType::Normal), -1);
    }

    #[test]
    fn test_read_mesh_rejects_non_uint8_colors() {
        let file = NamedTempFile::new().unwrap();
        let ply = r#"ply
format ascii 1.0
element vertex 1
property float x
property float y
property float z
property int red
property int green
property int blue
end_header
0 0 0 1 2 3
"#;

        std::fs::write(file.path(), ply).unwrap();

        let mut reader = PlyReader::open(file.path()).unwrap();
        let error = reader.read_mesh().unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
        assert!(error.to_string().contains("Color properties must be uint8"));
    }

    /// Per-corner texture coordinates sit next to the indices on the face
    /// element, and Draco's own PLY encoder writes them there. Both are lists,
    /// so a reader that takes every face list for indices reads floats as
    /// vertex numbers — which is a hard parse error, not a wrong mesh.
    #[test]
    fn test_read_mesh_skips_non_index_face_lists() {
        let file = NamedTempFile::new().unwrap();
        let ply = r#"ply
format ascii 1.0
element vertex 4
property float x
property float y
property float z
element face 2
property list uchar int vertex_indices
property list uchar float texcoord
end_header
0 0 0
1 0 0
1 1 0
0 1 0
3 0 1 2 6 0 0 1 0 1 1
4 0 1 2 3 8 0 0 1 0 1 1 0 1
"#;

        std::fs::write(file.path(), ply).unwrap();

        let mut reader = PlyReader::open(file.path()).unwrap();
        let mesh = reader.read_mesh().unwrap();

        assert_eq!(mesh.num_points(), 4);
        assert_eq!(mesh.num_faces(), 3);
        assert_eq!(
            mesh.face(draco_core::geometry_indices::FaceIndex(2)),
            [0u32.into(), 2u32.into(), 3u32.into()]
        );
    }

    /// The same file binary, where the float list is not merely mis-parsed but
    /// mis-sized: skipping it has to consume exactly its own bytes, or every
    /// face after the first reads from the wrong offset.
    #[test]
    fn test_read_binary_mesh_skips_non_index_face_lists() {
        let file = NamedTempFile::new().unwrap();
        let mut ply = Vec::new();
        ply.extend_from_slice(
            br#"ply
format binary_little_endian 1.0
element vertex 4
property float x
property float y
property float z
element face 2
property list uchar int vertex_indices
property list uchar float texcoord
end_header
"#,
        );

        for vertex in [
            [0.0f32, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [1.0, 1.0, 0.0],
            [0.0, 1.0, 0.0],
        ] {
            for component in vertex {
                ply.extend_from_slice(&component.to_le_bytes());
            }
        }

        for indices in [vec![0i32, 1, 2], vec![0, 2, 3]] {
            ply.push(indices.len() as u8);
            for index in &indices {
                ply.extend_from_slice(&index.to_le_bytes());
            }
            ply.push((indices.len() * 2) as u8);
            for corner in 0..indices.len() * 2 {
                ply.extend_from_slice(&(corner as f32).to_le_bytes());
            }
        }

        std::fs::write(file.path(), ply).unwrap();

        let mut reader = PlyReader::open(file.path()).unwrap();
        let mesh = reader.read_mesh().unwrap();

        assert_eq!(mesh.num_points(), 4);
        assert_eq!(mesh.num_faces(), 2);
        assert_eq!(
            mesh.face(draco_core::geometry_indices::FaceIndex(1)),
            [0u32.into(), 2u32.into(), 3u32.into()]
        );
    }

    #[test]
    fn test_read_binary_little_endian_mesh() {
        let file = NamedTempFile::new().unwrap();
        let mut ply = Vec::new();
        ply.extend_from_slice(
            br#"ply
format binary_little_endian 1.0
element vertex 4
property float x
property float y
property float z
element face 2
property list uchar int vertex_indices
end_header
"#,
        );

        for vertex in [
            [0.0f32, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [1.0, 1.0, 0.0],
            [0.0, 1.0, 0.0],
        ] {
            for component in vertex {
                ply.extend_from_slice(&component.to_le_bytes());
            }
        }

        ply.push(3);
        for index in [0i32, 1, 2] {
            ply.extend_from_slice(&index.to_le_bytes());
        }

        ply.push(4);
        for index in [0i32, 1, 2, 3] {
            ply.extend_from_slice(&index.to_le_bytes());
        }

        std::fs::write(file.path(), ply).unwrap();

        let mut reader = PlyReader::open(file.path()).unwrap();
        let mesh = reader.read_mesh().unwrap();

        assert_eq!(mesh.num_points(), 4);
        assert_eq!(mesh.num_faces(), 3);
        assert_eq!(
            mesh.face(draco_core::geometry_indices::FaceIndex(0)),
            [0u32.into(), 1u32.into(), 2u32.into()]
        );
        assert_eq!(
            mesh.face(draco_core::geometry_indices::FaceIndex(1)),
            [0u32.into(), 1u32.into(), 2u32.into()]
        );
        assert_eq!(
            mesh.face(draco_core::geometry_indices::FaceIndex(2)),
            [0u32.into(), 2u32.into(), 3u32.into()]
        );
    }

    #[test]
    fn test_read_binary_little_endian_mesh_with_cr_only_header() {
        let mut ply = b"ply\rformat binary_little_endian 1.0\relement vertex 24\rproperty float x\rproperty float y\rproperty float z\relement face 1\rproperty list uchar int vertex_indices\rend_header\r".to_vec();
        for index in 0..24 {
            ply.extend_from_slice(&(index as f32).to_le_bytes());
            ply.extend_from_slice(&0.0f32.to_le_bytes());
            ply.extend_from_slice(&0.0f32.to_le_bytes());
        }
        ply.extend_from_slice(&[3]);
        for index in [0i32, 1, 2] {
            ply.extend_from_slice(&index.to_le_bytes());
        }

        let mesh =
            PlyReader::read_from_bytes(&ply).expect("CR-only binary PLY header should parse");

        // Three of the twenty-four vertices, because the one face names three
        // and a vertex no face names is dropped on the way out. What this test
        // is about is the header, so it checks the payload landed at the right
        // stride rather than counting what survived: the surviving positions
        // are vertices 0, 1 and 2, whose x is their own index.
        assert_eq!(mesh.num_faces(), 1);
        assert_eq!(mesh.num_points(), 3);
        let positions = mesh.attribute(0).read_f32s(mesh.num_points(), 3);
        assert_eq!(
            positions,
            vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 2.0, 0.0, 0.0],
            "the CR-only header left the vertex payload misaligned"
        );
    }

    #[test]
    fn test_read_binary_little_endian_attributes_and_int_positions() {
        let file = NamedTempFile::new().unwrap();
        let mut ply = Vec::new();
        ply.extend_from_slice(
            br#"ply
format binary_little_endian 1.0
element vertex 2
property int x
property int y
property int z
property float nx
property float ny
property float nz
property uchar red
property uchar green
property uchar blue
property uchar alpha
end_header
"#,
        );

        for (position, normal, color) in [
            ([1i32, 2, 3], [0.0f32, 0.0, 1.0], [10u8, 20, 30, 40]),
            ([4i32, 5, 6], [0.0f32, 1.0, 0.0], [50u8, 60, 70, 80]),
        ] {
            for component in position {
                ply.extend_from_slice(&component.to_le_bytes());
            }
            for component in normal {
                ply.extend_from_slice(&component.to_le_bytes());
            }
            ply.extend_from_slice(&color);
        }

        std::fs::write(file.path(), ply).unwrap();

        let mut reader = PlyReader::open(file.path()).unwrap();
        let mesh = reader.read_mesh().unwrap();

        let position_att = mesh
            .named_attribute(GeometryAttributeType::Position)
            .unwrap();
        assert_eq!(position_att.data_type(), DataType::Int32);
        assert_eq!(position_att.num_components(), 3);

        let position_data = position_att.buffer().data();
        let first_position = [
            i32::from_le_bytes(position_data[0..4].try_into().unwrap()),
            i32::from_le_bytes(position_data[4..8].try_into().unwrap()),
            i32::from_le_bytes(position_data[8..12].try_into().unwrap()),
        ];
        assert_eq!(first_position, [1, 2, 3]);

        let normal_att = mesh.named_attribute(GeometryAttributeType::Normal).unwrap();
        assert_eq!(normal_att.data_type(), DataType::Float32);
        assert_eq!(normal_att.num_components(), 3);

        let normal_data = normal_att.buffer().data();
        let first_normal = [
            f32::from_le_bytes(normal_data[0..4].try_into().unwrap()),
            f32::from_le_bytes(normal_data[4..8].try_into().unwrap()),
            f32::from_le_bytes(normal_data[8..12].try_into().unwrap()),
        ];
        assert_eq!(first_normal, [0.0, 0.0, 1.0]);

        let color_att = mesh.named_attribute(GeometryAttributeType::Color).unwrap();
        assert_eq!(color_att.data_type(), DataType::Uint8);
        assert_eq!(color_att.num_components(), 4);
        assert!(color_att.normalized());
        assert_eq!(color_att.buffer().data(), &[10, 20, 30, 40, 50, 60, 70, 80]);
    }

    #[test]
    fn test_read_binary_big_endian_mesh() {
        let mut ply = Vec::new();
        ply.extend_from_slice(
            br#"ply
format binary_big_endian 1.0
element vertex 4
property float x
property float y
property float z
element face 1
property list uchar int vertex_indices
end_header
"#,
        );

        for vertex in [
            [0.0f32, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [1.0, 1.0, 0.0],
            [0.0, 1.0, 0.0],
        ] {
            for component in vertex {
                ply.extend_from_slice(&component.to_be_bytes());
            }
        }

        ply.push(4);
        for index in [0i32, 1, 2, 3] {
            ply.extend_from_slice(&index.to_be_bytes());
        }

        let mesh = PlyReader::read_from_bytes(&ply).unwrap();
        assert_eq!(mesh.num_points(), 4);
        assert_eq!(mesh.num_faces(), 2);
        assert_eq!(
            mesh.face(draco_core::geometry_indices::FaceIndex(1)),
            [0u32.into(), 2u32.into(), 3u32.into()]
        );
    }

    #[test]
    fn test_loss_report_is_empty_for_a_file_the_reader_carries_whole() {
        let ply = r#"ply
format ascii 1.0
element vertex 1
property float x
property float y
property float z
property float nx
property float ny
property float nz
property uchar red
property uchar green
property uchar blue
element face 1
property list uchar int vertex_indices
end_header
0 0 0 0 0 1 255 0 0
3 0 0 0
"#;

        let report = PlyReader::from_bytes(ply.as_bytes().to_vec())
            .loss_report()
            .unwrap();
        assert!(report.is_lossless(), "{:?}", report.dropped());
    }

    // The set of properties a read consumes is decided by `build_read_schema`
    // and re-derived by `build_loss_report`, so the two can drift apart and the
    // report starts naming a property that was in fact read. Every recognized
    // spelling gets a case here: a name this crate learns to consume without
    // the report learning it too fails on the line that names it.
    #[test]
    fn test_loss_report_omits_every_property_spelling_the_reader_consumes() {
        for (label, texcoords) in [
            ("texture_u/texture_v", ("texture_u", "texture_v")),
            ("u/v", ("u", "v")),
            ("s/t", ("s", "t")),
        ] {
            let (u, v) = texcoords;
            let ply = format!(
                "ply\n\
                 format ascii 1.0\n\
                 element vertex 1\n\
                 property float x\n\
                 property float y\n\
                 property float z\n\
                 property float nx\n\
                 property float ny\n\
                 property float nz\n\
                 property uchar red\n\
                 property uchar green\n\
                 property uchar blue\n\
                 property uchar alpha\n\
                 property float {u}\n\
                 property float {v}\n\
                 end_header\n\
                 0 0 0 0 0 1 255 0 0 255 0.5 0.5\n"
            );

            let report = PlyReader::from_bytes(ply.into_bytes())
                .loss_report()
                .unwrap();
            assert!(
                report.is_lossless(),
                "{label} is read but reported as lost: {:?}",
                report.dropped()
            );
        }
    }

    // The other direction: only the pair actually chosen is consumed, so a
    // file carrying a second spelling must still hear about it.
    #[test]
    fn test_loss_report_names_the_texcoord_pair_that_lost() {
        let ply = r#"ply
format ascii 1.0
element vertex 1
property float x
property float y
property float z
property float u
property float v
property float s
property float t
end_header
0 0 0 0.5 0.5 0.25 0.75
"#;

        let report = PlyReader::from_bytes(ply.as_bytes().to_vec())
            .loss_report()
            .unwrap();
        assert_eq!(
            report.dropped(),
            [
                PlyDroppedItem::VertexProperty {
                    name: "s".to_string(),
                    data_type: Some(DataType::Float32),
                },
                PlyDroppedItem::VertexProperty {
                    name: "t".to_string(),
                    data_type: Some(DataType::Float32),
                },
            ]
        );
    }

    /// A property that shares a name with half of a texture-coordinate pair
    /// is an ordinary property unless the whole pair is there, as `float`.
    ///
    /// The reader used to refuse these files outright. Upstream Draco reads
    /// no texture coordinates from a PLY at all, and `plyfile` reads the file
    /// as it stands, so the refusal turned away valid files -- a lidar cloud
    /// with a `t` for time, for one.
    #[test]
    fn test_an_incomplete_texcoord_pair_is_an_ordinary_property() {
        let lone = r#"ply
format ascii 1.0
element vertex 2
property float x
property float y
property float z
property float t
end_header
0 0 0 0.5
1 0 0 1.5
"#;
        let (mesh, report) = PlyReader::from_bytes(lone.as_bytes().to_vec())
            .read_mesh_reporting_loss()
            .expect("a lone t is not a malformed texture coordinate");
        assert_eq!(mesh.num_points(), 2);
        assert!(mesh.named_attribute_id(GeometryAttributeType::TexCoord) < 0);
        assert_eq!(
            report.dropped(),
            [PlyDroppedItem::VertexProperty {
                name: "t".to_string(),
                data_type: Some(DataType::Float32),
            }]
        );

        // Carried under its own name when generics are asked for.
        let mesh = PlyReader::from_bytes(lone.as_bytes().to_vec())
            .with_generic_attributes(true)
            .read_mesh()
            .unwrap();
        assert_eq!(generic_values(&mesh, "t"), Some(vec![0.5, 1.5]));
    }

    /// A complete pair that is not `float` is not a texture coordinate either,
    /// and a complete spelling still wins over an incomplete one beside it.
    #[test]
    fn test_only_a_complete_float_pair_is_read_as_texture_coordinates() {
        let doubles = r#"ply
format ascii 1.0
element vertex 1
property float x
property float y
property float z
property double u
property double v
end_header
0 0 0 0.25 0.75
"#;
        let (mesh, report) = PlyReader::from_bytes(doubles.as_bytes().to_vec())
            .read_mesh_reporting_loss()
            .expect("a double pair reads as two ordinary properties");
        assert!(mesh.named_attribute_id(GeometryAttributeType::TexCoord) < 0);
        assert_eq!(report.dropped().len(), 2, "{:?}", report.dropped());

        let mixed = r#"ply
format ascii 1.0
element vertex 1
property float x
property float y
property float z
property float s
property float u
property float v
end_header
0 0 0 9 0.25 0.75
"#;
        let (mesh, report) = PlyReader::from_bytes(mixed.as_bytes().to_vec())
            .read_mesh_reporting_loss()
            .unwrap();
        assert!(mesh.named_attribute_id(GeometryAttributeType::TexCoord) >= 0);
        assert_eq!(
            report.dropped(),
            [PlyDroppedItem::VertexProperty {
                name: "s".to_string(),
                data_type: Some(DataType::Float32),
            }]
        );
    }

    #[test]
    fn test_read_mesh_reporting_loss_agrees_with_reading_each_half_alone() {
        let ply = r#"ply
format ascii 1.0
element vertex 2
property float x
property float y
property float z
property float confidence
element face 1
property list uchar int vertex_indices
property uchar flags
end_header
0 0 0 0.25
1 0 0 0.75
3 0 1 1
"#;

        let (mesh, report) = PlyReader::from_bytes(ply.as_bytes().to_vec())
            .read_mesh_reporting_loss()
            .unwrap();
        let separate_mesh = PlyReader::from_bytes(ply.as_bytes().to_vec())
            .read_mesh()
            .unwrap();
        let separate_report = PlyReader::from_bytes(ply.as_bytes().to_vec())
            .loss_report()
            .unwrap();

        assert_eq!(mesh.num_points(), separate_mesh.num_points());
        assert_eq!(mesh.num_faces(), separate_mesh.num_faces());
        assert_eq!(report, separate_report);
        assert_eq!(
            report.dropped(),
            [
                PlyDroppedItem::VertexProperty {
                    name: "confidence".to_string(),
                    data_type: Some(DataType::Float32),
                },
                PlyDroppedItem::FaceProperty {
                    name: "flags".to_string(),
                },
            ]
        );
    }

    #[test]
    fn test_dropped_items_describe_themselves() {
        // The wrappers hand these to a caller as plain strings, so the wording
        // lives here rather than in each of them.
        let rendered: Vec<String> = [
            PlyDroppedItem::VertexProperty {
                name: "f_dc_0".to_string(),
                data_type: Some(DataType::Float32),
            },
            PlyDroppedItem::VertexProperty {
                name: "weights".to_string(),
                data_type: None,
            },
            PlyDroppedItem::Normals,
            PlyDroppedItem::FaceProperty {
                name: "texcoord".to_string(),
            },
            PlyDroppedItem::Element {
                name: "camera".to_string(),
                count: 2,
            },
        ]
        .iter()
        .map(ToString::to_string)
        .collect();

        assert_eq!(
            rendered,
            [
                "vertex property \"f_dc_0\" (Float32) has no attribute to read it into",
                "vertex property \"weights\" is a list, which the vertex element has no reading for",
                "normals are declared but not as three float32 components, so they are not read",
                "face property \"texcoord\" is not the corner-index list and is skipped",
                "element \"camera\" and its 2 entries are skipped entirely",
            ]
        );
    }

    /// Read one carried attribute back as `f64`, whatever width it was built at.
    fn generic_values(mesh: &Mesh, name: &str) -> Option<Vec<f64>> {
        for id in 0..mesh.num_attributes() {
            let attribute = mesh.attribute(id);
            let unique_id = attribute.unique_id();
            let carries_name = mesh
                .attribute_metadata_by_unique_id(unique_id)
                .and_then(|metadata| metadata.metadata().get_string("name"))
                .is_some_and(|found| found == name);
            if !carries_name {
                continue;
            }
            let width = attribute.data_type().byte_length();
            let data = attribute.buffer().data();
            return Some(
                (0..mesh.num_points())
                    .map(|index| {
                        let bytes = &data[index * width..(index + 1) * width];
                        match attribute.data_type() {
                            DataType::Uint8 => bytes[0] as f64,
                            DataType::Int32 => i32::from_le_bytes(bytes.try_into().unwrap()) as f64,
                            DataType::Float64 => f64::from_le_bytes(bytes.try_into().unwrap()),
                            _ => f32::from_le_bytes(bytes.try_into().unwrap()) as f64,
                        }
                    })
                    .collect(),
            );
        }
        None
    }

    const SPLAT_PLY: &str = r#"ply
format ascii 1.0
element vertex 2
property float x
property float y
property float z
property float f_dc_0
property float opacity
property uchar confidence
end_header
0 0 0 1.5 -3.0 200
1 0 0 2.5 -4.0 100
"#;

    #[test]
    fn test_generic_attributes_are_off_unless_asked_for() {
        let mesh = PlyReader::from_bytes(SPLAT_PLY.as_bytes().to_vec())
            .read_mesh()
            .unwrap();
        // Position only: the default read is what it always was.
        assert_eq!(mesh.num_attributes(), 1);
        assert!(generic_values(&mesh, "f_dc_0").is_none());
    }

    #[test]
    fn test_generic_attributes_carry_values_names_and_declared_types() {
        let mesh = PlyReader::from_bytes(SPLAT_PLY.as_bytes().to_vec())
            .with_generic_attributes(true)
            .read_mesh()
            .unwrap();

        assert_eq!(mesh.num_attributes(), 4, "position plus three carried");
        assert_eq!(generic_values(&mesh, "f_dc_0"), Some(vec![1.5, 2.5]));
        assert_eq!(generic_values(&mesh, "opacity"), Some(vec![-3.0, -4.0]));
        assert_eq!(
            generic_values(&mesh, "confidence"),
            Some(vec![200.0, 100.0])
        );

        // The declared width is kept rather than everything being widened.
        let confidence = (0..mesh.num_attributes())
            .map(|id| mesh.attribute(id))
            .find(|attribute| attribute.data_type() == DataType::Uint8)
            .expect("the uchar property stays a uchar");
        assert_eq!(confidence.attribute_type(), GeometryAttributeType::Generic);
        assert_eq!(confidence.num_components(), 1);
    }

    /// A mesh is finalized, and finalizing merges each attribute's repeated
    /// values, so a `double` property has to survive that merge rather than
    /// fail the whole file. Read back through the point map, each vertex keeps
    /// its own value, the repeat included.
    #[test]
    fn test_a_double_property_is_carried_onto_a_mesh() {
        let ply = r#"ply
format ascii 1.0
element vertex 4
property float x
property float y
property float z
property double gps_time
element face 2
property list uchar int vertex_indices
end_header
0 0 0 1e300
1 0 0 0.5
0 1 0 1e300
1 1 0 -0.0
3 0 1 2
3 1 3 2
"#;

        let mesh = PlyReader::from_bytes(ply.as_bytes().to_vec())
            .with_generic_attributes(true)
            .read_mesh()
            .unwrap();

        let attribute = (0..mesh.num_attributes())
            .map(|id| mesh.attribute(id))
            .find(|attribute| attribute.data_type() == DataType::Float64)
            .expect("the double property stays a double");
        assert_eq!(attribute.size(), 3, "the repeated value is stored once");
        let positions = mesh
            .named_attribute(GeometryAttributeType::Position)
            .unwrap();
        let mut by_position: Vec<([f32; 3], u64)> = (0..mesh.num_points())
            .map(|point| {
                let point = draco_core::geometry_indices::PointIndex(point as u32);
                let mut position = [0.0f32; 3];
                let at = positions.mapped_index(point).0 as usize * 12;
                for (axis, value) in position.iter_mut().enumerate() {
                    let bytes = &positions.buffer().data()[at + axis * 4..at + axis * 4 + 4];
                    *value = f32::from_le_bytes(bytes.try_into().unwrap());
                }
                let at = attribute.mapped_index(point).0 as usize * 8;
                let bytes = &attribute.buffer().data()[at..at + 8];
                (position, u64::from_le_bytes(bytes.try_into().unwrap()))
            })
            .collect();
        by_position.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
        assert_eq!(
            by_position,
            [
                ([0.0, 0.0, 0.0], 1e300f64.to_bits()),
                ([0.0, 1.0, 0.0], 1e300f64.to_bits()),
                ([1.0, 0.0, 0.0], 0.5f64.to_bits()),
                ([1.0, 1.0, 0.0], (-0.0f64).to_bits()),
            ]
        );
    }

    #[test]
    fn test_carrying_removes_the_properties_from_the_loss_report() {
        let dropped_by_default = PlyReader::from_bytes(SPLAT_PLY.as_bytes().to_vec())
            .loss_report()
            .unwrap();
        assert_eq!(dropped_by_default.dropped().len(), 3);

        let carried = PlyReader::from_bytes(SPLAT_PLY.as_bytes().to_vec())
            .with_generic_attributes(true)
            .loss_report()
            .unwrap();
        assert!(
            carried.is_lossless(),
            "a carried property is not lost, so naming it would name a non-problem: {:?}",
            carried.dropped()
        );
    }

    #[test]
    fn test_lists_stay_dropped_and_reported_even_when_carrying() {
        // A list has no fixed width per point, so it cannot become an
        // attribute however the option is set.
        let ply = r#"ply
format ascii 1.0
element vertex 1
property float x
property float y
property float z
property list uchar int weights
property float confidence
end_header
0 0 0 2 7 8 0.5
"#;

        let (mesh, report) = PlyReader::from_bytes(ply.as_bytes().to_vec())
            .with_generic_attributes(true)
            .read_mesh_reporting_loss()
            .unwrap();

        assert_eq!(generic_values(&mesh, "confidence"), Some(vec![0.5]));
        assert_eq!(
            report.dropped(),
            [PlyDroppedItem::VertexProperty {
                name: "weights".to_string(),
                data_type: None,
            }]
        );
    }

    #[test]
    fn test_generic_attributes_survive_the_binary_path() {
        let mut ply = b"ply\nformat binary_little_endian 1.0\nelement vertex 2\n\
            property float x\nproperty float y\nproperty float z\n\
            property float opacity\nproperty uchar confidence\nend_header\n"
            .to_vec();
        for (position, opacity, confidence) in [
            ([0.0f32, 0.0, 0.0], -3.0f32, 200u8),
            ([1.0f32, 0.0, 0.0], -4.0f32, 100u8),
        ] {
            for value in position {
                ply.extend_from_slice(&value.to_le_bytes());
            }
            ply.extend_from_slice(&opacity.to_le_bytes());
            ply.push(confidence);
        }

        let mesh = PlyReader::from_bytes(ply)
            .with_generic_attributes(true)
            .read_mesh()
            .unwrap();
        assert_eq!(generic_values(&mesh, "opacity"), Some(vec![-3.0, -4.0]));
        assert_eq!(
            generic_values(&mesh, "confidence"),
            Some(vec![200.0, 100.0])
        );
    }

    #[test]
    fn test_loss_report_names_gaussian_splat_properties() {
        // The shape a splat PLY has, trimmed to one coefficient per group: the
        // reader takes the position and reports the rest rather than failing.
        let ply = r#"ply
format ascii 1.0
element vertex 1
property float x
property float y
property float z
property float f_dc_0
property float f_rest_0
property float opacity
property float scale_0
property float rot_0
end_header
0 0 0 1.2 0.1 -3.0 -2.5 1.0
"#;

        let report = PlyReader::from_bytes(ply.as_bytes().to_vec())
            .loss_report()
            .unwrap();
        let names: Vec<&str> = report
            .dropped()
            .iter()
            .map(|item| match item {
                PlyDroppedItem::VertexProperty { name, data_type } => {
                    assert_eq!(*data_type, Some(DataType::Float32));
                    name.as_str()
                }
                other => panic!("unexpected drop: {other:?}"),
            })
            .collect();
        assert_eq!(names, ["f_dc_0", "f_rest_0", "opacity", "scale_0", "rot_0"]);

        // And the read itself still succeeds, silently, which is what the
        // report exists to say out loud.
        let mesh = PlyReader::read_from_bytes(ply.as_bytes()).unwrap();
        assert_eq!(mesh.num_points(), 1);
    }

    #[test]
    fn test_loss_report_covers_normals_faces_and_whole_elements() {
        let ply = r#"ply
format ascii 1.0
element vertex 1
property double nx
property double ny
property double nz
property float x
property float y
property float z
element face 1
property list uchar int vertex_indices
property list uchar float texcoord
element camera 2
property float view_px
end_header
0 0 1 0 0 0
3 0 0 0
0.5
0.5
"#;

        let report = PlyReader::from_bytes(ply.as_bytes().to_vec())
            .loss_report()
            .unwrap();
        assert_eq!(
            report.dropped(),
            [
                PlyDroppedItem::Normals,
                PlyDroppedItem::FaceProperty {
                    name: "texcoord".to_string(),
                },
                PlyDroppedItem::Element {
                    name: "camera".to_string(),
                    count: 2,
                },
            ]
        );
    }
}