Skip to main content

ifc_geometry/lower/
layers.rs

1//! A product's Body split by a stack of parallel planes: one exact part per
2//! material layer (#455).
3//!
4//! # What this does and does not know
5//!
6//! The planes arrive as a neutral [`LayerCut`]: a unit normal and ascending
7//! signed distances in the product's object frame, metres. Where they come
8//! from (an `IfcMaterialLayerSetUsage`, its thicknesses, its offset) is the
9//! facade's business; this crate does not depend on `ifc-material`.
10//!
11//! # The cut, in the host's frame
12//!
13//! The Body is lowered in the host's own frame (see the `net` module, #388),
14//! where the planes are stated, split into its solid parts, and each part of
15//! layer `k` gets one exact `Difference` per inner boundary of the layer:
16//!
17//! ```text
18//! part_k = body - HalfSpace(n.x < b_k) - HalfSpace(n.x > b_(k+1))
19//! ```
20//!
21//! One `Instance` with the host's world transform sits above each part, as
22//! above the net body. Nothing is evaluated or tessellated here (ADR 0004).
23//!
24//! # Outer layers extend
25//!
26//! Only the inner boundaries cut. The first layer with thickness keeps
27//! everything of the Body below its upper plane, the last everything above its
28//! lower plane, so a Body that is thicker or thinner than its stack is never
29//! left with a remainder that belongs to no layer, and the parts add up to the
30//! Body by construction. A zero-thick layer owns no part (`None`) and no
31//! boundary of its own: the next layer with thickness extends over it.
32//!
33//! # Polarity
34//!
35//! The kernel's `HalfSpace.agreement = true` selects the NORMAL side. The
36//! tool removed below a boundary therefore has `agreement = false`, the one
37//! removed above it `true`.
38
39use axiolid_core::{BooleanOperator, Plane3, Point3, Vec3};
40use axiolid_model::{GeometryNode, NodeId, SolidOperation};
41use axiolid_primitive::HalfSpace;
42use ifc_model::EntityId;
43
44use crate::error::GeometryResult;
45use crate::lower::net::{
46    degenerate, lower_body_in_host_frame, place, solid_parts, NetLowering, NetOptions,
47};
48use crate::lower::LoweringSession;
49
50/// How close to unit length a [`LayerCut`] normal must be.
51const UNIT_TOLERANCE: f64 = 1e-9;
52
53/// A stack of parallel planes in a product's object frame.
54#[derive(Debug, Clone, PartialEq)]
55#[non_exhaustive]
56pub struct LayerCut {
57    /// Unit normal of the planes.
58    pub normal: [f64; 3],
59    /// `n + 1` signed distances along `normal` from the object origin,
60    /// metres, non-decreasing (equal where a layer is zero-thick).
61    pub boundaries: Vec<f64>,
62}
63
64impl LayerCut {
65    /// A cut of `boundaries.len() - 1` layers.
66    #[must_use]
67    pub fn new(normal: [f64; 3], boundaries: Vec<f64>) -> Self {
68        Self { normal, boundaries }
69    }
70}
71
72impl From<&crate::LayerBoundaries> for LayerCut {
73    fn from(bounds: &crate::LayerBoundaries) -> Self {
74        Self::new(bounds.normal, bounds.boundaries.clone())
75    }
76}
77
78/// Which Body is split.
79#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
80#[non_exhaustive]
81pub enum LayerBody {
82    /// The gross Body. The default, as everywhere (ADR 0014).
83    #[default]
84    Gross,
85    /// The Body with every voiding opening subtracted, on explicit request.
86    Net(NetOptions),
87}
88
89/// A Body split by a [`LayerCut`].
90#[derive(Debug, Clone, PartialEq, Eq)]
91#[non_exhaustive]
92pub struct LayeredLowering {
93    /// The Body that was split, in world space: the gross Body, or the net
94    /// root for [`LayerBody::Net`].
95    pub body: NodeId,
96    /// The net lowering behind `body`, for [`LayerBody::Net`].
97    pub net: Option<NetLowering>,
98    /// One entry per layer, in world space; `None` for a zero-thick layer.
99    pub parts: Vec<Option<NodeId>>,
100}
101
102/// Split `product`'s Body by `cut`: one exact part per layer.
103///
104/// `Ok(None)` when the product has no Body. The parts are exact nodes in the
105/// session's graph; compile them with the `compile` feature's
106/// `compile_product_layer_meshes_with`.
107///
108/// # Errors
109///
110/// [`GeometryError::Degenerate`](crate::error::GeometryError::Degenerate) naming `product` when the cut is invalid (a
111/// normal that is not finite or not of unit length, fewer than two
112/// boundaries, a boundary that is not finite or is smaller than the one
113/// before it) or no layer has thickness. A net body that falls back to world
114/// coordinates is [`GeometryError::Unsupported`](crate::error::GeometryError::Unsupported). Any error lowering the Body
115/// is returned as is, including the net refusals of `lower_product_net`.
116pub fn lower_product_layers(
117    session: &mut LoweringSession<'_>,
118    product: EntityId,
119    cut: &LayerCut,
120    body: LayerBody,
121) -> GeometryResult<Option<LayeredLowering>> {
122    let thick = validate(session, product, cut)?;
123    let net = match body {
124        LayerBody::Gross => None,
125        LayerBody::Net(options) => Some(options),
126    };
127    let Some(local) = lower_body_in_host_frame(session, product, net)? else {
128        return Ok(None);
129    };
130    let heads = solid_parts(session, local.local, product)?;
131
132    let plane = |boundary: f64| Plane3 {
133        origin: Point3::from_array(cut.normal.map(|n| n * boundary)),
134        normal: Vec3::from_array(cut.normal),
135    };
136    // One node per boundary and side, shared by every part it cuts.
137    let mut tools: Vec<[Option<NodeId>; 2]> = vec![[None; 2]; cut.boundaries.len()];
138    let mut tool = |session: &mut LoweringSession<'_>, boundary: usize, above: bool| {
139        let slot = &mut tools[boundary][usize::from(above)];
140        if let Some(node) = *slot {
141            return Ok(node);
142        }
143        let node = session.node_for(
144            product,
145            GeometryNode::HalfSpace(HalfSpace {
146                boundary: plane(cut.boundaries[boundary]),
147                agreement: above,
148            }),
149        )?;
150        *slot = Some(node);
151        GeometryResult::Ok(node)
152    };
153
154    let mut parts = vec![None; cut.boundaries.len() - 1];
155    for (position, &layer) in thick.iter().enumerate() {
156        let mut cut_heads = heads.clone();
157        // Below the layer: everything under its lower plane is removed,
158        // unless it is the first layer with thickness, which extends.
159        // Above: likewise for the last.
160        let mut sides = Vec::with_capacity(2);
161        if position > 0 {
162            sides.push((layer, false));
163        }
164        if position + 1 < thick.len() {
165            sides.push((layer + 1, true));
166        }
167        for (boundary, above) in sides {
168            let node = tool(session, boundary, above)?;
169            for head in &mut cut_heads {
170                *head = session.node_for(
171                    product,
172                    GeometryNode::SolidOperation(SolidOperation::Boolean {
173                        left: *head,
174                        right: node,
175                        operator: BooleanOperator::Difference,
176                    }),
177                )?;
178            }
179        }
180        let layer_node = match cut_heads.as_slice() {
181            [single] => *single,
182            _ => session.node_for(product, GeometryNode::Collection(cut_heads))?,
183        };
184        parts[layer] = Some(place(session, layer_node, local.to_world, product)?);
185    }
186
187    let body_node = local.net.as_ref().map_or(local.gross, |net| net.root);
188    Ok(Some(LayeredLowering {
189        body: body_node,
190        net: local.net,
191        parts,
192    }))
193}
194
195/// Check the cut and return the layers that have thickness, ascending.
196fn validate(
197    session: &LoweringSession<'_>,
198    product: EntityId,
199    cut: &LayerCut,
200) -> GeometryResult<Vec<usize>> {
201    let invalid = |detail: &str| degenerate(session, product, detail);
202    let length = cut.normal.iter().map(|n| n * n).sum::<f64>().sqrt();
203    if !cut.normal.iter().all(|n| n.is_finite()) || (length - 1.0).abs() > UNIT_TOLERANCE {
204        return Err(invalid(
205            "the layer cut's normal is not a finite unit vector",
206        ));
207    }
208    if cut.boundaries.len() < 2 {
209        return Err(invalid("a layer cut needs at least two boundaries"));
210    }
211    if !cut.boundaries.iter().all(|b| b.is_finite()) {
212        return Err(invalid("a layer cut boundary is not finite"));
213    }
214    if cut.boundaries.windows(2).any(|pair| pair[1] < pair[0]) {
215        return Err(invalid("the layer cut's boundaries are not ascending"));
216    }
217    let thick: Vec<usize> = cut
218        .boundaries
219        .windows(2)
220        .enumerate()
221        .filter(|(_, pair)| pair[1] > pair[0])
222        .map(|(index, _)| index)
223        .collect();
224    if thick.is_empty() {
225        return Err(invalid("no layer of the cut has thickness"));
226    }
227    Ok(thick)
228}