ifc_lite_geometry/representation/
select.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//! Which of a product's representations a caller means: the single canonical
6//! definition of which `IfcShapeRepresentation`s carry renderable body geometry
7//! ([`Select::Meshed`]) and the other questions asked of the same list.
8
9use ifc_lite_core::{slot, DecodedEntity, IfcType};
10
11/// Whether an `IfcShapeRepresentation.RepresentationType` names a meshable
12/// body/surface (as opposed to a curve/axis/annotation/footprint/box). This is
13/// the SINGLE canonical definition of "renderable 3D geometry", shared by the
14/// element meshing path (`processing.rs`), the void probe (opening extraction),
15/// RTC-offset detection, and material-layer slicing so every site agrees on what
16/// counts as real geometry. Drift here is a bug: an element meshed as body but
17/// judged non-body by RTC detection casts a spurious origin vote (see
18/// `rtc_offset::sample_element_translation`).
19///
20/// `MappedRepresentation` is included (its `IfcMappedItem`s expand to real
21/// solids); callers that specifically mean DIRECT (non-mapped) geometry use
22/// [`is_direct_body_representation`] instead.
23pub(crate) fn is_body_representation(rep_type: &str) -> bool {
24    matches!(
25        rep_type,
26        "Body"
27            | "SweptSolid"
28            | "Brep"
29            | "CSG"
30            | "Clipping"
31            | "Tessellation"
32            | "MappedRepresentation"
33            | "SolidModel"
34            | "SurfaceModel"
35            | "Surface3D"
36            | "AdvancedSweptSolid"
37            | "AdvancedBrep"
38    )
39}
40
41/// Whether a `RepresentationType` names DIRECT (non-mapped) body geometry, i.e.
42/// [`is_body_representation`] minus the `MappedRepresentation` sentinel. Used to
43/// decide whether an element's `MappedRepresentation` duplicates geometry it
44/// already carries directly (and so can be skipped to avoid double-meshing).
45pub(crate) fn is_direct_body_representation(rep_type: &str) -> bool {
46    rep_type != "MappedRepresentation" && is_body_representation(rep_type)
47}
48
49/// Whether a near-origin element with this `RepresentationType` may cast a
50/// "no-shift" `(0,0,0)` RTC vote when the vertex probe can't cheaply read a
51/// coordinate. This is [`is_body_representation`] MINUS `"Surface3D"` —
52/// meshable does NOT imply RTC-votable.
53///
54/// A `Surface3D` rep (`IfcBSplineSurfaceWithKnots`, `IfcSectionedSurface`,
55/// trimmed/curve-bounded surfaces) keeps its geometry in absolute model-space
56/// control points that the RTC vertex probe cannot navigate, so a near-origin
57/// identity-placed Surface3D element would fall through to voting its placement
58/// `(0,0,0)` even though its real geometry can sit on a national grid hundreds
59/// of km away. On IFC4X3 corridor models with many such surfaces ahead of a few
60/// large-coordinate solids, those origin votes drag the median to zero and/or
61/// exhaust the 50-sample budget, suppressing a legitimate rebase — the #1526
62/// curve-only pollution rebuilt via Surface3D. So Surface3D must ABSTAIN here,
63/// like a curve/axis rep. Scoped to RTC voting only: the meshing / void / layer
64/// paths still treat Surface3D as body geometry.
65pub(crate) fn is_rtc_votable_representation(rep_type: &str) -> bool {
66    rep_type != "Surface3D" && is_body_representation(rep_type)
67}
68
69/// The string that should drive body-representation filtering for an
70/// `IfcShapeRepresentation`: `RepresentationType` (attribute 2) when present
71/// and non-blank, else the `RepresentationIdentifier` (attribute 1).
72///
73/// CATIA exports write `IFCSHAPEREPRESENTATION(#ctx,'Body','',(items))` —
74/// the TYPE is an empty string while the IDENTIFIER carries 'Body'. Filtering
75/// on the raw type alone vetoes the whole representation and the element
76/// meshes to zero triangles (issue #1661: both reported walls). A `$` (null)
77/// type never reached the filter, so only the empty-string spelling was
78/// affected.
79pub(crate) fn effective_rep_type(shape_rep: &DecodedEntity) -> Option<&str> {
80    [2usize, 1].into_iter().find_map(|idx| {
81        shape_rep
82            .get(idx)
83            .and_then(|a| a.as_string())
84            .filter(|s| !s.trim().is_empty())
85    })
86}
87
88/// Opening Reference geometry describes an existing hole, never a cutter.
89/// Keep ordinary products' rendering convention unchanged; only opening
90/// semantics override the otherwise type-first representation predicate (#4433).
91pub(crate) fn effective_element_rep_type<'a>(element: &DecodedEntity, shape_rep: &'a DecodedEntity) -> Option<&'a str> {
92    if element.ifc_type.is_subtype_of(IfcType::IfcOpeningElement)
93        && shape_rep.get_string(1).is_some_and(|id| id.eq_ignore_ascii_case("Reference")) {
94        return Some("Reference");
95    }
96    effective_rep_type(shape_rep)
97}
98
99/// Which of a product's representations a caller means. The variants are the
100/// distinct questions the router asks of one `Representations` list; each is a
101/// filter over the same list, in list order.
102#[non_exhaustive]
103#[derive(Clone, Copy)]
104pub enum Select {
105    /// What the mesh path renders ([`meshed_representations`]): the one
106    /// definition of "what renders".
107    Meshed,
108    /// `IfcShapeRepresentation`s whose effective type is body geometry, with no
109    /// mapped-duplicate exclusion (material-layer slicing).
110    Body,
111    /// What may cast an RTC vote: `IfcShapeRepresentation`s of an
112    /// RTC-votable body type, plus a structural `Face` topology representation.
113    RtcVotable,
114    /// Every representation.
115    Any,
116    /// A caller predicate over `(element, representation, effective type)`.
117    Where(fn(&DecodedEntity, &DecodedEntity, Option<&str>) -> bool),
118}
119
120impl Select {
121    /// Whether `rep` of `element` is selected. `has_direct_geometry` is
122    /// [`has_direct_geometry`] of the whole list, read only by `Meshed`.
123    pub(super) fn admits(
124        self,
125        element: &DecodedEntity,
126        rep: &DecodedEntity,
127        has_direct_geometry: bool,
128    ) -> bool {
129        // A drawing camera's box is no building geometry under any body
130        // policy: excluding it from meshing alone would leave it voting the
131        // RTC origin and feeding layer slicing (the drift noted above).
132        if matches!(self, Select::Body | Select::RtcVotable) && is_drawing_camera_annotation(element) {
133            return false;
134        }
135        match self {
136            Select::Meshed => meshed_admits(element, rep, has_direct_geometry),
137            Select::Body => {
138                rep.ifc_type == IfcType::IfcShapeRepresentation
139                    && effective_element_rep_type(element, rep)
140                        .is_some_and(is_body_representation)
141            }
142            Select::RtcVotable => effective_element_rep_type(element, rep).is_some_and(|rep_type| {
143                (rep.ifc_type == IfcType::IfcShapeRepresentation
144                    && is_rtc_votable_representation(rep_type))
145                    || (rep.ifc_type == IfcType::IfcTopologyRepresentation
146                        && (rep_type == "Face"
147                            || (rep_type == "Undefined"
148                                && element.ifc_type.is_subtype_of(IfcType::IfcStructuralSurfaceMember)))
149                        && crate::router::structural::accepts(element, rep_type))
150            }),
151            Select::Any => true,
152            Select::Where(keep) => keep(element, rep, effective_element_rep_type(element, rep)),
153        }
154    }
155
156    /// Whether `has_direct_geometry` must be computed for this policy.
157    pub(super) fn needs_direct_geometry(self) -> bool {
158        matches!(self, Select::Meshed)
159    }
160}
161
162/// Whether the list carries direct (non-mapped) body geometry, which makes a
163/// `MappedRepresentation` of the same element a duplicate.
164pub(super) fn has_direct_geometry(element: &DecodedEntity, representations: &[DecodedEntity]) -> bool {
165    representations
166        .iter()
167        .filter(|rep| rep.ifc_type == IfcType::IfcShapeRepresentation)
168        .any(|rep| {
169            effective_element_rep_type(element, rep).is_some_and(is_direct_body_representation)
170        })
171}
172
173/// Whether `element` is a Bonsai drawing camera: an `IfcAnnotation` whose
174/// `ObjectType` is `DRAWING`. Bonsai makes each
175/// drawing (plan, section, elevation, schedule) such an annotation, with an
176/// `EPset_Drawing` property set and the camera's extent as a box body; it is
177/// the drawing's frame, never part of the building. Bonsai itself selects
178/// drawings by this test: IfcOpenShell `src/bonsai/bonsai/bim/module/drawing/operator.py`
179/// (`ObjectType == "DRAWING"` over `IfcAnnotation`) and `prop.py`
180/// (`EPset_Drawing`). Other annotations (grid, text, markup) are untouched.
181pub(crate) fn is_drawing_camera_annotation(element: &DecodedEntity) -> bool {
182    element.ifc_type == IfcType::IfcAnnotation
183        && element
184            .string_at(slot::IfcAnnotation::OBJECT_TYPE)
185            .is_some_and(|t| t.trim().eq_ignore_ascii_case("DRAWING"))
186}
187
188fn meshed_admits(element: &DecodedEntity, rep: &DecodedEntity, has_direct_geometry: bool) -> bool {
189    // A drawing camera meshes nothing (`admits` also bars it from `Body` and
190    // `RtcVotable`); every meshing path selects through here.
191    if is_drawing_camera_annotation(element) {
192        return false;
193    }
194    // A structural curve member's edge geometry lives on an
195    // `IfcTopologyRepresentation`, not an `IfcShapeRepresentation` — a
196    // different entity type entirely, though both are `IfcRepresentation`
197    // subtypes sharing the same `ContextOfItems`/`RepresentationIdentifier`/
198    // `RepresentationType`/`Items` attribute layout, so `effective_rep_type`
199    // reads it the same way. Gated on `structural::accepts` so this doesn't
200    // open `IfcTopologyRepresentation` up generally (e.g. the fixture's
201    // `'Vertex'`-typed ones on `IfcStructuralPointConnection`, out of scope
202    // here — see `structural::accepts`'s doc comment).
203    let is_meshable_rep = rep.ifc_type == IfcType::IfcShapeRepresentation
204        || (rep.ifc_type == IfcType::IfcTopologyRepresentation
205            && effective_rep_type(rep)
206                .is_some_and(|rt| crate::router::structural::accepts(element, rt)));
207    is_meshable_rep
208        && effective_element_rep_type(element, rep).is_none_or(|rep_type| {
209            !(rep_type == "MappedRepresentation" && has_direct_geometry)
210                && (is_body_representation(rep_type)
211                    || crate::router::annotation::accepts(element, rep_type)
212                    || crate::router::structural::accepts(element, rep_type))
213        })
214}
215
216/// The representations of `element` (its `IfcProductDefinitionShape`
217/// `Representations`, decoded) that the element meshing paths mesh, in order:
218/// each `IfcShapeRepresentation` whose effective type is body geometry, or an
219/// annotation's 2D fill, or that names no type at all, minus a
220/// `MappedRepresentation` when the element also carries direct body geometry.
221/// Anything that must agree with what renders (the `IgnoreOpaque` opening
222/// filter in `ifc-lite-processing`, #4699) selects through this.
223pub fn meshed_representations<'a>(
224    element: &'a DecodedEntity,
225    representations: &'a [DecodedEntity],
226) -> impl Iterator<Item = &'a DecodedEntity> + 'a {
227    let direct = has_direct_geometry(element, representations);
228    representations.iter().filter(move |rep| meshed_admits(element, rep, direct))
229}