1use ifc_model::value::Value;
30use ifc_model::{EntityId, Model};
31
32use crate::conversion::{OperationKind, ProjectToMap};
33use crate::error::{GeorefError, GeorefResult};
34use crate::slot;
35
36#[derive(Debug, Clone, Copy, PartialEq)]
39pub enum NorthReference {
40 Project,
42 True {
45 direction: (f64, f64),
47 },
48 Grid {
50 direction: (f64, f64),
52 },
53}
54
55impl NorthReference {
56 #[must_use]
58 pub fn direction(&self) -> (f64, f64) {
59 match self {
60 Self::Project => project_north_direction(),
61 Self::True { direction } | Self::Grid { direction } => *direction,
62 }
63 }
64}
65
66#[must_use]
72pub const fn project_north_direction() -> (f64, f64) {
73 (0.0, 1.0)
74}
75
76pub fn resolve_true_north(model: &Model, context: EntityId) -> GeorefResult<NorthReference> {
85 let entity = model.get(context).ok_or(GeorefError::MissingEntity {
86 referrer: context,
87 missing: context,
88 })?;
89 if !entity.is_type("IFCGEOMETRICREPRESENTATIONCONTEXT")
90 && !entity.is_type("IFCGEOMETRICREPRESENTATIONSUBCONTEXT")
91 {
92 return Err(GeorefError::WrongType {
93 entity: context,
94 expected: "IFCGEOMETRICREPRESENTATIONCONTEXT",
95 actual: entity.type_name.to_string(),
96 });
97 }
98 let direction = match entity
99 .attribute(slot::geometric_context::TRUE_NORTH)
100 .map(Value::unwrap_typed)
101 {
102 None | Some(Value::Null) => project_north_direction(),
103 Some(Value::Ref(direction_id)) => direction_ratios_2d(
104 model,
105 *direction_id,
106 context,
107 slot::geometric_context::TRUE_NORTH,
108 "TrueNorth",
109 )?,
110 Some(_) => {
111 return Err(GeorefError::InvalidAttribute {
112 entity: context,
113 index: slot::geometric_context::TRUE_NORTH,
114 name: "TrueNorth",
115 })
116 }
117 };
118 Ok(NorthReference::True { direction })
119}
120
121#[must_use]
144pub fn grid_north_direction(operation: &ProjectToMap) -> NorthReference {
145 let (a, b) = operation.x_axis_direction;
146 let direction = match operation.kind {
147 OperationKind::MapConversionScaled {
148 factors: (fx, fy, _),
149 } if fx != fy => {
150 let (x, y) = (b / fx, a / fy);
151 let norm = x.hypot(y);
152 (x / norm, y / norm)
153 }
154 _ => (b, a),
155 };
156 NorthReference::Grid { direction }
157}
158
159fn direction_ratios_2d(
161 model: &Model,
162 direction_id: EntityId,
163 referrer: EntityId,
164 index: usize,
165 name: &'static str,
166) -> GeorefResult<(f64, f64)> {
167 let direction = model.get(direction_id).ok_or(GeorefError::MissingEntity {
168 referrer,
169 missing: direction_id,
170 })?;
171 if !direction.is_type("IFCDIRECTION") {
172 return Err(GeorefError::WrongType {
173 entity: direction_id,
174 expected: "IFCDIRECTION",
175 actual: direction.type_name.to_string(),
176 });
177 }
178 let ratios = direction
179 .attribute(slot::direction::DIRECTION_RATIOS)
180 .map(Value::unwrap_typed)
181 .and_then(Value::as_list)
182 .ok_or(GeorefError::InvalidAttribute {
183 entity: referrer,
184 index,
185 name,
186 })?;
187 let (x, y) = match ratios {
188 [x, y] => (
189 x.unwrap_typed()
190 .as_f64()
191 .ok_or(GeorefError::InvalidAttribute {
192 entity: direction_id,
193 index: slot::direction::DIRECTION_RATIOS,
194 name: "DirectionRatios",
195 })?,
196 y.unwrap_typed()
197 .as_f64()
198 .ok_or(GeorefError::InvalidAttribute {
199 entity: direction_id,
200 index: slot::direction::DIRECTION_RATIOS,
201 name: "DirectionRatios",
202 })?,
203 ),
204 _ => {
208 return Err(GeorefError::InvalidAttribute {
209 entity: referrer,
210 index,
211 name,
212 })
213 }
214 };
215 let norm = x.hypot(y);
216 if !norm.is_finite() || norm <= f64::EPSILON {
217 return Err(GeorefError::NonFiniteDirection {
218 entity: direction_id,
219 });
220 }
221 Ok((x / norm, y / norm))
222}
223
224#[cfg(test)]
225mod tests {
226 use std::sync::Arc;
227
228 use ifc_model::Entity;
229
230 use super::*;
231 use crate::conversion::resolve_project_to_map;
232
233 fn id(value: u64) -> EntityId {
234 EntityId(value)
235 }
236
237 fn r(value: u64) -> Value {
238 Value::Ref(id(value))
239 }
240
241 fn real(value: f64) -> Value {
242 Value::Real(value)
243 }
244
245 #[test]
246 fn true_north_defaults_to_project_north_when_absent() {
247 let mut model = Model::new();
248 model.insert(
249 id(1),
250 Entity::new("IFCGEOMETRICREPRESENTATIONCONTEXT", vec![]),
251 );
252
253 let north = resolve_true_north(&model, id(1)).expect("default applies");
254 assert_eq!(north.direction(), (0.0, 1.0));
255 assert!(matches!(north, NorthReference::True { .. }));
256 }
257
258 #[test]
259 fn true_north_reads_an_explicit_declared_direction() {
260 let mut model = Model::new();
261 model.insert(
262 id(2),
263 Entity::new(
264 "IFCDIRECTION",
265 vec![Value::List(vec![real(1.0), real(1.0)])],
266 ),
267 );
268 model.insert(
269 id(1),
270 Entity::new(
271 "IFCGEOMETRICREPRESENTATIONCONTEXT",
272 vec![
273 Value::Null,
274 Value::Null,
275 Value::Integer(3),
276 Value::Null,
277 Value::Null,
278 r(2),
279 ],
280 ),
281 );
282
283 let north = resolve_true_north(&model, id(1)).expect("explicit direction resolves");
284 let root_two = 2.0_f64.sqrt();
285 let (x, y) = north.direction();
286 assert!((x - 1.0 / root_two).abs() < 1e-12);
287 assert!((y - 1.0 / root_two).abs() < 1e-12);
288 }
289
290 #[test]
291 fn true_north_rejects_a_zero_length_direction() {
292 let mut model = Model::new();
293 model.insert(
294 id(2),
295 Entity::new(
296 "IFCDIRECTION",
297 vec![Value::List(vec![real(0.0), real(0.0)])],
298 ),
299 );
300 model.insert(
301 id(1),
302 Entity::new(
303 "IFCGEOMETRICREPRESENTATIONCONTEXT",
304 vec![
305 Value::Null,
306 Value::Null,
307 Value::Integer(3),
308 Value::Null,
309 Value::Null,
310 r(2),
311 ],
312 ),
313 );
314
315 assert!(matches!(
316 resolve_true_north(&model, id(1)),
317 Err(GeorefError::NonFiniteDirection { entity }) if entity == id(2)
318 ));
319 }
320
321 #[test]
322 fn grid_north_matches_project_north_when_the_map_conversion_has_no_rotation() {
323 let mut model = Model::new();
324 model.insert(
325 id(1),
326 Entity::new("IFCGEOMETRICREPRESENTATIONCONTEXT", vec![]),
327 );
328 model.insert(
329 id(2),
330 Entity::new(
331 "IFCPROJECTEDCRS",
332 vec![Value::Text(Arc::from("EPSG:25832"))],
333 ),
334 );
335 model.insert(
336 id(4),
337 Entity::new(
338 "IFCMAPCONVERSION",
339 vec![
340 r(1),
341 r(2),
342 real(0.0),
343 real(0.0),
344 real(0.0),
345 real(1.0),
346 real(0.0),
347 real(1.0),
348 ],
349 ),
350 );
351
352 let operation = resolve_project_to_map(&model, id(4), 1.0).expect("resolves");
353 let grid_north = grid_north_direction(&operation);
354 assert_eq!(grid_north.direction(), (0.0, 1.0));
355 }
356
357 #[test]
358 fn grid_north_rotates_a_quarter_turn_when_the_map_conversion_does() {
359 let mut model = Model::new();
360 model.insert(
361 id(1),
362 Entity::new("IFCGEOMETRICREPRESENTATIONCONTEXT", vec![]),
363 );
364 model.insert(
365 id(2),
366 Entity::new(
367 "IFCPROJECTEDCRS",
368 vec![Value::Text(Arc::from("EPSG:25832"))],
369 ),
370 );
371 model.insert(
372 id(4),
373 Entity::new(
374 "IFCMAPCONVERSION",
375 vec![
376 r(1),
377 r(2),
378 real(0.0),
379 real(0.0),
380 real(0.0),
381 real(0.0),
382 real(1.0),
383 real(1.0),
384 ],
385 ),
386 );
387
388 let operation = resolve_project_to_map(&model, id(4), 1.0).expect("resolves");
389 let grid_north = grid_north_direction(&operation);
390 let (x, y) = grid_north.direction();
391 assert!((x - 1.0).abs() < 1e-12);
392 assert!(y.abs() < 1e-12);
393 }
394
395 #[test]
396 fn project_north_is_always_the_project_y_axis() {
397 assert_eq!(
398 NorthReference::Project.direction(),
399 project_north_direction()
400 );
401 assert_eq!(project_north_direction(), (0.0, 1.0));
402 }
403}