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
//! Scalar cache and fetch analyzers from pinned `indexanalyzer.cpp`.
use crate::workspace::{checked_bytes, topology};
use crate::{Error, Workspace};

/// Result of upstream `meshopt_analyzeVertexCache`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct VertexCacheStatistics {
    /// Number of vertex shader transforms.
    pub vertices_transformed: u32,
    /// Number of nonempty simulated warps.
    pub warps_executed: u32,
    /// Transforms divided by triangle count.
    pub acmr: f32,
    /// Transforms divided by unique vertex count.
    pub atvr: f32,
}

/// Result of upstream `meshopt_analyzeVertexFetch`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct VertexFetchStatistics {
    /// Bytes read by the simulated cache.
    pub bytes_fetched: u32,
    /// Bytes fetched divided by referenced vertex bytes.
    pub overfetch: f32,
}

#[allow(clippy::too_many_arguments)]
fn cache_run<const WARP: bool, const GROUP: bool, const CHARGE: bool>(
    indices: &[u32],
    timestamps: &mut [u32],
    cache_size: u32,
    warp_size: u32,
    primgroup_size: u32,
    work: &mut crate::workspace::Work,
) -> Result<(VertexCacheStatistics, u32), Error> {
    let mut result = VertexCacheStatistics::default();
    let mut timestamp = cache_size.wrapping_add(1);
    let (mut warp_offset, mut primgroup_offset) = (0u32, 0u32);
    for triangle in indices.as_chunks::<3>().0 {
        if CHARGE {
            work.add(3)?;
        }
        let [a, b, c] = *triangle;
        let misses = if WARP {
            u32::from(timestamp.wrapping_sub(timestamps[a as usize]) > cache_size)
                + u32::from(timestamp.wrapping_sub(timestamps[b as usize]) > cache_size)
                + u32::from(timestamp.wrapping_sub(timestamps[c as usize]) > cache_size)
        } else {
            0
        };
        if (GROUP && primgroup_offset == primgroup_size)
            || (WARP && warp_offset + misses > warp_size)
        {
            result.warps_executed += u32::from(warp_offset > 0);
            warp_offset = 0;
            primgroup_offset = 0;
            timestamp = timestamp.wrapping_add(cache_size).wrapping_add(1);
        }
        for index in [a, b, c] {
            let entry = &mut timestamps[index as usize];
            if timestamp.wrapping_sub(*entry) > cache_size {
                *entry = timestamp;
                timestamp = timestamp.wrapping_add(1);
                // topology limits the index stream to u32::MAX entries;
                // one entry can trigger at most one transform here.
                result.vertices_transformed += 1;
                warp_offset += 1;
            }
        }
        if GROUP {
            primgroup_offset += 1;
        }
    }
    Ok((result, warp_offset))
}

#[inline(always)]
fn cache_simple(
    indices: &[u32],
    timestamps: &mut [u32],
    cache_size: u32,
) -> (VertexCacheStatistics, u32) {
    let mut result = VertexCacheStatistics::default();
    let mut timestamp = cache_size.wrapping_add(1);
    for &index in indices {
        let entry = &mut timestamps[index as usize];
        if timestamp.wrapping_sub(*entry) > cache_size {
            *entry = timestamp;
            timestamp = timestamp.wrapping_add(1);
            result.vertices_transformed += 1;
        }
    }
    let present = u32::from(result.vertices_transformed > 0);
    (result, present)
}

/// Analyze a triangle list using upstream's simplified FIFO transform cache.
///
/// # Errors
/// `InvalidTopology` for incomplete triangles or `IndexOutOfBounds` for invalid vertex references.
/// `InvalidParameter` for unsupported analyzer settings; `SizeOverflow` for size overflow, `LimitExceeded` for exhausted limits, or `AllocationFailed` for failed reservation.
#[inline(always)]
pub fn analyze_vertex_cache_generic<I: crate::Index>(
    indices: &[I],
    vertex_count: usize,
    cache_size: u32,
    warp_size: u32,
    primgroup_size: u32,
    workspace: &mut Workspace,
) -> Result<VertexCacheStatistics, Error> {
    I::with_input(indices, workspace, |indices, workspace| {
        analyze_vertex_cache_u32(
            indices,
            vertex_count,
            cache_size,
            warp_size,
            primgroup_size,
            workspace,
        )
    })
}

fn analyze_vertex_cache_u32(
    indices: &[u32],
    vertex_count: usize,
    cache_size: u32,
    warp_size: u32,
    primgroup_size: u32,
    workspace: &mut Workspace,
) -> Result<VertexCacheStatistics, Error> {
    let mut work = workspace.begin();
    let result = vertex_cache_impl(
        indices,
        vertex_count,
        cache_size,
        warp_size,
        primgroup_size,
        workspace,
        &mut work,
    );
    workspace.finish(&work);
    result
}

#[inline(always)]
#[allow(clippy::too_many_arguments)]
fn vertex_cache_impl(
    indices: &[u32],
    vertex_count: usize,
    cache_size: u32,
    warp_size: u32,
    primgroup_size: u32,
    workspace: &mut Workspace,
    work: &mut crate::workspace::Work,
) -> Result<VertexCacheStatistics, Error> {
    if cache_size < 3 || (warp_size != 0 && warp_size < 3) {
        return Err(Error::InvalidParameter);
    }
    topology(indices, vertex_count, work)?;
    checked_bytes(vertex_count, 4)?;
    let retained = workspace.integers.len().min(vertex_count);
    workspace.prepare_timestamps(vertex_count)?;
    let timestamps = &mut workspace.integers[..vertex_count];
    // prepare zero-initializes newly added entries; only retained values
    // can contain timestamps from a previous call.
    timestamps[..retained].fill(0);
    let bulk_work = work.covers(indices.len())?;
    if bulk_work {
        work.add(indices.len())?;
    }
    let (mut result, warp_offset) = match (warp_size != 0, primgroup_size != 0, bulk_work) {
        (false, false, false) => cache_run::<false, false, true>(
            indices,
            timestamps,
            cache_size,
            warp_size,
            primgroup_size,
            work,
        )?,
        (false, false, true) => cache_simple(indices, timestamps, cache_size),
        (false, true, false) => cache_run::<false, true, true>(
            indices,
            timestamps,
            cache_size,
            warp_size,
            primgroup_size,
            work,
        )?,
        (false, true, true) => cache_run::<false, true, false>(
            indices,
            timestamps,
            cache_size,
            warp_size,
            primgroup_size,
            work,
        )?,
        (true, false, false) => cache_run::<true, false, true>(
            indices,
            timestamps,
            cache_size,
            warp_size,
            primgroup_size,
            work,
        )?,
        (true, false, true) => cache_run::<true, false, false>(
            indices,
            timestamps,
            cache_size,
            warp_size,
            primgroup_size,
            work,
        )?,
        (true, true, false) => cache_run::<true, true, true>(
            indices,
            timestamps,
            cache_size,
            warp_size,
            primgroup_size,
            work,
        )?,
        (true, true, true) => cache_run::<true, true, false>(
            indices,
            timestamps,
            cache_size,
            warp_size,
            primgroup_size,
            work,
        )?,
    };
    let unique = timestamps.iter().filter(|&&value| value > 0).count();
    work.add(vertex_count)?;
    result.warps_executed += u32::from(warp_offset > 0);
    result.acmr = if indices.is_empty() {
        0.0
    } else {
        result.vertices_transformed as f32 / (indices.len() / 3) as f32
    };
    result.atvr = if unique == 0 {
        0.0
    } else {
        result.vertices_transformed as f32 / unique as f32
    };
    Ok(result)
}

// With <=64-byte vertices and the proven fuel/u32 bounds, an index
// touches one or two lines. Avoid a general range loop for that common case.
fn fetch_small(
    indices: &[u32],
    visited: &mut [u8],
    vertex_size: usize,
    cache: &mut [usize; 2048],
    work: &mut crate::workspace::Work,
) -> Result<u32, Error> {
    let mut bytes_fetched = 0;
    let mut extra_lines = 0;
    for &index in indices {
        visited[index as usize] = 1;
        let start = index as usize * vertex_size;
        let tag = start / 64;
        let first = &mut cache[tag % 2048];
        bytes_fetched += u32::from(*first != tag + 1) * 64;
        *first = tag + 1;
        if (start & 63) + vertex_size > 64 {
            let second = &mut cache[(tag + 1) % 2048];
            bytes_fetched += u32::from(*second != tag + 2) * 64;
            *second = tag + 2;
            extra_lines += 1;
        }
    }
    // The caller proved 6*len visits fit, so this <=3*len count cannot overflow.
    work.add(indices.len() * 2 + extra_lines)?;
    Ok(bytes_fetched)
}

fn fetch_run<const CHARGE: bool, const CHECK: bool>(
    indices: &[u32],
    visited: &mut [u8],
    vertex_size: usize,
    cache: &mut [usize; 2048],
    work: &mut crate::workspace::Work,
) -> Result<u32, Error> {
    let mut bytes_fetched = 0u32;
    let mut visits = if CHECK { 0 } else { indices.len() };
    for &index in indices {
        if CHARGE {
            work.add(1)?;
        }
        if CHECK {
            visits += 1;
        }
        visited[index as usize] = 1;
        let start = index as usize * vertex_size;
        let end = start + vertex_size;
        // The validated vertex byte extent is at most isize::MAX, so
        // adding 63 cannot overflow usize on either supported word size.
        let start_tag = start / 64;
        #[allow(clippy::manual_div_ceil)] // Proven non-overflowing add has cheaper codegen.
        let end_tag = (end + 63) / 64;
        if !CHECK {
            visits += end_tag - start_tag;
        }
        for tag in start_tag..end_tag {
            if CHARGE {
                work.add(1)?;
            }
            if CHECK {
                visits += 1;
            }
            let line = &mut cache[tag % 2048];
            if CHECK {
                if *line != tag + 1 {
                    bytes_fetched = match bytes_fetched.checked_add(64) {
                        Some(bytes) => bytes,
                        None => {
                            if !CHARGE {
                                work.add(visits)?;
                            }
                            return Err(Error::SizeOverflow);
                        }
                    };
                }
            } else {
                bytes_fetched += u32::from(*line != tag + 1) * 64;
            }
            *line = tag + 1;
        }
    }
    if !CHARGE {
        work.add(visits)?;
    }
    Ok(bytes_fetched)
}

/// Analyze index order with upstream's direct-mapped 128 KiB fetch-cache model.
///
/// # Errors
/// `IndexOutOfBounds` for invalid vertex references;
/// `InvalidParameter` for unsupported analyzer settings; `SizeOverflow` for size overflow, `LimitExceeded` for exhausted limits, or `AllocationFailed` for failed reservation.
#[inline]
pub fn analyze_vertex_fetch_generic<I: crate::Index>(
    indices: &[I],
    vertex_count: usize,
    vertex_size: usize,
    workspace: &mut Workspace,
) -> Result<VertexFetchStatistics, Error> {
    I::with_input(indices, workspace, |indices, workspace| {
        analyze_vertex_fetch_u32(indices, vertex_count, vertex_size, workspace)
    })
}

fn analyze_vertex_fetch_u32(
    indices: &[u32],
    vertex_count: usize,
    vertex_size: usize,
    workspace: &mut Workspace,
) -> Result<VertexFetchStatistics, Error> {
    let mut work = workspace.begin();
    let result = (|| {
        if !(1..=256).contains(&vertex_size) {
            return Err(Error::InvalidParameter);
        }
        if vertex_count > u32::MAX as usize {
            return Err(Error::SizeOverflow);
        }
        checked_bytes(vertex_count, vertex_size)?;
        work.indices(indices, vertex_count)?;
        let retained = workspace.flags.len().min(vertex_count);
        workspace.prepare([0, 0, vertex_count, 0], 0)?;
        let visited = &mut workspace.flags[..vertex_count];
        visited[..retained].fill(0);
        let mut cache = [0usize; 2048];
        let mut result = VertexFetchStatistics::default();
        // An index visits at most five cache lines. With sufficient fuel,
        // count the visits locally and charge once; the fallback keeps the
        // exact exhaustion point and partial usage for low limits.
        let bulk_work = match indices.len().checked_mul(6) {
            Some(max_visits) => work.covers(max_visits)?,
            None => false,
        };
        // A vertex spans at most five 64-byte lines. This upper bound proves
        // u32 accumulation safe without weakening the overflow error contract.
        let bounded_bytes = indices.len() <= u32::MAX as usize / (5 * 64);
        result.bytes_fetched = if bulk_work && bounded_bytes && vertex_size <= 64 {
            fetch_small(indices, visited, vertex_size, &mut cache, &mut work)?
        } else {
            match (bulk_work, bounded_bytes) {
                (true, true) => {
                    fetch_run::<false, false>(indices, visited, vertex_size, &mut cache, &mut work)?
                }
                (true, false) => {
                    fetch_run::<false, true>(indices, visited, vertex_size, &mut cache, &mut work)?
                }
                (false, true) => {
                    fetch_run::<true, false>(indices, visited, vertex_size, &mut cache, &mut work)?
                }
                (false, false) => {
                    fetch_run::<true, true>(indices, visited, vertex_size, &mut cache, &mut work)?
                }
            }
        };
        // Every visited flag was initialized to zero and is written only as one.
        let unique: usize = visited.iter().map(|&value| usize::from(value)).sum();
        work.add(vertex_count)?;
        result.overfetch = if unique == 0 {
            0.0
        } else {
            result.bytes_fetched as f32 / (unique * vertex_size) as f32
        };
        Ok(result)
    })();
    workspace.finish(&work);
    result
}

/// The source-compatible u32 entry point; see [`analyze_vertex_cache_generic`] for selectable index widths.
#[inline]
pub fn analyze_vertex_cache(
    indices: &[u32],
    vertex_count: usize,
    cache_size: u32,
    warp_size: u32,
    primgroup_size: u32,
    workspace: &mut Workspace,
) -> Result<VertexCacheStatistics, Error> {
    analyze_vertex_cache_generic::<u32>(
        indices,
        vertex_count,
        cache_size,
        warp_size,
        primgroup_size,
        workspace,
    )
}

/// The source-compatible u32 entry point; see [`analyze_vertex_fetch_generic`] for selectable index widths.
#[inline]
pub fn analyze_vertex_fetch(
    indices: &[u32],
    vertex_count: usize,
    vertex_size: usize,
    workspace: &mut Workspace,
) -> Result<VertexFetchStatistics, Error> {
    analyze_vertex_fetch_generic::<u32>(indices, vertex_count, vertex_size, workspace)
}