Skip to main content

openbim_ifc_binding_core/
material.rs

1//! Materials (feature `material`, #123).
2//!
3//! The facade's material view resolves the one material association that
4//! applies to an object: its own `IfcRelAssociatesMaterial`, or else its
5//! type object's. The association crosses as one record: what it points at
6//! (a material, a list, a layer, profile or constituent set, or a set
7//! usage), the set's layers, profiles or constituents with their materials,
8//! and a usage's placement parameters. Records are read against the release
9//! the header declares, IFC2X3, IFC4 or IFC4X3; any other is refused with
10//! `unsupported-schema`.
11//!
12//! Thicknesses, fractions and offsets are attributes the schema types as
13//! `REAL` measures, in the file's length unit, so they cross as host
14//! numbers; nothing is converted. A descriptive attribute the bound release
15//! does not declare (`Name` of an IFC2X3 `IfcMaterialLayer`, `Category` of
16//! an IFC2X3 `IfcMaterial`) is `null`, as is one the file leaves unset.
17
18use crate::record::{Field, Record, ToRecord};
19use crate::value::Tagged;
20use crate::{BindingError, IfcModel};
21
22/// The material association that applies to an object.
23#[derive(Debug, Clone, PartialEq)]
24pub struct MaterialAssignment {
25    /// The `IfcRelAssociatesMaterial`.
26    pub relationship: u64,
27    /// The relationship's `GlobalId`.
28    pub global_id: Option<String>,
29    /// `occurrence`: associated with the queried object; `type`: inherited
30    /// from its type object.
31    pub source: String,
32    /// For `type`, the type object's id.
33    pub type_object: Option<u64>,
34    /// The `RelatingMaterial`.
35    pub target: u64,
36    /// The target's entity type, upper-case.
37    pub type_name: String,
38    /// `material`, `list`, `layer`, `layer-set`, `layer-set-usage`,
39    /// `profile`, `profile-set`, `profile-set-usage`, `constituent` or
40    /// `constituent-set`.
41    pub kind: String,
42    /// For a set or a usage, the set's id (a usage's `ForLayerSet` or
43    /// `ForProfileSet`).
44    pub set: Option<u64>,
45    /// The set's `LayerSetName` or `Name`.
46    pub name: Option<String>,
47    /// `material`: the material; `list`: its materials, in file order.
48    pub materials: Vec<MaterialRef>,
49    /// `layer`, `layer-set`, `layer-set-usage`: the layers, in file order.
50    pub layers: Vec<MaterialLayer>,
51    /// `profile`, `profile-set`, `profile-set-usage`: the profiles.
52    pub profiles: Vec<MaterialProfile>,
53    /// `constituent`, `constituent-set`: the constituents.
54    pub constituents: Vec<MaterialConstituent>,
55    /// `layer-set-usage` and `profile-set-usage`: how the set is placed.
56    pub usage: Option<MaterialUsage>,
57}
58
59/// An `IfcMaterial`.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct MaterialRef {
62    /// Its entity id.
63    pub id: u64,
64    /// `Name`.
65    pub name: String,
66    /// `Category` (IFC4, IFC4X3).
67    pub category: Option<String>,
68}
69
70/// An `IfcMaterialLayer` (or `IfcMaterialLayerWithOffsets`).
71#[derive(Debug, Clone, PartialEq)]
72pub struct MaterialLayer {
73    /// Its entity id.
74    pub id: u64,
75    /// `Material`, when stated (an air gap may have none).
76    pub material: Option<MaterialRef>,
77    /// `LayerThickness`, in the file's length unit.
78    pub thickness: f64,
79    /// `IsVentilated`: `bool`, `unknown`, or `null` when unset.
80    pub is_ventilated: Tagged,
81    /// `Name` (IFC4, IFC4X3).
82    pub name: Option<String>,
83    /// `Category` (IFC4, IFC4X3).
84    pub category: Option<String>,
85    /// `Priority` (IFC4, IFC4X3).
86    pub priority: Option<i64>,
87}
88
89/// An `IfcMaterialProfile` (or `IfcMaterialProfileWithOffsets`).
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct MaterialProfile {
92    /// Its entity id.
93    pub id: u64,
94    /// `Material`, when stated.
95    pub material: Option<MaterialRef>,
96    /// `Profile`: the `IfcProfileDef`.
97    pub profile: u64,
98    /// `Name`.
99    pub name: Option<String>,
100    /// `Category`.
101    pub category: Option<String>,
102    /// `Priority`.
103    pub priority: Option<i64>,
104}
105
106/// An `IfcMaterialConstituent`.
107#[derive(Debug, Clone, PartialEq)]
108pub struct MaterialConstituent {
109    /// Its entity id.
110    pub id: u64,
111    /// `Material`.
112    pub material: MaterialRef,
113    /// `Name`.
114    pub name: Option<String>,
115    /// `Category`.
116    pub category: Option<String>,
117    /// `Fraction`, a ratio.
118    pub fraction: Option<f64>,
119}
120
121/// How a layer or profile set is placed relative to the element.
122#[derive(Debug, Clone, PartialEq)]
123pub struct MaterialUsage {
124    /// Layer sets: `AXIS1`, `AXIS2` or `AXIS3`.
125    pub layer_set_direction: Option<String>,
126    /// Layer sets: `POSITIVE` or `NEGATIVE`.
127    pub direction_sense: Option<String>,
128    /// Layer sets: `OffsetFromReferenceLine`, in the file's length unit.
129    pub offset_from_reference_line: Option<f64>,
130    /// `ReferenceExtent`, when stated.
131    pub reference_extent: Option<f64>,
132    /// Profile sets: `CardinalPoint`.
133    pub cardinal_point: Option<i64>,
134    /// Tapering profile sets: `ForProfileEndSet`.
135    pub end_set: Option<u64>,
136    /// Tapering profile sets: `CardinalEndPoint`.
137    pub cardinal_end_point: Option<i64>,
138}
139
140impl IfcModel {
141    /// The material association that applies to `object`, or `None` when
142    /// neither it nor its type object has one.
143    ///
144    /// Refused with `missing-entity` for an id not in the model,
145    /// `unsupported-schema` for a release other than IFC2X3, IFC4 or
146    /// IFC4X3, `invalid-model` when two associations (or two types) compete,
147    /// `missing-reference` for a dangling one, and `feature-disabled`
148    /// without the `material` feature.
149    pub fn material(&self, object: u64) -> Result<Option<MaterialAssignment>, BindingError> {
150        #[cfg(feature = "material")]
151        {
152            read::material(self, object)
153        }
154        #[cfg(not(feature = "material"))]
155        {
156            let _ = object;
157            Err(BindingError::FeatureDisabled("material"))
158        }
159    }
160}
161
162#[cfg(feature = "material")]
163mod read {
164    use ifc::material::{
165        material_schema, AssignmentSource, LogicalValue, MaterialDefinition, MaterialError,
166        MaterialResult, MaterialUsageDefinition, MaterialView, ResolvedMaterialSelect,
167    };
168    use ifc::EntityId;
169
170    use super::{
171        MaterialAssignment, MaterialConstituent, MaterialLayer, MaterialProfile, MaterialRef,
172        MaterialUsage,
173    };
174    use crate::value::Tagged;
175    use crate::{BindingError, IfcModel};
176
177    pub(super) fn material(
178        model: &IfcModel,
179        object: u64,
180    ) -> Result<Option<MaterialAssignment>, BindingError> {
181        if !model.inner.contains(EntityId(object)) {
182            return Err(BindingError::MissingEntity(object));
183        }
184        material_schema(&model.inner).map_err(error)?;
185        let view = MaterialView::new(&model.inner);
186        let Some(resolved) = view.assigned_material(EntityId(object)).map_err(error)? else {
187            return Ok(None);
188        };
189        let (source, type_object) = match resolved.source {
190            AssignmentSource::Occurrence => ("occurrence", None),
191            AssignmentSource::Type(id) => ("type", Some(id.0)),
192        };
193        let target = resolved.assignment.relating_material_id().map_err(error)?;
194        let mut out = MaterialAssignment {
195            relationship: resolved.assignment.id().0,
196            global_id: Some(resolved.assignment.global_id().map_err(error)?.to_owned()),
197            source: source.to_owned(),
198            type_object,
199            target: target.0,
200            type_name: model.type_of(target.0)?.to_owned(),
201            kind: String::new(),
202            set: None,
203            name: None,
204            materials: Vec::new(),
205            layers: Vec::new(),
206            profiles: Vec::new(),
207            constituents: Vec::new(),
208            usage: None,
209        };
210        fill(view, resolved.material, &mut out)?;
211        Ok(Some(out))
212    }
213
214    /// Fill `out` from the resolved select branch.
215    fn fill(
216        view: MaterialView<'_>,
217        select: ResolvedMaterialSelect<'_>,
218        out: &mut MaterialAssignment,
219    ) -> Result<(), BindingError> {
220        use MaterialDefinition as D;
221        use MaterialUsageDefinition as U;
222        use ResolvedMaterialSelect as S;
223        match select {
224            S::Definition(D::Material(material)) => {
225                out.kind = "material".to_owned();
226                out.materials.push(material_ref(view, material.id())?);
227            }
228            S::List(list) => {
229                out.kind = "list".to_owned();
230                for id in list.material_ids().map_err(error)? {
231                    out.materials.push(material_ref(view, id)?);
232                }
233            }
234            S::Definition(D::Layer(_) | D::LayerWithOffsets(_)) => {
235                out.kind = "layer".to_owned();
236                out.layers.push(layer(view, EntityId(out.target))?);
237            }
238            S::Definition(D::LayerSet(set)) => {
239                out.kind = "layer-set".to_owned();
240                layer_set(view, set.id(), out)?;
241            }
242            S::Usage(U::LayerSet(usage)) => {
243                out.kind = "layer-set-usage".to_owned();
244                layer_set(view, usage.layer_set_id().map_err(error)?, out)?;
245                out.usage = Some(MaterialUsage {
246                    layer_set_direction: Some(
247                        usage
248                            .layer_set_direction()
249                            .map_err(error)?
250                            .as_token()
251                            .to_owned(),
252                    ),
253                    direction_sense: Some(
254                        usage
255                            .direction_sense()
256                            .map_err(error)?
257                            .as_token()
258                            .to_owned(),
259                    ),
260                    offset_from_reference_line: Some(
261                        usage.offset_from_reference_line().map_err(error)?,
262                    ),
263                    reference_extent: declared(usage.reference_extent())?.flatten(),
264                    cardinal_point: None,
265                    end_set: None,
266                    cardinal_end_point: None,
267                });
268            }
269            S::Definition(D::Profile(_) | D::ProfileWithOffsets(_)) => {
270                out.kind = "profile".to_owned();
271                out.profiles.push(profile(view, EntityId(out.target))?);
272            }
273            S::Definition(D::ProfileSet(set)) => {
274                out.kind = "profile-set".to_owned();
275                profile_set(view, set.id(), out)?;
276            }
277            S::Usage(U::ProfileSet(usage)) => {
278                out.kind = "profile-set-usage".to_owned();
279                profile_set(view, usage.profile_set_id().map_err(error)?, out)?;
280                let mut placed = MaterialUsage {
281                    layer_set_direction: None,
282                    direction_sense: None,
283                    offset_from_reference_line: None,
284                    reference_extent: usage.reference_extent().map_err(error)?,
285                    cardinal_point: cardinal(usage.cardinal_point().map_err(error)?),
286                    end_set: None,
287                    cardinal_end_point: None,
288                };
289                if let Some(tapering) = usage.tapering() {
290                    placed.end_set = Some(tapering.end_profile_set_id().map_err(error)?.0);
291                    placed.cardinal_end_point =
292                        cardinal(tapering.cardinal_end_point().map_err(error)?);
293                }
294                out.usage = Some(placed);
295            }
296            S::Usage(U::ProfileSetTapering(usage)) => {
297                out.kind = "profile-set-usage".to_owned();
298                profile_set(view, usage.profile_set_id().map_err(error)?, out)?;
299                out.usage = Some(MaterialUsage {
300                    layer_set_direction: None,
301                    direction_sense: None,
302                    offset_from_reference_line: None,
303                    reference_extent: usage.reference_extent().map_err(error)?,
304                    cardinal_point: cardinal(usage.cardinal_point().map_err(error)?),
305                    end_set: Some(usage.end_profile_set_id().map_err(error)?.0),
306                    cardinal_end_point: cardinal(usage.cardinal_end_point().map_err(error)?),
307                });
308            }
309            S::Definition(D::Constituent(_)) => {
310                out.kind = "constituent".to_owned();
311                out.constituents
312                    .push(constituent(view, EntityId(out.target))?);
313            }
314            S::Definition(D::ConstituentSet(set)) => {
315                out.kind = "constituent-set".to_owned();
316                out.set = Some(set.id().0);
317                out.name = declared(set.name())?.flatten().map(str::to_owned);
318                for id in set.constituent_ids().map_err(error)?.unwrap_or_default() {
319                    out.constituents.push(constituent(view, id)?);
320                }
321            }
322        }
323        Ok(())
324    }
325
326    fn layer_set(
327        view: MaterialView<'_>,
328        id: EntityId,
329        out: &mut MaterialAssignment,
330    ) -> Result<(), BindingError> {
331        let set = ifc::material::MaterialLayerSet::try_from_view(view, id).map_err(error)?;
332        out.set = Some(id.0);
333        out.name = declared(set.name())?.flatten().map(str::to_owned);
334        for layer_id in set.layer_ids().map_err(error)? {
335            out.layers.push(layer(view, layer_id)?);
336        }
337        Ok(())
338    }
339
340    fn profile_set(
341        view: MaterialView<'_>,
342        id: EntityId,
343        out: &mut MaterialAssignment,
344    ) -> Result<(), BindingError> {
345        let set = ifc::material::MaterialProfileSet::try_from_view(view, id).map_err(error)?;
346        out.set = Some(id.0);
347        out.name = declared(set.name())?.flatten().map(str::to_owned);
348        for profile_id in set.profile_ids().map_err(error)? {
349            out.profiles.push(profile(view, profile_id)?);
350        }
351        Ok(())
352    }
353
354    /// The shared accessors of a layer and a layer with offsets.
355    macro_rules! read_layer {
356        ($view:expr, $layer:expr) => {{
357            let layer = $layer;
358            Ok(MaterialLayer {
359                id: layer.id().0,
360                material: optional_material($view, layer.material_id().map_err(error)?)?,
361                thickness: layer.thickness().map_err(error)?,
362                is_ventilated: match layer.is_ventilated().map_err(error)? {
363                    None => Tagged::Null,
364                    Some(LogicalValue::True) => Tagged::Bool(true),
365                    Some(LogicalValue::False) => Tagged::Bool(false),
366                    Some(LogicalValue::Unknown) => Tagged::Unknown,
367                },
368                name: declared(layer.name())?.flatten().map(str::to_owned),
369                category: declared(layer.category())?.flatten().map(str::to_owned),
370                priority: declared(layer.priority())?.flatten(),
371            })
372        }};
373    }
374
375    fn layer(view: MaterialView<'_>, id: EntityId) -> Result<MaterialLayer, BindingError> {
376        match view.resolve_material_select(id).map_err(error)? {
377            ResolvedMaterialSelect::Definition(MaterialDefinition::Layer(layer)) => {
378                read_layer!(view, layer)
379            }
380            ResolvedMaterialSelect::Definition(MaterialDefinition::LayerWithOffsets(layer)) => {
381                read_layer!(view, layer)
382            }
383            _ => Err(wrong(view, id, "IfcMaterialLayer")),
384        }
385    }
386
387    /// The shared accessors of a profile and a profile with offsets.
388    macro_rules! read_profile {
389        ($view:expr, $profile:expr) => {{
390            let profile = $profile;
391            Ok(MaterialProfile {
392                id: profile.id().0,
393                material: optional_material($view, profile.material_id().map_err(error)?)?,
394                profile: profile.profile_id().map_err(error)?.0,
395                name: declared(profile.name())?.flatten().map(str::to_owned),
396                category: declared(profile.category())?.flatten().map(str::to_owned),
397                priority: declared(profile.priority())?.flatten(),
398            })
399        }};
400    }
401
402    fn profile(view: MaterialView<'_>, id: EntityId) -> Result<MaterialProfile, BindingError> {
403        match view.resolve_material_select(id).map_err(error)? {
404            ResolvedMaterialSelect::Definition(MaterialDefinition::Profile(profile)) => {
405                read_profile!(view, profile)
406            }
407            ResolvedMaterialSelect::Definition(MaterialDefinition::ProfileWithOffsets(profile)) => {
408                read_profile!(view, profile)
409            }
410            _ => Err(wrong(view, id, "IfcMaterialProfile")),
411        }
412    }
413
414    fn constituent(
415        view: MaterialView<'_>,
416        id: EntityId,
417    ) -> Result<MaterialConstituent, BindingError> {
418        let constituent =
419            ifc::material::MaterialConstituent::try_from_view(view, id).map_err(error)?;
420        Ok(MaterialConstituent {
421            id: id.0,
422            material: material_ref(view, constituent.material_id().map_err(error)?)?,
423            name: declared(constituent.name())?.flatten().map(str::to_owned),
424            category: declared(constituent.category())?
425                .flatten()
426                .map(str::to_owned),
427            fraction: declared(constituent.fraction())?.flatten(),
428        })
429    }
430
431    fn optional_material(
432        view: MaterialView<'_>,
433        id: Option<EntityId>,
434    ) -> Result<Option<MaterialRef>, BindingError> {
435        id.map(|id| material_ref(view, id)).transpose()
436    }
437
438    fn material_ref(view: MaterialView<'_>, id: EntityId) -> Result<MaterialRef, BindingError> {
439        let material = ifc::material::Material::try_from_view(view, id).map_err(error)?;
440        Ok(MaterialRef {
441            id: id.0,
442            name: material.name().map_err(error)?.to_owned(),
443            category: declared(material.category())?.flatten().map(str::to_owned),
444        })
445    }
446
447    fn cardinal(point: Option<ifc::material::CardinalPointReference>) -> Option<i64> {
448        point.map(|point| i64::try_from(point.get()).unwrap_or(i64::MAX))
449    }
450
451    fn wrong(view: MaterialView<'_>, id: EntityId, expected: &str) -> BindingError {
452        let actual = view
453            .model()
454            .get(id)
455            .map_or("nothing", |entity| &*entity.type_name);
456        BindingError::WrongEntityType(format!("#{} is {actual}, not {expected}", id.0))
457    }
458
459    /// An attribute the bound release does not declare reads as `None`;
460    /// every other failure is the read's.
461    fn declared<T>(read: MaterialResult<T>) -> Result<Option<T>, BindingError> {
462        match read {
463            Ok(value) => Ok(Some(value)),
464            Err(MaterialError::NotInSchema { .. }) => Ok(None),
465            Err(other) => Err(error(other)),
466        }
467    }
468
469    fn error(error: MaterialError) -> BindingError {
470        use MaterialError as E;
471        let detail = error.to_string();
472        match error {
473            E::UnsupportedSchema { schema } => BindingError::UnsupportedSchema(schema),
474            E::MultipleSchemas { .. } => BindingError::UnsupportedSchema(detail),
475            E::UnknownEntity { id } => BindingError::MissingEntity(id.0),
476            E::DanglingReference { .. } => BindingError::MissingReference(detail),
477            E::WrongEntityType { .. } => BindingError::WrongEntityType(detail),
478            _ => BindingError::InvalidModel(detail),
479        }
480    }
481}
482
483impl ToRecord for MaterialAssignment {
484    fn to_record(&self) -> Record {
485        Record::new(
486            "MaterialAssignment",
487            vec![
488                ("relationship", Field::Id(self.relationship)),
489                ("global_id", Field::text(self.global_id.clone())),
490                ("source", Field::Text(self.source.clone())),
491                ("type_object", Field::id(self.type_object)),
492                ("target", Field::Id(self.target)),
493                ("type_name", Field::Text(self.type_name.clone())),
494                ("kind", Field::Text(self.kind.clone())),
495                ("set", Field::id(self.set)),
496                ("name", Field::text(self.name.clone())),
497                ("materials", Field::records(&self.materials)),
498                ("layers", Field::records(&self.layers)),
499                ("profiles", Field::records(&self.profiles)),
500                ("constituents", Field::records(&self.constituents)),
501                ("usage", Field::record(self.usage.as_ref())),
502            ],
503        )
504    }
505}
506
507impl ToRecord for MaterialRef {
508    fn to_record(&self) -> Record {
509        Record::new(
510            "MaterialRef",
511            vec![
512                ("id", Field::Id(self.id)),
513                ("name", Field::Text(self.name.clone())),
514                ("category", Field::text(self.category.clone())),
515            ],
516        )
517    }
518}
519
520impl ToRecord for MaterialLayer {
521    fn to_record(&self) -> Record {
522        Record::new(
523            "MaterialLayer",
524            vec![
525                ("id", Field::Id(self.id)),
526                ("material", Field::record(self.material.as_ref())),
527                ("thickness", Field::Real(self.thickness)),
528                ("is_ventilated", Field::Value(self.is_ventilated.clone())),
529                ("name", Field::text(self.name.clone())),
530                ("category", Field::text(self.category.clone())),
531                ("priority", Field::optional(self.priority, Field::Int)),
532            ],
533        )
534    }
535}
536
537impl ToRecord for MaterialProfile {
538    fn to_record(&self) -> Record {
539        Record::new(
540            "MaterialProfile",
541            vec![
542                ("id", Field::Id(self.id)),
543                ("material", Field::record(self.material.as_ref())),
544                ("profile", Field::Id(self.profile)),
545                ("name", Field::text(self.name.clone())),
546                ("category", Field::text(self.category.clone())),
547                ("priority", Field::optional(self.priority, Field::Int)),
548            ],
549        )
550    }
551}
552
553impl ToRecord for MaterialConstituent {
554    fn to_record(&self) -> Record {
555        Record::new(
556            "MaterialConstituent",
557            vec![
558                ("id", Field::Id(self.id)),
559                ("material", Field::Record(self.material.to_record())),
560                ("name", Field::text(self.name.clone())),
561                ("category", Field::text(self.category.clone())),
562                ("fraction", Field::optional(self.fraction, Field::Real)),
563            ],
564        )
565    }
566}
567
568impl ToRecord for MaterialUsage {
569    fn to_record(&self) -> Record {
570        Record::new(
571            "MaterialUsage",
572            vec![
573                (
574                    "layer_set_direction",
575                    Field::text(self.layer_set_direction.clone()),
576                ),
577                ("direction_sense", Field::text(self.direction_sense.clone())),
578                (
579                    "offset_from_reference_line",
580                    Field::optional(self.offset_from_reference_line, Field::Real),
581                ),
582                (
583                    "reference_extent",
584                    Field::optional(self.reference_extent, Field::Real),
585                ),
586                (
587                    "cardinal_point",
588                    Field::optional(self.cardinal_point, Field::Int),
589                ),
590                ("end_set", Field::id(self.end_set)),
591                (
592                    "cardinal_end_point",
593                    Field::optional(self.cardinal_end_point, Field::Int),
594                ),
595            ],
596        )
597    }
598}