Skip to main content

ifc_properties/template/
property_set.rs

1//! `IfcPropertySetTemplate` and the sets it governs.
2//!
3//! ```text
4//! IfcPropertySetTemplate   TemplateType ApplicableEntity HasPropertyTemplates
5//! IfcRelDefinesByTemplate  RelatedPropertySets RelatingTemplate
6//! ```
7//!
8//! Every attribute is read by name from the bound release's table
9//! ([`Layout`]); both releases that define templates (IFC4 ADD2 TC1, IFC4X3
10//! ADD2) place them after the four `IfcRoot` attributes.
11//!
12//! A template DESCRIBES what a property set should contain; it does not carry
13//! values. Reading it as a property set yields nothing useful, which is why
14//! it lives here rather than in `pset`.
15
16use std::collections::BTreeMap;
17use std::sync::Arc;
18
19use ifc_model::{EntityId, Model, Value};
20
21use super::layout::Layout;
22use super::property::{member_templates, PropertyTemplate};
23use crate::error::{PropertyAnomaly, TemplateError};
24use crate::nesting::Nesting;
25
26/// An `IfcPropertySetTemplate` with its property templates.
27#[derive(Debug, Clone, PartialEq)]
28#[non_exhaustive]
29pub struct PropertySetTemplate {
30    /// The entity.
31    pub id: EntityId,
32    /// `Name`, required by `ExistsName`.
33    pub name: Option<Arc<str>>,
34    /// `Description`.
35    pub description: Option<Arc<str>>,
36    /// `TemplateType`, e.g. `PSET_TYPEDRIVENOVERRIDE`.
37    pub template_type: Option<Arc<str>>,
38    /// `ApplicableEntity`: which IFC entity the set applies to.
39    ///
40    /// A free-text identifier such as `IfcWall`, not a validated reference.
41    pub applicable_entity: Option<Arc<str>>,
42    /// Property templates, in file order, simple and complex, complex ones
43    /// with their nested templates.
44    pub properties: Vec<PropertyTemplate>,
45}
46
47impl PropertySetTemplate {
48    /// Look up a property template by name.
49    pub fn property(&self, name: &str) -> Option<&PropertyTemplate> {
50        self.properties
51            .iter()
52            .find(|p| p.name.as_deref() == Some(name))
53    }
54}
55
56/// Read one `IfcPropertySetTemplate` by id.
57///
58/// `None` when the entity is absent, is not a set template, or the release
59/// the header declares defines none (IFC2X3). Members the traversal refuses
60/// are left out without saying so; use [`property_set_template_checked`] to
61/// have each one reported.
62pub fn property_set_template(model: &Model, id: EntityId) -> Option<PropertySetTemplate> {
63    let mut anomalies = Vec::new();
64    read_set_template(model, Layout::permissive(model), id, &mut anomalies)
65}
66
67/// Read one `IfcPropertySetTemplate` bound to the release the model
68/// declares, reporting every malformed fact met on the way.
69///
70/// The anomalies are those described on
71/// [`property_template_checked`](crate::property_template_checked), for the
72/// set template and every template below it. Only nested members cost the
73/// traversal budget, as for property sets.
74///
75/// # Errors
76///
77/// [`TemplateError::Release`] or [`TemplateError::NoTemplates`] when the
78/// model binds to no release that has templates;
79/// [`TemplateError::MissingEntity`] or [`TemplateError::NotATemplate`] for
80/// the entity itself.
81pub fn property_set_template_checked(
82    model: &Model,
83    id: EntityId,
84) -> Result<(PropertySetTemplate, Vec<PropertyAnomaly>), TemplateError> {
85    let layout = Layout::declared(model)?;
86    let entity = model.get(id).ok_or(TemplateError::MissingEntity { id })?;
87    let mut anomalies = Vec::new();
88    let template = read_set_template(model, layout, id, &mut anomalies).ok_or(
89        TemplateError::NotATemplate {
90            id,
91            type_name: entity.type_name.to_string(),
92        },
93    )?;
94    Ok((template, anomalies))
95}
96
97pub(crate) fn read_set_template(
98    model: &Model,
99    layout: Layout,
100    id: EntityId,
101    anomalies: &mut Vec<PropertyAnomaly>,
102) -> Option<PropertySetTemplate> {
103    let entity = model.get(id)?;
104    if !layout.is_a(&entity.type_name, "IFCPROPERTYSETTEMPLATE") {
105        return None;
106    }
107    layout.check_arity(id, entity, anomalies);
108    let mut template = PropertySetTemplate {
109        id,
110        name: layout.text(id, entity, "Name", anomalies),
111        description: layout.text(id, entity, "Description", anomalies),
112        template_type: layout.enumeration(id, entity, "TemplateType", anomalies),
113        applicable_entity: layout.text(id, entity, "ApplicableEntity", anomalies),
114        properties: Vec::new(),
115    };
116    let mut nesting = Nesting::new(anomalies);
117    let members = layout.get(entity, "HasPropertyTemplates");
118    template.properties = member_templates(model, layout, id, members, &mut nesting);
119    Some(template)
120}
121
122/// Every template in the file, ascending by id.
123pub fn property_set_templates(model: &Model) -> Vec<PropertySetTemplate> {
124    let mut ids: Vec<_> = model.ids_of_type("IFCPROPERTYSETTEMPLATE").to_vec();
125    ids.sort_unstable();
126    ids.into_iter()
127        .filter_map(|id| property_set_template(model, id))
128        .collect()
129}
130
131/// Which templates define each property set, via `IfcRelDefinesByTemplate`.
132///
133/// A set with no entry is untemplated, which is normal: templates describe
134/// custom property sets and standard Psets rely on the published catalogue
135/// instead.
136///
137/// Each set maps to EVERY template defining it, ascending by id and without
138/// repeats. `IfcPropertySetDefinition.IsDefinedBy` is `SET [0:?] OF
139/// IfcRelDefinesByTemplate`, so several templates are legal. Before 0.4 this
140/// returned one template per set, and silently dropped the rest (#60).
141pub fn template_of_set(model: &Model) -> BTreeMap<EntityId, Vec<EntityId>> {
142    template_links(model, Layout::permissive(model))
143        .into_iter()
144        .map(|(set, links)| {
145            let mut templates: Vec<EntityId> = links.into_iter().map(|(_, t)| t).collect();
146            templates.sort_unstable();
147            templates.dedup();
148            (set, templates)
149        })
150        .collect()
151}
152
153/// Every `(relationship, template)` pair naming each set, in relationship
154/// id order.
155pub(crate) fn template_links(
156    model: &Model,
157    layout: Layout,
158) -> BTreeMap<EntityId, Vec<(EntityId, EntityId)>> {
159    let mut out: BTreeMap<EntityId, Vec<(EntityId, EntityId)>> = BTreeMap::new();
160    let mut relationships = model.ids_of_type("IFCRELDEFINESBYTEMPLATE").to_vec();
161    relationships.sort_unstable();
162    for id in relationships {
163        let Some(rel) = model.get(id) else { continue };
164        let Some(template) = layout.get(rel, "RelatingTemplate").and_then(one_ref) else {
165            continue;
166        };
167        let sets = match layout.get(rel, "RelatedPropertySets") {
168            Some(Value::List(items)) => items.iter().filter_map(one_ref).collect(),
169            _ => Vec::new(),
170        };
171        for set in sets {
172            out.entry(set).or_default().push((id, template));
173        }
174    }
175    out
176}
177
178fn one_ref(value: &Value) -> Option<EntityId> {
179    match value.unwrap_typed() {
180        Value::Ref(id) => Some(*id),
181        _ => None,
182    }
183}