ifc_lite_geometry/placement/
validate.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//! [`validate_chain`]: check a placement chain against a consumer's own
6//! limits without composing it. The walk is the same as [`super::resolve_chain`]
7//! (cycle-checked, uncapped); the rules a consumer adds are stated once here
8//! instead of being re-derived at each site.
9
10use super::chain::LinkKind;
11use super::chain_walk::{climb, Climb, Frame};
12use super::{missing, unsupported, Axis2Placement, PlacementError, PlacementResult};
13use ifc_lite_core::{DecodedEntity, EntityDecoder, IfcType};
14
15/// What a consumer accepts in a chain. All `false` is the strictest
16/// `IfcLocalPlacement`-only, 3D-only chain.
17#[derive(Debug, Clone, Copy, Default)]
18pub struct ChainPolicy {
19    /// Accept `IfcGridPlacement` links.
20    pub grid: bool,
21    /// Accept `IfcLinearPlacement` links.
22    pub linear: bool,
23    /// Accept an `IfcAxis2Placement2D` as `RelativePlacement`.
24    pub planar_relative: bool,
25    /// The alignment and export-preflight rule: every 3D `RelativePlacement`
26    /// has exactly 3 location coordinates, non-zero directions of exactly 3
27    /// ratios, and an Axis that is not parallel to its RefDirection.
28    pub strict_spatial: bool,
29}
30
31/// Walk `placement` up to the root and check every link against `policy`.
32/// A broken rule is [`PlacementError::Policy`], a consumer's limit rather
33/// than bad input, so it is not counted as a refused record.
34pub fn validate_chain(
35    placement: &DecodedEntity,
36    decoder: &mut EntityDecoder,
37    policy: &ChainPolicy,
38) -> PlacementResult<()> {
39    let mut climbed = Climb::new();
40    climb(&mut climbed, placement, decoder, false, false, None)?;
41    if let Some((at, found)) = climbed.stopped_at {
42        return Err(unsupported(decoder, at, found));
43    }
44    check_frames(&climbed.frames, decoder, policy)
45}
46
47pub(super) fn check_frames(
48    frames: &[Frame],
49    decoder: &mut EntityDecoder,
50    policy: &ChainPolicy,
51) -> PlacementResult<()> {
52    for frame in frames {
53        let at = frame.entity.id;
54        match frame.kind {
55            LinkKind::Local => check_relative(frame, decoder, policy)?,
56            LinkKind::Linear if policy.linear => {
57                super::linear::validate_source(&frame.entity, decoder)?
58            }
59            LinkKind::Grid if policy.grid => check_grid(frame, decoder)?,
60            LinkKind::Linear => {
61                return Err(PlacementError::Policy {
62                    at,
63                    rule: "IfcLinearPlacement is not accepted",
64                })
65            }
66            LinkKind::Grid => {
67                return Err(PlacementError::Policy {
68                    at,
69                    rule: "IfcGridPlacement is not accepted",
70                })
71            }
72        }
73    }
74    Ok(())
75}
76
77// Admission is independent of the climb's optional owner lookup: a missing
78// or wrong-type location must never become a cached validation proof (#7779).
79fn check_grid(frame: &Frame, decoder: &mut EntityDecoder) -> PlacementResult<()> {
80    let location_slot = super::grid_frame::GridPlacementLayout::of(decoder)
81        .location
82        .ok_or_else(|| missing(decoder, frame.entity.id, "PlacementLocation"))?;
83    let location = decoder
84        .resolve_optional(&frame.entity, location_slot)?
85        .ok_or_else(|| missing(decoder, frame.entity.id, "PlacementLocation"))?;
86    if location.ifc_type != IfcType::IfcVirtualGridIntersection {
87        return Err(unsupported(decoder, location.id, location.ifc_type));
88    }
89    Ok(())
90}
91
92fn check_relative(
93    frame: &Frame,
94    decoder: &mut EntityDecoder,
95    policy: &ChainPolicy,
96) -> PlacementResult<()> {
97    let at = frame.entity.id;
98    let attr = frame
99        .entity
100        .get(1)
101        .filter(|attr| !attr.is_null())
102        .ok_or_else(|| missing(decoder, at, "RelativePlacement"))?;
103    let rel = decoder
104        .resolve_ref(attr)?
105        .ok_or_else(|| missing(decoder, at, "RelativePlacement"))?;
106    match rel.ifc_type {
107        IfcType::IfcAxis2Placement3D if policy.strict_spatial => {
108            validate_spatial_frame(&rel, decoder)
109        }
110        // Readable under the leaf rule too, so a validator refuses exactly
111        // what `resolve_chain` would (malformed leaves are counted).
112        IfcType::IfcAxis2Placement3D => Axis2Placement::read_3d(&rel, decoder).map(drop),
113        IfcType::IfcAxis2Placement2D if policy.planar_relative => {
114            Axis2Placement::read_2d(&rel, decoder).map(drop)
115        }
116        IfcType::IfcAxis2Placement2D => Err(PlacementError::Policy {
117            at: rel.id,
118            rule: "IfcAxis2Placement2D is not accepted",
119        }),
120        found => Err(unsupported(decoder, rel.id, found)),
121    }
122}
123
124/// Validate an `IfcAxis2Placement3D` under the strict spatial policy.
125///
126/// Strict consumers add arity/degeneracy constraints AFTER the canonical
127/// typed leaf read. Do not bypass that read: unreadable input is refused and
128/// counted even when its attr0 happens to look like three coordinates (#7779).
129pub fn validate_spatial_frame(
130    rel: &DecodedEntity,
131    decoder: &mut EntityDecoder,
132) -> PlacementResult<()> {
133    let frame = Axis2Placement::read_3d(rel, decoder)?;
134    for slot in 0..3 {
135        if let Some(record) = decoder.resolve_optional(rel, slot)? {
136            if record.get_list(0).is_none_or(|list| list.len() != 3) {
137                return Err(PlacementError::Policy {
138                    at: rel.id,
139                    rule: "placement point or direction must have exactly 3 components",
140                });
141            }
142        }
143    }
144    let unit = |v: [f64; 3]| {
145        let v = nalgebra::Vector3::from(v);
146        let norm = v.norm();
147        if !norm.is_finite() || norm == 0.0 {
148            return Err(PlacementError::Policy {
149                at: rel.id,
150                rule: "placement direction is zero or unbounded",
151            });
152        }
153        Ok(v / norm)
154    };
155    // Defaults participate in the WR too. Explicit +X Axis with omitted
156    // RefDirection (default +X) is parallel, just like two explicit +X axes.
157    let axis = unit(frame.axis.unwrap_or(super::Z))?;
158    let reference = unit(frame.ref_direction.unwrap_or(super::X))?;
159    if axis.cross(&reference).norm() <= 1e-12 {
160        return Err(PlacementError::Policy {
161            at: rel.id,
162            rule: "Axis is parallel to RefDirection",
163        });
164    }
165    Ok(())
166}