Skip to main content

ifc_georef/conversion/
rigid.rs

1//! IFC4X3 `IfcRigidOperation`: a translation with no rotation or scale.
2//!
3//! IFC4X3 ADD2 declares
4//!
5//! ```text
6//! FirstCoordinate  : IfcMeasureValue;
7//! SecondCoordinate : IfcMeasureValue;
8//! Height           : OPTIONAL IfcLengthMeasure;
9//! WHERE SameCoordinateType :
10//!   (IFCLENGTHMEASURE IN TYPEOF(First) AND IFCLENGTHMEASURE IN TYPEOF(Second))
11//!   OR (IFCPLANEANGLEMEASURE IN TYPEOF(First) AND IFCPLANEANGLEMEASURE IN TYPEOF(Second))
12//! ```
13//!
14//! `IfcMeasureValue` is a SELECT, so each coordinate must carry its type
15//! (`IFCLENGTHMEASURE(10.)`); an untyped REAL satisfies neither branch and
16//! is a `SameCoordinateType` violation. `TYPEOF` of a defined type includes
17//! the types it is defined on, so `IfcPositiveLengthMeasure` and
18//! `IfcNonNegativeLengthMeasure` (both `= IfcLengthMeasure`) count as
19//! length, and `IfcPositivePlaneAngleMeasure` (`= IfcPlaneAngleMeasure`)
20//! as plane angle.
21//!
22//! # Length coordinates: a translation
23//!
24//! The two coordinates are the offset along the target `IfcProjectedCRS`'s
25//! first and second axes, and `Height` the vertical offset, all in the
26//! target's `MapUnit` (the project length unit when it has none), the
27//! convention `IfcMapConversion`'s `Eastings`/`Northings` use. "Rigid"
28//! means distance-preserving, so the linear part is the identity in
29//! metres whatever the two units are. A length rigid operation whose
30//! target is not an `IfcProjectedCRS` is refused with `WrongType`: a metre
31//! offset on latitude/longitude axes denotes nothing.
32//!
33//! # Plane-angle coordinates: a geographic offset
34//!
35//! Angles offset latitude and longitude on an `IfcGeographicCRS`. No
36//! metre-to-metre affine transform expresses that, so
37//! [`crate::resolve_project_to_map`] refuses the form with
38//! [`GeorefError::CoordinateMeasureMismatch`], and
39//! [`resolve_geographic_offset_in`] reads it as authored instead. Nothing
40//! converts the angles: the schema does not tie `IfcPlaneAngleMeasure`
41//! here to the target's `AngleUnit`, so the values and the declared unit
42//! are both returned and the caller decides.
43
44use ifc_model::value::Value;
45use ifc_model::EntityId;
46
47use crate::context::OperationSource;
48use crate::crs::{geographic_crs, projected_crs, Damage, GeographicCrs, LengthUnit};
49use crate::error::{GeorefError, GeorefResult};
50use crate::slot::map_conversion as base;
51use crate::slot::rigid_operation as slot;
52use crate::view::GeorefView;
53
54use super::operation::{Operation, OperationKind, ProjectToMap};
55
56const LENGTH: &str = "IFCLENGTHMEASURE";
57const PLANE_ANGLE: &str = "IFCPLANEANGLEMEASURE";
58
59/// An IFC4X3 `IfcRigidOperation` with plane-angle coordinates, read as
60/// authored.
61#[derive(Debug, Clone, PartialEq)]
62#[non_exhaustive]
63pub struct GeographicOffset {
64    /// The `IfcRigidOperation` entity.
65    pub operation: EntityId,
66    /// The validated `SourceCRS`.
67    pub source: OperationSource,
68    /// The target `IfcGeographicCRS`, with its declared units.
69    pub target_crs: GeographicCrs,
70    /// `FirstCoordinate`, the `IfcPlaneAngleMeasure` value as authored.
71    pub first_coordinate: f64,
72    /// `SecondCoordinate`, the `IfcPlaneAngleMeasure` value as authored.
73    pub second_coordinate: f64,
74    /// `Height`, the `IfcLengthMeasure` value as authored, when stated.
75    pub height: Option<f64>,
76}
77
78/// Read an IFC4X3 `IfcRigidOperation` whose coordinates are plane angles.
79///
80/// # Errors
81///
82/// [`GeorefError::UnsupportedOperation`] under IFC4, which declares no
83/// `IfcRigidOperation`; [`GeorefError::WrongType`] for another entity or a
84/// target that is not an `IfcGeographicCRS`;
85/// [`GeorefError::RuleViolation`] `SameCoordinateType`;
86/// [`GeorefError::CoordinateMeasureMismatch`] for length coordinates,
87/// which [`crate::resolve_project_to_map_in`] lowers instead; and every
88/// source error of [`crate::resolve_operation_source`].
89pub fn resolve_geographic_offset_in(
90    view: &GeorefView,
91    id: EntityId,
92) -> GeorefResult<GeographicOffset> {
93    let actual = view.require_known_type(id)?;
94    let entity = view.model.get(id).ok_or(GeorefError::MissingEntity {
95        referrer: id,
96        missing: id,
97    })?;
98    if !actual.eq_ignore_ascii_case("IFCRIGIDOPERATION") {
99        return Err(GeorefError::WrongType {
100            entity: id,
101            expected: "IFCRIGIDOPERATION",
102            actual: actual.to_owned(),
103        });
104    }
105    let damage = Damage::of(view.model)?;
106    let op = Operation {
107        model: view.model,
108        view: Some(view),
109        id,
110        entity,
111        damage: &damage,
112    };
113    damage.check(id)?;
114    let coordinates = coordinates(&op)?;
115    if coordinates.measure != PLANE_ANGLE {
116        return Err(GeorefError::CoordinateMeasureMismatch {
117            entity: id,
118            expected: PLANE_ANGLE,
119            actual: coordinates.measure,
120        });
121    }
122    let source = op.source()?;
123    let target = op.required_ref(base::TARGET_CRS, "TargetCRS")?;
124    let target_crs = geographic_crs(view.model, target, &damage)?;
125    damage.settle(GeographicOffset {
126        operation: id,
127        source,
128        target_crs,
129        first_coordinate: coordinates.first,
130        second_coordinate: coordinates.second,
131        height: coordinates.height,
132    })
133}
134
135/// Lower a length-coordinate `IfcRigidOperation` to a translation.
136pub(super) fn lower(
137    op: &Operation<'_, '_>,
138    project_unit: LengthUnit,
139) -> GeorefResult<ProjectToMap> {
140    let coordinates = coordinates(op)?;
141    if coordinates.measure != LENGTH {
142        return Err(GeorefError::CoordinateMeasureMismatch {
143            entity: op.id,
144            expected: LENGTH,
145            actual: coordinates.measure,
146        });
147    }
148    let source = op.source()?;
149    let target = op.required_ref(base::TARGET_CRS, "TargetCRS")?;
150    let target_crs = projected_crs(op.model, target, op.damage)?;
151    let map_unit = target_crs
152        .map_unit
153        .clone()
154        .unwrap_or_else(|| project_unit.clone());
155    let metres = map_unit.metres_per_unit;
156    let translation = [
157        op.finite(
158            slot::FIRST_COORDINATE,
159            "FirstCoordinate",
160            coordinates.first * metres,
161        )?,
162        op.finite(
163            slot::SECOND_COORDINATE,
164            "SecondCoordinate",
165            coordinates.second * metres,
166        )?,
167        op.finite(
168            slot::HEIGHT,
169            "Height",
170            coordinates.height.unwrap_or(0.0) * metres,
171        )?,
172    ];
173    Ok(ProjectToMap::new(
174        source,
175        op.id,
176        OperationKind::RigidOperation {
177            height: coordinates.height,
178        },
179        target_crs,
180        [
181            coordinates.first,
182            coordinates.second,
183            coordinates.height.unwrap_or(0.0),
184        ],
185        (project_unit, map_unit),
186        1.0,
187        (1.0, 0.0),
188        [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
189        translation,
190    ))
191}
192
193/// The two coordinates, their shared measure, and the optional height.
194struct Coordinates {
195    measure: &'static str,
196    first: f64,
197    second: f64,
198    height: Option<f64>,
199}
200
201fn coordinates(op: &Operation<'_, '_>) -> GeorefResult<Coordinates> {
202    let (first_measure, first) = measure(op, slot::FIRST_COORDINATE, "FirstCoordinate")?;
203    let (second_measure, second) = measure(op, slot::SECOND_COORDINATE, "SecondCoordinate")?;
204    let measure = match (first_measure, second_measure) {
205        (Some(a), Some(b)) if a == b => a,
206        _ => {
207            return Err(GeorefError::RuleViolation {
208                entity: op.id,
209                rule: "SameCoordinateType",
210            })
211        }
212    };
213    let height = op
214        .optional_number(slot::HEIGHT, "Height")?
215        .map(|value| op.finite(slot::HEIGHT, "Height", value))
216        .transpose()?;
217    Ok(Coordinates {
218        measure,
219        first: op.finite(slot::FIRST_COORDINATE, "FirstCoordinate", first)?,
220        second: op.finite(slot::SECOND_COORDINATE, "SecondCoordinate", second)?,
221        height,
222    })
223}
224
225/// One `IfcMeasureValue` slot: which `SameCoordinateType` branch its type
226/// satisfies (`None` for neither, including an untyped REAL), and its value.
227fn measure(
228    op: &Operation<'_, '_>,
229    index: usize,
230    name: &'static str,
231) -> GeorefResult<(Option<&'static str>, f64)> {
232    let invalid = GeorefError::InvalidAttribute {
233        entity: op.id,
234        index,
235        name,
236    };
237    match op.entity.attribute(index) {
238        None | Some(Value::Null) => Err(GeorefError::MissingAttribute {
239            entity: op.id,
240            index,
241            name,
242        }),
243        Some(Value::Typed { type_name, value }) => {
244            let number = value.as_f64().ok_or(invalid)?;
245            let branch = match type_name.to_ascii_uppercase().as_str() {
246                "IFCLENGTHMEASURE" | "IFCPOSITIVELENGTHMEASURE" | "IFCNONNEGATIVELENGTHMEASURE" => {
247                    Some(LENGTH)
248                }
249                "IFCPLANEANGLEMEASURE" | "IFCPOSITIVEPLANEANGLEMEASURE" => Some(PLANE_ANGLE),
250                _ => None,
251            };
252            Ok((branch, number))
253        }
254        Some(value) => value.as_f64().map(|n| (None, n)).ok_or(invalid),
255    }
256}