Skip to main content

bread_format/
mesh.rs

1/*
2 * SPDX-FileCopyrightText: 2026 SynrgStudio
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! The mesh chunk: one triangle mesh, lossless (`SPEC.md`, section 6).
7//!
8//! Vertices and triangles go through meshoptimizer's codecs, which keep every
9//! vertex bit for bit. The triangle codec may start a triangle at another of
10//! its corners (same winding), so the payload also lists those triangles and
11//! the decoder turns them back: the mesh comes back identical, face order and
12//! first corners included.
13//!
14//! Both codecs are pinned to version 1, whatever the library's default, so a
15//! newer meshoptimizer cannot change what a chunk means. Facet normals a
16//! source STL declared are not kept: they are file data, not geometry.
17//!
18//! ```text
19//! metadata    u8 0 | 1, then name and comment (u8 0 | 1, u32 length, UTF-8)
20//! vertices    u32 count, u32 length, meshopt vertex buffer of [f32; 3]
21//! triangles   u32 count, u32 length, meshopt index buffer
22//! rotations   u32 count, then per triangle: u32 gap from the previous
23//!             listed triangle, u8 corner (1 | 2) the stored one starts at
24//! ```
25
26use std::fmt;
27
28use crate::bytes::{In, Out, fits_u32};
29use crate::container::ChunkTag;
30use crate::meta::{Meta, read_meta, write_meta};
31
32/// The tag of a mesh chunk.
33pub const MESH_TAG: ChunkTag = ChunkTag(*b"MESH");
34
35/// The newest mesh payload layout this build reads. Version 1 is read too.
36pub const MESH_VERSION: u16 = 2;
37
38/// The first byte of a vertex buffer: attribute codec version 1.
39const VERTEX_HEADER: u8 = 0xa1;
40/// The first byte of an index buffer: triangle codec version 1.
41const INDEX_HEADER: u8 = 0xe1;
42
43/// The vertex codec version written, and its level: 2 is the library's
44/// default, so the bytes match what the plain encoder writes.
45const VERTEX_VERSION: i32 = 1;
46const VERTEX_LEVEL: i32 = 2;
47
48/// Bounds on what a damaged count may ask for, from the codecs' densest
49/// output: each block of up to 256 vertices spends at least its 3-byte control
50/// header, and each triangle at least a byte besides the index buffer's first
51/// byte and 16-byte tail.
52const VERTICES_PER_BLOCK: usize = 256;
53const BLOCK_HEADER_BYTES: usize = 3;
54const INDEX_BUFFER_OVERHEAD: usize = 17;
55
56/// A triangle mesh, as a mesh chunk keeps it.
57#[derive(Clone, Debug, Default, PartialEq)]
58pub struct Mesh {
59    /// The name and comment, such as an STL header, or `None` for a mesh
60    /// without metadata.
61    pub meta: Option<Meta>,
62    /// The vertex positions: x, y and z.
63    pub vertices: Vec<[f32; 3]>,
64    /// The triangles: three indices into `vertices` each, first corner first.
65    pub triangles: Vec<[u32; 3]>,
66}
67
68/// Why a mesh could not be encoded.
69#[derive(Clone, Debug, PartialEq, Eq)]
70pub enum EncodeMeshError {
71    /// A triangle names a vertex the mesh does not have.
72    VertexOutOfRange,
73    /// The mesh has 2^32 or more vertices or triangles, or encodes to 4 GiB
74    /// or more.
75    TooLarge,
76    /// The mesh does not meet what the chosen version 2 coding needs.
77    Unsupported,
78}
79
80impl fmt::Display for EncodeMeshError {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        f.write_str(match self {
83            Self::VertexOutOfRange => "a triangle names a vertex the mesh does not have",
84            Self::TooLarge => "the mesh is too large for a mesh chunk",
85            Self::Unsupported => "the mesh cannot be stored with the chosen coding",
86        })
87    }
88}
89
90impl std::error::Error for EncodeMeshError {}
91
92/// Why a mesh payload could not be decoded.
93#[derive(Clone, Debug, PartialEq, Eq)]
94pub enum DecodeMeshError {
95    /// The payload is cut short, padded or self-contradictory.
96    Malformed,
97    /// A triangle names a vertex the mesh does not have.
98    VertexOutOfRange,
99}
100
101impl fmt::Display for DecodeMeshError {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        f.write_str(match self {
104            Self::Malformed => "the mesh data is malformed",
105            Self::VertexOutOfRange => "a triangle names a vertex the mesh does not have",
106        })
107    }
108}
109
110impl std::error::Error for DecodeMeshError {}
111
112/// Encodes `mesh` as a mesh chunk payload.
113pub fn encode_mesh(mesh: &Mesh) -> Result<Vec<u8>, EncodeMeshError> {
114    let vertex_count = mesh.vertices.len();
115    if !fits_u32(vertex_count) || !fits_u32(mesh.triangles.len()) {
116        return Err(EncodeMeshError::TooLarge);
117    }
118    let indices = mesh.triangles.as_flattened();
119    if indices.iter().any(|&index| index as usize >= vertex_count) {
120        return Err(EncodeMeshError::VertexOutOfRange);
121    }
122    let encoded_vertices =
123        meshopt::encode_vertex_buffer_level(&mesh.vertices, VERTEX_LEVEL, Some(VERTEX_VERSION))
124            .expect("12-byte vertices encode");
125    let encoded_indices =
126        meshopt::encode_index_buffer(indices, vertex_count).expect("whole triangles encode");
127    // The triangle codec's version can only be set through a global, unsafe
128    // switch, so its default is checked instead.
129    assert_eq!(
130        encoded_indices.first(),
131        Some(&INDEX_HEADER),
132        "the triangle codec writes version 1"
133    );
134    if !fits_u32(encoded_vertices.len()) || !fits_u32(encoded_indices.len()) {
135        return Err(EncodeMeshError::TooLarge);
136    }
137    let stored: Vec<u32> = meshopt::decode_index_buffer(&encoded_indices, indices.len())
138        .expect("the codec reads its own output");
139
140    let mut out = Out::default();
141    write_meta(&mut out, mesh.meta.as_ref());
142    out.len(vertex_count);
143    out.bytes(&encoded_vertices);
144    out.len(mesh.triangles.len());
145    out.bytes(&encoded_indices);
146
147    let rotations: Vec<(usize, u8)> = stored
148        .as_chunks::<3>()
149        .0
150        .iter()
151        .zip(&mesh.triangles)
152        .enumerate()
153        .filter(|(_, (stored, original))| stored != original)
154        .map(|(triangle, (stored, original))| {
155            let corner = (1..3u8)
156                .find(|&r| (0..3).all(|k| stored[(k + usize::from(r)) % 3] == original[k]))
157                .expect("the codec only rotates triangles");
158            (triangle, corner)
159        })
160        .collect();
161    out.len(rotations.len());
162    let mut previous = 0;
163    for (triangle, corner) in rotations {
164        out.len(triangle - previous);
165        out.u8(corner);
166        previous = triangle;
167    }
168    Ok(out.0)
169}
170
171/// Decodes a mesh chunk payload.
172pub fn decode_mesh(payload: &[u8]) -> Result<Mesh, DecodeMeshError> {
173    decode(&mut In(payload)).ok_or(DecodeMeshError::Malformed)?
174}
175
176fn decode(input: &mut In<'_>) -> Option<Result<Mesh, DecodeMeshError>> {
177    let meta = read_meta(input)?;
178    let vertex_count = input.len()?;
179    let encoded_vertices = input.bytes()?;
180    if encoded_vertices.first() != Some(&VERTEX_HEADER)
181        || vertex_count.checked_mul(BLOCK_HEADER_BYTES)?
182            >= encoded_vertices.len().checked_mul(VERTICES_PER_BLOCK)?
183    {
184        return None;
185    }
186    let triangle_count = input.len()?;
187    let encoded_indices = input.bytes()?;
188    if encoded_indices.first() != Some(&INDEX_HEADER)
189        || triangle_count > encoded_indices.len().checked_sub(INDEX_BUFFER_OVERHEAD)?
190    {
191        return None;
192    }
193    let vertices: Vec<[f32; 3]> =
194        meshopt::decode_vertex_buffer(encoded_vertices, vertex_count).ok()?;
195    let mut indices: Vec<u32> =
196        meshopt::decode_index_buffer(encoded_indices, triangle_count.checked_mul(3)?).ok()?;
197
198    let faces = indices.as_chunks_mut::<3>().0;
199    let rotations = input.count(5)?;
200    let mut triangle = 0usize;
201    for listed in 0..rotations {
202        let gap = input.len()?;
203        if listed > 0 && gap == 0 {
204            return None;
205        }
206        triangle = triangle.checked_add(gap)?;
207        let corner = usize::from(input.u8()?);
208        if !(1..3).contains(&corner) {
209            return None;
210        }
211        faces.get_mut(triangle)?.rotate_left(corner);
212    }
213    if !input.is_empty() {
214        return None;
215    }
216    if indices.iter().any(|&index| index as usize >= vertex_count) {
217        return Some(Err(DecodeMeshError::VertexOutOfRange));
218    }
219    Some(Ok(Mesh {
220        meta,
221        vertices,
222        triangles: indices.as_chunks::<3>().0.to_vec(),
223    }))
224}