Skip to main content

bread_format/
surface.rs

1/*
2 * SPDX-FileCopyrightText: 2026 SynrgStudio
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! The surface paint chunk (`SPEC.md`, section 10): what a person painted on
7//! the faces of models, one mask per program, leaf and kind.
8//!
9//! Each entry names the program it belongs to, so that one program's paint
10//! never mixes with another's: a program changes and drops only its own
11//! entries. Chunk version 1, which named no program, is still read.
12//!
13//! Only the envelope is checked: each entry names a program and a leaf, and
14//! no two entries share a program, a leaf and a kind. Documents are carried
15//! without being read, since a document never makes a file unreadable; the
16//! program that uses the paint checks it against the leaf's mesh, with
17//! [`SurfaceEntry::paint`] or the codecs of [`crate::paint`].
18//!
19//! ```text
20//! entries   u32 count, then per entry:
21//!           u32 length, the program's name (not in chunk version 1)
22//!           u32 the leaf's node index in the scene chunk
23//!           u8  the kind: 0 detail, 1 supports must touch, 2 must not touch,
24//!               3 supports both ways
25//!           u32 document version
26//!           u32 length, document
27//! ```
28
29use std::collections::HashSet;
30use std::fmt;
31
32use crate::bytes::{In, Out, fits_u32};
33use crate::container::ChunkTag;
34use crate::program::is_name;
35use crate::scene::Scene;
36
37/// The tag of the surface paint chunk.
38pub const SURFACE_TAG: ChunkTag = ChunkTag(*b"SURF");
39
40/// The surface paint payload layout this build writes. It reads version 1
41/// too.
42pub const SURFACE_VERSION: u16 = 2;
43
44/// One painted mask of one leaf.
45#[derive(Clone, Debug, Default, PartialEq, Eq)]
46pub struct SurfaceEntry {
47    /// The program the paint belongs to, such as `nudl`, by the rules of a
48    /// program name ([`crate::is_program_name`]). `None` only for an entry
49    /// read from chunk version 1, which named no program: a program that
50    /// writes it back names the program that painted it, if it knows it, and
51    /// otherwise itself.
52    pub program: Option<String>,
53    /// The painted leaf, as an index into the scene's nodes.
54    pub leaf: usize,
55    /// What the paint means: 0 detail, 1 supports must touch, 2 supports
56    /// must not touch, 3 supports both ways (see [`crate::paint`]). Other
57    /// values are reserved, and carried as they are.
58    pub kind: u8,
59    /// The version of the document.
60    pub version: u32,
61    /// The mask, carried without being read.
62    pub document: Vec<u8>,
63}
64
65/// Why a list of paint entries could not be encoded.
66#[derive(Clone, Debug, PartialEq, Eq)]
67pub enum EncodeSurfaceError {
68    /// An entry names no program: it was read from chunk version 1.
69    NoProgram,
70    /// A program name breaks the rules of a program name.
71    BadName { program: String },
72    /// An entry names a node the scene does not have, or one that is not a
73    /// leaf.
74    NotALeaf,
75    /// Two entries have the same program, leaf and kind.
76    SameEntry,
77    /// There are 2^32 or more entries, or a document of 4 GiB or more.
78    TooLarge,
79}
80
81impl fmt::Display for EncodeSurfaceError {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        match self {
84            Self::NoProgram => f.write_str("a surface paint entry names no program"),
85            Self::BadName { program } => write!(f, "{program:?} is not a program name"),
86            Self::NotALeaf => f.write_str(NOT_A_LEAF),
87            Self::SameEntry => f.write_str(SAME_ENTRY),
88            Self::TooLarge => f.write_str("the surface paint is too large for its chunk"),
89        }
90    }
91}
92
93impl std::error::Error for EncodeSurfaceError {}
94
95/// Why a surface paint payload could not be decoded.
96#[derive(Clone, Debug, PartialEq, Eq)]
97pub enum DecodeSurfaceError {
98    /// The payload is cut short or padded, or a program name breaks the
99    /// rules of a program name.
100    Malformed,
101    /// An entry names a node the scene does not have, or one that is not a
102    /// leaf.
103    NotALeaf,
104    /// Two entries have the same program, leaf and kind.
105    SameEntry,
106}
107
108impl fmt::Display for DecodeSurfaceError {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        match self {
111            Self::Malformed => f.write_str("the surface paint data is malformed"),
112            Self::NotALeaf => f.write_str(NOT_A_LEAF),
113            Self::SameEntry => f.write_str(SAME_ENTRY),
114        }
115    }
116}
117
118impl std::error::Error for DecodeSurfaceError {}
119
120const NOT_A_LEAF: &str = "surface paint names a scene part that is not a leaf";
121const SAME_ENTRY: &str = "two surface paint entries have the same program, leaf and kind";
122
123/// A rule of section 10 that some entries break.
124enum Broken {
125    NotALeaf,
126    SameEntry,
127}
128
129impl From<Broken> for EncodeSurfaceError {
130    fn from(broken: Broken) -> Self {
131        match broken {
132            Broken::NotALeaf => Self::NotALeaf,
133            Broken::SameEntry => Self::SameEntry,
134        }
135    }
136}
137
138impl From<Broken> for DecodeSurfaceError {
139    fn from(broken: Broken) -> Self {
140        match broken {
141            Broken::NotALeaf => Self::NotALeaf,
142            Broken::SameEntry => Self::SameEntry,
143        }
144    }
145}
146
147/// Encodes `entries` as a surface paint payload of version
148/// [`SURFACE_VERSION`], in their order, checking them against `scene`. Every
149/// entry names its program.
150pub fn encode_surface(
151    entries: &[SurfaceEntry],
152    scene: &Scene,
153) -> Result<Vec<u8>, EncodeSurfaceError> {
154    for entry in entries {
155        let program = entry
156            .program
157            .as_ref()
158            .ok_or(EncodeSurfaceError::NoProgram)?;
159        if !is_name(program.as_bytes()) {
160            return Err(EncodeSurfaceError::BadName {
161                program: program.clone(),
162            });
163        }
164    }
165    check(entries, scene)?;
166    if !fits_u32(entries.len()) || entries.iter().any(|entry| !fits_u32(entry.document.len())) {
167        return Err(EncodeSurfaceError::TooLarge);
168    }
169    let mut out = Out::default();
170    out.len(entries.len());
171    for entry in entries {
172        // The program was checked above.
173        out.bytes(entry.program.as_deref().unwrap_or_default().as_bytes());
174        // The leaf was checked against the scene, whose node count fits.
175        out.len(entry.leaf);
176        out.u8(entry.kind);
177        out.u32(entry.version);
178        out.bytes(&entry.document);
179    }
180    Ok(out.0)
181}
182
183/// Decodes a surface paint payload of version [`SURFACE_VERSION`], checking
184/// it against `scene`, the scene of the same file.
185pub fn decode_surface(
186    payload: &[u8],
187    scene: &Scene,
188) -> Result<Vec<SurfaceEntry>, DecodeSurfaceError> {
189    decode(payload, scene, true)
190}
191
192/// Decodes a surface paint payload of version 1, whose entries name no
193/// program, checking it against `scene`, the scene of the same file.
194pub fn decode_surface_v1(
195    payload: &[u8],
196    scene: &Scene,
197) -> Result<Vec<SurfaceEntry>, DecodeSurfaceError> {
198    decode(payload, scene, false)
199}
200
201/// Decodes a payload whose entries name their program when `named`.
202fn decode(
203    payload: &[u8],
204    scene: &Scene,
205    named: bool,
206) -> Result<Vec<SurfaceEntry>, DecodeSurfaceError> {
207    let mut input = In(payload);
208    let malformed = DecodeSurfaceError::Malformed;
209    // The smallest entry: a program name of one byte when there is one, the
210    // leaf, the kind, the version and an empty document.
211    let smallest = if named { 18 } else { 13 };
212    let count = input.count(smallest).ok_or(malformed.clone())?;
213    let mut entries = Vec::with_capacity(count);
214    for _ in 0..count {
215        let program = if named {
216            let name = input.bytes().ok_or(malformed.clone())?;
217            if !is_name(name) {
218                return Err(malformed);
219            }
220            // A program name is ASCII.
221            Some(String::from_utf8_lossy(name).into_owned())
222        } else {
223            None
224        };
225        let leaf = input.len().ok_or(malformed.clone())?;
226        let kind = input.u8().ok_or(malformed.clone())?;
227        let version = input.u32().ok_or(malformed.clone())?;
228        let document = input.bytes().ok_or(malformed.clone())?.to_vec();
229        entries.push(SurfaceEntry {
230            program,
231            leaf,
232            kind,
233            version,
234            document,
235        });
236    }
237    if !input.is_empty() {
238        return Err(malformed);
239    }
240    check(&entries, scene)?;
241    Ok(entries)
242}
243
244/// Every entry names a leaf, and no two share a program, a leaf and a kind.
245/// The entries of chunk version 1 name no program, so no two of them share a
246/// leaf and a kind.
247fn check(entries: &[SurfaceEntry], scene: &Scene) -> Result<(), Broken> {
248    let mut seen = HashSet::new();
249    for entry in entries {
250        scene.leaf_mesh(entry.leaf).ok_or(Broken::NotALeaf)?;
251        if !seen.insert((entry.program.as_deref(), entry.leaf, entry.kind)) {
252            return Err(Broken::SameEntry);
253        }
254    }
255    Ok(())
256}