bread-format 0.6.0

Reads and writes .bread files: tiny, lossless meshes and scenes, with room for slicer data such as editable supports.
Documentation
/*
 * SPDX-FileCopyrightText: 2026 SynrgStudio
 * SPDX-License-Identifier: Apache-2.0
 */

//! The volume chunk (`SPEC.md`, section 14): meshes that belong to a model
//! and act on it without being printed. Support enforcers and blockers,
//! modifiers, and negative volumes, which the model's leaf shows already cut,
//! with the model as it was before the cut beside them.
//!
//! A volume's mesh is shown by no leaf, so a reader that skips the chunk
//! never prints it. Reserved kinds are carried as they are: a program treats
//! them as absent. How volumes agree with the supports, hollows and roles is
//! checked where the whole file is read and written.
//!
//! ```text
//! entries   u32 count, then per entry:
//!           u32 the model's leaf, as a node index in the scene chunk
//!           u8  the kind: 1 support enforcer, 2 support blocker,
//!               3 modifier, 4 negative volume, 5 the model before the cut
//!           u32 the entry's mesh, as a mesh index
//!           optional string, the entry's name
//!           u8  has transform; then twelve f64 when it is 1
//!           byte string, the name of the program the entry belongs to
//!           u32 the program's version of the document
//!           byte string, the document
//! ```

use std::collections::{HashMap, HashSet};
use std::fmt;

use crate::bytes::{In, Out, fits_u32};
use crate::container::ChunkTag;
use crate::program::is_name;
use crate::scene::{NodeKind, Scene, Transform, read_transform, write_transform};

/// The tag of the volume chunk.
pub const VOLUME_TAG: ChunkTag = ChunkTag(*b"VOLM");

/// The volume payload layout this build writes and reads.
pub const VOLUME_VERSION: u16 = 1;

/// Supports go where the model's surface inside the volume needs them.
pub const VOLUME_SUPPORT_ENFORCER: u8 = 1;

/// No support touches the model's surface inside the volume.
pub const VOLUME_SUPPORT_BLOCKER: u8 = 2;

/// Inside the volume, the model prints with the settings of the document.
pub const VOLUME_MODIFIER: u8 = 3;

/// The volume was cut away from the model, whose leaf shows it already cut.
pub const VOLUME_NEGATIVE: u8 = 4;

/// The model's mesh before its negative volumes were cut away.
pub const VOLUME_UNCUT: u8 = 5;

/// One entry of the volume chunk.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct VolumeEntry {
    /// The model's leaf, as an index into the scene's nodes.
    pub model: usize,
    /// What the entry is: one of the `VOLUME_*` kinds. Other values are
    /// reserved, carried as they are, and mean nothing.
    pub kind: u8,
    /// The entry's mesh, as an index into the scene's meshes.
    pub mesh: usize,
    /// The entry's name.
    pub name: Option<String>,
    /// From the entry's mesh to the model leaf's own space; `None` is the
    /// identity. An uncut model has none.
    pub transform: Option<Transform>,
    /// The program the entry belongs to, such as `nudl`, by the rules of a
    /// program name ([`crate::is_program_name`]). Every entry has one, even
    /// without a document.
    pub program: String,
    /// The program's own version of `document`.
    pub version: u32,
    /// A modifier's settings, or what the program keeps about the entry, in
    /// the program's own format.
    pub document: Vec<u8>,
}

impl VolumeEntry {
    /// Whether the kind is one this version of the format names, and not a
    /// reserved one.
    pub fn is_known(&self) -> bool {
        matches!(
            self.kind,
            VOLUME_SUPPORT_ENFORCER
                | VOLUME_SUPPORT_BLOCKER
                | VOLUME_MODIFIER
                | VOLUME_NEGATIVE
                | VOLUME_UNCUT
        )
    }

    /// Whether the entry is a volume, kinds 1 to 4, whose mesh never prints.
    pub fn is_volume(&self) -> bool {
        self.is_known() && self.kind != VOLUME_UNCUT
    }
}

/// Why a list of volumes could not be encoded.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EncodeVolumesError {
    /// A program name breaks the rules of a program name.
    BadName { program: String },
    /// A model names a node the scene does not have, or one that is not a
    /// leaf.
    NotALeaf,
    /// An entry names a mesh the scene does not have.
    NoSuchMesh,
    /// A leaf shows the mesh of a volume.
    VolumeShown,
    /// An uncut model has a transform.
    UncutMoved,
    /// A model has negative volumes without exactly one uncut model, or an
    /// uncut model without negative volumes.
    UncutCount,
    /// An entry has a reserved kind, which a writer must not write.
    ReservedKind,
    /// There are 2^32 or more entries, or a name or document
    /// of 4 GiB or more.
    TooLarge,
}

impl fmt::Display for EncodeVolumesError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::BadName { program } => write!(f, "{program:?} is not a program name"),
            Self::NotALeaf => f.write_str(NOT_A_LEAF),
            Self::NoSuchMesh => f.write_str(NO_SUCH_MESH),
            Self::VolumeShown => f.write_str(VOLUME_SHOWN),
            Self::UncutMoved => f.write_str(UNCUT_MOVED),
            Self::UncutCount => f.write_str(UNCUT_COUNT),
            Self::ReservedKind => f.write_str("a volume entry has a reserved kind"),
            Self::TooLarge => f.write_str("the volumes are too large for their chunk"),
        }
    }
}

impl std::error::Error for EncodeVolumesError {}

/// Why a volume payload could not be decoded.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DecodeVolumesError {
    /// The payload is cut short, padded, or not text where text belongs, or
    /// a program name breaks the rules of a program name.
    Malformed,
    /// A model names a node the scene does not have, or one that is not a
    /// leaf.
    NotALeaf,
    /// An entry names a mesh the scene does not have.
    NoSuchMesh,
    /// A leaf shows the mesh of a volume.
    VolumeShown,
    /// An uncut model has a transform.
    UncutMoved,
    /// A model has negative volumes without exactly one uncut model, or an
    /// uncut model without negative volumes.
    UncutCount,
}

impl fmt::Display for DecodeVolumesError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Malformed => f.write_str("the volume data is malformed"),
            Self::NotALeaf => f.write_str(NOT_A_LEAF),
            Self::NoSuchMesh => f.write_str(NO_SUCH_MESH),
            Self::VolumeShown => f.write_str(VOLUME_SHOWN),
            Self::UncutMoved => f.write_str(UNCUT_MOVED),
            Self::UncutCount => f.write_str(UNCUT_COUNT),
        }
    }
}

impl std::error::Error for DecodeVolumesError {}

const NOT_A_LEAF: &str = "a volume belongs to a scene part that is not a leaf";
const NO_SUCH_MESH: &str = "a volume names a mesh the file does not have";
const VOLUME_SHOWN: &str = "a leaf shows the mesh of a volume, which never prints";
const UNCUT_MOVED: &str = "the uncut model of a volume entry has a transform";
const UNCUT_COUNT: &str = "a model's negative volumes and its uncut model do not go together";

/// A rule of section 14 that some entries break.
enum Broken {
    NotALeaf,
    NoSuchMesh,
    VolumeShown,
    UncutMoved,
    UncutCount,
}

impl From<Broken> for EncodeVolumesError {
    fn from(broken: Broken) -> Self {
        match broken {
            Broken::NotALeaf => Self::NotALeaf,
            Broken::NoSuchMesh => Self::NoSuchMesh,
            Broken::VolumeShown => Self::VolumeShown,
            Broken::UncutMoved => Self::UncutMoved,
            Broken::UncutCount => Self::UncutCount,
        }
    }
}

impl From<Broken> for DecodeVolumesError {
    fn from(broken: Broken) -> Self {
        match broken {
            Broken::NotALeaf => Self::NotALeaf,
            Broken::NoSuchMesh => Self::NoSuchMesh,
            Broken::VolumeShown => Self::VolumeShown,
            Broken::UncutMoved => Self::UncutMoved,
            Broken::UncutCount => Self::UncutCount,
        }
    }
}

/// The smallest entry: model, kind, mesh, no name, no transform, a program
/// name of one byte, a version and an empty document.
const MIN_ENTRY: usize = 4 + 1 + 4 + 1 + 1 + 5 + 4 + 4;

/// Encodes `entries` as a volume payload, in their order, checking them
/// against `scene`.
pub fn encode_volumes(
    entries: &[VolumeEntry],
    scene: &Scene,
) -> Result<Vec<u8>, EncodeVolumesError> {
    if let Some(entry) = entries
        .iter()
        .find(|entry| !is_name(entry.program.as_bytes()))
    {
        return Err(EncodeVolumesError::BadName {
            program: entry.program.clone(),
        });
    }
    check(entries, scene)?;
    if entries.iter().any(|entry| !entry.is_known()) {
        return Err(EncodeVolumesError::ReservedKind);
    }
    let fits = fits_u32(entries.len())
        && entries.iter().all(|entry| {
            entry.name.as_ref().is_none_or(|name| fits_u32(name.len()))
                && fits_u32(entry.document.len())
        });
    if !fits {
        return Err(EncodeVolumesError::TooLarge);
    }
    let mut out = Out::default();
    out.len(entries.len());
    for entry in entries {
        // The model and the mesh were checked against the scene, whose
        // counts fit.
        out.len(entry.model);
        out.u8(entry.kind);
        out.len(entry.mesh);
        out.text(entry.name.as_deref());
        write_transform(&mut out, entry.transform.as_ref());
        out.bytes(entry.program.as_bytes());
        out.u32(entry.version);
        out.bytes(&entry.document);
    }
    Ok(out.0)
}

/// Decodes a volume payload, checking it against `scene`, the scene of the
/// same file.
pub fn decode_volumes(
    payload: &[u8],
    scene: &Scene,
) -> Result<Vec<VolumeEntry>, DecodeVolumesError> {
    let mut input = In(payload);
    let entries = read(&mut input).ok_or(DecodeVolumesError::Malformed)?;
    if !input.is_empty() {
        return Err(DecodeVolumesError::Malformed);
    }
    check(&entries, scene)?;
    Ok(entries)
}

fn read(input: &mut In<'_>) -> Option<Vec<VolumeEntry>> {
    let count = input.count(MIN_ENTRY)?;
    let mut entries = Vec::with_capacity(count);
    for _ in 0..count {
        let model = input.len()?;
        let kind = input.u8()?;
        let mesh = input.len()?;
        let name = input.text()?;
        let transform = read_transform(input)?;
        let program = input.bytes()?;
        if !is_name(program) {
            return None;
        }
        // A program name is ASCII.
        let program = String::from_utf8_lossy(program).into_owned();
        let version = input.u32()?;
        let document = input.bytes()?.to_vec();
        entries.push(VolumeEntry {
            model,
            kind,
            mesh,
            name,
            transform,
            program,
            version,
            document,
        });
    }
    Some(entries)
}

/// The rules of section 14 that need only the scene: every model is a leaf
/// and every mesh exists; no leaf shows a volume; an uncut model has no
/// transform; and a model has one uncut model exactly when it has negative
/// volumes.
fn check(entries: &[VolumeEntry], scene: &Scene) -> Result<(), Broken> {
    for entry in entries {
        scene.leaf_mesh(entry.model).ok_or(Broken::NotALeaf)?;
        if entry.mesh >= scene.meshes.len() {
            return Err(Broken::NoSuchMesh);
        }
    }
    let shown = shown_meshes(scene);
    let mut cut = HashSet::new();
    let mut uncut: HashMap<usize, usize> = HashMap::new();
    for entry in entries.iter().filter(|entry| entry.is_known()) {
        if entry.is_volume() && shown.contains(&entry.mesh) {
            return Err(Broken::VolumeShown);
        }
        match entry.kind {
            VOLUME_NEGATIVE => {
                cut.insert(entry.model);
            }
            VOLUME_UNCUT => {
                if entry.transform.is_some() {
                    return Err(Broken::UncutMoved);
                }
                *uncut.entry(entry.model).or_default() += 1;
            }
            _ => {}
        }
    }
    let one_each = uncut.values().all(|&n| n == 1);
    let same_models = cut.len() == uncut.len() && cut.iter().all(|model| uncut.contains_key(model));
    if !one_each || !same_models {
        return Err(Broken::UncutCount);
    }
    Ok(())
}

/// The meshes a leaf of the scene shows, directly or through a mesh
/// resource.
fn shown_meshes(scene: &Scene) -> HashSet<usize> {
    scene
        .nodes
        .iter()
        .filter_map(|node| match node.kind {
            NodeKind::Leaf { mesh } => Some(mesh),
            NodeKind::SharedLeaf { resource } => scene.mesh_resources.get(resource).copied(),
            _ => None,
        })
        .collect()
}