Skip to main content

bread_format/
file.rs

1/*
2 * SPDX-FileCopyrightText: 2026 SynrgStudio
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! A whole `.bread` file: the thumbnail when there is one, the scene chunk,
7//! the project settings, the supports, the hollows and the surface paint when
8//! there are any, then one mesh chunk per mesh of the scene, in its order, and
9//! last the support previews when there are any.
10//!
11//! Reading skips the chunks this build does not know, official or private,
12//! and writing leaves them out, as section 7.2 allows. It also skips supports
13//! and hollows chunks of version 1, which only drafts of the format wrote, as
14//! section 7.3 allows: their models open without editable supports, and their
15//! hollows without the original. The support previews of draft supports are
16//! skipped with them, since they could not be checked against the supports.
17
18use std::fmt;
19use std::io::{self, Read, Write};
20
21use crate::app::{
22    DecodeDocumentsError, EncodeDocumentsError, HOLLOWS_TAG, HOLLOWS_VERSION, HollowEntry,
23    SETTINGS_TAG, SETTINGS_VERSION, SUPPORTS_TAG, SUPPORTS_VERSION, SupportEntry, decode_hollows,
24    decode_supports, encode_hollows, encode_supports,
25};
26use crate::container::{BreadReader, BreadWriter, ChunkTag, ReadBreadError};
27use crate::mesh::{DecodeMeshError, EncodeMeshError, MESH_TAG, MESH_VERSION, Mesh, decode_mesh};
28use crate::mesh_v2::{decode_mesh_v2, encode_mesh_v2};
29use crate::parallel;
30use crate::preview::{
31    DecodePreviewsError, EncodePreviewsError, SUPPORT_PREVIEW_TAG, SUPPORT_PREVIEW_VERSION,
32    SupportPreview, decode_previews, encode_previews,
33};
34use crate::scene::{
35    DecodeSceneError, EncodeSceneError, SCENE_TAG, SCENE_VERSION, Scene, decode_scene, encode_scene,
36};
37use crate::surface::{
38    DecodeSurfaceError, EncodeSurfaceError, SURFACE_TAG, SURFACE_VERSION, SurfaceEntry,
39    decode_surface, encode_surface,
40};
41
42/// The tag of the thumbnail chunk, whose payload is a PNG file. Section 8
43/// asks writers to put it first, so a program that only wants the picture
44/// reads one chunk.
45pub const THUMBNAIL_TAG: ChunkTag = ChunkTag(*b"THMB");
46
47/// The thumbnail chunk version this build writes and reads.
48pub const THUMBNAIL_VERSION: u16 = 1;
49
50/// What a `.bread` file holds.
51#[derive(Clone, Debug, Default, PartialEq)]
52pub struct BreadFile {
53    /// The scene and its meshes.
54    pub scene: Scene,
55    /// The project settings document, carried without being read.
56    pub settings: Option<Vec<u8>>,
57    /// Supports kept as data. Their support leaves show an empty mesh.
58    pub supports: Vec<SupportEntry>,
59    /// How hollowed models were made. Their leaves show the hollow.
60    pub hollows: Vec<HollowEntry>,
61    /// A small picture of the file: a PNG, at most 512 x 512 and best
62    /// 256 x 256, in sRGB. It is carried without being read: the PNG is
63    /// neither checked nor decoded.
64    pub thumbnail: Option<Vec<u8>>,
65    /// The mesh of the supports, for readers that do not rebuild them from
66    /// their documents. Each preview names the support leaf of an entry of
67    /// `supports`. A program that edits the supports writes new previews, or
68    /// none.
69    pub support_previews: Vec<SupportPreview>,
70    /// What was painted on the faces of leaves: one mask per leaf and kind,
71    /// each document carried without being read.
72    pub surface: Vec<SurfaceEntry>,
73}
74
75/// Why a file could not be written.
76#[derive(Debug)]
77pub enum WriteFileError {
78    Io(io::Error),
79    Scene(EncodeSceneError),
80    Mesh(EncodeMeshError),
81    Supports(EncodeDocumentsError),
82    Hollows(EncodeDocumentsError),
83    Previews(EncodePreviewsError),
84    Surface(EncodeSurfaceError),
85    /// A support leaf shows a mesh with vertices or triangles: support
86    /// leaves are stored with an empty mesh.
87    SupportMeshNotEmpty {
88        leaf: usize,
89    },
90    /// A support leaf is also a hollowed model.
91    SupportIsHollowed {
92        leaf: usize,
93    },
94    /// A support preview names a leaf that no supports entry shows.
95    PreviewWithoutSupports {
96        leaf: usize,
97    },
98}
99
100impl fmt::Display for WriteFileError {
101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102        match self {
103            Self::Io(err) => write!(f, "{err}"),
104            Self::Scene(err) => write!(f, "{err}"),
105            Self::Mesh(err) => write!(f, "{err}"),
106            Self::Supports(err) | Self::Hollows(err) => write!(f, "{err}"),
107            Self::Previews(err) => write!(f, "{err}"),
108            Self::Surface(err) => write!(f, "{err}"),
109            Self::SupportMeshNotEmpty { leaf } => {
110                write!(
111                    f,
112                    "the support leaf {leaf} shows a mesh instead of an empty one"
113                )
114            }
115            Self::SupportIsHollowed { leaf } => write!(f, "{}", SupportIsHollowed(*leaf)),
116            Self::PreviewWithoutSupports { leaf } => {
117                write!(f, "{}", PreviewWithoutSupports(*leaf))
118            }
119        }
120    }
121}
122
123impl std::error::Error for WriteFileError {}
124
125impl From<io::Error> for WriteFileError {
126    fn from(err: io::Error) -> Self {
127        Self::Io(err)
128    }
129}
130
131/// Why a `.bread` file could not be read.
132#[derive(Debug)]
133pub enum ReadFileError {
134    File(ReadBreadError),
135    /// A chunk this build reads has a version it does not read: a newer one,
136    /// or 0, which no version is.
137    ChunkVersion {
138        tag: ChunkTag,
139        version: u16,
140    },
141    /// The file holds a number of chunks of one tag that the format does not
142    /// allow: no scene chunk, or two of a chunk that comes at most once.
143    ChunkCount {
144        tag: ChunkTag,
145        count: usize,
146    },
147    Mesh(DecodeMeshError),
148    Scene(DecodeSceneError),
149    Supports(DecodeDocumentsError),
150    Hollows(DecodeDocumentsError),
151    Previews(DecodePreviewsError),
152    Surface(DecodeSurfaceError),
153    /// A support leaf is also a hollowed model.
154    SupportIsHollowed {
155        leaf: usize,
156    },
157    /// A support preview names a leaf that no supports entry shows.
158    PreviewWithoutSupports {
159        leaf: usize,
160    },
161}
162
163impl fmt::Display for ReadFileError {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        match self {
166            Self::File(err) => write!(f, "{err}"),
167            Self::ChunkVersion { tag, version: 0 } => {
168                write!(f, "the {tag} chunk has version 0, which does not exist")
169            }
170            Self::ChunkVersion { tag, version } => {
171                write!(
172                    f,
173                    "the {tag} chunk is written in a newer version ({version})"
174                )
175            }
176            Self::ChunkCount { tag, count } => write!(f, "the file holds {count} {tag} chunks"),
177            Self::Mesh(err) => write!(f, "{err}"),
178            Self::Scene(err) => write!(f, "{err}"),
179            Self::Supports(err) | Self::Hollows(err) => write!(f, "{err}"),
180            Self::Previews(err) => write!(f, "{err}"),
181            Self::Surface(err) => write!(f, "{err}"),
182            Self::SupportIsHollowed { leaf } => write!(f, "{}", SupportIsHollowed(*leaf)),
183            Self::PreviewWithoutSupports { leaf } => {
184                write!(f, "{}", PreviewWithoutSupports(*leaf))
185            }
186        }
187    }
188}
189
190impl std::error::Error for ReadFileError {}
191
192/// The message of both `SupportIsHollowed` errors.
193struct SupportIsHollowed(usize);
194
195impl fmt::Display for SupportIsHollowed {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        write!(f, "the support leaf {} is also a hollowed model", self.0)
198    }
199}
200
201/// The message of both `PreviewWithoutSupports` errors.
202struct PreviewWithoutSupports(usize);
203
204impl fmt::Display for PreviewWithoutSupports {
205    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206        write!(
207            f,
208            "the support preview of leaf {} has no supports entry",
209            self.0
210        )
211    }
212}
213
214impl From<ReadBreadError> for ReadFileError {
215    fn from(err: ReadBreadError) -> Self {
216        Self::File(err)
217    }
218}
219
220/// The newest version of the chunk `tag` this build reads, or `None` for a
221/// tag it does not know, which a reader skips. Every version from 1 up to it
222/// is read, though older supports and hollows chunks are skipped; any other
223/// version makes the file unreadable.
224pub fn supported_version(tag: ChunkTag) -> Option<u16> {
225    Some(match tag {
226        THUMBNAIL_TAG => THUMBNAIL_VERSION,
227        SCENE_TAG => SCENE_VERSION,
228        SETTINGS_TAG => SETTINGS_VERSION,
229        SUPPORTS_TAG => SUPPORTS_VERSION,
230        HOLLOWS_TAG => HOLLOWS_VERSION,
231        MESH_TAG => MESH_VERSION,
232        SUPPORT_PREVIEW_TAG => SUPPORT_PREVIEW_VERSION,
233        SURFACE_TAG => SURFACE_VERSION,
234        _ => return None,
235    })
236}
237
238/// Writes `file` as a `.bread` file to `out`, handing `out` back. When it
239/// fails, what it wrote to `out` is not a valid file.
240pub fn write_file<W: Write>(file: &BreadFile, out: W) -> Result<W, WriteFileError> {
241    let scene = &file.scene;
242    let scene_payload = encode_scene(scene).map_err(WriteFileError::Scene)?;
243    let supports = encode_supports(&file.supports, scene).map_err(WriteFileError::Supports)?;
244    let hollows = encode_hollows(&file.hollows, scene).map_err(WriteFileError::Hollows)?;
245    let previews =
246        encode_previews(&file.support_previews, scene).map_err(WriteFileError::Previews)?;
247    let surface = encode_surface(&file.surface, scene).map_err(WriteFileError::Surface)?;
248    for entry in &file.supports {
249        let leaf = entry.support;
250        if scene
251            .leaf_mesh(leaf)
252            .is_some_and(|mesh| !mesh.vertices.is_empty() || !mesh.triangles.is_empty())
253        {
254            return Err(WriteFileError::SupportMeshNotEmpty { leaf });
255        }
256    }
257    if let Some(leaf) = hollowed_support(&file.supports, &file.hollows) {
258        return Err(WriteFileError::SupportIsHollowed { leaf });
259    }
260    if let Some(leaf) = unsupported_preview(&file.support_previews, &file.supports) {
261        return Err(WriteFileError::PreviewWithoutSupports { leaf });
262    }
263    // Each mesh is encoded on its own, so they are encoded side by side.
264    let meshes: Vec<Vec<u8>> = parallel::map(&scene.meshes, encode_mesh_v2)
265        .into_iter()
266        .collect::<Result<_, _>>()
267        .map_err(WriteFileError::Mesh)?;
268
269    let mut writer = BreadWriter::new(out)?;
270    if let Some(thumbnail) = &file.thumbnail {
271        writer.chunk(THUMBNAIL_TAG, THUMBNAIL_VERSION, thumbnail)?;
272    }
273    writer.chunk(SCENE_TAG, SCENE_VERSION, &scene_payload)?;
274    if let Some(settings) = &file.settings {
275        writer.chunk(SETTINGS_TAG, SETTINGS_VERSION, settings)?;
276    }
277    if !file.supports.is_empty() {
278        writer.chunk(SUPPORTS_TAG, SUPPORTS_VERSION, &supports)?;
279    }
280    if !file.hollows.is_empty() {
281        writer.chunk(HOLLOWS_TAG, HOLLOWS_VERSION, &hollows)?;
282    }
283    if !file.surface.is_empty() {
284        writer.chunk(SURFACE_TAG, SURFACE_VERSION, &surface)?;
285    }
286    for payload in &meshes {
287        writer.chunk(MESH_TAG, MESH_VERSION, payload)?;
288    }
289    if !file.support_previews.is_empty() {
290        writer.chunk(SUPPORT_PREVIEW_TAG, SUPPORT_PREVIEW_VERSION, &previews)?;
291    }
292    Ok(writer.finish()?)
293}
294
295/// Mesh payloads smaller than this are decoded where they are read: a thread
296/// of their own would cost more than it saves.
297const MESH_ON_ITS_OWN_THREAD: usize = 1 << 16;
298
299/// A mesh chunk being decoded, or decoded already.
300enum PendingMesh<'scope> {
301    Done(Result<Mesh, DecodeMeshError>),
302    Running(std::thread::ScopedJoinHandle<'scope, Result<Mesh, DecodeMeshError>>),
303}
304
305impl PendingMesh<'_> {
306    fn finish(self) -> Result<Mesh, DecodeMeshError> {
307        match self {
308            Self::Done(mesh) => mesh,
309            Self::Running(handle) => handle
310                .join()
311                .unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
312        }
313    }
314}
315
316fn decode_mesh_chunk(version: u16, payload: &[u8]) -> Result<Mesh, DecodeMeshError> {
317    match version {
318        1 => decode_mesh(payload),
319        _ => decode_mesh_v2(payload),
320    }
321}
322
323/// Reads the `.bread` file in `input`.
324///
325/// Large meshes are decoded on threads of their own while the rest of the
326/// file is read. A file is refused for the same reason as if every chunk
327/// were read in order: the first fault in file order.
328pub fn read_file<R: Read>(input: R) -> Result<BreadFile, ReadFileError> {
329    let mut reader = BreadReader::new(input)?;
330    std::thread::scope(|scope| read_chunks(&mut reader, scope))
331}
332
333fn read_chunks<'scope, R: Read>(
334    reader: &mut BreadReader<R>,
335    scope: &'scope std::thread::Scope<'scope, '_>,
336) -> Result<BreadFile, ReadFileError> {
337    let (mut thumbnails, mut scenes, mut settings, mut supports, mut hollows, mut previews) = (
338        Vec::new(),
339        Vec::new(),
340        Vec::new(),
341        Vec::new(),
342        Vec::new(),
343        Vec::new(),
344    );
345    let mut surfaces = Vec::new();
346    let mut pending: Vec<PendingMesh<'scope>> = Vec::new();
347    let mut running = std::collections::VecDeque::new();
348    let threads = parallel::threads();
349    let mut read_all = || -> Result<(), ReadFileError> {
350        while let Some(chunk) = reader.next_chunk()? {
351            let Some(supported) = supported_version(chunk.tag) else {
352                continue;
353            };
354            if chunk.version == 0 || chunk.version > supported {
355                return Err(ReadFileError::ChunkVersion {
356                    tag: chunk.tag,
357                    version: chunk.version,
358                });
359            }
360            // An older supports or hollows chunk is a draft one: it still counts
361            // as the one chunk of its tag, but its payload is not read.
362            let current = chunk.version == supported;
363            match chunk.tag {
364                THUMBNAIL_TAG => thumbnails.push(chunk.payload),
365                SCENE_TAG => scenes.push(chunk.payload),
366                SETTINGS_TAG => settings.push(chunk.payload),
367                SUPPORTS_TAG => supports.push(current.then_some(chunk.payload)),
368                HOLLOWS_TAG => hollows.push(current.then_some(chunk.payload)),
369                SUPPORT_PREVIEW_TAG => previews.push(chunk.payload),
370                SURFACE_TAG => surfaces.push(chunk.payload),
371                _ => {
372                    let (version, payload) = (chunk.version, chunk.payload);
373                    if threads < 2 || payload.len() < MESH_ON_ITS_OWN_THREAD {
374                        pending.push(PendingMesh::Done(decode_mesh_chunk(version, &payload)));
375                        continue;
376                    }
377                    // At most as many meshes at once as the machine runs threads.
378                    if running.len() >= threads {
379                        let oldest: usize = running.pop_front().expect("one is running");
380                        let mesh = std::mem::replace(
381                            &mut pending[oldest],
382                            PendingMesh::Done(Err(DecodeMeshError::Malformed)),
383                        );
384                        pending[oldest] = PendingMesh::Done(mesh.finish());
385                    }
386                    running.push_back(pending.len());
387                    pending.push(PendingMesh::Running(
388                        scope.spawn(move || decode_mesh_chunk(version, &payload)),
389                    ));
390                }
391            }
392        }
393        Ok(())
394    };
395    let read = read_all();
396    // A mesh refused comes before any fault found after it in the file, as
397    // when each mesh is decoded the moment it is read.
398    let meshes = pending
399        .into_iter()
400        .map(PendingMesh::finish)
401        .collect::<Result<Vec<_>, _>>()
402        .map_err(ReadFileError::Mesh)?;
403    read?;
404    let scene = single(SCENE_TAG, scenes)?.ok_or(ReadFileError::ChunkCount {
405        tag: SCENE_TAG,
406        count: 0,
407    })?;
408    let thumbnail = single(THUMBNAIL_TAG, thumbnails)?;
409    let settings = single(SETTINGS_TAG, settings)?;
410    let supports = single(SUPPORTS_TAG, supports)?;
411    let draft_supports = matches!(supports, Some(None));
412    let supports = supports.flatten();
413    let hollows = single(HOLLOWS_TAG, hollows)?.flatten();
414    let previews = single(SUPPORT_PREVIEW_TAG, previews)?;
415    let surface = single(SURFACE_TAG, surfaces)?;
416
417    let scene = decode_scene(&scene, meshes).map_err(ReadFileError::Scene)?;
418    let supports = match supports {
419        None => Vec::new(),
420        Some(payload) => decode_supports(&payload, &scene).map_err(ReadFileError::Supports)?,
421    };
422    let hollows = match hollows {
423        None => Vec::new(),
424        Some(payload) => decode_hollows(&payload, &scene).map_err(ReadFileError::Hollows)?,
425    };
426    if let Some(leaf) = hollowed_support(&supports, &hollows) {
427        return Err(ReadFileError::SupportIsHollowed { leaf });
428    }
429    let support_previews = match previews {
430        Some(payload) if !draft_supports => {
431            decode_previews(&payload, &scene).map_err(ReadFileError::Previews)?
432        }
433        _ => Vec::new(),
434    };
435    if let Some(leaf) = unsupported_preview(&support_previews, &supports) {
436        return Err(ReadFileError::PreviewWithoutSupports { leaf });
437    }
438    let surface = match surface {
439        None => Vec::new(),
440        Some(payload) => decode_surface(&payload, &scene).map_err(ReadFileError::Surface)?,
441    };
442    Ok(BreadFile {
443        scene,
444        settings,
445        supports,
446        hollows,
447        thumbnail,
448        support_previews,
449        surface,
450    })
451}
452
453/// A support leaf that is also the model of a hollow, which section 7.3
454/// forbids across the two chunks.
455fn hollowed_support(supports: &[SupportEntry], hollows: &[HollowEntry]) -> Option<usize> {
456    supports
457        .iter()
458        .map(|entry| entry.support)
459        .find(|&leaf| hollows.iter().any(|hollow| hollow.model == leaf))
460}
461
462/// A preview's leaf that is not the support leaf of any supports entry,
463/// which section 9 forbids.
464fn unsupported_preview(previews: &[SupportPreview], supports: &[SupportEntry]) -> Option<usize> {
465    previews
466        .iter()
467        .map(|preview| preview.leaf)
468        .find(|&leaf| !supports.iter().any(|entry| entry.support == leaf))
469}
470
471/// The chunk of a tag that comes at most once.
472fn single<T>(tag: ChunkTag, chunks: Vec<T>) -> Result<Option<T>, ReadFileError> {
473    if chunks.len() > 1 {
474        return Err(ReadFileError::ChunkCount {
475            tag,
476            count: chunks.len(),
477        });
478    }
479    Ok(chunks.into_iter().next())
480}