Skip to main content

ifc_geometry/input/
layers.rs

1//! Where a material layer set usage measures its layers from (#455).
2//!
3//! `IfcMaterialLayerSetUsage` says how thick each layer is and how far the
4//! stack is offset, but not from what. The reference comes from the product
5//! (IFC4 ADD2 TC1, the "Material Layer Set Usage" clauses of `IfcWall`,
6//! `IfcSlab` and `IfcPlate`):
7//!
8//! - **AXIS2, walls.** Layers are measured from the wall's `Axis`
9//!   representation, a curve in the object coordinate system. The offset
10//!   moves the base line along the local y axis, positive towards +y, and a
11//!   `POSITIVE` sense then builds the layers toward +y. The extrusion may run
12//!   across the wall (perpendicular to y) or through its thickness (parallel
13//!   to y, an edited profile); an oblique one is refused. `IfcWallStandardCase`
14//!   additionally keeps the axis parallel to the local x axis, which this
15//!   module checks for every wall rather than assuming.
16//! - **AXIS3, slabs and plates.** Layers are measured from the plane of the
17//!   body extrusion's profile, along that plane's normal, which is the z axis
18//!   of the `IfcExtrudedAreaSolid.Position` frame. It does not depend on
19//!   `ExtrudedDirection`, so a roof slab extruded along a leaning direction
20//!   still has its layers parallel to the profile plane.
21//! - **AXIS1** has no use definition for any element in that release.
22//!
23//! The usage attributes `ForLayerSet`, `LayerSetDirection`, `DirectionSense`
24//! and `OffsetFromReferenceLine` exist in every release; IFC4 and IFC4X3 add
25//! `ReferenceExtent`, which only matters for fitting a body, not here.
26//! `LayerThickness` is positive in IFC2X3 and non-negative from IFC4, so a
27//! zero-thick layer is legal and yields two equal boundaries.
28//!
29//! The answer is a set of exact boundary planes, not split bodies: this crate
30//! never tessellates or executes booleans. Everything is in the product's
31//! object frame, in metres. The `Position` is optional from IFC4 (absent
32//! means identity) and a clipping chain (`IfcBooleanClippingResult`) is
33//! walked to its extrusion, because clipping trims the body without changing
34//! which plane the layers hang from. A body of several items (an interrupted
35//! wall) is accepted when they share the `Position` orientation, the profile plane and the
36//! extrusion direction.
37
38use ifc_model::{EntityId, Model};
39
40use super::material_usage::{DirectionSense, LayerSetDirection};
41use super::representation::{select_product_representation, Representation, RepresentationPurpose};
42use crate::curve::polyline::Polyline;
43use crate::error::{GeometryError, GeometryResult};
44use crate::resource::placement::axis_placement_transform;
45use crate::resource::resolve;
46use crate::solid::boolean::BooleanClippingResult;
47use crate::solid::swept::area::ExtrudedAreaSolid;
48use crate::transform::Transform;
49use crate::units::UnitScale;
50
51/// Longest clipping chain walked to the extrusion.
52const MAX_CLIPPING_DEPTH: usize = 64;
53/// Wall-axis straightness and extent tolerance, metres.
54const AXIS_TOLERANCE: f64 = 1e-6;
55/// Tolerance on unit direction components.
56const DIRECTION_TOLERANCE: f64 = 1e-9;
57const AXIS2_CLASSES: [&str; 2] = ["IFCWALL", "IFCWALLSTANDARDCASE"];
58const AXIS3_CLASSES: [&str; 4] = [
59    "IFCSLAB",
60    "IFCSLABSTANDARDCASE",
61    "IFCPLATE",
62    "IFCPLATESTANDARDCASE",
63];
64
65/// Where a material layer set usage measures its layers from, in the
66/// product's object coordinate system.
67#[derive(Debug, Clone, PartialEq)]
68#[non_exhaustive]
69pub struct LayerSetReference {
70    /// The product the reference was read from.
71    pub product: EntityId,
72    /// The usage's layer direction.
73    pub direction: LayerSetDirection,
74    /// Unit normal of every layer boundary plane, object frame: +y for AXIS2,
75    /// the extrusion `Position`'s z for AXIS3.
76    pub normal: [f64; 3],
77    /// Signed distance, metres, along `normal` from the product origin to the
78    /// reference line (AXIS2) or plane (AXIS3).
79    pub distance: f64,
80    /// The Axis `IfcPolyline` (AXIS2) or the `IfcExtrudedAreaSolid` (AXIS3)
81    /// the reference was read from.
82    pub source: EntityId,
83    product_type: String,
84}
85
86/// The boundary planes of a layer stack along a [`LayerSetReference`] normal.
87#[derive(Debug, Clone, PartialEq)]
88#[non_exhaustive]
89pub struct LayerBoundaries {
90    /// Unit normal of the planes, object frame.
91    pub normal: [f64; 3],
92    /// n + 1 signed distances along `normal`, metres, non-decreasing (equal
93    /// where a layer is zero-thick).
94    pub boundaries: Vec<f64>,
95    /// `order[k]` is the index in `IfcMaterialLayerSet.MaterialLayers` of the
96    /// layer between `boundaries[k]` and `boundaries[k + 1]`.
97    pub order: Vec<usize>,
98}
99
100fn unsupported(id: EntityId, type_name: &str, detail: &'static str) -> GeometryError {
101    GeometryError::Unsupported {
102        entity: id,
103        type_name: type_name.to_string(),
104        detail,
105    }
106}
107
108fn degenerate(id: EntityId, type_name: &str, detail: impl Into<String>) -> GeometryError {
109    GeometryError::Degenerate {
110        entity: id,
111        type_name: type_name.to_string(),
112        detail: detail.into(),
113    }
114}
115
116/// Read where the layers of `product`'s usage are measured from.
117///
118/// Only `IfcWall`/`IfcWallStandardCase` along AXIS2 and
119/// `IfcSlab`/`IfcPlate` (and their standard cases) along AXIS3 are
120/// interpreted; everything else is [`GeometryError::Unsupported`]. The body
121/// is one or several coaxial `IfcExtrudedAreaSolid` items (an interrupted
122/// wall), each optionally clipped; an item that disagrees is refused by name.
123pub fn layer_set_reference(
124    model: &Model,
125    units: &UnitScale,
126    product: EntityId,
127    direction: LayerSetDirection,
128) -> GeometryResult<LayerSetReference> {
129    let entity = model.get(product).ok_or(GeometryError::MissingEntity {
130        referrer: product,
131        missing: product,
132    })?;
133    let product_type = entity.type_name.to_string();
134    let classes: &[&str] =
135        match direction {
136            LayerSetDirection::Axis2 => &AXIS2_CLASSES,
137            LayerSetDirection::Axis3 => &AXIS3_CLASSES,
138            _ => return Err(unsupported(
139                product,
140                &product_type,
141                "LayerSetDirection AXIS1 has no use definition for any element in IFC4 ADD2 TC1; \
142                 only AXIS2 walls and AXIS3 slabs and plates are interpreted",
143            )),
144        };
145    if !classes.iter().any(|class| entity.is_type(class)) {
146        return Err(unsupported(
147            product,
148            &product_type,
149            "a material layer set usage is interpreted along AXIS2 for IfcWall and \
150             IfcWallStandardCase, and along AXIS3 for IfcSlab, IfcSlabStandardCase, IfcPlate \
151             and IfcPlateStandardCase, only",
152        ));
153    }
154
155    let body = select_product_representation(model, product, RepresentationPurpose::Body)?
156        .ok_or_else(|| GeometryError::MissingAttribute {
157            entity: product,
158            type_name: product_type.clone(),
159            attribute: "Body representation",
160        })?;
161    let (extrusion_id, local, sweep) = coaxial_frame(model, units, body, direction)?;
162
163    let (normal, distance, source) = match direction {
164        LayerSetDirection::Axis2 => {
165            let along_y = sweep[1].abs();
166            if along_y > DIRECTION_TOLERANCE && along_y < 1.0 - DIRECTION_TOLERANCE {
167                return Err(unsupported(
168                    extrusion_id,
169                    "IFCEXTRUDEDAREASOLID",
170                    "the extrusion is neither perpendicular nor parallel to the AXIS2 layer \
171                     direction (the product's local y axis), so the layers are not slabs \
172                     along it",
173                ));
174            }
175            let (distance, polyline) = wall_axis(model, units, product, &product_type)?;
176            ([0.0, 1.0, 0.0], distance, polyline)
177        }
178        _ => {
179            let normal = local.basis[2];
180            if dot(sweep, normal).abs() <= DIRECTION_TOLERANCE {
181                return Err(degenerate(
182                    extrusion_id,
183                    "IFCEXTRUDEDAREASOLID",
184                    "ExtrudedDirection lies in the profile plane",
185                ));
186            }
187            (normal, dot(normal, local.origin), extrusion_id)
188        }
189    };
190    Ok(LayerSetReference {
191        product,
192        direction,
193        normal,
194        distance,
195        source,
196        product_type,
197    })
198}
199
200/// The id of the first item, and the frame and unit sweep direction shared by
201/// every item of `body`.
202///
203/// Each item is one `IfcExtrudedAreaSolid`, through any clipping chain. An
204/// interrupted wall is several of them, each positioned along the wall; they
205/// must share the `Position` orientation and profile plane (origins may slide
206/// within it) and the extrusion direction, or the layers would not hang from
207/// one plane. The depth is not compared: the reference reads neither it nor
208/// the profile. Along AXIS2 the origins may not differ along the layer
209/// direction (the object y axis) either: pieces slide along or up the wall,
210/// not across its layers. A refusal names the body item.
211fn coaxial_frame(
212    model: &Model,
213    units: &UnitScale,
214    body: EntityId,
215    direction: LayerSetDirection,
216) -> GeometryResult<(EntityId, Transform, [f64; 3])> {
217    let representation = model.get(body).ok_or(GeometryError::MissingEntity {
218        referrer: body,
219        missing: body,
220    })?;
221    let items = Representation::new(body, representation).items()?;
222    if items.is_empty() {
223        return Err(unsupported(
224            body,
225            &representation.type_name,
226            "a layered body must hold at least one item",
227        ));
228    }
229    let mut first: Option<(EntityId, Transform, [f64; 3])> = None;
230    for item in items {
231        let (id, extrusion) = extrusion_of(model, body, item)?;
232        let local = match extrusion.base().position() {
233            Some(position) => {
234                let placement = model.get(position).ok_or(GeometryError::MissingEntity {
235                    referrer: id,
236                    missing: position,
237                })?;
238                axis_placement_transform(model, position, placement)?.to_metres(units)
239            }
240            None => Transform::identity(),
241        };
242        let sweep = resolve::direction(model, id, extrusion.extruded_direction()?)?.unit()?;
243        let sweep = normalised(local.apply_direction(sweep));
244        match &first {
245            None => first = Some((id, local, sweep)),
246            Some((_, frame, first_sweep)) => {
247                let shift = [0, 1, 2].map(|i| local.origin[i] - frame.origin[i]);
248                let across = matches!(direction, LayerSetDirection::Axis2)
249                    && shift[1].abs() > AXIS_TOLERANCE;
250                let same_frame = !across
251                    && dot(frame.basis[2], shift).abs() <= AXIS_TOLERANCE
252                    && frame
253                        .basis
254                        .iter()
255                        .zip(&local.basis)
256                        .all(|(a, b)| vectors_agree(*a, *b));
257                if !same_frame || !vectors_agree(*first_sweep, sweep) {
258                    return Err(unsupported(
259                        item,
260                        "body item",
261                        "the body items are not coaxial: this item differs in Position \
262                         orientation, profile plane, offset across the layers or \
263                         ExtrudedDirection from the first item, so the layers have no single \
264                         reference plane",
265                    ));
266                }
267            }
268        }
269    }
270    let (id, local, sweep) = first.expect("a body with items has a first");
271    Ok((id, local, sweep))
272}
273
274fn vectors_agree(a: [f64; 3], b: [f64; 3]) -> bool {
275    a.iter()
276        .zip(&b)
277        .all(|(x, y)| (x - y).abs() <= AXIS_TOLERANCE)
278}
279
280/// The extrusion of one body item, through any clipping chain.
281fn extrusion_of(
282    model: &Model,
283    body: EntityId,
284    first: EntityId,
285) -> GeometryResult<(EntityId, ExtrudedAreaSolid<'_>)> {
286    let mut id = first;
287    for _ in 0..=MAX_CLIPPING_DEPTH {
288        let item = model.get(id).ok_or(GeometryError::MissingEntity {
289            referrer: body,
290            missing: id,
291        })?;
292        if item.is_type("IFCBOOLEANCLIPPINGRESULT") {
293            let clipping = BooleanClippingResult::new(id, item);
294            clipping.checked_operator()?;
295            id = clipping.base().first_operand()?;
296        } else if item.is_type("IFCEXTRUDEDAREASOLID") {
297            return Ok((id, ExtrudedAreaSolid::new(id, item)));
298        } else {
299            return Err(unsupported(
300                id,
301                &item.type_name,
302                "a layered body must be IfcExtrudedAreaSolid items, optionally clipped by \
303                 IfcBooleanClippingResult",
304            ));
305        }
306    }
307    Err(GeometryError::ChainTooDeep {
308        entity: first,
309        kind: "boolean clipping",
310        limit: MAX_CLIPPING_DEPTH,
311    })
312}
313
314/// The y of the wall's straight Axis polyline, metres, and the polyline.
315fn wall_axis(
316    model: &Model,
317    units: &UnitScale,
318    product: EntityId,
319    product_type: &str,
320) -> GeometryResult<(f64, EntityId)> {
321    let axis = select_product_representation(model, product, RepresentationPurpose::Axis)?
322        .ok_or_else(|| GeometryError::MissingAttribute {
323            entity: product,
324            type_name: product_type.to_string(),
325            attribute: "Axis representation",
326        })?;
327    let representation = model.get(axis).ok_or(GeometryError::MissingEntity {
328        referrer: product,
329        missing: axis,
330    })?;
331    let items = Representation::new(axis, representation).items()?;
332    let [curve] = items.as_slice() else {
333        return Err(unsupported(
334            axis,
335            &representation.type_name,
336            "the Axis representation must hold exactly one curve",
337        ));
338    };
339    let entity = model.get(*curve).ok_or(GeometryError::MissingEntity {
340        referrer: axis,
341        missing: *curve,
342    })?;
343    if !entity.is_type("IFCPOLYLINE") {
344        return Err(unsupported(
345            *curve,
346            &entity.type_name,
347            "only an IfcPolyline wall axis is interpreted; trimmed, indexed and curved axes \
348             are not yet",
349        ));
350    }
351    let mut points = Vec::new();
352    for point in Polyline::new(*curve, entity).points(model)? {
353        let coordinates = point.coordinates()?;
354        let [x, y, ..] = coordinates[..] else {
355            return Err(degenerate(
356                point.id(),
357                "IFCCARTESIANPOINT",
358                "an axis point has no y coordinate",
359            ));
360        };
361        points.push([units.length(x), units.length(y)]);
362    }
363    let y0 = points[0][1];
364    if points.iter().any(|p| (p[1] - y0).abs() > AXIS_TOLERANCE) {
365        return Err(unsupported(
366            *curve,
367            "IFCPOLYLINE",
368            "the wall axis is not parallel to the product's local x axis",
369        ));
370    }
371    let (low, high) = points
372        .iter()
373        .fold((f64::MAX, f64::MIN), |(l, h), p| (l.min(p[0]), h.max(p[0])));
374    if high - low <= AXIS_TOLERANCE {
375        return Err(degenerate(
376            *curve,
377            "IFCPOLYLINE",
378            "the wall axis has no extent along the product's local x axis",
379        ));
380    }
381    Ok((y0, *curve))
382}
383
384impl LayerSetReference {
385    /// The boundary planes of a stack of layers.
386    ///
387    /// `offset` is `OffsetFromReferenceLine` and `thicknesses` the
388    /// `LayerThickness` values in set order, both in project length units.
389    /// `POSITIVE` builds from the offset reference toward +`normal`;
390    /// `NEGATIVE` toward -`normal`, and the result is reported ascending, so
391    /// `order` lists the layers last to first.
392    pub fn boundaries(
393        &self,
394        units: &UnitScale,
395        sense: DirectionSense,
396        offset: f64,
397        thicknesses: &[f64],
398    ) -> GeometryResult<LayerBoundaries> {
399        let fail = |detail: String| degenerate(self.product, &self.product_type, detail);
400        if thicknesses.is_empty() {
401            return Err(fail("a material layer set holds no layer".into()));
402        }
403        if !offset.is_finite() {
404            return Err(fail("OffsetFromReferenceLine is not finite".into()));
405        }
406        let sign = match sense {
407            DirectionSense::Positive => 1.0,
408            DirectionSense::Negative => -1.0,
409        };
410        let mut at = self.distance + units.length(offset);
411        let mut boundaries = vec![at];
412        for (i, &thickness) in thicknesses.iter().enumerate() {
413            if !thickness.is_finite() || thickness < 0.0 {
414                return Err(fail(format!(
415                    "layer thickness {i} is negative or not finite"
416                )));
417            }
418            at += sign * units.length(thickness);
419            boundaries.push(at);
420        }
421        let mut order: Vec<usize> = (0..thicknesses.len()).collect();
422        if sign < 0.0 {
423            boundaries.reverse();
424            order.reverse();
425        }
426        Ok(LayerBoundaries {
427            normal: self.normal,
428            boundaries,
429            order,
430        })
431    }
432}
433
434fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
435    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
436}
437
438fn normalised(v: [f64; 3]) -> [f64; 3] {
439    let length = dot(v, v).sqrt();
440    v.map(|c| c / length)
441}
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446
447    fn reference(distance: f64) -> LayerSetReference {
448        LayerSetReference {
449            product: EntityId(30),
450            direction: LayerSetDirection::Axis2,
451            normal: [0.0, 1.0, 0.0],
452            distance,
453            source: EntityId(40),
454            product_type: "IFCWALL".into(),
455        }
456    }
457
458    fn mm() -> UnitScale {
459        UnitScale {
460            length_to_metres: 0.001,
461            ..UnitScale::SI
462        }
463    }
464
465    fn close(actual: &[f64], expected: &[f64]) {
466        assert_eq!(actual.len(), expected.len(), "{actual:?}");
467        for (a, e) in actual.iter().zip(expected) {
468            assert!((a - e).abs() < 1e-12, "{actual:?} != {expected:?}");
469        }
470    }
471
472    const CAVITY: [f64; 4] = [115.0, 100.0, 40.0, 115.0];
473
474    #[test]
475    fn a_positive_stack_builds_from_the_offset_toward_the_normal() {
476        let b = reference(0.0)
477            .boundaries(&mm(), DirectionSense::Positive, -185.0, &CAVITY)
478            .expect("bounds");
479        close(&b.boundaries, &[-0.185, -0.07, 0.03, 0.07, 0.185]);
480        assert_eq!(b.order, [0, 1, 2, 3]);
481        assert_eq!(b.normal, [0.0, 1.0, 0.0]);
482    }
483
484    #[test]
485    fn a_negative_stack_builds_against_the_normal_and_lists_layers_reversed() {
486        let b = reference(0.0)
487            .boundaries(&mm(), DirectionSense::Negative, 185.0, &CAVITY)
488            .expect("bounds");
489        close(&b.boundaries, &[-0.185, -0.07, -0.03, 0.07, 0.185]);
490        assert_eq!(b.order, [3, 2, 1, 0]);
491    }
492
493    #[test]
494    fn the_reference_distance_shifts_every_boundary() {
495        let b = reference(0.1)
496            .boundaries(&mm(), DirectionSense::Positive, 0.0, &[200.0])
497            .expect("bounds");
498        close(&b.boundaries, &[0.1, 0.3]);
499    }
500
501    #[test]
502    fn a_zero_thick_layer_repeats_a_boundary() {
503        let b = reference(0.0)
504            .boundaries(&mm(), DirectionSense::Positive, 0.0, &[100.0, 0.0, 50.0])
505            .expect("bounds");
506        close(&b.boundaries, &[0.0, 0.1, 0.1, 0.15]);
507    }
508
509    #[test]
510    fn unusable_inputs_are_degenerate() {
511        let r = reference(0.0);
512        let cases: [(f64, &[f64]); 5] = [
513            (0.0, &[]),
514            (f64::NAN, &[1.0]),
515            (0.0, &[-1.0]),
516            (0.0, &[f64::NAN]),
517            (0.0, &[f64::INFINITY]),
518        ];
519        for (offset, thicknesses) in cases {
520            let err = r
521                .boundaries(&mm(), DirectionSense::Positive, offset, thicknesses)
522                .expect_err("refused");
523            assert!(
524                matches!(&err, GeometryError::Degenerate { entity, type_name, .. }
525                    if *entity == EntityId(30) && type_name == "IFCWALL"),
526                "{err:?}"
527            );
528        }
529    }
530}