Skip to main content

ifc_geometry/rules/
solid.rs

1//! Where-rules on solids and booleans.
2//!
3//! The rules here catch the two failures that waste the most time downstream:
4//! an extrusion whose direction lies in the plane of its profile (produces a
5//! zero-volume solid), and a boolean between operands of different
6//! dimensionality (produces a kernel error with no useful location).
7
8use super::release::Subject;
9use super::{RuleViolation, ViolationKind};
10use crate::resource::direction::Direction;
11use ifc_model::{Entity, EntityId, Model, Value};
12use ifc_schema::SchemaVersion;
13
14/// Run the solid rules that apply to this entity.
15///
16/// The rules are those of the release `model` declares in `FILE_SCHEMA`,
17/// named as it names them.
18pub fn check(model: &Model, id: EntityId, entity: &Entity, out: &mut Vec<RuleViolation>) {
19    super::run_one(model, id, entity, out, run);
20}
21
22/// The solid rules for one entity in its release.
23pub(crate) fn run(s: &Subject<'_>, out: &mut Vec<RuleViolation>) {
24    advanced_brep_faces(s, out);
25    boolean_operands(s, out);
26    extruded_area_solid(s, out);
27    boolean_clipping_result(s, out);
28    polygonal_bounded_half_space(s, out);
29    revolved_area_solid(s, out);
30}
31
32/// `IfcExtrudedAreaSolid.ValidExtrusionDirection` (IFC2X3 TC1 `WR31`).
33///
34/// The schema states it as a dot product: the extrusion direction must not be
35/// perpendicular to the z axis of the position coordinate system. Equivalently
36/// the direction must not lie in the profile's plane -- sweeping a 2D profile
37/// along a direction inside its own plane sweeps out no volume. The text is
38/// the same in every bundled release.
39fn extruded_area_solid(s: &Subject<'_>, out: &mut Vec<RuleViolation>) {
40    const TYPE: &str = "IFCEXTRUDEDAREASOLID";
41    if !s.is_a(TYPE) {
42        return;
43    }
44    let (model, entity) = (s.model, s.entity);
45
46    // Slot 2 is ExtrudedDirection: SweptArea and Position are inherited and
47    // occupy slots 0 and 1. See crates/ifc-geometry/data/absolute-slots.txt.
48    let direction = entity
49        .attributes
50        .get(2)
51        .and_then(|v| v.as_ref_id())
52        .and_then(|dir_id| Some((dir_id, model.get(dir_id)?)))
53        .and_then(|(dir_id, dir)| Some((dir_id, Direction::new(dir_id, dir).ratios().ok()?)));
54    if let (Some(rule), Some((dir_id, ratios))) =
55        (s.rule(TYPE, "ValidExtrusionDirection"), direction)
56    {
57        // The profile lies in the XY plane of the position system, so the z
58        // component is the dot product with the plane normal.
59        let z = ratios.get(2).copied().unwrap_or(0.0);
60        let magnitude_sq: f64 = ratios.iter().map(|r| r * r).sum();
61        // A zero direction is the IfcDirection rule's to report.
62        if magnitude_sq > 0.0 && (z * z) / magnitude_sq < 1e-20 {
63            out.push(s.violation(
64                rule,
65                ViolationKind::Degenerate,
66                format!(
67                    "ExtrudedDirection {dir_id} lies in the profile plane; \
68                     the extrusion has zero volume"
69                ),
70            ));
71        }
72    }
73
74    // Depth must be positive: IfcPositiveLengthMeasure. A type constraint
75    // rather than an entity WHERE rule, so it is reported under the
76    // attribute's name in every release.
77    if let Some(depth) = entity
78        .attributes
79        .get(3)
80        .and_then(|v| v.unwrap_typed().as_f64())
81    {
82        if depth <= 0.0 {
83            out.push(s.violation(
84                "Depth",
85                ViolationKind::OutOfRange,
86                format!("Depth is {depth}, must be a positive length"),
87            ));
88        }
89    }
90}
91
92/// `IfcRevolvedAreaSolid.AxisStartInXY`/`AxisDirectionInXY`, and the
93/// angle.
94fn revolved_area_solid(s: &Subject<'_>, out: &mut Vec<RuleViolation>) {
95    if !s.is_a("IFCREVOLVEDAREASOLID") {
96        return;
97    }
98    revolution_axis_in_xy(s, out);
99
100    // Slot 3 is Angle; slots 0-1 inherited, slot 2 is Axis. No release
101    // states this as a WHERE rule; it is kept under its historical name.
102    if let Some(angle) = s
103        .entity
104        .attributes
105        .get(3)
106        .and_then(|v| v.unwrap_typed().as_f64())
107    {
108        if angle <= 0.0 {
109            out.push(s.violation(
110                "AngleGreaterZero",
111                ViolationKind::OutOfRange,
112                format!("Angle is {angle}, must be greater than zero"),
113            ));
114        }
115    }
116}
117
118/// The `IfcBooleanClippingResult` restrictions, per release.
119///
120/// `SameDim` is NOT checked here: it lives in `boolean_operands`, which
121/// resolves operand dimensionality through `dimension::dim_of` and so reaches
122/// curve operands too.
123///
124/// `FirstOperandType` (IFC2X3 TC1 `WR1`) differs by release:
125///
126/// - IFC2X3 TC1: `('IFC2X3.IFCSWEPTAREASOLID' IN TYPEOF(FirstOperand)) OR
127///   ('IFC2X3.IFCBOOLEANCLIPPINGRESULT' IN TYPEOF(FirstOperand))`;
128/// - IFC4 ADD2 TC1, IFC4X1, IFC4X2 and IFC4X3 ADD2 add a third disjunct,
129///   spelt `'IFC4.IFCSWEPTDISCSOLID' IN TYPEOF(FirstOperand)` (each under its
130///   own schema prefix).
131///
132/// # The `IFCSWEPTDISCSOLID` typo
133///
134/// No release declares an entity `IfcSweptDiscSolid`, so read literally the
135/// third disjunct is always FALSE and adds nothing to IFC2X3's rule. It is
136/// read here as `IfcSweptDiskSolid`, the entity it evidently names:
137/// buildingSMART tracks the spelling as a defect
138/// (buildingSMART/IFC4.x-development#927, "IfcBooleanClippingResult has
139/// spelling mistake in where rule", open) and the proposed correction
140/// (buildingSMART/IFC4.x-development#1107, open against `ifc4.4-main`)
141/// changes only the spelling, stating that it "now allows IfcSweptDiskSolid
142/// as a valid type". A literal reading would flag every IFC4 file that
143/// clips a swept disk, which the rule's authors intended to admit. IFC2X3
144/// TC1 has no such disjunct, so there a swept disk is refused.
145///
146/// `SecondOperandType` (`WR2`) and `OperatorType` (`WR3`) read the same in
147/// every bundled release.
148fn boolean_clipping_result(s: &Subject<'_>, out: &mut Vec<RuleViolation>) {
149    const TYPE: &str = "IFCBOOLEANCLIPPINGRESULT";
150    let entity = s.entity;
151    let first = entity.attributes.get(1).and_then(|v| v.as_ref_id());
152    let second = entity.attributes.get(2).and_then(|v| v.as_ref_id());
153
154    if let Some(rule) = s.rule(TYPE, "OperatorType") {
155        if let Some(Value::Enum(op)) = entity.attributes.first() {
156            if !op.eq_ignore_ascii_case("DIFFERENCE") {
157                out.push(s.violation(
158                    rule,
159                    ViolationKind::WrongType,
160                    format!("clipping must use DIFFERENCE, found {op}"),
161                ));
162            }
163        }
164    }
165    if let (Some(rule), Some(a)) = (s.rule(TYPE, "FirstOperandType"), first) {
166        if let Some(e) = s.model.get(a) {
167            let (admitted, names): (&[&str], _) = match s.release.version() {
168                SchemaVersion::Ifc2x3 => (
169                    &["IFCSWEPTAREASOLID", "IFCBOOLEANCLIPPINGRESULT"],
170                    "a swept area or nested clipping result",
171                ),
172                _ => (
173                    &[
174                        "IFCSWEPTAREASOLID",
175                        "IFCSWEPTDISKSOLID",
176                        "IFCBOOLEANCLIPPINGRESULT",
177                    ],
178                    "a swept area, swept disk or nested clipping result",
179                ),
180            };
181            if s.ref_is_none_of(a, admitted) {
182                out.push(s.violation(
183                    rule,
184                    ViolationKind::WrongType,
185                    format!(
186                        "clipping requires {names} as FirstOperand in {}, found {}",
187                        s.release.version().release_id(),
188                        e.type_name
189                    ),
190                ));
191            }
192        }
193    }
194    if let (Some(rule), Some(b)) = (s.rule(TYPE, "SecondOperandType"), second) {
195        if let Some(e) = s.model.get(b) {
196            if s.ref_is_none_of(b, &["IFCHALFSPACESOLID"]) {
197                out.push(s.violation(
198                    rule,
199                    ViolationKind::WrongType,
200                    format!(
201                        "clipping requires a half space as SecondOperand, found {}",
202                        e.type_name
203                    ),
204                ));
205            }
206        }
207    }
208}
209
210/// `IfcPolygonalBoundedHalfSpace.BoundaryType`, in the model's own release.
211///
212/// `BoundaryDim` is checked with the other dimension rules. The admitted
213/// boundary types differ by release:
214///
215/// - IFC4 ADD2 TC1: `SIZEOF(TYPEOF(PolygonalBoundary) *
216///   ['IFC4.IFCPOLYLINE', 'IFC4.IFCCOMPOSITECURVE']) = 1`; IFC2X3 TC1
217///   (`WR42`), IFC4X1 and IFC4X2 state the same two types under their own
218///   schema prefix;
219/// - IFC4X3 ADD2: `SIZEOF(TYPEOF(PolygonalBoundary) *
220///   ['IFC4X3_ADD2.IFCPOLYLINE', 'IFC4X3_ADD2.IFCCOMPOSITECURVE',
221///   'IFC4X3_ADD2.IFCINDEXEDPOLYCURVE']) = 1`.
222///
223/// `TYPEOF` carries every supertype, and the admitted types are disjoint,
224/// so the rule holds exactly when the boundary is one of them or a subtype
225/// of one (an `IfcBoundaryCurve` is an `IfcCompositeCurve`), judged in that
226/// release's own entity table.
227fn polygonal_bounded_half_space(s: &Subject<'_>, out: &mut Vec<RuleViolation>) {
228    let Some(rule) = s.rule("IFCPOLYGONALBOUNDEDHALFSPACE", "BoundaryType") else {
229        return;
230    };
231    // Slot 3 is PolygonalBoundary: BaseSurface and AgreementFlag are
232    // inherited (0, 1) and Position is slot 2.
233    let Some(boundary) = s.entity.attributes.get(3).and_then(|v| v.as_ref_id()) else {
234        return;
235    };
236    let Some(curve) = s.model.get(boundary) else {
237        return;
238    };
239    let release = s.release.version();
240    let admitted: &[&str] = match release {
241        SchemaVersion::Ifc4x3 => &["IFCPOLYLINE", "IFCCOMPOSITECURVE", "IFCINDEXEDPOLYCURVE"],
242        _ => &["IFCPOLYLINE", "IFCCOMPOSITECURVE"],
243    };
244    if s.ref_is_none_of(boundary, admitted) {
245        let names = match release {
246            SchemaVersion::Ifc4x3 => "IfcPolyline, IfcCompositeCurve or IfcIndexedPolyCurve",
247            _ => "IfcPolyline or IfcCompositeCurve",
248        };
249        let name = curve.type_name.to_ascii_uppercase();
250        out.push(s.violation(
251            rule,
252            ViolationKind::WrongType,
253            format!(
254                "PolygonalBoundary must be {names} in {}, found {name}",
255                release.release_id()
256            ),
257        ));
258    }
259}
260
261/// `HasAdvancedFaces` and `VoidsHaveAdvancedFaces`, IFC4 ADD2 TC1 on.
262///
263/// Both demand that every face of a shell be an `IfcAdvancedFace`
264/// (`'IFCADVANCEDFACE' IN TYPEOF(Afs)`); they differ only in which shells
265/// they walk. IFC2X3 TC1 has no advanced B-rep.
266fn advanced_brep_faces(s: &Subject<'_>, out: &mut Vec<RuleViolation>) {
267    // Outer is slot 0, inherited from IfcManifoldSolidBrep.
268    if let Some(rule) = s.rule("IFCADVANCEDBREP", "HasAdvancedFaces") {
269        if let Some(Value::Ref(outer)) = s.entity.attribute(0).map(|v| v.unwrap_typed()) {
270            if let Some(face) = non_advanced_faces(s, *outer).first() {
271                out.push(s.violation(
272                    rule,
273                    ViolationKind::WrongType,
274                    format!("the outer shell holds {face}, which is not an IfcAdvancedFace"),
275                ));
276            }
277        }
278    }
279
280    // Voids is slot 1 and exists only on IfcAdvancedBrepWithVoids.
281    let Some(rule) = s.rule("IFCADVANCEDBREPWITHVOIDS", "VoidsHaveAdvancedFaces") else {
282        return;
283    };
284    for void in super::dimension::list_refs(s.entity, 1) {
285        if let Some(face) = non_advanced_faces(s, void).first() {
286            out.push(s.violation(
287                rule,
288                ViolationKind::WrongType,
289                format!("void shell {void} holds {face}, which is not an IfcAdvancedFace"),
290            ));
291            return;
292        }
293    }
294}
295
296/// The faces of `shell` (`CfsFaces`, slot 0) that are not
297/// `IfcAdvancedFace`s in the release. An unresolvable face is not evidence
298/// of a non-advanced one.
299fn non_advanced_faces(s: &Subject<'_>, shell: EntityId) -> Vec<EntityId> {
300    let Some(entity) = s.model.get(shell) else {
301        return Vec::new();
302    };
303    super::dimension::list_refs(entity, 0)
304        .into_iter()
305        .filter(|face| s.model.get(*face).is_some() && !s.ref_is_a(*face, "IFCADVANCEDFACE"))
306        .collect()
307}
308
309/// The three `IfcBooleanResult` operand rules.
310///
311/// `SameDim` (IFC2X3 TC1 `WR1`) compares the operands' dimensionality. The
312/// two `*Closed` rules, IFC4 ADD2 TC1 on, apply only when an operand is an
313/// `IfcTessellatedFaceSet`: such a set may bound a solid only if it declares
314/// itself closed. IFC2X3 TC1 declares neither.
315fn boolean_operands(s: &Subject<'_>, out: &mut Vec<RuleViolation>) {
316    const TYPE: &str = "IFCBOOLEANRESULT";
317    // Operator, FirstOperand, SecondOperand.
318    let first = slot_ref(s.entity, 1);
319    let second = slot_ref(s.entity, 2);
320
321    if let (Some(rule), Some(a), Some(b)) = (s.rule(TYPE, "SameDim"), first, second) {
322        if let (Some(da), Some(db)) = (
323            super::dimension::dim_of(s.release, s.model, a),
324            super::dimension::dim_of(s.release, s.model, b),
325        ) {
326            if da != db {
327                out.push(s.violation(
328                    rule,
329                    ViolationKind::Dimensionality,
330                    format!("first operand is {da}D but second operand is {db}D"),
331                ));
332            }
333        }
334    }
335
336    for (operand, label) in [
337        (first, "FirstOperandClosed"),
338        (second, "SecondOperandClosed"),
339    ] {
340        let (Some(rule), Some(operand)) = (s.rule(TYPE, label), operand) else {
341            continue;
342        };
343        let Some(target) = s.model.get(operand) else {
344            continue;
345        };
346        // Closed sits at a different slot per subtype: after Normals on
347        // IfcTriangulatedFaceSet (and its IFC4X1-on subtype
348        // IfcTriangulatedIrregularNetwork), immediately after the inherited
349        // Coordinates on IfcPolygonalFaceSet. It is OPTIONAL, and the rule
350        // demands EXISTS(Closed) AND Closed, so an omitted flag violates
351        // exactly as a false one does.
352        let slot = if s.ref_is_a(operand, "IFCTRIANGULATEDFACESET") {
353            2
354        } else if s.ref_is_a(operand, "IFCPOLYGONALFACESET") {
355            1
356        } else {
357            // Not a tessellated face set, or a subtype whose Closed slot
358            // no bundled release fixes: nothing to read.
359            continue;
360        };
361        let closed = match target.attribute(slot).map(|v| v.unwrap_typed()) {
362            Some(Value::Bool(flag)) => Some(*flag),
363            _ => None,
364        };
365        if closed != Some(true) {
366            let detail = match closed {
367                Some(false) => "declares Closed = FALSE",
368                _ => "does not declare Closed",
369            };
370            out.push(s.violation(
371                rule,
372                ViolationKind::Disagreement,
373                format!("tessellated operand {operand} {detail}, so it cannot bound a solid"),
374            ));
375        }
376    }
377}
378
379/// The entity referenced at `slot`, unwrapping any defined-type wrapper.
380fn slot_ref(entity: &Entity, slot: usize) -> Option<EntityId> {
381    match entity.attribute(slot).map(|v| v.unwrap_typed()) {
382        Some(Value::Ref(id)) => Some(*id),
383        _ => None,
384    }
385}
386
387/// `AxisStartInXY` and `AxisDirectionInXY` (IFC2X3 TC1 `WR31`, `WR32`).
388///
389/// A revolved area solid sweeps its profile about an axis that must lie in
390/// the profile's own xy plane: the schema states this as the z component of
391/// both the axis location and its direction being zero. An axis leaving
392/// that plane would sweep the profile out of its own frame.
393///
394/// `AxisStartInXY` differs by release:
395///
396/// - IFC2X3 TC1 to IFC4X2: `Axis.Location.Coordinates[3] = 0.0`, where
397///   `Location` is typed `IfcCartesianPoint`;
398/// - IFC4X3 ADD2 types `Location` as any `IfcPoint` and states
399///   `('IFC4X3_ADD2.IFCCARTESIANPOINT' IN TYPEOF(Axis.Location)) AND
400///   (Axis.Location\IfcCartesianPoint.Coordinates[3] = 0.0)`, so a
401///   location that is not a Cartesian point violates it.
402///
403/// `AxisDirectionInXY` reads `Axis.Z.DirectionRatios[3] = 0.0` in every
404/// bundled release.
405fn revolution_axis_in_xy(s: &Subject<'_>, out: &mut Vec<RuleViolation>) {
406    const TYPE: &str = "IFCREVOLVEDAREASOLID";
407    // Axis is slot 2 and is an IfcAxis1Placement: Location, Axis.
408    let Some(Value::Ref(axis)) = s.entity.attribute(2).map(|v| v.unwrap_typed()) else {
409        return;
410    };
411    let Some(placement) = s.model.get(*axis) else {
412        return;
413    };
414
415    for (slot, label, what) in [
416        (0usize, "AxisStartInXY", "Location"),
417        (1, "AxisDirectionInXY", "Z direction"),
418    ] {
419        let Some(rule) = s.rule(TYPE, label) else {
420            continue;
421        };
422        let Some(Value::Ref(target)) = placement.attribute(slot).map(|v| v.unwrap_typed()) else {
423            continue;
424        };
425        let Some(target_entity) = s.model.get(*target) else {
426            continue;
427        };
428        if slot == 0
429            && s.release.version() == SchemaVersion::Ifc4x3
430            && s.ref_is_none_of(*target, &["IFCCARTESIANPOINT"])
431        {
432            out.push(s.violation(
433                rule,
434                ViolationKind::WrongType,
435                format!(
436                    "the revolution axis Location {target} is {}, must be an \
437                     IfcCartesianPoint in IFC4X3_ADD2",
438                    target_entity.type_name.to_ascii_uppercase()
439                ),
440            ));
441            continue;
442        }
443        // Coordinates on a point, DirectionRatios on a direction: both are
444        // the entity's only attribute, so one read serves both.
445        let Some(Value::List(values)) = target_entity.attribute(0).map(|v| v.unwrap_typed()) else {
446            continue;
447        };
448        // A 2D location or direction already lies in the plane; the rule
449        // reads index 3, which such a value does not have.
450        let Some(z) = values.get(2).and_then(|v| v.unwrap_typed().as_f64()) else {
451            continue;
452        };
453        if z != 0.0 {
454            out.push(s.violation(
455                rule,
456                ViolationKind::OutOfRange,
457                format!("the revolution axis {what} has z = {z}, which must be 0"),
458            ));
459        }
460    }
461}