meshoptimizer-rs 0.2.20

Rust port of meshoptimizer 1.3 with byte-identical output. Covers mesh simplification, meshlets, cluster LOD, vertex/index compression analysis, remeshing and optional parallel batch APIs and audited SIMD codecs.
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
//! Pure-Rust port of the pinned upstream `demo/clusterlod.h` (MIT, Arseny Kapoulkine).
//!
//! This module follows the demo output, not a stable meshoptimizer library
//! contract. Positions are explicit mutable packed XYZ because border dilation
//! changes them. Callback identifiers retain the demo's refinement semantics.
#![allow(clippy::too_many_arguments)]
mod bounds_math;
mod dag;
mod flat;
pub use flat::{FlatDagCluster, FlatDagGroup, LodBounds};
pub mod attributes;
pub mod cut;
pub mod dag_format;
pub mod page;
#[cfg(feature = "parallel")]
mod parallel;
mod support;
pub mod v2;
use crate::processing::{cross, dot, finite, point, sub, Context};
use crate::{Attributes, Error, MeshletSettings, Positions, VertexFlags, Workspace};
use alloc::vec::Vec;
pub use dag::{build_dag_into, build_dag_into_generic, DagBuffers, DagBuffersGeneric, DagCounts};

/// Complete configuration of the upstream cluster-LOD demo.
#[derive(Clone, Copy, Debug)]
pub struct Config {
    /// Maximum vertices per cluster.
    pub max_vertices: usize,
    /// Minimum triangles per cluster.
    pub min_triangles: usize,
    /// Maximum triangles per cluster.
    pub max_triangles: usize,
    /// Include positions when partitioning.
    pub partition_spatial: bool,
    /// Sort partitions spatially.
    pub partition_sort: bool,
    /// Target clusters per partition.
    /// V2 parent partitions grow to accommodate twice the largest indivisible
    /// replacement region, allowing partial regions to merge.
    pub partition_size: usize,
    /// Use the spatial meshlet builder.
    pub cluster_spatial: bool,
    /// Spatial builder fill weight.
    pub cluster_fill_weight: f32,
    /// Flexible builder split factor.
    pub cluster_split_factor: f32,
    /// Target triangle ratio at each level.
    pub simplify_ratio: f32,
    /// Maximum retained ratio before declaring a legacy group stuck.
    /// V2 reports reductions above this threshold as partial steps.
    pub simplify_threshold: f32,
    /// Multiplier applied to inherited error.
    pub simplify_error_merge_previous: f32,
    /// Additive fraction of this level's error.
    pub simplify_error_merge_additive: f32,
    /// Error multiplier after sloppy fallback in legacy builds.
    pub simplify_error_factor_sloppy: f32,
    /// Legacy edge-length cap on the simplifier estimate; zero disables it.
    pub simplify_error_edge_limit: f32,
    /// Clamp attribute error to positional scale.
    pub simplify_error_clamped: bool,
    /// Enable permissive simplification.
    pub simplify_permissive: bool,
    /// Retry stuck regular simplification in permissive mode.
    pub simplify_fallback_permissive: bool,
    /// Retry stuck simplification with grid-based sloppy simplification.
    pub simplify_fallback_sloppy: bool,
    /// Apply stronger regularization.
    pub simplify_regularize: bool,
    /// Preserve opposing geometric folds.
    pub simplify_preserve_folds: bool,
    /// Dilate simplified open boundaries, mutating positions.
    pub simplify_dilate_borders: bool,
    /// Compute precise culling bounds for simplified output clusters.
    pub optimize_bounds: bool,
    /// Optimize cluster topology.
    pub optimize_clusters: bool,
    /// Meshlet optimization level, zero through nine.
    pub optimize_clusters_level: u8,
}
/// `clodDefaultConfig`: rasterization defaults, for 4 through 256 triangles.
///
/// # Errors
/// `InvalidParameter` if `max_triangles` is outside 4 through 256.
pub fn default_config(max_triangles: usize) -> Result<Config, Error> {
    if !(4..=256).contains(&max_triangles) {
        return Err(Error::InvalidParameter);
    }
    Ok(Config {
        max_vertices: max_triangles,
        min_triangles: max_triangles / 3,
        max_triangles,
        partition_spatial: true,
        partition_sort: false,
        partition_size: 16,
        cluster_spatial: false,
        cluster_fill_weight: 0.,
        cluster_split_factor: 2.,
        optimize_clusters: true,
        optimize_clusters_level: 1,
        simplify_ratio: 0.5,
        simplify_threshold: 0.85,
        simplify_error_merge_previous: 1.,
        simplify_error_merge_additive: 0.,
        simplify_error_factor_sloppy: 2.,
        simplify_error_edge_limit: 0.,
        simplify_error_clamped: true,
        simplify_permissive: true,
        simplify_fallback_permissive: false,
        simplify_fallback_sloppy: true,
        simplify_regularize: false,
        simplify_preserve_folds: false,
        simplify_dilate_borders: false,
        optimize_bounds: false,
    })
}
/// `clodDefaultConfigRT`: ray-tracing defaults.
///
/// # Errors
/// `InvalidParameter` if `max_triangles` is outside 4 through 256.
pub fn default_config_rt(max_triangles: usize) -> Result<Config, Error> {
    let mut c = default_config(max_triangles)?;
    c.min_triangles = max_triangles / 4;
    c.max_vertices = 256.min(max_triangles * 2);
    c.cluster_spatial = true;
    c.cluster_fill_weight = 0.5;
    Ok(c)
}
/// Explicit borrowed mesh inputs. Weights and attribute components must match.
pub struct MeshGeneric<'a, I: crate::Index = u32> {
    /// Triangle topology referencing the full vertex array.
    pub indices: &'a [I],
    /// Mutable positions; only dilation changes these.
    pub positions: &'a mut [[f32; 3]],
    /// Optional checked attribute view.
    pub attributes: Option<Attributes<'a>>,
    /// Optional per-vertex flags.
    pub vertex_lock: Option<&'a [VertexFlags]>,
    /// Attribute weights for simplification.
    pub attribute_weights: &'a [f32],
    /// Bit K protects discontinuities in component K.
    pub attribute_protect_mask: u32,
}
/// Cluster emitted by the demo builder.
#[derive(Debug, Default, PartialEq)]
pub struct ClusterGeneric<I: crate::Index = u32> {
    /// More refined group identifier, or -1 for original geometry.
    pub refined: i32,
    /// Culling bounds; error is not necessarily monotonic across the DAG.
    pub bounds: LodBounds,
    /// Topology referencing the original vertex array.
    pub indices: Vec<I>,
    /// Number of unique vertex references.
    pub vertex_count: usize,
}
/// Group metadata passed to the output callback.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Group {
    /// DAG level.
    pub depth: i32,
    /// Simplified-group bounds used for monotonic LOD selection.
    pub simplified: LodBounds,
}
/// Owned group record and its emitted clusters.
#[derive(Debug, Default, PartialEq)]
pub struct GroupOutputGeneric<I: crate::Index = u32> {
    /// Group metadata.
    pub group: Group,
    /// Clusters in callback order.
    pub clusters: Vec<ClusterGeneric<I>>,
}
/// Node in the per-level spatial forest.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Node {
    /// Conservative subtree bounds.
    pub bounds: LodBounds,
    /// Group identifier, or -1 for internal nodes.
    pub group: i32,
    /// Offset of consecutive children.
    pub child_offset: u32,
    /// Number of children.
    pub child_count: u32,
}
#[derive(Clone, Copy, Default)]
struct Pending {
    vertices: usize,
    offset: usize,
    count: usize,
    refined: i32,
    bounds: LodBounds,
}
type CompactGroup = (Vec<u32>, Vec<[f32; 3]>, Vec<u32>);
fn merged(bounds: &[LodBounds], ctx: &mut Context<'_>) -> Result<LodBounds, Error> {
    let mut p = ctx.alloc(bounds.len())?;
    let mut radii = ctx.alloc(bounds.len())?;
    let mut error = 0.;
    for (i, b) in bounds.iter().enumerate() {
        p[i] = b.center;
        radii[i] = b.radius;
        if b.error > error {
            error = b.error;
        }
    }
    let r = Attributes::from_interleaved(&radii, bounds.len(), 1, 1, 0)?;
    let b =
        ctx.child(|ws| crate::compute_sphere_bounds(Positions::from_packed(&p), Some(r), ws))?;
    ctx.free(p)?;
    ctx.free(radii)?;
    Ok(LodBounds {
        center: b.center,
        radius: b.radius,
        error,
    })
}
fn clusterize(
    indices: &[u32],
    p: Positions<'_>,
    c: Config,
    refined: i32,
    moderate: bool,
    ctx: &mut Context<'_>,
) -> Result<(Vec<Pending>, Vec<u32>), Error> {
    let s = MeshletSettings {
        max_vertices: c.max_vertices,
        max_triangles: c.max_triangles,
    };
    let mut m = if !c.cluster_spatial && p.len() > indices.len().saturating_mul(4) {
        // Upstream switches to sparse adjacency for small groups of a large
        // source mesh. Compacting only the temporary builder input lets the
        // safe Rust builder use group-sized adjacency and live-vertex arrays.
        let (local_indices_generic, local_positions, originals) = compact_group(indices, p, ctx)?;
        let mut result = ctx.child(|ws| {
            crate::meshlet::build_meshlets_flex_validated(
                &local_indices_generic,
                Positions::from_packed(&local_positions),
                s,
                c.min_triangles,
                0.,
                c.cluster_split_factor,
                moderate,
                ws,
            )
        })?;
        for v in &mut result.vertices {
            *v = originals[*v as usize];
        }
        ctx.free(local_indices_generic)?;
        ctx.free(local_positions)?;
        ctx.free(originals)?;
        result
    } else {
        ctx.child(|ws| {
            if c.cluster_spatial {
                crate::meshlet::build_meshlets_spatial_validated(
                    indices,
                    p,
                    s,
                    c.min_triangles,
                    c.cluster_fill_weight,
                    moderate,
                    ws,
                )
            } else {
                crate::meshlet::build_meshlets_flex_validated(
                    indices,
                    p,
                    s,
                    c.min_triangles,
                    0.,
                    c.cluster_split_factor,
                    moderate,
                    ws,
                )
            }
        })?
    };
    let mut clusters = ctx.alloc::<Pending>(m.meshlets.len())?;
    let mut idx = ctx.alloc(indices.len())?;
    let mut offset = 0;
    for (i, d) in m.meshlets.iter().enumerate() {
        let v = &mut m.vertices[d.vertex_offset as usize..][..d.vertex_count as usize];
        let t = &mut m.triangles[d.triangle_offset as usize..][..d.triangle_count as usize * 3];
        if c.optimize_clusters {
            ctx.child(|ws| {
                crate::optimize_meshlet_level_in_place_generic(v, t, c.optimize_clusters_level, ws)
            })?;
        }
        clusters[i] = Pending {
            vertices: v.len(),
            offset,
            count: t.len(),
            refined,
            bounds: LodBounds::default(),
        };
        for &t in t.iter() {
            idx[offset] = v[t as usize];
            offset += 1;
        }
    }
    ctx.free(m.meshlets)?;
    ctx.free(m.vertices)?;
    ctx.free(m.triangles)?;
    Ok((clusters, idx))
}
fn compact_group(
    indices: &[u32],
    p: Positions<'_>,
    ctx: &mut Context<'_>,
) -> Result<CompactGroup, Error> {
    let size = indices
        .len()
        .checked_mul(2)
        .and_then(usize::checked_next_power_of_two)
        .ok_or(Error::SizeOverflow)?;
    let mut table = ctx.filled(size, u64::MAX)?;
    let mut local_indices_generic = ctx.copy::<u32>(&[])?;
    let mut local_positions = ctx.copy::<[f32; 3]>(&[])?;
    let mut originals = ctx.copy::<u32>(&[])?;
    ctx.grow(&mut local_indices_generic, indices.len())?;
    ctx.grow(&mut local_positions, indices.len())?;
    ctx.grow(&mut originals, indices.len())?;
    let mut count = 0usize;
    for &source in indices {
        let mut slot = source.wrapping_mul(0x9e3779b9) as usize & (size - 1);
        loop {
            ctx.tick(1)?;
            let entry = table[slot];
            if entry == u64::MAX {
                table[slot] = ((source as u64) << 32) | count as u64;
                local_positions.push(p.get(source as usize).ok_or(Error::IndexOutOfBounds)?);
                originals.push(source);
                local_indices_generic.push(count as u32);
                count += 1;
                break;
            }
            if entry >> 32 == source as u64 {
                local_indices_generic.push(entry as u32);
                break;
            }
            slot = (slot + 1) & (size - 1);
        }
    }
    ctx.free(table)?;
    Ok((local_indices_generic, local_positions, originals))
}
fn position_remap(p: Positions<'_>, ctx: &mut Context<'_>) -> Result<Vec<u32>, Error> {
    let mut size = 1usize;
    let target = p
        .len()
        .checked_add(p.len() / 4)
        .ok_or(Error::SizeOverflow)?;
    while size < target {
        size = size.checked_mul(2).ok_or(Error::SizeOverflow)?;
    }
    let mut table = ctx.alloc::<u32>(size)?;
    table.fill(u32::MAX);
    let mut out = ctx.alloc(p.len())?;
    let mask = size - 1;
    for (i, v) in out.iter_mut().enumerate() {
        let p0 = point(p, i as u32);
        let xyz = p0.map(|x| {
            let b = if x == 0. { 0 } else { x.to_bits() };
            b ^ (b >> 17)
        });
        let hash = xyz[0].wrapping_mul(73856093)
            ^ xyz[1].wrapping_mul(19349663)
            ^ xyz[2].wrapping_mul(83492791);
        let mut slot = hash as usize & mask;
        for probe in 0..size {
            ctx.tick(1)?;
            if table[slot] == u32::MAX {
                table[slot] = i as u32;
                break;
            }
            if point(p, table[slot]) == p0 {
                break;
            }
            slot = (slot + probe + 1) & mask;
        }
        *v = table[slot];
    }
    ctx.free(table)?;
    Ok(out)
}
fn partition(
    clusters: &mut [Pending],
    indices: &[u32],
    remap: &[u32],
    p: Positions<'_>,
    c: Config,
    ctx: &mut Context<'_>,
) -> Result<Vec<u32>, Error> {
    if clusters.len() <= c.partition_size {
        let mut o = ctx.alloc(2)?;
        o[1] = clusters.len() as u32;
        return Ok(o);
    }
    let mut counts = ctx.alloc(clusters.len())?;
    let mut idx = ctx.alloc(indices.len())?;
    let mut off = 0;
    for (i, cl) in clusters.iter().enumerate() {
        counts[i] = cl.count as u32;
        for &v in &indices[cl.offset..cl.offset + cl.count] {
            idx[off] = remap[v as usize];
            off += 1;
        }
    }
    let mut parts = ctx.child(|ws| {
        crate::partition_clusters_generic(
            &idx[..off],
            &counts,
            remap.len(),
            if c.partition_spatial { Some(p) } else { None },
            c.partition_size,
            ws,
        )
    })?;
    if c.partition_sort {
        let mut centers = ctx.alloc(parts.count)?;
        for (i, cl) in clusters.iter().enumerate() {
            centers[parts.assignments[i] as usize] = cl.bounds.center;
        }
        let order = ctx.child(|ws| {
            crate::spatial_sort_remap_generic::<u32>(Positions::from_packed(&centers), ws)
        })?;
        for v in &mut parts.assignments {
            *v = order[*v as usize];
        }
        ctx.free(centers)?;
        ctx.free(order)?;
    }
    let mut offsets = ctx.alloc::<u32>(parts.count + 1)?;
    for &v in &parts.assignments {
        offsets[v as usize + 1] += 1;
    }
    for i in 1..offsets.len() {
        offsets[i] += offsets[i - 1];
    }
    let mut write = ctx.alloc::<u32>(offsets.len())?;
    write.copy_from_slice(&offsets);
    let mut sorted = ctx.alloc(clusters.len())?;
    for (i, &cl) in clusters.iter().enumerate() {
        let w = &mut write[parts.assignments[i] as usize];
        sorted[*w as usize] = cl;
        *w += 1;
    }
    clusters.copy_from_slice(&sorted);
    ctx.free(counts)?;
    ctx.free(idx)?;
    ctx.free(parts.assignments)?;
    ctx.free(write)?;
    ctx.free(sorted)?;
    Ok(offsets)
}
// Partition replacement regions as indivisible weighted graph vertices. Moving
// siblings after partitioning damages both the balanced sizes and the boundary
// adjacency the partitioner optimized. Pending siblings are contiguous because
// ordered group assembly emits each replacement as one run.
fn partition_regions(
    clusters: &mut [Pending],
    indices: &[u32],
    remap: &[u32],
    p: Positions<'_>,
    c: Config,
    ctx: &mut Context<'_>,
) -> Result<Vec<u32>, Error> {
    if clusters.len() <= c.partition_size || clusters.iter().all(|cl| cl.refined < 0) {
        return partition(clusters, indices, remap, p, c, ctx);
    }
    let mut starts = ctx.alloc::<usize>(0)?;
    for (i, cl) in clusters.iter().enumerate() {
        ctx.tick(1)?;
        if i == 0 || cl.refined < 0 || cl.refined != clusters[i - 1].refined {
            v2::grow_output(ctx, &mut starts, 1)?;
            starts.push(i);
        }
    }
    v2::grow_output(ctx, &mut starts, 1)?;
    starts.push(clusters.len());
    let units = starts.len() - 1;
    let mut counts = ctx.alloc::<u32>(units)?;
    let mut weights = ctx.alloc::<u32>(units)?;
    let mut idx = ctx.alloc::<u32>(indices.len())?;
    let mut off = 0;
    for (unit, pair) in starts.windows(2).enumerate() {
        weights[unit] = u32::try_from(pair[1] - pair[0]).map_err(|_| Error::SizeOverflow)?;
        for cl in &clusters[pair[0]..pair[1]] {
            ctx.tick(cl.count)?;
            counts[unit] = counts[unit]
                .checked_add(cl.count as u32)
                .ok_or(Error::SizeOverflow)?;
            for &v in &indices[cl.offset..cl.offset + cl.count] {
                idx[off] = remap[v as usize];
                off += 1;
            }
        }
    }
    let mut assignments = ctx.alloc::<u32>(units)?;
    let mut parts = 0;
    // A partial replacement can occupy an entire nominal partition. Give it
    // room to join another region on the next level; otherwise the same
    // boundary locks can strand it in a singleton partition indefinitely.
    let region_partition_size = weights
        .iter()
        .copied()
        .max()
        .map_or(c.partition_size, |weight| {
            c.partition_size.max((weight as usize).saturating_mul(2))
        });
    ctx.child(|ws| {
        parts = crate::partition::partition_weighted(
            &mut assignments,
            &idx[..off],
            &counts,
            Some(&weights),
            remap.len(),
            if c.partition_spatial { Some(p) } else { None },
            region_partition_size,
            &mut Context::new(ws)?,
        )?;
        Ok(())
    })?;
    if c.partition_sort {
        let mut centers = ctx.alloc(parts)?;
        for (unit, pair) in starts.windows(2).enumerate() {
            centers[assignments[unit] as usize] = clusters[pair[1] - 1].bounds.center;
        }
        let order = ctx.child(|ws| {
            crate::spatial_sort_remap_generic::<u32>(Positions::from_packed(&centers), ws)
        })?;
        for v in &mut assignments {
            *v = order[*v as usize];
        }
        ctx.free(centers)?;
        ctx.free(order)?;
    }
    let mut offsets = ctx.alloc::<u32>(parts + 1)?;
    for (&part, &weight) in assignments.iter().zip(&weights) {
        offsets[part as usize + 1] += weight;
    }
    for i in 1..offsets.len() {
        offsets[i] += offsets[i - 1];
    }
    let mut write = ctx.copy(&offsets)?;
    let mut sorted = ctx.alloc::<Pending>(clusters.len())?;
    for (unit, pair) in starts.windows(2).enumerate() {
        ctx.tick(pair[1] - pair[0])?;
        let at = &mut write[assignments[unit] as usize];
        let len = pair[1] - pair[0];
        sorted[*at as usize..*at as usize + len].copy_from_slice(&clusters[pair[0]..pair[1]]);
        *at += len as u32;
    }
    clusters.copy_from_slice(&sorted);
    ctx.free(starts)?;
    ctx.free(counts)?;
    ctx.free(weights)?;
    ctx.free(idx)?;
    ctx.free(assignments)?;
    ctx.free(write)?;
    ctx.free(sorted)?;
    Ok(offsets)
}
// Reuse the existing byte-sized boundary storage as simplifier flags. Bit 7
// is private discovery state and is removed from every entry before return.
fn lock_boundary(
    locks: &mut [support::VertexFlags],
    clusters: &[Pending],
    offsets: &[u32],
    indices: &[u32],
    remap: &[u32],
    flags: Option<&[VertexFlags]>,
    ctx: &mut Context<'_>,
) -> Result<(), Error> {
    ctx.tick(locks.len())?;
    for l in locks.iter_mut() {
        *l.boundary_bits_mut() &= !(1 | 128);
    }
    for pair in offsets.windows(2) {
        for cl in &clusters[pair[0] as usize..pair[1] as usize] {
            for &v in &indices[cl.offset..cl.offset + cl.count] {
                ctx.tick(1)?;
                let r = remap[v as usize] as usize;
                let bits = locks[r].bits();
                *locks[r].boundary_bits_mut() |= bits >> 7;
            }
        }
        for cl in &clusters[pair[0] as usize..pair[1] as usize] {
            for &v in &indices[cl.offset..cl.offset + cl.count] {
                ctx.tick(1)?;
                *locks[remap[v as usize] as usize].boundary_bits_mut() |= 128;
            }
        }
    }
    for (i, &r) in remap.iter().enumerate() {
        let bits = (locks[r as usize].bits() & 1) | (locks[i].bits() & 2);
        *locks[i].boundary_bits_mut() = bits;
        if let Some(f) = flags {
            *locks[i].boundary_bits_mut() |= f[i].bits();
        }
    }
    Ok(())
}

#[cfg(test)]
mod region_partition_tests {
    use super::*;

    #[test]
    fn full_partial_regions_can_merge_and_release_their_shared_boundary() {
        let positions: Vec<_> = (0..=16)
            .flat_map(|x| [[x as f32, 0., 0.], [x as f32, 1., 0.]])
            .collect();
        let indices: Vec<u32> = (0..16)
            .flat_map(|x| [2 * x, 2 * x + 2, 2 * x + 1, 2 * x + 1, 2 * x + 2, 2 * x + 3])
            .collect();
        let mut clusters: Vec<_> = (0..32)
            .map(|i| Pending {
                offset: i * 3,
                count: 3,
                refined: (i / 16) as i32,
                ..Pending::default()
            })
            .collect();
        let remap: Vec<u32> = (0..positions.len() as u32).collect();
        let mut locks = alloc::vec![support::VertexFlags::default(); positions.len()];
        let mut workspace = Workspace::default();
        let mut ctx = Context::new(&mut workspace).expect("workspace");
        lock_boundary(
            &mut locks,
            &clusters,
            &[0, 16, 32],
            &indices,
            &remap,
            None,
            &mut ctx,
        )
        .expect("initial boundaries");
        assert_ne!(locks[16].bits() & 1, 0);
        let offsets = partition_regions(
            &mut clusters,
            &indices,
            &remap,
            Positions::from_packed(&positions),
            default_config(128).expect("config"),
            &mut ctx,
        )
        .expect("partition");
        lock_boundary(
            &mut locks, &clusters, &offsets, &indices, &remap, None, &mut ctx,
        )
        .expect("merged boundaries");
        assert_eq!(locks[16].bits() & 1, 0);
        assert_eq!(locks[17].bits() & 1, 0);
    }
}

fn simplify(
    indices: &[u32],
    mesh: &MeshGeneric<'_>,
    locks: &[support::VertexFlags],
    c: Config,
    target: usize,
    measured: bool,
    ctx: &mut Context<'_>,
) -> Result<(Vec<u32>, f32, bool), Error> {
    let p = support::Positions::from_packed(mesh.positions);
    debug_assert!(locks.iter().all(|f| f.bits() & !7 == 0));
    let a = match mesh.attributes {
        Some(source) => support::Attributes::from_source(source),
        None => support::Attributes::from_interleaved(&[], mesh.positions.len(), 0, 0, 0)?,
    };
    let mut bits = 2 | 4;
    if c.simplify_error_clamped {
        bits |= 256;
    }
    if c.simplify_permissive {
        bits |= 32;
    }
    if c.simplify_regularize {
        bits |= 16;
    }
    if c.simplify_preserve_folds {
        bits |= 128;
    }
    let mut run = |bits: u32| -> Result<support::SimplifiedMesh, Error> {
        let limits = ctx.remaining_limits()?;
        let mut ws = support::Workspace::new(support::Limits {
            max_bytes: limits.max_bytes,
            max_work: limits.max_work,
        });
        let options = support::SimplifyOptions::from_bits(bits)?;
        let result = support::simplify_validated(
            indices,
            p,
            a,
            mesh.attribute_weights,
            locks,
            support::SimplifySettings {
                target_index_count: target,
                target_error: f32::MAX,
                options,
            },
            &mut ws,
        );
        ctx.absorb(
            ws.usage().bytes,
            ws.usage().work,
            result.as_ref().map_or(0, |r| r.indices.capacity() * 4),
        )?;
        result
    };
    let mut result = run(bits)?;
    if result.indices.len() > target && c.simplify_fallback_permissive && !c.simplify_permissive {
        let next = run(bits | 32)?;
        ctx.free(result.indices)?;
        result = next;
    }
    // A measured-policy step that still removed triangles is kept as a partial
    // step instead of degrading to grid clustering; the next level retries it.
    let mut sloppy = false;
    if result.indices.len() > target
        && c.simplify_fallback_sloppy
        && !(measured && result.indices.len() < indices.len())
    {
        sloppy = true;
        let mut subset = ctx.alloc::<[f32; 3]>(indices.len())?;
        let mut slocks = ctx.alloc(indices.len())?;
        let mut seq = ctx.alloc(indices.len())?;
        for (i, &v) in indices.iter().enumerate() {
            subset[i] = mesh.positions[v as usize];
            slocks[i] = support::VertexFlags::from_bits(locks[v as usize].bits() & 1)?;
            seq[i] = i as u32;
        }
        let p = support::Positions::from_packed(&subset);
        let limits = ctx.remaining_limits()?;
        let mut ws = support::Workspace::new(support::Limits {
            max_bytes: limits.max_bytes,
            max_work: limits.max_work,
        });
        let next = support::simplify_sloppy(&seq, p, Some(&slocks), target, f32::MAX, &mut ws);
        ctx.absorb(
            ws.usage().bytes,
            ws.usage().work,
            next.as_ref().map_or(0, |r| r.indices.capacity() * 4),
        )?;
        ctx.free(result.indices)?;
        result = next?;
        result.error *= support::simplify_scale(p)?;
        if !measured {
            result.error *= c.simplify_error_factor_sloppy;
        }
        for v in &mut result.indices {
            *v = indices[*v as usize];
        }
        ctx.free(subset)?;
        ctx.free(slocks)?;
        ctx.free(seq)?;
    }
    if result.indices.is_empty() && !indices.is_empty() {
        let mut fallback = ctx.alloc(3)?;
        fallback.copy_from_slice(&indices[..3]);
        ctx.free(result.indices)?;
        result.indices = fallback;
    }
    if !measured && c.simplify_error_edge_limit > 0. {
        let mut maxsq = 0f32;
        for t in indices.as_chunks::<3>().0 {
            ctx.tick(1)?;
            let a = mesh.positions[t[0] as usize];
            let b = mesh.positions[t[1] as usize];
            let cc = mesh.positions[t[2] as usize];
            let (ab, ac, bc) = (sub(a, b), sub(a, cc), sub(b, cc));
            let (ab, ac, bc) = (
                finite(dot(ab, ab))?,
                finite(dot(ac, ac))?,
                finite(dot(bc, bc))?,
            );
            let max = ab.max(ac).max(bc);
            let min = ab.min(ac).min(bc);
            maxsq = maxsq.max(min.max(max / 4.));
        }
        result.error = result
            .error
            .min(crate::math::sqrt(maxsq) * c.simplify_error_edge_limit);
    }
    finite(result.error)?;
    Ok((result.indices, result.error, sloppy))
}
fn edge_slot(table: &[u64], key: u64, ctx: &mut Context<'_>) -> Result<usize, Error> {
    let mask = table.len() - 1;
    let mut h = (key.wrapping_mul(0x9e3779b97f4a7c15) >> 32) as usize & mask;
    while table[h] != u64::MAX && table[h] != key {
        ctx.tick(1)?;
        h = (h + 1) & mask;
    }
    Ok(h)
}
fn boundary_area(
    p: Positions<'_>,
    indices: &[u32],
    locks: &[support::VertexFlags],
    remap: &[u32],
    table: &mut [u64],
    ctx: &mut Context<'_>,
) -> Result<f32, Error> {
    table.fill(u64::MAX);
    for t in indices.as_chunks::<3>().0 {
        for e in 0..3 {
            ctx.tick(1)?;
            let (a, b) = (remap[t[e] as usize], remap[t[(e + 1) % 3] as usize]);
            let key = (a as u64) << 32 | b as u64;
            let slot = edge_slot(table, key, ctx)?;
            table[slot] = key;
        }
    }
    let mut area = 0.;
    for t in indices.as_chunks::<3>().0 {
        let mut border = false;
        for e in 0..3 {
            ctx.tick(1)?;
            let (a, b) = (remap[t[e] as usize], remap[t[(e + 1) % 3] as usize]);
            let key = (b as u64) << 32 | a as u64;
            border |= (locks[a as usize].bits() & locks[b as usize].bits() & 1) == 0
                && table[edge_slot(table, key, ctx)?] == u64::MAX;
        }
        if border {
            let a = point(p, t[0]);
            let nt = cross(sub(point(p, t[1]), a), sub(point(p, t[2]), a));
            area = finite(area + crate::math::sqrt(finite(dot(nt, nt))?) * 0.5)?;
        }
    }
    Ok(area)
}
fn dilate(
    mesh: &mut MeshGeneric<'_>,
    old: &[u32],
    new: &[u32],
    locks: &[support::VertexFlags],
    remap: &[u32],
    bounds: &mut LodBounds,
    offsets: &mut [[f32; 4]],
    ctx: &mut Context<'_>,
) -> Result<(), Error> {
    let mut size = 16usize;
    let capacity = old
        .len()
        .checked_add(old.len() / 2)
        .ok_or(Error::SizeOverflow)?;
    while size < capacity {
        size = size.checked_mul(2).ok_or(Error::SizeOverflow)?;
    }
    let mut table = ctx.alloc::<u64>(size)?;
    let p = Positions::from_packed(mesh.positions);
    let oa = boundary_area(p, old, locks, remap, &mut table, ctx)?;
    if oa == 0. {
        ctx.free(table)?;
        return Ok(());
    }
    let na = boundary_area(p, new, locks, remap, &mut table, ctx)?;
    if na >= oa || na < oa / 4. {
        ctx.free(table)?;
        return Ok(());
    }
    let mut perimeter = 0.;
    for t in new.as_chunks::<3>().0 {
        for e in 0..3 {
            ctx.tick(1)?;
            let (a, b) = (
                remap[t[e] as usize] as usize,
                remap[t[(e + 1) % 3] as usize] as usize,
            );
            let key = (b as u64) << 32 | a as u64;
            if locks[a].bits() & locks[b].bits() & 1 != 0
                || table[edge_slot(&table, key, ctx)?] != u64::MAX
            {
                continue;
            }
            let va = point(p, t[e]);
            let vb = point(p, t[(e + 1) % 3]);
            let vc = point(p, t[(e + 2) % 3]);
            let ev = sub(vb, va);
            let el = crate::math::sqrt(finite(dot(ev, ev))?);
            let cv = sub(va, vc);
            let cp = dot(cv, ev) / if el > 0. { el * el } else { 1. };
            let nv = [cv[0] - ev[0] * cp, cv[1] - ev[1] * cp, cv[2] - ev[2] * cp];
            let nl = crate::math::sqrt(finite(dot(nv, nv))?);
            let ns = if nl > 0. { el / nl } else { 0. };
            for v in [a, b] {
                if locks[v].bits() & 1 == 0 {
                    for (k, &n) in nv.iter().enumerate() {
                        offsets[v][k] += n * ns;
                    }
                    offsets[v][3] += el;
                }
            }
            perimeter += el;
        }
    }
    let distance = if perimeter > 0. {
        (oa - na) / perimeter
    } else {
        0.
    };
    for &v in new {
        ctx.tick(1)?;
        let r = remap[v as usize] as usize;
        if locks[r].bits() & 1 != 0 {
            continue;
        }
        let n = &mut offsets[r];
        if n[3] > 0. {
            let nn = [n[0] / n[3], n[1] / n[3], n[2] / n[3]];
            let l = dot(nn, nn);
            let ns = distance / if l > 0.15 { l } else { 0.15 };
            for (k, &x) in nn.iter().enumerate() {
                mesh.positions[r][k] = finite(mesh.positions[r][k] + x * ns)?;
            }
            *n = [0.; 4];
            let d = sub(mesh.positions[r], bounds.center);
            bounds.radius = bounds.radius.max(crate::math::sqrt(finite(dot(d, d))?));
        }
        mesh.positions[v as usize] = mesh.positions[r];
    }
    ctx.free(table)?;
    Ok(())
}
fn output(
    group: &[Pending],
    idx: &[u32],
    mesh: &MeshGeneric<'_>,
    c: Config,
    bounds: LodBounds,
    depth: i32,
    diagnostics: v2::GroupDiagnostics,
    callback: &mut impl FnMut(
        Group,
        v2::GroupDiagnostics,
        Vec<ClusterGeneric>,
        &[[f32; 3]],
        &mut Context<'_>,
    ) -> Result<i32, Error>,
    ctx: &mut Context<'_>,
) -> Result<i32, Error> {
    let mut out = ctx.alloc::<ClusterGeneric>(group.len())?;
    for (i, cl) in group.iter().enumerate() {
        let indices = &idx[cl.offset..cl.offset + cl.count];
        let b = if c.optimize_bounds && cl.refined != -1 {
            let b = ctx.child(|ws| {
                crate::compute_cluster_bounds_generic(
                    indices,
                    Positions::from_packed(mesh.positions),
                    ws,
                )
            })?;
            LodBounds {
                center: b.center,
                radius: b.radius,
                error: cl.bounds.error,
            }
        } else {
            cl.bounds
        };
        let copy = ctx.copy(indices)?;
        out[i] = ClusterGeneric {
            refined: cl.refined,
            bounds: b,
            indices: copy,
            vertex_count: cl.vertices,
        };
    }
    callback(
        Group {
            depth,
            simplified: bounds,
        },
        diagnostics,
        out,
        mesh.positions,
        ctx,
    )
}
fn validate(mesh: &MeshGeneric<'_>, c: Config, ctx: &mut Context<'_>) -> Result<(), Error> {
    crate::build_meshlets_bound(mesh.indices.len(), c.max_vertices, c.max_triangles)?;
    if c.min_triangles == 0
        || c.min_triangles > c.max_triangles
        || c.partition_size == 0
        || c.optimize_clusters_level > 9
    {
        return Err(Error::InvalidParameter);
    }
    for v in [
        c.cluster_fill_weight,
        c.cluster_split_factor,
        c.simplify_ratio,
        c.simplify_threshold,
        c.simplify_error_merge_previous,
        c.simplify_error_merge_additive,
        c.simplify_error_factor_sloppy,
        c.simplify_error_edge_limit,
    ] {
        if !v.is_finite() || v < 0. {
            return Err(Error::InvalidParameter);
        }
    }
    if c.simplify_ratio >= 1. || c.simplify_threshold >= 1. {
        return Err(Error::InvalidParameter);
    }
    let n = mesh.positions.len();
    ctx.positions(Positions::from_packed(mesh.positions))?;
    ctx.topology(mesh.indices, n)?;
    crate::validate_vertex_flags(mesh.vertex_lock, n)?;
    if mesh.attribute_weights.len() > 32 {
        return Err(Error::InvalidLayout);
    }
    if let Some(a) = mesh.attributes {
        if a.len() != n || a.components() != mesh.attribute_weights.len() {
            return Err(Error::InvalidLayout);
        }
        ctx.tick(n.checked_mul(a.components()).ok_or(Error::SizeOverflow)?)?;
        for i in 0..n {
            for j in 0..a.components() {
                finite(a.get(i, j).ok_or(Error::InvalidLayout)?)?;
            }
        }
    } else if !mesh.attribute_weights.is_empty() {
        return Err(Error::InvalidLayout);
    }
    for &w in mesh.attribute_weights {
        if !w.is_finite() || w < 0. {
            return Err(Error::InvalidParameter);
        }
    }
    if mesh.attribute_weights.len() < 32
        && mesh.attribute_protect_mask >> mesh.attribute_weights.len() != 0
    {
        return Err(Error::InvalidParameter);
    }
    Ok(())
}
#[derive(Clone, Copy)]
struct BuildPolicy<'a> {
    material_component: Option<usize>,
    alpha: Option<v2::AlphaCoverage<'a>>,
}
struct Prepared {
    merged_idx: Vec<u32>,
    gb: Vec<LodBounds>,
    simplified: Vec<u32>,
    bounds: LodBounds,
    stuck: bool,
    material_mixed: bool,
    alpha_failed: bool,
    diagnostics: v2::GroupDiagnostics,
}
fn prepare_group(
    group: &[Pending],
    idx: &[u32],
    mesh: &MeshGeneric<'_>,
    locks: &[support::VertexFlags],
    c: Config,
    ctx: &mut Context<'_>,
    policy: Option<BuildPolicy<'_>>,
) -> Result<Prepared, Error> {
    let n = group.iter().map(|cl| cl.count).sum();
    let mut merged_idx = ctx.alloc::<u32>(n)?;
    let mut write = 0;
    let mut gb = ctx.alloc::<LodBounds>(group.len())?;
    for (i, cl) in group.iter().enumerate() {
        merged_idx[write..write + cl.count].copy_from_slice(&idx[cl.offset..cl.offset + cl.count]);
        write += cl.count;
        gb[i] = cl.bounds;
    }
    let target = ((merged_idx.len() / 3) as f32 * c.simplify_ratio) as usize * 3;
    let mut bounds = merged(&gb, ctx)?;
    // Every accepted partial step strictly removes triangles. Repartitioning
    // its survivors can release boundary locks at the following level.
    let allow_partial = policy.is_some();
    let (simplified, error, sloppy_fallback) =
        simplify(&merged_idx, mesh, locks, c, target, allow_partial, ctx)?;
    let mixed = policy
        .and_then(|p| p.material_component)
        .is_some_and(|slot| {
            mesh.attributes.is_some_and(|a| {
                simplified.as_chunks::<3>().0.iter().any(|t| {
                    a.get(t[0] as usize, slot) != a.get(t[1] as usize, slot)
                        || a.get(t[0] as usize, slot) != a.get(t[2] as usize, slot)
                })
            })
        });
    let over_threshold = simplified.len() as f32 > merged_idx.len() as f32 * c.simplify_threshold;
    let partial = allow_partial && over_threshold && simplified.len() < merged_idx.len();
    let stuck =
        mixed || (policy.is_some() && simplified.is_empty()) || (over_threshold && !partial);
    let alpha_failed = if !stuck {
        if let Some(alpha) = policy.and_then(|p| p.alpha) {
            v2::alpha_failed(
                &merged_idx,
                &simplified,
                mesh,
                policy.and_then(|p| p.material_component),
                alpha,
                ctx,
            )?
        } else {
            false
        }
    } else {
        false
    };
    let status = if mixed {
        v2::GroupStatus::MixedMaterial
    } else if simplified.is_empty() {
        v2::GroupStatus::Empty
    } else if stuck {
        v2::GroupStatus::RetainedRatio
    } else if alpha_failed {
        v2::GroupStatus::AlphaCoverage
    } else if partial {
        v2::GroupStatus::PartialReduction
    } else {
        v2::GroupStatus::Simplified
    };
    let simplifier_error = error;
    let inherited_error = bounds.error;
    let stuck = stuck || alpha_failed;
    let step_error = if policy.is_some() && !stuck {
        // Measure accepted geometry independently of the simplifier estimate.
        v2::step_error(&merged_idx, &simplified, mesh.positions, 0.0, ctx)?
    } else {
        error
    };
    // Keep the regular estimate as a floor for missed samples. The sloppy
    // grid estimate can saturate every coarser level through inheritance.
    let error = if sloppy_fallback {
        step_error
    } else {
        step_error.max(simplifier_error)
    };
    if stuck {
        bounds.error = f32::MAX;
    } else {
        bounds.error = finite(
            (bounds.error * c.simplify_error_merge_previous).max(error)
                + error * c.simplify_error_merge_additive,
        )?;
    }
    Ok(Prepared {
        merged_idx,
        gb,
        simplified,
        bounds,
        stuck,
        material_mixed: mixed,
        alpha_failed,
        diagnostics: v2::GroupDiagnostics {
            status,
            simplifier_error,
            step_error,
            source_error: 0.0,
            inherited_error,
            sloppy_fallback,
            error_measured: false,
        },
    })
}
fn build_internal(
    parallel: bool,
    c: Config,
    mesh: MeshGeneric<'_>,
    callback: &mut impl FnMut(
        Group,
        v2::GroupDiagnostics,
        Vec<ClusterGeneric>,
        &[[f32; 3]],
        &mut Context<'_>,
    ) -> Result<i32, Error>,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    let mut ctx = Context::new(workspace)?;
    build_in_context_mode(c, mesh, callback, &mut ctx, parallel, None).map(|_| ())
}
fn build_in_context(
    c: Config,
    mesh: MeshGeneric<'_>,
    callback: &mut impl FnMut(
        Group,
        v2::GroupDiagnostics,
        Vec<ClusterGeneric>,
        &[[f32; 3]],
        &mut Context<'_>,
    ) -> Result<i32, Error>,
    ctx: &mut Context<'_>,
) -> Result<(), Error> {
    build_in_context_mode(c, mesh, callback, ctx, false, None).map(|_| ())
}
fn build_in_context_mode(
    c: Config,
    mut mesh: MeshGeneric<'_>,
    callback: &mut impl FnMut(
        Group,
        v2::GroupDiagnostics,
        Vec<ClusterGeneric>,
        &[[f32; 3]],
        &mut Context<'_>,
    ) -> Result<i32, Error>,
    ctx: &mut Context<'_>,
    _parallel: bool,
    policy: Option<BuildPolicy<'_>>,
) -> Result<(usize, usize, usize), Error> {
    validate(&mesh, c, ctx)?;
    let (mut stuck_count, mut mixed_count, mut alpha_count) = (0, 0, 0);
    let mut moderate = ctx.moderate;
    let p = Positions::from_packed(mesh.positions);
    let remap = position_remap(p, ctx)?;
    let mut locks = ctx.alloc::<support::VertexFlags>(p.len())?;
    if let Some(a) = mesh.attributes {
        for (i, l) in locks.iter_mut().enumerate() {
            let r = remap[i] as usize;
            for j in 0..a.components() {
                if r != i
                    && mesh.attribute_protect_mask & (1u32 << j) != 0
                    && a.get(i, j) != a.get(r, j)
                {
                    *l.boundary_bits_mut() |= 2;
                }
            }
        }
    }
    let mut offsets = ctx.alloc::<[f32; 4]>(if c.simplify_dilate_borders {
        p.len()
    } else {
        0
    })?;
    let (mut clusters, mut idx) = clusterize(mesh.indices, p, c, -1, moderate, ctx)?;
    for cl in &mut clusters {
        let b = ctx.child(|ws| {
            crate::meshlet_util::compute_cluster_bounds_validated(
                &idx[cl.offset..cl.offset + cl.count],
                p,
                moderate,
                ws,
            )
        })?;
        cl.bounds = LodBounds {
            center: b.center,
            radius: b.radius,
            error: 0.,
        };
    }
    let mut depth = 0;
    // Leave the last level available to pin the current geometry. Even a
    // progressing replacement can leave multiple clusters for another step.
    while clusters.len() > 1
        && (policy.is_none() || (depth as u32) + 1 < dag_format::v2::MAX_LEVELS)
    {
        let partitioner = if policy.is_some() {
            partition_regions
        } else {
            partition
        };
        let group_offsets = partitioner(
            &mut clusters,
            &idx,
            &remap,
            Positions::from_packed(mesh.positions),
            c,
            ctx,
        )?;
        lock_boundary(
            &mut locks,
            &clusters,
            &group_offsets,
            &idx,
            &remap,
            mesh.vertex_lock,
            ctx,
        )?;
        let mut pending = ctx.alloc::<Pending>(idx.len() / 3)?;
        let mut pi = ctx.alloc::<u32>(idx.len())?;
        let (mut pc, mut ic) = (0, 0);
        #[cfg(feature = "parallel")]
        let mut computed = if _parallel && parallel::eligible(c, ctx.workspace.limits()) {
            let remaining_work = ctx.remaining_limits()?.max_work;
            parallel::level(
                c,
                &mesh,
                &locks,
                &clusters,
                &idx,
                &group_offsets,
                moderate,
                remaining_work,
                policy,
            )
            .map(Vec::into_iter)
        } else {
            None
        };
        for pair in group_offsets.windows(2) {
            let group = &clusters[pair[0] as usize..pair[1] as usize];
            #[cfg(feature = "parallel")]
            let speculative = computed.as_mut().and_then(|items| items.next());
            #[cfg(not(feature = "parallel"))]
            let speculative: Option<Prepared> = None;
            #[cfg(feature = "parallel")]
            let (prepared, clustered) = if let Some(item) = speculative {
                ctx.absorb(item.usage.bytes, item.usage.work, item.live)?;
                (item.prepared, item.clustered)
            } else {
                (
                    prepare_group(group, &idx, &mesh, &locks, c, ctx, policy)?,
                    None,
                )
            };
            #[cfg(not(feature = "parallel"))]
            let (prepared, _clustered) = (
                prepare_group(group, &idx, &mesh, &locks, c, ctx, policy)?,
                speculative,
            );
            let Prepared {
                merged_idx,
                gb,
                simplified,
                mut bounds,
                stuck,
                material_mixed,
                alpha_failed,
                diagnostics,
            } = prepared;
            if stuck {
                stuck_count += 1;
                mixed_count += usize::from(material_mixed);
                alpha_count += usize::from(alpha_failed);
                output(
                    group,
                    &idx,
                    &mesh,
                    c,
                    bounds,
                    depth,
                    diagnostics,
                    callback,
                    ctx,
                )?;
                ctx.free(merged_idx)?;
                ctx.free(gb)?;
                ctx.free(simplified)?;
                continue;
            }
            let refined = output(
                group,
                &idx,
                &mesh,
                c,
                bounds,
                depth,
                diagnostics,
                callback,
                ctx,
            )?;
            if c.simplify_dilate_borders {
                dilate(
                    &mut mesh,
                    &merged_idx,
                    &simplified,
                    &locks,
                    &remap,
                    &mut bounds,
                    &mut offsets,
                    ctx,
                )?;
                // Dilation can move a coordinate beyond the validated range.
                // Use the checked flex/bounds path for this and later levels.
                moderate = false;
            }
            #[cfg(feature = "parallel")]
            let (new, ni) = if let Some(item) = clustered {
                ctx.absorb(item.usage.bytes, item.usage.work, item.live)?;
                let (mut new, ni) = item.output;
                for cl in &mut new {
                    cl.refined = refined;
                }
                (new, ni)
            } else {
                clusterize(
                    &simplified,
                    Positions::from_packed(mesh.positions),
                    c,
                    refined,
                    moderate,
                    ctx,
                )?
            };
            #[cfg(not(feature = "parallel"))]
            let (new, ni) = clusterize(
                &simplified,
                Positions::from_packed(mesh.positions),
                c,
                refined,
                moderate,
                ctx,
            )?;
            for &original in &new {
                let mut cl = original;
                cl.offset += ic;
                cl.bounds = bounds;
                pending[pc] = cl;
                pc += 1;
            }
            pi[ic..ic + ni.len()].copy_from_slice(&ni);
            ic += ni.len();
            ctx.free(new)?;
            ctx.free(ni)?;
            ctx.free(merged_idx)?;
            ctx.free(gb)?;
            ctx.free(simplified)?;
        }
        ctx.free(group_offsets)?;
        pending.truncate(pc);
        pi.truncate(ic);
        ctx.free(clusters)?;
        ctx.free(idx)?;
        clusters = pending;
        idx = pi;
        depth += 1;
    }
    if !clusters.is_empty() {
        let (mut bounds, status) = if clusters.len() == 1 {
            (clusters[0].bounds, v2::GroupStatus::Root)
        } else {
            let mut group_bounds = ctx.alloc::<LodBounds>(clusters.len())?;
            for (bounds, cluster) in group_bounds.iter_mut().zip(&clusters) {
                *bounds = cluster.bounds;
            }
            let bounds = merged(&group_bounds, ctx)?;
            ctx.free(group_bounds)?;
            stuck_count += 1;
            (bounds, v2::GroupStatus::DepthLimit)
        };
        bounds.error = f32::MAX;
        output(
            &clusters,
            &idx,
            &mesh,
            c,
            bounds,
            depth,
            v2::GroupDiagnostics {
                status,
                ..v2::GroupDiagnostics::default()
            },
            callback,
            ctx,
        )?;
    }
    ctx.free(remap)?;
    ctx.free(locks)?;
    ctx.free(offsets)?;
    ctx.free(clusters)?;
    ctx.free(idx)?;
    Ok((stuck_count, mixed_count, alpha_count))
}
/// `clodBuild`, with explicit callback return identifiers. A late error may leave
/// dilated positions changed and callbacks already emitted.
///
/// # Errors
/// Same errors as [`build`]. Any `Error` returned by the output callback is propagated.
///
/// # Panics
/// Panics if the supplied callback panics.
pub fn build_with_output_generic<I: crate::Index>(
    c: Config,
    mesh: MeshGeneric<'_, I>,
    output: impl FnMut(Group, &[ClusterGeneric<I>]) -> Result<i32, Error>,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    I::with_input(mesh.indices, workspace, |indices, workspace| {
        let mesh = MeshGeneric {
            indices,
            positions: mesh.positions,
            attributes: mesh.attributes,
            vertex_lock: mesh.vertex_lock,
            attribute_weights: mesh.attribute_weights,
            attribute_protect_mask: mesh.attribute_protect_mask,
        };
        build_with_output_u32::<I>(c, mesh, output, workspace)
    })
}

fn build_with_output_u32<I: crate::Index>(
    c: Config,
    mesh: MeshGeneric<'_>,
    output: impl FnMut(Group, &[ClusterGeneric<I>]) -> Result<i32, Error>,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    build_with_output_mode(false, c, mesh, output, workspace)
}
fn build_with_output_mode<I: crate::Index>(
    parallel: bool,
    c: Config,
    mesh: MeshGeneric<'_>,
    mut output: impl FnMut(Group, &[ClusterGeneric<I>]) -> Result<i32, Error>,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    build_internal(
        parallel,
        c,
        mesh,
        &mut |g, _diagnostics, clusters, _positions, ctx| {
            let result = I::with_clusters(&clusters, ctx.bytes(), ctx.workspace, |clusters| {
                output(g, clusters)
            });
            for cl in &clusters {
                ctx.release(&cl.indices)?;
            }
            ctx.free(clusters)?;
            result
        },
        workspace,
    )
}
/// Allocating demo hierarchy. Refined identifiers index the returned group list.
/// Dilation may change positions even if a later operation fails.
///
/// # Errors
/// `InvalidLayout` for incompatible attributes/flags; `InvalidParameter` for unsupported configuration;
/// `InvalidTopology` or `IndexOutOfBounds` for invalid topology; `NumericalFailure` for non-finite geometry or calculations.
/// `SizeOverflow` for size overflow, `LimitExceeded` for exhausted limits, or `AllocationFailed` for failed reservation.
pub fn build_generic<I: crate::Index>(
    c: Config,
    mesh: MeshGeneric<'_, I>,
    workspace: &mut Workspace,
) -> Result<Vec<GroupOutputGeneric<I>>, Error> {
    I::with_input(mesh.indices, workspace, |indices, workspace| {
        let mesh = MeshGeneric {
            indices,
            positions: mesh.positions,
            attributes: mesh.attributes,
            vertex_lock: mesh.vertex_lock,
            attribute_weights: mesh.attribute_weights,
            attribute_protect_mask: mesh.attribute_protect_mask,
        };
        build_u32(c, mesh, workspace).and_then(|groups| I::from_groups(groups, workspace))
    })
}

fn build_u32(
    c: Config,
    mesh: MeshGeneric<'_>,
    workspace: &mut Workspace,
) -> Result<Vec<GroupOutputGeneric>, Error> {
    build_mode(false, c, mesh, workspace)
}
fn build_mode(
    parallel: bool,
    c: Config,
    mesh: MeshGeneric<'_>,
    workspace: &mut Workspace,
) -> Result<Vec<GroupOutputGeneric>, Error> {
    let mut result = Vec::new();
    build_internal(
        parallel,
        c,
        mesh,
        &mut |g, _diagnostics, clusters, _positions, ctx| {
            if result.len() >= i32::MAX as usize {
                return Err(Error::SizeOverflow);
            }
            let id = result.len() as i32;
            ctx.tick(1)?;
            ctx.grow(&mut result, 1)?;
            result.push(GroupOutputGeneric { group: g, clusters });
            Ok(id)
        },
        workspace,
    )?;
    Ok(result)
}
/// `clodLocalIndices`: first-visit local extraction.
///
/// # Errors
/// Same errors as [`crate::extract_meshlet_indices`].
pub fn local_indices_generic<I: crate::Index>(
    indices: &[I],
    workspace: &mut Workspace,
) -> Result<crate::LocalMeshletGeneric<I>, Error> {
    crate::extract_meshlet_indices_generic(indices, workspace)
}
/// `clodBuildHierarchyBound`: checked bound for a per-level spatial forest.
///
/// # Errors
/// `InvalidParameter` if `node_width` is below two; `SizeOverflow` if the bound overflows.
pub fn build_hierarchy_bound(
    group_count: usize,
    node_width: usize,
    level_count: usize,
) -> Result<usize, Error> {
    if node_width < 2 {
        return Err(Error::InvalidParameter);
    }
    let mut total = level_count;
    let mut frontier = group_count;
    while frontier > 1 {
        total = total
            .checked_add(frontier)
            .and_then(|n| n.checked_add(level_count))
            .ok_or(Error::SizeOverflow)?;
        frontier = frontier
            .checked_add(node_width - 1)
            .ok_or(Error::SizeOverflow)?
            / node_width;
    }
    Ok(total)
}
/// `clodBuildHierarchy`: every supplied level must have at least one group.
///
/// # Errors
/// `InvalidParameter` for invalid width, depths, bounds or missing levels; `NumericalFailure` for non-finite geometry or calculations.
/// `SizeOverflow` for size overflow, `LimitExceeded` for exhausted limits, or `AllocationFailed` for failed reservation.
pub fn build_hierarchy(
    groups: &[Group],
    node_width: usize,
    level_count: usize,
    workspace: &mut Workspace,
) -> Result<Vec<Node>, Error> {
    let mut ctx = Context::new(workspace)?;
    hierarchy_in_context(groups, node_width, level_count, &mut ctx)
}
fn hierarchy_in_context(
    groups: &[Group],
    node_width: usize,
    level_count: usize,
    ctx: &mut Context<'_>,
) -> Result<Vec<Node>, Error> {
    let bound = build_hierarchy_bound(groups.len(), node_width, level_count)?;
    if groups.len() > i32::MAX as usize || bound > u32::MAX as usize {
        return Err(Error::SizeOverflow);
    }
    ctx.tick(groups.len())?;
    for g in groups {
        if g.depth < 0
            || g.depth as usize >= level_count
            || !g.simplified.radius.is_finite()
            || g.simplified.radius < 0.
            || !g.simplified.error.is_finite()
            || g.simplified.error < 0.
            || g.simplified.center.iter().any(|v| !v.is_finite())
        {
            return Err(Error::InvalidParameter);
        }
    }
    let mut nodes = ctx.alloc::<Node>(bound)?;
    let mut row = ctx.alloc::<Node>(groups.len())?;
    let mut offset = level_count;
    for level in 0..level_count {
        ctx.tick(groups.len())?;
        let mut n = 0;
        for (i, g) in groups.iter().enumerate() {
            if g.depth as usize == level {
                row[n] = Node {
                    bounds: g.simplified,
                    group: i as i32,
                    child_offset: 0,
                    child_count: 0,
                };
                n += 1;
            }
        }
        if n == 0 {
            return Err(Error::InvalidParameter);
        }
        while n > 1 {
            let mut p = ctx.alloc(n)?;
            for i in 0..n {
                p[i] = row[i].bounds.center;
            }
            let order = ctx.child(|ws| {
                crate::spatial_cluster_points_generic::<u32>(
                    Positions::from_packed(&p),
                    node_width,
                    ws,
                )
            })?;
            ctx.tick(n.checked_mul(2).ok_or(Error::SizeOverflow)?)?;
            for i in 0..n {
                nodes[offset + i] = row[order[i] as usize];
            }
            let mut next = 0;
            for i in (0..n).step_by(node_width) {
                let count = node_width.min(n - i);
                let mut bs = ctx.alloc(count)?;
                for j in 0..count {
                    bs[j] = nodes[offset + i + j].bounds;
                }
                row[next] = Node {
                    bounds: merged(&bs, ctx)?,
                    group: -1,
                    child_offset: (offset + i) as u32,
                    child_count: count as u32,
                };
                next += 1;
                ctx.free(bs)?;
            }
            ctx.free(p)?;
            ctx.free(order)?;
            offset += n;
            n = next;
        }
        nodes[level] = row[0];
    }
    ctx.free(row)?;
    nodes.truncate(offset);
    Ok(nodes)
}

/// Opt-in intra-mesh parallel builder, not in C++ meshoptimizer.
///
/// Uses the current Rayon pool. Partitioning, boundary locks, callback emission
/// and assembly stay serial; each group's arithmetic and reduction order are
/// unchanged. Refined identifiers index the returned group list.
///
/// Parallel execution requires both limits to be maximal (`usize::MAX` bytes,
/// `u64::MAX` work) and border dilation disabled. All finite limits (including
/// defaults), dilation, a speculative group failure, or insufficient remaining
/// work for a conservative level bound select serial execution.
/// Single-group levels also run serially. This preserves serial error and
/// callback prefixes. `Usage` describes the serial logical peak and work;
/// simultaneous worker scratch, queued results and Rayon infrastructure are
/// additional physical memory, excluded from that logical measurement.
///
/// # Errors
/// Same as [`build`].
///
/// # Panics
/// Panics if Rayon cannot initialize its pool or a worker panics.
#[cfg(feature = "parallel")]
pub fn build_parallel_generic<I: crate::Index>(
    c: Config,
    mesh: MeshGeneric<'_, I>,
    workspace: &mut Workspace,
) -> Result<Vec<GroupOutputGeneric<I>>, Error> {
    I::with_input(mesh.indices, workspace, |indices, workspace| {
        let mesh = MeshGeneric {
            indices,
            positions: mesh.positions,
            attributes: mesh.attributes,
            vertex_lock: mesh.vertex_lock,
            attribute_weights: mesh.attribute_weights,
            attribute_protect_mask: mesh.attribute_protect_mask,
        };
        build_parallel_u32(c, mesh, workspace).and_then(|groups| I::from_groups(groups, workspace))
    })
}

#[cfg(feature = "parallel")]
fn build_parallel_u32(
    c: Config,
    mesh: MeshGeneric<'_>,
    workspace: &mut Workspace,
) -> Result<Vec<GroupOutputGeneric>, Error> {
    build_mode(true, c, mesh, workspace)
}

/// Opt-in parallel variant of [`build_with_output`], not in C++ meshoptimizer.
///
/// Fallback and memory rules are those of [`build_parallel`]. Callbacks run on
/// the calling thread in serial order and need not be `Send` or `Sync`. Their
/// returned IDs and errors take effect before any later callback is emitted.
///
/// # Errors
/// Same as [`build_with_output`], including callback errors.
///
/// # Panics
/// Panics if the callback or a worker panics, or Rayon cannot initialize its pool.
#[cfg(feature = "parallel")]
pub fn build_parallel_with_output_generic<I: crate::Index>(
    c: Config,
    mesh: MeshGeneric<'_, I>,
    output: impl FnMut(Group, &[ClusterGeneric<I>]) -> Result<i32, Error>,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    I::with_input(mesh.indices, workspace, |indices, workspace| {
        let mesh = MeshGeneric {
            indices,
            positions: mesh.positions,
            attributes: mesh.attributes,
            vertex_lock: mesh.vertex_lock,
            attribute_weights: mesh.attribute_weights,
            attribute_protect_mask: mesh.attribute_protect_mask,
        };
        build_parallel_with_output_u32::<I>(c, mesh, output, workspace)
    })
}

#[cfg(feature = "parallel")]
fn build_parallel_with_output_u32<I: crate::Index>(
    c: Config,
    mesh: MeshGeneric<'_>,
    output: impl FnMut(Group, &[ClusterGeneric<I>]) -> Result<i32, Error>,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    build_with_output_mode(true, c, mesh, output, workspace)
}

pub(crate) fn convert_groups<I: crate::Index>(
    groups: Vec<GroupOutputGeneric>,
    workspace: &mut Workspace,
) -> Result<Vec<GroupOutputGeneric<I>>, Error> {
    let mut live = crate::workspace::checked_bytes(
        groups.capacity(),
        core::mem::size_of::<GroupOutputGeneric>(),
    )?;
    for group in &groups {
        live = live
            .checked_add(crate::workspace::checked_bytes(
                group.clusters.capacity(),
                core::mem::size_of::<ClusterGeneric>(),
            )?)
            .ok_or(Error::SizeOverflow)?;
        for cluster in &group.clusters {
            live = live
                .checked_add(crate::workspace::checked_bytes(
                    cluster.indices.capacity(),
                    4,
                )?)
                .ok_or(Error::SizeOverflow)?;
        }
    }
    let mut budget = crate::budget::Budget::with_bytes(workspace, live);
    let mut result = budget.reserved(groups.len())?;
    for group in groups {
        let mut clusters = budget.reserved(group.clusters.len())?;
        for cluster in group.clusters {
            let mut indices = budget.reserved(cluster.indices.len())?;
            for value in cluster.indices {
                indices.push(I::from_u32(value)?);
            }
            clusters.push(ClusterGeneric {
                indices,
                refined: cluster.refined,
                bounds: cluster.bounds,
                vertex_count: cluster.vertex_count,
            });
        }
        result.push(GroupOutputGeneric {
            group: group.group,
            clusters,
        });
    }
    Ok(result)
}

/// The source-compatible u32 entry point; see [`build_with_output_generic`] for selectable index widths.
#[inline]
pub fn build_with_output(
    c: Config,
    mesh: Mesh<'_>,
    mut output: impl FnMut(Group, &[Cluster]) -> Result<i32, Error>,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    build_internal(
        false,
        c,
        mesh.into(),
        &mut |g, _diagnostics, clusters, _positions, ctx| {
            let clusters: Vec<Cluster> = clusters.into_iter().map(Into::into).collect();
            let result = output(g, &clusters);
            for cl in &clusters {
                ctx.release(&cl.indices)?;
            }
            ctx.free(clusters)?;
            result
        },
        workspace,
    )
}

/// The source-compatible u32 entry point; see [`build_generic`] for selectable index widths.
#[inline]
pub fn build(
    c: Config,
    mesh: Mesh<'_>,
    workspace: &mut Workspace,
) -> Result<Vec<GroupOutput>, Error> {
    build_generic::<u32>(c, mesh.into(), workspace)
        .map(|values| values.into_iter().map(Into::into).collect())
}

/// The source-compatible u32 entry point; see [`local_indices_generic`] for selectable index widths.
#[inline]
pub fn local_indices(
    indices: &[u32],
    workspace: &mut Workspace,
) -> Result<crate::LocalMeshlet, Error> {
    local_indices_generic::<u32>(indices, workspace).map(Into::into)
}

/// The source-compatible u32 entry point; see [`build_parallel_generic`] for selectable index widths.
#[cfg(feature = "parallel")]
#[inline]
pub fn build_parallel(
    c: Config,
    mesh: Mesh<'_>,
    workspace: &mut Workspace,
) -> Result<Vec<GroupOutput>, Error> {
    build_parallel_generic::<u32>(c, mesh.into(), workspace)
        .map(|values| values.into_iter().map(Into::into).collect())
}

/// The source-compatible u32 entry point; see [`build_parallel_with_output_generic`] for selectable index widths.
#[cfg(feature = "parallel")]
#[inline]
pub fn build_parallel_with_output(
    c: Config,
    mesh: Mesh<'_>,
    mut output: impl FnMut(Group, &[Cluster]) -> Result<i32, Error>,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    build_internal(
        true,
        c,
        mesh.into(),
        &mut |g, _diagnostics, clusters, _positions, ctx| {
            let clusters: Vec<Cluster> = clusters.into_iter().map(Into::into).collect();
            let result = output(g, &clusters);
            for cl in &clusters {
                ctx.release(&cl.indices)?;
            }
            ctx.free(clusters)?;
            result
        },
        workspace,
    )
}

/// The source-compatible u32 form of [`MeshGeneric`].
/// Explicit borrowed mesh inputs. Weights and attribute components must match.
pub struct Mesh<'a> {
    /// Triangle topology referencing the full vertex array.
    pub indices: &'a [u32],
    /// Mutable positions; only dilation changes these.
    pub positions: &'a mut [[f32; 3]],
    /// Optional checked attribute view.
    pub attributes: Option<Attributes<'a>>,
    /// Optional per-vertex flags.
    pub vertex_lock: Option<&'a [VertexFlags]>,
    /// Attribute weights for simplification.
    pub attribute_weights: &'a [f32],
    /// Bit K protects discontinuities in component K.
    pub attribute_protect_mask: u32,
}
impl<'a> From<MeshGeneric<'a, u32>> for Mesh<'a> {
    #[inline]
    fn from(value: MeshGeneric<'a, u32>) -> Self {
        Self {
            indices: value.indices,
            positions: value.positions,
            attributes: value.attributes,
            vertex_lock: value.vertex_lock,
            attribute_weights: value.attribute_weights,
            attribute_protect_mask: value.attribute_protect_mask,
        }
    }
}

impl<'a> From<Mesh<'a>> for MeshGeneric<'a, u32> {
    #[inline]
    fn from(value: Mesh<'a>) -> Self {
        Self {
            indices: value.indices,
            positions: value.positions,
            attributes: value.attributes,
            vertex_lock: value.vertex_lock,
            attribute_weights: value.attribute_weights,
            attribute_protect_mask: value.attribute_protect_mask,
        }
    }
}

/// The source-compatible u32 form of [`ClusterGeneric`].
/// Cluster emitted by the demo builder.
#[derive(Debug, Default, PartialEq)]
pub struct Cluster {
    /// More refined group identifier, or -1 for original geometry.
    pub refined: i32,
    /// Culling bounds; error is not necessarily monotonic across the DAG.
    pub bounds: LodBounds,
    /// Topology referencing the original vertex array.
    pub indices: Vec<u32>,
    /// Number of unique vertex references.
    pub vertex_count: usize,
}
impl From<ClusterGeneric<u32>> for Cluster {
    #[inline]
    fn from(value: ClusterGeneric<u32>) -> Self {
        Self {
            refined: value.refined,
            bounds: value.bounds,
            indices: value.indices,
            vertex_count: value.vertex_count,
        }
    }
}

impl From<Cluster> for ClusterGeneric<u32> {
    #[inline]
    fn from(value: Cluster) -> Self {
        Self {
            refined: value.refined,
            bounds: value.bounds,
            indices: value.indices,
            vertex_count: value.vertex_count,
        }
    }
}

/// The source-compatible u32 form of [`GroupOutputGeneric`].
/// Owned group record and its emitted clusters.
#[derive(Debug, Default, PartialEq)]
pub struct GroupOutput {
    /// Group metadata.
    pub group: Group,
    /// Clusters in callback order.
    pub clusters: Vec<Cluster>,
}
impl From<GroupOutputGeneric<u32>> for GroupOutput {
    #[inline]
    fn from(value: GroupOutputGeneric<u32>) -> Self {
        Self {
            group: value.group,
            clusters: value.clusters.into_iter().map(Into::into).collect(),
        }
    }
}

impl From<GroupOutput> for GroupOutputGeneric<u32> {
    #[inline]
    fn from(value: GroupOutput) -> Self {
        Self {
            group: value.group,
            clusters: value.clusters.into_iter().map(Into::into).collect(),
        }
    }
}