Skip to main content

Crate meshoptimizer_rs

Crate meshoptimizer_rs 

Source
Expand description

A Rust port of meshoptimizer 1.3.

Every ported function produces byte-identical output to meshoptimizer 1.3 (scalar build). Differential runs against the C++ library, seeded sweeps, fuzzing and a wasm32 identity check prove this on the recorded inputs.

The crate is safe Rust except for one module, codec::simd, which holds the SIMD kernels for vertex decoding, EXT filters and meshlet decoding. Every unsafe block there has a written safety argument, and every SIMD path must produce the same bytes as the scalar safe-Rust path, which is the reference and the fallback. Build with default-features = false (adding std if needed) to compile no unsafe code; output is identical. Cargo feature unification applies: if any other crate in the dependency graph enables simd, the module is compiled for the whole graph. Simplification, optimization, index decoding and all encoders contain no unsafe in either configuration. See the safety audit.

The crate needs no C++ toolchain. It supports no_std with alloc. Invalid input returns a typed Error instead of undefined behaviour. A reusable Workspace holds scratch memory, makes every allocation fallible and enforces per-call memory and work Limits.

This is an independent project. It is not affiliated with meshoptimizer or its author. Coverage, measured performance and the parity records are in the README.

Coverage includes vertex processing, simplification, meshlets, codecs, analyzers, opacity maps, tangents, normals, remeshing, parallel batches and SIMD decoding. Cluster-LOD requires clusterlod; batches require parallel and std. Normal generation and remeshing require experimental.

§Recipes

§Simplify a mesh

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

let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0]];
let indices = [0, 1, 2, 2, 1, 3];
let mut workspace = Workspace::default();

let settings = SimplifySettings {
    target_index_count: 3,
    target_error: 0.01,
    options: SimplifyOptions::EMPTY,
};
let lod = simplify(&indices, Positions::from_packed(&positions), settings, &mut workspace)?;
println!("{} indices, relative error {}", lod.indices.len(), lod.error);

§Optimize for the vertex cache, then for overdraw

use meshoptimizer_rs::{optimize_overdraw, optimize_vertex_cache, Positions, Workspace};

let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0]];
let indices = [0, 1, 2, 2, 1, 3];
let mut workspace = Workspace::default();

let cached = optimize_vertex_cache(&indices, positions.len(), &mut workspace)?;
let ordered = optimize_overdraw(&cached, Positions::from_packed(&positions), 1.05, &mut workspace)?;
assert_eq!(ordered.len(), indices.len());

§Build meshlets

use meshoptimizer_rs::{build_meshlets, MeshletSettings, Positions, Workspace};

let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0]];
let indices = [0, 1, 2, 2, 1, 3];
let mut workspace = Workspace::default();

// 64 vertices and 124 triangles per meshlet; cone weight 0.25.
let built = build_meshlets(
    &indices,
    Positions::from_packed(&positions),
    MeshletSettings::default(),
    0.25,
    &mut workspace,
)?;
for meshlet in &built.meshlets {
    let start = meshlet.vertex_offset as usize;
    let vertices = &built.vertices[start..start + meshlet.vertex_count as usize];
    println!("{} triangles over vertices {:?}", meshlet.triangle_count, vertices);
}

§Compress vertex and index buffers

The codec module reads and writes the EXT_meshopt_compression formats. Buffers are little-endian bytes. The format version and level are set per call instead of through global setters.

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]; 4] = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0]];
let indices = [0, 1, 2, 2, 1, 3];
let mut workspace = Workspace::default();

let vertex_bytes: Vec<u8> = positions.iter().flatten().flat_map(|v| v.to_le_bytes()).collect();
let packed = encode_vertex_buffer(&vertex_bytes, 4, 12, VertexEncoding::DEFAULT, &mut workspace)?;
assert_eq!(decode_vertex_buffer(4, 12, &packed, &mut workspace)?, vertex_bytes);

let packed = encode_index_buffer(&indices, IndexEncoding::DEFAULT, &mut workspace)?;
let decoded = decode_index_buffer(indices.len(), 4, &packed, &mut workspace)?; // u32 bytes
assert_eq!(decoded.len(), indices.len() * 4);

§Features

  • std (default): implements std::error::Error for Error. Disable default features for no_std; an allocator is still required.
  • clusterlod: the cluster-LOD builder from upstream’s demo/clusterlod.h. It reproduces the pinned demo exactly; it is not a stable upstream API.
  • experimental: upstream functions and options marked experimental.
  • parallel: ordered Rayon batch APIs for independent meshes and buffer views; enables std. See the parallel module for limits and error semantics.

Modules§

clusterlod
Pure-Rust port of the pinned upstream demo/clusterlod.h (MIT, Arseny Kapoulkine).
codec
meshoptimizer 1.3 codecs, with explicit little-endian byte buffers.
guide
Task recipes with complete, checked examples.
parallel
Ordered batches of independent sequential operations, using Rayon.

Structs§

Attributes
Checked borrowed attribute view with at most 32 components per vertex.
AttributesMut
Checked mutable attribute components for destructive update simplification.
Bounds
Meaningful fields of meshopt_Bounds, without native padding.
BoundsPositions
A borrowed positions view whose bounds-validation scan is cached once.
CoverageStatistics
Result of meshopt_analyzeCoverage.
FetchIndices
Borrowed fetch-remap input with its index-validation result cached once.
FetchedMesh
Fetch-ordered initialized vertex bytes and rewritten indices.
Limits
Per-call limits for crate-owned heap storage and counted work.
LocalMeshlet
Meshlet-local topology with first-visit vertex references.
Meshlet
Current 1.3 descriptor: triangle offsets are consecutive byte offsets, without padding.
MeshletSettings
Limits used by all meshlet builders.
MeshletSizes
Used prefixes after caller-buffer meshlet construction.
Meshlets
Complete tightly packed meshlet output.
OpacityMapMeasure
Output of upstream meshopt_opacityMapMeasure.
OverdrawStatistics
Result of meshopt_analyzeOverdraw.
Partitions
Cluster-to-partition assignments in upstream order.
Positions
Checked borrowed XYZ view, preserving all supplied vertices, including unused ones.
PositionsMut
Checked mutable positions for destructive update simplification.
ProvokingMesh
Unique first-corner indices and source vertices for provoking-vertex rendering.
SimplifiedMesh
Simplified topology referencing the original vertex array.
SimplifyOptions
Stable simplification options supported by this port.
SimplifyResult
Caller-buffer simplification result.
SimplifySettings
Parameters for edge-collapse simplification.
Usage
Resource measurements for the most recent algorithm call.
VertexCacheStatistics
Result of upstream meshopt_analyzeVertexCache.
VertexFetchStatistics
Result of upstream meshopt_analyzeVertexFetch.
VertexFlags
Independent upstream simplification vertex flags; unknown bits are rejected.
VertexRemap
A compact vertex numbering; unused vertices retain u32::MAX.
VertexStream
Initialized byte records used as binary equality keys. Supplied padding is part of equality; no typed object is reinterpreted as bytes.
Workspace
Reusable fallibly allocated scratch storage and per-call resource limits.

Enums§

ByteOrder
Explicit byte order of floating-point components in byte-backed views.
Error
Checked input, resource, allocation, or numerical failure.
Retention
Policy for retaining reusable algorithm scratch between calls.

Constants§

REMESH_SHELL
Produce a two-sided surface shell.
REMESH_SOLVE
Solve the output positions using accumulated quadrics.
TANGENT_COMPATIBLE
Preserve MikkTSpace weighting instead of upstream’s area-weighted default.
TANGENT_ZERO_FALLBACK
Emit zero tangents for isolated degenerate faces.

Functions§

analyze_coverage
Analyze projected coverage on three axes with the upstream rasterizer.
analyze_overdraw
Analyze raster overdraw with upstream’s 256-pixel viewport model.
analyze_vertex_cache
Analyze a triangle list using upstream’s simplified FIFO transform cache.
analyze_vertex_fetch
Analyze index order with upstream’s direct-mapped 128 KiB fetch-cache model.
build_meshlets
meshopt_buildMeshlets: connectivity and cone-aware meshlets.
build_meshlets_bound
meshopt_buildMeshletsBound: conservative descriptor capacity, with checked arithmetic.
build_meshlets_flex
meshopt_buildMeshletsFlex: variable triangle counts and optional spatial splits.
build_meshlets_flex_into
Caller-buffer flexible builder; a late failure may modify output prefixes.
build_meshlets_into
Caller-buffer standard builder; a late failure may modify output prefixes.
build_meshlets_scan
meshopt_buildMeshletsScan: consume triangles in input order.
build_meshlets_scan_into
Caller-buffer scan builder; a late work-limit failure may modify output prefixes.
build_meshlets_spatial
meshopt_buildMeshletsSpatial: surface-area heuristic meshlets for ray tracing.
build_meshlets_spatial_into
Caller-buffer spatial builder; a late failure may modify output prefixes.
compute_cluster_bounds
meshopt_computeClusterBounds: sphere and conservative normal cone.
compute_cluster_bounds_with_positions
Compute cluster bounds using a cached positions-validation scan.
compute_meshlet_bounds
meshopt_computeMeshletBounds: bounds of byte-local triangles.
compute_meshlet_bounds_with_positions
Compute meshlet bounds using a cached positions-validation scan.
compute_position_exponent
Compute the exponent of a conservative signed position grid. Bounds must be finite and ordered; min_exp is at least -126 and max_bits is 2 through 24. Overflowing scaled bounds return an error.
compute_sphere_bounds
meshopt_computeSphereBounds. Optional radii use a checked one-component view.
dequantize_half
Expand a half value; flush half subnormals, preserve signed zero and NaN payloads.
extract_meshlet_indices
meshopt_extractMeshletIndices: preserve first-visit vertex order.
extract_meshlet_indices_into
Caller-buffer extraction. Errors leave both destinations unchanged; tails are preserved.
filter_index_buffer
Remove binary-degenerate and duplicate triangles; preserve surviving source corners and winding. Rotated duplicates are removed; reversed winding stays.
filter_index_buffer_into
Caller-buffer filtering. The tail is preserved; work exhaustion can leave partial output.
filter_index_buffer_multi
Multi-stream triangle filtering.
filter_index_buffer_multi_into
Caller-buffer multi-stream filtering; late work exhaustion can leave partial output.
generate_adjacency_index_buffer
Generate six adjacency indices per triangle using binary position welding.
generate_adjacency_index_buffer_into
Caller-buffer adjacency; requires twice input-length capacity. Late work exhaustion can leave partial output.
generate_normals
Experimental upstream meshopt_generateNormals, exposed only with experimental. None indices denote an unindexed triangle list.
generate_normals_into
Caller-buffer form of the experimental normal generator. The destination is unchanged if validation or allocation fails.
generate_position_remap
Map each position to its first numerically equal vertex. Signed zeros weld; NaNs do not compare equal. The output refers to original indices.
generate_position_remap_into
Caller-buffer numerical position remap. The tail is preserved; work exhaustion can leave partial output.
generate_provoking_index_buffer
Generate a unique first-corner vertex for each triangle, with the same wrapping eight-bit valence heuristic and cyclic rotations as upstream.
generate_provoking_index_buffer_into
Write provoking topology and used reorder prefix. Requires vertex-count plus triangle-count reorder capacity; work exhaustion can partially modify both outputs.
generate_shadow_index_buffer
Replace triangle references with first referenced binary-equal vertices.
generate_shadow_index_buffer_into
Caller-buffer shadow indices; late work exhaustion can leave partial output.
generate_shadow_index_buffer_multi
Multi-stream shadow indices, preserving original vertex numbering.
generate_shadow_index_buffer_multi_into
Caller-buffer multi-stream shadow indices; late work exhaustion can leave partial output.
generate_tangents
Generate per-corner XYZ plus handedness, matching meshopt_generateTangents. None indices denote an unindexed triangle list. Normals and UVs are packed.
generate_tangents_into
Caller-buffer form of meshopt_generateTangents; writes one vector per corner. The destination is unchanged if validation or allocation fails.
generate_tessellation_index_buffer
Generate twelve tessellation indices per triangle using binary position welding.
generate_tessellation_index_buffer_into
Caller-buffer tessellation; requires four times input-length capacity. Late work exhaustion can leave partial output.
generate_vertex_remap
Generate compact numbering from tightly packed binary keys. None visits every vertex in original order; indexed input need not be a triangle list.
generate_vertex_remap_custom
Generate compact numbering with a callback invoked only for numerically equal positions, in exactly upstream’s hash-probe order. Signed zeros weld.
generate_vertex_remap_custom_into
Caller-buffer custom numbering with exact callback traversal. Work exhaustion can leave partial output.
generate_vertex_remap_into
Single-stream caller-buffer compact numbering.
generate_vertex_remap_multi
Generate compact numbering from one through sixteen initialized key streams.
generate_vertex_remap_multi_into
Generate compact numbering into caller storage. The tail is untouched; work exhaustion may leave the used prefix partially modified.
opacity_map_compact
Compact OMM data in place, as upstream meshopt_opacityMapCompact does.
opacity_map_entry_size
Packed byte count for one micromap, corresponding to meshopt_opacityMapEntrySize.
opacity_map_measure
Deduplicate triangles by quantized UV and choose adaptive OMM levels.
opacity_map_measure_into
Caller-buffer form of meshopt_opacityMapMeasure; returns unique entry count. The three destinations are unchanged when validation fails.
opacity_map_rasterize
Rasterize one upstream opacity entry using an alpha-channel byte view.
opacity_map_rasterize_into
Caller-buffer form of meshopt_opacityMapRasterize. Returns the number of bytes written and preserves the destination on error.
optimize_meshlet
Allocating meshopt_optimizeMeshlet (level zero).
optimize_meshlet_in_place
Atomic destructive meshopt_optimizeMeshlet (level zero).
optimize_meshlet_into
Caller-buffer level-zero meshlet optimization, preserving unused tails.
optimize_meshlet_level
Allocating meshopt_optimizeMeshletLevel; unused vertex suffix stays unchanged.
optimize_meshlet_level_in_place
meshopt_optimizeMeshletLevel: atomic destructive variant, levels 0 through 9.
optimize_meshlet_level_into
Caller-buffer meshlet optimization. Errors leave destinations unchanged; suffixes beyond the supplied vertex and triangle lengths are preserved.
optimize_overdraw
Reorder cache-optimized triangles using upstream meshopt_optimizeOverdraw.
optimize_overdraw_in_place
Destructively apply upstream overdraw ordering, leaving input unchanged on error. A fallibly allocated temporary output counts toward the byte limit.
optimize_overdraw_into
Write upstream overdraw ordering to the used prefix of a caller buffer.
optimize_vertex_cache
Reorder triangles using upstream meshopt_optimizeVertexCache (standard variant).
optimize_vertex_cache_fifo
Optimize using upstream’s FIFO cache heuristic. Cache size is at least three.
optimize_vertex_cache_fifo_in_place
Destructively apply FIFO ordering, preserving indices on error.
optimize_vertex_cache_fifo_into
Write FIFO cache ordering; work exhaustion may partially modify the prefix.
optimize_vertex_cache_in_place
Destructively apply upstream standard cache ordering, leaving input unchanged on error. A fallibly allocated temporary output counts toward the byte limit.
optimize_vertex_cache_into
Write upstream standard cache ordering to the used prefix of destination.
optimize_vertex_cache_strip
Optimize cache ordering using upstream’s strip-oriented score table.
optimize_vertex_cache_strip_in_place
Destructively apply strip-oriented ordering, preserving indices on error.
optimize_vertex_cache_strip_into
Write strip-oriented cache ordering; work exhaustion may partially modify the used prefix. The unused destination tail is untouched.
optimize_vertex_fetch
Allocate first-use vertex bytes and rewritten arbitrary indices.
optimize_vertex_fetch_in_place
Explicit destructive spelling for caller-buffer fetch optimization. This is the same checked operation as optimize_vertex_fetch_into. Write fetch-ordered bytes while rewriting indices in place. Validation and allocation precede writes; counted-work exhaustion may modify both buffers.
optimize_vertex_fetch_into
Write fetch-ordered bytes while rewriting indices in place. Validation and allocation precede writes; counted-work exhaustion may modify both buffers.
optimize_vertex_fetch_remap
Generate first-use fetch numbering for an arbitrary index sequence.
optimize_vertex_fetch_remap_into
Fetch numbering into caller storage. Unused vertices are u32::MAX; work exhaustion may partially modify the used prefix.
optimize_vertex_fetch_remap_with_indices
Generate first-use fetch numbering using cached index validation.
optimize_vertex_fetch_remap_with_indices_into
Generate fetch numbering into caller storage using cached validation.
partition_clusters
meshopt_partitionClusters. Clusters may contain arbitrary index lists; empty clusters are invalid. Positions are optional; without them only connected clusters merge.
partition_clusters_into
Caller-buffer cluster partitioning; a late failure may modify the used prefix.
quantize_float
Round to 0 through 23 mantissa bits. Preserve infinity and NaN payloads; flush all exponent-zero values, including negative zero, to positive zero.
quantize_half
Convert to upstream’s half representation, flushing subnormals and canonicalizing NaNs to signed quiet NaNs.
quantize_snorm
Quantize to a signed normalized integer with 1 through 31 bits. Infinities clamp; NaN follows upstream comparisons and becomes the minimum.
quantize_unorm
Quantize to an unsigned normalized integer with 0 through 30 bits. Infinities clamp; NaN follows upstream comparisons and becomes zero.
remap_index_buffer
Allocate remapped indices.
remap_index_buffer_into
Remap arbitrary index sequences. None remaps all vertices in order; references to the unused sentinel are rejected before writes.
remap_vertex_buffer
Allocate remapped tightly packed bytes, zero-initializing unmapped records.
remap_vertex_buffer_into
Remap initialized vertex bytes into caller storage. Repeated destinations use the last source record, matching upstream; unmapped records are untouched. Validation precedes writes; work exhaustion may leave partial output.
remesh
Allocate the upper bound, remesh, and return three vertices per output triangle.
remesh_bound
Return the upstream triangle-count upper bound with no output allocation.
remesh_into
Write up to destination.len()/3 triangles and return the full triangle count. A short destination receives a prefix, matching upstream’s partial-write rule.
simplify
Allocate meshopt_simplify’s result, preserving upstream ordering and error bits. No welding, fetch compaction or cache optimization is applied to the result.
simplify_into
Write meshopt_simplify’s result into a caller buffer of at least input length. The tail after the input length is preserved. A late resource or numerical error may modify the input-length prefix; use the allocating API for atomicity.
simplify_points
Simplify points to original vertex indices using grid reservoirs. Optional colors are checked three-component views; all supplied values must be finite.
simplify_points_into
Caller-buffer point reduction. Requires target-count capacity; work exhaustion may partially modify output.
simplify_prune
Remove disconnected components whose bounding-sphere radius is at most the relative error. Position welding is numerical, including signed zeros; unused positions affect bounds.
simplify_prune_into
Caller-buffer component pruning. Requires input-length capacity; work exhaustion may partially modify output.
simplify_scale
Return meshopt_simplifyScale’s maximum axis extent, without an epsilon clamp. Empty and coincident positions return zero; non-finite inputs and overflowing extents return an error. This operation allocates no memory.
simplify_sloppy
Grid-based sloppy triangle simplification. Only LOCK flags are accepted; target error and returned error are relative to the full position extent.
simplify_sloppy_into
Caller-buffer sloppy simplification. Requires input-length capacity; work exhaustion may partially modify output.
simplify_with_attributes
Allocate meshopt_simplifyWithAttributes’s result. All three vertex flags are supported; weights must be finite and nonnegative, with one per component. Zero-weight components do not contribute to error. All supplied values must be finite, including unused vertices and zero-weight components.
simplify_with_attributes_into
Caller-buffer attribute simplification, with the same contracts as simplify_with_attributes and the mutation guarantee of simplify_into.
simplify_with_update
Destructively simplify indices and solve surviving positions and weighted attributes. Late work or numerical failures may modify the index prefix; position and attribute writes start only after solving completes. Unused vertices, externally locked vertices and zero-weight attributes are preserved.
simplify_with_update_in_place
Explicit destructive spelling for update simplification with mutable views. This is the same checked operation as simplify_with_update. Destructively simplify indices and solve surviving positions and weighted attributes. Late work or numerical failures may modify the index prefix; position and attribute writes start only after solving completes. Unused vertices, externally locked vertices and zero-weight attributes are preserved.
spatial_cluster_points
meshopt_spatialClusterPoints: new-to-old permutation in fixed-size clusters.
spatial_cluster_points_into
Caller-buffer point clustering; the unused tail is preserved.
spatial_sort_remap
meshopt_spatialSortRemap: old-to-new Morton remap.
spatial_sort_remap_into
Caller-buffer Morton remap; the unused tail is preserved.
spatial_sort_triangles
meshopt_spatialSortTriangles: reorder complete triangles by centroid Morton order.
spatial_sort_triangles_in_place
Atomic in-place spatial triangle sorting.
spatial_sort_triangles_into
Caller-buffer spatial triangle sorting; the unused tail is preserved.
stripify
Convert triangles to an exact upstream strip. A nonzero restart_index enables restarts.
stripify_bound
Worst-case output index count for meshopt_stripify.
stripify_into
Caller-buffer form of meshopt_stripify; destination needs the bound capacity.
unstripify
Convert a strip to triangles, skipping degenerate triangles as upstream does.
unstripify_bound
Worst-case output index count for meshopt_unstripify.
unstripify_into
Caller-buffer form of meshopt_unstripify; destination needs the bound capacity.
validate_vertex_flags
Validate that optional vertex flags have exactly one entry per vertex.