Skip to main content

ifc_georef/crs/
projected.rs

1//! Borrowed `IfcProjectedCRS` interpretation.
2
3use ifc_model::value::Value;
4use ifc_model::{Entity, EntityId, Model};
5use ifc_schema::SchemaVersion;
6
7use crate::crs::unit::{resolve_length_unit, LengthUnit};
8use crate::crs::Damage;
9use crate::error::{GeorefError, GeorefResult};
10use crate::slot::projected_crs as slot;
11use crate::slot::well_known_text as wkt_slot;
12
13/// A projected coordinate reference system read from `IfcProjectedCRS`.
14#[derive(Debug, Clone, PartialEq)]
15#[non_exhaustive]
16pub struct ProjectedCrs {
17    /// The `IfcProjectedCRS` entity this was read from, or for IFC2X3 the
18    /// `ePSet_ProjectedCRS` property set.
19    pub entity: EntityId,
20    /// CRS identifier, conventionally an EPSG code such as `EPSG:25832`.
21    ///
22    /// Always present under IFC4, which declares it mandatory. IFC4X3 makes
23    /// it optional under `NameOrWKT`: an unnamed CRS is read only when
24    /// exactly one `IfcWellKnownText` defines it (see `well_known_text`).
25    pub name: Option<String>,
26    /// Optional human-readable description.
27    pub description: Option<String>,
28    /// Optional horizontal datum, such as `ETRS89`.
29    pub geodetic_datum: Option<String>,
30    /// Optional vertical datum, such as `DHHN2016`.
31    pub vertical_datum: Option<String>,
32    /// Optional projection name, such as `UTM`.
33    pub map_projection: Option<String>,
34    /// Optional projection zone, such as `32N`.
35    pub map_zone: Option<String>,
36    /// `MapUnit` as authored: `None` when the file leaves it unset. For
37    /// IFC2X3, the optional `MapUnit` text property, an SI length unit name.
38    ///
39    /// IFC4 and IFC4X3 both declare `MapUnit : OPTIONAL IfcNamedUnit`
40    /// (`WHERE` it is a `LENGTHUNIT` when it exists); an omitted unit means
41    /// the coordinate axes use the project's default length unit. This field
42    /// never fills that default in, so a CRS that states the project's unit
43    /// stays distinguishable from one that states none. The resolved unit,
44    /// with the default applied, is [`ProjectToMap::map_unit`]; the same
45    /// declared value is [`ProjectToMap::declared_map_unit`] (#296).
46    ///
47    /// [`ProjectToMap::map_unit`]: crate::ProjectToMap::map_unit
48    /// [`ProjectToMap::declared_map_unit`]: crate::ProjectToMap::declared_map_unit
49    pub map_unit: Option<LengthUnit>,
50    /// IFC4X3: the OGC WKT literal of the one `IfcWellKnownText` whose
51    /// `CoordinateReferenceSystem` is this CRS, verbatim. Always `None`
52    /// under IFC4, which declares no `IfcWellKnownText`.
53    pub well_known_text: Option<String>,
54}
55
56pub(crate) fn projected_crs(
57    model: &Model,
58    id: EntityId,
59    damage: &Damage,
60) -> GeorefResult<ProjectedCrs> {
61    damage.check(id)?;
62    let entity = model.get(id).ok_or(GeorefError::MissingEntity {
63        referrer: id,
64        missing: id,
65    })?;
66    if !entity.is_type("IFCPROJECTEDCRS") {
67        return Err(GeorefError::WrongType {
68            entity: id,
69            expected: "IFCPROJECTEDCRS",
70            actual: entity.type_name.to_string(),
71        });
72    }
73    // Slots are pinned against the bundled IFC4 and IFC4X3 tables in
74    // `crate::slot`; the two versions declare them differently but place
75    // them identically. What differs is whether `Name` is optional.
76    let (name, well_known_text) = if declares_ifc4x3(model) {
77        name_or_wkt(model, id, entity, damage)?
78    } else {
79        let name = entity
80            .text(slot::NAME)
81            .ok_or(GeorefError::MissingAttribute {
82                entity: id,
83                index: slot::NAME,
84                name: "Name",
85            })?;
86        (Some(name.to_owned()), None)
87    };
88    let map_unit = match entity.attribute(slot::MAP_UNIT) {
89        None | Some(ifc_model::value::Value::Null) => None,
90        Some(value) => {
91            let unit = value.as_ref_id().ok_or(GeorefError::InvalidAttribute {
92                entity: id,
93                index: slot::MAP_UNIT,
94                name: "MapUnit",
95            })?;
96            Some(resolve_length_unit(model, unit, damage)?)
97        }
98    };
99    Ok(ProjectedCrs {
100        entity: id,
101        name,
102        description: entity.text(slot::DESCRIPTION).map(str::to_owned),
103        geodetic_datum: entity.text(slot::GEODETIC_DATUM).map(str::to_owned),
104        vertical_datum: entity.text(slot::VERTICAL_DATUM).map(str::to_owned),
105        map_projection: entity.text(slot::MAP_PROJECTION).map(str::to_owned),
106        map_zone: entity.text(slot::MAP_ZONE).map(str::to_owned),
107        map_unit,
108        well_known_text,
109    })
110}
111
112/// Whether the header binds IFC4X3, the one release where
113/// `IfcCoordinateReferenceSystem.Name` is `OPTIONAL`. A missing or
114/// ambiguous header keeps the IFC4 rule, which requires the name.
115fn declares_ifc4x3(model: &Model) -> bool {
116    matches!(
117        model.header().schema.as_slice(),
118        [token] if SchemaVersion::from_header_token(token) == Some(SchemaVersion::Ifc4x3)
119    )
120}
121
122/// IFC4X3 `Name : OPTIONAL IfcLabel` with
123/// `NameOrWKT : (HIINDEX(WellKnownText) = 1) OR EXISTS(Name)`, where
124/// `WellKnownText` is the inverse `SET [0:1] OF IfcWellKnownText FOR
125/// CoordinateReferenceSystem`.
126///
127/// More than one `IfcWellKnownText` for the CRS breaks the inverse's
128/// cardinality and is refused whether or not the CRS is named, rather than
129/// one definition being picked.
130pub(crate) fn name_or_wkt(
131    model: &Model,
132    id: EntityId,
133    entity: &Entity,
134    damage: &Damage,
135) -> GeorefResult<(Option<String>, Option<String>)> {
136    let name = match entity.attribute(slot::NAME) {
137        None | Some(Value::Null) => None,
138        Some(value) => Some(
139            value
140                .unwrap_typed()
141                .as_text()
142                .ok_or(GeorefError::InvalidAttribute {
143                    entity: id,
144                    index: slot::NAME,
145                    name: "Name",
146                })?
147                .to_owned(),
148        ),
149    };
150    // Every definition scanned is checked before its CRS is read: a reported
151    // one may be the copy that named another CRS (#690).
152    let mut matching = Vec::new();
153    for (wkt_id, wkt) in model.of_type("IFCWELLKNOWNTEXT") {
154        damage.check(wkt_id)?;
155        if wkt
156            .attribute(wkt_slot::COORDINATE_REFERENCE_SYSTEM)
157            .and_then(Value::as_ref_id)
158            == Some(id)
159        {
160            matching.push((wkt_id, wkt));
161        }
162    }
163    let mut definitions = matching.into_iter();
164    let well_known_text = match (definitions.next(), definitions.next()) {
165        (None, _) => None,
166        (Some((wkt_id, wkt)), None) => Some({
167            damage.check(wkt_id)?;
168            wkt.text(wkt_slot::WELL_KNOWN_TEXT)
169                .ok_or(GeorefError::InvalidAttribute {
170                    entity: wkt_id,
171                    index: wkt_slot::WELL_KNOWN_TEXT,
172                    name: "WellKnownText",
173                })?
174                .to_owned()
175        }),
176        (Some(_), Some(_)) => {
177            return Err(GeorefError::RuleViolation {
178                entity: id,
179                rule: "WellKnownText : SET [0:1] OF IfcWellKnownText",
180            })
181        }
182    };
183    if name.is_none() && well_known_text.is_none() {
184        return Err(GeorefError::RuleViolation {
185            entity: id,
186            rule: "NameOrWKT",
187        });
188    }
189    Ok((name, well_known_text))
190}