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
// Port of meshoptimizer 1.3 meshletutils.cpp (MIT, Arseny Kapoulkine).
use crate::math::LANES;

use crate::processing::{cross, dot, finite, point, sub, Context};
use crate::{Attributes, Error, Positions, Workspace};
use alloc::vec::Vec;

#[inline(always)]
fn sqrt8(values: [f32; LANES]) -> [f32; LANES] {
    #[cfg(feature = "simd")]
    if let Some(result) = crate::codec::bounds_roots(values) {
        return result;
    }
    crate::math::sqrt8(values)
}

/// A borrowed positions view whose bounds-validation scan is cached once.
///
/// Construction scans all positions in O(n) time without allocating. The scan
/// result, including a failure, is retained: bounds calls report it at their
/// original validation point, after topology checks and work-limit checks.
/// This preserves error precedence even for malformed topology combined with
/// non-finite positions. Repeated calls do no full-view scan, but charge the
/// original logical position visits to preserve [`Workspace`] limits and usage.
#[derive(Clone, Copy, Debug)]
pub struct BoundsPositions<'a> {
    positions: Positions<'a>,
    validation: Result<bool, Error>,
}
impl<'a> BoundsPositions<'a> {
    /// Scan and cache the size, finiteness and arithmetic-range checks for `positions`.
    ///
    /// Errors are deferred to the bounds operation to preserve its precedence.
    pub fn new(positions: Positions<'a>) -> Self {
        Self {
            positions,
            validation: crate::processing::validate_positions(positions),
        }
    }
    fn apply(self, ctx: &mut Context<'_>) -> Result<bool, Error> {
        if self.positions.len() > u32::MAX as usize {
            return Err(Error::SizeOverflow);
        }
        ctx.tick(self.positions.len())?;
        self.validation
    }
}

/// Meaningful fields of `meshopt_Bounds`, without native padding.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Bounds {
    /// Sphere center.
    pub center: [f32; 3],
    /// Sphere radius.
    pub radius: f32,
    /// Perspective normal-cone apex.
    pub cone_apex: [f32; 3],
    /// Unit normal-cone axis.
    pub cone_axis: [f32; 3],
    /// Cone culling cutoff.
    pub cone_cutoff: f32,
    /// Conservative signed-normalized axis.
    pub cone_axis_s8: [i8; 3],
    /// Conservative signed-normalized cutoff.
    pub cone_cutoff_s8: i8,
}
/// Meshlet-local topology with first-visit vertex references.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct LocalMeshletGeneric<I: crate::Index = u32> {
    /// References to the original vertex buffer.
    pub vertices: Vec<I>,
    /// Three local byte indices per triangle.
    pub triangles: Vec<u8>,
}

// The bounded fast path has finite intermediates by construction. Its largest
// product is a squared cross product of differences at most 2e8 (below 1e35).
// Larger finite inputs retain every original intermediate check.
#[inline(always)]
fn number<const CHECK: bool>(value: f32) -> Result<f32, Error> {
    if CHECK {
        finite(value)
    } else {
        Ok(value)
    }
}
trait SphereSource {
    fn sample(&self, index: usize) -> ([f32; 3], f32);
}
// Select a packed layout once before repeated point reads. The view fallback
// retains checked access for strided, byte-ordered and mapped positions.
trait BoundsSource: Copy {
    fn point(self, index: u32) -> [f32; 3];
}
impl BoundsSource for Positions<'_> {
    #[inline(always)]
    fn point(self, index: u32) -> [f32; 3] {
        point(self, index)
    }
}
impl BoundsSource for &[[f32; 3]] {
    #[inline(always)]
    fn point(self, index: u32) -> [f32; 3] {
        self[index as usize]
    }
}
struct PointSource<'a, P = Positions<'a>> {
    p: P,
    indices: Option<&'a [u32]>,
    radii: Option<Attributes<'a>>,
}
impl<P: BoundsSource> SphereSource for PointSource<'_, P> {
    #[inline(always)]
    fn sample(&self, index: usize) -> ([f32; 3], f32) {
        let v = self.indices.map_or(index as u32, |i| i[index]);
        (
            self.p.point(v),
            self.radii
                .map_or(0., |r| r.get(v as usize, 0).expect("validated radius")),
        )
    }
}
struct NormalSource<'a>(&'a [[f32; 4]]);
impl SphereSource for NormalSource<'_> {
    #[inline(always)]
    fn sample(&self, index: usize) -> ([f32; 3], f32) {
        let p = self.0[index];
        ([p[0], p[1], p[2]], 0.)
    }
}
// The scalar fallback in sqrt8 computes every component, including unused 1.0
// padding. For one-triangle bounds, omit those unused fallback calls while
// keeping the used operands, backend and evaluation order identical.
#[inline(always)]
fn bounds_roots(values: [f32; LANES], used: usize) -> [f32; LANES] {
    if used < LANES
        && values[..used]
            .iter()
            .any(|v| v.to_bits().wrapping_sub(0x0080_0000) >= 0x7f00_0000)
    {
        let mut result = [1.; LANES];
        for i in 0..used {
            result[i] = crate::math::sqrt(values[i]);
        }
        result
    } else {
        sqrt8(values)
    }
}
#[inline(always)]
fn sphere<const A: usize, const CHECK: bool>(
    count: usize,
    get: impl SphereSource,
    skip_padding: bool,
    ctx: &mut Context<'_>,
) -> Result<([f32; 3], f32), Error> {
    if count == 0 {
        return Ok(([0.0; 3], 0.0));
    }
    let axes = [
        [1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.],
        [0.57735026; 3],
        [-0.57735026, 0.57735026, 0.57735026],
        [0.57735026, -0.57735026, 0.57735026],
        [0.57735026, 0.57735026, -0.57735026],
    ];
    let mut pmin = [0u32; 7];
    let mut pmax = [0u32; 7];
    let mut tmin = [f32::MAX; 7];
    let mut tmax = [-f32::MAX; 7];
    ctx.tick(count * 2)?;
    for i in 0..count {
        let (p, r) = get.sample(i);
        for k in 0..A {
            let tp = number::<CHECK>(dot(axes[k], p))?;
            let lo = number::<CHECK>(tp - r)?;
            let hi = number::<CHECK>(tp + r)?;
            let lower = lo < tmin[k];
            let upper = hi > tmax[k];
            pmin[k] = if lower { i as u32 } else { pmin[k] };
            pmax[k] = if upper { i as u32 } else { pmax[k] };
            tmin[k] = if lower { lo } else { tmin[k] };
            tmax[k] = if upper { hi } else { tmax[k] };
        }
    }
    // The axis extents are independent: take their roots together. Failures
    // are all NumericalFailure, so the grouped check order is unobservable.
    let mut squares = [1f32; LANES];
    for k in 0..A {
        let (a, _) = get.sample(pmin[k] as usize);
        let (b, _) = get.sample(pmax[k] as usize);
        let d = sub(b, a);
        squares[k] = number::<CHECK>(dot(d, d))?;
    }
    let lengths = if skip_padding {
        bounds_roots(squares, A)
    } else {
        sqrt8(squares)
    };
    let mut axis = 0;
    let mut dr = 0.;
    for k in 0..A {
        let (_, ar) = get.sample(pmin[k] as usize);
        let (_, br) = get.sample(pmax[k] as usize);
        let v = number::<CHECK>(lengths[k] + ar + br)?;
        if v > dr {
            dr = v;
            axis = k;
        }
    }
    let (a, ar) = get.sample(pmin[axis] as usize);
    let (b, br) = get.sample(pmax[axis] as usize);
    let delta = sub(b, a);
    // The same difference as the selected axis extent: reuse its root.
    let d = lengths[axis];
    let k = if d > 0. { (d + br - ar) / (2. * d) } else { 0. };
    let mut center = [
        a[0] + delta[0] * k,
        a[1] + delta[1] * k,
        a[2] + delta[2] * k,
    ];
    let mut radius = dr / 2.;
    for i in 0..count {
        let (p, r) = get.sample(i);
        let dp = sub(p, center);
        let d2 = number::<CHECK>(dot(dp, dp))?;
        // sqrt(round(x*x)) rounds to x when x*x is normal. Lower the
        // rounded radius-r by one representable value, so adding r cannot
        // exceed radius. This only avoids a sqrt whose update would be false.
        let limit = radius - r;
        if limit >= 1.0e-18 {
            let lower = f32::from_bits(limit.to_bits() - 1);
            if d2 <= lower * lower {
                continue;
            }
        }
        let d = ctx.sqrt(d2);
        if d + r > radius {
            let k = if d > 0. {
                (d + r - radius) / (2. * d)
            } else {
                0.
            };
            for j in 0..3 {
                center[j] += k * (p[j] - center[j]);
            }
            radius = (radius + d + r) / 2.;
        }
    }
    for v in center {
        number::<CHECK>(v)?;
    }
    number::<CHECK>(radius)?;
    Ok((center, radius))
}
fn bounds<const CHECK: bool, const N: usize>(
    indices: &[u32],
    corners: &[u32],
    p: impl BoundsSource,
    ctx: &mut Context<'_>,
) -> Result<Bounds, Error> {
    let mut normals = [[0f32; 4]; N];
    let mut n = 0;
    ctx.tick(indices.len() / 3)?;
    // Triangle areas are independent: take their roots eight at a time. Every
    // failure is the same NumericalFailure and work is charged above, so the
    // grouped check order is unobservable.
    for group in indices.as_chunks::<3>().0.chunks(LANES) {
        let mut corners = [[0f32; 3]; LANES];
        let mut normals_raw = [[0f32; 3]; LANES];
        let mut squares = [1f32; LANES];
        for (k, t) in group.iter().enumerate() {
            let a = p.point(t[0]);
            let normal = cross(sub(p.point(t[1]), a), sub(p.point(t[2]), a));
            squares[k] = number::<CHECK>(dot(normal, normal))?;
            corners[k] = a;
            normals_raw[k] = normal;
        }
        let areas = if N == 1 && group.len() == 1 {
            bounds_roots(squares, 1)
        } else {
            sqrt8(squares)
        };
        for k in 0..group.len() {
            let area = areas[k];
            if area == 0. {
                continue;
            }
            let mut normal = normals_raw[k];
            for v in &mut normal {
                *v /= area;
            }
            normals[n] = [
                normal[0],
                normal[1],
                normal[2],
                -number::<CHECK>(dot(normal, corners[k]))?,
            ];
            n += 1;
        }
    }
    let mut b = Bounds::default();
    if n == 0 {
        return Ok(b);
    }
    let (center, radius) = sphere::<7, CHECK>(
        corners.len(),
        PointSource {
            p,
            indices: Some(corners),
            radii: None,
        },
        N == 1,
        ctx,
    )?;
    b.center = center;
    b.radius = radius;
    let (mut axis, _) = sphere::<3, CHECK>(n, NormalSource(&normals[..n]), N == 1, ctx)?;
    let len = ctx.sqrt(number::<CHECK>(dot(axis, axis))?);
    let inv = if len == 0. { 0. } else { 1. / len };
    for a in &mut axis {
        *a *= inv;
    }
    let mut mindp = 1.;
    ctx.tick(n * 2)?;
    for normal in &normals[..n] {
        let dp = dot([normal[0], normal[1], normal[2]], axis);
        if dp < mindp {
            mindp = dp;
        }
    }
    if mindp <= 0.1 {
        b.cone_cutoff = 1.;
        b.cone_cutoff_s8 = 127;
        return Ok(b);
    }
    let mut maxt = 0.;
    for normal in &normals[..n] {
        let nn = [normal[0], normal[1], normal[2]];
        let dc = dot(center, nn) + normal[3];
        let dn = dot(axis, nn);
        let t = number::<CHECK>(dc / dn)?;
        if t > maxt {
            maxt = t;
        }
    }
    for j in 0..3 {
        b.cone_apex[j] = number::<CHECK>(center[j] - axis[j] * maxt)?;
        b.cone_axis[j] = axis[j];
        let v = axis[j].clamp(-1., 1.);
        b.cone_axis_s8[j] = (v * 127. + if v >= 0. { 0.5 } else { -0.5 }) as i8;
    }
    b.cone_cutoff = ctx.sqrt(number::<CHECK>(1. - mindp * mindp)?);
    let e0 = (b.cone_axis_s8[0] as f32 / 127. - axis[0]).abs();
    let e1 = (b.cone_axis_s8[1] as f32 / 127. - axis[1]).abs();
    let e2 = (b.cone_axis_s8[2] as f32 / 127. - axis[2]).abs();
    b.cone_cutoff_s8 = ((127. * (b.cone_cutoff + e0 + e1 + e2) + 1.) as i32).min(127) as i8;
    Ok(b)
}
/// `meshopt_computeClusterBounds`: sphere and conservative normal cone.
///
/// Scans all positions in O(n) time per call. For repeated bounds queries use
/// [`BoundsPositions`] with [`compute_cluster_bounds_with_positions`].
///
/// # Errors
/// `InvalidTopology` for incomplete triangles or `IndexOutOfBounds` for invalid vertex references.
/// `InvalidParameter` for too many indices; `NumericalFailure` for non-finite geometry or calculations.
/// `SizeOverflow` for size overflow or `LimitExceeded` for exhausted limits.
#[inline]
pub fn compute_cluster_bounds_generic<I: crate::Index>(
    indices: &[I],
    p: Positions<'_>,
    workspace: &mut Workspace,
) -> Result<Bounds, Error> {
    I::with_input(indices, workspace, |indices, workspace| {
        compute_cluster_bounds_u32(indices, p, workspace)
    })
}

fn compute_cluster_bounds_u32(
    indices: &[u32],
    p: Positions<'_>,
    workspace: &mut Workspace,
) -> Result<Bounds, Error> {
    let mut ctx = Context::new(workspace)?;
    if indices.len() > 1536 {
        return Err(Error::InvalidParameter);
    }
    if indices.len() <= 96 {
        cluster_bounds::<96, 32>(indices, p, &mut ctx, None)
    } else if indices.len() <= 384 {
        cluster_bounds::<384, 128>(indices, p, &mut ctx, None)
    } else {
        cluster_bounds::<1536, 512>(indices, p, &mut ctx, None)
    }
}
/// Compute cluster bounds using a cached positions-validation scan.
///
/// Output bits, errors, error precedence and logical workspace usage match
/// [`compute_cluster_bounds`]. Per-call work is O(indices.len()), without a
/// full positions scan; constructing [`BoundsPositions`] costs O(n) once.
///
/// # Errors
/// Same errors as [`compute_cluster_bounds`].
#[inline]
pub fn compute_cluster_bounds_with_positions_generic<I: crate::Index>(
    indices: &[I],
    p: BoundsPositions<'_>,
    workspace: &mut Workspace,
) -> Result<Bounds, Error> {
    I::with_input(indices, workspace, |indices, workspace| {
        compute_cluster_bounds_with_positions_u32(indices, p, workspace)
    })
}

fn compute_cluster_bounds_with_positions_u32(
    indices: &[u32],
    p: BoundsPositions<'_>,
    workspace: &mut Workspace,
) -> Result<Bounds, Error> {
    let mut ctx = Context::new(workspace)?;
    if indices.len() > 1536 {
        return Err(Error::InvalidParameter);
    }
    if indices.len() <= 96 {
        cluster_bounds_cached::<96, 32>(indices, p, &mut ctx)
    } else if indices.len() <= 384 {
        cluster_bounds_cached::<384, 128>(indices, p, &mut ctx)
    } else {
        cluster_bounds_cached::<1536, 512>(indices, p, &mut ctx)
    }
}
fn cluster_bounds_cached<const M: usize, const N: usize>(
    indices: &[u32],
    p: BoundsPositions<'_>,
    ctx: &mut Context<'_>,
) -> Result<Bounds, Error> {
    ctx.topology(indices, p.positions.len())?;
    ctx.moderate = p.apply(ctx)?;
    cluster_bounds_body::<M, N>(indices, p.positions, ctx)
}
fn cluster_bounds_body<const M: usize, const N: usize>(
    indices: &[u32],
    p: Positions<'_>,
    ctx: &mut Context<'_>,
) -> Result<Bounds, Error> {
    let mut cache = [u32::MAX; 512];
    let mut corners = [0u32; M];
    let mut n = 0;
    ctx.tick(indices.len())?;
    for &v in indices {
        let c = &mut cache[v as usize & 511];
        if *c != v {
            corners[n] = v;
            n += 1;
        }
        *c = v;
    }
    meshlet_bounds_result::<N>(indices, &corners[..n], p, ctx)
}
#[cfg(feature = "clusterlod")]
pub(crate) fn compute_cluster_bounds_validated(
    indices: &[u32],
    p: Positions<'_>,
    moderate: bool,
    workspace: &mut Workspace,
) -> Result<Bounds, Error> {
    let mut ctx = Context::new(workspace)?;
    if indices.len() > 1536 {
        return Err(Error::InvalidParameter);
    }
    if indices.len() <= 96 {
        cluster_bounds::<96, 32>(indices, p, &mut ctx, Some(moderate))
    } else if indices.len() <= 384 {
        cluster_bounds::<384, 128>(indices, p, &mut ctx, Some(moderate))
    } else {
        cluster_bounds::<1536, 512>(indices, p, &mut ctx, Some(moderate))
    }
}
fn cluster_bounds<const M: usize, const N: usize>(
    indices: &[u32],
    p: Positions<'_>,
    ctx: &mut Context<'_>,
    trusted_moderate: Option<bool>,
) -> Result<Bounds, Error> {
    ctx.topology(indices, p.len())?;
    if let Some(moderate) = trusted_moderate {
        ctx.moderate = moderate;
    } else {
        ctx.positions(p)?;
    }
    let mut cache = [u32::MAX; 512];
    let mut corners = [0u32; M];
    let mut n = 0;
    ctx.tick(indices.len())?;
    for &v in indices {
        let c = &mut cache[v as usize & 511];
        if *c != v {
            corners[n] = v;
            n += 1;
        }
        *c = v;
    }
    meshlet_bounds_result::<N>(indices, &corners[..n], p, ctx)
}
/// `meshopt_computeMeshletBounds`: bounds of byte-local triangles.
///
/// Scans all positions in O(n) time per call. For repeated bounds queries use
/// [`BoundsPositions`] with [`compute_meshlet_bounds_with_positions`].
///
/// # Errors
/// `InvalidTopology` for incomplete triangles or `IndexOutOfBounds` for invalid vertex references.
/// `InvalidParameter` for unsupported meshlet counts; `NumericalFailure` for non-finite geometry or calculations.
/// `SizeOverflow` for size overflow or `LimitExceeded` for exhausted limits.
#[inline]
pub fn compute_meshlet_bounds_generic<I: crate::Index>(
    vertices: &[I],
    triangles: &[u8],
    p: Positions<'_>,
    workspace: &mut Workspace,
) -> Result<Bounds, Error> {
    I::with_input(vertices, workspace, |vertices, workspace| {
        compute_meshlet_bounds_u32(vertices, triangles, p, workspace)
    })
}

fn compute_meshlet_bounds_u32(
    vertices: &[u32],
    triangles: &[u8],
    p: Positions<'_>,
    workspace: &mut Workspace,
) -> Result<Bounds, Error> {
    let mut ctx = Context::new(workspace)?;
    validate_local(vertices, triangles)?;
    if triangles.len() <= 96 {
        meshlet_bounds::<96, 32>(vertices, triangles, p, &mut ctx)
    } else if triangles.len() <= 384 {
        meshlet_bounds::<384, 128>(vertices, triangles, p, &mut ctx)
    } else {
        meshlet_bounds::<1536, 512>(vertices, triangles, p, &mut ctx)
    }
}
/// Compute meshlet bounds using a cached positions-validation scan.
///
/// Output bits, errors, error precedence and logical workspace usage match
/// [`compute_meshlet_bounds`]. Per-call work is O(vertices.len() + triangles.len()),
/// without a full positions scan; constructing [`BoundsPositions`] costs O(n) once.
///
/// # Errors
/// Same errors as [`compute_meshlet_bounds`].
#[inline]
pub fn compute_meshlet_bounds_with_positions_generic<I: crate::Index>(
    vertices: &[I],
    triangles: &[u8],
    p: BoundsPositions<'_>,
    workspace: &mut Workspace,
) -> Result<Bounds, Error> {
    I::with_input(vertices, workspace, |vertices, workspace| {
        compute_meshlet_bounds_with_positions_u32(vertices, triangles, p, workspace)
    })
}

fn compute_meshlet_bounds_with_positions_u32(
    vertices: &[u32],
    triangles: &[u8],
    p: BoundsPositions<'_>,
    workspace: &mut Workspace,
) -> Result<Bounds, Error> {
    let mut ctx = Context::new(workspace)?;
    validate_local(vertices, triangles)?;
    ctx.moderate = p.apply(&mut ctx)?;
    if triangles.len() <= 3 {
        meshlet_bounds_body::<3, 1>(vertices, triangles, p.positions, &mut ctx)
    } else if triangles.len() <= 96 {
        meshlet_bounds_body::<96, 32>(vertices, triangles, p.positions, &mut ctx)
    } else if triangles.len() <= 384 {
        meshlet_bounds_body::<384, 128>(vertices, triangles, p.positions, &mut ctx)
    } else {
        meshlet_bounds_body::<1536, 512>(vertices, triangles, p.positions, &mut ctx)
    }
}
fn meshlet_bounds<const M: usize, const N: usize>(
    vertices: &[u32],
    triangles: &[u8],
    p: Positions<'_>,
    ctx: &mut Context<'_>,
) -> Result<Bounds, Error> {
    ctx.positions(p)?;
    ctx.tick(vertices.len() + triangles.len())?;
    if vertices.iter().any(|&v| v as usize >= p.len()) {
        return Err(Error::IndexOutOfBounds);
    }
    let mut indices = [0u32; M];
    let mut n = 0;
    for (i, &v) in triangles.iter().enumerate() {
        indices[i] = vertices[v as usize];
        n = n.max(v as usize + 1);
    }
    meshlet_bounds_result::<N>(&indices[..triangles.len()], &vertices[..n], p, ctx)
}
fn meshlet_bounds_body<const M: usize, const N: usize>(
    vertices: &[u32],
    triangles: &[u8],
    p: Positions<'_>,
    ctx: &mut Context<'_>,
) -> Result<Bounds, Error> {
    ctx.tick(vertices.len() + triangles.len())?;
    if vertices
        .iter()
        .copied()
        .max()
        .is_some_and(|v| v as usize >= p.len())
    {
        return Err(Error::IndexOutOfBounds);
    }
    if N == 1 {
        let Some(triangle) = triangles.first_chunk::<3>() else {
            return Ok(Bounds::default());
        };
        let indices = triangle.map(|v| vertices[v as usize]);
        let n = triangle.iter().copied().max().unwrap() as usize + 1;
        return meshlet_bounds_result::<N>(&indices, &vertices[..n], p, ctx);
    }
    let mut indices = [0u32; M];
    let mut n = 0;
    for (i, &v) in triangles.iter().enumerate() {
        indices[i] = vertices[v as usize];
        n = n.max(v as usize + 1);
    }
    meshlet_bounds_result::<N>(&indices[..triangles.len()], &vertices[..n], p, ctx)
}
#[inline(always)]
fn meshlet_bounds_result<const N: usize>(
    indices: &[u32],
    corners: &[u32],
    p: Positions<'_>,
    ctx: &mut Context<'_>,
) -> Result<Bounds, Error> {
    if let Some(packed) = p.packed_values() {
        if ctx.moderate {
            bounds::<false, N>(indices, corners, packed, ctx)
        } else {
            bounds::<true, N>(indices, corners, packed, ctx)
        }
    } else if ctx.moderate {
        bounds::<false, N>(indices, corners, p, ctx)
    } else {
        bounds::<true, N>(indices, corners, p, ctx)
    }
}
/// `meshopt_computeSphereBounds`. Optional radii use a checked one-component view.
///
/// # Errors
/// `InvalidLayout` for mismatched radii; `InvalidParameter` for negative or non-finite radii;
/// `NumericalFailure` for non-finite geometry or calculations.
/// `SizeOverflow` for size overflow or `LimitExceeded` for exhausted limits.
pub fn compute_sphere_bounds(
    p: Positions<'_>,
    radii: Option<Attributes<'_>>,
    workspace: &mut Workspace,
) -> Result<Bounds, Error> {
    let mut ctx = Context::new(workspace)?;
    ctx.positions(p)?;
    if let Some(r) = radii {
        if r.len() != p.len() || r.components() != 1 {
            return Err(Error::InvalidLayout);
        }
        ctx.tick(r.len())?;
        for i in 0..r.len() {
            let v = r.get(i, 0).ok_or(Error::InvalidLayout)?;
            ctx.moderate &= v <= 1.0e8;
            if !v.is_finite() || v < 0. {
                return Err(Error::InvalidParameter);
            }
        }
    }
    let get = PointSource {
        p,
        indices: None,
        radii,
    };
    let (center, radius) = if ctx.moderate {
        sphere::<7, false>(p.len(), get, false, &mut ctx)?
    } else {
        sphere::<7, true>(p.len(), get, false, &mut ctx)?
    };
    Ok(Bounds {
        center,
        radius,
        ..Bounds::default()
    })
}
fn validate_local(v: &[u32], t: &[u8]) -> Result<(), Error> {
    if !t.len().is_multiple_of(3) {
        return Err(Error::InvalidTopology);
    }
    if v.len() > 256 || t.len() > 1536 {
        return Err(Error::InvalidParameter);
    }
    if t.iter().any(|&i| i as usize >= v.len()) {
        return Err(Error::IndexOutOfBounds);
    }
    Ok(())
}
fn extract<const V: usize, const T: usize>(
    indices: &[u32],
    vertices: &mut [u32; V],
    triangles: &mut [u8; T],
    ctx: &mut Context<'_>,
) -> Result<usize, Error> {
    if !indices.len().is_multiple_of(3) {
        return Err(Error::InvalidTopology);
    }
    if indices.len() > 1536 {
        return Err(Error::InvalidParameter);
    }
    let mut n = 0;
    let mut cache = [-1i16; 1024];
    ctx.tick(indices.len())?;
    for (i, &v) in indices.iter().enumerate() {
        let key = v as usize & 1023;
        let c = cache[key];
        if c >= 0 && vertices[c as u8 as usize] == v {
            triangles[i] = c as u8;
            continue;
        }
        let pos = if c < 0 {
            n
        } else {
            ctx.tick(n)?;
            vertices[..n].iter().position(|&x| x == v).unwrap_or(n)
        };
        if pos == n {
            if n == 256 {
                return Err(Error::InvalidParameter);
            }
            vertices[n] = v;
            n += 1;
        }
        cache[key] = pos as i16;
        triangles[i] = pos as u8;
    }
    Ok(n)
}
/// `meshopt_extractMeshletIndices`: preserve first-visit vertex order.
///
/// # Errors
/// `InvalidTopology` for incomplete triangles; `InvalidParameter` for unsupported meshlet counts;
/// `SizeOverflow` for size overflow, `LimitExceeded` for exhausted limits, or `AllocationFailed` for failed reservation.
#[inline]
pub fn extract_meshlet_indices_generic<I: crate::Index>(
    indices: &[I],
    workspace: &mut Workspace,
) -> Result<LocalMeshletGeneric<I>, Error> {
    I::with_input(indices, workspace, |indices, workspace| {
        extract_meshlet_indices_u32(indices, workspace)
            .and_then(|value| crate::index::Convert::<I>::convert(value, workspace))
    })
}

fn extract_meshlet_indices_u32(
    indices: &[u32],
    workspace: &mut Workspace,
) -> Result<LocalMeshletGeneric, Error> {
    let mut ctx = Context::new(workspace)?;
    extracted(indices, &mut ctx, |v, t, ctx| {
        Ok(LocalMeshletGeneric {
            vertices: ctx.copy(v)?,
            triangles: ctx.copy(t)?,
        })
    })
}
// Run `extract` with stack scratch sized to the input (no larger than the
// 256-vertex and 1536-index limits), so small meshlets do not clear the
// full-size arrays. Validation order and results are unchanged.
#[inline(always)]
fn extracted<R>(
    indices: &[u32],
    ctx: &mut Context<'_>,
    finish: impl FnOnce(&[u32], &[u8], &mut Context<'_>) -> Result<R, Error>,
) -> Result<R, Error> {
    if indices.len() <= 96 {
        let (mut v, mut t) = ([0; 96], [0; 96]);
        let n = extract(indices, &mut v, &mut t, ctx)?;
        finish(&v[..n], &t[..indices.len()], ctx)
    } else if indices.len() <= 384 {
        let (mut v, mut t) = ([0; 256], [0; 384]);
        let n = extract(indices, &mut v, &mut t, ctx)?;
        finish(&v[..n], &t[..indices.len()], ctx)
    } else {
        let (mut v, mut t) = ([0; 256], [0; 1536]);
        let n = extract(indices, &mut v, &mut t, ctx)?;
        finish(&v[..n], &t[..indices.len()], ctx)
    }
}
/// Caller-buffer extraction. Errors leave both destinations unchanged; tails are preserved.
///
/// # Errors
/// Same errors as [`extract_meshlet_indices`]. `BufferTooSmall` if either output is too short; no output allocation is needed.
#[inline]
pub fn extract_meshlet_indices_into_generic<I: crate::Index>(
    vertices: &mut [I],
    triangles: &mut [u8],
    indices: &[I],
    workspace: &mut Workspace,
) -> Result<usize, Error> {
    I::with_input(indices, workspace, |indices, workspace| {
        I::with_mut(vertices, workspace, |vertices, workspace| {
            extract_meshlet_indices_into_u32(vertices, triangles, indices, workspace)
        })
    })
}

fn extract_meshlet_indices_into_u32(
    vertices: &mut [u32],
    triangles: &mut [u8],
    indices: &[u32],
    workspace: &mut Workspace,
) -> Result<usize, Error> {
    let mut ctx = Context::new(workspace)?;
    if triangles.len() < indices.len() {
        return Err(Error::BufferTooSmall);
    }
    extracted(indices, &mut ctx, |v, t, _| {
        if vertices.len() < v.len() {
            return Err(Error::BufferTooSmall);
        }
        vertices[..v.len()].copy_from_slice(v);
        triangles[..t.len()].copy_from_slice(t);
        Ok(v.len())
    })
}
// All entry points validate sizes and local references before copying/mutation.
fn optimize(v: &mut [u32], t: &mut [u8], level: u8, ctx: &mut Context<'_>) -> Result<(), Error> {
    if level > 9 {
        return Err(Error::InvalidParameter);
    }
    if level == 0 {
        optimize_body::<false>(v, t, level, ctx)
    } else {
        optimize_body::<true>(v, t, level, ctx)
    }
}
fn optimize_body<const ADVANCED: bool>(
    v: &mut [u32],
    t: &mut [u8],
    level: u8,
    ctx: &mut Context<'_>,
) -> Result<(), Error> {
    let n = t.len() / 3;
    // A single triangle cannot change order or rotation at any level. Keep the
    // exact work-charge sequence, including short-budget failure points.
    if n <= 1 {
        ctx.tick(t.len())?;
        if n == 1 {
            ctx.tick(1)?;
            ctx.tick(1)?;
            if ADVANCED {
                ctx.tick(1)?;
            }
        }
        ctx.tick(t.len())?;
        let mut source = [0u8; 3];
        let mut order = [0u32; 3];
        let mut count = 0;
        for x in t {
            let local = match source[..count].iter().position(|&i| i == *x) {
                Some(local) => local,
                None => {
                    source[count] = *x;
                    order[count] = v[*x as usize];
                    count += 1;
                    count - 1
                }
            };
            *x = local as u8;
        }
        v[..count].copy_from_slice(&order[..count]);
        return Ok(());
    }
    let mut cache = [0u8; 256];
    let mut last = 128u8;
    let mut valence = [0u8; 256];
    ctx.tick(t.len())?;
    for &i in t.iter() {
        valence[i as usize] = valence[i as usize].wrapping_add(1);
    }
    for i in 0..n {
        let mut next = i;
        let mut best = -1;
        let mut edges = 0;
        ctx.search(
            t.as_chunks::<3>().0[i..].iter().enumerate(),
            |(offset, tri)| {
                let (a, b, c) = (tri[0] as usize, tri[1] as usize, tri[2] as usize);
                let (ad, bd, cd) = (
                    last.wrapping_sub(cache[a]),
                    last.wrapping_sub(cache[b]),
                    last.wrapping_sub(cache[c]),
                );
                let matches = i32::from(ad < 3) + i32::from(bd < 3) + i32::from(cd < 3);
                let score = if ADVANCED {
                    (matches * 1024 + (1023 - ad as i32 - bd as i32 - cd as i32)) * 256
                        + (255 - valence[a].min(valence[b]).min(valence[c]) as i32)
                } else {
                    matches
                };
                if score > best {
                    best = score;
                    next = i + offset;
                }
                if matches >= 2 {
                    edges += 1;
                    if !ADVANCED || edges >= level {
                        return true;
                    }
                }
                false
            },
        )?;
        ctx.tick(next - i + 1)?;
        let tri = [t[next * 3], t[next * 3 + 1], t[next * 3 + 2]];
        t.copy_within(i * 3..next * 3, (i + 1) * 3);
        t[i * 3..i * 3 + 3].copy_from_slice(&tri);
        last = last.wrapping_add(1);
        for x in tri {
            cache[x as usize] = last;
            valence[x as usize] = valence[x as usize].wrapping_sub(1);
        }
    }
    if ADVANCED {
        cache.fill(0);
        for i in 0..n {
            ctx.tick(1)?;
            let mut tri = [t[i * 3], t[i * 3 + 1], t[i * 3 + 2]];
            let [a, b, c] = tri;
            if cache[a as usize] == 0 && cache[b as usize] != 0 && cache[c as usize] == 0 {
                tri.rotate_left(1);
            } else if cache[a as usize] == 0 && cache[b as usize] == 0 && cache[c as usize] == 0 {
                let (mut ab, mut bc, mut ca) = (false, false, false);
                for j in i + 1..n.min(i + 4) {
                    ctx.tick(1)?;
                    let [oa, ob, oc] = [t[j * 3], t[j * 3 + 1], t[j * 3 + 2]];
                    ab |= (oa == b && ob == a) || (ob == b && oc == a) || (oc == b && oa == a);
                    bc |= (oa == c && ob == b) || (ob == c && oc == b) || (oc == c && oa == b);
                    ca |= (oa == a && ob == c) || (ob == a && oc == c) || (oc == a && oa == c);
                }
                if ab && !bc {
                    tri.rotate_left(1);
                } else if (ab && !ca) || (!ab && bc && !ca) {
                    tri.rotate_right(1);
                }
            }
            t[i * 3..i * 3 + 3].copy_from_slice(&tri);
            for x in tri {
                cache[x as usize] = 1;
            }
        }
    }
    let mut remap = [-1i16; 256];
    let mut order = [0u32; 256];
    let mut count = 0;
    ctx.tick(t.len())?;
    for x in t {
        let r = &mut remap[*x as usize];
        if *r < 0 {
            *r = count as i16;
            order[count] = v[*x as usize];
            count += 1;
        }
        *x = *r as u8;
    }
    v[..count].copy_from_slice(&order[..count]);
    Ok(())
}
/// `meshopt_optimizeMeshletLevel`: atomic destructive variant, levels 0 through 9.
///
/// # Errors
/// `InvalidTopology` for incomplete triangles or `IndexOutOfBounds` for invalid vertex references.
/// `InvalidParameter` for unsupported meshlet counts or level; `SizeOverflow` for size overflow or `LimitExceeded` for exhausted limits.
#[inline]
pub fn optimize_meshlet_level_in_place_generic<I: crate::Index>(
    vertices: &mut [I],
    triangles: &mut [u8],
    level: u8,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    I::with_mut(vertices, workspace, |vertices, workspace| {
        optimize_meshlet_level_in_place_u32(vertices, triangles, level, workspace)
    })
}

fn optimize_meshlet_level_in_place_u32(
    vertices: &mut [u32],
    triangles: &mut [u8],
    level: u8,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    let mut ctx = Context::new(workspace)?;
    validate_local(vertices, triangles)?;
    let mut v = [0; 256];
    let mut t = [0; 1536];
    v[..vertices.len()].copy_from_slice(vertices);
    t[..triangles.len()].copy_from_slice(triangles);
    optimize(
        &mut v[..vertices.len()],
        &mut t[..triangles.len()],
        level,
        &mut ctx,
    )?;
    vertices.copy_from_slice(&v[..vertices.len()]);
    triangles.copy_from_slice(&t[..triangles.len()]);
    Ok(())
}
/// Atomic destructive `meshopt_optimizeMeshlet` (level zero).
///
/// # Errors
/// Same errors as [`optimize_meshlet_level_in_place`].
#[inline]
pub fn optimize_meshlet_in_place_generic<I: crate::Index>(
    vertices: &mut [I],
    triangles: &mut [u8],
    workspace: &mut Workspace,
) -> Result<(), Error> {
    I::with_mut(vertices, workspace, |vertices, workspace| {
        optimize_meshlet_in_place_u32(vertices, triangles, workspace)
    })
}

fn optimize_meshlet_in_place_u32(
    vertices: &mut [u32],
    triangles: &mut [u8],
    workspace: &mut Workspace,
) -> Result<(), Error> {
    optimize_meshlet_level_in_place_generic(vertices, triangles, 0, workspace)
}
/// Allocating `meshopt_optimizeMeshletLevel`; unused vertex suffix stays unchanged.
///
/// # Errors
/// Same errors as [`optimize_meshlet_level_in_place`]. `AllocationFailed` if output reservation fails.
#[inline]
pub fn optimize_meshlet_level_generic<I: crate::Index>(
    vertices: &[I],
    triangles: &[u8],
    level: u8,
    workspace: &mut Workspace,
) -> Result<LocalMeshletGeneric<I>, Error> {
    I::with_input(vertices, workspace, |vertices, workspace| {
        optimize_meshlet_level_u32(vertices, triangles, level, workspace)
            .and_then(|value| crate::index::Convert::<I>::convert(value, workspace))
    })
}

fn optimize_meshlet_level_u32(
    vertices: &[u32],
    triangles: &[u8],
    level: u8,
    workspace: &mut Workspace,
) -> Result<LocalMeshletGeneric, Error> {
    let mut ctx = Context::new(workspace)?;
    validate_local(vertices, triangles)?;
    let mut v = ctx.copy(vertices)?;
    let mut t = ctx.copy(triangles)?;
    optimize(&mut v, &mut t, level, &mut ctx)?;
    Ok(LocalMeshletGeneric {
        vertices: v,
        triangles: t,
    })
}
/// Allocating `meshopt_optimizeMeshlet` (level zero).
///
/// # Errors
/// Same errors as [`optimize_meshlet_level_in_place`]. `AllocationFailed` if output reservation fails.
#[inline]
pub fn optimize_meshlet_generic<I: crate::Index>(
    vertices: &[I],
    triangles: &[u8],
    workspace: &mut Workspace,
) -> Result<LocalMeshletGeneric<I>, Error> {
    I::with_input(vertices, workspace, |vertices, workspace| {
        optimize_meshlet_u32(vertices, triangles, workspace)
            .and_then(|value| crate::index::Convert::<I>::convert(value, workspace))
    })
}

fn optimize_meshlet_u32(
    vertices: &[u32],
    triangles: &[u8],
    workspace: &mut Workspace,
) -> Result<LocalMeshletGeneric, Error> {
    optimize_meshlet_level_generic(vertices, triangles, 0, workspace)
}

/// Caller-buffer meshlet optimization. Errors leave destinations unchanged;
/// suffixes beyond the supplied vertex and triangle lengths are preserved.
///
/// # Errors
/// Same errors as [`optimize_meshlet_level_in_place`]. `BufferTooSmall` if either destination is too short.
#[inline]
pub fn optimize_meshlet_level_into_generic<I: crate::Index>(
    out_vertices: &mut [I],
    out_triangles: &mut [u8],
    vertices: &[I],
    triangles: &[u8],
    level: u8,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    I::with_input(vertices, workspace, |vertices, workspace| {
        I::with_mut(out_vertices, workspace, |out_vertices, workspace| {
            optimize_meshlet_level_into_u32(
                out_vertices,
                out_triangles,
                vertices,
                triangles,
                level,
                workspace,
            )
        })
    })
}

fn optimize_meshlet_level_into_u32(
    out_vertices: &mut [u32],
    out_triangles: &mut [u8],
    vertices: &[u32],
    triangles: &[u8],
    level: u8,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    let mut ctx = Context::new(workspace)?;
    if out_vertices.len() < vertices.len() || out_triangles.len() < triangles.len() {
        return Err(Error::BufferTooSmall);
    }
    validate_local(vertices, triangles)?;
    let mut v = [0; 256];
    let mut t = [0; 1536];
    v[..vertices.len()].copy_from_slice(vertices);
    t[..triangles.len()].copy_from_slice(triangles);
    optimize(
        &mut v[..vertices.len()],
        &mut t[..triangles.len()],
        level,
        &mut ctx,
    )?;
    out_vertices[..vertices.len()].copy_from_slice(&v[..vertices.len()]);
    out_triangles[..triangles.len()].copy_from_slice(&t[..triangles.len()]);
    Ok(())
}
/// Caller-buffer level-zero meshlet optimization, preserving unused tails.
///
/// # Errors
/// Same errors as [`optimize_meshlet_level_in_place`]. `BufferTooSmall` if either destination is too short.
#[inline]
pub fn optimize_meshlet_into_generic<I: crate::Index>(
    out_vertices: &mut [I],
    out_triangles: &mut [u8],
    vertices: &[I],
    triangles: &[u8],
    workspace: &mut Workspace,
) -> Result<(), Error> {
    I::with_input(vertices, workspace, |vertices, workspace| {
        I::with_mut(out_vertices, workspace, |out_vertices, workspace| {
            optimize_meshlet_into_u32(out_vertices, out_triangles, vertices, triangles, workspace)
        })
    })
}

fn optimize_meshlet_into_u32(
    out_vertices: &mut [u32],
    out_triangles: &mut [u8],
    vertices: &[u32],
    triangles: &[u8],
    workspace: &mut Workspace,
) -> Result<(), Error> {
    optimize_meshlet_level_into_generic(
        out_vertices,
        out_triangles,
        vertices,
        triangles,
        0,
        workspace,
    )
}

/// The source-compatible u32 entry point; see [`compute_cluster_bounds_generic`] for selectable index widths.
#[inline]
pub fn compute_cluster_bounds(
    indices: &[u32],
    p: Positions<'_>,
    workspace: &mut Workspace,
) -> Result<Bounds, Error> {
    compute_cluster_bounds_generic::<u32>(indices, p, workspace)
}

/// The source-compatible u32 entry point; see [`compute_cluster_bounds_with_positions_generic`] for selectable index widths.
#[inline]
pub fn compute_cluster_bounds_with_positions(
    indices: &[u32],
    p: BoundsPositions<'_>,
    workspace: &mut Workspace,
) -> Result<Bounds, Error> {
    compute_cluster_bounds_with_positions_generic::<u32>(indices, p, workspace)
}

/// The source-compatible u32 entry point; see [`compute_meshlet_bounds_generic`] for selectable index widths.
#[inline]
pub fn compute_meshlet_bounds(
    vertices: &[u32],
    triangles: &[u8],
    p: Positions<'_>,
    workspace: &mut Workspace,
) -> Result<Bounds, Error> {
    compute_meshlet_bounds_generic::<u32>(vertices, triangles, p, workspace)
}

/// The source-compatible u32 entry point; see [`compute_meshlet_bounds_with_positions_generic`] for selectable index widths.
#[inline]
pub fn compute_meshlet_bounds_with_positions(
    vertices: &[u32],
    triangles: &[u8],
    p: BoundsPositions<'_>,
    workspace: &mut Workspace,
) -> Result<Bounds, Error> {
    compute_meshlet_bounds_with_positions_generic::<u32>(vertices, triangles, p, workspace)
}

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

/// The source-compatible u32 entry point; see [`extract_meshlet_indices_into_generic`] for selectable index widths.
#[inline]
pub fn extract_meshlet_indices_into(
    vertices: &mut [u32],
    triangles: &mut [u8],
    indices: &[u32],
    workspace: &mut Workspace,
) -> Result<usize, Error> {
    extract_meshlet_indices_into_generic::<u32>(vertices, triangles, indices, workspace)
}

/// The source-compatible u32 entry point; see [`optimize_meshlet_level_in_place_generic`] for selectable index widths.
#[inline]
pub fn optimize_meshlet_level_in_place(
    vertices: &mut [u32],
    triangles: &mut [u8],
    level: u8,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    optimize_meshlet_level_in_place_generic::<u32>(vertices, triangles, level, workspace)
}

/// The source-compatible u32 entry point; see [`optimize_meshlet_in_place_generic`] for selectable index widths.
#[inline]
pub fn optimize_meshlet_in_place(
    vertices: &mut [u32],
    triangles: &mut [u8],
    workspace: &mut Workspace,
) -> Result<(), Error> {
    optimize_meshlet_in_place_generic::<u32>(vertices, triangles, workspace)
}

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

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

/// The source-compatible u32 entry point; see [`optimize_meshlet_level_into_generic`] for selectable index widths.
#[inline]
pub fn optimize_meshlet_level_into(
    out_vertices: &mut [u32],
    out_triangles: &mut [u8],
    vertices: &[u32],
    triangles: &[u8],
    level: u8,
    workspace: &mut Workspace,
) -> Result<(), Error> {
    optimize_meshlet_level_into_generic::<u32>(
        out_vertices,
        out_triangles,
        vertices,
        triangles,
        level,
        workspace,
    )
}

/// The source-compatible u32 entry point; see [`optimize_meshlet_into_generic`] for selectable index widths.
#[inline]
pub fn optimize_meshlet_into(
    out_vertices: &mut [u32],
    out_triangles: &mut [u8],
    vertices: &[u32],
    triangles: &[u8],
    workspace: &mut Workspace,
) -> Result<(), Error> {
    optimize_meshlet_into_generic::<u32>(
        out_vertices,
        out_triangles,
        vertices,
        triangles,
        workspace,
    )
}

/// The source-compatible u32 form of [`LocalMeshletGeneric`].
/// Meshlet-local topology with first-visit vertex references.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct LocalMeshlet {
    /// References to the original vertex buffer.
    pub vertices: Vec<u32>,
    /// Three local byte indices per triangle.
    pub triangles: Vec<u8>,
}
impl From<LocalMeshletGeneric<u32>> for LocalMeshlet {
    #[inline]
    fn from(value: LocalMeshletGeneric<u32>) -> Self {
        Self {
            vertices: value.vertices,
            triangles: value.triangles,
        }
    }
}

impl From<LocalMeshlet> for LocalMeshletGeneric<u32> {
    #[inline]
    fn from(value: LocalMeshlet) -> Self {
        Self {
            vertices: value.vertices,
            triangles: value.triangles,
        }
    }
}

#[cfg(test)]
mod bounds_root_tests {
    use super::{bounds_roots, sqrt8, LANES};

    #[test]
    fn used_roots_match_full_lanes_bit_for_bit() {
        let mut state = 0x1357_2468u32;
        let special = [
            0,
            1,
            0x007f_ffff,
            0x0080_0000,
            0x3f80_0000,
            0x7f7f_ffff,
            0x8000_0000,
            0xbf80_0000,
            0x7f80_0000,
            0x7fc0_1234,
        ];
        for sample in 0..512 {
            for used in 1..=LANES {
                let mut values = [1.; LANES];
                for value in &mut values[..used] {
                    state = state.wrapping_mul(1664525).wrapping_add(1013904223);
                    let bits = if sample < special.len() {
                        special[sample]
                    } else if sample.is_multiple_of(2) {
                        0x0080_0000 + state % 0x7f00_0000
                    } else {
                        state
                    };
                    *value = f32::from_bits(bits);
                }
                assert_eq!(
                    bounds_roots(values, used).map(f32::to_bits),
                    sqrt8(values).map(f32::to_bits)
                );
            }
        }
    }
}