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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
/*
 * SPDX-FileCopyrightText: 2026 SynrgStudio
 * SPDX-License-Identifier: Apache-2.0
 */

//! A whole `.bread` file: the thumbnail when there is one, the scene chunk,
//! the metadata when there is any, the project settings, the supports, the
//! hollows, the program data and the surface paint when there are any, the
//! roles of leaves that are not models, the volumes that act on models when
//! there are any, then one mesh chunk per mesh of the scene, in its order, the
//! support previews when there are any, and last the chunks this build does
//! not know.
//!
//! Reading keeps the chunks this build does not know, official or private, as
//! they are, and writing writes them back at the end, in their order: a
//! program that opens a file and saves it does not drop other programs'
//! chunks. A program that changes the scene should drop them, since they may
//! name nodes or meshes by an index that changed (section 7.2). Reading skips
//! a chunk whose tag is not four ASCII letters or digits starting with a
//! letter, which no writer may write. It also skips supports
//! and hollows chunks of version 1, which only drafts of the format wrote, as
//! section 7.3 allows: their models open without editable supports, and their
//! hollows without the original. The support previews of draft supports are
//! skipped with them, since they could not be checked against the supports.

use std::fmt;
use std::io::{self, Read, Write};

use crate::app::{
    DecodeDocumentsError, EncodeDocumentsError, HOLLOWS_TAG, HOLLOWS_VERSION, HollowEntry,
    SETTINGS_TAG, SETTINGS_VERSION, SUPPORTS_TAG, SUPPORTS_VERSION, SupportEntry, decode_hollows,
    decode_supports, encode_hollows, encode_supports,
};
use crate::container::{BreadReader, BreadWriter, Chunk, ChunkTag, ReadBreadError};
use crate::mesh::{DecodeMeshError, EncodeMeshError, MESH_TAG, MESH_VERSION, Mesh, decode_mesh};
use crate::mesh_v2::{decode_mesh_v2, encode_mesh_v2};
use crate::metadata::{
    EncodeMetadataError, METADATA_TAG, METADATA_VERSION, MetadataEntry, decode_metadata,
    encode_metadata,
};
use crate::parallel;
use crate::preview::{
    DecodePreviewsError, EncodePreviewsError, SUPPORT_PREVIEW_TAG, SUPPORT_PREVIEW_VERSION,
    SupportPreview, decode_previews, encode_previews,
};
use crate::program::{
    DecodeProgramDataError, EncodeProgramDataError, PROGRAM_TAG, PROGRAM_VERSION, ProgramEntry,
    decode_program_data, encode_program_data,
};
use crate::role::{
    DecodeRolesError, EncodeRolesError, ROLE_RAFT, ROLE_TAG, ROLE_VERSION, RoleEntry, decode_roles,
    encode_roles,
};
use crate::scene::{
    DecodeSceneError, EncodeSceneError, SCENE_TAG, SCENE_VERSION, Scene, decode_scene, encode_scene,
};
use crate::surface::{
    DecodeSurfaceError, EncodeSurfaceError, SURFACE_TAG, SURFACE_VERSION, SurfaceEntry,
    decode_surface, decode_surface_v1, encode_surface,
};
use crate::volume::{
    DecodeVolumesError, EncodeVolumesError, VOLUME_NEGATIVE, VOLUME_TAG, VOLUME_UNCUT,
    VOLUME_VERSION, VolumeEntry, decode_volumes, encode_volumes,
};

/// The tag of the thumbnail chunk, whose payload is a PNG file. Section 8
/// asks writers to put it first, so a program that only wants the picture
/// reads one chunk.
pub const THUMBNAIL_TAG: ChunkTag = ChunkTag(*b"THMB");

/// The thumbnail chunk version this build writes and reads.
pub const THUMBNAIL_VERSION: u16 = 1;

/// What a `.bread` file holds.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BreadFile {
    /// The scene and its meshes.
    pub scene: Scene,
    /// The project settings document, carried without being read.
    pub settings: Option<Vec<u8>>,
    /// Supports kept as data. Their support leaves show an empty mesh.
    pub supports: Vec<SupportEntry>,
    /// How hollowed models were made. Their leaves show the hollow.
    pub hollows: Vec<HollowEntry>,
    /// A small picture of the file: a PNG, at most 512 x 512 and best
    /// 256 x 256, in sRGB. It is carried without being read: the PNG is
    /// neither checked nor decoded.
    pub thumbnail: Option<Vec<u8>>,
    /// The mesh of the supports, for readers that do not rebuild them from
    /// their documents. Each preview names the support leaf of an entry of
    /// `supports`. A program that edits the supports writes new previews, or
    /// none.
    pub support_previews: Vec<SupportPreview>,
    /// What was painted on the faces of leaves: one mask per program, leaf
    /// and kind, each document carried without being read. A program changes
    /// and drops only its own entries. Entries read from chunk version 1 name
    /// no program, and must be given one before the file is written.
    pub surface: Vec<SurfaceEntry>,
    /// The leaves that are not models: supports or a raft. A support leaf of
    /// `supports` is supports whether it is listed here or not.
    pub roles: Vec<RoleEntry>,
    /// Who made the file, how it may be used, and lasting ids for its parts.
    /// Reading leaves out what breaks a rule of section 12, so metadata never
    /// makes a file unreadable.
    pub metadata: Vec<MetadataEntry>,
    /// Meshes that act on a model without printing: support enforcers and
    /// blockers, modifiers, and negative volumes with the model before the
    /// cut. No leaf shows a volume's mesh.
    pub volumes: Vec<VolumeEntry>,
    /// Each program's own documents, about the whole file or one node, each
    /// carried without being read (section 13).
    pub program_data: Vec<ProgramEntry>,
    /// The chunks this build does not know, official or private, as they
    /// were read, in their order. Writing writes them back last. A program
    /// keeps them, unless it removes or renumbers nodes or meshes: then it
    /// may clear them, since they may name nodes or meshes by an index that
    /// changed (section 7.4).
    pub other_chunks: Vec<Chunk>,
}

/// Why a file could not be written.
#[derive(Debug)]
pub enum WriteFileError {
    Io(io::Error),
    Scene(EncodeSceneError),
    Mesh(EncodeMeshError),
    Supports(EncodeDocumentsError),
    Hollows(EncodeDocumentsError),
    Previews(EncodePreviewsError),
    Surface(EncodeSurfaceError),
    Roles(EncodeRolesError),
    /// A role contradicts the supports or hollows: a support leaf given the
    /// role of a raft, or a model of either given a role.
    RoleConflict {
        leaf: usize,
    },
    Metadata(EncodeMetadataError),
    Volumes(EncodeVolumesError),
    /// A volume belongs to a support leaf or a leaf with the role of
    /// supports or a raft, or a hollowed model has a negative volume.
    VolumeConflict {
        model: usize,
    },
    ProgramData(EncodeProgramDataError),
    /// One of `other_chunks` has a tag this build knows, which it writes
    /// itself, or a tag that is not four ASCII letters or digits starting
    /// with a letter.
    OtherChunk {
        tag: ChunkTag,
    },
    /// A support leaf shows a mesh with vertices or triangles: support
    /// leaves are stored with an empty mesh.
    SupportMeshNotEmpty {
        leaf: usize,
    },
    /// A support leaf is also a hollowed model.
    SupportIsHollowed {
        leaf: usize,
    },
    /// A support preview names a leaf that no supports entry shows.
    PreviewWithoutSupports {
        leaf: usize,
    },
}

impl fmt::Display for WriteFileError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(err) => write!(f, "{err}"),
            Self::Scene(err) => write!(f, "{err}"),
            Self::Mesh(err) => write!(f, "{err}"),
            Self::Supports(err) | Self::Hollows(err) => write!(f, "{err}"),
            Self::Previews(err) => write!(f, "{err}"),
            Self::Surface(err) => write!(f, "{err}"),
            Self::Roles(err) => write!(f, "{err}"),
            Self::RoleConflict { leaf } => write!(f, "{}", RoleConflict(*leaf)),
            Self::Metadata(err) => write!(f, "{err}"),
            Self::Volumes(err) => write!(f, "{err}"),
            Self::VolumeConflict { model } => write!(f, "{}", VolumeConflict(*model)),
            Self::ProgramData(err) => write!(f, "{err}"),
            Self::OtherChunk { tag } => write!(
                f,
                "the {tag} chunk cannot be carried: its tag is known or not a tag"
            ),
            Self::SupportMeshNotEmpty { leaf } => {
                write!(
                    f,
                    "the support leaf {leaf} shows a mesh instead of an empty one"
                )
            }
            Self::SupportIsHollowed { leaf } => write!(f, "{}", SupportIsHollowed(*leaf)),
            Self::PreviewWithoutSupports { leaf } => {
                write!(f, "{}", PreviewWithoutSupports(*leaf))
            }
        }
    }
}

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

impl From<io::Error> for WriteFileError {
    fn from(err: io::Error) -> Self {
        Self::Io(err)
    }
}

/// Why a `.bread` file could not be read.
#[derive(Debug)]
pub enum ReadFileError {
    File(ReadBreadError),
    /// A chunk this build reads has a version it does not read: a newer one,
    /// or 0, which no version is.
    ChunkVersion {
        tag: ChunkTag,
        version: u16,
    },
    /// The file holds a number of chunks of one tag that the format does not
    /// allow: no scene chunk, or two of a chunk that comes at most once.
    ChunkCount {
        tag: ChunkTag,
        count: usize,
    },
    Mesh(DecodeMeshError),
    Scene(DecodeSceneError),
    Supports(DecodeDocumentsError),
    Hollows(DecodeDocumentsError),
    Previews(DecodePreviewsError),
    Surface(DecodeSurfaceError),
    Roles(DecodeRolesError),
    ProgramData(DecodeProgramDataError),
    /// A role contradicts the supports or hollows: a support leaf given the
    /// role of a raft, or a model of either given a role.
    RoleConflict {
        leaf: usize,
    },
    /// A support leaf is also a hollowed model.
    SupportIsHollowed {
        leaf: usize,
    },
    /// A support preview names a leaf that no supports entry shows.
    PreviewWithoutSupports {
        leaf: usize,
    },
    Volumes(DecodeVolumesError),
    /// A volume belongs to a support leaf or a leaf with the role of
    /// supports or a raft, or a hollowed model has a negative volume.
    VolumeConflict {
        model: usize,
    },
}

impl fmt::Display for ReadFileError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::File(err) => write!(f, "{err}"),
            Self::ChunkVersion { tag, version: 0 } => {
                write!(f, "the {tag} chunk has version 0, which does not exist")
            }
            Self::ChunkVersion { tag, version } => {
                write!(
                    f,
                    "the {tag} chunk is written in a newer version ({version})"
                )
            }
            Self::ChunkCount { tag, count } => write!(f, "the file holds {count} {tag} chunks"),
            Self::Mesh(err) => write!(f, "{err}"),
            Self::Scene(err) => write!(f, "{err}"),
            Self::Supports(err) | Self::Hollows(err) => write!(f, "{err}"),
            Self::Previews(err) => write!(f, "{err}"),
            Self::Surface(err) => write!(f, "{err}"),
            Self::Roles(err) => write!(f, "{err}"),
            Self::ProgramData(err) => write!(f, "{err}"),
            Self::RoleConflict { leaf } => write!(f, "{}", RoleConflict(*leaf)),
            Self::SupportIsHollowed { leaf } => write!(f, "{}", SupportIsHollowed(*leaf)),
            Self::PreviewWithoutSupports { leaf } => {
                write!(f, "{}", PreviewWithoutSupports(*leaf))
            }
            Self::Volumes(err) => write!(f, "{err}"),
            Self::VolumeConflict { model } => write!(f, "{}", VolumeConflict(*model)),
        }
    }
}

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

/// The message of both `RoleConflict` errors.
struct RoleConflict(usize);

impl fmt::Display for RoleConflict {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "the role of leaf {} contradicts the supports or hollows",
            self.0
        )
    }
}

/// The message of both `VolumeConflict` errors.
struct VolumeConflict(usize);

impl fmt::Display for VolumeConflict {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "the volumes of leaf {} contradict the supports, hollows or roles",
            self.0
        )
    }
}

/// The message of both `SupportIsHollowed` errors.
struct SupportIsHollowed(usize);

impl fmt::Display for SupportIsHollowed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "the support leaf {} is also a hollowed model", self.0)
    }
}

/// The message of both `PreviewWithoutSupports` errors.
struct PreviewWithoutSupports(usize);

impl fmt::Display for PreviewWithoutSupports {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "the support preview of leaf {} has no supports entry",
            self.0
        )
    }
}

impl From<ReadBreadError> for ReadFileError {
    fn from(err: ReadBreadError) -> Self {
        Self::File(err)
    }
}

/// The newest version of the chunk `tag` this build reads, or `None` for a
/// tag it does not know, which a reader skips. Every version from 1 up to it
/// is read, though older supports and hollows chunks are skipped; any other
/// version makes the file unreadable.
pub fn supported_version(tag: ChunkTag) -> Option<u16> {
    Some(match tag {
        THUMBNAIL_TAG => THUMBNAIL_VERSION,
        SCENE_TAG => SCENE_VERSION,
        SETTINGS_TAG => SETTINGS_VERSION,
        SUPPORTS_TAG => SUPPORTS_VERSION,
        HOLLOWS_TAG => HOLLOWS_VERSION,
        MESH_TAG => MESH_VERSION,
        SUPPORT_PREVIEW_TAG => SUPPORT_PREVIEW_VERSION,
        SURFACE_TAG => SURFACE_VERSION,
        ROLE_TAG => ROLE_VERSION,
        METADATA_TAG => METADATA_VERSION,
        VOLUME_TAG => VOLUME_VERSION,
        PROGRAM_TAG => PROGRAM_VERSION,
        _ => return None,
    })
}

/// Writes `file` as a `.bread` file to `out`, handing `out` back. When it
/// fails, what it wrote to `out` is not a valid file.
pub fn write_file<W: Write>(file: &BreadFile, out: W) -> Result<W, WriteFileError> {
    let scene = &file.scene;
    let scene_payload = encode_scene(scene).map_err(WriteFileError::Scene)?;
    let supports = encode_supports(&file.supports, scene).map_err(WriteFileError::Supports)?;
    let hollows = encode_hollows(&file.hollows, scene).map_err(WriteFileError::Hollows)?;
    let previews =
        encode_previews(&file.support_previews, scene).map_err(WriteFileError::Previews)?;
    let surface = encode_surface(&file.surface, scene).map_err(WriteFileError::Surface)?;
    let roles = encode_roles(&file.roles, scene).map_err(WriteFileError::Roles)?;
    let metadata = encode_metadata(&file.metadata, scene).map_err(WriteFileError::Metadata)?;
    let volumes = encode_volumes(&file.volumes, scene).map_err(WriteFileError::Volumes)?;
    let program_data =
        encode_program_data(&file.program_data, scene).map_err(WriteFileError::ProgramData)?;
    if let Some(chunk) = file
        .other_chunks
        .iter()
        .find(|chunk| !is_tag(chunk.tag) || supported_version(chunk.tag).is_some())
    {
        return Err(WriteFileError::OtherChunk { tag: chunk.tag });
    }
    for entry in &file.supports {
        let leaf = entry.support;
        if scene
            .leaf_mesh(leaf)
            .is_some_and(|mesh| !mesh.vertices.is_empty() || !mesh.triangles.is_empty())
        {
            return Err(WriteFileError::SupportMeshNotEmpty { leaf });
        }
    }
    if let Some(leaf) = hollowed_support(&file.supports, &file.hollows) {
        return Err(WriteFileError::SupportIsHollowed { leaf });
    }
    if let Some(leaf) = unsupported_preview(&file.support_previews, &file.supports) {
        return Err(WriteFileError::PreviewWithoutSupports { leaf });
    }
    if let Some(leaf) = role_conflict(&file.roles, &file.supports, &file.hollows) {
        return Err(WriteFileError::RoleConflict { leaf });
    }
    if let Some(model) = volume_conflict(&file.volumes, &file.supports, &file.hollows, &file.roles)
    {
        return Err(WriteFileError::VolumeConflict { model });
    }
    // Each mesh is encoded on its own, so they are encoded side by side.
    let meshes: Vec<Vec<u8>> = parallel::map(&scene.meshes, encode_mesh_v2)
        .into_iter()
        .collect::<Result<_, _>>()
        .map_err(WriteFileError::Mesh)?;

    let mut writer = BreadWriter::new(out)?;
    if let Some(thumbnail) = &file.thumbnail {
        writer.chunk(THUMBNAIL_TAG, THUMBNAIL_VERSION, thumbnail)?;
    }
    writer.chunk(SCENE_TAG, SCENE_VERSION, &scene_payload)?;
    if !file.metadata.is_empty() {
        writer.chunk(METADATA_TAG, METADATA_VERSION, &metadata)?;
    }
    if let Some(settings) = &file.settings {
        writer.chunk(SETTINGS_TAG, SETTINGS_VERSION, settings)?;
    }
    if !file.supports.is_empty() {
        writer.chunk(SUPPORTS_TAG, SUPPORTS_VERSION, &supports)?;
    }
    if !file.hollows.is_empty() {
        writer.chunk(HOLLOWS_TAG, HOLLOWS_VERSION, &hollows)?;
    }
    if !file.program_data.is_empty() {
        writer.chunk(PROGRAM_TAG, PROGRAM_VERSION, &program_data)?;
    }
    if !file.surface.is_empty() {
        writer.chunk(SURFACE_TAG, SURFACE_VERSION, &surface)?;
    }
    if !file.roles.is_empty() {
        writer.chunk(ROLE_TAG, ROLE_VERSION, &roles)?;
    }
    if !file.volumes.is_empty() {
        writer.chunk(VOLUME_TAG, VOLUME_VERSION, &volumes)?;
    }
    for payload in &meshes {
        writer.chunk(MESH_TAG, MESH_VERSION, payload)?;
    }
    if !file.support_previews.is_empty() {
        writer.chunk(SUPPORT_PREVIEW_TAG, SUPPORT_PREVIEW_VERSION, &previews)?;
    }
    for chunk in &file.other_chunks {
        writer.chunk(chunk.tag, chunk.version, &chunk.payload)?;
    }
    Ok(writer.finish()?)
}

/// Whether `tag` is one a writer may write: four ASCII letters or digits,
/// the first a letter (section 7).
fn is_tag(tag: ChunkTag) -> bool {
    tag.0[0].is_ascii_alphabetic() && tag.0.iter().all(u8::is_ascii_alphanumeric)
}

/// Mesh payloads smaller than this are decoded where they are read: a thread
/// of their own would cost more than it saves.
const MESH_ON_ITS_OWN_THREAD: usize = 1 << 16;

/// A mesh chunk being decoded, or decoded already.
enum PendingMesh<'scope> {
    Done(Result<Mesh, DecodeMeshError>),
    Running(std::thread::ScopedJoinHandle<'scope, Result<Mesh, DecodeMeshError>>),
}

impl PendingMesh<'_> {
    fn finish(self) -> Result<Mesh, DecodeMeshError> {
        match self {
            Self::Done(mesh) => mesh,
            Self::Running(handle) => handle
                .join()
                .unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
        }
    }
}

fn decode_mesh_chunk(version: u16, payload: &[u8]) -> Result<Mesh, DecodeMeshError> {
    match version {
        1 => decode_mesh(payload),
        _ => decode_mesh_v2(payload),
    }
}

/// Reads the `.bread` file in `input`.
///
/// Large meshes are decoded on threads of their own while the rest of the
/// file is read. A file is refused for the same reason as if every chunk
/// were read in order: the first fault in file order.
pub fn read_file<R: Read>(input: R) -> Result<BreadFile, ReadFileError> {
    let mut reader = BreadReader::new(input)?;
    std::thread::scope(|scope| read_chunks(&mut reader, scope))
}

fn read_chunks<'scope, R: Read>(
    reader: &mut BreadReader<R>,
    scope: &'scope std::thread::Scope<'scope, '_>,
) -> Result<BreadFile, ReadFileError> {
    let (mut thumbnails, mut scenes, mut settings, mut supports, mut hollows, mut previews) = (
        Vec::new(),
        Vec::new(),
        Vec::new(),
        Vec::new(),
        Vec::new(),
        Vec::new(),
    );
    let mut volumes = Vec::new();
    let (mut surfaces, mut roles, mut metadata, mut programs) =
        (Vec::new(), Vec::new(), Vec::new(), Vec::new());
    let mut other_chunks = Vec::new();
    let mut pending: Vec<PendingMesh<'scope>> = Vec::new();
    let mut running = std::collections::VecDeque::new();
    let threads = parallel::threads();
    let mut read_all = || -> Result<(), ReadFileError> {
        while let Some(chunk) = reader.next_chunk()? {
            let Some(supported) = supported_version(chunk.tag) else {
                if is_tag(chunk.tag) {
                    other_chunks.push(chunk);
                }
                continue;
            };
            if chunk.version == 0 || chunk.version > supported {
                return Err(ReadFileError::ChunkVersion {
                    tag: chunk.tag,
                    version: chunk.version,
                });
            }
            // An older supports or hollows chunk is a draft one: it still counts
            // as the one chunk of its tag, but its payload is not read.
            let current = chunk.version == supported;
            match chunk.tag {
                THUMBNAIL_TAG => thumbnails.push(chunk.payload),
                SCENE_TAG => scenes.push(chunk.payload),
                SETTINGS_TAG => settings.push(chunk.payload),
                SUPPORTS_TAG => supports.push(current.then_some(chunk.payload)),
                HOLLOWS_TAG => hollows.push(current.then_some(chunk.payload)),
                SUPPORT_PREVIEW_TAG => previews.push(chunk.payload),
                SURFACE_TAG => surfaces.push((chunk.version, chunk.payload)),
                ROLE_TAG => roles.push(chunk.payload),
                METADATA_TAG => metadata.push(chunk.payload),
                VOLUME_TAG => volumes.push(chunk.payload),
                PROGRAM_TAG => programs.push(chunk.payload),
                _ => {
                    let (version, payload) = (chunk.version, chunk.payload);
                    if threads < 2 || payload.len() < MESH_ON_ITS_OWN_THREAD {
                        pending.push(PendingMesh::Done(decode_mesh_chunk(version, &payload)));
                        continue;
                    }
                    // At most as many meshes at once as the machine runs threads.
                    if running.len() >= threads {
                        let oldest: usize = running.pop_front().expect("one is running");
                        let mesh = std::mem::replace(
                            &mut pending[oldest],
                            PendingMesh::Done(Err(DecodeMeshError::Malformed)),
                        );
                        pending[oldest] = PendingMesh::Done(mesh.finish());
                    }
                    running.push_back(pending.len());
                    pending.push(PendingMesh::Running(
                        scope.spawn(move || decode_mesh_chunk(version, &payload)),
                    ));
                }
            }
        }
        Ok(())
    };
    let read = read_all();
    // A mesh refused comes before any fault found after it in the file, as
    // when each mesh is decoded the moment it is read.
    let meshes = pending
        .into_iter()
        .map(PendingMesh::finish)
        .collect::<Result<Vec<_>, _>>()
        .map_err(ReadFileError::Mesh)?;
    read?;
    let scene = single(SCENE_TAG, scenes)?.ok_or(ReadFileError::ChunkCount {
        tag: SCENE_TAG,
        count: 0,
    })?;
    let thumbnail = single(THUMBNAIL_TAG, thumbnails)?;
    let settings = single(SETTINGS_TAG, settings)?;
    let supports = single(SUPPORTS_TAG, supports)?;
    let draft_supports = matches!(supports, Some(None));
    let supports = supports.flatten();
    let hollows = single(HOLLOWS_TAG, hollows)?.flatten();
    let previews = single(SUPPORT_PREVIEW_TAG, previews)?;
    let surface = single(SURFACE_TAG, surfaces)?;
    let roles = single(ROLE_TAG, roles)?;
    let metadata = single(METADATA_TAG, metadata)?;
    let volumes = single(VOLUME_TAG, volumes)?;
    let programs = single(PROGRAM_TAG, programs)?;

    let scene = decode_scene(&scene, meshes).map_err(ReadFileError::Scene)?;
    let supports = match supports {
        None => Vec::new(),
        Some(payload) => decode_supports(&payload, &scene).map_err(ReadFileError::Supports)?,
    };
    let hollows = match hollows {
        None => Vec::new(),
        Some(payload) => decode_hollows(&payload, &scene).map_err(ReadFileError::Hollows)?,
    };
    if let Some(leaf) = hollowed_support(&supports, &hollows) {
        return Err(ReadFileError::SupportIsHollowed { leaf });
    }
    let support_previews = match previews {
        Some(payload) if !draft_supports => {
            decode_previews(&payload, &scene).map_err(ReadFileError::Previews)?
        }
        _ => Vec::new(),
    };
    if let Some(leaf) = unsupported_preview(&support_previews, &supports) {
        return Err(ReadFileError::PreviewWithoutSupports { leaf });
    }
    let surface = match surface {
        None => Vec::new(),
        Some((1, payload)) => {
            decode_surface_v1(&payload, &scene).map_err(ReadFileError::Surface)?
        }
        Some((_, payload)) => decode_surface(&payload, &scene).map_err(ReadFileError::Surface)?,
    };
    let roles = match roles {
        None => Vec::new(),
        Some(payload) => decode_roles(&payload, &scene).map_err(ReadFileError::Roles)?,
    };
    if let Some(leaf) = role_conflict(&roles, &supports, &hollows) {
        return Err(ReadFileError::RoleConflict { leaf });
    }
    let volumes = match volumes {
        None => Vec::new(),
        Some(payload) => decode_volumes(&payload, &scene).map_err(ReadFileError::Volumes)?,
    };
    if let Some(model) = volume_conflict(&volumes, &supports, &hollows, &roles) {
        return Err(ReadFileError::VolumeConflict { model });
    }
    let metadata = metadata.map_or_else(Vec::new, |payload| decode_metadata(&payload, &scene));
    let program_data = match programs {
        None => Vec::new(),
        Some(payload) => {
            decode_program_data(&payload, &scene).map_err(ReadFileError::ProgramData)?
        }
    };
    Ok(BreadFile {
        scene,
        settings,
        supports,
        hollows,
        thumbnail,
        support_previews,
        surface,
        roles,
        metadata,
        volumes,
        program_data,
        other_chunks,
    })
}

/// A leaf whose role contradicts the supports or hollows, which section 11
/// forbids: a support leaf given the role of a raft, or the model of either
/// given the role of supports or of a raft. Reserved roles mean a model, so
/// they contradict nothing.
fn role_conflict(
    roles: &[RoleEntry],
    supports: &[SupportEntry],
    hollows: &[HollowEntry],
) -> Option<usize> {
    roles
        .iter()
        .filter(|entry| entry.is_known())
        .find(|entry| {
            let raft_on_support = entry.role == ROLE_RAFT
                && supports.iter().any(|support| support.support == entry.leaf);
            let model = supports.iter().any(|support| support.model == entry.leaf)
                || hollows.iter().any(|hollow| hollow.model == entry.leaf);
            raft_on_support || model
        })
        .map(|entry| entry.leaf)
}

/// The model of a volume entry that contradicts the supports, hollows or
/// roles, which section 14 forbids: a support leaf, a leaf with the role of
/// supports or of a raft, or a hollowed model with a negative volume or an
/// uncut model. Reserved kinds mean nothing, so they contradict nothing.
fn volume_conflict(
    volumes: &[VolumeEntry],
    supports: &[SupportEntry],
    hollows: &[HollowEntry],
    roles: &[RoleEntry],
) -> Option<usize> {
    volumes
        .iter()
        .filter(|entry| entry.is_known())
        .find(|entry| {
            let support = supports
                .iter()
                .any(|support| support.support == entry.model)
                || roles
                    .iter()
                    .any(|role| role.is_known() && role.leaf == entry.model);
            let cut = matches!(entry.kind, VOLUME_NEGATIVE | VOLUME_UNCUT)
                && hollows.iter().any(|hollow| hollow.model == entry.model);
            support || cut
        })
        .map(|entry| entry.model)
}

/// A support leaf that is also the model of a hollow, which section 7.3
/// forbids across the two chunks.
fn hollowed_support(supports: &[SupportEntry], hollows: &[HollowEntry]) -> Option<usize> {
    supports
        .iter()
        .map(|entry| entry.support)
        .find(|&leaf| hollows.iter().any(|hollow| hollow.model == leaf))
}

/// A preview's leaf that is not the support leaf of any supports entry,
/// which section 9 forbids.
fn unsupported_preview(previews: &[SupportPreview], supports: &[SupportEntry]) -> Option<usize> {
    previews
        .iter()
        .map(|preview| preview.leaf)
        .find(|&leaf| !supports.iter().any(|entry| entry.support == leaf))
}

/// The chunk of a tag that comes at most once.
fn single<T>(tag: ChunkTag, chunks: Vec<T>) -> Result<Option<T>, ReadFileError> {
    if chunks.len() > 1 {
        return Err(ReadFileError::ChunkCount {
            tag,
            count: chunks.len(),
        });
    }
    Ok(chunks.into_iter().next())
}