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
# Using meshoptimizer-rs

These recipes use triangle lists of `u32` indices and borrowed vertex views.
`Positions::from_packed` borrows XYZ records (`&[[f32; 3]]`). For interleaved
floats, strides and offsets count `f32` components; for byte views they count
bytes and the byte order is explicit. Indices refer to the full position array.

## Tuning for a specific GPU cache

`VertexScoreTable` and `optimize_vertex_cache_with_table` are opt-in extensions
not in C++ meshoptimizer. Start from `VertexScoreTable::default()`, copy its
`cache_scores()` and `live_scores()`, adjust the scores, and validate them with
`VertexScoreTable::new(&cache, &live)?`. Pass the table before the workspace to
`optimize_vertex_cache_with_table`, or use `optimize_vertex_cache_with_table_into`
with a caller-owned destination. The constructor requires exactly 17 finite
cache scores and 9 finite live-valence scores; it does not change cache capacity.

Cache entry zero scores vertices outside the cache, entries 1–16 score cache
positions, and live entry eight also scores all higher valences. Only triangles
whose summed score is positive are picked by score; otherwise the next unemitted
triangle in input order follows, so keep the scores you want to favour positive.
Tuned tables
must be validated on the target hardware using representative meshes; a changed
ordering does not establish a GPU performance gain. The existing standard and
strip APIs retain their upstream presets.

```rust
use meshoptimizer_rs::{
    optimize_vertex_cache, optimize_vertex_cache_with_table, VertexScoreTable, Workspace,
};

let indices = [0, 1, 2, 2, 1, 3];
let mut workspace = Workspace::default();
let preset = VertexScoreTable::default();
let mut cache = *preset.cache_scores();
let live = *preset.live_scores();
let table = VertexScoreTable::new(&cache, &live)?;
assert_eq!(
    optimize_vertex_cache_with_table(&indices, 4, &table, &mut workspace)?,
    optimize_vertex_cache(&indices, 4, &mut workspace)?,
);
cache[1] *= 1.1;
let tuned = VertexScoreTable::new(&cache, &live)?;
let reordered = optimize_vertex_cache_with_table(&indices, 4, &tuned, &mut workspace)?;
assert_eq!(reordered.len(), indices.len());
# Ok::<(), meshoptimizer_rs::Error>(())
```

## Non-packed positions

```text
pub fn from_interleaved(
    data: &[f32],
    count: usize,
    stride: usize,
    offset: usize,
) -> Result<Positions<'_>, Error>

pub fn from_bytes(
    data: &[u8],
    count: usize,
    stride: usize,
    offset: usize,
    order: ByteOrder,
) -> Result<Positions<'_>, Error>
```

Both are `Positions` constructors. For `from_interleaved`, `stride` (3 to 64) and
`offset` count `f32` components. For `from_bytes`, they count bytes: `stride` is a
multiple of four from 12 to 256, and `order` is `ByteOrder::LittleEndian` or
`ByteOrder::BigEndian`. `count` is the number of vertices. Both return
`InvalidLayout` if the layout or buffer length is invalid. The views borrow
`data` and copy nothing.

```rust
use meshoptimizer_rs::{
    simplify, ByteOrder, Positions, SimplifyOptions, SimplifySettings, Workspace,
};

let indices = [0, 1, 2, 2, 1, 3];
let settings = SimplifySettings {
    target_index_count: 3,
    target_error: 0.01,
    options: SimplifyOptions::EMPTY,
};
let mut workspace = Workspace::default();

// x, y, z, u, v per vertex: stride 5 floats, XYZ at offset 0.
let floats = [
    0., 0., 0., 0., 0.,
    1., 0., 0., 1., 0.,
    0., 1., 0., 0., 1.,
    1., 1., 0., 1., 1.,
];
let view = Positions::from_interleaved(&floats, 4, 5, 0)?;
simplify(&indices, view, settings, &mut workspace)?;

// The same vertices as big-endian bytes: stride 20 bytes, XYZ at byte offset 0.
let bytes: Vec<u8> = floats.iter().flat_map(|v| v.to_be_bytes()).collect();
let view = Positions::from_bytes(&bytes, 4, 20, 0, ByteOrder::BigEndian)?;
simplify(&indices, view, settings, &mut workspace)?;
# Ok::<(), meshoptimizer_rs::Error>(())
```

## Typed Rust vertex fields

`VertexLayout` is an opt-in extension not in C++ meshoptimizer. Use `offset_of!`
and a typed selector to check a field against the struct's size and alignment.
See the [`VertexLayout`](crate::VertexLayout) doctest for a complete `#[repr(C)]`
vertex with position, normal and UV fields.

```rust
use core::mem::offset_of;
use meshoptimizer_rs::{VertexFieldSnapshot, VertexLayout, VertexLayoutError};

#[repr(C)]
struct Vertex {
    position: [f32; 3],
    normal: [f32; 3],
    uv: [f32; 2],
}
let vertices = [Vertex {
    position: [0., 0., 0.], normal: [0., 0., 1.], uv: [0., 0.],
}];
let layout = VertexLayout::new(offset_of!(Vertex, position), |v: &Vertex| &v.position)?;
let data = layout.copy_from(&vertices)?;
let positions = data.positions()?;
assert_eq!(positions.get(0), Some([0., 0., 0.]));
let normals = VertexFieldSnapshot::from_vertices(
    &vertices, offset_of!(Vertex, normal), |v| &v.normal,
)?;
assert_eq!(normals.attributes()?.components(), 3);
# Ok::<(), VertexLayoutError>(())
```

Keep `data` alive while using its views. Construction copies selected floats into
a zero-filled, little-endian snapshot with the original stride and offset; it
never reads struct padding. The allocation is one full struct stride per vertex,
outside `Workspace` limits, so bound caller input sizes first. Later vertex edits
require a new snapshot. Selectors may be capturing closures and enforce float
element types at compile time;
layout, field-width and address failures return `VertexLayoutError`. Empty input
checks the layout but has no field address to verify. Packed position slices can
continue to use `Positions::from_packed` without a copy.

## Simplify one mesh

```text
pub fn simplify(
    indices: &[u32],
    positions: Positions<'_>,
    settings: SimplifySettings,
    workspace: &mut Workspace,
) -> Result<SimplifiedMesh, Error>
```

Returns `SimplifiedMesh { indices, error }`. Indices still refer to the original
vertices; there is no implicit welding, fetch compaction or cache optimization.
The target counts indices, not triangles, and is a goal rather than a guarantee.
By default `error` is relative to the mesh extent; `ERROR_ABSOLUTE` selects position units.
`target_error` must be finite and nonnegative; all supplied positions must be finite.

```rust
use meshoptimizer_rs::{simplify, Positions, SimplifyOptions, SimplifySettings, Workspace};

let positions = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [1., 1., 0.]];
let indices = [0, 1, 2, 2, 1, 3];
let settings = SimplifySettings {
    target_index_count: 3,
    target_error: 0.01,
    options: SimplifyOptions::EMPTY,
};
let mut workspace = Workspace::default();
let lod = simplify(&indices, Positions::from_packed(&positions), settings, &mut workspace)?;
assert!(lod.indices.len() <= indices.len());
# Ok::<(), meshoptimizer_rs::Error>(())
```

Errors: `InvalidTopology` for incomplete triangles, `IndexOutOfBounds` for invalid
references, `InvalidParameter` for invalid settings (including
`target_index_count > indices.len()`) or non-finite positions,
`NumericalFailure` for non-finite calculations, and the resource errors below.
Use `SimplifyOptions::from_bits` to validate raw options (`UnknownFlags` on rejection).

## Per-mesh LOD chain

```text
pub fn simplify_scale(positions: Positions<'_>) -> Result<f32, Error>

pub fn simplify(
    indices: &[u32],
    positions: Positions<'_>,
    settings: SimplifySettings,
    workspace: &mut Workspace,
) -> Result<SimplifiedMesh, Error>

pub fn optimize_vertex_cache(
    indices: &[u32],
    vertex_count: usize,
    workspace: &mut Workspace,
) -> Result<Vec<u32>, Error>

pub fn optimize_overdraw(
    indices: &[u32],
    positions: Positions<'_>,
    threshold: f32,
    workspace: &mut Workspace,
) -> Result<Vec<u32>, Error>
```

Keep the full vertex array for every level. Each target below simplifies the
previous level's topology, then orders it for the vertex cache and overdraw.
`scale` is the largest axis extent; multiply a relative error by it to get
position units. Each level's error is relative to that level's input, not an
accumulated bound against the original mesh. The optimizers return reordered
`Vec<u32>` triangle lists. Reuse one workspace for the whole chain: it keeps
scratch capacity between calls, so later calls skip reallocating.

```rust
use meshoptimizer_rs::{
    optimize_overdraw, optimize_vertex_cache, simplify, simplify_scale, Error,
    Positions, SimplifyOptions, SimplifySettings, Workspace,
};

fn main() -> Result<(), Error> {
    let positions = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [1., 1., 0.]];
    let indices = [0, 1, 2, 2, 1, 3];
    let view = Positions::from_packed(&positions);
    let mut workspace = Workspace::default();
    let scale = simplify_scale(view)?;
    let mut current = indices.to_vec();
    for target_index_count in [6, 3, 0] {
        let settings = SimplifySettings {
            target_index_count,
            target_error: 0.01,
            options: SimplifyOptions::EMPTY,
        };
        let lod = simplify(&current, view, settings, &mut workspace)?;
        let cached = optimize_vertex_cache(&lod.indices, positions.len(), &mut workspace)?;
        current = optimize_overdraw(&cached, view, 1.05, &mut workspace)?;
        println!("{} indices, absolute error {}", current.len(), lod.error * scale);
    }
    Ok(())
}
```

Errors: simplification's errors above; `simplify_scale` returns `InvalidParameter`
for non-finite positions and `NumericalFailure` for an overflowing extent.
Cache ordering checks topology and indices; overdraw also rejects a non-finite
threshold with `InvalidParameter` and non-finite geometry/calculations with
`NumericalFailure`. Both optimizers can return the resource errors below.

## Meshlets with bounds

```text
pub fn build_meshlets(
    indices: &[u32],
    p: Positions<'_>,
    s: MeshletSettings,
    cone_weight: f32,
    workspace: &mut Workspace,
) -> Result<Meshlets, Error>
```

```text
pub fn new(positions: Positions<'a>) -> Self // BoundsPositions<'a>
```

```text
pub fn compute_meshlet_bounds_with_positions(
    vertices: &[u32],
    triangles: &[u8],
    p: BoundsPositions<'_>,
    workspace: &mut Workspace,
) -> Result<Bounds, Error>
```

`build_meshlets` returns `Meshlets`: descriptors, original vertex references and
three local `u8` indices per triangle. Descriptor triangle offsets are byte
offsets, with no padding between meshlets. Bounds return a sphere and normal cone
in `Bounds`. Cache the full position validation once with `BoundsPositions` when
querying many meshlets; failures are stored and reported by the bounds operation.

`MeshletSettings::default()` is `max_vertices: 64`, `max_triangles: 124`. Valid
ranges are 3 to 256 vertices and 1 to 512 triangles; anything else returns
`InvalidParameter`. `cone_weight` (finite, 0.0 to 1.0) makes the builder prefer
triangles that face the same way, which helps cone culling; 0.0 ignores facing.
The example uses 0.25.

```rust
use meshoptimizer_rs::{
    build_meshlets, compute_meshlet_bounds_with_positions, BoundsPositions, Error,
    MeshletSettings, Positions, Workspace,
};

fn main() -> Result<(), Error> {
    let positions = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [1., 1., 0.]];
    let indices = [0, 1, 2, 2, 1, 3];
    let view = Positions::from_packed(&positions);
    let mut workspace = Workspace::default();
    let built = build_meshlets(&indices, view, MeshletSettings::default(), 0.25, &mut workspace)?;
    let positions = BoundsPositions::new(view);
    for m in &built.meshlets {
        let v = m.vertex_offset as usize;
        let t = m.triangle_offset as usize;
        let bounds = compute_meshlet_bounds_with_positions(
            &built.vertices[v..v + m.vertex_count as usize],
            &built.triangles[t..t + m.triangle_count as usize * 3],
            positions,
            &mut workspace,
        )?;
        println!("center {:?}, radius {}", bounds.center, bounds.radius);
    }
    Ok(())
}
```

Errors: `InvalidTopology`, `IndexOutOfBounds`, `InvalidParameter` for unsupported
meshlet sizes or builder settings, `NumericalFailure` for non-finite geometry or
calculations, and the resource errors below. Bounds also validate meshlet-local
indices and supported vertex/triangle counts. `BoundsPositions::new` defers errors.

## Vertex and index encode and decode

```text
pub fn encode_vertex_buffer(
    vertices: &[u8],
    count: usize,
    stride: usize,
    encoding: VertexEncoding,
    workspace: &mut Workspace,
) -> Result<Vec<u8>, Error>

pub fn decode_vertex_buffer(
    count: usize,
    stride: usize,
    source: &[u8],
    workspace: &mut Workspace,
) -> Result<Vec<u8>, Error>

pub fn encode_index_buffer(
    indices: &[u32],
    encoding: IndexEncoding,
    workspace: &mut Workspace,
) -> Result<Vec<u8>, Error>

pub fn decode_index_buffer(
    count: usize,
    stride: usize,
    source: &[u8],
    workspace: &mut Workspace,
) -> Result<Vec<u8>, Error>
```

Vertex input is `count * stride` initialized bytes; stride is a positive multiple
of four, at most 256. This recipe serializes packed XYZ as little-endian floats.
Index encoding takes a `u32` triangle list. Decoding returns little-endian bytes:
index stride 2 gives `u16` bytes and stride 4 gives `u32` bytes. At stride 2,
indices above 65535 wrap (upstream's truncating `u16` conversion); use stride 4
for such meshes. Counts and strides
come from your container format; encoded streams do not supply them for you.
Each allocating codec returns a `Vec<u8>`. Triangle encoding may rotate corners
within each triangle, preserving winding; decoded index order reflects those rotations.

```rust
use meshoptimizer_rs::codec::{
    decode_index_buffer, decode_vertex_buffer, encode_index_buffer, encode_vertex_buffer,
    IndexEncoding, VertexEncoding,
};
use meshoptimizer_rs::Workspace;

let positions: [[f32; 3]; 3] = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.]];
let indices = [0u32, 1, 2];
let vertices: Vec<u8> = positions.iter().flatten().flat_map(|v| v.to_le_bytes()).collect();
let mut workspace = Workspace::default();
let encoded = encode_vertex_buffer(&vertices, 3, 12, VertexEncoding::DEFAULT, &mut workspace)?;
assert_eq!(decode_vertex_buffer(3, 12, &encoded, &mut workspace)?, vertices);
let encoded = encode_index_buffer(&indices, IndexEncoding::DEFAULT, &mut workspace)?;
let decoded = decode_index_buffer(3, 4, &encoded, &mut workspace)?;
let expected: Vec<u8> = indices.iter().flat_map(|v| v.to_le_bytes()).collect();
assert_eq!(decoded, expected);
# Ok::<(), meshoptimizer_rs::Error>(())
```

Errors: `InvalidLayout` for invalid vertex/index strides or vertex byte lengths,
`InvalidTopology` for incomplete triangles, `InvalidStream` for malformed data,
`UnsupportedVersion` for unsupported codec versions, and the resource errors below.
Encoding constructors validate versions and levels (`InvalidParameter` for an
unsupported vertex level), so an invalid encoding configuration cannot be built.

With the `simd` feature, vertex decoding selects the widest kernel the CPU
supports when the program runs: AVX-512 VBMI/VBMI2 on x86-64 CPUs that report
those features, then SSE4.1, SSSE3 and SSE2, NEON on AArch64 and simd128 on wasm32.
Every level returns the same bytes and errors as the scalar decoder. Without
`std`, the AVX-512 kernel is used only when the build enables its target features.
There is nothing to configure.

## Streaming index sequences

`codec::IndexSequenceDecoder` is an opt-in extension, not in C++ meshoptimizer.
It accepts ordinary version 0/1 index-sequence bytes as they arrive, without
heap allocation or a Cargo feature. The container supplies the index count.
Keep the decoder across transport chunks and resubmit the unconsumed input
suffix when output space runs out. Zero output space is valid and yields
`NeedOutput` while indices remain; use at least one slot to make progress.

```rust
use meshoptimizer_rs::{codec::{IndexSequenceDecoder, Status}, Limits};

let compressed = [0xd1, 0, 4, 0xcd, 1, 4, 7, 0x98, 0x1f, 0, 0, 0, 0];
let mut decoder = IndexSequenceDecoder::new(6, Limits::default())?;
let mut provisional = Vec::new();
for chunk in compressed.chunks(2) { // replace with your transport's chunks
    let mut input = chunk;
    loop {
        let mut output = [0u32; 1];
        let progress = decoder.push(input, &mut output)?;
        provisional.extend_from_slice(&output[..progress.written]);
        input = &input[progress.consumed..];
        // `Status` is non-exhaustive; anything but NeedOutput ends this chunk.
        if progress.status != Status::NeedOutput {
            assert!(input.is_empty());
            break;
        }
    }
}
decoder.finish()?; // transport EOF: only now commit provisional indices
assert_eq!(provisional, [0, 1, 51, 2, 49, 1000]);
# Ok::<(), meshoptimizer_rs::Error>(())
```

All output is provisional until `finish()` succeeds. Submit every byte of the
stream, including any bytes arriving after `Done`: these are rejected as extra
input. `finish()` rejects incomplete headers, varints, counts, and padding.
Padding is exactly four opaque bytes, as in the one-shot decoder. Noncanonical
varints retain upstream's five-byte/truncated-high-bit semantics. Header errors
are reported immediately, even before enough bytes exist for the one-shot
minimum-length check. Errors are terminal and repeat on subsequent calls; an
error may follow provisional writes in the same call without a progress receipt.

`new` checks decoded size and charges four work units per declared index.
`push` charges one per consumed compressed byte against the remaining budget;
chunking and empty calls do not reset it. Fixed state and caller buffers are
outside `max_bytes` (zero is allowed). This enables bounded staging; the
application chooses whether to retain provisional output. Vertex and triangle
streams require trailer information and are not supported by this decoder.

## Untrusted input with Limits

```text
pub fn new(limits: Limits) -> Self // Workspace
```

```text
pub fn decode_vertex_buffer(
    count: usize,
    stride: usize,
    source: &[u8],
    workspace: &mut Workspace,
) -> Result<Vec<u8>, Error>
```

The default `Limits` allow 1 GiB of crate-owned output plus retained scratch
capacity and 2^34 counted record visits per call. Caller buffers, allocator overhead,
stack storage and the application's retained outputs are outside this accounting.
Choose smaller limits for the request, and check transport sizes and decoded size
before allocating caller buffers. There is no wall-clock timeout in `Limits`.

```rust
use meshoptimizer_rs::{codec::decode_vertex_buffer, Error, Limits, Workspace};

fn main() -> Result<(), Error> {
    // Check transport sizes before buffering a request or creating its views.
    let source = [0u8; 4]; // Deliberately malformed stream supplied by a client.
    let count = 3usize;
    let stride = 12usize;
    let limits = Limits { max_bytes: 64 << 20, max_work: 1 << 20 };
    if source.len() > limits.max_bytes || count > limits.max_bytes / stride {
        return Err(Error::LimitExceeded);
    }
    let mut workspace = Workspace::new(limits);
    match decode_vertex_buffer(count, stride, &source, &mut workspace) {
        Ok(bytes) => println!("{} decoded bytes", bytes.len()),
        Err(Error::InvalidStream) => println!("rejected malformed input"),
        Err(error) => return Err(error),
    }
    Ok(())
}
```

Returns decoded bytes or an error; this example treats `InvalidStream` as a
malformed client stream to reject, not a failure. Decoding can also return `InvalidLayout`, `UnsupportedVersion`,
`SizeOverflow`, `LimitExceeded` or `AllocationFailed`. `Workspace::new` is infallible.
`BoundsPositions::new` and `simplify_scale` have no workspace budget: bound input
sizes before calling them on untrusted data.

## Parallel workers

Each worker calls `simplify` (signature above) on a shared immutable XYZ array
and triangle list, and owns its workspace and returned mesh. The following uses standard threads and needs no `parallel` feature.

```rust
use meshoptimizer_rs::{simplify, Error, Positions, SimplifyOptions, SimplifySettings, Workspace};

let positions = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [1., 1., 0.]];
let indices = [0, 1, 2, 2, 1, 3];
let results = std::thread::scope(|scope| {
    let mut workers = Vec::new();
    for target_index_count in [6, 3] {
        let (positions, indices) = (&positions, &indices);
        workers.push(scope.spawn(move || {
            let mut workspace = Workspace::default();
            let settings = SimplifySettings {
                target_index_count, target_error: 0.01, options: SimplifyOptions::EMPTY,
            };
            // Reuse this workspace for further jobs handled by this worker.
            simplify(indices, Positions::from_packed(positions), settings, &mut workspace)
        }));
    }
    workers.into_iter().map(|worker| worker.join().expect("worker panicked"))
        .collect::<Result<Vec<_>, Error>>()
})?;
assert_eq!(results.len(), 2);
# Ok::<(), Error>(())
```

Returns one `SimplifiedMesh` per worker. With the `parallel` feature,
[`simplify_lod_chains_batch`](https://docs.rs/meshoptimizer-rs/latest/meshoptimizer_rs/parallel/fn.simplify_lod_chains_batch.html)
provides ordered per-mesh chains using Rayon. It panics if Rayon cannot start or
a worker panics. Its outer error is result-slot
`SizeOverflow` or `AllocationFailed`; item errors stay in input order and do not
cancel other items. Limits apply separately to each item, with no aggregate cap.

## Parallel groups within one cluster LOD mesh

Enable `parallel` and `clusterlod` for the opt-in `clusterlod::build_parallel`
(or `build_parallel_with_output`). This extension is not in C++ meshoptimizer.
Choose an existing Rayon pool and explicitly opt out of finite logical limits:

```rust
# #[cfg(all(feature = "parallel", feature = "clusterlod"))]
# {
use meshoptimizer_rs::{clusterlod, Limits, Workspace};
let mut positions = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.]];
let indices = [0, 1, 2];
let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build()?;
let mut workspace = Workspace::new(Limits {
    max_bytes: usize::MAX,
    max_work: u64::MAX,
});
let config = clusterlod::default_config(128)?; // dilation disabled
let groups = pool.install(|| clusterlod::build_parallel(config, clusterlod::Mesh {
    indices: &indices,
    positions: &mut positions,
    attributes: None,
    vertex_lock: None,
    attribute_weights: &[],
    attribute_protect_mask: 0,
}, &mut workspace))?;
assert!(!groups.is_empty());
assert_eq!(groups[0].clusters[0].indices, indices);
# }
# Ok::<(), Box<dyn std::error::Error>>(())
```

Partitioning and boundary locks run serially each level; groups use the existing
serial kernels and assemble in ordinal order. Callbacks run serially on the
calling thread, including their custom IDs and failure prefixes. Dilation,
any finite work/storage limit (including `Limits::default()`), single-group
levels, and speculative worker failures use the serial algorithm. Existing
`build` and batch APIs retain their behavior.

`Usage` reports identical logical serial work and peak storage. Concurrent
worker scratch, held speculative results, and Rayon infrastructure consume
additional physical memory. Select a pool size that fits the mesh and available
memory. No parallel speedup is guaranteed.

## Cluster LOD DAG files

`clusterlod::dag_format` serializes a built cluster DAG into an MDAG 1 file whose
geometry is split into pages that decode independently. It is an extension, not in
C++ meshoptimizer, and needs no Cargo feature; building the DAG needs `clusterlod`.
Pass the prefixes `build_dag_into` returned (its `DagCounts`) to `write`, then open
the bytes with `Reader::read`, which validates every table, refinement link and
codec payload before it returns. A client that fetched one page decodes it with
`decode_page` and the reader's resident tables only. `DEFAULT_PAGE_SIZE` is 128 KiB;
a cluster never straddles two pages.

```rust
# #[cfg(feature = "clusterlod")]
# {
use meshoptimizer_rs::clusterlod::{
    self, dag_format, DagBuffers, FlatDagCluster, FlatDagGroup, Mesh, Node,
};
use meshoptimizer_rs::Workspace;
let mut positions = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.]];
let indices = [0u32, 1, 2];
let mut workspace = Workspace::default();
let mut vertex_source = [0u32; 24];
let mut vertex_positions = [[0.; 3]; 24];
let mut flat_indices = [0u32; 24];
let mut clusters = [FlatDagCluster::default(); 16];
let mut groups = [FlatDagGroup::default(); 16];
let mut nodes = [Node::default(); 128];
let counts = clusterlod::build_dag_into(
    clusterlod::default_config(128)?,
    Mesh { indices: &indices, positions: &mut positions, attributes: None,
           vertex_lock: None, attribute_weights: &[], attribute_protect_mask: 0 },
    8,
    DagBuffers { vertex_source: &mut vertex_source, vertex_positions: &mut vertex_positions,
                 indices: &mut flat_indices, clusters: &mut clusters, groups: &mut groups,
                 nodes: &mut nodes },
    &mut workspace,
)?;
let file = dag_format::write(
    &groups[..counts.groups], &clusters[..counts.clusters],
    &vertex_positions[..counts.vertices], &flat_indices[..counts.indices],
    dag_format::DEFAULT_PAGE_SIZE, &mut workspace,
)?;
let reader = dag_format::Reader::read(&file, &mut workspace)?;
assert_eq!(reader.cluster_count(), counts.clusters);
let mut triangles = 0;
for page in 0..reader.page_count() {
    // A client fetches only `file[range]`; here the whole file is in memory.
    let range = reader.page_range(page)?;
    for cluster in reader.decode_page(page, &file[range], &mut workspace)? {
        triangles += cluster.indices.len() / 3;
    }
}
assert!(triangles >= 1);
# }
# Ok::<(), meshoptimizer_rs::clusterlod::dag_format::Error>(())
```

`group` and `cluster_record` return the resident metadata and `cluster_page` maps a
cluster to its page. `Reader` borrows the file bytes and currently needs the whole
file to open; it is not a remote directory reader. The same input always produces
the same bytes. `write_generic` and `decode_page_generic` select `u16` or `u32`
indices. Errors are typed (`Invalid`, `Unsupported`, `Limit`, `Allocation`,
`Codec`). The wire layout, limits and compatibility policy are in
[DAG_FORMAT.md](https://github.com/Tavrin/meshoptimizer-rs/blob/v0.2.17/docs/DAG_FORMAT.md).

## Parallel vertex codec and spatial meshlets for one large mesh

With `parallel`, three opt-in functions in the `parallel` module use the
current Rayon pool for a single large input. They are not in C++
meshoptimizer, and each returns exactly the bytes of the serial function for
every pool size:

- `encode_vertex_buffer_parallel` runs the per-channel estimators and runs of
  blocks concurrently. Block bodies depend only on the input.
- `decode_vertex_buffer_parallel` finds block starts with a serial scan of the
  group selectors, decodes runs of blocks from a zero baseline concurrently,
  chains each run's last vertex and applies the baselines. This works because
  every channel is a prefix sum or prefix xor, so a decoded block is linear in
  its starting vertex. A damaged stream is judged by the serial decoder.
- `build_meshlets_spatial_parallel` runs box construction, the three axis
  sorts and the recursive cut on independent subtrees; emission stays a serial
  scan. Only a workspace with `max_bytes == usize::MAX` and
  `max_work == u64::MAX` takes the concurrent path, because per-worker scratch
  is not counted; the work count matches serial. The scan and flex builders keep
  one open meshlet across the whole triangle sequence and have no exactly
  equal parallel form. The index codecs carry FIFO and next-vertex state from
  triangle to triangle with no resynchronization points in the format, so they
  are not parallelized.

Encoding and spatial meshlets take the serial path for a one-worker pool or a
buffer of fewer than eight blocks. Decoding takes it for fewer than four
workers, an output under 48 MiB (32 MiB for strides of 8 or less), or fewer
than eight blocks.
Measured speed-ups: `docs/PERFORMANCE.md`.

```rust
# #[cfg(feature = "parallel")]
# {
use meshoptimizer_rs::{codec::VertexEncoding, parallel, Workspace};
let vertices: Vec<u8> = (0..64_000u32).flat_map(|i| (i * 3).to_le_bytes()).collect();
let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build()?;
let mut workspace = Workspace::default();
let encoded = pool.install(|| {
    parallel::encode_vertex_buffer_parallel(&vertices, 64_000, 4, VertexEncoding::DEFAULT, &mut workspace)
})?;
let decoded = pool.install(|| parallel::decode_vertex_buffer_parallel(64_000, 4, &encoded, &mut workspace))?;
assert_eq!(decoded, vertices);
# }
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Lower peak memory with Retention::Lean

```text
pub fn set_retention(&mut self, retention: Retention) // Workspace
```

Use the same position and index layouts as simplification. `set_retention` returns
`()` and cannot fail. With `Retention::Lean`, the workspace keeps less scratch
between calls, so peak memory is lower. Later calls have to reallocate that
scratch, so they are slower. It applies to simplify, vertex-cache and overdraw
calls; other operations keep their scratch.

```rust
use meshoptimizer_rs::{simplify, Positions, Retention, SimplifyOptions, SimplifySettings, Workspace};

let positions = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [1., 1., 0.]];
let indices = [0, 1, 2, 2, 1, 3];
let mut workspace = Workspace::default();
workspace.set_retention(Retention::Lean);
let lod = simplify(&indices, Positions::from_packed(&positions), SimplifySettings {
    target_index_count: 3, target_error: 0.01, options: SimplifyOptions::EMPTY,
}, &mut workspace)?;
assert!(lod.indices.len() <= indices.len());
# Ok::<(), meshoptimizer_rs::Error>(())
```

Returns the same simplification result and errors as the first recipe. Lean is
opt-in: it lowers peak memory, but later calls reallocate scratch and run slower.

## Mesh repair

Fan splitting and crack stitching are opt-in extensions, not in C++ meshoptimizer.
`split_non_manifold_vertices(indices, records, workspace)` accepts a `VertexStream`
of complete initialized attribute records and returns packed copies plus indices
and `SplitVerticesReport`. The lowest-corner fan retains the original index;
other fans get appended copies, preserving every supplied attribute byte.
Fans are joined across shared edges as `analyze_mesh` defines them, so afterwards
`non_manifold_vertices` is zero; edges shared by more than two faces stay shared.
Unreferenced records remain.

`stitch_cracks(indices, records, positions, tolerance, workspace)` returns packed
records, indices and `StitchReport` (accepted pairs, T-junction splits, refused
candidates, remaining boundary length). `None` uses 1e-6 times the largest mesh
bounds extent; `Some(distance)` selects an absolute Euclidean tolerance, including
zero. Positions must describe the same vertices as the records. This is a
position-only seam policy: the winning representative's complete attributes win.
T-junctions reuse existing vertices, so attributes need no interpolation.
Caller-provided position views must agree with the position bytes in the records.
The returned records stay uncompact; downstream fetch optimization can compact them.

A deterministic sorted spatial grid finds near boundary pairs. Candidates are
accepted only with positive old/new face-normal dot products on changed faces and
without increasing the counts of edges with more than two faces, equally directed
two-face edges or surplus vertex fans. Refusals leave the current topology
unchanged; defects already in the input do not block other stitches.
This is a conservative local operation, not a general surface reconstruction or
self-intersection test. The pipeline stitches before splitting so a T-junction can be joined
before disconnected endpoint fans are separated. Isolated coincident fans
are refused by stitching and then separated by splitting. Each original boundary vertex can subdivide at
most one edge per call. Whole-mesh validation can make dense cases expensive;
all candidate visits, sorting and temporary storage obey workspace limits.
An exhausted budget returns an error without a partial mesh.

Both APIs have `_generic` forms for u16/u32; appended indices narrow with checked
`IndexOverflow`. Use `ProcessOptions::split_non_manifold_vertices = true` and
`ProcessOptions::stitch_cracks = Some(None)` (or `Some(Some(distance))`) to insert
these stages after orientation and before hole filling and LOD generation.
They default off. Existing welding and sanitation should precede repair.

```rust
use meshoptimizer_rs::{split_non_manifold_vertices, VertexStream, Workspace};
let records = [10u8, 20, 30, 40, 50];
let result = split_non_manifold_vertices(
    &[0, 1, 2, 0, 3, 4], VertexStream::packed(&records, 1)?,
    &mut Workspace::default(),
)?;
assert_eq!(result.indices, [0, 1, 2, 5, 3, 4]);
assert_eq!(result.vertices, [10, 20, 30, 40, 50, 10]);
# Ok::<(), meshoptimizer_rs::Error>(())
```


`sanitize` is an extension; it is not in C++ meshoptimizer.

```text
pub fn sanitize(
    indices: &[u32],
    positions: Positions<'_>,
    options: SanitizeOptions,
    workspace: &mut Workspace,
) -> Result<SanitizedMesh, Error>
```

Use it on uploaded or generated meshes before simplification or meshlet
building. It only removes triangles: out-of-range indices, non-finite positions,
repeated indices and later copies of the same face. Kept triangles stay in input
order with their original indices and winding, so vertex streams need no change.
`SanitizeOptions::COINCIDENT_CORNERS` also drops triangles with two corners at
bit-identical positions (collinear triangles are kept; no area is computed),
`WELD_POSITIONS` compares duplicate faces by position instead of by
index, `IGNORE_ORIENTATION` also drops reverse-wound copies, and `REJECT_INVALID`
returns an error instead of dropping invalid triangles.

```rust
use meshoptimizer_rs::{sanitize, Positions, SanitizeOptions, Workspace};

let positions = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [0., 1., 0.]];
// A face, its rotated copy, its reverse-wound copy, and a face whose
// corners 2 and 3 share a position.
let indices = [0, 1, 2, 1, 2, 0, 0, 2, 1, 0, 2, 3];
let mut workspace = Workspace::default();
let options = SanitizeOptions::COINCIDENT_CORNERS | SanitizeOptions::IGNORE_ORIENTATION;
let mesh = sanitize(&indices, Positions::from_packed(&positions), options, &mut workspace)?;
assert_eq!(mesh.indices, [0, 1, 2]);
let report = mesh.report;
assert_eq!((report.duplicate, report.reversed_duplicate, report.coincident_corners), (1, 1, 1));
# Ok::<(), meshoptimizer_rs::Error>(())
```

Returns the kept indices and a `SanitizeReport` with one count per removal
reason. `sanitize_into` writes to a caller buffer of at least
`sanitize_bound(indices.len())` indices and leaves it unchanged on any error.
Sanitation does not weld vertices, fill holes or fix orientation; the result is
not guaranteed to be manifold or closed.

### Tolerance welding, orientation and small holes

These are opt-in calls, like `sanitize`; they are extensions, not in C++
meshoptimizer.
Welding returns original representatives without moving or compacting vertices.
Choose an explicit seam policy; use `WeldPolicy::AttributeEquality` to compare
UVs, normals, materials or other caller attributes. Every merged vertex lies
within tolerance of its representative; nearby chains do not merge transitively.
Always apply the remap and sanitize faces again before proceeding.

```rust
use meshoptimizer_rs::{weld_vertices, orient_faces, fill_holes, sanitize,
    Positions, SanitizeOptions, WeldPolicy, Workspace};
let vertices = [[0.,0.,0.], [1.,0.,0.], [1.,1.,0.], [0.,1.,0.], [0.001,0.,0.]];
let uv_classes = [0, 0, 0, 0, 0];
let mut workspace = Workspace::default();
let positions = Positions::from_packed(&vertices);
let welded = weld_vertices(positions, 0.01,
    WeldPolicy::AttributeEquality(&|a,b| uv_classes[a as usize] == uv_classes[b as usize]),
    &mut workspace)?;
assert_eq!(welded.remap, [0,1,2,3,0]);
let indices: Vec<u32> = [4,1,2,0,3,2].map(|v| welded.remap[v]).to_vec();
let clean = sanitize(&indices, positions, SanitizeOptions::EMPTY, &mut workspace)?;
let oriented = orient_faces(&clean.indices, vertices.len(), &mut workspace)?;
assert_eq!(oriented.report.flipped_faces, [1]);
assert!(oriented.report.conflicts.is_empty());
let filled = fill_holes(&oriented.indices, positions, 4, &mut workspace)?;
assert_eq!(filled.report.filled.len(), 1);
assert_eq!(filled.report.output_triangles, 4);
assert!(filled.indices.iter().all(|&v| v < vertices.len() as u32));
# Ok::<(), meshoptimizer_rs::Error>(())
```

`orient_faces` preserves each component's lowest face as its winding seed;
it does not choose outward orientation. Inspect `conflicts` and
`ambiguous_components` before relying on the result. Non-manifold edges never
provide propagation links. `fill_holes` appends deterministic ear triangles for
simple, approximately planar boundary loops within the inclusive edge limit.
It reports oversized, non-simple and ambiguous components separately, uses no
new vertices, and does not test intersections with other mesh surfaces. Intended
openings can also be filled: the caller must choose whether to invoke it.

Each API has an `_into` variant and a bound function. Caller-buffer variants
stage decisions in checked heap scratch and leave the entire destination
unchanged on any error, including limits and insufficient capacity. Reports
list original face/vertex indices, so callers can inspect changes. Added faces
have no inherited material or face attributes; assign those explicitly.

## Mesh topology analysis

`analyze_mesh`, also an extension, reports what is wrong before anything is
removed. It changes nothing and returns a `MeshAnalysis`: triangle
classifications, then counts of boundary edges and components,
non-manifold edges (more than two faces) and vertices (more than one fan of
faces), orientation conflicts (exactly two incident faces using an edge in the
same direction) and
connected components. `AnalyzeOptions::with_weld_positions(true)` treats
vertices with equal positions as one, which shows whether split seams close a
surface; `with_list_limit(n)` also lists the first `n` defects of each kind.
Analyze, sanitize, then analyze the result to see what remains:

```rust
use meshoptimizer_rs::{analyze_mesh, sanitize, AnalyzeOptions, Positions, SanitizeOptions, Workspace};

let positions = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [0., 0., 1.]];
// A tetrahedron plus a duplicate of its first face.
let indices = [0, 2, 1, 0, 1, 3, 1, 2, 3, 0, 3, 2, 2, 1, 0];
let mut workspace = Workspace::default();
let positions = Positions::from_packed(&positions);
let before = analyze_mesh(&indices, positions, AnalyzeOptions::EMPTY, &mut workspace)?;
assert_eq!((before.duplicate, before.non_manifold_edges), (1, 3));
let mesh = sanitize(&indices, positions, SanitizeOptions::EMPTY, &mut workspace)?;
let after = analyze_mesh(&mesh.indices, positions, AnalyzeOptions::EMPTY, &mut workspace)?;
assert_eq!((after.boundary_edges, after.non_manifold_edges, after.orientation_conflicts), (0, 0, 0));
# Ok::<(), meshoptimizer_rs::Error>(())
```

## Resource errors

Workspace operations can return `SizeOverflow` when size arithmetic or platform
allocation bounds overflow, `LimitExceeded` when the per-call bytes or counted work
exceed `Limits`, and `AllocationFailed` when fallible reservation fails.
Caller-buffer `_into` forms also return `BufferTooSmall` for insufficient capacity;
a late error may leave a used prefix modified. The `_into` functions are
`simplify_into`, `optimize_vertex_cache_into`, `optimize_overdraw_into` and
`build_meshlets_into`, among others.

## Gotchas

- **Indices:** `u32` only. Pass the full position count as `vertex_count`, not the number of vertices a LOD uses. An index at or beyond that count returns `IndexOutOfBounds`.
- **Simplify target:** `target_index_count` larger than `indices.len()` returns `InvalidParameter`.
- **Index decode at stride 2:** indices above 65535 wrap (upstream's truncating `u16` conversion). Use stride 4 for meshes with more than 65536 vertices.
- **Position layout:** use `Positions::from_packed(&[[f32; 3]])` when you can; it is the fastest layout. Other layouts work but read more slowly.
- **Workspace reuse:** use one `Workspace` per worker thread and reuse it across calls; see [Per-mesh LOD chain]#per-mesh-lod-chain.
- **Retention::Lean:** lowers peak memory at the cost of time; the default is `Retention::Reuse`.
- **Default Limits:** 1 GiB of crate-owned storage and 2^34 counted visits per call; set smaller `max_bytes` and `max_work` for untrusted input and check caller allocations separately.
- **Byte-identical output:** results match C++ meshoptimizer 1.3 (scalar build); recorded differential inputs and exceptions are described in the README.
- **Semver policy:** 0.2.x patch releases are drop-in, with no API break and the same output.

## One-call LOD chain

`build_lod_chain` is an extension not in C++ meshoptimizer. Targets are
relative to the original mesh; each level defaults to the previous output.

```rust
use meshoptimizer_rs::{build_lod_chain, LodChainOptions, LodTargets, LodErrors, Positions, Workspace};
let positions = [[0.,0.,0.], [1.,0.,0.], [0.,1.,0.], [1.,1.,0.]];
let options = LodChainOptions::new(LodTargets::Ratios(&[0.5]), LodErrors::Uniform(1.0));
let chain = build_lod_chain(&[0,1,2,2,1,3], Positions::from_packed(&positions), &options, &mut Workspace::default())?;
assert_eq!(chain.levels.len(), 1);
# Ok::<(), meshoptimizer_rs::LodChainError>(())
```

Options are built with `LodChainOptions::new` and the `with_simplify_options`,
`with_attributes`, `with_vertex_flags` and `with_independent` setters; the option
and enum types are `#[non_exhaustive]`. Vertex flags (locks) apply with or
without attributes. Each level owns a `Vec<u32>`; other outputs such as meshlets
or clusters would be separate APIs.

- **Targets:** ratios become `floor(ratio * source_triangles) * 3` indices. The
  ratios must decrease strictly, but two neighbouring ratios may round to the
  same count on a small mesh.
- **Error and scale:** `LodLevel::error` is the simplifier's own returned value
  for that level, unconverted. In successive mode it is relative to the previous
  level, not to the source and not cumulative; with attributes it includes the
  attribute terms. `LodLevel::scale` is the extent it was normalized by (the
  referenced vertices only, with `SPARSE`). Units follow `ERROR_ABSOLUTE`.
- **`stopped_at_error_limit`:** the simplifier stopped because the next collapse
  candidate exceeded the level's error limit. A looser limit is not guaranteed
  to reach the target; a missed target may also reflect topology constraints.
- **Limits and usage:** the workspace limits cover the whole call, including the
  builder's own scans, every level's work, and the chain metadata plus retained
  level outputs together with scratch. `Workspace::usage()` reports the call's
  total work and peak bytes, on success and on failure.
- **Failure:** the result is atomic. `LodChainError::level` is the zero-based
  failing level, or `None` for a failure of the call as a whole.

## LOD quality and switch distances

`measure_lod_quality` and `measure_lod_chain_quality` measure sampled surface
distances and shading-normal angles. This extension is not in C++ meshoptimizer. It does not change
`simplify` or `build_lod_chain`.

```rust
use meshoptimizer_rs::{measure_lod_quality, LodQualityMesh, LodQualityOptions,
    LodCamera, Positions, Workspace};
let source = [[0.,0.,0.], [1.,0.,0.], [0.,1.,0.]];
let level = [[0.,0.,0.1], [1.,0.,0.1], [0.,1.,0.1]];
let indices = [0, 1, 2];
let quality = measure_lod_quality(
    LodQualityMesh::new(&indices, Positions::from_packed(&source)),
    LodQualityMesh::new(&indices, Positions::from_packed(&level)),
    &LodQualityOptions::default(), &mut Workspace::default())?;
let camera = LodCamera::new(60_f64.to_radians(), 1080., 1.)?;
let depth = camera.switch_distance(quality.symmetric.max)?;
assert!(depth > 90. && depth < 100.);
# Ok::<(), meshoptimizer_rs::Error>(())
```

`measure_lod_chain_quality(source, &chain, &options, Some(camera), &mut workspace)`
returns one report per level, measured against the source using the chain's
shared vertex buffers. Empty simplified surfaces return `InvalidParameter`.
Assign `LodQualityMesh::normals` on both surfaces to compare interpolated shading
normals in radians. Normals must be finite and nonzero; cancelling interpolated
normals return `NumericalFailure`.

Every triangle contributes its three corners plus `ceil(area * density)`
barycentric samples. Shared corners repeat. The deterministic sequence and BVH
tie rule are specified on `measure_lod_quality`. RMS/mean weight samples equally.
Maxima are sampled estimates and can miss continuous surface extrema, including
with high density. Increasing density is useful for convergence checks.

Switch distances use a pinhole camera and the sampled symmetric maximum:
`error * height / (2 * tan(vertical_fov/2) * pixel_tolerance)`. The result is the
minimum camera-space depth for a transverse displacement of that magnitude.
For camera-to-mesh-center distances, add a conservative bounding radius. This
model excludes texture error, occlusion and rasterization; it is not a certified
screen-space bound. Chain thresholds may be nonmonotone. Limits bound the whole
measurement call, including all chain reports, validation, BVH and query visits.

## Hidden-surface removal

This extension is not in C++ meshoptimizer and needs no Cargo feature.
Use it on opaque, static imported geometry before simplification. The default
rasterizes 26 orthographic views into an 8x8 tiled item/depth buffer using
fixed-point edges. `pixel_size` is the world-space pixel width; zero selects
longest referenced mesh side / 128. The square view spans twice that side;
resolution is ceil(2*side / pixel_size), from 1 to 2048. Finer requests return
`InvalidParameter`. Fully covered pixels certify occlusion with conservative
depth bounds; uncertain pixels retain geometry. Every triangle visible over at
least a pixel-area from a tested direction is retained, including partially
visible triangles. The outward coverage rule additionally retains smaller
slivers and preserves the existing lattice-sample guarantee. Coarse meshes and
small openings can leave many uncertain triangles, which are retained. A final
BVH sample check only for raster-hidden candidates preserves the original
floating-point sample behavior, including shared-edge rounding misses; it only
restores faces. It can be expensive on meshes with many hidden candidates.
Finite cameras use BVH rays from a barycentric lattice (denominator 2: six
boundary points plus centroid); every visible tested sample keeps the triangle.
Use more subdivisions for finer finite-camera sampling. Faces are two-sided, and
coplanar contacts do not occlude each other. A support surface visible from below
remains present with outside views. Restrict views to reachable camera positions
when that is the intended visibility domain.

```rust
use meshoptimizer_rs::{remove_hidden_triangles, remove_hidden_triangles_into,
    HiddenOptions, HiddenViews, Positions, Workspace};
let positions = [[0.,0.,0.], [1.,0.,0.], [0.,1.,0.]];
let indices = [0,1,2, 1,2,0];
let cameras = [[0.,0.,5.], [2.,2.,3.]];
let mut options = HiddenOptions::default();
options.views = HiddenViews::Points(&cameras);
options.subdivisions = 4;
options.tolerance = 1e-6; // world units; near contacts retain more geometry
let mut workspace = Workspace::default();
let mesh = remove_hidden_triangles(&indices, Positions::from_packed(&positions),
    options, &mut workspace)?;
assert_eq!(mesh.report.duplicate, 1);
let mut output = [u32::MAX; 9];
let report = remove_hidden_triangles_into(&mut output, &indices,
    Positions::from_packed(&positions), options, &mut workspace)?;
assert_eq!(&output[..report.index_count()], mesh.indices);
assert_eq!(&output[report.index_count()..], &[u32::MAX; 6]);
# Ok::<(), meshoptimizer_rs::Error>(())
```

`HiddenViews::Bounds { min, max }` samples eight box corners and its center,
not every point in the volume. Reports distinguish exact same-winding duplicates,
occluded faces with exact reverse-wound counterparts, and other occluded faces.
Back-to-back walls that can be seen are retained. Indices and winding remain in
input order. The caller-buffer form leaves all storage untouched on error.
Limits meter sorting, projections, raster rectangles and buffer initialization;
finite cameras also meter BVH construction, node visits and intersections, which
can still approach quadratic work. Outside views execute serially with identical
output regardless of the `parallel` feature or thread-pool size. Occlusion is measured against
the original mesh; removing its sampled-hidden surfaces does not guarantee
identical continuous visibility of the filtered mesh.

## Alpha-cutout card trimming

This extension is not in C++ meshoptimizer and needs no Cargo feature. Alpha-tested
foliage cards are mostly transparent, and the GPU still rasterizes and tests every
transparent texel they cover. `trim_alpha_cards` replaces each card with a convex
polygon of at most `max_vertices` vertices that contains every texel with
`alpha >= threshold`, the problem solved by Emil Persson's
[particle trimmer](http://www.humus.name/index.php?page=Cool&ID=8) (2009). It takes
the convex hull of the visible texels, then the smallest polygon built from hull
edge lines, corner bisectors and lines parallel to the card outline, chosen by an
exact search after a greedy reduction of long hulls. This is not always the global
minimum. The polygon stays inside the card.

A card is a group of triangles connected through shared vertex-index edges with
nonzero texture area. Every float of the vertex is interpolated. Planar cards with
attributes linear in UV become one fan of `max_vertices - 2` or fewer triangles.
Bent or curved cards, and cards whose triangles do not form a convex region in
texture space, are clipped per source triangle with that triangle's own
interpolation, so rendering is unchanged where the card is kept; these cards may
exceed the vertex budget and are counted in `split_cards`. Cards without visible
texels are removed, and cards without a smaller polygon are copied.

Texel `(x, y)` covers `[x, x + 1) x [y, y + 1)` in `(u * width, v * height)`, with
`v = 0` in the first row. `AlphaWrap` selects clamp-to-edge or repeat for texels
outside the mask. `padding` expands each visible texel: 0.5 (the default) covers
bilinear sampling at full resolution, 0 covers nearest sampling, and
`1.5 * 2^L - 1` covers bilinear sampling of box-filtered mip level `L`. Mips with
rescaled alpha (coverage-preserving mip generation) are not covered. A margin of
`1/256` texel plus `|coordinate| / 2^22` absorbs f32 rounding of the new UVs.

```rust
use meshoptimizer_rs::{trim_alpha_cards, AlphaMask, AlphaWrap, CardTrimOptions, Workspace};
// A 16x16 mask with a visible disc; real masks come from the card texture.
let mut alpha = [0u8; 256];
for y in 0..16 {
    for x in 0..16 {
        let (dx, dy) = (x as f32 - 7.5, y as f32 - 7.5);
        if dx * dx + dy * dy < 25.0 {
            alpha[y * 16 + x] = 255;
        }
    }
}
// RGBA data would use AlphaMask::with_layout(&rgba[3..], 4, 4 * width, width, height).
let mask = AlphaMask::new(&alpha, 16, 16)?;
// One quad: x, y, z, u, v per vertex.
let vertices = [
    -1., -1., 0., 0., 0.,
    1., -1., 0., 1., 0.,
    1., 1., 0., 1., 1.,
    -1., 1., 0., 0., 1.,
];
let mut options = CardTrimOptions::default();
options.max_vertices = 6;
options.wrap = AlphaWrap::Repeat;
let trimmed = trim_alpha_cards(&[0, 1, 2, 0, 2, 3], &vertices, 5, 3, mask, options,
    &mut Workspace::default())?;
let report = trimmed.report;
assert_eq!((report.trimmed_cards, report.output_triangles), (1, 4));
assert!(report.area_after < 0.8 * report.area_before);
// Transparent area estimate: covered area minus visible texel centers.
let transparent = report.area_after - report.opaque_texels as f64;
assert!(transparent < 80.0);
# Ok::<(), meshoptimizer_rs::Error>(())
```

The result is a new vertex buffer in first-use order and a new index buffer; run
the usual cache and fetch optimizations afterwards. Output winding follows each
source triangle. Normals are interpolated, not renormalized. Cards with identical
UV triangles share one fit, so instanced foliage costs one fit per distinct card.
Limits meter the scanned texels and the polygon search. Larger budgets trade
triangles for area: a quad card becomes `max_vertices - 2` triangles whenever a
smaller polygon exists, even when the last vertices remove little area.

`CardTrimOptions::vertex_cost` stops that. It is the price of one polygon vertex
in square mask texels (default 0: always use the full budget, as before). Each
card takes the vertex count `c` that minimizes `polygon area + vertex_cost * c`,
so a vertex is added only while it removes at least that much transparent area
(ties go to fewer vertices). The cost is compared with the card's fitted
polygon, so it is an absolute area: pick it from the mask size, for example a
fraction of the mask's texel count, and sweep it as below.
`TrimmedCards::card_vertices` lists the vertex count chosen for each card in
input order: the fitted polygon's count for a trimmed card, 0 for a removed
card and the distinct vertex count of an unchanged card, so a caller can see
which cards stopped early.

On four CC0 Poly Haven plants with their 2048x2048 alpha maps, plain quad cards
(the UV bounding rectangle of each authored card) lost 2-16% of their transparent
area at budget 4, 27-50% at budget 6 and 31-55% at budget 8. The authored meshes,
already modelled around the leaf shapes, lost 0-15%.

`vertex_cost` on the same quad cards at budget 8, with the 2048x2048 masks
(texture area removed, in Mtexel², and triangles after trimming; cost 0 is the
full budget):

| asset (cards, input triangles) | cost 0 | 100 | 300 | 1000 | 3000 | 10000 |
|---|---|---|---|---|---|---|
| fir_sapling (49,189 cards, 98,378) | 293,402 tris, 42.2 | 183,696, 38.2 | 134,943, 28.7 | 98,388, 3.5 | 98,387, 3.5 | 98,385, 3.5 |
| shrub_01 (1,736 cards, 3,472) | 9,092, 26.4 | 8,500, 26.4 | 7,564, 26.2 | 7,133, 26.0 | 5,517, 22.9 | 3,765, 16.1 |
| grass_medium_02 (191 cards, 382) | 1,146, 15.3 | 1,117, 15.3 | 950, 15.2 | 890, 15.2 | 696, 14.9 | 567, 14.1 |
| fern_02 (53 cards, 106) | 318, 7.27 | 318, 7.27 | 318, 7.27 | 318, 7.27 | 312, 7.26 | 230, 6.85 |

The cheapest vertices are the last ones: on the shrub, a cost of 300 texels²
keeps 99% of the removed area with 17% fewer triangles, and on the fir 100
keeps 90% with 37% fewer. The cost is absolute, so the same value stops
earlier on cards with little to gain (nearly every fir card went back to its 4-vertex
quad at 1000 while the larger fern cards still used 8). Pick it per mask
size and sweep it as above.

## Octahedral impostors

This extension is not in C++ meshoptimizer and needs no Cargo feature. Beyond
some distance a tree or prop can be drawn as one camera-facing card textured
from an atlas of views. `bake_impostor` captures those views on the CPU, using
the layout of Ryan Brucks'
[octahedral impostors](https://shaderbits.com/blog/octahedral-impostors) (2018):
view directions sit on the vertices of an `N x N` grid over the octahedral map
of the upper hemisphere (`ImpostorLayout::Hemisphere`, the usual choice for
trees) or the whole sphere (`ImpostorLayout::Sphere`), and the runtime blends
the three views of the grid triangle that contains the camera direction.

Directions point from the object toward the viewer in the mesh frame, with +Y
up. `ImpostorLayout::encode` and `decode` convert between a direction and its
octahedral point in `[-1, 1]^2`. View `(i, j)` has index `j * N + i`, point
`[2i / (N - 1) - 1, 2j / (N - 1) - 1]` and the tile at
`(i * view_resolution, j * view_resolution)` in the atlas.
`ImpostorGrid::blend(direction)` returns the three view indices and their
barycentric weights; `ImpostorGrid::view_frame(view)` returns the capture
frame (`direction`, `right`, `up`). Every view frames the same bounding sphere:
a point `p` lands at tile coordinates
`((p - c) . right / r + 1) / 2` and `(1 - (p - c) . up / r) / 2` (row 0 at
the top), and its stored depth is `(1 - (p - c) . direction / r) / 2`.

```rust
use meshoptimizer_rs::{bake_impostor, impostor_switch_distance, ImpostorAlbedo,
    ImpostorGrid, ImpostorLayout, ImpostorOptions, LodCamera, Positions, Workspace};
// Two crossed quads with a UV-driven texture lookup.
let p = [[-1., 0., 0.], [1., 0., 0.], [1., 2., 0.], [-1., 2., 0.],
         [0., 0., -1.], [0., 0., 1.], [0., 2., 1.], [0., 2., -1.]];
let uv = [[0., 1.], [1., 1.], [1., 0.], [0., 0.], [0., 1.], [1., 1.], [1., 0.], [0., 0.]];
let indices = [0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7];
// A disc of leaves: alpha from distance to the card center.
let leaves = |_triangle: usize, uv: [f32; 2]| {
    let (du, dv) = (uv[0] - 0.5, uv[1] - 0.5);
    [0.2, 0.5, 0.1, if du * du + dv * dv < 0.2 { 1.0 } else { 0.0 }]
};
let mut options = ImpostorOptions::default();
options.grid = ImpostorGrid::new(ImpostorLayout::Hemisphere, 8)?;
options.view_resolution = 32;
let atlas = bake_impostor(&indices, Positions::from_packed(&p), None,
    ImpostorAlbedo::Texture { uvs: &uv, sampler: &leaves }, options,
    &mut Workspace::default())?;
assert_eq!(atlas.size, 256);
assert_eq!(atlas.report.empty_views, 0);
// Runtime: the views to blend for a camera direction.
let blend = atlas.grid.blend([0.3, 0.5, 0.8])?;
assert!((blend.weights.iter().sum::<f32>() - 1.0).abs() < 1e-6);
// When to switch, for a 60 degree, 1080 px camera and a 1 px tolerance.
let camera = LodCamera::new(60_f64.to_radians(), 1080., 1.)?;
let switch = impostor_switch_distance(atlas.bounds, atlas.grid, 32, camera)?;
assert!(switch.distance > switch.view_error);
# Ok::<(), meshoptimizer_rs::Error>(())
```

Each view is rasterized at `view_resolution * samples_per_axis` samples per side
with exact integer edge functions, a top-left fill rule and a nearer-wins depth
test. Fragments whose source alpha is below `alpha_cutoff` are discarded before
the depth test, as with glTF `MASK` materials, so leaves behind a transparent
texel stay visible. Colour comes from `ImpostorAlbedo`: white, vertex colours
or a texture callback `sampler(triangle, uv)`; the triangle index lets one
callback serve several materials. A texel averages the colour of its covered
samples, stores the renormalized mesh-frame normal as `n * 0.5 + 0.5` and the
nearest depth. Its alpha is conservative: the covered fraction divided by
`coverage_threshold` (default 0.5), clamped to one, so thin branches do not
dissolve at the distance where impostors are used. `dilation` copies colour,
normal and depth into empty neighbours with alpha 0, which keeps bilinear
filtering from pulling black into the silhouette. Back faces are drawn with
reversed normals unless `double_sided` is false. The bounding sphere is
computed from the referenced vertices, or fixed with `bounds` so that several
assets share one frame.

`impostor_switch_distance` returns the camera-to-center distance beyond which
two errors project below the pixel tolerance: one texel (`2r / resolution`)
and the view error, the radius times the largest blend-weighted distance
between a direction and its blended view directions. The view error bounds how
far a point on the bounding sphere moves when views are blended without
parallax correction, and it dominates for practical grids. A runtime that
offsets by the stored depth sees less; it can pass `texel_error` to
`LodCamera::switch_distance` and add the radius instead.

The baker is deterministic: the same input gives the same bytes on every
platform, provided the texture callback is deterministic. Workspace limits
meter the atlas, one view of 32-byte samples and the rasterized samples.

Measured on three CC0 [Poly Haven](https://polyhaven.com/license) assets (the
first mesh of each: `fern_02`, 2,384 triangles; `fir_sapling`, 157,402; and
`shrub_01`, 156,012, which is a row of about a dozen small shrubs) with their
1k diffuse and alpha textures, hemisphere layout, 2 x 2 samples per texel, on
one laptop CPU core. The error columns compare 12 novel directions between
views (elevations 12, 37 and 63 degrees) reconstructed from the atlas with
the three blended views, against a direct render of the same direction: mask
IoU at alpha 0.5, and mean absolute RGB error (0-255) over the union of both
masks.

| views | view px | atlas (2 planes) | bake time | IoU fern / fir / shrub | RGB error fern / fir / shrub |
|---|---|---|---|---|---|
| 8 x 8 | 128 | 1024², 8 MiB | 0.10-0.40 s | 0.74 / 0.60 / 0.45 | 22 / 39 / 66 |
| 8 x 8 | 256 | 2048², 32 MiB | 0.44-0.83 s | 0.71 / 0.57 / 0.42 | 24 / 41 / 69 |
| 12 x 12 | 128 | 1536², 18 MiB | 0.29-0.90 s | 0.84 / 0.72 / 0.55 | 16 / 30 / 57 |
| 12 x 12 | 256 | 3072², 72 MiB | 0.99-1.98 s | 0.82 / 0.69 / 0.51 | 18 / 32 / 61 |

The three-view blend beats the nearest single view by 0.02-0.04 IoU on the
fern and the fir, and is level on the sparse shrub row. More views help more
than more texels: the error is dominated by the angle between views, as
`impostor_switch_distance` predicts (view error 0.14-0.42 world units against
a texel error of 0.005-0.02). The reconstruction above is the plain blend: it
samples all three views at the same card point, so geometry in front of or
behind the center plane ghosts.

### Depth-aware reconstruction

`ImpostorAtlas::reconstruct_texel` and `reconstruct_view` are the CPU reference
for the shader that draws an impostor, with the parallax offset of Brucks'
impostors applied in each of the three blended views before blending. Per
pixel and per view: project the ray's card point into the view, read the stored
depth there, slide the point along the ray to that depth, and repeat
`ImpostorReconstruct::parallax_steps` times (default 3; 0 is the plain blend,
also available as `ImpostorReconstruct::PLAIN`). The final point is sampled
bilinearly and the three taps are blended with `ImpostorGrid::blend` weights in
alpha-premultiplied form. A runtime mirrors these few lines per pixel; the
function documentation lists them with the formulas. Dilated texels carry depth,
so the first lookup may land up to `dilation` texels outside the silhouette; a
surface farther than that from the ray's card point is not found, and the
fixed-point iteration is not monotone (a step can overshoot).

```rust
use meshoptimizer_rs::{bake_impostor, ImpostorAlbedo, ImpostorGrid,
    ImpostorLayout, ImpostorOptions, ImpostorReconstruct, Positions, Workspace};
let p = [[-1.0, -1.0, 0.0], [1.0, -1.0, 0.0], [1.0, 1.0, 0.0], [-1.0, 1.0, 0.0]];
let mut options = ImpostorOptions::default();
options.grid = ImpostorGrid::new(ImpostorLayout::Sphere, 3)?;
options.view_resolution = 16;
let atlas = bake_impostor(&[0, 1, 2, 0, 2, 3], Positions::from_packed(&p), None,
    ImpostorAlbedo::White, options, &mut Workspace::default())?;
// Reconstruct a view into a caller buffer. Any direction works; this one
// coincides with a baked view, so the result is that view.
let direction = [0.0, 0.0, 1.0];
let mut view = vec![[0.0f32; 4]; 16 * 16];
atlas.reconstruct_view(direction, 16, ImpostorReconstruct::default(), &mut view)?;
assert_eq!(view[8 * 16 + 8], [1.0, 1.0, 1.0, 1.0]);
# Ok::<(), meshoptimizer_rs::Error>(())
```

On the same assets and 12 novel directions (128 px views), mask IoU and mean
RGB error against the direct render, plain blend before and three parallax
steps after:

| views | IoU fern / fir / shrub | RGB error fern / fir / shrub |
|---|---|---|
| 8 x 8 plain | 0.74 / 0.60 / 0.45 | 22.4 / 38.7 / 66.3 |
| 8 x 8 parallax | 0.83 / 0.73 / 0.67 | 16.2 / 28.9 / 44.0 |
| 12 x 12 plain | 0.84 / 0.72 / 0.55 | 15.8 / 29.6 / 57.3 |
| 12 x 12 parallax | 0.90 / 0.81 / 0.74 | 11.0 / 21.9 / 36.5 |

One step already gives most of the gain on the fern and the fir (0.82 and 0.70 at
8 x 8); the shrub row, whose depth is far from a shell, needs two (0.64, then
0.67). A 128 px view takes 2.3-3.3 ms on one core with three steps against
1.4-1.6 ms plain. A stored-depth test that drops a view when its surface at the
sample point disagrees with the ray point (tolerances 0.04 to 0.3 radii, with
and without parallax) did not raise IoU in any setting measured and lowered it
by 0.001 to 0.22, so the helper does not include it. The 12 directions are
spread over the hemisphere, so the numbers compare methods; they are not a
quality guarantee.


Existing names retain their exact u32 signatures. Add `_generic` to any
index-processing function or width-aware method name to select an index width.
These additions accept a sealed `Index` element type: `u16` or
`u32`. The width-aware input and result structs have a `Generic` suffix,
for example `MeshletsGeneric<u16>` and `LodQualityMeshGeneric`. Original
struct names remain non-generic structs with their original fields and traits, preserving standalone literal inference.
Conversions between legacy structs and their `Generic<u32>` counterparts move owned index buffers.
`parallel::EncodeInputGeneric` is the width-aware descriptor enum; the original
`EncodeInput` enum and its variant imports remain available. Remap tables, face identifiers, offsets and packed
local triangle words retain their documented metadata types.

```rust
use meshoptimizer_rs::{optimize_vertex_cache_generic, Error, Workspace};
let indices = [0u16, 1, 2];
let ordered: Vec<u16> = optimize_vertex_cache_generic(&indices, 3, &mut Workspace::default())?;
assert_eq!(ordered, indices);
# Ok::<(), Error>(())
```

For output-only operations, select the element type with a return annotation
or a turbofish, for example `simplify_points_generic::<u16>`. Annotate otherwise
unconstrained integer literals (`0u32` or `0u16`). The u32 adapter borrows
buffers directly and moves owned output without conversion. The u16 adapter
uses fallible temporary u32 storage charged to workspace limits. An output
index above 65,535 returns `Error::IndexOverflow`; it is never truncated.
Caller-buffer tails are preserved. A failed narrowing conversion leaves its
index destination unchanged; mutable vertex data follows each operation's
existing partial-mutation contract. Byte-oriented index decoders retain their
explicit element-width argument and check two-byte output for overflow.
## Character LODs

`simplify_character` and `build_character_lod_chain` are opt-in extensions
not in C++ meshoptimizer. Existing simplification entry points are unchanged.
Pass `CharacterInputs` with an optional `CharacterSkin`, borrowed blend-shape
delta arrays, and optional joint sample matrices. Four or eight vertex-major
influences are supported. Weights must be nonnegative and sum to one within
0.001; duplicate bone IDs are summed, including importance. Each importance
and global metric weight must be finite and nonnegative.

Before simplifying an imported character, merge its triangle primitives in a
common model space, transforming positions, normals and morph deltas
consistently. Convert joints and inverse bind matrices to the same space. Weld
exact coincident vertices with `generate_vertex_remap_multi`, then apply the
remap to indices and all vertex streams. Include normals, tangents, UVs,
colors, material boundaries, skin indices and weights, and every morph
attribute in the equality keys. A rigid morph part mixed with skinned parts
needs one full influence on its actual node transform, rather than zero skin
weights; preserve that node's real animation when evaluating poses. Position-
only welding can merge different deformations or shading seams. Unwelded
triangle soup can prevent reduction; attribute-preserving welding can still
leave genuine seams.

Start with unit bone importance. Where authored bone names identify the head,
hands or fingers, try a higher value (the evaluation uses four), and measure it
over the asset's real clips and full morph targets. Compare at the triangles
actually reached: increasing importance can trade bind-pose accuracy or reduction
for deformation detail, and does not guarantee a lower worst-pose deviation.
For rigs with opaque names, retain unit importance rather than guessing bone IDs.

The metric uses one channel per bone with value
`weight * bone_importance * skin_weight`, plus three channels per blend target
containing `(rest_position + delta) / rest_extent * blend_shape_weight`.
The rest geometry contributes the usual position quadrics. Constant-position
meshes use extent one. Bone identity is exact: integer IDs never become scalar
attributes. Character calls retain all `bone_count + 3 * blend_count` channels,
including rigs and morph sets above 32 channels, bounded by `Workspace` memory
and work limits. There is no truncation or hashing. Prepared attributes and wide
metric weights are charged to those limits. The general `Attributes` constructors
retain their C++-compatible 32-component bound; the wider packed view is private
to character preparation. Existing character calls at 32 channels or fewer retain
their previous arithmetic and resource accounting.

The existing attribute quadrics sum residual energies across the rest and
target positions. This penalizes changes in bone influence and in any full-
weight blend target. The returned simplifier error includes the attribute
terms; it is not a maximum geometric error across poses. A high importance
increases a bone channel's squared contribution. It is a soft preference, not a
vertex lock. Constant bone weights inside a rigid region have no influence
gradient, so this knob does not directly preserve all geometry attached to that
bone. Names alone do not establish that higher importance improves the measured
maximum.
`LodChainOptions::vertex_flags` can enforce locks in the chain API. The chain's
existing `attributes` option must be absent in the default mode; character channels occupy it.

```rust
use meshoptimizer_rs::*;
let positions = [[0.,0.,0.], [1.,0.,0.], [0.,1.,0.], [1.,1.,0.]];
let delta = [[0.,0.,0.], [0.,0.,0.], [0.,0.,1.], [0.,0.,1.]];
let shapes = [delta.as_slice()];
let mut character = CharacterInputs::new();
character.blend_shapes = &shapes;
let chain_options = LodChainOptions::new(
    LodTargets::Ratios(&[0.5]), LodErrors::Uniform(1.0));
let result = build_character_lod_chain(
    &[0,1,2,2,1,3], Positions::from_packed(&positions), &character,
    &CharacterOptions::default(), &chain_options,
    &LodQualityOptions::default(), &mut Workspace::default())?;
assert_eq!(result.quality.len(), 2); // bind, full blend target
# Ok::<(), Error>(())
```

`CharacterLodChain::quality` is pose-major then level-major. It contains the LOD quality
report against the original source for the bind pose, every blend target at
weight one, then each caller joint pose. Joint matrices are row-major affine
3-by-4 model-space skin transforms, already including inverse bind transforms.
Joint samples use linear blend skinning of rest positions. They affect quality
reports, not collapse costs. Morph and joint samples are separate: combined
poses, intermediate animation times, and simultaneous blend weights require
caller analysis. LOD quality maxima are deterministic sampled lower estimates, not
continuous Hausdorff bounds. Normals are not supplied by this API.

Set `CharacterOptions::best_of = true` to build both candidates per level and
select by lower worst sampled symmetric deviation, then fewer triangles, then
plain. `CharacterLodChain::selections` records `method`, `plain_max`, and
`character_max` per level (empty in default mode). The selected quality report
remains in `quality`. Successive levels start from the winner; independent mode
starts each level from the source. Optional chain attributes apply to the plain
candidate only; both candidates share flags, targets and caps. Default behavior
is unchanged. Both simplification and quality work count against whole-call limits.

`CharacterInputs::sample_poses` accepts additional pre-evaluated vertex positions,
including combined morph/animation poses; these follow joint poses in `quality`.
These samples affect selection and reports, but do not add metric channels.
The guarantee is against the plain candidate from the same level input under
these exact samples. It does not compare to a separately evolving plain chain
or bound unobserved poses. Independent-target corpus results and timing cost are
recorded in the character measurements.

Choose an error cap and validate the resulting levels in real poses; a ratio
alone is not an acceptance test. Aggressive targets with a loose error cap can
remove entire components. Default topology rules can also stall on hard normal
seams and complex wedges even after exact welding. An explicitly requested
`SimplifyOptions::PERMISSIVE` can change that tradeoff, but needs a separate
quality check; character simplification does not enable it implicitly.

Levels retain original vertex indices; apply the original skin and blend
streams when rendering them. Whole-call limits include prepared channels,
retained outputs, reports, pose buffers, and nested simplifier/quality work.
Failures return no partial result. See
[character measurements](https://github.com/Tavrin/meshoptimizer-rs/blob/v0.2.17/parity/0217-character/RESULTS.md) for the measured
tradeoffs and reproducible public-model comparison procedure.

## One-call asset pipeline

`process_mesh` is an extension, not in C++ meshoptimizer. Supply complete,
initialized little-endian vertex records; all bytes participate in welding,
including UV, normal and skin seams. Defaults sanitize and weld, generate 50%
and 25% LOD targets with 1% error, then optimize cache, overdraw (1.05) and fetch
for the source and each LOD. Sampled LOD quality compares each output to the
sanitized, welded, repaired source. It is a sampled estimate, not an error bound.
Repair, meshlets, cluster LOD (the existing `clusterlod` feature), and codecs are
opt-in fields on `ProcessOptions`. Cluster results include their own positions,
including any builder dilation. Skin fields select the character builder;
attribute weights and offsets select static simplification attributes. Skin
joints and weights must be part of each vertex record and survive fetch intact.

```rust
use meshoptimizer_rs::{process_mesh, ProcessOptions, Workspace};
let positions = [[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
let bytes: Vec<u8> = positions.iter().flatten().flat_map(|v| v.to_le_bytes()).collect();
let mut options = ProcessOptions::default();
options.lod = None; // Keep just the optimized source.
let mesh = process_mesh(&[0, 1, 2], &bytes, 12, 0, &options, &mut Workspace::default())?;
assert_eq!(mesh.levels.len(), 1);
assert_eq!(mesh.report.quality.len(), 1);
# Ok::<(), meshoptimizer_rs::ProcessError>(())
```

One shared workspace meters the whole call. Limits are restored on success and
failure. Byte accounting conservatively retains charges for released intermediate
buffers, so a manually streamed sequence can fit a smaller byte limit. Stage
reports contain counts, charged work and elapsed nanoseconds (`None` on
`no_std` and `wasm32-unknown-unknown`); only timing varies between identical calls. Errors identify the stage
and, for per-level processing, the level. Output is atomic. Empty surfaces have
`None` quality. Level zero is always the processed source.

### Incremental vertex and triangle decoding

`codec::VertexBufferDecoder` and `codec::IndexBufferDecoder` are Rust extensions
(not in C++ meshoptimizer). Fetch format metadata first, then stream only the
body. For vertices, supply the header byte and complete padded trailer to
`VertexBufferDecoder::new(count, stride, header, trailer, body_len, limits)`.
Trailer length is `max(stride, 32)` for v0 and
`max(stride + stride / 4, 24)` for v1. For triangles, pass the leading header
plus one code byte per triangle and the final sixteen-byte codebook to
`IndexBufferDecoder::new(index_count, prefix, trailer, body_len, limits)`.
The triangle codes remain borrowed; the caller must retain that separate array.

Call `push(input_chunk, output_chunk)`, advance by `Progress::consumed`, and
retain `Progress::written` output elements. Vertex output elements are bytes;
triangle elements are u32 indices (`push_generic` also supports truncating u16,
as the one-shot triangle codec does). Resubmit unconsumed input, including when
`NeedOutput` requests more destination space. Empty calls are allowed. After
all body bytes arrive, drain pending output with empty input and call `finish`.
Only a successful `finish` commits the provisional output. Extra body bytes,
incomplete input and undrained output fail validation; terminal errors stick.

Storage is bounded independently of stream length: vertex decoding uses at
most one 8 KiB decoded block and a 9216-byte compressed scratch buffer, plus
fixed predictors/trailer state. Triangle decoding uses fixed scratch/FIFOs,
plus the caller-owned code array (one byte per triangle, required by the
format's separate code and data streams). Both preflight work as encoded plus
decoded bytes (triangle construction budgets four bytes per index, including
when output is later narrowed to u16); fixed storage and caller buffers are excluded from `max_bytes`.
Vertex parsing needs up to 24 lookahead bytes and triangle parsing up to sixteen,
so output can lag the last semantic byte by that amount. An incomplete vertex
block is retried on the next chunk; very small chunks therefore cost more work
than bulk decoding. Fetching trailers requires a seekable source or container
that transports trailers separately. A forward-only transport must arrange
that split before using these APIs.
Streaming is a memory-bounded interface, not a faster one. On a 65,536-vertex
stride-32 buffer and a 390,150-index grid it executes 1.26x to 1.32x the
instructions of the one-shot decoders for vertices with 4 KiB chunks and 1.04x
with 64 KiB chunks, and 1.03x to 1.15x for triangles (instruction counts from
`parity/0217-qualify/streaming-costs.json`). Decode whole buffers when they fit
in memory.