Skip to main content

ifc_geometry/rules/
placement.rs

1//! Where-rules on placements and directions.
2//!
3//! These are the rules whose violation produces the most confusing downstream
4//! symptoms: geometry that renders in the wrong orientation, or a transform
5//! that silently shears because two axes were not independent.
6
7use super::release::Subject;
8use super::{RuleViolation, ViolationKind};
9use crate::resource::{direction::Direction, point::CartesianPoint};
10use ifc_model::{Entity, EntityId, Model, Value};
11
12/// Run the placement rules that apply to this entity.
13///
14/// The rules are those of the release `model` declares in `FILE_SCHEMA`,
15/// named as it names them.
16pub fn check(model: &Model, id: EntityId, entity: &Entity, out: &mut Vec<RuleViolation>) {
17    super::run_one(model, id, entity, out, run);
18}
19
20/// The placement rules for one entity in its release.
21pub(crate) fn run(s: &Subject<'_>, out: &mut Vec<RuleViolation>) {
22    axis2_placement_3d(s, out);
23    axis2_placement_2d(s, out);
24    axis1_placement(s, out);
25    location_is_cartesian(s, out);
26    direction(s, out);
27    correct_local_placement(s, out);
28}
29
30/// `IfcAxis2Placement3D` (IFC2X3 TC1 `WR1`-`WR5`).
31///
32/// - `LocationIs3D`     - the location must be a 3D point
33/// - `AxisIs3D`         - Axis, if present, is 3D
34/// - `RefDirIs3D`       - RefDirection, if present, is 3D
35/// - `AxisToRefDirPosition` - they must not be parallel
36/// - `AxisAndRefDirProvision` - both or neither, never one
37///
38/// The text is the same in every bundled release; IFC4X3 ADD2 adds
39/// `LocationIsCP`, checked in [`location_is_cartesian`].
40fn axis2_placement_3d(s: &Subject<'_>, out: &mut Vec<RuleViolation>) {
41    const TYPE: &str = "IFCAXIS2PLACEMENT3D";
42    let model = s.model;
43    let attrs = &s.entity.attributes;
44
45    if let Some(rule) = s.rule(TYPE, "LocationIs3D") {
46        if let Some(loc) = attrs.first().and_then(|v| v.as_ref_id()) {
47            if let Some(dim) = point_dim(model, loc) {
48                if dim != 3 {
49                    out.push(s.violation(
50                        rule,
51                        ViolationKind::Dimensionality,
52                        format!("Location {loc} is {dim}D, must be 3D"),
53                    ));
54                }
55            }
56        }
57    }
58
59    let axis = attrs.get(1).and_then(|v| v.as_ref_id());
60    let ref_dir = attrs.get(2).and_then(|v| v.as_ref_id());
61
62    for (slot, label) in [(axis, "AxisIs3D"), (ref_dir, "RefDirIs3D")] {
63        let (Some(rule), Some(dir_id)) = (s.rule(TYPE, label), slot) else {
64            continue;
65        };
66        if let Some(dim) = direction_dim(model, dir_id) {
67            if dim != 3 {
68                out.push(s.violation(
69                    rule,
70                    ViolationKind::Dimensionality,
71                    format!("{dir_id} is {dim}D, must be 3D"),
72                ));
73            }
74        }
75    }
76
77    // AxisAndRefDirProvision: NOT (EXISTS(Axis) XOR EXISTS(RefDirection)).
78    // One without the other is under-determined: the schema requires both or
79    // neither, defaulting to the global axes when absent.
80    if let Some(rule) = s.rule(TYPE, "AxisAndRefDirProvision") {
81        if axis.is_some() != ref_dir.is_some() {
82            out.push(s.violation(
83                rule,
84                ViolationKind::Disagreement,
85                "Axis and RefDirection must both be present or both absent",
86            ));
87        }
88    }
89
90    // AxisToRefDirPosition: the cross product must be non-zero, i.e. the two
91    // directions must not be parallel. This is the rule that silently produces
92    // a degenerate basis when ignored.
93    if let (Some(rule), Some(a), Some(r)) = (s.rule(TYPE, "AxisToRefDirPosition"), axis, ref_dir) {
94        if cross_product_vanishes(model, a, r) {
95            out.push(s.violation(
96                rule,
97                ViolationKind::Degenerate,
98                format!("Axis {a} is parallel to RefDirection {r}; the basis is degenerate"),
99            ));
100        }
101    }
102}
103
104/// `IfcAxis2Placement2D`: location and RefDirection must be 2D
105/// (`LocationIs2D`, `RefDirIs2D`; IFC2X3 TC1 `WR2`, `WR1`).
106fn axis2_placement_2d(s: &Subject<'_>, out: &mut Vec<RuleViolation>) {
107    const TYPE: &str = "IFCAXIS2PLACEMENT2D";
108    if let Some(rule) = s.rule(TYPE, "LocationIs2D") {
109        if let Some(loc) = s.entity.attributes.first().and_then(|v| v.as_ref_id()) {
110            if let Some(dim) = point_dim(s.model, loc) {
111                if dim != 2 {
112                    out.push(s.violation(
113                        rule,
114                        ViolationKind::Dimensionality,
115                        format!("Location {loc} is {dim}D, must be 2D"),
116                    ));
117                }
118            }
119        }
120    }
121    if let Some(rule) = s.rule(TYPE, "RefDirIs2D") {
122        if let Some(rd) = s.entity.attributes.get(1).and_then(|v| v.as_ref_id()) {
123            if let Some(dim) = direction_dim(s.model, rd) {
124                if dim != 2 {
125                    out.push(s.violation(
126                        rule,
127                        ViolationKind::Dimensionality,
128                        format!("RefDirection {rd} is {dim}D, must be 2D"),
129                    ));
130                }
131            }
132        }
133    }
134}
135
136/// `IfcAxis1Placement`: `LocationIs3D` and `AxisIs3D` (IFC2X3 TC1 `WR2`,
137/// `WR1`).
138fn axis1_placement(s: &Subject<'_>, out: &mut Vec<RuleViolation>) {
139    const TYPE: &str = "IFCAXIS1PLACEMENT";
140    if let Some(rule) = s.rule(TYPE, "LocationIs3D") {
141        if let Some(loc) = s.entity.attributes.first().and_then(|v| v.as_ref_id()) {
142            if let Some(dim) = point_dim(s.model, loc) {
143                if dim != 3 {
144                    out.push(s.violation(
145                        rule,
146                        ViolationKind::Dimensionality,
147                        format!("Location {loc} is {dim}D, must be 3D"),
148                    ));
149                }
150            }
151        }
152    }
153    if let Some(rule) = s.rule(TYPE, "AxisIs3D") {
154        if let Some(axis) = s.entity.attributes.get(1).and_then(|v| v.as_ref_id()) {
155            if let Some(dim) = direction_dim(s.model, axis) {
156                if dim != 3 {
157                    out.push(s.violation(
158                        rule,
159                        ViolationKind::Dimensionality,
160                        format!("Axis {axis} is {dim}D, must be 3D"),
161                    ));
162                }
163            }
164        }
165    }
166}
167
168/// `LocationIsCP` on the three axis placements, IFC4X3 ADD2 only.
169///
170/// IFC4X3 ADD2 widens `IfcPlacement.Location` from `IfcCartesianPoint` to
171/// `IfcPoint` and restores the old restriction on these three with
172/// `LocationIsCP : 'IFC4X3_ADD2.IFCCARTESIANPOINT' IN
173/// TYPEOF(SELF\IfcPlacement.Location)`. Earlier releases type `Location`
174/// as `IfcCartesianPoint` and declare no such rule.
175fn location_is_cartesian(s: &Subject<'_>, out: &mut Vec<RuleViolation>) {
176    let rule = [
177        "IFCAXIS1PLACEMENT",
178        "IFCAXIS2PLACEMENT2D",
179        "IFCAXIS2PLACEMENT3D",
180    ]
181    .into_iter()
182    .find_map(|declared_on| s.rule(declared_on, "LocationIsCP"));
183    let Some(rule) = rule else {
184        return;
185    };
186    // Location is slot 0, inherited from IfcPlacement.
187    let Some(Value::Ref(location)) = s.entity.attribute(0).map(|v| v.unwrap_typed()) else {
188        return;
189    };
190    let Some(point) = s.model.get(*location) else {
191        return;
192    };
193    if s.ref_is_none_of(*location, &["IFCCARTESIANPOINT"]) {
194        out.push(s.violation(
195            rule,
196            ViolationKind::WrongType,
197            format!(
198                "Location {location} is {}, must be an IfcCartesianPoint",
199                point.type_name.to_ascii_uppercase()
200            ),
201        ));
202    }
203}
204
205/// `IfcDirection.MagnitudeGreaterZero`, IFC4 ADD2 TC1 on.
206///
207/// A zero-length direction has no orientation; every normalisation downstream
208/// divides by zero. IFC2X3 TC1 declares no rule on `IfcDirection`, so an
209/// IFC2X3 file is not checked for it.
210fn direction(s: &Subject<'_>, out: &mut Vec<RuleViolation>) {
211    let Some(rule) = s.rule("IFCDIRECTION", "MagnitudeGreaterZero") else {
212        return;
213    };
214    let view = Direction::new(s.id, s.entity);
215    if let Ok(ratios) = view.ratios() {
216        let magnitude_sq: f64 = ratios.iter().map(|r| r * r).sum();
217        if magnitude_sq <= 0.0 {
218            out.push(s.violation(
219                rule,
220                ViolationKind::Degenerate,
221                "all direction ratios are zero",
222            ));
223        }
224    }
225}
226
227/// `IfcLocalPlacement.WR21`, via `IfcCorrectLocalPlacement`.
228///
229/// The rule and its function test the same three types in every bundled
230/// release (IFC4 on qualify `RelPlacement\IfcLocalPlacement`, which changes
231/// nothing for a local placement).
232///
233/// # The function is genuinely three-valued
234///
235/// It returns UNKNOWN (`?`) for a grid placement and for any case it
236/// does not recognise, and EXPRESS treats an UNKNOWN where-rule as
237/// satisfied. Only the one explicit FALSE branch is a violation: a 3D
238/// relative placement hung off a parent whose own placement is 2D.
239/// Reporting the UNKNOWN cases would flag every valid grid placement.
240fn correct_local_placement(s: &Subject<'_>, out: &mut Vec<RuleViolation>) {
241    let Some(rule) = s.rule("IFCLOCALPLACEMENT", "WR21") else {
242        return;
243    };
244    let (model, entity) = (s.model, s.entity);
245    // PlacementRelTo is slot 0, RelativePlacement slot 1.
246    let Some(Value::Ref(rel_to)) = entity.attribute(0).map(|v| v.unwrap_typed()) else {
247        // No parent: the function returns TRUE.
248        return;
249    };
250    let Some(Value::Ref(axis)) = entity.attribute(1).map(|v| v.unwrap_typed()) else {
251        return;
252    };
253    let Some(parent) = model.get(*rel_to) else {
254        return;
255    };
256    // Only IfcLocalPlacement parents reach a decidable branch.
257    if !s.ref_is_a(*rel_to, "IFCLOCALPLACEMENT") {
258        return;
259    }
260    // A 2D axis placement returns TRUE regardless of the parent.
261    if !s.ref_is_a(*axis, "IFCAXIS2PLACEMENT3D") {
262        return;
263    }
264    // The FALSE branch: parent RelativePlacement.Dim must be 3.
265    let Some(Value::Ref(parent_axis)) = parent.attribute(1).map(|v| v.unwrap_typed()) else {
266        return;
267    };
268    let Some(dim) = super::dimension::dim_of(s.release, model, *parent_axis) else {
269        return;
270    };
271    if dim != 3 {
272        out.push(s.violation(
273            rule,
274            ViolationKind::Dimensionality,
275            format!(
276                "a 3D RelativePlacement hangs off {rel_to}, whose own \
277                 placement is {dim}D"
278            ),
279        ));
280    }
281}
282
283/// Dimensionality of a referenced `IfcCartesianPoint`.
284fn point_dim(model: &Model, id: EntityId) -> Option<usize> {
285    let entity = model.get(id)?;
286    CartesianPoint::new(id, entity)
287        .coordinates()
288        .ok()
289        .map(|c| c.len())
290}
291
292/// Dimensionality of a referenced `IfcDirection`.
293fn direction_dim(model: &Model, id: EntityId) -> Option<usize> {
294    direction_ratios(model, id).map(|r| r.len())
295}
296
297/// Ratios of a referenced `IfcDirection`.
298fn direction_ratios(model: &Model, id: EntityId) -> Option<Vec<f64>> {
299    let entity = model.get(id)?;
300    Direction::new(id, entity).ratios().ok()
301}
302
303/// `IfcCrossProduct(a, b).Magnitude > 0.0` is FALSE for two referenced
304/// directions: both resolve, both are 3D, and they are parallel.
305///
306/// `IfcCrossProduct` returns `?` for a 2D argument, which makes the rule
307/// UNKNOWN, so only 3D pairs are judged. Shared by
308/// `IfcAxis2Placement3D.AxisToRefDirPosition` and
309/// `IfcAxis2PlacementLinear.WR2`, whose texts are the same.
310pub(super) fn cross_product_vanishes(model: &Model, a: EntityId, b: EntityId) -> bool {
311    match (direction_ratios(model, a), direction_ratios(model, b)) {
312        (Some(av), Some(bv)) => is_parallel(&av, &bv),
313        _ => false,
314    }
315}
316
317/// Are two vectors parallel (cross product effectively zero)?
318///
319/// Compares against a relative tolerance rather than an absolute one: an
320/// absolute epsilon misjudges both millimetre-scale and kilometre-scale
321/// models, and IFC files legitimately contain both.
322fn is_parallel(a: &[f64], b: &[f64]) -> bool {
323    if a.len() < 3 || b.len() < 3 {
324        return false;
325    }
326    let cross = [
327        a[1] * b[2] - a[2] * b[1],
328        a[2] * b[0] - a[0] * b[2],
329        a[0] * b[1] - a[1] * b[0],
330    ];
331    let cross_sq: f64 = cross.iter().map(|c| c * c).sum();
332    let scale = (a.iter().map(|x| x * x).sum::<f64>()) * (b.iter().map(|x| x * x).sum::<f64>());
333    if scale <= 0.0 {
334        return false;
335    }
336    // sin^2(theta) below 1e-20 means the directions are parallel to any
337    // precision a downstream kernel could exploit.
338    cross_sq / scale < 1e-20
339}