1pub mod profile;
2pub use crate::arrangement::Vec2;
3use crate::classification::{classify_point, parameter_point_in_face, PolygonClass};
4pub use crate::fragment::{FaceFragmentRecord, FragmentEdgeSource};
5pub use crate::imprint::{
6 EdgeSplitRecord, FaceImprints, FaceKey, ImprintOptions, ImprintPieceRecord,
7 ImprintResultRecord, ImprintVertex,
8};
9use crate::tolerance::{assembler_weld, commit_weld};
10pub use crate::topology::{
11 adaptive_coedge_error, BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord,
12 ShellRecord, VertexRecord,
13};
14pub use crate::{
15 KernelRefusal, OrRefuse, RefusalClass,
16 apply_edge_splits, apply_edge_splits_with_map, build_imprints, build_pcurve_on_surface,
17 build_pcurve_on_surface_range, classify_surface_pair,
18 fragment_solid, interpolate_curve, merge_curve_continuation_edges,
19 merge_same_surface_faces_excluding, merge_same_surface_faces_scoped,
20 project_point_to_curve, project_point_to_surface, solid_signed_volume, solid_signed_volume_for_sign, AffineTransform,
21 DiagnosticSeverity, KernelDiagnostics, KernelOutcome, KernelStage, KernelTolerances, NurbsCurve,
22 PointClass, SolidClassifier, SurfacePairRelation, Vec3,
23};
24pub use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
25use serde::{Deserialize, Serialize};
26pub use web_time::Instant;
27
28thread_local! {
29 pub static CONFORMANCE_REPAIRS: std::cell::Cell<u64> =
35 const { std::cell::Cell::new(0) };
36}
37
38#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
39#[serde(rename_all = "lowercase")]
40pub enum BooleanOperation {
41 Union,
42 Intersect,
43 Subtract,
44}
45
46#[derive(Clone, Debug, Deserialize)]
47pub struct BooleanOptions {
48 #[serde(default = "default_tolerance")]
49 pub tolerance: f64,
50 #[serde(default)]
53 pub tolerances: Option<KernelTolerances>,
54 #[serde(default)]
55 pub imprint: ImprintOptions,
56 #[serde(default = "default_true")]
59 pub merge_coplanar_faces: bool,
60 #[serde(default)]
70 pub keep_unmerged_name_substrs: Vec<String>,
71 #[serde(default = "default_true")]
75 pub untouched_passthrough: bool,
76 #[serde(default = "default_true")]
80 pub disjoint_fast_path: bool,
81 #[serde(default = "default_true")]
91 pub contact_fast_path: bool,
92 #[serde(default)]
100 pub touched_assembly: bool,
101 #[serde(default = "default_true")]
109 pub sector_classification: bool,
110 #[serde(default = "default_true")]
114 pub sheet_trim: bool,
115 #[serde(default)]
119 pub keep_cells: bool,
120 #[serde(default)]
125 pub seam_reseat_later_references: Option<Vec<String>>,
126 #[serde(default)]
133 pub seam_rejoin_later_references: Option<Vec<String>>,
134}
135
136thread_local! {
137 static WITHOUT_PERTURBATION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
138}
139
140pub fn without_perturbation<T>(action: impl FnOnce() -> T) -> T {
147 struct Restore(bool);
148 impl Drop for Restore {
149 fn drop(&mut self) {
150 WITHOUT_PERTURBATION.with(|cell| cell.set(self.0));
151 }
152 }
153 let _restore = Restore(WITHOUT_PERTURBATION.with(|cell| cell.replace(true)));
154 action()
155}
156
157fn touched_assembly(options: &BooleanOptions) -> bool {
159 match std::env::var("BREP_TOUCHED_ASSEMBLY").as_deref() {
160 Ok("0") => false,
161 Ok(_) => true,
162 Err(_) => options.touched_assembly,
163 }
164}
165
166fn disjoint_fast_path(options: &BooleanOptions) -> bool {
168 match std::env::var("BREP_DISJOINT_FAST_PATH").as_deref() {
169 Ok("0") => false,
170 Ok(_) => true,
171 Err(_) => options.disjoint_fast_path,
172 }
173}
174
175fn contact_fast_path(options: &BooleanOptions) -> bool {
177 match std::env::var("BREP_CONTACT_FAST_PATH").as_deref() {
178 Ok("0") => false,
179 Ok(_) => true,
180 Err(_) => options.contact_fast_path,
181 }
182}
183
184fn untouched_passthrough(options: &BooleanOptions) -> bool {
186 match std::env::var("BREP_UNTOUCHED_PASSTHROUGH").as_deref() {
187 Ok("0") => false,
188 Ok(_) => true,
189 Err(_) => options.untouched_passthrough,
190 }
191}
192
193fn default_tolerance() -> f64 {
194 1e-7
195}
196
197fn default_true() -> bool {
198 true
199}
200
201impl Default for BooleanOptions {
202 fn default() -> Self {
203 Self {
204 tolerance: default_tolerance(),
205 tolerances: None,
206 imprint: ImprintOptions::default(),
207 merge_coplanar_faces: true,
208 keep_unmerged_name_substrs: Vec::new(),
209 untouched_passthrough: true,
210 disjoint_fast_path: true,
211 contact_fast_path: true,
212 touched_assembly: false,
213 sector_classification: true,
214 sheet_trim: true,
215 keep_cells: false,
216 seam_reseat_later_references: None,
217 seam_rejoin_later_references: None,
218 }
219 }
220}
221
222mod select;
223mod sheet;
224mod cellular;
225pub mod sector;
226pub mod assemble;
227mod operand_state;
228mod rim;
229mod coincident;
230mod touch;
231pub(crate) mod reseat;
232mod ball_align;
233mod rejoin;
234mod window_retry;
235mod isotropic_chart;
236
237pub use rim::*;
238use select::*;
239use coincident::*;
240use touch::TouchCensus;
241pub use assemble::{
242 assemble_fragments, assemble_open_fragments, commit_nearby_edge_endpoints,
243 clear_candidate_memo, edge_interior_lies_on, finalize_assembled_solid, refresh_derived_genus,
244};
245use assemble::{assemble_fragments_scoped, AssemblyScope};
246#[allow(unused_imports)]
248pub use assemble::apply_assembly_heal_chain;
249
250
251struct WorkingScale {
256 factor: f64,
257 solids: Vec<BrepSolid>,
258 options: BooleanOptions,
259}
260
261thread_local! {
262 static ORIGINAL_WORKING_SCALE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
265}
266
267impl WorkingScale {
268 fn of(operands: &[&BrepSolid], options: &BooleanOptions) -> Result<Option<Self>, KernelRefusal> {
269 let Some(bounds) = crate::rescale::bounds_of(operands.iter().copied()) else {
270 return Ok(None);
271 };
272 let Some(factor) = crate::rescale::guard_factor(bounds).or_else(|| {
273 if ORIGINAL_WORKING_SCALE.with(|state| state.get()) { None }
274 else { crate::rescale::large_guard_factor(bounds) }
275 }) else {
276 return Ok(None);
277 };
278 crate::rescale::profile_fired("boolean", factor, bounds);
279 let solids = operands
280 .iter()
281 .map(|solid| crate::rescale::scale_operand(solid, factor, "boolean"))
282 .collect::<Result<Vec<_>, _>>()?;
283 let mut options = options.clone();
285 options.imprint.maximum_ssi_step = options.imprint.maximum_ssi_step.map(|step| step * factor);
286 Ok(Some(Self { factor, solids, options }))
287 }
288
289 fn run<T>(
292 &self,
293 original: impl FnOnce() -> Result<T, KernelRefusal>,
294 scaled: impl FnOnce() -> Result<T, KernelRefusal>,
295 ) -> Result<T, KernelRefusal> {
296 if self.factor >= 1.0 { return scaled(); }
297 struct Restore(bool);
298 impl Drop for Restore {
299 fn drop(&mut self) { ORIGINAL_WORKING_SCALE.with(|state| state.set(self.0)); }
300 }
301 let answer = {
302 let _restore = Restore(ORIGINAL_WORKING_SCALE.with(|state| state.replace(true)));
303 original()
304 };
305 match answer {
306 Ok(value) => Ok(value),
307 Err(original) => scaled().or(Err(original)),
308 }
309 }
310
311 fn back(&self, solid: &BrepSolid) -> Result<BrepSolid, KernelRefusal> {
312 crate::rescale::scale_operand(solid, 1.0 / self.factor, "boolean")
313 }
314
315 fn refusal(&self, error: KernelRefusal) -> KernelRefusal {
316 crate::rescale::name_scale(error, self.factor)
317 }
318}
319
320pub fn boolean_operation(
321 first: &BrepSolid,
322 second: &BrepSolid,
323 operation: BooleanOperation,
324 options: &BooleanOptions,
325) -> Result<BrepSolid, KernelRefusal> {
326 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
327 return scaled.run(
328 || boolean_operation(first, second, operation, options),
329 || boolean_operation(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
330 .map_err(|error| scaled.refusal(error))
331 .and_then(|solid| scaled.back(&solid)),
332 );
333 }
334 if isotropic_chart::active() {
337 return boolean_operation_unscaled(first, second, operation, options);
338 }
339 boolean_operation_unscaled(first, second, operation, options).or_else(|refused| {
340 isotropic_chart::suppressed(|| window_retry::retry(first, second, operation, options, refused, boolean_operation_unscaled))
343 })
344}
345
346fn boolean_operation_unscaled(
348 first: &BrepSolid,
349 second: &BrepSolid,
350 operation: BooleanOperation,
351 options: &BooleanOptions,
352) -> Result<BrepSolid, KernelRefusal> {
353 match boolean_operation_with_diagnostics(first, second, operation, options) {
354 Ok(outcome) => {
355 if below_tolerance_refusal_enabled()
358 && outcome.value.shells.iter().all(|shell| shell.faces.is_empty())
359 && !matches!(operation, BooleanOperation::Union)
360 {
361 if let Some(refusal) = below_tolerance_refusal(first, second, None) {
362 if let Some(answer) = below_tolerance_answer(first, second, operation) {
363 return Ok(answer);
364 }
365 if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
366 return Ok(answer);
367 }
368 return Err(refusal);
369 }
370 }
371 if unresolved_merge_refusal_enabled() && !matches!(operation, BooleanOperation::Subtract) {
372 if let Some(refusal) = unresolved_merge_refusal(first, second) {
373 return Err(refusal);
374 }
375 }
376 if below_tolerance_slivers_enabled()
379 && !matches!(operation, BooleanOperation::Subtract)
380 && [first, second].iter().all(|solid| face_count(solid) <= SLIVER_ANSWER_FACES)
381 && near_coincident_planar_faces(first, second).is_some()
382 {
383 if let Some(answer) = below_tolerance_answer(first, second, operation) {
384 return Ok(answer);
385 }
386 }
387 Ok(outcome.value)
388 }
389 Err(error) => {
390 if below_tolerance_refusal_enabled() {
391 if let Some(refusal) = below_tolerance_refusal(first, second, Some(&error)) {
392 if let Some(answer) = below_tolerance_answer(first, second, operation) {
393 return Ok(answer);
394 }
395 if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
396 return Ok(answer);
397 }
398 return Err(refusal);
399 }
400 }
401 if isotropic_chart::isotropic_chart_on() && !isotropic_chart::active() && !isotropic_chart::is_suppressed() {
410 let (a, b) = (isotropic_chart::isotropic(first), isotropic_chart::isotropic(second));
411 if a.is_some() || b.is_some() {
412 let (a, b) = (a.as_ref().unwrap_or(first), b.as_ref().unwrap_or(second));
413 match isotropic_chart::with_active(|| boolean_operation(a, b, operation, options)) {
414 Ok(result) => match isotropic_chart_identity(first, second, a, b, operation, options, &result) {
415 Ok(()) => return Ok(result),
416 Err(why) => {
417 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
418 eprintln!("isotropic chart: the rescaled boolean is not admitted ({why}); on to the perturbation ladder");
419 }
420 }
421 },
422 Err(second_refusal) => {
423 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
424 eprintln!("isotropic chart: the rescaled boolean refused too ({second_refusal}); on to the perturbation ladder");
425 }
426 }
427 }
428 }
429 }
430 if isotropic_chart::active() {
433 return Err(error);
434 }
435 if std::env::var("BREP_NO_PERTURB").as_deref() == Ok("1")
443 || !error.class.perturbation_eligible()
444 {
445 return Err(error);
446 }
447 if std::env::var("BREP_OPEN_OPERAND_GATE").as_deref() != Ok("0") {
469 if let Some((operand, open)) = [first, second]
470 .iter()
471 .enumerate()
472 .find_map(|(operand, solid)| {
473 let open = one_use_edges(solid);
474 (open > 0).then_some((operand, open))
475 })
476 {
477 return Err(error.with_message(|message| format!(
478 "{message}; operand {operand} is not a closed shell: {open} of its edges bound \
479 only one face, so no boolean of it encloses a solid and no perturbation \
480 can close it"
481 )));
482 }
483 }
484 if let Some((operand, face_id, deviation, weld)) =
485 planar_operand_off_its_plane(first, second, options)
486 {
487 return Err(error.with_message(|message| format!(
488 "{message}; operand {operand} face {face_id} is a plane whose straight \
489 boundary sits {deviation:.3e} off it (assembly weld {weld:.1e}), which \
490 no perturbation can reconcile — the body's planes must contain their \
491 boundary before it can take part in an exact boolean"
492 )));
493 }
494 if matches!(operation, BooleanOperation::Subtract)
509 && std::env::var("BREP_PINCH_GATE").as_deref() != Ok("0")
510 && subtract_pinches_at_internal_tangency(first, second, options.tolerance)
511 .unwrap_or(false)
512 {
513 if let Some(solid) = subtract_through_the_common_part(first, second, options) {
516 return Ok(solid);
517 }
518 return Err(error.with_message(|message| format!(
519 "{message}; internal tangency: the operands touch tangentially with \
520 co-directed normals, so the exact difference pinches to zero thickness \
521 (non-manifold, unrepresentable in a boundary model) — refusing rather \
522 than returning a perturbed sliver"
523 )));
524 }
525 if matches!(error.class, RefusalClass::TangentNodeSingularity)
541 && std::env::var("BREP_TANGENT_NODE_GATE").as_deref() != Ok("0")
542 {
543 return Err(error);
544 }
545 if matches!(operation, BooleanOperation::Union) {
549 if let Some(solid) = union_through_the_difference(first, second, options) {
550 return Ok(solid);
551 }
552 }
553 if WITHOUT_PERTURBATION.with(|cell| cell.get()) {
555 return Err(error);
556 }
557 match perturbation_retry(first, second, operation, options) {
558 Ok(solid) => Ok(solid),
559 Err(refused) if refused.is_empty() => Err(error),
560 Err(refused) => {
561 Err(error.with_message(|message| format!("{message}; {}", refused.join("; "))))
562 }
563 }
564 }
565 }
566}
567
568const PINCH_PROBE_STEPS: usize = 8;
573
574const PINCH_ANGULAR_TOLERANCE: f64 = 1e-4;
577
578const PINCH_SEPARATION_STEP: f64 = 1e-2;
582
583fn subtract_through_the_common_part(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
601 if !switch!("BREP_PINCH_COMMON_RETRY", true) || !options.imprint.tangent_curve_imprint {
604 return None;
605 }
606 let common = boolean_operation_with_diagnostics(first, second, BooleanOperation::Intersect, options).ok()?.value;
607 if common.shells.iter().all(|shell| shell.faces.is_empty()) {
608 return None;
609 }
610 let cut = boolean_operation_with_diagnostics(first, &common, BooleanOperation::Subtract, options).ok()?.value;
611 if !cut.validate().is_empty() {
612 return None;
613 }
614 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
615 let (whole, taken, left) = (volume(first)?, volume(&common)?, volume(&cut)?);
616 ((left - (whole - taken)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(cut)
617}
618
619fn union_through_the_difference(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
632 if !switch!("BREP_TANGENT_UNION_DIFFERENCE_RETRY", true) || !options.imprint.tangent_curve_imprint {
633 return None;
634 }
635 let pinches = |a: &BrepSolid, b: &BrepSolid| subtract_pinches_at_internal_tangency(a, b, options.tolerance).unwrap_or(false);
636 if !pinches(first, second) && !pinches(second, first) {
637 return None;
638 }
639 let difference = match boolean_operation_with_diagnostics(first, second, BooleanOperation::Subtract, options) {
640 Ok(outcome) => outcome.value,
641 Err(_) => subtract_through_the_common_part(first, second, options)?,
642 };
643 if difference.shells.iter().all(|shell| shell.faces.is_empty()) || !difference.validate().is_empty() {
644 return None;
645 }
646 let union = boolean_operation_with_diagnostics(second, &difference, BooleanOperation::Union, options).ok()?.value;
647 if !union.validate().is_empty() {
648 return None;
649 }
650 let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
651 let (left, added, whole) = (volume(&difference)?, volume(second)?, volume(&union)?);
652 ((whole - (left + added)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(union)
653}
654
655pub fn subtract_pinches_at_internal_tangency(
677 first: &BrepSolid,
678 second: &BrepSolid,
679 tolerance: f64,
680) -> Result<bool, KernelRefusal> {
681 let contact = (tolerance * 100.0).max(1e-12);
684 let probes_a = first
685 .shells
686 .iter()
687 .flat_map(|shell| &shell.faces)
688 .map(PinchProbe::of)
689 .collect::<Result<Vec<_>, _>>()?;
690 let probes_b = second
691 .shells
692 .iter()
693 .flat_map(|shell| &shell.faces)
694 .map(PinchProbe::of)
695 .collect::<Result<Vec<_>, _>>()?;
696 for probe_a in &probes_a {
697 for probe_b in &probes_b {
698 let pad = 1e-2 * probe_a.extent().max(probe_b.extent());
705 if probe_a.separation(probe_b) > contact + pad {
706 continue;
707 }
708 if classify_surface_pair(
715 &probe_a.face.surface,
716 &probe_b.face.surface,
717 tolerance,
718 PINCH_ANGULAR_TOLERANCE,
719 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")?
720 .relation
721 == SurfacePairRelation::Cosurface
722 {
723 continue;
724 }
725 if faces_touch_with_codirected_normals(probe_a, probe_b, contact)? {
726 return Ok(true);
727 }
728 }
729 }
730 Ok(false)
731}
732
733struct PinchProbe<'a> {
736 face: &'a FaceRecord,
737 samples: Vec<(f64, f64, Vec3)>,
739 minimum: [f64; 3],
740 maximum: [f64; 3],
741}
742
743impl<'a> PinchProbe<'a> {
744 fn of(face: &'a FaceRecord) -> Result<Self, KernelRefusal> {
745 let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
746 let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
747 let steps = PINCH_PROBE_STEPS as f64;
748 let mut samples = Vec::with_capacity((PINCH_PROBE_STEPS + 1).pow(2));
749 let mut minimum = [f64::INFINITY; 3];
750 let mut maximum = [f64::NEG_INFINITY; 3];
751 for i in 0..=PINCH_PROBE_STEPS {
752 let u = u0 + (u1 - u0) * i as f64 / steps;
753 for j in 0..=PINCH_PROBE_STEPS {
754 let v = v0 + (v1 - v0) * j as f64 / steps;
755 let Ok(point) = face.surface.evaluate(u, v) else {
756 continue;
757 };
758 for (axis, value) in [point.x, point.y, point.z].into_iter().enumerate() {
759 minimum[axis] = minimum[axis].min(value);
760 maximum[axis] = maximum[axis].max(value);
761 }
762 samples.push((u, v, point));
763 }
764 }
765 Ok(Self {
766 face,
767 samples,
768 minimum,
769 maximum,
770 })
771 }
772
773 fn extent(&self) -> f64 {
775 (0..3)
776 .map(|axis| self.maximum[axis] - self.minimum[axis])
777 .fold(0.0f64, f64::max)
778 }
779
780 fn separation(&self, other: &Self) -> f64 {
782 let mut gap: f64 = 0.0;
783 for axis in 0..3 {
784 gap = gap.max(self.minimum[axis] - other.maximum[axis]);
785 gap = gap.max(other.minimum[axis] - self.maximum[axis]);
786 }
787 gap
788 }
789}
790
791fn faces_touch_with_codirected_normals(
796 probe_a: &PinchProbe<'_>,
797 probe_b: &PinchProbe<'_>,
798 contact: f64,
799) -> Result<bool, KernelRefusal> {
800 for (probe, other) in [(probe_a, probe_b), (probe_b, probe_a)] {
801 let source = probe.face;
802 let target = other.face;
803 for &(u, v, point) in &probe.samples {
804 let projection = project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?;
805 if projection.distance > contact {
806 continue;
807 }
808 let (Ok(source_normal), Ok(target_normal)) = (
811 source.surface.normal(u, v),
812 target.surface.normal(projection.u, projection.v),
813 ) else {
814 continue;
815 };
816 let source_outward = outward_normal(source_normal, source.same_sense);
817 let target_outward = outward_normal(target_normal, target.same_sense);
818 if source_outward.cross(target_outward).length() > PINCH_ANGULAR_TOLERANCE
819 || source_outward.dot(target_outward) <= 0.0
820 {
821 continue;
822 }
823 if parameter_point_in_face(source, Vec2 { x: u, y: v }, 1e-6).or_refuse(KernelStage::Validate, "parameter_point_in_face")?
824 == PolygonClass::Outside
825 || parameter_point_in_face(
826 target,
827 Vec2 {
828 x: projection.u,
829 y: projection.v,
830 },
831 1e-6,
832 ).or_refuse(KernelStage::Validate, "csg.boolean.mod")? == PolygonClass::Outside
833 {
834 continue;
835 }
836 if contact_separates_locally(source, target, u, v, contact)? {
837 return Ok(true);
838 }
839 }
840 }
841 Ok(false)
842}
843
844fn outward_normal(normal: Vec3, same_sense: bool) -> Vec3 {
845 if same_sense {
846 normal
847 } else {
848 normal.scale(-1.0)
849 }
850}
851
852fn contact_separates_locally(
858 source: &FaceRecord,
859 target: &FaceRecord,
860 u: f64,
861 v: f64,
862 contact: f64,
863) -> Result<bool, KernelRefusal> {
864 let [u0, u1] = source.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
865 let [v0, v1] = source.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
866 let step_u = (u1 - u0) * PINCH_SEPARATION_STEP;
867 let step_v = (v1 - v0) * PINCH_SEPARATION_STEP;
868 for (probe_u, probe_v) in [
869 ((u + step_u).min(u1), v),
870 ((u - step_u).max(u0), v),
871 (u, (v + step_v).min(v1)),
872 (u, (v - step_v).max(v0)),
873 ] {
874 if (probe_u - u).abs() < f64::EPSILON && (probe_v - v).abs() < f64::EPSILON {
875 continue;
876 }
877 let Ok(point) = source.surface.evaluate(probe_u, probe_v) else {
878 continue;
879 };
880 if project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?.distance > contact * 10.0 {
883 return Ok(true);
884 }
885 }
886 Ok(false)
887}
888
889fn perturbation_retry(
943 first: &BrepSolid,
944 second: &BrepSolid,
945 operation: BooleanOperation,
946 options: &BooleanOptions,
947) -> Result<BrepSolid, Vec<String>> {
948 const DIRECTIONS: [[f64; 3]; 4] = [
959 [0.4034, 0.7973, 0.4491],
960 [0.7973, 0.4491, 0.4034],
961 [0.4491, 0.4034, 0.7973],
962 [0.5774, -0.5774, 0.5774],
963 ];
964 const FRACTIONS: [f64; 5] = PERTURBATION_FRACTIONS;
970
971 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
972 let scale = crate::solid_tolerance::solid_scale(first)
973 .max(crate::solid_tolerance::solid_scale(second))
974 .max(1.0);
975
976 let _caller = crate::mass_caller("boolean.perturbation_rescue");
980 let va = solid_signed_volume(first).ok().map(f64::abs);
981 let vb = solid_signed_volume(second).ok().map(f64::abs);
982 let hold_identity = std::env::var("BREP_PERTURB_IDENTITY").as_deref() != Ok("0");
983 let hold_mirror = hold_identity && std::env::var("BREP_PERTURB_MIRROR").as_deref() != Ok("0");
986 let early_exit = std::env::var("BREP_MIRROR_EARLY_EXIT").as_deref() != Ok("0");
989 let mut trends = [MirrorTrend::default(); 4];
990 let mut identity: Option<Option<InclusionExclusion>> = None;
992 let mut refused = Vec::new();
993 let ladder = std::env::var("BREP_DEBUG_PERTURB_LADDER").is_ok();
997 let ladder_start = web_time::Instant::now();
998 if ladder {
999 let measured = inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
1000 match &measured {
1001 Some(identity) => eprintln!(
1002 "[ladder] identity {} = {:.9} from the exact lane's {} ({:.9}); V(first) {:?} V(second) {:?}",
1003 identity.formula, identity.expected, identity.reading, identity.read, va, vb
1004 ),
1005 None => eprintln!("[ladder] no identity: no exact-lane boolean of these operands clears in either order"),
1006 }
1007 identity = Some(measured);
1008 }
1009 let rung_miss = |identity: &Option<Option<InclusionExclusion>>, candidate: &BrepSolid| -> String {
1010 let volume = body_volume(candidate);
1011 match (identity, volume) {
1012 (Some(Some(identity)), Some(volume)) => format!(
1013 "volume {volume:.9} miss {:+.3e} bar {:.3e}",
1014 volume - identity.expected,
1015 crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * identity.expected.abs())
1016 ),
1017 (_, Some(volume)) => format!("volume {volume:.9}"),
1018 _ => "no volume".to_string(),
1019 }
1020 };
1021
1022 for &fraction in &FRACTIONS {
1023 let magnitude = scale * fraction;
1024 for (direction, dir) in DIRECTIONS.iter().enumerate() {
1025 if trends[direction].closed {
1026 if ladder {
1027 eprintln!("[ladder] dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}: not tried, its direction is closed");
1028 }
1029 continue;
1030 }
1031 let offset = [dir[0] * magnitude, dir[1] * magnitude, dir[2] * magnitude];
1032 let translate = match AffineTransform::new([
1033 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,
1037 ]) {
1038 Ok(transform) => transform,
1039 Err(_) => continue,
1040 };
1041 let moved = match crate::transform_brep(second, translate, false) {
1042 Ok(solid) => solid,
1043 Err(_) => continue,
1044 };
1045 let rung = format!("dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}");
1046 let rung_start = web_time::Instant::now();
1047 let candidate =
1048 match boolean_operation_with_diagnostics(first, &moved, operation, options) {
1049 Ok(outcome) => outcome.value,
1050 Err(error) => {
1051 if ladder {
1052 eprintln!("[ladder] {rung}: exact lane refused {:?}", error.class);
1053 }
1054 continue;
1055 }
1056 };
1057 let built = rung_start.elapsed();
1058 if candidate.shells.is_empty() {
1060 if ladder {
1061 eprintln!("[ladder] {rung}: empty");
1062 }
1063 continue;
1064 }
1065 if let (Some(va), Some(vb)) = (va, vb) {
1070 if let Ok(vr) = solid_signed_volume(&candidate) {
1071 if !volume_within_csg_bounds(operation, va, vb, vr.abs()) {
1072 if ladder {
1073 eprintln!("[ladder] {rung}: outside the CSG bound, {}", rung_miss(&identity, &candidate));
1074 }
1075 continue;
1076 }
1077 }
1078 }
1079 let bounded = rung_start.elapsed();
1084 if hold_identity {
1086 let identity = identity.get_or_insert_with(|| {
1087 let identity =
1088 inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
1089 if debug && identity.is_none() {
1090 eprintln!(
1091 "[perturb] no exact-lane boolean of these operands clears in either \
1092 order; no identity to hold"
1093 );
1094 }
1095 identity
1096 });
1097 if let Some(identity) = identity {
1098 let expected = identity.expected;
1099 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * expected.abs());
1100 let volume = body_volume(&candidate);
1101 let miss = volume.map(|volume| (volume - expected).abs());
1102 if !miss.is_some_and(|miss| miss <= bar) {
1103 let sentence = format!(
1104 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1105 (offset {magnitude:.3e}) refused: its body reads {} against the \
1106 inclusion–exclusion identity {} = {expected:.9} (the exact lane's \
1107 {} reads {:.9}), a miss of {} beyond the volume drift bar {bar:.3e}",
1108 volume.map_or("no volume".to_string(), |volume| format!("{volume:.9}")),
1109 identity.formula,
1110 identity.reading,
1111 identity.read,
1112 miss.map_or("unmeasured".to_string(), |miss| format!("{miss:.3e}")),
1113 );
1114 if debug {
1115 eprintln!("[perturb] {sentence}");
1116 }
1117 if ladder {
1118 eprintln!(
1119 "[ladder] {rung}: refused by the identity, volume {} miss {} bar {bar:.3e}",
1120 volume.map_or("none".to_string(), |volume| format!("{volume:.9}")),
1121 volume.map_or("unmeasured".to_string(), |volume| format!("{:+.3e}", volume - expected)),
1122 );
1123 }
1124 refused.push(sentence);
1125 continue;
1126 }
1127 } else if hold_mirror {
1128 let mirror_start = web_time::Instant::now();
1131 let mirrored = AffineTransform::new([
1132 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,
1136 ])
1137 .ok()
1138 .and_then(|transform| crate::transform_brep(second, transform, false).ok());
1139 let mirror = mirrored.as_ref().and_then(|mirrored| {
1140 inclusion_exclusion_volume(first, mirrored, operation, options, va, vb, true)
1141 });
1142 let mirror_time = mirror_start.elapsed();
1143 let volume = body_volume(&candidate);
1144 let mut measured = None;
1145 let verdict = match (&mirror, volume) {
1146 (Some(mirror), Some(volume)) => {
1147 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * mirror.expected.abs());
1148 let miss = 0.5 * (volume - mirror.expected).abs();
1149 measured = Some((0.5 * (volume - mirror.expected), bar));
1150 if ladder {
1151 eprintln!(
1152 "[ladder] {rung}: mirror at −offset reads {} = {:.9} (the mirrored {} {:.9}); body {volume:.9}, first-order translation error {:+.3e} bar {bar:.3e}",
1153 mirror.formula, mirror.expected, mirror.reading, mirror.read, 0.5 * (volume - mirror.expected)
1154 );
1155 }
1156 (miss > bar).then(|| format!(
1157 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1158 (offset {magnitude:.3e}) refused: no exact-lane boolean of the \
1159 operands clears, so the rung is held to its mirror: its body reads \
1160 {volume:.9} with the second operand moved +offset and {} = {:.9} \
1161 with it moved −offset (the mirrored {} reads {:.9}), a first-order \
1162 translation error of {miss:.3e} beyond the volume drift bar {bar:.3e}",
1163 mirror.formula, mirror.expected, mirror.reading, mirror.read
1164 ))
1165 }
1166 _ => Some(format!(
1167 "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1168 (offset {magnitude:.3e}) refused: no exact-lane boolean of the operands \
1169 clears, and none clears with the second operand moved −offset either, \
1170 so nothing checks the rung's body{}",
1171 volume.map_or(String::new(), |volume| format!(" ({volume:.9})"))
1172 )),
1173 };
1174 match verdict {
1175 None => trends[direction].cleared(),
1176 Some(sentence) => {
1177 if debug {
1178 eprintln!("[perturb] {sentence}");
1179 }
1180 if ladder {
1181 eprintln!(
1182 "[ladder] {rung}: refused by its mirror (rung {:.0} ms: built {:.0}, bound {:.0}, mirror {:.0} ms; ladder {:.1} s)",
1183 rung_start.elapsed().as_secs_f64() * 1e3,
1184 built.as_secs_f64() * 1e3,
1185 (bounded - built).as_secs_f64() * 1e3,
1186 mirror_time.as_secs_f64() * 1e3,
1187 ladder_start.elapsed().as_secs_f64()
1188 );
1189 }
1190 refused.push(sentence);
1191 let closure = measured.and_then(|(error, bar)| {
1194 let earlier = trends[direction].refused(magnitude, error, early_exit)?;
1195 Some((earlier, error, bar))
1196 });
1197 if let Some(((earlier_offset, earlier_error), error, bar)) = closure {
1198 let closed = format!(
1199 "perturbation direction dir={dir:?} closed after offset {magnitude:.3e}: its \
1200 rungs' first-order translation errors read {earlier_error:+.3e} at offset \
1201 {earlier_offset:.3e} and {error:+.3e} at {magnitude:.3e}, one sign and \
1202 growing, so no larger offset along it comes back to the volume drift bar \
1203 {bar:.3e}"
1204 );
1205 if debug {
1206 eprintln!("[perturb] {closed}");
1207 }
1208 if ladder {
1209 eprintln!("[ladder] {closed}");
1210 }
1211 refused.push(closed);
1212 }
1213 continue;
1214 }
1215 }
1216 }
1217 }
1218 match crate::oracle::boolean_semantic_disagreement(
1222 first, second, operation, &candidate, 400,
1223 ) {
1224 Ok(report) if report.considered >= 30 && !report.is_flagged() => {
1225 if ladder {
1226 eprintln!(
1227 "[ladder] {rung}: accepted (oracle {} considered, rate {:.4}), {}",
1228 report.considered, report.disagreement_rate, rung_miss(&identity, &candidate)
1229 );
1230 }
1231 if debug {
1232 eprintln!(
1233 "[perturb] rescued {operation:?}: dir={dir:?} fraction={fraction:.1e} \
1234 magnitude={magnitude:.3e} offset={offset:?} \
1235 (oracle considered={} rate={:.4})",
1236 report.considered, report.disagreement_rate
1237 );
1238 }
1239 return Ok(candidate);
1240 }
1241 report => {
1242 if ladder {
1243 let verdict = match &report {
1244 Ok(report) => format!("oracle {} considered, rate {:.4}", report.considered, report.disagreement_rate),
1245 Err(error) => format!("oracle error {error:?}"),
1246 };
1247 eprintln!("[ladder] {rung}: refused by the oracle ({verdict}), {}", rung_miss(&identity, &candidate));
1248 }
1249 continue;
1250 }
1251 }
1252 }
1253 }
1254 if debug {
1255 eprintln!("[perturb] ladder exhausted for {operation:?}; no rung produced a clean result");
1256 }
1257 Err(refused)
1258}
1259
1260pub const PERTURBATION_FRACTIONS: [f64; 5] = [3e-5, 1e-4, 3e-4, 1e-3, 3e-3];
1263
1264#[derive(Clone, Copy, Default)]
1288pub struct MirrorTrend {
1289 last: Option<(f64, f64)>,
1291 pub closed: bool,
1292}
1293
1294impl MirrorTrend {
1295 pub fn refused(&mut self, offset: f64, error: f64, close: bool) -> Option<(f64, f64)> {
1300 let earlier = self
1301 .last
1302 .filter(|&(_, earlier)| earlier.signum() == error.signum() && error.abs() >= earlier.abs())
1303 .filter(|_| close);
1304 self.last = Some((offset, error));
1305 self.closed |= earlier.is_some();
1306 earlier
1307 }
1308
1309 pub fn cleared(&mut self) {
1311 self.last = None;
1312 }
1313}
1314
1315pub fn below_tolerance_refusal_enabled() -> bool {
1330 crate::switch!("BREP_BELOW_TOLERANCE_REFUSAL", true)
1331}
1332
1333pub fn below_tolerance_slivers_enabled() -> bool {
1350 crate::switch!("BREP_BELOW_TOLERANCE_SLIVERS", true)
1351}
1352
1353const SLIVER_ANSWER_FACES: usize = 64;
1356
1357fn face_count(solid: &BrepSolid) -> usize {
1358 solid.shells.iter().map(|shell| shell.faces.len()).sum()
1359}
1360
1361fn below_tolerance_answer(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<BrepSolid> {
1363 if !below_tolerance_slivers_enabled() || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES) {
1364 return None;
1365 }
1366 if ![first, second].iter().all(|solid| closed_single_shell(solid)) {
1367 return None;
1368 }
1369 let inside = |x: &BrepSolid, y: &BrepSolid| difference_all_sliver(x, y);
1370 if matches!(operation, BooleanOperation::Subtract) {
1371 return inside(first, second).then(empty_solid);
1372 }
1373 let (first_in, second_in) = (inside(first, second), inside(second, first));
1374 let first_larger = || match (body_volume(first), body_volume(second)) {
1377 (Some(a), Some(b)) => a >= b,
1378 _ => true,
1379 };
1380 let outer_is_first = match (first_in, second_in) {
1381 (false, false) => return None,
1382 (true, false) => false,
1383 (false, true) => true,
1384 (true, true) => first_larger(),
1385 };
1386 let (outer, inner) = if outer_is_first { (first, second) } else { (second, first) };
1387 Some(match operation {
1388 BooleanOperation::Union => outer.clone(),
1389 _ => inner.clone(),
1390 })
1391}
1392
1393fn closed_single_shell(solid: &BrepSolid) -> bool {
1395 if !solid.kind.is_solid() || solid.shells.len() != 1 {
1396 return false;
1397 }
1398 let mut uses: HashMap<u64, usize> = HashMap::default();
1399 for coedge in solid.shells[0].faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1400 *uses.entry(coedge.edge_id).or_default() += 1;
1401 }
1402 !uses.is_empty() && uses.values().all(|&count| count == 2) && solid.edges.iter().all(|edge| uses.contains_key(&edge.id))
1403}
1404
1405fn difference_all_sliver(first: &BrepSolid, second: &BrepSolid) -> bool {
1416 let Some(bounds) = difference_bounds(first, second) else {
1417 return false;
1418 };
1419 let Ok(properties) = crate::solid_mass_properties(first) else {
1420 return false;
1421 };
1422 bounds.out <= BELOW_TOLERANCE_BAND
1423 && bounds.upper.is_finite()
1424 && bounds.upper <= crate::tolerance::COINCIDENCE_DISTANCE_FLOOR * properties.surface_area
1425}
1426
1427struct DifferenceBounds {
1433 lower: f64,
1434 upper: f64,
1435 out: f64,
1437}
1438
1439fn difference_bounds(first: &BrepSolid, second: &BrepSolid) -> Option<DifferenceBounds> {
1440 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1441 let (polygons_a, polygons_b) = (face_polygons(first, scale)?, face_polygons(second, scale)?);
1442 let vertices_b: Vec<Vec3> = second.vertices.iter().map(|vertex| vertex.point).collect();
1443 let vertices_a: Vec<Vec3> = first.vertices.iter().map(|vertex| vertex.point).collect();
1444 let flat = 1e-9 * scale;
1445 let mut bounds = DifferenceBounds { lower: 0.0, upper: 0.0, out: 0.0 };
1446 for polygon in &polygons_b {
1447 let (origin, normal) = polygon_plane(polygon)?;
1448 if vertices_b.iter().any(|vertex| vertex.sub(origin).dot(normal) > flat) {
1450 return None;
1451 }
1452 let out = vertices_a.iter().map(|vertex| vertex.sub(origin).dot(normal)).fold(0.0f64, f64::max);
1453 bounds.out = bounds.out.max(out);
1454 if out <= 0.0 {
1455 continue;
1456 }
1457 let part: f64 = polygons_a.iter().map(|face| clipped_cone_volume(face, origin, normal)).sum();
1458 bounds.lower = bounds.lower.max(part);
1459 bounds.upper += part;
1460 }
1461 Some(bounds)
1462}
1463
1464pub fn below_tolerance_rescale_enabled() -> bool {
1474 crate::switch!("BREP_BELOW_TOLERANCE_RESCALE", false)
1475}
1476
1477fn below_tolerance_rescaled(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions) -> Option<BrepSolid> {
1478 if !below_tolerance_rescale_enabled()
1479 || options.tolerances.is_some()
1480 || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES || !closed_single_shell(solid))
1481 {
1482 return None;
1483 }
1484 let (volume_exact, area_exact) = convex_pair_measures(first, second, operation)?;
1485 let volume_slack = 1e-9 * body_volume(first)?.max(body_volume(second)?);
1486 let area_slack = 1e-9 * area_exact.max(1.0);
1487 for factor in [100.0, 1000.0] {
1488 let scaled = |solid: &BrepSolid| crate::rescale::scale_operand(solid, factor, "boolean").ok();
1489 let (Some(a), Some(b)) = (scaled(first), scaled(second)) else {
1490 continue;
1491 };
1492 let mut scaled_options = options.clone();
1493 scaled_options.imprint.maximum_ssi_step = scaled_options.imprint.maximum_ssi_step.map(|step| step * factor);
1494 let Ok(outcome) = boolean_operation_with_diagnostics(&a, &b, operation, &scaled_options) else {
1495 continue;
1496 };
1497 let Ok(answer) = crate::rescale::scale_operand(&outcome.value, 1.0 / factor, "boolean") else {
1498 continue;
1499 };
1500 let Ok(properties) = crate::solid_mass_properties(&answer) else {
1501 continue;
1502 };
1503 if (properties.volume.abs() - volume_exact).abs() <= volume_slack
1504 && (properties.surface_area - area_exact).abs() <= area_slack
1505 && !answer.validate().iter().any(|issue| issue.severity == "error")
1506 {
1507 return Some(answer);
1508 }
1509 }
1510 None
1511}
1512
1513fn convex_pair_measures(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<(f64, f64)> {
1519 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1520 let (polygons_a, polygons_b) = (face_polygons(first, scale)?, face_polygons(second, scale)?);
1521 let (planes_a, planes_b) = (convex_planes(&polygons_a, scale)?, convex_planes(&polygons_b, scale)?);
1522 let zero = Vec3::new(0.0, 0.0, 0.0);
1523 let read = |polygons: &[Vec<Vec3>], planes: &[(Vec3, Vec3)]| {
1525 let (mut cone, mut area, mut inside_area) = (0.0, 0.0, 0.0);
1526 for polygon in polygons {
1527 area += vector_area(polygon, zero).length();
1528 let mut inside = polygon.clone();
1529 for &(origin, normal) in planes {
1530 inside = clip_polygon(&inside, origin, normal.scale(-1.0));
1531 if inside.len() < 3 {
1532 break;
1533 }
1534 }
1535 if inside.len() >= 3 {
1536 let vector = vector_area(&inside, zero);
1537 cone += inside[0].dot(vector) / 3.0;
1538 inside_area += vector.length();
1539 }
1540 }
1541 (cone, area, inside_area)
1542 };
1543 let (cone_a, area_a, inside_a) = read(&polygons_a, &planes_b);
1544 let (cone_b, area_b, inside_b) = read(&polygons_b, &planes_a);
1545 let (volume_a, volume_b) = (body_volume(first)?, body_volume(second)?);
1546 let common = cone_a + cone_b;
1547 Some(match operation {
1548 BooleanOperation::Intersect => (common, inside_a + inside_b),
1549 BooleanOperation::Union => (volume_a + volume_b - common, (area_a - inside_a) + (area_b - inside_b)),
1550 BooleanOperation::Subtract => (volume_a - common, (area_a - inside_a) + inside_b),
1551 })
1552}
1553
1554fn convex_planes(polygons: &[Vec<Vec3>], scale: f64) -> Option<Vec<(Vec3, Vec3)>> {
1557 let planes = polygons.iter().map(|polygon| polygon_plane(polygon)).collect::<Option<Vec<_>>>()?;
1558 let flat = 1e-9 * scale;
1559 let convex = planes.iter().all(|&(origin, normal)| polygons.iter().flatten().all(|vertex| vertex.sub(origin).dot(normal) <= flat));
1560 convex.then_some(planes)
1561}
1562
1563fn clip_polygon(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> Vec<Vec3> {
1566 let side = |point: Vec3| point.sub(origin).dot(normal);
1567 let mut kept = Vec::with_capacity(polygon.len() + 2);
1568 for (index, &point) in polygon.iter().enumerate() {
1569 let next = polygon[(index + 1) % polygon.len()];
1570 let (here, there) = (side(point), side(next));
1571 if here >= 0.0 {
1572 kept.push(point);
1573 }
1574 if (here >= 0.0) != (there >= 0.0) {
1575 let t = here / (here - there);
1576 kept.push(point.add(next.sub(point).scale(t)));
1577 }
1578 }
1579 kept
1580}
1581
1582fn face_polygons(solid: &BrepSolid, scale: f64) -> Option<Vec<Vec<Vec3>>> {
1586 let vertex = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1587 let mut polygons = Vec::new();
1588 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
1589 if !face.surface.is_affine().ok()? {
1590 return None;
1591 }
1592 for lp in &face.loops {
1593 let mut polygon = Vec::with_capacity(lp.coedges.len());
1594 for coedge in &lp.coedges {
1595 let edge = solid.edges.iter().find(|edge| edge.id == coedge.edge_id)?;
1596 let (start, end) = (vertex(edge.start_vertex_id)?, vertex(edge.end_vertex_id)?);
1597 let chord = end.sub(start);
1598 let length = chord.length();
1599 if edge.degenerate || length <= 1e-12 * scale {
1600 return None;
1601 }
1602 for control in &edge.curve.control_points {
1603 let offset = control.point().ok()?.sub(start);
1604 if offset.cross(chord).length() / length > 1e-9 * scale {
1605 return None;
1606 }
1607 }
1608 polygon.push(if coedge.forward { start } else { end });
1609 }
1610 polygons.push(polygon);
1611 }
1612 }
1613 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();
1615 if !(volume.abs() > 0.0) {
1616 return None;
1617 }
1618 if volume < 0.0 {
1619 for polygon in &mut polygons {
1620 polygon.reverse();
1621 }
1622 }
1623 Some(polygons)
1624}
1625
1626fn polygon_plane(polygon: &[Vec3]) -> Option<(Vec3, Vec3)> {
1628 let origin = *polygon.first()?;
1629 Some((origin, vector_area(polygon, origin).normalized().ok()?))
1630}
1631
1632fn vector_area(polygon: &[Vec3], origin: Vec3) -> Vec3 {
1633 let mut area = Vec3::new(0.0, 0.0, 0.0);
1634 for (index, point) in polygon.iter().enumerate() {
1635 let next = polygon[(index + 1) % polygon.len()];
1636 area = area.add(point.sub(origin).cross(next.sub(origin)));
1637 }
1638 area.scale(0.5)
1639}
1640
1641fn clipped_cone_volume(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> f64 {
1647 let clipped: Vec<Vec3> = if normal.length() == 0.0 { polygon.to_vec() } else { clip_polygon(polygon, origin, normal) };
1648 if clipped.len() < 3 {
1649 return 0.0;
1650 }
1651 clipped[0].sub(origin).dot(vector_area(&clipped, origin)) / 3.0
1652}
1653
1654const BELOW_TOLERANCE_BAND: f64 = 10.0 * crate::tolerance::WELD_FLOOR;
1657
1658pub fn unresolved_merge_refusal_enabled() -> bool {
1668 crate::switch!("BREP_UNRESOLVED_MERGE_REFUSAL", false)
1669}
1670
1671pub fn sliver_shell_drop_enabled() -> bool {
1684 crate::switch!("BREP_SLIVER_SHELL_DROP", true)
1685}
1686
1687const SLIVER_SHELL_THICKNESS: f64 = 1e-12;
1691
1692pub fn sliver_shell_fast_on() -> bool {
1707 crate::switch!("BREP_SLIVER_SHELL_FAST", true)
1708}
1709
1710fn sliver_shell_fast_check_on() -> bool {
1711 crate::switch!("BREP_SLIVER_SHELL_FAST_CHECK", false)
1712}
1713
1714thread_local! {
1715 static SLIVER_FAST_CHECK: std::cell::Cell<(u64, u64, u64)> = const { std::cell::Cell::new((0, 0, 0)) };
1716}
1717
1718pub fn sliver_shell_fast_check_take() -> (u64, u64, u64) {
1721 SLIVER_FAST_CHECK.with(|cell| cell.replace((0, 0, 0)))
1722}
1723
1724fn sliver_fast_record(compared: u64, differed: u64, kept: u64) {
1725 SLIVER_FAST_CHECK.with(|cell| {
1726 let (a, b, c) = cell.get();
1727 cell.set((a + compared, b + differed, c + kept));
1728 });
1729}
1730
1731fn face_area_upper_bound(surface: &crate::NurbsSurface) -> Option<f64> {
1739 let net = &surface.control_points;
1740 let rows = net.len();
1741 let columns = net.first()?.len();
1742 if rows < 2 || columns < 2 || net.iter().any(|row| row.len() != columns) {
1743 return None;
1744 }
1745 let (p, q) = (surface.degree_u, surface.degree_v);
1746 let (us, vs) = (&surface.knots_u, &surface.knots_v);
1747 if us.len() != rows + p + 1 || vs.len() != columns + q + 1 {
1748 return None;
1749 }
1750 let mut w_min = f64::INFINITY;
1751 let mut w_max = 0.0f64;
1752 let mut point_max = 0.0f64;
1753 for c in net.iter().flatten() {
1754 if !(c.w > 0.0) {
1755 return None;
1756 }
1757 w_min = w_min.min(c.w);
1758 w_max = w_max.max(c.w);
1759 point_max = point_max.max((c.x * c.x + c.y * c.y + c.z * c.z).sqrt());
1760 }
1761 let hodograph = |along_u: bool| -> Option<(f64, f64)> {
1763 let (count, degree, knots) = if along_u { (rows, p, us) } else { (columns, q, vs) };
1764 let (mut dp, mut dw) = (0.0f64, 0.0f64);
1765 for i in 0..count - 1 {
1766 let span = knots[i + degree + 1] - knots[i + 1];
1767 if !(span > 0.0) {
1768 continue;
1769 }
1770 let scale = degree as f64 / span;
1771 let others = if along_u { columns } else { rows };
1772 for j in 0..others {
1773 let (a, b) = if along_u { (net[i][j], net[i + 1][j]) } else { (net[j][i], net[j][i + 1]) };
1774 let (x, y, z) = (b.x - a.x, b.y - a.y, b.z - a.z);
1775 dp = dp.max(scale * (x * x + y * y + z * z).sqrt());
1776 dw = dw.max(scale * (b.w - a.w).abs());
1777 }
1778 }
1779 Some((dp, dw))
1780 };
1781 let (pu, wu) = hodograph(true)?;
1782 let (pv, wv) = hodograph(false)?;
1783 let su = (pu * w_max + point_max * wu) / (w_min * w_min);
1784 let sv = (pv * w_max + point_max * wv) / (w_min * w_min);
1785 let extent_u = us[us.len() - 1] - us[0];
1786 let extent_v = vs[vs.len() - 1] - vs[0];
1787 let bound = su * sv * extent_u * extent_v;
1788 bound.is_finite().then_some(bound)
1789}
1790
1791pub fn trimmed_face_area_upper_bound(face: &crate::topology::FaceRecord) -> Option<f64> {
1799 let s = &face.surface;
1800 let (u0, u1) = (*s.knots_u.first()?, *s.knots_u.last()?);
1801 let (v0, v1) = (*s.knots_v.first()?, *s.knots_v.last()?);
1802 let (du, dv) = (1e-12 * (u1 - u0).abs(), 1e-12 * (v1 - v0).abs());
1804 if !(du > 0.0 && dv > 0.0) {
1805 return None;
1806 }
1807 for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
1808 for c in &coedge.pcurve.control_points {
1809 if !(c.w > 0.0) {
1810 return None;
1811 }
1812 let (u, v) = (c.x / c.w, c.y / c.w);
1813 if !(u >= u0 - du && u <= u1 + du && v >= v0 - dv && v <= v1 + dv) {
1814 return None;
1815 }
1816 }
1817 }
1818 face_area_upper_bound(s).map(|bound| 2.0 * bound)
1819}
1820
1821fn drop_sliver_shells(solid: &mut BrepSolid) -> usize {
1824 if !sliver_shell_drop_enabled() || !solid.kind.is_solid() || solid.shells.len() < 2 {
1825 return 0;
1826 }
1827 let floor = SLIVER_SHELL_THICKNESS * crate::solid_tolerance::solid_scale(solid).max(1.0);
1828 let degenerate: std::collections::HashSet<u64> = solid.edges.iter().filter(|edge| edge.degenerate).map(|edge| edge.id).collect();
1829 let mut drop = vec![false; solid.shells.len()];
1830 for (index, shell) in solid.shells.iter().enumerate() {
1831 if shell.faces.is_empty() {
1832 continue;
1833 }
1834 let mut uses: HashMap<u64, usize> = HashMap::default();
1836 for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1837 if !degenerate.contains(&coedge.edge_id) {
1838 *uses.entry(coedge.edge_id).or_default() += 1;
1839 }
1840 }
1841 if uses.is_empty() || uses.values().any(|&count| count != 2) {
1842 continue;
1843 }
1844 let alone = BrepSolid { shells: vec![shell.clone()], mass_properties_cache: Default::default(), ..solid.clone() };
1845 let (fast, check) = (sliver_shell_fast_on(), sliver_shell_fast_check_on());
1846 let kept_fast = (fast || check)
1847 && shell
1848 .faces
1849 .iter()
1850 .map(trimmed_face_area_upper_bound)
1851 .sum::<Option<f64>>()
1852 .map(|area| floor * area)
1853 .filter(|bar| bar.is_finite() && *bar > 0.0)
1854 .and_then(|bar| crate::solid_signed_volume_for_sign(&alone, bar).ok().map(|volume| volume > bar))
1855 .unwrap_or(false);
1856 if kept_fast && !check {
1857 sliver_fast_record(0, 0, 1);
1858 continue;
1859 }
1860 let Ok(mass) = crate::solid_mass_properties(&alone) else {
1861 continue;
1862 };
1863 let thickness = mass.volume.abs() / mass.surface_area.max(f64::MIN_POSITIVE);
1864 if env_read!("BREP_DEBUG_SLIVER_SHELL").is_some() {
1865 eprintln!(
1866 "sliver-shell: shell {index} of {}: volume {:.6e} area {:.6e} thickness {thickness:.3e}",
1867 solid.shells.len(),
1868 mass.volume,
1869 mass.surface_area
1870 );
1871 }
1872 drop[index] = thickness < floor;
1873 if check {
1874 sliver_fast_record(1, u64::from(kept_fast && drop[index]), u64::from(kept_fast));
1875 }
1876 }
1877 let dropped = drop.iter().filter(|&&d| d).count();
1878 if dropped == 0 || dropped == solid.shells.len() {
1879 return 0;
1880 }
1881 let mut index = 0;
1882 solid.shells.retain(|_| {
1883 let keep = !drop[index];
1884 index += 1;
1885 keep
1886 });
1887 let used_edges: std::collections::HashSet<u64> = solid
1888 .shells
1889 .iter()
1890 .flat_map(|shell| &shell.faces)
1891 .flat_map(|face| &face.loops)
1892 .flat_map(|lp| &lp.coedges)
1893 .map(|coedge| coedge.edge_id)
1894 .collect();
1895 solid.edges.retain(|edge| used_edges.contains(&edge.id));
1896 let used_vertices: std::collections::HashSet<u64> =
1897 solid.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
1898 solid.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
1899 solid.mass_properties_cache = Default::default();
1900 refresh_derived_genus(solid);
1902 dropped
1903}
1904
1905fn unresolved_merge_refusal(first: &BrepSolid, second: &BrepSolid) -> Option<KernelRefusal> {
1906 let (lower, upper) = (crate::tolerance::COINCIDENCE_DISTANCE_FLOOR, crate::tolerance::WELD_FLOOR);
1907 let (face_a, face_b, separation) = planar_faces_apart_within(first, second, lower, upper)?;
1908 Some(KernelRefusal::unsupported(
1909 KernelStage::Intersect,
1910 "below_modelling_tolerance",
1911 format!(
1912 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1913 another, {separation:.3e} apart at most over their shared extent: farther than a coincidence \
1914 ({lower:.0e}) and closer than the kernel resolves ({upper:.0e}), so the step between them would be \
1915 welded away"
1916 ),
1917 ))
1918}
1919
1920fn below_tolerance_refusal(first: &BrepSolid, second: &BrepSolid, error: Option<&KernelRefusal>) -> Option<KernelRefusal> {
1921 let (face_a, face_b, separation) = near_coincident_planar_faces(first, second)?;
1922 let message = format!(
1923 "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1924 another, {separation:.3e} apart at most over their shared extent: the slivers between them are below the \
1925 modelling tolerance ({BELOW_TOLERANCE_BAND:.0e}), so the kernel cannot resolve them{}",
1926 error.map(|error| format!(" (the exact arrangement said: {})", error.message.chars().take(160).collect::<String>())).unwrap_or_default()
1927 );
1928 Some(KernelRefusal::unsupported(KernelStage::Intersect, "below_modelling_tolerance", message))
1929}
1930
1931fn near_coincident_planar_faces(first: &BrepSolid, second: &BrepSolid) -> Option<(u64, u64, f64)> {
1935 let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1936 planar_faces_apart_within(first, second, 1e-9 * scale, BELOW_TOLERANCE_BAND)
1937}
1938
1939fn planar_faces_apart_within(first: &BrepSolid, second: &BrepSolid, lower: f64, upper: f64) -> Option<(u64, u64, f64)> {
1943 struct Planar {
1944 id: u64,
1945 origin: Vec3,
1946 normal: Vec3,
1947 corners: Vec<Vec3>,
1948 bounds: crate::spatial::Aabb,
1949 }
1950 let read = |solid: &BrepSolid| -> Vec<Planar> {
1951 let at = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1952 solid
1953 .shells
1954 .iter()
1955 .flat_map(|shell| &shell.faces)
1956 .filter_map(|face| {
1957 if !face.surface.is_affine().ok()? {
1958 return None;
1959 }
1960 let origin = face.surface.control_points[0][0].point().ok()?;
1961 let a = face.surface.control_points[1][0].point().ok()?.sub(origin);
1962 let b = face.surface.control_points[0][1].point().ok()?.sub(origin);
1963 let normal = a.cross(b).normalized().ok()?;
1964 let corners: Vec<Vec3> = face
1965 .loops
1966 .iter()
1967 .flat_map(|lp| &lp.coedges)
1968 .filter_map(|coedge| solid.edges.iter().find(|edge| edge.id == coedge.edge_id))
1969 .flat_map(|edge| [at(edge.start_vertex_id), at(edge.end_vertex_id)])
1970 .flatten()
1971 .collect();
1972 if corners.is_empty() {
1973 return None;
1974 }
1975 let bounds = crate::spatial::Aabb::from_points(corners.clone());
1976 Some(Planar { id: face.id, origin, normal, corners, bounds })
1977 })
1978 .collect()
1979 };
1980 let (faces_a, faces_b) = (read(first), read(second));
1981 for a in &faces_a {
1982 for b in &faces_b {
1983 if a.normal.cross(b.normal).length() > 1e-3 {
1984 continue;
1985 }
1986 if !a.bounds.intersects(b.bounds, upper) {
1987 continue;
1988 }
1989 let separation = a
1990 .corners
1991 .iter()
1992 .map(|corner| corner.sub(b.origin).dot(b.normal).abs())
1993 .chain(b.corners.iter().map(|corner| corner.sub(a.origin).dot(a.normal).abs()))
1994 .fold(0.0f64, f64::max);
1995 if separation > lower && separation <= upper {
1996 return Some((a.id, b.id, separation));
1997 }
1998 }
1999 }
2000 None
2001}
2002
2003pub fn one_use_edges(solid: &BrepSolid) -> usize {
2004 let mut uses: HashMap<u64, usize> = HashMap::default();
2005 for coedge in solid
2006 .shells
2007 .iter()
2008 .flat_map(|shell| &shell.faces)
2009 .flat_map(|face| &face.loops)
2010 .flat_map(|loop_record| &loop_record.coedges)
2011 {
2012 *uses.entry(coedge.edge_id).or_default() += 1;
2013 }
2014 solid
2015 .edges
2016 .iter()
2017 .filter(|edge| !edge.degenerate && uses.get(&edge.id) == Some(&1))
2018 .count()
2019}
2020
2021fn body_volume(solid: &BrepSolid) -> Option<f64> {
2023 if solid.shells.is_empty() {
2024 return Some(0.0);
2025 }
2026 solid_signed_volume(solid).ok().map(f64::abs)
2027}
2028
2029struct InclusionExclusion {
2032 formula: &'static str,
2035 reading: &'static str,
2037 read: f64,
2039 expected: f64,
2041}
2042
2043fn isotropic_chart_identity(
2052 first: &BrepSolid,
2053 second: &BrepSolid,
2054 rescaled_first: &BrepSolid,
2055 rescaled_second: &BrepSolid,
2056 operation: BooleanOperation,
2057 options: &BooleanOptions,
2058 result: &BrepSolid,
2059) -> Result<(), String> {
2060 let _caller = crate::mass_caller("boolean.isotropic_chart_identity");
2061 let va = solid_signed_volume(first).ok().map(f64::abs);
2062 let vb = solid_signed_volume(second).ok().map(f64::abs);
2063 let volume = body_volume(result).ok_or("its body has no volume")?;
2064 if let (Some(va), Some(vb)) = (va, vb) {
2065 if !volume_within_csg_bounds(operation, va, vb, volume) {
2066 return Err(format!("volume {volume:.9} outside the CSG bound of {va:.9} and {vb:.9}"));
2067 }
2068 }
2069 let identity = inclusion_exclusion_volume(first, second, operation, options, va, vb, false)
2070 .or_else(|| isotropic_chart::with_active(|| inclusion_exclusion_volume(rescaled_first, rescaled_second, operation, options, va, vb, false)))
2071 .ok_or("no exact-lane boolean of the operands clears to read the inclusion-exclusion identity")?;
2072 let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * identity.expected.abs());
2073 if (volume - identity.expected).abs() > bar {
2074 return Err(format!(
2075 "volume {volume:.9} against the identity {} = {:.9} (the {} reads {:.9}), bar {bar:.3e}",
2076 identity.formula, identity.expected, identity.reading, identity.read
2077 ));
2078 }
2079 Ok(())
2080}
2081
2082fn inclusion_exclusion_volume(
2093 first: &BrepSolid,
2094 second: &BrepSolid,
2095 operation: BooleanOperation,
2096 options: &BooleanOptions,
2097 va: Option<f64>,
2098 vb: Option<f64>,
2099 own_first: bool,
2100) -> Option<InclusionExclusion> {
2101 use BooleanOperation::{Intersect, Subtract, Union};
2102 let (va, vb) = (va?, vb?);
2103 let own = match operation {
2104 Intersect => (Intersect, false, "first ∩ second"),
2105 Union => (Union, false, "first ∪ second"),
2106 Subtract => (Subtract, false, "first − second"),
2107 };
2108 let readings = [
2109 (Intersect, false, "first ∩ second"),
2110 (Intersect, true, "second ∩ first"),
2111 (Union, false, "first ∪ second"),
2112 (Union, true, "second ∪ first"),
2113 (Subtract, false, "first − second"),
2114 (Subtract, true, "second − first"),
2115 ];
2116 let own_reading = own_first.then_some(own);
2117 let leading = usize::from(own_first);
2118 for (index, (other, swapped, reading)) in own_reading.into_iter().chain(readings).enumerate() {
2119 if index >= leading && !swapped && std::mem::discriminant(&other) == std::mem::discriminant(&operation) {
2120 continue;
2121 }
2122 let (x, y) = if swapped { (second, first) } else { (first, second) };
2123 let Some(read) = boolean_operation_with_diagnostics(x, y, other, options)
2124 .ok()
2125 .and_then(|outcome| body_volume(&outcome.value))
2126 else {
2127 continue;
2128 };
2129 let intersection = match (other, swapped) {
2130 (Intersect, _) => read,
2131 (Union, _) => va + vb - read,
2132 (Subtract, false) => va - read,
2133 (Subtract, true) => vb - read,
2134 };
2135 let (formula, expected) = match operation {
2136 Intersect => ("V(first ∩ second)", intersection),
2137 Union => ("V(first) + V(second) − V(first ∩ second)", va + vb - intersection),
2138 Subtract => ("V(first) − V(first ∩ second)", va - intersection),
2139 };
2140 return Some(InclusionExclusion { formula, reading, read, expected });
2141 }
2142 None
2143}
2144
2145fn planar_operand_off_its_plane(
2154 first: &BrepSolid,
2155 second: &BrepSolid,
2156 options: &BooleanOptions,
2157) -> Option<(u8, u64, f64, f64)> {
2158 let policy = options
2159 .tolerances
2160 .clone()
2161 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
2162 let weld = crate::tolerance::assembler_weld(policy.model);
2163 let mut worst: Option<(u8, u64, f64)> = None;
2164 for (operand, solid) in [(0u8, first), (1u8, second)] {
2165 let vertex_point = |id: u64| solid.vertices.iter().find(|v| v.id == id).map(|v| v.point);
2166 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2167 let Some(crate::AnalyticSurface::Plane {
2168 origin,
2169 u_dir,
2170 v_dir,
2171 ..
2172 }) = face.surface.analytic()
2173 else {
2174 continue;
2175 };
2176 let [loop_record] = face.loops.as_slice() else {
2177 continue;
2178 };
2179 let Ok(normal) = u_dir.cross(*v_dir).normalized() else {
2180 continue;
2181 };
2182 let mut off_plane = 0.0f64;
2183 let mut straight = true;
2184 for coedge in &loop_record.coedges {
2185 let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else {
2186 straight = false;
2187 break;
2188 };
2189 let (Some(start), Some(end)) =
2190 (vertex_point(edge.start_vertex_id), vertex_point(edge.end_vertex_id))
2191 else {
2192 straight = false;
2193 break;
2194 };
2195 let chord = end.sub(start);
2196 let length = chord.length();
2197 if edge.degenerate || length <= weld {
2198 straight = false;
2199 break;
2200 }
2201 let direction = chord.scale(1.0 / length);
2202 for fraction in [0.25, 0.5, 0.75] {
2203 let Ok(point) = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction) else {
2204 straight = false;
2205 break;
2206 };
2207 let delta = point.sub(start);
2208 let along = delta.dot(direction);
2209 if delta.sub(direction.scale(along)).length() > weld
2210 || along < -weld
2211 || along > length + weld
2212 {
2213 straight = false;
2214 break;
2215 }
2216 }
2217 if !straight {
2218 break;
2219 }
2220 off_plane = off_plane.max(start.sub(*origin).dot(normal).abs());
2221 }
2222 if straight && off_plane > weld && worst.is_none_or(|(_, _, gap)| off_plane > gap) {
2223 worst = Some((operand, face.id, off_plane));
2224 }
2225 }
2226 }
2227 worst.map(|(operand, face_id, gap)| (operand, face_id, gap, weld))
2228}
2229
2230fn volume_within_csg_bounds(operation: BooleanOperation, va: f64, vb: f64, vr: f64) -> bool {
2233 let slack = 1e-2 * (va + vb).max(1.0);
2234 match operation {
2235 BooleanOperation::Union => vr >= va.max(vb) - slack && vr <= va + vb + slack,
2237 BooleanOperation::Subtract => vr <= va + slack && vr >= -slack,
2239 BooleanOperation::Intersect => vr <= va.min(vb) + slack && vr >= -slack,
2241 }
2242}
2243
2244fn reverse_fragment(fragment: &mut FaceFragmentRecord) -> Result<(), KernelRefusal> {
2271 fragment.same_sense = !fragment.same_sense;
2272 for loop_record in &mut fragment.loops {
2273 loop_record.coedges.reverse();
2274 for coedge in &mut loop_record.coedges {
2275 coedge.forward = !coedge.forward;
2276 coedge.pcurve = coedge.pcurve.reversed().or_refuse(KernelStage::Validate, "reversed")?;
2277 }
2278 }
2279 Ok(())
2280}
2281
2282fn build_nary_imprint(
2291 operands: &[BrepSolid],
2292 options: &ImprintOptions,
2293) -> Result<(ImprintResultRecord, Vec<(FaceKey, FaceKey)>), KernelRefusal> {
2294 let mut section_evidence = false;
2295 let mut cosurface: Vec<(FaceKey, FaceKey)> = Vec::new();
2296 let mut vertices: Vec<ImprintVertex> = Vec::new();
2297 let mut pieces: Vec<ImprintPieceRecord> = Vec::new();
2298 let mut by_face: HashMap<(u8, u64), Vec<u64>> = HashMap::default();
2299 let mut edge_splits: HashMap<(u8, u64), Vec<f64>> = HashMap::default();
2300 let mut next_vertex_id: u64 = 1;
2301 let mut next_piece_id: u64 = 1;
2302
2303 let profile = crate::profile::profile_enabled();
2305 let (mut empty_pairs, mut empty_ms, mut full_pairs, mut full_ms) = (0usize, 0.0f64, 0usize, 0.0f64);
2306 for i in 0..operands.len() {
2307 for j in (i + 1)..operands.len() {
2308 let pair_started = profile.then(web_time::Instant::now);
2309 let pair = build_imprints(&operands[i], &operands[j], options)?;
2310 if let Some(started) = pair_started {
2311 let ms = started.elapsed().as_secs_f64() * 1000.0;
2312 if pair.pieces.is_empty() && pair.vertices.is_empty() && pair.edge_splits.is_empty() {
2313 empty_pairs += 1;
2314 empty_ms += ms;
2315 } else {
2316 full_pairs += 1;
2317 full_ms += ms;
2318 }
2319 }
2320 let remap = |operand: u8| -> u8 {
2321 if operand == 0 {
2322 i as u8
2323 } else {
2324 j as u8
2325 }
2326 };
2327
2328 section_evidence = section_evidence || pair.section_evidence;
2329 for (first, second) in &pair.cosurface_pairs {
2330 let global = |key: &FaceKey| FaceKey { operand: remap(key.operand), face_id: key.face_id };
2331 cosurface.push((global(first), global(second)));
2332 }
2333 let mut vertex_map: HashMap<u64, u64> = HashMap::default();
2334 for vertex in &pair.vertices {
2335 let global = next_vertex_id;
2336 next_vertex_id += 1;
2337 vertex_map.insert(vertex.id, global);
2338 vertices.push(ImprintVertex {
2339 id: global,
2340 point: vertex.point,
2341 });
2342 }
2343
2344 let mut piece_map: HashMap<u64, u64> = HashMap::default();
2345 for piece in &pair.pieces {
2346 let global = next_piece_id;
2347 next_piece_id += 1;
2348 piece_map.insert(piece.id, global);
2349 let mut mapped = piece.clone();
2350 mapped.id = global;
2351 mapped.start_vertex_id = *vertex_map
2352 .get(&piece.start_vertex_id)
2353 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2354 mapped.end_vertex_id = *vertex_map
2355 .get(&piece.end_vertex_id)
2356 .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2357 for pcurve in &mut mapped.pcurves {
2358 pcurve.operand = remap(pcurve.operand);
2359 }
2360 mapped.support_faces = [
2361 FaceKey {
2362 operand: remap(piece.support_faces[0].operand),
2363 face_id: piece.support_faces[0].face_id,
2364 },
2365 FaceKey {
2366 operand: remap(piece.support_faces[1].operand),
2367 face_id: piece.support_faces[1].face_id,
2368 },
2369 ];
2370 pieces.push(mapped);
2371 }
2372
2373 for entry in &pair.by_face {
2374 let list = by_face
2375 .entry((remap(entry.operand), entry.face_id))
2376 .or_default();
2377 for piece_id in &entry.piece_ids {
2378 let global = *piece_map.get(piece_id).ok_or_else(|| {
2379 KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: by_face references unknown piece")
2380 })?;
2381 list.push(global);
2382 }
2383 }
2384
2385 for split in &pair.edge_splits {
2386 edge_splits
2387 .entry((remap(split.operand), split.edge_id))
2388 .or_default()
2389 .extend(split.parameters.iter().copied());
2390 }
2391 }
2392 }
2393 if profile {
2394 profile_line!("boolean.nary.imprint_pairs empty={empty_pairs} empty_ms={empty_ms:.2} full={full_pairs} full_ms={full_ms:.2}");
2395 }
2396
2397 Ok((ImprintResultRecord {
2398 faces_in_unproved_pairs: None,
2399 vertices,
2400 pieces,
2401 tangent_nodes: Vec::new(),
2402 barrier_edges: Vec::new(),
2403 section_evidence,
2404 cosurface_pairs: Vec::new(),
2405 operand_sliver_regions: Vec::new(),
2406 tangent_sections: Vec::new(),
2407 by_face: by_face
2408 .into_iter()
2409 .map(|((operand, face_id), piece_ids)| FaceImprints {
2410 operand,
2411 face_id,
2412 piece_ids,
2413 })
2414 .collect(),
2415 edge_splits: edge_splits
2416 .into_iter()
2417 .map(|((operand, edge_id), parameters)| EdgeSplitRecord {
2418 operand,
2419 edge_id,
2420 parameters,
2421 })
2422 .collect(),
2423 }, cosurface))
2424}
2425
2426pub fn boolean_operation_nary(
2437 operands: &[BrepSolid],
2438 operation: BooleanOperation,
2439) -> Result<BrepSolid, KernelRefusal> {
2440 boolean_operation_nary_with_options(operands, operation, &BooleanOptions::default())
2441}
2442
2443pub fn boolean_operation_nary_with_options(
2449 operands: &[BrepSolid],
2450 operation: BooleanOperation,
2451 options: &BooleanOptions,
2452) -> Result<BrepSolid, KernelRefusal> {
2453 let most = nary_chunk();
2458 if operands.len() > most && nary_chunks_on() {
2459 let mut whole = boolean_operation_nary_with_options(&operands[..most], operation, options)?;
2460 for chunk in operands[most..].chunks(most - 1) {
2461 if let [only] = chunk {
2464 whole = boolean_operation(&whole, only, operation, options)?;
2465 continue;
2466 }
2467 let mut next = Vec::with_capacity(chunk.len() + 1);
2468 next.push(whole);
2469 next.extend_from_slice(chunk);
2470 whole = boolean_operation_nary_with_options(&next, operation, options)?;
2471 }
2472 return Ok(whole);
2473 }
2474 let arranged = boolean_operation_nary_arranged(operands, operation, options);
2475 match arranged {
2476 Err(error) if nary_sequential_fallback_enabled() && operands.len() > 2 && error.message.contains("boolean assembly") => {
2477 let mut whole = operands[0].clone();
2480 for operand in &operands[1..] {
2481 whole = match boolean_operation(&whole, operand, operation, options) {
2482 Ok(solid) => solid,
2483 Err(_) => return Err(error),
2484 };
2485 }
2486 Ok(whole)
2487 }
2488 other => other,
2489 }
2490}
2491
2492const NARY_MOST: usize = 255;
2501
2502fn nary_chunk() -> usize {
2505 NARY_MOST
2506}
2507
2508
2509fn nary_chunks_on() -> bool {
2512 crate::switch!("BREP_NARY_CHUNKS", true)
2513}
2514
2515fn nary_scoped_on() -> bool {
2528 crate::switch!("BREP_NARY_SCOPED", true)
2529}
2530
2531fn nary_sequential_fallback_enabled() -> bool {
2532 crate::switch!("BREP_NARY_SEQUENTIAL_FALLBACK", true)
2533}
2534
2535fn boolean_operation_nary_arranged(
2536 operands: &[BrepSolid],
2537 operation: BooleanOperation,
2538 options: &BooleanOptions,
2539) -> Result<BrepSolid, KernelRefusal> {
2540 if operands.len() > 1 {
2541 if let Some(scaled) = WorkingScale::of(&operands.iter().collect::<Vec<_>>(), options)? {
2542 return scaled.run(
2543 || boolean_operation_nary_with_options(operands, operation, options),
2544 || boolean_operation_nary_with_options(&scaled.solids, operation, &scaled.options)
2545 .map_err(|error| scaled.refusal(error))
2546 .and_then(|solid| scaled.back(&solid)),
2547 );
2548 }
2549 }
2550 if operands.is_empty() {
2551 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: no operands provided"));
2552 }
2553 if operands.len() == 1 {
2554 return Ok(operands[0].clone());
2555 }
2556 if operands.len() > nary_chunk() {
2557 return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: at most 255 operands supported"));
2558 }
2559 if let Some(aligned) = ball_align::align_balls_nary(operands, operation, options.tolerance) {
2562 return boolean_operation_nary_with_options(&aligned, operation, options);
2563 }
2564 let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
2565
2566 let mut policy = KernelTolerances::for_solid(&operands[0], options.tolerance);
2570 for operand in &operands[1..] {
2571 let candidate = KernelTolerances::for_solid(operand, options.tolerance);
2572 if candidate.sew_search > policy.sew_search {
2573 policy = candidate;
2574 }
2575 }
2576 policy.check().or_input(KernelStage::Collect, "tolerances")?;
2577 let tolerance = policy.model;
2578
2579 let nary_clock = NaryClock::start();
2582 let mut healed = operands.to_vec();
2583 let refit_scopes: Option<Vec<std::collections::HashSet<u64>>> = (nary_scoped_on() && crate::switch!("BREP_NARY_SCOPED_REFIT", true)).then(|| {
2588 let bounds: Vec<Option<crate::Aabb>> = operands
2589 .iter()
2590 .map(|operand| crate::fragment::bounded_carriers(operand).then(|| operand_bounds(operand)))
2591 .collect();
2592 operands
2593 .iter()
2594 .enumerate()
2595 .map(|(index, operand)| {
2596 operand
2597 .shells
2598 .iter()
2599 .flat_map(|shell| &shell.faces)
2600 .filter(|face| {
2601 !bounds.iter().enumerate().filter(|(other, _)| *other != index).all(|(_, other)| {
2602 other.as_ref().is_some_and(|other| crate::fragment::face_separated(face, *other, policy.sew_search))
2603 })
2604 })
2605 .map(|face| face.id)
2606 .collect()
2607 })
2608 .collect()
2609 });
2610 for (index, operand) in healed.iter_mut().enumerate() {
2611 crate::heal::heal_operands(operand, &policy)?;
2612 nary_clock.lap("nary.heal.operands_ms");
2613 match &refit_scopes {
2616 Some(scopes) => crate::heal::with_refit_face_scope(scopes[index].clone(), || crate::heal::refit_inherited_trims_reused(operand, &policy))?,
2617 None => crate::heal::refit_inherited_trims_reused(operand, &policy)?,
2618 }
2619 nary_clock.lap("nary.heal.refit_ms");
2620 normalize_operand_band_seams(operand)?;
2623 nary_clock.lap("nary.heal.seams_ms");
2624 }
2625
2626 let mut imprint_options = options.imprint.clone();
2628 imprint_options.tolerance = tolerance;
2629 let (imprint, cosurface) = build_nary_imprint(&healed, &imprint_options)?;
2630 nary_clock.lap("nary.imprint_ms");
2631
2632 let mut split = Vec::with_capacity(healed.len());
2634 for (index, operand) in healed.iter().enumerate() {
2635 split.push(apply_edge_splits(operand, index as u8, &imprint)?);
2636 }
2637 let mut fragments = Vec::with_capacity(split.len());
2638 for (index, solid) in split.iter().enumerate() {
2639 fragments.push(fragment_solid(solid, index as u8, &imprint)?);
2640 }
2641 nary_clock.lap("nary.split_fragment_ms");
2642
2643 let selected = select_fragments_nary(&fragments, &healed, operation, tolerance, debug)?;
2645 nary_clock.lap("nary.select_ms");
2646
2647 let solids: HashMap<u8, &BrepSolid> = split
2649 .iter()
2650 .enumerate()
2651 .map(|(index, solid)| (index as u8, solid))
2652 .collect();
2653 let solid = if nary_scoped_on() {
2654 let prepared: Vec<&BrepSolid> = healed.iter().collect();
2658 let touch = touch::TouchCensus::build_all(&prepared, &imprint, &cosurface);
2659 assemble::assemble_fragments_inherited_scoped(selected, &solids, &imprint, tolerance, &touch)?
2660 } else {
2661 assemble_fragments(selected, &solids, &imprint, tolerance)?
2662 };
2663 nary_clock.lap("nary.assemble_ms");
2664 let solid = if options.merge_coplanar_faces
2665 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
2666 {
2667 let merged = merge_same_surface_faces_excluding(
2668 &solid,
2669 tolerance,
2670 &options.keep_unmerged_name_substrs,
2671 )?;
2672 let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
2673 rejoin::rejoin_unless_referenced(merged, options, tolerance)
2674 } else {
2675 solid
2676 };
2677 nary_clock.lap("nary.merge_ms");
2678 let validation = solid.validate_detailed(&policy);
2679 nary_clock.lap("nary.validate_ms");
2680 if !validation.issues.is_empty() {
2681 return Err(KernelRefusal::new(
2682 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
2683 KernelStage::Validate,
2684 format!(
2685 "boolean_operation_nary: invalid result: {:?}",
2686 validation.issues
2687 )));
2688 }
2689 if debug {
2690 if let Ok(report) =
2691 crate::oracle::boolean_semantic_disagreement_nary(&healed, operation, &solid, 300)
2692 {
2693 if report.is_flagged() {
2694 eprintln!(
2695 "[oracle] n-ary semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
2696 report.disagreement_rate,
2697 report.disagreements.len(),
2698 report.considered,
2699 report.sample_disagreement()
2700 );
2701 }
2702 }
2703 }
2704 Ok(solid)
2705}
2706
2707fn attribute_to_tangent_node(error: KernelRefusal, nodes: &[Vec3]) -> KernelRefusal {
2738 let Some(node) = nodes.first() else {
2739 return error;
2740 };
2741 if !error.class.perturbation_eligible()
2742 || matches!(error.class, RefusalClass::TangentNodeSingularity)
2743 {
2744 return error;
2745 }
2746 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
2747 eprintln!(
2748 "boolean: tear downstream of the tangent node at ({:.6},{:.6},{:.6}) attributed to it; the stage read: {}",
2749 node.x, node.y, node.z, error.message
2750 );
2751 }
2752 KernelRefusal::new(
2753 RefusalClass::TangentNodeSingularity,
2754 error.stage,
2755 format!(
2756 "boolean: unsupported singular/tangent-node surface intersection \
2757 at the tangent node at ({:.6},{:.6},{:.6}): the section through it did not \
2758 assemble into a closed shell",
2759 node.x, node.y, node.z
2760 ),
2761 )
2762}
2763
2764pub fn attribute_to_tangent_section(
2786 error: KernelRefusal,
2787 sections: &[crate::imprint::TangentSectionRecord],
2788 origins: &[FaceKey],
2789) -> KernelRefusal {
2790 if sections.is_empty()
2791 || !error.class.perturbation_eligible()
2792 || matches!(error.class, RefusalClass::TangentNodeSingularity)
2793 {
2794 return error;
2795 }
2796 let named = refusal_result_faces(&error.message)
2797 .into_iter()
2798 .filter_map(|id| origins.get(id.checked_sub(1)? as usize).copied())
2799 .collect::<Vec<FaceKey>>();
2800 let involving = |fallback: bool| {
2804 sections.iter().find(|section| {
2805 section.grazing.is_empty() != fallback && named.iter().any(|face| section.faces.contains(face))
2806 })
2807 };
2808 let Some(section) = involving(false).or_else(|| involving(true)) else {
2809 return error;
2810 };
2811 let at = |point: Vec3| {
2814 let shown = |value: f64| if value.abs() < 5e-7 { 0.0 } else { value };
2815 format!("({:.6},{:.6},{:.6})", shown(point.x), shown(point.y), shown(point.z))
2816 };
2817 let pierces = (!section.grazing.is_empty()).then(|| {
2823 let shown = section.grazing.len().min(4);
2824 let mut listed = section.grazing[..shown]
2825 .iter()
2826 .map(|(point, tangency)| format!("{} at |tan·n| = {tangency:.4}", at(*point)))
2827 .collect::<Vec<_>>()
2828 .join(", ");
2829 if section.grazing.len() > shown {
2830 listed.push_str(&format!(" and {} more", section.grazing.len() - shown));
2831 }
2832 listed
2833 });
2834 let pierce_only = section.pierce_only();
2835 let shape = if let (true, Some(pierces)) = (pierce_only, pierces.as_deref()) {
2836 format!(
2837 "cross at a grazing angle: a trim edge pierces the other carrier inside both \
2838 trims at {pierces}, below the marcher's start gate, and no transverse section was \
2839 marched between the pierces — a near-tangent crossing born on a tangent contact \
2840 (a third-order singularity) the imprint does not build yet"
2841 )
2842 } else if section.planar {
2843 format!(
2844 "touch along a tangent curve from {} to {} (length {:.6}, {} stations{}) which the \
2845 imprint does not build yet",
2846 at(section.start),
2847 at(section.end),
2848 section.length,
2849 section.stations,
2850 if section.closed { ", closed" } else { "" }
2851 )
2852 } else {
2853 format!(
2854 "touch along a curve through {} with neither carrier planar, a curved/curved \
2855 tangent contact the lane does not trace yet",
2856 at(section.start)
2857 )
2858 };
2859 let shape = match (pierce_only, pierces) {
2860 (false, Some(pierces)) => format!(
2861 "{shape}; a trim edge also pierces the other carrier inside both trims at {pierces}, \
2862 below the marcher's start gate, with no transverse section marched"
2863 ),
2864 _ => shape,
2865 };
2866 let involved = named
2867 .iter()
2868 .filter(|face| section.faces.contains(face))
2869 .map(|face| format!("{}/{}", face.operand, face.face_id))
2870 .collect::<Vec<_>>()
2871 .join(", ");
2872 KernelRefusal::new(
2873 RefusalClass::TangentNodeSingularity,
2874 error.stage,
2875 format!(
2876 "boolean: unsupported tangent-curve surface intersection between faces {}/{} and {}/{}: \
2877 the carriers {shape}; the refusal names face(s) {involved} the contact involves; {}",
2878 section.first.operand, section.first.face_id, section.second.operand, section.second.face_id,
2879 error.message
2880 ),
2881 )
2882}
2883
2884pub fn refusal_result_faces(message: &str) -> Vec<u64> {
2889 let mut ids = Vec::new();
2890 let digits_after = |text: &str| -> Option<u64> {
2891 let end = text.find(|c: char| !c.is_ascii_digit()).unwrap_or(text.len());
2892 text[..end].parse().ok()
2893 };
2894 for (index, _) in message.match_indices("face ") {
2895 if let Some(id) = digits_after(&message[index + "face ".len()..]) {
2896 ids.push(id);
2897 }
2898 }
2899 if let Some(start) = message.find("on faces [") {
2900 let rest = &message[start + "on faces [".len()..];
2901 let list = &rest[..rest.find(']').unwrap_or(rest.len())];
2902 for entry in list.split(", ") {
2903 let entry = entry.trim_start();
2904 if let Some(id) = digits_after(entry) {
2905 if entry[id.to_string().len()..].starts_with(" '") {
2906 ids.push(id);
2907 }
2908 }
2909 }
2910 }
2911 ids.sort_unstable();
2912 ids.dedup();
2913 ids
2914}
2915
2916pub fn boolean_operation_with_diagnostics(
2917 first: &BrepSolid,
2918 second: &BrepSolid,
2919 operation: BooleanOperation,
2920 options: &BooleanOptions,
2921) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2922 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2923 return scaled.run(
2924 || boolean_operation_with_diagnostics(first, second, operation, options),
2925 || {
2926 let mut outcome = boolean_operation_with_diagnostics(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
2927 .map_err(|error| scaled.refusal(error))?;
2928 outcome.value = scaled.back(&outcome.value)?;
2929 outcome.diagnostics.count_n("working_scale.fired", 1);
2930 outcome.diagnostics.measure_max("working_scale.factor", scaled.factor);
2931 Ok(outcome)
2932 },
2933 );
2934 }
2935 let _account = profile::Scope::new("boolean.other");
2936 let (first_aligned, second_aligned) = ball_align::align_balls(first, second, operation, options.tolerance);
2939 let (first, second) = (first_aligned.as_ref(), second_aligned.as_ref());
2940 let closed_inputs = matches!(std::env::var("BREP_CLOSED_OPERAND_INPUT").as_deref(), Err(_) | Ok("1") | Ok("on"));
2941 if let (true, Some(later)) = (reseat::seam_reseat_enabled(), &options.seam_reseat_later_references) {
2942 let started = Instant::now();
2943 let (first, second) = reseat::reseat_tangent_seams(first, second, later, options.tolerance);
2944 profile_stage("seam_prepare_ms", started.elapsed().as_secs_f64() * 1000.0);
2945 return boolean_operation_with_diagnostics_impl(&first, &second, operation, options, closed_inputs).map(without_sliver_shells);
2946 }
2947 let cylinders = reseat::seam_reseat_cylinders_mode();
2950 if reseat::seam_reseat_enabled() && cylinders != crate::env_read::Mode::Off {
2951 let kinds = reseat::ContactKinds { planes: false, cylinders: true };
2952 let volume = |result: &Result<KernelOutcome<BrepSolid>, KernelRefusal>| {
2953 result.as_ref().ok().and_then(|outcome| crate::solid_mass_properties(&outcome.value).ok()).map(|mass| mass.volume)
2954 };
2955 if reseat::seam_reseat_retry_enabled() {
2956 let plain = boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells);
2962 if plain.is_ok() {
2963 return plain;
2964 }
2965 let (reseated_first, reseated_second) = reseat::reseat_tangent_seams_of(first, second, &[], options.tolerance, kinds);
2966 let moved = matches!(reseated_first, std::borrow::Cow::Owned(_)) || matches!(reseated_second, std::borrow::Cow::Owned(_));
2967 if !moved {
2968 return plain;
2969 }
2970 let reseated = crate::imprint::driver::with_tangent_cylinder_filter(|| {
2971 boolean_operation_with_diagnostics_impl(&reseated_first, &reseated_second, operation, options, closed_inputs).map(without_sliver_shells)
2972 });
2973 if cylinders == crate::env_read::Mode::Check {
2974 eprintln!(
2975 "boolean.seam_reseat_cylinders check: plain refused, reseated retry {} volume {:?}",
2976 if reseated.is_ok() { "built" } else { "refused" },
2977 volume(&reseated)
2978 );
2979 return plain;
2980 }
2981 return match reseated {
2982 Ok(mut outcome) => {
2983 outcome.diagnostics.count_n("seam_reseat_cylinders.retry_built", 1);
2984 Ok(outcome)
2985 }
2986 Err(_) => plain,
2987 };
2988 }
2989 let (reseated_first, reseated_second) = reseat::reseat_tangent_seams_of(first, second, &[], options.tolerance, kinds);
2990 let moved = matches!(reseated_first, std::borrow::Cow::Owned(_)) || matches!(reseated_second, std::borrow::Cow::Owned(_));
2991 if moved {
2992 let reseated = boolean_operation_with_diagnostics_impl(&reseated_first, &reseated_second, operation, options, closed_inputs).map(without_sliver_shells);
2993 if cylinders == crate::env_read::Mode::On {
2994 return reseated;
2995 }
2996 let plain = boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells);
2997 eprintln!(
2998 "boolean.seam_reseat_cylinders check: plain {} volume {:?}, reseated {} volume {:?}",
2999 if plain.is_ok() { "built" } else { "refused" },
3000 volume(&plain),
3001 if reseated.is_ok() { "built" } else { "refused" },
3002 volume(&reseated)
3003 );
3004 return plain;
3005 }
3006 }
3007 boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells)
3008}
3009
3010fn without_sliver_shells(mut outcome: KernelOutcome<BrepSolid>) -> KernelOutcome<BrepSolid> {
3012 let dropped = drop_sliver_shells(&mut outcome.value);
3013 if dropped > 0 {
3014 outcome.diagnostics.count_n("sliver_shell.dropped", dropped as u64);
3015 }
3016 outcome
3017}
3018
3019pub fn boolean_operation_with_diagnostics_impl(
3020 first: &BrepSolid,
3021 second: &BrepSolid,
3022 operation: BooleanOperation,
3023 options: &BooleanOptions,
3024 closed_inputs: bool,
3025) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
3026 let _coedge_memo = crate::topology::CoedgeMemoScope::open(true);
3029 if matches!(operation, BooleanOperation::Intersect)
3032 && [first, second].iter().any(|body| body.kind == crate::BodyKind::Sheet)
3033 && match std::env::var("BREP_SHEET_TRIM").as_deref() {
3034 Ok("1") => true,
3035 Ok("0") => false,
3036 _ => options.sheet_trim,
3037 }
3038 {
3039 return sheet::trim(first, second, options);
3040 }
3041 if matches!(operation, BooleanOperation::Union | BooleanOperation::Subtract) {
3050 if let Some(operand) = [first, second]
3051 .iter()
3052 .position(|solid| solid.kind == crate::BodyKind::Sheet)
3053 {
3054 return Err(KernelRefusal::input(
3055 KernelStage::Collect,
3056 "sheet_operand",
3057 format!(
3058 "boolean: operand {operand} is a Sheet, which encloses no solid; union and \
3059 subtract of a sheet are refused; Intersect trims a Sheet by a Solid"
3060 ),
3061 ));
3062 }
3063 }
3064 let mut outcome = boolean_operation_with_diagnostics_core(first, second, operation, options)?;
3070 let closure_started = closed_inputs.then(Instant::now);
3071 if closed_inputs {
3072 for (operand, solid) in [first, second].into_iter().enumerate() {
3073 let open = one_use_edges(solid);
3074 if open > 0 {
3075 return Err(KernelRefusal::input(KernelStage::Collect, "operand_closure", format!(
3076 "boolean: operand {operand} is not a closed shell: {open} of its edges bound only one face, so its inside is undefined"
3077 )));
3078 }
3079 }
3080 }
3081 if let Some(started) = closure_started {
3082 let ms = started.elapsed().as_secs_f64() * 1000.0;
3083 profile_stage("operand_closure_ms", ms);
3084 outcome.diagnostics.measure_max("timing.operand_closure_ms", ms);
3085 }
3086 Ok(outcome)
3087}
3088
3089fn boolean_operation_with_diagnostics_core(
3090 first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions,
3091) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
3092
3093 if let Some(offset) = crate::recentre::control_offset_at_entry() {
3096 return boolean_operation_with_diagnostics_at_offset(first, second, operation, options, offset);
3097 }
3098 let mut bounds = operand_bounds(first);
3101 bounds.include(operand_bounds(second));
3102 if let Some(offset) = crate::recentre::guard_offset(bounds) {
3103 crate::recentre::profile_fired("boolean", offset, bounds);
3104 let mut outcome = boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Guard)?;
3105 outcome.diagnostics.count_n("recentre.fired", 1);
3106 outcome.diagnostics.measure_max("recentre.distance", offset.length());
3107 return Ok(outcome);
3108 }
3109 let mut tangent_nodes = Vec::new();
3110 let (mut outcome, soundness_candidates) =
3111 boolean_pipeline(first, second, operation, options, &mut tangent_nodes)
3112 .map_err(|error| attribute_to_tangent_node(error, &tangent_nodes))?;
3113 let stage_started = Instant::now();
3126 let accepted = match &soundness_candidates {
3127 Some(candidates) => crate::accept_sound_against_scoped(&[first, second], outcome.value, "boolean", candidates),
3130 None => crate::accept_sound_against(&[first, second], outcome.value, "boolean"),
3131 };
3132 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3133 profile_stage("soundness_ms", stage_ms);
3134 outcome.diagnostics.measure_max("timing.soundness_ms", stage_ms);
3135 outcome.value = accepted?;
3136 Ok(outcome)
3137}
3138
3139pub fn boolean_operation_with_diagnostics_at_offset(
3143 first: &BrepSolid,
3144 second: &BrepSolid,
3145 operation: BooleanOperation,
3146 options: &BooleanOptions,
3147 offset: Vec3,
3148) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
3149 boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Control)
3150}
3151
3152fn boolean_translated(
3154 first: &BrepSolid,
3155 second: &BrepSolid,
3156 operation: BooleanOperation,
3157 options: &BooleanOptions,
3158 offset: Vec3,
3159 kind: crate::recentre::EntryKind,
3160) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
3161 let _entry = crate::recentre::TranslatedEntry::open(kind);
3162 let translate = |solid: &BrepSolid, offset: Vec3| {
3163 crate::recentre::translate_solid(solid, offset).map_err(|message| {
3164 KernelRefusal::internal(
3165 KernelStage::Collect,
3166 "translation_control",
3167 format!("boolean: the translation control could not move an operand: {message}"),
3168 )
3169 })
3170 };
3171 let moved_first = translate(first, offset)?;
3172 let moved_second = translate(second, offset)?;
3173 let outcome = boolean_operation_with_diagnostics(&moved_first, &moved_second, operation, options)?;
3174 let value = translate(&outcome.value, offset.scale(-1.0))?;
3175 Ok(KernelOutcome { value, diagnostics: outcome.diagnostics })
3176}
3177
3178struct NaryClock(Option<std::cell::Cell<web_time::Instant>>);
3181
3182impl NaryClock {
3183 fn start() -> Self {
3184 Self(crate::profile::profile_enabled().then(|| std::cell::Cell::new(web_time::Instant::now())))
3185 }
3186
3187 fn lap(&self, code: &str) {
3188 if let Some(cell) = &self.0 {
3189 let now = web_time::Instant::now();
3190 profile_stage(code, (now - cell.get()).as_secs_f64() * 1000.0);
3191 cell.set(now);
3192 }
3193 }
3194}
3195
3196fn profile_stage(code: &str, ms: f64) {
3200 let row = match code {
3201 "heal_ms" => Some("boolean.operand_prepare"),
3202 "imprint_ms" => Some("boolean.imprint"),
3203 "edge_split_ms" => Some("boolean.edge_split"),
3204 "fragment_ms" => Some("boolean.fragment"),
3205 "select_ms" => Some("boolean.select"),
3206 "assemble_ms" => Some("boolean.assemble"),
3207 "face_merge_ms" => Some("boolean.face_merge"),
3208 "soundness_ms" => Some("boolean.soundness"),
3209 "operand_closure_ms" => Some("boolean.operand_closure"),
3210 "seam_prepare_ms" => Some("boolean.seam_prepare"),
3211 "final_validate_ms" => Some("boolean.final_validate"),
3212 _ => None,
3213 };
3214 if let Some(row) = row { profile::record(row, ms); }
3215 if crate::profile::profile_enabled() {
3216 profile_line!("boolean.{code}={ms:.2}");
3217 }
3218}
3219
3220struct BooleanStageDump {
3225 directory: std::path::PathBuf,
3226 serial: usize,
3227}
3228
3229impl BooleanStageDump {
3230 fn open() -> Option<Self> {
3231 static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
3232 let directory = std::env::var("BREP_BOOLEAN_DUMP").ok().filter(|value| !value.is_empty())?;
3233 let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3234 Some(Self { directory: directory.into(), serial })
3235 }
3236
3237 fn write<T: Serialize + ?Sized>(&self, stage: &str, value: &T) {
3238 let path = self.directory.join(format!("{:03}-{stage}.json", self.serial));
3239 match serde_json::to_string(value) {
3240 Ok(text) => {
3241 if let Err(error) = std::fs::write(&path, text) {
3242 eprintln!("BREP_BOOLEAN_DUMP {}: {error}", path.display());
3243 }
3244 }
3245 Err(error) => eprintln!("BREP_BOOLEAN_DUMP {stage}: {error}"),
3246 }
3247 }
3248}
3249
3250pub fn boolean_policy(
3252 first: &BrepSolid,
3253 second: &BrepSolid,
3254 options: &BooleanOptions,
3255) -> Result<KernelTolerances, KernelRefusal> {
3256 let policy = options
3257 .tolerances
3258 .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
3259 policy.check().or_input(KernelStage::Collect, "tolerances")?;
3260 Ok(policy)
3261}
3262
3263fn prepared_operands(
3266 first: &BrepSolid,
3267 second: &BrepSolid,
3268 policy: &KernelTolerances,
3269) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
3270 let stage_started = Instant::now();
3279 let mut first_owned = first.clone();
3280 let mut second_owned = second.clone();
3281 crate::heal::heal_operands(&mut first_owned, policy)?;
3282 crate::heal::heal_operands(&mut second_owned, policy)?;
3283 profile_stage("heal.operands_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
3284 let refit_started = Instant::now();
3288 crate::heal::refit_inherited_trims_reused(&mut first_owned, policy)?;
3289 crate::heal::refit_inherited_trims_reused(&mut second_owned, policy)?;
3290 profile_stage("heal.refit_ms", refit_started.elapsed().as_secs_f64() * 1_000.0);
3291 if crate::profile::profile_enabled() {
3292 let (hits, misses) = crate::reading_memo::counts();
3293 profile_line!("boolean.reading_memo hits={hits} misses={misses}");
3294 let (served, stored) = crate::heal::refit_memo_counts_served_stored();
3295 profile_line!("boolean.refit_memo served={served} stored={stored}");
3296 let (served, stored, mismatches) = crate::heal::claim_record_memo_counts();
3297 profile_line!("boolean.claim_record_memo served={served} stored={stored} check_mismatches={mismatches}");
3298 }
3299 profile_stage("heal_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
3300 normalize_operand_band_seams(&mut first_owned)?;
3305 normalize_operand_band_seams(&mut second_owned)?;
3306 Ok((first_owned, second_owned))
3307}
3308
3309fn boolean_imprint_options(options: &BooleanOptions, tolerance: f64) -> ImprintOptions {
3310 let mut imprint_options = options.imprint.clone();
3311 imprint_options.tolerance = tolerance;
3312 imprint_options
3313}
3314
3315pub fn boolean_split_operands(
3325 first: &BrepSolid,
3326 second: &BrepSolid,
3327 options: &BooleanOptions,
3328) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
3329 if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
3330 return scaled.run(
3331 || boolean_split_operands(first, second, options),
3332 || {
3333 let (split_first, split_second) = boolean_split_operands(&scaled.solids[0], &scaled.solids[1], &scaled.options)
3334 .map_err(|error| scaled.refusal(error))?;
3335 Ok((scaled.back(&split_first)?, scaled.back(&split_second)?))
3336 },
3337 );
3338 }
3339 let policy = boolean_policy(first, second, options)?;
3340 let (first, second) = prepared_operands(first, second, &policy)?;
3341 let imprint = build_imprints(&first, &second, &boolean_imprint_options(options, policy.model))?;
3342 let (split_first, _) = apply_edge_splits_with_map(&first, 0, &imprint)?;
3343 let (split_second, _) = apply_edge_splits_with_map(&second, 1, &imprint)?;
3344 Ok((split_first, split_second))
3345}
3346
3347fn operand_bounds(solid: &BrepSolid) -> crate::Aabb {
3351 let mut bounds = crate::Aabb::from_points(solid.vertices.iter().map(|vertex| vertex.point));
3352 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
3353 match crate::Aabb::from_surface_controls(&face.surface) {
3354 Ok(face_bounds) => bounds.include(face_bounds),
3355 Err(_) => {
3356 return crate::Aabb {
3357 minimum: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
3358 maximum: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
3359 }
3360 }
3361 }
3362 }
3363 bounds
3364}
3365
3366fn line_or_point_contact(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
3372 apart_axes(bounds) >= 2 && plain_hull_solid(first) && plain_hull_solid(second)
3373}
3374
3375fn boxes_share_no_interior(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
3378 apart_axes(bounds) >= 1 && plain_hull_solid(first) && plain_hull_solid(second)
3379}
3380
3381fn apart_axes([a, b]: [crate::Aabb; 2]) -> usize {
3383 let apart = |a_min: f64, a_max: f64, b_min: f64, b_max: f64| a_max <= b_min || b_max <= a_min;
3384 [
3385 apart(a.minimum.x, a.maximum.x, b.minimum.x, b.maximum.x),
3386 apart(a.minimum.y, a.maximum.y, b.minimum.y, b.maximum.y),
3387 apart(a.minimum.z, a.maximum.z, b.minimum.z, b.maximum.z),
3388 ]
3389 .into_iter()
3390 .filter(|&apart| apart)
3391 .count()
3392}
3393
3394fn plain_hull_solid(solid: &BrepSolid) -> bool {
3396 solid.kind == crate::BodyKind::Solid
3397 && solid.cells.is_empty()
3398 && solid.shells.iter().flat_map(|shell| &shell.faces).all(|face| {
3399 face.surface.control_points.iter().flatten().all(|control| control.w > 0.0 && control.w.is_finite())
3400 })
3401}
3402
3403fn scope_proved_apart_on() -> bool {
3407 switch!(live "BREP_SCOPE_PROVED_APART", true)
3408}
3409
3410fn soundness_candidates(
3425 solid: &BrepSolid,
3426 scope: &AssemblyScope,
3427 bounds: [crate::Aabb; 2],
3428 band: f64,
3429 unproved: Option<&HashSet<crate::imprint::FaceKey>>,
3430) -> HashSet<u64> {
3431 let mut candidates = HashSet::default();
3432 for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
3433 if scope.examined.contains(&face.id) {
3434 candidates.insert(face.id);
3435 continue;
3436 }
3437 let Some(&operand) = scope.operand_of.get(&face.id) else {
3438 candidates.insert(face.id);
3439 continue;
3440 };
3441 let other = bounds[usize::from(operand == 0)];
3442 match crate::Aabb::from_surface_controls(&face.surface) {
3443 Ok(face_bounds) if !face_bounds.intersects(other, band) => {}
3444 _ => {
3445 let proved_clear = unproved.is_some_and(|unproved| {
3446 scope.source_of.get(&face.id).is_some_and(|key| !unproved.contains(key))
3447 });
3448 if !proved_clear {
3449 candidates.insert(face.id);
3450 }
3451 }
3452 }
3453 }
3454 candidates
3455}
3456
3457
3458fn touching_empty_enabled() -> bool {
3466 switch!("BREP_TOUCHING_EMPTY", true)
3467}
3468
3469thread_local! {
3470 static TOUCHING_PROOF: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3473}
3474
3475fn hair_deep_overlap(first: &BrepSolid, second: &BrepSolid, tolerance: f64) -> bool {
3482 use crate::AnalyticSurface as A;
3483 fn faces(solid: &BrepSolid) -> Vec<(&crate::AnalyticSurface, crate::spatial::Aabb, &crate::NurbsSurface, &crate::FaceRecord)> {
3484 solid
3485 .shells
3486 .iter()
3487 .flat_map(|shell| &shell.faces)
3488 .filter_map(|face| Some((face.surface.analytic()?, crate::Aabb::from_surface_controls(&face.surface).ok()?, &face.surface, face)))
3489 .collect()
3490 }
3491 let along = |surface: &crate::NurbsSurface, axis: Vec3| {
3493 surface.control_points.iter().flatten().filter_map(|control| control.point().ok()).fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), point| {
3494 let at = point.dot(axis);
3495 (low.min(at), high.max(at))
3496 })
3497 };
3498 let crossing = |distance: f64, ra: f64, rb: f64| {
3499 let outer = ra + rb - distance;
3500 let nested = distance - (ra - rb).abs();
3501 outer > tolerance && nested > tolerance
3502 };
3503 let boxes_overlap = |a: &crate::spatial::Aabb, b: &crate::spatial::Aabb| {
3504 (a.maximum.x.min(b.maximum.x) - a.minimum.x.max(b.minimum.x)) > tolerance
3505 && (a.maximum.y.min(b.maximum.y) - a.minimum.y.max(b.minimum.y)) > tolerance
3506 && (a.maximum.z.min(b.maximum.z) - a.minimum.z.max(b.minimum.z)) > tolerance
3507 };
3508 for (a, box_a, surface_a, face_a) in faces(first) {
3509 for (b, box_b, surface_b, face_b) in faces(second) {
3510 if !boxes_overlap(&box_a, &box_b) {
3511 continue;
3512 }
3513 match (a, b) {
3514 (A::RuledRevolution { frame: fa, rho0: a0, rho1: a1, .. }, A::RuledRevolution { frame: fb, rho0: b0, rho1: b1, .. })
3515 if (a0 - a1).abs() <= tolerance && (b0 - b1).abs() <= tolerance =>
3516 {
3517 let offset = fb.origin.sub(fa.origin);
3518 let normal = fa.axis.cross(fb.axis);
3519 if normal.length() <= 1e-12 {
3522 let (low_a, high_a) = along(surface_a, fa.axis);
3523 let (low_b, high_b) = along(surface_b, fa.axis);
3524 if high_a.min(high_b) - low_a.max(low_b) <= tolerance {
3525 continue;
3526 }
3527 }
3528 let apart = if normal.length() <= 1e-12 {
3529 offset.sub(fa.axis.scale(offset.dot(fa.axis))).length()
3530 } else {
3531 offset.dot(normal).abs() / normal.length()
3532 };
3533 if crossing(apart, a0.abs(), b0.abs()) {
3534 return true;
3535 }
3536 }
3537 (A::Sphere { frame: fa, radius: ra }, A::Sphere { frame: fb, radius: rb }) => {
3538 if crossing(fb.origin.sub(fa.origin).length(), *ra, *rb)
3543 && !circle_off_face(face_a, first, (fa.origin, *ra), (fb.origin, *rb), tolerance)
3544 && !circle_off_face(face_b, second, (fb.origin, *rb), (fa.origin, *ra), tolerance)
3545 {
3546 return true;
3547 }
3548 }
3549 _ => {}
3550 }
3551 }
3552 }
3553 false
3554}
3555
3556fn circle_off_face(face: &crate::FaceRecord, solid: &BrepSolid, own: (Vec3, f64), other: (Vec3, f64), tolerance: f64) -> bool {
3564 use crate::classification::{parameter_point_in_face, PolygonClass};
3565 let ((ca, ra), (cb, rb)) = (own, other);
3566 if face.loops.iter().all(|lp| lp.coedges.is_empty()) {
3567 return false;
3568 }
3569 fn clear(curve: &crate::NurbsCurve, depth: u32, centre: Vec3, radius: f64, tolerance: f64) -> bool {
3574 let points: Option<Vec<Vec3>> = curve.control_points.iter().map(|control| if control.w > 0.0 { control.point().ok() } else { None }).collect();
3575 let Some(points) = points else { return false };
3576 if points.iter().all(|point| point.sub(centre).length() < radius - tolerance) {
3577 return true;
3578 }
3579 let (mut low, mut high) = (Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY));
3580 for point in &points {
3581 low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
3582 high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
3583 }
3584 let near = Vec3::new(centre.x.clamp(low.x, high.x), centre.y.clamp(low.y, high.y), centre.z.clamp(low.z, high.z));
3585 if near.sub(centre).length() > radius + tolerance {
3586 return true;
3587 }
3588 if depth == 0 {
3589 return false;
3590 }
3591 let Ok([t0, t1]) = curve.domain() else { return false };
3592 match curve.split(0.5 * (t0 + t1)) {
3593 Ok((left, right)) => clear(&left, depth - 1, centre, radius, tolerance) && clear(&right, depth - 1, centre, radius, tolerance),
3594 Err(_) => false,
3595 }
3596 }
3597 for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
3598 let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else { return false };
3599 let Ok([d0, d1]) = edge.curve.domain() else { return false };
3600 let mut span = edge.curve.clone();
3602 if edge.t1 < d1 {
3603 match span.split(edge.t1) {
3604 Ok((left, _)) => span = left,
3605 Err(_) => return false,
3606 }
3607 }
3608 if edge.t0 > d0 {
3609 match span.split(edge.t0) {
3610 Ok((_, right)) => span = right,
3611 Err(_) => return false,
3612 }
3613 }
3614 if !clear(&span, 10, cb, rb, tolerance) {
3615 return false;
3616 }
3617 }
3618 let axis = cb.sub(ca);
3619 let distance = axis.length();
3620 let Ok(n) = axis.normalized() else { return false };
3621 let along = (distance * distance + ra * ra - rb * rb) / (2.0 * distance);
3622 let across = ra * ra - along * along;
3623 let Ok(side) = n.perpendicular() else { return false };
3624 if !(across > 0.0) {
3625 return false;
3626 }
3627 let point = ca.add(n.scale(along)).add(side.scale(across.sqrt()));
3628 let Ok(projection) = crate::project_point_to_surface(&face.surface, point) else { return false };
3629 matches!(parameter_point_in_face(face, crate::Vec2 { x: projection.u, y: projection.v }, 1e-9), Ok(PolygonClass::Outside))
3630}
3631
3632
3633fn empty_solid() -> BrepSolid {
3635 BrepSolid {
3636 mass_properties_cache: Default::default(),
3637 cells: Default::default(),
3638 id: 0,
3639 vertices: Vec::new(),
3640 edges: Vec::new(),
3641 shells: Vec::new(),
3642 genus: 0,
3643 kind: crate::BodyKind::Solid,
3644 }
3645}
3646
3647fn concatenate_disjoint(first: &BrepSolid, second: &BrepSolid) -> BrepSolid {
3653 let mut vertices = Vec::new();
3654 let mut edges = Vec::new();
3655 let mut shells = Vec::new();
3656 let mut used_face_names = HashSet::<String>::default();
3657 let (mut next_face_id, mut next_loop_id, mut next_coedge_id) = (1u64, 1u64, 1u64);
3658 for operand in [first, second] {
3659 let vertex_base = vertices.len() as u64;
3660 let edge_base = edges.len() as u64;
3661 let mut vertex_ids: HashMap<u64, u64> = HashMap::default();
3662 for (index, vertex) in operand.vertices.iter().enumerate() {
3663 let id = vertex_base + index as u64 + 1;
3664 vertex_ids.insert(vertex.id, id);
3665 vertices.push(VertexRecord { id, point: vertex.point });
3666 }
3667 let mut edge_ids: HashMap<u64, u64> = HashMap::default();
3668 for (index, edge) in operand.edges.iter().enumerate() {
3669 let id = edge_base + index as u64 + 1;
3670 edge_ids.insert(edge.id, id);
3671 edges.push(EdgeRecord {
3672 id,
3673 curve: edge.curve.clone(),
3674 t0: edge.t0,
3675 t1: edge.t1,
3676 start_vertex_id: vertex_ids.get(&edge.start_vertex_id).copied().unwrap_or(edge.start_vertex_id),
3677 end_vertex_id: vertex_ids.get(&edge.end_vertex_id).copied().unwrap_or(edge.end_vertex_id),
3678 degenerate: edge.degenerate,
3679 name: edge.name.clone(),
3680 });
3681 }
3682 for shell in &operand.shells {
3683 let mut faces = Vec::with_capacity(shell.faces.len());
3684 for face in &shell.faces {
3685 let loops = face
3686 .loops
3687 .iter()
3688 .map(|loop_record| {
3689 let coedges = loop_record
3690 .coedges
3691 .iter()
3692 .map(|coedge| {
3693 let id = next_coedge_id;
3694 next_coedge_id += 1;
3695 CoedgeRecord {
3696 id,
3697 edge_id: edge_ids.get(&coedge.edge_id).copied().unwrap_or(coedge.edge_id),
3698 forward: coedge.forward,
3699 pcurve: coedge.pcurve.clone(),
3700 }
3701 })
3702 .collect();
3703 let id = next_loop_id;
3704 next_loop_id += 1;
3705 LoopRecord { id, coedges }
3706 })
3707 .collect();
3708 let name = face.name.clone().map(|base| {
3709 if used_face_names.insert(base.clone()) {
3710 base
3711 } else {
3712 let mut suffix = 1usize;
3713 loop {
3714 let candidate = format!("{base}_{suffix}");
3715 if used_face_names.insert(candidate.clone()) {
3716 break candidate;
3717 }
3718 suffix += 1;
3719 }
3720 }
3721 });
3722 faces.push(FaceRecord {
3723 id: next_face_id,
3724 surface: face.surface.clone(),
3725 same_sense: face.same_sense,
3726 loops,
3727 name,
3728 });
3729 next_face_id += 1;
3730 }
3731 shells.push(ShellRecord { id: shells.len() as u64 + 1, faces });
3732 }
3733 }
3734 BrepSolid {
3735 mass_properties_cache: Default::default(),
3736 cells: Default::default(),
3737 id: 1,
3738 vertices,
3739 edges,
3740 shells,
3741 genus: first.genus + second.genus,
3742 kind: crate::BodyKind::Solid,
3743 }
3744}
3745
3746fn boolean_pipeline(
3749 first: &BrepSolid,
3750 second: &BrepSolid,
3751 operation: BooleanOperation,
3752 options: &BooleanOptions,
3753 tangent_nodes: &mut Vec<Vec3>,
3754) -> Result<(KernelOutcome<BrepSolid>, Option<HashSet<u64>>), KernelRefusal> {
3755 let _work = crate::imprint::work_profile::Scope::open("boolean");
3756 let replaced_operands = operand_state::replace_operands(first, second, operation, options);
3757 let (first, second) = match &replaced_operands {
3758 Some((first, second)) => (first, second),
3759 None => (first, second),
3760 };
3761 let policy = boolean_policy(first, second, options)?;
3762 let tolerance = policy.model;
3763 let bounds = [operand_bounds(first), operand_bounds(second)];
3778 let disjoint = disjoint_fast_path(options) && !bounds[0].intersects(bounds[1], policy.sew_search);
3779 let contact = !disjoint
3780 && contact_fast_path(options)
3781 && options.seam_reseat_later_references.is_some()
3782 && line_or_point_contact(first, second, bounds);
3783 let contact = contact
3788 || (!disjoint
3789 && matches!(operation, BooleanOperation::Intersect)
3790 && contact_fast_path(options)
3791 && boxes_share_no_interior(first, second, bounds));
3792 if disjoint || contact {
3793 let operation_started = Instant::now();
3794 let mut diagnostics = KernelDiagnostics::default();
3795 diagnostics.count_n(
3796 "collect.faces",
3797 first.shells.iter().chain(&second.shells).map(|shell| shell.faces.len() as u64).sum(),
3798 );
3799 diagnostics.count(if contact { "boolean.contact_fast_path" } else { "boolean.disjoint_fast_path" });
3800 diagnostics.measure_max("tolerance.model", policy.model);
3801 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3802 let value = match operation {
3803 BooleanOperation::Union => concatenate_disjoint(first, second),
3804 BooleanOperation::Subtract => first.clone(),
3805 BooleanOperation::Intersect => {
3806 diagnostics.event(
3807 DiagnosticSeverity::Info,
3808 KernelStage::Select,
3809 "boolean.empty_result",
3810 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
3811 );
3812 empty_solid()
3813 }
3814 };
3815 let stage_ms = operation_started.elapsed().as_secs_f64() * 1_000.0;
3816 profile_stage("disjoint_fast_path_ms", stage_ms);
3817 diagnostics.measure_max("timing.total_ms", stage_ms);
3818 return Ok((KernelOutcome { value, diagnostics }, Some(HashSet::default())));
3819 }
3820 let heal_started = Instant::now();
3821 let (first_owned, second_owned) = prepared_operands(first, second, &policy)?;
3822 let heal_ms = heal_started.elapsed().as_secs_f64() * 1_000.0;
3823 let first = &first_owned;
3824 let second = &second_owned;
3825
3826 let mut diagnostics = KernelDiagnostics::default();
3827 diagnostics.measure_max("timing.heal_ms", heal_ms);
3830 let fit_scope = crate::PcurveFitScope::open();
3835 let polyline_scope = crate::PolylineFitScope::open();
3839 let operation_started = Instant::now();
3840 diagnostics.count_n(
3841 "collect.faces",
3842 first
3843 .shells
3844 .iter()
3845 .chain(&second.shells)
3846 .map(|shell| shell.faces.len() as u64)
3847 .sum(),
3848 );
3849 diagnostics.measure_max("tolerance.model", policy.model);
3850 diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3851
3852 let imprint_options = boolean_imprint_options(options, tolerance);
3853 let stage_started = Instant::now();
3854 let imprint = build_imprints(first, second, &imprint_options)?;
3855 tangent_nodes.extend_from_slice(&imprint.tangent_nodes);
3856 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
3857 for piece in &imprint.pieces {
3858 let start = piece.curve.evaluate(piece.t0);
3859 let end = piece.curve.evaluate(piece.t1);
3860 eprintln!(
3861 "piece {} supports={:?} t=[{:.6},{:.6}] start={:?} end={:?}",
3862 piece.id, piece.support_faces, piece.t0, piece.t1, start, end
3863 );
3864 }
3865 for entry in &imprint.by_face {
3866 eprintln!(
3867 "by_face operand={} face={} pieces={:?}",
3868 entry.operand, entry.face_id, entry.piece_ids
3869 );
3870 }
3871 for split in &imprint.edge_splits {
3872 eprintln!(
3873 "edge_split operand={} edge={} params={:?}",
3874 split.operand, split.edge_id, split.parameters
3875 );
3876 }
3877 }
3878 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3879 profile_stage("imprint_ms", stage_ms);
3880 diagnostics.measure_max("timing.imprint_ms", stage_ms);
3881 diagnostics.count_n("intersect.pieces", imprint.pieces.len() as u64);
3882 diagnostics.count_n("intersect.vertices", imprint.vertices.len() as u64);
3883 diagnostics.count_n("intersect.edge_splits", imprint.edge_splits.len() as u64);
3884 let (march_swap_rescues, clip_swap_rescues) = crate::imprint::take_rescue_firings();
3885 diagnostics.count_n("intersect.march_swap_rescue", march_swap_rescues);
3886 diagnostics.count_n("intersect.clip_swap_rescue", clip_swap_rescues);
3887 let touch = TouchCensus::build([first, second], &imprint);
3888 touch.report(&mut diagnostics);
3889 let stage_started = Instant::now();
3890 let (split_first, split_map_first) = apply_edge_splits_with_map(first, 0, &imprint)?;
3891 let (split_second, split_map_second) = apply_edge_splits_with_map(second, 1, &imprint)?;
3892 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3893 profile_stage("edge_split_ms", stage_ms);
3894 diagnostics.measure_max("timing.edge_split_ms", stage_ms);
3895 let stage_started = Instant::now();
3896 crate::classification::classify_profile_begin();
3897 let fragments_a = crate::fragment::fragment_solid_against(&split_first, 0, &imprint, crate::fragment::bounded_carriers(second).then_some((bounds[1], policy.sew_search)))?;
3898 let fragments_b = crate::fragment::fragment_solid_against(&split_second, 1, &imprint, crate::fragment::bounded_carriers(first).then_some((bounds[0], policy.sew_search)))?;
3899 crate::classification::classify_profile_report("fragment");
3900 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3901 profile_stage("fragment_ms", stage_ms);
3902 diagnostics.measure_max("timing.fragment_ms", stage_ms);
3903 diagnostics.count_n(
3904 "fragment.candidates",
3905 (fragments_a.len() + fragments_b.len()) as u64,
3906 );
3907 touch.report_fragments(&[&fragments_a, &fragments_b], &mut diagnostics);
3908 let a_surface_samples: Vec<Vec3> = fragments_a
3913 .iter()
3914 .flat_map(|fragment| {
3915 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
3916 })
3917 .collect();
3918 let b_surface_samples: Vec<Vec3> = fragments_b
3919 .iter()
3920 .flat_map(|fragment| {
3921 std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
3922 })
3923 .collect();
3924 let stage_started = Instant::now();
3925 let mut barrier_edges: HashSet<(u8, u64)> = imprint
3926 .pieces
3927 .iter()
3928 .filter_map(|piece| piece.shared_edge.map(|(operand, edge_id, _)| (operand, edge_id)))
3929 .collect();
3930 barrier_edges.extend(imprint.barrier_edges.iter().copied());
3931 for (operand, split_map) in [(0u8, &split_map_first), (1u8, &split_map_second)] {
3937 let minted: Vec<(u8, u64)> = barrier_edges
3938 .iter()
3939 .filter(|(barrier_operand, _)| *barrier_operand == operand)
3940 .filter_map(|(_, edge_id)| split_map.get(edge_id))
3941 .flat_map(|sub_ids| sub_ids.iter().map(|sub_id| (operand, *sub_id)))
3942 .collect();
3943 barrier_edges.extend(minted);
3944 }
3945 crate::classification::classify_profile_begin();
3946 let coincident = coincident_pairs(
3947 &fragments_a,
3948 &fragments_b,
3949 first,
3950 second,
3951 &imprint.cosurface_pairs,
3952 tolerance,
3953 )?;
3954 let sector_mode = sector::sector_mode(options);
3955 let mut select_census = sector::SelectCensus::default();
3956 let mut selected = select_fragments(
3957 fragments_a,
3958 fragments_b,
3959 first,
3960 second,
3961 operation,
3962 tolerance,
3963 &barrier_edges,
3964 &imprint,
3965 &coincident,
3966 sector_mode,
3967 &mut select_census,
3968 )?;
3969 let resewn = resew_coincident_rims(
3970 &mut selected,
3971 [&split_first, &split_second],
3972 [first, second],
3973 &imprint.cosurface_pairs,
3974 operation,
3975 tolerance,
3976 )?;
3977 diagnostics.count_n("select.coincident_pairs", coincident.len() as u64);
3978 diagnostics.count_n("select.rims_resewn", resewn as u64);
3979 crate::classification::classify_profile_report("select");
3980 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3981 profile_stage("select_ms", stage_ms);
3982 diagnostics.measure_max("timing.select_ms", stage_ms);
3983 diagnostics.count_n("select.fragments", selected.len() as u64);
3984 diagnostics.count_n("select.sector_eligible", select_census.eligible);
3986 diagnostics.count_n("select.sector_primary", select_census.sector_primary);
3987 diagnostics.count_n("select.sector_fallback", select_census.sector_fallback);
3988 diagnostics.count_n("select.sector_disagree", select_census.disagree);
3989 diagnostics.count_n("select.ray_casts", select_census.ray_casts);
3990 diagnostics.count_n("select.on_votes", select_census.on_votes);
3991 diagnostics.count_n("select.overturns", select_census.overturns);
3992 if sector_mode != sector::SectorMode::Off || std::env::var_os("BREP_SECTOR_CENSUS").is_some() {
3993 sector::sector_census_line(|| {
3994 format!(
3995 "selection mode={sector_mode:?} select_ms={stage_ms:.3} selected={} eligible={} primary={} fallback={} disagree={} ray_casts={} on_votes={} overturns={}",
3996 selected.len(),
3997 select_census.eligible,
3998 select_census.sector_primary,
3999 select_census.sector_fallback,
4000 select_census.disagree,
4001 select_census.ray_casts,
4002 select_census.on_votes,
4003 select_census.overturns
4004 )
4005 });
4006 }
4007 if selected.is_empty()
4029 && !imprint.section_evidence
4030 && std::env::var("BREP_EMPTY_BOOLEAN").as_deref() != Ok("0")
4031 {
4032 let strictly_inside = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
4033 for &sample in samples {
4034 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::In {
4035 return Ok(true);
4036 }
4037 }
4038 Ok(false)
4039 };
4040 let outside_witness = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
4041 for &sample in samples {
4042 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::Out {
4043 return Ok(true);
4044 }
4045 }
4046 Ok(false)
4047 };
4048 let legitimate = match operation {
4049 BooleanOperation::Intersect => {
4050 !strictly_inside(&a_surface_samples, second)?
4051 && !strictly_inside(&b_surface_samples, first)?
4052 }
4053 BooleanOperation::Subtract => !outside_witness(&a_surface_samples, second)?,
4054 BooleanOperation::Union => false,
4055 };
4056 if legitimate {
4057 diagnostics.event(
4058 DiagnosticSeverity::Info,
4059 KernelStage::Select,
4060 "boolean.empty_result",
4061 format!("{operation:?} of witnessed-non-overlapping operands is empty"),
4062 );
4063 fit_scope.close().report_into(&mut diagnostics);
4064 polyline_scope.close().report_into(&mut diagnostics);
4065 diagnostics.measure_max(
4066 "timing.total_ms",
4067 operation_started.elapsed().as_secs_f64() * 1_000.0,
4068 );
4069 return Ok((
4070 KernelOutcome {
4071 value: empty_solid(),
4072 diagnostics,
4073 },
4074 None,
4075 ));
4076 }
4077 }
4078 if selected.is_empty()
4087 && imprint.section_evidence
4088 && !matches!(operation, BooleanOperation::Union)
4089 && touching_empty_enabled()
4090 && !TOUCHING_PROOF.with(std::cell::Cell::get)
4091 {
4092 let strict = |samples: &[Vec3], other: &BrepSolid, class: PointClass| -> Result<bool, KernelRefusal> {
4093 for &sample in samples {
4094 if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == class {
4095 return Ok(true);
4096 }
4097 }
4098 Ok(false)
4099 };
4100 let witnessed = match operation {
4101 BooleanOperation::Intersect => {
4102 !strict(&a_surface_samples, second, PointClass::In)? && !strict(&b_surface_samples, first, PointClass::In)?
4103 }
4104 BooleanOperation::Subtract => !strict(&a_surface_samples, second, PointClass::Out)?,
4105 BooleanOperation::Union => false,
4106 };
4107 let overlap_free = !hair_deep_overlap(first, second, tolerance);
4113 if witnessed && overlap_free {
4114 TOUCHING_PROOF.with(|flag| flag.set(true));
4115 let proof = inclusion_exclusion_volume(first, second, operation, options, body_volume(first), body_volume(second), false);
4116 TOUCHING_PROOF.with(|flag| flag.set(false));
4117 let volume = |solid: &BrepSolid| body_volume(solid).unwrap_or(f64::INFINITY);
4122 let band = 1e-9 * volume(first).max(volume(second));
4123 if let Some(proof) = proof.filter(|proof| proof.expected.is_finite() && proof.expected.abs() <= band) {
4124 diagnostics.event(
4125 DiagnosticSeverity::Info,
4126 KernelStage::Select,
4127 "boolean.empty_touching",
4128 format!(
4129 "{operation:?} of touching operands is empty: {} reads {:.3e} by {} (band {band:.3e})",
4130 proof.formula, proof.expected, proof.reading
4131 ),
4132 );
4133 fit_scope.close().report_into(&mut diagnostics);
4134 polyline_scope.close().report_into(&mut diagnostics);
4135 diagnostics.measure_max("timing.total_ms", operation_started.elapsed().as_secs_f64() * 1_000.0);
4136 return Ok((KernelOutcome { value: empty_solid(), diagnostics }, None));
4137 }
4138 }
4139 }
4140 let solids = [(0, &split_first), (1, &split_second)]
4141 .into_iter()
4142 .collect::<HashMap<_, _>>();
4143 let dump = BooleanStageDump::open();
4144 if let Some(dump) = &dump {
4145 dump.write("first", &split_first);
4146 dump.write("second", &split_second);
4147 dump.write("selected", &selected);
4148 }
4149 let stage_started = Instant::now();
4150 let assembled_origins: Vec<FaceKey> = if imprint.tangent_sections.is_empty() {
4154 Vec::new()
4155 } else {
4156 selected
4157 .iter()
4158 .map(|fragment| FaceKey { operand: fragment.operand, face_id: fragment.source_face_id })
4159 .collect()
4160 };
4161 let attributable: Vec<crate::imprint::TangentSectionRecord> = imprint
4168 .tangent_sections
4169 .iter()
4170 .filter(|section| imprint.tangent_nodes.is_empty() || section.grazing.is_empty())
4171 .cloned()
4172 .collect();
4173 let attribute = |error: KernelRefusal| {
4174 attribute_to_tangent_section(error, &attributable, &assembled_origins)
4175 };
4176 let cellular_result = matches!(operation, BooleanOperation::Union)
4177 && cellular::enabled(options)
4178 && cellular::complete_contact(first, second, &selected, tolerance);
4179 let (solid, scope) = if cellular_result {
4180 (assemble::assemble_cellular_fragments(selected, &solids, &imprint, tolerance)
4181 .map_err(attribute)?, None)
4182 } else if untouched_passthrough(options) {
4183 assemble_fragments_scoped(selected, &solids, &imprint, tolerance, &touch, touched_assembly(options))
4184 .map_err(attribute)?
4185 } else {
4186 (assemble_fragments(selected, &solids, &imprint, tolerance).map_err(attribute)?, None)
4187 };
4188 if let Some(scope) = &scope {
4189 diagnostics.count_n("passthrough.faces_examined", scope.examined.len() as u64);
4190 }
4191 if let Some(dump) = &dump {
4192 dump.write("assembled", &solid);
4193 }
4194 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
4195 profile_stage("assemble_ms", stage_ms);
4196 diagnostics.measure_max("timing.assemble_ms", stage_ms);
4197 let stage_started = Instant::now();
4198 let declines_before = crate::face_merge::declines_served();
4199 let area_checks_before = crate::face_merge::boundary_area_checks();
4200 if std::env::var("BREP_DEBUG_PREMERGE_VALIDATE").is_ok() {
4201 let issues = solid.validate();
4202 eprintln!(
4203 "pre-merge validation: {} issue(s){}",
4204 issues.len(),
4205 issues
4206 .first()
4207 .map(|issue| format!(" — first: {}", issue.message))
4208 .unwrap_or_default()
4209 );
4210 }
4211 let solid = if solid.kind != crate::BodyKind::Cellular && options.merge_coplanar_faces
4212 && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
4213 {
4214 let merged = match &scope {
4215 Some(scope) => merge_same_surface_faces_scoped(
4219 &solid,
4220 tolerance,
4221 &options.keep_unmerged_name_substrs,
4222 &scope.examined,
4223 )?,
4224 None => merge_same_surface_faces_excluding(
4225 &solid,
4226 tolerance,
4227 &options.keep_unmerged_name_substrs,
4228 )?,
4229 };
4230 let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
4235 rejoin::rejoin_unless_referenced(merged, options, tolerance)
4236 } else {
4237 solid
4238 };
4239 if let Some(dump) = &dump {
4240 dump.write("merged", &solid);
4241 }
4242 let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
4243 profile_stage("face_merge_ms", stage_ms);
4244 if crate::profile::profile_enabled() {
4245 profile_line!("boolean.merge_declines served={}", crate::face_merge::declines_served() - declines_before);
4246 let area_checks = crate::face_merge::boundary_area_checks();
4247 if area_checks != area_checks_before {
4248 profile_line!("boolean.merge_area_checks boundary={} integrated={}", area_checks.0 - area_checks_before.0, area_checks.1 - area_checks_before.1);
4249 }
4250 }
4251 diagnostics.measure_max("timing.face_merge_ms", stage_ms);
4252 let validation_started = Instant::now();
4253 let validation = solid.validate_detailed_scoped(&policy, scope.as_ref().map(|scope| &scope.examined));
4254 profile_stage("final_validate_ms", validation_started.elapsed().as_secs_f64() * 1000.0);
4255 diagnostics.count_n("validate.issues", validation.issues.len() as u64);
4256 diagnostics.count_n(
4257 "validate.wire_warnings",
4258 validation.wire_warnings.len() as u64,
4259 );
4260 diagnostics.measure_max("validate.max_pcurve_error", validation.max_pcurve_error);
4261 for warning in &validation.wire_warnings {
4262 diagnostics.event(
4263 DiagnosticSeverity::Warning,
4264 KernelStage::Validate,
4265 "validate.uv_wire",
4266 warning.message.clone(),
4267 );
4268 }
4269 for issue in &validation.issues {
4270 diagnostics.event(
4271 DiagnosticSeverity::Error,
4272 KernelStage::Validate,
4273 "validate.brep",
4274 issue.message.clone(),
4275 );
4276 }
4277 fit_scope.close().report_into(&mut diagnostics);
4278 polyline_scope.close().report_into(&mut diagnostics);
4279 diagnostics.measure_max(
4280 "timing.total_ms",
4281 operation_started.elapsed().as_secs_f64() * 1_000.0,
4282 );
4283 if !validation.issues.is_empty() {
4284 return Err(KernelRefusal::new(
4285 RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
4286 KernelStage::Validate,
4287 format!(
4288 "boolean_operation: invalid result: {:?}",
4289 validation.issues
4290 )));
4291 }
4292 if std::env::var("BREP_DEBUG_BOOL").is_ok() {
4298 if let Ok(report) =
4299 crate::oracle::boolean_semantic_disagreement(first, second, operation, &solid, 200)
4300 {
4301 if report.is_flagged() {
4302 eprintln!(
4303 "[oracle] semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
4304 report.disagreement_rate,
4305 report.disagreements.len(),
4306 report.considered,
4307 report.sample_disagreement()
4308 );
4309 }
4310 }
4311 let fusable_band = crate::tolerance::assembler_weld(policy.model);
4312 let fusables = crate::oracle::boolean_residual_fusables(&solid, fusable_band);
4313 if !fusables.is_empty() {
4314 eprintln!(
4315 "[oracle] {} residual fusable(s) after weld; sample {:?}",
4316 fusables.len(),
4317 fusables.first()
4318 );
4319 }
4320 }
4321 let candidates = scope.as_ref().map(|scope| {
4322 let unproved = (scope_proved_apart_on() && plain_hull_solid(first) && plain_hull_solid(second))
4323 .then(|| imprint.faces_in_unproved_pairs.as_ref())
4324 .flatten()
4325 .map(|faces| faces.iter().copied().collect::<HashSet<_>>());
4326 let candidates = soundness_candidates(
4327 &solid,
4328 scope,
4329 [operand_bounds(first), operand_bounds(second)],
4330 policy.sew_search,
4331 unproved.as_ref(),
4332 );
4333 diagnostics.count_n("passthrough.soundness_candidates", candidates.len() as u64);
4334 crate::soundness::census::profile_operation(&solid, &[first, second], Some(&scope.touched), "boolean");
4335 candidates
4336 });
4337 Ok((
4338 KernelOutcome {
4339 value: solid,
4340 diagnostics,
4341 },
4342 candidates,
4343 ))
4344}
4345
4346