Skip to main content

ifc_georef/
view.rs

1//! Pins the model's declared schema to IFC4 or IFC4X3, and names the
2//! coordinate-operation entities each schema version actually declares.
3//!
4//! # Why this crate does not need per-attribute version dispatch
5//!
6//! `IfcCoordinateReferenceSystem`/`IfcProjectedCRS`'s attribute *counts*
7//! differ between IFC4 and IFC4X3 (IFC4X3 drops `VerticalDatum` from the
8//! base `IfcCoordinateReferenceSystem` and re-adds it one level down on
9//! `IfcProjectedCRS`), but the two changes cancel out: the absolute
10//! attribute slots `crs::projected` reads (`Name`=0, `Description`=1,
11//! `GeodeticDatum`=2, `VerticalDatum`=3, `MapProjection`=4, `MapZone`=5,
12//! `MapUnit`=6) are identical in both schemas. `IfcMapConversion`'s own six
13//! attributes are unchanged too. So `resolve_project_to_map` and
14//! `projected_crs` need no version branch for slots -- confirmed against
15//! `IFC4.exp`/`IFC4X3_ADD2.exp` directly, and asserted against both bundled
16//! schema tables by `crate::slot`'s tests.
17//!
18//! The one rule that does differ is `Name`: mandatory in IFC4, `OPTIONAL`
19//! in IFC4X3 under `NameOrWKT : (HIINDEX(WellKnownText) = 1) OR
20//! EXISTS(Name)`. `projected_crs` reads the header's release for that alone
21//! (#142): under IFC4X3 an unnamed CRS reads when exactly one
22//! `IfcWellKnownText` defines it; anything else requires the name.
23//!
24//! # What actually differs
25//!
26//! - **IFC2X3** declares no georeferencing entities at all (`IfcMapConversion`,
27//!   `IfcProjectedCRS`, `IfcCoordinateReferenceSystem` do not exist in
28//!   `IFC2X3_TC1.exp`), so this view refuses it. IFC2X3 files carry the same
29//!   parameters in the `ePSet_MapConversion` and `ePSet_ProjectedCRS`
30//!   property sets instead, read by
31//!   [`crate::resolve_property_set_georeferencing`] without a view.
32//! - **IFC4** declares exactly one coordinate-operation shape:
33//!   `IfcMapConversion` targeting `IfcProjectedCRS` (the only
34//!   `IfcCoordinateReferenceSystem` subtype IFC4 has).
35//! - **IFC4X3** adds three shapes IFC4 cannot express at all:
36//!   `IfcMapConversionScaled` (per-axis scale factors), `IfcRigidOperation`
37//!   (a pure offset with no scale/rotation, in length or plane-angle
38//!   coordinates), and `IfcGeographicCRS` (a second
39//!   `IfcCoordinateReferenceSystem` subtype, for geodetic rather than
40//!   projected targets). The first two lower to a project-to-map transform
41//!   (a rigid operation only with length coordinates); a plane-angle rigid
42//!   operation onto an `IfcGeographicCRS` is read, not lowered, by
43//!   [`crate::resolve_geographic_offset_in`]. Under an IFC4 header all
44//!   three are refused with [`GeorefError::UnsupportedOperation`] naming
45//!   the release that does not declare them.
46
47use ifc_model::{EntityId, Model};
48use ifc_schema::{for_version, Schema, SchemaVersion};
49
50use crate::error::{GeorefError, GeorefResult};
51
52/// A model whose declared schema has been pinned to IFC4 or IFC4X3.
53#[derive(Debug, Clone, Copy)]
54pub struct GeorefView<'m> {
55    pub(crate) model: &'m Model,
56    pub(crate) schema: &'static Schema,
57    pub(crate) version: SchemaVersion,
58}
59
60impl<'m> GeorefView<'m> {
61    /// Pin the model's declared schema and confirm it is IFC4 or IFC4X3.
62    ///
63    /// IFC2X3 is refused: it declares no `IfcMapConversion`,
64    /// `IfcProjectedCRS`, or `IfcCoordinateReferenceSystem` at all. Its
65    /// property-set georeferencing is read by
66    /// [`crate::resolve_property_set_georeferencing`].
67    pub fn for_model(model: &'m Model) -> GeorefResult<Self> {
68        let (token, version) = declared_release(model)?;
69        let schema = match version {
70            // A verified release whose table this build leaves out (#306)
71            // is refused like an unverified one.
72            SchemaVersion::Ifc4 | SchemaVersion::Ifc4x3 => {
73                for_version(version).map_err(|_| GeorefError::UnsupportedSchema {
74                    token: token.clone(),
75                })?
76            }
77            // IFC2X3 predates these layouts; IFC4X1 and IFC4X2 are bundled
78            // by ifc-schema but not verified here. Refused, never aliased.
79            _ => {
80                return Err(GeorefError::UnsupportedSchema {
81                    token: token.clone(),
82                });
83            }
84            // A release added to `SchemaVersion` later has no reviewed
85            // georeferencing layout: refused rather than read with another's.
86            #[allow(unreachable_patterns)]
87            _ => {
88                return Err(GeorefError::UnsupportedSchema {
89                    token: token.clone(),
90                });
91            }
92        };
93        Ok(Self {
94            model,
95            schema,
96            version,
97        })
98    }
99
100    /// The pinned schema version.
101    #[must_use]
102    pub const fn version(&self) -> SchemaVersion {
103        self.version
104    }
105
106    /// The pinned schema, for subtype-aware (`is_a`) queries.
107    #[must_use]
108    pub const fn schema(&self) -> &'static Schema {
109        self.schema
110    }
111
112    /// Confirm `id` is declared in the pinned schema at all, distinguishing
113    /// a version-specific entity (declared in IFC4X3, not IFC4) from a
114    /// genuinely unknown or malformed type name.
115    pub(crate) fn require_known_type(&self, id: EntityId) -> GeorefResult<&'m str> {
116        let entity = self.model.get(id).ok_or(GeorefError::MissingEntity {
117            referrer: id,
118            missing: id,
119        })?;
120        let type_name = entity.type_name.as_ref();
121        if self.schema.entity(type_name).is_none() {
122            return Err(GeorefError::UnsupportedOperation {
123                entity: id,
124                actual: format!(
125                    "{type_name} (not declared in {})",
126                    self.version.release_id()
127                ),
128            });
129        }
130        Ok(type_name)
131    }
132}
133
134/// The one `FILE_SCHEMA` token of `model` and the release it names.
135///
136/// # Errors
137///
138/// [`GeorefError::MissingSchema`] for no token,
139/// [`GeorefError::AmbiguousSchema`] for more than one, and
140/// [`GeorefError::UnsupportedSchema`] for a token that names no release.
141pub(crate) fn declared_release(model: &Model) -> GeorefResult<(&String, SchemaVersion)> {
142    let token = match model.header().schema.as_slice() {
143        [] => return Err(GeorefError::MissingSchema),
144        [token] => token,
145        tokens => {
146            return Err(GeorefError::AmbiguousSchema {
147                tokens: tokens.to_vec(),
148            });
149        }
150    };
151    let version =
152        SchemaVersion::from_header_token(token).ok_or_else(|| GeorefError::UnsupportedSchema {
153            token: token.clone(),
154        })?;
155    Ok((token, version))
156}
157
158#[cfg(test)]
159mod tests {
160    use ifc_model::Entity;
161
162    use super::*;
163
164    fn model_with_schema(token: &str) -> Model {
165        let mut model = Model::new();
166        model.header_mut().schema = vec![token.to_owned()];
167        model
168    }
169
170    #[test]
171    fn accepts_ifc4() {
172        let model = model_with_schema("IFC4");
173        let view = GeorefView::for_model(&model).expect("IFC4 is accepted");
174        assert_eq!(view.version(), SchemaVersion::Ifc4);
175    }
176
177    #[test]
178    fn accepts_ifc4x3_and_its_add2_variant() {
179        for token in ["IFC4X3", "IFC4X3_ADD2"] {
180            let model = model_with_schema(token);
181            let view = GeorefView::for_model(&model).expect("IFC4X3 is accepted");
182            assert_eq!(view.version(), SchemaVersion::Ifc4x3);
183        }
184    }
185
186    #[test]
187    fn refuses_ifc2x3_because_it_declares_no_georeferencing_entities() {
188        let model = model_with_schema("IFC2X3");
189        assert!(matches!(
190            GeorefView::for_model(&model),
191            Err(GeorefError::UnsupportedSchema { token }) if token == "IFC2X3"
192        ));
193    }
194
195    #[test]
196    fn refuses_an_unrecognized_schema_token() {
197        let model = model_with_schema("IFC5");
198        assert!(matches!(
199            GeorefView::for_model(&model),
200            Err(GeorefError::UnsupportedSchema { token }) if token == "IFC5"
201        ));
202    }
203
204    #[test]
205    fn refuses_a_missing_schema_declaration() {
206        let model = Model::new();
207        assert!(matches!(
208            GeorefView::for_model(&model),
209            Err(GeorefError::MissingSchema)
210        ));
211    }
212
213    #[test]
214    fn refuses_an_ambiguous_schema_declaration() {
215        let mut model = Model::new();
216        model.header_mut().schema = vec!["IFC4".to_owned(), "IFC4X3".to_owned()];
217        assert!(matches!(
218            GeorefView::for_model(&model),
219            Err(GeorefError::AmbiguousSchema { tokens })
220                if tokens == vec!["IFC4".to_owned(), "IFC4X3".to_owned()]
221        ));
222    }
223
224    #[test]
225    fn names_an_ifc4x3_only_coordinate_operation_when_read_under_ifc4() {
226        let mut model = model_with_schema("IFC4");
227        model.insert(EntityId(1), Entity::new("IFCGEOGRAPHICCRS", vec![]));
228        let view = GeorefView::for_model(&model).expect("IFC4 is accepted");
229        assert!(matches!(
230            view.require_known_type(EntityId(1)),
231            Err(GeorefError::UnsupportedOperation { entity, actual })
232                if entity == EntityId(1) && actual.contains("IFCGEOGRAPHICCRS") && actual.contains("IFC4_ADD2_TC1")
233        ));
234    }
235
236    #[test]
237    fn recognizes_an_ifc4x3_only_coordinate_operation_when_read_under_ifc4x3() {
238        let mut model = model_with_schema("IFC4X3");
239        model.insert(EntityId(1), Entity::new("IFCGEOGRAPHICCRS", vec![]));
240        let view = GeorefView::for_model(&model).expect("IFC4X3 is accepted");
241        assert_eq!(
242            view.require_known_type(EntityId(1))
243                .expect("declared in IFC4X3"),
244            "IFCGEOGRAPHICCRS"
245        );
246    }
247}
248
249#[cfg(test)]
250mod intermediate_release_tests {
251    use super::*;
252
253    /// IFC4X1 and IFC4X2 have bundled tables but no verified layout here:
254    /// refused with the unsupported-schema error, never read as IFC4/IFC4X3.
255    #[test]
256    fn ifc4x1_and_ifc4x2_are_refused_not_aliased() {
257        for token in ["IFC4X1", "IFC4X2"] {
258            let mut model = Model::new();
259            model.header_mut().schema = vec![token.to_owned()];
260            assert!(
261                matches!(
262                    GeorefView::for_model(&model),
263                    Err(GeorefError::UnsupportedSchema { token: found }) if found == token
264                ),
265                "{token} must be refused"
266            );
267        }
268    }
269}