//! A Rust port of [meshoptimizer](https://github.com/zeux/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, meshlet decoding and spatial meshlet box sweeps. 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).
//!
//! 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](https://github.com/Tavrin/meshoptimizer-rs#readme).
//!
//! Coverage includes vertex processing, simplification, meshlets, codecs,
//! analyzers, opacity maps, tangents, normals, remeshing, parallel batches
//! and SIMD decoding.
//! Cluster-LOD building requires `clusterlod`; DAG serialization is always available.
//! Batches require `parallel` and `std`.
//! Normal generation and remeshing require `experimental`.
//!
//! # Index widths
//!
//! Existing names keep their u32 signatures. Add `_generic` to index-processing
//! function and width-aware method names to select the sealed [`Index`] trait
//! (`u16` or `u32`). For example, [`optimize_vertex_cache_generic`] accepts
//! `&[u16]` and returns `Vec<u16>`. Output-only calls take a type argument,
//! such as `simplify_points_generic::<u16>`. Narrowing returns
//! [`Error::IndexOverflow`] instead of truncating.
//! Width-aware structs use a `Generic` suffix, such as [`MeshletsGeneric`].
//! Original struct names remain concrete u32 forms.
//! Existing byte-oriented codec layouts retain their upstream conversion rules;
//! the typed index APIs check narrowing.
//! See the [16-bit recipe](guide#16-bit-vertex-indices).
//!
//! # Recipes
//!
//! - [Non-packed positions](guide#non-packed-positions).
//! - [Simplify one mesh](guide#simplify-one-mesh).
//! - [Per-mesh LOD chain](guide#per-mesh-lod-chain).
//! - [Meshlets with bounds](guide#meshlets-with-bounds).
//! - [Vertex and index encode and decode](guide#vertex-and-index-encode-and-decode).
//! - [Streaming index sequences](guide#streaming-index-sequences) (an extension, not in C++ meshoptimizer).
//! - [Untrusted input with Limits](guide#untrusted-input-with-limits).
//! - [Parallel workers](guide#parallel-workers).
//! - [Lower peak memory with Retention::Lean](guide#lower-peak-memory-with-retentionlean).
//! - [Mesh repair](guide#mesh-repair) (an extension, not in C++ meshoptimizer).
//!
//! - [LOD quality and switch distances](guide#lod-quality-and-switch-distances) (not in C++ meshoptimizer).
//! - [Hidden-surface removal](guide#hidden-surface-removal) (an extension, not in C++ meshoptimizer).
//! - [Alpha-cutout card trimming](guide#alpha-cutout-card-trimming) (an extension, not in C++ meshoptimizer).
//! - [Cluster LOD DAG files](guide#cluster-lod-dag-files) (an extension, not in C++ meshoptimizer).
//! - [Parallel vertex codec and spatial meshlets](guide#parallel-vertex-codec-and-spatial-meshlets-for-one-large-mesh) (an extension, not in C++ meshoptimizer).
//! - [Character LODs](guide#character-lods) (an extension, not in C++ meshoptimizer).
//! - [One-call asset pipeline](guide#one-call-asset-pipeline) (an extension, not in C++ meshoptimizer).
//! - [Incremental vertex and triangle decoding](guide#incremental-vertex-and-triangle-decoding) (an extension, not in C++ meshoptimizer).
//!
//! # 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);
//! # Ok::<(), meshoptimizer_rs::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());
//! # Ok::<(), meshoptimizer_rs::Error>(())
//! ```
//!
//! # 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);
//! }
//! # Ok::<(), meshoptimizer_rs::Error>(())
//! ```
//!
//! # 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);
//! # Ok::<(), meshoptimizer_rs::Error>(())
//! ```
//!
//! # 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`.
//! DAG serialization and flat record types are always available.
//! 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, plus parallel vertex encode/decode and spatial meshlet building
//! for one large input; enables `std`. See the `parallel` module for limits
//! and error semantics.
#![deny(unsafe_code)]
#![cfg_attr(not(feature = "simd"), forbid(unsafe_code))]
#![deny(
unsafe_op_in_unsafe_fn,
clippy::undocumented_unsafe_blocks,
clippy::multiple_unsafe_ops_per_block,
clippy::missing_safety_doc
)]
#![cfg_attr(not(feature = "std"), no_std)]
#![deny(missing_docs)]
extern crate alloc;
/// Compiles and runs every `rust` block in the README as a doctest.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
pub struct ReadmeDoctests;
/// Compiles and runs the migration guide examples as doctests.
#[cfg(doctest)]
#[doc = include_str!("../docs/MIGRATING_FROM_MESHOPT.md")]
pub struct MigrationDoctests;
/// Task recipes with complete, checked examples.
pub mod guide {
#![doc = include_str!("../docs/USING.md")]
}
mod budget;
mod hidden;
pub use hidden::{
remove_hidden_triangles, remove_hidden_triangles_generic, remove_hidden_triangles_into,
remove_hidden_triangles_into_generic, HiddenOptions, HiddenReport, HiddenViews, VisibleMesh,
VisibleMeshGeneric,
};
mod cutout;
pub use cutout::{
trim_alpha_cards, trim_alpha_cards_generic, AlphaMask, AlphaWrap, CardTrimOptions,
CardTrimReport, TrimmedCards, TrimmedCardsGeneric,
};
mod impostor;
pub use impostor::{
bake_impostor, bake_impostor_generic, impostor_switch_distance, ImpostorAlbedo, ImpostorAtlas,
ImpostorBlend, ImpostorBounds, ImpostorFrame, ImpostorGrid, ImpostorLayout, ImpostorOptions,
ImpostorReconstruct, ImpostorReport, ImpostorSwitch,
};
mod analyze;
mod cache;
pub mod codec;
mod error;
mod index;
pub use index::Index;
mod input;
mod math;
mod mesh_analysis;
#[cfg(feature = "experimental")]
mod normal;
mod opacity;
mod overdraw;
mod quantize;
mod remap;
mod repair;
mod sanitize;
pub use repair::{
fill_holes, fill_holes_bound, fill_holes_generic, fill_holes_into, fill_holes_into_generic,
orient_faces, orient_faces_bound, orient_faces_generic, orient_faces_into,
orient_faces_into_generic, split_non_manifold_vertices, split_non_manifold_vertices_generic,
stitch_cracks, stitch_cracks_generic, weld_vertices, weld_vertices_bound, weld_vertices_into,
weld_vertices_into_generic, FillHolesReport, FilledMesh, FilledMeshGeneric, HoleLoop,
OrientReport, OrientedMesh, OrientedMeshGeneric, SplitVerticesReport, StitchReport,
TopologyRepairGeneric, WeldPolicy, WeldReport, WeldedVertices,
};
mod character;
pub use character::{
build_character_lod_chain, simplify_character, CharacterInputs, CharacterLodChain,
CharacterLodMethod, CharacterLodSelection, CharacterOptions, CharacterSkin,
};
mod lod_quality;
pub use lod_quality::{
measure_lod_chain_quality, measure_lod_chain_quality_generic, measure_lod_quality,
measure_lod_quality_generic, LodCamera, LodDistance, LodNormalDeviation, LodQuality,
LodQualityLevel, LodQualityMesh, LodQualityMeshGeneric, LodQualityOptions,
};
mod lod_chain;
mod raster;
#[cfg(feature = "experimental")]
mod remesh;
pub use lod_chain::{
build_lod_chain, build_lod_chain_generic, LodChain, LodChainAttributes, LodChainError,
LodChainGeneric, LodChainOptions, LodErrors, LodLevel, LodLevelGeneric, LodTargets,
};
mod simplify;
mod strip;
mod tangent;
mod vertex_layout;
mod workspace;
pub use simplify::{
simplify, simplify_generic, simplify_into, simplify_into_generic, simplify_points,
simplify_points_generic, simplify_points_into, simplify_points_into_generic, simplify_prune,
simplify_prune_generic, simplify_prune_into, simplify_prune_into_generic, simplify_scale,
simplify_sloppy, simplify_sloppy_generic, simplify_sloppy_into, simplify_sloppy_into_generic,
simplify_with_attributes, simplify_with_attributes_generic, simplify_with_attributes_into,
simplify_with_attributes_into_generic, simplify_with_update, simplify_with_update_generic,
SimplifiedMesh, SimplifiedMeshGeneric, SimplifyOptions, SimplifyResult, SimplifySettings,
};
pub use vertex_layout::{VertexFieldSnapshot, VertexLayout, VertexLayoutError};
pub use analyze::{
analyze_vertex_cache, analyze_vertex_cache_generic, analyze_vertex_fetch,
analyze_vertex_fetch_generic, VertexCacheStatistics, VertexFetchStatistics,
};
pub use cache::{
optimize_vertex_cache, optimize_vertex_cache_fifo, optimize_vertex_cache_fifo_generic,
optimize_vertex_cache_fifo_in_place, optimize_vertex_cache_fifo_in_place_generic,
optimize_vertex_cache_fifo_into, optimize_vertex_cache_fifo_into_generic,
optimize_vertex_cache_generic, optimize_vertex_cache_in_place,
optimize_vertex_cache_in_place_generic, optimize_vertex_cache_into,
optimize_vertex_cache_into_generic, optimize_vertex_cache_strip,
optimize_vertex_cache_strip_generic, optimize_vertex_cache_strip_in_place,
optimize_vertex_cache_strip_in_place_generic, optimize_vertex_cache_strip_into,
optimize_vertex_cache_strip_into_generic, optimize_vertex_cache_with_table,
optimize_vertex_cache_with_table_generic, optimize_vertex_cache_with_table_into,
optimize_vertex_cache_with_table_into_generic, VertexScoreTable,
};
pub use error::Error;
pub use input::{
validate_vertex_flags, Attributes, AttributesMut, ByteOrder, Positions, PositionsMut,
VertexFlags,
};
pub use mesh_analysis::{
analyze_mesh, analyze_mesh_generic, AnalysisLists, AnalyzeOptions, BoundaryComponent,
MeshAnalysis,
};
pub use overdraw::{
optimize_overdraw, optimize_overdraw_generic, optimize_overdraw_in_place,
optimize_overdraw_in_place_generic, optimize_overdraw_into, optimize_overdraw_into_generic,
};
pub use quantize::{
compute_position_exponent, dequantize_half, quantize_float, quantize_half, quantize_snorm,
quantize_unorm,
};
pub use remap::*;
pub use sanitize::{
sanitize, sanitize_bound, sanitize_generic, sanitize_into, sanitize_into_generic,
SanitizeOptions, SanitizeReport, SanitizedMesh, SanitizedMeshGeneric,
};
#[cfg(feature = "experimental")]
pub use normal::{
generate_normals, generate_normals_generic, generate_normals_into,
generate_normals_into_generic,
};
pub use opacity::{
opacity_map_compact, opacity_map_entry_size, opacity_map_measure, opacity_map_measure_generic,
opacity_map_measure_into, opacity_map_measure_into_generic, opacity_map_rasterize,
opacity_map_rasterize_into, OpacityMapMeasure,
};
pub use raster::{
analyze_coverage, analyze_coverage_generic, analyze_overdraw, analyze_overdraw_generic,
CoverageStatistics, OverdrawStatistics,
};
#[cfg(feature = "experimental")]
pub use remesh::{
remesh, remesh_bound, remesh_bound_generic, remesh_generic, remesh_into, remesh_into_generic,
REMESH_SHELL, REMESH_SOLVE,
};
pub use strip::{
stripify, stripify_bound, stripify_generic, stripify_into, stripify_into_generic, unstripify,
unstripify_bound, unstripify_generic, unstripify_into, unstripify_into_generic,
};
pub use tangent::{
generate_tangents, generate_tangents_generic, generate_tangents_into,
generate_tangents_into_generic, TANGENT_COMPATIBLE, TANGENT_ZERO_FALLBACK,
};
pub use workspace::{Limits, Retention, Usage, Workspace};
mod meshlet;
mod meshlet_spatial;
mod meshlet_util;
mod processing;
mod spatial;
pub use meshlet::*;
pub use meshlet_util::*;
pub use spatial::*;
mod partition;
pub use partition::*;
#[cfg(feature = "clusterlod")]
pub mod clusterlod;
#[cfg(not(feature = "clusterlod"))]
#[path = "clusterlod/format_only.rs"]
pub mod clusterlod;
#[cfg(feature = "parallel")]
pub mod parallel;
/// Explicit destructive spelling for caller-buffer fetch optimization.
/// This is the same checked operation as `optimize_vertex_fetch_into`.
pub use remap::optimize_vertex_fetch_into as optimize_vertex_fetch_in_place;
/// Explicit destructive spelling for update simplification with mutable views.
/// This is the same checked operation as `simplify_with_update`.
pub use simplify::simplify_with_update as simplify_with_update_in_place;
/// Selectable index-width fetch optimization.
pub use remap::optimize_vertex_fetch_into_generic as optimize_vertex_fetch_in_place_generic;
/// Selectable index-width update simplification.
pub use simplify::simplify_with_update_generic as simplify_with_update_in_place_generic;
mod pipeline;
pub use pipeline::{
process_mesh, ProcessError, ProcessLevel, ProcessOptions, ProcessReport, ProcessSkin,
ProcessStage, ProcessStageReport, ProcessedMesh,
};
#[cfg(feature = "clusterlod")]
pub use pipeline::ProcessClusters;