ifc_lite_geometry_runtime/
worker_dependencies.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Retained Boolean operands in one common object-local metre frame. Each
3//! result owns its solid through its own managed lease, independently of the
4//! receipts it was built from.
5use super::{
6    rigid, AffineCertificate, BrepHandle, MeshLimits, NumericalOutcome, RetainedAffineCopy,
7    RetainedRealization, SmlibWorker, TessellatedMesh, WorkerError,
8};
9use crate::protocol::BooleanOperation;
10use ifc_lite_geometry::document::RetainedRequest;
11use ifc_lite_geometry::math::mat4::compose_frame;
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::sync::Arc;
14
15/// Deepest admitted chain of retained Boolean and affine-copy operations.
16pub(super) const MAX_OPERATIONS: usize = 128;
17
18/// A sealed numerical operand. A raw handle cannot manufacture one.
19pub enum RetainedDependency<'a> {
20    /// A realization placed by `world_from_source`: column-major, raw
21    /// solid-local file units -> world metres. Composed with the request's
22    /// frame it must be a proper rigid metre motion.
23    Source {
24        realization: &'a RetainedRealization,
25        world_from_source: [f64; 16],
26    },
27    /// An earlier result, in its own unchanged world frame.
28    Result(&'a RetainedDependencyResult),
29    /// Reuse an earlier result at this explicit proper-rigid placement. Replaces
30    /// the evaluation-to-world frame; does not compose another occurrence twice.
31    #[cfg(feature = "retained-runtime")]
32    PlacedResult { result: &'a RetainedDependencyResult, world_from_result: [f64; 16] },
33    /// A baked affine copy placed by an explicit proper rigid
34    /// `world_from_affine` (column-major, copy metres -> world metres). Never
35    /// inferred from authored units or a relative-to-centre origin.
36    Affine {
37        copy: &'a RetainedAffineCopy,
38        world_from_affine: [f64; 16],
39    },
40}
41
42/// The evaluated operations behind a result, separate from revision-local SDK
43/// faces and display data. It records numerical provenance, not complete
44/// representation coverage.
45#[derive(Debug, Clone)]
46pub enum RetainedLineage {
47    Source {
48        request: Box<RetainedRequest>,
49        world_from_source: [f64; 16],
50    },
51    Boolean {
52        operation: BooleanOperation,
53        left: Arc<Self>,
54        right: Arc<Self>,
55    },
56    /// A realization's raw authored source in its own evaluation frame, as
57    /// the input of an affine copy (no world placement applies to it).
58    Definition {
59        request: Box<RetainedRequest>,
60        source_from_evaluation: [f64; 16],
61        evaluation_from_source: [f64; 16],
62    },
63    /// A bounded affine copy of `input`, in the input's evaluation frame.
64    AffineCopy {
65        input: Arc<Self>,
66        column_major: [f64; 16],
67        certificate: AffineCertificate,
68    },
69    /// An explicit rigid placement of a copied value as a Boolean operand.
70    Placed {
71        value: Arc<Self>,
72        world_from_evaluation: [f64; 16],
73    },
74}
75
76/// Read-only identity sealed from the actual ordered numerical invocation.
77/// This metadata cannot create a result or acquire an object lease.
78#[cfg(feature = "retained-runtime")]
79#[derive(Debug, Clone, PartialEq)]
80pub struct RetainedBooleanIdentity {
81    pub operation: BooleanOperation,
82    pub left: BrepHandle,
83    pub right: BrepHandle,
84    pub world_from_left: [f64; 16],
85    pub world_from_right: [f64; 16],
86}
87
88/// One retained Boolean output, owned by its own object lease. Dropping it
89/// releases only this solid; its operands' receipts are unaffected. This is a
90/// numerical result, not a final product receipt.
91#[derive(Debug)]
92pub struct RetainedDependencyResult {
93    solid: BrepHandle,
94    owner: crate::RuntimeOwner,
95    _lease: Arc<super::objects::ManagedObjectLease>,
96    object_live: Arc<AtomicBool>,
97    mesh: TessellatedMesh,
98    #[cfg(feature = "retained-runtime")]
99    identity: RetainedBooleanIdentity,
100    world_from_evaluation: [f64; 16],
101    lineage: Arc<RetainedLineage>,
102    operations: usize,
103}
104
105impl RetainedDependencyResult {
106    /// Immutable actual ordered inputs and their bit-preserved invocation frames.
107    #[cfg(feature = "retained-runtime")]
108    pub fn operation_identity(&self) -> &RetainedBooleanIdentity { &self.identity }
109    pub fn solid(&self) -> BrepHandle {
110        self.solid
111    }
112    /// Sealed from the actual result solid. An empty result is a valid,
113    /// independently owned operand of later Booleans, not a failure.
114    pub fn outcome(&self) -> NumericalOutcome {
115        self.mesh.outcome()
116    }
117    pub fn is_empty(&self) -> bool {
118        self.mesh.is_empty()
119    }
120    /// Display mesh in the result's evaluation frame; no buffers when empty.
121    pub fn mesh(&self) -> &TessellatedMesh {
122        &self.mesh
123    }
124    /// Column-major evaluation metres -> world metres (the left operand's frame).
125    pub fn world_from_evaluation(&self) -> &[f64; 16] {
126        &self.world_from_evaluation
127    }
128    pub fn lineage(&self) -> &RetainedLineage {
129        &self.lineage
130    }
131    pub fn owner(&self) -> &crate::RuntimeOwner {
132        &self.owner
133    }
134    /// The producing process is live and the solid has not been released.
135    pub fn validate_live(&self) -> Result<(), WorkerError> {
136        if self.owner.incarnation() == Some(self.solid.worker)
137            && self.object_live.load(Ordering::Acquire)
138        {
139            Ok(())
140        } else {
141            Err(WorkerError::WrongWorker)
142        }
143    }
144    /// Live solid, shared lineage and operation count, for a further operation.
145    pub(super) fn parts(&self) -> Result<(BrepHandle, Arc<RetainedLineage>, usize), WorkerError> {
146        self.validate_live()?;
147        Ok((self.solid, self.lineage.clone(), self.operations))
148    }
149}
150
151type Operand = (BrepHandle, [f64; 16], Arc<RetainedLineage>, usize);
152
153impl RetainedDependency<'_> {
154    fn operand(&self) -> Result<Operand, WorkerError> {
155        match self {
156            Self::Source {
157                realization,
158                world_from_source,
159            } => {
160                realization.validate_live()?;
161                // Bit-identical to the controller's frame (#7955).
162                let frame = compose_frame(
163                    world_from_source,
164                    &realization.completion().source_from_evaluation,
165                );
166                rigid(frame).map_err(WorkerError::InvalidArgument)?;
167                let lineage = RetainedLineage::Source {
168                    request: Box::new(realization.completion().request().clone()),
169                    world_from_source: *world_from_source,
170                };
171                Ok((realization.solid(), frame, Arc::new(lineage), 0))
172            }
173            Self::Result(result) => {
174                let (solid, lineage, operations) = result.parts()?;
175                Ok((solid, result.world_from_evaluation, lineage, operations))
176            }
177            #[cfg(feature = "retained-runtime")]
178            Self::PlacedResult { result, world_from_result } => {
179                let (solid, value, operations) = result.parts()?;
180                rigid(*world_from_result).map_err(WorkerError::InvalidArgument)?;
181                let lineage = RetainedLineage::Placed { value, world_from_evaluation: *world_from_result };
182                Ok((solid, *world_from_result, Arc::new(lineage), operations))
183            }
184            Self::Affine {
185                copy,
186                world_from_affine,
187            } => {
188                let (solid, value, operations) = copy.parts()?;
189                rigid(*world_from_affine).map_err(WorkerError::InvalidArgument)?;
190                let lineage = RetainedLineage::Placed {
191                    value,
192                    world_from_evaluation: *world_from_affine,
193                };
194                Ok((solid, *world_from_affine, Arc::new(lineage), operations))
195            }
196        }
197    }
198}
199
200impl SmlibWorker {
201    /// Evaluate two sealed operands. The left operand's frame is the common
202    /// local frame, so world coordinates never enter the SDK; the right operand
203    /// is copied into it and the copy is released. Both inputs stay unchanged.
204    /// A certified-empty result is sealed as [`NumericalOutcome::Empty`].
205    pub fn evaluate_retained_boolean(
206        &mut self,
207        left: RetainedDependency<'_>,
208        right: RetainedDependency<'_>,
209        operation: BooleanOperation,
210        chord_metres: f64,
211        angle_degrees: f64,
212        limits: MeshLimits,
213    ) -> Result<RetainedDependencyResult, WorkerError> {
214        let (a, frame, left_lineage, left_count) = left.operand()?;
215        let (b, right_frame, right_lineage, right_count) = right.operand()?;
216        self.object_liveness(a)?;
217        self.object_liveness(b)?;
218        let operations = left_count
219            .checked_add(right_count)
220            .and_then(|n| n.checked_add(1))
221            .filter(|&n| n <= MAX_OPERATIONS)
222            .ok_or(WorkerError::ResourceLimit("retained dependency depth"))?;
223        let relative = relative(frame, right_frame).map_err(WorkerError::InvalidArgument)?;
224        let transformed = self.copy_transform(b, relative)?;
225        let boolean = self.boolean(a, transformed, operation);
226        let cleanup = self.release(transformed);
227        // Both ran: report the Boolean failure first. A failed cleanup has
228        // already retired the process.
229        let solid = boolean?;
230        cleanup?;
231        let mesh = match self.tessellate(solid, chord_metres, angle_degrees, limits) {
232            Ok(mesh) => mesh,
233            Err(error) => {
234                if self.release(solid).is_err() {
235                    self.retire();
236                }
237                return Err(error);
238            }
239        };
240        Ok(RetainedDependencyResult {
241            _lease: self.manage_object(solid)?,
242            object_live: self.object_liveness(solid)?,
243            solid,
244            owner: self.retained_owner(),
245            mesh,
246            #[cfg(feature = "retained-runtime")]
247            identity: RetainedBooleanIdentity { operation, left: a, right: b,
248                world_from_left: frame, world_from_right: right_frame },
249            world_from_evaluation: frame,
250            lineage: Arc::new(RetainedLineage::Boolean {
251                operation,
252                left: left_lineage,
253                right: right_lineage,
254            }),
255            operations,
256        })
257    }
258}
259
260/// `inverse(a) * b` for proper rigid frames. Translations are subtracted
261/// before rotating, so survey-scale origins cancel in f64.
262fn relative(a: [f64; 16], b: [f64; 16]) -> Result<[f64; 16], &'static str> {
263    rigid(a)?;
264    rigid(b)?;
265    let mut out = [0.; 16];
266    out[15] = 1.;
267    for col in 0..3 {
268        for row in 0..3 {
269            out[col * 4 + row] = (0..3).map(|k| a[row * 4 + k] * b[col * 4 + k]).sum();
270        }
271    }
272    for row in 0..3 {
273        out[12 + row] = (0..3)
274            .map(|k| a[row * 4 + k] * (b[12 + k] - a[12 + k]))
275            .sum();
276    }
277    rigid(out)?;
278    Ok(out)
279}
280
281#[cfg(test)]
282#[path = "worker_dependencies_tests.rs"]
283mod tests;