Skip to main content

ifc_georef/north/
directions.rs

1//! True, grid, and project north as distinct 2D directions.
2//!
3//! IFC distinguishes three "north" references that frequently disagree in
4//! real files:
5//!
6//! - **Project north**: the project's own local Y axis. By construction this
7//!   is always `(0, 1)` in the project's own XY plane -- it is the reference
8//!   every other north direction is measured against, not something to
9//!   resolve from the file.
10//! - **True north**: `IfcGeometricRepresentationContext.TrueNorth`, the
11//!   geographic (geodetic) northing direction expressed in the project XY
12//!   plane. Optional; defaults to `(0, 1)` (project north) when absent, per
13//!   the IFC4/IFC4X3 attribute definition.
14//! - **Grid north**: the direction of the target map's northing axis,
15//!   expressed back in the project XY plane. This is derived from
16//!   `IfcMapConversion`'s `XAxisAbscissa`/`XAxisOrdinate` rotation, not read
17//!   directly from any single attribute.
18//!
19//! The schema is explicit that these can disagree, and states the
20//! resolution order itself: "If a geographic placement is provided using
21//! `IfcMapConversion` then the true north is for information only. In case
22//! of inconsistency, the value provided with `IfcMapConversion` shall take
23//! precedence." So grid north (when a map conversion exists) is
24//! authoritative for georeferencing; true north remains informational
25//! metadata. This module keeps both distinguishable rather than collapsing
26//! them into one direction, so a caller can still detect and report the
27//! disagreement instead of silently picking one.
28
29use 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/// A resolved north reference: a unit-length 2D direction in the project's
37/// own XY plane, plus which reference it names.
38#[derive(Debug, Clone, Copy, PartialEq)]
39pub enum NorthReference {
40    /// The project's own Y axis: always `(0, 1)` by definition.
41    Project,
42    /// Geodetic north, from `IfcGeometricRepresentationContext.TrueNorth`
43    /// (or its `(0, 1)` default when the attribute is absent).
44    True {
45        /// Unit-length direction in the project's XY plane.
46        direction: (f64, f64),
47    },
48    /// The target map's northing axis, derived from an `IfcMapConversion`.
49    Grid {
50        /// Unit-length direction in the project's XY plane.
51        direction: (f64, f64),
52    },
53}
54
55impl NorthReference {
56    /// The direction as a unit vector in the project's XY plane.
57    #[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/// The project's own north reference: always `(0, 1)` in its own XY plane.
67///
68/// This is a definitional constant, not something resolved from a model:
69/// "project north" means the project's local Y axis, and every other north
70/// reference is stated relative to it.
71#[must_use]
72pub const fn project_north_direction() -> (f64, f64) {
73    (0.0, 1.0)
74}
75
76/// Resolve `IfcGeometricRepresentationContext.TrueNorth`.
77///
78/// `TrueNorth` is attribute slot 5 (`IfcRepresentationContext` contributes 0
79/// and 1; `IfcGeometricRepresentationContext` adds `CoordinateSpaceDimension`
80/// at 2, `Precision` at 3, `WorldCoordinateSystem` at 4, `TrueNorth` at 5 --
81/// identical in IFC4 and IFC4X3, pinned in `crate::slot`). Returns the spec default `(0, 1)` when the
82/// attribute is absent, exactly as `IfcGeometricRepresentationContext`
83/// documents: "If not present, it defaults to \[0.,1.\]".
84pub 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/// Resolve grid north from an already-computed `IfcMapConversion` operation.
122///
123/// The map conversion rotation takes a project XY vector `(x, y)` to a map
124/// XY vector `(ax - by, bx + ay)` where `(a, b)` is the normalized
125/// `(XAxisAbscissa, XAxisOrdinate)` pair
126/// ([`ProjectToMap::x_axis_direction`]). Grid north is the map's northing
127/// axis, `(0, 1)` in map coordinates, pulled back through the *inverse* of
128/// that rotation into the project frame: since the rotation matrix is
129/// orthonormal, its inverse is its transpose, giving `(b, a)`.
130///
131/// A worked check: `a = 1, b = 0` (no rotation) gives grid north `(0, 1)`,
132/// i.e. grid north coincides with project north when the project's local X
133/// axis is already aligned with the map's easting axis. `a = 0, b = 1`
134/// (project X rotated 90 degrees onto map northing) gives grid north
135/// `(1, 0)`, i.e. the project's own X axis now points toward map north --
136/// consistent with the project frame having been rotated a quarter turn
137/// relative to the map.
138///
139/// An IFC4X3 `IfcMapConversionScaled` scales the project axes by `FactorX`
140/// and `FactorY` before rotating, so the pull-back also divides by them:
141/// `(b / FactorX, a / FactorY)`, normalized. With equal factors that is
142/// `(b, a)` again, and it is returned unchanged.
143#[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
159/// Read an `IfcDirection`'s two-component `DirectionRatios` and normalize.
160fn 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        // North2D requires exactly two ratios; a 3D direction here is a
205        // schema violation this crate refuses rather than silently
206        // projecting to 2D.
207        _ => {
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}