Skip to main content

ifc_properties/exact/
predefined.rs

1//! Predefined property sets in exact resolution (#149, #66).
2//!
3//! A predefined set (`IfcDoorLiningProperties`, `IfcDoorPanelProperties`,
4//! their window counterparts, and every other `IfcPropertySetDefinition`
5//! that is neither an `IfcPropertySet` nor a quantity set) keeps its values
6//! in attributes of its own entity rather than in named properties. Its
7//! members are therefore the attributes its entity declares below
8//! `IfcPropertySetDefinition`, in the bound release's order and spelling:
9//!
10//! ```text
11//! IfcDoorLiningProperties  4 LiningDepth  5 LiningThickness  ...
12//! IfcDoorPanelProperties   4 PanelDepth   5 PanelOperation   6 PanelWidth
13//!                          7 PanelPosition  8 ShapeAspectStyle
14//! ```
15//!
16//! Every attribute is read from the release's table, never by a hard-wired
17//! slot, so IFC2X3's `LiningThickness : IfcPositiveLengthMeasure` and IFC4's
18//! `IfcNonNegativeLengthMeasure`, or IFC4's added `LiningToPanelOffsetX`,
19//! come out as each release declares them. A value is typed by its declared
20//! type:
21//!
22//! - a defined type or EXPRESS simple type gives a scalar with that type as
23//!   `value_type` (`IFCPOSITIVELENGTHMEASURE`, `IFCNORMALISEDRATIOMEASURE`);
24//!   no unit is stated, so the project unit applies (`exact_unit`);
25//! - an enumeration gives [`ExactValue::Enum`] checked against the
26//!   release's members (`FIXEDPANEL` is an IFC4 addition);
27//! - a select gives the typed member it holds, as a single value does;
28//! - an entity gives [`ExactValue::Entity`], the target checked but not
29//!   followed;
30//! - `$` on an `OPTIONAL` attribute is [`ExactValue::Null`] with the declared
31//!   type, an exact absence of the value; `$` on a required one is refused.
32//!
33//! An aggregate attribute (`IfcReinforcementDefinitionProperties.
34//! ReinforcementSectionDefinitions`) is not read and refuses when selected,
35//! as the whole set did before (#66).
36
37use std::{collections::BTreeSet, sync::Arc};
38
39use ifc_model::{Entity, EntityId, Model, Value};
40use ifc_schema::TypeKind;
41
42use super::assignment::{assigned_sets, Relations};
43use super::composite::{entity_target, enum_accepts};
44use super::refs::text_at;
45use super::release::{validate_model, Release};
46use super::set::{load_named, Member, SetKind};
47use super::value::{
48    exact_value, select_member, simple_payload_matches, typed_payload_matches, ResolvedValue,
49};
50use super::{
51    ExactEntityRef, ExactLogical, ExactProperty, ExactPropertyEntry, ExactPropertyError,
52    ExactSource, ExactValue,
53};
54
55/// A predefined property set assigned to an object, with every attribute
56/// its entity declares itself resolved exactly.
57///
58/// Returned by [`exact_predefined_sets`].
59#[derive(Debug, Clone, PartialEq)]
60#[non_exhaustive]
61pub struct ExactPredefinedSet {
62    /// Whether the set is assigned to the occurrence or inherited from its
63    /// `IfcTypeObject` (an `IfcDoorType`, or an IFC2X3 `IfcDoorStyle`); a
64    /// queried type object's own sets are `Type` of that object.
65    pub source: ExactSource,
66    /// Entity id of the set.
67    pub set_id: EntityId,
68    /// The set's entity in the release's spelling, e.g.
69    /// `IfcDoorPanelProperties`.
70    pub entity: Arc<str>,
71    /// The set's `Name`, if stated.
72    pub name: Option<Arc<str>>,
73    /// Each attribute the entity declares below `IfcPropertySetDefinition`,
74    /// in schema order, named as the schema names it (`PanelWidth`). Each
75    /// [`ExactProperty`] has the set's id as both `set_id` and
76    /// `property_id`, the attribute's declared type as `value_type`, no
77    /// `unit_id`, and `property_set` equal to `name` or else `entity`.
78    pub attributes: Vec<ExactPropertyEntry>,
79}
80
81impl ExactPredefinedSet {
82    /// The attribute named `name` (schema spelling, e.g. `LiningDepth`), or
83    /// `None` when the entity declares no such attribute in this release.
84    #[must_use]
85    pub fn attribute(&self, name: &str) -> Option<&ExactProperty> {
86        self.attributes
87            .iter()
88            .find(|entry| entry.name.as_ref() == name)
89            .map(|entry| &entry.property)
90    }
91}
92
93/// Every predefined property set of entity type `entity` (or a subtype)
94/// assigned to `object`, each with all its own attributes resolved.
95///
96/// A door can carry several sets of one type, one
97/// `IfcDoorPanelProperties` per leaf, which [`exact_property`] would refuse
98/// as ambiguous; this lists them all. Occurrence sets come first, then
99/// those of the object's `IfcTypeObject`, each in assignment order. No
100/// override is applied between the two sources: every set is reported with
101/// its [`ExactSource`], and which one governs is the caller's decision (for
102/// example the occurrence's sets when it has any, else the type's). An
103/// empty result is a proven absence of such sets. The traversal, model and
104/// assignment validation are those of [`exact_property`], so `object` may
105/// be a type object (an `IfcDoorType`, an IFC2X3 `IfcDoorStyle`), whose own
106/// `HasPropertySets` are listed with [`ExactSource::Type`] of `object`
107/// (#193).
108///
109/// # Door and window geometry
110///
111/// This is the read path for derived door operation geometry (#148): per
112/// leaf, `PanelOperation` and `PanelPosition` come as
113/// [`ExactValue::Enum`], and `PanelWidth` as an `IFCNORMALISEDRATIOMEASURE`
114/// fraction of the door's `OverallWidth`; `LiningDepth` and
115/// `LiningThickness` are lengths in the project length unit, which
116/// [`exact_unit`] resolves from their `value_type`.
117///
118/// ```
119/// use ifc_model::{EntityId, Model};
120/// use ifc_properties::{exact_predefined_sets, exact_unit, ExactValue};
121///
122/// /// (operation, position, width fraction) of each leaf of `door`.
123/// fn leaves(model: &Model, door: EntityId) -> Option<Vec<(String, String, f64)>> {
124///     let panels = exact_predefined_sets(model, door, "IfcDoorPanelProperties").ok()?;
125///     panels
126///         .iter()
127///         .map(|panel| {
128///             let text = |name| match &panel.attribute(name)?.value {
129///                 ExactValue::Enum(value) => Some(value.to_string()),
130///                 _ => None,
131///             };
132///             let width = match panel.attribute("PanelWidth")?.value {
133///                 ExactValue::Real(fraction) => fraction,
134///                 _ => return None, // `$`: no width stated
135///             };
136///             Some((text("PanelOperation")?, text("PanelPosition")?, width))
137///         })
138///         .collect()
139/// }
140///
141/// /// The lining depth of `door` in metres.
142/// fn lining_depth(model: &Model, door: EntityId) -> Option<f64> {
143///     let linings = exact_predefined_sets(model, door, "IfcDoorLiningProperties").ok()?;
144///     let depth = linings.first()?.attribute("LiningDepth")?;
145///     let ExactValue::Real(value) = depth.value else { return None };
146///     let unit = exact_unit(model, depth.value_type.as_deref()?, depth.unit_id).ok()?;
147///     Some(value * unit.scale)
148/// }
149/// # let _ = (leaves, lining_depth);
150/// ```
151///
152/// # Errors
153///
154/// [`ExactPropertyError::NotAPredefinedSet`] when the declared release does
155/// not declare `entity` as a predefined property set, and otherwise any
156/// [`ExactPropertyError`] of [`exact_property`], including a set attribute
157/// that cannot be read exactly (an aggregate refuses as
158/// [`ExactPropertyError::UnsupportedDefinition`]).
159///
160/// [`exact_property`]: super::exact_property
161/// [`exact_unit`]: super::exact_unit
162pub fn exact_predefined_sets(
163    model: &Model,
164    object: EntityId,
165    entity: &str,
166) -> Result<Vec<ExactPredefinedSet>, ExactPropertyError> {
167    let release = validate_model(model)?;
168    predefined_sets_in(model, release, None, object, entity)
169}
170
171/// [`exact_predefined_sets`] once the model is bound to `release`, from a
172/// scan of every relationship when one is given.
173pub(super) fn predefined_sets_in(
174    model: &Model,
175    release: Release,
176    relations: Option<&Relations>,
177    object: EntityId,
178    entity: &str,
179) -> Result<Vec<ExactPredefinedSet>, ExactPropertyError> {
180    let schema = release.schema;
181    let predefined = schema.entity(entity).is_some()
182        && schema.is_a(entity, "IFCPROPERTYSETDEFINITION")
183        && !schema.is_a("IFCPROPERTYSET", entity)
184        && !schema.is_a("IFCELEMENTQUANTITY", entity);
185    if !predefined {
186        return Err(ExactPropertyError::NotAPredefinedSet {
187            name: entity.into(),
188            schema: release.version,
189        });
190    }
191    let assigned = assigned_sets(model, release, relations, object)?;
192    let mut sources = vec![(ExactSource::Occurrence, &assigned.occurrence_sets)];
193    if let Some((type_id, sets)) = &assigned.type_sets {
194        sources.push((ExactSource::Type(*type_id), sets));
195    }
196    let mut found = Vec::new();
197    for (source, sets) in sources {
198        for &set_id in sets {
199            let set = load_named(model, release, set_id)?;
200            if set.kind != SetKind::Predefined || !schema.is_a(&set.entity.type_name, entity) {
201                continue;
202            }
203            let attributes = own_attributes(release, set.entity)
204                .map(|(slot, name)| {
205                    let member = Member::Attribute(slot);
206                    let resolved = set.value(model, release, member)?;
207                    Ok(ExactPropertyEntry {
208                        name: name.into(),
209                        property: set.exact(source, member, resolved),
210                    })
211                })
212                .collect::<Result<_, ExactPropertyError>>()?;
213            found.push(ExactPredefinedSet {
214                source,
215                set_id,
216                entity: canonical_name(release, set.entity).into(),
217                name: set.named.then(|| set.name.into()),
218                attributes,
219            });
220        }
221    }
222    Ok(found)
223}
224
225/// The name a set selector sees for a predefined or material set, and
226/// whether it is a stated `Name`: its `Name`, or its entity name when `Name`
227/// is `$` where the release allows it, or when the entity declares no
228/// `Name` (an IFC2X3 typed `IfcMaterialProperties` subtype, #218).
229///
230/// # Errors
231///
232/// [`ExactPropertyError::MalformedName`] for a `Name` that is neither text
233/// nor an allowed `$`.
234pub(super) fn predefined_key(
235    release: Release,
236    set_id: EntityId,
237    set: &Entity,
238) -> Result<(&str, bool), ExactPropertyError> {
239    let Some((slot, attribute)) = release.attribute(&set.type_name, "Name") else {
240        return Ok((canonical_name(release, set), false));
241    };
242    match set.attributes.get(slot) {
243        Some(Value::Null) if attribute.optional => Ok((canonical_name(release, set), false)),
244        name => text_at(set_id, name, "Name").map(|name| (name, true)),
245    }
246}
247
248/// The entity's name as the release spells it (`IfcDoorLiningProperties`).
249fn canonical_name(release: Release, set: &Entity) -> &'static str {
250    release
251        .schema
252        .entity(&set.type_name)
253        .map_or("", |definition| definition.name.as_str())
254}
255
256/// The slot and name of each attribute a predefined set declares below
257/// `IfcPropertySetDefinition` (whose `IfcRoot` attributes every set shares),
258/// or an IFC2X3 typed material property set below `IfcMaterialProperties`
259/// (whose `Material` every such set shares, #218).
260pub(super) fn own_attributes(
261    release: Release,
262    set: &Entity,
263) -> impl Iterator<Item = (usize, &'static str)> {
264    let schema = release.schema;
265    let base = if schema.is_a(set.type_name.as_ref(), "IFCMATERIALPROPERTIES") {
266        "IFCMATERIALPROPERTIES"
267    } else {
268        "IFCPROPERTYSETDEFINITION"
269    };
270    let inherited = schema.attribute_names(base).len();
271    schema
272        .attributes(set.type_name.as_ref())
273        .into_iter()
274        .enumerate()
275        .skip(inherited)
276        .map(|(slot, attribute)| (slot, attribute.name.as_str()))
277}
278
279/// The value of a predefined set's attribute at `slot`, typed by its
280/// declaration in the bound release.
281///
282/// # Errors
283///
284/// [`ExactPropertyError::UnsupportedDefinition`] for an aggregate
285/// attribute, [`ExactPropertyError::MissingValueSlot`] for `$` on a required
286/// one, and [`ExactPropertyError::UnsupportedValue`] (or a reference or
287/// release error) for a value its declared type does not accept.
288pub(super) fn attribute_value(
289    model: &Model,
290    release: Release,
291    set_id: EntityId,
292    set: &Entity,
293    slot: usize,
294) -> Result<ResolvedValue, ExactPropertyError> {
295    let schema = release.schema;
296    let attribute = schema.attributes(&set.type_name)[slot];
297    if attribute.aggregate {
298        return Err(ExactPropertyError::UnsupportedDefinition {
299            entity: set_id,
300            type_name: set.type_name.clone(),
301        });
302    }
303    let declared: Arc<str> = attribute.type_name.to_ascii_uppercase().into();
304    let value = &set.attributes[slot];
305    let scalar = |value, value_type| {
306        Ok(ResolvedValue {
307            value,
308            value_type: Some(value_type),
309            unit_id: None,
310        })
311    };
312    let unsupported = || ExactPropertyError::UnsupportedValue { property: set_id };
313    match value {
314        Value::Null if attribute.optional => return scalar(ExactValue::Null, declared),
315        Value::Null => return Err(ExactPropertyError::MissingValueSlot { property: set_id }),
316        _ => {}
317    }
318    let entity_ref = |target: EntityId| {
319        let entity = entity_target(model, release, set_id, target, attribute)?;
320        Ok(ExactValue::Entity(ExactEntityRef {
321            id: target,
322            type_name: entity.type_name.clone(),
323        }))
324    };
325    if schema.entity(&declared).is_some() {
326        let Value::Ref(target) = value else {
327            return Err(unsupported());
328        };
329        return scalar(entity_ref(*target)?, declared);
330    }
331    match schema
332        .type_def(&declared)
333        .map(|definition| &definition.kind)
334    {
335        Some(TypeKind::Enumeration(_)) => match value {
336            Value::Enum(member) if enum_accepts(release, &declared, member) => {
337                scalar(ExactValue::Enum(member.clone()), declared)
338            }
339            _ => Err(unsupported()),
340        },
341        Some(TypeKind::Select(_)) => match value {
342            Value::Ref(target) => scalar(entity_ref(*target)?, declared),
343            value => {
344                let typed = select_member(release, set_id, &declared, value)?;
345                scalar(typed.value, typed.value_type)
346            }
347        },
348        Some(TypeKind::Defined(_))
349            if typed_payload_matches(schema, &declared, value, &mut BTreeSet::new()) =>
350        {
351            let logical = schema
352                .resolve_defined(&declared)
353                .eq_ignore_ascii_case("LOGICAL");
354            scalar(bare(set_id, value, logical)?, declared)
355        }
356        None if simple_payload_matches(&declared, value) => {
357            scalar(bare(set_id, value, &*declared == "LOGICAL")?, declared)
358        }
359        _ => Err(unsupported()),
360    }
361}
362
363/// A bare attribute payload, keeping a `LOGICAL` three-state.
364fn bare(set_id: EntityId, value: &Value, logical: bool) -> Result<ExactValue, ExactPropertyError> {
365    Ok(match (exact_value(set_id, Some(value))?, logical) {
366        (ExactValue::Bool(true), true) => ExactValue::Logical(ExactLogical::True),
367        (ExactValue::Bool(false), true) => ExactValue::Logical(ExactLogical::False),
368        (other, _) => other,
369    })
370}
371
372#[cfg(test)]
373mod tests {
374    //! No predefined set of IFC2X3, IFC4 or IFC4X3 declares a `LOGICAL`
375    //! attribute, so the three-state reading is pinned on a minimal schema.
376
377    use ifc_model::{Entity, EntityId, Model, Value};
378    use ifc_schema::{Schema, SchemaVersion};
379
380    use super::{attribute_value, Release};
381    use crate::{ExactLogical, ExactValue};
382
383    const EXPRESS: &str = "SCHEMA IFC4;
384TYPE IfcLogical = LOGICAL;
385END_TYPE;
386ENTITY IfcPropertySetDefinition;
387  GlobalId : STRING;
388  OwnerHistory : OPTIONAL STRING;
389  Name : OPTIONAL STRING;
390  Description : OPTIONAL STRING;
391END_ENTITY;
392ENTITY IfcFlagProperties
393 SUBTYPE OF (IfcPropertySetDefinition);
394  Flag : OPTIONAL IfcLogical;
395  Bare : OPTIONAL LOGICAL;
396END_ENTITY;
397END_SCHEMA;";
398
399    #[test]
400    fn a_logical_attribute_keeps_three_states() {
401        let release = Release {
402            version: SchemaVersion::Ifc4,
403            schema: Box::leak(Box::new(Schema::from_express(EXPRESS))),
404        };
405        let model = Model::new();
406        for (value, expected) in [
407            (Value::Bool(true), ExactLogical::True),
408            (Value::Bool(false), ExactLogical::False),
409            (Value::LogicalUnknown, ExactLogical::Unknown),
410        ] {
411            for slot in [4, 5] {
412                let mut attributes = vec![Value::Null; 6];
413                attributes[slot] = value.clone();
414                let set = Entity::new("IFCFLAGPROPERTIES", attributes);
415                let resolved = attribute_value(&model, release, EntityId(1), &set, slot)
416                    .expect("a logical resolves");
417                assert_eq!(resolved.value, ExactValue::Logical(expected), "slot {slot}");
418            }
419        }
420    }
421}