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