1use crate::error::{GeometryError, GeometryResult};
41use crate::slots::Slots;
42use ifc_model::{EntityId, Model, Value};
43
44mod damage;
45
46use damage::Damage;
47
48#[derive(Debug, Clone, Copy, PartialEq)]
50pub struct UnitScale {
51 pub length_to_metres: f64,
53 pub angle_to_radians: Option<f64>,
56}
57
58impl UnitScale {
59 pub const SI: Self = Self {
62 length_to_metres: 1.0,
63 angle_to_radians: Some(1.0),
64 };
65
66 pub fn length(&self, value: f64) -> f64 {
68 value * self.length_to_metres
69 }
70
71 pub fn angle(&self, entity: EntityId, value: f64) -> GeometryResult<f64> {
76 Ok(value * self.radians_per_unit(entity)?)
77 }
78
79 pub fn radians_per_unit(&self, entity: EntityId) -> GeometryResult<f64> {
86 self.angle_to_radians
87 .ok_or(GeometryError::AngleUnitUndeclared { entity })
88 }
89
90 pub fn is_metric_identity(&self) -> bool {
92 (self.length_to_metres - 1.0).abs() < f64::EPSILON
93 }
94}
95
96pub 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 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
206fn unit_type<'m>(slots: &Slots<'m>) -> Option<&'m str> {
208 match slots.type_name() {
209 "IFCSIUNIT"
213 | "IFCCONVERSIONBASEDUNIT"
214 | "IFCCONVERSIONBASEDUNITWITHOFFSET"
215 | "IFCCONTEXTDEPENDENTUNIT" => slots.opt_enum(1),
216 _ => None,
217 }
218}
219
220fn 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
268fn 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
293fn 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 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
358fn 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;