Skip to main content

ifc_lite_processing/
georeferencing.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Georeferencing extraction for the HTTP server response.
6//!
7//! The browser parser (`@ifc-lite/parse`) exposes `IfcMapConversion` /
8//! `IfcProjectedCRS` georeferencing via `extractGeoreferencing`. The server
9//! previously surfaced only a coarse `is_geo_referenced` boolean, so consumers
10//! couldn't recover the real-world CRS, false eastings/northings, or grid-north
11//! rotation. This module reuses the shared `ifc_lite_core::GeoRefExtractor`
12//! (the same extraction the desktop/native paths use) and maps it into a
13//! serializable, server-friendly shape carried inline on every geometry
14//! endpoint's `ModelMetadata` (issue #900 parity follow-up).
15
16use std::sync::Arc;
17
18use ifc_lite_core::{
19    keyword_eq, EntityDecoder, EntityIndex, EntityScanner, GeoRefExtractor, IfcType,
20};
21use serde::{Deserialize, Serialize};
22
23/// Georeferencing metadata (`IfcMapConversion` + `IfcProjectedCRS`).
24///
25/// Mirrors `ifc_lite_core::GeoReference` with two derived conveniences
26/// (`rotation_degrees`, `transform_matrix`) so consumers don't have to
27/// recompute the rotation or the local→map matrix.
28#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
29pub struct Georeferencing {
30    /// Projected CRS name from `IfcProjectedCRS.Name` (e.g. `"EPSG:32632"`).
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub crs_name: Option<String>,
33    /// Geodetic datum (e.g. `"WGS84"`).
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub geodetic_datum: Option<String>,
36    /// Vertical datum (e.g. `"NAVD88"`).
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub vertical_datum: Option<String>,
39    /// Map projection (e.g. `"UTM"`).
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub map_projection: Option<String>,
42    /// False easting — X offset to the map CRS, in the project's length unit.
43    pub eastings: f64,
44    /// False northing — Y offset to the map CRS, in the project's length unit.
45    pub northings: f64,
46    /// Orthogonal height — Z offset to the map CRS.
47    pub orthogonal_height: f64,
48    /// X-axis abscissa: cosine of the rotation to grid north.
49    pub x_axis_abscissa: f64,
50    /// X-axis ordinate: sine of the rotation to grid north.
51    pub x_axis_ordinate: f64,
52    /// Scale factor applied during the local→map transform (default `1.0`).
53    pub scale: f64,
54    /// Rotation to grid north in degrees, derived from the X-axis direction.
55    pub rotation_degrees: f64,
56    /// Local→map transform as a column-major 4×4 matrix (16 values).
57    pub transform_matrix: [f64; 16],
58    /// CRS description from `IfcProjectedCRS.Description`.
59    #[serde(skip_serializing_if = "Option::is_none", default)]
60    pub crs_description: Option<String>,
61    /// Map zone (e.g. `"32N"`) from `IfcProjectedCRS.MapZone`.
62    #[serde(skip_serializing_if = "Option::is_none", default)]
63    pub map_zone: Option<String>,
64    /// Map unit name resolved from `IfcProjectedCRS.MapUnit` (e.g. `"METRE"`,
65    /// `"MILLIMETRE"`); absent when no MapUnit is authored.
66    #[serde(skip_serializing_if = "Option::is_none", default)]
67    pub map_unit: Option<String>,
68    /// Scale factor converting MapConversion values to metres (0.001 for
69    /// millimetres); absent when no MapUnit is authored.
70    #[serde(skip_serializing_if = "Option::is_none", default)]
71    pub map_unit_scale: Option<f64>,
72    /// Provenance: `"mapConversion"`, `"ePSetMapConversion"`, or
73    /// `"siteLocation"` — same labels as the TS parser's
74    /// `GeoreferenceInfo.source`.
75    #[serde(skip_serializing_if = "Option::is_none", default)]
76    pub source: Option<String>,
77}
78
79impl Georeferencing {
80    fn from_core(geo: &ifc_lite_core::GeoReference) -> Self {
81        Self {
82            crs_name: geo.crs_name.clone(),
83            geodetic_datum: geo.geodetic_datum.clone(),
84            vertical_datum: geo.vertical_datum.clone(),
85            map_projection: geo.map_projection.clone(),
86            eastings: geo.eastings,
87            northings: geo.northings,
88            orthogonal_height: geo.orthogonal_height,
89            x_axis_abscissa: geo.x_axis_abscissa,
90            x_axis_ordinate: geo.x_axis_ordinate,
91            scale: geo.scale,
92            rotation_degrees: geo.rotation().to_degrees(),
93            transform_matrix: geo.to_matrix(),
94            crs_description: geo.crs_description.clone(),
95            map_zone: geo.map_zone.clone(),
96            map_unit: geo.map_unit.clone(),
97            map_unit_scale: geo.map_unit_scale,
98            source: Some(geo.source.label().to_string()),
99        }
100    }
101}
102
103/// Extract georeferencing from an IFC file, returning `None` when the model
104/// carries no `IfcMapConversion` / `ePSet_MapConversion` data.
105///
106/// Only the entity types the extractor needs (`IfcMapConversion`,
107/// `IfcProjectedCRS`, and `IfcPropertySet` for the IFC2x3 `ePSet_MapConversion`
108/// fallback) are collected from the scan — their `IfcType` is known from the
109/// entity name, so no decoding happens while building the candidate list.
110pub fn extract_georeferencing<T>(content: &T) -> Option<Georeferencing>
111where
112    T: AsRef<[u8]> + ?Sized,
113{
114    let content = content.as_ref();
115    // Parallel on native (byte-identical to `build_entity_index`), serial on wasm.
116    let entity_index = Arc::new(crate::build_entity_index_parallel(content));
117    extract_georeferencing_with_index(content, &entity_index)
118}
119
120/// [`extract_georeferencing`], reusing an index the caller already holds.
121///
122/// The extractor resolves its references by id, so this pass genuinely needs an
123/// index; what it does not need is a second one. A caller that has already
124/// scanned the file (the geometry pipeline holds one for its whole run) was
125/// paying a full extra scan to build a map it had in hand.
126///
127/// `entity_index` must have been built from this same `content`. Given that, the
128/// result is identical to the wrapper's.
129pub fn extract_georeferencing_with_index(
130    content: &[u8],
131    entity_index: &Arc<EntityIndex>,
132) -> Option<Georeferencing> {
133    let mut entity_types = Vec::new();
134    let mut scanner = EntityScanner::new(content);
135    while let Some((id, type_name, _, _)) = scanner.next_entity() {
136        if let Some(ifc_type) = georeferencing_candidate_type(type_name) {
137            entity_types.push((id, ifc_type));
138        }
139    }
140    extract_georeferencing_from_candidates(
141        &mut EntityDecoder::with_arc_index(content, entity_index.clone()), &entity_types)
142}
143
144/// Candidate classification shared by standalone extraction and the native
145/// geometry scan. Preserves file order, including all sites.
146///
147/// `type_name` is the STEP keyword exactly as the scanner read it, and STEP
148/// keyword case is not significant (ISO 10303-21), so the comparison is
149/// case-insensitive. A case-sensitive match silently classified every entity in
150/// a lowercase- or CamelCase-keyword file as a non-candidate, and the model then
151/// reported no georeferencing at all despite carrying complete data (#4497).
152/// `keyword_eq` rather than an uppercase copy: this runs once per entity in
153/// the scan loop, and the comparison is against fixed literals, so there is
154/// nothing an allocated canonical form would be reused for — the same shape
155/// `processor::quick_metadata::is_quick_spatial_type_ci` uses.
156pub(crate) fn georeferencing_candidate_type(type_name: &str) -> Option<IfcType> {
157    // Scaled's first eight attributes have the base conversion layout.
158    if keyword_eq(type_name, "IFCMAPCONVERSION")
159        || keyword_eq(type_name, "IFCMAPCONVERSIONSCALED")
160    {
161        return Some(IfcType::IfcMapConversion);
162    }
163    if keyword_eq(type_name, "IFCPROJECTEDCRS") {
164        return Some(IfcType::IfcProjectedCRS);
165    }
166    if keyword_eq(type_name, "IFCPROPERTYSET") {
167        return Some(IfcType::IfcPropertySet);
168    }
169    if keyword_eq(type_name, "IFCSITE") {
170        return Some(IfcType::IfcSite);
171    }
172    None
173}
174
175/// Reuse candidates from the geometry scan, avoiding the remaining whole-file
176/// scan after index reuse. A fresh decoder preserves the standalone extractor's
177/// lookup semantics, including duplicate ids, rather than inheriting scan caches.
178pub(crate) fn extract_georeferencing_from_candidates(
179    decoder: &mut EntityDecoder<'_>,
180    entity_types: &[(u32, IfcType)],
181) -> Option<Georeferencing> {
182    if entity_types.is_empty() {
183        return None;
184    }
185
186    match GeoRefExtractor::extract(decoder, entity_types) {
187        Ok(Some(geo)) => Some(Georeferencing::from_core(&geo)),
188        Ok(None) => None,
189        Err(e) => {
190            tracing::debug!(error = %e, "Georeferencing extraction failed");
191            None
192        }
193    }
194}
195
196#[cfg(test)]
197#[path = "georeferencing_tests.rs"]
198mod tests;