Skip to main content

ifc_geometry/
units.rs

1//! Unit resolution: what one coordinate unit actually means.
2//!
3//! # Why this is not optional
4//!
5//! IFC coordinates are bare numbers. `IFCCARTESIANPOINT((3000.,0.,0.))` is
6//! three metres or three millimetres depending on the project's
7//! `IfcUnitAssignment`, and nothing in the geometry says which. A viewer that
8//! assumes metres renders a 1000x oversized building; one that assumes
9//! millimetres renders a speck.
10//!
11//! The resolved [`UnitScale`] is therefore an input to every lowering
12//! operation, not an afterthought. IFC defines no default length or plane
13//! angle unit, and `UnitsInContext` is optional on `IfcContext` in IFC4 and
14//! IFC4X3, so a model that does not declare its length unit has no scale to
15//! resolve: [`resolve`] refuses it (#585).
16//!
17//! # What is resolved
18//!
19//! - `IfcSIUnit` with an `IfcSIPrefix` (`MILLI`, `CENTI`, `KILO`, ...); a
20//!   length unit must be the `METRE` and an angle unit the `RADIAN`
21//!   (`IfcNamedUnit` WR1)
22//! - `IfcConversionBasedUnit` (inch, foot, degree): its `ValueComponent`
23//!   stated in its `UnitComponent`, so an inch given as 25.4 millimetres reads
24//!   as 0.0254 metres
25//! - Angle units, because `IfcPlaneAngleMeasure` may be degrees or radians and
26//!   every rotation depends on knowing which. A missing angle unit is refused
27//!   only where an angle is read ([`UnitScale::angle`])
28//!
29//! # What is refused
30//!
31//! No project, no `UnitsInContext`, no `LENGTHUNIT`; two projects; two units
32//! of one type; an unknown prefix; a misnamed SI unit; a context-dependent or
33//! offset unit; a conversion factor that is not a positive finite number.
34//! A project, assignment, assigned unit, conversion factor, unit component or
35//! `Dimensions` the reader reported, and a lenient model whose skipped records
36//! may hide one, are refused too (#684).
37//! A conversion-based unit defined through another one is
38//! [`GeometryError::Unsupported`].
39
40use crate::error::{GeometryError, GeometryResult};
41use crate::slots::Slots;
42use ifc_model::{EntityId, Model, Value};
43
44mod damage;
45
46use damage::Damage;
47
48/// Multipliers converting file units into SI base units.
49#[derive(Debug, Clone, Copy, PartialEq)]
50pub struct UnitScale {
51    /// Multiply a stored length by this to get metres.
52    pub length_to_metres: f64,
53    /// Multiply a stored plane angle by this to get radians; `None` when the
54    /// project declares no `PLANEANGLEUNIT`.
55    pub angle_to_radians: Option<f64>,
56}
57
58impl UnitScale {
59    /// Metres and radians, both factors of one; never a fallback for a
60    /// model's missing units.
61    pub const SI: Self = Self {
62        length_to_metres: 1.0,
63        angle_to_radians: Some(1.0),
64    };
65
66    /// Convert a stored length to metres.
67    pub fn length(&self, value: f64) -> f64 {
68        value * self.length_to_metres
69    }
70
71    /// Convert a stored plane angle to radians.
72    ///
73    /// `entity` is the entity holding the angle; it names the refusal when the
74    /// project declares no angle unit.
75    pub fn angle(&self, entity: EntityId, value: f64) -> GeometryResult<f64> {
76        Ok(value * self.radians_per_unit(entity)?)
77    }
78
79    /// Radians per stored plane angle unit.
80    ///
81    /// # Errors
82    ///
83    /// [`GeometryError::AngleUnitUndeclared`] naming `entity` when the project
84    /// declares no angle unit.
85    pub fn radians_per_unit(&self, entity: EntityId) -> GeometryResult<f64> {
86        self.angle_to_radians
87            .ok_or(GeometryError::AngleUnitUndeclared { entity })
88    }
89
90    /// Are lengths already in metres?
91    pub fn is_metric_identity(&self) -> bool {
92        (self.length_to_metres - 1.0).abs() < f64::EPSILON
93    }
94}
95
96/// Resolve the project's unit assignment.
97///
98/// Reads the length and angle units from `IfcProject.UnitsInContext`. Any
99/// `Err` means the model has no usable scale; nothing is assumed.
100///
101/// # Errors
102///
103/// [`GeometryError::LengthUnitUndeclared`] when there is no project, no
104/// assignment or no `LENGTHUNIT`; [`GeometryError::UnitsAmbiguous`] for two
105/// projects or two units of one type; [`GeometryError::UnitUnreadable`] for a
106/// declared length or angle unit without an exact factor;
107/// [`GeometryError::UnitRecordDamaged`] for a unit record the reader reported
108/// and [`GeometryError::UnitsIncomplete`] when its diagnostics may hide one
109/// (#684). A missing angle unit
110/// is not an error here: see [`UnitScale::angle`].
111pub fn resolve(model: &Model) -> GeometryResult<UnitScale> {
112    let damage = Damage::of(model)?;
113    let project = match model.ids_of_type("IFCPROJECT") {
114        [] => return Err(damage.no_project()),
115        [project] => *project,
116        [first, second, ..] => {
117            return Err(GeometryError::UnitsAmbiguous {
118                first: *first,
119                second: *second,
120                kind: "IFCPROJECT",
121            });
122        }
123    };
124    let project_entity = model
125        .get(project)
126        .ok_or(GeometryError::LengthUnitUndeclared {
127            project: Some(project),
128            assignment: None,
129        })?;
130    damage.check(project)?;
131    let project_slots = Slots::new(project, project_entity);
132    let Some(value) = project_slots.opt(8) else {
133        return Err(GeometryError::LengthUnitUndeclared {
134            project: Some(project),
135            assignment: None,
136        });
137    };
138    let assignment = value
139        .as_ref_id()
140        .ok_or_else(|| project_slots.kind_error("UnitsInContext", "an entity reference", value))?;
141    let assignment_entity = project_slots.resolve(model, assignment)?;
142    damage.check(assignment)?;
143    if &*assignment_entity.type_name != "IFCUNITASSIGNMENT" {
144        return Err(GeometryError::WrongEntityType {
145            entity: assignment,
146            actual: assignment_entity.type_name.to_string(),
147            expected: "IFCUNITASSIGNMENT",
148        });
149    }
150    let slots = Slots::new(assignment, assignment_entity);
151
152    // Classify every member first: two units of one type are ambiguous even
153    // when the first cannot be read.
154    let mut length: Option<EntityId> = None;
155    let mut angle: Option<EntityId> = None;
156    for unit_id in slots.req_ref_list(0, "Units")? {
157        let unit = slots.resolve(model, unit_id)?;
158        damage.check(unit_id)?;
159        match unit_type(&Slots::new(unit_id, unit)) {
160            Some("LENGTHUNIT") => {
161                if let Some(first) = length {
162                    return Err(ambiguous(first, unit_id, "LENGTHUNIT"));
163                }
164                length = Some(unit_id);
165            }
166            Some("PLANEANGLEUNIT") => {
167                if let Some(first) = angle {
168                    return Err(ambiguous(first, unit_id, "PLANEANGLEUNIT"));
169                }
170                angle = Some(unit_id);
171            }
172            _ => {}
173        }
174    }
175    let read = |unit_id: EntityId, kind: &'static str| -> GeometryResult<f64> {
176        let unit = slots.resolve(model, unit_id)?;
177        factor(model, &damage, &Slots::new(unit_id, unit), kind)
178    };
179    let length = length
180        .map(|unit_id| read(unit_id, "LENGTHUNIT"))
181        .transpose()?;
182    let angle = angle
183        .map(|unit_id| read(unit_id, "PLANEANGLEUNIT"))
184        .transpose()?;
185
186    let Some(length_to_metres) = length else {
187        return Err(GeometryError::LengthUnitUndeclared {
188            project: Some(project),
189            assignment: Some(assignment),
190        });
191    };
192    damage.settle(UnitScale {
193        length_to_metres,
194        angle_to_radians: angle,
195    })
196}
197
198fn ambiguous(first: EntityId, second: EntityId, kind: &'static str) -> GeometryError {
199    GeometryError::UnitsAmbiguous {
200        first,
201        second,
202        kind,
203    }
204}
205
206/// The `UnitType` enum of an `IfcNamedUnit` (attribute 1).
207fn unit_type<'m>(slots: &Slots<'m>) -> Option<&'m str> {
208    match slots.type_name() {
209        // IfcSIUnit: (Dimensions, UnitType, Prefix, Name)
210        // IfcConversionBasedUnit[WithOffset]: (Dimensions, UnitType, Name, ConversionFactor[, ConversionOffset])
211        // IfcContextDependentUnit: (Dimensions, UnitType, Name)
212        "IFCSIUNIT"
213        | "IFCCONVERSIONBASEDUNIT"
214        | "IFCCONVERSIONBASEDUNITWITHOFFSET"
215        | "IFCCONTEXTDEPENDENTUNIT" => slots.opt_enum(1),
216        _ => None,
217    }
218}
219
220/// Metres per stored length unit, or radians per stored angle unit.
221fn factor(
222    model: &Model,
223    damage: &Damage,
224    slots: &Slots<'_>,
225    kind: &'static str,
226) -> GeometryResult<f64> {
227    let unreadable = |detail: String| GeometryError::UnitUnreadable {
228        unit: slots.id(),
229        unit_type: kind,
230        detail,
231    };
232    let factor = match slots.type_name() {
233        "IFCSIUNIT" => si_factor(slots, kind)?,
234        "IFCCONVERSIONBASEDUNIT" | "IFCCONVERSIONBASEDUNITWITHOFFSET" => {
235            if slots.type_name() == "IFCCONVERSIONBASEDUNITWITHOFFSET" {
236                match slots.opt(4) {
237                    None => {}
238                    Some(offset) if offset.unwrap_typed().as_f64() == Some(0.0) => {}
239                    Some(_) => {
240                        return Err(unreadable(
241                            "an offset unit has no linear factor".to_string(),
242                        ));
243                    }
244                }
245            }
246            conversion_factor(model, damage, slots, kind)?
247        }
248        "IFCCONTEXTDEPENDENTUNIT" => {
249            return Err(unreadable(
250                "a context-dependent unit states no conversion".to_string(),
251            ));
252        }
253        other => {
254            return Err(unreadable(format!(
255                "{other} is not a unit this build reads"
256            )))
257        }
258    };
259    if factor.is_finite() && factor > 0.0 {
260        Ok(factor)
261    } else {
262        Err(unreadable(format!(
263            "its factor {factor} is not a positive finite number"
264        )))
265    }
266}
267
268/// `IfcSIUnit`: the base unit's prefix factor, after checking its name.
269fn si_factor(slots: &Slots<'_>, kind: &'static str) -> GeometryResult<f64> {
270    let unreadable = |detail: String| GeometryError::UnitUnreadable {
271        unit: slots.id(),
272        unit_type: kind,
273        detail,
274    };
275    let expected = if kind == "LENGTHUNIT" {
276        "METRE"
277    } else {
278        "RADIAN"
279    };
280    if slots.opt_enum(3) != Some(expected) {
281        return Err(unreadable(format!(
282            "a {kind} IfcSIUnit must be named {expected} (IfcNamedUnit WR1)"
283        )));
284    }
285    match slots.opt(2) {
286        None => Ok(1.0),
287        Some(Value::Enum(prefix)) => prefix_factor(prefix)
288            .ok_or_else(|| unreadable(format!("{prefix} is not an IfcSIPrefix"))),
289        Some(_) => Err(unreadable("its prefix is not an enumeration".to_string())),
290    }
291}
292
293/// `IfcConversionBasedUnit`: `ConversionFactor.ValueComponent` stated in its
294/// `UnitComponent`.
295fn conversion_factor(
296    model: &Model,
297    damage: &Damage,
298    slots: &Slots<'_>,
299    kind: &'static str,
300) -> GeometryResult<f64> {
301    let unreadable = |detail: String| GeometryError::UnitUnreadable {
302        unit: slots.id(),
303        unit_type: kind,
304        detail,
305    };
306    // The `Dimensions` reference is not read; a reported one is refused so
307    // that this resolution and `ifc-properties` agree.
308    if let Some(dimensions) = slots.opt(0).and_then(Value::as_ref_id) {
309        damage.check(dimensions)?;
310    }
311    let measure_id = slots
312        .req_ref(3, "ConversionFactor")
313        .map_err(|e| unreadable(e.to_string()))?;
314    let measure = slots
315        .resolve(model, measure_id)
316        .map_err(|e| unreadable(e.to_string()))?;
317    damage.check(measure_id)?;
318    if &*measure.type_name != "IFCMEASUREWITHUNIT" {
319        return Err(unreadable(format!(
320            "its ConversionFactor {measure_id} is {}, not IFCMEASUREWITHUNIT",
321            measure.type_name
322        )));
323    }
324    let measure_slots = Slots::new(measure_id, measure);
325    let value = measure_slots
326        .req_f64(0, "ValueComponent")
327        .map_err(|e| unreadable(e.to_string()))?;
328    let component_id = measure_slots
329        .req_ref(1, "UnitComponent")
330        .map_err(|e| unreadable(e.to_string()))?;
331    let component = measure_slots
332        .resolve(model, component_id)
333        .map_err(|e| unreadable(e.to_string()))?;
334    damage.check(component_id)?;
335    let component_slots = Slots::new(component_id, component);
336    match &*component.type_name {
337        "IFCSIUNIT" => {
338            if component_slots.opt_enum(1) != Some(kind) {
339                return Err(unreadable(format!(
340                    "its UnitComponent {component_id} is not a {kind}"
341                )));
342            }
343            Ok(value * si_factor(&component_slots, kind)?)
344        }
345        "IFCCONVERSIONBASEDUNIT" | "IFCCONVERSIONBASEDUNITWITHOFFSET" => {
346            Err(GeometryError::Unsupported {
347                entity: component_id,
348                type_name: component.type_name.to_string(),
349                detail: "a conversion-based unit defined through another conversion-based unit is not resolved",
350            })
351        }
352        other => Err(unreadable(format!(
353            "its UnitComponent {component_id} is {other}, not an IfcSIUnit"
354        ))),
355    }
356}
357
358/// Multiplier for an `IfcSIPrefix`, or `None` for an unknown token.
359///
360/// Values from ISO 80000; `EXA` through `ATTO` are all legal in IFC even where
361/// nonsensical for a building, so the whole table is present rather than the
362/// three prefixes that occur in practice.
363fn prefix_factor(prefix: &str) -> Option<f64> {
364    Some(match prefix {
365        "EXA" => 1e18,
366        "PETA" => 1e15,
367        "TERA" => 1e12,
368        "GIGA" => 1e9,
369        "MEGA" => 1e6,
370        "KILO" => 1e3,
371        "HECTO" => 1e2,
372        "DECA" => 1e1,
373        "DECI" => 1e-1,
374        "CENTI" => 1e-2,
375        "MILLI" => 1e-3,
376        "MICRO" => 1e-6,
377        "NANO" => 1e-9,
378        "PICO" => 1e-12,
379        "FEMTO" => 1e-15,
380        "ATTO" => 1e-18,
381        _ => return None,
382    })
383}
384
385#[cfg(test)]
386mod tests;