Skip to main content

ifc_geometry/compile/
layers.rs

1//! Per-layer meshes: one mesh for each material layer of a product's Body
2//! (#455).
3
4use axiolid_contracts::ExecutionOptions;
5use axiolid_mesh_compile_contract::MeshCompiler;
6use axiolid_model::GeometryNode;
7use ifc_model::{EntityId, Model};
8
9use super::{attribute_net_refusal, refused, MeshClosure, Tolerance, TriMesh};
10use crate::error::{GeometryError, GeometryResult};
11use crate::lower::{lower_product_layers, LayerBody, LayerCut, LoweringSession};
12use crate::units;
13
14/// One layer of a split Body, meshed.
15#[derive(Debug, Clone)]
16#[non_exhaustive]
17pub struct LayerMesh {
18    /// World-space triangles in metres. Empty where the layer has no volume
19    /// in the Body (a Body that does not reach it).
20    pub mesh: TriMesh,
21    /// As [`CompiledMesh::closure`](super::CompiledMesh::closure).
22    pub closure: MeshClosure,
23}
24
25/// A product's Body split by a [`LayerCut`], one mesh per layer.
26#[derive(Debug, Clone)]
27#[non_exhaustive]
28pub struct LayerMeshes {
29    /// One entry per layer of the cut, in order; `None` for a zero-thick
30    /// layer.
31    pub parts: Vec<Option<LayerMesh>>,
32    /// The openings subtracted, in ascending id, for [`LayerBody::Net`].
33    pub openings: Vec<EntityId>,
34    /// The openings the Body already carries, taken as applied, for
35    /// [`LayerBody::Net`].
36    pub taken_as_applied: Vec<EntityId>,
37}
38
39/// Mesh each layer of a product's Body, split by `cut` (#455).
40///
41/// Uses [`default_backend`](super::default_backend);
42/// [`compile_product_layer_meshes_with`] takes your own.
43///
44/// # Errors
45///
46/// As [`compile_product_layer_meshes_with`].
47#[cfg(feature = "compile-reference-backend")]
48pub fn compile_product_layer_meshes(
49    model: &Model,
50    product: EntityId,
51    cut: &LayerCut,
52    body: LayerBody,
53    tolerance: Tolerance,
54) -> GeometryResult<Option<LayerMeshes>> {
55    compile_product_layer_meshes_with(
56        &super::default_backend(),
57        model,
58        product,
59        cut,
60        body,
61        tolerance,
62    )
63}
64
65/// Mesh each layer of a product's Body with a caller-supplied backend.
66///
67/// Each part is the Body cut by the inner boundaries of its layer, in the
68/// product's frame; the outermost layers extend, so the parts add up to the
69/// Body (see [`lower_product_layers`]). The Body is gross, or net on request.
70///
71/// # Return values
72///
73/// `Ok(None)` when the product has no Body representation.
74///
75/// # Cost
76///
77/// The success path compiles each part once; the backend's cache shares the
78/// Body across them. Only a refusal pays more: the Body is compiled alone, to
79/// tell a refusal of the Body from one of a layer.
80///
81/// # Errors
82///
83/// As [`lower_product_layers`]. A refusal the Body alone would raise is
84/// reported as the gross or net path reports it (for a net Body,
85/// [`GeometryError::OpeningNotSubtracted`]); otherwise it is
86/// [`GeometryError::LayerNotSplit`] naming the first layer refused.
87pub fn compile_product_layer_meshes_with<B: MeshCompiler>(
88    backend: &B,
89    model: &Model,
90    product: EntityId,
91    cut: &LayerCut,
92    body: LayerBody,
93    tolerance: Tolerance,
94) -> GeometryResult<Option<LayerMeshes>> {
95    let scale = units::resolve(model)?;
96    let mut session = LoweringSession::new(model, &scale);
97    let Some(layered) = lower_product_layers(&mut session, product, cut, body)? else {
98        return Ok(None);
99    };
100    let present: Vec<_> = layered.parts.iter().flatten().copied().collect();
101    let root = session.node_for(product, GeometryNode::Collection(present))?;
102    let lowered = session.finish(root)?;
103    let options = ExecutionOptions::new(tolerance);
104
105    let mut parts = Vec::with_capacity(layered.parts.len());
106    for (layer, part) in layered.parts.iter().enumerate() {
107        let Some(part) = part else {
108            parts.push(None);
109            continue;
110        };
111        match backend.compile_mesh_reported(&lowered.graph, *part, &options) {
112            Ok(outcome) => parts.push(Some(LayerMesh {
113                mesh: outcome.mesh,
114                closure: outcome.closure,
115            })),
116            Err(error) => {
117                // Is it the Body or the cut that the backend refuses?
118                let body_error = match &layered.net {
119                    Some(net) => backend
120                        .compile_mesh_reported(&lowered.graph, net.root, &options)
121                        .err()
122                        .map(|_| {
123                            attribute_net_refusal(
124                                backend,
125                                &lowered,
126                                net,
127                                &options,
128                                product,
129                                error.clone(),
130                            )
131                        }),
132                    None => backend
133                        .compile_mesh_reported(&lowered.graph, layered.body, &options)
134                        .err()
135                        .map(|body| refused(product, body, &lowered.provenance)),
136                };
137                return Err(body_error.unwrap_or_else(|| GeometryError::LayerNotSplit {
138                    product,
139                    layer,
140                    cause: Box::new(refused(product, error, &lowered.provenance)),
141                }));
142            }
143        }
144    }
145    let (openings, taken_as_applied) = layered.net.as_ref().map_or_else(
146        || (Vec::new(), Vec::new()),
147        |net| {
148            (
149                net.openings(),
150                net.taken_as_applied.iter().map(|a| a.opening).collect(),
151            )
152        },
153    );
154    Ok(Some(LayerMeshes {
155        parts,
156        openings,
157        taken_as_applied,
158    }))
159}