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;
234
235pub use rim::*;
236use select::*;
237use coincident::*;
238use touch::TouchCensus;
239pub use assemble::{
240 assemble_fragments, assemble_open_fragments, commit_nearby_edge_endpoints,
241 clear_candidate_memo, edge_interior_lies_on, finalize_assembled_solid, refresh_derived_genus,
242};
243use assemble::{assemble_fragments_scoped, AssemblyScope};
244#[allow(unused_imports)]
246pub use assemble::apply_assembly_heal_chain;
247
248
249struct WorkingScale {
252 factor: f64,
253 solids: Vec<BrepSolid>,
254 options: BooleanOptions,
255}
256
257impl WorkingScale {
258 fn of(operands: &[&BrepSolid], options: &BooleanOptions) -> Result<Option<Self>, KernelRefusal> {
259 let Some(bounds) = crate::rescale::bounds_of(operands.iter().copied()) else {
260 return Ok(None);
261 };
262 let Some(factor) = crate::rescale::guard_factor(bounds) else {
263 return Ok(None);
264 };
265 crate::rescale::profile_fired("boolean", factor, bounds);
266 let solids = operands
267 .iter()
268 .map(|solid| crate::rescale::scale_operand(solid, factor, "boolean"))
269 .collect::<Result<Vec<_>, _>>()?;
270 let mut options = options.clone();
272 options.imprint.maximum_ssi_step = options.imprint.maximum_ssi_step.map(|step| step * factor);
273 Ok(Some(Self { factor, solids, options }))
274 }
275
276 fn back(&self, solid: &BrepSolid) -> Result<BrepSolid, KernelRefusal> {
277 crate::rescale::scale_operand(solid, 1.0 / self.factor, "boolean")
278 }
279
280 fn refusal(&self, error: KernelRefusal) -> KernelRefusal {
281 crate::rescale::name_scale(error, self.factor)
282 }
283}
284
285pub fn boolean_operation(
286 first: &BrepSolid,
287 second: &BrepSolid,
288 operation: BooleanOperation,
289 options: &BooleanOptions,
290) -> Result<BrepSolid, KernelRefusal> {
291 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
292 return boolean_operation(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
293 .map_err(|error| scaled.refusal(error))
294 .and_then(|solid| scaled.back(&solid));
295 }
296 match boolean_operation_with_diagnostics(first, second, operation, options) {
297 Ok(outcome) => {
298 if below_tolerance_refusal_enabled()
301 && outcome.value.shells.iter().all(|shell| shell.faces.is_empty())
302 && !matches!(operation, BooleanOperation::Union)
303 {
304 if let Some(refusal) = below_tolerance_refusal(first, second, None) {
305 if let Some(answer) = below_tolerance_answer(first, second, operation) {
306 return Ok(answer);
307 }
308 if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
309 return Ok(answer);
310 }
311 return Err(refusal);
312 }
313 }
314 if unresolved_merge_refusal_enabled() && !matches!(operation, BooleanOperation::Subtract) {
315 if let Some(refusal) = unresolved_merge_refusal(first, second) {
316 return Err(refusal);
317 }
318 }
319 if below_tolerance_slivers_enabled()
322 && !matches!(operation, BooleanOperation::Subtract)
323 && [first, second].iter().all(|solid| face_count(solid) <= SLIVER_ANSWER_FACES)
324 && near_coincident_planar_faces(first, second).is_some()
325 {
326 if let Some(answer) = below_tolerance_answer(first, second, operation) {
327 return Ok(answer);
328 }
329 }
330 Ok(outcome.value)
331 }
332 Err(error) => {
333 if below_tolerance_refusal_enabled() {
334 if let Some(refusal) = below_tolerance_refusal(first, second, Some(&error)) {
335 if let Some(answer) = below_tolerance_answer(first, second, operation) {
336 return Ok(answer);
337 }
338 if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
339 return Ok(answer);
340 }
341 return Err(refusal);
342 }
343 }
344 if std::env::var("BREP_NO_PERTURB").as_deref() == Ok("1")
352 || !error.class.perturbation_eligible()
353 {
354 return Err(error);
355 }
356 if std::env::var("BREP_OPEN_OPERAND_GATE").as_deref() != Ok("0") {
378 if let Some((operand, open)) = [first, second]
379 .iter()
380 .enumerate()
381 .find_map(|(operand, solid)| {
382 let open = one_use_edges(solid);
383 (open > 0).then_some((operand, open))
384 })
385 {
386 return Err(error.with_message(|message| format!(
387 "{message}; operand {operand} is not a closed shell: {open} of its edges bound \
388 only one face, so no boolean of it encloses a solid and no perturbation \
389 can close it"
390 )));
391 }
392 }
393 if let Some((operand, face_id, deviation, weld)) =
394 planar_operand_off_its_plane(first, second, options)
395 {
396 return Err(error.with_message(|message| format!(
397 "{message}; operand {operand} face {face_id} is a plane whose straight \
398 boundary sits {deviation:.3e} off it (assembly weld {weld:.1e}), which \
399 no perturbation can reconcile — the body's planes must contain their \
400 boundary before it can take part in an exact boolean"
401 )));
402 }
403 if matches!(operation, BooleanOperation::Subtract)
418 && std::env::var("BREP_PINCH_GATE").as_deref() != Ok("0")
419 && subtract_pinches_at_internal_tangency(first, second, options.tolerance)
420 .unwrap_or(false)
421 {
422 if let Some(solid) = subtract_through_the_common_part(first, second, options) {
425 return Ok(solid);
426 }
427 return Err(error.with_message(|message| format!(
428 "{message}; internal tangency: the operands touch tangentially with \
429 co-directed normals, so the exact difference pinches to zero thickness \
430 (non-manifold, unrepresentable in a boundary model) — refusing rather \
431 than returning a perturbed sliver"
432 )));
433 }
434 if matches!(error.class, RefusalClass::TangentNodeSingularity)
450 && std::env::var("BREP_TANGENT_NODE_GATE").as_deref() != Ok("0")
451 {
452 return Err(error);
453 }
454 if matches!(operation, BooleanOperation::Union) {
458 if let Some(solid) = union_through_the_difference(first, second, options) {
459 return Ok(solid);
460 }
461 }
462 if WITHOUT_PERTURBATION.with(|cell| cell.get()) {
464 return Err(error);
465 }
466 match perturbation_retry(first, second, operation, options) {
467 Ok(solid) => Ok(solid),
468 Err(refused) if refused.is_empty() => Err(error),
469 Err(refused) => {
470 Err(error.with_message(|message| format!("{message}; {}", refused.join("; "))))
471 }
472 }
473 }
474 }
475}
476
477const PINCH_PROBE_STEPS: usize = 8;
482
483const PINCH_ANGULAR_TOLERANCE: f64 = 1e-4;
486
487const PINCH_SEPARATION_STEP: f64 = 1e-2;
491
492fn subtract_through_the_common_part(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
510 if !switch!("BREP_PINCH_COMMON_RETRY", true) || !options.imprint.tangent_curve_imprint {
513 return None;
514 }
515 let common = boolean_operation_with_diagnostics(first, second, BooleanOperation::Intersect, options).ok()?.value;
516 if common.shells.iter().all(|shell| shell.faces.is_empty()) {
517 return None;
518 }
519 let cut = boolean_operation_with_diagnostics(first, &common, BooleanOperation::Subtract, options).ok()?.value;
520 if !cut.validate().is_empty() {
521 return None;
522 }
523 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
524 let (whole, taken, left) = (volume(first)?, volume(&common)?, volume(&cut)?);
525 ((left - (whole - taken)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(cut)
526}
527
528fn union_through_the_difference(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
541 if !switch!("BREP_TANGENT_UNION_DIFFERENCE_RETRY", true) || !options.imprint.tangent_curve_imprint {
542 return None;
543 }
544 let pinches = |a: &BrepSolid, b: &BrepSolid| subtract_pinches_at_internal_tangency(a, b, options.tolerance).unwrap_or(false);
545 if !pinches(first, second) && !pinches(second, first) {
546 return None;
547 }
548 let difference = match boolean_operation_with_diagnostics(first, second, BooleanOperation::Subtract, options) {
549 Ok(outcome) => outcome.value,
550 Err(_) => subtract_through_the_common_part(first, second, options)?,
551 };
552 if difference.shells.iter().all(|shell| shell.faces.is_empty()) || !difference.validate().is_empty() {
553 return None;
554 }
555 let union = boolean_operation_with_diagnostics(second, &difference, BooleanOperation::Union, options).ok()?.value;
556 if !union.validate().is_empty() {
557 return None;
558 }
559 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
560 let (left, added, whole) = (volume(&difference)?, volume(second)?, volume(&union)?);
561 ((whole - (left + added)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(union)
562}
563
564pub fn subtract_pinches_at_internal_tangency(
586 first: &BrepSolid,
587 second: &BrepSolid,
588 tolerance: f64,
589) -> Result<bool, KernelRefusal> {
590 let contact = (tolerance * 100.0).max(1e-12);
593 let probes_a = first
594 .shells
595 .iter()
596 .flat_map(|shell| &shell.faces)
597 .map(PinchProbe::of)
598 .collect::<Result<Vec<_>, _>>()?;
599 let probes_b = second
600 .shells
601 .iter()
602 .flat_map(|shell| &shell.faces)
603 .map(PinchProbe::of)
604 .collect::<Result<Vec<_>, _>>()?;
605 for probe_a in &probes_a {
606 for probe_b in &probes_b {
607 let pad = 1e-2 * probe_a.extent().max(probe_b.extent());
614 if probe_a.separation(probe_b) > contact + pad {
615 continue;
616 }
617 if classify_surface_pair(
624 &probe_a.face.surface,
625 &probe_b.face.surface,
626 tolerance,
627 PINCH_ANGULAR_TOLERANCE,
628 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")?
629 .relation
630 == SurfacePairRelation::Cosurface
631 {
632 continue;
633 }
634 if faces_touch_with_codirected_normals(probe_a, probe_b, contact)? {
635 return Ok(true);
636 }
637 }
638 }
639 Ok(false)
640}
641
642struct PinchProbe<'a> {
645 face: &'a FaceRecord,
646 samples: Vec<(f64, f64, Vec3)>,
648 minimum: [f64; 3],
649 maximum: [f64; 3],
650}
651
652impl<'a> PinchProbe<'a> {
653 fn of(face: &'a FaceRecord) -> Result<Self, KernelRefusal> {
654 let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
655 let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
656 let steps = PINCH_PROBE_STEPS as f64;
657 let mut samples = Vec::with_capacity((PINCH_PROBE_STEPS + 1).pow(2));
658 let mut minimum = [f64::INFINITY; 3];
659 let mut maximum = [f64::NEG_INFINITY; 3];
660 for i in 0..=PINCH_PROBE_STEPS {
661 let u = u0 + (u1 - u0) * i as f64 / steps;
662 for j in 0..=PINCH_PROBE_STEPS {
663 let v = v0 + (v1 - v0) * j as f64 / steps;
664 let Ok(point) = face.surface.evaluate(u, v) else {
665 continue;
666 };
667 for (axis, value) in [point.x, point.y, point.z].into_iter().enumerate() {
668 minimum[axis] = minimum[axis].min(value);
669 maximum[axis] = maximum[axis].max(value);
670 }
671 samples.push((u, v, point));
672 }
673 }
674 Ok(Self {
675 face,
676 samples,
677 minimum,
678 maximum,
679 })
680 }
681
682 fn extent(&self) -> f64 {
684 (0..3)
685 .map(|axis| self.maximum[axis] - self.minimum[axis])
686 .fold(0.0f64, f64::max)
687 }
688
689 fn separation(&self, other: &Self) -> f64 {
691 let mut gap: f64 = 0.0;
692 for axis in 0..3 {
693 gap = gap.max(self.minimum[axis] - other.maximum[axis]);
694 gap = gap.max(other.minimum[axis] - self.maximum[axis]);
695 }
696 gap
697 }
698}
699
700fn faces_touch_with_codirected_normals(
705 probe_a: &PinchProbe<'_>,
706 probe_b: &PinchProbe<'_>,
707 contact: f64,
708) -> Result<bool, KernelRefusal> {
709 for (probe, other) in [(probe_a, probe_b), (probe_b, probe_a)] {
710 let source = probe.face;
711 let target = other.face;
712 for &(u, v, point) in &probe.samples {
713 let projection = project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?;
714 if projection.distance > contact {
715 continue;
716 }
717 let (Ok(source_normal), Ok(target_normal)) = (
720 source.surface.normal(u, v),
721 target.surface.normal(projection.u, projection.v),
722 ) else {
723 continue;
724 };
725 let source_outward = outward_normal(source_normal, source.same_sense);
726 let target_outward = outward_normal(target_normal, target.same_sense);
727 if source_outward.cross(target_outward).length() > PINCH_ANGULAR_TOLERANCE
728 || source_outward.dot(target_outward) <= 0.0
729 {
730 continue;
731 }
732 if parameter_point_in_face(source, Vec2 { x: u, y: v }, 1e-6).or_refuse(KernelStage::Validate, "parameter_point_in_face")?
733 == PolygonClass::Outside
734 || parameter_point_in_face(
735 target,
736 Vec2 {
737 x: projection.u,
738 y: projection.v,
739 },
740 1e-6,
741 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")? == PolygonClass::Outside
742 {
743 continue;
744 }
745 if contact_separates_locally(source, target, u, v, contact)? {
746 return Ok(true);
747 }
748 }
749 }
750 Ok(false)
751}
752
753fn outward_normal(normal: Vec3, same_sense: bool) -> Vec3 {
754 if same_sense {
755 normal
756 } else {
757 normal.scale(-1.0)
758 }
759}
760
761fn contact_separates_locally(
767 source: &FaceRecord,
768 target: &FaceRecord,
769 u: f64,
770 v: f64,
771 contact: f64,
772) -> Result<bool, KernelRefusal> {
773 let [u0, u1] = source.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
774 let [v0, v1] = source.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
775 let step_u = (u1 - u0) * PINCH_SEPARATION_STEP;
776 let step_v = (v1 - v0) * PINCH_SEPARATION_STEP;
777 for (probe_u, probe_v) in [
778 ((u + step_u).min(u1), v),
779 ((u - step_u).max(u0), v),
780 (u, (v + step_v).min(v1)),
781 (u, (v - step_v).max(v0)),
782 ] {
783 if (probe_u - u).abs() < f64::EPSILON && (probe_v - v).abs() < f64::EPSILON {
784 continue;
785 }
786 let Ok(point) = source.surface.evaluate(probe_u, probe_v) else {
787 continue;
788 };
789 if project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?.distance > contact * 10.0 {
792 return Ok(true);
793 }
794 }
795 Ok(false)
796}
797
798fn perturbation_retry(
852 first: &BrepSolid,
853 second: &BrepSolid,
854 operation: BooleanOperation,
855 options: &BooleanOptions,
856) -> Result<BrepSolid, Vec<String>> {
857 const DIRECTIONS: [[f64; 3]; 4] = [
868 [0.4034, 0.7973, 0.4491],
869 [0.7973, 0.4491, 0.4034],
870 [0.4491, 0.4034, 0.7973],
871 [0.5774, -0.5774, 0.5774],
872 ];
873 const FRACTIONS: [f64; 5] = PERTURBATION_FRACTIONS;
879
880 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
881 let scale = crate::solid_tolerance::solid_scale(first)
882 .max(crate::solid_tolerance::solid_scale(second))
883 .max(1.0);
884
885 let _caller = crate::mass_caller("boolean.perturbation_rescue");
889 let va = solid_signed_volume(first).ok().map(f64::abs);
890 let vb = solid_signed_volume(second).ok().map(f64::abs);
891 let hold_identity = std::env::var("BREP_PERTURB_IDENTITY").as_deref() != Ok("0");
892 let hold_mirror = hold_identity && std::env::var("BREP_PERTURB_MIRROR").as_deref() != Ok("0");
895 let early_exit = std::env::var("BREP_MIRROR_EARLY_EXIT").as_deref() != Ok("0");
898 let mut trends = [MirrorTrend::default(); 4];
899 let mut identity: Option<Option<InclusionExclusion>> = None;
901 let mut refused = Vec::new();
902 let ladder = std::env::var("BREP_DEBUG_PERTURB_LADDER").is_ok();
906 let ladder_start = web_time::Instant::now();
907 if ladder {
908 let measured = inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
909 match &measured {
910 Some(identity) => eprintln!(
911 "[ladder] identity {} = {:.9} from the exact lane's {} ({:.9}); V(first) {:?} V(second) {:?}",
912 identity.formula, identity.expected, identity.reading, identity.read, va, vb
913 ),
914 None => eprintln!("[ladder] no identity: no exact-lane boolean of these operands clears in either order"),
915 }
916 identity = Some(measured);
917 }
918 let rung_miss = |identity: &Option<Option<InclusionExclusion>>, candidate: &BrepSolid| -> String {
919 let volume = body_volume(candidate);
920 match (identity, volume) {
921 (Some(Some(identity)), Some(volume)) => format!(
922 "volume {volume:.9} miss {:+.3e} bar {:.3e}",
923 volume - identity.expected,
924 crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * identity.expected.abs())
925 ),
926 (_, Some(volume)) => format!("volume {volume:.9}"),
927 _ => "no volume".to_string(),
928 }
929 };
930
931 for &fraction in &FRACTIONS {
932 let magnitude = scale * fraction;
933 for (direction, dir) in DIRECTIONS.iter().enumerate() {
934 if trends[direction].closed {
935 if ladder {
936 eprintln!("[ladder] dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}: not tried, its direction is closed");
937 }
938 continue;
939 }
940 let offset = [dir[0] * magnitude, dir[1] * magnitude, dir[2] * magnitude];
941 let translate = match AffineTransform::new([
942 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,
946 ]) {
947 Ok(transform) => transform,
948 Err(_) => continue,
949 };
950 let moved = match crate::transform_brep(second, translate, false) {
951 Ok(solid) => solid,
952 Err(_) => continue,
953 };
954 let rung = format!("dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}");
955 let rung_start = web_time::Instant::now();
956 let candidate =
957 match boolean_operation_with_diagnostics(first, &moved, operation, options) {
958 Ok(outcome) => outcome.value,
959 Err(error) => {
960 if ladder {
961 eprintln!("[ladder] {rung}: exact lane refused {:?}", error.class);
962 }
963 continue;
964 }
965 };
966 let built = rung_start.elapsed();
967 if candidate.shells.is_empty() {
969 if ladder {
970 eprintln!("[ladder] {rung}: empty");
971 }
972 continue;
973 }
974 if let (Some(va), Some(vb)) = (va, vb) {
979 if let Ok(vr) = solid_signed_volume(&candidate) {
980 if !volume_within_csg_bounds(operation, va, vb, vr.abs()) {
981 if ladder {
982 eprintln!("[ladder] {rung}: outside the CSG bound, {}", rung_miss(&identity, &candidate));
983 }
984 continue;
985 }
986 }
987 }
988 let bounded = rung_start.elapsed();
993 if hold_identity {
995 let identity = identity.get_or_insert_with(|| {
996 let identity =
997 inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
998 if debug && identity.is_none() {
999 eprintln!(
1000 "[perturb] no exact-lane boolean of these operands clears in either \
1001 order; no identity to hold"
1002 );
1003 }
1004 identity
1005 });
1006 if let Some(identity) = identity {
1007 let expected = identity.expected;
1008 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * expected.abs());
1009 let volume = body_volume(&candidate);
1010 let miss = volume.map(|volume| (volume - expected).abs());
1011 if !miss.is_some_and(|miss| miss <= bar) {
1012 let sentence = format!(
1013 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1014 (offset {magnitude:.3e}) refused: its body reads {} against the \
1015 inclusion–exclusion identity {} = {expected:.9} (the exact lane's \
1016 {} reads {:.9}), a miss of {} beyond the volume drift bar {bar:.3e}",
1017 volume.map_or("no volume".to_string(), |volume| format!("{volume:.9}")),
1018 identity.formula,
1019 identity.reading,
1020 identity.read,
1021 miss.map_or("unmeasured".to_string(), |miss| format!("{miss:.3e}")),
1022 );
1023 if debug {
1024 eprintln!("[perturb] {sentence}");
1025 }
1026 if ladder {
1027 eprintln!(
1028 "[ladder] {rung}: refused by the identity, volume {} miss {} bar {bar:.3e}",
1029 volume.map_or("none".to_string(), |volume| format!("{volume:.9}")),
1030 volume.map_or("unmeasured".to_string(), |volume| format!("{:+.3e}", volume - expected)),
1031 );
1032 }
1033 refused.push(sentence);
1034 continue;
1035 }
1036 } else if hold_mirror {
1037 let mirror_start = web_time::Instant::now();
1040 let mirrored = AffineTransform::new([
1041 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,
1045 ])
1046 .ok()
1047 .and_then(|transform| crate::transform_brep(second, transform, false).ok());
1048 let mirror = mirrored.as_ref().and_then(|mirrored| {
1049 inclusion_exclusion_volume(first, mirrored, operation, options, va, vb, true)
1050 });
1051 let mirror_time = mirror_start.elapsed();
1052 let volume = body_volume(&candidate);
1053 let mut measured = None;
1054 let verdict = match (&mirror, volume) {
1055 (Some(mirror), Some(volume)) => {
1056 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * mirror.expected.abs());
1057 let miss = 0.5 * (volume - mirror.expected).abs();
1058 measured = Some((0.5 * (volume - mirror.expected), bar));
1059 if ladder {
1060 eprintln!(
1061 "[ladder] {rung}: mirror at −offset reads {} = {:.9} (the mirrored {} {:.9}); body {volume:.9}, first-order translation error {:+.3e} bar {bar:.3e}",
1062 mirror.formula, mirror.expected, mirror.reading, mirror.read, 0.5 * (volume - mirror.expected)
1063 );
1064 }
1065 (miss > bar).then(|| format!(
1066 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1067 (offset {magnitude:.3e}) refused: no exact-lane boolean of the \
1068 operands clears, so the rung is held to its mirror: its body reads \
1069 {volume:.9} with the second operand moved +offset and {} = {:.9} \
1070 with it moved −offset (the mirrored {} reads {:.9}), a first-order \
1071 translation error of {miss:.3e} beyond the volume drift bar {bar:.3e}",
1072 mirror.formula, mirror.expected, mirror.reading, mirror.read
1073 ))
1074 }
1075 _ => Some(format!(
1076 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1077 (offset {magnitude:.3e}) refused: no exact-lane boolean of the operands \
1078 clears, and none clears with the second operand moved −offset either, \
1079 so nothing checks the rung's body{}",
1080 volume.map_or(String::new(), |volume| format!(" ({volume:.9})"))
1081 )),
1082 };
1083 match verdict {
1084 None => trends[direction].cleared(),
1085 Some(sentence) => {
1086 if debug {
1087 eprintln!("[perturb] {sentence}");
1088 }
1089 if ladder {
1090 eprintln!(
1091 "[ladder] {rung}: refused by its mirror (rung {:.0} ms: built {:.0}, bound {:.0}, mirror {:.0} ms; ladder {:.1} s)",
1092 rung_start.elapsed().as_secs_f64() * 1e3,
1093 built.as_secs_f64() * 1e3,
1094 (bounded - built).as_secs_f64() * 1e3,
1095 mirror_time.as_secs_f64() * 1e3,
1096 ladder_start.elapsed().as_secs_f64()
1097 );
1098 }
1099 refused.push(sentence);
1100 let closure = measured.and_then(|(error, bar)| {
1103 let earlier = trends[direction].refused(magnitude, error, early_exit)?;
1104 Some((earlier, error, bar))
1105 });
1106 if let Some(((earlier_offset, earlier_error), error, bar)) = closure {
1107 let closed = format!(
1108 "perturbation direction dir={dir:?} closed after offset {magnitude:.3e}: its \
1109 rungs' first-order translation errors read {earlier_error:+.3e} at offset \
1110 {earlier_offset:.3e} and {error:+.3e} at {magnitude:.3e}, one sign and \
1111 growing, so no larger offset along it comes back to the volume drift bar \
1112 {bar:.3e}"
1113 );
1114 if debug {
1115 eprintln!("[perturb] {closed}");
1116 }
1117 if ladder {
1118 eprintln!("[ladder] {closed}");
1119 }
1120 refused.push(closed);
1121 }
1122 continue;
1123 }
1124 }
1125 }
1126 }
1127 match crate::oracle::boolean_semantic_disagreement(
1131 first, second, operation, &candidate, 400,
1132 ) {
1133 Ok(report) if report.considered >= 30 && !report.is_flagged() => {
1134 if ladder {
1135 eprintln!(
1136 "[ladder] {rung}: accepted (oracle {} considered, rate {:.4}), {}",
1137 report.considered, report.disagreement_rate, rung_miss(&identity, &candidate)
1138 );
1139 }
1140 if debug {
1141 eprintln!(
1142 "[perturb] rescued {operation:?}: dir={dir:?} fraction={fraction:.1e} \
1143 magnitude={magnitude:.3e} offset={offset:?} \
1144 (oracle considered={} rate={:.4})",
1145 report.considered, report.disagreement_rate
1146 );
1147 }
1148 return Ok(candidate);
1149 }
1150 report => {
1151 if ladder {
1152 let verdict = match &report {
1153 Ok(report) => format!("oracle {} considered, rate {:.4}", report.considered, report.disagreement_rate),
1154 Err(error) => format!("oracle error {error:?}"),
1155 };
1156 eprintln!("[ladder] {rung}: refused by the oracle ({verdict}), {}", rung_miss(&identity, &candidate));
1157 }
1158 continue;
1159 }
1160 }
1161 }
1162 }
1163 if debug {
1164 eprintln!("[perturb] ladder exhausted for {operation:?}; no rung produced a clean result");
1165 }
1166 Err(refused)
1167}
1168
1169pub const PERTURBATION_FRACTIONS: [f64; 5] = [3e-5, 1e-4, 3e-4, 1e-3, 3e-3];
1172
1173#[derive(Clone, Copy, Default)]
1197pub struct MirrorTrend {
1198 last: Option<(f64, f64)>,
1200 pub closed: bool,
1201}
1202
1203impl MirrorTrend {
1204 pub fn refused(&mut self, offset: f64, error: f64, close: bool) -> Option<(f64, f64)> {
1209 let earlier = self
1210 .last
1211 .filter(|&(_, earlier)| earlier.signum() == error.signum() && error.abs() >= earlier.abs())
1212 .filter(|_| close);
1213 self.last = Some((offset, error));
1214 self.closed |= earlier.is_some();
1215 earlier
1216 }
1217
1218 pub fn cleared(&mut self) {
1220 self.last = None;
1221 }
1222}
1223
1224pub fn below_tolerance_refusal_enabled() -> bool {
1239 crate::switch!("BREP_BELOW_TOLERANCE_REFUSAL", true)
1240}
1241
1242pub fn below_tolerance_slivers_enabled() -> bool {
1259 crate::switch!("BREP_BELOW_TOLERANCE_SLIVERS", true)
1260}
1261
1262const SLIVER_ANSWER_FACES: usize = 64;
1265
1266fn face_count(solid: &BrepSolid) -> usize {
1267 solid.shells.iter().map(|shell| shell.faces.len()).sum()
1268}
1269
1270fn below_tolerance_answer(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<BrepSolid> {
1272 if !below_tolerance_slivers_enabled() || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES) {
1273 return None;
1274 }
1275 if ![first, second].iter().all(|solid| closed_single_shell(solid)) {
1276 return None;
1277 }
1278 let inside = |x: &BrepSolid, y: &BrepSolid| difference_all_sliver(x, y);
1279 if matches!(operation, BooleanOperation::Subtract) {
1280 return inside(first, second).then(empty_solid);
1281 }
1282 let (first_in, second_in) = (inside(first, second), inside(second, first));
1283 let first_larger = || match (body_volume(first), body_volume(second)) {
1286 (Some(a), Some(b)) => a >= b,
1287 _ => true,
1288 };
1289 let outer_is_first = match (first_in, second_in) {
1290 (false, false) => return None,
1291 (true, false) => false,
1292 (false, true) => true,
1293 (true, true) => first_larger(),
1294 };
1295 let (outer, inner) = if outer_is_first { (first, second) } else { (second, first) };
1296 Some(match operation {
1297 BooleanOperation::Union => outer.clone(),
1298 _ => inner.clone(),
1299 })
1300}
1301
1302fn closed_single_shell(solid: &BrepSolid) -> bool {
1304 if !solid.kind.is_solid() || solid.shells.len() != 1 {
1305 return false;
1306 }
1307 let mut uses: HashMap<u64, usize> = HashMap::default();
1308 for coedge in solid.shells[0].faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1309 *uses.entry(coedge.edge_id).or_default() += 1;
1310 }
1311 !uses.is_empty() && uses.values().all(|&count| count == 2) && solid.edges.iter().all(|edge| uses.contains_key(&edge.id))
1312}
1313
1314fn difference_all_sliver(first: &BrepSolid, second: &BrepSolid) -> bool {
1325 let Some(bounds) = difference_bounds(first, second) else {
1326 return false;
1327 };
1328 let Ok(properties) = crate::solid_mass_properties(first) else {
1329 return false;
1330 };
1331 bounds.out <= BELOW_TOLERANCE_BAND
1332 && bounds.upper.is_finite()
1333 && bounds.upper <= crate::tolerance::COINCIDENCE_DISTANCE_FLOOR * properties.surface_area
1334}
1335
1336struct DifferenceBounds {
1342 lower: f64,
1343 upper: f64,
1344 out: f64,
1346}
1347
1348fn difference_bounds(first: &BrepSolid, second: &BrepSolid) -> Option<DifferenceBounds> {
1349 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1350 let (polygons_a, polygons_b) = (face_polygons(first, scale)?, face_polygons(second, scale)?);
1351 let vertices_b: Vec<Vec3> = second.vertices.iter().map(|vertex| vertex.point).collect();
1352 let vertices_a: Vec<Vec3> = first.vertices.iter().map(|vertex| vertex.point).collect();
1353 let flat = 1e-9 * scale;
1354 let mut bounds = DifferenceBounds { lower: 0.0, upper: 0.0, out: 0.0 };
1355 for polygon in &polygons_b {
1356 let (origin, normal) = polygon_plane(polygon)?;
1357 if vertices_b.iter().any(|vertex| vertex.sub(origin).dot(normal) > flat) {
1359 return None;
1360 }
1361 let out = vertices_a.iter().map(|vertex| vertex.sub(origin).dot(normal)).fold(0.0f64, f64::max);
1362 bounds.out = bounds.out.max(out);
1363 if out <= 0.0 {
1364 continue;
1365 }
1366 let part: f64 = polygons_a.iter().map(|face| clipped_cone_volume(face, origin, normal)).sum();
1367 bounds.lower = bounds.lower.max(part);
1368 bounds.upper += part;
1369 }
1370 Some(bounds)
1371}
1372
1373pub fn below_tolerance_rescale_enabled() -> bool {
1383 crate::switch!("BREP_BELOW_TOLERANCE_RESCALE", false)
1384}
1385
1386fn below_tolerance_rescaled(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions) -> Option<BrepSolid> {
1387 if !below_tolerance_rescale_enabled()
1388 || options.tolerances.is_some()
1389 || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES || !closed_single_shell(solid))
1390 {
1391 return None;
1392 }
1393 let (volume_exact, area_exact) = convex_pair_measures(first, second, operation)?;
1394 let volume_slack = 1e-9 * body_volume(first)?.max(body_volume(second)?);
1395 let area_slack = 1e-9 * area_exact.max(1.0);
1396 for factor in [100.0, 1000.0] {
1397 let scaled = |solid: &BrepSolid| crate::rescale::scale_operand(solid, factor, "boolean").ok();
1398 let (Some(a), Some(b)) = (scaled(first), scaled(second)) else {
1399 continue;
1400 };
1401 let mut scaled_options = options.clone();
1402 scaled_options.imprint.maximum_ssi_step = scaled_options.imprint.maximum_ssi_step.map(|step| step * factor);
1403 let Ok(outcome) = boolean_operation_with_diagnostics(&a, &b, operation, &scaled_options) else {
1404 continue;
1405 };
1406 let Ok(answer) = crate::rescale::scale_operand(&outcome.value, 1.0 / factor, "boolean") else {
1407 continue;
1408 };
1409 let Ok(properties) = crate::solid_mass_properties(&answer) else {
1410 continue;
1411 };
1412 if (properties.volume.abs() - volume_exact).abs() <= volume_slack
1413 && (properties.surface_area - area_exact).abs() <= area_slack
1414 && !answer.validate().iter().any(|issue| issue.severity == "error")
1415 {
1416 return Some(answer);
1417 }
1418 }
1419 None
1420}
1421
1422fn convex_pair_measures(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<(f64, f64)> {
1428 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1429 let (polygons_a, polygons_b) = (face_polygons(first, scale)?, face_polygons(second, scale)?);
1430 let (planes_a, planes_b) = (convex_planes(&polygons_a, scale)?, convex_planes(&polygons_b, scale)?);
1431 let zero = Vec3::new(0.0, 0.0, 0.0);
1432 let read = |polygons: &[Vec<Vec3>], planes: &[(Vec3, Vec3)]| {
1434 let (mut cone, mut area, mut inside_area) = (0.0, 0.0, 0.0);
1435 for polygon in polygons {
1436 area += vector_area(polygon, zero).length();
1437 let mut inside = polygon.clone();
1438 for &(origin, normal) in planes {
1439 inside = clip_polygon(&inside, origin, normal.scale(-1.0));
1440 if inside.len() < 3 {
1441 break;
1442 }
1443 }
1444 if inside.len() >= 3 {
1445 let vector = vector_area(&inside, zero);
1446 cone += inside[0].dot(vector) / 3.0;
1447 inside_area += vector.length();
1448 }
1449 }
1450 (cone, area, inside_area)
1451 };
1452 let (cone_a, area_a, inside_a) = read(&polygons_a, &planes_b);
1453 let (cone_b, area_b, inside_b) = read(&polygons_b, &planes_a);
1454 let (volume_a, volume_b) = (body_volume(first)?, body_volume(second)?);
1455 let common = cone_a + cone_b;
1456 Some(match operation {
1457 BooleanOperation::Intersect => (common, inside_a + inside_b),
1458 BooleanOperation::Union => (volume_a + volume_b - common, (area_a - inside_a) + (area_b - inside_b)),
1459 BooleanOperation::Subtract => (volume_a - common, (area_a - inside_a) + inside_b),
1460 })
1461}
1462
1463fn convex_planes(polygons: &[Vec<Vec3>], scale: f64) -> Option<Vec<(Vec3, Vec3)>> {
1466 let planes = polygons.iter().map(|polygon| polygon_plane(polygon)).collect::<Option<Vec<_>>>()?;
1467 let flat = 1e-9 * scale;
1468 let convex = planes.iter().all(|&(origin, normal)| polygons.iter().flatten().all(|vertex| vertex.sub(origin).dot(normal) <= flat));
1469 convex.then_some(planes)
1470}
1471
1472fn clip_polygon(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> Vec<Vec3> {
1475 let side = |point: Vec3| point.sub(origin).dot(normal);
1476 let mut kept = Vec::with_capacity(polygon.len() + 2);
1477 for (index, &point) in polygon.iter().enumerate() {
1478 let next = polygon[(index + 1) % polygon.len()];
1479 let (here, there) = (side(point), side(next));
1480 if here >= 0.0 {
1481 kept.push(point);
1482 }
1483 if (here >= 0.0) != (there >= 0.0) {
1484 let t = here / (here - there);
1485 kept.push(point.add(next.sub(point).scale(t)));
1486 }
1487 }
1488 kept
1489}
1490
1491fn face_polygons(solid: &BrepSolid, scale: f64) -> Option<Vec<Vec<Vec3>>> {
1495 let vertex = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1496 let mut polygons = Vec::new();
1497 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
1498 if !face.surface.is_affine().ok()? {
1499 return None;
1500 }
1501 for lp in &face.loops {
1502 let mut polygon = Vec::with_capacity(lp.coedges.len());
1503 for coedge in &lp.coedges {
1504 let edge = solid.edges.iter().find(|edge| edge.id == coedge.edge_id)?;
1505 let (start, end) = (vertex(edge.start_vertex_id)?, vertex(edge.end_vertex_id)?);
1506 let chord = end.sub(start);
1507 let length = chord.length();
1508 if edge.degenerate || length <= 1e-12 * scale {
1509 return None;
1510 }
1511 for control in &edge.curve.control_points {
1512 let offset = control.point().ok()?.sub(start);
1513 if offset.cross(chord).length() / length > 1e-9 * scale {
1514 return None;
1515 }
1516 }
1517 polygon.push(if coedge.forward { start } else { end });
1518 }
1519 polygons.push(polygon);
1520 }
1521 }
1522 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();
1524 if !(volume.abs() > 0.0) {
1525 return None;
1526 }
1527 if volume < 0.0 {
1528 for polygon in &mut polygons {
1529 polygon.reverse();
1530 }
1531 }
1532 Some(polygons)
1533}
1534
1535fn polygon_plane(polygon: &[Vec3]) -> Option<(Vec3, Vec3)> {
1537 let origin = *polygon.first()?;
1538 Some((origin, vector_area(polygon, origin).normalized().ok()?))
1539}
1540
1541fn vector_area(polygon: &[Vec3], origin: Vec3) -> Vec3 {
1542 let mut area = Vec3::new(0.0, 0.0, 0.0);
1543 for (index, point) in polygon.iter().enumerate() {
1544 let next = polygon[(index + 1) % polygon.len()];
1545 area = area.add(point.sub(origin).cross(next.sub(origin)));
1546 }
1547 area.scale(0.5)
1548}
1549
1550fn clipped_cone_volume(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> f64 {
1556 let clipped: Vec<Vec3> = if normal.length() == 0.0 { polygon.to_vec() } else { clip_polygon(polygon, origin, normal) };
1557 if clipped.len() < 3 {
1558 return 0.0;
1559 }
1560 clipped[0].sub(origin).dot(vector_area(&clipped, origin)) / 3.0
1561}
1562
1563const BELOW_TOLERANCE_BAND: f64 = 10.0 * crate::tolerance::WELD_FLOOR;
1566
1567pub fn unresolved_merge_refusal_enabled() -> bool {
1577 crate::switch!("BREP_UNRESOLVED_MERGE_REFUSAL", false)
1578}
1579
1580pub fn sliver_shell_drop_enabled() -> bool {
1593 crate::switch!("BREP_SLIVER_SHELL_DROP", true)
1594}
1595
1596const SLIVER_SHELL_THICKNESS: f64 = 1e-12;
1600
1601pub fn sliver_shell_fast_on() -> bool {
1616 crate::switch!("BREP_SLIVER_SHELL_FAST", true)
1617}
1618
1619fn sliver_shell_fast_check_on() -> bool {
1620 crate::switch!("BREP_SLIVER_SHELL_FAST_CHECK", false)
1621}
1622
1623thread_local! {
1624 static SLIVER_FAST_CHECK: std::cell::Cell<(u64, u64, u64)> = const { std::cell::Cell::new((0, 0, 0)) };
1625}
1626
1627pub fn sliver_shell_fast_check_take() -> (u64, u64, u64) {
1630 SLIVER_FAST_CHECK.with(|cell| cell.replace((0, 0, 0)))
1631}
1632
1633fn sliver_fast_record(compared: u64, differed: u64, kept: u64) {
1634 SLIVER_FAST_CHECK.with(|cell| {
1635 let (a, b, c) = cell.get();
1636 cell.set((a + compared, b + differed, c + kept));
1637 });
1638}
1639
1640fn face_area_upper_bound(surface: &crate::NurbsSurface) -> Option<f64> {
1648 let net = &surface.control_points;
1649 let rows = net.len();
1650 let columns = net.first()?.len();
1651 if rows < 2 || columns < 2 || net.iter().any(|row| row.len() != columns) {
1652 return None;
1653 }
1654 let (p, q) = (surface.degree_u, surface.degree_v);
1655 let (us, vs) = (&surface.knots_u, &surface.knots_v);
1656 if us.len() != rows + p + 1 || vs.len() != columns + q + 1 {
1657 return None;
1658 }
1659 let mut w_min = f64::INFINITY;
1660 let mut w_max = 0.0f64;
1661 let mut point_max = 0.0f64;
1662 for c in net.iter().flatten() {
1663 if !(c.w > 0.0) {
1664 return None;
1665 }
1666 w_min = w_min.min(c.w);
1667 w_max = w_max.max(c.w);
1668 point_max = point_max.max((c.x * c.x + c.y * c.y + c.z * c.z).sqrt());
1669 }
1670 let hodograph = |along_u: bool| -> Option<(f64, f64)> {
1672 let (count, degree, knots) = if along_u { (rows, p, us) } else { (columns, q, vs) };
1673 let (mut dp, mut dw) = (0.0f64, 0.0f64);
1674 for i in 0..count - 1 {
1675 let span = knots[i + degree + 1] - knots[i + 1];
1676 if !(span > 0.0) {
1677 continue;
1678 }
1679 let scale = degree as f64 / span;
1680 let others = if along_u { columns } else { rows };
1681 for j in 0..others {
1682 let (a, b) = if along_u { (net[i][j], net[i + 1][j]) } else { (net[j][i], net[j][i + 1]) };
1683 let (x, y, z) = (b.x - a.x, b.y - a.y, b.z - a.z);
1684 dp = dp.max(scale * (x * x + y * y + z * z).sqrt());
1685 dw = dw.max(scale * (b.w - a.w).abs());
1686 }
1687 }
1688 Some((dp, dw))
1689 };
1690 let (pu, wu) = hodograph(true)?;
1691 let (pv, wv) = hodograph(false)?;
1692 let su = (pu * w_max + point_max * wu) / (w_min * w_min);
1693 let sv = (pv * w_max + point_max * wv) / (w_min * w_min);
1694 let extent_u = us[us.len() - 1] - us[0];
1695 let extent_v = vs[vs.len() - 1] - vs[0];
1696 let bound = su * sv * extent_u * extent_v;
1697 bound.is_finite().then_some(bound)
1698}
1699
1700pub fn trimmed_face_area_upper_bound(face: &crate::topology::FaceRecord) -> Option<f64> {
1708 let s = &face.surface;
1709 let (u0, u1) = (*s.knots_u.first()?, *s.knots_u.last()?);
1710 let (v0, v1) = (*s.knots_v.first()?, *s.knots_v.last()?);
1711 let (du, dv) = (1e-12 * (u1 - u0).abs(), 1e-12 * (v1 - v0).abs());
1713 if !(du > 0.0 && dv > 0.0) {
1714 return None;
1715 }
1716 for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
1717 for c in &coedge.pcurve.control_points {
1718 if !(c.w > 0.0) {
1719 return None;
1720 }
1721 let (u, v) = (c.x / c.w, c.y / c.w);
1722 if !(u >= u0 - du && u <= u1 + du && v >= v0 - dv && v <= v1 + dv) {
1723 return None;
1724 }
1725 }
1726 }
1727 face_area_upper_bound(s).map(|bound| 2.0 * bound)
1728}
1729
1730fn drop_sliver_shells(solid: &mut BrepSolid) -> usize {
1733 if !sliver_shell_drop_enabled() || !solid.kind.is_solid() || solid.shells.len() < 2 {
1734 return 0;
1735 }
1736 let floor = SLIVER_SHELL_THICKNESS * crate::solid_tolerance::solid_scale(solid).max(1.0);
1737 let degenerate: std::collections::HashSet<u64> = solid.edges.iter().filter(|edge| edge.degenerate).map(|edge| edge.id).collect();
1738 let mut drop = vec![false; solid.shells.len()];
1739 for (index, shell) in solid.shells.iter().enumerate() {
1740 if shell.faces.is_empty() {
1741 continue;
1742 }
1743 let mut uses: HashMap<u64, usize> = HashMap::default();
1745 for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1746 if !degenerate.contains(&coedge.edge_id) {
1747 *uses.entry(coedge.edge_id).or_default() += 1;
1748 }
1749 }
1750 if uses.is_empty() || uses.values().any(|&count| count != 2) {
1751 continue;
1752 }
1753 let alone = BrepSolid { shells: vec![shell.clone()], mass_properties_cache: Default::default(), ..solid.clone() };
1754 let (fast, check) = (sliver_shell_fast_on(), sliver_shell_fast_check_on());
1755 let kept_fast = (fast || check)
1756 && shell
1757 .faces
1758 .iter()
1759 .map(trimmed_face_area_upper_bound)
1760 .sum::<Option<f64>>()
1761 .map(|area| floor * area)
1762 .filter(|bar| bar.is_finite() && *bar > 0.0)
1763 .and_then(|bar| crate::solid_signed_volume_for_sign(&alone, bar).ok().map(|volume| volume > bar))
1764 .unwrap_or(false);
1765 if kept_fast && !check {
1766 sliver_fast_record(0, 0, 1);
1767 continue;
1768 }
1769 let Ok(mass) = crate::solid_mass_properties(&alone) else {
1770 continue;
1771 };
1772 let thickness = mass.volume.abs() / mass.surface_area.max(f64::MIN_POSITIVE);
1773 if env_read!("BREP_DEBUG_SLIVER_SHELL").is_some() {
1774 eprintln!(
1775 "sliver-shell: shell {index} of {}: volume {:.6e} area {:.6e} thickness {thickness:.3e}",
1776 solid.shells.len(),
1777 mass.volume,
1778 mass.surface_area
1779 );
1780 }
1781 drop[index] = thickness < floor;
1782 if check {
1783 sliver_fast_record(1, u64::from(kept_fast && drop[index]), u64::from(kept_fast));
1784 }
1785 }
1786 let dropped = drop.iter().filter(|&&d| d).count();
1787 if dropped == 0 || dropped == solid.shells.len() {
1788 return 0;
1789 }
1790 let mut index = 0;
1791 solid.shells.retain(|_| {
1792 let keep = !drop[index];
1793 index += 1;
1794 keep
1795 });
1796 let used_edges: std::collections::HashSet<u64> = solid
1797 .shells
1798 .iter()
1799 .flat_map(|shell| &shell.faces)
1800 .flat_map(|face| &face.loops)
1801 .flat_map(|lp| &lp.coedges)
1802 .map(|coedge| coedge.edge_id)
1803 .collect();
1804 solid.edges.retain(|edge| used_edges.contains(&edge.id));
1805 let used_vertices: std::collections::HashSet<u64> =
1806 solid.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
1807 solid.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
1808 solid.mass_properties_cache = Default::default();
1809 refresh_derived_genus(solid);
1811 dropped
1812}
1813
1814fn unresolved_merge_refusal(first: &BrepSolid, second: &BrepSolid) -> Option<KernelRefusal> {
1815 let (lower, upper) = (crate::tolerance::COINCIDENCE_DISTANCE_FLOOR, crate::tolerance::WELD_FLOOR);
1816 let (face_a, face_b, separation) = planar_faces_apart_within(first, second, lower, upper)?;
1817 Some(KernelRefusal::unsupported(
1818 KernelStage::Intersect,
1819 "below_modelling_tolerance",
1820 format!(
1821 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1822 another, {separation:.3e} apart at most over their shared extent: farther than a coincidence \
1823 ({lower:.0e}) and closer than the kernel resolves ({upper:.0e}), so the step between them would be \
1824 welded away"
1825 ),
1826 ))
1827}
1828
1829fn below_tolerance_refusal(first: &BrepSolid, second: &BrepSolid, error: Option<&KernelRefusal>) -> Option<KernelRefusal> {
1830 let (face_a, face_b, separation) = near_coincident_planar_faces(first, second)?;
1831 let message = format!(
1832 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1833 another, {separation:.3e} apart at most over their shared extent: the slivers between them are below the \
1834 modelling tolerance ({BELOW_TOLERANCE_BAND:.0e}), so the kernel cannot resolve them{}",
1835 error.map(|error| format!(" (the exact arrangement said: {})", error.message.chars().take(160).collect::<String>())).unwrap_or_default()
1836 );
1837 Some(KernelRefusal::unsupported(KernelStage::Intersect, "below_modelling_tolerance", message))
1838}
1839
1840fn near_coincident_planar_faces(first: &BrepSolid, second: &BrepSolid) -> Option<(u64, u64, f64)> {
1844 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1845 planar_faces_apart_within(first, second, 1e-9 * scale, BELOW_TOLERANCE_BAND)
1846}
1847
1848fn planar_faces_apart_within(first: &BrepSolid, second: &BrepSolid, lower: f64, upper: f64) -> Option<(u64, u64, f64)> {
1852 struct Planar {
1853 id: u64,
1854 origin: Vec3,
1855 normal: Vec3,
1856 corners: Vec<Vec3>,
1857 bounds: crate::spatial::Aabb,
1858 }
1859 let read = |solid: &BrepSolid| -> Vec<Planar> {
1860 let at = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1861 solid
1862 .shells
1863 .iter()
1864 .flat_map(|shell| &shell.faces)
1865 .filter_map(|face| {
1866 if !face.surface.is_affine().ok()? {
1867 return None;
1868 }
1869 let origin = face.surface.control_points[0][0].point().ok()?;
1870 let a = face.surface.control_points[1][0].point().ok()?.sub(origin);
1871 let b = face.surface.control_points[0][1].point().ok()?.sub(origin);
1872 let normal = a.cross(b).normalized().ok()?;
1873 let corners: Vec<Vec3> = face
1874 .loops
1875 .iter()
1876 .flat_map(|lp| &lp.coedges)
1877 .filter_map(|coedge| solid.edges.iter().find(|edge| edge.id == coedge.edge_id))
1878 .flat_map(|edge| [at(edge.start_vertex_id), at(edge.end_vertex_id)])
1879 .flatten()
1880 .collect();
1881 if corners.is_empty() {
1882 return None;
1883 }
1884 let bounds = crate::spatial::Aabb::from_points(corners.clone());
1885 Some(Planar { id: face.id, origin, normal, corners, bounds })
1886 })
1887 .collect()
1888 };
1889 let (faces_a, faces_b) = (read(first), read(second));
1890 for a in &faces_a {
1891 for b in &faces_b {
1892 if a.normal.cross(b.normal).length() > 1e-3 {
1893 continue;
1894 }
1895 if !a.bounds.intersects(b.bounds, upper) {
1896 continue;
1897 }
1898 let separation = a
1899 .corners
1900 .iter()
1901 .map(|corner| corner.sub(b.origin).dot(b.normal).abs())
1902 .chain(b.corners.iter().map(|corner| corner.sub(a.origin).dot(a.normal).abs()))
1903 .fold(0.0f64, f64::max);
1904 if separation > lower && separation <= upper {
1905 return Some((a.id, b.id, separation));
1906 }
1907 }
1908 }
1909 None
1910}
1911
1912pub fn one_use_edges(solid: &BrepSolid) -> usize {
1913 let mut uses: HashMap<u64, usize> = HashMap::default();
1914 for coedge in solid
1915 .shells
1916 .iter()
1917 .flat_map(|shell| &shell.faces)
1918 .flat_map(|face| &face.loops)
1919 .flat_map(|loop_record| &loop_record.coedges)
1920 {
1921 *uses.entry(coedge.edge_id).or_default() += 1;
1922 }
1923 solid
1924 .edges
1925 .iter()
1926 .filter(|edge| !edge.degenerate && uses.get(&edge.id) == Some(&1))
1927 .count()
1928}
1929
1930fn body_volume(solid: &BrepSolid) -> Option<f64> {
1932 if solid.shells.is_empty() {
1933 return Some(0.0);
1934 }
1935 solid_signed_volume(solid).ok().map(f64::abs)
1936}
1937
1938struct InclusionExclusion {
1941 formula: &'static str,
1944 reading: &'static str,
1946 read: f64,
1948 expected: f64,
1950}
1951
1952fn inclusion_exclusion_volume(
1963 first: &BrepSolid,
1964 second: &BrepSolid,
1965 operation: BooleanOperation,
1966 options: &BooleanOptions,
1967 va: Option<f64>,
1968 vb: Option<f64>,
1969 own_first: bool,
1970) -> Option<InclusionExclusion> {
1971 use BooleanOperation::{Intersect, Subtract, Union};
1972 let (va, vb) = (va?, vb?);
1973 let own = match operation {
1974 Intersect => (Intersect, false, "first ∩ second"),
1975 Union => (Union, false, "first ∪ second"),
1976 Subtract => (Subtract, false, "first − second"),
1977 };
1978 let readings = [
1979 (Intersect, false, "first ∩ second"),
1980 (Intersect, true, "second ∩ first"),
1981 (Union, false, "first ∪ second"),
1982 (Union, true, "second ∪ first"),
1983 (Subtract, false, "first − second"),
1984 (Subtract, true, "second − first"),
1985 ];
1986 let own_reading = own_first.then_some(own);
1987 let leading = usize::from(own_first);
1988 for (index, (other, swapped, reading)) in own_reading.into_iter().chain(readings).enumerate() {
1989 if index >= leading && !swapped && std::mem::discriminant(&other) == std::mem::discriminant(&operation) {
1990 continue;
1991 }
1992 let (x, y) = if swapped { (second, first) } else { (first, second) };
1993 let Some(read) = boolean_operation_with_diagnostics(x, y, other, options)
1994 .ok()
1995 .and_then(|outcome| body_volume(&outcome.value))
1996 else {
1997 continue;
1998 };
1999 let intersection = match (other, swapped) {
2000 (Intersect, _) => read,
2001 (Union, _) => va + vb - read,
2002 (Subtract, false) => va - read,
2003 (Subtract, true) => vb - read,
2004 };
2005 let (formula, expected) = match operation {
2006 Intersect => ("V(first ∩ second)", intersection),
2007 Union => ("V(first) + V(second) − V(first ∩ second)", va + vb - intersection),
2008 Subtract => ("V(first) − V(first ∩ second)", va - intersection),
2009 };
2010 return Some(InclusionExclusion { formula, reading, read, expected });
2011 }
2012 None
2013}
2014
2015fn planar_operand_off_its_plane(
2024 first: &BrepSolid,
2025 second: &BrepSolid,
2026 options: &BooleanOptions,
2027) -> Option<(u8, u64, f64, f64)> {
2028 let policy = options
2029 .tolerances
2030 .clone()
2031 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
2032 let weld = crate::tolerance::assembler_weld(policy.model);
2033 let mut worst: Option<(u8, u64, f64)> = None;
2034 for (operand, solid) in [(0u8, first), (1u8, second)] {
2035 let vertex_point = |id: u64| solid.vertices.iter().find(|v| v.id == id).map(|v| v.point);
2036 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2037 let Some(crate::AnalyticSurface::Plane {
2038 origin,
2039 u_dir,
2040 v_dir,
2041 ..
2042 }) = face.surface.analytic()
2043 else {
2044 continue;
2045 };
2046 let [loop_record] = face.loops.as_slice() else {
2047 continue;
2048 };
2049 let Ok(normal) = u_dir.cross(*v_dir).normalized() else {
2050 continue;
2051 };
2052 let mut off_plane = 0.0f64;
2053 let mut straight = true;
2054 for coedge in &loop_record.coedges {
2055 let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else {
2056 straight = false;
2057 break;
2058 };
2059 let (Some(start), Some(end)) =
2060 (vertex_point(edge.start_vertex_id), vertex_point(edge.end_vertex_id))
2061 else {
2062 straight = false;
2063 break;
2064 };
2065 let chord = end.sub(start);
2066 let length = chord.length();
2067 if edge.degenerate || length <= weld {
2068 straight = false;
2069 break;
2070 }
2071 let direction = chord.scale(1.0 / length);
2072 for fraction in [0.25, 0.5, 0.75] {
2073 let Ok(point) = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction) else {
2074 straight = false;
2075 break;
2076 };
2077 let delta = point.sub(start);
2078 let along = delta.dot(direction);
2079 if delta.sub(direction.scale(along)).length() > weld
2080 || along < -weld
2081 || along > length + weld
2082 {
2083 straight = false;
2084 break;
2085 }
2086 }
2087 if !straight {
2088 break;
2089 }
2090 off_plane = off_plane.max(start.sub(*origin).dot(normal).abs());
2091 }
2092 if straight && off_plane > weld && worst.is_none_or(|(_, _, gap)| off_plane > gap) {
2093 worst = Some((operand, face.id, off_plane));
2094 }
2095 }
2096 }
2097 worst.map(|(operand, face_id, gap)| (operand, face_id, gap, weld))
2098}
2099
2100fn volume_within_csg_bounds(operation: BooleanOperation, va: f64, vb: f64, vr: f64) -> bool {
2103 let slack = 1e-2 * (va + vb).max(1.0);
2104 match operation {
2105 BooleanOperation::Union => vr >= va.max(vb) - slack && vr <= va + vb + slack,
2107 BooleanOperation::Subtract => vr <= va + slack && vr >= -slack,
2109 BooleanOperation::Intersect => vr <= va.min(vb) + slack && vr >= -slack,
2111 }
2112}
2113
2114fn reverse_fragment(fragment: &mut FaceFragmentRecord) -> Result<(), KernelRefusal> {
2141 fragment.same_sense = !fragment.same_sense;
2142 for loop_record in &mut fragment.loops {
2143 loop_record.coedges.reverse();
2144 for coedge in &mut loop_record.coedges {
2145 coedge.forward = !coedge.forward;
2146 coedge.pcurve = coedge.pcurve.reversed().or_refuse(KernelStage::Validate, "reversed")?;
2147 }
2148 }
2149 Ok(())
2150}
2151
2152fn build_nary_imprint(
2159 operands: &[BrepSolid],
2160 options: &ImprintOptions,
2161) -> Result<ImprintResultRecord, KernelRefusal> {
2162 let mut section_evidence = false;
2163 let mut vertices: Vec<ImprintVertex> = Vec::new();
2164 let mut pieces: Vec<ImprintPieceRecord> = Vec::new();
2165 let mut by_face: HashMap<(u8, u64), Vec<u64>> = HashMap::default();
2166 let mut edge_splits: HashMap<(u8, u64), Vec<f64>> = HashMap::default();
2167 let mut next_vertex_id: u64 = 1;
2168 let mut next_piece_id: u64 = 1;
2169
2170 for i in 0..operands.len() {
2171 for j in (i + 1)..operands.len() {
2172 let pair = build_imprints(&operands[i], &operands[j], options)?;
2173 let remap = |operand: u8| -> u8 {
2174 if operand == 0 {
2175 i as u8
2176 } else {
2177 j as u8
2178 }
2179 };
2180
2181 section_evidence = section_evidence || pair.section_evidence;
2182 let mut vertex_map: HashMap<u64, u64> = HashMap::default();
2183 for vertex in &pair.vertices {
2184 let global = next_vertex_id;
2185 next_vertex_id += 1;
2186 vertex_map.insert(vertex.id, global);
2187 vertices.push(ImprintVertex {
2188 id: global,
2189 point: vertex.point,
2190 });
2191 }
2192
2193 let mut piece_map: HashMap<u64, u64> = HashMap::default();
2194 for piece in &pair.pieces {
2195 let global = next_piece_id;
2196 next_piece_id += 1;
2197 piece_map.insert(piece.id, global);
2198 let mut mapped = piece.clone();
2199 mapped.id = global;
2200 mapped.start_vertex_id = *vertex_map
2201 .get(&piece.start_vertex_id)
2202 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2203 mapped.end_vertex_id = *vertex_map
2204 .get(&piece.end_vertex_id)
2205 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2206 for pcurve in &mut mapped.pcurves {
2207 pcurve.operand = remap(pcurve.operand);
2208 }
2209 mapped.support_faces = [
2210 FaceKey {
2211 operand: remap(piece.support_faces[0].operand),
2212 face_id: piece.support_faces[0].face_id,
2213 },
2214 FaceKey {
2215 operand: remap(piece.support_faces[1].operand),
2216 face_id: piece.support_faces[1].face_id,
2217 },
2218 ];
2219 pieces.push(mapped);
2220 }
2221
2222 for entry in &pair.by_face {
2223 let list = by_face
2224 .entry((remap(entry.operand), entry.face_id))
2225 .or_default();
2226 for piece_id in &entry.piece_ids {
2227 let global = *piece_map.get(piece_id).ok_or_else(|| {
2228 KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: by_face references unknown piece")
2229 })?;
2230 list.push(global);
2231 }
2232 }
2233
2234 for split in &pair.edge_splits {
2235 edge_splits
2236 .entry((remap(split.operand), split.edge_id))
2237 .or_default()
2238 .extend(split.parameters.iter().copied());
2239 }
2240 }
2241 }
2242
2243 Ok(ImprintResultRecord {
2244 faces_in_unproved_pairs: None,
2245 vertices,
2246 pieces,
2247 tangent_nodes: Vec::new(),
2248 barrier_edges: Vec::new(),
2249 section_evidence,
2250 cosurface_pairs: Vec::new(),
2251 tangent_sections: Vec::new(),
2252 by_face: by_face
2253 .into_iter()
2254 .map(|((operand, face_id), piece_ids)| FaceImprints {
2255 operand,
2256 face_id,
2257 piece_ids,
2258 })
2259 .collect(),
2260 edge_splits: edge_splits
2261 .into_iter()
2262 .map(|((operand, edge_id), parameters)| EdgeSplitRecord {
2263 operand,
2264 edge_id,
2265 parameters,
2266 })
2267 .collect(),
2268 })
2269}
2270
2271pub fn boolean_operation_nary(
2282 operands: &[BrepSolid],
2283 operation: BooleanOperation,
2284) -> Result<BrepSolid, KernelRefusal> {
2285 boolean_operation_nary_with_options(operands, operation, &BooleanOptions::default())
2286}
2287
2288pub fn boolean_operation_nary_with_options(
2294 operands: &[BrepSolid],
2295 operation: BooleanOperation,
2296 options: &BooleanOptions,
2297) -> Result<BrepSolid, KernelRefusal> {
2298 let most = nary_chunk();
2303 if operands.len() > most && nary_chunks_on() {
2304 let mut whole = boolean_operation_nary_with_options(&operands[..most], operation, options)?;
2305 for chunk in operands[most..].chunks(most - 1) {
2306 if let [only] = chunk {
2309 whole = boolean_operation(&whole, only, operation, options)?;
2310 continue;
2311 }
2312 let mut next = Vec::with_capacity(chunk.len() + 1);
2313 next.push(whole);
2314 next.extend_from_slice(chunk);
2315 whole = boolean_operation_nary_with_options(&next, operation, options)?;
2316 }
2317 return Ok(whole);
2318 }
2319 let arranged = boolean_operation_nary_arranged(operands, operation, options);
2320 match arranged {
2321 Err(error) if nary_sequential_fallback_enabled() && operands.len() > 2 && error.message.contains("boolean assembly") => {
2322 let mut whole = operands[0].clone();
2325 for operand in &operands[1..] {
2326 whole = match boolean_operation(&whole, operand, operation, options) {
2327 Ok(solid) => solid,
2328 Err(_) => return Err(error),
2329 };
2330 }
2331 Ok(whole)
2332 }
2333 other => other,
2334 }
2335}
2336
2337const NARY_MOST: usize = 255;
2346
2347fn nary_chunk() -> usize {
2350 NARY_MOST
2351}
2352
2353
2354fn nary_chunks_on() -> bool {
2357 crate::switch!("BREP_NARY_CHUNKS", true)
2358}
2359
2360fn nary_sequential_fallback_enabled() -> bool {
2361 crate::switch!("BREP_NARY_SEQUENTIAL_FALLBACK", true)
2362}
2363
2364fn boolean_operation_nary_arranged(
2365 operands: &[BrepSolid],
2366 operation: BooleanOperation,
2367 options: &BooleanOptions,
2368) -> Result<BrepSolid, KernelRefusal> {
2369 if operands.len() > 1 {
2370 if let Some(scaled) = WorkingScale::of(&operands.iter().collect::<Vec<_>>(), options)? {
2371 return boolean_operation_nary_with_options(&scaled.solids, operation, &scaled.options)
2372 .map_err(|error| scaled.refusal(error))
2373 .and_then(|solid| scaled.back(&solid));
2374 }
2375 }
2376 if operands.is_empty() {
2377 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: no operands provided"));
2378 }
2379 if operands.len() == 1 {
2380 return Ok(operands[0].clone());
2381 }
2382 if operands.len() > nary_chunk() {
2383 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: at most 255 operands supported"));
2384 }
2385 if let Some(aligned) = ball_align::align_balls_nary(operands, operation, options.tolerance) {
2388 return boolean_operation_nary_with_options(&aligned, operation, options);
2389 }
2390 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
2391
2392 let mut policy = KernelTolerances::for_solid(&operands[0], options.tolerance);
2396 for operand in &operands[1..] {
2397 let candidate = KernelTolerances::for_solid(operand, options.tolerance);
2398 if candidate.sew_search > policy.sew_search {
2399 policy = candidate;
2400 }
2401 }
2402 policy.check().or_input(KernelStage::Collect, "tolerances")?;
2403 let tolerance = policy.model;
2404
2405 let mut healed = operands.to_vec();
2408 for operand in &mut healed {
2409 crate::heal::heal_operands(operand, &policy)?;
2410 crate::heal::refit_inherited_trims_reused(operand, &policy)?;
2413 normalize_operand_band_seams(operand)?;
2416 }
2417
2418 let mut imprint_options = options.imprint.clone();
2420 imprint_options.tolerance = tolerance;
2421 let imprint = build_nary_imprint(&healed, &imprint_options)?;
2422
2423 let mut split = Vec::with_capacity(healed.len());
2425 for (index, operand) in healed.iter().enumerate() {
2426 split.push(apply_edge_splits(operand, index as u8, &imprint)?);
2427 }
2428 let mut fragments = Vec::with_capacity(split.len());
2429 for (index, solid) in split.iter().enumerate() {
2430 fragments.push(fragment_solid(solid, index as u8, &imprint)?);
2431 }
2432
2433 let selected = select_fragments_nary(&fragments, &healed, operation, tolerance, debug)?;
2435
2436 let solids: HashMap<u8, &BrepSolid> = split
2438 .iter()
2439 .enumerate()
2440 .map(|(index, solid)| (index as u8, solid))
2441 .collect();
2442 let solid = assemble_fragments(selected, &solids, &imprint, tolerance)?;
2443 let solid = if options.merge_coplanar_faces
2444 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
2445 {
2446 let merged = merge_same_surface_faces_excluding(
2447 &solid,
2448 tolerance,
2449 &options.keep_unmerged_name_substrs,
2450 )?;
2451 let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
2452 rejoin::rejoin_unless_referenced(merged, options, tolerance)
2453 } else {
2454 solid
2455 };
2456 let validation = solid.validate_detailed(&policy);
2457 if !validation.issues.is_empty() {
2458 return Err(KernelRefusal::new(
2459 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
2460 KernelStage::Validate,
2461 format!(
2462 "boolean_operation_nary: invalid result: {:?}",
2463 validation.issues
2464 )));
2465 }
2466 if debug {
2467 if let Ok(report) =
2468 crate::oracle::boolean_semantic_disagreement_nary(&healed, operation, &solid, 300)
2469 {
2470 if report.is_flagged() {
2471 eprintln!(
2472 "[oracle] n-ary semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
2473 report.disagreement_rate,
2474 report.disagreements.len(),
2475 report.considered,
2476 report.sample_disagreement()
2477 );
2478 }
2479 }
2480 }
2481 Ok(solid)
2482}
2483
2484fn attribute_to_tangent_node(error: KernelRefusal, nodes: &[Vec3]) -> KernelRefusal {
2515 let Some(node) = nodes.first() else {
2516 return error;
2517 };
2518 if !error.class.perturbation_eligible()
2519 || matches!(error.class, RefusalClass::TangentNodeSingularity)
2520 {
2521 return error;
2522 }
2523 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
2524 eprintln!(
2525 "boolean: tear downstream of the tangent node at ({:.6},{:.6},{:.6}) attributed to it; the stage read: {}",
2526 node.x, node.y, node.z, error.message
2527 );
2528 }
2529 KernelRefusal::new(
2530 RefusalClass::TangentNodeSingularity,
2531 error.stage,
2532 format!(
2533 "boolean: unsupported singular/tangent-node surface intersection \
2534 at the tangent node at ({:.6},{:.6},{:.6}): the section through it did not \
2535 assemble into a closed shell",
2536 node.x, node.y, node.z
2537 ),
2538 )
2539}
2540
2541pub fn attribute_to_tangent_section(
2563 error: KernelRefusal,
2564 sections: &[crate::imprint::TangentSectionRecord],
2565 origins: &[FaceKey],
2566) -> KernelRefusal {
2567 if sections.is_empty()
2568 || !error.class.perturbation_eligible()
2569 || matches!(error.class, RefusalClass::TangentNodeSingularity)
2570 {
2571 return error;
2572 }
2573 let named = refusal_result_faces(&error.message)
2574 .into_iter()
2575 .filter_map(|id| origins.get(id.checked_sub(1)? as usize).copied())
2576 .collect::<Vec<FaceKey>>();
2577 let involving = |fallback: bool| {
2581 sections.iter().find(|section| {
2582 section.grazing.is_empty() != fallback && named.iter().any(|face| section.faces.contains(face))
2583 })
2584 };
2585 let Some(section) = involving(false).or_else(|| involving(true)) else {
2586 return error;
2587 };
2588 let at = |point: Vec3| {
2591 let shown = |value: f64| if value.abs() < 5e-7 { 0.0 } else { value };
2592 format!("({:.6},{:.6},{:.6})", shown(point.x), shown(point.y), shown(point.z))
2593 };
2594 let pierces = (!section.grazing.is_empty()).then(|| {
2600 let shown = section.grazing.len().min(4);
2601 let mut listed = section.grazing[..shown]
2602 .iter()
2603 .map(|(point, tangency)| format!("{} at |tan·n| = {tangency:.4}", at(*point)))
2604 .collect::<Vec<_>>()
2605 .join(", ");
2606 if section.grazing.len() > shown {
2607 listed.push_str(&format!(" and {} more", section.grazing.len() - shown));
2608 }
2609 listed
2610 });
2611 let pierce_only = section.pierce_only();
2612 let shape = if let (true, Some(pierces)) = (pierce_only, pierces.as_deref()) {
2613 format!(
2614 "cross at a grazing angle: a trim edge pierces the other carrier inside both \
2615 trims at {pierces}, below the marcher's start gate, and no transverse section was \
2616 marched between the pierces — a near-tangent crossing born on a tangent contact \
2617 (a third-order singularity) the imprint does not build yet"
2618 )
2619 } else if section.planar {
2620 format!(
2621 "touch along a tangent curve from {} to {} (length {:.6}, {} stations{}) which the \
2622 imprint does not build yet",
2623 at(section.start),
2624 at(section.end),
2625 section.length,
2626 section.stations,
2627 if section.closed { ", closed" } else { "" }
2628 )
2629 } else {
2630 format!(
2631 "touch along a curve through {} with neither carrier planar, a curved/curved \
2632 tangent contact the lane does not trace yet",
2633 at(section.start)
2634 )
2635 };
2636 let shape = match (pierce_only, pierces) {
2637 (false, Some(pierces)) => format!(
2638 "{shape}; a trim edge also pierces the other carrier inside both trims at {pierces}, \
2639 below the marcher's start gate, with no transverse section marched"
2640 ),
2641 _ => shape,
2642 };
2643 let involved = named
2644 .iter()
2645 .filter(|face| section.faces.contains(face))
2646 .map(|face| format!("{}/{}", face.operand, face.face_id))
2647 .collect::<Vec<_>>()
2648 .join(", ");
2649 KernelRefusal::new(
2650 RefusalClass::TangentNodeSingularity,
2651 error.stage,
2652 format!(
2653 "boolean: unsupported tangent-curve surface intersection between faces {}/{} and {}/{}: \
2654 the carriers {shape}; the refusal names face(s) {involved} the contact involves; {}",
2655 section.first.operand, section.first.face_id, section.second.operand, section.second.face_id,
2656 error.message
2657 ),
2658 )
2659}
2660
2661pub fn refusal_result_faces(message: &str) -> Vec<u64> {
2666 let mut ids = Vec::new();
2667 let digits_after = |text: &str| -> Option<u64> {
2668 let end = text.find(|c: char| !c.is_ascii_digit()).unwrap_or(text.len());
2669 text[..end].parse().ok()
2670 };
2671 for (index, _) in message.match_indices("face ") {
2672 if let Some(id) = digits_after(&message[index + "face ".len()..]) {
2673 ids.push(id);
2674 }
2675 }
2676 if let Some(start) = message.find("on faces [") {
2677 let rest = &message[start + "on faces [".len()..];
2678 let list = &rest[..rest.find(']').unwrap_or(rest.len())];
2679 for entry in list.split(", ") {
2680 let entry = entry.trim_start();
2681 if let Some(id) = digits_after(entry) {
2682 if entry[id.to_string().len()..].starts_with(" '") {
2683 ids.push(id);
2684 }
2685 }
2686 }
2687 }
2688 ids.sort_unstable();
2689 ids.dedup();
2690 ids
2691}
2692
2693pub fn boolean_operation_with_diagnostics(
2694 first: &BrepSolid,
2695 second: &BrepSolid,
2696 operation: BooleanOperation,
2697 options: &BooleanOptions,
2698) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2699 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2700 let mut outcome = boolean_operation_with_diagnostics(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
2701 .map_err(|error| scaled.refusal(error))?;
2702 outcome.value = scaled.back(&outcome.value)?;
2703 outcome.diagnostics.count_n("working_scale.fired", 1);
2704 outcome.diagnostics.measure_max("working_scale.factor", scaled.factor);
2705 return Ok(outcome);
2706 }
2707 let _account = profile::Scope::new("boolean.other");
2708 let (first_aligned, second_aligned) = ball_align::align_balls(first, second, operation, options.tolerance);
2711 let (first, second) = (first_aligned.as_ref(), second_aligned.as_ref());
2712 let closed_inputs = matches!(std::env::var("BREP_CLOSED_OPERAND_INPUT").as_deref(), Err(_) | Ok("1") | Ok("on"));
2713 if let (true, Some(later)) = (reseat::seam_reseat_enabled(), &options.seam_reseat_later_references) {
2714 let started = Instant::now();
2715 let (first, second) = reseat::reseat_tangent_seams(first, second, later, options.tolerance);
2716 profile_stage("seam_prepare_ms", started.elapsed().as_secs_f64() * 1000.0);
2717 return boolean_operation_with_diagnostics_impl(&first, &second, operation, options, closed_inputs).map(without_sliver_shells);
2718 }
2719 let cylinders = reseat::seam_reseat_cylinders_mode();
2722 if reseat::seam_reseat_enabled() && cylinders != crate::env_read::Mode::Off {
2723 let kinds = reseat::ContactKinds { planes: false, cylinders: true };
2724 let (reseated_first, reseated_second) = reseat::reseat_tangent_seams_of(first, second, &[], options.tolerance, kinds);
2725 let moved = matches!(reseated_first, std::borrow::Cow::Owned(_)) || matches!(reseated_second, std::borrow::Cow::Owned(_));
2726 if moved {
2727 let reseated = boolean_operation_with_diagnostics_impl(&reseated_first, &reseated_second, operation, options, closed_inputs).map(without_sliver_shells);
2728 if cylinders == crate::env_read::Mode::On {
2729 return reseated;
2730 }
2731 let plain = boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells);
2732 let volume = |result: &Result<KernelOutcome<BrepSolid>, KernelRefusal>| {
2733 result.as_ref().ok().and_then(|outcome| crate::solid_mass_properties(&outcome.value).ok()).map(|mass| mass.volume)
2734 };
2735 eprintln!(
2736 "boolean.seam_reseat_cylinders check: plain {} volume {:?}, reseated {} volume {:?}",
2737 if plain.is_ok() { "built" } else { "refused" },
2738 volume(&plain),
2739 if reseated.is_ok() { "built" } else { "refused" },
2740 volume(&reseated)
2741 );
2742 return plain;
2743 }
2744 }
2745 boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells)
2746}
2747
2748fn without_sliver_shells(mut outcome: KernelOutcome<BrepSolid>) -> KernelOutcome<BrepSolid> {
2750 let dropped = drop_sliver_shells(&mut outcome.value);
2751 if dropped > 0 {
2752 outcome.diagnostics.count_n("sliver_shell.dropped", dropped as u64);
2753 }
2754 outcome
2755}
2756
2757pub fn boolean_operation_with_diagnostics_impl(
2758 first: &BrepSolid,
2759 second: &BrepSolid,
2760 operation: BooleanOperation,
2761 options: &BooleanOptions,
2762 closed_inputs: bool,
2763) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2764 let _coedge_memo = crate::topology::CoedgeMemoScope::open(true);
2767 if matches!(operation, BooleanOperation::Intersect)
2770 && [first, second].iter().any(|body| body.kind == crate::BodyKind::Sheet)
2771 && match std::env::var("BREP_SHEET_TRIM").as_deref() {
2772 Ok("1") => true,
2773 Ok("0") => false,
2774 _ => options.sheet_trim,
2775 }
2776 {
2777 return sheet::trim(first, second, options);
2778 }
2779 if matches!(operation, BooleanOperation::Union | BooleanOperation::Subtract) {
2788 if let Some(operand) = [first, second]
2789 .iter()
2790 .position(|solid| solid.kind == crate::BodyKind::Sheet)
2791 {
2792 return Err(KernelRefusal::input(
2793 KernelStage::Collect,
2794 "sheet_operand",
2795 format!(
2796 "boolean: operand {operand} is a Sheet, which encloses no solid; union and \
2797 subtract of a sheet are refused; Intersect trims a Sheet by a Solid"
2798 ),
2799 ));
2800 }
2801 }
2802 let mut outcome = boolean_operation_with_diagnostics_core(first, second, operation, options)?;
2808 let closure_started = closed_inputs.then(Instant::now);
2809 if closed_inputs {
2810 for (operand, solid) in [first, second].into_iter().enumerate() {
2811 let open = one_use_edges(solid);
2812 if open > 0 {
2813 return Err(KernelRefusal::input(KernelStage::Collect, "operand_closure", format!(
2814 "boolean: operand {operand} is not a closed shell: {open} of its edges bound only one face, so its inside is undefined"
2815 )));
2816 }
2817 }
2818 }
2819 if let Some(started) = closure_started {
2820 let ms = started.elapsed().as_secs_f64() * 1000.0;
2821 profile_stage("operand_closure_ms", ms);
2822 outcome.diagnostics.measure_max("timing.operand_closure_ms", ms);
2823 }
2824 Ok(outcome)
2825}
2826
2827fn boolean_operation_with_diagnostics_core(
2828 first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions,
2829) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2830
2831 if let Some(offset) = crate::recentre::control_offset_at_entry() {
2834 return boolean_operation_with_diagnostics_at_offset(first, second, operation, options, offset);
2835 }
2836 let mut bounds = operand_bounds(first);
2839 bounds.include(operand_bounds(second));
2840 if let Some(offset) = crate::recentre::guard_offset(bounds) {
2841 crate::recentre::profile_fired("boolean", offset, bounds);
2842 let mut outcome = boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Guard)?;
2843 outcome.diagnostics.count_n("recentre.fired", 1);
2844 outcome.diagnostics.measure_max("recentre.distance", offset.length());
2845 return Ok(outcome);
2846 }
2847 let mut tangent_nodes = Vec::new();
2848 let (mut outcome, soundness_candidates) =
2849 boolean_pipeline(first, second, operation, options, &mut tangent_nodes)
2850 .map_err(|error| attribute_to_tangent_node(error, &tangent_nodes))?;
2851 let stage_started = Instant::now();
2864 let accepted = match &soundness_candidates {
2865 Some(candidates) => crate::accept_sound_against_scoped(&[first, second], outcome.value, "boolean", candidates),
2868 None => crate::accept_sound_against(&[first, second], outcome.value, "boolean"),
2869 };
2870 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2871 profile_stage("soundness_ms", stage_ms);
2872 outcome.diagnostics.measure_max("timing.soundness_ms", stage_ms);
2873 outcome.value = accepted?;
2874 Ok(outcome)
2875}
2876
2877pub fn boolean_operation_with_diagnostics_at_offset(
2881 first: &BrepSolid,
2882 second: &BrepSolid,
2883 operation: BooleanOperation,
2884 options: &BooleanOptions,
2885 offset: Vec3,
2886) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2887 boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Control)
2888}
2889
2890fn boolean_translated(
2892 first: &BrepSolid,
2893 second: &BrepSolid,
2894 operation: BooleanOperation,
2895 options: &BooleanOptions,
2896 offset: Vec3,
2897 kind: crate::recentre::EntryKind,
2898) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2899 let _entry = crate::recentre::TranslatedEntry::open(kind);
2900 let translate = |solid: &BrepSolid, offset: Vec3| {
2901 crate::recentre::translate_solid(solid, offset).map_err(|message| {
2902 KernelRefusal::internal(
2903 KernelStage::Collect,
2904 "translation_control",
2905 format!("boolean: the translation control could not move an operand: {message}"),
2906 )
2907 })
2908 };
2909 let moved_first = translate(first, offset)?;
2910 let moved_second = translate(second, offset)?;
2911 let outcome = boolean_operation_with_diagnostics(&moved_first, &moved_second, operation, options)?;
2912 let value = translate(&outcome.value, offset.scale(-1.0))?;
2913 Ok(KernelOutcome { value, diagnostics: outcome.diagnostics })
2914}
2915
2916fn profile_stage(code: &str, ms: f64) {
2920 let row = match code {
2921 "heal_ms" => Some("boolean.operand_prepare"),
2922 "imprint_ms" => Some("boolean.imprint"),
2923 "edge_split_ms" => Some("boolean.edge_split"),
2924 "fragment_ms" => Some("boolean.fragment"),
2925 "select_ms" => Some("boolean.select"),
2926 "assemble_ms" => Some("boolean.assemble"),
2927 "face_merge_ms" => Some("boolean.face_merge"),
2928 "soundness_ms" => Some("boolean.soundness"),
2929 "operand_closure_ms" => Some("boolean.operand_closure"),
2930 "seam_prepare_ms" => Some("boolean.seam_prepare"),
2931 "final_validate_ms" => Some("boolean.final_validate"),
2932 _ => None,
2933 };
2934 if let Some(row) = row { profile::record(row, ms); }
2935 if crate::profile::profile_enabled() {
2936 profile_line!("boolean.{code}={ms:.2}");
2937 }
2938}
2939
2940struct BooleanStageDump {
2945 directory: std::path::PathBuf,
2946 serial: usize,
2947}
2948
2949impl BooleanStageDump {
2950 fn open() -> Option<Self> {
2951 static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2952 let directory = std::env::var("BREP_BOOLEAN_DUMP").ok().filter(|value| !value.is_empty())?;
2953 let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2954 Some(Self { directory: directory.into(), serial })
2955 }
2956
2957 fn write<T: Serialize + ?Sized>(&self, stage: &str, value: &T) {
2958 let path = self.directory.join(format!("{:03}-{stage}.json", self.serial));
2959 match serde_json::to_string(value) {
2960 Ok(text) => {
2961 if let Err(error) = std::fs::write(&path, text) {
2962 eprintln!("BREP_BOOLEAN_DUMP {}: {error}", path.display());
2963 }
2964 }
2965 Err(error) => eprintln!("BREP_BOOLEAN_DUMP {stage}: {error}"),
2966 }
2967 }
2968}
2969
2970pub fn boolean_policy(
2972 first: &BrepSolid,
2973 second: &BrepSolid,
2974 options: &BooleanOptions,
2975) -> Result<KernelTolerances, KernelRefusal> {
2976 let policy = options
2977 .tolerances
2978 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
2979 policy.check().or_input(KernelStage::Collect, "tolerances")?;
2980 Ok(policy)
2981}
2982
2983fn prepared_operands(
2986 first: &BrepSolid,
2987 second: &BrepSolid,
2988 policy: &KernelTolerances,
2989) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
2990 let stage_started = Instant::now();
2999 let mut first_owned = first.clone();
3000 let mut second_owned = second.clone();
3001 crate::heal::heal_operands(&mut first_owned, policy)?;
3002 crate::heal::heal_operands(&mut second_owned, policy)?;
3003 profile_stage("heal.operands_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
3004 let refit_started = Instant::now();
3008 crate::heal::refit_inherited_trims_reused(&mut first_owned, policy)?;
3009 crate::heal::refit_inherited_trims_reused(&mut second_owned, policy)?;
3010 profile_stage("heal.refit_ms", refit_started.elapsed().as_secs_f64() * 1_000.0);
3011 if crate::profile::profile_enabled() {
3012 let (hits, misses) = crate::reading_memo::counts();
3013 profile_line!("boolean.reading_memo hits={hits} misses={misses}");
3014 let (served, stored) = crate::heal::refit_memo_counts_served_stored();
3015 profile_line!("boolean.refit_memo served={served} stored={stored}");
3016 let (served, stored, mismatches) = crate::heal::claim_record_memo_counts();
3017 profile_line!("boolean.claim_record_memo served={served} stored={stored} check_mismatches={mismatches}");
3018 }
3019 profile_stage("heal_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
3020 normalize_operand_band_seams(&mut first_owned)?;
3025 normalize_operand_band_seams(&mut second_owned)?;
3026 Ok((first_owned, second_owned))
3027}
3028
3029fn boolean_imprint_options(options: &BooleanOptions, tolerance: f64) -> ImprintOptions {
3030 let mut imprint_options = options.imprint.clone();
3031 imprint_options.tolerance = tolerance;
3032 imprint_options
3033}
3034
3035pub fn boolean_split_operands(
3045 first: &BrepSolid,
3046 second: &BrepSolid,
3047 options: &BooleanOptions,
3048) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
3049 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
3050 let (split_first, split_second) = boolean_split_operands(&scaled.solids[0], &scaled.solids[1], &scaled.options)
3051 .map_err(|error| scaled.refusal(error))?;
3052 return Ok((scaled.back(&split_first)?, scaled.back(&split_second)?));
3053 }
3054 let policy = boolean_policy(first, second, options)?;
3055 let (first, second) = prepared_operands(first, second, &policy)?;
3056 let imprint = build_imprints(&first, &second, &boolean_imprint_options(options, policy.model))?;
3057 let (split_first, _) = apply_edge_splits_with_map(&first, 0, &imprint)?;
3058 let (split_second, _) = apply_edge_splits_with_map(&second, 1, &imprint)?;
3059 Ok((split_first, split_second))
3060}
3061
3062fn operand_bounds(solid: &BrepSolid) -> crate::Aabb {
3066 let mut bounds = crate::Aabb::from_points(solid.vertices.iter().map(|vertex| vertex.point));
3067 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
3068 match crate::Aabb::from_surface_controls(&face.surface) {
3069 Ok(face_bounds) => bounds.include(face_bounds),
3070 Err(_) => {
3071 return crate::Aabb {
3072 minimum: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
3073 maximum: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
3074 }
3075 }
3076 }
3077 }
3078 bounds
3079}
3080
3081fn line_or_point_contact(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
3087 apart_axes(bounds) >= 2 && plain_hull_solid(first) && plain_hull_solid(second)
3088}
3089
3090fn boxes_share_no_interior(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
3093 apart_axes(bounds) >= 1 && plain_hull_solid(first) && plain_hull_solid(second)
3094}
3095
3096fn apart_axes([a, b]: [crate::Aabb; 2]) -> usize {
3098 let apart = |a_min: f64, a_max: f64, b_min: f64, b_max: f64| a_max <= b_min || b_max <= a_min;
3099 [
3100 apart(a.minimum.x, a.maximum.x, b.minimum.x, b.maximum.x),
3101 apart(a.minimum.y, a.maximum.y, b.minimum.y, b.maximum.y),
3102 apart(a.minimum.z, a.maximum.z, b.minimum.z, b.maximum.z),
3103 ]
3104 .into_iter()
3105 .filter(|&apart| apart)
3106 .count()
3107}
3108
3109fn plain_hull_solid(solid: &BrepSolid) -> bool {
3111 solid.kind == crate::BodyKind::Solid
3112 && solid.cells.is_empty()
3113 && solid.shells.iter().flat_map(|shell| &shell.faces).all(|face| {
3114 face.surface.control_points.iter().flatten().all(|control| control.w > 0.0 && control.w.is_finite())
3115 })
3116}
3117
3118fn scope_proved_apart_on() -> bool {
3122 switch!(live "BREP_SCOPE_PROVED_APART", true)
3123}
3124
3125fn soundness_candidates(
3140 solid: &BrepSolid,
3141 scope: &AssemblyScope,
3142 bounds: [crate::Aabb; 2],
3143 band: f64,
3144 unproved: Option<&HashSet<crate::imprint::FaceKey>>,
3145) -> HashSet<u64> {
3146 let mut candidates = HashSet::default();
3147 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
3148 if scope.examined.contains(&face.id) {
3149 candidates.insert(face.id);
3150 continue;
3151 }
3152 let Some(&operand) = scope.operand_of.get(&face.id) else {
3153 candidates.insert(face.id);
3154 continue;
3155 };
3156 let other = bounds[usize::from(operand == 0)];
3157 match crate::Aabb::from_surface_controls(&face.surface) {
3158 Ok(face_bounds) if !face_bounds.intersects(other, band) => {}
3159 _ => {
3160 let proved_clear = unproved.is_some_and(|unproved| {
3161 scope.source_of.get(&face.id).is_some_and(|key| !unproved.contains(key))
3162 });
3163 if !proved_clear {
3164 candidates.insert(face.id);
3165 }
3166 }
3167 }
3168 }
3169 candidates
3170}
3171
3172
3173fn touching_empty_enabled() -> bool {
3181 switch!("BREP_TOUCHING_EMPTY", true)
3182}
3183
3184thread_local! {
3185 static TOUCHING_PROOF: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3188}
3189
3190fn hair_deep_overlap(first: &BrepSolid, second: &BrepSolid, tolerance: f64) -> bool {
3197 use crate::AnalyticSurface as A;
3198 fn faces(solid: &BrepSolid) -> Vec<(&crate::AnalyticSurface, crate::spatial::Aabb, &crate::NurbsSurface, &crate::FaceRecord)> {
3199 solid
3200 .shells
3201 .iter()
3202 .flat_map(|shell| &shell.faces)
3203 .filter_map(|face| Some((face.surface.analytic()?, crate::Aabb::from_surface_controls(&face.surface).ok()?, &face.surface, face)))
3204 .collect()
3205 }
3206 let along = |surface: &crate::NurbsSurface, axis: Vec3| {
3208 surface.control_points.iter().flatten().filter_map(|control| control.point().ok()).fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), point| {
3209 let at = point.dot(axis);
3210 (low.min(at), high.max(at))
3211 })
3212 };
3213 let crossing = |distance: f64, ra: f64, rb: f64| {
3214 let outer = ra + rb - distance;
3215 let nested = distance - (ra - rb).abs();
3216 outer > tolerance && nested > tolerance
3217 };
3218 let boxes_overlap = |a: &crate::spatial::Aabb, b: &crate::spatial::Aabb| {
3219 (a.maximum.x.min(b.maximum.x) - a.minimum.x.max(b.minimum.x)) > tolerance
3220 && (a.maximum.y.min(b.maximum.y) - a.minimum.y.max(b.minimum.y)) > tolerance
3221 && (a.maximum.z.min(b.maximum.z) - a.minimum.z.max(b.minimum.z)) > tolerance
3222 };
3223 for (a, box_a, surface_a, face_a) in faces(first) {
3224 for (b, box_b, surface_b, face_b) in faces(second) {
3225 if !boxes_overlap(&box_a, &box_b) {
3226 continue;
3227 }
3228 match (a, b) {
3229 (A::RuledRevolution { frame: fa, rho0: a0, rho1: a1, .. }, A::RuledRevolution { frame: fb, rho0: b0, rho1: b1, .. })
3230 if (a0 - a1).abs() <= tolerance && (b0 - b1).abs() <= tolerance =>
3231 {
3232 let offset = fb.origin.sub(fa.origin);
3233 let normal = fa.axis.cross(fb.axis);
3234 if normal.length() <= 1e-12 {
3237 let (low_a, high_a) = along(surface_a, fa.axis);
3238 let (low_b, high_b) = along(surface_b, fa.axis);
3239 if high_a.min(high_b) - low_a.max(low_b) <= tolerance {
3240 continue;
3241 }
3242 }
3243 let apart = if normal.length() <= 1e-12 {
3244 offset.sub(fa.axis.scale(offset.dot(fa.axis))).length()
3245 } else {
3246 offset.dot(normal).abs() / normal.length()
3247 };
3248 if crossing(apart, a0.abs(), b0.abs()) {
3249 return true;
3250 }
3251 }
3252 (A::Sphere { frame: fa, radius: ra }, A::Sphere { frame: fb, radius: rb }) => {
3253 if crossing(fb.origin.sub(fa.origin).length(), *ra, *rb)
3258 && !circle_off_face(face_a, first, (fa.origin, *ra), (fb.origin, *rb), tolerance)
3259 && !circle_off_face(face_b, second, (fb.origin, *rb), (fa.origin, *ra), tolerance)
3260 {
3261 return true;
3262 }
3263 }
3264 _ => {}
3265 }
3266 }
3267 }
3268 false
3269}
3270
3271fn circle_off_face(face: &crate::FaceRecord, solid: &BrepSolid, own: (Vec3, f64), other: (Vec3, f64), tolerance: f64) -> bool {
3279 use crate::classification::{parameter_point_in_face, PolygonClass};
3280 let ((ca, ra), (cb, rb)) = (own, other);
3281 if face.loops.iter().all(|lp| lp.coedges.is_empty()) {
3282 return false;
3283 }
3284 fn clear(curve: &crate::NurbsCurve, depth: u32, centre: Vec3, radius: f64, tolerance: f64) -> bool {
3289 let points: Option<Vec<Vec3>> = curve.control_points.iter().map(|control| if control.w > 0.0 { control.point().ok() } else { None }).collect();
3290 let Some(points) = points else { return false };
3291 if points.iter().all(|point| point.sub(centre).length() < radius - tolerance) {
3292 return true;
3293 }
3294 let (mut low, mut high) = (Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY));
3295 for point in &points {
3296 low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
3297 high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
3298 }
3299 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));
3300 if near.sub(centre).length() > radius + tolerance {
3301 return true;
3302 }
3303 if depth == 0 {
3304 return false;
3305 }
3306 let Ok([t0, t1]) = curve.domain() else { return false };
3307 match curve.split(0.5 * (t0 + t1)) {
3308 Ok((left, right)) => clear(&left, depth - 1, centre, radius, tolerance) && clear(&right, depth - 1, centre, radius, tolerance),
3309 Err(_) => false,
3310 }
3311 }
3312 for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
3313 let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else { return false };
3314 let Ok([d0, d1]) = edge.curve.domain() else { return false };
3315 let mut span = edge.curve.clone();
3317 if edge.t1 < d1 {
3318 match span.split(edge.t1) {
3319 Ok((left, _)) => span = left,
3320 Err(_) => return false,
3321 }
3322 }
3323 if edge.t0 > d0 {
3324 match span.split(edge.t0) {
3325 Ok((_, right)) => span = right,
3326 Err(_) => return false,
3327 }
3328 }
3329 if !clear(&span, 10, cb, rb, tolerance) {
3330 return false;
3331 }
3332 }
3333 let axis = cb.sub(ca);
3334 let distance = axis.length();
3335 let Ok(n) = axis.normalized() else { return false };
3336 let along = (distance * distance + ra * ra - rb * rb) / (2.0 * distance);
3337 let across = ra * ra - along * along;
3338 let Ok(side) = n.perpendicular() else { return false };
3339 if !(across > 0.0) {
3340 return false;
3341 }
3342 let point = ca.add(n.scale(along)).add(side.scale(across.sqrt()));
3343 let Ok(projection) = crate::project_point_to_surface(&face.surface, point) else { return false };
3344 matches!(parameter_point_in_face(face, crate::Vec2 { x: projection.u, y: projection.v }, 1e-9), Ok(PolygonClass::Outside))
3345}
3346
3347
3348fn empty_solid() -> BrepSolid {
3350 BrepSolid {
3351 mass_properties_cache: Default::default(),
3352 cells: Default::default(),
3353 id: 0,
3354 vertices: Vec::new(),
3355 edges: Vec::new(),
3356 shells: Vec::new(),
3357 genus: 0,
3358 kind: crate::BodyKind::Solid,
3359 }
3360}
3361
3362fn concatenate_disjoint(first: &BrepSolid, second: &BrepSolid) -> BrepSolid {
3368 let mut vertices = Vec::new();
3369 let mut edges = Vec::new();
3370 let mut shells = Vec::new();
3371 let mut used_face_names = HashSet::<String>::default();
3372 let (mut next_face_id, mut next_loop_id, mut next_coedge_id) = (1u64, 1u64, 1u64);
3373 for operand in [first, second] {
3374 let vertex_base = vertices.len() as u64;
3375 let edge_base = edges.len() as u64;
3376 let mut vertex_ids: HashMap<u64, u64> = HashMap::default();
3377 for (index, vertex) in operand.vertices.iter().enumerate() {
3378 let id = vertex_base + index as u64 + 1;
3379 vertex_ids.insert(vertex.id, id);
3380 vertices.push(VertexRecord { id, point: vertex.point });
3381 }
3382 let mut edge_ids: HashMap<u64, u64> = HashMap::default();
3383 for (index, edge) in operand.edges.iter().enumerate() {
3384 let id = edge_base + index as u64 + 1;
3385 edge_ids.insert(edge.id, id);
3386 edges.push(EdgeRecord {
3387 id,
3388 curve: edge.curve.clone(),
3389 t0: edge.t0,
3390 t1: edge.t1,
3391 start_vertex_id: vertex_ids.get(&edge.start_vertex_id).copied().unwrap_or(edge.start_vertex_id),
3392 end_vertex_id: vertex_ids.get(&edge.end_vertex_id).copied().unwrap_or(edge.end_vertex_id),
3393 degenerate: edge.degenerate,
3394 name: edge.name.clone(),
3395 });
3396 }
3397 for shell in &operand.shells {
3398 let mut faces = Vec::with_capacity(shell.faces.len());
3399 for face in &shell.faces {
3400 let loops = face
3401 .loops
3402 .iter()
3403 .map(|loop_record| {
3404 let coedges = loop_record
3405 .coedges
3406 .iter()
3407 .map(|coedge| {
3408 let id = next_coedge_id;
3409 next_coedge_id += 1;
3410 CoedgeRecord {
3411 id,
3412 edge_id: edge_ids.get(&coedge.edge_id).copied().unwrap_or(coedge.edge_id),
3413 forward: coedge.forward,
3414 pcurve: coedge.pcurve.clone(),
3415 }
3416 })
3417 .collect();
3418 let id = next_loop_id;
3419 next_loop_id += 1;
3420 LoopRecord { id, coedges }
3421 })
3422 .collect();
3423 let name = face.name.clone().map(|base| {
3424 if used_face_names.insert(base.clone()) {
3425 base
3426 } else {
3427 let mut suffix = 1usize;
3428 loop {
3429 let candidate = format!("{base}_{suffix}");
3430 if used_face_names.insert(candidate.clone()) {
3431 break candidate;
3432 }
3433 suffix += 1;
3434 }
3435 }
3436 });
3437 faces.push(FaceRecord {
3438 id: next_face_id,
3439 surface: face.surface.clone(),
3440 same_sense: face.same_sense,
3441 loops,
3442 name,
3443 });
3444 next_face_id += 1;
3445 }
3446 shells.push(ShellRecord { id: shells.len() as u64 + 1, faces });
3447 }
3448 }
3449 BrepSolid {
3450 mass_properties_cache: Default::default(),
3451 cells: Default::default(),
3452 id: 1,
3453 vertices,
3454 edges,
3455 shells,
3456 genus: first.genus + second.genus,
3457 kind: crate::BodyKind::Solid,
3458 }
3459}
3460
3461fn boolean_pipeline(
3464 first: &BrepSolid,
3465 second: &BrepSolid,
3466 operation: BooleanOperation,
3467 options: &BooleanOptions,
3468 tangent_nodes: &mut Vec<Vec3>,
3469) -> Result<(KernelOutcome<BrepSolid>, Option<HashSet<u64>>), KernelRefusal> {
3470 let _work = crate::imprint::work_profile::Scope::open("boolean");
3471 let replaced_operands = operand_state::replace_operands(first, second, operation, options);
3472 let (first, second) = match &replaced_operands {
3473 Some((first, second)) => (first, second),
3474 None => (first, second),
3475 };
3476 let policy = boolean_policy(first, second, options)?;
3477 let tolerance = policy.model;
3478 let bounds = [operand_bounds(first), operand_bounds(second)];
3493 let disjoint = disjoint_fast_path(options) && !bounds[0].intersects(bounds[1], policy.sew_search);
3494 let contact = !disjoint
3495 && contact_fast_path(options)
3496 && options.seam_reseat_later_references.is_some()
3497 && line_or_point_contact(first, second, bounds);
3498 let contact = contact
3503 || (!disjoint
3504 && matches!(operation, BooleanOperation::Intersect)
3505 && contact_fast_path(options)
3506 && boxes_share_no_interior(first, second, bounds));
3507 if disjoint || contact {
3508 let operation_started = Instant::now();
3509 let mut diagnostics = KernelDiagnostics::default();
3510 diagnostics.count_n(
3511 "collect.faces",
3512 first.shells.iter().chain(&second.shells).map(|shell| shell.faces.len() as u64).sum(),
3513 );
3514 diagnostics.count(if contact { "boolean.contact_fast_path" } else { "boolean.disjoint_fast_path" });
3515 diagnostics.measure_max("tolerance.model", policy.model);
3516 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3517 let value = match operation {
3518 BooleanOperation::Union => concatenate_disjoint(first, second),
3519 BooleanOperation::Subtract => first.clone(),
3520 BooleanOperation::Intersect => {
3521 diagnostics.event(
3522 DiagnosticSeverity::Info,
3523 KernelStage::Select,
3524 "boolean.empty_result",
3525 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
3526 );
3527 empty_solid()
3528 }
3529 };
3530 let stage_ms = operation_started.elapsed().as_secs_f64() * 1_000.0;
3531 profile_stage("disjoint_fast_path_ms", stage_ms);
3532 diagnostics.measure_max("timing.total_ms", stage_ms);
3533 return Ok((KernelOutcome { value, diagnostics }, Some(HashSet::default())));
3534 }
3535 let heal_started = Instant::now();
3536 let (first_owned, second_owned) = prepared_operands(first, second, &policy)?;
3537 let heal_ms = heal_started.elapsed().as_secs_f64() * 1_000.0;
3538 let first = &first_owned;
3539 let second = &second_owned;
3540
3541 let mut diagnostics = KernelDiagnostics::default();
3542 diagnostics.measure_max("timing.heal_ms", heal_ms);
3545 let fit_scope = crate::PcurveFitScope::open();
3550 let polyline_scope = crate::PolylineFitScope::open();
3554 let operation_started = Instant::now();
3555 diagnostics.count_n(
3556 "collect.faces",
3557 first
3558 .shells
3559 .iter()
3560 .chain(&second.shells)
3561 .map(|shell| shell.faces.len() as u64)
3562 .sum(),
3563 );
3564 diagnostics.measure_max("tolerance.model", policy.model);
3565 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3566
3567 let imprint_options = boolean_imprint_options(options, tolerance);
3568 let stage_started = Instant::now();
3569 let imprint = build_imprints(first, second, &imprint_options)?;
3570 tangent_nodes.extend_from_slice(&imprint.tangent_nodes);
3571 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
3572 for piece in &imprint.pieces {
3573 let start = piece.curve.evaluate(piece.t0);
3574 let end = piece.curve.evaluate(piece.t1);
3575 eprintln!(
3576 "piece {} supports={:?} t=[{:.6},{:.6}] start={:?} end={:?}",
3577 piece.id, piece.support_faces, piece.t0, piece.t1, start, end
3578 );
3579 }
3580 for entry in &imprint.by_face {
3581 eprintln!(
3582 "by_face operand={} face={} pieces={:?}",
3583 entry.operand, entry.face_id, entry.piece_ids
3584 );
3585 }
3586 for split in &imprint.edge_splits {
3587 eprintln!(
3588 "edge_split operand={} edge={} params={:?}",
3589 split.operand, split.edge_id, split.parameters
3590 );
3591 }
3592 }
3593 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3594 profile_stage("imprint_ms", stage_ms);
3595 diagnostics.measure_max("timing.imprint_ms", stage_ms);
3596 diagnostics.count_n("intersect.pieces", imprint.pieces.len() as u64);
3597 diagnostics.count_n("intersect.vertices", imprint.vertices.len() as u64);
3598 diagnostics.count_n("intersect.edge_splits", imprint.edge_splits.len() as u64);
3599 let (march_swap_rescues, clip_swap_rescues) = crate::imprint::take_rescue_firings();
3600 diagnostics.count_n("intersect.march_swap_rescue", march_swap_rescues);
3601 diagnostics.count_n("intersect.clip_swap_rescue", clip_swap_rescues);
3602 let touch = TouchCensus::build([first, second], &imprint);
3603 touch.report(&mut diagnostics);
3604 let stage_started = Instant::now();
3605 let (split_first, split_map_first) = apply_edge_splits_with_map(first, 0, &imprint)?;
3606 let (split_second, split_map_second) = apply_edge_splits_with_map(second, 1, &imprint)?;
3607 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3608 profile_stage("edge_split_ms", stage_ms);
3609 diagnostics.measure_max("timing.edge_split_ms", stage_ms);
3610 let stage_started = Instant::now();
3611 crate::classification::classify_profile_begin();
3612 let fragments_a = crate::fragment::fragment_solid_against(&split_first, 0, &imprint, crate::fragment::bounded_carriers(second).then_some((bounds[1], policy.sew_search)))?;
3613 let fragments_b = crate::fragment::fragment_solid_against(&split_second, 1, &imprint, crate::fragment::bounded_carriers(first).then_some((bounds[0], policy.sew_search)))?;
3614 crate::classification::classify_profile_report("fragment");
3615 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3616 profile_stage("fragment_ms", stage_ms);
3617 diagnostics.measure_max("timing.fragment_ms", stage_ms);
3618 diagnostics.count_n(
3619 "fragment.candidates",
3620 (fragments_a.len() + fragments_b.len()) as u64,
3621 );
3622 touch.report_fragments(&[&fragments_a, &fragments_b], &mut diagnostics);
3623 let a_surface_samples: Vec<Vec3> = fragments_a
3628 .iter()
3629 .flat_map(|fragment| {
3630 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
3631 })
3632 .collect();
3633 let b_surface_samples: Vec<Vec3> = fragments_b
3634 .iter()
3635 .flat_map(|fragment| {
3636 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
3637 })
3638 .collect();
3639 let stage_started = Instant::now();
3640 let mut barrier_edges: HashSet<(u8, u64)> = imprint
3641 .pieces
3642 .iter()
3643 .filter_map(|piece| piece.shared_edge.map(|(operand, edge_id, _)| (operand, edge_id)))
3644 .collect();
3645 barrier_edges.extend(imprint.barrier_edges.iter().copied());
3646 for (operand, split_map) in [(0u8, &split_map_first), (1u8, &split_map_second)] {
3652 let minted: Vec<(u8, u64)> = barrier_edges
3653 .iter()
3654 .filter(|(barrier_operand, _)| *barrier_operand == operand)
3655 .filter_map(|(_, edge_id)| split_map.get(edge_id))
3656 .flat_map(|sub_ids| sub_ids.iter().map(|sub_id| (operand, *sub_id)))
3657 .collect();
3658 barrier_edges.extend(minted);
3659 }
3660 crate::classification::classify_profile_begin();
3661 let coincident = coincident_pairs(
3662 &fragments_a,
3663 &fragments_b,
3664 first,
3665 second,
3666 &imprint.cosurface_pairs,
3667 tolerance,
3668 )?;
3669 let sector_mode = sector::sector_mode(options);
3670 let mut select_census = sector::SelectCensus::default();
3671 let mut selected = select_fragments(
3672 fragments_a,
3673 fragments_b,
3674 first,
3675 second,
3676 operation,
3677 tolerance,
3678 &barrier_edges,
3679 &imprint,
3680 &coincident,
3681 sector_mode,
3682 &mut select_census,
3683 )?;
3684 let resewn = resew_coincident_rims(
3685 &mut selected,
3686 [&split_first, &split_second],
3687 [first, second],
3688 &imprint.cosurface_pairs,
3689 operation,
3690 tolerance,
3691 )?;
3692 diagnostics.count_n("select.coincident_pairs", coincident.len() as u64);
3693 diagnostics.count_n("select.rims_resewn", resewn as u64);
3694 crate::classification::classify_profile_report("select");
3695 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3696 profile_stage("select_ms", stage_ms);
3697 diagnostics.measure_max("timing.select_ms", stage_ms);
3698 diagnostics.count_n("select.fragments", selected.len() as u64);
3699 diagnostics.count_n("select.sector_eligible", select_census.eligible);
3701 diagnostics.count_n("select.sector_primary", select_census.sector_primary);
3702 diagnostics.count_n("select.sector_fallback", select_census.sector_fallback);
3703 diagnostics.count_n("select.sector_disagree", select_census.disagree);
3704 diagnostics.count_n("select.ray_casts", select_census.ray_casts);
3705 diagnostics.count_n("select.on_votes", select_census.on_votes);
3706 diagnostics.count_n("select.overturns", select_census.overturns);
3707 if sector_mode != sector::SectorMode::Off || std::env::var_os("BREP_SECTOR_CENSUS").is_some() {
3708 sector::sector_census_line(|| {
3709 format!(
3710 "selection mode={sector_mode:?} select_ms={stage_ms:.3} selected={} eligible={} primary={} fallback={} disagree={} ray_casts={} on_votes={} overturns={}",
3711 selected.len(),
3712 select_census.eligible,
3713 select_census.sector_primary,
3714 select_census.sector_fallback,
3715 select_census.disagree,
3716 select_census.ray_casts,
3717 select_census.on_votes,
3718 select_census.overturns
3719 )
3720 });
3721 }
3722 if selected.is_empty()
3744 && !imprint.section_evidence
3745 && std::env::var("BREP_EMPTY_BOOLEAN").as_deref() != Ok("0")
3746 {
3747 let strictly_inside = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
3748 for &sample in samples {
3749 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::In {
3750 return Ok(true);
3751 }
3752 }
3753 Ok(false)
3754 };
3755 let outside_witness = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
3756 for &sample in samples {
3757 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::Out {
3758 return Ok(true);
3759 }
3760 }
3761 Ok(false)
3762 };
3763 let legitimate = match operation {
3764 BooleanOperation::Intersect => {
3765 !strictly_inside(&a_surface_samples, second)?
3766 && !strictly_inside(&b_surface_samples, first)?
3767 }
3768 BooleanOperation::Subtract => !outside_witness(&a_surface_samples, second)?,
3769 BooleanOperation::Union => false,
3770 };
3771 if legitimate {
3772 diagnostics.event(
3773 DiagnosticSeverity::Info,
3774 KernelStage::Select,
3775 "boolean.empty_result",
3776 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
3777 );
3778 fit_scope.close().report_into(&mut diagnostics);
3779 polyline_scope.close().report_into(&mut diagnostics);
3780 diagnostics.measure_max(
3781 "timing.total_ms",
3782 operation_started.elapsed().as_secs_f64() * 1_000.0,
3783 );
3784 return Ok((
3785 KernelOutcome {
3786 value: empty_solid(),
3787 diagnostics,
3788 },
3789 None,
3790 ));
3791 }
3792 }
3793 if selected.is_empty()
3802 && imprint.section_evidence
3803 && !matches!(operation, BooleanOperation::Union)
3804 && touching_empty_enabled()
3805 && !TOUCHING_PROOF.with(std::cell::Cell::get)
3806 {
3807 let strict = |samples: &[Vec3], other: &BrepSolid, class: PointClass| -> Result<bool, KernelRefusal> {
3808 for &sample in samples {
3809 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == class {
3810 return Ok(true);
3811 }
3812 }
3813 Ok(false)
3814 };
3815 let witnessed = match operation {
3816 BooleanOperation::Intersect => {
3817 !strict(&a_surface_samples, second, PointClass::In)? && !strict(&b_surface_samples, first, PointClass::In)?
3818 }
3819 BooleanOperation::Subtract => !strict(&a_surface_samples, second, PointClass::Out)?,
3820 BooleanOperation::Union => false,
3821 };
3822 let overlap_free = !hair_deep_overlap(first, second, tolerance);
3828 if witnessed && overlap_free {
3829 TOUCHING_PROOF.with(|flag| flag.set(true));
3830 let proof = inclusion_exclusion_volume(first, second, operation, options, body_volume(first), body_volume(second), false);
3831 TOUCHING_PROOF.with(|flag| flag.set(false));
3832 let volume = |solid: &BrepSolid| body_volume(solid).unwrap_or(f64::INFINITY);
3837 let band = 1e-9 * volume(first).max(volume(second));
3838 if let Some(proof) = proof.filter(|proof| proof.expected.is_finite() && proof.expected.abs() <= band) {
3839 diagnostics.event(
3840 DiagnosticSeverity::Info,
3841 KernelStage::Select,
3842 "boolean.empty_touching",
3843 format!(
3844 "{operation:?} of touching operands is empty: {} reads {:.3e} by {} (band {band:.3e})",
3845 proof.formula, proof.expected, proof.reading
3846 ),
3847 );
3848 fit_scope.close().report_into(&mut diagnostics);
3849 polyline_scope.close().report_into(&mut diagnostics);
3850 diagnostics.measure_max("timing.total_ms", operation_started.elapsed().as_secs_f64() * 1_000.0);
3851 return Ok((KernelOutcome { value: empty_solid(), diagnostics }, None));
3852 }
3853 }
3854 }
3855 let solids = [(0, &split_first), (1, &split_second)]
3856 .into_iter()
3857 .collect::<HashMap<_, _>>();
3858 let dump = BooleanStageDump::open();
3859 if let Some(dump) = &dump {
3860 dump.write("first", &split_first);
3861 dump.write("second", &split_second);
3862 dump.write("selected", &selected);
3863 }
3864 let stage_started = Instant::now();
3865 let assembled_origins: Vec<FaceKey> = if imprint.tangent_sections.is_empty() {
3869 Vec::new()
3870 } else {
3871 selected
3872 .iter()
3873 .map(|fragment| FaceKey { operand: fragment.operand, face_id: fragment.source_face_id })
3874 .collect()
3875 };
3876 let attributable: Vec<crate::imprint::TangentSectionRecord> = imprint
3883 .tangent_sections
3884 .iter()
3885 .filter(|section| imprint.tangent_nodes.is_empty() || section.grazing.is_empty())
3886 .cloned()
3887 .collect();
3888 let attribute = |error: KernelRefusal| {
3889 attribute_to_tangent_section(error, &attributable, &assembled_origins)
3890 };
3891 let cellular_result = matches!(operation, BooleanOperation::Union)
3892 && cellular::enabled(options)
3893 && cellular::complete_contact(first, second, &selected, tolerance);
3894 let (solid, scope) = if cellular_result {
3895 (assemble::assemble_cellular_fragments(selected, &solids, &imprint, tolerance)
3896 .map_err(attribute)?, None)
3897 } else if untouched_passthrough(options) {
3898 assemble_fragments_scoped(selected, &solids, &imprint, tolerance, &touch, touched_assembly(options))
3899 .map_err(attribute)?
3900 } else {
3901 (assemble_fragments(selected, &solids, &imprint, tolerance).map_err(attribute)?, None)
3902 };
3903 if let Some(scope) = &scope {
3904 diagnostics.count_n("passthrough.faces_examined", scope.examined.len() as u64);
3905 }
3906 if let Some(dump) = &dump {
3907 dump.write("assembled", &solid);
3908 }
3909 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3910 profile_stage("assemble_ms", stage_ms);
3911 diagnostics.measure_max("timing.assemble_ms", stage_ms);
3912 let stage_started = Instant::now();
3913 let declines_before = crate::face_merge::declines_served();
3914 let area_checks_before = crate::face_merge::boundary_area_checks();
3915 if std::env::var("BREP_DEBUG_PREMERGE_VALIDATE").is_ok() {
3916 let issues = solid.validate();
3917 eprintln!(
3918 "pre-merge validation: {} issue(s){}",
3919 issues.len(),
3920 issues
3921 .first()
3922 .map(|issue| format!(" — first: {}", issue.message))
3923 .unwrap_or_default()
3924 );
3925 }
3926 let solid = if solid.kind != crate::BodyKind::Cellular && options.merge_coplanar_faces
3927 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
3928 {
3929 let merged = match &scope {
3930 Some(scope) => merge_same_surface_faces_scoped(
3934 &solid,
3935 tolerance,
3936 &options.keep_unmerged_name_substrs,
3937 &scope.examined,
3938 )?,
3939 None => merge_same_surface_faces_excluding(
3940 &solid,
3941 tolerance,
3942 &options.keep_unmerged_name_substrs,
3943 )?,
3944 };
3945 let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
3950 rejoin::rejoin_unless_referenced(merged, options, tolerance)
3951 } else {
3952 solid
3953 };
3954 if let Some(dump) = &dump {
3955 dump.write("merged", &solid);
3956 }
3957 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3958 profile_stage("face_merge_ms", stage_ms);
3959 if crate::profile::profile_enabled() {
3960 profile_line!("boolean.merge_declines served={}", crate::face_merge::declines_served() - declines_before);
3961 let area_checks = crate::face_merge::boundary_area_checks();
3962 if area_checks != area_checks_before {
3963 profile_line!("boolean.merge_area_checks boundary={} integrated={}", area_checks.0 - area_checks_before.0, area_checks.1 - area_checks_before.1);
3964 }
3965 }
3966 diagnostics.measure_max("timing.face_merge_ms", stage_ms);
3967 let validation_started = Instant::now();
3968 let validation = solid.validate_detailed_scoped(&policy, scope.as_ref().map(|scope| &scope.examined));
3969 profile_stage("final_validate_ms", validation_started.elapsed().as_secs_f64() * 1000.0);
3970 diagnostics.count_n("validate.issues", validation.issues.len() as u64);
3971 diagnostics.count_n(
3972 "validate.wire_warnings",
3973 validation.wire_warnings.len() as u64,
3974 );
3975 diagnostics.measure_max("validate.max_pcurve_error", validation.max_pcurve_error);
3976 for warning in &validation.wire_warnings {
3977 diagnostics.event(
3978 DiagnosticSeverity::Warning,
3979 KernelStage::Validate,
3980 "validate.uv_wire",
3981 warning.message.clone(),
3982 );
3983 }
3984 for issue in &validation.issues {
3985 diagnostics.event(
3986 DiagnosticSeverity::Error,
3987 KernelStage::Validate,
3988 "validate.brep",
3989 issue.message.clone(),
3990 );
3991 }
3992 fit_scope.close().report_into(&mut diagnostics);
3993 polyline_scope.close().report_into(&mut diagnostics);
3994 diagnostics.measure_max(
3995 "timing.total_ms",
3996 operation_started.elapsed().as_secs_f64() * 1_000.0,
3997 );
3998 if !validation.issues.is_empty() {
3999 return Err(KernelRefusal::new(
4000 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
4001 KernelStage::Validate,
4002 format!(
4003 "boolean_operation: invalid result: {:?}",
4004 validation.issues
4005 )));
4006 }
4007 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
4013 if let Ok(report) =
4014 crate::oracle::boolean_semantic_disagreement(first, second, operation, &solid, 200)
4015 {
4016 if report.is_flagged() {
4017 eprintln!(
4018 "[oracle] semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
4019 report.disagreement_rate,
4020 report.disagreements.len(),
4021 report.considered,
4022 report.sample_disagreement()
4023 );
4024 }
4025 }
4026 let fusable_band = crate::tolerance::assembler_weld(policy.model);
4027 let fusables = crate::oracle::boolean_residual_fusables(&solid, fusable_band);
4028 if !fusables.is_empty() {
4029 eprintln!(
4030 "[oracle] {} residual fusable(s) after weld; sample {:?}",
4031 fusables.len(),
4032 fusables.first()
4033 );
4034 }
4035 }
4036 let candidates = scope.as_ref().map(|scope| {
4037 let unproved = (scope_proved_apart_on() && plain_hull_solid(first) && plain_hull_solid(second))
4038 .then(|| imprint.faces_in_unproved_pairs.as_ref())
4039 .flatten()
4040 .map(|faces| faces.iter().copied().collect::<HashSet<_>>());
4041 let candidates = soundness_candidates(
4042 &solid,
4043 scope,
4044 [operand_bounds(first), operand_bounds(second)],
4045 policy.sew_search,
4046 unproved.as_ref(),
4047 );
4048 diagnostics.count_n("passthrough.soundness_candidates", candidates.len() as u64);
4049 crate::soundness::census::profile_operation(&solid, &[first, second], Some(&scope.touched), "boolean");
4050 candidates
4051 });
4052 Ok((
4053 KernelOutcome {
4054 value: solid,
4055 diagnostics,
4056 },
4057 candidates,
4058 ))
4059}
4060