Skip to main content

ifc_geometry/lower/
mapped.rs

1//! Mapped-item instancing: reuse one lowered subtree under many transforms.
2//!
3//! # Why this preserves instancing
4//!
5//! A mapped item is IFC's only first-class instancing mechanism. A furniture
6//! family placed 400 times is authored once as an `IfcRepresentationMap` and
7//! referenced by 400 `IfcMappedItem`s. Flattening that into 400 copies of the
8//! geometry is the single most expensive mistake an importer can make, so the
9//! lowered form keeps the shared subtree and emits one `Instance` per use.
10//!
11//! # Transform composition
12//!
13//! Three frames stack, outermost first:
14//!
15//! ```text
16//!   world  o  MappingTarget  o  MappingOrigin
17//! ```
18//!
19//! `MappingOrigin` locates the geometry inside the map's own space, and
20//! `MappingTarget` places the instance. Getting the order backwards produces
21//! geometry that is plausibly near the right place, which is far worse than an
22//! obvious failure.
23
24use axiolid_model::{GeometryNode, Instance, NodeId};
25use ifc_model::EntityId;
26
27use crate::error::GeometryResult;
28use crate::lower::session::LoweringSession;
29use crate::resource::mapped::{MappedItem, RepresentationMap};
30use crate::resource::operator::operator_transform;
31use crate::resource::placement::axis_placement_transform;
32use crate::transform::Transform;
33
34/// Family label for mapped-item memoization.
35const MAPPED: &str = "mapped-item";
36
37/// Family label for representation memoization.
38const REPRESENTATION: &str = "representation";
39
40/// Chain kind reported when a mapping graph closes on itself.
41pub(crate) const KIND: &str = "mapped item";
42
43/// Attribute index of `Items` on `IfcRepresentation`.
44const REPRESENTATION_ITEMS: usize = 3;
45
46/// Lower one `IfcMappedItem` into an `Instance` over its shared source.
47///
48/// The source representation is lowered once per world frame and memoized, so
49/// repeated occurrences of one map share a subtree instead of duplicating it.
50pub fn lower_mapped_item_node(
51    session: &mut LoweringSession<'_>,
52    id: EntityId,
53    world: Transform,
54) -> GeometryResult<NodeId> {
55    if let Some(node) = session.memoized(id, MAPPED, world) {
56        return Ok(node);
57    }
58    session.enter(id, KIND)?;
59    let node = lower_mapped_item_inner(session, id, world);
60    session.exit(id);
61    let node = node?;
62    session.memoize(id, MAPPED, world, node);
63    Ok(node)
64}
65
66fn lower_mapped_item_inner(
67    session: &mut LoweringSession<'_>,
68    id: EntityId,
69    world: Transform,
70) -> GeometryResult<NodeId> {
71    let occurrence = mapped_occurrence(session, id, world)?;
72
73    // The source subtree is lowered in the map's own space. Keeping the world
74    // frame OUT of the shared subtree is what lets many occurrences reuse it;
75    // the per-occurrence placement rides on the Instance transform instead.
76    let source = lower_representation(session, occurrence.representation)?;
77
78    session.node_for(
79        id,
80        GeometryNode::Instance(Instance {
81            source,
82            transform: occurrence.placement.to_geom(),
83        }),
84    )
85}
86
87/// One `IfcMappedItem` resolved: the map's representation and the placement of
88/// this occurrence.
89pub(crate) struct MappedOccurrence {
90    /// The `IfcRepresentation` the map's `MappedRepresentation` names.
91    pub(crate) representation: EntityId,
92    /// `world . MappingTarget . MappingOrigin`, in metres.
93    pub(crate) placement: Transform,
94}
95
96/// Resolve source, target, map, origin and representation of a mapped item and
97/// compose its placement under `frame`.
98pub(crate) fn mapped_occurrence(
99    session: &LoweringSession<'_>,
100    id: EntityId,
101    frame: Transform,
102) -> GeometryResult<MappedOccurrence> {
103    let entity = session.entity(id, id)?;
104    let item = MappedItem::new(id, entity);
105    let source_ref = item.mapping_source()?;
106    let target_ref = item.mapping_target()?;
107
108    let map_entity = session.entity(id, source_ref)?;
109    let map = RepresentationMap::new(source_ref, map_entity);
110    let origin_ref = map.mapping_origin()?;
111    let representation = map.mapped_representation()?;
112
113    // MappingTarget places the instance; MappingOrigin locates geometry inside
114    // the map's own space. Both are resolved before recursing so a malformed
115    // operator fails fast against the item that referenced it.
116    let target_entity = session.entity(id, target_ref)?;
117    // Both frames carry file-unit coordinates; convert exactly once here.
118    let target =
119        operator_transform(session.model(), target_ref, target_entity)?.to_metres(session.units());
120    let origin_entity = session.entity(source_ref, origin_ref)?;
121    let origin = axis_placement_transform(session.model(), origin_ref, origin_entity)?
122        .to_metres(session.units());
123
124    Ok(MappedOccurrence {
125        representation,
126        placement: frame.compose(&target).compose(&origin),
127    })
128}
129
130/// The `Items` of an `IfcRepresentation`, in authored order.
131pub(crate) fn representation_items(
132    session: &LoweringSession<'_>,
133    id: EntityId,
134) -> GeometryResult<Vec<EntityId>> {
135    let slots = session.slots(id)?;
136    slots.req_ref_list(REPRESENTATION_ITEMS, "Items")
137}
138
139/// Lower every item of an `IfcRepresentation` into one collection node.
140///
141/// A representation is an ordered set of items, so the neutral form is a
142/// `Collection`. An empty item list is valid IFC and lowers to an empty
143/// collection rather than an error.
144pub fn lower_representation(
145    session: &mut LoweringSession<'_>,
146    id: EntityId,
147) -> GeometryResult<NodeId> {
148    let frame = Transform::identity();
149    if let Some(node) = session.memoized(id, REPRESENTATION, frame) {
150        return Ok(node);
151    }
152    session.enter(id, KIND)?;
153    let node = lower_representation_inner(session, id);
154    session.exit(id);
155    let node = node?;
156    session.memoize(id, REPRESENTATION, frame, node);
157    Ok(node)
158}
159
160fn lower_representation_inner(
161    session: &mut LoweringSession<'_>,
162    id: EntityId,
163) -> GeometryResult<NodeId> {
164    let items = representation_items(session, id)?;
165
166    let mut members = Vec::with_capacity(items.len());
167    for item in items {
168        // Items inside a map are lowered in the map's own space; the
169        // occurrence transform lives on the Instance that wraps this
170        // collection, never baked into the shared geometry.
171        members.push(session.lower_operand(item, Transform::identity())?);
172    }
173    session.node_for(id, GeometryNode::Collection(members))
174}