Skip to main content

ifc_georef/crs/
unit.rs

1//! Explicit length- and plane-angle-unit resolution for CRS coordinates.
2//!
3//! Both kinds reduce the same way: an `IfcSIUnit` of the expected
4//! `UnitType` and base name, optionally prefixed, or an
5//! `IfcConversionBasedUnit` whose `ConversionFactor` bottoms out in one.
6//! Only the expected `UnitType`/base name and the base factor differ.
7
8use ifc_model::value::Value;
9use ifc_model::{EntityId, Model};
10
11use crate::crs::damage::Damage;
12use crate::error::{GeorefError, GeorefResult};
13use crate::slot::{conversion_based_unit, measure_with_unit, si_unit};
14
15/// A length unit reduced to a metre factor.
16#[derive(Debug, Clone, PartialEq)]
17pub struct LengthUnit {
18    /// Unit name, either an SI token such as `MILLIMETRE` or the authored
19    /// `IfcConversionBasedUnit.Name` such as `FOOT`.
20    pub name: String,
21    /// Metres per one unit. Always finite and strictly positive.
22    pub metres_per_unit: f64,
23}
24
25/// A plane-angle unit reduced to a radian factor, as an IFC4X3
26/// `IfcGeographicCRS.AngleUnit` declares it.
27#[derive(Debug, Clone, PartialEq)]
28#[non_exhaustive]
29pub struct AngleUnit {
30    /// Unit name, either an SI token such as `RADIAN` or the authored
31    /// `IfcConversionBasedUnit.Name` such as `DEGREE`.
32    pub name: String,
33    /// Radians per one unit. Always finite and strictly positive.
34    pub radians_per_unit: f64,
35}
36
37/// The unit kind being reduced: its `IfcUnitEnum` token and SI base name.
38#[derive(Clone, Copy)]
39struct Kind {
40    unit_type: &'static str,
41    si_name: &'static str,
42}
43
44const LENGTH: Kind = Kind {
45    unit_type: "LENGTHUNIT",
46    si_name: "METRE",
47};
48
49const PLANE_ANGLE: Kind = Kind {
50    unit_type: "PLANEANGLEUNIT",
51    si_name: "RADIAN",
52};
53
54/// Reduce a length unit against the entry point's `damage`. The caller
55/// settles the damage once its whole reading is done.
56pub(crate) fn resolve_length_unit(
57    model: &Model,
58    id: EntityId,
59    damage: &Damage,
60) -> GeorefResult<LengthUnit> {
61    let (name, metres_per_unit) = resolve(model, id, LENGTH, &mut Vec::new(), damage)?;
62    Ok(LengthUnit {
63        name,
64        metres_per_unit,
65    })
66}
67
68pub(crate) fn resolve_angle_unit(
69    model: &Model,
70    id: EntityId,
71    damage: &Damage,
72) -> GeorefResult<AngleUnit> {
73    let (name, radians_per_unit) = resolve(model, id, PLANE_ANGLE, &mut Vec::new(), damage)?;
74    Ok(AngleUnit {
75        name,
76        radians_per_unit,
77    })
78}
79
80/// Reduce `id` to `(name, SI base units per unit)`.
81fn resolve(
82    model: &Model,
83    id: EntityId,
84    kind: Kind,
85    chain: &mut Vec<EntityId>,
86    damage: &Damage,
87) -> GeorefResult<(String, f64)> {
88    if chain.len() >= 16 || chain.contains(&id) {
89        return Err(GeorefError::UnitCycle { entity: id });
90    }
91    damage.check_unit(id)?;
92    chain.push(id);
93    let entity = model.get(id).ok_or(GeorefError::MissingEntity {
94        referrer: id,
95        missing: id,
96    })?;
97    let result = match entity.type_name.as_ref() {
98        "IFCSIUNIT" => {
99            require_enum(entity.attribute(si_unit::UNIT_TYPE), id, kind.unit_type)?;
100            let prefix = optional_enum(
101                entity.attribute(si_unit::PREFIX),
102                id,
103                si_unit::PREFIX,
104                "Prefix",
105            )?;
106            require_enum(entity.attribute(si_unit::NAME), id, kind.si_name)?;
107            let factor = match prefix.as_deref() {
108                None => 1.0,
109                Some("EXA") => 1e18,
110                Some("PETA") => 1e15,
111                Some("TERA") => 1e12,
112                Some("GIGA") => 1e9,
113                Some("MEGA") => 1e6,
114                Some("KILO") => 1e3,
115                Some("HECTO") => 1e2,
116                Some("DECA") => 1e1,
117                Some("DECI") => 1e-1,
118                Some("CENTI") => 1e-2,
119                Some("MILLI") => 1e-3,
120                Some("MICRO") => 1e-6,
121                Some("NANO") => 1e-9,
122                Some("PICO") => 1e-12,
123                Some("FEMTO") => 1e-15,
124                Some("ATTO") => 1e-18,
125                Some(_) => {
126                    return Err(GeorefError::InvalidUnit {
127                        entity: id,
128                        detail: "unknown SI prefix",
129                    })
130                }
131            };
132            (
133                prefix.map_or_else(|| kind.si_name.into(), |p| format!("{p}{}", kind.si_name)),
134                factor,
135            )
136        }
137        "IFCCONVERSIONBASEDUNIT" => {
138            require_enum(
139                entity.attribute(conversion_based_unit::UNIT_TYPE),
140                id,
141                kind.unit_type,
142            )?;
143            let name = entity
144                .text(conversion_based_unit::NAME)
145                .ok_or(GeorefError::MissingAttribute {
146                    entity: id,
147                    index: conversion_based_unit::NAME,
148                    name: "Name",
149                })?
150                .to_owned();
151            let factor_ref = entity
152                .reference(conversion_based_unit::CONVERSION_FACTOR)
153                .ok_or(GeorefError::InvalidAttribute {
154                    entity: id,
155                    index: conversion_based_unit::CONVERSION_FACTOR,
156                    name: "ConversionFactor",
157                })?;
158            damage.check_unit(factor_ref)?;
159            let factor_entity = model.get(factor_ref).ok_or(GeorefError::MissingEntity {
160                referrer: id,
161                missing: factor_ref,
162            })?;
163            if !factor_entity.is_type("IFCMEASUREWITHUNIT") {
164                return Err(GeorefError::WrongType {
165                    entity: factor_ref,
166                    expected: "IFCMEASUREWITHUNIT",
167                    actual: factor_entity.type_name.to_string(),
168                });
169            }
170            let value = factor_entity
171                .attribute(measure_with_unit::VALUE_COMPONENT)
172                .and_then(|v| v.unwrap_typed().as_f64())
173                .ok_or(GeorefError::InvalidAttribute {
174                    entity: factor_ref,
175                    index: measure_with_unit::VALUE_COMPONENT,
176                    name: "ValueComponent",
177                })?;
178            let base_ref = factor_entity
179                .reference(measure_with_unit::UNIT_COMPONENT)
180                .ok_or(GeorefError::InvalidAttribute {
181                    entity: factor_ref,
182                    index: measure_with_unit::UNIT_COMPONENT,
183                    name: "UnitComponent",
184                })?;
185            let (_, base) = resolve(model, base_ref, kind, chain, damage)?;
186            (name, value * base)
187        }
188        actual => {
189            return Err(GeorefError::WrongType {
190                entity: id,
191                expected: "IFCSIUNIT or IFCCONVERSIONBASEDUNIT",
192                actual: actual.to_owned(),
193            })
194        }
195    };
196    chain.pop();
197    if !result.1.is_finite() || result.1 <= 0.0 {
198        return Err(GeorefError::InvalidUnit {
199            entity: id,
200            detail: "conversion factor must be finite and positive",
201        });
202    }
203    Ok(result)
204}
205
206fn require_enum(value: Option<&Value>, id: EntityId, expected: &'static str) -> GeorefResult<()> {
207    match value.map(Value::unwrap_typed) {
208        Some(Value::Enum(actual)) if actual.eq_ignore_ascii_case(expected) => Ok(()),
209        _ => Err(GeorefError::InvalidUnit {
210            entity: id,
211            detail: expected,
212        }),
213    }
214}
215
216fn optional_enum(
217    value: Option<&Value>,
218    id: EntityId,
219    index: usize,
220    name: &'static str,
221) -> GeorefResult<Option<String>> {
222    match value.map(Value::unwrap_typed) {
223        None | Some(Value::Null) => Ok(None),
224        Some(Value::Enum(value)) => Ok(Some(value.to_ascii_uppercase())),
225        _ => Err(GeorefError::InvalidAttribute {
226            entity: id,
227            index,
228            name,
229        }),
230    }
231}