meshoptimizer_rs/lib.rs
1//! A Rust port of [meshoptimizer](https://github.com/zeux/meshoptimizer) 1.3.
2//!
3//! Every ported function produces byte-identical output to meshoptimizer 1.3
4//! (scalar build). Differential runs against the C++ library, seeded sweeps,
5//! fuzzing and a wasm32 identity check prove this on the recorded inputs.
6//!
7//! 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](https://github.com/Tavrin/meshoptimizer-rs/blob/main/src/codec/simd/SAFETY.md).
8//!
9//! The crate needs no C++ toolchain.
10//! It supports `no_std` with `alloc`. Invalid input returns a typed [`Error`]
11//! instead of undefined behaviour. A reusable [`Workspace`] holds scratch
12//! memory, makes every allocation fallible and enforces per-call memory and
13//! work [`Limits`].
14//!
15//! This is an independent project. It is not affiliated with meshoptimizer or
16//! its author. Coverage, measured performance and the parity records are in the
17//! [README](https://github.com/Tavrin/meshoptimizer-rs#readme).
18//!
19//! Coverage includes vertex processing, simplification, meshlets, codecs,
20//! analyzers, opacity maps, tangents, normals, remeshing, parallel batches
21//! and SIMD decoding.
22//! Cluster-LOD requires `clusterlod`; batches require `parallel` and `std`.
23//! Normal generation and remeshing require `experimental`.
24//!
25//! # Recipes
26//!
27//! - [Non-packed positions](guide#non-packed-positions).
28//! - [Simplify one mesh](guide#simplify-one-mesh).
29//! - [Per-mesh LOD chain](guide#per-mesh-lod-chain).
30//! - [Meshlets with bounds](guide#meshlets-with-bounds).
31//! - [Vertex and index encode and decode](guide#vertex-and-index-encode-and-decode).
32//! - [Untrusted input with Limits](guide#untrusted-input-with-limits).
33//! - [Parallel workers](guide#parallel-workers).
34//! - [Lower peak memory with Retention::Lean](guide#lower-peak-memory-with-retentionlean).
35//!
36//! # Simplify a mesh
37//!
38//! ```
39//! use meshoptimizer_rs::{simplify, Positions, SimplifyOptions, SimplifySettings, Workspace};
40//!
41//! 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]];
42//! let indices = [0, 1, 2, 2, 1, 3];
43//! let mut workspace = Workspace::default();
44//!
45//! let settings = SimplifySettings {
46//! target_index_count: 3,
47//! target_error: 0.01,
48//! options: SimplifyOptions::EMPTY,
49//! };
50//! let lod = simplify(&indices, Positions::from_packed(&positions), settings, &mut workspace)?;
51//! println!("{} indices, relative error {}", lod.indices.len(), lod.error);
52//! # Ok::<(), meshoptimizer_rs::Error>(())
53//! ```
54//!
55//! # Optimize for the vertex cache, then for overdraw
56//!
57//! ```
58//! use meshoptimizer_rs::{optimize_overdraw, optimize_vertex_cache, Positions, Workspace};
59//!
60//! 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]];
61//! let indices = [0, 1, 2, 2, 1, 3];
62//! let mut workspace = Workspace::default();
63//!
64//! let cached = optimize_vertex_cache(&indices, positions.len(), &mut workspace)?;
65//! let ordered = optimize_overdraw(&cached, Positions::from_packed(&positions), 1.05, &mut workspace)?;
66//! assert_eq!(ordered.len(), indices.len());
67//! # Ok::<(), meshoptimizer_rs::Error>(())
68//! ```
69//!
70//! # Build meshlets
71//!
72//! ```
73//! use meshoptimizer_rs::{build_meshlets, MeshletSettings, Positions, Workspace};
74//!
75//! 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]];
76//! let indices = [0, 1, 2, 2, 1, 3];
77//! let mut workspace = Workspace::default();
78//!
79//! // 64 vertices and 124 triangles per meshlet; cone weight 0.25.
80//! let built = build_meshlets(
81//! &indices,
82//! Positions::from_packed(&positions),
83//! MeshletSettings::default(),
84//! 0.25,
85//! &mut workspace,
86//! )?;
87//! for meshlet in &built.meshlets {
88//! let start = meshlet.vertex_offset as usize;
89//! let vertices = &built.vertices[start..start + meshlet.vertex_count as usize];
90//! println!("{} triangles over vertices {:?}", meshlet.triangle_count, vertices);
91//! }
92//! # Ok::<(), meshoptimizer_rs::Error>(())
93//! ```
94//!
95//! # Compress vertex and index buffers
96//!
97//! The [`codec`] module reads and writes the `EXT_meshopt_compression` formats.
98//! Buffers are little-endian bytes. The format version and level are set per
99//! call instead of through global setters.
100//!
101//! ```
102//! use meshoptimizer_rs::codec::{
103//! decode_index_buffer, decode_vertex_buffer, encode_index_buffer, encode_vertex_buffer,
104//! IndexEncoding, VertexEncoding,
105//! };
106//! use meshoptimizer_rs::Workspace;
107//!
108//! 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]];
109//! let indices = [0, 1, 2, 2, 1, 3];
110//! let mut workspace = Workspace::default();
111//!
112//! let vertex_bytes: Vec<u8> = positions.iter().flatten().flat_map(|v| v.to_le_bytes()).collect();
113//! let packed = encode_vertex_buffer(&vertex_bytes, 4, 12, VertexEncoding::DEFAULT, &mut workspace)?;
114//! assert_eq!(decode_vertex_buffer(4, 12, &packed, &mut workspace)?, vertex_bytes);
115//!
116//! let packed = encode_index_buffer(&indices, IndexEncoding::DEFAULT, &mut workspace)?;
117//! let decoded = decode_index_buffer(indices.len(), 4, &packed, &mut workspace)?; // u32 bytes
118//! assert_eq!(decoded.len(), indices.len() * 4);
119//! # Ok::<(), meshoptimizer_rs::Error>(())
120//! ```
121//!
122//! # Features
123//!
124//! - `std` (default): implements `std::error::Error` for [`Error`]. Disable
125//! default features for `no_std`; an allocator is still required.
126//! - `clusterlod`: the cluster-LOD builder from upstream's `demo/clusterlod.h`.
127//! It reproduces the pinned demo exactly; it is not a stable upstream API.
128//! - `experimental`: upstream functions and options marked experimental.
129//! - `parallel`: ordered Rayon batch APIs for independent meshes and buffer
130//! views; enables `std`. See the `parallel` module for limits and error semantics.
131#![deny(unsafe_code)]
132#![cfg_attr(not(feature = "simd"), forbid(unsafe_code))]
133#![deny(
134 unsafe_op_in_unsafe_fn,
135 clippy::undocumented_unsafe_blocks,
136 clippy::multiple_unsafe_ops_per_block,
137 clippy::missing_safety_doc
138)]
139#![cfg_attr(not(feature = "std"), no_std)]
140#![deny(missing_docs)]
141
142extern crate alloc;
143
144/// Compiles and runs every `rust` block in the README as a doctest.
145#[cfg(doctest)]
146#[doc = include_str!("../README.md")]
147pub struct ReadmeDoctests;
148
149/// Compiles and runs the migration guide examples as doctests.
150#[cfg(doctest)]
151#[doc = include_str!("../docs/MIGRATING_FROM_MESHOPT.md")]
152pub struct MigrationDoctests;
153
154/// Task recipes with complete, checked examples.
155pub mod guide {
156 #![doc = include_str!("../docs/USING.md")]
157}
158
159mod budget;
160
161mod analyze;
162mod cache;
163pub mod codec;
164mod error;
165mod input;
166mod math;
167#[cfg(feature = "experimental")]
168mod normal;
169mod opacity;
170mod overdraw;
171mod quantize;
172mod remap;
173
174mod raster;
175#[cfg(feature = "experimental")]
176mod remesh;
177mod simplify;
178mod strip;
179mod tangent;
180mod workspace;
181pub use simplify::{
182 simplify, simplify_into, simplify_points, simplify_points_into, simplify_prune,
183 simplify_prune_into, simplify_scale, simplify_sloppy, simplify_sloppy_into,
184 simplify_with_attributes, simplify_with_attributes_into, simplify_with_update, SimplifiedMesh,
185 SimplifyOptions, SimplifyResult, SimplifySettings,
186};
187
188pub use analyze::{
189 analyze_vertex_cache, analyze_vertex_fetch, VertexCacheStatistics, VertexFetchStatistics,
190};
191pub use cache::{
192 optimize_vertex_cache, optimize_vertex_cache_fifo, optimize_vertex_cache_fifo_in_place,
193 optimize_vertex_cache_fifo_into, optimize_vertex_cache_in_place, optimize_vertex_cache_into,
194 optimize_vertex_cache_strip, optimize_vertex_cache_strip_in_place,
195 optimize_vertex_cache_strip_into,
196};
197pub use error::Error;
198pub use input::{
199 validate_vertex_flags, Attributes, AttributesMut, ByteOrder, Positions, PositionsMut,
200 VertexFlags,
201};
202pub use overdraw::{optimize_overdraw, optimize_overdraw_in_place, optimize_overdraw_into};
203pub use quantize::{
204 compute_position_exponent, dequantize_half, quantize_float, quantize_half, quantize_snorm,
205 quantize_unorm,
206};
207pub use remap::*;
208
209#[cfg(feature = "experimental")]
210pub use normal::{generate_normals, generate_normals_into};
211pub use opacity::{
212 opacity_map_compact, opacity_map_entry_size, opacity_map_measure, opacity_map_measure_into,
213 opacity_map_rasterize, opacity_map_rasterize_into, OpacityMapMeasure,
214};
215pub use raster::{analyze_coverage, analyze_overdraw, CoverageStatistics, OverdrawStatistics};
216#[cfg(feature = "experimental")]
217pub use remesh::{remesh, remesh_bound, remesh_into, REMESH_SHELL, REMESH_SOLVE};
218pub use strip::{
219 stripify, stripify_bound, stripify_into, unstripify, unstripify_bound, unstripify_into,
220};
221pub use tangent::{
222 generate_tangents, generate_tangents_into, TANGENT_COMPATIBLE, TANGENT_ZERO_FALLBACK,
223};
224pub use workspace::{Limits, Retention, Usage, Workspace};
225
226mod meshlet;
227mod meshlet_spatial;
228mod meshlet_util;
229mod processing;
230mod spatial;
231pub use meshlet::*;
232pub use meshlet_util::*;
233pub use spatial::*;
234
235mod partition;
236pub use partition::*;
237
238#[cfg(feature = "clusterlod")]
239pub mod clusterlod;
240#[cfg(feature = "parallel")]
241pub mod parallel;
242/// Explicit destructive spelling for caller-buffer fetch optimization.
243/// This is the same checked operation as `optimize_vertex_fetch_into`.
244pub use remap::optimize_vertex_fetch_into as optimize_vertex_fetch_in_place;
245/// Explicit destructive spelling for update simplification with mutable views.
246/// This is the same checked operation as `simplify_with_update`.
247pub use simplify::simplify_with_update as simplify_with_update_in_place;