ifc_lite_geometry/placement/
mod.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//! The one home for placement frames and the `ObjectPlacement` chain (F3b).
6//!
7//! - [`Axis2Placement`] / [`Axis1Placement`]: the attributes of an
8//!   `IfcAxis2Placement3D` / `IfcAxis1Placement`, read once.
9//! - [`build_axis2_matrix`]: the only orthonormalisation of a frame.
10//! - [`resolve_chain`] / [`resolve_object_placement`]: the world transform of
11//!   a placement, walked iteratively up `PlacementRelTo` with a visited set
12//!   and no depth cap (D27), memoised on the decoder.
13//! - [`chain`] / [`validate_chain`]: the same walk without transforms, for
14//!   consumers that check a chain against their own rules.
15//!
16//! Results are **unscaled** (file units, the memo's unit); the caller scales.
17
18mod chain;
19mod chain_walk;
20mod grid;
21mod grid_frame;
22mod heading;
23pub(crate) mod linear;
24mod validate;
25mod validated_chain;
26#[cfg(test)]
27mod validated_chain_tests;
28
29#[cfg(test)]
30mod axis_frame_tests;
31#[cfg(test)]
32mod chain_policy_tests;
33#[cfg(test)]
34mod chain_tests;
35#[cfg(test)]
36mod grid_tests;
37#[cfg(test)]
38mod linear_tests;
39#[cfg(test)]
40mod leaf_policy_tests;
41#[cfg(test)]
42mod mod_tests;
43
44pub use chain::{chain, resolve_chain, resolve_chain_relative, resolve_object_placement, Link, LinkKind};
45pub use heading::rotation_angle_about_z;
46pub use validate::{validate_chain, validate_spatial_frame, ChainPolicy};
47pub use validated_chain::ChainValidator;
48
49use crate::math::tol;
50use crate::axis_projection::perpendicular_x_axis;
51use ifc_lite_core::{slot, DecodedEntity, EntityDecoder, IfcType};
52use nalgebra::{Matrix4, Point3, Vector3};
53
54/// Why a placement could not be resolved.
55#[derive(Debug, thiserror::Error)]
56#[non_exhaustive]
57pub enum PlacementError {
58    /// `PlacementRelTo` loops back on itself; `at` is the repeated placement.
59    #[error("placement chain is cyclic at #{at}")]
60    Cyclic { at: u32 },
61    /// A record of the wrong type in a placement slot.
62    #[error("#{at}: unsupported placement record {found}")]
63    Unsupported { at: u32, found: IfcType },
64    /// A mandatory attribute (`$` or absent) is missing.
65    #[error("#{at}: missing {attr}")]
66    Missing { at: u32, attr: &'static str },
67    /// [`validate_chain`] only: the chain breaks the caller's [`ChainPolicy`].
68    /// A consumer's limit, not bad input.
69    #[error("#{at}: {rule}")]
70    Policy { at: u32, rule: &'static str },
71    /// A source execution cancellation or resource refusal, never bad geometry.
72    #[error(transparent)]
73    ProgramStopped(#[from] crate::resource::ProgramStop),
74    /// A dangling id or a core decode refusal.
75    #[error(transparent)]
76    Decode(#[from] ifc_lite_core::Error),
77}
78
79impl From<PlacementError> for crate::Error {
80    fn from(error: PlacementError) -> Self {
81        match error {
82            PlacementError::Decode(core) => Self::CoreError(core),
83            PlacementError::ProgramStopped(stop) => Self::ProgramStopped(stop),
84            other => Self::GeometryError(other.to_string()),
85        }
86    }
87}
88
89impl PlacementError {
90    /// The refusals D15/D30 drop rather than keep at a fallback position:
91    /// input admission refused a real (`UnrepresentableReal`), a point or
92    /// direction is malformed (`MalformedRecord`), or a mandatory attribute is
93    /// missing. A dangling id, a wrong record type and a cycle are not.
94    pub fn is_admission_refusal(&self) -> bool {
95        matches!(
96            self,
97            Self::Missing { .. }
98                | Self::Decode(
99                    ifc_lite_core::Error::UnrepresentableReal(_)
100                        | ifc_lite_core::Error::MalformedRecord(_)
101                )
102        )
103    }
104}
105
106/// `Result` of the placement readers.
107pub type PlacementResult<T> = std::result::Result<T, PlacementError>;
108
109const Z: [f64; 3] = [0.0, 0.0, 1.0];
110const X: [f64; 3] = [1.0, 0.0, 0.0];
111
112/// The attributes of an `IfcAxis2Placement3D` or `IfcAxis2Placement2D`: raw
113/// `Axis` and `RefDirection` ratios (`None` when `$`), orthonormalised only by
114/// [`Self::matrix`].
115///
116/// Points and directions are read under the one leaf rule of
117/// `EntityDecoder::{point3, direction3}` (D26): 2 or 3 finite numbers, a 2D
118/// value promotes to z = 0, anything else is refused and counted (D3).
119#[derive(Debug, Clone, Copy, PartialEq)]
120pub struct Axis2Placement {
121    pub location: [f64; 3],
122    pub axis: Option<[f64; 3]>,
123    pub ref_direction: Option<[f64; 3]>,
124    /// Read from an `IfcAxis2Placement2D`: `axis` is +Z, `location` has z = 0.
125    pub planar: bool,
126}
127
128impl Axis2Placement {
129    /// Read the attribute layout of an `IfcAxis2Placement3D`: Location (0),
130    /// Axis (1), RefDirection (2). A wrong record type is refused and counted.
131    pub fn read_3d(placement: &DecodedEntity, decoder: &mut EntityDecoder) -> PlacementResult<Self> {
132        if placement.ifc_type != IfcType::IfcAxis2Placement3D {
133            return Err(unsupported(decoder, placement.id, placement.ifc_type.clone()));
134        }
135        Ok(Self {
136            location: location(placement, decoder)?,
137            axis: decoder.direction3_at(placement, slot::IfcAxis2Placement3D::AXIS.index())?,
138            ref_direction: decoder.direction3_at(placement, slot::IfcAxis2Placement3D::REF_DIRECTION.index())?,
139            planar: false,
140        })
141    }
142
143    /// Read the attribute layout of an `IfcAxis2Placement2D`: Location (0),
144    /// RefDirection (1). The Axis is +Z, so [`Self::matrix`] is the XY frame
145    /// of [`build_axis2_matrix`]. A wrong record type is refused and counted.
146    pub fn read_2d(placement: &DecodedEntity, decoder: &mut EntityDecoder) -> PlacementResult<Self> {
147        if placement.ifc_type != IfcType::IfcAxis2Placement2D {
148            return Err(unsupported(decoder, placement.id, placement.ifc_type.clone()));
149        }
150        Ok(Self {
151            location: location(placement, decoder)?,
152            axis: Some(Z),
153            ref_direction: decoder.direction3_at(placement, slot::IfcAxis2Placement2D::REF_DIRECTION.index())?,
154            planar: true,
155        })
156    }
157
158    /// [`Self::read_3d`] or [`Self::read_2d`] by the record's type; any other
159    /// type is [`PlacementError::Unsupported`].
160    pub fn read(placement: &DecodedEntity, decoder: &mut EntityDecoder) -> PlacementResult<Self> {
161        match &placement.ifc_type {
162            IfcType::IfcAxis2Placement3D => Self::read_3d(placement, decoder),
163            IfcType::IfcAxis2Placement2D => Self::read_2d(placement, decoder),
164            found => Err(unsupported(decoder, placement.id, found.clone())),
165        }
166    }
167
168    /// Decode `id`, then [`Self::read`].
169    pub fn read_id(id: u32, decoder: &mut EntityDecoder) -> PlacementResult<Self> {
170        let placement = decoder.decode_by_id(id)?;
171        Self::read(&placement, decoder)
172    }
173
174    /// The local-to-parent frame: [`build_axis2_matrix`] with the IFC defaults
175    /// (+Z, +X) for an absent Axis or RefDirection.
176    pub fn matrix(&self) -> Matrix4<f64> {
177        build_axis2_matrix(
178            Point3::from(self.location),
179            Vector3::from(self.axis.unwrap_or(Z)),
180            Vector3::from(self.ref_direction.unwrap_or(X)),
181        )
182    }
183}
184
185/// The attributes of an `IfcAxis1Placement`: Location (0), Axis (1).
186#[derive(Debug, Clone, Copy, PartialEq)]
187pub struct Axis1Placement {
188    pub location: [f64; 3],
189    pub axis: Option<[f64; 3]>,
190}
191
192impl Axis1Placement {
193    pub fn read(placement: &DecodedEntity, decoder: &mut EntityDecoder) -> PlacementResult<Self> {
194        if placement.ifc_type != IfcType::IfcAxis1Placement {
195            return Err(unsupported(decoder, placement.id, placement.ifc_type.clone()));
196        }
197        Ok(Self { location: location(placement, decoder)?, axis: decoder.direction3_at(placement, slot::IfcAxis1Placement::AXIS.index())? })
198    }
199
200    /// The Axis, or the IFC derived default +Z. A consumer whose WR rules the
201    /// default out refuses on `axis == None` itself.
202    pub fn axis_or_ifc_default(&self) -> [f64; 3] {
203        self.axis.unwrap_or(Z)
204    }
205}
206
207/// The mandatory Location (attribute 0) under the leaf rule.
208fn location(placement: &DecodedEntity, decoder: &mut EntityDecoder) -> PlacementResult<[f64; 3]> {
209    decoder
210        .point3_at(placement, slot::IfcPlacement::LOCATION.index())?
211        .ok_or_else(|| missing(decoder, placement.id, "Location"))
212}
213
214/// A refused mandatory attribute (`$` or absent), counted once per record
215/// (D3, D30). Everything that refuses a placement goes through here or
216/// [`unsupported`], so the counter and the error cannot drift apart.
217pub(super) fn missing(decoder: &EntityDecoder, at: u32, attr: &'static str) -> PlacementError {
218    let _counted = decoder.refuse_malformed(at);
219    PlacementError::Missing { at, attr }
220}
221
222/// A refused record of the wrong type in a placement slot, counted (D30).
223pub(super) fn unsupported(decoder: &EntityDecoder, at: u32, found: IfcType) -> PlacementError {
224    let _counted = decoder.refuse_malformed(at);
225    PlacementError::Unsupported { at, found }
226}
227
228/// Sampling may fail to produce a frame, but execution stops retain their
229/// resource/source authority and must not be counted as malformed input.
230fn sampled<T>(result: crate::Result<T>) -> PlacementResult<Option<T>> {
231    crate::resource::check_current()?;
232    match result {
233        Ok(value) => Ok(Some(value)),
234        Err(crate::Error::ProgramStopped(stop)) => Err(PlacementError::ProgramStopped(stop)),
235        Err(crate::Error::CoreError(error)) => Err(PlacementError::Decode(error)),
236        Err(_) => Ok(None), // Unsupported/unusable curves are refused by the frame caller.
237    }
238}
239
240/// Orthonormalize a placement's raw axes + location into a column-major 4×4
241/// transform (columns = world-space local X, Y, Z, then translation).
242///
243/// `z_axis` is the raw Axis (local +Z), `x_axis` the raw RefDirection (local
244/// +X); both are normalized here. This is the only orthonormalisation of a
245/// frame in the crate and the single home for the degenerate-axis fallback:
246/// when RefDirection is parallel to Axis the projected X collapses, so instead
247/// of normalizing a zero vector (a NaN matrix) a deterministic perpendicular
248/// direction is picked. The math is the canonical Gram–Schmidt (normalize Z,
249/// project RefDirection onto the plane ⟂ Z, then Y = Z × X).
250pub(crate) fn build_axis2_matrix(
251    location: Point3<f64>,
252    z_axis: Vector3<f64>,
253    x_axis: Vector3<f64>,
254) -> Matrix4<f64> {
255    // A malformed IfcDirection((0,0,0)) as Axis/RefDirection would make a bare
256    // normalize() emit NaN (0/0) and poison the whole placement matrix. A zero
257    // Axis falls back to +Z; a zero RefDirection routes into the
258    // parallel-axis fallback below.
259    let z_axis_final = z_axis
260        .try_normalize(tol::AXIS_MIN_LEN)
261        .unwrap_or_else(|| Vector3::new(0.0, 0.0, 1.0));
262    let x_axis_normalized = x_axis
263        .try_normalize(tol::AXIS_MIN_LEN)
264        .unwrap_or_else(|| Vector3::new(1.0, 0.0, 0.0));
265
266    let x_axis_final = perpendicular_x_axis(z_axis_final, x_axis_normalized);
267
268    // Y axis is cross product of Z and X (right-hand rule: Y = Z × X)
269    let y_axis = z_axis_final.cross(&x_axis_final).normalize();
270
271    // Columns represent world-space directions of local axes
272    let mut transform = Matrix4::identity();
273    transform[(0, 0)] = x_axis_final.x;
274    transform[(1, 0)] = x_axis_final.y;
275    transform[(2, 0)] = x_axis_final.z;
276    transform[(0, 1)] = y_axis.x;
277    transform[(1, 1)] = y_axis.y;
278    transform[(2, 1)] = y_axis.z;
279    transform[(0, 2)] = z_axis_final.x;
280    transform[(1, 2)] = z_axis_final.y;
281    transform[(2, 2)] = z_axis_final.z;
282    transform[(0, 3)] = location.x;
283    transform[(1, 3)] = location.y;
284    transform[(2, 3)] = location.z;
285
286    transform
287}