Skip to main content

bread_format/
preview.rs

1/*
2 * SPDX-FileCopyrightText: 2026 SynrgStudio
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! The support preview chunk (`SPEC.md`, section 9): for support leaves,
7//! which are stored with an empty mesh, the mesh of the supports as they were
8//! when the file was written, so that any reader can show them.
9//!
10//! Each mesh is a whole mesh chunk payload, so it is checked, and kept, like
11//! any other mesh.
12//!
13//! ```text
14//! previews  u32 count, then per preview:
15//!           u32 the support leaf's node index in the scene chunk
16//!           u32 length, mesh chunk payload (version 1)
17//! ```
18
19use std::collections::HashSet;
20use std::fmt;
21
22use crate::bytes::{In, Out, fits_u32};
23use crate::container::ChunkTag;
24use crate::mesh::{DecodeMeshError, EncodeMeshError, Mesh, decode_mesh, encode_mesh};
25use crate::scene::Scene;
26
27/// The tag of the support preview chunk.
28pub const SUPPORT_PREVIEW_TAG: ChunkTag = ChunkTag(*b"SPRV");
29
30/// The support preview payload layout this build writes and reads. It holds
31/// meshes of mesh chunk version 1.
32pub const SUPPORT_PREVIEW_VERSION: u16 = 1;
33
34/// What a reader that skips the supports chunk can show for one support leaf.
35#[derive(Clone, Debug, Default, PartialEq)]
36pub struct SupportPreview {
37    /// The support leaf, as an index into the scene's nodes.
38    pub leaf: usize,
39    /// The supports, in the leaf's own space.
40    pub mesh: Mesh,
41}
42
43/// Why a list of support previews could not be encoded.
44#[derive(Clone, Debug, PartialEq, Eq)]
45pub enum EncodePreviewsError {
46    /// A preview names a node the scene does not have, or one that is not a
47    /// leaf.
48    NotALeaf,
49    /// A preview names a leaf that shows a mesh with vertices or triangles.
50    MeshNotEmpty,
51    /// Two previews name the same leaf.
52    SameLeaf,
53    Mesh(EncodeMeshError),
54    /// There are 2^32 or more previews, or a mesh encodes to 4 GiB or more.
55    TooLarge,
56}
57
58impl fmt::Display for EncodePreviewsError {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        match self {
61            Self::NotALeaf => f.write_str(NOT_A_LEAF),
62            Self::MeshNotEmpty => f.write_str(MESH_NOT_EMPTY),
63            Self::SameLeaf => f.write_str(SAME_LEAF),
64            Self::Mesh(err) => write!(f, "{err}"),
65            Self::TooLarge => f.write_str("the previews are too large for their chunk"),
66        }
67    }
68}
69
70impl std::error::Error for EncodePreviewsError {}
71
72/// Why a support preview payload could not be decoded.
73#[derive(Clone, Debug, PartialEq, Eq)]
74pub enum DecodePreviewsError {
75    /// The payload is cut short or padded.
76    Malformed,
77    /// A preview's mesh is not a valid mesh chunk payload.
78    Mesh(DecodeMeshError),
79    /// A preview names a node the scene does not have, or one that is not a
80    /// leaf.
81    NotALeaf,
82    /// A preview names a leaf that shows a mesh with vertices or triangles.
83    MeshNotEmpty,
84    /// Two previews name the same leaf.
85    SameLeaf,
86}
87
88impl fmt::Display for DecodePreviewsError {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        match self {
91            Self::Malformed => f.write_str("the support preview data is malformed"),
92            Self::Mesh(err) => write!(f, "{err}"),
93            Self::NotALeaf => f.write_str(NOT_A_LEAF),
94            Self::MeshNotEmpty => f.write_str(MESH_NOT_EMPTY),
95            Self::SameLeaf => f.write_str(SAME_LEAF),
96        }
97    }
98}
99
100impl std::error::Error for DecodePreviewsError {}
101
102const NOT_A_LEAF: &str = "a support preview names a scene part that is not a leaf";
103const MESH_NOT_EMPTY: &str = "a support preview names a leaf that shows a mesh of its own";
104const SAME_LEAF: &str = "two support previews name the same leaf";
105
106/// A rule of section 9 that some previews break.
107enum Broken {
108    NotALeaf,
109    MeshNotEmpty,
110    SameLeaf,
111}
112
113impl From<Broken> for EncodePreviewsError {
114    fn from(broken: Broken) -> Self {
115        match broken {
116            Broken::NotALeaf => Self::NotALeaf,
117            Broken::MeshNotEmpty => Self::MeshNotEmpty,
118            Broken::SameLeaf => Self::SameLeaf,
119        }
120    }
121}
122
123impl From<Broken> for DecodePreviewsError {
124    fn from(broken: Broken) -> Self {
125        match broken {
126            Broken::NotALeaf => Self::NotALeaf,
127            Broken::MeshNotEmpty => Self::MeshNotEmpty,
128            Broken::SameLeaf => Self::SameLeaf,
129        }
130    }
131}
132
133/// Encodes `previews` as a support preview payload, checking them against
134/// `scene`.
135pub fn encode_previews(
136    previews: &[SupportPreview],
137    scene: &Scene,
138) -> Result<Vec<u8>, EncodePreviewsError> {
139    check(previews, scene)?;
140    if !fits_u32(previews.len()) {
141        return Err(EncodePreviewsError::TooLarge);
142    }
143    let mut out = Out::default();
144    out.len(previews.len());
145    for preview in previews {
146        let mesh = encode_mesh(&preview.mesh).map_err(EncodePreviewsError::Mesh)?;
147        if !fits_u32(mesh.len()) {
148            return Err(EncodePreviewsError::TooLarge);
149        }
150        // The leaf was checked against the scene, whose node count fits.
151        out.len(preview.leaf);
152        out.bytes(&mesh);
153    }
154    Ok(out.0)
155}
156
157/// Decodes a support preview payload, checking it against `scene`, the scene
158/// of the same file.
159pub fn decode_previews(
160    payload: &[u8],
161    scene: &Scene,
162) -> Result<Vec<SupportPreview>, DecodePreviewsError> {
163    let mut input = In(payload);
164    let malformed = DecodePreviewsError::Malformed;
165    let count = input.count(8).ok_or(malformed.clone())?;
166    let mut previews = Vec::with_capacity(count);
167    for _ in 0..count {
168        let leaf = input.len().ok_or(malformed.clone())?;
169        let mesh = input.bytes().ok_or(malformed.clone())?;
170        let mesh = decode_mesh(mesh).map_err(DecodePreviewsError::Mesh)?;
171        previews.push(SupportPreview { leaf, mesh });
172    }
173    if !input.is_empty() {
174        return Err(malformed);
175    }
176    check(&previews, scene)?;
177    Ok(previews)
178}
179
180/// Every preview names a leaf with an empty mesh, and no two the same one.
181fn check(previews: &[SupportPreview], scene: &Scene) -> Result<(), Broken> {
182    let mut leaves = HashSet::new();
183    for preview in previews {
184        let mesh = scene.leaf_mesh(preview.leaf).ok_or(Broken::NotALeaf)?;
185        if !mesh.vertices.is_empty() || !mesh.triangles.is_empty() {
186            return Err(Broken::MeshNotEmpty);
187        }
188        if !leaves.insert(preview.leaf) {
189            return Err(Broken::SameLeaf);
190        }
191    }
192    Ok(())
193}