1pub mod profile;
2pub use crate::arrangement::Vec2;
3use crate::classification::{classify_point, parameter_point_in_face, PolygonClass};
4pub use crate::fragment::{FaceFragmentRecord, FragmentEdgeSource};
5pub use crate::imprint::{
6 EdgeSplitRecord, FaceImprints, FaceKey, ImprintOptions, ImprintPieceRecord,
7 ImprintResultRecord, ImprintVertex,
8};
9use crate::tolerance::{assembler_weld, commit_weld};
10pub use crate::topology::{
11 adaptive_coedge_error, BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord,
12 ShellRecord, VertexRecord,
13};
14pub use 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};
24pub use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
25use serde::{Deserialize, Serialize};
26pub use web_time::Instant;
27
28thread_local! {
29 pub 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 #[serde(default)]
133 pub seam_rejoin_later_references: Option<Vec<String>>,
134}
135
136thread_local! {
137 static WITHOUT_PERTURBATION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
138}
139
140pub fn without_perturbation<T>(action: impl FnOnce() -> T) -> T {
147 struct Restore(bool);
148 impl Drop for Restore {
149 fn drop(&mut self) {
150 WITHOUT_PERTURBATION.with(|cell| cell.set(self.0));
151 }
152 }
153 let _restore = Restore(WITHOUT_PERTURBATION.with(|cell| cell.replace(true)));
154 action()
155}
156
157fn touched_assembly(options: &BooleanOptions) -> bool {
159 match std::env::var("BREP_TOUCHED_ASSEMBLY").as_deref() {
160 Ok("0") => false,
161 Ok(_) => true,
162 Err(_) => options.touched_assembly,
163 }
164}
165
166fn disjoint_fast_path(options: &BooleanOptions) -> bool {
168 match std::env::var("BREP_DISJOINT_FAST_PATH").as_deref() {
169 Ok("0") => false,
170 Ok(_) => true,
171 Err(_) => options.disjoint_fast_path,
172 }
173}
174
175fn contact_fast_path(options: &BooleanOptions) -> bool {
177 match std::env::var("BREP_CONTACT_FAST_PATH").as_deref() {
178 Ok("0") => false,
179 Ok(_) => true,
180 Err(_) => options.contact_fast_path,
181 }
182}
183
184fn untouched_passthrough(options: &BooleanOptions) -> bool {
186 match std::env::var("BREP_UNTOUCHED_PASSTHROUGH").as_deref() {
187 Ok("0") => false,
188 Ok(_) => true,
189 Err(_) => options.untouched_passthrough,
190 }
191}
192
193fn default_tolerance() -> f64 {
194 1e-7
195}
196
197fn default_true() -> bool {
198 true
199}
200
201impl Default for BooleanOptions {
202 fn default() -> Self {
203 Self {
204 tolerance: default_tolerance(),
205 tolerances: None,
206 imprint: ImprintOptions::default(),
207 merge_coplanar_faces: true,
208 keep_unmerged_name_substrs: Vec::new(),
209 untouched_passthrough: true,
210 disjoint_fast_path: true,
211 contact_fast_path: true,
212 touched_assembly: false,
213 sector_classification: true,
214 sheet_trim: true,
215 keep_cells: false,
216 seam_reseat_later_references: None,
217 seam_rejoin_later_references: None,
218 }
219 }
220}
221
222mod select;
223mod sheet;
224mod cellular;
225pub mod sector;
226pub mod assemble;
227mod operand_state;
228mod rim;
229mod coincident;
230mod touch;
231pub(crate) mod reseat;
232mod ball_align;
233mod rejoin;
234mod window_retry;
235
236pub use rim::*;
237use select::*;
238use coincident::*;
239use touch::TouchCensus;
240pub use assemble::{
241 assemble_fragments, assemble_open_fragments, commit_nearby_edge_endpoints,
242 clear_candidate_memo, edge_interior_lies_on, finalize_assembled_solid, refresh_derived_genus,
243};
244use assemble::{assemble_fragments_scoped, AssemblyScope};
245#[allow(unused_imports)]
247pub use assemble::apply_assembly_heal_chain;
248
249
250struct WorkingScale {
253 factor: f64,
254 solids: Vec<BrepSolid>,
255 options: BooleanOptions,
256}
257
258impl WorkingScale {
259 fn of(operands: &[&BrepSolid], options: &BooleanOptions) -> Result<Option<Self>, KernelRefusal> {
260 let Some(bounds) = crate::rescale::bounds_of(operands.iter().copied()) else {
261 return Ok(None);
262 };
263 let Some(factor) = crate::rescale::guard_factor(bounds) else {
264 return Ok(None);
265 };
266 crate::rescale::profile_fired("boolean", factor, bounds);
267 let solids = operands
268 .iter()
269 .map(|solid| crate::rescale::scale_operand(solid, factor, "boolean"))
270 .collect::<Result<Vec<_>, _>>()?;
271 let mut options = options.clone();
273 options.imprint.maximum_ssi_step = options.imprint.maximum_ssi_step.map(|step| step * factor);
274 Ok(Some(Self { factor, solids, options }))
275 }
276
277 fn back(&self, solid: &BrepSolid) -> Result<BrepSolid, KernelRefusal> {
278 crate::rescale::scale_operand(solid, 1.0 / self.factor, "boolean")
279 }
280
281 fn refusal(&self, error: KernelRefusal) -> KernelRefusal {
282 crate::rescale::name_scale(error, self.factor)
283 }
284}
285
286pub fn boolean_operation(
287 first: &BrepSolid,
288 second: &BrepSolid,
289 operation: BooleanOperation,
290 options: &BooleanOptions,
291) -> Result<BrepSolid, KernelRefusal> {
292 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
293 return boolean_operation(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
294 .map_err(|error| scaled.refusal(error))
295 .and_then(|solid| scaled.back(&solid));
296 }
297 boolean_operation_unscaled(first, second, operation, options)
298 .or_else(|refused| window_retry::retry(first, second, operation, options, refused, boolean_operation_unscaled))
299}
300
301fn boolean_operation_unscaled(
303 first: &BrepSolid,
304 second: &BrepSolid,
305 operation: BooleanOperation,
306 options: &BooleanOptions,
307) -> Result<BrepSolid, KernelRefusal> {
308 match boolean_operation_with_diagnostics(first, second, operation, options) {
309 Ok(outcome) => {
310 if below_tolerance_refusal_enabled()
313 && outcome.value.shells.iter().all(|shell| shell.faces.is_empty())
314 && !matches!(operation, BooleanOperation::Union)
315 {
316 if let Some(refusal) = below_tolerance_refusal(first, second, None) {
317 if let Some(answer) = below_tolerance_answer(first, second, operation) {
318 return Ok(answer);
319 }
320 if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
321 return Ok(answer);
322 }
323 return Err(refusal);
324 }
325 }
326 if unresolved_merge_refusal_enabled() && !matches!(operation, BooleanOperation::Subtract) {
327 if let Some(refusal) = unresolved_merge_refusal(first, second) {
328 return Err(refusal);
329 }
330 }
331 if below_tolerance_slivers_enabled()
334 && !matches!(operation, BooleanOperation::Subtract)
335 && [first, second].iter().all(|solid| face_count(solid) <= SLIVER_ANSWER_FACES)
336 && near_coincident_planar_faces(first, second).is_some()
337 {
338 if let Some(answer) = below_tolerance_answer(first, second, operation) {
339 return Ok(answer);
340 }
341 }
342 Ok(outcome.value)
343 }
344 Err(error) => {
345 if below_tolerance_refusal_enabled() {
346 if let Some(refusal) = below_tolerance_refusal(first, second, Some(&error)) {
347 if let Some(answer) = below_tolerance_answer(first, second, operation) {
348 return Ok(answer);
349 }
350 if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
351 return Ok(answer);
352 }
353 return Err(refusal);
354 }
355 }
356 if std::env::var("BREP_NO_PERTURB").as_deref() == Ok("1")
364 || !error.class.perturbation_eligible()
365 {
366 return Err(error);
367 }
368 if std::env::var("BREP_OPEN_OPERAND_GATE").as_deref() != Ok("0") {
390 if let Some((operand, open)) = [first, second]
391 .iter()
392 .enumerate()
393 .find_map(|(operand, solid)| {
394 let open = one_use_edges(solid);
395 (open > 0).then_some((operand, open))
396 })
397 {
398 return Err(error.with_message(|message| format!(
399 "{message}; operand {operand} is not a closed shell: {open} of its edges bound \
400 only one face, so no boolean of it encloses a solid and no perturbation \
401 can close it"
402 )));
403 }
404 }
405 if let Some((operand, face_id, deviation, weld)) =
406 planar_operand_off_its_plane(first, second, options)
407 {
408 return Err(error.with_message(|message| format!(
409 "{message}; operand {operand} face {face_id} is a plane whose straight \
410 boundary sits {deviation:.3e} off it (assembly weld {weld:.1e}), which \
411 no perturbation can reconcile — the body's planes must contain their \
412 boundary before it can take part in an exact boolean"
413 )));
414 }
415 if matches!(operation, BooleanOperation::Subtract)
430 && std::env::var("BREP_PINCH_GATE").as_deref() != Ok("0")
431 && subtract_pinches_at_internal_tangency(first, second, options.tolerance)
432 .unwrap_or(false)
433 {
434 if let Some(solid) = subtract_through_the_common_part(first, second, options) {
437 return Ok(solid);
438 }
439 return Err(error.with_message(|message| format!(
440 "{message}; internal tangency: the operands touch tangentially with \
441 co-directed normals, so the exact difference pinches to zero thickness \
442 (non-manifold, unrepresentable in a boundary model) — refusing rather \
443 than returning a perturbed sliver"
444 )));
445 }
446 if matches!(error.class, RefusalClass::TangentNodeSingularity)
462 && std::env::var("BREP_TANGENT_NODE_GATE").as_deref() != Ok("0")
463 {
464 return Err(error);
465 }
466 if matches!(operation, BooleanOperation::Union) {
470 if let Some(solid) = union_through_the_difference(first, second, options) {
471 return Ok(solid);
472 }
473 }
474 if WITHOUT_PERTURBATION.with(|cell| cell.get()) {
476 return Err(error);
477 }
478 match perturbation_retry(first, second, operation, options) {
479 Ok(solid) => Ok(solid),
480 Err(refused) if refused.is_empty() => Err(error),
481 Err(refused) => {
482 Err(error.with_message(|message| format!("{message}; {}", refused.join("; "))))
483 }
484 }
485 }
486 }
487}
488
489const PINCH_PROBE_STEPS: usize = 8;
494
495const PINCH_ANGULAR_TOLERANCE: f64 = 1e-4;
498
499const PINCH_SEPARATION_STEP: f64 = 1e-2;
503
504fn subtract_through_the_common_part(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
522 if !switch!("BREP_PINCH_COMMON_RETRY", true) || !options.imprint.tangent_curve_imprint {
525 return None;
526 }
527 let common = boolean_operation_with_diagnostics(first, second, BooleanOperation::Intersect, options).ok()?.value;
528 if common.shells.iter().all(|shell| shell.faces.is_empty()) {
529 return None;
530 }
531 let cut = boolean_operation_with_diagnostics(first, &common, BooleanOperation::Subtract, options).ok()?.value;
532 if !cut.validate().is_empty() {
533 return None;
534 }
535 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
536 let (whole, taken, left) = (volume(first)?, volume(&common)?, volume(&cut)?);
537 ((left - (whole - taken)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(cut)
538}
539
540fn union_through_the_difference(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
553 if !switch!("BREP_TANGENT_UNION_DIFFERENCE_RETRY", true) || !options.imprint.tangent_curve_imprint {
554 return None;
555 }
556 let pinches = |a: &BrepSolid, b: &BrepSolid| subtract_pinches_at_internal_tangency(a, b, options.tolerance).unwrap_or(false);
557 if !pinches(first, second) && !pinches(second, first) {
558 return None;
559 }
560 let difference = match boolean_operation_with_diagnostics(first, second, BooleanOperation::Subtract, options) {
561 Ok(outcome) => outcome.value,
562 Err(_) => subtract_through_the_common_part(first, second, options)?,
563 };
564 if difference.shells.iter().all(|shell| shell.faces.is_empty()) || !difference.validate().is_empty() {
565 return None;
566 }
567 let union = boolean_operation_with_diagnostics(second, &difference, BooleanOperation::Union, options).ok()?.value;
568 if !union.validate().is_empty() {
569 return None;
570 }
571 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
572 let (left, added, whole) = (volume(&difference)?, volume(second)?, volume(&union)?);
573 ((whole - (left + added)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(union)
574}
575
576pub fn subtract_pinches_at_internal_tangency(
598 first: &BrepSolid,
599 second: &BrepSolid,
600 tolerance: f64,
601) -> Result<bool, KernelRefusal> {
602 let contact = (tolerance * 100.0).max(1e-12);
605 let probes_a = first
606 .shells
607 .iter()
608 .flat_map(|shell| &shell.faces)
609 .map(PinchProbe::of)
610 .collect::<Result<Vec<_>, _>>()?;
611 let probes_b = second
612 .shells
613 .iter()
614 .flat_map(|shell| &shell.faces)
615 .map(PinchProbe::of)
616 .collect::<Result<Vec<_>, _>>()?;
617 for probe_a in &probes_a {
618 for probe_b in &probes_b {
619 let pad = 1e-2 * probe_a.extent().max(probe_b.extent());
626 if probe_a.separation(probe_b) > contact + pad {
627 continue;
628 }
629 if classify_surface_pair(
636 &probe_a.face.surface,
637 &probe_b.face.surface,
638 tolerance,
639 PINCH_ANGULAR_TOLERANCE,
640 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")?
641 .relation
642 == SurfacePairRelation::Cosurface
643 {
644 continue;
645 }
646 if faces_touch_with_codirected_normals(probe_a, probe_b, contact)? {
647 return Ok(true);
648 }
649 }
650 }
651 Ok(false)
652}
653
654struct PinchProbe<'a> {
657 face: &'a FaceRecord,
658 samples: Vec<(f64, f64, Vec3)>,
660 minimum: [f64; 3],
661 maximum: [f64; 3],
662}
663
664impl<'a> PinchProbe<'a> {
665 fn of(face: &'a FaceRecord) -> Result<Self, KernelRefusal> {
666 let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
667 let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
668 let steps = PINCH_PROBE_STEPS as f64;
669 let mut samples = Vec::with_capacity((PINCH_PROBE_STEPS + 1).pow(2));
670 let mut minimum = [f64::INFINITY; 3];
671 let mut maximum = [f64::NEG_INFINITY; 3];
672 for i in 0..=PINCH_PROBE_STEPS {
673 let u = u0 + (u1 - u0) * i as f64 / steps;
674 for j in 0..=PINCH_PROBE_STEPS {
675 let v = v0 + (v1 - v0) * j as f64 / steps;
676 let Ok(point) = face.surface.evaluate(u, v) else {
677 continue;
678 };
679 for (axis, value) in [point.x, point.y, point.z].into_iter().enumerate() {
680 minimum[axis] = minimum[axis].min(value);
681 maximum[axis] = maximum[axis].max(value);
682 }
683 samples.push((u, v, point));
684 }
685 }
686 Ok(Self {
687 face,
688 samples,
689 minimum,
690 maximum,
691 })
692 }
693
694 fn extent(&self) -> f64 {
696 (0..3)
697 .map(|axis| self.maximum[axis] - self.minimum[axis])
698 .fold(0.0f64, f64::max)
699 }
700
701 fn separation(&self, other: &Self) -> f64 {
703 let mut gap: f64 = 0.0;
704 for axis in 0..3 {
705 gap = gap.max(self.minimum[axis] - other.maximum[axis]);
706 gap = gap.max(other.minimum[axis] - self.maximum[axis]);
707 }
708 gap
709 }
710}
711
712fn faces_touch_with_codirected_normals(
717 probe_a: &PinchProbe<'_>,
718 probe_b: &PinchProbe<'_>,
719 contact: f64,
720) -> Result<bool, KernelRefusal> {
721 for (probe, other) in [(probe_a, probe_b), (probe_b, probe_a)] {
722 let source = probe.face;
723 let target = other.face;
724 for &(u, v, point) in &probe.samples {
725 let projection = project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?;
726 if projection.distance > contact {
727 continue;
728 }
729 let (Ok(source_normal), Ok(target_normal)) = (
732 source.surface.normal(u, v),
733 target.surface.normal(projection.u, projection.v),
734 ) else {
735 continue;
736 };
737 let source_outward = outward_normal(source_normal, source.same_sense);
738 let target_outward = outward_normal(target_normal, target.same_sense);
739 if source_outward.cross(target_outward).length() > PINCH_ANGULAR_TOLERANCE
740 || source_outward.dot(target_outward) <= 0.0
741 {
742 continue;
743 }
744 if parameter_point_in_face(source, Vec2 { x: u, y: v }, 1e-6).or_refuse(KernelStage::Validate, "parameter_point_in_face")?
745 == PolygonClass::Outside
746 || parameter_point_in_face(
747 target,
748 Vec2 {
749 x: projection.u,
750 y: projection.v,
751 },
752 1e-6,
753 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")? == PolygonClass::Outside
754 {
755 continue;
756 }
757 if contact_separates_locally(source, target, u, v, contact)? {
758 return Ok(true);
759 }
760 }
761 }
762 Ok(false)
763}
764
765fn outward_normal(normal: Vec3, same_sense: bool) -> Vec3 {
766 if same_sense {
767 normal
768 } else {
769 normal.scale(-1.0)
770 }
771}
772
773fn contact_separates_locally(
779 source: &FaceRecord,
780 target: &FaceRecord,
781 u: f64,
782 v: f64,
783 contact: f64,
784) -> Result<bool, KernelRefusal> {
785 let [u0, u1] = source.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
786 let [v0, v1] = source.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
787 let step_u = (u1 - u0) * PINCH_SEPARATION_STEP;
788 let step_v = (v1 - v0) * PINCH_SEPARATION_STEP;
789 for (probe_u, probe_v) in [
790 ((u + step_u).min(u1), v),
791 ((u - step_u).max(u0), v),
792 (u, (v + step_v).min(v1)),
793 (u, (v - step_v).max(v0)),
794 ] {
795 if (probe_u - u).abs() < f64::EPSILON && (probe_v - v).abs() < f64::EPSILON {
796 continue;
797 }
798 let Ok(point) = source.surface.evaluate(probe_u, probe_v) else {
799 continue;
800 };
801 if project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?.distance > contact * 10.0 {
804 return Ok(true);
805 }
806 }
807 Ok(false)
808}
809
810fn perturbation_retry(
864 first: &BrepSolid,
865 second: &BrepSolid,
866 operation: BooleanOperation,
867 options: &BooleanOptions,
868) -> Result<BrepSolid, Vec<String>> {
869 const DIRECTIONS: [[f64; 3]; 4] = [
880 [0.4034, 0.7973, 0.4491],
881 [0.7973, 0.4491, 0.4034],
882 [0.4491, 0.4034, 0.7973],
883 [0.5774, -0.5774, 0.5774],
884 ];
885 const FRACTIONS: [f64; 5] = PERTURBATION_FRACTIONS;
891
892 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
893 let scale = crate::solid_tolerance::solid_scale(first)
894 .max(crate::solid_tolerance::solid_scale(second))
895 .max(1.0);
896
897 let _caller = crate::mass_caller("boolean.perturbation_rescue");
901 let va = solid_signed_volume(first).ok().map(f64::abs);
902 let vb = solid_signed_volume(second).ok().map(f64::abs);
903 let hold_identity = std::env::var("BREP_PERTURB_IDENTITY").as_deref() != Ok("0");
904 let hold_mirror = hold_identity && std::env::var("BREP_PERTURB_MIRROR").as_deref() != Ok("0");
907 let early_exit = std::env::var("BREP_MIRROR_EARLY_EXIT").as_deref() != Ok("0");
910 let mut trends = [MirrorTrend::default(); 4];
911 let mut identity: Option<Option<InclusionExclusion>> = None;
913 let mut refused = Vec::new();
914 let ladder = std::env::var("BREP_DEBUG_PERTURB_LADDER").is_ok();
918 let ladder_start = web_time::Instant::now();
919 if ladder {
920 let measured = inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
921 match &measured {
922 Some(identity) => eprintln!(
923 "[ladder] identity {} = {:.9} from the exact lane's {} ({:.9}); V(first) {:?} V(second) {:?}",
924 identity.formula, identity.expected, identity.reading, identity.read, va, vb
925 ),
926 None => eprintln!("[ladder] no identity: no exact-lane boolean of these operands clears in either order"),
927 }
928 identity = Some(measured);
929 }
930 let rung_miss = |identity: &Option<Option<InclusionExclusion>>, candidate: &BrepSolid| -> String {
931 let volume = body_volume(candidate);
932 match (identity, volume) {
933 (Some(Some(identity)), Some(volume)) => format!(
934 "volume {volume:.9} miss {:+.3e} bar {:.3e}",
935 volume - identity.expected,
936 crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * identity.expected.abs())
937 ),
938 (_, Some(volume)) => format!("volume {volume:.9}"),
939 _ => "no volume".to_string(),
940 }
941 };
942
943 for &fraction in &FRACTIONS {
944 let magnitude = scale * fraction;
945 for (direction, dir) in DIRECTIONS.iter().enumerate() {
946 if trends[direction].closed {
947 if ladder {
948 eprintln!("[ladder] dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}: not tried, its direction is closed");
949 }
950 continue;
951 }
952 let offset = [dir[0] * magnitude, dir[1] * magnitude, dir[2] * magnitude];
953 let translate = match AffineTransform::new([
954 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,
958 ]) {
959 Ok(transform) => transform,
960 Err(_) => continue,
961 };
962 let moved = match crate::transform_brep(second, translate, false) {
963 Ok(solid) => solid,
964 Err(_) => continue,
965 };
966 let rung = format!("dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}");
967 let rung_start = web_time::Instant::now();
968 let candidate =
969 match boolean_operation_with_diagnostics(first, &moved, operation, options) {
970 Ok(outcome) => outcome.value,
971 Err(error) => {
972 if ladder {
973 eprintln!("[ladder] {rung}: exact lane refused {:?}", error.class);
974 }
975 continue;
976 }
977 };
978 let built = rung_start.elapsed();
979 if candidate.shells.is_empty() {
981 if ladder {
982 eprintln!("[ladder] {rung}: empty");
983 }
984 continue;
985 }
986 if let (Some(va), Some(vb)) = (va, vb) {
991 if let Ok(vr) = solid_signed_volume(&candidate) {
992 if !volume_within_csg_bounds(operation, va, vb, vr.abs()) {
993 if ladder {
994 eprintln!("[ladder] {rung}: outside the CSG bound, {}", rung_miss(&identity, &candidate));
995 }
996 continue;
997 }
998 }
999 }
1000 let bounded = rung_start.elapsed();
1005 if hold_identity {
1007 let identity = identity.get_or_insert_with(|| {
1008 let identity =
1009 inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
1010 if debug && identity.is_none() {
1011 eprintln!(
1012 "[perturb] no exact-lane boolean of these operands clears in either \
1013 order; no identity to hold"
1014 );
1015 }
1016 identity
1017 });
1018 if let Some(identity) = identity {
1019 let expected = identity.expected;
1020 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * expected.abs());
1021 let volume = body_volume(&candidate);
1022 let miss = volume.map(|volume| (volume - expected).abs());
1023 if !miss.is_some_and(|miss| miss <= bar) {
1024 let sentence = format!(
1025 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1026 (offset {magnitude:.3e}) refused: its body reads {} against the \
1027 inclusion–exclusion identity {} = {expected:.9} (the exact lane's \
1028 {} reads {:.9}), a miss of {} beyond the volume drift bar {bar:.3e}",
1029 volume.map_or("no volume".to_string(), |volume| format!("{volume:.9}")),
1030 identity.formula,
1031 identity.reading,
1032 identity.read,
1033 miss.map_or("unmeasured".to_string(), |miss| format!("{miss:.3e}")),
1034 );
1035 if debug {
1036 eprintln!("[perturb] {sentence}");
1037 }
1038 if ladder {
1039 eprintln!(
1040 "[ladder] {rung}: refused by the identity, volume {} miss {} bar {bar:.3e}",
1041 volume.map_or("none".to_string(), |volume| format!("{volume:.9}")),
1042 volume.map_or("unmeasured".to_string(), |volume| format!("{:+.3e}", volume - expected)),
1043 );
1044 }
1045 refused.push(sentence);
1046 continue;
1047 }
1048 } else if hold_mirror {
1049 let mirror_start = web_time::Instant::now();
1052 let mirrored = AffineTransform::new([
1053 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,
1057 ])
1058 .ok()
1059 .and_then(|transform| crate::transform_brep(second, transform, false).ok());
1060 let mirror = mirrored.as_ref().and_then(|mirrored| {
1061 inclusion_exclusion_volume(first, mirrored, operation, options, va, vb, true)
1062 });
1063 let mirror_time = mirror_start.elapsed();
1064 let volume = body_volume(&candidate);
1065 let mut measured = None;
1066 let verdict = match (&mirror, volume) {
1067 (Some(mirror), Some(volume)) => {
1068 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * mirror.expected.abs());
1069 let miss = 0.5 * (volume - mirror.expected).abs();
1070 measured = Some((0.5 * (volume - mirror.expected), bar));
1071 if ladder {
1072 eprintln!(
1073 "[ladder] {rung}: mirror at −offset reads {} = {:.9} (the mirrored {} {:.9}); body {volume:.9}, first-order translation error {:+.3e} bar {bar:.3e}",
1074 mirror.formula, mirror.expected, mirror.reading, mirror.read, 0.5 * (volume - mirror.expected)
1075 );
1076 }
1077 (miss > bar).then(|| format!(
1078 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1079 (offset {magnitude:.3e}) refused: no exact-lane boolean of the \
1080 operands clears, so the rung is held to its mirror: its body reads \
1081 {volume:.9} with the second operand moved +offset and {} = {:.9} \
1082 with it moved −offset (the mirrored {} reads {:.9}), a first-order \
1083 translation error of {miss:.3e} beyond the volume drift bar {bar:.3e}",
1084 mirror.formula, mirror.expected, mirror.reading, mirror.read
1085 ))
1086 }
1087 _ => Some(format!(
1088 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1089 (offset {magnitude:.3e}) refused: no exact-lane boolean of the operands \
1090 clears, and none clears with the second operand moved −offset either, \
1091 so nothing checks the rung's body{}",
1092 volume.map_or(String::new(), |volume| format!(" ({volume:.9})"))
1093 )),
1094 };
1095 match verdict {
1096 None => trends[direction].cleared(),
1097 Some(sentence) => {
1098 if debug {
1099 eprintln!("[perturb] {sentence}");
1100 }
1101 if ladder {
1102 eprintln!(
1103 "[ladder] {rung}: refused by its mirror (rung {:.0} ms: built {:.0}, bound {:.0}, mirror {:.0} ms; ladder {:.1} s)",
1104 rung_start.elapsed().as_secs_f64() * 1e3,
1105 built.as_secs_f64() * 1e3,
1106 (bounded - built).as_secs_f64() * 1e3,
1107 mirror_time.as_secs_f64() * 1e3,
1108 ladder_start.elapsed().as_secs_f64()
1109 );
1110 }
1111 refused.push(sentence);
1112 let closure = measured.and_then(|(error, bar)| {
1115 let earlier = trends[direction].refused(magnitude, error, early_exit)?;
1116 Some((earlier, error, bar))
1117 });
1118 if let Some(((earlier_offset, earlier_error), error, bar)) = closure {
1119 let closed = format!(
1120 "perturbation direction dir={dir:?} closed after offset {magnitude:.3e}: its \
1121 rungs' first-order translation errors read {earlier_error:+.3e} at offset \
1122 {earlier_offset:.3e} and {error:+.3e} at {magnitude:.3e}, one sign and \
1123 growing, so no larger offset along it comes back to the volume drift bar \
1124 {bar:.3e}"
1125 );
1126 if debug {
1127 eprintln!("[perturb] {closed}");
1128 }
1129 if ladder {
1130 eprintln!("[ladder] {closed}");
1131 }
1132 refused.push(closed);
1133 }
1134 continue;
1135 }
1136 }
1137 }
1138 }
1139 match crate::oracle::boolean_semantic_disagreement(
1143 first, second, operation, &candidate, 400,
1144 ) {
1145 Ok(report) if report.considered >= 30 && !report.is_flagged() => {
1146 if ladder {
1147 eprintln!(
1148 "[ladder] {rung}: accepted (oracle {} considered, rate {:.4}), {}",
1149 report.considered, report.disagreement_rate, rung_miss(&identity, &candidate)
1150 );
1151 }
1152 if debug {
1153 eprintln!(
1154 "[perturb] rescued {operation:?}: dir={dir:?} fraction={fraction:.1e} \
1155 magnitude={magnitude:.3e} offset={offset:?} \
1156 (oracle considered={} rate={:.4})",
1157 report.considered, report.disagreement_rate
1158 );
1159 }
1160 return Ok(candidate);
1161 }
1162 report => {
1163 if ladder {
1164 let verdict = match &report {
1165 Ok(report) => format!("oracle {} considered, rate {:.4}", report.considered, report.disagreement_rate),
1166 Err(error) => format!("oracle error {error:?}"),
1167 };
1168 eprintln!("[ladder] {rung}: refused by the oracle ({verdict}), {}", rung_miss(&identity, &candidate));
1169 }
1170 continue;
1171 }
1172 }
1173 }
1174 }
1175 if debug {
1176 eprintln!("[perturb] ladder exhausted for {operation:?}; no rung produced a clean result");
1177 }
1178 Err(refused)
1179}
1180
1181pub const PERTURBATION_FRACTIONS: [f64; 5] = [3e-5, 1e-4, 3e-4, 1e-3, 3e-3];
1184
1185#[derive(Clone, Copy, Default)]
1209pub struct MirrorTrend {
1210 last: Option<(f64, f64)>,
1212 pub closed: bool,
1213}
1214
1215impl MirrorTrend {
1216 pub fn refused(&mut self, offset: f64, error: f64, close: bool) -> Option<(f64, f64)> {
1221 let earlier = self
1222 .last
1223 .filter(|&(_, earlier)| earlier.signum() == error.signum() && error.abs() >= earlier.abs())
1224 .filter(|_| close);
1225 self.last = Some((offset, error));
1226 self.closed |= earlier.is_some();
1227 earlier
1228 }
1229
1230 pub fn cleared(&mut self) {
1232 self.last = None;
1233 }
1234}
1235
1236pub fn below_tolerance_refusal_enabled() -> bool {
1251 crate::switch!("BREP_BELOW_TOLERANCE_REFUSAL", true)
1252}
1253
1254pub fn below_tolerance_slivers_enabled() -> bool {
1271 crate::switch!("BREP_BELOW_TOLERANCE_SLIVERS", true)
1272}
1273
1274const SLIVER_ANSWER_FACES: usize = 64;
1277
1278fn face_count(solid: &BrepSolid) -> usize {
1279 solid.shells.iter().map(|shell| shell.faces.len()).sum()
1280}
1281
1282fn below_tolerance_answer(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<BrepSolid> {
1284 if !below_tolerance_slivers_enabled() || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES) {
1285 return None;
1286 }
1287 if ![first, second].iter().all(|solid| closed_single_shell(solid)) {
1288 return None;
1289 }
1290 let inside = |x: &BrepSolid, y: &BrepSolid| difference_all_sliver(x, y);
1291 if matches!(operation, BooleanOperation::Subtract) {
1292 return inside(first, second).then(empty_solid);
1293 }
1294 let (first_in, second_in) = (inside(first, second), inside(second, first));
1295 let first_larger = || match (body_volume(first), body_volume(second)) {
1298 (Some(a), Some(b)) => a >= b,
1299 _ => true,
1300 };
1301 let outer_is_first = match (first_in, second_in) {
1302 (false, false) => return None,
1303 (true, false) => false,
1304 (false, true) => true,
1305 (true, true) => first_larger(),
1306 };
1307 let (outer, inner) = if outer_is_first { (first, second) } else { (second, first) };
1308 Some(match operation {
1309 BooleanOperation::Union => outer.clone(),
1310 _ => inner.clone(),
1311 })
1312}
1313
1314fn closed_single_shell(solid: &BrepSolid) -> bool {
1316 if !solid.kind.is_solid() || solid.shells.len() != 1 {
1317 return false;
1318 }
1319 let mut uses: HashMap<u64, usize> = HashMap::default();
1320 for coedge in solid.shells[0].faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1321 *uses.entry(coedge.edge_id).or_default() += 1;
1322 }
1323 !uses.is_empty() && uses.values().all(|&count| count == 2) && solid.edges.iter().all(|edge| uses.contains_key(&edge.id))
1324}
1325
1326fn difference_all_sliver(first: &BrepSolid, second: &BrepSolid) -> bool {
1337 let Some(bounds) = difference_bounds(first, second) else {
1338 return false;
1339 };
1340 let Ok(properties) = crate::solid_mass_properties(first) else {
1341 return false;
1342 };
1343 bounds.out <= BELOW_TOLERANCE_BAND
1344 && bounds.upper.is_finite()
1345 && bounds.upper <= crate::tolerance::COINCIDENCE_DISTANCE_FLOOR * properties.surface_area
1346}
1347
1348struct DifferenceBounds {
1354 lower: f64,
1355 upper: f64,
1356 out: f64,
1358}
1359
1360fn difference_bounds(first: &BrepSolid, second: &BrepSolid) -> Option<DifferenceBounds> {
1361 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1362 let (polygons_a, polygons_b) = (face_polygons(first, scale)?, face_polygons(second, scale)?);
1363 let vertices_b: Vec<Vec3> = second.vertices.iter().map(|vertex| vertex.point).collect();
1364 let vertices_a: Vec<Vec3> = first.vertices.iter().map(|vertex| vertex.point).collect();
1365 let flat = 1e-9 * scale;
1366 let mut bounds = DifferenceBounds { lower: 0.0, upper: 0.0, out: 0.0 };
1367 for polygon in &polygons_b {
1368 let (origin, normal) = polygon_plane(polygon)?;
1369 if vertices_b.iter().any(|vertex| vertex.sub(origin).dot(normal) > flat) {
1371 return None;
1372 }
1373 let out = vertices_a.iter().map(|vertex| vertex.sub(origin).dot(normal)).fold(0.0f64, f64::max);
1374 bounds.out = bounds.out.max(out);
1375 if out <= 0.0 {
1376 continue;
1377 }
1378 let part: f64 = polygons_a.iter().map(|face| clipped_cone_volume(face, origin, normal)).sum();
1379 bounds.lower = bounds.lower.max(part);
1380 bounds.upper += part;
1381 }
1382 Some(bounds)
1383}
1384
1385pub fn below_tolerance_rescale_enabled() -> bool {
1395 crate::switch!("BREP_BELOW_TOLERANCE_RESCALE", false)
1396}
1397
1398fn below_tolerance_rescaled(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions) -> Option<BrepSolid> {
1399 if !below_tolerance_rescale_enabled()
1400 || options.tolerances.is_some()
1401 || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES || !closed_single_shell(solid))
1402 {
1403 return None;
1404 }
1405 let (volume_exact, area_exact) = convex_pair_measures(first, second, operation)?;
1406 let volume_slack = 1e-9 * body_volume(first)?.max(body_volume(second)?);
1407 let area_slack = 1e-9 * area_exact.max(1.0);
1408 for factor in [100.0, 1000.0] {
1409 let scaled = |solid: &BrepSolid| crate::rescale::scale_operand(solid, factor, "boolean").ok();
1410 let (Some(a), Some(b)) = (scaled(first), scaled(second)) else {
1411 continue;
1412 };
1413 let mut scaled_options = options.clone();
1414 scaled_options.imprint.maximum_ssi_step = scaled_options.imprint.maximum_ssi_step.map(|step| step * factor);
1415 let Ok(outcome) = boolean_operation_with_diagnostics(&a, &b, operation, &scaled_options) else {
1416 continue;
1417 };
1418 let Ok(answer) = crate::rescale::scale_operand(&outcome.value, 1.0 / factor, "boolean") else {
1419 continue;
1420 };
1421 let Ok(properties) = crate::solid_mass_properties(&answer) else {
1422 continue;
1423 };
1424 if (properties.volume.abs() - volume_exact).abs() <= volume_slack
1425 && (properties.surface_area - area_exact).abs() <= area_slack
1426 && !answer.validate().iter().any(|issue| issue.severity == "error")
1427 {
1428 return Some(answer);
1429 }
1430 }
1431 None
1432}
1433
1434fn convex_pair_measures(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<(f64, f64)> {
1440 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1441 let (polygons_a, polygons_b) = (face_polygons(first, scale)?, face_polygons(second, scale)?);
1442 let (planes_a, planes_b) = (convex_planes(&polygons_a, scale)?, convex_planes(&polygons_b, scale)?);
1443 let zero = Vec3::new(0.0, 0.0, 0.0);
1444 let read = |polygons: &[Vec<Vec3>], planes: &[(Vec3, Vec3)]| {
1446 let (mut cone, mut area, mut inside_area) = (0.0, 0.0, 0.0);
1447 for polygon in polygons {
1448 area += vector_area(polygon, zero).length();
1449 let mut inside = polygon.clone();
1450 for &(origin, normal) in planes {
1451 inside = clip_polygon(&inside, origin, normal.scale(-1.0));
1452 if inside.len() < 3 {
1453 break;
1454 }
1455 }
1456 if inside.len() >= 3 {
1457 let vector = vector_area(&inside, zero);
1458 cone += inside[0].dot(vector) / 3.0;
1459 inside_area += vector.length();
1460 }
1461 }
1462 (cone, area, inside_area)
1463 };
1464 let (cone_a, area_a, inside_a) = read(&polygons_a, &planes_b);
1465 let (cone_b, area_b, inside_b) = read(&polygons_b, &planes_a);
1466 let (volume_a, volume_b) = (body_volume(first)?, body_volume(second)?);
1467 let common = cone_a + cone_b;
1468 Some(match operation {
1469 BooleanOperation::Intersect => (common, inside_a + inside_b),
1470 BooleanOperation::Union => (volume_a + volume_b - common, (area_a - inside_a) + (area_b - inside_b)),
1471 BooleanOperation::Subtract => (volume_a - common, (area_a - inside_a) + inside_b),
1472 })
1473}
1474
1475fn convex_planes(polygons: &[Vec<Vec3>], scale: f64) -> Option<Vec<(Vec3, Vec3)>> {
1478 let planes = polygons.iter().map(|polygon| polygon_plane(polygon)).collect::<Option<Vec<_>>>()?;
1479 let flat = 1e-9 * scale;
1480 let convex = planes.iter().all(|&(origin, normal)| polygons.iter().flatten().all(|vertex| vertex.sub(origin).dot(normal) <= flat));
1481 convex.then_some(planes)
1482}
1483
1484fn clip_polygon(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> Vec<Vec3> {
1487 let side = |point: Vec3| point.sub(origin).dot(normal);
1488 let mut kept = Vec::with_capacity(polygon.len() + 2);
1489 for (index, &point) in polygon.iter().enumerate() {
1490 let next = polygon[(index + 1) % polygon.len()];
1491 let (here, there) = (side(point), side(next));
1492 if here >= 0.0 {
1493 kept.push(point);
1494 }
1495 if (here >= 0.0) != (there >= 0.0) {
1496 let t = here / (here - there);
1497 kept.push(point.add(next.sub(point).scale(t)));
1498 }
1499 }
1500 kept
1501}
1502
1503fn face_polygons(solid: &BrepSolid, scale: f64) -> Option<Vec<Vec<Vec3>>> {
1507 let vertex = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1508 let mut polygons = Vec::new();
1509 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
1510 if !face.surface.is_affine().ok()? {
1511 return None;
1512 }
1513 for lp in &face.loops {
1514 let mut polygon = Vec::with_capacity(lp.coedges.len());
1515 for coedge in &lp.coedges {
1516 let edge = solid.edges.iter().find(|edge| edge.id == coedge.edge_id)?;
1517 let (start, end) = (vertex(edge.start_vertex_id)?, vertex(edge.end_vertex_id)?);
1518 let chord = end.sub(start);
1519 let length = chord.length();
1520 if edge.degenerate || length <= 1e-12 * scale {
1521 return None;
1522 }
1523 for control in &edge.curve.control_points {
1524 let offset = control.point().ok()?.sub(start);
1525 if offset.cross(chord).length() / length > 1e-9 * scale {
1526 return None;
1527 }
1528 }
1529 polygon.push(if coedge.forward { start } else { end });
1530 }
1531 polygons.push(polygon);
1532 }
1533 }
1534 let volume: f64 = polygons.iter().map(|polygon| clipped_cone_volume(polygon, Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 0.0))).sum();
1536 if !(volume.abs() > 0.0) {
1537 return None;
1538 }
1539 if volume < 0.0 {
1540 for polygon in &mut polygons {
1541 polygon.reverse();
1542 }
1543 }
1544 Some(polygons)
1545}
1546
1547fn polygon_plane(polygon: &[Vec3]) -> Option<(Vec3, Vec3)> {
1549 let origin = *polygon.first()?;
1550 Some((origin, vector_area(polygon, origin).normalized().ok()?))
1551}
1552
1553fn vector_area(polygon: &[Vec3], origin: Vec3) -> Vec3 {
1554 let mut area = Vec3::new(0.0, 0.0, 0.0);
1555 for (index, point) in polygon.iter().enumerate() {
1556 let next = polygon[(index + 1) % polygon.len()];
1557 area = area.add(point.sub(origin).cross(next.sub(origin)));
1558 }
1559 area.scale(0.5)
1560}
1561
1562fn clipped_cone_volume(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> f64 {
1568 let clipped: Vec<Vec3> = if normal.length() == 0.0 { polygon.to_vec() } else { clip_polygon(polygon, origin, normal) };
1569 if clipped.len() < 3 {
1570 return 0.0;
1571 }
1572 clipped[0].sub(origin).dot(vector_area(&clipped, origin)) / 3.0
1573}
1574
1575const BELOW_TOLERANCE_BAND: f64 = 10.0 * crate::tolerance::WELD_FLOOR;
1578
1579pub fn unresolved_merge_refusal_enabled() -> bool {
1589 crate::switch!("BREP_UNRESOLVED_MERGE_REFUSAL", false)
1590}
1591
1592pub fn sliver_shell_drop_enabled() -> bool {
1605 crate::switch!("BREP_SLIVER_SHELL_DROP", true)
1606}
1607
1608const SLIVER_SHELL_THICKNESS: f64 = 1e-12;
1612
1613pub fn sliver_shell_fast_on() -> bool {
1628 crate::switch!("BREP_SLIVER_SHELL_FAST", true)
1629}
1630
1631fn sliver_shell_fast_check_on() -> bool {
1632 crate::switch!("BREP_SLIVER_SHELL_FAST_CHECK", false)
1633}
1634
1635thread_local! {
1636 static SLIVER_FAST_CHECK: std::cell::Cell<(u64, u64, u64)> = const { std::cell::Cell::new((0, 0, 0)) };
1637}
1638
1639pub fn sliver_shell_fast_check_take() -> (u64, u64, u64) {
1642 SLIVER_FAST_CHECK.with(|cell| cell.replace((0, 0, 0)))
1643}
1644
1645fn sliver_fast_record(compared: u64, differed: u64, kept: u64) {
1646 SLIVER_FAST_CHECK.with(|cell| {
1647 let (a, b, c) = cell.get();
1648 cell.set((a + compared, b + differed, c + kept));
1649 });
1650}
1651
1652fn face_area_upper_bound(surface: &crate::NurbsSurface) -> Option<f64> {
1660 let net = &surface.control_points;
1661 let rows = net.len();
1662 let columns = net.first()?.len();
1663 if rows < 2 || columns < 2 || net.iter().any(|row| row.len() != columns) {
1664 return None;
1665 }
1666 let (p, q) = (surface.degree_u, surface.degree_v);
1667 let (us, vs) = (&surface.knots_u, &surface.knots_v);
1668 if us.len() != rows + p + 1 || vs.len() != columns + q + 1 {
1669 return None;
1670 }
1671 let mut w_min = f64::INFINITY;
1672 let mut w_max = 0.0f64;
1673 let mut point_max = 0.0f64;
1674 for c in net.iter().flatten() {
1675 if !(c.w > 0.0) {
1676 return None;
1677 }
1678 w_min = w_min.min(c.w);
1679 w_max = w_max.max(c.w);
1680 point_max = point_max.max((c.x * c.x + c.y * c.y + c.z * c.z).sqrt());
1681 }
1682 let hodograph = |along_u: bool| -> Option<(f64, f64)> {
1684 let (count, degree, knots) = if along_u { (rows, p, us) } else { (columns, q, vs) };
1685 let (mut dp, mut dw) = (0.0f64, 0.0f64);
1686 for i in 0..count - 1 {
1687 let span = knots[i + degree + 1] - knots[i + 1];
1688 if !(span > 0.0) {
1689 continue;
1690 }
1691 let scale = degree as f64 / span;
1692 let others = if along_u { columns } else { rows };
1693 for j in 0..others {
1694 let (a, b) = if along_u { (net[i][j], net[i + 1][j]) } else { (net[j][i], net[j][i + 1]) };
1695 let (x, y, z) = (b.x - a.x, b.y - a.y, b.z - a.z);
1696 dp = dp.max(scale * (x * x + y * y + z * z).sqrt());
1697 dw = dw.max(scale * (b.w - a.w).abs());
1698 }
1699 }
1700 Some((dp, dw))
1701 };
1702 let (pu, wu) = hodograph(true)?;
1703 let (pv, wv) = hodograph(false)?;
1704 let su = (pu * w_max + point_max * wu) / (w_min * w_min);
1705 let sv = (pv * w_max + point_max * wv) / (w_min * w_min);
1706 let extent_u = us[us.len() - 1] - us[0];
1707 let extent_v = vs[vs.len() - 1] - vs[0];
1708 let bound = su * sv * extent_u * extent_v;
1709 bound.is_finite().then_some(bound)
1710}
1711
1712pub fn trimmed_face_area_upper_bound(face: &crate::topology::FaceRecord) -> Option<f64> {
1720 let s = &face.surface;
1721 let (u0, u1) = (*s.knots_u.first()?, *s.knots_u.last()?);
1722 let (v0, v1) = (*s.knots_v.first()?, *s.knots_v.last()?);
1723 let (du, dv) = (1e-12 * (u1 - u0).abs(), 1e-12 * (v1 - v0).abs());
1725 if !(du > 0.0 && dv > 0.0) {
1726 return None;
1727 }
1728 for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
1729 for c in &coedge.pcurve.control_points {
1730 if !(c.w > 0.0) {
1731 return None;
1732 }
1733 let (u, v) = (c.x / c.w, c.y / c.w);
1734 if !(u >= u0 - du && u <= u1 + du && v >= v0 - dv && v <= v1 + dv) {
1735 return None;
1736 }
1737 }
1738 }
1739 face_area_upper_bound(s).map(|bound| 2.0 * bound)
1740}
1741
1742fn drop_sliver_shells(solid: &mut BrepSolid) -> usize {
1745 if !sliver_shell_drop_enabled() || !solid.kind.is_solid() || solid.shells.len() < 2 {
1746 return 0;
1747 }
1748 let floor = SLIVER_SHELL_THICKNESS * crate::solid_tolerance::solid_scale(solid).max(1.0);
1749 let degenerate: std::collections::HashSet<u64> = solid.edges.iter().filter(|edge| edge.degenerate).map(|edge| edge.id).collect();
1750 let mut drop = vec![false; solid.shells.len()];
1751 for (index, shell) in solid.shells.iter().enumerate() {
1752 if shell.faces.is_empty() {
1753 continue;
1754 }
1755 let mut uses: HashMap<u64, usize> = HashMap::default();
1757 for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1758 if !degenerate.contains(&coedge.edge_id) {
1759 *uses.entry(coedge.edge_id).or_default() += 1;
1760 }
1761 }
1762 if uses.is_empty() || uses.values().any(|&count| count != 2) {
1763 continue;
1764 }
1765 let alone = BrepSolid { shells: vec![shell.clone()], mass_properties_cache: Default::default(), ..solid.clone() };
1766 let (fast, check) = (sliver_shell_fast_on(), sliver_shell_fast_check_on());
1767 let kept_fast = (fast || check)
1768 && shell
1769 .faces
1770 .iter()
1771 .map(trimmed_face_area_upper_bound)
1772 .sum::<Option<f64>>()
1773 .map(|area| floor * area)
1774 .filter(|bar| bar.is_finite() && *bar > 0.0)
1775 .and_then(|bar| crate::solid_signed_volume_for_sign(&alone, bar).ok().map(|volume| volume > bar))
1776 .unwrap_or(false);
1777 if kept_fast && !check {
1778 sliver_fast_record(0, 0, 1);
1779 continue;
1780 }
1781 let Ok(mass) = crate::solid_mass_properties(&alone) else {
1782 continue;
1783 };
1784 let thickness = mass.volume.abs() / mass.surface_area.max(f64::MIN_POSITIVE);
1785 if env_read!("BREP_DEBUG_SLIVER_SHELL").is_some() {
1786 eprintln!(
1787 "sliver-shell: shell {index} of {}: volume {:.6e} area {:.6e} thickness {thickness:.3e}",
1788 solid.shells.len(),
1789 mass.volume,
1790 mass.surface_area
1791 );
1792 }
1793 drop[index] = thickness < floor;
1794 if check {
1795 sliver_fast_record(1, u64::from(kept_fast && drop[index]), u64::from(kept_fast));
1796 }
1797 }
1798 let dropped = drop.iter().filter(|&&d| d).count();
1799 if dropped == 0 || dropped == solid.shells.len() {
1800 return 0;
1801 }
1802 let mut index = 0;
1803 solid.shells.retain(|_| {
1804 let keep = !drop[index];
1805 index += 1;
1806 keep
1807 });
1808 let used_edges: std::collections::HashSet<u64> = solid
1809 .shells
1810 .iter()
1811 .flat_map(|shell| &shell.faces)
1812 .flat_map(|face| &face.loops)
1813 .flat_map(|lp| &lp.coedges)
1814 .map(|coedge| coedge.edge_id)
1815 .collect();
1816 solid.edges.retain(|edge| used_edges.contains(&edge.id));
1817 let used_vertices: std::collections::HashSet<u64> =
1818 solid.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
1819 solid.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
1820 solid.mass_properties_cache = Default::default();
1821 refresh_derived_genus(solid);
1823 dropped
1824}
1825
1826fn unresolved_merge_refusal(first: &BrepSolid, second: &BrepSolid) -> Option<KernelRefusal> {
1827 let (lower, upper) = (crate::tolerance::COINCIDENCE_DISTANCE_FLOOR, crate::tolerance::WELD_FLOOR);
1828 let (face_a, face_b, separation) = planar_faces_apart_within(first, second, lower, upper)?;
1829 Some(KernelRefusal::unsupported(
1830 KernelStage::Intersect,
1831 "below_modelling_tolerance",
1832 format!(
1833 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1834 another, {separation:.3e} apart at most over their shared extent: farther than a coincidence \
1835 ({lower:.0e}) and closer than the kernel resolves ({upper:.0e}), so the step between them would be \
1836 welded away"
1837 ),
1838 ))
1839}
1840
1841fn below_tolerance_refusal(first: &BrepSolid, second: &BrepSolid, error: Option<&KernelRefusal>) -> Option<KernelRefusal> {
1842 let (face_a, face_b, separation) = near_coincident_planar_faces(first, second)?;
1843 let message = format!(
1844 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1845 another, {separation:.3e} apart at most over their shared extent: the slivers between them are below the \
1846 modelling tolerance ({BELOW_TOLERANCE_BAND:.0e}), so the kernel cannot resolve them{}",
1847 error.map(|error| format!(" (the exact arrangement said: {})", error.message.chars().take(160).collect::<String>())).unwrap_or_default()
1848 );
1849 Some(KernelRefusal::unsupported(KernelStage::Intersect, "below_modelling_tolerance", message))
1850}
1851
1852fn near_coincident_planar_faces(first: &BrepSolid, second: &BrepSolid) -> Option<(u64, u64, f64)> {
1856 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1857 planar_faces_apart_within(first, second, 1e-9 * scale, BELOW_TOLERANCE_BAND)
1858}
1859
1860fn planar_faces_apart_within(first: &BrepSolid, second: &BrepSolid, lower: f64, upper: f64) -> Option<(u64, u64, f64)> {
1864 struct Planar {
1865 id: u64,
1866 origin: Vec3,
1867 normal: Vec3,
1868 corners: Vec<Vec3>,
1869 bounds: crate::spatial::Aabb,
1870 }
1871 let read = |solid: &BrepSolid| -> Vec<Planar> {
1872 let at = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1873 solid
1874 .shells
1875 .iter()
1876 .flat_map(|shell| &shell.faces)
1877 .filter_map(|face| {
1878 if !face.surface.is_affine().ok()? {
1879 return None;
1880 }
1881 let origin = face.surface.control_points[0][0].point().ok()?;
1882 let a = face.surface.control_points[1][0].point().ok()?.sub(origin);
1883 let b = face.surface.control_points[0][1].point().ok()?.sub(origin);
1884 let normal = a.cross(b).normalized().ok()?;
1885 let corners: Vec<Vec3> = face
1886 .loops
1887 .iter()
1888 .flat_map(|lp| &lp.coedges)
1889 .filter_map(|coedge| solid.edges.iter().find(|edge| edge.id == coedge.edge_id))
1890 .flat_map(|edge| [at(edge.start_vertex_id), at(edge.end_vertex_id)])
1891 .flatten()
1892 .collect();
1893 if corners.is_empty() {
1894 return None;
1895 }
1896 let bounds = crate::spatial::Aabb::from_points(corners.clone());
1897 Some(Planar { id: face.id, origin, normal, corners, bounds })
1898 })
1899 .collect()
1900 };
1901 let (faces_a, faces_b) = (read(first), read(second));
1902 for a in &faces_a {
1903 for b in &faces_b {
1904 if a.normal.cross(b.normal).length() > 1e-3 {
1905 continue;
1906 }
1907 if !a.bounds.intersects(b.bounds, upper) {
1908 continue;
1909 }
1910 let separation = a
1911 .corners
1912 .iter()
1913 .map(|corner| corner.sub(b.origin).dot(b.normal).abs())
1914 .chain(b.corners.iter().map(|corner| corner.sub(a.origin).dot(a.normal).abs()))
1915 .fold(0.0f64, f64::max);
1916 if separation > lower && separation <= upper {
1917 return Some((a.id, b.id, separation));
1918 }
1919 }
1920 }
1921 None
1922}
1923
1924pub fn one_use_edges(solid: &BrepSolid) -> usize {
1925 let mut uses: HashMap<u64, usize> = HashMap::default();
1926 for coedge in solid
1927 .shells
1928 .iter()
1929 .flat_map(|shell| &shell.faces)
1930 .flat_map(|face| &face.loops)
1931 .flat_map(|loop_record| &loop_record.coedges)
1932 {
1933 *uses.entry(coedge.edge_id).or_default() += 1;
1934 }
1935 solid
1936 .edges
1937 .iter()
1938 .filter(|edge| !edge.degenerate && uses.get(&edge.id) == Some(&1))
1939 .count()
1940}
1941
1942fn body_volume(solid: &BrepSolid) -> Option<f64> {
1944 if solid.shells.is_empty() {
1945 return Some(0.0);
1946 }
1947 solid_signed_volume(solid).ok().map(f64::abs)
1948}
1949
1950struct InclusionExclusion {
1953 formula: &'static str,
1956 reading: &'static str,
1958 read: f64,
1960 expected: f64,
1962}
1963
1964fn inclusion_exclusion_volume(
1975 first: &BrepSolid,
1976 second: &BrepSolid,
1977 operation: BooleanOperation,
1978 options: &BooleanOptions,
1979 va: Option<f64>,
1980 vb: Option<f64>,
1981 own_first: bool,
1982) -> Option<InclusionExclusion> {
1983 use BooleanOperation::{Intersect, Subtract, Union};
1984 let (va, vb) = (va?, vb?);
1985 let own = match operation {
1986 Intersect => (Intersect, false, "first ∩ second"),
1987 Union => (Union, false, "first ∪ second"),
1988 Subtract => (Subtract, false, "first − second"),
1989 };
1990 let readings = [
1991 (Intersect, false, "first ∩ second"),
1992 (Intersect, true, "second ∩ first"),
1993 (Union, false, "first ∪ second"),
1994 (Union, true, "second ∪ first"),
1995 (Subtract, false, "first − second"),
1996 (Subtract, true, "second − first"),
1997 ];
1998 let own_reading = own_first.then_some(own);
1999 let leading = usize::from(own_first);
2000 for (index, (other, swapped, reading)) in own_reading.into_iter().chain(readings).enumerate() {
2001 if index >= leading && !swapped && std::mem::discriminant(&other) == std::mem::discriminant(&operation) {
2002 continue;
2003 }
2004 let (x, y) = if swapped { (second, first) } else { (first, second) };
2005 let Some(read) = boolean_operation_with_diagnostics(x, y, other, options)
2006 .ok()
2007 .and_then(|outcome| body_volume(&outcome.value))
2008 else {
2009 continue;
2010 };
2011 let intersection = match (other, swapped) {
2012 (Intersect, _) => read,
2013 (Union, _) => va + vb - read,
2014 (Subtract, false) => va - read,
2015 (Subtract, true) => vb - read,
2016 };
2017 let (formula, expected) = match operation {
2018 Intersect => ("V(first ∩ second)", intersection),
2019 Union => ("V(first) + V(second) − V(first ∩ second)", va + vb - intersection),
2020 Subtract => ("V(first) − V(first ∩ second)", va - intersection),
2021 };
2022 return Some(InclusionExclusion { formula, reading, read, expected });
2023 }
2024 None
2025}
2026
2027fn planar_operand_off_its_plane(
2036 first: &BrepSolid,
2037 second: &BrepSolid,
2038 options: &BooleanOptions,
2039) -> Option<(u8, u64, f64, f64)> {
2040 let policy = options
2041 .tolerances
2042 .clone()
2043 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
2044 let weld = crate::tolerance::assembler_weld(policy.model);
2045 let mut worst: Option<(u8, u64, f64)> = None;
2046 for (operand, solid) in [(0u8, first), (1u8, second)] {
2047 let vertex_point = |id: u64| solid.vertices.iter().find(|v| v.id == id).map(|v| v.point);
2048 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2049 let Some(crate::AnalyticSurface::Plane {
2050 origin,
2051 u_dir,
2052 v_dir,
2053 ..
2054 }) = face.surface.analytic()
2055 else {
2056 continue;
2057 };
2058 let [loop_record] = face.loops.as_slice() else {
2059 continue;
2060 };
2061 let Ok(normal) = u_dir.cross(*v_dir).normalized() else {
2062 continue;
2063 };
2064 let mut off_plane = 0.0f64;
2065 let mut straight = true;
2066 for coedge in &loop_record.coedges {
2067 let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else {
2068 straight = false;
2069 break;
2070 };
2071 let (Some(start), Some(end)) =
2072 (vertex_point(edge.start_vertex_id), vertex_point(edge.end_vertex_id))
2073 else {
2074 straight = false;
2075 break;
2076 };
2077 let chord = end.sub(start);
2078 let length = chord.length();
2079 if edge.degenerate || length <= weld {
2080 straight = false;
2081 break;
2082 }
2083 let direction = chord.scale(1.0 / length);
2084 for fraction in [0.25, 0.5, 0.75] {
2085 let Ok(point) = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction) else {
2086 straight = false;
2087 break;
2088 };
2089 let delta = point.sub(start);
2090 let along = delta.dot(direction);
2091 if delta.sub(direction.scale(along)).length() > weld
2092 || along < -weld
2093 || along > length + weld
2094 {
2095 straight = false;
2096 break;
2097 }
2098 }
2099 if !straight {
2100 break;
2101 }
2102 off_plane = off_plane.max(start.sub(*origin).dot(normal).abs());
2103 }
2104 if straight && off_plane > weld && worst.is_none_or(|(_, _, gap)| off_plane > gap) {
2105 worst = Some((operand, face.id, off_plane));
2106 }
2107 }
2108 }
2109 worst.map(|(operand, face_id, gap)| (operand, face_id, gap, weld))
2110}
2111
2112fn volume_within_csg_bounds(operation: BooleanOperation, va: f64, vb: f64, vr: f64) -> bool {
2115 let slack = 1e-2 * (va + vb).max(1.0);
2116 match operation {
2117 BooleanOperation::Union => vr >= va.max(vb) - slack && vr <= va + vb + slack,
2119 BooleanOperation::Subtract => vr <= va + slack && vr >= -slack,
2121 BooleanOperation::Intersect => vr <= va.min(vb) + slack && vr >= -slack,
2123 }
2124}
2125
2126fn reverse_fragment(fragment: &mut FaceFragmentRecord) -> Result<(), KernelRefusal> {
2153 fragment.same_sense = !fragment.same_sense;
2154 for loop_record in &mut fragment.loops {
2155 loop_record.coedges.reverse();
2156 for coedge in &mut loop_record.coedges {
2157 coedge.forward = !coedge.forward;
2158 coedge.pcurve = coedge.pcurve.reversed().or_refuse(KernelStage::Validate, "reversed")?;
2159 }
2160 }
2161 Ok(())
2162}
2163
2164fn build_nary_imprint(
2171 operands: &[BrepSolid],
2172 options: &ImprintOptions,
2173) -> Result<ImprintResultRecord, KernelRefusal> {
2174 let mut section_evidence = false;
2175 let mut vertices: Vec<ImprintVertex> = Vec::new();
2176 let mut pieces: Vec<ImprintPieceRecord> = Vec::new();
2177 let mut by_face: HashMap<(u8, u64), Vec<u64>> = HashMap::default();
2178 let mut edge_splits: HashMap<(u8, u64), Vec<f64>> = HashMap::default();
2179 let mut next_vertex_id: u64 = 1;
2180 let mut next_piece_id: u64 = 1;
2181
2182 for i in 0..operands.len() {
2183 for j in (i + 1)..operands.len() {
2184 let pair = build_imprints(&operands[i], &operands[j], options)?;
2185 let remap = |operand: u8| -> u8 {
2186 if operand == 0 {
2187 i as u8
2188 } else {
2189 j as u8
2190 }
2191 };
2192
2193 section_evidence = section_evidence || pair.section_evidence;
2194 let mut vertex_map: HashMap<u64, u64> = HashMap::default();
2195 for vertex in &pair.vertices {
2196 let global = next_vertex_id;
2197 next_vertex_id += 1;
2198 vertex_map.insert(vertex.id, global);
2199 vertices.push(ImprintVertex {
2200 id: global,
2201 point: vertex.point,
2202 });
2203 }
2204
2205 let mut piece_map: HashMap<u64, u64> = HashMap::default();
2206 for piece in &pair.pieces {
2207 let global = next_piece_id;
2208 next_piece_id += 1;
2209 piece_map.insert(piece.id, global);
2210 let mut mapped = piece.clone();
2211 mapped.id = global;
2212 mapped.start_vertex_id = *vertex_map
2213 .get(&piece.start_vertex_id)
2214 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2215 mapped.end_vertex_id = *vertex_map
2216 .get(&piece.end_vertex_id)
2217 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2218 for pcurve in &mut mapped.pcurves {
2219 pcurve.operand = remap(pcurve.operand);
2220 }
2221 mapped.support_faces = [
2222 FaceKey {
2223 operand: remap(piece.support_faces[0].operand),
2224 face_id: piece.support_faces[0].face_id,
2225 },
2226 FaceKey {
2227 operand: remap(piece.support_faces[1].operand),
2228 face_id: piece.support_faces[1].face_id,
2229 },
2230 ];
2231 pieces.push(mapped);
2232 }
2233
2234 for entry in &pair.by_face {
2235 let list = by_face
2236 .entry((remap(entry.operand), entry.face_id))
2237 .or_default();
2238 for piece_id in &entry.piece_ids {
2239 let global = *piece_map.get(piece_id).ok_or_else(|| {
2240 KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: by_face references unknown piece")
2241 })?;
2242 list.push(global);
2243 }
2244 }
2245
2246 for split in &pair.edge_splits {
2247 edge_splits
2248 .entry((remap(split.operand), split.edge_id))
2249 .or_default()
2250 .extend(split.parameters.iter().copied());
2251 }
2252 }
2253 }
2254
2255 Ok(ImprintResultRecord {
2256 faces_in_unproved_pairs: None,
2257 vertices,
2258 pieces,
2259 tangent_nodes: Vec::new(),
2260 barrier_edges: Vec::new(),
2261 section_evidence,
2262 cosurface_pairs: Vec::new(),
2263 operand_sliver_regions: Vec::new(),
2264 tangent_sections: Vec::new(),
2265 by_face: by_face
2266 .into_iter()
2267 .map(|((operand, face_id), piece_ids)| FaceImprints {
2268 operand,
2269 face_id,
2270 piece_ids,
2271 })
2272 .collect(),
2273 edge_splits: edge_splits
2274 .into_iter()
2275 .map(|((operand, edge_id), parameters)| EdgeSplitRecord {
2276 operand,
2277 edge_id,
2278 parameters,
2279 })
2280 .collect(),
2281 })
2282}
2283
2284pub fn boolean_operation_nary(
2295 operands: &[BrepSolid],
2296 operation: BooleanOperation,
2297) -> Result<BrepSolid, KernelRefusal> {
2298 boolean_operation_nary_with_options(operands, operation, &BooleanOptions::default())
2299}
2300
2301pub fn boolean_operation_nary_with_options(
2307 operands: &[BrepSolid],
2308 operation: BooleanOperation,
2309 options: &BooleanOptions,
2310) -> Result<BrepSolid, KernelRefusal> {
2311 let most = nary_chunk();
2316 if operands.len() > most && nary_chunks_on() {
2317 let mut whole = boolean_operation_nary_with_options(&operands[..most], operation, options)?;
2318 for chunk in operands[most..].chunks(most - 1) {
2319 if let [only] = chunk {
2322 whole = boolean_operation(&whole, only, operation, options)?;
2323 continue;
2324 }
2325 let mut next = Vec::with_capacity(chunk.len() + 1);
2326 next.push(whole);
2327 next.extend_from_slice(chunk);
2328 whole = boolean_operation_nary_with_options(&next, operation, options)?;
2329 }
2330 return Ok(whole);
2331 }
2332 let arranged = boolean_operation_nary_arranged(operands, operation, options);
2333 match arranged {
2334 Err(error) if nary_sequential_fallback_enabled() && operands.len() > 2 && error.message.contains("boolean assembly") => {
2335 let mut whole = operands[0].clone();
2338 for operand in &operands[1..] {
2339 whole = match boolean_operation(&whole, operand, operation, options) {
2340 Ok(solid) => solid,
2341 Err(_) => return Err(error),
2342 };
2343 }
2344 Ok(whole)
2345 }
2346 other => other,
2347 }
2348}
2349
2350const NARY_MOST: usize = 255;
2359
2360fn nary_chunk() -> usize {
2363 NARY_MOST
2364}
2365
2366
2367fn nary_chunks_on() -> bool {
2370 crate::switch!("BREP_NARY_CHUNKS", true)
2371}
2372
2373fn nary_sequential_fallback_enabled() -> bool {
2374 crate::switch!("BREP_NARY_SEQUENTIAL_FALLBACK", true)
2375}
2376
2377fn boolean_operation_nary_arranged(
2378 operands: &[BrepSolid],
2379 operation: BooleanOperation,
2380 options: &BooleanOptions,
2381) -> Result<BrepSolid, KernelRefusal> {
2382 if operands.len() > 1 {
2383 if let Some(scaled) = WorkingScale::of(&operands.iter().collect::<Vec<_>>(), options)? {
2384 return boolean_operation_nary_with_options(&scaled.solids, operation, &scaled.options)
2385 .map_err(|error| scaled.refusal(error))
2386 .and_then(|solid| scaled.back(&solid));
2387 }
2388 }
2389 if operands.is_empty() {
2390 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: no operands provided"));
2391 }
2392 if operands.len() == 1 {
2393 return Ok(operands[0].clone());
2394 }
2395 if operands.len() > nary_chunk() {
2396 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: at most 255 operands supported"));
2397 }
2398 if let Some(aligned) = ball_align::align_balls_nary(operands, operation, options.tolerance) {
2401 return boolean_operation_nary_with_options(&aligned, operation, options);
2402 }
2403 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
2404
2405 let mut policy = KernelTolerances::for_solid(&operands[0], options.tolerance);
2409 for operand in &operands[1..] {
2410 let candidate = KernelTolerances::for_solid(operand, options.tolerance);
2411 if candidate.sew_search > policy.sew_search {
2412 policy = candidate;
2413 }
2414 }
2415 policy.check().or_input(KernelStage::Collect, "tolerances")?;
2416 let tolerance = policy.model;
2417
2418 let mut healed = operands.to_vec();
2421 for operand in &mut healed {
2422 crate::heal::heal_operands(operand, &policy)?;
2423 crate::heal::refit_inherited_trims_reused(operand, &policy)?;
2426 normalize_operand_band_seams(operand)?;
2429 }
2430
2431 let mut imprint_options = options.imprint.clone();
2433 imprint_options.tolerance = tolerance;
2434 let imprint = build_nary_imprint(&healed, &imprint_options)?;
2435
2436 let mut split = Vec::with_capacity(healed.len());
2438 for (index, operand) in healed.iter().enumerate() {
2439 split.push(apply_edge_splits(operand, index as u8, &imprint)?);
2440 }
2441 let mut fragments = Vec::with_capacity(split.len());
2442 for (index, solid) in split.iter().enumerate() {
2443 fragments.push(fragment_solid(solid, index as u8, &imprint)?);
2444 }
2445
2446 let selected = select_fragments_nary(&fragments, &healed, operation, tolerance, debug)?;
2448
2449 let solids: HashMap<u8, &BrepSolid> = split
2451 .iter()
2452 .enumerate()
2453 .map(|(index, solid)| (index as u8, solid))
2454 .collect();
2455 let solid = assemble_fragments(selected, &solids, &imprint, tolerance)?;
2456 let solid = if options.merge_coplanar_faces
2457 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
2458 {
2459 let merged = merge_same_surface_faces_excluding(
2460 &solid,
2461 tolerance,
2462 &options.keep_unmerged_name_substrs,
2463 )?;
2464 let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
2465 rejoin::rejoin_unless_referenced(merged, options, tolerance)
2466 } else {
2467 solid
2468 };
2469 let validation = solid.validate_detailed(&policy);
2470 if !validation.issues.is_empty() {
2471 return Err(KernelRefusal::new(
2472 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
2473 KernelStage::Validate,
2474 format!(
2475 "boolean_operation_nary: invalid result: {:?}",
2476 validation.issues
2477 )));
2478 }
2479 if debug {
2480 if let Ok(report) =
2481 crate::oracle::boolean_semantic_disagreement_nary(&healed, operation, &solid, 300)
2482 {
2483 if report.is_flagged() {
2484 eprintln!(
2485 "[oracle] n-ary semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
2486 report.disagreement_rate,
2487 report.disagreements.len(),
2488 report.considered,
2489 report.sample_disagreement()
2490 );
2491 }
2492 }
2493 }
2494 Ok(solid)
2495}
2496
2497fn attribute_to_tangent_node(error: KernelRefusal, nodes: &[Vec3]) -> KernelRefusal {
2528 let Some(node) = nodes.first() else {
2529 return error;
2530 };
2531 if !error.class.perturbation_eligible()
2532 || matches!(error.class, RefusalClass::TangentNodeSingularity)
2533 {
2534 return error;
2535 }
2536 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
2537 eprintln!(
2538 "boolean: tear downstream of the tangent node at ({:.6},{:.6},{:.6}) attributed to it; the stage read: {}",
2539 node.x, node.y, node.z, error.message
2540 );
2541 }
2542 KernelRefusal::new(
2543 RefusalClass::TangentNodeSingularity,
2544 error.stage,
2545 format!(
2546 "boolean: unsupported singular/tangent-node surface intersection \
2547 at the tangent node at ({:.6},{:.6},{:.6}): the section through it did not \
2548 assemble into a closed shell",
2549 node.x, node.y, node.z
2550 ),
2551 )
2552}
2553
2554pub fn attribute_to_tangent_section(
2576 error: KernelRefusal,
2577 sections: &[crate::imprint::TangentSectionRecord],
2578 origins: &[FaceKey],
2579) -> KernelRefusal {
2580 if sections.is_empty()
2581 || !error.class.perturbation_eligible()
2582 || matches!(error.class, RefusalClass::TangentNodeSingularity)
2583 {
2584 return error;
2585 }
2586 let named = refusal_result_faces(&error.message)
2587 .into_iter()
2588 .filter_map(|id| origins.get(id.checked_sub(1)? as usize).copied())
2589 .collect::<Vec<FaceKey>>();
2590 let involving = |fallback: bool| {
2594 sections.iter().find(|section| {
2595 section.grazing.is_empty() != fallback && named.iter().any(|face| section.faces.contains(face))
2596 })
2597 };
2598 let Some(section) = involving(false).or_else(|| involving(true)) else {
2599 return error;
2600 };
2601 let at = |point: Vec3| {
2604 let shown = |value: f64| if value.abs() < 5e-7 { 0.0 } else { value };
2605 format!("({:.6},{:.6},{:.6})", shown(point.x), shown(point.y), shown(point.z))
2606 };
2607 let pierces = (!section.grazing.is_empty()).then(|| {
2613 let shown = section.grazing.len().min(4);
2614 let mut listed = section.grazing[..shown]
2615 .iter()
2616 .map(|(point, tangency)| format!("{} at |tan·n| = {tangency:.4}", at(*point)))
2617 .collect::<Vec<_>>()
2618 .join(", ");
2619 if section.grazing.len() > shown {
2620 listed.push_str(&format!(" and {} more", section.grazing.len() - shown));
2621 }
2622 listed
2623 });
2624 let pierce_only = section.pierce_only();
2625 let shape = if let (true, Some(pierces)) = (pierce_only, pierces.as_deref()) {
2626 format!(
2627 "cross at a grazing angle: a trim edge pierces the other carrier inside both \
2628 trims at {pierces}, below the marcher's start gate, and no transverse section was \
2629 marched between the pierces — a near-tangent crossing born on a tangent contact \
2630 (a third-order singularity) the imprint does not build yet"
2631 )
2632 } else if section.planar {
2633 format!(
2634 "touch along a tangent curve from {} to {} (length {:.6}, {} stations{}) which the \
2635 imprint does not build yet",
2636 at(section.start),
2637 at(section.end),
2638 section.length,
2639 section.stations,
2640 if section.closed { ", closed" } else { "" }
2641 )
2642 } else {
2643 format!(
2644 "touch along a curve through {} with neither carrier planar, a curved/curved \
2645 tangent contact the lane does not trace yet",
2646 at(section.start)
2647 )
2648 };
2649 let shape = match (pierce_only, pierces) {
2650 (false, Some(pierces)) => format!(
2651 "{shape}; a trim edge also pierces the other carrier inside both trims at {pierces}, \
2652 below the marcher's start gate, with no transverse section marched"
2653 ),
2654 _ => shape,
2655 };
2656 let involved = named
2657 .iter()
2658 .filter(|face| section.faces.contains(face))
2659 .map(|face| format!("{}/{}", face.operand, face.face_id))
2660 .collect::<Vec<_>>()
2661 .join(", ");
2662 KernelRefusal::new(
2663 RefusalClass::TangentNodeSingularity,
2664 error.stage,
2665 format!(
2666 "boolean: unsupported tangent-curve surface intersection between faces {}/{} and {}/{}: \
2667 the carriers {shape}; the refusal names face(s) {involved} the contact involves; {}",
2668 section.first.operand, section.first.face_id, section.second.operand, section.second.face_id,
2669 error.message
2670 ),
2671 )
2672}
2673
2674pub fn refusal_result_faces(message: &str) -> Vec<u64> {
2679 let mut ids = Vec::new();
2680 let digits_after = |text: &str| -> Option<u64> {
2681 let end = text.find(|c: char| !c.is_ascii_digit()).unwrap_or(text.len());
2682 text[..end].parse().ok()
2683 };
2684 for (index, _) in message.match_indices("face ") {
2685 if let Some(id) = digits_after(&message[index + "face ".len()..]) {
2686 ids.push(id);
2687 }
2688 }
2689 if let Some(start) = message.find("on faces [") {
2690 let rest = &message[start + "on faces [".len()..];
2691 let list = &rest[..rest.find(']').unwrap_or(rest.len())];
2692 for entry in list.split(", ") {
2693 let entry = entry.trim_start();
2694 if let Some(id) = digits_after(entry) {
2695 if entry[id.to_string().len()..].starts_with(" '") {
2696 ids.push(id);
2697 }
2698 }
2699 }
2700 }
2701 ids.sort_unstable();
2702 ids.dedup();
2703 ids
2704}
2705
2706pub fn boolean_operation_with_diagnostics(
2707 first: &BrepSolid,
2708 second: &BrepSolid,
2709 operation: BooleanOperation,
2710 options: &BooleanOptions,
2711) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2712 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2713 let mut outcome = boolean_operation_with_diagnostics(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
2714 .map_err(|error| scaled.refusal(error))?;
2715 outcome.value = scaled.back(&outcome.value)?;
2716 outcome.diagnostics.count_n("working_scale.fired", 1);
2717 outcome.diagnostics.measure_max("working_scale.factor", scaled.factor);
2718 return Ok(outcome);
2719 }
2720 let _account = profile::Scope::new("boolean.other");
2721 let (first_aligned, second_aligned) = ball_align::align_balls(first, second, operation, options.tolerance);
2724 let (first, second) = (first_aligned.as_ref(), second_aligned.as_ref());
2725 let closed_inputs = matches!(std::env::var("BREP_CLOSED_OPERAND_INPUT").as_deref(), Err(_) | Ok("1") | Ok("on"));
2726 if let (true, Some(later)) = (reseat::seam_reseat_enabled(), &options.seam_reseat_later_references) {
2727 let started = Instant::now();
2728 let (first, second) = reseat::reseat_tangent_seams(first, second, later, options.tolerance);
2729 profile_stage("seam_prepare_ms", started.elapsed().as_secs_f64() * 1000.0);
2730 return boolean_operation_with_diagnostics_impl(&first, &second, operation, options, closed_inputs).map(without_sliver_shells);
2731 }
2732 let cylinders = reseat::seam_reseat_cylinders_mode();
2735 if reseat::seam_reseat_enabled() && cylinders != crate::env_read::Mode::Off {
2736 let kinds = reseat::ContactKinds { planes: false, cylinders: true };
2737 let volume = |result: &Result<KernelOutcome<BrepSolid>, KernelRefusal>| {
2738 result.as_ref().ok().and_then(|outcome| crate::solid_mass_properties(&outcome.value).ok()).map(|mass| mass.volume)
2739 };
2740 if reseat::seam_reseat_retry_enabled() {
2741 let plain = boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells);
2747 if plain.is_ok() {
2748 return plain;
2749 }
2750 let (reseated_first, reseated_second) = reseat::reseat_tangent_seams_of(first, second, &[], options.tolerance, kinds);
2751 let moved = matches!(reseated_first, std::borrow::Cow::Owned(_)) || matches!(reseated_second, std::borrow::Cow::Owned(_));
2752 if !moved {
2753 return plain;
2754 }
2755 let reseated = crate::imprint::driver::with_tangent_cylinder_filter(|| {
2756 boolean_operation_with_diagnostics_impl(&reseated_first, &reseated_second, operation, options, closed_inputs).map(without_sliver_shells)
2757 });
2758 if cylinders == crate::env_read::Mode::Check {
2759 eprintln!(
2760 "boolean.seam_reseat_cylinders check: plain refused, reseated retry {} volume {:?}",
2761 if reseated.is_ok() { "built" } else { "refused" },
2762 volume(&reseated)
2763 );
2764 return plain;
2765 }
2766 return match reseated {
2767 Ok(mut outcome) => {
2768 outcome.diagnostics.count_n("seam_reseat_cylinders.retry_built", 1);
2769 Ok(outcome)
2770 }
2771 Err(_) => plain,
2772 };
2773 }
2774 let (reseated_first, reseated_second) = reseat::reseat_tangent_seams_of(first, second, &[], options.tolerance, kinds);
2775 let moved = matches!(reseated_first, std::borrow::Cow::Owned(_)) || matches!(reseated_second, std::borrow::Cow::Owned(_));
2776 if moved {
2777 let reseated = boolean_operation_with_diagnostics_impl(&reseated_first, &reseated_second, operation, options, closed_inputs).map(without_sliver_shells);
2778 if cylinders == crate::env_read::Mode::On {
2779 return reseated;
2780 }
2781 let plain = boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells);
2782 eprintln!(
2783 "boolean.seam_reseat_cylinders check: plain {} volume {:?}, reseated {} volume {:?}",
2784 if plain.is_ok() { "built" } else { "refused" },
2785 volume(&plain),
2786 if reseated.is_ok() { "built" } else { "refused" },
2787 volume(&reseated)
2788 );
2789 return plain;
2790 }
2791 }
2792 boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells)
2793}
2794
2795fn without_sliver_shells(mut outcome: KernelOutcome<BrepSolid>) -> KernelOutcome<BrepSolid> {
2797 let dropped = drop_sliver_shells(&mut outcome.value);
2798 if dropped > 0 {
2799 outcome.diagnostics.count_n("sliver_shell.dropped", dropped as u64);
2800 }
2801 outcome
2802}
2803
2804pub fn boolean_operation_with_diagnostics_impl(
2805 first: &BrepSolid,
2806 second: &BrepSolid,
2807 operation: BooleanOperation,
2808 options: &BooleanOptions,
2809 closed_inputs: bool,
2810) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2811 let _coedge_memo = crate::topology::CoedgeMemoScope::open(true);
2814 if matches!(operation, BooleanOperation::Intersect)
2817 && [first, second].iter().any(|body| body.kind == crate::BodyKind::Sheet)
2818 && match std::env::var("BREP_SHEET_TRIM").as_deref() {
2819 Ok("1") => true,
2820 Ok("0") => false,
2821 _ => options.sheet_trim,
2822 }
2823 {
2824 return sheet::trim(first, second, options);
2825 }
2826 if matches!(operation, BooleanOperation::Union | BooleanOperation::Subtract) {
2835 if let Some(operand) = [first, second]
2836 .iter()
2837 .position(|solid| solid.kind == crate::BodyKind::Sheet)
2838 {
2839 return Err(KernelRefusal::input(
2840 KernelStage::Collect,
2841 "sheet_operand",
2842 format!(
2843 "boolean: operand {operand} is a Sheet, which encloses no solid; union and \
2844 subtract of a sheet are refused; Intersect trims a Sheet by a Solid"
2845 ),
2846 ));
2847 }
2848 }
2849 let mut outcome = boolean_operation_with_diagnostics_core(first, second, operation, options)?;
2855 let closure_started = closed_inputs.then(Instant::now);
2856 if closed_inputs {
2857 for (operand, solid) in [first, second].into_iter().enumerate() {
2858 let open = one_use_edges(solid);
2859 if open > 0 {
2860 return Err(KernelRefusal::input(KernelStage::Collect, "operand_closure", format!(
2861 "boolean: operand {operand} is not a closed shell: {open} of its edges bound only one face, so its inside is undefined"
2862 )));
2863 }
2864 }
2865 }
2866 if let Some(started) = closure_started {
2867 let ms = started.elapsed().as_secs_f64() * 1000.0;
2868 profile_stage("operand_closure_ms", ms);
2869 outcome.diagnostics.measure_max("timing.operand_closure_ms", ms);
2870 }
2871 Ok(outcome)
2872}
2873
2874fn boolean_operation_with_diagnostics_core(
2875 first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions,
2876) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2877
2878 if let Some(offset) = crate::recentre::control_offset_at_entry() {
2881 return boolean_operation_with_diagnostics_at_offset(first, second, operation, options, offset);
2882 }
2883 let mut bounds = operand_bounds(first);
2886 bounds.include(operand_bounds(second));
2887 if let Some(offset) = crate::recentre::guard_offset(bounds) {
2888 crate::recentre::profile_fired("boolean", offset, bounds);
2889 let mut outcome = boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Guard)?;
2890 outcome.diagnostics.count_n("recentre.fired", 1);
2891 outcome.diagnostics.measure_max("recentre.distance", offset.length());
2892 return Ok(outcome);
2893 }
2894 let mut tangent_nodes = Vec::new();
2895 let (mut outcome, soundness_candidates) =
2896 boolean_pipeline(first, second, operation, options, &mut tangent_nodes)
2897 .map_err(|error| attribute_to_tangent_node(error, &tangent_nodes))?;
2898 let stage_started = Instant::now();
2911 let accepted = match &soundness_candidates {
2912 Some(candidates) => crate::accept_sound_against_scoped(&[first, second], outcome.value, "boolean", candidates),
2915 None => crate::accept_sound_against(&[first, second], outcome.value, "boolean"),
2916 };
2917 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2918 profile_stage("soundness_ms", stage_ms);
2919 outcome.diagnostics.measure_max("timing.soundness_ms", stage_ms);
2920 outcome.value = accepted?;
2921 Ok(outcome)
2922}
2923
2924pub fn boolean_operation_with_diagnostics_at_offset(
2928 first: &BrepSolid,
2929 second: &BrepSolid,
2930 operation: BooleanOperation,
2931 options: &BooleanOptions,
2932 offset: Vec3,
2933) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2934 boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Control)
2935}
2936
2937fn boolean_translated(
2939 first: &BrepSolid,
2940 second: &BrepSolid,
2941 operation: BooleanOperation,
2942 options: &BooleanOptions,
2943 offset: Vec3,
2944 kind: crate::recentre::EntryKind,
2945) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2946 let _entry = crate::recentre::TranslatedEntry::open(kind);
2947 let translate = |solid: &BrepSolid, offset: Vec3| {
2948 crate::recentre::translate_solid(solid, offset).map_err(|message| {
2949 KernelRefusal::internal(
2950 KernelStage::Collect,
2951 "translation_control",
2952 format!("boolean: the translation control could not move an operand: {message}"),
2953 )
2954 })
2955 };
2956 let moved_first = translate(first, offset)?;
2957 let moved_second = translate(second, offset)?;
2958 let outcome = boolean_operation_with_diagnostics(&moved_first, &moved_second, operation, options)?;
2959 let value = translate(&outcome.value, offset.scale(-1.0))?;
2960 Ok(KernelOutcome { value, diagnostics: outcome.diagnostics })
2961}
2962
2963fn profile_stage(code: &str, ms: f64) {
2967 let row = match code {
2968 "heal_ms" => Some("boolean.operand_prepare"),
2969 "imprint_ms" => Some("boolean.imprint"),
2970 "edge_split_ms" => Some("boolean.edge_split"),
2971 "fragment_ms" => Some("boolean.fragment"),
2972 "select_ms" => Some("boolean.select"),
2973 "assemble_ms" => Some("boolean.assemble"),
2974 "face_merge_ms" => Some("boolean.face_merge"),
2975 "soundness_ms" => Some("boolean.soundness"),
2976 "operand_closure_ms" => Some("boolean.operand_closure"),
2977 "seam_prepare_ms" => Some("boolean.seam_prepare"),
2978 "final_validate_ms" => Some("boolean.final_validate"),
2979 _ => None,
2980 };
2981 if let Some(row) = row { profile::record(row, ms); }
2982 if crate::profile::profile_enabled() {
2983 profile_line!("boolean.{code}={ms:.2}");
2984 }
2985}
2986
2987struct BooleanStageDump {
2992 directory: std::path::PathBuf,
2993 serial: usize,
2994}
2995
2996impl BooleanStageDump {
2997 fn open() -> Option<Self> {
2998 static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2999 let directory = std::env::var("BREP_BOOLEAN_DUMP").ok().filter(|value| !value.is_empty())?;
3000 let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3001 Some(Self { directory: directory.into(), serial })
3002 }
3003
3004 fn write<T: Serialize + ?Sized>(&self, stage: &str, value: &T) {
3005 let path = self.directory.join(format!("{:03}-{stage}.json", self.serial));
3006 match serde_json::to_string(value) {
3007 Ok(text) => {
3008 if let Err(error) = std::fs::write(&path, text) {
3009 eprintln!("BREP_BOOLEAN_DUMP {}: {error}", path.display());
3010 }
3011 }
3012 Err(error) => eprintln!("BREP_BOOLEAN_DUMP {stage}: {error}"),
3013 }
3014 }
3015}
3016
3017pub fn boolean_policy(
3019 first: &BrepSolid,
3020 second: &BrepSolid,
3021 options: &BooleanOptions,
3022) -> Result<KernelTolerances, KernelRefusal> {
3023 let policy = options
3024 .tolerances
3025 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
3026 policy.check().or_input(KernelStage::Collect, "tolerances")?;
3027 Ok(policy)
3028}
3029
3030fn prepared_operands(
3033 first: &BrepSolid,
3034 second: &BrepSolid,
3035 policy: &KernelTolerances,
3036) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
3037 let stage_started = Instant::now();
3046 let mut first_owned = first.clone();
3047 let mut second_owned = second.clone();
3048 crate::heal::heal_operands(&mut first_owned, policy)?;
3049 crate::heal::heal_operands(&mut second_owned, policy)?;
3050 profile_stage("heal.operands_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
3051 let refit_started = Instant::now();
3055 crate::heal::refit_inherited_trims_reused(&mut first_owned, policy)?;
3056 crate::heal::refit_inherited_trims_reused(&mut second_owned, policy)?;
3057 profile_stage("heal.refit_ms", refit_started.elapsed().as_secs_f64() * 1_000.0);
3058 if crate::profile::profile_enabled() {
3059 let (hits, misses) = crate::reading_memo::counts();
3060 profile_line!("boolean.reading_memo hits={hits} misses={misses}");
3061 let (served, stored) = crate::heal::refit_memo_counts_served_stored();
3062 profile_line!("boolean.refit_memo served={served} stored={stored}");
3063 let (served, stored, mismatches) = crate::heal::claim_record_memo_counts();
3064 profile_line!("boolean.claim_record_memo served={served} stored={stored} check_mismatches={mismatches}");
3065 }
3066 profile_stage("heal_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
3067 normalize_operand_band_seams(&mut first_owned)?;
3072 normalize_operand_band_seams(&mut second_owned)?;
3073 Ok((first_owned, second_owned))
3074}
3075
3076fn boolean_imprint_options(options: &BooleanOptions, tolerance: f64) -> ImprintOptions {
3077 let mut imprint_options = options.imprint.clone();
3078 imprint_options.tolerance = tolerance;
3079 imprint_options
3080}
3081
3082pub fn boolean_split_operands(
3092 first: &BrepSolid,
3093 second: &BrepSolid,
3094 options: &BooleanOptions,
3095) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
3096 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
3097 let (split_first, split_second) = boolean_split_operands(&scaled.solids[0], &scaled.solids[1], &scaled.options)
3098 .map_err(|error| scaled.refusal(error))?;
3099 return Ok((scaled.back(&split_first)?, scaled.back(&split_second)?));
3100 }
3101 let policy = boolean_policy(first, second, options)?;
3102 let (first, second) = prepared_operands(first, second, &policy)?;
3103 let imprint = build_imprints(&first, &second, &boolean_imprint_options(options, policy.model))?;
3104 let (split_first, _) = apply_edge_splits_with_map(&first, 0, &imprint)?;
3105 let (split_second, _) = apply_edge_splits_with_map(&second, 1, &imprint)?;
3106 Ok((split_first, split_second))
3107}
3108
3109fn operand_bounds(solid: &BrepSolid) -> crate::Aabb {
3113 let mut bounds = crate::Aabb::from_points(solid.vertices.iter().map(|vertex| vertex.point));
3114 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
3115 match crate::Aabb::from_surface_controls(&face.surface) {
3116 Ok(face_bounds) => bounds.include(face_bounds),
3117 Err(_) => {
3118 return crate::Aabb {
3119 minimum: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
3120 maximum: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
3121 }
3122 }
3123 }
3124 }
3125 bounds
3126}
3127
3128fn line_or_point_contact(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
3134 apart_axes(bounds) >= 2 && plain_hull_solid(first) && plain_hull_solid(second)
3135}
3136
3137fn boxes_share_no_interior(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
3140 apart_axes(bounds) >= 1 && plain_hull_solid(first) && plain_hull_solid(second)
3141}
3142
3143fn apart_axes([a, b]: [crate::Aabb; 2]) -> usize {
3145 let apart = |a_min: f64, a_max: f64, b_min: f64, b_max: f64| a_max <= b_min || b_max <= a_min;
3146 [
3147 apart(a.minimum.x, a.maximum.x, b.minimum.x, b.maximum.x),
3148 apart(a.minimum.y, a.maximum.y, b.minimum.y, b.maximum.y),
3149 apart(a.minimum.z, a.maximum.z, b.minimum.z, b.maximum.z),
3150 ]
3151 .into_iter()
3152 .filter(|&apart| apart)
3153 .count()
3154}
3155
3156fn plain_hull_solid(solid: &BrepSolid) -> bool {
3158 solid.kind == crate::BodyKind::Solid
3159 && solid.cells.is_empty()
3160 && solid.shells.iter().flat_map(|shell| &shell.faces).all(|face| {
3161 face.surface.control_points.iter().flatten().all(|control| control.w > 0.0 && control.w.is_finite())
3162 })
3163}
3164
3165fn scope_proved_apart_on() -> bool {
3169 switch!(live "BREP_SCOPE_PROVED_APART", true)
3170}
3171
3172fn soundness_candidates(
3187 solid: &BrepSolid,
3188 scope: &AssemblyScope,
3189 bounds: [crate::Aabb; 2],
3190 band: f64,
3191 unproved: Option<&HashSet<crate::imprint::FaceKey>>,
3192) -> HashSet<u64> {
3193 let mut candidates = HashSet::default();
3194 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
3195 if scope.examined.contains(&face.id) {
3196 candidates.insert(face.id);
3197 continue;
3198 }
3199 let Some(&operand) = scope.operand_of.get(&face.id) else {
3200 candidates.insert(face.id);
3201 continue;
3202 };
3203 let other = bounds[usize::from(operand == 0)];
3204 match crate::Aabb::from_surface_controls(&face.surface) {
3205 Ok(face_bounds) if !face_bounds.intersects(other, band) => {}
3206 _ => {
3207 let proved_clear = unproved.is_some_and(|unproved| {
3208 scope.source_of.get(&face.id).is_some_and(|key| !unproved.contains(key))
3209 });
3210 if !proved_clear {
3211 candidates.insert(face.id);
3212 }
3213 }
3214 }
3215 }
3216 candidates
3217}
3218
3219
3220fn touching_empty_enabled() -> bool {
3228 switch!("BREP_TOUCHING_EMPTY", true)
3229}
3230
3231thread_local! {
3232 static TOUCHING_PROOF: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3235}
3236
3237fn hair_deep_overlap(first: &BrepSolid, second: &BrepSolid, tolerance: f64) -> bool {
3244 use crate::AnalyticSurface as A;
3245 fn faces(solid: &BrepSolid) -> Vec<(&crate::AnalyticSurface, crate::spatial::Aabb, &crate::NurbsSurface, &crate::FaceRecord)> {
3246 solid
3247 .shells
3248 .iter()
3249 .flat_map(|shell| &shell.faces)
3250 .filter_map(|face| Some((face.surface.analytic()?, crate::Aabb::from_surface_controls(&face.surface).ok()?, &face.surface, face)))
3251 .collect()
3252 }
3253 let along = |surface: &crate::NurbsSurface, axis: Vec3| {
3255 surface.control_points.iter().flatten().filter_map(|control| control.point().ok()).fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), point| {
3256 let at = point.dot(axis);
3257 (low.min(at), high.max(at))
3258 })
3259 };
3260 let crossing = |distance: f64, ra: f64, rb: f64| {
3261 let outer = ra + rb - distance;
3262 let nested = distance - (ra - rb).abs();
3263 outer > tolerance && nested > tolerance
3264 };
3265 let boxes_overlap = |a: &crate::spatial::Aabb, b: &crate::spatial::Aabb| {
3266 (a.maximum.x.min(b.maximum.x) - a.minimum.x.max(b.minimum.x)) > tolerance
3267 && (a.maximum.y.min(b.maximum.y) - a.minimum.y.max(b.minimum.y)) > tolerance
3268 && (a.maximum.z.min(b.maximum.z) - a.minimum.z.max(b.minimum.z)) > tolerance
3269 };
3270 for (a, box_a, surface_a, face_a) in faces(first) {
3271 for (b, box_b, surface_b, face_b) in faces(second) {
3272 if !boxes_overlap(&box_a, &box_b) {
3273 continue;
3274 }
3275 match (a, b) {
3276 (A::RuledRevolution { frame: fa, rho0: a0, rho1: a1, .. }, A::RuledRevolution { frame: fb, rho0: b0, rho1: b1, .. })
3277 if (a0 - a1).abs() <= tolerance && (b0 - b1).abs() <= tolerance =>
3278 {
3279 let offset = fb.origin.sub(fa.origin);
3280 let normal = fa.axis.cross(fb.axis);
3281 if normal.length() <= 1e-12 {
3284 let (low_a, high_a) = along(surface_a, fa.axis);
3285 let (low_b, high_b) = along(surface_b, fa.axis);
3286 if high_a.min(high_b) - low_a.max(low_b) <= tolerance {
3287 continue;
3288 }
3289 }
3290 let apart = if normal.length() <= 1e-12 {
3291 offset.sub(fa.axis.scale(offset.dot(fa.axis))).length()
3292 } else {
3293 offset.dot(normal).abs() / normal.length()
3294 };
3295 if crossing(apart, a0.abs(), b0.abs()) {
3296 return true;
3297 }
3298 }
3299 (A::Sphere { frame: fa, radius: ra }, A::Sphere { frame: fb, radius: rb }) => {
3300 if crossing(fb.origin.sub(fa.origin).length(), *ra, *rb)
3305 && !circle_off_face(face_a, first, (fa.origin, *ra), (fb.origin, *rb), tolerance)
3306 && !circle_off_face(face_b, second, (fb.origin, *rb), (fa.origin, *ra), tolerance)
3307 {
3308 return true;
3309 }
3310 }
3311 _ => {}
3312 }
3313 }
3314 }
3315 false
3316}
3317
3318fn circle_off_face(face: &crate::FaceRecord, solid: &BrepSolid, own: (Vec3, f64), other: (Vec3, f64), tolerance: f64) -> bool {
3326 use crate::classification::{parameter_point_in_face, PolygonClass};
3327 let ((ca, ra), (cb, rb)) = (own, other);
3328 if face.loops.iter().all(|lp| lp.coedges.is_empty()) {
3329 return false;
3330 }
3331 fn clear(curve: &crate::NurbsCurve, depth: u32, centre: Vec3, radius: f64, tolerance: f64) -> bool {
3336 let points: Option<Vec<Vec3>> = curve.control_points.iter().map(|control| if control.w > 0.0 { control.point().ok() } else { None }).collect();
3337 let Some(points) = points else { return false };
3338 if points.iter().all(|point| point.sub(centre).length() < radius - tolerance) {
3339 return true;
3340 }
3341 let (mut low, mut high) = (Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY));
3342 for point in &points {
3343 low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
3344 high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
3345 }
3346 let near = Vec3::new(centre.x.clamp(low.x, high.x), centre.y.clamp(low.y, high.y), centre.z.clamp(low.z, high.z));
3347 if near.sub(centre).length() > radius + tolerance {
3348 return true;
3349 }
3350 if depth == 0 {
3351 return false;
3352 }
3353 let Ok([t0, t1]) = curve.domain() else { return false };
3354 match curve.split(0.5 * (t0 + t1)) {
3355 Ok((left, right)) => clear(&left, depth - 1, centre, radius, tolerance) && clear(&right, depth - 1, centre, radius, tolerance),
3356 Err(_) => false,
3357 }
3358 }
3359 for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
3360 let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else { return false };
3361 let Ok([d0, d1]) = edge.curve.domain() else { return false };
3362 let mut span = edge.curve.clone();
3364 if edge.t1 < d1 {
3365 match span.split(edge.t1) {
3366 Ok((left, _)) => span = left,
3367 Err(_) => return false,
3368 }
3369 }
3370 if edge.t0 > d0 {
3371 match span.split(edge.t0) {
3372 Ok((_, right)) => span = right,
3373 Err(_) => return false,
3374 }
3375 }
3376 if !clear(&span, 10, cb, rb, tolerance) {
3377 return false;
3378 }
3379 }
3380 let axis = cb.sub(ca);
3381 let distance = axis.length();
3382 let Ok(n) = axis.normalized() else { return false };
3383 let along = (distance * distance + ra * ra - rb * rb) / (2.0 * distance);
3384 let across = ra * ra - along * along;
3385 let Ok(side) = n.perpendicular() else { return false };
3386 if !(across > 0.0) {
3387 return false;
3388 }
3389 let point = ca.add(n.scale(along)).add(side.scale(across.sqrt()));
3390 let Ok(projection) = crate::project_point_to_surface(&face.surface, point) else { return false };
3391 matches!(parameter_point_in_face(face, crate::Vec2 { x: projection.u, y: projection.v }, 1e-9), Ok(PolygonClass::Outside))
3392}
3393
3394
3395fn empty_solid() -> BrepSolid {
3397 BrepSolid {
3398 mass_properties_cache: Default::default(),
3399 cells: Default::default(),
3400 id: 0,
3401 vertices: Vec::new(),
3402 edges: Vec::new(),
3403 shells: Vec::new(),
3404 genus: 0,
3405 kind: crate::BodyKind::Solid,
3406 }
3407}
3408
3409fn concatenate_disjoint(first: &BrepSolid, second: &BrepSolid) -> BrepSolid {
3415 let mut vertices = Vec::new();
3416 let mut edges = Vec::new();
3417 let mut shells = Vec::new();
3418 let mut used_face_names = HashSet::<String>::default();
3419 let (mut next_face_id, mut next_loop_id, mut next_coedge_id) = (1u64, 1u64, 1u64);
3420 for operand in [first, second] {
3421 let vertex_base = vertices.len() as u64;
3422 let edge_base = edges.len() as u64;
3423 let mut vertex_ids: HashMap<u64, u64> = HashMap::default();
3424 for (index, vertex) in operand.vertices.iter().enumerate() {
3425 let id = vertex_base + index as u64 + 1;
3426 vertex_ids.insert(vertex.id, id);
3427 vertices.push(VertexRecord { id, point: vertex.point });
3428 }
3429 let mut edge_ids: HashMap<u64, u64> = HashMap::default();
3430 for (index, edge) in operand.edges.iter().enumerate() {
3431 let id = edge_base + index as u64 + 1;
3432 edge_ids.insert(edge.id, id);
3433 edges.push(EdgeRecord {
3434 id,
3435 curve: edge.curve.clone(),
3436 t0: edge.t0,
3437 t1: edge.t1,
3438 start_vertex_id: vertex_ids.get(&edge.start_vertex_id).copied().unwrap_or(edge.start_vertex_id),
3439 end_vertex_id: vertex_ids.get(&edge.end_vertex_id).copied().unwrap_or(edge.end_vertex_id),
3440 degenerate: edge.degenerate,
3441 name: edge.name.clone(),
3442 });
3443 }
3444 for shell in &operand.shells {
3445 let mut faces = Vec::with_capacity(shell.faces.len());
3446 for face in &shell.faces {
3447 let loops = face
3448 .loops
3449 .iter()
3450 .map(|loop_record| {
3451 let coedges = loop_record
3452 .coedges
3453 .iter()
3454 .map(|coedge| {
3455 let id = next_coedge_id;
3456 next_coedge_id += 1;
3457 CoedgeRecord {
3458 id,
3459 edge_id: edge_ids.get(&coedge.edge_id).copied().unwrap_or(coedge.edge_id),
3460 forward: coedge.forward,
3461 pcurve: coedge.pcurve.clone(),
3462 }
3463 })
3464 .collect();
3465 let id = next_loop_id;
3466 next_loop_id += 1;
3467 LoopRecord { id, coedges }
3468 })
3469 .collect();
3470 let name = face.name.clone().map(|base| {
3471 if used_face_names.insert(base.clone()) {
3472 base
3473 } else {
3474 let mut suffix = 1usize;
3475 loop {
3476 let candidate = format!("{base}_{suffix}");
3477 if used_face_names.insert(candidate.clone()) {
3478 break candidate;
3479 }
3480 suffix += 1;
3481 }
3482 }
3483 });
3484 faces.push(FaceRecord {
3485 id: next_face_id,
3486 surface: face.surface.clone(),
3487 same_sense: face.same_sense,
3488 loops,
3489 name,
3490 });
3491 next_face_id += 1;
3492 }
3493 shells.push(ShellRecord { id: shells.len() as u64 + 1, faces });
3494 }
3495 }
3496 BrepSolid {
3497 mass_properties_cache: Default::default(),
3498 cells: Default::default(),
3499 id: 1,
3500 vertices,
3501 edges,
3502 shells,
3503 genus: first.genus + second.genus,
3504 kind: crate::BodyKind::Solid,
3505 }
3506}
3507
3508fn boolean_pipeline(
3511 first: &BrepSolid,
3512 second: &BrepSolid,
3513 operation: BooleanOperation,
3514 options: &BooleanOptions,
3515 tangent_nodes: &mut Vec<Vec3>,
3516) -> Result<(KernelOutcome<BrepSolid>, Option<HashSet<u64>>), KernelRefusal> {
3517 let _work = crate::imprint::work_profile::Scope::open("boolean");
3518 let replaced_operands = operand_state::replace_operands(first, second, operation, options);
3519 let (first, second) = match &replaced_operands {
3520 Some((first, second)) => (first, second),
3521 None => (first, second),
3522 };
3523 let policy = boolean_policy(first, second, options)?;
3524 let tolerance = policy.model;
3525 let bounds = [operand_bounds(first), operand_bounds(second)];
3540 let disjoint = disjoint_fast_path(options) && !bounds[0].intersects(bounds[1], policy.sew_search);
3541 let contact = !disjoint
3542 && contact_fast_path(options)
3543 && options.seam_reseat_later_references.is_some()
3544 && line_or_point_contact(first, second, bounds);
3545 let contact = contact
3550 || (!disjoint
3551 && matches!(operation, BooleanOperation::Intersect)
3552 && contact_fast_path(options)
3553 && boxes_share_no_interior(first, second, bounds));
3554 if disjoint || contact {
3555 let operation_started = Instant::now();
3556 let mut diagnostics = KernelDiagnostics::default();
3557 diagnostics.count_n(
3558 "collect.faces",
3559 first.shells.iter().chain(&second.shells).map(|shell| shell.faces.len() as u64).sum(),
3560 );
3561 diagnostics.count(if contact { "boolean.contact_fast_path" } else { "boolean.disjoint_fast_path" });
3562 diagnostics.measure_max("tolerance.model", policy.model);
3563 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3564 let value = match operation {
3565 BooleanOperation::Union => concatenate_disjoint(first, second),
3566 BooleanOperation::Subtract => first.clone(),
3567 BooleanOperation::Intersect => {
3568 diagnostics.event(
3569 DiagnosticSeverity::Info,
3570 KernelStage::Select,
3571 "boolean.empty_result",
3572 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
3573 );
3574 empty_solid()
3575 }
3576 };
3577 let stage_ms = operation_started.elapsed().as_secs_f64() * 1_000.0;
3578 profile_stage("disjoint_fast_path_ms", stage_ms);
3579 diagnostics.measure_max("timing.total_ms", stage_ms);
3580 return Ok((KernelOutcome { value, diagnostics }, Some(HashSet::default())));
3581 }
3582 let heal_started = Instant::now();
3583 let (first_owned, second_owned) = prepared_operands(first, second, &policy)?;
3584 let heal_ms = heal_started.elapsed().as_secs_f64() * 1_000.0;
3585 let first = &first_owned;
3586 let second = &second_owned;
3587
3588 let mut diagnostics = KernelDiagnostics::default();
3589 diagnostics.measure_max("timing.heal_ms", heal_ms);
3592 let fit_scope = crate::PcurveFitScope::open();
3597 let polyline_scope = crate::PolylineFitScope::open();
3601 let operation_started = Instant::now();
3602 diagnostics.count_n(
3603 "collect.faces",
3604 first
3605 .shells
3606 .iter()
3607 .chain(&second.shells)
3608 .map(|shell| shell.faces.len() as u64)
3609 .sum(),
3610 );
3611 diagnostics.measure_max("tolerance.model", policy.model);
3612 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3613
3614 let imprint_options = boolean_imprint_options(options, tolerance);
3615 let stage_started = Instant::now();
3616 let imprint = build_imprints(first, second, &imprint_options)?;
3617 tangent_nodes.extend_from_slice(&imprint.tangent_nodes);
3618 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
3619 for piece in &imprint.pieces {
3620 let start = piece.curve.evaluate(piece.t0);
3621 let end = piece.curve.evaluate(piece.t1);
3622 eprintln!(
3623 "piece {} supports={:?} t=[{:.6},{:.6}] start={:?} end={:?}",
3624 piece.id, piece.support_faces, piece.t0, piece.t1, start, end
3625 );
3626 }
3627 for entry in &imprint.by_face {
3628 eprintln!(
3629 "by_face operand={} face={} pieces={:?}",
3630 entry.operand, entry.face_id, entry.piece_ids
3631 );
3632 }
3633 for split in &imprint.edge_splits {
3634 eprintln!(
3635 "edge_split operand={} edge={} params={:?}",
3636 split.operand, split.edge_id, split.parameters
3637 );
3638 }
3639 }
3640 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3641 profile_stage("imprint_ms", stage_ms);
3642 diagnostics.measure_max("timing.imprint_ms", stage_ms);
3643 diagnostics.count_n("intersect.pieces", imprint.pieces.len() as u64);
3644 diagnostics.count_n("intersect.vertices", imprint.vertices.len() as u64);
3645 diagnostics.count_n("intersect.edge_splits", imprint.edge_splits.len() as u64);
3646 let (march_swap_rescues, clip_swap_rescues) = crate::imprint::take_rescue_firings();
3647 diagnostics.count_n("intersect.march_swap_rescue", march_swap_rescues);
3648 diagnostics.count_n("intersect.clip_swap_rescue", clip_swap_rescues);
3649 let touch = TouchCensus::build([first, second], &imprint);
3650 touch.report(&mut diagnostics);
3651 let stage_started = Instant::now();
3652 let (split_first, split_map_first) = apply_edge_splits_with_map(first, 0, &imprint)?;
3653 let (split_second, split_map_second) = apply_edge_splits_with_map(second, 1, &imprint)?;
3654 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3655 profile_stage("edge_split_ms", stage_ms);
3656 diagnostics.measure_max("timing.edge_split_ms", stage_ms);
3657 let stage_started = Instant::now();
3658 crate::classification::classify_profile_begin();
3659 let fragments_a = crate::fragment::fragment_solid_against(&split_first, 0, &imprint, crate::fragment::bounded_carriers(second).then_some((bounds[1], policy.sew_search)))?;
3660 let fragments_b = crate::fragment::fragment_solid_against(&split_second, 1, &imprint, crate::fragment::bounded_carriers(first).then_some((bounds[0], policy.sew_search)))?;
3661 crate::classification::classify_profile_report("fragment");
3662 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3663 profile_stage("fragment_ms", stage_ms);
3664 diagnostics.measure_max("timing.fragment_ms", stage_ms);
3665 diagnostics.count_n(
3666 "fragment.candidates",
3667 (fragments_a.len() + fragments_b.len()) as u64,
3668 );
3669 touch.report_fragments(&[&fragments_a, &fragments_b], &mut diagnostics);
3670 let a_surface_samples: Vec<Vec3> = fragments_a
3675 .iter()
3676 .flat_map(|fragment| {
3677 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
3678 })
3679 .collect();
3680 let b_surface_samples: Vec<Vec3> = fragments_b
3681 .iter()
3682 .flat_map(|fragment| {
3683 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
3684 })
3685 .collect();
3686 let stage_started = Instant::now();
3687 let mut barrier_edges: HashSet<(u8, u64)> = imprint
3688 .pieces
3689 .iter()
3690 .filter_map(|piece| piece.shared_edge.map(|(operand, edge_id, _)| (operand, edge_id)))
3691 .collect();
3692 barrier_edges.extend(imprint.barrier_edges.iter().copied());
3693 for (operand, split_map) in [(0u8, &split_map_first), (1u8, &split_map_second)] {
3699 let minted: Vec<(u8, u64)> = barrier_edges
3700 .iter()
3701 .filter(|(barrier_operand, _)| *barrier_operand == operand)
3702 .filter_map(|(_, edge_id)| split_map.get(edge_id))
3703 .flat_map(|sub_ids| sub_ids.iter().map(|sub_id| (operand, *sub_id)))
3704 .collect();
3705 barrier_edges.extend(minted);
3706 }
3707 crate::classification::classify_profile_begin();
3708 let coincident = coincident_pairs(
3709 &fragments_a,
3710 &fragments_b,
3711 first,
3712 second,
3713 &imprint.cosurface_pairs,
3714 tolerance,
3715 )?;
3716 let sector_mode = sector::sector_mode(options);
3717 let mut select_census = sector::SelectCensus::default();
3718 let mut selected = select_fragments(
3719 fragments_a,
3720 fragments_b,
3721 first,
3722 second,
3723 operation,
3724 tolerance,
3725 &barrier_edges,
3726 &imprint,
3727 &coincident,
3728 sector_mode,
3729 &mut select_census,
3730 )?;
3731 let resewn = resew_coincident_rims(
3732 &mut selected,
3733 [&split_first, &split_second],
3734 [first, second],
3735 &imprint.cosurface_pairs,
3736 operation,
3737 tolerance,
3738 )?;
3739 diagnostics.count_n("select.coincident_pairs", coincident.len() as u64);
3740 diagnostics.count_n("select.rims_resewn", resewn as u64);
3741 crate::classification::classify_profile_report("select");
3742 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3743 profile_stage("select_ms", stage_ms);
3744 diagnostics.measure_max("timing.select_ms", stage_ms);
3745 diagnostics.count_n("select.fragments", selected.len() as u64);
3746 diagnostics.count_n("select.sector_eligible", select_census.eligible);
3748 diagnostics.count_n("select.sector_primary", select_census.sector_primary);
3749 diagnostics.count_n("select.sector_fallback", select_census.sector_fallback);
3750 diagnostics.count_n("select.sector_disagree", select_census.disagree);
3751 diagnostics.count_n("select.ray_casts", select_census.ray_casts);
3752 diagnostics.count_n("select.on_votes", select_census.on_votes);
3753 diagnostics.count_n("select.overturns", select_census.overturns);
3754 if sector_mode != sector::SectorMode::Off || std::env::var_os("BREP_SECTOR_CENSUS").is_some() {
3755 sector::sector_census_line(|| {
3756 format!(
3757 "selection mode={sector_mode:?} select_ms={stage_ms:.3} selected={} eligible={} primary={} fallback={} disagree={} ray_casts={} on_votes={} overturns={}",
3758 selected.len(),
3759 select_census.eligible,
3760 select_census.sector_primary,
3761 select_census.sector_fallback,
3762 select_census.disagree,
3763 select_census.ray_casts,
3764 select_census.on_votes,
3765 select_census.overturns
3766 )
3767 });
3768 }
3769 if selected.is_empty()
3791 && !imprint.section_evidence
3792 && std::env::var("BREP_EMPTY_BOOLEAN").as_deref() != Ok("0")
3793 {
3794 let strictly_inside = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
3795 for &sample in samples {
3796 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::In {
3797 return Ok(true);
3798 }
3799 }
3800 Ok(false)
3801 };
3802 let outside_witness = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
3803 for &sample in samples {
3804 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::Out {
3805 return Ok(true);
3806 }
3807 }
3808 Ok(false)
3809 };
3810 let legitimate = match operation {
3811 BooleanOperation::Intersect => {
3812 !strictly_inside(&a_surface_samples, second)?
3813 && !strictly_inside(&b_surface_samples, first)?
3814 }
3815 BooleanOperation::Subtract => !outside_witness(&a_surface_samples, second)?,
3816 BooleanOperation::Union => false,
3817 };
3818 if legitimate {
3819 diagnostics.event(
3820 DiagnosticSeverity::Info,
3821 KernelStage::Select,
3822 "boolean.empty_result",
3823 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
3824 );
3825 fit_scope.close().report_into(&mut diagnostics);
3826 polyline_scope.close().report_into(&mut diagnostics);
3827 diagnostics.measure_max(
3828 "timing.total_ms",
3829 operation_started.elapsed().as_secs_f64() * 1_000.0,
3830 );
3831 return Ok((
3832 KernelOutcome {
3833 value: empty_solid(),
3834 diagnostics,
3835 },
3836 None,
3837 ));
3838 }
3839 }
3840 if selected.is_empty()
3849 && imprint.section_evidence
3850 && !matches!(operation, BooleanOperation::Union)
3851 && touching_empty_enabled()
3852 && !TOUCHING_PROOF.with(std::cell::Cell::get)
3853 {
3854 let strict = |samples: &[Vec3], other: &BrepSolid, class: PointClass| -> Result<bool, KernelRefusal> {
3855 for &sample in samples {
3856 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == class {
3857 return Ok(true);
3858 }
3859 }
3860 Ok(false)
3861 };
3862 let witnessed = match operation {
3863 BooleanOperation::Intersect => {
3864 !strict(&a_surface_samples, second, PointClass::In)? && !strict(&b_surface_samples, first, PointClass::In)?
3865 }
3866 BooleanOperation::Subtract => !strict(&a_surface_samples, second, PointClass::Out)?,
3867 BooleanOperation::Union => false,
3868 };
3869 let overlap_free = !hair_deep_overlap(first, second, tolerance);
3875 if witnessed && overlap_free {
3876 TOUCHING_PROOF.with(|flag| flag.set(true));
3877 let proof = inclusion_exclusion_volume(first, second, operation, options, body_volume(first), body_volume(second), false);
3878 TOUCHING_PROOF.with(|flag| flag.set(false));
3879 let volume = |solid: &BrepSolid| body_volume(solid).unwrap_or(f64::INFINITY);
3884 let band = 1e-9 * volume(first).max(volume(second));
3885 if let Some(proof) = proof.filter(|proof| proof.expected.is_finite() && proof.expected.abs() <= band) {
3886 diagnostics.event(
3887 DiagnosticSeverity::Info,
3888 KernelStage::Select,
3889 "boolean.empty_touching",
3890 format!(
3891 "{operation:?} of touching operands is empty: {} reads {:.3e} by {} (band {band:.3e})",
3892 proof.formula, proof.expected, proof.reading
3893 ),
3894 );
3895 fit_scope.close().report_into(&mut diagnostics);
3896 polyline_scope.close().report_into(&mut diagnostics);
3897 diagnostics.measure_max("timing.total_ms", operation_started.elapsed().as_secs_f64() * 1_000.0);
3898 return Ok((KernelOutcome { value: empty_solid(), diagnostics }, None));
3899 }
3900 }
3901 }
3902 let solids = [(0, &split_first), (1, &split_second)]
3903 .into_iter()
3904 .collect::<HashMap<_, _>>();
3905 let dump = BooleanStageDump::open();
3906 if let Some(dump) = &dump {
3907 dump.write("first", &split_first);
3908 dump.write("second", &split_second);
3909 dump.write("selected", &selected);
3910 }
3911 let stage_started = Instant::now();
3912 let assembled_origins: Vec<FaceKey> = if imprint.tangent_sections.is_empty() {
3916 Vec::new()
3917 } else {
3918 selected
3919 .iter()
3920 .map(|fragment| FaceKey { operand: fragment.operand, face_id: fragment.source_face_id })
3921 .collect()
3922 };
3923 let attributable: Vec<crate::imprint::TangentSectionRecord> = imprint
3930 .tangent_sections
3931 .iter()
3932 .filter(|section| imprint.tangent_nodes.is_empty() || section.grazing.is_empty())
3933 .cloned()
3934 .collect();
3935 let attribute = |error: KernelRefusal| {
3936 attribute_to_tangent_section(error, &attributable, &assembled_origins)
3937 };
3938 let cellular_result = matches!(operation, BooleanOperation::Union)
3939 && cellular::enabled(options)
3940 && cellular::complete_contact(first, second, &selected, tolerance);
3941 let (solid, scope) = if cellular_result {
3942 (assemble::assemble_cellular_fragments(selected, &solids, &imprint, tolerance)
3943 .map_err(attribute)?, None)
3944 } else if untouched_passthrough(options) {
3945 assemble_fragments_scoped(selected, &solids, &imprint, tolerance, &touch, touched_assembly(options))
3946 .map_err(attribute)?
3947 } else {
3948 (assemble_fragments(selected, &solids, &imprint, tolerance).map_err(attribute)?, None)
3949 };
3950 if let Some(scope) = &scope {
3951 diagnostics.count_n("passthrough.faces_examined", scope.examined.len() as u64);
3952 }
3953 if let Some(dump) = &dump {
3954 dump.write("assembled", &solid);
3955 }
3956 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3957 profile_stage("assemble_ms", stage_ms);
3958 diagnostics.measure_max("timing.assemble_ms", stage_ms);
3959 let stage_started = Instant::now();
3960 let declines_before = crate::face_merge::declines_served();
3961 let area_checks_before = crate::face_merge::boundary_area_checks();
3962 if std::env::var("BREP_DEBUG_PREMERGE_VALIDATE").is_ok() {
3963 let issues = solid.validate();
3964 eprintln!(
3965 "pre-merge validation: {} issue(s){}",
3966 issues.len(),
3967 issues
3968 .first()
3969 .map(|issue| format!(" — first: {}", issue.message))
3970 .unwrap_or_default()
3971 );
3972 }
3973 let solid = if solid.kind != crate::BodyKind::Cellular && options.merge_coplanar_faces
3974 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
3975 {
3976 let merged = match &scope {
3977 Some(scope) => merge_same_surface_faces_scoped(
3981 &solid,
3982 tolerance,
3983 &options.keep_unmerged_name_substrs,
3984 &scope.examined,
3985 )?,
3986 None => merge_same_surface_faces_excluding(
3987 &solid,
3988 tolerance,
3989 &options.keep_unmerged_name_substrs,
3990 )?,
3991 };
3992 let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
3997 rejoin::rejoin_unless_referenced(merged, options, tolerance)
3998 } else {
3999 solid
4000 };
4001 if let Some(dump) = &dump {
4002 dump.write("merged", &solid);
4003 }
4004 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
4005 profile_stage("face_merge_ms", stage_ms);
4006 if crate::profile::profile_enabled() {
4007 profile_line!("boolean.merge_declines served={}", crate::face_merge::declines_served() - declines_before);
4008 let area_checks = crate::face_merge::boundary_area_checks();
4009 if area_checks != area_checks_before {
4010 profile_line!("boolean.merge_area_checks boundary={} integrated={}", area_checks.0 - area_checks_before.0, area_checks.1 - area_checks_before.1);
4011 }
4012 }
4013 diagnostics.measure_max("timing.face_merge_ms", stage_ms);
4014 let validation_started = Instant::now();
4015 let validation = solid.validate_detailed_scoped(&policy, scope.as_ref().map(|scope| &scope.examined));
4016 profile_stage("final_validate_ms", validation_started.elapsed().as_secs_f64() * 1000.0);
4017 diagnostics.count_n("validate.issues", validation.issues.len() as u64);
4018 diagnostics.count_n(
4019 "validate.wire_warnings",
4020 validation.wire_warnings.len() as u64,
4021 );
4022 diagnostics.measure_max("validate.max_pcurve_error", validation.max_pcurve_error);
4023 for warning in &validation.wire_warnings {
4024 diagnostics.event(
4025 DiagnosticSeverity::Warning,
4026 KernelStage::Validate,
4027 "validate.uv_wire",
4028 warning.message.clone(),
4029 );
4030 }
4031 for issue in &validation.issues {
4032 diagnostics.event(
4033 DiagnosticSeverity::Error,
4034 KernelStage::Validate,
4035 "validate.brep",
4036 issue.message.clone(),
4037 );
4038 }
4039 fit_scope.close().report_into(&mut diagnostics);
4040 polyline_scope.close().report_into(&mut diagnostics);
4041 diagnostics.measure_max(
4042 "timing.total_ms",
4043 operation_started.elapsed().as_secs_f64() * 1_000.0,
4044 );
4045 if !validation.issues.is_empty() {
4046 return Err(KernelRefusal::new(
4047 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
4048 KernelStage::Validate,
4049 format!(
4050 "boolean_operation: invalid result: {:?}",
4051 validation.issues
4052 )));
4053 }
4054 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
4060 if let Ok(report) =
4061 crate::oracle::boolean_semantic_disagreement(first, second, operation, &solid, 200)
4062 {
4063 if report.is_flagged() {
4064 eprintln!(
4065 "[oracle] semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
4066 report.disagreement_rate,
4067 report.disagreements.len(),
4068 report.considered,
4069 report.sample_disagreement()
4070 );
4071 }
4072 }
4073 let fusable_band = crate::tolerance::assembler_weld(policy.model);
4074 let fusables = crate::oracle::boolean_residual_fusables(&solid, fusable_band);
4075 if !fusables.is_empty() {
4076 eprintln!(
4077 "[oracle] {} residual fusable(s) after weld; sample {:?}",
4078 fusables.len(),
4079 fusables.first()
4080 );
4081 }
4082 }
4083 let candidates = scope.as_ref().map(|scope| {
4084 let unproved = (scope_proved_apart_on() && plain_hull_solid(first) && plain_hull_solid(second))
4085 .then(|| imprint.faces_in_unproved_pairs.as_ref())
4086 .flatten()
4087 .map(|faces| faces.iter().copied().collect::<HashSet<_>>());
4088 let candidates = soundness_candidates(
4089 &solid,
4090 scope,
4091 [operand_bounds(first), operand_bounds(second)],
4092 policy.sew_search,
4093 unproved.as_ref(),
4094 );
4095 diagnostics.count_n("passthrough.soundness_candidates", candidates.len() as u64);
4096 crate::soundness::census::profile_operation(&solid, &[first, second], Some(&scope.touched), "boolean");
4097 candidates
4098 });
4099 Ok((
4100 KernelOutcome {
4101 value: solid,
4102 diagnostics,
4103 },
4104 candidates,
4105 ))
4106}
4107