Skip to main content

ifc_georef/site/
reference.rs

1//! Reading `IfcSite.RefLatitude`, `RefLongitude` and `RefElevation`.
2
3use ifc_model::value::Value;
4use ifc_model::{EntityId, Model};
5use ifc_schema::SchemaVersion;
6
7use super::angle::{read_angle, Axis, CompoundPlaneAngle};
8use crate::error::{GeorefError, GeorefResult};
9use crate::slot::site as slot;
10
11/// The WGS84 reference point an `IfcSite` states for its placement origin.
12#[non_exhaustive]
13#[derive(Debug, Clone, PartialEq)]
14pub struct SiteReference {
15    /// The `IfcSite` entity this was read from.
16    pub entity: EntityId,
17    /// The release the model header declares, whose rules were applied.
18    pub version: SchemaVersion,
19    /// `RefLatitude`, validated against the release's WHERE rules and the
20    /// WGS84 range `[-90, 90]`.
21    pub ref_latitude: Option<CompoundPlaneAngle>,
22    /// `RefLongitude`, validated against the release's WHERE rules and the
23    /// WGS84 range `[-180, 180]`.
24    pub ref_longitude: Option<CompoundPlaneAngle>,
25    /// `RefElevation` in metres: the authored value times the project
26    /// length scale. Height above sea level in an unnamed local datum.
27    pub ref_elevation: Option<f64>,
28}
29
30impl SiteReference {
31    /// `RefLatitude` in decimal degrees, north positive.
32    #[must_use]
33    pub fn latitude_degrees(&self) -> Option<f64> {
34        self.ref_latitude.map(|a| a.decimal_degrees())
35    }
36
37    /// `RefLongitude` in decimal degrees, east positive.
38    #[must_use]
39    pub fn longitude_degrees(&self) -> Option<f64> {
40        self.ref_longitude.map(|a| a.decimal_degrees())
41    }
42}
43
44/// Read the reference point of the `IfcSite` `site`.
45///
46/// `project_metres_per_unit` is the project's `IfcUnitAssignment` length
47/// scale, explicit as for [`crate::resolve_project_to_map`]: `RefElevation`
48/// is an `IfcLengthMeasure` in the project length unit.
49///
50/// The release is bound from the header: IFC2X3, IFC4 and IFC4X3 are read;
51/// a missing, ambiguous or other schema is refused with the crate's schema
52/// errors. Every absent attribute is `None`, never a default.
53pub fn site_reference(
54    model: &Model,
55    site: EntityId,
56    project_metres_per_unit: f64,
57) -> GeorefResult<SiteReference> {
58    let version = site_release(model)?;
59    let entity = model.get(site).ok_or(GeorefError::MissingEntity {
60        referrer: site,
61        missing: site,
62    })?;
63    if !entity.is_type("IFCSITE") {
64        return Err(GeorefError::WrongType {
65            entity: site,
66            expected: "IFCSITE",
67            actual: entity.type_name.to_string(),
68        });
69    }
70    if !project_metres_per_unit.is_finite() || project_metres_per_unit <= 0.0 {
71        return Err(GeorefError::InvalidUnit {
72            entity: site,
73            detail: "project length scale must be finite and positive",
74        });
75    }
76    let ref_latitude = read_angle(
77        entity.attribute(slot::REF_LATITUDE),
78        site,
79        slot::REF_LATITUDE,
80        Axis::Latitude,
81        version,
82    )?;
83    let ref_longitude = read_angle(
84        entity.attribute(slot::REF_LONGITUDE),
85        site,
86        slot::REF_LONGITUDE,
87        Axis::Longitude,
88        version,
89    )?;
90    let invalid_elevation = GeorefError::InvalidAttribute {
91        entity: site,
92        index: slot::REF_ELEVATION,
93        name: "RefElevation",
94    };
95    let ref_elevation = match entity
96        .attribute(slot::REF_ELEVATION)
97        .map(Value::unwrap_typed)
98    {
99        None | Some(Value::Null) => None,
100        Some(value) => {
101            let metres = value.as_f64().ok_or(invalid_elevation.clone())? * project_metres_per_unit;
102            if !metres.is_finite() {
103                return Err(invalid_elevation);
104            }
105            Some(metres)
106        }
107    };
108    Ok(SiteReference {
109        entity: site,
110        version,
111        ref_latitude,
112        ref_longitude,
113        ref_elevation,
114    })
115}
116
117/// The header's release, if it is one whose `IfcSite` layout is verified.
118///
119/// Wider than [`crate::GeorefView`]: IFC2X3 declares `IfcSite` with the
120/// same reference attributes although it has no coordinate operations.
121fn site_release(model: &Model) -> GeorefResult<SchemaVersion> {
122    let token = match model.header().schema.as_slice() {
123        [] => return Err(GeorefError::MissingSchema),
124        [token] => token,
125        tokens => {
126            return Err(GeorefError::AmbiguousSchema {
127                tokens: tokens.to_vec(),
128            })
129        }
130    };
131    match SchemaVersion::from_header_token(token) {
132        Some(version @ (SchemaVersion::Ifc2x3 | SchemaVersion::Ifc4 | SchemaVersion::Ifc4x3)) => {
133            Ok(version)
134        }
135        // IFC4X1/IFC4X2 are bundled but not verified here: refused, never
136        // read with another release's rules.
137        _ => Err(GeorefError::UnsupportedSchema {
138            token: token.clone(),
139        }),
140    }
141}