ifc_lite_geometry/representation/
mod.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! The structural home of a product's representations: the
6//! `Representation(6) → IfcProductDefinitionShape.Representations(2) → Items(3)`
7//! chain, which representations a caller means ([`Select`]) and a visitor walk
8//! over the items and the `IfcMappedItem`s among them ([`RepresentationWalk`]).
9//!
10//! Decoder-only: this module meshes nothing and owns no cache. The router,
11//! RTC-vote probes and the layer slicer are all callers of it.
12
13pub(crate) mod first_seen;
14pub(crate) mod mapped_transform;
15pub(crate) mod product_budget;
16mod refusal;
17mod select;
18pub(crate) mod structural;
19pub use structural::{mapped_item_representation_id, pds_representation_ids, product_shape_id, rep_item_ids};
20pub(crate) mod unwrap;
21mod walk;
22pub use select::{meshed_representations, Select};
23pub use walk::{Flow, MappedLevel, NestedMaps, RepresentationWalk, WalkCtx, WalkBudgetRefusal, WalkRefusal, WalkVisitor, MAX_WALK_LEVELS};
24
25pub(crate) use select::{
26    effective_element_rep_type, effective_rep_type, is_body_representation,
27    is_drawing_camera_annotation,
28};
29
30use ifc_lite_core::{DecodedEntity, EntityDecoder, IfcType};
31
32/// Why a product's shape chain could not be read. [`ShapeError`] converts into
33/// the geometry [`Error`](crate::Error) with the exact message text the strict
34/// element paths have always reported.
35#[derive(Debug)]
36pub enum ShapeError {
37    /// The product has no attribute 6 at all.
38    NoRepresentationAttribute { element: u32 },
39    /// Attribute 6 is a reference that does not resolve.
40    Unresolved,
41    /// Attribute 6 resolves to something other than an `IfcProductDefinitionShape`.
42    NotAProductDefinitionShape(IfcType),
43    /// The `IfcProductDefinitionShape` has no `Representations` attribute.
44    MissingRepresentations,
45    /// A representation has no `Items` attribute.
46    MissingItems,
47    /// The decoder failed on a reference.
48    Decode(ifc_lite_core::Error),
49}
50
51impl From<ifc_lite_core::Error> for ShapeError {
52    fn from(error: ifc_lite_core::Error) -> Self {
53        ShapeError::Decode(error)
54    }
55}
56
57impl From<ShapeError> for crate::Error {
58    fn from(error: ShapeError) -> Self {
59        match error {
60            ShapeError::NoRepresentationAttribute { element } => crate::Error::geometry(format!(
61                "Element #{element} has no representation attribute"
62            )),
63            ShapeError::Unresolved => {
64                crate::Error::geometry("Failed to resolve representation".to_string())
65            }
66            ShapeError::NotAProductDefinitionShape(found) => crate::Error::geometry(format!(
67                "Expected IfcProductDefinitionShape, got {found}"
68            )),
69            ShapeError::MissingRepresentations => crate::Error::geometry(
70                "IfcProductDefinitionShape missing Representations".to_string(),
71            ),
72            ShapeError::MissingItems => {
73                crate::Error::geometry("IfcShapeRepresentation missing Items".to_string())
74            }
75            ShapeError::Decode(error) => crate::Error::CoreError(error),
76        }
77    }
78}
79
80/// `IfcProductDefinitionShape.Representations` of a product, decoded once.
81pub struct ProductShape {
82    /// The `IfcProductDefinitionShape`'s id.
83    pub id: u32,
84    representations: Vec<DecodedEntity>,
85}
86
87/// The shape of `element`: `Ok(None)` iff its `Representation` (attribute 6) is
88/// `$`. Every other malformation is an `Err` carrying today's message text; the
89/// probes that abstain on malformed input call `.ok().flatten()`, so the
90/// leniency stays visible at the call site.
91pub fn product_shape(element: &DecodedEntity, decoder: &mut EntityDecoder) -> Result<Option<ProductShape>, ShapeError> {
92    product_shape_with_type_check(element, decoder, true)
93}
94
95// Opening probes historically admit the same slots on any shape record type.
96// Keep that policy private: strict public product_shape admission is unchanged.
97pub(crate) fn product_shape_unchecked(
98    element: &DecodedEntity,
99    decoder: &mut EntityDecoder,
100) -> Result<Option<ProductShape>, ShapeError> {
101    product_shape_with_type_check(element, decoder, false)
102}
103
104fn product_shape_with_type_check(
105    element: &DecodedEntity,
106    decoder: &mut EntityDecoder,
107    check_type: bool,
108) -> Result<Option<ProductShape>, ShapeError> {
109    // IfcProduct: GlobalId, OwnerHistory, Name, Description, ObjectType, ObjectPlacement, Representation, Tag
110    let attr = element
111        .get(6)
112        .ok_or(ShapeError::NoRepresentationAttribute { element: element.id })?;
113    if attr.is_null() {
114        return Ok(None);
115    }
116    let shape = decoder.resolve_ref(attr)?.ok_or(ShapeError::Unresolved)?;
117    // IFC2X3 types `Representation` as the then non-abstract
118    // `IfcProductRepresentation`, and AxisVM writes one for every structural
119    // curve member (#9668). Admitted for structural members only: elsewhere
120    // it stays malformed (#7781).
121    let bare_structural = shape.ifc_type == IfcType::IfcProductRepresentation
122        && element.ifc_type.is_subtype_of(IfcType::IfcStructuralMember);
123    if check_type && shape.ifc_type != IfcType::IfcProductDefinitionShape && !bare_structural {
124        return Err(ShapeError::NotAProductDefinitionShape(shape.ifc_type));
125    }
126    let list = shape.get(2).ok_or(ShapeError::MissingRepresentations)?;
127    Ok(Some(ProductShape { id: shape.id, representations: decoder.resolve_ref_list(list)? }))
128}
129
130impl ProductShape {
131    /// Every representation, in list order.
132    pub fn representations(&self) -> &[DecodedEntity] {
133        &self.representations
134    }
135
136    /// The representations `select` admits for `element`, in list order.
137    pub fn select<'a>(
138        &'a self,
139        element: &'a DecodedEntity,
140        select: Select,
141    ) -> impl Iterator<Item = &'a DecodedEntity> + 'a {
142        let direct =
143            select.needs_direct_geometry() && select::has_direct_geometry(element, &self.representations);
144        self.representations.iter().filter(move |rep| select.admits(element, rep, direct))
145    }
146}
147
148/// `Items` (attribute 3) of an `IfcShapeRepresentation`, an
149/// `IfcTopologyRepresentation` or a mapped representation, decoded.
150pub fn rep_items(
151    rep: &DecodedEntity,
152    decoder: &mut EntityDecoder,
153) -> Result<Vec<DecodedEntity>, ShapeError> {
154    let items = rep.get(3).ok_or(ShapeError::MissingItems)?;
155    Ok(decoder.resolve_ref_list(items)?)
156}
157
158#[cfg(test)]
159mod walk_tests;
160
161#[cfg(test)]
162mod work_budget_tests;
163
164#[cfg(test)]
165mod entry_policy_tests;
166
167#[cfg(test)]
168mod work_budget_regression_tests;