Skip to main content

ifc_geometry/input/
representation.rs

1//! Context and representation-selection views.
2//!
3//! # Why selection is a policy, not a first entry
4//!
5//! A product commonly carries several representations: an Axis
6//! centreline, a FootPrint outline and a Body solid, in file
7//! order. Taking Representations[0] yields a 2D curve for any
8//! wall authored by Revit, which renders as nothing. Callers
9//! that want a solid must ask for one by identifier.
10
11use ifc_model::{Entity, EntityId, Model};
12
13use crate::error::{GeometryError, GeometryResult};
14use crate::slots::Slots;
15
16/// Absolute slots on IfcProductRepresentation.
17pub mod product_shape_slot {
18    /// LIST of IfcRepresentation.
19    pub const REPRESENTATIONS: usize = 2;
20}
21
22/// Absolute slots on IfcRepresentation.
23pub mod representation_slot {
24    /// The IfcRepresentationContext this representation is authored into.
25    pub const CONTEXT_OF_ITEMS: usize = 0;
26    /// Body, Axis, FootPrint; OPTIONAL in the schema.
27    pub const REPRESENTATION_IDENTIFIER: usize = 1;
28    /// Plan, Curve2D, SweptSolid, Brep; OPTIONAL in the schema.
29    pub const REPRESENTATION_TYPE: usize = 2;
30    /// The representation items themselves.
31    pub const ITEMS: usize = 3;
32}
33
34/// One IfcRepresentation: a named set of items in a context.
35#[derive(Debug, Clone, Copy)]
36pub struct Representation<'m> {
37    slots: Slots<'m>,
38}
39
40impl<'m> Representation<'m> {
41    /// Wrap an entity assumed to be an IfcRepresentation subtype.
42    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
43        Self {
44            slots: Slots::new(id, entity),
45        }
46    }
47
48    /// Body, Axis, FootPrint; absent when the author omitted it.
49    pub fn identifier(&self) -> Option<String> {
50        self.slots
51            .opt_text(representation_slot::REPRESENTATION_IDENTIFIER)
52    }
53
54    /// Plan, Curve2D, SweptSolid, Brep; absent when the author omitted it.
55    pub fn representation_type(&self) -> Option<String> {
56        self.slots
57            .opt_text(representation_slot::REPRESENTATION_TYPE)
58    }
59
60    /// The `IfcRepresentationContext` this representation is authored into.
61    pub fn context(&self) -> Option<EntityId> {
62        match self.slots.opt(representation_slot::CONTEXT_OF_ITEMS)? {
63            ifc_model::Value::Ref(id) => Some(*id),
64            _ => None,
65        }
66    }
67
68    /// The representation items to lower.
69    pub fn items(&self) -> GeometryResult<Vec<EntityId>> {
70        self.slots.req_ref_list(representation_slot::ITEMS, "Items")
71    }
72}
73
74/// One IfcProductRepresentation: the ordered representations of a product.
75#[derive(Debug, Clone, Copy)]
76pub struct ProductShape<'m> {
77    slots: Slots<'m>,
78}
79
80impl<'m> ProductShape<'m> {
81    /// Wrap an entity assumed to be an IfcProductRepresentation subtype.
82    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
83        Self {
84            slots: Slots::new(id, entity),
85        }
86    }
87
88    /// Representations in authored order.
89    pub fn representations(&self) -> GeometryResult<Vec<EntityId>> {
90        self.slots
91            .req_ref_list(product_shape_slot::REPRESENTATIONS, "Representations")
92    }
93}
94
95/// Representation identifiers that carry solid geometry, best first.
96///
97/// Body is the shape a viewer draws. Facetation is the IFC2x3-era
98/// fallback some exporters still emit. Axis and FootPrint are
99/// deliberately absent: they are 2D annotations, and selecting one
100/// silently replaces a solid with a line.
101pub const SOLID_IDENTIFIERS: &[&str] = &["Body", "Facetation"];
102
103/// Pick the representation a viewer should draw for this product.
104///
105/// Preference order is SOLID_IDENTIFIERS, then any representation whose
106/// identifier is missing. A file whose only representation is an Axis
107/// returns None rather than a curve masquerading as a body.
108pub fn select_shape_representation(
109    model: &Model,
110    product: EntityId,
111) -> GeometryResult<Option<EntityId>> {
112    let entity = model.get(product).ok_or(GeometryError::MissingEntity {
113        referrer: product,
114        missing: product,
115    })?;
116    let Some(shape_id) = super::product::Product::new(product, entity).representation() else {
117        return Ok(None);
118    };
119
120    let shape_entity = model.get(shape_id).ok_or(GeometryError::MissingEntity {
121        referrer: product,
122        missing: shape_id,
123    })?;
124    let candidates = ProductShape::new(shape_id, shape_entity).representations()?;
125
126    for wanted in SOLID_IDENTIFIERS {
127        for &candidate in &candidates {
128            let Some(entity) = model.get(candidate) else {
129                continue;
130            };
131            let identifier = Representation::new(candidate, entity).identifier();
132            if identifier.as_deref() == Some(*wanted) {
133                return Ok(Some(candidate));
134            }
135        }
136    }
137
138    // No named solid representation: accept an unnamed one, since some
139    // authors omit the identifier entirely, but never an Axis/FootPrint.
140    for &candidate in &candidates {
141        let Some(entity) = model.get(candidate) else {
142            continue;
143        };
144        if Representation::new(candidate, entity)
145            .identifier()
146            .is_none()
147        {
148            return Ok(Some(candidate));
149        }
150    }
151    Ok(None)
152}
153
154/// Representation identifiers that carry 2D drawing geometry, best first.
155///
156/// The inverse of [`SOLID_IDENTIFIERS`]. `Plan` and `Annotation` are authored
157/// for drawings directly; `FootPrint` is the product outline a plan is usually
158/// built from; `Axis` is the centreline, useful but least specific.
159///
160/// `Body` is deliberately absent: a solid in a plan selector would have to be
161/// sectioned before it means anything in 2D, and returning one would let a
162/// caller draw a projected solid where a plan curve was expected.
163pub const PLAN_IDENTIFIERS: &[&str] = &["Plan", "Annotation", "FootPrint", "Axis"];
164
165/// Caller intent for representation selection.
166///
167/// `Body` and `Plan` are policies over several identifiers
168/// ([`SOLID_IDENTIFIERS`], [`PLAN_IDENTIFIERS`]). The others name one
169/// `RepresentationIdentifier` (#458): the first representation the product
170/// authors with it, in authored order, whatever its context. A product
171/// without one has none for that purpose, which is not a failure.
172#[non_exhaustive]
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
174pub enum RepresentationPurpose {
175    /// Product shape suitable for model/body consumers.
176    Body,
177    /// Plan/annotation/axis geometry suitable for 2D drawing consumers.
178    Plan,
179    /// The `Axis` representation: a wall's or a member's centreline.
180    Axis,
181    /// The `FootPrint` representation: the product's outline on its floor.
182    FootPrint,
183    /// The `Annotation` representation: drawing curves and text.
184    Annotation,
185    /// The `Surface` representation: a surface standing for the product,
186    /// such as a structural surface member's mid-surface.
187    Surface,
188    /// The `Reference` representation: geometry provided beside the Body
189    /// for reference, such as an IFC4 Reference View `IfcOpeningElement`'s
190    /// void, which is not subtracted from its host (IFC4 ADD2 TC1
191    /// `IfcOpeningElement`; ADR 0014).
192    Reference,
193}
194
195impl RepresentationPurpose {
196    /// The one `RepresentationIdentifier` this purpose selects, or `None`
197    /// for the `Body` and `Plan` policies over several.
198    #[must_use]
199    pub const fn identifier(self) -> Option<&'static str> {
200        match self {
201            Self::Body | Self::Plan => None,
202            Self::Axis => Some("Axis"),
203            Self::FootPrint => Some("FootPrint"),
204            Self::Annotation => Some("Annotation"),
205            Self::Surface => Some("Surface"),
206            Self::Reference => Some("Reference"),
207        }
208    }
209
210    /// The purpose named `name`: `Body`, `Plan`, or one of the identifiers
211    /// [`Self::identifier`] names, exactly as IFC spells them.
212    #[must_use]
213    pub fn from_name(name: &str) -> Option<Self> {
214        [
215            Self::Body,
216            Self::Plan,
217            Self::Axis,
218            Self::FootPrint,
219            Self::Annotation,
220            Self::Surface,
221            Self::Reference,
222        ]
223        .into_iter()
224        .find(|purpose| purpose.name() == name)
225    }
226
227    /// The name [`Self::from_name`] reads.
228    #[must_use]
229    pub const fn name(self) -> &'static str {
230        match self {
231            Self::Body => "Body",
232            Self::Plan => "Plan",
233            Self::Axis => "Axis",
234            Self::FootPrint => "FootPrint",
235            Self::Annotation => "Annotation",
236            Self::Surface => "Surface",
237            Self::Reference => "Reference",
238        }
239    }
240}
241
242/// Select a product representation using an explicit consumer purpose.
243pub fn select_product_representation(
244    model: &Model,
245    product: EntityId,
246    purpose: RepresentationPurpose,
247) -> GeometryResult<Option<EntityId>> {
248    match purpose.identifier() {
249        Some(identifier) => select_identified_representation(model, product, identifier),
250        None if purpose == RepresentationPurpose::Plan => {
251            select_plan_representation(model, product)
252        }
253        None => select_shape_representation(model, product),
254    }
255}
256
257/// The first of the product's representations whose identifier is
258/// `identifier`, in authored order (#458).
259fn select_identified_representation(
260    model: &Model,
261    product: EntityId,
262    identifier: &str,
263) -> GeometryResult<Option<EntityId>> {
264    let entity = model.get(product).ok_or(GeometryError::MissingEntity {
265        referrer: product,
266        missing: product,
267    })?;
268    let Some(shape_id) = super::product::Product::new(product, entity).representation() else {
269        return Ok(None);
270    };
271    let shape_entity = model.get(shape_id).ok_or(GeometryError::MissingEntity {
272        referrer: product,
273        missing: shape_id,
274    })?;
275    let candidates = ProductShape::new(shape_id, shape_entity).representations()?;
276    Ok(candidates.into_iter().find(|&candidate| {
277        model.get(candidate).is_some_and(|entity| {
278            Representation::new(candidate, entity)
279                .identifier()
280                .as_deref()
281                == Some(identifier)
282        })
283    }))
284}
285
286/// Pick the representation a 2D drawing should use for this product.
287///
288/// Preference is, in order:
289///
290/// 1. a [`PLAN_IDENTIFIERS`] match **inside** a `PLAN_VIEW` sub-context --
291///    drawable geometry the author explicitly targeted at a plan;
292/// 2. otherwise the best [`PLAN_IDENTIFIERS`] match in any context.
293///
294/// The two rules are intersected, not ordered. Treating the context as
295/// sufficient on its own looks reasonable -- an author who sets
296/// `TargetView = .PLAN_VIEW.` has stated intent -- but ArchiCAD authors
297/// `Box`/`BoundingBox` shape representations *inside* a `PLAN_VIEW`
298/// sub-context. A context-first rule returns those boxes and never reaches
299/// the identifier list: on `AC20-FZK-Haus.ifc` that was 107 of 253 shape
300/// representations, and every plan lookup came back a box. Authorial intent
301/// selects *between* drawable candidates; it does not make a bounding box
302/// drawable.
303///
304/// Returns `None` when the product has only solid or bounding-box geometry.
305/// That is a real answer, not a failure: deriving a plan from a solid needs
306/// sectioning, which this crate does not do. A caller that wants an outline
307/// anyway should say so explicitly rather than be handed a box that claims
308/// to be a plan.
309pub fn select_plan_representation(
310    model: &Model,
311    product: EntityId,
312) -> GeometryResult<Option<EntityId>> {
313    let entity = model.get(product).ok_or(GeometryError::MissingEntity {
314        referrer: product,
315        missing: product,
316    })?;
317    let Some(shape_id) = super::product::Product::new(product, entity).representation() else {
318        return Ok(None);
319    };
320    let shape_entity = model.get(shape_id).ok_or(GeometryError::MissingEntity {
321        referrer: product,
322        missing: shape_id,
323    })?;
324    let candidates = ProductShape::new(shape_id, shape_entity).representations()?;
325
326    // 1. Drawable AND explicitly targeted at a plan.
327    for wanted in PLAN_IDENTIFIERS {
328        for &candidate in &candidates {
329            let Some(entity) = model.get(candidate) else {
330                continue;
331            };
332            if Representation::new(candidate, entity)
333                .identifier()
334                .as_deref()
335                != Some(*wanted)
336            {
337                continue;
338            }
339            let Some(context) = super::context::context_of(model, candidate) else {
340                continue;
341            };
342            if context.is_plan_view() {
343                return Ok(Some(candidate));
344            }
345        }
346    }
347
348    // 2. Drawable in any context.
349
350    for wanted in PLAN_IDENTIFIERS {
351        for &candidate in &candidates {
352            let Some(entity) = model.get(candidate) else {
353                continue;
354            };
355            if Representation::new(candidate, entity)
356                .identifier()
357                .as_deref()
358                == Some(*wanted)
359            {
360                return Ok(Some(candidate));
361            }
362        }
363    }
364    Ok(None)
365}