brep_render/engine_state/interference.rs
1use super::*;
2use crate::camera::Aabb;
3
4// ===========================================================================
5// Interference check (assemblies build-spec §9) — pairwise NON-DESTRUCTIVE
6// kernel INTERSECT booleans over the component instances, reporting every
7// overlapping pair + its intersection volume. Zero interference is a PASS.
8//
9// Runs MAIN-SIDE like every other assembly op (the thread-local rule): the
10// component solids' kernel handles come from [`EngineState::
11// resident_solid_handles`] — a warm-cache replay of the rolled-to history on
12// THIS thread — and `brep_kernel::boolean_handle` / `mass_properties_handle_
13// native` read the SAME thread-local registry. The operand handles belong to
14// the incremental cache + scene; ONLY the boolean RESULT handle is freed.
15//
16// Scale sanity: N components = N·(N−1)/2 pairs, but a full boolean only runs
17// for pairs whose (inflated, mesh-derived) bboxes overlap — [`plan_pairs`]
18// prefilters, so disjoint pairs are PROVEN clear for the cost of a box test.
19// Bbox-overlapping pairs beyond [`MAX_BOOLEAN_PAIRS`] are SKIPPED with an
20// explicit per-pair note (never silently). Hidden components participate —
21// interference is a physical question — with the pair flagged so the window
22// can note it.
23// ===========================================================================
24
25/// Budget of component pairs allowed to run REAL booleans per check run. Full
26/// booleans cost ~10–100 ms each; the bbox prefilter keeps normal assemblies
27/// far below this. Pairs beyond the budget are reported as skipped.
28const MAX_BOOLEAN_PAIRS: usize = 64;
29
30/// Interference counts only above this intersection volume (mm³): exact face
31/// contact (mated components) integrates to ~0 and must read as clear.
32const VOLUME_EPSILON: f64 = 1e-6;
33
34/// One INTERFERING component pair: the two owning ACOMP feature ids, their
35/// summed intersection volume (mm³, over all member-solid cross pairs), and
36/// whether either participant is currently hidden (it still participates —
37/// the window notes it).
38#[derive(Debug, Clone, PartialEq)]
39pub struct InterferencePair {
40 pub a: String,
41 pub b: String,
42 pub volume: f64,
43 pub a_hidden: bool,
44 pub b_hidden: bool,
45}
46
47/// The result of one interference run — everything the results window shows.
48/// `pairs` empty + `skipped`/`unverified` empty = the green all-clear.
49#[derive(Debug, Clone, Default, PartialEq)]
50pub struct InterferenceReport {
51 /// Number of component instances that participated.
52 pub component_count: usize,
53 /// Every pair considered: N·(N−1)/2.
54 pub pair_total: usize,
55 /// Pairs that ran the boolean lane (bbox-overlapping, within budget).
56 /// The rest were PROVEN clear by the bbox prefilter (or noted below).
57 pub booleans_run: usize,
58 /// The interfering pairs, largest intersection volume first.
59 pub pairs: Vec<InterferencePair>,
60 /// Anything NOT fully checked, one human-readable line each: pairs beyond
61 /// the boolean budget, components with no resident geometry. NEVER silent.
62 pub skipped: Vec<String>,
63 /// Pairs whose boolean REFUSED (the kernel is conservative on grazing /
64 /// tangent contact): not a pass, not an interference — shown under their
65 /// own heading so a mated assembly never reads as a wall of errors.
66 pub unverified: Vec<String>,
67}
68
69// --- the test seam: count trips through the boolean lane --------------------
70
71
72/// Tally one boolean-lane invocation (test-observable; free in release).
73fn note_boolean_call() {
74}
75
76
77
78// --- the boolean lane -------------------------------------------------------
79
80/// Intersection volume (mm³) of two RESIDENT solids, non-destructively:
81/// `boolean_handle_native` reads both operands by reference (pipeline-default
82/// options), the result registers under a NEW handle whose exact volume is
83/// integrated, and that intermediate is freed. A legitimately-disjoint
84/// intersect yields an EMPTY solid → volume 0. The OPERAND handles are owned
85/// by the incremental cache + scene — never free them here.
86fn intersect_volume(a: u32, b: u32) -> Result<f64, String> {
87 note_boolean_call();
88 let result = brep_kernel::boolean_handle_native(
89 a,
90 b,
91 brep_kernel::BooleanOperation::Intersect,
92 &brep_kernel::BooleanOptions::default(),
93 )?;
94 let volume = brep_kernel::mass_properties_handle_native(result, 1.0).map(|p| p.volume);
95 // Free ONLY the result — the intermediate this check minted.
96 brep_kernel::free_solid(result);
97 volume
98}
99
100// --- the pure pair planner (prefilter + budget) ------------------------------
101
102/// One component as the planner sees it: id, the union bbox of its member
103/// solids (EMPTY = no resident geometry), and the hidden flag.
104pub(crate) struct PlanComponent {
105 pub id: String,
106 pub bbox: Aabb,
107 pub hidden: bool,
108}
109
110/// What [`plan_pairs`] decides: which index pairs go to the boolean lane, and
111/// the explicit notes for everything that will NOT be boolean-checked.
112pub(crate) struct PairPlan {
113 pub boolean_pairs: Vec<(usize, usize)>,
114 pub skipped: Vec<String>,
115 pub pair_total: usize,
116}
117
118/// Grow a mesh-derived bbox conservatively before the overlap test: the scene
119/// bbox is over TESSELLATED positions, which under-approximate curved BREP by
120/// up to the chord deviation — a false positive costs one boolean that comes
121/// back empty; a false negative would silently miss real interference.
122fn inflated(bbox: &Aabb) -> Aabb {
123 if bbox.is_empty() {
124 return *bbox;
125 }
126 let size = bbox.size();
127 let diagonal = (size[0] * size[0] + size[1] * size[1] + size[2] * size[2]).sqrt();
128 let margin = (diagonal * 0.01).max(1e-6);
129 let mut out = *bbox;
130 for axis in 0..3 {
131 out.min[axis] -= margin;
132 out.max[axis] += margin;
133 }
134 out
135}
136
137/// Axis-aligned overlap (empty boxes never overlap).
138fn overlaps(a: &Aabb, b: &Aabb) -> bool {
139 if a.is_empty() || b.is_empty() {
140 return false;
141 }
142 (0..3).all(|axis| a.min[axis] <= b.max[axis] && b.min[axis] <= a.max[axis])
143}
144
145/// The PURE planning pass: which pairs must pay for a boolean. Bbox-disjoint
146/// pairs are PROVEN clear (checked, not skipped); pairs past `cap` and
147/// geometry-less components get explicit notes. Deterministic id order.
148pub(crate) fn plan_pairs(components: &[PlanComponent], cap: usize) -> PairPlan {
149 let mut plan = PairPlan {
150 boolean_pairs: Vec::new(),
151 skipped: Vec::new(),
152 pair_total: components.len().saturating_sub(1) * components.len() / 2,
153 };
154 for component in components {
155 if component.bbox.is_empty() {
156 plan.skipped
157 .push(format!("{} — no resident geometry, not checked", component.id));
158 }
159 }
160 let boxes: Vec<Aabb> = components.iter().map(|c| inflated(&c.bbox)).collect();
161 for i in 0..components.len() {
162 for j in (i + 1)..components.len() {
163 if !overlaps(&boxes[i], &boxes[j]) {
164 continue; // proven clear by the prefilter — no boolean needed
165 }
166 if plan.boolean_pairs.len() >= cap {
167 plan.skipped.push(format!(
168 "{} × {} — skipped (boolean budget of {cap} pairs reached)",
169 components[i].id, components[j].id
170 ));
171 continue;
172 }
173 plan.boolean_pairs.push((i, j));
174 }
175 }
176 plan
177}
178
179// --- the engine surface ------------------------------------------------------
180
181impl EngineState {
182 /// Run the interference check over every component instance (hidden ones
183 /// included — interference is a physical question). Non-destructive: the
184 /// component solids are only READ; each pairwise INTERSECT result is
185 /// measured and freed. Returns the full report for the results window.
186 pub fn interference_check(&mut self) -> InterferenceReport {
187
188 // Gather the participants: members + union bbox + hidden, in the
189 // deterministic history order component_ids() gives.
190 let ids = self.component_ids();
191 let mut members: Vec<Vec<String>> = Vec::with_capacity(ids.len());
192 let mut plan_input: Vec<PlanComponent> = Vec::with_capacity(ids.len());
193 for id in &ids {
194 let info = self.component_info(id);
195 let solids = info.map(|info| info.members).unwrap_or_default();
196 let mut bbox = Aabb::empty();
197 let mut hidden = false;
198 for name in &solids {
199 if let Some(solid) = self.scene.solid(name) {
200 bbox.union(&solid.bbox);
201 hidden |= !solid.visible;
202 }
203 }
204 plan_input.push(PlanComponent {
205 id: id.clone(),
206 bbox,
207 hidden,
208 });
209 members.push(solids);
210 }
211
212 let plan = plan_pairs(&plan_input, MAX_BOOLEAN_PAIRS);
213 let mut report = InterferenceReport {
214 component_count: ids.len(),
215 pair_total: plan.pair_total,
216 booleans_run: 0,
217 pairs: Vec::new(),
218 skipped: plan.skipped,
219 unverified: Vec::new(),
220 };
221 if plan.boolean_pairs.is_empty() {
222 return report;
223 }
224
225 // The warm MAIN-SIDE handle map (cache-hit replay on this thread) —
226 // the same lane the Info windows' mass properties ride.
227 let handles = self.resident_solid_handles();
228 for (i, j) in plan.boolean_pairs {
229 report.booleans_run += 1;
230 let mut volume = 0.0;
231 let mut refusal: Option<String> = None;
232 for solid_a in &members[i] {
233 for solid_b in &members[j] {
234 let (Some(&ha), Some(&hb)) = (handles.get(solid_a), handles.get(solid_b))
235 else {
236 continue; // not resident (rolled back mid-frame)
237 };
238 // Member-level prefilter: within an overlapping component
239 // pair, only member solids whose own boxes overlap pay.
240 let (Some(a), Some(b)) =
241 (self.scene.solid(solid_a), self.scene.solid(solid_b))
242 else {
243 continue;
244 };
245 if !overlaps(&inflated(&a.bbox), &inflated(&b.bbox)) {
246 continue;
247 }
248 match intersect_volume(ha, hb) {
249 Ok(v) => volume += v,
250 Err(error) => {
251 // A conservative kernel refusal (grazing/tangent
252 // contact): the pair is UNVERIFIED, never a
253 // silent pass and never fake interference.
254 refusal.get_or_insert(error);
255 }
256 }
257 }
258 }
259 let (a, b) = (&plan_input[i], &plan_input[j]);
260 if let Some(error) = refusal {
261 report
262 .unverified
263 .push(format!("{} × {} — boolean refused: {error}", a.id, b.id));
264 }
265 if volume > VOLUME_EPSILON {
266 report.pairs.push(InterferencePair {
267 a: a.id.clone(),
268 b: b.id.clone(),
269 volume,
270 a_hidden: a.hidden,
271 b_hidden: b.hidden,
272 });
273 }
274 }
275 // Largest interference first (stable → id order breaks ties).
276 report
277 .pairs
278 .sort_by(|x, y| y.volume.total_cmp(&x.volume));
279 report
280 }
281}
282