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
// Adapted from Moss dc4af42a; MIT, Moss contributors and Arseny Kapoulkine.
use super::byte_at;
use crate::Error;
const INDEX_HEADER: u8 = 0xe0;
const SEQUENCE_HEADER: u8 = 0xd0;
#[inline]
fn decode_vbyte(data: &[u8], position: &mut usize) -> Result<u32, Error> {
    // The four-byte sequence tail and sixteen-byte triangle tail make a
    // five-byte checked lookahead equivalent to the reference's cursor guard.
    let bytes: &[u8; 5] = data
        .get(*position..*position + 5)
        .ok_or(Error::InvalidStream)?
        .try_into()
        .map_err(|_| Error::InvalidStream)?;
    *position += 1;
    let lead = bytes[0];
    if lead < 128 {
        return Ok(u32::from(lead));
    }
    let mut result = u32::from(lead & 127);
    for (i, &group) in bytes[1..].iter().enumerate() {
        *position += 1;
        result |= u32::from(group & 127) << ((i + 1) * 7);
        if group < 128 {
            break;
        }
    }
    Ok(result)
}

fn decode_index(data: &[u8], position: &mut usize, last: u32) -> Result<u32, Error> {
    let value = decode_vbyte(data, position)?;
    let delta = (value >> 1) ^ 0u32.wrapping_sub(value & 1);
    Ok(last.wrapping_add(delta))
}

const CODE_AUX_TABLE_SIZE: usize = 16;

fn triangles_width<const STRIDE: usize, const TRI_BYTES: usize>(
    output: &mut [u8],
    count: usize,
    data: &[u8],
) -> Result<(), Error> {
    if !count.is_multiple_of(3) {
        return Err(Error::InvalidTopology);
    }
    if data.len() < 1 + count / 3 + CODE_AUX_TABLE_SIZE {
        return Err(Error::InvalidStream);
    }
    if data[0] & 0xf0 != INDEX_HEADER {
        return Err(Error::InvalidStream);
    }
    let version = data[0] & 0x0f;
    if version > 1 {
        return Err(Error::UnsupportedVersion);
    }
    let mut edge_fifo = [[u32::MAX; 2]; 16];
    let mut vertex_fifo = [u32::MAX; 16];
    let mut edge_offset = 0usize;
    let mut vertex_offset = 0usize;
    let push_edge = |fifo: &mut [[u32; 2]; 16], offset: &mut usize, a: u32, b: u32| {
        fifo[*offset] = [a, b];
        *offset = (*offset + 1) & 15;
    };
    let push_vertex = |fifo: &mut [u32; 16], offset: &mut usize, v: u32, advance: bool| {
        fifo[*offset] = v;
        *offset = (*offset + usize::from(advance)) & 15;
    };
    let mut next = 0u32;
    let mut last = 0u32;
    let fec_max = if version >= 1 { 13 } else { 15 };
    let mut position = 1 + count / 3;
    let safe_end = data.len() - CODE_AUX_TABLE_SIZE;
    let code_aux_table = &data[safe_end..];
    // Public entry points supply exactly count * STRIDE bytes. Checked
    // code and output records make all three stores bounded by one array.
    // `TriangleState::run` is the same loop for the incremental decoder; this
    // copy stays separate so the one-shot path keeps its exact code generation.
    let codes = &data[1..position];
    for (&code_tri, triangle) in codes.iter().zip(output.as_chunks_mut::<TRI_BYTES>().0) {
        if position > safe_end {
            return Err(Error::InvalidStream);
        }
        let (a, b, c);
        if code_tri < 0xf0 {
            let fe = usize::from(code_tri >> 4);
            let edge = edge_fifo[(edge_offset.wrapping_sub(1 + fe)) & 15];
            a = edge[0];
            b = edge[1];
            let fec = usize::from(code_tri & 15);
            if fec < fec_max {
                let cached = vertex_fifo[(vertex_offset.wrapping_sub(1 + fec)) & 15];
                c = if fec == 0 { next } else { cached };
                if fec == 0 {
                    next = next.wrapping_add(1);
                }
                push_vertex(&mut vertex_fifo, &mut vertex_offset, c, fec == 0);
            } else {
                c = if fec != 15 {
                    // 13 and 14 encode -1 and +1 relative to the last free index.
                    let delta = fec as i32 - (fec ^ 3) as i32;
                    last.wrapping_add_signed(delta)
                } else {
                    decode_index(data, &mut position, last)?
                };
                last = c;
                push_vertex(&mut vertex_fifo, &mut vertex_offset, c, true);
            }
            push_edge(&mut edge_fifo, &mut edge_offset, c, b);
            push_edge(&mut edge_fifo, &mut edge_offset, a, c);
        } else if code_tri < 0xfe {
            let code_aux = code_aux_table[usize::from(code_tri & 15)];
            let feb = usize::from(code_aux >> 4);
            let fec = usize::from(code_aux & 15);
            a = next;
            next = next.wrapping_add(1);
            let cached_b = vertex_fifo[(vertex_offset.wrapping_sub(feb)) & 15];
            b = if feb == 0 { next } else { cached_b };
            if feb == 0 {
                next = next.wrapping_add(1);
            }
            let cached_c = vertex_fifo[(vertex_offset.wrapping_sub(fec)) & 15];
            c = if fec == 0 { next } else { cached_c };
            if fec == 0 {
                next = next.wrapping_add(1);
            }
            push_vertex(&mut vertex_fifo, &mut vertex_offset, a, true);
            push_vertex(&mut vertex_fifo, &mut vertex_offset, b, feb == 0);
            push_vertex(&mut vertex_fifo, &mut vertex_offset, c, fec == 0);
            push_edge(&mut edge_fifo, &mut edge_offset, b, a);
            push_edge(&mut edge_fifo, &mut edge_offset, c, b);
            push_edge(&mut edge_fifo, &mut edge_offset, a, c);
        } else {
            let code_aux = byte_at(data, position)?;
            position += 1;
            let fea = if code_tri == 0xfe { 0 } else { 15 };
            let feb = usize::from(code_aux >> 4);
            let fec = usize::from(code_aux & 15);
            if code_aux == 0 {
                next = 0;
            }
            let mut take_next = || {
                let value = next;
                next = next.wrapping_add(1);
                value
            };
            let mut first = if fea == 0 { take_next() } else { 0 };
            let mut second = if feb == 0 {
                take_next()
            } else {
                vertex_fifo[(vertex_offset.wrapping_sub(feb)) & 15]
            };
            let mut third = if fec == 0 {
                take_next()
            } else {
                vertex_fifo[(vertex_offset.wrapping_sub(fec)) & 15]
            };
            if fea == 15 {
                first = decode_index(data, &mut position, last)?;
                last = first;
            }
            if feb == 15 {
                second = decode_index(data, &mut position, last)?;
                last = second;
            }
            if fec == 15 {
                third = decode_index(data, &mut position, last)?;
                last = third;
            }
            a = first;
            b = second;
            c = third;
            push_vertex(&mut vertex_fifo, &mut vertex_offset, a, true);
            push_vertex(
                &mut vertex_fifo,
                &mut vertex_offset,
                b,
                feb == 0 || feb == 15,
            );
            push_vertex(
                &mut vertex_fifo,
                &mut vertex_offset,
                c,
                fec == 0 || fec == 15,
            );
            push_edge(&mut edge_fifo, &mut edge_offset, b, a);
            push_edge(&mut edge_fifo, &mut edge_offset, c, b);
            push_edge(&mut edge_fifo, &mut edge_offset, a, c);
        }
        triangle[..STRIDE].copy_from_slice(&a.to_le_bytes()[..STRIDE]);
        triangle[STRIDE..STRIDE * 2].copy_from_slice(&b.to_le_bytes()[..STRIDE]);
        triangle[STRIDE * 2..].copy_from_slice(&c.to_le_bytes()[..STRIDE]);
    }
    if position != safe_end {
        return Err(Error::InvalidStream);
    }
    Ok(())
}

// Sequence lookahead uses remaining length, avoiding numeric cursor
// addition/overflow checks. The four padding bytes remain visible, matching
// the original five-byte varint semantics even for overlong encodings.
#[inline]
fn decode_sequence_vbyte(cursor: &mut &[u8]) -> Result<u32, Error> {
    let bytes = cursor.first_chunk::<5>().ok_or(Error::InvalidStream)?;
    let lead = bytes[0];
    if lead < 128 {
        *cursor = &cursor[1..];
        return Ok(u32::from(lead));
    }
    let mut result = u32::from(lead & 127);
    let mut used = 1;
    for (i, &group) in bytes[1..].iter().enumerate() {
        used += 1;
        result |= u32::from(group & 127) << ((i + 1) * 7);
        if group < 128 {
            break;
        }
    }
    *cursor = &cursor[used..];
    Ok(result)
}

fn sequence_width<const STRIDE: usize>(
    output: &mut [u8],
    count: usize,
    data: &[u8],
) -> Result<(), Error> {
    let mut cursor = sequence_start(count, data)?;
    let mut last = [0u32; 2];
    for output in output.as_chunks_mut::<STRIDE>().0 {
        let index = sequence_one(&mut cursor, &mut last)?;
        output.copy_from_slice(&index.to_le_bytes()[..STRIDE]);
    }
    if cursor.len() != 4 {
        return Err(Error::InvalidStream);
    }
    Ok(())
}

#[inline]
fn sequence_start(count: usize, data: &[u8]) -> Result<&[u8], Error> {
    if data.len() < 1 + count + 4 || data[0] & 0xf0 != SEQUENCE_HEADER {
        return Err(Error::InvalidStream);
    }
    if data[0] & 0x0f > 1 {
        return Err(Error::UnsupportedVersion);
    }
    Ok(&data[1..])
}
#[inline]
fn sequence_one(cursor: &mut &[u8], last: &mut [u32; 2]) -> Result<u32, Error> {
    let value = decode_sequence_vbyte(cursor)?;
    let baseline = (value & 1) as usize;
    let value = value >> 1;
    let delta = (value >> 1) ^ 0u32.wrapping_sub(value & 1);
    let index = last[baseline].wrapping_add(delta);
    last[baseline] = index;
    Ok(index)
}

// Capacity has already been reserved and accounted. Decode small initialized
// stack blocks and append them without a second full-output zero-fill pass.
// Appending a block amortizes Vec's capacity check; errors still stop at once.
fn sequence_append_width<const STRIDE: usize>(
    output: &mut alloc::vec::Vec<u8>,
    count: usize,
    data: &[u8],
) -> Result<(), Error> {
    let mut cursor = sequence_start(count, data)?;
    let mut last = [0u32; 2];
    let mut block = [0u8; 256];
    for first in (0..count).step_by(64) {
        let size = (count - first).min(64) * STRIDE;
        for record in block[..size].as_chunks_mut::<STRIDE>().0 {
            let index = sequence_one(&mut cursor, &mut last)?;
            record.copy_from_slice(&index.to_le_bytes()[..STRIDE]);
        }
        output.extend_from_slice(&block[..size]);
    }
    if cursor.len() != 4 {
        return Err(Error::InvalidStream);
    }
    Ok(())
}
pub(super) fn sequence_append(
    output: &mut alloc::vec::Vec<u8>,
    count: usize,
    stride: usize,
    data: &[u8],
) -> Result<(), Error> {
    if stride == 2 {
        sequence_append_width::<2>(output, count, data)
    } else {
        sequence_append_width::<4>(output, count, data)
    }
}

pub(super) fn triangles(
    output: &mut [u8],
    count: usize,
    stride: usize,
    data: &[u8],
) -> Result<(), Error> {
    if stride == 2 {
        triangles_width::<2, 6>(output, count, data)
    } else {
        triangles_width::<4, 12>(output, count, data)
    }
}
pub(super) fn sequence(
    output: &mut [u8],
    count: usize,
    stride: usize,
    data: &[u8],
) -> Result<(), Error> {
    if stride == 2 {
        sequence_width::<2>(output, count, data)
    } else {
        sequence_width::<4>(output, count, data)
    }
}

#[derive(Clone, Default)]
pub(super) struct TriangleState {
    edge_fifo: [[u32; 2]; 16],
    vertex_fifo: [u32; 16],
    edge_offset: usize,
    vertex_offset: usize,
    next: u32,
    last: u32,
}
impl TriangleState {
    pub(super) fn new() -> Self {
        Self {
            edge_fifo: [[u32::MAX; 2]; 16],
            vertex_fifo: [u32::MAX; 16],
            ..Self::default()
        }
    }
    /// Decode one triangle per entry of `codes`, stopping early when `outs` is
    /// exhausted. `write` stores each triangle in its output slot, `cursor` is
    /// the position in `data`, and `safe_end` bounds the body (the aux table
    /// follows it). Returns the triangles completed and the status. Every
    /// fallible step precedes the first state change of its triangle, so a
    /// failure leaves the state, cursor and outputs at the last complete
    /// triangle and a caller with more input can resume with the rest.
    #[allow(clippy::too_many_arguments)]
    #[inline(always)]
    pub(super) fn run<O>(
        &mut self,
        codes: &[u8],
        outs: &mut [O],
        data: &[u8],
        cursor: &mut usize,
        safe_end: usize,
        code_aux_table: &[u8],
        version: u8,
        mut write: impl FnMut(&mut O, [u32; 3]),
    ) -> (usize, Result<(), Error>) {
        let (mut edge_offset, mut vertex_offset, mut next, mut last) =
            (self.edge_offset, self.vertex_offset, self.next, self.last);
        let (edge_fifo, vertex_fifo) = (&mut self.edge_fifo, &mut self.vertex_fifo);
        let push_edge = |fifo: &mut [[u32; 2]; 16], offset: &mut usize, a, b| {
            fifo[*offset] = [a, b];
            *offset = (*offset + 1) & 15;
        };
        let push_vertex = |fifo: &mut [u32; 16], offset: &mut usize, v, advance: bool| {
            fifo[*offset] = v;
            *offset = (*offset + usize::from(advance)) & 15;
        };
        let fec_max = if version >= 1 { 13 } else { 15 };
        let mut position = *cursor;
        let mut done = 0;
        let status = 'run: {
            for (&code_tri, out) in codes.iter().zip(outs.iter_mut()) {
                if position > safe_end {
                    break 'run Err(Error::InvalidStream);
                }
                let (a, b, c);
                if code_tri < 0xf0 {
                    let fe = usize::from(code_tri >> 4);
                    let edge = edge_fifo[(edge_offset.wrapping_sub(1 + fe)) & 15];
                    a = edge[0];
                    b = edge[1];
                    let fec = usize::from(code_tri & 15);
                    if fec < fec_max {
                        let cached = vertex_fifo[(vertex_offset.wrapping_sub(1 + fec)) & 15];
                        c = if fec == 0 { next } else { cached };
                        if fec == 0 {
                            next = next.wrapping_add(1);
                        }
                        push_vertex(&mut *vertex_fifo, &mut vertex_offset, c, fec == 0);
                    } else {
                        c = if fec != 15 {
                            // 13 and 14 encode -1 and +1 relative to the last free index.
                            let delta = fec as i32 - (fec ^ 3) as i32;
                            last.wrapping_add_signed(delta)
                        } else {
                            match decode_index(data, &mut position, last) {
                                Ok(value) => value,
                                Err(e) => break 'run Err(e),
                            }
                        };
                        last = c;
                        push_vertex(&mut *vertex_fifo, &mut vertex_offset, c, true);
                    }
                    push_edge(&mut *edge_fifo, &mut edge_offset, c, b);
                    push_edge(&mut *edge_fifo, &mut edge_offset, a, c);
                } else if code_tri < 0xfe {
                    let code_aux = code_aux_table[usize::from(code_tri & 15)];
                    let feb = usize::from(code_aux >> 4);
                    let fec = usize::from(code_aux & 15);
                    a = next;
                    next = next.wrapping_add(1);
                    let cached_b = vertex_fifo[(vertex_offset.wrapping_sub(feb)) & 15];
                    b = if feb == 0 { next } else { cached_b };
                    if feb == 0 {
                        next = next.wrapping_add(1);
                    }
                    let cached_c = vertex_fifo[(vertex_offset.wrapping_sub(fec)) & 15];
                    c = if fec == 0 { next } else { cached_c };
                    if fec == 0 {
                        next = next.wrapping_add(1);
                    }
                    push_vertex(&mut *vertex_fifo, &mut vertex_offset, a, true);
                    push_vertex(&mut *vertex_fifo, &mut vertex_offset, b, feb == 0);
                    push_vertex(&mut *vertex_fifo, &mut vertex_offset, c, fec == 0);
                    push_edge(&mut *edge_fifo, &mut edge_offset, b, a);
                    push_edge(&mut *edge_fifo, &mut edge_offset, c, b);
                    push_edge(&mut *edge_fifo, &mut edge_offset, a, c);
                } else {
                    let code_aux = match byte_at(data, position) {
                        Ok(value) => value,
                        Err(e) => break 'run Err(e),
                    };
                    let fea = if code_tri == 0xfe { 0 } else { 15 };
                    let feb = usize::from(code_aux >> 4);
                    let fec = usize::from(code_aux & 15);
                    // Cursor, free-index and last-index work on copies until all
                    // three corners decoded, so a failure leaves this triangle unstarted.
                    let (mut cursor_here, mut next_here, mut last_here) =
                        (position + 1, if code_aux == 0 { 0 } else { next }, last);
                    let mut take_next = || {
                        let value = next_here;
                        next_here = next_here.wrapping_add(1);
                        value
                    };
                    let mut first = if fea == 0 { take_next() } else { 0 };
                    let mut second = if feb == 0 {
                        take_next()
                    } else {
                        vertex_fifo[(vertex_offset.wrapping_sub(feb)) & 15]
                    };
                    let mut third = if fec == 0 {
                        take_next()
                    } else {
                        vertex_fifo[(vertex_offset.wrapping_sub(fec)) & 15]
                    };
                    if fea == 15 {
                        first = match decode_index(data, &mut cursor_here, last_here) {
                            Ok(value) => value,
                            Err(e) => break 'run Err(e),
                        };
                        last_here = first;
                    }
                    if feb == 15 {
                        second = match decode_index(data, &mut cursor_here, last_here) {
                            Ok(value) => value,
                            Err(e) => break 'run Err(e),
                        };
                        last_here = second;
                    }
                    if fec == 15 {
                        third = match decode_index(data, &mut cursor_here, last_here) {
                            Ok(value) => value,
                            Err(e) => break 'run Err(e),
                        };
                        last_here = third;
                    }
                    (position, next, last) = (cursor_here, next_here, last_here);
                    a = first;
                    b = second;
                    c = third;
                    push_vertex(&mut *vertex_fifo, &mut vertex_offset, a, true);
                    push_vertex(
                        &mut *vertex_fifo,
                        &mut vertex_offset,
                        b,
                        feb == 0 || feb == 15,
                    );
                    push_vertex(
                        &mut *vertex_fifo,
                        &mut vertex_offset,
                        c,
                        fec == 0 || fec == 15,
                    );
                    push_edge(&mut *edge_fifo, &mut edge_offset, b, a);
                    push_edge(&mut *edge_fifo, &mut edge_offset, c, b);
                    push_edge(&mut *edge_fifo, &mut edge_offset, a, c);
                }
                write(out, [a, b, c]);
                done += 1;
            }
            Ok(())
        };
        *cursor = position;
        self.edge_offset = edge_offset;
        self.vertex_offset = vertex_offset;
        self.next = next;
        self.last = last;
        (done, status)
    }
}