BREP_kernel 0.14.0

A boundary representation (BREP) geometry kernel for building CAD applications.
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
//! The 3MF core model part: `<model>` → `<resources>` → `<object>` → `<mesh>` /
//! `<components>`, and `<build>` → `<item>`.
//!
//! Every element is matched by NAMESPACE and local name, so an extension that
//! reuses a core name (or a core element written through a prefix) is
//! classified correctly. Non-core subtrees are skipped whole — see the module
//! doc of [`super`] for what that deliberately discards.

use super::xml::{Event, StartTag, XmlReader};
use super::{ThreeMfError, ThreeMfUnit, CORE_NAMESPACE, IDENTITY, MAX_MESH_TRIANGLES,
    MAX_MESH_VERTICES};
use rustc_hash::FxHashMap;

/// One `<object>`'s `<mesh>`, in the file's own unit.
pub(super) struct RawMesh {
    pub object_id: u32,
    pub positions: Vec<f64>,
    pub indices: Vec<u32>,
    /// The object's own `pid`/`pindex`: the property every triangle inherits
    /// unless it states one.
    pub object_property: Option<Property>,
    /// One entry per triangle: its own `pid`/`p1`, or `None` to inherit.
    /// Resolved against [`ModelDocument::materials`] once the whole part is
    /// read, since the specification lets a group follow the objects that
    /// name it.
    pub properties: Vec<Option<Property>>,
}

/// A property reference as a triangle or object states it: the group id and
/// the index into that group. Only a group that is a `<basematerials>` can be
/// resolved to a colour; a reference into an extension's colour group or
/// texture stays unresolved.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Property {
    pub group: u32,
    pub index: u32,
}

pub(super) struct Component {
    pub object_id: u32,
    pub transform: [f64; 12],
}

pub(super) enum ObjectContent {
    /// Index into [`ModelDocument::meshes`].
    Mesh(usize),
    Components(Vec<Component>),
}

pub(super) struct Object {
    pub id: u32,
    /// `type="model"` (the default): printable geometry. The other types
    /// (`support`, `solidsupport`, `surface`, `other`) are resources of the
    /// print job and are not placed.
    pub model_type: bool,
    /// The `name` attribute, for naming the object in a refusal.
    pub name: Option<String>,
    pub content: ObjectContent,
}

pub(super) struct Item {
    pub object_id: u32,
    pub transform: [f64; 12],
}

pub(super) struct ModelDocument {
    pub unit: ThreeMfUnit,
    pub meshes: Vec<RawMesh>,
    pub objects: Vec<Object>,
    pub by_id: FxHashMap<u32, usize>,
    pub items: Vec<Item>,
    /// Every `<basematerials>` group by id: each `<base>`'s `displaycolor` as
    /// 8-bit sRGB, or `None` for one that does not spell `#RRGGBB[AA]`.
    pub materials: FxHashMap<u32, Vec<Option<[u8; 3]>>>,
}

impl ModelDocument {
    pub fn object(&self, id: u32) -> Option<&Object> {
        self.by_id.get(&id).map(|index| &self.objects[*index])
    }

    /// The colour a property reference names, if it names a base material.
    pub fn color(&self, property: Option<Property>) -> Option<[u8; 3]> {
        let property = property?;
        self.materials.get(&property.group)?.get(property.index as usize).copied().flatten()
    }
}

/// `#RRGGBB` or `#RRGGBBAA` (the alpha is dropped), either case. Anything
/// else — a named colour, a short form — is `None`: the base is kept so the
/// indices of its neighbours stay right, it just carries no colour.
pub(super) fn parse_display_color(text: &str) -> Option<[u8; 3]> {
    let hex = text.trim().strip_prefix('#')?;
    if hex.len() != 6 && hex.len() != 8 {
        return None;
    }
    let channel = |at: usize| u8::from_str_radix(hex.get(at..at + 2)?, 16).ok();
    Some([channel(0)?, channel(2)?, channel(4)?])
}

/// The reader plus the part name every error is reported against.
struct ModelParser<'a> {
    part: &'a str,
    reader: XmlReader<'a>,
}

impl<'a> ModelParser<'a> {
    fn fail<T>(&self, detail: impl Into<String>) -> Result<T, ThreeMfError> {
        Err(ThreeMfError::Model { part: self.part.to_owned(), detail: detail.into() })
    }

    fn next(&mut self) -> Result<Event, ThreeMfError> {
        self.reader.next().map_err(|error| ThreeMfError::Xml {
            part: self.part.to_owned(),
            detail: error.to_string(),
        })
    }

    fn skip(&mut self, tag: &StartTag) -> Result<(), ThreeMfError> {
        self.reader.skip_subtree(tag).map_err(|error| ThreeMfError::Xml {
            part: self.part.to_owned(),
            detail: error.to_string(),
        })
    }

    /// Consume a leaf element's end tag when it was not written `<tag/>`.
    fn close_leaf(&mut self, tag: &StartTag) -> Result<(), ThreeMfError> {
        if tag.empty {
            Ok(())
        } else {
            self.skip(tag)
        }
    }

    /// A required attribute, with the element named in the refusal.
    fn required<'t>(&self, tag: &'t StartTag, name: &str) -> Result<&'t str, ThreeMfError> {
        match tag.attribute(name) {
            Some(value) => Ok(value),
            None => Err(ThreeMfError::Model {
                part: self.part.to_owned(),
                detail: format!("<{}> has no {name} attribute", tag.name),
            }),
        }
    }

    fn coordinate(&self, tag: &StartTag, name: &str) -> Result<f64, ThreeMfError> {
        let text = self.required(tag, name)?;
        match text.trim().parse::<f64>() {
            Ok(value) if value.is_finite() => Ok(value),
            _ => self.fail(format!("<{}> has a non-finite {name}=\"{text}\"", tag.name)),
        }
    }

    fn identifier(&self, tag: &StartTag, name: &str) -> Result<u32, ThreeMfError> {
        let text = self.required(tag, name)?;
        match text.trim().parse::<u32>() {
            Ok(value) if value > 0 => Ok(value),
            _ => self.fail(format!("<{}> has an invalid {name}=\"{text}\"", tag.name)),
        }
    }

    fn index(&self, tag: &StartTag, name: &str) -> Result<u32, ThreeMfError> {
        let text = self.required(tag, name)?;
        match text.trim().parse::<u32>() {
            Ok(value) => Ok(value),
            _ => self.fail(format!("<{}> has an invalid {name}=\"{text}\"", tag.name)),
        }
    }

    /// A property reference (`pid` + `pindex`, or `pid` + `p1`): `None` when
    /// the element states none. A malformed one is `None` too, never a
    /// refusal — a property is appearance, not geometry.
    fn property(&self, tag: &StartTag, index_name: &str) -> Option<Property> {
        let group = tag.attribute("pid")?.trim().parse::<u32>().ok()?;
        let index = tag.attribute(index_name)?.trim().parse::<u32>().ok()?;
        Some(Property { group, index })
    }

    /// The optional 3x4 `transform`, defaulting to the identity.
    fn transform(&self, tag: &StartTag) -> Result<[f64; 12], ThreeMfError> {
        let Some(text) = tag.attribute("transform") else {
            return Ok(IDENTITY);
        };
        let mut values = [0.0; 12];
        let mut count = 0usize;
        for field in text.split_ascii_whitespace() {
            if count == 12 {
                return self.fail(format!(
                    "<{}> transform has more than 12 numbers",
                    tag.name
                ));
            }
            match field.parse::<f64>() {
                Ok(value) if value.is_finite() => values[count] = value,
                _ => {
                    return self.fail(format!(
                        "<{}> transform has a non-finite value \"{field}\"",
                        tag.name
                    ))
                }
            }
            count += 1;
        }
        if count != 12 {
            return self.fail(format!(
                "<{}> transform has {count} numbers, not 12",
                tag.name
            ));
        }
        Ok(values)
    }
}

/// Parse a 3MF core model part.
pub(super) fn parse_model(part: &str, text: &str) -> Result<ModelDocument, ThreeMfError> {
    let mut parser = ModelParser { part, reader: XmlReader::new(text) };
    // The root: the first element in the document must be a core <model>.
    let root = loop {
        match parser.next()? {
            Event::Start(tag) => break tag,
            Event::End { .. } => {}
            Event::Eof => {
                return parser.fail("the part contains no <model> element");
            }
        }
    };
    if root.namespace != CORE_NAMESPACE || root.name != "model" {
        return parser.fail(format!(
            "the root element is <{}> in namespace '{}', not a 3MF core <model>",
            root.name, root.namespace
        ));
    }
    let unit = match root.attribute("unit") {
        None => ThreeMfUnit::Millimeter,
        Some(text) => match ThreeMfUnit::parse(text) {
            Some(unit) => unit,
            None => return parser.fail(format!("<model> declares an unknown unit=\"{text}\"")),
        },
    };
    if let Some(required) = root.attribute("requiredextensions") {
        let required = required.trim();
        if !required.is_empty() {
            return Err(ThreeMfError::Unsupported {
                part: part.to_owned(),
                detail: format!(
                    "the model requires the extension(s) '{required}'; this reader implements \
                     the core specification only"
                ),
            });
        }
    }
    if root.empty {
        return parser.fail("<model> has no <resources> or <build>");
    }

    let mut document = ModelDocument {
        unit,
        meshes: Vec::new(),
        objects: Vec::new(),
        by_id: FxHashMap::default(),
        items: Vec::new(),
        materials: FxHashMap::default(),
    };
    let mut saw_build = false;
    loop {
        match parser.next()? {
            Event::Start(tag) => {
                if tag.namespace != CORE_NAMESPACE {
                    parser.skip(&tag)?;
                    continue;
                }
                match tag.name.as_str() {
                    "resources" => parse_resources(&mut parser, &tag, &mut document)?,
                    "build" => {
                        saw_build = true;
                        parse_build(&mut parser, &tag, &mut document)?;
                    }
                    // <metadata>, <metadatagroup>: no geometry.
                    _ => parser.skip(&tag)?,
                }
            }
            Event::End { name } if name == "model" => break,
            Event::End { .. } => {}
            Event::Eof => return parser.fail("the part ends inside <model>"),
        }
    }
    if !saw_build {
        return parser.fail("<model> has no <build> element");
    }
    if document.items.is_empty() {
        return parser.fail("<build> places no items, so the file has no geometry to import");
    }
    Ok(document)
}

fn parse_resources(
    parser: &mut ModelParser<'_>,
    resources: &StartTag,
    document: &mut ModelDocument,
) -> Result<(), ThreeMfError> {
    if resources.empty {
        return Ok(());
    }
    loop {
        match parser.next()? {
            Event::Start(tag) => {
                if tag.namespace != CORE_NAMESPACE {
                    parser.skip(&tag)?;
                    continue;
                }
                match tag.name.as_str() {
                    "object" => parse_object(parser, &tag, document)?,
                    // The core specification's one property group. The
                    // extension's colour groups, textures and composites are
                    // in another namespace and were skipped above.
                    "basematerials" => parse_base_materials(parser, &tag, document)?,
                    _ => parser.skip(&tag)?,
                }
            }
            Event::End { name } if name == "resources" => return Ok(()),
            Event::End { .. } => {}
            Event::Eof => return parser.fail("the part ends inside <resources>"),
        }
    }
}

/// `<basematerials id>` → its `<base displaycolor>`s, in order. A group with
/// an unreadable id is skipped (no triangle can name it); a repeated id keeps
/// the first definition.
fn parse_base_materials(
    parser: &mut ModelParser<'_>,
    group: &StartTag,
    document: &mut ModelDocument,
) -> Result<(), ThreeMfError> {
    let id = group.attribute("id").and_then(|text| text.trim().parse::<u32>().ok());
    let mut colors = Vec::new();
    if !group.empty {
        loop {
            match parser.next()? {
                Event::Start(tag) => {
                    if tag.namespace == CORE_NAMESPACE && tag.name == "base" {
                        colors.push(tag.attribute("displaycolor").and_then(parse_display_color));
                        parser.close_leaf(&tag)?;
                    } else {
                        parser.skip(&tag)?;
                    }
                }
                Event::End { name } if name == "basematerials" => break,
                Event::End { .. } => {}
                Event::Eof => return parser.fail("the part ends inside <basematerials>"),
            }
        }
    }
    if let Some(id) = id {
        document.materials.entry(id).or_insert(colors);
    }
    Ok(())
}

fn parse_object(
    parser: &mut ModelParser<'_>,
    object: &StartTag,
    document: &mut ModelDocument,
) -> Result<(), ThreeMfError> {
    let id = parser.identifier(object, "id")?;
    if document.by_id.contains_key(&id) {
        return parser.fail(format!("object id {id} is defined twice"));
    }
    let object_property = parser.property(object, "pindex");
    let model_type = match object.attribute("type") {
        None | Some("model") => true,
        Some("solidsupport" | "support" | "surface" | "other") => false,
        Some(other) => {
            return parser.fail(format!("object {id} has an unknown type=\"{other}\""))
        }
    };
    if object.empty {
        return parser.fail(format!("object {id} has neither <mesh> nor <components>"));
    }
    let mut content: Option<ObjectContent> = None;
    loop {
        match parser.next()? {
            Event::Start(tag) => {
                if tag.namespace != CORE_NAMESPACE {
                    parser.skip(&tag)?;
                    continue;
                }
                match tag.name.as_str() {
                    "mesh" => {
                        if content.is_some() {
                            return parser
                                .fail(format!("object {id} has more than one geometry element"));
                        }
                        let mesh = parse_mesh(parser, &tag, id, model_type, object_property)?;
                        document.meshes.push(mesh);
                        content = Some(ObjectContent::Mesh(document.meshes.len() - 1));
                    }
                    "components" => {
                        if content.is_some() {
                            return parser
                                .fail(format!("object {id} has more than one geometry element"));
                        }
                        content = Some(ObjectContent::Components(parse_components(
                            parser, &tag, id, document,
                        )?));
                    }
                    _ => parser.skip(&tag)?,
                }
            }
            Event::End { name } if name == "object" => break,
            Event::End { .. } => {}
            Event::Eof => return parser.fail(format!("the part ends inside object {id}")),
        }
    }
    let Some(content) = content else {
        return parser.fail(format!("object {id} has neither <mesh> nor <components>"));
    };
    let name = object
        .attribute("name")
        .map(str::trim)
        .filter(|name| !name.is_empty())
        .map(str::to_owned);
    document.objects.push(Object { id, model_type, name, content });
    document.by_id.insert(id, document.objects.len() - 1);
    Ok(())
}

fn parse_mesh(
    parser: &mut ModelParser<'_>,
    mesh: &StartTag,
    object_id: u32,
    model_type: bool,
    object_property: Option<Property>,
) -> Result<RawMesh, ThreeMfError> {
    let mut positions = Vec::<f64>::new();
    let mut indices = Vec::<u32>::new();
    let mut properties = Vec::<Option<Property>>::new();
    if !mesh.empty {
        loop {
            match parser.next()? {
                Event::Start(tag) => {
                    if tag.namespace != CORE_NAMESPACE {
                        parser.skip(&tag)?;
                        continue;
                    }
                    match tag.name.as_str() {
                        "vertices" => parse_vertices(parser, &tag, object_id, &mut positions)?,
                        "triangles" => {
                            parse_triangles(parser, &tag, object_id, &mut indices, &mut properties)?
                        }
                        // <beamlattice> is an extension; anything else here is
                        // not geometry the core spec defines.
                        _ => parser.skip(&tag)?,
                    }
                }
                Event::End { name } if name == "mesh" => break,
                Event::End { .. } => {}
                Event::Eof => {
                    return parser.fail(format!("the part ends inside object {object_id}'s <mesh>"))
                }
            }
        }
    }
    let vertex_count = positions.len() / 3;
    for (triangle, corners) in indices.chunks_exact(3).enumerate() {
        for corner in corners {
            if *corner as usize >= vertex_count {
                return parser.fail(format!(
                    "object {object_id} triangle {triangle} names vertex {corner}, but the mesh \
                     has {vertex_count} vertices"
                ));
            }
        }
        if corners[0] == corners[1] || corners[1] == corners[2] || corners[0] == corners[2] {
            return parser.fail(format!(
                "object {object_id} triangle {triangle} repeats a vertex index"
            ));
        }
    }
    // A model object is printable geometry; the core spec requires a mesh that
    // encloses volume, which an empty one cannot.
    if model_type && (vertex_count < 3 || indices.is_empty()) {
        return parser.fail(format!(
            "object {object_id} is a model object whose mesh has {vertex_count} vertices and {} \
             triangles",
            indices.len() / 3
        ));
    }
    Ok(RawMesh { object_id, positions, indices, object_property, properties })
}

fn parse_vertices(
    parser: &mut ModelParser<'_>,
    vertices: &StartTag,
    object_id: u32,
    positions: &mut Vec<f64>,
) -> Result<(), ThreeMfError> {
    if vertices.empty {
        return Ok(());
    }
    loop {
        match parser.next()? {
            Event::Start(tag) => {
                if tag.namespace != CORE_NAMESPACE {
                    parser.skip(&tag)?;
                    continue;
                }
                if tag.name != "vertex" {
                    parser.skip(&tag)?;
                    continue;
                }
                if positions.len() / 3 >= MAX_MESH_VERTICES {
                    return Err(ThreeMfError::Bounds {
                        part: parser.part.to_owned(),
                        detail: format!(
                            "object {object_id} declares more than {MAX_MESH_VERTICES} vertices"
                        ),
                    });
                }
                let x = parser.coordinate(&tag, "x")?;
                let y = parser.coordinate(&tag, "y")?;
                let z = parser.coordinate(&tag, "z")?;
                positions.extend([x, y, z]);
                parser.close_leaf(&tag)?;
            }
            Event::End { name } if name == "vertices" => return Ok(()),
            Event::End { .. } => {}
            Event::Eof => {
                return parser
                    .fail(format!("the part ends inside object {object_id}'s <vertices>"))
            }
        }
    }
}

fn parse_triangles(
    parser: &mut ModelParser<'_>,
    triangles: &StartTag,
    object_id: u32,
    indices: &mut Vec<u32>,
    properties: &mut Vec<Option<Property>>,
) -> Result<(), ThreeMfError> {
    if triangles.empty {
        return Ok(());
    }
    loop {
        match parser.next()? {
            Event::Start(tag) => {
                if tag.namespace != CORE_NAMESPACE {
                    parser.skip(&tag)?;
                    continue;
                }
                if tag.name != "triangle" {
                    parser.skip(&tag)?;
                    continue;
                }
                if indices.len() / 3 >= MAX_MESH_TRIANGLES {
                    return Err(ThreeMfError::Bounds {
                        part: parser.part.to_owned(),
                        detail: format!(
                            "object {object_id} declares more than {MAX_MESH_TRIANGLES} triangles"
                        ),
                    });
                }
                // v1/v2/v3 are the geometry. pid/p1 is the triangle's own
                // property (a base material resolves to a colour; p2/p3 may
                // only differ for an extension's per-vertex groups, which are
                // not read); without one the triangle inherits its object's.
                let v1 = parser.index(&tag, "v1")?;
                let v2 = parser.index(&tag, "v2")?;
                let v3 = parser.index(&tag, "v3")?;
                indices.extend([v1, v2, v3]);
                properties.push(parser.property(&tag, "p1"));
                parser.close_leaf(&tag)?;
            }
            Event::End { name } if name == "triangles" => return Ok(()),
            Event::End { .. } => {}
            Event::Eof => {
                return parser
                    .fail(format!("the part ends inside object {object_id}'s <triangles>"))
            }
        }
    }
}

fn parse_components(
    parser: &mut ModelParser<'_>,
    components: &StartTag,
    object_id: u32,
    document: &ModelDocument,
) -> Result<Vec<Component>, ThreeMfError> {
    let mut out = Vec::new();
    if components.empty {
        return parser.fail(format!("object {object_id} has an empty <components>"));
    }
    loop {
        match parser.next()? {
            Event::Start(tag) => {
                if tag.namespace != CORE_NAMESPACE {
                    parser.skip(&tag)?;
                    continue;
                }
                if tag.name != "component" {
                    parser.skip(&tag)?;
                    continue;
                }
                let referenced = parser.identifier(&tag, "objectid")?;
                // The core spec requires a component's object to be defined
                // BEFORE it is used, which is also what makes the resource
                // graph acyclic. A forward or self reference is refused here.
                if !document.by_id.contains_key(&referenced) {
                    return parser.fail(format!(
                        "object {object_id} has a component naming object {referenced}, which is \
                         not defined before it"
                    ));
                }
                let transform = parser.transform(&tag)?;
                out.push(Component { object_id: referenced, transform });
                parser.close_leaf(&tag)?;
            }
            Event::End { name } if name == "components" => break,
            Event::End { .. } => {}
            Event::Eof => {
                return parser
                    .fail(format!("the part ends inside object {object_id}'s <components>"))
            }
        }
    }
    if out.is_empty() {
        return parser.fail(format!("object {object_id} has an empty <components>"));
    }
    Ok(out)
}

fn parse_build(
    parser: &mut ModelParser<'_>,
    build: &StartTag,
    document: &mut ModelDocument,
) -> Result<(), ThreeMfError> {
    if build.empty {
        return Ok(());
    }
    loop {
        match parser.next()? {
            Event::Start(tag) => {
                if tag.namespace != CORE_NAMESPACE {
                    parser.skip(&tag)?;
                    continue;
                }
                if tag.name != "item" {
                    parser.skip(&tag)?;
                    continue;
                }
                let object_id = parser.identifier(&tag, "objectid")?;
                if !document.by_id.contains_key(&object_id) {
                    return parser.fail(format!(
                        "<build> places object {object_id}, which <resources> does not define"
                    ));
                }
                let transform = parser.transform(&tag)?;
                document.items.push(Item { object_id, transform });
                parser.close_leaf(&tag)?;
            }
            Event::End { name } if name == "build" => return Ok(()),
            Event::End { .. } => {}
            Event::Eof => return parser.fail("the part ends inside <build>"),
        }
    }
}