Skip to main content

bread_format/
volume.rs

1/*
2 * SPDX-FileCopyrightText: 2026 SynrgStudio
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! The volume chunk (`SPEC.md`, section 14): meshes that belong to a model
7//! and act on it without being printed. Support enforcers and blockers,
8//! modifiers, and negative volumes, which the model's leaf shows already cut,
9//! with the model as it was before the cut beside them.
10//!
11//! A volume's mesh is shown by no leaf, so a reader that skips the chunk
12//! never prints it. Reserved kinds are carried as they are: a program treats
13//! them as absent. How volumes agree with the supports, hollows and roles is
14//! checked where the whole file is read and written.
15//!
16//! ```text
17//! entries   u32 count, then per entry:
18//!           u32 the model's leaf, as a node index in the scene chunk
19//!           u8  the kind: 1 support enforcer, 2 support blocker,
20//!               3 modifier, 4 negative volume, 5 the model before the cut
21//!           u32 the entry's mesh, as a mesh index
22//!           optional string, the entry's name
23//!           u8  has transform; then twelve f64 when it is 1
24//!           byte string, the name of the program the entry belongs to
25//!           u32 the program's version of the document
26//!           byte string, the document
27//! ```
28
29use std::collections::{HashMap, HashSet};
30use std::fmt;
31
32use crate::bytes::{In, Out, fits_u32};
33use crate::container::ChunkTag;
34use crate::program::is_name;
35use crate::scene::{NodeKind, Scene, Transform, read_transform, write_transform};
36
37/// The tag of the volume chunk.
38pub const VOLUME_TAG: ChunkTag = ChunkTag(*b"VOLM");
39
40/// The volume payload layout this build writes and reads.
41pub const VOLUME_VERSION: u16 = 1;
42
43/// Supports go where the model's surface inside the volume needs them.
44pub const VOLUME_SUPPORT_ENFORCER: u8 = 1;
45
46/// No support touches the model's surface inside the volume.
47pub const VOLUME_SUPPORT_BLOCKER: u8 = 2;
48
49/// Inside the volume, the model prints with the settings of the document.
50pub const VOLUME_MODIFIER: u8 = 3;
51
52/// The volume was cut away from the model, whose leaf shows it already cut.
53pub const VOLUME_NEGATIVE: u8 = 4;
54
55/// The model's mesh before its negative volumes were cut away.
56pub const VOLUME_UNCUT: u8 = 5;
57
58/// One entry of the volume chunk.
59#[derive(Clone, Debug, Default, PartialEq)]
60pub struct VolumeEntry {
61    /// The model's leaf, as an index into the scene's nodes.
62    pub model: usize,
63    /// What the entry is: one of the `VOLUME_*` kinds. Other values are
64    /// reserved, carried as they are, and mean nothing.
65    pub kind: u8,
66    /// The entry's mesh, as an index into the scene's meshes.
67    pub mesh: usize,
68    /// The entry's name.
69    pub name: Option<String>,
70    /// From the entry's mesh to the model leaf's own space; `None` is the
71    /// identity. An uncut model has none.
72    pub transform: Option<Transform>,
73    /// The program the entry belongs to, such as `nudl`, by the rules of a
74    /// program name ([`crate::is_program_name`]). Every entry has one, even
75    /// without a document.
76    pub program: String,
77    /// The program's own version of `document`.
78    pub version: u32,
79    /// A modifier's settings, or what the program keeps about the entry, in
80    /// the program's own format.
81    pub document: Vec<u8>,
82}
83
84impl VolumeEntry {
85    /// Whether the kind is one this version of the format names, and not a
86    /// reserved one.
87    pub fn is_known(&self) -> bool {
88        matches!(
89            self.kind,
90            VOLUME_SUPPORT_ENFORCER
91                | VOLUME_SUPPORT_BLOCKER
92                | VOLUME_MODIFIER
93                | VOLUME_NEGATIVE
94                | VOLUME_UNCUT
95        )
96    }
97
98    /// Whether the entry is a volume, kinds 1 to 4, whose mesh never prints.
99    pub fn is_volume(&self) -> bool {
100        self.is_known() && self.kind != VOLUME_UNCUT
101    }
102}
103
104/// Why a list of volumes could not be encoded.
105#[derive(Clone, Debug, PartialEq, Eq)]
106pub enum EncodeVolumesError {
107    /// A program name breaks the rules of a program name.
108    BadName { program: String },
109    /// A model names a node the scene does not have, or one that is not a
110    /// leaf.
111    NotALeaf,
112    /// An entry names a mesh the scene does not have.
113    NoSuchMesh,
114    /// A leaf shows the mesh of a volume.
115    VolumeShown,
116    /// An uncut model has a transform.
117    UncutMoved,
118    /// A model has negative volumes without exactly one uncut model, or an
119    /// uncut model without negative volumes.
120    UncutCount,
121    /// An entry has a reserved kind, which a writer must not write.
122    ReservedKind,
123    /// There are 2^32 or more entries, or a name or document
124    /// of 4 GiB or more.
125    TooLarge,
126}
127
128impl fmt::Display for EncodeVolumesError {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        match self {
131            Self::BadName { program } => write!(f, "{program:?} is not a program name"),
132            Self::NotALeaf => f.write_str(NOT_A_LEAF),
133            Self::NoSuchMesh => f.write_str(NO_SUCH_MESH),
134            Self::VolumeShown => f.write_str(VOLUME_SHOWN),
135            Self::UncutMoved => f.write_str(UNCUT_MOVED),
136            Self::UncutCount => f.write_str(UNCUT_COUNT),
137            Self::ReservedKind => f.write_str("a volume entry has a reserved kind"),
138            Self::TooLarge => f.write_str("the volumes are too large for their chunk"),
139        }
140    }
141}
142
143impl std::error::Error for EncodeVolumesError {}
144
145/// Why a volume payload could not be decoded.
146#[derive(Clone, Debug, PartialEq, Eq)]
147pub enum DecodeVolumesError {
148    /// The payload is cut short, padded, or not text where text belongs, or
149    /// a program name breaks the rules of a program name.
150    Malformed,
151    /// A model names a node the scene does not have, or one that is not a
152    /// leaf.
153    NotALeaf,
154    /// An entry names a mesh the scene does not have.
155    NoSuchMesh,
156    /// A leaf shows the mesh of a volume.
157    VolumeShown,
158    /// An uncut model has a transform.
159    UncutMoved,
160    /// A model has negative volumes without exactly one uncut model, or an
161    /// uncut model without negative volumes.
162    UncutCount,
163}
164
165impl fmt::Display for DecodeVolumesError {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        match self {
168            Self::Malformed => f.write_str("the volume data is malformed"),
169            Self::NotALeaf => f.write_str(NOT_A_LEAF),
170            Self::NoSuchMesh => f.write_str(NO_SUCH_MESH),
171            Self::VolumeShown => f.write_str(VOLUME_SHOWN),
172            Self::UncutMoved => f.write_str(UNCUT_MOVED),
173            Self::UncutCount => f.write_str(UNCUT_COUNT),
174        }
175    }
176}
177
178impl std::error::Error for DecodeVolumesError {}
179
180const NOT_A_LEAF: &str = "a volume belongs to a scene part that is not a leaf";
181const NO_SUCH_MESH: &str = "a volume names a mesh the file does not have";
182const VOLUME_SHOWN: &str = "a leaf shows the mesh of a volume, which never prints";
183const UNCUT_MOVED: &str = "the uncut model of a volume entry has a transform";
184const UNCUT_COUNT: &str = "a model's negative volumes and its uncut model do not go together";
185
186/// A rule of section 14 that some entries break.
187enum Broken {
188    NotALeaf,
189    NoSuchMesh,
190    VolumeShown,
191    UncutMoved,
192    UncutCount,
193}
194
195impl From<Broken> for EncodeVolumesError {
196    fn from(broken: Broken) -> Self {
197        match broken {
198            Broken::NotALeaf => Self::NotALeaf,
199            Broken::NoSuchMesh => Self::NoSuchMesh,
200            Broken::VolumeShown => Self::VolumeShown,
201            Broken::UncutMoved => Self::UncutMoved,
202            Broken::UncutCount => Self::UncutCount,
203        }
204    }
205}
206
207impl From<Broken> for DecodeVolumesError {
208    fn from(broken: Broken) -> Self {
209        match broken {
210            Broken::NotALeaf => Self::NotALeaf,
211            Broken::NoSuchMesh => Self::NoSuchMesh,
212            Broken::VolumeShown => Self::VolumeShown,
213            Broken::UncutMoved => Self::UncutMoved,
214            Broken::UncutCount => Self::UncutCount,
215        }
216    }
217}
218
219/// The smallest entry: model, kind, mesh, no name, no transform, a program
220/// name of one byte, a version and an empty document.
221const MIN_ENTRY: usize = 4 + 1 + 4 + 1 + 1 + 5 + 4 + 4;
222
223/// Encodes `entries` as a volume payload, in their order, checking them
224/// against `scene`.
225pub fn encode_volumes(
226    entries: &[VolumeEntry],
227    scene: &Scene,
228) -> Result<Vec<u8>, EncodeVolumesError> {
229    if let Some(entry) = entries
230        .iter()
231        .find(|entry| !is_name(entry.program.as_bytes()))
232    {
233        return Err(EncodeVolumesError::BadName {
234            program: entry.program.clone(),
235        });
236    }
237    check(entries, scene)?;
238    if entries.iter().any(|entry| !entry.is_known()) {
239        return Err(EncodeVolumesError::ReservedKind);
240    }
241    let fits = fits_u32(entries.len())
242        && entries.iter().all(|entry| {
243            entry.name.as_ref().is_none_or(|name| fits_u32(name.len()))
244                && fits_u32(entry.document.len())
245        });
246    if !fits {
247        return Err(EncodeVolumesError::TooLarge);
248    }
249    let mut out = Out::default();
250    out.len(entries.len());
251    for entry in entries {
252        // The model and the mesh were checked against the scene, whose
253        // counts fit.
254        out.len(entry.model);
255        out.u8(entry.kind);
256        out.len(entry.mesh);
257        out.text(entry.name.as_deref());
258        write_transform(&mut out, entry.transform.as_ref());
259        out.bytes(entry.program.as_bytes());
260        out.u32(entry.version);
261        out.bytes(&entry.document);
262    }
263    Ok(out.0)
264}
265
266/// Decodes a volume payload, checking it against `scene`, the scene of the
267/// same file.
268pub fn decode_volumes(
269    payload: &[u8],
270    scene: &Scene,
271) -> Result<Vec<VolumeEntry>, DecodeVolumesError> {
272    let mut input = In(payload);
273    let entries = read(&mut input).ok_or(DecodeVolumesError::Malformed)?;
274    if !input.is_empty() {
275        return Err(DecodeVolumesError::Malformed);
276    }
277    check(&entries, scene)?;
278    Ok(entries)
279}
280
281fn read(input: &mut In<'_>) -> Option<Vec<VolumeEntry>> {
282    let count = input.count(MIN_ENTRY)?;
283    let mut entries = Vec::with_capacity(count);
284    for _ in 0..count {
285        let model = input.len()?;
286        let kind = input.u8()?;
287        let mesh = input.len()?;
288        let name = input.text()?;
289        let transform = read_transform(input)?;
290        let program = input.bytes()?;
291        if !is_name(program) {
292            return None;
293        }
294        // A program name is ASCII.
295        let program = String::from_utf8_lossy(program).into_owned();
296        let version = input.u32()?;
297        let document = input.bytes()?.to_vec();
298        entries.push(VolumeEntry {
299            model,
300            kind,
301            mesh,
302            name,
303            transform,
304            program,
305            version,
306            document,
307        });
308    }
309    Some(entries)
310}
311
312/// The rules of section 14 that need only the scene: every model is a leaf
313/// and every mesh exists; no leaf shows a volume; an uncut model has no
314/// transform; and a model has one uncut model exactly when it has negative
315/// volumes.
316fn check(entries: &[VolumeEntry], scene: &Scene) -> Result<(), Broken> {
317    for entry in entries {
318        scene.leaf_mesh(entry.model).ok_or(Broken::NotALeaf)?;
319        if entry.mesh >= scene.meshes.len() {
320            return Err(Broken::NoSuchMesh);
321        }
322    }
323    let shown = shown_meshes(scene);
324    let mut cut = HashSet::new();
325    let mut uncut: HashMap<usize, usize> = HashMap::new();
326    for entry in entries.iter().filter(|entry| entry.is_known()) {
327        if entry.is_volume() && shown.contains(&entry.mesh) {
328            return Err(Broken::VolumeShown);
329        }
330        match entry.kind {
331            VOLUME_NEGATIVE => {
332                cut.insert(entry.model);
333            }
334            VOLUME_UNCUT => {
335                if entry.transform.is_some() {
336                    return Err(Broken::UncutMoved);
337                }
338                *uncut.entry(entry.model).or_default() += 1;
339            }
340            _ => {}
341        }
342    }
343    let one_each = uncut.values().all(|&n| n == 1);
344    let same_models = cut.len() == uncut.len() && cut.iter().all(|model| uncut.contains_key(model));
345    if !one_each || !same_models {
346        return Err(Broken::UncutCount);
347    }
348    Ok(())
349}
350
351/// The meshes a leaf of the scene shows, directly or through a mesh
352/// resource.
353fn shown_meshes(scene: &Scene) -> HashSet<usize> {
354    scene
355        .nodes
356        .iter()
357        .filter_map(|node| match node.kind {
358            NodeKind::Leaf { mesh } => Some(mesh),
359            NodeKind::SharedLeaf { resource } => scene.mesh_resources.get(resource).copied(),
360            _ => None,
361        })
362        .collect()
363}