Skip to main content

openbim_ifc_binding_core/
geometry.rs

1//! Geometry for the hosts (#328, #367, ADR 0021), at three levels.
2//!
3//! - **Placements** (feature `placements`, default): per product, the world
4//!   placement as a 4x4 column-major matrix in metres and the Body
5//!   representation a viewer draws, with its identifier, type and context.
6//!   Kernel-free: the facade's `product_placements`.
7//! - **Graphs** (feature `graph`, #367): per product, the Body lowered
8//!   into Axiolid's neutral geometry graph, exact, serialised in Axiolid's
9//!   versioned wire format (1.0 to 1.5) as JSON or CBOR ([`graph`]).
10//!   Computes nothing; the facade's `product_graphs`.
11//! - **Meshes** (feature `mesh`, opt-in): per product, triangles compiled by
12//!   the reference backend, `f32` positions relative to the product's world
13//!   placement and `u32` indices. The facade's `product_meshes`; it links an
14//!   execution provider, which ADR 0004 keeps out of every default build.
15//!   Each mesh carries its surface colour (#449): RGB and transparency, and
16//!   whether the representation item, its presentation layer or its
17//!   material supplied it; `null` when nothing colours the product, with a
18//!   typed `colour_refusal` when its colour cannot be resolved; and its
19//!   `closure` (#458): `solid`, `surface` (area, no volume) or `unknown`.
20//!   `product_meshes_for` meshes another representation, such as `Surface`.
21//! - **Polylines** (feature `mesh`, #458): per product, the curves of a
22//!   curve representation (`Axis`, `FootPrint`, an annotation's curves),
23//!   one `f32` position array relative to the world placement and one
24//!   `ProductPolyline` record per curve, with its certified chord bound
25//!   ([`curves`]).
26//!
27//! A representation is named by a host as `Body` (the meshes' default),
28//! `Plan` (the polylines' default: `Plan`, `Annotation`, `FootPrint` or
29//! `Axis`, preferring a `PLAN_VIEW` context), or one identifier: `Axis`,
30//! `FootPrint`, `Annotation`, `Surface`, `Reference`. Another name is refused with
31//! `invalid-value`.
32//!
33//! A product that cannot be placed, selected or meshed is a record with a
34//! typed [`GeometryRefusal`], never an error that aborts the call: one
35//! broken wall does not hide the building. The refusal codes are the
36//! shared binding codes `unsupported`, `invalid-model`, `missing-reference`
37//! and `budget-exceeded`. Without its feature an operation refuses with
38//! `feature-disabled`.
39
40use crate::record::{Field, Record, ToRecord};
41use crate::{BindingError, IfcModel};
42
43pub mod curves;
44pub mod graph;
45
46/// Why one product has no placement, representation, graph or mesh.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct GeometryRefusal {
49    /// `unsupported` (valid IFC this build does not interpret, or a mesh
50    /// the backend refused), `invalid-model` (geometry the file states
51    /// wrongly), `missing-reference` (a reference to an entity the file
52    /// lacks) or `budget-exceeded` (a cycle, or a chain or aggregate over
53    /// its limit).
54    pub code: String,
55    /// The entity at fault, when the refusal names one.
56    pub entity: Option<u64>,
57    /// A one-line explanation.
58    pub message: String,
59}
60
61/// The `IfcShapeRepresentation` selected as a product's Body, and its
62/// context.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct SelectedRepresentation {
65    /// The representation's entity id.
66    pub id: u64,
67    /// `RepresentationIdentifier`, e.g. `Body`.
68    pub identifier: Option<String>,
69    /// `RepresentationType`, e.g. `SweptSolid`.
70    pub representation_type: Option<String>,
71    /// `ContextOfItems`, when the file contains it.
72    pub context: Option<u64>,
73    /// The context's `ContextType`, e.g. `Model` (a sub-context's derived
74    /// from its parent).
75    pub context_type: Option<String>,
76    /// The context's `ContextIdentifier`, e.g. `Body`.
77    pub context_identifier: Option<String>,
78    /// A sub-context's `TargetView` literal, e.g. `MODEL_VIEW`.
79    pub target_view: Option<String>,
80}
81
82/// One product's world placement and selected Body representation.
83#[derive(Debug, Clone, PartialEq)]
84pub struct ProductPlacement {
85    /// The product's entity id.
86    pub id: u64,
87    /// Its `GlobalId`.
88    pub global_id: Option<String>,
89    /// Its entity type, upper-case: `IFCWALL`, ...
90    pub type_name: String,
91    /// The world placement, 4x4 column-major, metres; `None` when refused.
92    pub transform: Option<[f64; 16]>,
93    /// The Body representation; `None` when the product has no solid
94    /// representation (an axis only) or its selection was refused.
95    pub representation: Option<SelectedRepresentation>,
96    /// Why the placement or the selection was refused, the placement's
97    /// reason first.
98    pub refusal: Option<GeometryRefusal>,
99}
100
101/// The surface colour a mesh is painted with (#449).
102#[derive(Debug, Clone, PartialEq)]
103pub struct SurfaceColour {
104    /// Red, in `[0, 1]`.
105    pub red: f64,
106    /// Green, in `[0, 1]`.
107    pub green: f64,
108    /// Blue, in `[0, 1]`.
109    pub blue: f64,
110    /// `Transparency` in `[0, 1]`, 0 opaque; `None` when the file states
111    /// none, which the standard reads as opaque.
112    pub transparency: Option<f64>,
113    /// Where the style was assigned: `item` (an `IfcStyledItem` on the
114    /// representation item), `layer` (an `IfcPresentationLayerWithStyle`),
115    /// `material` (the `IfcMaterial`'s
116    /// `IfcMaterialDefinitionRepresentation`) or `materialSet` (a layer,
117    /// profile or constituent set whose materials all state this colour,
118    /// #603), in that precedence.
119    pub source: String,
120    /// The `IfcStyledItem`, the layer assignment, the `IfcMaterial` or, for
121    /// `materialSet`, the set: an `IfcMaterialLayerSet`,
122    /// `IfcMaterialProfileSet`, `IfcMaterialConstituentSet` or
123    /// `IfcMaterialList`, or a usage of one (`IfcMaterialLayerSetUsage`,
124    /// `IfcMaterialProfileSetUsage` and its `Tapering`).
125    pub source_entity: u64,
126    /// The `IfcSurfaceStyle` the colour is read from.
127    pub surface_style: u64,
128    /// When `source` is `materialSet`, the materials of the set that colour
129    /// the item: every one, or the constituents its shape aspects name
130    /// (ascending id, distinct); else empty. Last, so the earlier fields
131    /// keep their positions.
132    pub source_materials: Vec<u64>,
133}
134
135/// One product's Body as triangles.
136#[derive(Debug, Clone, PartialEq)]
137pub struct ProductMesh {
138    /// The product's entity id.
139    pub id: u64,
140    /// Its `GlobalId`.
141    pub global_id: Option<String>,
142    /// Its entity type, upper-case.
143    pub type_name: String,
144    /// The world placement, 4x4 column-major, metres: a vertex's world
145    /// position is this matrix applied to it. `None` when refused.
146    pub transform: Option<[f64; 16]>,
147    /// `x, y, z` per vertex, metres, relative to `transform`.
148    pub positions: Vec<f32>,
149    /// Three vertex indices per triangle.
150    pub indices: Vec<u32>,
151    /// Why there is no mesh. Empty arrays and no refusal is a product
152    /// with no Body representation (an axis only).
153    pub refusal: Option<GeometryRefusal>,
154    /// The surface colour the Body's items agree on; `None` when nothing
155    /// colours the product or its colour is refused.
156    pub colour: Option<SurfaceColour>,
157    /// Why the colour could not be resolved: `ambiguous` (two styled items
158    /// or two colours at one level, a layer or profile set of several
159    /// materials, a constituent set no shape aspect resolves, or Body items
160    /// of different colours), or the shared codes `invalid-model`,
161    /// `missing-reference`, `unsupported` and `budget-exceeded`. Never
162    /// refuses the mesh itself.
163    pub colour_refusal: Option<GeometryRefusal>,
164    /// `solid` when the mesh bounds a volume the file declared, `surface`
165    /// for a surface (a surface model, a face, a trimmed surface: an area
166    /// and no volume), `unknown` for an empty or refused mesh (#458).
167    pub closure: String,
168}
169
170impl IfcModel {
171    /// The world placement and selected Body of each of `products`, or,
172    /// with `None`, of every product that has a shape, in id order.
173    ///
174    /// An id the model lacks is a record refused with `missing-reference`.
175    /// Refused as a whole only with `unsupported-schema` (the header names
176    /// a release this build does not bundle, as for the domain views) and
177    /// `feature-disabled` without the `placements` feature.
178    pub fn product_placements(
179        &self,
180        products: Option<&[u64]>,
181    ) -> Result<Vec<ProductPlacement>, BindingError> {
182        #[cfg(feature = "placements")]
183        {
184            placements(self, products)
185        }
186        #[cfg(not(feature = "placements"))]
187        {
188            let _ = products;
189            Err(BindingError::FeatureDisabled("placements"))
190        }
191    }
192
193    /// The Body mesh of each of `products`, or, with `None`, of every
194    /// product that has a shape, in id order. Tolerance: one millimetre.
195    ///
196    /// Refused as a whole only as [`Self::product_placements`] is, and with
197    /// `feature-disabled` without the `mesh` feature.
198    pub fn product_meshes(
199        &self,
200        products: Option<&[u64]>,
201    ) -> Result<Vec<ProductMesh>, BindingError> {
202        self.product_meshes_for(products, "Body")
203    }
204
205    /// The surfaces and solids of each product's `representation` as one
206    /// mesh (#458): `Body` as [`Self::product_meshes`], or another name the
207    /// module docs list, such as `Surface`. Curves are not meshed:
208    /// [`Self::product_curves`] returns them. A product without that
209    /// representation, or with curves only, has an empty mesh and no
210    /// refusal. Only a Body mesh carries a colour.
211    ///
212    /// Refused as a whole as [`Self::product_meshes`] is, and with
213    /// `invalid-value` for a representation name it does not know.
214    pub fn product_meshes_for(
215        &self,
216        products: Option<&[u64]>,
217        representation: &str,
218    ) -> Result<Vec<ProductMesh>, BindingError> {
219        #[cfg(feature = "mesh")]
220        {
221            meshes(self, products, purpose(representation)?)
222        }
223        #[cfg(not(feature = "mesh"))]
224        {
225            let _ = (products, representation);
226            Err(BindingError::FeatureDisabled("mesh"))
227        }
228    }
229}
230
231/// The selector purpose a host names, or `invalid-value`.
232#[cfg(feature = "mesh")]
233fn purpose(name: &str) -> Result<ifc::RepresentationPurpose, BindingError> {
234    ifc::RepresentationPurpose::from_name(name).ok_or_else(|| {
235        BindingError::InvalidValue(format!(
236            "representation must be Body, Plan, Axis, FootPrint, Annotation, Surface or Reference, \
237             not {name:?}"
238        ))
239    })
240}
241
242#[cfg(feature = "placements")]
243fn ids(products: Option<&[u64]>) -> Option<Vec<ifc::EntityId>> {
244    products.map(|ids| ids.iter().copied().map(ifc::EntityId).collect())
245}
246
247/// `GlobalId` and entity type of a product, or of an id the model lacks.
248#[cfg(feature = "placements")]
249fn product_identity(model: &IfcModel, id: u64) -> Result<(Option<String>, String), BindingError> {
250    let identity = model.identity(id)?;
251    let type_name = model
252        .inner
253        .get(ifc::EntityId(id))
254        .map_or_else(String::new, |entity| entity.type_name.to_string());
255    Ok((identity.global_id, type_name))
256}
257
258#[cfg(feature = "placements")]
259fn placements(
260    model: &IfcModel,
261    products: Option<&[u64]>,
262) -> Result<Vec<ProductPlacement>, BindingError> {
263    let products = ids(products);
264    let mut out = Vec::new();
265    for placement in ifc::product_placements(&model.inner, products.as_deref()) {
266        let id = placement.product.0;
267        let (global_id, type_name) = product_identity(model, id)?;
268        let refusal = placement
269            .world
270            .as_ref()
271            .err()
272            .or(placement.body.as_ref().err())
273            .map(refusal);
274        let representation = placement.body.ok().flatten().map(|body| {
275            let context = body.context.as_ref();
276            SelectedRepresentation {
277                id: body.id.0,
278                identifier: body.identifier.clone(),
279                representation_type: body.representation_type.clone(),
280                context: context.map(|c| c.id.0),
281                context_type: context.and_then(|c| c.context_type.clone()),
282                context_identifier: context.and_then(|c| c.identifier.clone()),
283                target_view: context.and_then(|c| c.target_view.clone()),
284            }
285        });
286        out.push(ProductPlacement {
287            id,
288            global_id,
289            type_name,
290            transform: placement.world.ok().map(|world| ifc::column_major(&world)),
291            representation,
292            refusal,
293        });
294    }
295    Ok(out)
296}
297
298#[cfg(feature = "mesh")]
299fn meshes(
300    model: &IfcModel,
301    products: Option<&[u64]>,
302    purpose: ifc::RepresentationPurpose,
303) -> Result<Vec<ProductMesh>, BindingError> {
304    let products = ids(products);
305    let mut out = Vec::new();
306    for (product, mesh) in ifc::product_meshes_for(&model.inner, products.as_deref(), purpose) {
307        let (global_id, type_name) = product_identity(model, product.0)?;
308        let mut record = ProductMesh {
309            id: product.0,
310            global_id,
311            type_name,
312            transform: None,
313            positions: Vec::new(),
314            indices: Vec::new(),
315            refusal: None,
316            colour: None,
317            colour_refusal: None,
318            closure: "unknown".to_owned(),
319        };
320        match mesh {
321            Ok(mesh) => {
322                record.transform = Some(ifc::column_major(&mesh.world));
323                record.positions = mesh.positions;
324                record.indices = mesh.indices;
325                record.closure = closure(mesh.closure).to_owned();
326                match mesh.colour {
327                    Ok(colour) => record.colour = colour.as_ref().map(surface_colour),
328                    Err(error) => record.colour_refusal = Some(colour_refusal(&error)),
329                }
330            }
331            Err(error) => record.refusal = Some(refusal(&error)),
332        }
333        out.push(record);
334    }
335    Ok(out)
336}
337
338/// The typed refusal for a geometry error.
339#[cfg(feature = "placements")]
340fn refusal(error: &ifc::geometry::GeometryError) -> GeometryRefusal {
341    use ifc::geometry::GeometryError as E;
342    let code = match error {
343        E::MissingEntity { .. } => "missing-reference",
344        E::CyclicChain { .. } | E::ChainTooDeep { .. } | E::AggregateTooLarge { .. } => {
345            "budget-exceeded"
346        }
347        E::Unsupported { .. } => "unsupported",
348        #[cfg(feature = "mesh")]
349        E::CompilationRefused { .. } => "unsupported",
350        // A net refusal is as typed as its cause; gross meshes never raise it.
351        E::OpeningNotSubtracted { cause, .. } => return refusal(cause),
352        E::MissingAttribute { .. }
353        | E::WrongValueKind { .. }
354        | E::WrongEntityType { .. }
355        | E::Degenerate { .. }
356        | E::Units(_)
357        | E::LengthUnitUndeclared { .. }
358        | E::AngleUnitUndeclared { .. }
359        | E::UnitUnreadable { .. }
360        | E::UnitsAmbiguous { .. }
361        | E::UnitRecordDamaged { .. }
362        | E::UnitsIncomplete { .. } => "invalid-model",
363        // A refusal added to the bridge after this binding, or one only an
364        // evaluator raises: still typed, never dropped.
365        other if other.is_unsupported() => "unsupported",
366        _ => "invalid-model",
367    };
368    GeometryRefusal {
369        code: code.to_owned(),
370        entity: error.entity().map(|id| id.0),
371        message: error.to_string(),
372    }
373}
374
375/// The host name of a mesh's closure.
376#[cfg(feature = "mesh")]
377fn closure(closure: ifc::geometry::compile::MeshClosure) -> &'static str {
378    use ifc::geometry::compile::MeshClosure as C;
379    match closure {
380        C::Solid => "solid",
381        C::Surface => "surface",
382        // `Unknown`, or a closure added to the contract after this binding.
383        _ => "unknown",
384    }
385}
386
387/// The host record of a resolved colour.
388#[cfg(feature = "mesh")]
389fn surface_colour(colour: &ifc::SurfaceColour) -> SurfaceColour {
390    use ifc::ColourSource as S;
391    let mut materials = Vec::new();
392    let (source, entity) = match &colour.source {
393        S::StyledItem(id) => ("item", *id),
394        S::PresentationLayer(id) => ("layer", *id),
395        S::Material { material, .. } => ("material", *material),
396        S::MaterialSet {
397            definition,
398            materials: set,
399        } => {
400            materials = set.iter().map(|id| id.0).collect();
401            ("materialSet", *definition)
402        }
403        // A source added to the facade after this binding: still typed.
404        _ => ("other", colour.surface_style),
405    };
406    let [red, green, blue] = colour.rgb;
407    SurfaceColour {
408        red,
409        green,
410        blue,
411        transparency: colour.transparency,
412        source: source.to_owned(),
413        source_entity: entity.0,
414        source_materials: materials,
415        surface_style: colour.surface_style.0,
416    }
417}
418
419/// The typed refusal for a colour that cannot be resolved.
420#[cfg(feature = "mesh")]
421fn colour_refusal(error: &ifc::ColourError) -> GeometryRefusal {
422    use ifc::material::MaterialError as M;
423    use ifc::style::StyleError as S;
424    use ifc::ColourError as E;
425    let (code, entity) = match error {
426        E::Geometry(error) => return refusal(error),
427        E::AmbiguousMaterial { item, .. } => ("ambiguous", Some(*item)),
428        E::ItemsDiffer { product, .. } => ("ambiguous", Some(*product)),
429        E::DecidersDiffer { product, .. } => ("ambiguous", Some(*product)),
430        E::UnsupportedSchema { .. } => ("unsupported", None),
431        E::Style(S::AmbiguousStyleAssignment { item, .. }) => ("ambiguous", Some(*item)),
432        E::Style(S::AmbiguousSurfaceColour { owner, .. }) => ("ambiguous", Some(*owner)),
433        E::Style(S::UnknownEntity { id }) => ("missing-reference", Some(*id)),
434        E::Style(S::DanglingReference { source_id, .. }) => ("missing-reference", Some(*source_id)),
435        E::Style(S::UnsupportedSchema { .. }) => ("unsupported", None),
436        E::Material(M::AmbiguousAssignment { object, .. } | M::AmbiguousType { object, .. }) => {
437            ("ambiguous", Some(*object))
438        }
439        E::Material(M::UnsupportedSchema { .. }) => ("unsupported", None),
440        E::Material(M::UnknownEntity { id }) => ("missing-reference", Some(*id)),
441        _ => ("invalid-model", None),
442    };
443    GeometryRefusal {
444        code: code.to_owned(),
445        entity: entity.map(|id| id.0),
446        message: error.to_string(),
447    }
448}
449
450/// A column-major matrix as a list of 16 reals, or `NULL`.
451fn matrix(transform: Option<&[f64; 16]>) -> Field {
452    Field::optional(transform, |m| {
453        Field::List(m.iter().copied().map(Field::Real).collect())
454    })
455}
456
457impl ToRecord for GeometryRefusal {
458    fn to_record(&self) -> Record {
459        Record::new(
460            "GeometryRefusal",
461            vec![
462                ("code", Field::Text(self.code.clone())),
463                ("entity", Field::id(self.entity)),
464                ("message", Field::Text(self.message.clone())),
465            ],
466        )
467    }
468}
469
470impl ToRecord for SelectedRepresentation {
471    fn to_record(&self) -> Record {
472        Record::new(
473            "SelectedRepresentation",
474            vec![
475                ("id", Field::Id(self.id)),
476                ("identifier", Field::text(self.identifier.clone())),
477                (
478                    "representation_type",
479                    Field::text(self.representation_type.clone()),
480                ),
481                ("context", Field::id(self.context)),
482                ("context_type", Field::text(self.context_type.clone())),
483                (
484                    "context_identifier",
485                    Field::text(self.context_identifier.clone()),
486                ),
487                ("target_view", Field::text(self.target_view.clone())),
488            ],
489        )
490    }
491}
492
493impl ToRecord for ProductPlacement {
494    fn to_record(&self) -> Record {
495        Record::new(
496            "ProductPlacement",
497            vec![
498                ("id", Field::Id(self.id)),
499                ("global_id", Field::text(self.global_id.clone())),
500                ("type_name", Field::Text(self.type_name.clone())),
501                ("transform", matrix(self.transform.as_ref())),
502                (
503                    "representation",
504                    Field::record(self.representation.as_ref()),
505                ),
506                ("refusal", Field::record(self.refusal.as_ref())),
507            ],
508        )
509    }
510}
511
512/// The mesh's metadata: the arrays cross separately, in each host's
513/// typed-array form (`Float32Array`, `array('f')`, a caller `float`
514/// buffer), never as a list of reals.
515impl ToRecord for ProductMesh {
516    fn to_record(&self) -> Record {
517        Record::new(
518            "ProductMesh",
519            vec![
520                ("id", Field::Id(self.id)),
521                ("global_id", Field::text(self.global_id.clone())),
522                ("type_name", Field::Text(self.type_name.clone())),
523                ("transform", matrix(self.transform.as_ref())),
524                ("vertex_count", Field::Count(self.positions.len() / 3)),
525                ("triangle_count", Field::Count(self.indices.len() / 3)),
526                ("refusal", Field::record(self.refusal.as_ref())),
527                ("colour", Field::record(self.colour.as_ref())),
528                (
529                    "colour_refusal",
530                    Field::record(self.colour_refusal.as_ref()),
531                ),
532                ("closure", Field::Text(self.closure.clone())),
533            ],
534        )
535    }
536}
537
538impl ToRecord for SurfaceColour {
539    fn to_record(&self) -> Record {
540        Record::new(
541            "SurfaceColour",
542            vec![
543                ("red", Field::Real(self.red)),
544                ("green", Field::Real(self.green)),
545                ("blue", Field::Real(self.blue)),
546                (
547                    "transparency",
548                    Field::optional(self.transparency.as_ref(), |t| Field::Real(*t)),
549                ),
550                ("source", Field::Text(self.source.clone())),
551                ("source_entity", Field::Id(self.source_entity)),
552                ("surface_style", Field::Id(self.surface_style)),
553                (
554                    "source_materials",
555                    Field::List(
556                        self.source_materials
557                            .iter()
558                            .map(|&id| Field::Id(id))
559                            .collect(),
560                    ),
561                ),
562            ],
563        )
564    }
565}