Skip to main content

ifc_properties/pset/
predefined.rs

1//! Predefined property sets: door and window lining and panel data,
2//! permeable coverings, and the reinforcement/section families.
3//!
4//! These are `IfcPropertySetDefinition` subtypes, so they carry the four
5//! `IfcRoot` slots before their own attributes. Unlike a generic
6//! `IfcPropertySet` they have fixed, named, typed attributes and a set of
7//! WHERE rules over them. The linings are in `lining.rs`; the release
8//! each is written in is explained in `owned.rs`.
9
10use ifc_model::guid::Guid;
11use ifc_model::{Entity, EntityId, Model, Transaction, Value};
12
13use crate::{PropertyError, PropertyResult};
14
15use super::authoring::optional_text;
16use super::owned::{stage_ifc4, stage_owned, Rooted};
17
18pub(super) fn invalid(
19    entity: &'static str,
20    attribute: &'static str,
21    value: impl Into<String>,
22) -> PropertyError {
23    PropertyError::AuthoringInvalid {
24        entity,
25        attribute,
26        value: value.into(),
27    }
28}
29
30/// Refuse a GlobalId that is not a 22-character IFC GUID.
31pub(super) fn require_guid(entity: &'static str, global_id: &str) -> PropertyResult<()> {
32    if Guid::parse(global_id).is_none() {
33        return Err(invalid(entity, "GlobalId", global_id));
34    }
35    Ok(())
36}
37
38/// The three length measure kinds these entities use.
39///
40/// `IfcLengthMeasure` admits negatives: an offset may sit either side of
41/// its reference. Collapsing all three into a non-negative check would
42/// silently refuse legal files.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub(super) enum Measure {
45    /// `IfcPositiveLengthMeasure`: strictly greater than zero.
46    Positive,
47    /// `IfcNonNegativeLengthMeasure`: zero or greater.
48    NonNegative,
49    /// `IfcLengthMeasure`: any finite value, including negative.
50    Length,
51}
52
53pub(super) fn measure(
54    entity: &'static str,
55    attribute: &'static str,
56    value: Option<f64>,
57    kind: Measure,
58) -> PropertyResult<Value> {
59    let Some(value) = value else {
60        return Ok(Value::Null);
61    };
62    let ok = value.is_finite()
63        && match kind {
64            Measure::Positive => value > 0.0,
65            Measure::NonNegative => value >= 0.0,
66            Measure::Length => true,
67        };
68    if !ok {
69        return Err(invalid(entity, attribute, format!("{value}")));
70    }
71    Ok(Value::Real(value))
72}
73
74/// An `IfcNormalisedRatioMeasure`, bounded to `[0, 1]`.
75pub(super) fn ratio(
76    entity: &'static str,
77    attribute: &'static str,
78    value: Option<f64>,
79) -> PropertyResult<Value> {
80    let Some(value) = value else {
81        return Ok(Value::Null);
82    };
83    if !value.is_finite() || !(0.0..=1.0).contains(&value) {
84        return Err(invalid(entity, attribute, format!("{value}")));
85    }
86    Ok(Value::Real(value))
87}
88
89const DOOR_PANEL_OPERATION: &[&str] = &[
90    "DOUBLE_ACTING",
91    "FIXEDPANEL",
92    "FOLDING",
93    "REVOLVING",
94    "ROLLINGUP",
95    "SLIDING",
96    "SWINGING",
97    "USERDEFINED",
98    "NOTDEFINED",
99];
100const DOOR_PANEL_POSITION: &[&str] = &["LEFT", "MIDDLE", "RIGHT", "NOTDEFINED"];
101const WINDOW_PANEL_OPERATION: &[&str] = &[
102    "BOTTOMHUNG",
103    "FIXEDCASEMENT",
104    "OTHEROPERATION",
105    "PIVOTHORIZONTAL",
106    "PIVOTVERTICAL",
107    "REMOVABLECASEMENT",
108    "SIDEHUNGLEFTHAND",
109    "SIDEHUNGRIGHTHAND",
110    "SLIDINGHORIZONTAL",
111    "SLIDINGVERTICAL",
112    "TILTANDTURNLEFTHAND",
113    "TILTANDTURNRIGHTHAND",
114    "TOPHUNG",
115    "NOTDEFINED",
116];
117const WINDOW_PANEL_POSITION: &[&str] = &["BOTTOM", "LEFT", "MIDDLE", "RIGHT", "TOP", "NOTDEFINED"];
118const PERMEABLE_COVERING_OPERATION: &[&str] =
119    &["GRILL", "LOUVER", "SCREEN", "USERDEFINED", "NOTDEFINED"];
120
121pub(super) fn token(
122    entity: &'static str,
123    attribute: &'static str,
124    value: &str,
125    allowed: &[&str],
126) -> PropertyResult<Value> {
127    if !allowed.contains(&value) {
128        return Err(invalid(entity, attribute, value));
129    }
130    Ok(Value::Enum(value.into()))
131}
132
133/// Stage an `IfcDoorPanelProperties`.
134///
135/// `PanelOperation` and `PanelPosition` are mandatory: the schema does
136/// not mark them OPTIONAL, so a panel always states how it moves and
137/// where it sits.
138///
139/// Takes no model, so it writes the IFC4 layout with `OwnerHistory` `$`:
140/// valid IFC4 and IFC4X3, never valid IFC2X3. Use
141/// [`add_door_panel_properties_with_owner_history`] to write the model's
142/// declared release.
143///
144/// # Errors
145///
146/// Refuses a malformed GlobalId, a token outside its own enumeration,
147/// a non-positive panel depth, and a panel width outside `[0, 1]`
148/// (`PanelWidth` is an `IfcNormalisedRatioMeasure`, a fraction of the
149/// opening rather than a length).
150pub fn add_door_panel_properties(
151    tx: &mut Transaction,
152    global_id: &str,
153    name: Option<&str>,
154    operation: &str,
155    position: &str,
156    panel: (Option<f64>, Option<f64>),
157) -> PropertyResult<EntityId> {
158    stage_ifc4(tx, door_panel(global_id, name, operation, position, panel)?)
159}
160
161/// [`add_door_panel_properties`] in the model's declared release, with a
162/// caller-supplied `IfcOwnerHistory`, which IFC2X3 requires (#202).
163///
164/// # Errors
165///
166/// Those of [`add_door_panel_properties`], a token the release's own
167/// enumeration does not list, and the release and owner-history refusals
168/// of [`add_door_lining_properties_with_owner_history`](crate::add_door_lining_properties_with_owner_history).
169/// Nothing is staged on an error.
170#[allow(clippy::too_many_arguments)]
171pub fn add_door_panel_properties_with_owner_history(
172    tx: &mut Transaction,
173    model: &Model,
174    global_id: &str,
175    name: Option<&str>,
176    operation: &str,
177    position: &str,
178    panel: (Option<f64>, Option<f64>),
179    owner_history: EntityId,
180) -> PropertyResult<EntityId> {
181    let rooted = door_panel(global_id, name, operation, position, panel)?;
182    stage_owned(tx, model, rooted, owner_history)
183}
184
185fn door_panel<'a>(
186    global_id: &'a str,
187    name: Option<&'a str>,
188    operation: &str,
189    position: &str,
190    (depth, width): (Option<f64>, Option<f64>),
191) -> PropertyResult<Rooted<'a>> {
192    const ENTITY: &str = "IFCDOORPANELPROPERTIES";
193    require_guid(ENTITY, global_id)?;
194    let values = vec![
195        (
196            "PanelDepth",
197            measure(ENTITY, "PanelDepth", depth, Measure::Positive)?,
198        ),
199        (
200            "PanelOperation",
201            token(ENTITY, "PanelOperation", operation, DOOR_PANEL_OPERATION)?,
202        ),
203        ("PanelWidth", ratio(ENTITY, "PanelWidth", width)?),
204        (
205            "PanelPosition",
206            token(ENTITY, "PanelPosition", position, DOOR_PANEL_POSITION)?,
207        ),
208    ];
209    Ok(Rooted {
210        entity: ENTITY,
211        global_id,
212        name,
213        description: None,
214        values,
215    })
216}
217
218/// Stage an `IfcWindowPanelProperties`.
219///
220/// Takes no model, so it writes the IFC4 layout with `OwnerHistory` `$`:
221/// valid IFC4 and IFC4X3, never valid IFC2X3. Use
222/// [`add_window_panel_properties_with_owner_history`] to write the
223/// model's declared release.
224///
225/// # Errors
226///
227/// As for the door panel, against the window enumerations. Note that
228/// `IfcWindowPanelOperationEnum` has no `USERDEFINED` member, so a
229/// caller cannot fall back to it here.
230pub fn add_window_panel_properties(
231    tx: &mut Transaction,
232    global_id: &str,
233    name: Option<&str>,
234    operation: &str,
235    position: &str,
236    frame: (Option<f64>, Option<f64>),
237) -> PropertyResult<EntityId> {
238    let rooted = framed(WINDOW_PANEL, global_id, name, operation, position, frame)?;
239    stage_ifc4(tx, rooted)
240}
241
242/// [`add_window_panel_properties`] in the model's declared release, with
243/// a caller-supplied `IfcOwnerHistory`, which IFC2X3 requires (#202).
244///
245/// # Errors
246///
247/// Those of [`add_door_panel_properties_with_owner_history`], against the
248/// window enumerations. Nothing is staged on an error.
249#[allow(clippy::too_many_arguments)]
250pub fn add_window_panel_properties_with_owner_history(
251    tx: &mut Transaction,
252    model: &Model,
253    global_id: &str,
254    name: Option<&str>,
255    operation: &str,
256    position: &str,
257    frame: (Option<f64>, Option<f64>),
258    owner_history: EntityId,
259) -> PropertyResult<EntityId> {
260    let rooted = framed(WINDOW_PANEL, global_id, name, operation, position, frame)?;
261    stage_owned(tx, model, rooted, owner_history)
262}
263
264/// Stage an `IfcPermeableCoveringProperties`.
265///
266/// Takes no model, so it writes the IFC4 layout with `OwnerHistory` `$`:
267/// valid IFC4 and IFC4X3, never valid IFC2X3. Use
268/// [`add_permeable_covering_properties_with_owner_history`] to write the
269/// model's declared release.
270///
271/// # Errors
272///
273/// As for the panels, against the permeable-covering operation
274/// enumeration and the window panel positions it shares.
275pub fn add_permeable_covering_properties(
276    tx: &mut Transaction,
277    global_id: &str,
278    name: Option<&str>,
279    operation: &str,
280    position: &str,
281    frame: (Option<f64>, Option<f64>),
282) -> PropertyResult<EntityId> {
283    let rooted = framed(PERMEABLE, global_id, name, operation, position, frame)?;
284    stage_ifc4(tx, rooted)
285}
286
287/// [`add_permeable_covering_properties`] in the model's declared release,
288/// with a caller-supplied `IfcOwnerHistory`, which IFC2X3 requires (#202).
289///
290/// # Errors
291///
292/// Those of [`add_door_panel_properties_with_owner_history`], against the
293/// permeable-covering enumerations. Nothing is staged on an error.
294#[allow(clippy::too_many_arguments)]
295pub fn add_permeable_covering_properties_with_owner_history(
296    tx: &mut Transaction,
297    model: &Model,
298    global_id: &str,
299    name: Option<&str>,
300    operation: &str,
301    position: &str,
302    frame: (Option<f64>, Option<f64>),
303    owner_history: EntityId,
304) -> PropertyResult<EntityId> {
305    let rooted = framed(PERMEABLE, global_id, name, operation, position, frame)?;
306    stage_owned(tx, model, rooted, owner_history)
307}
308
309/// A window panel or permeable covering: its entity and the enumerations
310/// its `OperationType` and `PanelPosition` take.
311struct Framed {
312    entity: &'static str,
313    operations: &'static [&'static str],
314}
315
316const WINDOW_PANEL: Framed = Framed {
317    entity: "IFCWINDOWPANELPROPERTIES",
318    operations: WINDOW_PANEL_OPERATION,
319};
320const PERMEABLE: Framed = Framed {
321    entity: "IFCPERMEABLECOVERINGPROPERTIES",
322    operations: PERMEABLE_COVERING_OPERATION,
323};
324
325fn framed<'a>(
326    kind: Framed,
327    global_id: &'a str,
328    name: Option<&'a str>,
329    operation: &str,
330    position: &str,
331    (frame_depth, frame_thickness): (Option<f64>, Option<f64>),
332) -> PropertyResult<Rooted<'a>> {
333    let entity = kind.entity;
334    require_guid(entity, global_id)?;
335    let values = vec![
336        (
337            "OperationType",
338            token(entity, "OperationType", operation, kind.operations)?,
339        ),
340        (
341            "PanelPosition",
342            token(entity, "PanelPosition", position, WINDOW_PANEL_POSITION)?,
343        ),
344        (
345            "FrameDepth",
346            measure(entity, "FrameDepth", frame_depth, Measure::Positive)?,
347        ),
348        (
349            "FrameThickness",
350            measure(entity, "FrameThickness", frame_thickness, Measure::Positive)?,
351        ),
352    ];
353    Ok(Rooted {
354        entity,
355        global_id,
356        name,
357        description: None,
358        values,
359    })
360}
361
362/// The STEP type name of an `IfcValue`, for the homogeneity rule.
363///
364/// TYPEOF compares the declared measure, so a wrapped value is named by
365/// its wrapper and a bare literal by its syntactic kind. Two values that
366/// print the same can still differ here, which is exactly what WR01 is
367/// about.
368fn value_type(value: &Value) -> Option<String> {
369    Some(match value {
370        Value::Typed { type_name, .. } => type_name.to_ascii_uppercase(),
371        Value::Bool(_) | Value::LogicalUnknown => "BOOLEAN".to_owned(),
372        Value::Integer(_) => "INTEGER".to_owned(),
373        Value::Real(_) => "REAL".to_owned(),
374        Value::Text(_) => "STRING".to_owned(),
375        Value::Binary(_) => "BINARY".to_owned(),
376        Value::Enum(_) => "ENUM".to_owned(),
377        // `$`, `*`, refs and aggregates are not single measures.
378        _ => return None,
379    })
380}
381
382/// Stage an `IfcPropertyEnumeration`.
383///
384/// # Errors
385///
386/// Refuses a blank name (UR1 makes it the unique key), an empty value
387/// list, a value that is not a single measure, a duplicate value (the
388/// list is UNIQUE), and a list mixing measure types (WR01). Each value
389/// is an `IfcValue`: a bare literal is refused with
390/// [`PropertyError::ValueForm`](crate::PropertyError::ValueForm).
391pub fn add_property_enumeration(
392    tx: &mut Transaction,
393    name: &str,
394    values: Vec<Value>,
395    unit: Option<EntityId>,
396) -> PropertyResult<EntityId> {
397    const ENTITY: &str = "IFCPROPERTYENUMERATION";
398    if name.trim().is_empty() {
399        return Err(invalid(ENTITY, "Name", name));
400    }
401    if values.is_empty() {
402        return Err(invalid(ENTITY, "EnumerationValues", "empty"));
403    }
404    super::value_form::require_ifc_values(ENTITY, "EnumerationValues", &values)?;
405    let mut first: Option<String> = None;
406    for value in &values {
407        let Some(kind) = value_type(value) else {
408            return Err(invalid(ENTITY, "EnumerationValues", format!("{value:?}")));
409        };
410        match &first {
411            None => first = Some(kind),
412            Some(expected) if *expected != kind => {
413                return Err(invalid(
414                    ENTITY,
415                    "EnumerationValues",
416                    format!("WR01: {kind} among {expected}"),
417                ));
418            }
419            Some(_) => {}
420        }
421    }
422    for (index, value) in values.iter().enumerate() {
423        if values[..index].contains(value) {
424            return Err(invalid(ENTITY, "EnumerationValues", "duplicate value"));
425        }
426    }
427    let attributes = vec![
428        Value::Text(name.into()),
429        Value::List(values),
430        unit.map_or(Value::Null, Value::Ref),
431    ];
432    Ok(tx.create(Entity::new(ENTITY, attributes)))
433}
434
435/// Stage an `IfcPropertyDependencyRelationship`.
436///
437/// # Errors
438///
439/// Refuses a relationship whose depending and dependant property are
440/// the same entity (NoSelfReference): a property cannot derive from
441/// itself, and such a record makes a dependency walk loop forever.
442pub fn add_property_dependency_relationship(
443    tx: &mut Transaction,
444    name: Option<&str>,
445    description: Option<&str>,
446    properties: (EntityId, EntityId),
447    expression: Option<&str>,
448) -> PropertyResult<EntityId> {
449    const ENTITY: &str = "IFCPROPERTYDEPENDENCYRELATIONSHIP";
450    let (depending, dependant) = properties;
451    if depending == dependant {
452        return Err(invalid(ENTITY, "DependingProperty", "NoSelfReference"));
453    }
454    let attributes = vec![
455        optional_text(name),
456        optional_text(description),
457        Value::Ref(depending),
458        Value::Ref(dependant),
459        optional_text(expression),
460    ];
461    Ok(tx.create(Entity::new(ENTITY, attributes)))
462}