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
/*
 * SPDX-FileCopyrightText: 2026 SynrgStudio
 * SPDX-License-Identifier: Apache-2.0
 */

//! The documents of the surface paint chunk (`SPEC.md`, section 10.1): the
//! masks themselves, which [`crate::surface`] carries without reading.
//!
//! Version 1 gives every triangle of a mesh one value, as runs. Version 2
//! gives every painted triangle a tree that splits it into smaller pieces,
//! each with its own value: what a support brush paints when it covers part
//! of a triangle.
//!
//! ```text
//! version 1   u32 triangle count, 48 bytes fingerprint,
//!             u32 count, then per run: u32 length, u8 value
//! version 2   u32 triangle count, 48 bytes fingerprint,
//!             u32 count, then per painted triangle: u32 gap,
//!             u32 length, the trees as a bit stream of 4-bit groups
//! ```
//!
//! A document that breaks a rule never makes a file unreadable: a reader
//! treats its entry as absent. [`SurfaceEntry::paint`] does that check, with
//! the leaf's mesh, and gives the document only when it applies.

use std::fmt;

use crate::bytes::{In, Out, fits_u32};
#[cfg(feature = "fingerprint")]
use crate::mesh::Mesh;
#[cfg(feature = "fingerprint")]
use crate::surface::SurfaceEntry;

/// The kind of paint that marks details to keep: values 0 to 255.
pub const PAINT_DETAIL: u8 = 0;
/// The kind of paint that marks where supports must touch: values 0 to 255.
pub const PAINT_SUPPORTS_MUST_TOUCH: u8 = 1;
/// The kind of paint that marks where supports must not touch: values 0 to
/// 255.
pub const PAINT_SUPPORTS_MUST_NOT_TOUCH: u8 = 2;
/// The kind of paint that marks both, as a support brush paints them: 0
/// bare, 1 supports must touch, 2 supports must not touch.
pub const PAINT_SUPPORTS_BOTH_WAYS: u8 = 3;

/// The value of kind [`PAINT_SUPPORTS_BOTH_WAYS`] where supports must touch.
pub const MUST_TOUCH: u8 = 1;
/// The value of kind [`PAINT_SUPPORTS_BOTH_WAYS`] where supports must not
/// touch.
pub const MUST_NOT_TOUCH: u8 = 2;

/// How deep a node of a version 2 tree may be: the root is at depth 0.
pub const MAX_PAINT_DEPTH: usize = 32;

/// The size of a mesh fingerprint, a SHA-384 digest.
pub const FINGERPRINT_SIZE: usize = 48;

/// A surface paint document.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PaintDocument {
    /// Version 1: one value per triangle.
    Runs(PaintRuns),
    /// Version 2: a tree per painted triangle.
    Trees(PaintTrees),
}

/// A version 1 document: the value of every triangle, as runs.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PaintRuns {
    /// How many triangles the painted mesh has.
    pub triangle_count: u32,
    /// The painted mesh's fingerprint ([`mesh_fingerprint`]).
    pub fingerprint: [u8; FINGERPRINT_SIZE],
    /// The runs, from the first triangle on.
    pub runs: Vec<PaintRun>,
}

/// Triangles in a row that have the same value.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PaintRun {
    /// How many triangles the run covers.
    pub length: u32,
    /// Their value.
    pub value: u8,
}

/// A version 2 document: the painted triangles and their trees.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PaintTrees {
    /// How many triangles the painted mesh has.
    pub triangle_count: u32,
    /// The painted mesh's fingerprint ([`mesh_fingerprint`]).
    pub fingerprint: [u8; FINGERPRINT_SIZE],
    /// The painted triangles, in increasing order. The others have the value
    /// 0 all over.
    pub triangles: Vec<PaintedTriangle>,
}

/// One painted triangle of a version 2 document.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PaintedTriangle {
    /// The triangle's index in its mesh.
    pub triangle: u32,
    /// How it is split, and the value of each piece.
    pub tree: PaintNode,
}

/// A node of a version 2 tree.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PaintNode {
    /// A piece of the triangle, with its value.
    Leaf(u8),
    /// A triangle split into 2, 3 or 4 children (1, 2 or 3 sides split),
    /// named from its special corner, 0 to 2.
    Split {
        /// The corner the split is named from: see [`PaintNode::pieces`].
        special: u8,
        /// The children, first to last: 2, 3 or 4 of them.
        children: Vec<PaintNode>,
    },
}

/// A piece of a painted triangle, the leaf of its tree.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PaintPiece {
    /// The piece's three corners, in order, each as its weights over the
    /// triangle's corners *A*0, *A*1 and *A*2. The weights are multiples of
    /// a power of two, so they are exact.
    pub corners: [[f64; 3]; 3],
    /// The piece's value.
    pub value: u8,
}

/// Why a document could not be decoded.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DecodePaintError {
    /// A document version this build does not know.
    UnknownVersion(u32),
    /// The document breaks a rule of section 10.1.
    Malformed,
}

impl fmt::Display for DecodePaintError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownVersion(version) => {
                write!(
                    f,
                    "surface paint document version {version} is not supported"
                )
            }
            Self::Malformed => f.write_str("the surface paint document is malformed"),
        }
    }
}

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

/// Why a document could not be encoded.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EncodePaintError {
    /// The runs of a version 1 document do not add up to the triangle count.
    RunsDoNotCover,
    /// The painted triangles of a version 2 document are not in increasing
    /// order, or one is past the mesh's last triangle.
    NotInOrder,
    /// A split node has fewer than 2 or more than 4 children, or a special
    /// corner above 2.
    BadSplit,
    /// A node is deeper than [`MAX_PAINT_DEPTH`].
    TooDeep,
    /// The document has 2^32 or more runs or painted triangles, or its trees
    /// take 4 GiB or more.
    TooLarge,
}

impl fmt::Display for EncodePaintError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::RunsDoNotCover => "the paint runs do not cover exactly the mesh's triangles",
            Self::NotInOrder => "the painted triangles are out of order, or past the mesh",
            Self::BadSplit => "a paint tree splits a triangle in a way the format does not have",
            Self::TooDeep => "a paint tree is deeper than the format allows",
            Self::TooLarge => "the paint document is too large",
        })
    }
}

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

impl PaintDocument {
    /// The document version: 1 for runs, 2 for trees.
    #[must_use]
    pub fn version(&self) -> u32 {
        match self {
            Self::Runs(_) => 1,
            Self::Trees(_) => 2,
        }
    }

    /// How many triangles the painted mesh has.
    #[must_use]
    pub fn triangle_count(&self) -> u32 {
        match self {
            Self::Runs(runs) => runs.triangle_count,
            Self::Trees(trees) => trees.triangle_count,
        }
    }

    /// The painted mesh's fingerprint.
    #[must_use]
    pub fn fingerprint(&self) -> &[u8; FINGERPRINT_SIZE] {
        match self {
            Self::Runs(runs) => &runs.fingerprint,
            Self::Trees(trees) => &trees.fingerprint,
        }
    }

    /// The largest value anywhere in the document, 0 when nothing is painted.
    #[must_use]
    pub fn max_value(&self) -> u8 {
        match self {
            Self::Runs(runs) => runs.runs.iter().map(|run| run.value).max().unwrap_or(0),
            Self::Trees(trees) => trees
                .triangles
                .iter()
                .map(|painted| painted.tree.max_value())
                .max()
                .unwrap_or(0),
        }
    }

    /// Whether the document's values are allowed for paint of `kind`: any
    /// value for kinds 0 to 2, at most 2 for kind 3, and nothing for the
    /// reserved kinds.
    #[must_use]
    pub fn allows_kind(&self, kind: u8) -> bool {
        match kind {
            PAINT_DETAIL | PAINT_SUPPORTS_MUST_TOUCH | PAINT_SUPPORTS_MUST_NOT_TOUCH => true,
            PAINT_SUPPORTS_BOTH_WAYS => self.max_value() <= MUST_NOT_TOUCH,
            _ => false,
        }
    }

    /// Whether the document was made on `mesh`, of `triangle_count`
    /// triangles and with `fingerprint`, and covers it: version 1 runs that
    /// add up to the triangle count. Version 2 documents are checked against
    /// the triangle count when they are decoded.
    #[must_use]
    pub fn fits(&self, triangle_count: usize, fingerprint: &[u8; FINGERPRINT_SIZE]) -> bool {
        if usize::try_from(self.triangle_count()).ok() != Some(triangle_count)
            || self.fingerprint() != fingerprint
        {
            return false;
        }
        match self {
            Self::Runs(runs) => runs.covered() == Some(u64::from(runs.triangle_count)),
            Self::Trees(_) => true,
        }
    }
}

impl PaintRuns {
    /// How many triangles the runs cover, or `None` past `u64`.
    fn covered(&self) -> Option<u64> {
        self.runs
            .iter()
            .try_fold(0u64, |sum, run| sum.checked_add(u64::from(run.length)))
    }

    /// The value of every triangle, from the first on.
    pub fn values(&self) -> impl Iterator<Item = u8> + '_ {
        self.runs
            .iter()
            .flat_map(|run| std::iter::repeat_n(run.value, run.length as usize))
    }
}

impl PaintNode {
    /// The largest value in the tree.
    #[must_use]
    pub fn max_value(&self) -> u8 {
        match self {
            Self::Leaf(value) => *value,
            Self::Split { children, .. } => children.iter().map(Self::max_value).max().unwrap_or(0),
        }
    }

    /// The pieces of the triangle, depth first and each node's children
    /// first to last, with their corners as weights over the triangle's
    /// corners (section 10.1). A split node with corners C0, C1, C2 and
    /// special corner s takes P0 = Cs, P1 = Cs+1, P2 = Cs+2, indices modulo 3,
    /// and Mij the midpoint of Pi and Pj; its children are:
    ///
    /// ```text
    /// 1 side split   (P0, P1, M12), (M12, P2, P0)
    /// 2 sides split  (P0, M01, M20), (M01, P1, M20), (P1, P2, M20)
    /// 3 sides split  (P0, M01, M20), (M01, P1, M12), (M12, P2, M20), (M01, M12, M20)
    /// ```
    ///
    /// The pieces depend on the tree alone, never on neighbouring pieces or
    /// triangles: they cover the triangle exactly once, each wound like it.
    #[must_use]
    pub fn pieces(&self) -> Vec<PaintPiece> {
        const WHOLE: [[f64; 3]; 3] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
        let mut pieces = Vec::new();
        let mut stack = vec![(self, WHOLE)];
        while let Some((node, corners)) = stack.pop() {
            match node {
                Self::Leaf(value) => pieces.push(PaintPiece {
                    corners,
                    value: *value,
                }),
                Self::Split { special, children } => {
                    let Some(split) = split_corners(corners, *special, children.len()) else {
                        continue;
                    };
                    // Pushed last to first, so the first child comes out first.
                    for (child, child_corners) in children.iter().zip(split).rev() {
                        stack.push((child, child_corners));
                    }
                }
            }
        }
        pieces
    }

    /// Reads the tree of one triangle from the string of hex digits that
    /// 3MF files of filament slicers hold for it: one digit per group of 4
    /// bits, the last digit holding the first group. `None` when the string
    /// is not exactly one tree that version 2 allows.
    #[must_use]
    pub fn from_3mf(digits: &str) -> Option<Self> {
        let mut groups = Vec::with_capacity(digits.len());
        for c in digits.chars().rev() {
            groups.push(u8::try_from(c.to_digit(16)?).ok()?);
        }
        let mut reader = GroupReader {
            groups: GroupSource::List(&groups),
            next: 0,
        };
        let node = read_node(&mut reader, 0).ok()?;
        (reader.next == groups.len()).then_some(node)
    }

    /// The tree as the string of hex digits a 3MF file holds for its
    /// triangle (see [`PaintNode::from_3mf`]), in upper case. `None` for a
    /// tree version 2 does not allow.
    #[must_use]
    pub fn to_3mf(&self) -> Option<String> {
        let mut groups = Vec::new();
        write_node(self, 0, &mut |group| groups.push(group)).ok()?;
        groups
            .iter()
            .rev()
            .map(|&group| char::from_digit(u32::from(group), 16).map(|c| c.to_ascii_uppercase()))
            .collect()
    }
}

impl PaintPiece {
    /// The piece's corners as points, given the triangle's corners in the
    /// mesh's order, first corner first.
    #[must_use]
    pub fn points(&self, triangle: [[f64; 3]; 3]) -> [[f64; 3]; 3] {
        self.corners.map(|weights| {
            let mut point = [0.0; 3];
            for (weight, corner) in weights.iter().zip(&triangle) {
                for (p, c) in point.iter_mut().zip(corner) {
                    *p += weight * c;
                }
            }
            point
        })
    }
}

/// The corners of the children of a node with `corners`, split from
/// `special` into `count` children; `None` for a split the format does not
/// have.
fn split_corners(corners: [[f64; 3]; 3], special: u8, count: usize) -> Option<Vec<[[f64; 3]; 3]>> {
    if special > 2 {
        return None;
    }
    let s = usize::from(special);
    let p = [corners[s], corners[(s + 1) % 3], corners[(s + 2) % 3]];
    let mid = |a: [f64; 3], b: [f64; 3]| {
        [
            0.5 * (a[0] + b[0]),
            0.5 * (a[1] + b[1]),
            0.5 * (a[2] + b[2]),
        ]
    };
    let (m01, m12, m20) = (mid(p[0], p[1]), mid(p[1], p[2]), mid(p[2], p[0]));
    Some(match count {
        2 => vec![[p[0], p[1], m12], [m12, p[2], p[0]]],
        3 => vec![[p[0], m01, m20], [m01, p[1], m20], [p[1], p[2], m20]],
        4 => vec![
            [p[0], m01, m20],
            [m01, p[1], m12],
            [m12, p[2], m20],
            [m01, m12, m20],
        ],
        _ => return None,
    })
}

/// Decodes a surface paint document of `version`.
///
/// # Errors
///
/// [`DecodePaintError::UnknownVersion`] for a version other than 1 or 2, and
/// [`DecodePaintError::Malformed`] for a document that breaks a rule of
/// section 10.1. Either way a reader treats the entry as absent.
pub fn decode_paint(version: u32, document: &[u8]) -> Result<PaintDocument, DecodePaintError> {
    let malformed = DecodePaintError::Malformed;
    let mut input = In(document);
    let triangle_count = input.u32().ok_or(malformed.clone())?;
    let fingerprint: [u8; FINGERPRINT_SIZE] = input
        .take(FINGERPRINT_SIZE)
        .and_then(|bytes| bytes.try_into().ok())
        .ok_or(malformed.clone())?;
    let decoded = match version {
        1 => {
            let count = input.count(5).ok_or(malformed.clone())?;
            let mut runs = Vec::with_capacity(count);
            for _ in 0..count {
                let length = input.u32().ok_or(malformed.clone())?;
                let value = input.u8().ok_or(malformed.clone())?;
                runs.push(PaintRun { length, value });
            }
            PaintDocument::Runs(PaintRuns {
                triangle_count,
                fingerprint,
                runs,
            })
        }
        2 => {
            let count = input.count(4).ok_or(malformed.clone())?;
            let mut indices = Vec::with_capacity(count);
            let mut previous: Option<u32> = None;
            for _ in 0..count {
                let gap = input.u32().ok_or(malformed.clone())?;
                let index = match previous {
                    None => gap,
                    Some(_) if gap == 0 => return Err(malformed),
                    Some(previous) => previous.checked_add(gap).ok_or(malformed.clone())?,
                };
                if index >= triangle_count {
                    return Err(malformed);
                }
                indices.push(index);
                previous = Some(index);
            }
            let stream = input.bytes().ok_or(malformed.clone())?;
            let mut reader = GroupReader {
                groups: GroupSource::Bytes(stream),
                next: 0,
            };
            let mut triangles = Vec::with_capacity(count);
            for triangle in indices {
                let tree = read_node(&mut reader, 0).map_err(|()| malformed.clone())?;
                triangles.push(PaintedTriangle { triangle, tree });
            }
            // The stream ends with the last tree: at most the unused half of
            // its last byte is left, and it is 0.
            let used_bytes = reader.next.div_ceil(2);
            if used_bytes != stream.len()
                || (reader.next % 2 == 1 && stream.last().is_some_and(|byte| byte >> 4 != 0))
            {
                return Err(malformed);
            }
            PaintDocument::Trees(PaintTrees {
                triangle_count,
                fingerprint,
                triangles,
            })
        }
        other => return Err(DecodePaintError::UnknownVersion(other)),
    };
    if !input.is_empty() {
        return Err(malformed);
    }
    Ok(decoded)
}

/// Encodes a surface paint document, as the version [`PaintDocument::version`]
/// gives.
///
/// # Errors
///
/// When the document breaks a rule of section 10.1: see [`EncodePaintError`].
pub fn encode_paint(document: &PaintDocument) -> Result<Vec<u8>, EncodePaintError> {
    let mut out = Out::default();
    out.u32(document.triangle_count());
    out.0.extend_from_slice(document.fingerprint());
    match document {
        PaintDocument::Runs(runs) => {
            if runs.covered() != Some(u64::from(runs.triangle_count)) {
                return Err(EncodePaintError::RunsDoNotCover);
            }
            if !fits_u32(runs.runs.len()) {
                return Err(EncodePaintError::TooLarge);
            }
            out.len(runs.runs.len());
            for run in &runs.runs {
                out.u32(run.length);
                out.u8(run.value);
            }
        }
        PaintDocument::Trees(trees) => {
            if !fits_u32(trees.triangles.len()) {
                return Err(EncodePaintError::TooLarge);
            }
            out.len(trees.triangles.len());
            let mut previous: Option<u32> = None;
            for painted in &trees.triangles {
                if painted.triangle >= trees.triangle_count
                    || previous.is_some_and(|previous| painted.triangle <= previous)
                {
                    return Err(EncodePaintError::NotInOrder);
                }
                out.u32(painted.triangle - previous.unwrap_or(0));
                previous = Some(painted.triangle);
            }
            let mut stream = Vec::new();
            let mut groups = 0usize;
            for painted in &trees.triangles {
                write_node(&painted.tree, 0, &mut |group| {
                    if groups.is_multiple_of(2) {
                        stream.push(group);
                    } else if let Some(last) = stream.last_mut() {
                        *last |= group << 4;
                    }
                    groups += 1;
                })?;
            }
            if !fits_u32(stream.len()) {
                return Err(EncodePaintError::TooLarge);
            }
            out.bytes(&stream);
        }
    }
    Ok(out.0)
}

/// Where the groups of a tree come from: a bit stream, two groups a byte
/// with the first in the low half, or a list of groups.
enum GroupSource<'a> {
    Bytes(&'a [u8]),
    List(&'a [u8]),
}

/// Reads 4-bit groups one after the other.
struct GroupReader<'a> {
    groups: GroupSource<'a>,
    /// The index of the next group.
    next: usize,
}

impl GroupReader<'_> {
    fn group(&mut self) -> Result<u8, ()> {
        let group = match self.groups {
            GroupSource::Bytes(bytes) => {
                let byte = *bytes.get(self.next / 2).ok_or(())?;
                if self.next.is_multiple_of(2) {
                    byte & 0x0f
                } else {
                    byte >> 4
                }
            }
            GroupSource::List(groups) => *groups.get(self.next).ok_or(())?,
        };
        self.next += 1;
        Ok(group)
    }
}

/// Reads one node at `depth`, and its children.
fn read_node(reader: &mut GroupReader<'_>, depth: usize) -> Result<PaintNode, ()> {
    if depth > MAX_PAINT_DEPTH {
        return Err(());
    }
    let group = reader.group()?;
    let sides = group & 3;
    let high = group >> 2;
    if sides == 0 {
        let mut value = u32::from(high);
        if high == 3 {
            loop {
                let more = reader.group()?;
                value += u32::from(more);
                if value > 255 {
                    return Err(());
                }
                if more != 15 {
                    break;
                }
            }
        }
        return Ok(PaintNode::Leaf(u8::try_from(value).map_err(|_| ())?));
    }
    if high == 3 {
        return Err(());
    }
    let mut children = Vec::with_capacity(usize::from(sides) + 1);
    for _ in 0..=sides {
        children.push(read_node(reader, depth + 1)?);
    }
    // The stream holds the last child first.
    children.reverse();
    Ok(PaintNode::Split {
        special: high,
        children,
    })
}

/// Writes one node at `depth`, and its children, a group at a time.
fn write_node(
    node: &PaintNode,
    depth: usize,
    out: &mut impl FnMut(u8),
) -> Result<(), EncodePaintError> {
    if depth > MAX_PAINT_DEPTH {
        return Err(EncodePaintError::TooDeep);
    }
    match node {
        PaintNode::Leaf(value) if *value < 3 => out(value << 2),
        PaintNode::Leaf(value) => {
            out(3 << 2);
            let mut rest = value - 3;
            while rest >= 15 {
                out(15);
                rest -= 15;
            }
            out(rest);
        }
        PaintNode::Split { special, children } => {
            let sides = match children.len() {
                2 => 1,
                3 => 2,
                4 => 3,
                _ => return Err(EncodePaintError::BadSplit),
            };
            if *special > 2 {
                return Err(EncodePaintError::BadSplit);
            }
            out(sides | (special << 2));
            for child in children.iter().rev() {
                write_node(child, depth + 1, out)?;
            }
        }
    }
    Ok(())
}

/// The fingerprint that names a mesh in a paint document (section 10.1): the
/// SHA-384 digest of the vertex count as a `u64`, the bits of every
/// coordinate as `u32`s, the triangle count as a `u64`, and every triangle's
/// indices as `u32`s, all little-endian.
#[cfg(feature = "fingerprint")]
#[must_use]
pub fn mesh_fingerprint(mesh: &Mesh) -> [u8; FINGERPRINT_SIZE] {
    use sha2::{Digest, Sha384};
    let mut hasher = Sha384::new();
    hasher.update((mesh.vertices.len() as u64).to_le_bytes());
    for vertex in &mesh.vertices {
        for coordinate in vertex {
            hasher.update(coordinate.to_bits().to_le_bytes());
        }
    }
    hasher.update((mesh.triangles.len() as u64).to_le_bytes());
    for triangle in &mesh.triangles {
        for index in triangle {
            hasher.update(index.to_le_bytes());
        }
    }
    hasher.finalize().into()
}

#[cfg(feature = "fingerprint")]
impl SurfaceEntry {
    /// The entry's document, when a reader keeps it for the leaf's `mesh`
    /// (section 10.2): a kind and a document version this build knows, a
    /// document that is not malformed, made on `mesh`, covering it, and with
    /// values its kind allows. `None` means the entry is treated as absent.
    #[must_use]
    pub fn paint(&self, mesh: &Mesh) -> Option<PaintDocument> {
        let document = decode_paint(self.version, &self.document).ok()?;
        (document.allows_kind(self.kind)
            && document.fits(mesh.triangles.len(), &mesh_fingerprint(mesh)))
        .then_some(document)
    }
}