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
136fn touched_assembly(options: &BooleanOptions) -> bool {
138 match std::env::var("BREP_TOUCHED_ASSEMBLY").as_deref() {
139 Ok("0") => false,
140 Ok(_) => true,
141 Err(_) => options.touched_assembly,
142 }
143}
144
145fn disjoint_fast_path(options: &BooleanOptions) -> bool {
147 match std::env::var("BREP_DISJOINT_FAST_PATH").as_deref() {
148 Ok("0") => false,
149 Ok(_) => true,
150 Err(_) => options.disjoint_fast_path,
151 }
152}
153
154fn contact_fast_path(options: &BooleanOptions) -> bool {
156 match std::env::var("BREP_CONTACT_FAST_PATH").as_deref() {
157 Ok("0") => false,
158 Ok(_) => true,
159 Err(_) => options.contact_fast_path,
160 }
161}
162
163fn untouched_passthrough(options: &BooleanOptions) -> bool {
165 match std::env::var("BREP_UNTOUCHED_PASSTHROUGH").as_deref() {
166 Ok("0") => false,
167 Ok(_) => true,
168 Err(_) => options.untouched_passthrough,
169 }
170}
171
172fn default_tolerance() -> f64 {
173 1e-7
174}
175
176fn default_true() -> bool {
177 true
178}
179
180impl Default for BooleanOptions {
181 fn default() -> Self {
182 Self {
183 tolerance: default_tolerance(),
184 tolerances: None,
185 imprint: ImprintOptions::default(),
186 merge_coplanar_faces: true,
187 keep_unmerged_name_substrs: Vec::new(),
188 untouched_passthrough: true,
189 disjoint_fast_path: true,
190 contact_fast_path: true,
191 touched_assembly: false,
192 sector_classification: true,
193 sheet_trim: true,
194 keep_cells: false,
195 seam_reseat_later_references: None,
196 seam_rejoin_later_references: None,
197 }
198 }
199}
200
201mod select;
202mod sheet;
203mod cellular;
204pub mod sector;
205pub mod assemble;
206mod operand_state;
207mod rim;
208mod coincident;
209mod touch;
210pub(crate) mod reseat;
211mod ball_align;
212mod rejoin;
213
214pub use rim::*;
215use select::*;
216use coincident::*;
217use touch::TouchCensus;
218pub use assemble::{
219 assemble_fragments, assemble_open_fragments, commit_nearby_edge_endpoints,
220 clear_candidate_memo, edge_interior_lies_on, finalize_assembled_solid, refresh_derived_genus,
221};
222use assemble::{assemble_fragments_scoped, AssemblyScope};
223#[allow(unused_imports)]
225pub use assemble::apply_assembly_heal_chain;
226
227
228struct WorkingScale {
231 factor: f64,
232 solids: Vec<BrepSolid>,
233 options: BooleanOptions,
234}
235
236impl WorkingScale {
237 fn of(operands: &[&BrepSolid], options: &BooleanOptions) -> Result<Option<Self>, KernelRefusal> {
238 let Some(bounds) = crate::rescale::bounds_of(operands.iter().copied()) else {
239 return Ok(None);
240 };
241 let Some(factor) = crate::rescale::guard_factor(bounds) else {
242 return Ok(None);
243 };
244 crate::rescale::profile_fired("boolean", factor, bounds);
245 let solids = operands
246 .iter()
247 .map(|solid| crate::rescale::scale_operand(solid, factor, "boolean"))
248 .collect::<Result<Vec<_>, _>>()?;
249 let mut options = options.clone();
251 options.imprint.maximum_ssi_step = options.imprint.maximum_ssi_step.map(|step| step * factor);
252 Ok(Some(Self { factor, solids, options }))
253 }
254
255 fn back(&self, solid: &BrepSolid) -> Result<BrepSolid, KernelRefusal> {
256 crate::rescale::scale_operand(solid, 1.0 / self.factor, "boolean")
257 }
258
259 fn refusal(&self, error: KernelRefusal) -> KernelRefusal {
260 crate::rescale::name_scale(error, self.factor)
261 }
262}
263
264pub fn boolean_operation(
265 first: &BrepSolid,
266 second: &BrepSolid,
267 operation: BooleanOperation,
268 options: &BooleanOptions,
269) -> Result<BrepSolid, KernelRefusal> {
270 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
271 return boolean_operation(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
272 .map_err(|error| scaled.refusal(error))
273 .and_then(|solid| scaled.back(&solid));
274 }
275 match boolean_operation_with_diagnostics(first, second, operation, options) {
276 Ok(outcome) => {
277 if below_tolerance_refusal_enabled()
280 && outcome.value.shells.iter().all(|shell| shell.faces.is_empty())
281 && !matches!(operation, BooleanOperation::Union)
282 {
283 if let Some(refusal) = below_tolerance_refusal(first, second, None) {
284 if let Some(answer) = below_tolerance_answer(first, second, operation) {
285 return Ok(answer);
286 }
287 if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
288 return Ok(answer);
289 }
290 return Err(refusal);
291 }
292 }
293 if unresolved_merge_refusal_enabled() && !matches!(operation, BooleanOperation::Subtract) {
294 if let Some(refusal) = unresolved_merge_refusal(first, second) {
295 return Err(refusal);
296 }
297 }
298 if below_tolerance_slivers_enabled()
301 && !matches!(operation, BooleanOperation::Subtract)
302 && [first, second].iter().all(|solid| face_count(solid) <= SLIVER_ANSWER_FACES)
303 && near_coincident_planar_faces(first, second).is_some()
304 {
305 if let Some(answer) = below_tolerance_answer(first, second, operation) {
306 return Ok(answer);
307 }
308 }
309 Ok(outcome.value)
310 }
311 Err(error) => {
312 if below_tolerance_refusal_enabled() {
313 if let Some(refusal) = below_tolerance_refusal(first, second, Some(&error)) {
314 if let Some(answer) = below_tolerance_answer(first, second, operation) {
315 return Ok(answer);
316 }
317 if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
318 return Ok(answer);
319 }
320 return Err(refusal);
321 }
322 }
323 if std::env::var("BREP_NO_PERTURB").as_deref() == Ok("1")
331 || !error.class.perturbation_eligible()
332 {
333 return Err(error);
334 }
335 if std::env::var("BREP_OPEN_OPERAND_GATE").as_deref() != Ok("0") {
357 if let Some((operand, open)) = [first, second]
358 .iter()
359 .enumerate()
360 .find_map(|(operand, solid)| {
361 let open = one_use_edges(solid);
362 (open > 0).then_some((operand, open))
363 })
364 {
365 return Err(error.with_message(|message| format!(
366 "{message}; operand {operand} is not a closed shell: {open} of its edges bound \
367 only one face, so no boolean of it encloses a solid and no perturbation \
368 can close it"
369 )));
370 }
371 }
372 if let Some((operand, face_id, deviation, weld)) =
373 planar_operand_off_its_plane(first, second, options)
374 {
375 return Err(error.with_message(|message| format!(
376 "{message}; operand {operand} face {face_id} is a plane whose straight \
377 boundary sits {deviation:.3e} off it (assembly weld {weld:.1e}), which \
378 no perturbation can reconcile — the body's planes must contain their \
379 boundary before it can take part in an exact boolean"
380 )));
381 }
382 if matches!(operation, BooleanOperation::Subtract)
397 && std::env::var("BREP_PINCH_GATE").as_deref() != Ok("0")
398 && subtract_pinches_at_internal_tangency(first, second, options.tolerance)
399 .unwrap_or(false)
400 {
401 if let Some(solid) = subtract_through_the_common_part(first, second, options) {
404 return Ok(solid);
405 }
406 return Err(error.with_message(|message| format!(
407 "{message}; internal tangency: the operands touch tangentially with \
408 co-directed normals, so the exact difference pinches to zero thickness \
409 (non-manifold, unrepresentable in a boundary model) — refusing rather \
410 than returning a perturbed sliver"
411 )));
412 }
413 if matches!(error.class, RefusalClass::TangentNodeSingularity)
429 && std::env::var("BREP_TANGENT_NODE_GATE").as_deref() != Ok("0")
430 {
431 return Err(error);
432 }
433 if matches!(operation, BooleanOperation::Union) {
437 if let Some(solid) = union_through_the_difference(first, second, options) {
438 return Ok(solid);
439 }
440 }
441 match perturbation_retry(first, second, operation, options) {
442 Ok(solid) => Ok(solid),
443 Err(refused) if refused.is_empty() => Err(error),
444 Err(refused) => {
445 Err(error.with_message(|message| format!("{message}; {}", refused.join("; "))))
446 }
447 }
448 }
449 }
450}
451
452const PINCH_PROBE_STEPS: usize = 8;
457
458const PINCH_ANGULAR_TOLERANCE: f64 = 1e-4;
461
462const PINCH_SEPARATION_STEP: f64 = 1e-2;
466
467fn subtract_through_the_common_part(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
485 if !switch!("BREP_PINCH_COMMON_RETRY", true) || !options.imprint.tangent_curve_imprint {
488 return None;
489 }
490 let common = boolean_operation_with_diagnostics(first, second, BooleanOperation::Intersect, options).ok()?.value;
491 if common.shells.iter().all(|shell| shell.faces.is_empty()) {
492 return None;
493 }
494 let cut = boolean_operation_with_diagnostics(first, &common, BooleanOperation::Subtract, options).ok()?.value;
495 if !cut.validate().is_empty() {
496 return None;
497 }
498 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
499 let (whole, taken, left) = (volume(first)?, volume(&common)?, volume(&cut)?);
500 ((left - (whole - taken)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(cut)
501}
502
503fn union_through_the_difference(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
516 if !switch!("BREP_TANGENT_UNION_DIFFERENCE_RETRY", true) || !options.imprint.tangent_curve_imprint {
517 return None;
518 }
519 let pinches = |a: &BrepSolid, b: &BrepSolid| subtract_pinches_at_internal_tangency(a, b, options.tolerance).unwrap_or(false);
520 if !pinches(first, second) && !pinches(second, first) {
521 return None;
522 }
523 let difference = match boolean_operation_with_diagnostics(first, second, BooleanOperation::Subtract, options) {
524 Ok(outcome) => outcome.value,
525 Err(_) => subtract_through_the_common_part(first, second, options)?,
526 };
527 if difference.shells.iter().all(|shell| shell.faces.is_empty()) || !difference.validate().is_empty() {
528 return None;
529 }
530 let union = boolean_operation_with_diagnostics(second, &difference, BooleanOperation::Union, options).ok()?.value;
531 if !union.validate().is_empty() {
532 return None;
533 }
534 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
535 let (left, added, whole) = (volume(&difference)?, volume(second)?, volume(&union)?);
536 ((whole - (left + added)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(union)
537}
538
539pub fn subtract_pinches_at_internal_tangency(
561 first: &BrepSolid,
562 second: &BrepSolid,
563 tolerance: f64,
564) -> Result<bool, KernelRefusal> {
565 let contact = (tolerance * 100.0).max(1e-12);
568 let probes_a = first
569 .shells
570 .iter()
571 .flat_map(|shell| &shell.faces)
572 .map(PinchProbe::of)
573 .collect::<Result<Vec<_>, _>>()?;
574 let probes_b = second
575 .shells
576 .iter()
577 .flat_map(|shell| &shell.faces)
578 .map(PinchProbe::of)
579 .collect::<Result<Vec<_>, _>>()?;
580 for probe_a in &probes_a {
581 for probe_b in &probes_b {
582 let pad = 1e-2 * probe_a.extent().max(probe_b.extent());
589 if probe_a.separation(probe_b) > contact + pad {
590 continue;
591 }
592 if classify_surface_pair(
599 &probe_a.face.surface,
600 &probe_b.face.surface,
601 tolerance,
602 PINCH_ANGULAR_TOLERANCE,
603 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")?
604 .relation
605 == SurfacePairRelation::Cosurface
606 {
607 continue;
608 }
609 if faces_touch_with_codirected_normals(probe_a, probe_b, contact)? {
610 return Ok(true);
611 }
612 }
613 }
614 Ok(false)
615}
616
617struct PinchProbe<'a> {
620 face: &'a FaceRecord,
621 samples: Vec<(f64, f64, Vec3)>,
623 minimum: [f64; 3],
624 maximum: [f64; 3],
625}
626
627impl<'a> PinchProbe<'a> {
628 fn of(face: &'a FaceRecord) -> Result<Self, KernelRefusal> {
629 let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
630 let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
631 let steps = PINCH_PROBE_STEPS as f64;
632 let mut samples = Vec::with_capacity((PINCH_PROBE_STEPS + 1).pow(2));
633 let mut minimum = [f64::INFINITY; 3];
634 let mut maximum = [f64::NEG_INFINITY; 3];
635 for i in 0..=PINCH_PROBE_STEPS {
636 let u = u0 + (u1 - u0) * i as f64 / steps;
637 for j in 0..=PINCH_PROBE_STEPS {
638 let v = v0 + (v1 - v0) * j as f64 / steps;
639 let Ok(point) = face.surface.evaluate(u, v) else {
640 continue;
641 };
642 for (axis, value) in [point.x, point.y, point.z].into_iter().enumerate() {
643 minimum[axis] = minimum[axis].min(value);
644 maximum[axis] = maximum[axis].max(value);
645 }
646 samples.push((u, v, point));
647 }
648 }
649 Ok(Self {
650 face,
651 samples,
652 minimum,
653 maximum,
654 })
655 }
656
657 fn extent(&self) -> f64 {
659 (0..3)
660 .map(|axis| self.maximum[axis] - self.minimum[axis])
661 .fold(0.0f64, f64::max)
662 }
663
664 fn separation(&self, other: &Self) -> f64 {
666 let mut gap: f64 = 0.0;
667 for axis in 0..3 {
668 gap = gap.max(self.minimum[axis] - other.maximum[axis]);
669 gap = gap.max(other.minimum[axis] - self.maximum[axis]);
670 }
671 gap
672 }
673}
674
675fn faces_touch_with_codirected_normals(
680 probe_a: &PinchProbe<'_>,
681 probe_b: &PinchProbe<'_>,
682 contact: f64,
683) -> Result<bool, KernelRefusal> {
684 for (probe, other) in [(probe_a, probe_b), (probe_b, probe_a)] {
685 let source = probe.face;
686 let target = other.face;
687 for &(u, v, point) in &probe.samples {
688 let projection = project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?;
689 if projection.distance > contact {
690 continue;
691 }
692 let (Ok(source_normal), Ok(target_normal)) = (
695 source.surface.normal(u, v),
696 target.surface.normal(projection.u, projection.v),
697 ) else {
698 continue;
699 };
700 let source_outward = outward_normal(source_normal, source.same_sense);
701 let target_outward = outward_normal(target_normal, target.same_sense);
702 if source_outward.cross(target_outward).length() > PINCH_ANGULAR_TOLERANCE
703 || source_outward.dot(target_outward) <= 0.0
704 {
705 continue;
706 }
707 if parameter_point_in_face(source, Vec2 { x: u, y: v }, 1e-6).or_refuse(KernelStage::Validate, "parameter_point_in_face")?
708 == PolygonClass::Outside
709 || parameter_point_in_face(
710 target,
711 Vec2 {
712 x: projection.u,
713 y: projection.v,
714 },
715 1e-6,
716 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")? == PolygonClass::Outside
717 {
718 continue;
719 }
720 if contact_separates_locally(source, target, u, v, contact)? {
721 return Ok(true);
722 }
723 }
724 }
725 Ok(false)
726}
727
728fn outward_normal(normal: Vec3, same_sense: bool) -> Vec3 {
729 if same_sense {
730 normal
731 } else {
732 normal.scale(-1.0)
733 }
734}
735
736fn contact_separates_locally(
742 source: &FaceRecord,
743 target: &FaceRecord,
744 u: f64,
745 v: f64,
746 contact: f64,
747) -> Result<bool, KernelRefusal> {
748 let [u0, u1] = source.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
749 let [v0, v1] = source.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
750 let step_u = (u1 - u0) * PINCH_SEPARATION_STEP;
751 let step_v = (v1 - v0) * PINCH_SEPARATION_STEP;
752 for (probe_u, probe_v) in [
753 ((u + step_u).min(u1), v),
754 ((u - step_u).max(u0), v),
755 (u, (v + step_v).min(v1)),
756 (u, (v - step_v).max(v0)),
757 ] {
758 if (probe_u - u).abs() < f64::EPSILON && (probe_v - v).abs() < f64::EPSILON {
759 continue;
760 }
761 let Ok(point) = source.surface.evaluate(probe_u, probe_v) else {
762 continue;
763 };
764 if project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?.distance > contact * 10.0 {
767 return Ok(true);
768 }
769 }
770 Ok(false)
771}
772
773fn perturbation_retry(
827 first: &BrepSolid,
828 second: &BrepSolid,
829 operation: BooleanOperation,
830 options: &BooleanOptions,
831) -> Result<BrepSolid, Vec<String>> {
832 const DIRECTIONS: [[f64; 3]; 4] = [
843 [0.4034, 0.7973, 0.4491],
844 [0.7973, 0.4491, 0.4034],
845 [0.4491, 0.4034, 0.7973],
846 [0.5774, -0.5774, 0.5774],
847 ];
848 const FRACTIONS: [f64; 5] = PERTURBATION_FRACTIONS;
854
855 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
856 let scale = crate::solid_tolerance::solid_scale(first)
857 .max(crate::solid_tolerance::solid_scale(second))
858 .max(1.0);
859
860 let _caller = crate::mass_caller("boolean.perturbation_rescue");
864 let va = solid_signed_volume(first).ok().map(f64::abs);
865 let vb = solid_signed_volume(second).ok().map(f64::abs);
866 let hold_identity = std::env::var("BREP_PERTURB_IDENTITY").as_deref() != Ok("0");
867 let hold_mirror = hold_identity && std::env::var("BREP_PERTURB_MIRROR").as_deref() != Ok("0");
870 let early_exit = std::env::var("BREP_MIRROR_EARLY_EXIT").as_deref() != Ok("0");
873 let mut trends = [MirrorTrend::default(); 4];
874 let mut identity: Option<Option<InclusionExclusion>> = None;
876 let mut refused = Vec::new();
877 let ladder = std::env::var("BREP_DEBUG_PERTURB_LADDER").is_ok();
881 let ladder_start = web_time::Instant::now();
882 if ladder {
883 let measured = inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
884 match &measured {
885 Some(identity) => eprintln!(
886 "[ladder] identity {} = {:.9} from the exact lane's {} ({:.9}); V(first) {:?} V(second) {:?}",
887 identity.formula, identity.expected, identity.reading, identity.read, va, vb
888 ),
889 None => eprintln!("[ladder] no identity: no exact-lane boolean of these operands clears in either order"),
890 }
891 identity = Some(measured);
892 }
893 let rung_miss = |identity: &Option<Option<InclusionExclusion>>, candidate: &BrepSolid| -> String {
894 let volume = body_volume(candidate);
895 match (identity, volume) {
896 (Some(Some(identity)), Some(volume)) => format!(
897 "volume {volume:.9} miss {:+.3e} bar {:.3e}",
898 volume - identity.expected,
899 crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * identity.expected.abs())
900 ),
901 (_, Some(volume)) => format!("volume {volume:.9}"),
902 _ => "no volume".to_string(),
903 }
904 };
905
906 for &fraction in &FRACTIONS {
907 let magnitude = scale * fraction;
908 for (direction, dir) in DIRECTIONS.iter().enumerate() {
909 if trends[direction].closed {
910 if ladder {
911 eprintln!("[ladder] dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}: not tried, its direction is closed");
912 }
913 continue;
914 }
915 let offset = [dir[0] * magnitude, dir[1] * magnitude, dir[2] * magnitude];
916 let translate = match AffineTransform::new([
917 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,
921 ]) {
922 Ok(transform) => transform,
923 Err(_) => continue,
924 };
925 let moved = match crate::transform_brep(second, translate, false) {
926 Ok(solid) => solid,
927 Err(_) => continue,
928 };
929 let rung = format!("dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}");
930 let rung_start = web_time::Instant::now();
931 let candidate =
932 match boolean_operation_with_diagnostics(first, &moved, operation, options) {
933 Ok(outcome) => outcome.value,
934 Err(error) => {
935 if ladder {
936 eprintln!("[ladder] {rung}: exact lane refused {:?}", error.class);
937 }
938 continue;
939 }
940 };
941 let built = rung_start.elapsed();
942 if candidate.shells.is_empty() {
944 if ladder {
945 eprintln!("[ladder] {rung}: empty");
946 }
947 continue;
948 }
949 if let (Some(va), Some(vb)) = (va, vb) {
954 if let Ok(vr) = solid_signed_volume(&candidate) {
955 if !volume_within_csg_bounds(operation, va, vb, vr.abs()) {
956 if ladder {
957 eprintln!("[ladder] {rung}: outside the CSG bound, {}", rung_miss(&identity, &candidate));
958 }
959 continue;
960 }
961 }
962 }
963 let bounded = rung_start.elapsed();
968 if hold_identity {
970 let identity = identity.get_or_insert_with(|| {
971 let identity =
972 inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
973 if debug && identity.is_none() {
974 eprintln!(
975 "[perturb] no exact-lane boolean of these operands clears in either \
976 order; no identity to hold"
977 );
978 }
979 identity
980 });
981 if let Some(identity) = identity {
982 let expected = identity.expected;
983 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * expected.abs());
984 let volume = body_volume(&candidate);
985 let miss = volume.map(|volume| (volume - expected).abs());
986 if !miss.is_some_and(|miss| miss <= bar) {
987 let sentence = format!(
988 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
989 (offset {magnitude:.3e}) refused: its body reads {} against the \
990 inclusion–exclusion identity {} = {expected:.9} (the exact lane's \
991 {} reads {:.9}), a miss of {} beyond the volume drift bar {bar:.3e}",
992 volume.map_or("no volume".to_string(), |volume| format!("{volume:.9}")),
993 identity.formula,
994 identity.reading,
995 identity.read,
996 miss.map_or("unmeasured".to_string(), |miss| format!("{miss:.3e}")),
997 );
998 if debug {
999 eprintln!("[perturb] {sentence}");
1000 }
1001 if ladder {
1002 eprintln!(
1003 "[ladder] {rung}: refused by the identity, volume {} miss {} bar {bar:.3e}",
1004 volume.map_or("none".to_string(), |volume| format!("{volume:.9}")),
1005 volume.map_or("unmeasured".to_string(), |volume| format!("{:+.3e}", volume - expected)),
1006 );
1007 }
1008 refused.push(sentence);
1009 continue;
1010 }
1011 } else if hold_mirror {
1012 let mirror_start = web_time::Instant::now();
1015 let mirrored = AffineTransform::new([
1016 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,
1020 ])
1021 .ok()
1022 .and_then(|transform| crate::transform_brep(second, transform, false).ok());
1023 let mirror = mirrored.as_ref().and_then(|mirrored| {
1024 inclusion_exclusion_volume(first, mirrored, operation, options, va, vb, true)
1025 });
1026 let mirror_time = mirror_start.elapsed();
1027 let volume = body_volume(&candidate);
1028 let mut measured = None;
1029 let verdict = match (&mirror, volume) {
1030 (Some(mirror), Some(volume)) => {
1031 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * mirror.expected.abs());
1032 let miss = 0.5 * (volume - mirror.expected).abs();
1033 measured = Some((0.5 * (volume - mirror.expected), bar));
1034 if ladder {
1035 eprintln!(
1036 "[ladder] {rung}: mirror at −offset reads {} = {:.9} (the mirrored {} {:.9}); body {volume:.9}, first-order translation error {:+.3e} bar {bar:.3e}",
1037 mirror.formula, mirror.expected, mirror.reading, mirror.read, 0.5 * (volume - mirror.expected)
1038 );
1039 }
1040 (miss > bar).then(|| format!(
1041 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1042 (offset {magnitude:.3e}) refused: no exact-lane boolean of the \
1043 operands clears, so the rung is held to its mirror: its body reads \
1044 {volume:.9} with the second operand moved +offset and {} = {:.9} \
1045 with it moved −offset (the mirrored {} reads {:.9}), a first-order \
1046 translation error of {miss:.3e} beyond the volume drift bar {bar:.3e}",
1047 mirror.formula, mirror.expected, mirror.reading, mirror.read
1048 ))
1049 }
1050 _ => Some(format!(
1051 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1052 (offset {magnitude:.3e}) refused: no exact-lane boolean of the operands \
1053 clears, and none clears with the second operand moved −offset either, \
1054 so nothing checks the rung's body{}",
1055 volume.map_or(String::new(), |volume| format!(" ({volume:.9})"))
1056 )),
1057 };
1058 match verdict {
1059 None => trends[direction].cleared(),
1060 Some(sentence) => {
1061 if debug {
1062 eprintln!("[perturb] {sentence}");
1063 }
1064 if ladder {
1065 eprintln!(
1066 "[ladder] {rung}: refused by its mirror (rung {:.0} ms: built {:.0}, bound {:.0}, mirror {:.0} ms; ladder {:.1} s)",
1067 rung_start.elapsed().as_secs_f64() * 1e3,
1068 built.as_secs_f64() * 1e3,
1069 (bounded - built).as_secs_f64() * 1e3,
1070 mirror_time.as_secs_f64() * 1e3,
1071 ladder_start.elapsed().as_secs_f64()
1072 );
1073 }
1074 refused.push(sentence);
1075 let closure = measured.and_then(|(error, bar)| {
1078 let earlier = trends[direction].refused(magnitude, error, early_exit)?;
1079 Some((earlier, error, bar))
1080 });
1081 if let Some(((earlier_offset, earlier_error), error, bar)) = closure {
1082 let closed = format!(
1083 "perturbation direction dir={dir:?} closed after offset {magnitude:.3e}: its \
1084 rungs' first-order translation errors read {earlier_error:+.3e} at offset \
1085 {earlier_offset:.3e} and {error:+.3e} at {magnitude:.3e}, one sign and \
1086 growing, so no larger offset along it comes back to the volume drift bar \
1087 {bar:.3e}"
1088 );
1089 if debug {
1090 eprintln!("[perturb] {closed}");
1091 }
1092 if ladder {
1093 eprintln!("[ladder] {closed}");
1094 }
1095 refused.push(closed);
1096 }
1097 continue;
1098 }
1099 }
1100 }
1101 }
1102 match crate::oracle::boolean_semantic_disagreement(
1106 first, second, operation, &candidate, 400,
1107 ) {
1108 Ok(report) if report.considered >= 30 && !report.is_flagged() => {
1109 if ladder {
1110 eprintln!(
1111 "[ladder] {rung}: accepted (oracle {} considered, rate {:.4}), {}",
1112 report.considered, report.disagreement_rate, rung_miss(&identity, &candidate)
1113 );
1114 }
1115 if debug {
1116 eprintln!(
1117 "[perturb] rescued {operation:?}: dir={dir:?} fraction={fraction:.1e} \
1118 magnitude={magnitude:.3e} offset={offset:?} \
1119 (oracle considered={} rate={:.4})",
1120 report.considered, report.disagreement_rate
1121 );
1122 }
1123 return Ok(candidate);
1124 }
1125 report => {
1126 if ladder {
1127 let verdict = match &report {
1128 Ok(report) => format!("oracle {} considered, rate {:.4}", report.considered, report.disagreement_rate),
1129 Err(error) => format!("oracle error {error:?}"),
1130 };
1131 eprintln!("[ladder] {rung}: refused by the oracle ({verdict}), {}", rung_miss(&identity, &candidate));
1132 }
1133 continue;
1134 }
1135 }
1136 }
1137 }
1138 if debug {
1139 eprintln!("[perturb] ladder exhausted for {operation:?}; no rung produced a clean result");
1140 }
1141 Err(refused)
1142}
1143
1144pub const PERTURBATION_FRACTIONS: [f64; 5] = [3e-5, 1e-4, 3e-4, 1e-3, 3e-3];
1147
1148#[derive(Clone, Copy, Default)]
1172pub struct MirrorTrend {
1173 last: Option<(f64, f64)>,
1175 pub closed: bool,
1176}
1177
1178impl MirrorTrend {
1179 pub fn refused(&mut self, offset: f64, error: f64, close: bool) -> Option<(f64, f64)> {
1184 let earlier = self
1185 .last
1186 .filter(|&(_, earlier)| earlier.signum() == error.signum() && error.abs() >= earlier.abs())
1187 .filter(|_| close);
1188 self.last = Some((offset, error));
1189 self.closed |= earlier.is_some();
1190 earlier
1191 }
1192
1193 pub fn cleared(&mut self) {
1195 self.last = None;
1196 }
1197}
1198
1199pub fn below_tolerance_refusal_enabled() -> bool {
1214 crate::switch!("BREP_BELOW_TOLERANCE_REFUSAL", true)
1215}
1216
1217pub fn below_tolerance_slivers_enabled() -> bool {
1234 crate::switch!("BREP_BELOW_TOLERANCE_SLIVERS", true)
1235}
1236
1237const SLIVER_ANSWER_FACES: usize = 64;
1240
1241fn face_count(solid: &BrepSolid) -> usize {
1242 solid.shells.iter().map(|shell| shell.faces.len()).sum()
1243}
1244
1245fn below_tolerance_answer(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<BrepSolid> {
1247 if !below_tolerance_slivers_enabled() || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES) {
1248 return None;
1249 }
1250 if ![first, second].iter().all(|solid| closed_single_shell(solid)) {
1251 return None;
1252 }
1253 let inside = |x: &BrepSolid, y: &BrepSolid| difference_all_sliver(x, y);
1254 if matches!(operation, BooleanOperation::Subtract) {
1255 return inside(first, second).then(empty_solid);
1256 }
1257 let (first_in, second_in) = (inside(first, second), inside(second, first));
1258 let first_larger = || match (body_volume(first), body_volume(second)) {
1261 (Some(a), Some(b)) => a >= b,
1262 _ => true,
1263 };
1264 let outer_is_first = match (first_in, second_in) {
1265 (false, false) => return None,
1266 (true, false) => false,
1267 (false, true) => true,
1268 (true, true) => first_larger(),
1269 };
1270 let (outer, inner) = if outer_is_first { (first, second) } else { (second, first) };
1271 Some(match operation {
1272 BooleanOperation::Union => outer.clone(),
1273 _ => inner.clone(),
1274 })
1275}
1276
1277fn closed_single_shell(solid: &BrepSolid) -> bool {
1279 if !solid.kind.is_solid() || solid.shells.len() != 1 {
1280 return false;
1281 }
1282 let mut uses: HashMap<u64, usize> = HashMap::default();
1283 for coedge in solid.shells[0].faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1284 *uses.entry(coedge.edge_id).or_default() += 1;
1285 }
1286 !uses.is_empty() && uses.values().all(|&count| count == 2) && solid.edges.iter().all(|edge| uses.contains_key(&edge.id))
1287}
1288
1289fn difference_all_sliver(first: &BrepSolid, second: &BrepSolid) -> bool {
1300 let Some(bounds) = difference_bounds(first, second) else {
1301 return false;
1302 };
1303 let Ok(properties) = crate::solid_mass_properties(first) else {
1304 return false;
1305 };
1306 bounds.out <= BELOW_TOLERANCE_BAND
1307 && bounds.upper.is_finite()
1308 && bounds.upper <= crate::tolerance::COINCIDENCE_DISTANCE_FLOOR * properties.surface_area
1309}
1310
1311struct DifferenceBounds {
1317 lower: f64,
1318 upper: f64,
1319 out: f64,
1321}
1322
1323fn difference_bounds(first: &BrepSolid, second: &BrepSolid) -> Option<DifferenceBounds> {
1324 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1325 let (polygons_a, polygons_b) = (face_polygons(first, scale)?, face_polygons(second, scale)?);
1326 let vertices_b: Vec<Vec3> = second.vertices.iter().map(|vertex| vertex.point).collect();
1327 let vertices_a: Vec<Vec3> = first.vertices.iter().map(|vertex| vertex.point).collect();
1328 let flat = 1e-9 * scale;
1329 let mut bounds = DifferenceBounds { lower: 0.0, upper: 0.0, out: 0.0 };
1330 for polygon in &polygons_b {
1331 let (origin, normal) = polygon_plane(polygon)?;
1332 if vertices_b.iter().any(|vertex| vertex.sub(origin).dot(normal) > flat) {
1334 return None;
1335 }
1336 let out = vertices_a.iter().map(|vertex| vertex.sub(origin).dot(normal)).fold(0.0f64, f64::max);
1337 bounds.out = bounds.out.max(out);
1338 if out <= 0.0 {
1339 continue;
1340 }
1341 let part: f64 = polygons_a.iter().map(|face| clipped_cone_volume(face, origin, normal)).sum();
1342 bounds.lower = bounds.lower.max(part);
1343 bounds.upper += part;
1344 }
1345 Some(bounds)
1346}
1347
1348pub fn below_tolerance_rescale_enabled() -> bool {
1358 crate::switch!("BREP_BELOW_TOLERANCE_RESCALE", false)
1359}
1360
1361fn below_tolerance_rescaled(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions) -> Option<BrepSolid> {
1362 if !below_tolerance_rescale_enabled()
1363 || options.tolerances.is_some()
1364 || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES || !closed_single_shell(solid))
1365 {
1366 return None;
1367 }
1368 let (volume_exact, area_exact) = convex_pair_measures(first, second, operation)?;
1369 let volume_slack = 1e-9 * body_volume(first)?.max(body_volume(second)?);
1370 let area_slack = 1e-9 * area_exact.max(1.0);
1371 for factor in [100.0, 1000.0] {
1372 let scaled = |solid: &BrepSolid| crate::rescale::scale_operand(solid, factor, "boolean").ok();
1373 let (Some(a), Some(b)) = (scaled(first), scaled(second)) else {
1374 continue;
1375 };
1376 let mut scaled_options = options.clone();
1377 scaled_options.imprint.maximum_ssi_step = scaled_options.imprint.maximum_ssi_step.map(|step| step * factor);
1378 let Ok(outcome) = boolean_operation_with_diagnostics(&a, &b, operation, &scaled_options) else {
1379 continue;
1380 };
1381 let Ok(answer) = crate::rescale::scale_operand(&outcome.value, 1.0 / factor, "boolean") else {
1382 continue;
1383 };
1384 let Ok(properties) = crate::solid_mass_properties(&answer) else {
1385 continue;
1386 };
1387 if (properties.volume.abs() - volume_exact).abs() <= volume_slack
1388 && (properties.surface_area - area_exact).abs() <= area_slack
1389 && !answer.validate().iter().any(|issue| issue.severity == "error")
1390 {
1391 return Some(answer);
1392 }
1393 }
1394 None
1395}
1396
1397fn convex_pair_measures(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<(f64, f64)> {
1403 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1404 let (polygons_a, polygons_b) = (face_polygons(first, scale)?, face_polygons(second, scale)?);
1405 let (planes_a, planes_b) = (convex_planes(&polygons_a, scale)?, convex_planes(&polygons_b, scale)?);
1406 let zero = Vec3::new(0.0, 0.0, 0.0);
1407 let read = |polygons: &[Vec<Vec3>], planes: &[(Vec3, Vec3)]| {
1409 let (mut cone, mut area, mut inside_area) = (0.0, 0.0, 0.0);
1410 for polygon in polygons {
1411 area += vector_area(polygon, zero).length();
1412 let mut inside = polygon.clone();
1413 for &(origin, normal) in planes {
1414 inside = clip_polygon(&inside, origin, normal.scale(-1.0));
1415 if inside.len() < 3 {
1416 break;
1417 }
1418 }
1419 if inside.len() >= 3 {
1420 let vector = vector_area(&inside, zero);
1421 cone += inside[0].dot(vector) / 3.0;
1422 inside_area += vector.length();
1423 }
1424 }
1425 (cone, area, inside_area)
1426 };
1427 let (cone_a, area_a, inside_a) = read(&polygons_a, &planes_b);
1428 let (cone_b, area_b, inside_b) = read(&polygons_b, &planes_a);
1429 let (volume_a, volume_b) = (body_volume(first)?, body_volume(second)?);
1430 let common = cone_a + cone_b;
1431 Some(match operation {
1432 BooleanOperation::Intersect => (common, inside_a + inside_b),
1433 BooleanOperation::Union => (volume_a + volume_b - common, (area_a - inside_a) + (area_b - inside_b)),
1434 BooleanOperation::Subtract => (volume_a - common, (area_a - inside_a) + inside_b),
1435 })
1436}
1437
1438fn convex_planes(polygons: &[Vec<Vec3>], scale: f64) -> Option<Vec<(Vec3, Vec3)>> {
1441 let planes = polygons.iter().map(|polygon| polygon_plane(polygon)).collect::<Option<Vec<_>>>()?;
1442 let flat = 1e-9 * scale;
1443 let convex = planes.iter().all(|&(origin, normal)| polygons.iter().flatten().all(|vertex| vertex.sub(origin).dot(normal) <= flat));
1444 convex.then_some(planes)
1445}
1446
1447fn clip_polygon(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> Vec<Vec3> {
1450 let side = |point: Vec3| point.sub(origin).dot(normal);
1451 let mut kept = Vec::with_capacity(polygon.len() + 2);
1452 for (index, &point) in polygon.iter().enumerate() {
1453 let next = polygon[(index + 1) % polygon.len()];
1454 let (here, there) = (side(point), side(next));
1455 if here >= 0.0 {
1456 kept.push(point);
1457 }
1458 if (here >= 0.0) != (there >= 0.0) {
1459 let t = here / (here - there);
1460 kept.push(point.add(next.sub(point).scale(t)));
1461 }
1462 }
1463 kept
1464}
1465
1466fn face_polygons(solid: &BrepSolid, scale: f64) -> Option<Vec<Vec<Vec3>>> {
1470 let vertex = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1471 let mut polygons = Vec::new();
1472 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
1473 if !face.surface.is_affine().ok()? {
1474 return None;
1475 }
1476 for lp in &face.loops {
1477 let mut polygon = Vec::with_capacity(lp.coedges.len());
1478 for coedge in &lp.coedges {
1479 let edge = solid.edges.iter().find(|edge| edge.id == coedge.edge_id)?;
1480 let (start, end) = (vertex(edge.start_vertex_id)?, vertex(edge.end_vertex_id)?);
1481 let chord = end.sub(start);
1482 let length = chord.length();
1483 if edge.degenerate || length <= 1e-12 * scale {
1484 return None;
1485 }
1486 for control in &edge.curve.control_points {
1487 let offset = control.point().ok()?.sub(start);
1488 if offset.cross(chord).length() / length > 1e-9 * scale {
1489 return None;
1490 }
1491 }
1492 polygon.push(if coedge.forward { start } else { end });
1493 }
1494 polygons.push(polygon);
1495 }
1496 }
1497 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();
1499 if !(volume.abs() > 0.0) {
1500 return None;
1501 }
1502 if volume < 0.0 {
1503 for polygon in &mut polygons {
1504 polygon.reverse();
1505 }
1506 }
1507 Some(polygons)
1508}
1509
1510fn polygon_plane(polygon: &[Vec3]) -> Option<(Vec3, Vec3)> {
1512 let origin = *polygon.first()?;
1513 Some((origin, vector_area(polygon, origin).normalized().ok()?))
1514}
1515
1516fn vector_area(polygon: &[Vec3], origin: Vec3) -> Vec3 {
1517 let mut area = Vec3::new(0.0, 0.0, 0.0);
1518 for (index, point) in polygon.iter().enumerate() {
1519 let next = polygon[(index + 1) % polygon.len()];
1520 area = area.add(point.sub(origin).cross(next.sub(origin)));
1521 }
1522 area.scale(0.5)
1523}
1524
1525fn clipped_cone_volume(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> f64 {
1531 let clipped: Vec<Vec3> = if normal.length() == 0.0 { polygon.to_vec() } else { clip_polygon(polygon, origin, normal) };
1532 if clipped.len() < 3 {
1533 return 0.0;
1534 }
1535 clipped[0].sub(origin).dot(vector_area(&clipped, origin)) / 3.0
1536}
1537
1538const BELOW_TOLERANCE_BAND: f64 = 10.0 * crate::tolerance::WELD_FLOOR;
1541
1542pub fn unresolved_merge_refusal_enabled() -> bool {
1552 crate::switch!("BREP_UNRESOLVED_MERGE_REFUSAL", false)
1553}
1554
1555pub fn sliver_shell_drop_enabled() -> bool {
1568 crate::switch!("BREP_SLIVER_SHELL_DROP", true)
1569}
1570
1571const SLIVER_SHELL_THICKNESS: f64 = 1e-12;
1575
1576pub fn sliver_shell_fast_on() -> bool {
1591 crate::switch!("BREP_SLIVER_SHELL_FAST", true)
1592}
1593
1594fn sliver_shell_fast_check_on() -> bool {
1595 crate::switch!("BREP_SLIVER_SHELL_FAST_CHECK", false)
1596}
1597
1598thread_local! {
1599 static SLIVER_FAST_CHECK: std::cell::Cell<(u64, u64, u64)> = const { std::cell::Cell::new((0, 0, 0)) };
1600}
1601
1602pub fn sliver_shell_fast_check_take() -> (u64, u64, u64) {
1605 SLIVER_FAST_CHECK.with(|cell| cell.replace((0, 0, 0)))
1606}
1607
1608fn sliver_fast_record(compared: u64, differed: u64, kept: u64) {
1609 SLIVER_FAST_CHECK.with(|cell| {
1610 let (a, b, c) = cell.get();
1611 cell.set((a + compared, b + differed, c + kept));
1612 });
1613}
1614
1615fn face_area_upper_bound(surface: &crate::NurbsSurface) -> Option<f64> {
1623 let net = &surface.control_points;
1624 let rows = net.len();
1625 let columns = net.first()?.len();
1626 if rows < 2 || columns < 2 || net.iter().any(|row| row.len() != columns) {
1627 return None;
1628 }
1629 let (p, q) = (surface.degree_u, surface.degree_v);
1630 let (us, vs) = (&surface.knots_u, &surface.knots_v);
1631 if us.len() != rows + p + 1 || vs.len() != columns + q + 1 {
1632 return None;
1633 }
1634 let mut w_min = f64::INFINITY;
1635 let mut w_max = 0.0f64;
1636 let mut point_max = 0.0f64;
1637 for c in net.iter().flatten() {
1638 if !(c.w > 0.0) {
1639 return None;
1640 }
1641 w_min = w_min.min(c.w);
1642 w_max = w_max.max(c.w);
1643 point_max = point_max.max((c.x * c.x + c.y * c.y + c.z * c.z).sqrt());
1644 }
1645 let hodograph = |along_u: bool| -> Option<(f64, f64)> {
1647 let (count, degree, knots) = if along_u { (rows, p, us) } else { (columns, q, vs) };
1648 let (mut dp, mut dw) = (0.0f64, 0.0f64);
1649 for i in 0..count - 1 {
1650 let span = knots[i + degree + 1] - knots[i + 1];
1651 if !(span > 0.0) {
1652 continue;
1653 }
1654 let scale = degree as f64 / span;
1655 let others = if along_u { columns } else { rows };
1656 for j in 0..others {
1657 let (a, b) = if along_u { (net[i][j], net[i + 1][j]) } else { (net[j][i], net[j][i + 1]) };
1658 let (x, y, z) = (b.x - a.x, b.y - a.y, b.z - a.z);
1659 dp = dp.max(scale * (x * x + y * y + z * z).sqrt());
1660 dw = dw.max(scale * (b.w - a.w).abs());
1661 }
1662 }
1663 Some((dp, dw))
1664 };
1665 let (pu, wu) = hodograph(true)?;
1666 let (pv, wv) = hodograph(false)?;
1667 let su = (pu * w_max + point_max * wu) / (w_min * w_min);
1668 let sv = (pv * w_max + point_max * wv) / (w_min * w_min);
1669 let extent_u = us[us.len() - 1] - us[0];
1670 let extent_v = vs[vs.len() - 1] - vs[0];
1671 let bound = su * sv * extent_u * extent_v;
1672 bound.is_finite().then_some(bound)
1673}
1674
1675pub fn trimmed_face_area_upper_bound(face: &crate::topology::FaceRecord) -> Option<f64> {
1683 let s = &face.surface;
1684 let (u0, u1) = (*s.knots_u.first()?, *s.knots_u.last()?);
1685 let (v0, v1) = (*s.knots_v.first()?, *s.knots_v.last()?);
1686 let (du, dv) = (1e-12 * (u1 - u0).abs(), 1e-12 * (v1 - v0).abs());
1688 if !(du > 0.0 && dv > 0.0) {
1689 return None;
1690 }
1691 for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
1692 for c in &coedge.pcurve.control_points {
1693 if !(c.w > 0.0) {
1694 return None;
1695 }
1696 let (u, v) = (c.x / c.w, c.y / c.w);
1697 if !(u >= u0 - du && u <= u1 + du && v >= v0 - dv && v <= v1 + dv) {
1698 return None;
1699 }
1700 }
1701 }
1702 face_area_upper_bound(s).map(|bound| 2.0 * bound)
1703}
1704
1705fn drop_sliver_shells(solid: &mut BrepSolid) -> usize {
1708 if !sliver_shell_drop_enabled() || !solid.kind.is_solid() || solid.shells.len() < 2 {
1709 return 0;
1710 }
1711 let floor = SLIVER_SHELL_THICKNESS * crate::solid_tolerance::solid_scale(solid).max(1.0);
1712 let degenerate: std::collections::HashSet<u64> = solid.edges.iter().filter(|edge| edge.degenerate).map(|edge| edge.id).collect();
1713 let mut drop = vec![false; solid.shells.len()];
1714 for (index, shell) in solid.shells.iter().enumerate() {
1715 if shell.faces.is_empty() {
1716 continue;
1717 }
1718 let mut uses: HashMap<u64, usize> = HashMap::default();
1720 for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1721 if !degenerate.contains(&coedge.edge_id) {
1722 *uses.entry(coedge.edge_id).or_default() += 1;
1723 }
1724 }
1725 if uses.is_empty() || uses.values().any(|&count| count != 2) {
1726 continue;
1727 }
1728 let alone = BrepSolid { shells: vec![shell.clone()], mass_properties_cache: Default::default(), ..solid.clone() };
1729 let (fast, check) = (sliver_shell_fast_on(), sliver_shell_fast_check_on());
1730 let kept_fast = (fast || check)
1731 && shell
1732 .faces
1733 .iter()
1734 .map(trimmed_face_area_upper_bound)
1735 .sum::<Option<f64>>()
1736 .map(|area| floor * area)
1737 .filter(|bar| bar.is_finite() && *bar > 0.0)
1738 .and_then(|bar| crate::solid_signed_volume_for_sign(&alone, bar).ok().map(|volume| volume > bar))
1739 .unwrap_or(false);
1740 if kept_fast && !check {
1741 sliver_fast_record(0, 0, 1);
1742 continue;
1743 }
1744 let Ok(mass) = crate::solid_mass_properties(&alone) else {
1745 continue;
1746 };
1747 let thickness = mass.volume.abs() / mass.surface_area.max(f64::MIN_POSITIVE);
1748 if env_read!("BREP_DEBUG_SLIVER_SHELL").is_some() {
1749 eprintln!(
1750 "sliver-shell: shell {index} of {}: volume {:.6e} area {:.6e} thickness {thickness:.3e}",
1751 solid.shells.len(),
1752 mass.volume,
1753 mass.surface_area
1754 );
1755 }
1756 drop[index] = thickness < floor;
1757 if check {
1758 sliver_fast_record(1, u64::from(kept_fast && drop[index]), u64::from(kept_fast));
1759 }
1760 }
1761 let dropped = drop.iter().filter(|&&d| d).count();
1762 if dropped == 0 || dropped == solid.shells.len() {
1763 return 0;
1764 }
1765 let mut index = 0;
1766 solid.shells.retain(|_| {
1767 let keep = !drop[index];
1768 index += 1;
1769 keep
1770 });
1771 let used_edges: std::collections::HashSet<u64> = solid
1772 .shells
1773 .iter()
1774 .flat_map(|shell| &shell.faces)
1775 .flat_map(|face| &face.loops)
1776 .flat_map(|lp| &lp.coedges)
1777 .map(|coedge| coedge.edge_id)
1778 .collect();
1779 solid.edges.retain(|edge| used_edges.contains(&edge.id));
1780 let used_vertices: std::collections::HashSet<u64> =
1781 solid.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
1782 solid.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
1783 solid.mass_properties_cache = Default::default();
1784 refresh_derived_genus(solid);
1786 dropped
1787}
1788
1789fn unresolved_merge_refusal(first: &BrepSolid, second: &BrepSolid) -> Option<KernelRefusal> {
1790 let (lower, upper) = (crate::tolerance::COINCIDENCE_DISTANCE_FLOOR, crate::tolerance::WELD_FLOOR);
1791 let (face_a, face_b, separation) = planar_faces_apart_within(first, second, lower, upper)?;
1792 Some(KernelRefusal::unsupported(
1793 KernelStage::Intersect,
1794 "below_modelling_tolerance",
1795 format!(
1796 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1797 another, {separation:.3e} apart at most over their shared extent: farther than a coincidence \
1798 ({lower:.0e}) and closer than the kernel resolves ({upper:.0e}), so the step between them would be \
1799 welded away"
1800 ),
1801 ))
1802}
1803
1804fn below_tolerance_refusal(first: &BrepSolid, second: &BrepSolid, error: Option<&KernelRefusal>) -> Option<KernelRefusal> {
1805 let (face_a, face_b, separation) = near_coincident_planar_faces(first, second)?;
1806 let message = format!(
1807 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1808 another, {separation:.3e} apart at most over their shared extent: the slivers between them are below the \
1809 modelling tolerance ({BELOW_TOLERANCE_BAND:.0e}), so the kernel cannot resolve them{}",
1810 error.map(|error| format!(" (the exact arrangement said: {})", error.message.chars().take(160).collect::<String>())).unwrap_or_default()
1811 );
1812 Some(KernelRefusal::unsupported(KernelStage::Intersect, "below_modelling_tolerance", message))
1813}
1814
1815fn near_coincident_planar_faces(first: &BrepSolid, second: &BrepSolid) -> Option<(u64, u64, f64)> {
1819 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1820 planar_faces_apart_within(first, second, 1e-9 * scale, BELOW_TOLERANCE_BAND)
1821}
1822
1823fn planar_faces_apart_within(first: &BrepSolid, second: &BrepSolid, lower: f64, upper: f64) -> Option<(u64, u64, f64)> {
1827 struct Planar {
1828 id: u64,
1829 origin: Vec3,
1830 normal: Vec3,
1831 corners: Vec<Vec3>,
1832 bounds: crate::spatial::Aabb,
1833 }
1834 let read = |solid: &BrepSolid| -> Vec<Planar> {
1835 let at = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1836 solid
1837 .shells
1838 .iter()
1839 .flat_map(|shell| &shell.faces)
1840 .filter_map(|face| {
1841 if !face.surface.is_affine().ok()? {
1842 return None;
1843 }
1844 let origin = face.surface.control_points[0][0].point().ok()?;
1845 let a = face.surface.control_points[1][0].point().ok()?.sub(origin);
1846 let b = face.surface.control_points[0][1].point().ok()?.sub(origin);
1847 let normal = a.cross(b).normalized().ok()?;
1848 let corners: Vec<Vec3> = face
1849 .loops
1850 .iter()
1851 .flat_map(|lp| &lp.coedges)
1852 .filter_map(|coedge| solid.edges.iter().find(|edge| edge.id == coedge.edge_id))
1853 .flat_map(|edge| [at(edge.start_vertex_id), at(edge.end_vertex_id)])
1854 .flatten()
1855 .collect();
1856 if corners.is_empty() {
1857 return None;
1858 }
1859 let bounds = crate::spatial::Aabb::from_points(corners.clone());
1860 Some(Planar { id: face.id, origin, normal, corners, bounds })
1861 })
1862 .collect()
1863 };
1864 let (faces_a, faces_b) = (read(first), read(second));
1865 for a in &faces_a {
1866 for b in &faces_b {
1867 if a.normal.cross(b.normal).length() > 1e-3 {
1868 continue;
1869 }
1870 if !a.bounds.intersects(b.bounds, upper) {
1871 continue;
1872 }
1873 let separation = a
1874 .corners
1875 .iter()
1876 .map(|corner| corner.sub(b.origin).dot(b.normal).abs())
1877 .chain(b.corners.iter().map(|corner| corner.sub(a.origin).dot(a.normal).abs()))
1878 .fold(0.0f64, f64::max);
1879 if separation > lower && separation <= upper {
1880 return Some((a.id, b.id, separation));
1881 }
1882 }
1883 }
1884 None
1885}
1886
1887pub fn one_use_edges(solid: &BrepSolid) -> usize {
1888 let mut uses: HashMap<u64, usize> = HashMap::default();
1889 for coedge in solid
1890 .shells
1891 .iter()
1892 .flat_map(|shell| &shell.faces)
1893 .flat_map(|face| &face.loops)
1894 .flat_map(|loop_record| &loop_record.coedges)
1895 {
1896 *uses.entry(coedge.edge_id).or_default() += 1;
1897 }
1898 solid
1899 .edges
1900 .iter()
1901 .filter(|edge| !edge.degenerate && uses.get(&edge.id) == Some(&1))
1902 .count()
1903}
1904
1905fn body_volume(solid: &BrepSolid) -> Option<f64> {
1907 if solid.shells.is_empty() {
1908 return Some(0.0);
1909 }
1910 solid_signed_volume(solid).ok().map(f64::abs)
1911}
1912
1913struct InclusionExclusion {
1916 formula: &'static str,
1919 reading: &'static str,
1921 read: f64,
1923 expected: f64,
1925}
1926
1927fn inclusion_exclusion_volume(
1938 first: &BrepSolid,
1939 second: &BrepSolid,
1940 operation: BooleanOperation,
1941 options: &BooleanOptions,
1942 va: Option<f64>,
1943 vb: Option<f64>,
1944 own_first: bool,
1945) -> Option<InclusionExclusion> {
1946 use BooleanOperation::{Intersect, Subtract, Union};
1947 let (va, vb) = (va?, vb?);
1948 let own = match operation {
1949 Intersect => (Intersect, false, "first ∩ second"),
1950 Union => (Union, false, "first ∪ second"),
1951 Subtract => (Subtract, false, "first − second"),
1952 };
1953 let readings = [
1954 (Intersect, false, "first ∩ second"),
1955 (Intersect, true, "second ∩ first"),
1956 (Union, false, "first ∪ second"),
1957 (Union, true, "second ∪ first"),
1958 (Subtract, false, "first − second"),
1959 (Subtract, true, "second − first"),
1960 ];
1961 let own_reading = own_first.then_some(own);
1962 let leading = usize::from(own_first);
1963 for (index, (other, swapped, reading)) in own_reading.into_iter().chain(readings).enumerate() {
1964 if index >= leading && !swapped && std::mem::discriminant(&other) == std::mem::discriminant(&operation) {
1965 continue;
1966 }
1967 let (x, y) = if swapped { (second, first) } else { (first, second) };
1968 let Some(read) = boolean_operation_with_diagnostics(x, y, other, options)
1969 .ok()
1970 .and_then(|outcome| body_volume(&outcome.value))
1971 else {
1972 continue;
1973 };
1974 let intersection = match (other, swapped) {
1975 (Intersect, _) => read,
1976 (Union, _) => va + vb - read,
1977 (Subtract, false) => va - read,
1978 (Subtract, true) => vb - read,
1979 };
1980 let (formula, expected) = match operation {
1981 Intersect => ("V(first ∩ second)", intersection),
1982 Union => ("V(first) + V(second) − V(first ∩ second)", va + vb - intersection),
1983 Subtract => ("V(first) − V(first ∩ second)", va - intersection),
1984 };
1985 return Some(InclusionExclusion { formula, reading, read, expected });
1986 }
1987 None
1988}
1989
1990fn planar_operand_off_its_plane(
1999 first: &BrepSolid,
2000 second: &BrepSolid,
2001 options: &BooleanOptions,
2002) -> Option<(u8, u64, f64, f64)> {
2003 let policy = options
2004 .tolerances
2005 .clone()
2006 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
2007 let weld = crate::tolerance::assembler_weld(policy.model);
2008 let mut worst: Option<(u8, u64, f64)> = None;
2009 for (operand, solid) in [(0u8, first), (1u8, second)] {
2010 let vertex_point = |id: u64| solid.vertices.iter().find(|v| v.id == id).map(|v| v.point);
2011 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2012 let Some(crate::AnalyticSurface::Plane {
2013 origin,
2014 u_dir,
2015 v_dir,
2016 ..
2017 }) = face.surface.analytic()
2018 else {
2019 continue;
2020 };
2021 let [loop_record] = face.loops.as_slice() else {
2022 continue;
2023 };
2024 let Ok(normal) = u_dir.cross(*v_dir).normalized() else {
2025 continue;
2026 };
2027 let mut off_plane = 0.0f64;
2028 let mut straight = true;
2029 for coedge in &loop_record.coedges {
2030 let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else {
2031 straight = false;
2032 break;
2033 };
2034 let (Some(start), Some(end)) =
2035 (vertex_point(edge.start_vertex_id), vertex_point(edge.end_vertex_id))
2036 else {
2037 straight = false;
2038 break;
2039 };
2040 let chord = end.sub(start);
2041 let length = chord.length();
2042 if edge.degenerate || length <= weld {
2043 straight = false;
2044 break;
2045 }
2046 let direction = chord.scale(1.0 / length);
2047 for fraction in [0.25, 0.5, 0.75] {
2048 let Ok(point) = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction) else {
2049 straight = false;
2050 break;
2051 };
2052 let delta = point.sub(start);
2053 let along = delta.dot(direction);
2054 if delta.sub(direction.scale(along)).length() > weld
2055 || along < -weld
2056 || along > length + weld
2057 {
2058 straight = false;
2059 break;
2060 }
2061 }
2062 if !straight {
2063 break;
2064 }
2065 off_plane = off_plane.max(start.sub(*origin).dot(normal).abs());
2066 }
2067 if straight && off_plane > weld && worst.is_none_or(|(_, _, gap)| off_plane > gap) {
2068 worst = Some((operand, face.id, off_plane));
2069 }
2070 }
2071 }
2072 worst.map(|(operand, face_id, gap)| (operand, face_id, gap, weld))
2073}
2074
2075fn volume_within_csg_bounds(operation: BooleanOperation, va: f64, vb: f64, vr: f64) -> bool {
2078 let slack = 1e-2 * (va + vb).max(1.0);
2079 match operation {
2080 BooleanOperation::Union => vr >= va.max(vb) - slack && vr <= va + vb + slack,
2082 BooleanOperation::Subtract => vr <= va + slack && vr >= -slack,
2084 BooleanOperation::Intersect => vr <= va.min(vb) + slack && vr >= -slack,
2086 }
2087}
2088
2089fn reverse_fragment(fragment: &mut FaceFragmentRecord) -> Result<(), KernelRefusal> {
2116 fragment.same_sense = !fragment.same_sense;
2117 for loop_record in &mut fragment.loops {
2118 loop_record.coedges.reverse();
2119 for coedge in &mut loop_record.coedges {
2120 coedge.forward = !coedge.forward;
2121 coedge.pcurve = coedge.pcurve.reversed().or_refuse(KernelStage::Validate, "reversed")?;
2122 }
2123 }
2124 Ok(())
2125}
2126
2127fn build_nary_imprint(
2134 operands: &[BrepSolid],
2135 options: &ImprintOptions,
2136) -> Result<ImprintResultRecord, KernelRefusal> {
2137 let mut section_evidence = false;
2138 let mut vertices: Vec<ImprintVertex> = Vec::new();
2139 let mut pieces: Vec<ImprintPieceRecord> = Vec::new();
2140 let mut by_face: HashMap<(u8, u64), Vec<u64>> = HashMap::default();
2141 let mut edge_splits: HashMap<(u8, u64), Vec<f64>> = HashMap::default();
2142 let mut next_vertex_id: u64 = 1;
2143 let mut next_piece_id: u64 = 1;
2144
2145 for i in 0..operands.len() {
2146 for j in (i + 1)..operands.len() {
2147 let pair = build_imprints(&operands[i], &operands[j], options)?;
2148 let remap = |operand: u8| -> u8 {
2149 if operand == 0 {
2150 i as u8
2151 } else {
2152 j as u8
2153 }
2154 };
2155
2156 section_evidence = section_evidence || pair.section_evidence;
2157 let mut vertex_map: HashMap<u64, u64> = HashMap::default();
2158 for vertex in &pair.vertices {
2159 let global = next_vertex_id;
2160 next_vertex_id += 1;
2161 vertex_map.insert(vertex.id, global);
2162 vertices.push(ImprintVertex {
2163 id: global,
2164 point: vertex.point,
2165 });
2166 }
2167
2168 let mut piece_map: HashMap<u64, u64> = HashMap::default();
2169 for piece in &pair.pieces {
2170 let global = next_piece_id;
2171 next_piece_id += 1;
2172 piece_map.insert(piece.id, global);
2173 let mut mapped = piece.clone();
2174 mapped.id = global;
2175 mapped.start_vertex_id = *vertex_map
2176 .get(&piece.start_vertex_id)
2177 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2178 mapped.end_vertex_id = *vertex_map
2179 .get(&piece.end_vertex_id)
2180 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2181 for pcurve in &mut mapped.pcurves {
2182 pcurve.operand = remap(pcurve.operand);
2183 }
2184 mapped.support_faces = [
2185 FaceKey {
2186 operand: remap(piece.support_faces[0].operand),
2187 face_id: piece.support_faces[0].face_id,
2188 },
2189 FaceKey {
2190 operand: remap(piece.support_faces[1].operand),
2191 face_id: piece.support_faces[1].face_id,
2192 },
2193 ];
2194 pieces.push(mapped);
2195 }
2196
2197 for entry in &pair.by_face {
2198 let list = by_face
2199 .entry((remap(entry.operand), entry.face_id))
2200 .or_default();
2201 for piece_id in &entry.piece_ids {
2202 let global = *piece_map.get(piece_id).ok_or_else(|| {
2203 KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: by_face references unknown piece")
2204 })?;
2205 list.push(global);
2206 }
2207 }
2208
2209 for split in &pair.edge_splits {
2210 edge_splits
2211 .entry((remap(split.operand), split.edge_id))
2212 .or_default()
2213 .extend(split.parameters.iter().copied());
2214 }
2215 }
2216 }
2217
2218 Ok(ImprintResultRecord {
2219 faces_in_unproved_pairs: None,
2220 vertices,
2221 pieces,
2222 tangent_nodes: Vec::new(),
2223 barrier_edges: Vec::new(),
2224 section_evidence,
2225 cosurface_pairs: Vec::new(),
2226 tangent_sections: Vec::new(),
2227 by_face: by_face
2228 .into_iter()
2229 .map(|((operand, face_id), piece_ids)| FaceImprints {
2230 operand,
2231 face_id,
2232 piece_ids,
2233 })
2234 .collect(),
2235 edge_splits: edge_splits
2236 .into_iter()
2237 .map(|((operand, edge_id), parameters)| EdgeSplitRecord {
2238 operand,
2239 edge_id,
2240 parameters,
2241 })
2242 .collect(),
2243 })
2244}
2245
2246pub fn boolean_operation_nary(
2257 operands: &[BrepSolid],
2258 operation: BooleanOperation,
2259) -> Result<BrepSolid, KernelRefusal> {
2260 boolean_operation_nary_with_options(operands, operation, &BooleanOptions::default())
2261}
2262
2263pub fn boolean_operation_nary_with_options(
2269 operands: &[BrepSolid],
2270 operation: BooleanOperation,
2271 options: &BooleanOptions,
2272) -> Result<BrepSolid, KernelRefusal> {
2273 if operands.len() > 1 {
2274 if let Some(scaled) = WorkingScale::of(&operands.iter().collect::<Vec<_>>(), options)? {
2275 return boolean_operation_nary_with_options(&scaled.solids, operation, &scaled.options)
2276 .map_err(|error| scaled.refusal(error))
2277 .and_then(|solid| scaled.back(&solid));
2278 }
2279 }
2280 if operands.is_empty() {
2281 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: no operands provided"));
2282 }
2283 if operands.len() == 1 {
2284 return Ok(operands[0].clone());
2285 }
2286 if operands.len() > 255 {
2287 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: at most 255 operands supported"));
2288 }
2289 if let Some(aligned) = ball_align::align_balls_nary(operands, operation, options.tolerance) {
2292 return boolean_operation_nary_with_options(&aligned, operation, options);
2293 }
2294 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
2295
2296 let mut policy = KernelTolerances::for_solid(&operands[0], options.tolerance);
2300 for operand in &operands[1..] {
2301 let candidate = KernelTolerances::for_solid(operand, options.tolerance);
2302 if candidate.sew_search > policy.sew_search {
2303 policy = candidate;
2304 }
2305 }
2306 policy.check().or_input(KernelStage::Collect, "tolerances")?;
2307 let tolerance = policy.model;
2308
2309 let mut healed = operands.to_vec();
2312 for operand in &mut healed {
2313 crate::heal::heal_operands(operand, &policy)?;
2314 crate::heal::refit_inherited_trims_reused(operand, &policy)?;
2317 normalize_operand_band_seams(operand)?;
2320 }
2321
2322 let mut imprint_options = options.imprint.clone();
2324 imprint_options.tolerance = tolerance;
2325 let imprint = build_nary_imprint(&healed, &imprint_options)?;
2326
2327 let mut split = Vec::with_capacity(healed.len());
2329 for (index, operand) in healed.iter().enumerate() {
2330 split.push(apply_edge_splits(operand, index as u8, &imprint)?);
2331 }
2332 let mut fragments = Vec::with_capacity(split.len());
2333 for (index, solid) in split.iter().enumerate() {
2334 fragments.push(fragment_solid(solid, index as u8, &imprint)?);
2335 }
2336
2337 let selected = select_fragments_nary(&fragments, &healed, operation, tolerance, debug)?;
2339
2340 let solids: HashMap<u8, &BrepSolid> = split
2342 .iter()
2343 .enumerate()
2344 .map(|(index, solid)| (index as u8, solid))
2345 .collect();
2346 let solid = assemble_fragments(selected, &solids, &imprint, tolerance)?;
2347 let solid = if options.merge_coplanar_faces
2348 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
2349 {
2350 let merged = merge_same_surface_faces_excluding(
2351 &solid,
2352 tolerance,
2353 &options.keep_unmerged_name_substrs,
2354 )?;
2355 let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
2356 rejoin::rejoin_unless_referenced(merged, options, tolerance)
2357 } else {
2358 solid
2359 };
2360 let validation = solid.validate_detailed(&policy);
2361 if !validation.issues.is_empty() {
2362 return Err(KernelRefusal::new(
2363 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
2364 KernelStage::Validate,
2365 format!(
2366 "boolean_operation_nary: invalid result: {:?}",
2367 validation.issues
2368 )));
2369 }
2370 if debug {
2371 if let Ok(report) =
2372 crate::oracle::boolean_semantic_disagreement_nary(&healed, operation, &solid, 300)
2373 {
2374 if report.is_flagged() {
2375 eprintln!(
2376 "[oracle] n-ary semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
2377 report.disagreement_rate,
2378 report.disagreements.len(),
2379 report.considered,
2380 report.sample_disagreement()
2381 );
2382 }
2383 }
2384 }
2385 Ok(solid)
2386}
2387
2388fn attribute_to_tangent_node(error: KernelRefusal, nodes: &[Vec3]) -> KernelRefusal {
2419 let Some(node) = nodes.first() else {
2420 return error;
2421 };
2422 if !error.class.perturbation_eligible()
2423 || matches!(error.class, RefusalClass::TangentNodeSingularity)
2424 {
2425 return error;
2426 }
2427 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
2428 eprintln!(
2429 "boolean: tear downstream of the tangent node at ({:.6},{:.6},{:.6}) attributed to it; the stage read: {}",
2430 node.x, node.y, node.z, error.message
2431 );
2432 }
2433 KernelRefusal::new(
2434 RefusalClass::TangentNodeSingularity,
2435 error.stage,
2436 format!(
2437 "boolean: unsupported singular/tangent-node surface intersection \
2438 at the tangent node at ({:.6},{:.6},{:.6}): the section through it did not \
2439 assemble into a closed shell",
2440 node.x, node.y, node.z
2441 ),
2442 )
2443}
2444
2445pub fn attribute_to_tangent_section(
2467 error: KernelRefusal,
2468 sections: &[crate::imprint::TangentSectionRecord],
2469 origins: &[FaceKey],
2470) -> KernelRefusal {
2471 if sections.is_empty()
2472 || !error.class.perturbation_eligible()
2473 || matches!(error.class, RefusalClass::TangentNodeSingularity)
2474 {
2475 return error;
2476 }
2477 let named = refusal_result_faces(&error.message)
2478 .into_iter()
2479 .filter_map(|id| origins.get(id.checked_sub(1)? as usize).copied())
2480 .collect::<Vec<FaceKey>>();
2481 let involving = |fallback: bool| {
2485 sections.iter().find(|section| {
2486 section.grazing.is_empty() != fallback && named.iter().any(|face| section.faces.contains(face))
2487 })
2488 };
2489 let Some(section) = involving(false).or_else(|| involving(true)) else {
2490 return error;
2491 };
2492 let at = |point: Vec3| {
2495 let shown = |value: f64| if value.abs() < 5e-7 { 0.0 } else { value };
2496 format!("({:.6},{:.6},{:.6})", shown(point.x), shown(point.y), shown(point.z))
2497 };
2498 let pierces = (!section.grazing.is_empty()).then(|| {
2504 let shown = section.grazing.len().min(4);
2505 let mut listed = section.grazing[..shown]
2506 .iter()
2507 .map(|(point, tangency)| format!("{} at |tan·n| = {tangency:.4}", at(*point)))
2508 .collect::<Vec<_>>()
2509 .join(", ");
2510 if section.grazing.len() > shown {
2511 listed.push_str(&format!(" and {} more", section.grazing.len() - shown));
2512 }
2513 listed
2514 });
2515 let pierce_only = section.pierce_only();
2516 let shape = if let (true, Some(pierces)) = (pierce_only, pierces.as_deref()) {
2517 format!(
2518 "cross at a grazing angle: a trim edge pierces the other carrier inside both \
2519 trims at {pierces}, below the marcher's start gate, and no transverse section was \
2520 marched between the pierces — a near-tangent crossing born on a tangent contact \
2521 (a third-order singularity) the imprint does not build yet"
2522 )
2523 } else if section.planar {
2524 format!(
2525 "touch along a tangent curve from {} to {} (length {:.6}, {} stations{}) which the \
2526 imprint does not build yet",
2527 at(section.start),
2528 at(section.end),
2529 section.length,
2530 section.stations,
2531 if section.closed { ", closed" } else { "" }
2532 )
2533 } else {
2534 format!(
2535 "touch along a curve through {} with neither carrier planar, a curved/curved \
2536 tangent contact the lane does not trace yet",
2537 at(section.start)
2538 )
2539 };
2540 let shape = match (pierce_only, pierces) {
2541 (false, Some(pierces)) => format!(
2542 "{shape}; a trim edge also pierces the other carrier inside both trims at {pierces}, \
2543 below the marcher's start gate, with no transverse section marched"
2544 ),
2545 _ => shape,
2546 };
2547 let involved = named
2548 .iter()
2549 .filter(|face| section.faces.contains(face))
2550 .map(|face| format!("{}/{}", face.operand, face.face_id))
2551 .collect::<Vec<_>>()
2552 .join(", ");
2553 KernelRefusal::new(
2554 RefusalClass::TangentNodeSingularity,
2555 error.stage,
2556 format!(
2557 "boolean: unsupported tangent-curve surface intersection between faces {}/{} and {}/{}: \
2558 the carriers {shape}; the refusal names face(s) {involved} the contact involves; {}",
2559 section.first.operand, section.first.face_id, section.second.operand, section.second.face_id,
2560 error.message
2561 ),
2562 )
2563}
2564
2565pub fn refusal_result_faces(message: &str) -> Vec<u64> {
2570 let mut ids = Vec::new();
2571 let digits_after = |text: &str| -> Option<u64> {
2572 let end = text.find(|c: char| !c.is_ascii_digit()).unwrap_or(text.len());
2573 text[..end].parse().ok()
2574 };
2575 for (index, _) in message.match_indices("face ") {
2576 if let Some(id) = digits_after(&message[index + "face ".len()..]) {
2577 ids.push(id);
2578 }
2579 }
2580 if let Some(start) = message.find("on faces [") {
2581 let rest = &message[start + "on faces [".len()..];
2582 let list = &rest[..rest.find(']').unwrap_or(rest.len())];
2583 for entry in list.split(", ") {
2584 let entry = entry.trim_start();
2585 if let Some(id) = digits_after(entry) {
2586 if entry[id.to_string().len()..].starts_with(" '") {
2587 ids.push(id);
2588 }
2589 }
2590 }
2591 }
2592 ids.sort_unstable();
2593 ids.dedup();
2594 ids
2595}
2596
2597pub fn boolean_operation_with_diagnostics(
2598 first: &BrepSolid,
2599 second: &BrepSolid,
2600 operation: BooleanOperation,
2601 options: &BooleanOptions,
2602) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2603 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2604 let mut outcome = boolean_operation_with_diagnostics(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
2605 .map_err(|error| scaled.refusal(error))?;
2606 outcome.value = scaled.back(&outcome.value)?;
2607 outcome.diagnostics.count_n("working_scale.fired", 1);
2608 outcome.diagnostics.measure_max("working_scale.factor", scaled.factor);
2609 return Ok(outcome);
2610 }
2611 let _account = profile::Scope::new("boolean.other");
2612 let (first_aligned, second_aligned) = ball_align::align_balls(first, second, operation, options.tolerance);
2615 let (first, second) = (first_aligned.as_ref(), second_aligned.as_ref());
2616 let closed_inputs = matches!(std::env::var("BREP_CLOSED_OPERAND_INPUT").as_deref(), Err(_) | Ok("1") | Ok("on"));
2617 if let (true, Some(later)) = (reseat::seam_reseat_enabled(), &options.seam_reseat_later_references) {
2618 let started = Instant::now();
2619 let (first, second) = reseat::reseat_tangent_seams(first, second, later, options.tolerance);
2620 profile_stage("seam_prepare_ms", started.elapsed().as_secs_f64() * 1000.0);
2621 return boolean_operation_with_diagnostics_impl(&first, &second, operation, options, closed_inputs).map(without_sliver_shells);
2622 }
2623 boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells)
2624}
2625
2626fn without_sliver_shells(mut outcome: KernelOutcome<BrepSolid>) -> KernelOutcome<BrepSolid> {
2628 let dropped = drop_sliver_shells(&mut outcome.value);
2629 if dropped > 0 {
2630 outcome.diagnostics.count_n("sliver_shell.dropped", dropped as u64);
2631 }
2632 outcome
2633}
2634
2635pub fn boolean_operation_with_diagnostics_impl(
2636 first: &BrepSolid,
2637 second: &BrepSolid,
2638 operation: BooleanOperation,
2639 options: &BooleanOptions,
2640 closed_inputs: bool,
2641) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2642 let _coedge_memo = crate::topology::CoedgeMemoScope::open(true);
2645 if matches!(operation, BooleanOperation::Intersect)
2648 && [first, second].iter().any(|body| body.kind == crate::BodyKind::Sheet)
2649 && match std::env::var("BREP_SHEET_TRIM").as_deref() {
2650 Ok("1") => true,
2651 Ok("0") => false,
2652 _ => options.sheet_trim,
2653 }
2654 {
2655 return sheet::trim(first, second, options);
2656 }
2657 if matches!(operation, BooleanOperation::Union | BooleanOperation::Subtract) {
2666 if let Some(operand) = [first, second]
2667 .iter()
2668 .position(|solid| solid.kind == crate::BodyKind::Sheet)
2669 {
2670 return Err(KernelRefusal::input(
2671 KernelStage::Collect,
2672 "sheet_operand",
2673 format!(
2674 "boolean: operand {operand} is a Sheet, which encloses no solid; union and \
2675 subtract of a sheet are refused; Intersect trims a Sheet by a Solid"
2676 ),
2677 ));
2678 }
2679 }
2680 let mut outcome = boolean_operation_with_diagnostics_core(first, second, operation, options)?;
2686 let closure_started = closed_inputs.then(Instant::now);
2687 if closed_inputs {
2688 for (operand, solid) in [first, second].into_iter().enumerate() {
2689 let open = one_use_edges(solid);
2690 if open > 0 {
2691 return Err(KernelRefusal::input(KernelStage::Collect, "operand_closure", format!(
2692 "boolean: operand {operand} is not a closed shell: {open} of its edges bound only one face, so its inside is undefined"
2693 )));
2694 }
2695 }
2696 }
2697 if let Some(started) = closure_started {
2698 let ms = started.elapsed().as_secs_f64() * 1000.0;
2699 profile_stage("operand_closure_ms", ms);
2700 outcome.diagnostics.measure_max("timing.operand_closure_ms", ms);
2701 }
2702 Ok(outcome)
2703}
2704
2705fn boolean_operation_with_diagnostics_core(
2706 first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions,
2707) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2708
2709 if let Some(offset) = crate::recentre::control_offset_at_entry() {
2712 return boolean_operation_with_diagnostics_at_offset(first, second, operation, options, offset);
2713 }
2714 let mut bounds = operand_bounds(first);
2717 bounds.include(operand_bounds(second));
2718 if let Some(offset) = crate::recentre::guard_offset(bounds) {
2719 crate::recentre::profile_fired("boolean", offset, bounds);
2720 let mut outcome = boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Guard)?;
2721 outcome.diagnostics.count_n("recentre.fired", 1);
2722 outcome.diagnostics.measure_max("recentre.distance", offset.length());
2723 return Ok(outcome);
2724 }
2725 let mut tangent_nodes = Vec::new();
2726 let (mut outcome, soundness_candidates) =
2727 boolean_pipeline(first, second, operation, options, &mut tangent_nodes)
2728 .map_err(|error| attribute_to_tangent_node(error, &tangent_nodes))?;
2729 let stage_started = Instant::now();
2742 let accepted = match &soundness_candidates {
2743 Some(candidates) => crate::accept_sound_against_scoped(&[first, second], outcome.value, "boolean", candidates),
2746 None => crate::accept_sound_against(&[first, second], outcome.value, "boolean"),
2747 };
2748 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2749 profile_stage("soundness_ms", stage_ms);
2750 outcome.diagnostics.measure_max("timing.soundness_ms", stage_ms);
2751 outcome.value = accepted?;
2752 Ok(outcome)
2753}
2754
2755pub fn boolean_operation_with_diagnostics_at_offset(
2759 first: &BrepSolid,
2760 second: &BrepSolid,
2761 operation: BooleanOperation,
2762 options: &BooleanOptions,
2763 offset: Vec3,
2764) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2765 boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Control)
2766}
2767
2768fn boolean_translated(
2770 first: &BrepSolid,
2771 second: &BrepSolid,
2772 operation: BooleanOperation,
2773 options: &BooleanOptions,
2774 offset: Vec3,
2775 kind: crate::recentre::EntryKind,
2776) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2777 let _entry = crate::recentre::TranslatedEntry::open(kind);
2778 let translate = |solid: &BrepSolid, offset: Vec3| {
2779 crate::recentre::translate_solid(solid, offset).map_err(|message| {
2780 KernelRefusal::internal(
2781 KernelStage::Collect,
2782 "translation_control",
2783 format!("boolean: the translation control could not move an operand: {message}"),
2784 )
2785 })
2786 };
2787 let moved_first = translate(first, offset)?;
2788 let moved_second = translate(second, offset)?;
2789 let outcome = boolean_operation_with_diagnostics(&moved_first, &moved_second, operation, options)?;
2790 let value = translate(&outcome.value, offset.scale(-1.0))?;
2791 Ok(KernelOutcome { value, diagnostics: outcome.diagnostics })
2792}
2793
2794fn profile_stage(code: &str, ms: f64) {
2798 let row = match code {
2799 "heal_ms" => Some("boolean.operand_prepare"),
2800 "imprint_ms" => Some("boolean.imprint"),
2801 "edge_split_ms" => Some("boolean.edge_split"),
2802 "fragment_ms" => Some("boolean.fragment"),
2803 "select_ms" => Some("boolean.select"),
2804 "assemble_ms" => Some("boolean.assemble"),
2805 "face_merge_ms" => Some("boolean.face_merge"),
2806 "soundness_ms" => Some("boolean.soundness"),
2807 "operand_closure_ms" => Some("boolean.operand_closure"),
2808 "seam_prepare_ms" => Some("boolean.seam_prepare"),
2809 "final_validate_ms" => Some("boolean.final_validate"),
2810 _ => None,
2811 };
2812 if let Some(row) = row { profile::record(row, ms); }
2813 if crate::profile::profile_enabled() {
2814 profile_line!("boolean.{code}={ms:.2}");
2815 }
2816}
2817
2818struct BooleanStageDump {
2823 directory: std::path::PathBuf,
2824 serial: usize,
2825}
2826
2827impl BooleanStageDump {
2828 fn open() -> Option<Self> {
2829 static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2830 let directory = std::env::var("BREP_BOOLEAN_DUMP").ok().filter(|value| !value.is_empty())?;
2831 let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2832 Some(Self { directory: directory.into(), serial })
2833 }
2834
2835 fn write<T: Serialize + ?Sized>(&self, stage: &str, value: &T) {
2836 let path = self.directory.join(format!("{:03}-{stage}.json", self.serial));
2837 match serde_json::to_string(value) {
2838 Ok(text) => {
2839 if let Err(error) = std::fs::write(&path, text) {
2840 eprintln!("BREP_BOOLEAN_DUMP {}: {error}", path.display());
2841 }
2842 }
2843 Err(error) => eprintln!("BREP_BOOLEAN_DUMP {stage}: {error}"),
2844 }
2845 }
2846}
2847
2848pub fn boolean_policy(
2850 first: &BrepSolid,
2851 second: &BrepSolid,
2852 options: &BooleanOptions,
2853) -> Result<KernelTolerances, KernelRefusal> {
2854 let policy = options
2855 .tolerances
2856 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
2857 policy.check().or_input(KernelStage::Collect, "tolerances")?;
2858 Ok(policy)
2859}
2860
2861fn prepared_operands(
2864 first: &BrepSolid,
2865 second: &BrepSolid,
2866 policy: &KernelTolerances,
2867) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
2868 let stage_started = Instant::now();
2877 let mut first_owned = first.clone();
2878 let mut second_owned = second.clone();
2879 crate::heal::heal_operands(&mut first_owned, policy)?;
2880 crate::heal::heal_operands(&mut second_owned, policy)?;
2881 profile_stage("heal.operands_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
2882 let refit_started = Instant::now();
2886 crate::heal::refit_inherited_trims_reused(&mut first_owned, policy)?;
2887 crate::heal::refit_inherited_trims_reused(&mut second_owned, policy)?;
2888 profile_stage("heal.refit_ms", refit_started.elapsed().as_secs_f64() * 1_000.0);
2889 if crate::profile::profile_enabled() {
2890 let (hits, misses) = crate::reading_memo::counts();
2891 profile_line!("boolean.reading_memo hits={hits} misses={misses}");
2892 let (served, stored) = crate::heal::refit_memo_counts_served_stored();
2893 profile_line!("boolean.refit_memo served={served} stored={stored}");
2894 }
2895 profile_stage("heal_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
2896 normalize_operand_band_seams(&mut first_owned)?;
2901 normalize_operand_band_seams(&mut second_owned)?;
2902 Ok((first_owned, second_owned))
2903}
2904
2905fn boolean_imprint_options(options: &BooleanOptions, tolerance: f64) -> ImprintOptions {
2906 let mut imprint_options = options.imprint.clone();
2907 imprint_options.tolerance = tolerance;
2908 imprint_options
2909}
2910
2911pub fn boolean_split_operands(
2921 first: &BrepSolid,
2922 second: &BrepSolid,
2923 options: &BooleanOptions,
2924) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
2925 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2926 let (split_first, split_second) = boolean_split_operands(&scaled.solids[0], &scaled.solids[1], &scaled.options)
2927 .map_err(|error| scaled.refusal(error))?;
2928 return Ok((scaled.back(&split_first)?, scaled.back(&split_second)?));
2929 }
2930 let policy = boolean_policy(first, second, options)?;
2931 let (first, second) = prepared_operands(first, second, &policy)?;
2932 let imprint = build_imprints(&first, &second, &boolean_imprint_options(options, policy.model))?;
2933 let (split_first, _) = apply_edge_splits_with_map(&first, 0, &imprint)?;
2934 let (split_second, _) = apply_edge_splits_with_map(&second, 1, &imprint)?;
2935 Ok((split_first, split_second))
2936}
2937
2938fn operand_bounds(solid: &BrepSolid) -> crate::Aabb {
2942 let mut bounds = crate::Aabb::from_points(solid.vertices.iter().map(|vertex| vertex.point));
2943 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2944 match crate::Aabb::from_surface_controls(&face.surface) {
2945 Ok(face_bounds) => bounds.include(face_bounds),
2946 Err(_) => {
2947 return crate::Aabb {
2948 minimum: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
2949 maximum: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
2950 }
2951 }
2952 }
2953 }
2954 bounds
2955}
2956
2957fn line_or_point_contact(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
2963 apart_axes(bounds) >= 2 && plain_hull_solid(first) && plain_hull_solid(second)
2964}
2965
2966fn boxes_share_no_interior(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
2969 apart_axes(bounds) >= 1 && plain_hull_solid(first) && plain_hull_solid(second)
2970}
2971
2972fn apart_axes([a, b]: [crate::Aabb; 2]) -> usize {
2974 let apart = |a_min: f64, a_max: f64, b_min: f64, b_max: f64| a_max <= b_min || b_max <= a_min;
2975 [
2976 apart(a.minimum.x, a.maximum.x, b.minimum.x, b.maximum.x),
2977 apart(a.minimum.y, a.maximum.y, b.minimum.y, b.maximum.y),
2978 apart(a.minimum.z, a.maximum.z, b.minimum.z, b.maximum.z),
2979 ]
2980 .into_iter()
2981 .filter(|&apart| apart)
2982 .count()
2983}
2984
2985fn plain_hull_solid(solid: &BrepSolid) -> bool {
2987 solid.kind == crate::BodyKind::Solid
2988 && solid.cells.is_empty()
2989 && solid.shells.iter().flat_map(|shell| &shell.faces).all(|face| {
2990 face.surface.control_points.iter().flatten().all(|control| control.w > 0.0 && control.w.is_finite())
2991 })
2992}
2993
2994fn scope_proved_apart_on() -> bool {
2998 switch!(live "BREP_SCOPE_PROVED_APART", true)
2999}
3000
3001fn soundness_candidates(
3016 solid: &BrepSolid,
3017 scope: &AssemblyScope,
3018 bounds: [crate::Aabb; 2],
3019 band: f64,
3020 unproved: Option<&HashSet<crate::imprint::FaceKey>>,
3021) -> HashSet<u64> {
3022 let mut candidates = HashSet::default();
3023 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
3024 if scope.examined.contains(&face.id) {
3025 candidates.insert(face.id);
3026 continue;
3027 }
3028 let Some(&operand) = scope.operand_of.get(&face.id) else {
3029 candidates.insert(face.id);
3030 continue;
3031 };
3032 let other = bounds[usize::from(operand == 0)];
3033 match crate::Aabb::from_surface_controls(&face.surface) {
3034 Ok(face_bounds) if !face_bounds.intersects(other, band) => {}
3035 _ => {
3036 let proved_clear = unproved.is_some_and(|unproved| {
3037 scope.source_of.get(&face.id).is_some_and(|key| !unproved.contains(key))
3038 });
3039 if !proved_clear {
3040 candidates.insert(face.id);
3041 }
3042 }
3043 }
3044 }
3045 candidates
3046}
3047
3048
3049fn touching_empty_enabled() -> bool {
3057 switch!("BREP_TOUCHING_EMPTY", true)
3058}
3059
3060thread_local! {
3061 static TOUCHING_PROOF: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3064}
3065
3066fn hair_deep_overlap(first: &BrepSolid, second: &BrepSolid, tolerance: f64) -> bool {
3073 use crate::AnalyticSurface as A;
3074 fn faces(solid: &BrepSolid) -> Vec<(&crate::AnalyticSurface, crate::spatial::Aabb, &crate::NurbsSurface)> {
3075 solid
3076 .shells
3077 .iter()
3078 .flat_map(|shell| &shell.faces)
3079 .filter_map(|face| Some((face.surface.analytic()?, crate::Aabb::from_surface_controls(&face.surface).ok()?, &face.surface)))
3080 .collect()
3081 }
3082 let along = |surface: &crate::NurbsSurface, axis: Vec3| {
3084 surface.control_points.iter().flatten().filter_map(|control| control.point().ok()).fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), point| {
3085 let at = point.dot(axis);
3086 (low.min(at), high.max(at))
3087 })
3088 };
3089 let crossing = |distance: f64, ra: f64, rb: f64| {
3090 let outer = ra + rb - distance;
3091 let nested = distance - (ra - rb).abs();
3092 outer > tolerance && nested > tolerance
3093 };
3094 let boxes_overlap = |a: &crate::spatial::Aabb, b: &crate::spatial::Aabb| {
3095 (a.maximum.x.min(b.maximum.x) - a.minimum.x.max(b.minimum.x)) > tolerance
3096 && (a.maximum.y.min(b.maximum.y) - a.minimum.y.max(b.minimum.y)) > tolerance
3097 && (a.maximum.z.min(b.maximum.z) - a.minimum.z.max(b.minimum.z)) > tolerance
3098 };
3099 for (a, box_a, surface_a) in faces(first) {
3100 for (b, box_b, surface_b) in faces(second) {
3101 if !boxes_overlap(&box_a, &box_b) {
3102 continue;
3103 }
3104 match (a, b) {
3105 (A::RuledRevolution { frame: fa, rho0: a0, rho1: a1, .. }, A::RuledRevolution { frame: fb, rho0: b0, rho1: b1, .. })
3106 if (a0 - a1).abs() <= tolerance && (b0 - b1).abs() <= tolerance =>
3107 {
3108 let offset = fb.origin.sub(fa.origin);
3109 let normal = fa.axis.cross(fb.axis);
3110 if normal.length() <= 1e-12 {
3113 let (low_a, high_a) = along(surface_a, fa.axis);
3114 let (low_b, high_b) = along(surface_b, fa.axis);
3115 if high_a.min(high_b) - low_a.max(low_b) <= tolerance {
3116 continue;
3117 }
3118 }
3119 let apart = if normal.length() <= 1e-12 {
3120 offset.sub(fa.axis.scale(offset.dot(fa.axis))).length()
3121 } else {
3122 offset.dot(normal).abs() / normal.length()
3123 };
3124 if crossing(apart, a0.abs(), b0.abs()) {
3125 return true;
3126 }
3127 }
3128 (A::Sphere { frame: fa, radius: ra }, A::Sphere { frame: fb, radius: rb }) => {
3129 if crossing(fb.origin.sub(fa.origin).length(), *ra, *rb) {
3130 return true;
3131 }
3132 }
3133 _ => {}
3134 }
3135 }
3136 }
3137 false
3138}
3139
3140fn empty_solid() -> BrepSolid {
3142 BrepSolid {
3143 mass_properties_cache: Default::default(),
3144 cells: Default::default(),
3145 id: 0,
3146 vertices: Vec::new(),
3147 edges: Vec::new(),
3148 shells: Vec::new(),
3149 genus: 0,
3150 kind: crate::BodyKind::Solid,
3151 }
3152}
3153
3154fn concatenate_disjoint(first: &BrepSolid, second: &BrepSolid) -> BrepSolid {
3160 let mut vertices = Vec::new();
3161 let mut edges = Vec::new();
3162 let mut shells = Vec::new();
3163 let mut used_face_names = HashSet::<String>::default();
3164 let (mut next_face_id, mut next_loop_id, mut next_coedge_id) = (1u64, 1u64, 1u64);
3165 for operand in [first, second] {
3166 let vertex_base = vertices.len() as u64;
3167 let edge_base = edges.len() as u64;
3168 let mut vertex_ids: HashMap<u64, u64> = HashMap::default();
3169 for (index, vertex) in operand.vertices.iter().enumerate() {
3170 let id = vertex_base + index as u64 + 1;
3171 vertex_ids.insert(vertex.id, id);
3172 vertices.push(VertexRecord { id, point: vertex.point });
3173 }
3174 let mut edge_ids: HashMap<u64, u64> = HashMap::default();
3175 for (index, edge) in operand.edges.iter().enumerate() {
3176 let id = edge_base + index as u64 + 1;
3177 edge_ids.insert(edge.id, id);
3178 edges.push(EdgeRecord {
3179 id,
3180 curve: edge.curve.clone(),
3181 t0: edge.t0,
3182 t1: edge.t1,
3183 start_vertex_id: vertex_ids.get(&edge.start_vertex_id).copied().unwrap_or(edge.start_vertex_id),
3184 end_vertex_id: vertex_ids.get(&edge.end_vertex_id).copied().unwrap_or(edge.end_vertex_id),
3185 degenerate: edge.degenerate,
3186 name: edge.name.clone(),
3187 });
3188 }
3189 for shell in &operand.shells {
3190 let mut faces = Vec::with_capacity(shell.faces.len());
3191 for face in &shell.faces {
3192 let loops = face
3193 .loops
3194 .iter()
3195 .map(|loop_record| {
3196 let coedges = loop_record
3197 .coedges
3198 .iter()
3199 .map(|coedge| {
3200 let id = next_coedge_id;
3201 next_coedge_id += 1;
3202 CoedgeRecord {
3203 id,
3204 edge_id: edge_ids.get(&coedge.edge_id).copied().unwrap_or(coedge.edge_id),
3205 forward: coedge.forward,
3206 pcurve: coedge.pcurve.clone(),
3207 }
3208 })
3209 .collect();
3210 let id = next_loop_id;
3211 next_loop_id += 1;
3212 LoopRecord { id, coedges }
3213 })
3214 .collect();
3215 let name = face.name.clone().map(|base| {
3216 if used_face_names.insert(base.clone()) {
3217 base
3218 } else {
3219 let mut suffix = 1usize;
3220 loop {
3221 let candidate = format!("{base}_{suffix}");
3222 if used_face_names.insert(candidate.clone()) {
3223 break candidate;
3224 }
3225 suffix += 1;
3226 }
3227 }
3228 });
3229 faces.push(FaceRecord {
3230 id: next_face_id,
3231 surface: face.surface.clone(),
3232 same_sense: face.same_sense,
3233 loops,
3234 name,
3235 });
3236 next_face_id += 1;
3237 }
3238 shells.push(ShellRecord { id: shells.len() as u64 + 1, faces });
3239 }
3240 }
3241 BrepSolid {
3242 mass_properties_cache: Default::default(),
3243 cells: Default::default(),
3244 id: 1,
3245 vertices,
3246 edges,
3247 shells,
3248 genus: first.genus + second.genus,
3249 kind: crate::BodyKind::Solid,
3250 }
3251}
3252
3253fn boolean_pipeline(
3256 first: &BrepSolid,
3257 second: &BrepSolid,
3258 operation: BooleanOperation,
3259 options: &BooleanOptions,
3260 tangent_nodes: &mut Vec<Vec3>,
3261) -> Result<(KernelOutcome<BrepSolid>, Option<HashSet<u64>>), KernelRefusal> {
3262 let _work = crate::imprint::work_profile::Scope::open("boolean");
3263 let replaced_operands = operand_state::replace_operands(first, second, operation, options);
3264 let (first, second) = match &replaced_operands {
3265 Some((first, second)) => (first, second),
3266 None => (first, second),
3267 };
3268 let policy = boolean_policy(first, second, options)?;
3269 let tolerance = policy.model;
3270 let bounds = [operand_bounds(first), operand_bounds(second)];
3285 let disjoint = disjoint_fast_path(options) && !bounds[0].intersects(bounds[1], policy.sew_search);
3286 let contact = !disjoint
3287 && contact_fast_path(options)
3288 && options.seam_reseat_later_references.is_some()
3289 && line_or_point_contact(first, second, bounds);
3290 let contact = contact
3295 || (!disjoint
3296 && matches!(operation, BooleanOperation::Intersect)
3297 && contact_fast_path(options)
3298 && boxes_share_no_interior(first, second, bounds));
3299 if disjoint || contact {
3300 let operation_started = Instant::now();
3301 let mut diagnostics = KernelDiagnostics::default();
3302 diagnostics.count_n(
3303 "collect.faces",
3304 first.shells.iter().chain(&second.shells).map(|shell| shell.faces.len() as u64).sum(),
3305 );
3306 diagnostics.count(if contact { "boolean.contact_fast_path" } else { "boolean.disjoint_fast_path" });
3307 diagnostics.measure_max("tolerance.model", policy.model);
3308 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3309 let value = match operation {
3310 BooleanOperation::Union => concatenate_disjoint(first, second),
3311 BooleanOperation::Subtract => first.clone(),
3312 BooleanOperation::Intersect => {
3313 diagnostics.event(
3314 DiagnosticSeverity::Info,
3315 KernelStage::Select,
3316 "boolean.empty_result",
3317 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
3318 );
3319 empty_solid()
3320 }
3321 };
3322 let stage_ms = operation_started.elapsed().as_secs_f64() * 1_000.0;
3323 profile_stage("disjoint_fast_path_ms", stage_ms);
3324 diagnostics.measure_max("timing.total_ms", stage_ms);
3325 return Ok((KernelOutcome { value, diagnostics }, Some(HashSet::default())));
3326 }
3327 let heal_started = Instant::now();
3328 let (first_owned, second_owned) = prepared_operands(first, second, &policy)?;
3329 let heal_ms = heal_started.elapsed().as_secs_f64() * 1_000.0;
3330 let first = &first_owned;
3331 let second = &second_owned;
3332
3333 let mut diagnostics = KernelDiagnostics::default();
3334 diagnostics.measure_max("timing.heal_ms", heal_ms);
3337 let fit_scope = crate::PcurveFitScope::open();
3342 let polyline_scope = crate::PolylineFitScope::open();
3346 let operation_started = Instant::now();
3347 diagnostics.count_n(
3348 "collect.faces",
3349 first
3350 .shells
3351 .iter()
3352 .chain(&second.shells)
3353 .map(|shell| shell.faces.len() as u64)
3354 .sum(),
3355 );
3356 diagnostics.measure_max("tolerance.model", policy.model);
3357 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3358
3359 let imprint_options = boolean_imprint_options(options, tolerance);
3360 let stage_started = Instant::now();
3361 let imprint = build_imprints(first, second, &imprint_options)?;
3362 tangent_nodes.extend_from_slice(&imprint.tangent_nodes);
3363 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
3364 for piece in &imprint.pieces {
3365 let start = piece.curve.evaluate(piece.t0);
3366 let end = piece.curve.evaluate(piece.t1);
3367 eprintln!(
3368 "piece {} supports={:?} t=[{:.6},{:.6}] start={:?} end={:?}",
3369 piece.id, piece.support_faces, piece.t0, piece.t1, start, end
3370 );
3371 }
3372 for entry in &imprint.by_face {
3373 eprintln!(
3374 "by_face operand={} face={} pieces={:?}",
3375 entry.operand, entry.face_id, entry.piece_ids
3376 );
3377 }
3378 for split in &imprint.edge_splits {
3379 eprintln!(
3380 "edge_split operand={} edge={} params={:?}",
3381 split.operand, split.edge_id, split.parameters
3382 );
3383 }
3384 }
3385 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3386 profile_stage("imprint_ms", stage_ms);
3387 diagnostics.measure_max("timing.imprint_ms", stage_ms);
3388 diagnostics.count_n("intersect.pieces", imprint.pieces.len() as u64);
3389 diagnostics.count_n("intersect.vertices", imprint.vertices.len() as u64);
3390 diagnostics.count_n("intersect.edge_splits", imprint.edge_splits.len() as u64);
3391 let (march_swap_rescues, clip_swap_rescues) = crate::imprint::take_rescue_firings();
3392 diagnostics.count_n("intersect.march_swap_rescue", march_swap_rescues);
3393 diagnostics.count_n("intersect.clip_swap_rescue", clip_swap_rescues);
3394 let touch = TouchCensus::build([first, second], &imprint);
3395 touch.report(&mut diagnostics);
3396 let stage_started = Instant::now();
3397 let (split_first, split_map_first) = apply_edge_splits_with_map(first, 0, &imprint)?;
3398 let (split_second, split_map_second) = apply_edge_splits_with_map(second, 1, &imprint)?;
3399 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3400 profile_stage("edge_split_ms", stage_ms);
3401 diagnostics.measure_max("timing.edge_split_ms", stage_ms);
3402 let stage_started = Instant::now();
3403 crate::classification::classify_profile_begin();
3404 let fragments_a = crate::fragment::fragment_solid_against(&split_first, 0, &imprint, crate::fragment::bounded_carriers(second).then_some((bounds[1], policy.sew_search)))?;
3405 let fragments_b = crate::fragment::fragment_solid_against(&split_second, 1, &imprint, crate::fragment::bounded_carriers(first).then_some((bounds[0], policy.sew_search)))?;
3406 crate::classification::classify_profile_report("fragment");
3407 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3408 profile_stage("fragment_ms", stage_ms);
3409 diagnostics.measure_max("timing.fragment_ms", stage_ms);
3410 diagnostics.count_n(
3411 "fragment.candidates",
3412 (fragments_a.len() + fragments_b.len()) as u64,
3413 );
3414 touch.report_fragments(&[&fragments_a, &fragments_b], &mut diagnostics);
3415 let a_surface_samples: Vec<Vec3> = fragments_a
3420 .iter()
3421 .flat_map(|fragment| {
3422 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
3423 })
3424 .collect();
3425 let b_surface_samples: Vec<Vec3> = fragments_b
3426 .iter()
3427 .flat_map(|fragment| {
3428 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
3429 })
3430 .collect();
3431 let stage_started = Instant::now();
3432 let mut barrier_edges: HashSet<(u8, u64)> = imprint
3433 .pieces
3434 .iter()
3435 .filter_map(|piece| piece.shared_edge.map(|(operand, edge_id, _)| (operand, edge_id)))
3436 .collect();
3437 barrier_edges.extend(imprint.barrier_edges.iter().copied());
3438 for (operand, split_map) in [(0u8, &split_map_first), (1u8, &split_map_second)] {
3444 let minted: Vec<(u8, u64)> = barrier_edges
3445 .iter()
3446 .filter(|(barrier_operand, _)| *barrier_operand == operand)
3447 .filter_map(|(_, edge_id)| split_map.get(edge_id))
3448 .flat_map(|sub_ids| sub_ids.iter().map(|sub_id| (operand, *sub_id)))
3449 .collect();
3450 barrier_edges.extend(minted);
3451 }
3452 crate::classification::classify_profile_begin();
3453 let coincident = coincident_pairs(
3454 &fragments_a,
3455 &fragments_b,
3456 first,
3457 second,
3458 &imprint.cosurface_pairs,
3459 tolerance,
3460 )?;
3461 let sector_mode = sector::sector_mode(options);
3462 let mut select_census = sector::SelectCensus::default();
3463 let mut selected = select_fragments(
3464 fragments_a,
3465 fragments_b,
3466 first,
3467 second,
3468 operation,
3469 tolerance,
3470 &barrier_edges,
3471 &imprint,
3472 &coincident,
3473 sector_mode,
3474 &mut select_census,
3475 )?;
3476 let resewn = resew_coincident_rims(
3477 &mut selected,
3478 [&split_first, &split_second],
3479 [first, second],
3480 &imprint.cosurface_pairs,
3481 operation,
3482 tolerance,
3483 )?;
3484 diagnostics.count_n("select.coincident_pairs", coincident.len() as u64);
3485 diagnostics.count_n("select.rims_resewn", resewn as u64);
3486 crate::classification::classify_profile_report("select");
3487 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3488 profile_stage("select_ms", stage_ms);
3489 diagnostics.measure_max("timing.select_ms", stage_ms);
3490 diagnostics.count_n("select.fragments", selected.len() as u64);
3491 diagnostics.count_n("select.sector_eligible", select_census.eligible);
3493 diagnostics.count_n("select.sector_primary", select_census.sector_primary);
3494 diagnostics.count_n("select.sector_fallback", select_census.sector_fallback);
3495 diagnostics.count_n("select.sector_disagree", select_census.disagree);
3496 diagnostics.count_n("select.ray_casts", select_census.ray_casts);
3497 diagnostics.count_n("select.on_votes", select_census.on_votes);
3498 diagnostics.count_n("select.overturns", select_census.overturns);
3499 if sector_mode != sector::SectorMode::Off || std::env::var_os("BREP_SECTOR_CENSUS").is_some() {
3500 sector::sector_census_line(|| {
3501 format!(
3502 "selection mode={sector_mode:?} select_ms={stage_ms:.3} selected={} eligible={} primary={} fallback={} disagree={} ray_casts={} on_votes={} overturns={}",
3503 selected.len(),
3504 select_census.eligible,
3505 select_census.sector_primary,
3506 select_census.sector_fallback,
3507 select_census.disagree,
3508 select_census.ray_casts,
3509 select_census.on_votes,
3510 select_census.overturns
3511 )
3512 });
3513 }
3514 if selected.is_empty()
3536 && !imprint.section_evidence
3537 && std::env::var("BREP_EMPTY_BOOLEAN").as_deref() != Ok("0")
3538 {
3539 let strictly_inside = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
3540 for &sample in samples {
3541 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::In {
3542 return Ok(true);
3543 }
3544 }
3545 Ok(false)
3546 };
3547 let outside_witness = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
3548 for &sample in samples {
3549 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::Out {
3550 return Ok(true);
3551 }
3552 }
3553 Ok(false)
3554 };
3555 let legitimate = match operation {
3556 BooleanOperation::Intersect => {
3557 !strictly_inside(&a_surface_samples, second)?
3558 && !strictly_inside(&b_surface_samples, first)?
3559 }
3560 BooleanOperation::Subtract => !outside_witness(&a_surface_samples, second)?,
3561 BooleanOperation::Union => false,
3562 };
3563 if legitimate {
3564 diagnostics.event(
3565 DiagnosticSeverity::Info,
3566 KernelStage::Select,
3567 "boolean.empty_result",
3568 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
3569 );
3570 fit_scope.close().report_into(&mut diagnostics);
3571 polyline_scope.close().report_into(&mut diagnostics);
3572 diagnostics.measure_max(
3573 "timing.total_ms",
3574 operation_started.elapsed().as_secs_f64() * 1_000.0,
3575 );
3576 return Ok((
3577 KernelOutcome {
3578 value: empty_solid(),
3579 diagnostics,
3580 },
3581 None,
3582 ));
3583 }
3584 }
3585 if selected.is_empty()
3594 && imprint.section_evidence
3595 && !matches!(operation, BooleanOperation::Union)
3596 && touching_empty_enabled()
3597 && !TOUCHING_PROOF.with(std::cell::Cell::get)
3598 {
3599 let strict = |samples: &[Vec3], other: &BrepSolid, class: PointClass| -> Result<bool, KernelRefusal> {
3600 for &sample in samples {
3601 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == class {
3602 return Ok(true);
3603 }
3604 }
3605 Ok(false)
3606 };
3607 let witnessed = match operation {
3608 BooleanOperation::Intersect => {
3609 !strict(&a_surface_samples, second, PointClass::In)? && !strict(&b_surface_samples, first, PointClass::In)?
3610 }
3611 BooleanOperation::Subtract => !strict(&a_surface_samples, second, PointClass::Out)?,
3612 BooleanOperation::Union => false,
3613 };
3614 let overlap_free = !hair_deep_overlap(first, second, tolerance);
3620 if witnessed && overlap_free {
3621 TOUCHING_PROOF.with(|flag| flag.set(true));
3622 let proof = inclusion_exclusion_volume(first, second, operation, options, body_volume(first), body_volume(second), false);
3623 TOUCHING_PROOF.with(|flag| flag.set(false));
3624 let volume = |solid: &BrepSolid| body_volume(solid).unwrap_or(f64::INFINITY);
3629 let band = 1e-9 * volume(first).max(volume(second));
3630 if let Some(proof) = proof.filter(|proof| proof.expected.is_finite() && proof.expected.abs() <= band) {
3631 diagnostics.event(
3632 DiagnosticSeverity::Info,
3633 KernelStage::Select,
3634 "boolean.empty_touching",
3635 format!(
3636 "{operation:?} of touching operands is empty: {} reads {:.3e} by {} (band {band:.3e})",
3637 proof.formula, proof.expected, proof.reading
3638 ),
3639 );
3640 fit_scope.close().report_into(&mut diagnostics);
3641 polyline_scope.close().report_into(&mut diagnostics);
3642 diagnostics.measure_max("timing.total_ms", operation_started.elapsed().as_secs_f64() * 1_000.0);
3643 return Ok((KernelOutcome { value: empty_solid(), diagnostics }, None));
3644 }
3645 }
3646 }
3647 let solids = [(0, &split_first), (1, &split_second)]
3648 .into_iter()
3649 .collect::<HashMap<_, _>>();
3650 let dump = BooleanStageDump::open();
3651 if let Some(dump) = &dump {
3652 dump.write("first", &split_first);
3653 dump.write("second", &split_second);
3654 dump.write("selected", &selected);
3655 }
3656 let stage_started = Instant::now();
3657 let assembled_origins: Vec<FaceKey> = if imprint.tangent_sections.is_empty() {
3661 Vec::new()
3662 } else {
3663 selected
3664 .iter()
3665 .map(|fragment| FaceKey { operand: fragment.operand, face_id: fragment.source_face_id })
3666 .collect()
3667 };
3668 let attributable: Vec<crate::imprint::TangentSectionRecord> = imprint
3675 .tangent_sections
3676 .iter()
3677 .filter(|section| imprint.tangent_nodes.is_empty() || section.grazing.is_empty())
3678 .cloned()
3679 .collect();
3680 let attribute = |error: KernelRefusal| {
3681 attribute_to_tangent_section(error, &attributable, &assembled_origins)
3682 };
3683 let cellular_result = matches!(operation, BooleanOperation::Union)
3684 && cellular::enabled(options)
3685 && cellular::complete_contact(first, second, &selected, tolerance);
3686 let (solid, scope) = if cellular_result {
3687 (assemble::assemble_cellular_fragments(selected, &solids, &imprint, tolerance)
3688 .map_err(attribute)?, None)
3689 } else if untouched_passthrough(options) {
3690 assemble_fragments_scoped(selected, &solids, &imprint, tolerance, &touch, touched_assembly(options))
3691 .map_err(attribute)?
3692 } else {
3693 (assemble_fragments(selected, &solids, &imprint, tolerance).map_err(attribute)?, None)
3694 };
3695 if let Some(scope) = &scope {
3696 diagnostics.count_n("passthrough.faces_examined", scope.examined.len() as u64);
3697 }
3698 if let Some(dump) = &dump {
3699 dump.write("assembled", &solid);
3700 }
3701 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3702 profile_stage("assemble_ms", stage_ms);
3703 diagnostics.measure_max("timing.assemble_ms", stage_ms);
3704 let stage_started = Instant::now();
3705 let declines_before = crate::face_merge::declines_served();
3706 let area_checks_before = crate::face_merge::boundary_area_checks();
3707 if std::env::var("BREP_DEBUG_PREMERGE_VALIDATE").is_ok() {
3708 let issues = solid.validate();
3709 eprintln!(
3710 "pre-merge validation: {} issue(s){}",
3711 issues.len(),
3712 issues
3713 .first()
3714 .map(|issue| format!(" — first: {}", issue.message))
3715 .unwrap_or_default()
3716 );
3717 }
3718 let solid = if solid.kind != crate::BodyKind::Cellular && options.merge_coplanar_faces
3719 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
3720 {
3721 let merged = match &scope {
3722 Some(scope) => merge_same_surface_faces_scoped(
3726 &solid,
3727 tolerance,
3728 &options.keep_unmerged_name_substrs,
3729 &scope.examined,
3730 )?,
3731 None => merge_same_surface_faces_excluding(
3732 &solid,
3733 tolerance,
3734 &options.keep_unmerged_name_substrs,
3735 )?,
3736 };
3737 let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
3742 rejoin::rejoin_unless_referenced(merged, options, tolerance)
3743 } else {
3744 solid
3745 };
3746 if let Some(dump) = &dump {
3747 dump.write("merged", &solid);
3748 }
3749 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3750 profile_stage("face_merge_ms", stage_ms);
3751 if crate::profile::profile_enabled() {
3752 profile_line!("boolean.merge_declines served={}", crate::face_merge::declines_served() - declines_before);
3753 let area_checks = crate::face_merge::boundary_area_checks();
3754 if area_checks != area_checks_before {
3755 profile_line!("boolean.merge_area_checks boundary={} integrated={}", area_checks.0 - area_checks_before.0, area_checks.1 - area_checks_before.1);
3756 }
3757 }
3758 diagnostics.measure_max("timing.face_merge_ms", stage_ms);
3759 let validation_started = Instant::now();
3760 let validation = solid.validate_detailed_scoped(&policy, scope.as_ref().map(|scope| &scope.examined));
3761 profile_stage("final_validate_ms", validation_started.elapsed().as_secs_f64() * 1000.0);
3762 diagnostics.count_n("validate.issues", validation.issues.len() as u64);
3763 diagnostics.count_n(
3764 "validate.wire_warnings",
3765 validation.wire_warnings.len() as u64,
3766 );
3767 diagnostics.measure_max("validate.max_pcurve_error", validation.max_pcurve_error);
3768 for warning in &validation.wire_warnings {
3769 diagnostics.event(
3770 DiagnosticSeverity::Warning,
3771 KernelStage::Validate,
3772 "validate.uv_wire",
3773 warning.message.clone(),
3774 );
3775 }
3776 for issue in &validation.issues {
3777 diagnostics.event(
3778 DiagnosticSeverity::Error,
3779 KernelStage::Validate,
3780 "validate.brep",
3781 issue.message.clone(),
3782 );
3783 }
3784 fit_scope.close().report_into(&mut diagnostics);
3785 polyline_scope.close().report_into(&mut diagnostics);
3786 diagnostics.measure_max(
3787 "timing.total_ms",
3788 operation_started.elapsed().as_secs_f64() * 1_000.0,
3789 );
3790 if !validation.issues.is_empty() {
3791 return Err(KernelRefusal::new(
3792 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
3793 KernelStage::Validate,
3794 format!(
3795 "boolean_operation: invalid result: {:?}",
3796 validation.issues
3797 )));
3798 }
3799 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
3805 if let Ok(report) =
3806 crate::oracle::boolean_semantic_disagreement(first, second, operation, &solid, 200)
3807 {
3808 if report.is_flagged() {
3809 eprintln!(
3810 "[oracle] semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
3811 report.disagreement_rate,
3812 report.disagreements.len(),
3813 report.considered,
3814 report.sample_disagreement()
3815 );
3816 }
3817 }
3818 let fusable_band = crate::tolerance::assembler_weld(policy.model);
3819 let fusables = crate::oracle::boolean_residual_fusables(&solid, fusable_band);
3820 if !fusables.is_empty() {
3821 eprintln!(
3822 "[oracle] {} residual fusable(s) after weld; sample {:?}",
3823 fusables.len(),
3824 fusables.first()
3825 );
3826 }
3827 }
3828 let candidates = scope.as_ref().map(|scope| {
3829 let unproved = (scope_proved_apart_on() && plain_hull_solid(first) && plain_hull_solid(second))
3830 .then(|| imprint.faces_in_unproved_pairs.as_ref())
3831 .flatten()
3832 .map(|faces| faces.iter().copied().collect::<HashSet<_>>());
3833 let candidates = soundness_candidates(
3834 &solid,
3835 scope,
3836 [operand_bounds(first), operand_bounds(second)],
3837 policy.sew_search,
3838 unproved.as_ref(),
3839 );
3840 diagnostics.count_n("passthrough.soundness_candidates", candidates.len() as u64);
3841 crate::soundness::census::profile_operation(&solid, &[first, second], Some(&scope.touched), "boolean");
3842 candidates
3843 });
3844 Ok((
3845 KernelOutcome {
3846 value: solid,
3847 diagnostics,
3848 },
3849 candidates,
3850 ))
3851}
3852