1pub(crate) mod profile;
2use crate::arrangement::Vec2;
3use crate::classification::{classify_point, parameter_point_in_face, PolygonClass};
4use crate::fragment::{FaceFragmentRecord, FragmentEdgeSource};
5use crate::imprint::{
6 EdgeSplitRecord, FaceImprints, FaceKey, ImprintOptions, ImprintPieceRecord,
7 ImprintResultRecord, ImprintVertex,
8};
9use crate::tolerance::{assembler_weld, commit_weld};
10use crate::topology::{
11 adaptive_coedge_error, BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord,
12 ShellRecord, VertexRecord,
13};
14use crate::{
15 KernelRefusal, OrRefuse, RefusalClass,
16 apply_edge_splits, apply_edge_splits_with_map, build_imprints, build_pcurve_on_surface,
17 build_pcurve_on_surface_range, classify_surface_pair,
18 fragment_solid, interpolate_curve, merge_curve_continuation_edges,
19 merge_same_surface_faces_excluding, merge_same_surface_faces_scoped,
20 project_point_to_curve, project_point_to_surface, solid_signed_volume, solid_signed_volume_for_sign, AffineTransform,
21 DiagnosticSeverity, KernelDiagnostics, KernelOutcome, KernelStage, KernelTolerances, NurbsCurve,
22 PointClass, SolidClassifier, SurfacePairRelation, Vec3,
23};
24use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
25use serde::{Deserialize, Serialize};
26use web_time::Instant;
27
28thread_local! {
29 pub(crate) static CONFORMANCE_REPAIRS: std::cell::Cell<u64> =
35 const { std::cell::Cell::new(0) };
36}
37
38#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
39#[serde(rename_all = "lowercase")]
40pub enum BooleanOperation {
41 Union,
42 Intersect,
43 Subtract,
44}
45
46#[derive(Clone, Debug, Deserialize)]
47pub struct BooleanOptions {
48 #[serde(default = "default_tolerance")]
49 pub tolerance: f64,
50 #[serde(default)]
53 pub tolerances: Option<KernelTolerances>,
54 #[serde(default)]
55 pub imprint: ImprintOptions,
56 #[serde(default = "default_true")]
59 pub merge_coplanar_faces: bool,
60 #[serde(default)]
70 pub keep_unmerged_name_substrs: Vec<String>,
71 #[serde(default = "default_true")]
75 pub untouched_passthrough: bool,
76 #[serde(default = "default_true")]
80 pub disjoint_fast_path: bool,
81 #[serde(default = "default_true")]
91 pub contact_fast_path: bool,
92 #[serde(default)]
100 pub touched_assembly: bool,
101 #[serde(default = "default_true")]
109 pub sector_classification: bool,
110 #[serde(default = "default_true")]
114 pub sheet_trim: bool,
115 #[serde(default)]
119 pub keep_cells: bool,
120 #[serde(default)]
125 pub seam_reseat_later_references: Option<Vec<String>>,
126}
127
128fn touched_assembly(options: &BooleanOptions) -> bool {
130 match std::env::var("BREP_TOUCHED_ASSEMBLY").as_deref() {
131 Ok("0") => false,
132 Ok(_) => true,
133 Err(_) => options.touched_assembly,
134 }
135}
136
137fn disjoint_fast_path(options: &BooleanOptions) -> bool {
139 match std::env::var("BREP_DISJOINT_FAST_PATH").as_deref() {
140 Ok("0") => false,
141 Ok(_) => true,
142 Err(_) => options.disjoint_fast_path,
143 }
144}
145
146fn contact_fast_path(options: &BooleanOptions) -> bool {
148 match std::env::var("BREP_CONTACT_FAST_PATH").as_deref() {
149 Ok("0") => false,
150 Ok(_) => true,
151 Err(_) => options.contact_fast_path,
152 }
153}
154
155fn untouched_passthrough(options: &BooleanOptions) -> bool {
157 match std::env::var("BREP_UNTOUCHED_PASSTHROUGH").as_deref() {
158 Ok("0") => false,
159 Ok(_) => true,
160 Err(_) => options.untouched_passthrough,
161 }
162}
163
164fn default_tolerance() -> f64 {
165 1e-7
166}
167
168fn default_true() -> bool {
169 true
170}
171
172impl Default for BooleanOptions {
173 fn default() -> Self {
174 Self {
175 tolerance: default_tolerance(),
176 tolerances: None,
177 imprint: ImprintOptions::default(),
178 merge_coplanar_faces: true,
179 keep_unmerged_name_substrs: Vec::new(),
180 untouched_passthrough: true,
181 disjoint_fast_path: true,
182 contact_fast_path: true,
183 touched_assembly: false,
184 sector_classification: true,
185 sheet_trim: true,
186 keep_cells: false,
187 seam_reseat_later_references: None,
188 }
189 }
190}
191
192mod select;
193mod sheet;
194mod cellular;
195mod sector;
196mod assemble;
197mod operand_state;
198mod rim;
199mod coincident;
200mod touch;
201mod reseat;
202
203use rim::*;
204use select::*;
205use coincident::*;
206use touch::TouchCensus;
207pub(crate) use assemble::{
208 assemble_fragments, assemble_open_fragments, commit_nearby_edge_endpoints,
209 clear_candidate_memo, edge_interior_lies_on, finalize_assembled_solid, refresh_derived_genus,
210};
211use assemble::{assemble_fragments_scoped, AssemblyScope};
212#[allow(unused_imports)]
214pub(crate) use assemble::apply_assembly_heal_chain;
215
216
217struct WorkingScale {
220 factor: f64,
221 solids: Vec<BrepSolid>,
222 options: BooleanOptions,
223}
224
225impl WorkingScale {
226 fn of(operands: &[&BrepSolid], options: &BooleanOptions) -> Result<Option<Self>, KernelRefusal> {
227 let Some(bounds) = crate::rescale::bounds_of(operands.iter().copied()) else {
228 return Ok(None);
229 };
230 let Some(factor) = crate::rescale::guard_factor(bounds) else {
231 return Ok(None);
232 };
233 crate::rescale::profile_fired("boolean", factor, bounds);
234 let solids = operands
235 .iter()
236 .map(|solid| crate::rescale::scale_operand(solid, factor, "boolean"))
237 .collect::<Result<Vec<_>, _>>()?;
238 let mut options = options.clone();
240 options.imprint.maximum_ssi_step = options.imprint.maximum_ssi_step.map(|step| step * factor);
241 Ok(Some(Self { factor, solids, options }))
242 }
243
244 fn back(&self, solid: &BrepSolid) -> Result<BrepSolid, KernelRefusal> {
245 crate::rescale::scale_operand(solid, 1.0 / self.factor, "boolean")
246 }
247
248 fn refusal(&self, error: KernelRefusal) -> KernelRefusal {
249 crate::rescale::name_scale(error, self.factor)
250 }
251}
252
253pub fn boolean_operation(
254 first: &BrepSolid,
255 second: &BrepSolid,
256 operation: BooleanOperation,
257 options: &BooleanOptions,
258) -> Result<BrepSolid, KernelRefusal> {
259 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
260 return boolean_operation(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
261 .map_err(|error| scaled.refusal(error))
262 .and_then(|solid| scaled.back(&solid));
263 }
264 match boolean_operation_with_diagnostics(first, second, operation, options) {
265 Ok(outcome) => {
266 if below_tolerance_refusal_enabled()
269 && outcome.value.shells.iter().all(|shell| shell.faces.is_empty())
270 && !matches!(operation, BooleanOperation::Union)
271 {
272 if let Some(refusal) = below_tolerance_refusal(first, second, None) {
273 return Err(refusal);
274 }
275 }
276 if unresolved_merge_refusal_enabled() && !matches!(operation, BooleanOperation::Subtract) {
277 if let Some(refusal) = unresolved_merge_refusal(first, second) {
278 return Err(refusal);
279 }
280 }
281 Ok(outcome.value)
282 }
283 Err(error) => {
284 if below_tolerance_refusal_enabled() {
285 if let Some(refusal) = below_tolerance_refusal(first, second, Some(&error)) {
286 return Err(refusal);
287 }
288 }
289 if std::env::var("BREP_NO_PERTURB").as_deref() == Ok("1")
297 || !error.class.perturbation_eligible()
298 {
299 return Err(error);
300 }
301 if std::env::var("BREP_OPEN_OPERAND_GATE").as_deref() != Ok("0") {
323 if let Some((operand, open)) = [first, second]
324 .iter()
325 .enumerate()
326 .find_map(|(operand, solid)| {
327 let open = one_use_edges(solid);
328 (open > 0).then_some((operand, open))
329 })
330 {
331 return Err(error.with_message(|message| format!(
332 "{message}; operand {operand} is not a closed shell: {open} of its edges bound \
333 only one face, so no boolean of it encloses a solid and no perturbation \
334 can close it"
335 )));
336 }
337 }
338 if let Some((operand, face_id, deviation, weld)) =
339 planar_operand_off_its_plane(first, second, options)
340 {
341 return Err(error.with_message(|message| format!(
342 "{message}; operand {operand} face {face_id} is a plane whose straight \
343 boundary sits {deviation:.3e} off it (assembly weld {weld:.1e}), which \
344 no perturbation can reconcile — the body's planes must contain their \
345 boundary before it can take part in an exact boolean"
346 )));
347 }
348 if matches!(operation, BooleanOperation::Subtract)
363 && std::env::var("BREP_PINCH_GATE").as_deref() != Ok("0")
364 && subtract_pinches_at_internal_tangency(first, second, options.tolerance)
365 .unwrap_or(false)
366 {
367 if let Some(solid) = subtract_through_the_common_part(first, second, options) {
370 return Ok(solid);
371 }
372 return Err(error.with_message(|message| format!(
373 "{message}; internal tangency: the operands touch tangentially with \
374 co-directed normals, so the exact difference pinches to zero thickness \
375 (non-manifold, unrepresentable in a boundary model) — refusing rather \
376 than returning a perturbed sliver"
377 )));
378 }
379 if matches!(error.class, RefusalClass::TangentNodeSingularity)
395 && std::env::var("BREP_TANGENT_NODE_GATE").as_deref() != Ok("0")
396 {
397 return Err(error);
398 }
399 if matches!(operation, BooleanOperation::Union) {
403 if let Some(solid) = union_through_the_difference(first, second, options) {
404 return Ok(solid);
405 }
406 }
407 match perturbation_retry(first, second, operation, options) {
408 Ok(solid) => Ok(solid),
409 Err(refused) if refused.is_empty() => Err(error),
410 Err(refused) => {
411 Err(error.with_message(|message| format!("{message}; {}", refused.join("; "))))
412 }
413 }
414 }
415 }
416}
417
418const PINCH_PROBE_STEPS: usize = 8;
423
424const PINCH_ANGULAR_TOLERANCE: f64 = 1e-4;
427
428const PINCH_SEPARATION_STEP: f64 = 1e-2;
432
433fn subtract_through_the_common_part(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
451 if !switch!("BREP_PINCH_COMMON_RETRY", true) || !options.imprint.tangent_curve_imprint {
454 return None;
455 }
456 let common = boolean_operation_with_diagnostics(first, second, BooleanOperation::Intersect, options).ok()?.value;
457 if common.shells.iter().all(|shell| shell.faces.is_empty()) {
458 return None;
459 }
460 let cut = boolean_operation_with_diagnostics(first, &common, BooleanOperation::Subtract, options).ok()?.value;
461 if !cut.validate().is_empty() {
462 return None;
463 }
464 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
465 let (whole, taken, left) = (volume(first)?, volume(&common)?, volume(&cut)?);
466 ((left - (whole - taken)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(cut)
467}
468
469fn union_through_the_difference(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
482 if !switch!("BREP_TANGENT_UNION_DIFFERENCE_RETRY", true) || !options.imprint.tangent_curve_imprint {
483 return None;
484 }
485 let pinches = |a: &BrepSolid, b: &BrepSolid| subtract_pinches_at_internal_tangency(a, b, options.tolerance).unwrap_or(false);
486 if !pinches(first, second) && !pinches(second, first) {
487 return None;
488 }
489 let difference = match boolean_operation_with_diagnostics(first, second, BooleanOperation::Subtract, options) {
490 Ok(outcome) => outcome.value,
491 Err(_) => subtract_through_the_common_part(first, second, options)?,
492 };
493 if difference.shells.iter().all(|shell| shell.faces.is_empty()) || !difference.validate().is_empty() {
494 return None;
495 }
496 let union = boolean_operation_with_diagnostics(second, &difference, BooleanOperation::Union, options).ok()?.value;
497 if !union.validate().is_empty() {
498 return None;
499 }
500 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
501 let (left, added, whole) = (volume(&difference)?, volume(second)?, volume(&union)?);
502 ((whole - (left + added)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(union)
503}
504
505fn subtract_pinches_at_internal_tangency(
527 first: &BrepSolid,
528 second: &BrepSolid,
529 tolerance: f64,
530) -> Result<bool, KernelRefusal> {
531 let contact = (tolerance * 100.0).max(1e-12);
534 let probes_a = first
535 .shells
536 .iter()
537 .flat_map(|shell| &shell.faces)
538 .map(PinchProbe::of)
539 .collect::<Result<Vec<_>, _>>()?;
540 let probes_b = second
541 .shells
542 .iter()
543 .flat_map(|shell| &shell.faces)
544 .map(PinchProbe::of)
545 .collect::<Result<Vec<_>, _>>()?;
546 for probe_a in &probes_a {
547 for probe_b in &probes_b {
548 let pad = 1e-2 * probe_a.extent().max(probe_b.extent());
555 if probe_a.separation(probe_b) > contact + pad {
556 continue;
557 }
558 if classify_surface_pair(
565 &probe_a.face.surface,
566 &probe_b.face.surface,
567 tolerance,
568 PINCH_ANGULAR_TOLERANCE,
569 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")?
570 .relation
571 == SurfacePairRelation::Cosurface
572 {
573 continue;
574 }
575 if faces_touch_with_codirected_normals(probe_a, probe_b, contact)? {
576 return Ok(true);
577 }
578 }
579 }
580 Ok(false)
581}
582
583struct PinchProbe<'a> {
586 face: &'a FaceRecord,
587 samples: Vec<(f64, f64, Vec3)>,
589 minimum: [f64; 3],
590 maximum: [f64; 3],
591}
592
593impl<'a> PinchProbe<'a> {
594 fn of(face: &'a FaceRecord) -> Result<Self, KernelRefusal> {
595 let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
596 let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
597 let steps = PINCH_PROBE_STEPS as f64;
598 let mut samples = Vec::with_capacity((PINCH_PROBE_STEPS + 1).pow(2));
599 let mut minimum = [f64::INFINITY; 3];
600 let mut maximum = [f64::NEG_INFINITY; 3];
601 for i in 0..=PINCH_PROBE_STEPS {
602 let u = u0 + (u1 - u0) * i as f64 / steps;
603 for j in 0..=PINCH_PROBE_STEPS {
604 let v = v0 + (v1 - v0) * j as f64 / steps;
605 let Ok(point) = face.surface.evaluate(u, v) else {
606 continue;
607 };
608 for (axis, value) in [point.x, point.y, point.z].into_iter().enumerate() {
609 minimum[axis] = minimum[axis].min(value);
610 maximum[axis] = maximum[axis].max(value);
611 }
612 samples.push((u, v, point));
613 }
614 }
615 Ok(Self {
616 face,
617 samples,
618 minimum,
619 maximum,
620 })
621 }
622
623 fn extent(&self) -> f64 {
625 (0..3)
626 .map(|axis| self.maximum[axis] - self.minimum[axis])
627 .fold(0.0f64, f64::max)
628 }
629
630 fn separation(&self, other: &Self) -> f64 {
632 let mut gap: f64 = 0.0;
633 for axis in 0..3 {
634 gap = gap.max(self.minimum[axis] - other.maximum[axis]);
635 gap = gap.max(other.minimum[axis] - self.maximum[axis]);
636 }
637 gap
638 }
639}
640
641fn faces_touch_with_codirected_normals(
646 probe_a: &PinchProbe<'_>,
647 probe_b: &PinchProbe<'_>,
648 contact: f64,
649) -> Result<bool, KernelRefusal> {
650 for (probe, other) in [(probe_a, probe_b), (probe_b, probe_a)] {
651 let source = probe.face;
652 let target = other.face;
653 for &(u, v, point) in &probe.samples {
654 let projection = project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?;
655 if projection.distance > contact {
656 continue;
657 }
658 let (Ok(source_normal), Ok(target_normal)) = (
661 source.surface.normal(u, v),
662 target.surface.normal(projection.u, projection.v),
663 ) else {
664 continue;
665 };
666 let source_outward = outward_normal(source_normal, source.same_sense);
667 let target_outward = outward_normal(target_normal, target.same_sense);
668 if source_outward.cross(target_outward).length() > PINCH_ANGULAR_TOLERANCE
669 || source_outward.dot(target_outward) <= 0.0
670 {
671 continue;
672 }
673 if parameter_point_in_face(source, Vec2 { x: u, y: v }, 1e-6).or_refuse(KernelStage::Validate, "parameter_point_in_face")?
674 == PolygonClass::Outside
675 || parameter_point_in_face(
676 target,
677 Vec2 {
678 x: projection.u,
679 y: projection.v,
680 },
681 1e-6,
682 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")? == PolygonClass::Outside
683 {
684 continue;
685 }
686 if contact_separates_locally(source, target, u, v, contact)? {
687 return Ok(true);
688 }
689 }
690 }
691 Ok(false)
692}
693
694fn outward_normal(normal: Vec3, same_sense: bool) -> Vec3 {
695 if same_sense {
696 normal
697 } else {
698 normal.scale(-1.0)
699 }
700}
701
702fn contact_separates_locally(
708 source: &FaceRecord,
709 target: &FaceRecord,
710 u: f64,
711 v: f64,
712 contact: f64,
713) -> Result<bool, KernelRefusal> {
714 let [u0, u1] = source.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
715 let [v0, v1] = source.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
716 let step_u = (u1 - u0) * PINCH_SEPARATION_STEP;
717 let step_v = (v1 - v0) * PINCH_SEPARATION_STEP;
718 for (probe_u, probe_v) in [
719 ((u + step_u).min(u1), v),
720 ((u - step_u).max(u0), v),
721 (u, (v + step_v).min(v1)),
722 (u, (v - step_v).max(v0)),
723 ] {
724 if (probe_u - u).abs() < f64::EPSILON && (probe_v - v).abs() < f64::EPSILON {
725 continue;
726 }
727 let Ok(point) = source.surface.evaluate(probe_u, probe_v) else {
728 continue;
729 };
730 if project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?.distance > contact * 10.0 {
733 return Ok(true);
734 }
735 }
736 Ok(false)
737}
738
739fn perturbation_retry(
793 first: &BrepSolid,
794 second: &BrepSolid,
795 operation: BooleanOperation,
796 options: &BooleanOptions,
797) -> Result<BrepSolid, Vec<String>> {
798 const DIRECTIONS: [[f64; 3]; 4] = [
809 [0.4034, 0.7973, 0.4491],
810 [0.7973, 0.4491, 0.4034],
811 [0.4491, 0.4034, 0.7973],
812 [0.5774, -0.5774, 0.5774],
813 ];
814 const FRACTIONS: [f64; 5] = PERTURBATION_FRACTIONS;
820
821 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
822 let scale = crate::tolerance::solid_scale(first)
823 .max(crate::tolerance::solid_scale(second))
824 .max(1.0);
825
826 let _caller = crate::mass_caller("boolean.perturbation_rescue");
830 let va = solid_signed_volume(first).ok().map(f64::abs);
831 let vb = solid_signed_volume(second).ok().map(f64::abs);
832 let hold_identity = std::env::var("BREP_PERTURB_IDENTITY").as_deref() != Ok("0");
833 let hold_mirror = hold_identity && std::env::var("BREP_PERTURB_MIRROR").as_deref() != Ok("0");
836 let early_exit = std::env::var("BREP_MIRROR_EARLY_EXIT").as_deref() != Ok("0");
839 let mut trends = [MirrorTrend::default(); 4];
840 let mut identity: Option<Option<InclusionExclusion>> = None;
842 let mut refused = Vec::new();
843 let ladder = std::env::var("BREP_DEBUG_PERTURB_LADDER").is_ok();
847 let ladder_start = web_time::Instant::now();
848 if ladder {
849 let measured = inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
850 match &measured {
851 Some(identity) => eprintln!(
852 "[ladder] identity {} = {:.9} from the exact lane's {} ({:.9}); V(first) {:?} V(second) {:?}",
853 identity.formula, identity.expected, identity.reading, identity.read, va, vb
854 ),
855 None => eprintln!("[ladder] no identity: no exact-lane boolean of these operands clears in either order"),
856 }
857 identity = Some(measured);
858 }
859 let rung_miss = |identity: &Option<Option<InclusionExclusion>>, candidate: &BrepSolid| -> String {
860 let volume = body_volume(candidate);
861 match (identity, volume) {
862 (Some(Some(identity)), Some(volume)) => format!(
863 "volume {volume:.9} miss {:+.3e} bar {:.3e}",
864 volume - identity.expected,
865 crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * identity.expected.abs())
866 ),
867 (_, Some(volume)) => format!("volume {volume:.9}"),
868 _ => "no volume".to_string(),
869 }
870 };
871
872 for &fraction in &FRACTIONS {
873 let magnitude = scale * fraction;
874 for (direction, dir) in DIRECTIONS.iter().enumerate() {
875 if trends[direction].closed {
876 if ladder {
877 eprintln!("[ladder] dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}: not tried, its direction is closed");
878 }
879 continue;
880 }
881 let offset = [dir[0] * magnitude, dir[1] * magnitude, dir[2] * magnitude];
882 let translate = match AffineTransform::new([
883 1.0, 0.0, 0.0, offset[0], 0.0, 1.0, 0.0, offset[1], 0.0, 0.0, 1.0, offset[2], 0.0, 0.0, 0.0, 1.0,
887 ]) {
888 Ok(transform) => transform,
889 Err(_) => continue,
890 };
891 let moved = match crate::transform_brep(second, translate, false) {
892 Ok(solid) => solid,
893 Err(_) => continue,
894 };
895 let rung = format!("dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}");
896 let rung_start = web_time::Instant::now();
897 let candidate =
898 match boolean_operation_with_diagnostics(first, &moved, operation, options) {
899 Ok(outcome) => outcome.value,
900 Err(error) => {
901 if ladder {
902 eprintln!("[ladder] {rung}: exact lane refused {:?}", error.class);
903 }
904 continue;
905 }
906 };
907 let built = rung_start.elapsed();
908 if candidate.shells.is_empty() {
910 if ladder {
911 eprintln!("[ladder] {rung}: empty");
912 }
913 continue;
914 }
915 if let (Some(va), Some(vb)) = (va, vb) {
920 if let Ok(vr) = solid_signed_volume(&candidate) {
921 if !volume_within_csg_bounds(operation, va, vb, vr.abs()) {
922 if ladder {
923 eprintln!("[ladder] {rung}: outside the CSG bound, {}", rung_miss(&identity, &candidate));
924 }
925 continue;
926 }
927 }
928 }
929 let bounded = rung_start.elapsed();
934 if hold_identity {
936 let identity = identity.get_or_insert_with(|| {
937 let identity =
938 inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
939 if debug && identity.is_none() {
940 eprintln!(
941 "[perturb] no exact-lane boolean of these operands clears in either \
942 order; no identity to hold"
943 );
944 }
945 identity
946 });
947 if let Some(identity) = identity {
948 let expected = identity.expected;
949 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * expected.abs());
950 let volume = body_volume(&candidate);
951 let miss = volume.map(|volume| (volume - expected).abs());
952 if !miss.is_some_and(|miss| miss <= bar) {
953 let sentence = format!(
954 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
955 (offset {magnitude:.3e}) refused: its body reads {} against the \
956 inclusion–exclusion identity {} = {expected:.9} (the exact lane's \
957 {} reads {:.9}), a miss of {} beyond the volume drift bar {bar:.3e}",
958 volume.map_or("no volume".to_string(), |volume| format!("{volume:.9}")),
959 identity.formula,
960 identity.reading,
961 identity.read,
962 miss.map_or("unmeasured".to_string(), |miss| format!("{miss:.3e}")),
963 );
964 if debug {
965 eprintln!("[perturb] {sentence}");
966 }
967 if ladder {
968 eprintln!(
969 "[ladder] {rung}: refused by the identity, volume {} miss {} bar {bar:.3e}",
970 volume.map_or("none".to_string(), |volume| format!("{volume:.9}")),
971 volume.map_or("unmeasured".to_string(), |volume| format!("{:+.3e}", volume - expected)),
972 );
973 }
974 refused.push(sentence);
975 continue;
976 }
977 } else if hold_mirror {
978 let mirror_start = web_time::Instant::now();
981 let mirrored = AffineTransform::new([
982 1.0, 0.0, 0.0, -offset[0], 0.0, 1.0, 0.0, -offset[1], 0.0, 0.0, 1.0, -offset[2], 0.0, 0.0, 0.0, 1.0,
986 ])
987 .ok()
988 .and_then(|transform| crate::transform_brep(second, transform, false).ok());
989 let mirror = mirrored.as_ref().and_then(|mirrored| {
990 inclusion_exclusion_volume(first, mirrored, operation, options, va, vb, true)
991 });
992 let mirror_time = mirror_start.elapsed();
993 let volume = body_volume(&candidate);
994 let mut measured = None;
995 let verdict = match (&mirror, volume) {
996 (Some(mirror), Some(volume)) => {
997 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * mirror.expected.abs());
998 let miss = 0.5 * (volume - mirror.expected).abs();
999 measured = Some((0.5 * (volume - mirror.expected), bar));
1000 if ladder {
1001 eprintln!(
1002 "[ladder] {rung}: mirror at −offset reads {} = {:.9} (the mirrored {} {:.9}); body {volume:.9}, first-order translation error {:+.3e} bar {bar:.3e}",
1003 mirror.formula, mirror.expected, mirror.reading, mirror.read, 0.5 * (volume - mirror.expected)
1004 );
1005 }
1006 (miss > bar).then(|| format!(
1007 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1008 (offset {magnitude:.3e}) refused: no exact-lane boolean of the \
1009 operands clears, so the rung is held to its mirror: its body reads \
1010 {volume:.9} with the second operand moved +offset and {} = {:.9} \
1011 with it moved −offset (the mirrored {} reads {:.9}), a first-order \
1012 translation error of {miss:.3e} beyond the volume drift bar {bar:.3e}",
1013 mirror.formula, mirror.expected, mirror.reading, mirror.read
1014 ))
1015 }
1016 _ => Some(format!(
1017 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1018 (offset {magnitude:.3e}) refused: no exact-lane boolean of the operands \
1019 clears, and none clears with the second operand moved −offset either, \
1020 so nothing checks the rung's body{}",
1021 volume.map_or(String::new(), |volume| format!(" ({volume:.9})"))
1022 )),
1023 };
1024 match verdict {
1025 None => trends[direction].cleared(),
1026 Some(sentence) => {
1027 if debug {
1028 eprintln!("[perturb] {sentence}");
1029 }
1030 if ladder {
1031 eprintln!(
1032 "[ladder] {rung}: refused by its mirror (rung {:.0} ms: built {:.0}, bound {:.0}, mirror {:.0} ms; ladder {:.1} s)",
1033 rung_start.elapsed().as_secs_f64() * 1e3,
1034 built.as_secs_f64() * 1e3,
1035 (bounded - built).as_secs_f64() * 1e3,
1036 mirror_time.as_secs_f64() * 1e3,
1037 ladder_start.elapsed().as_secs_f64()
1038 );
1039 }
1040 refused.push(sentence);
1041 let closure = measured.and_then(|(error, bar)| {
1044 let earlier = trends[direction].refused(magnitude, error, early_exit)?;
1045 Some((earlier, error, bar))
1046 });
1047 if let Some(((earlier_offset, earlier_error), error, bar)) = closure {
1048 let closed = format!(
1049 "perturbation direction dir={dir:?} closed after offset {magnitude:.3e}: its \
1050 rungs' first-order translation errors read {earlier_error:+.3e} at offset \
1051 {earlier_offset:.3e} and {error:+.3e} at {magnitude:.3e}, one sign and \
1052 growing, so no larger offset along it comes back to the volume drift bar \
1053 {bar:.3e}"
1054 );
1055 if debug {
1056 eprintln!("[perturb] {closed}");
1057 }
1058 if ladder {
1059 eprintln!("[ladder] {closed}");
1060 }
1061 refused.push(closed);
1062 }
1063 continue;
1064 }
1065 }
1066 }
1067 }
1068 match crate::oracle::boolean_semantic_disagreement(
1072 first, second, operation, &candidate, 400,
1073 ) {
1074 Ok(report) if report.considered >= 30 && !report.is_flagged() => {
1075 if ladder {
1076 eprintln!(
1077 "[ladder] {rung}: accepted (oracle {} considered, rate {:.4}), {}",
1078 report.considered, report.disagreement_rate, rung_miss(&identity, &candidate)
1079 );
1080 }
1081 if debug {
1082 eprintln!(
1083 "[perturb] rescued {operation:?}: dir={dir:?} fraction={fraction:.1e} \
1084 magnitude={magnitude:.3e} offset={offset:?} \
1085 (oracle considered={} rate={:.4})",
1086 report.considered, report.disagreement_rate
1087 );
1088 }
1089 return Ok(candidate);
1090 }
1091 report => {
1092 if ladder {
1093 let verdict = match &report {
1094 Ok(report) => format!("oracle {} considered, rate {:.4}", report.considered, report.disagreement_rate),
1095 Err(error) => format!("oracle error {error:?}"),
1096 };
1097 eprintln!("[ladder] {rung}: refused by the oracle ({verdict}), {}", rung_miss(&identity, &candidate));
1098 }
1099 continue;
1100 }
1101 }
1102 }
1103 }
1104 if debug {
1105 eprintln!("[perturb] ladder exhausted for {operation:?}; no rung produced a clean result");
1106 }
1107 Err(refused)
1108}
1109
1110const PERTURBATION_FRACTIONS: [f64; 5] = [3e-5, 1e-4, 3e-4, 1e-3, 3e-3];
1113
1114#[derive(Clone, Copy, Default)]
1138struct MirrorTrend {
1139 last: Option<(f64, f64)>,
1141 closed: bool,
1142}
1143
1144impl MirrorTrend {
1145 fn refused(&mut self, offset: f64, error: f64, close: bool) -> Option<(f64, f64)> {
1150 let earlier = self
1151 .last
1152 .filter(|&(_, earlier)| earlier.signum() == error.signum() && error.abs() >= earlier.abs())
1153 .filter(|_| close);
1154 self.last = Some((offset, error));
1155 self.closed |= earlier.is_some();
1156 earlier
1157 }
1158
1159 fn cleared(&mut self) {
1161 self.last = None;
1162 }
1163}
1164
1165pub(crate) fn below_tolerance_refusal_enabled() -> bool {
1180 crate::switch!("BREP_BELOW_TOLERANCE_REFUSAL", true)
1181}
1182
1183const BELOW_TOLERANCE_BAND: f64 = 10.0 * crate::tolerance::WELD_FLOOR;
1186
1187pub(crate) fn unresolved_merge_refusal_enabled() -> bool {
1197 crate::switch!("BREP_UNRESOLVED_MERGE_REFUSAL", false)
1198}
1199
1200fn unresolved_merge_refusal(first: &BrepSolid, second: &BrepSolid) -> Option<KernelRefusal> {
1201 let (lower, upper) = (crate::tolerance::COINCIDENCE_DISTANCE_FLOOR, crate::tolerance::WELD_FLOOR);
1202 let (face_a, face_b, separation) = planar_faces_apart_within(first, second, lower, upper)?;
1203 Some(KernelRefusal::unsupported(
1204 KernelStage::Intersect,
1205 "below_modelling_tolerance",
1206 format!(
1207 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1208 another, {separation:.3e} apart at most over their shared extent: farther than a coincidence \
1209 ({lower:.0e}) and closer than the kernel resolves ({upper:.0e}), so the step between them would be \
1210 welded away"
1211 ),
1212 ))
1213}
1214
1215fn below_tolerance_refusal(first: &BrepSolid, second: &BrepSolid, error: Option<&KernelRefusal>) -> Option<KernelRefusal> {
1216 let (face_a, face_b, separation) = near_coincident_planar_faces(first, second)?;
1217 let message = format!(
1218 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1219 another, {separation:.3e} apart at most over their shared extent: the slivers between them are below the \
1220 modelling tolerance ({BELOW_TOLERANCE_BAND:.0e}), so the kernel cannot resolve them{}",
1221 error.map(|error| format!(" (the exact arrangement said: {})", error.message.chars().take(160).collect::<String>())).unwrap_or_default()
1222 );
1223 Some(KernelRefusal::unsupported(KernelStage::Intersect, "below_modelling_tolerance", message))
1224}
1225
1226fn near_coincident_planar_faces(first: &BrepSolid, second: &BrepSolid) -> Option<(u64, u64, f64)> {
1230 let scale = crate::tolerance::solid_scale(first).max(crate::tolerance::solid_scale(second)).max(1.0);
1231 planar_faces_apart_within(first, second, 1e-9 * scale, BELOW_TOLERANCE_BAND)
1232}
1233
1234fn planar_faces_apart_within(first: &BrepSolid, second: &BrepSolid, lower: f64, upper: f64) -> Option<(u64, u64, f64)> {
1238 struct Planar {
1239 id: u64,
1240 origin: Vec3,
1241 normal: Vec3,
1242 corners: Vec<Vec3>,
1243 bounds: crate::spatial::Aabb,
1244 }
1245 let read = |solid: &BrepSolid| -> Vec<Planar> {
1246 let at = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1247 solid
1248 .shells
1249 .iter()
1250 .flat_map(|shell| &shell.faces)
1251 .filter_map(|face| {
1252 if !face.surface.is_affine().ok()? {
1253 return None;
1254 }
1255 let origin = face.surface.control_points[0][0].point().ok()?;
1256 let a = face.surface.control_points[1][0].point().ok()?.sub(origin);
1257 let b = face.surface.control_points[0][1].point().ok()?.sub(origin);
1258 let normal = a.cross(b).normalized().ok()?;
1259 let corners: Vec<Vec3> = face
1260 .loops
1261 .iter()
1262 .flat_map(|lp| &lp.coedges)
1263 .filter_map(|coedge| solid.edges.iter().find(|edge| edge.id == coedge.edge_id))
1264 .flat_map(|edge| [at(edge.start_vertex_id), at(edge.end_vertex_id)])
1265 .flatten()
1266 .collect();
1267 if corners.is_empty() {
1268 return None;
1269 }
1270 let bounds = crate::spatial::Aabb::from_points(corners.clone());
1271 Some(Planar { id: face.id, origin, normal, corners, bounds })
1272 })
1273 .collect()
1274 };
1275 let (faces_a, faces_b) = (read(first), read(second));
1276 for a in &faces_a {
1277 for b in &faces_b {
1278 if a.normal.cross(b.normal).length() > 1e-3 {
1279 continue;
1280 }
1281 if !a.bounds.intersects(b.bounds, upper) {
1282 continue;
1283 }
1284 let separation = a
1285 .corners
1286 .iter()
1287 .map(|corner| corner.sub(b.origin).dot(b.normal).abs())
1288 .chain(b.corners.iter().map(|corner| corner.sub(a.origin).dot(a.normal).abs()))
1289 .fold(0.0f64, f64::max);
1290 if separation > lower && separation <= upper {
1291 return Some((a.id, b.id, separation));
1292 }
1293 }
1294 }
1295 None
1296}
1297
1298fn one_use_edges(solid: &BrepSolid) -> usize {
1299 let mut uses: HashMap<u64, usize> = HashMap::default();
1300 for coedge in solid
1301 .shells
1302 .iter()
1303 .flat_map(|shell| &shell.faces)
1304 .flat_map(|face| &face.loops)
1305 .flat_map(|loop_record| &loop_record.coedges)
1306 {
1307 *uses.entry(coedge.edge_id).or_default() += 1;
1308 }
1309 solid
1310 .edges
1311 .iter()
1312 .filter(|edge| !edge.degenerate && uses.get(&edge.id) == Some(&1))
1313 .count()
1314}
1315
1316fn body_volume(solid: &BrepSolid) -> Option<f64> {
1318 if solid.shells.is_empty() {
1319 return Some(0.0);
1320 }
1321 solid_signed_volume(solid).ok().map(f64::abs)
1322}
1323
1324struct InclusionExclusion {
1327 formula: &'static str,
1330 reading: &'static str,
1332 read: f64,
1334 expected: f64,
1336}
1337
1338fn inclusion_exclusion_volume(
1349 first: &BrepSolid,
1350 second: &BrepSolid,
1351 operation: BooleanOperation,
1352 options: &BooleanOptions,
1353 va: Option<f64>,
1354 vb: Option<f64>,
1355 own_first: bool,
1356) -> Option<InclusionExclusion> {
1357 use BooleanOperation::{Intersect, Subtract, Union};
1358 let (va, vb) = (va?, vb?);
1359 let own = match operation {
1360 Intersect => (Intersect, false, "first ∩ second"),
1361 Union => (Union, false, "first ∪ second"),
1362 Subtract => (Subtract, false, "first − second"),
1363 };
1364 let readings = [
1365 (Intersect, false, "first ∩ second"),
1366 (Intersect, true, "second ∩ first"),
1367 (Union, false, "first ∪ second"),
1368 (Union, true, "second ∪ first"),
1369 (Subtract, false, "first − second"),
1370 (Subtract, true, "second − first"),
1371 ];
1372 let own_reading = own_first.then_some(own);
1373 let leading = usize::from(own_first);
1374 for (index, (other, swapped, reading)) in own_reading.into_iter().chain(readings).enumerate() {
1375 if index >= leading && !swapped && std::mem::discriminant(&other) == std::mem::discriminant(&operation) {
1376 continue;
1377 }
1378 let (x, y) = if swapped { (second, first) } else { (first, second) };
1379 let Some(read) = boolean_operation_with_diagnostics(x, y, other, options)
1380 .ok()
1381 .and_then(|outcome| body_volume(&outcome.value))
1382 else {
1383 continue;
1384 };
1385 let intersection = match (other, swapped) {
1386 (Intersect, _) => read,
1387 (Union, _) => va + vb - read,
1388 (Subtract, false) => va - read,
1389 (Subtract, true) => vb - read,
1390 };
1391 let (formula, expected) = match operation {
1392 Intersect => ("V(first ∩ second)", intersection),
1393 Union => ("V(first) + V(second) − V(first ∩ second)", va + vb - intersection),
1394 Subtract => ("V(first) − V(first ∩ second)", va - intersection),
1395 };
1396 return Some(InclusionExclusion { formula, reading, read, expected });
1397 }
1398 None
1399}
1400
1401fn planar_operand_off_its_plane(
1410 first: &BrepSolid,
1411 second: &BrepSolid,
1412 options: &BooleanOptions,
1413) -> Option<(u8, u64, f64, f64)> {
1414 let policy = options
1415 .tolerances
1416 .clone()
1417 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
1418 let weld = crate::tolerance::assembler_weld(policy.model);
1419 let mut worst: Option<(u8, u64, f64)> = None;
1420 for (operand, solid) in [(0u8, first), (1u8, second)] {
1421 let vertex_point = |id: u64| solid.vertices.iter().find(|v| v.id == id).map(|v| v.point);
1422 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
1423 let Some(crate::AnalyticSurface::Plane {
1424 origin,
1425 u_dir,
1426 v_dir,
1427 ..
1428 }) = face.surface.analytic()
1429 else {
1430 continue;
1431 };
1432 let [loop_record] = face.loops.as_slice() else {
1433 continue;
1434 };
1435 let Ok(normal) = u_dir.cross(*v_dir).normalized() else {
1436 continue;
1437 };
1438 let mut off_plane = 0.0f64;
1439 let mut straight = true;
1440 for coedge in &loop_record.coedges {
1441 let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else {
1442 straight = false;
1443 break;
1444 };
1445 let (Some(start), Some(end)) =
1446 (vertex_point(edge.start_vertex_id), vertex_point(edge.end_vertex_id))
1447 else {
1448 straight = false;
1449 break;
1450 };
1451 let chord = end.sub(start);
1452 let length = chord.length();
1453 if edge.degenerate || length <= weld {
1454 straight = false;
1455 break;
1456 }
1457 let direction = chord.scale(1.0 / length);
1458 for fraction in [0.25, 0.5, 0.75] {
1459 let Ok(point) = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction) else {
1460 straight = false;
1461 break;
1462 };
1463 let delta = point.sub(start);
1464 let along = delta.dot(direction);
1465 if delta.sub(direction.scale(along)).length() > weld
1466 || along < -weld
1467 || along > length + weld
1468 {
1469 straight = false;
1470 break;
1471 }
1472 }
1473 if !straight {
1474 break;
1475 }
1476 off_plane = off_plane.max(start.sub(*origin).dot(normal).abs());
1477 }
1478 if straight && off_plane > weld && worst.is_none_or(|(_, _, gap)| off_plane > gap) {
1479 worst = Some((operand, face.id, off_plane));
1480 }
1481 }
1482 }
1483 worst.map(|(operand, face_id, gap)| (operand, face_id, gap, weld))
1484}
1485
1486fn volume_within_csg_bounds(operation: BooleanOperation, va: f64, vb: f64, vr: f64) -> bool {
1489 let slack = 1e-2 * (va + vb).max(1.0);
1490 match operation {
1491 BooleanOperation::Union => vr >= va.max(vb) - slack && vr <= va + vb + slack,
1493 BooleanOperation::Subtract => vr <= va + slack && vr >= -slack,
1495 BooleanOperation::Intersect => vr <= va.min(vb) + slack && vr >= -slack,
1497 }
1498}
1499
1500fn reverse_fragment(fragment: &mut FaceFragmentRecord) -> Result<(), KernelRefusal> {
1527 fragment.same_sense = !fragment.same_sense;
1528 for loop_record in &mut fragment.loops {
1529 loop_record.coedges.reverse();
1530 for coedge in &mut loop_record.coedges {
1531 coedge.forward = !coedge.forward;
1532 coedge.pcurve = coedge.pcurve.reversed().or_refuse(KernelStage::Validate, "reversed")?;
1533 }
1534 }
1535 Ok(())
1536}
1537
1538fn build_nary_imprint(
1545 operands: &[BrepSolid],
1546 options: &ImprintOptions,
1547) -> Result<ImprintResultRecord, KernelRefusal> {
1548 let mut section_evidence = false;
1549 let mut vertices: Vec<ImprintVertex> = Vec::new();
1550 let mut pieces: Vec<ImprintPieceRecord> = Vec::new();
1551 let mut by_face: HashMap<(u8, u64), Vec<u64>> = HashMap::default();
1552 let mut edge_splits: HashMap<(u8, u64), Vec<f64>> = HashMap::default();
1553 let mut next_vertex_id: u64 = 1;
1554 let mut next_piece_id: u64 = 1;
1555
1556 for i in 0..operands.len() {
1557 for j in (i + 1)..operands.len() {
1558 let pair = build_imprints(&operands[i], &operands[j], options)?;
1559 let remap = |operand: u8| -> u8 {
1560 if operand == 0 {
1561 i as u8
1562 } else {
1563 j as u8
1564 }
1565 };
1566
1567 section_evidence = section_evidence || pair.section_evidence;
1568 let mut vertex_map: HashMap<u64, u64> = HashMap::default();
1569 for vertex in &pair.vertices {
1570 let global = next_vertex_id;
1571 next_vertex_id += 1;
1572 vertex_map.insert(vertex.id, global);
1573 vertices.push(ImprintVertex {
1574 id: global,
1575 point: vertex.point,
1576 });
1577 }
1578
1579 let mut piece_map: HashMap<u64, u64> = HashMap::default();
1580 for piece in &pair.pieces {
1581 let global = next_piece_id;
1582 next_piece_id += 1;
1583 piece_map.insert(piece.id, global);
1584 let mut mapped = piece.clone();
1585 mapped.id = global;
1586 mapped.start_vertex_id = *vertex_map
1587 .get(&piece.start_vertex_id)
1588 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
1589 mapped.end_vertex_id = *vertex_map
1590 .get(&piece.end_vertex_id)
1591 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
1592 for pcurve in &mut mapped.pcurves {
1593 pcurve.operand = remap(pcurve.operand);
1594 }
1595 mapped.support_faces = [
1596 FaceKey {
1597 operand: remap(piece.support_faces[0].operand),
1598 face_id: piece.support_faces[0].face_id,
1599 },
1600 FaceKey {
1601 operand: remap(piece.support_faces[1].operand),
1602 face_id: piece.support_faces[1].face_id,
1603 },
1604 ];
1605 pieces.push(mapped);
1606 }
1607
1608 for entry in &pair.by_face {
1609 let list = by_face
1610 .entry((remap(entry.operand), entry.face_id))
1611 .or_default();
1612 for piece_id in &entry.piece_ids {
1613 let global = *piece_map.get(piece_id).ok_or_else(|| {
1614 KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: by_face references unknown piece")
1615 })?;
1616 list.push(global);
1617 }
1618 }
1619
1620 for split in &pair.edge_splits {
1621 edge_splits
1622 .entry((remap(split.operand), split.edge_id))
1623 .or_default()
1624 .extend(split.parameters.iter().copied());
1625 }
1626 }
1627 }
1628
1629 Ok(ImprintResultRecord {
1630 vertices,
1631 pieces,
1632 tangent_nodes: Vec::new(),
1633 barrier_edges: Vec::new(),
1634 section_evidence,
1635 cosurface_pairs: Vec::new(),
1636 tangent_sections: Vec::new(),
1637 by_face: by_face
1638 .into_iter()
1639 .map(|((operand, face_id), piece_ids)| FaceImprints {
1640 operand,
1641 face_id,
1642 piece_ids,
1643 })
1644 .collect(),
1645 edge_splits: edge_splits
1646 .into_iter()
1647 .map(|((operand, edge_id), parameters)| EdgeSplitRecord {
1648 operand,
1649 edge_id,
1650 parameters,
1651 })
1652 .collect(),
1653 })
1654}
1655
1656pub fn boolean_operation_nary(
1667 operands: &[BrepSolid],
1668 operation: BooleanOperation,
1669) -> Result<BrepSolid, KernelRefusal> {
1670 boolean_operation_nary_with_options(operands, operation, &BooleanOptions::default())
1671}
1672
1673pub fn boolean_operation_nary_with_options(
1679 operands: &[BrepSolid],
1680 operation: BooleanOperation,
1681 options: &BooleanOptions,
1682) -> Result<BrepSolid, KernelRefusal> {
1683 if operands.len() > 1 {
1684 if let Some(scaled) = WorkingScale::of(&operands.iter().collect::<Vec<_>>(), options)? {
1685 return boolean_operation_nary_with_options(&scaled.solids, operation, &scaled.options)
1686 .map_err(|error| scaled.refusal(error))
1687 .and_then(|solid| scaled.back(&solid));
1688 }
1689 }
1690 if operands.is_empty() {
1691 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: no operands provided"));
1692 }
1693 if operands.len() == 1 {
1694 return Ok(operands[0].clone());
1695 }
1696 if operands.len() > 255 {
1697 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: at most 255 operands supported"));
1698 }
1699 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
1700
1701 let mut policy = KernelTolerances::for_solid(&operands[0], options.tolerance);
1705 for operand in &operands[1..] {
1706 let candidate = KernelTolerances::for_solid(operand, options.tolerance);
1707 if candidate.sew_search > policy.sew_search {
1708 policy = candidate;
1709 }
1710 }
1711 policy.check().or_input(KernelStage::Collect, "tolerances")?;
1712 let tolerance = policy.model;
1713
1714 let mut healed = operands.to_vec();
1717 for operand in &mut healed {
1718 crate::heal::heal_operands(operand, &policy)?;
1719 crate::heal::refit_inherited_trims(operand, &policy)?;
1722 normalize_operand_band_seams(operand)?;
1725 }
1726
1727 let mut imprint_options = options.imprint.clone();
1729 imprint_options.tolerance = tolerance;
1730 let imprint = build_nary_imprint(&healed, &imprint_options)?;
1731
1732 let mut split = Vec::with_capacity(healed.len());
1734 for (index, operand) in healed.iter().enumerate() {
1735 split.push(apply_edge_splits(operand, index as u8, &imprint)?);
1736 }
1737 let mut fragments = Vec::with_capacity(split.len());
1738 for (index, solid) in split.iter().enumerate() {
1739 fragments.push(fragment_solid(solid, index as u8, &imprint)?);
1740 }
1741
1742 let selected = select_fragments_nary(&fragments, &healed, operation, tolerance, debug)?;
1744
1745 let solids: HashMap<u8, &BrepSolid> = split
1747 .iter()
1748 .enumerate()
1749 .map(|(index, solid)| (index as u8, solid))
1750 .collect();
1751 let solid = assemble_fragments(selected, &solids, &imprint, tolerance)?;
1752 let solid = if options.merge_coplanar_faces
1753 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
1754 {
1755 let merged = merge_same_surface_faces_excluding(
1756 &solid,
1757 tolerance,
1758 &options.keep_unmerged_name_substrs,
1759 )?;
1760 merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?
1761 } else {
1762 solid
1763 };
1764 let validation = solid.validate_detailed(&policy);
1765 if !validation.issues.is_empty() {
1766 return Err(KernelRefusal::new(
1767 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
1768 KernelStage::Validate,
1769 format!(
1770 "boolean_operation_nary: invalid result: {:?}",
1771 validation.issues
1772 )));
1773 }
1774 if debug {
1775 if let Ok(report) =
1776 crate::oracle::boolean_semantic_disagreement_nary(&healed, operation, &solid, 300)
1777 {
1778 if report.is_flagged() {
1779 eprintln!(
1780 "[oracle] n-ary semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
1781 report.disagreement_rate,
1782 report.disagreements.len(),
1783 report.considered,
1784 report.sample_disagreement()
1785 );
1786 }
1787 }
1788 }
1789 Ok(solid)
1790}
1791
1792fn attribute_to_tangent_node(error: KernelRefusal, nodes: &[Vec3]) -> KernelRefusal {
1823 let Some(node) = nodes.first() else {
1824 return error;
1825 };
1826 if !error.class.perturbation_eligible()
1827 || matches!(error.class, RefusalClass::TangentNodeSingularity)
1828 {
1829 return error;
1830 }
1831 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
1832 eprintln!(
1833 "boolean: tear downstream of the tangent node at ({:.6},{:.6},{:.6}) attributed to it; the stage read: {}",
1834 node.x, node.y, node.z, error.message
1835 );
1836 }
1837 KernelRefusal::new(
1838 RefusalClass::TangentNodeSingularity,
1839 error.stage,
1840 format!(
1841 "boolean: unsupported singular/tangent-node surface intersection \
1842 at the tangent node at ({:.6},{:.6},{:.6}): the section through it did not \
1843 assemble into a closed shell",
1844 node.x, node.y, node.z
1845 ),
1846 )
1847}
1848
1849fn attribute_to_tangent_section(
1871 error: KernelRefusal,
1872 sections: &[crate::imprint::TangentSectionRecord],
1873 origins: &[FaceKey],
1874) -> KernelRefusal {
1875 if sections.is_empty()
1876 || !error.class.perturbation_eligible()
1877 || matches!(error.class, RefusalClass::TangentNodeSingularity)
1878 {
1879 return error;
1880 }
1881 let named = refusal_result_faces(&error.message)
1882 .into_iter()
1883 .filter_map(|id| origins.get(id.checked_sub(1)? as usize).copied())
1884 .collect::<Vec<FaceKey>>();
1885 let involving = |fallback: bool| {
1889 sections.iter().find(|section| {
1890 section.grazing.is_empty() != fallback && named.iter().any(|face| section.faces.contains(face))
1891 })
1892 };
1893 let Some(section) = involving(false).or_else(|| involving(true)) else {
1894 return error;
1895 };
1896 let at = |point: Vec3| {
1899 let shown = |value: f64| if value.abs() < 5e-7 { 0.0 } else { value };
1900 format!("({:.6},{:.6},{:.6})", shown(point.x), shown(point.y), shown(point.z))
1901 };
1902 let pierces = (!section.grazing.is_empty()).then(|| {
1908 let shown = section.grazing.len().min(4);
1909 let mut listed = section.grazing[..shown]
1910 .iter()
1911 .map(|(point, tangency)| format!("{} at |tan·n| = {tangency:.4}", at(*point)))
1912 .collect::<Vec<_>>()
1913 .join(", ");
1914 if section.grazing.len() > shown {
1915 listed.push_str(&format!(" and {} more", section.grazing.len() - shown));
1916 }
1917 listed
1918 });
1919 let pierce_only = section.pierce_only();
1920 let shape = if let (true, Some(pierces)) = (pierce_only, pierces.as_deref()) {
1921 format!(
1922 "cross at a grazing angle: a trim edge pierces the other carrier inside both \
1923 trims at {pierces}, below the marcher's start gate, and no transverse section was \
1924 marched between the pierces — a near-tangent crossing born on a tangent contact \
1925 (a third-order singularity) the imprint does not build yet"
1926 )
1927 } else if section.planar {
1928 format!(
1929 "touch along a tangent curve from {} to {} (length {:.6}, {} stations{}) which the \
1930 imprint does not build yet",
1931 at(section.start),
1932 at(section.end),
1933 section.length,
1934 section.stations,
1935 if section.closed { ", closed" } else { "" }
1936 )
1937 } else {
1938 format!(
1939 "touch along a curve through {} with neither carrier planar, a curved/curved \
1940 tangent contact the lane does not trace yet",
1941 at(section.start)
1942 )
1943 };
1944 let shape = match (pierce_only, pierces) {
1945 (false, Some(pierces)) => format!(
1946 "{shape}; a trim edge also pierces the other carrier inside both trims at {pierces}, \
1947 below the marcher's start gate, with no transverse section marched"
1948 ),
1949 _ => shape,
1950 };
1951 let involved = named
1952 .iter()
1953 .filter(|face| section.faces.contains(face))
1954 .map(|face| format!("{}/{}", face.operand, face.face_id))
1955 .collect::<Vec<_>>()
1956 .join(", ");
1957 KernelRefusal::new(
1958 RefusalClass::TangentNodeSingularity,
1959 error.stage,
1960 format!(
1961 "boolean: unsupported tangent-curve surface intersection between faces {}/{} and {}/{}: \
1962 the carriers {shape}; the refusal names face(s) {involved} the contact involves; {}",
1963 section.first.operand, section.first.face_id, section.second.operand, section.second.face_id,
1964 error.message
1965 ),
1966 )
1967}
1968
1969fn refusal_result_faces(message: &str) -> Vec<u64> {
1974 let mut ids = Vec::new();
1975 let digits_after = |text: &str| -> Option<u64> {
1976 let end = text.find(|c: char| !c.is_ascii_digit()).unwrap_or(text.len());
1977 text[..end].parse().ok()
1978 };
1979 for (index, _) in message.match_indices("face ") {
1980 if let Some(id) = digits_after(&message[index + "face ".len()..]) {
1981 ids.push(id);
1982 }
1983 }
1984 if let Some(start) = message.find("on faces [") {
1985 let rest = &message[start + "on faces [".len()..];
1986 let list = &rest[..rest.find(']').unwrap_or(rest.len())];
1987 for entry in list.split(", ") {
1988 let entry = entry.trim_start();
1989 if let Some(id) = digits_after(entry) {
1990 if entry[id.to_string().len()..].starts_with(" '") {
1991 ids.push(id);
1992 }
1993 }
1994 }
1995 }
1996 ids.sort_unstable();
1997 ids.dedup();
1998 ids
1999}
2000
2001pub fn boolean_operation_with_diagnostics(
2002 first: &BrepSolid,
2003 second: &BrepSolid,
2004 operation: BooleanOperation,
2005 options: &BooleanOptions,
2006) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2007 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2008 let mut outcome = boolean_operation_with_diagnostics(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
2009 .map_err(|error| scaled.refusal(error))?;
2010 outcome.value = scaled.back(&outcome.value)?;
2011 outcome.diagnostics.count_n("working_scale.fired", 1);
2012 outcome.diagnostics.measure_max("working_scale.factor", scaled.factor);
2013 return Ok(outcome);
2014 }
2015 let _account = profile::Scope::new("boolean.other");
2016 let closed_inputs = matches!(std::env::var("BREP_CLOSED_OPERAND_INPUT").as_deref(), Err(_) | Ok("1") | Ok("on"));
2017 if let (true, Some(later)) = (reseat::seam_reseat_enabled(), &options.seam_reseat_later_references) {
2018 let started = Instant::now();
2019 let (first, second) = reseat::reseat_tangent_seams(first, second, later, options.tolerance);
2020 profile_stage("seam_prepare_ms", started.elapsed().as_secs_f64() * 1000.0);
2021 return boolean_operation_with_diagnostics_impl(&first, &second, operation, options, closed_inputs);
2022 }
2023 boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs)
2024}
2025
2026fn boolean_operation_with_diagnostics_impl(
2027 first: &BrepSolid,
2028 second: &BrepSolid,
2029 operation: BooleanOperation,
2030 options: &BooleanOptions,
2031 closed_inputs: bool,
2032) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2033 let _coedge_memo = crate::topology::CoedgeMemoScope::open(crate::topology::coedge_memo_enabled());
2036 if matches!(operation, BooleanOperation::Intersect)
2039 && [first, second].iter().any(|body| body.kind == crate::BodyKind::Sheet)
2040 && match std::env::var("BREP_SHEET_TRIM").as_deref() {
2041 Ok("1") => true,
2042 Ok("0") => false,
2043 _ => options.sheet_trim,
2044 }
2045 {
2046 return sheet::trim(first, second, options);
2047 }
2048 if matches!(operation, BooleanOperation::Union | BooleanOperation::Subtract) {
2057 if let Some(operand) = [first, second]
2058 .iter()
2059 .position(|solid| solid.kind == crate::BodyKind::Sheet)
2060 {
2061 return Err(KernelRefusal::input(
2062 KernelStage::Collect,
2063 "sheet_operand",
2064 format!(
2065 "boolean: operand {operand} is a Sheet, which encloses no solid; union and \
2066 subtract of a sheet are refused; Intersect trims a Sheet by a Solid"
2067 ),
2068 ));
2069 }
2070 }
2071 let mut outcome = boolean_operation_with_diagnostics_core(first, second, operation, options)?;
2077 let closure_started = closed_inputs.then(Instant::now);
2078 if closed_inputs {
2079 for (operand, solid) in [first, second].into_iter().enumerate() {
2080 let open = one_use_edges(solid);
2081 if open > 0 {
2082 return Err(KernelRefusal::input(KernelStage::Collect, "operand_closure", format!(
2083 "boolean: operand {operand} is not a closed shell: {open} of its edges bound only one face, so its inside is undefined"
2084 )));
2085 }
2086 }
2087 }
2088 if let Some(started) = closure_started {
2089 let ms = started.elapsed().as_secs_f64() * 1000.0;
2090 profile_stage("operand_closure_ms", ms);
2091 outcome.diagnostics.measure_max("timing.operand_closure_ms", ms);
2092 }
2093 Ok(outcome)
2094}
2095
2096fn boolean_operation_with_diagnostics_core(
2097 first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions,
2098) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2099
2100 if let Some(offset) = crate::recentre::control_offset_at_entry() {
2103 return boolean_operation_with_diagnostics_at_offset(first, second, operation, options, offset);
2104 }
2105 let mut bounds = operand_bounds(first);
2108 bounds.include(operand_bounds(second));
2109 if let Some(offset) = crate::recentre::guard_offset(bounds) {
2110 crate::recentre::profile_fired("boolean", offset, bounds);
2111 let mut outcome = boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Guard)?;
2112 outcome.diagnostics.count_n("recentre.fired", 1);
2113 outcome.diagnostics.measure_max("recentre.distance", offset.length());
2114 return Ok(outcome);
2115 }
2116 let mut tangent_nodes = Vec::new();
2117 let (mut outcome, soundness_candidates) =
2118 boolean_pipeline(first, second, operation, options, &mut tangent_nodes)
2119 .map_err(|error| attribute_to_tangent_node(error, &tangent_nodes))?;
2120 let stage_started = Instant::now();
2133 let accepted = match &soundness_candidates {
2134 Some(candidates) => crate::accept_sound_against_scoped(&[first, second], outcome.value, "boolean", candidates),
2137 None => crate::accept_sound_against(&[first, second], outcome.value, "boolean"),
2138 };
2139 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2140 profile_stage("soundness_ms", stage_ms);
2141 outcome.diagnostics.measure_max("timing.soundness_ms", stage_ms);
2142 outcome.value = accepted?;
2143 Ok(outcome)
2144}
2145
2146pub fn boolean_operation_with_diagnostics_at_offset(
2150 first: &BrepSolid,
2151 second: &BrepSolid,
2152 operation: BooleanOperation,
2153 options: &BooleanOptions,
2154 offset: Vec3,
2155) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2156 boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Control)
2157}
2158
2159fn boolean_translated(
2161 first: &BrepSolid,
2162 second: &BrepSolid,
2163 operation: BooleanOperation,
2164 options: &BooleanOptions,
2165 offset: Vec3,
2166 kind: crate::recentre::EntryKind,
2167) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2168 let _entry = crate::recentre::TranslatedEntry::open(kind);
2169 let translate = |solid: &BrepSolid, offset: Vec3| {
2170 crate::recentre::translate_solid(solid, offset).map_err(|message| {
2171 KernelRefusal::internal(
2172 KernelStage::Collect,
2173 "translation_control",
2174 format!("boolean: the translation control could not move an operand: {message}"),
2175 )
2176 })
2177 };
2178 let moved_first = translate(first, offset)?;
2179 let moved_second = translate(second, offset)?;
2180 let outcome = boolean_operation_with_diagnostics(&moved_first, &moved_second, operation, options)?;
2181 let value = translate(&outcome.value, offset.scale(-1.0))?;
2182 Ok(KernelOutcome { value, diagnostics: outcome.diagnostics })
2183}
2184
2185fn profile_stage(code: &str, ms: f64) {
2189 let row = match code {
2190 "heal_ms" => Some("boolean.operand_prepare"),
2191 "imprint_ms" => Some("boolean.imprint"),
2192 "edge_split_ms" => Some("boolean.edge_split"),
2193 "fragment_ms" => Some("boolean.fragment"),
2194 "select_ms" => Some("boolean.select"),
2195 "assemble_ms" => Some("boolean.assemble"),
2196 "face_merge_ms" => Some("boolean.face_merge"),
2197 "soundness_ms" => Some("boolean.soundness"),
2198 "operand_closure_ms" => Some("boolean.operand_closure"),
2199 "seam_prepare_ms" => Some("boolean.seam_prepare"),
2200 "final_validate_ms" => Some("boolean.final_validate"),
2201 _ => None,
2202 };
2203 if let Some(row) = row { profile::record(row, ms); }
2204 if crate::profile::profile_enabled() {
2205 profile_line!("boolean.{code}={ms:.2}");
2206 }
2207}
2208
2209struct BooleanStageDump {
2214 directory: std::path::PathBuf,
2215 serial: usize,
2216}
2217
2218impl BooleanStageDump {
2219 fn open() -> Option<Self> {
2220 static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2221 let directory = std::env::var("BREP_BOOLEAN_DUMP").ok().filter(|value| !value.is_empty())?;
2222 let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2223 Some(Self { directory: directory.into(), serial })
2224 }
2225
2226 fn write<T: Serialize + ?Sized>(&self, stage: &str, value: &T) {
2227 let path = self.directory.join(format!("{:03}-{stage}.json", self.serial));
2228 match serde_json::to_string(value) {
2229 Ok(text) => {
2230 if let Err(error) = std::fs::write(&path, text) {
2231 eprintln!("BREP_BOOLEAN_DUMP {}: {error}", path.display());
2232 }
2233 }
2234 Err(error) => eprintln!("BREP_BOOLEAN_DUMP {stage}: {error}"),
2235 }
2236 }
2237}
2238
2239fn boolean_policy(
2241 first: &BrepSolid,
2242 second: &BrepSolid,
2243 options: &BooleanOptions,
2244) -> Result<KernelTolerances, KernelRefusal> {
2245 let policy = options
2246 .tolerances
2247 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
2248 policy.check().or_input(KernelStage::Collect, "tolerances")?;
2249 Ok(policy)
2250}
2251
2252fn prepared_operands(
2255 first: &BrepSolid,
2256 second: &BrepSolid,
2257 policy: &KernelTolerances,
2258) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
2259 let stage_started = Instant::now();
2268 let mut first_owned = first.clone();
2269 let mut second_owned = second.clone();
2270 crate::heal::heal_operands(&mut first_owned, policy)?;
2271 crate::heal::heal_operands(&mut second_owned, policy)?;
2272 profile_stage("heal.operands_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
2273 let refit_started = Instant::now();
2277 crate::heal::refit_inherited_trims(&mut first_owned, policy)?;
2278 crate::heal::refit_inherited_trims(&mut second_owned, policy)?;
2279 profile_stage("heal.refit_ms", refit_started.elapsed().as_secs_f64() * 1_000.0);
2280 if crate::profile::profile_enabled() {
2281 let (hits, misses) = crate::reading_memo::counts();
2282 profile_line!("boolean.reading_memo hits={hits} misses={misses}");
2283 }
2284 profile_stage("heal_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
2285 normalize_operand_band_seams(&mut first_owned)?;
2290 normalize_operand_band_seams(&mut second_owned)?;
2291 Ok((first_owned, second_owned))
2292}
2293
2294fn boolean_imprint_options(options: &BooleanOptions, tolerance: f64) -> ImprintOptions {
2295 let mut imprint_options = options.imprint.clone();
2296 imprint_options.tolerance = tolerance;
2297 imprint_options
2298}
2299
2300pub fn boolean_split_operands(
2310 first: &BrepSolid,
2311 second: &BrepSolid,
2312 options: &BooleanOptions,
2313) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
2314 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2315 let (split_first, split_second) = boolean_split_operands(&scaled.solids[0], &scaled.solids[1], &scaled.options)
2316 .map_err(|error| scaled.refusal(error))?;
2317 return Ok((scaled.back(&split_first)?, scaled.back(&split_second)?));
2318 }
2319 let policy = boolean_policy(first, second, options)?;
2320 let (first, second) = prepared_operands(first, second, &policy)?;
2321 let imprint = build_imprints(&first, &second, &boolean_imprint_options(options, policy.model))?;
2322 let (split_first, _) = apply_edge_splits_with_map(&first, 0, &imprint)?;
2323 let (split_second, _) = apply_edge_splits_with_map(&second, 1, &imprint)?;
2324 Ok((split_first, split_second))
2325}
2326
2327fn operand_bounds(solid: &BrepSolid) -> crate::Aabb {
2331 let mut bounds = crate::Aabb::from_points(solid.vertices.iter().map(|vertex| vertex.point));
2332 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2333 match crate::Aabb::from_surface_controls(&face.surface) {
2334 Ok(face_bounds) => bounds.include(face_bounds),
2335 Err(_) => {
2336 return crate::Aabb {
2337 minimum: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
2338 maximum: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
2339 }
2340 }
2341 }
2342 }
2343 bounds
2344}
2345
2346fn line_or_point_contact(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
2352 apart_axes(bounds) >= 2 && plain_hull_solid(first) && plain_hull_solid(second)
2353}
2354
2355fn boxes_share_no_interior(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
2358 apart_axes(bounds) >= 1 && plain_hull_solid(first) && plain_hull_solid(second)
2359}
2360
2361fn apart_axes([a, b]: [crate::Aabb; 2]) -> usize {
2363 let apart = |a_min: f64, a_max: f64, b_min: f64, b_max: f64| a_max <= b_min || b_max <= a_min;
2364 [
2365 apart(a.minimum.x, a.maximum.x, b.minimum.x, b.maximum.x),
2366 apart(a.minimum.y, a.maximum.y, b.minimum.y, b.maximum.y),
2367 apart(a.minimum.z, a.maximum.z, b.minimum.z, b.maximum.z),
2368 ]
2369 .into_iter()
2370 .filter(|&apart| apart)
2371 .count()
2372}
2373
2374fn plain_hull_solid(solid: &BrepSolid) -> bool {
2376 solid.kind == crate::BodyKind::Solid
2377 && solid.cells.is_empty()
2378 && solid.shells.iter().flat_map(|shell| &shell.faces).all(|face| {
2379 face.surface.control_points.iter().flatten().all(|control| control.w > 0.0 && control.w.is_finite())
2380 })
2381}
2382
2383fn soundness_candidates(
2388 solid: &BrepSolid,
2389 scope: &AssemblyScope,
2390 bounds: [crate::Aabb; 2],
2391 band: f64,
2392) -> HashSet<u64> {
2393 let mut candidates = HashSet::default();
2394 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2395 if scope.examined.contains(&face.id) {
2396 candidates.insert(face.id);
2397 continue;
2398 }
2399 let Some(&operand) = scope.operand_of.get(&face.id) else {
2400 candidates.insert(face.id);
2401 continue;
2402 };
2403 let other = bounds[usize::from(operand == 0)];
2404 match crate::Aabb::from_surface_controls(&face.surface) {
2405 Ok(face_bounds) if !face_bounds.intersects(other, band) => {}
2406 _ => {
2407 candidates.insert(face.id);
2408 }
2409 }
2410 }
2411 candidates
2412}
2413
2414fn empty_solid() -> BrepSolid {
2416 BrepSolid {
2417 mass_properties_cache: Default::default(),
2418 cells: Default::default(),
2419 id: 0,
2420 vertices: Vec::new(),
2421 edges: Vec::new(),
2422 shells: Vec::new(),
2423 genus: 0,
2424 kind: crate::BodyKind::Solid,
2425 }
2426}
2427
2428fn concatenate_disjoint(first: &BrepSolid, second: &BrepSolid) -> BrepSolid {
2434 let mut vertices = Vec::new();
2435 let mut edges = Vec::new();
2436 let mut shells = Vec::new();
2437 let mut used_face_names = HashSet::<String>::default();
2438 let (mut next_face_id, mut next_loop_id, mut next_coedge_id) = (1u64, 1u64, 1u64);
2439 for operand in [first, second] {
2440 let vertex_base = vertices.len() as u64;
2441 let edge_base = edges.len() as u64;
2442 let mut vertex_ids: HashMap<u64, u64> = HashMap::default();
2443 for (index, vertex) in operand.vertices.iter().enumerate() {
2444 let id = vertex_base + index as u64 + 1;
2445 vertex_ids.insert(vertex.id, id);
2446 vertices.push(VertexRecord { id, point: vertex.point });
2447 }
2448 let mut edge_ids: HashMap<u64, u64> = HashMap::default();
2449 for (index, edge) in operand.edges.iter().enumerate() {
2450 let id = edge_base + index as u64 + 1;
2451 edge_ids.insert(edge.id, id);
2452 edges.push(EdgeRecord {
2453 id,
2454 curve: edge.curve.clone(),
2455 t0: edge.t0,
2456 t1: edge.t1,
2457 start_vertex_id: vertex_ids.get(&edge.start_vertex_id).copied().unwrap_or(edge.start_vertex_id),
2458 end_vertex_id: vertex_ids.get(&edge.end_vertex_id).copied().unwrap_or(edge.end_vertex_id),
2459 degenerate: edge.degenerate,
2460 name: edge.name.clone(),
2461 });
2462 }
2463 for shell in &operand.shells {
2464 let mut faces = Vec::with_capacity(shell.faces.len());
2465 for face in &shell.faces {
2466 let loops = face
2467 .loops
2468 .iter()
2469 .map(|loop_record| {
2470 let coedges = loop_record
2471 .coedges
2472 .iter()
2473 .map(|coedge| {
2474 let id = next_coedge_id;
2475 next_coedge_id += 1;
2476 CoedgeRecord {
2477 id,
2478 edge_id: edge_ids.get(&coedge.edge_id).copied().unwrap_or(coedge.edge_id),
2479 forward: coedge.forward,
2480 pcurve: coedge.pcurve.clone(),
2481 }
2482 })
2483 .collect();
2484 let id = next_loop_id;
2485 next_loop_id += 1;
2486 LoopRecord { id, coedges }
2487 })
2488 .collect();
2489 let name = face.name.clone().map(|base| {
2490 if used_face_names.insert(base.clone()) {
2491 base
2492 } else {
2493 let mut suffix = 1usize;
2494 loop {
2495 let candidate = format!("{base}_{suffix}");
2496 if used_face_names.insert(candidate.clone()) {
2497 break candidate;
2498 }
2499 suffix += 1;
2500 }
2501 }
2502 });
2503 faces.push(FaceRecord {
2504 id: next_face_id,
2505 surface: face.surface.clone(),
2506 same_sense: face.same_sense,
2507 loops,
2508 name,
2509 });
2510 next_face_id += 1;
2511 }
2512 shells.push(ShellRecord { id: shells.len() as u64 + 1, faces });
2513 }
2514 }
2515 BrepSolid {
2516 mass_properties_cache: Default::default(),
2517 cells: Default::default(),
2518 id: 1,
2519 vertices,
2520 edges,
2521 shells,
2522 genus: first.genus + second.genus,
2523 kind: crate::BodyKind::Solid,
2524 }
2525}
2526
2527fn boolean_pipeline(
2530 first: &BrepSolid,
2531 second: &BrepSolid,
2532 operation: BooleanOperation,
2533 options: &BooleanOptions,
2534 tangent_nodes: &mut Vec<Vec3>,
2535) -> Result<(KernelOutcome<BrepSolid>, Option<HashSet<u64>>), KernelRefusal> {
2536 let _work = crate::imprint::work_profile::Scope::open("boolean");
2537 let replaced_operands = operand_state::replace_operands(first, second, operation, options);
2538 let (first, second) = match &replaced_operands {
2539 Some((first, second)) => (first, second),
2540 None => (first, second),
2541 };
2542 let policy = boolean_policy(first, second, options)?;
2543 let tolerance = policy.model;
2544 let bounds = [operand_bounds(first), operand_bounds(second)];
2559 let disjoint = disjoint_fast_path(options) && !bounds[0].intersects(bounds[1], policy.sew_search);
2560 let contact = !disjoint
2561 && contact_fast_path(options)
2562 && options.seam_reseat_later_references.is_some()
2563 && line_or_point_contact(first, second, bounds);
2564 let contact = contact
2569 || (!disjoint
2570 && matches!(operation, BooleanOperation::Intersect)
2571 && contact_fast_path(options)
2572 && boxes_share_no_interior(first, second, bounds));
2573 if disjoint || contact {
2574 let operation_started = Instant::now();
2575 let mut diagnostics = KernelDiagnostics::default();
2576 diagnostics.count_n(
2577 "collect.faces",
2578 first.shells.iter().chain(&second.shells).map(|shell| shell.faces.len() as u64).sum(),
2579 );
2580 diagnostics.count(if contact { "boolean.contact_fast_path" } else { "boolean.disjoint_fast_path" });
2581 diagnostics.measure_max("tolerance.model", policy.model);
2582 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
2583 let value = match operation {
2584 BooleanOperation::Union => concatenate_disjoint(first, second),
2585 BooleanOperation::Subtract => first.clone(),
2586 BooleanOperation::Intersect => {
2587 diagnostics.event(
2588 DiagnosticSeverity::Info,
2589 KernelStage::Select,
2590 "boolean.empty_result",
2591 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
2592 );
2593 empty_solid()
2594 }
2595 };
2596 let stage_ms = operation_started.elapsed().as_secs_f64() * 1_000.0;
2597 profile_stage("disjoint_fast_path_ms", stage_ms);
2598 diagnostics.measure_max("timing.total_ms", stage_ms);
2599 return Ok((KernelOutcome { value, diagnostics }, Some(HashSet::default())));
2600 }
2601 let heal_started = Instant::now();
2602 let (first_owned, second_owned) = prepared_operands(first, second, &policy)?;
2603 let heal_ms = heal_started.elapsed().as_secs_f64() * 1_000.0;
2604 let first = &first_owned;
2605 let second = &second_owned;
2606
2607 let mut diagnostics = KernelDiagnostics::default();
2608 diagnostics.measure_max("timing.heal_ms", heal_ms);
2611 let fit_scope = crate::PcurveFitScope::open();
2616 let polyline_scope = crate::PolylineFitScope::open();
2620 let operation_started = Instant::now();
2621 diagnostics.count_n(
2622 "collect.faces",
2623 first
2624 .shells
2625 .iter()
2626 .chain(&second.shells)
2627 .map(|shell| shell.faces.len() as u64)
2628 .sum(),
2629 );
2630 diagnostics.measure_max("tolerance.model", policy.model);
2631 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
2632
2633 let imprint_options = boolean_imprint_options(options, tolerance);
2634 let stage_started = Instant::now();
2635 let imprint = build_imprints(first, second, &imprint_options)?;
2636 tangent_nodes.extend_from_slice(&imprint.tangent_nodes);
2637 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
2638 for piece in &imprint.pieces {
2639 let start = piece.curve.evaluate(piece.t0);
2640 let end = piece.curve.evaluate(piece.t1);
2641 eprintln!(
2642 "piece {} supports={:?} t=[{:.6},{:.6}] start={:?} end={:?}",
2643 piece.id, piece.support_faces, piece.t0, piece.t1, start, end
2644 );
2645 }
2646 for entry in &imprint.by_face {
2647 eprintln!(
2648 "by_face operand={} face={} pieces={:?}",
2649 entry.operand, entry.face_id, entry.piece_ids
2650 );
2651 }
2652 for split in &imprint.edge_splits {
2653 eprintln!(
2654 "edge_split operand={} edge={} params={:?}",
2655 split.operand, split.edge_id, split.parameters
2656 );
2657 }
2658 }
2659 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2660 profile_stage("imprint_ms", stage_ms);
2661 diagnostics.measure_max("timing.imprint_ms", stage_ms);
2662 diagnostics.count_n("intersect.pieces", imprint.pieces.len() as u64);
2663 diagnostics.count_n("intersect.vertices", imprint.vertices.len() as u64);
2664 diagnostics.count_n("intersect.edge_splits", imprint.edge_splits.len() as u64);
2665 let (march_swap_rescues, clip_swap_rescues) = crate::imprint::take_rescue_firings();
2666 diagnostics.count_n("intersect.march_swap_rescue", march_swap_rescues);
2667 diagnostics.count_n("intersect.clip_swap_rescue", clip_swap_rescues);
2668 let touch = TouchCensus::build([first, second], &imprint);
2669 touch.report(&mut diagnostics);
2670 let stage_started = Instant::now();
2671 let (split_first, split_map_first) = apply_edge_splits_with_map(first, 0, &imprint)?;
2672 let (split_second, split_map_second) = apply_edge_splits_with_map(second, 1, &imprint)?;
2673 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2674 profile_stage("edge_split_ms", stage_ms);
2675 diagnostics.measure_max("timing.edge_split_ms", stage_ms);
2676 let stage_started = Instant::now();
2677 crate::classification::classify_profile_begin();
2678 let fragments_a = crate::fragment::fragment_solid_against(&split_first, 0, &imprint, crate::fragment::bounded_carriers(second).then_some((bounds[1], policy.sew_search)))?;
2679 let fragments_b = crate::fragment::fragment_solid_against(&split_second, 1, &imprint, crate::fragment::bounded_carriers(first).then_some((bounds[0], policy.sew_search)))?;
2680 crate::classification::classify_profile_report("fragment");
2681 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2682 profile_stage("fragment_ms", stage_ms);
2683 diagnostics.measure_max("timing.fragment_ms", stage_ms);
2684 diagnostics.count_n(
2685 "fragment.candidates",
2686 (fragments_a.len() + fragments_b.len()) as u64,
2687 );
2688 touch.report_fragments(&[&fragments_a, &fragments_b], &mut diagnostics);
2689 let a_surface_samples: Vec<Vec3> = fragments_a
2694 .iter()
2695 .flat_map(|fragment| {
2696 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
2697 })
2698 .collect();
2699 let b_surface_samples: Vec<Vec3> = fragments_b
2700 .iter()
2701 .flat_map(|fragment| {
2702 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
2703 })
2704 .collect();
2705 let stage_started = Instant::now();
2706 let mut barrier_edges: HashSet<(u8, u64)> = imprint
2707 .pieces
2708 .iter()
2709 .filter_map(|piece| piece.shared_edge.map(|(operand, edge_id, _)| (operand, edge_id)))
2710 .collect();
2711 barrier_edges.extend(imprint.barrier_edges.iter().copied());
2712 for (operand, split_map) in [(0u8, &split_map_first), (1u8, &split_map_second)] {
2718 let minted: Vec<(u8, u64)> = barrier_edges
2719 .iter()
2720 .filter(|(barrier_operand, _)| *barrier_operand == operand)
2721 .filter_map(|(_, edge_id)| split_map.get(edge_id))
2722 .flat_map(|sub_ids| sub_ids.iter().map(|sub_id| (operand, *sub_id)))
2723 .collect();
2724 barrier_edges.extend(minted);
2725 }
2726 crate::classification::classify_profile_begin();
2727 let coincident = coincident_pairs(
2728 &fragments_a,
2729 &fragments_b,
2730 first,
2731 second,
2732 &imprint.cosurface_pairs,
2733 tolerance,
2734 )?;
2735 let sector_mode = sector::sector_mode(options);
2736 let mut select_census = sector::SelectCensus::default();
2737 let mut selected = select_fragments(
2738 fragments_a,
2739 fragments_b,
2740 first,
2741 second,
2742 operation,
2743 tolerance,
2744 &barrier_edges,
2745 &imprint,
2746 &coincident,
2747 sector_mode,
2748 &mut select_census,
2749 )?;
2750 let resewn = resew_coincident_rims(
2751 &mut selected,
2752 [&split_first, &split_second],
2753 [first, second],
2754 &imprint.cosurface_pairs,
2755 operation,
2756 tolerance,
2757 )?;
2758 diagnostics.count_n("select.coincident_pairs", coincident.len() as u64);
2759 diagnostics.count_n("select.rims_resewn", resewn as u64);
2760 crate::classification::classify_profile_report("select");
2761 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2762 profile_stage("select_ms", stage_ms);
2763 diagnostics.measure_max("timing.select_ms", stage_ms);
2764 diagnostics.count_n("select.fragments", selected.len() as u64);
2765 diagnostics.count_n("select.sector_eligible", select_census.eligible);
2767 diagnostics.count_n("select.sector_primary", select_census.sector_primary);
2768 diagnostics.count_n("select.sector_fallback", select_census.sector_fallback);
2769 diagnostics.count_n("select.sector_disagree", select_census.disagree);
2770 diagnostics.count_n("select.ray_casts", select_census.ray_casts);
2771 diagnostics.count_n("select.on_votes", select_census.on_votes);
2772 diagnostics.count_n("select.overturns", select_census.overturns);
2773 if sector_mode != sector::SectorMode::Off || std::env::var_os("BREP_SECTOR_CENSUS").is_some() {
2774 sector::sector_census_line(|| {
2775 format!(
2776 "selection mode={sector_mode:?} select_ms={stage_ms:.3} selected={} eligible={} primary={} fallback={} disagree={} ray_casts={} on_votes={} overturns={}",
2777 selected.len(),
2778 select_census.eligible,
2779 select_census.sector_primary,
2780 select_census.sector_fallback,
2781 select_census.disagree,
2782 select_census.ray_casts,
2783 select_census.on_votes,
2784 select_census.overturns
2785 )
2786 });
2787 }
2788 if selected.is_empty()
2810 && !imprint.section_evidence
2811 && std::env::var("BREP_EMPTY_BOOLEAN").as_deref() != Ok("0")
2812 {
2813 let strictly_inside = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
2814 for &sample in samples {
2815 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::In {
2816 return Ok(true);
2817 }
2818 }
2819 Ok(false)
2820 };
2821 let outside_witness = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
2822 for &sample in samples {
2823 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::Out {
2824 return Ok(true);
2825 }
2826 }
2827 Ok(false)
2828 };
2829 let legitimate = match operation {
2830 BooleanOperation::Intersect => {
2831 !strictly_inside(&a_surface_samples, second)?
2832 && !strictly_inside(&b_surface_samples, first)?
2833 }
2834 BooleanOperation::Subtract => !outside_witness(&a_surface_samples, second)?,
2835 BooleanOperation::Union => false,
2836 };
2837 if legitimate {
2838 diagnostics.event(
2839 DiagnosticSeverity::Info,
2840 KernelStage::Select,
2841 "boolean.empty_result",
2842 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
2843 );
2844 fit_scope.close().report_into(&mut diagnostics);
2845 polyline_scope.close().report_into(&mut diagnostics);
2846 diagnostics.measure_max(
2847 "timing.total_ms",
2848 operation_started.elapsed().as_secs_f64() * 1_000.0,
2849 );
2850 return Ok((
2851 KernelOutcome {
2852 value: empty_solid(),
2853 diagnostics,
2854 },
2855 None,
2856 ));
2857 }
2858 }
2859 let solids = [(0, &split_first), (1, &split_second)]
2860 .into_iter()
2861 .collect::<HashMap<_, _>>();
2862 let dump = BooleanStageDump::open();
2863 if let Some(dump) = &dump {
2864 dump.write("first", &split_first);
2865 dump.write("second", &split_second);
2866 dump.write("selected", &selected);
2867 }
2868 let stage_started = Instant::now();
2869 let assembled_origins: Vec<FaceKey> = if imprint.tangent_sections.is_empty() {
2873 Vec::new()
2874 } else {
2875 selected
2876 .iter()
2877 .map(|fragment| FaceKey { operand: fragment.operand, face_id: fragment.source_face_id })
2878 .collect()
2879 };
2880 let attributable: Vec<crate::imprint::TangentSectionRecord> = imprint
2887 .tangent_sections
2888 .iter()
2889 .filter(|section| imprint.tangent_nodes.is_empty() || section.grazing.is_empty())
2890 .cloned()
2891 .collect();
2892 let attribute = |error: KernelRefusal| {
2893 attribute_to_tangent_section(error, &attributable, &assembled_origins)
2894 };
2895 let cellular_result = matches!(operation, BooleanOperation::Union)
2896 && cellular::enabled(options)
2897 && cellular::complete_contact(first, second, &selected, tolerance);
2898 let (solid, scope) = if cellular_result {
2899 (assemble::assemble_cellular_fragments(selected, &solids, &imprint, tolerance)
2900 .map_err(attribute)?, None)
2901 } else if untouched_passthrough(options) {
2902 assemble_fragments_scoped(selected, &solids, &imprint, tolerance, &touch, touched_assembly(options))
2903 .map_err(attribute)?
2904 } else {
2905 (assemble_fragments(selected, &solids, &imprint, tolerance).map_err(attribute)?, None)
2906 };
2907 if let Some(scope) = &scope {
2908 diagnostics.count_n("passthrough.faces_examined", scope.examined.len() as u64);
2909 }
2910 if let Some(dump) = &dump {
2911 dump.write("assembled", &solid);
2912 }
2913 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2914 profile_stage("assemble_ms", stage_ms);
2915 diagnostics.measure_max("timing.assemble_ms", stage_ms);
2916 let stage_started = Instant::now();
2917 let declines_before = crate::face_merge::declines_served();
2918 if std::env::var("BREP_DEBUG_PREMERGE_VALIDATE").is_ok() {
2919 let issues = solid.validate();
2920 eprintln!(
2921 "pre-merge validation: {} issue(s){}",
2922 issues.len(),
2923 issues
2924 .first()
2925 .map(|issue| format!(" — first: {}", issue.message))
2926 .unwrap_or_default()
2927 );
2928 }
2929 let solid = if solid.kind != crate::BodyKind::Cellular && options.merge_coplanar_faces
2930 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
2931 {
2932 let merged = match &scope {
2933 Some(scope) => merge_same_surface_faces_scoped(
2937 &solid,
2938 tolerance,
2939 &options.keep_unmerged_name_substrs,
2940 &scope.examined,
2941 )?,
2942 None => merge_same_surface_faces_excluding(
2943 &solid,
2944 tolerance,
2945 &options.keep_unmerged_name_substrs,
2946 )?,
2947 };
2948 merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?
2953 } else {
2954 solid
2955 };
2956 if let Some(dump) = &dump {
2957 dump.write("merged", &solid);
2958 }
2959 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2960 profile_stage("face_merge_ms", stage_ms);
2961 if crate::profile::profile_enabled() {
2962 profile_line!("boolean.merge_declines served={}", crate::face_merge::declines_served() - declines_before);
2963 }
2964 diagnostics.measure_max("timing.face_merge_ms", stage_ms);
2965 let validation_started = Instant::now();
2966 let validation = solid.validate_detailed_scoped(&policy, scope.as_ref().map(|scope| &scope.examined));
2967 profile_stage("final_validate_ms", validation_started.elapsed().as_secs_f64() * 1000.0);
2968 diagnostics.count_n("validate.issues", validation.issues.len() as u64);
2969 diagnostics.count_n(
2970 "validate.wire_warnings",
2971 validation.wire_warnings.len() as u64,
2972 );
2973 diagnostics.measure_max("validate.max_pcurve_error", validation.max_pcurve_error);
2974 for warning in &validation.wire_warnings {
2975 diagnostics.event(
2976 DiagnosticSeverity::Warning,
2977 KernelStage::Validate,
2978 "validate.uv_wire",
2979 warning.message.clone(),
2980 );
2981 }
2982 for issue in &validation.issues {
2983 diagnostics.event(
2984 DiagnosticSeverity::Error,
2985 KernelStage::Validate,
2986 "validate.brep",
2987 issue.message.clone(),
2988 );
2989 }
2990 fit_scope.close().report_into(&mut diagnostics);
2991 polyline_scope.close().report_into(&mut diagnostics);
2992 diagnostics.measure_max(
2993 "timing.total_ms",
2994 operation_started.elapsed().as_secs_f64() * 1_000.0,
2995 );
2996 if !validation.issues.is_empty() {
2997 return Err(KernelRefusal::new(
2998 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
2999 KernelStage::Validate,
3000 format!(
3001 "boolean_operation: invalid result: {:?}",
3002 validation.issues
3003 )));
3004 }
3005 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
3011 if let Ok(report) =
3012 crate::oracle::boolean_semantic_disagreement(first, second, operation, &solid, 200)
3013 {
3014 if report.is_flagged() {
3015 eprintln!(
3016 "[oracle] semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
3017 report.disagreement_rate,
3018 report.disagreements.len(),
3019 report.considered,
3020 report.sample_disagreement()
3021 );
3022 }
3023 }
3024 let fusable_band = crate::tolerance::assembler_weld(policy.model);
3025 let fusables = crate::oracle::boolean_residual_fusables(&solid, fusable_band);
3026 if !fusables.is_empty() {
3027 eprintln!(
3028 "[oracle] {} residual fusable(s) after weld; sample {:?}",
3029 fusables.len(),
3030 fusables.first()
3031 );
3032 }
3033 }
3034 let candidates = scope.as_ref().map(|scope| {
3035 let candidates = soundness_candidates(
3036 &solid,
3037 scope,
3038 [operand_bounds(first), operand_bounds(second)],
3039 policy.sew_search,
3040 );
3041 diagnostics.count_n("passthrough.soundness_candidates", candidates.len() as u64);
3042 crate::soundness::census::profile_operation(&solid, &[first, second], Some(&scope.touched), "boolean");
3043 candidates
3044 });
3045 Ok((
3046 KernelOutcome {
3047 value: solid,
3048 diagnostics,
3049 },
3050 candidates,
3051 ))
3052}
3053