BREP_kernel 0.5.0

A boundary representation (BREP) geometry kernel for building CAD applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
use crate::{KernelRefusal, KernelStage, OrRefuse};
use super::*;

fn face_normal(fragment: &FaceFragmentRecord) -> Result<Vec3, KernelRefusal> {
    let normal = fragment
        .surface
        .normal(fragment.test_uv.x, fragment.test_uv.y).or_refuse(KernelStage::Select, "normal")?;
    Ok(if fragment.same_sense {
        normal
    } else {
        normal.scale(-1.0)
    })
}

/// Classify a fragment by its primary test point, letting the extra
/// interior points overturn the verdict only when they unanimously
/// contradict it.  An On primary keeps the normal-comparison path (coplanar
/// fragments legitimately sit On everywhere); extras voting On are ignored
/// as near-boundary noise.  A single test point landing in a pathological
/// spot must not decide the whole fragment.
fn classify_fragment(
    classifier: &SolidClassifier,
    fragment: &FaceFragmentRecord,
    debug: bool,
) -> Result<crate::PointClassification, KernelRefusal> {
    let primary = classifier.classify(fragment.test_point).or_refuse(KernelStage::Select, "classify")?;
    if debug {
        eprintln!(
            "frag src_face={} test=({:.6},{:.6},{:.6}) primary={:?} extras={}",
            fragment.source_face_id,
            fragment.test_point.x,
            fragment.test_point.y,
            fragment.test_point.z,
            primary.class,
            fragment.extra_test_points.len()
        );
    }
    if primary.class == PointClass::On {
        // A genuine coplanar overlap sits On over the WHOLE fragment; a
        // point or line TANGENCY is On only along a measure-zero locus that
        // can pass exactly through the max-clearance primary (a sphere
        // resting on a face touches its centre; a tangent cylinder's ruling
        // runs through a wall's midline). Triggering the coincident-face
        // logic there dissolves a face that merely touches the other body.
        // Trust On only when the extra interior points do not unanimously
        // disagree; otherwise adopt their verdict.
        let mut in_votes = 0usize;
        let mut out_votes = 0usize;
        let mut on_votes = 0usize;
        for &point in &fragment.extra_test_points {
            match classifier.classify(point).or_refuse(KernelStage::Select, "classify")?.class {
                PointClass::On => on_votes += 1,
                PointClass::In => in_votes += 1,
                PointClass::Out => out_votes += 1,
            }
        }
        // Disambiguate a measure-zero tangency from a partial coincidence
        // REGION that simply has no imprint splits (an open-sheet operand
        // overlapping part of a face): a region stays On just off the
        // primary, a tangency leaves the band immediately. Probe a short
        // step from the primary toward each extra before overturning.
        if on_votes == 0 && (in_votes >= 2 || out_votes >= 2) {
            for &extra in &fragment.extra_test_points {
                let step = fragment
                    .test_point
                    .add(extra.sub(fragment.test_point).scale(0.05));
                if classifier.classify(step).or_refuse(KernelStage::Select, "classify")?.class == PointClass::On {
                    on_votes += 1;
                    break;
                }
            }
        }
        if on_votes == 0 && in_votes == 0 && out_votes >= 2 {
            if debug {
                eprintln!(
                    "frag src_face={} tangential On overturned -> Out ({out_votes} extras)",
                    fragment.source_face_id
                );
            }
            return Ok(crate::PointClassification {
                class: PointClass::Out,
                on_normal: None,
            });
        }
        if on_votes == 0 && out_votes == 0 && in_votes >= 2 {
            if debug {
                eprintln!(
                    "frag src_face={} tangential On overturned -> In ({in_votes} extras)",
                    fragment.source_face_id
                );
            }
            return Ok(crate::PointClassification {
                class: PointClass::In,
                on_normal: None,
            });
        }
        return Ok(primary);
    }
    // A stray In/Out on a face that is actually coincident with the other
    // solid's boundary (near-coincident across a noise-scale gap that the
    // tight On band misses) is rescued to On here, using a size-derived band.
    // This never flips In<->Out; it only recovers the boundary verdict a
    // coplanar overlap should have produced.
    if let Some(on_normal) = classifier.coincident_on_normal(fragment.test_point).or_refuse(KernelStage::Select, "coincident_on_normal")? {
        if debug {
            eprintln!(
                "frag src_face={} coincident-On rescue {:?} -> On",
                fragment.source_face_id, primary.class
            );
        }
        return Ok(crate::PointClassification {
            class: PointClass::On,
            on_normal: Some(on_normal),
        });
    }
    if fragment.extra_test_points.is_empty() {
        return Ok(primary);
    }
    let mut agreeing = 0usize;
    let mut opposing = 0usize;
    for &point in &fragment.extra_test_points {
        match classifier.classify(point).or_refuse(KernelStage::Select, "classify")?.class {
            class if class == primary.class => agreeing += 1,
            PointClass::On => {}
            _ => opposing += 1,
        }
    }
    if opposing >= 2 && agreeing == 0 {
        let overturned = match primary.class {
            PointClass::In => PointClass::Out,
            _ => PointClass::In,
        };
        if debug {
            eprintln!(
                "frag src_face={} vote overturned {:?} -> {:?} ({} opposing)",
                fragment.source_face_id, primary.class, overturned, opposing
            );
        }
        return Ok(crate::PointClassification {
            class: overturned,
            on_normal: None,
        });
    }
    Ok(primary)
}

/// Adjacency key of a boundary coedge: the ORIGINAL edge id paired with
/// the quantized 3D midpoint of the coedge's chain.  The id distinguishes
/// geometrically coincident but distinct edges (tangency lines); the
/// midpoint distinguishes split siblings of one original edge, whose
/// fragment records only know the unsplit id.  True neighbors share both.
fn boundary_coedge_key(
    fragment: &FaceFragmentRecord,
    edge_id: u64,
    pcurve: &crate::NurbsCurve,
    quantum: f64,
) -> Option<(u64, [i64; 3])> {
    let [start, end] = pcurve.domain().ok()?;
    let uv = pcurve.evaluate((start + end) * 0.5).ok()?;
    let point = fragment.surface.evaluate(uv.x, uv.y).ok()?;
    Some((
        edge_id,
        [
            (point.x / quantum).round() as i64,
            (point.y / quantum).round() as i64,
            (point.z / quantum).round() as i64,
        ],
    ))
}

/// Keep/drop decisions for one operand's fragments (Golovanov §6.3:
/// untouched faces join the result shell by edge adjacency, not per-face
/// point classification).  Point classification runs only for fragments
/// the boolean TOUCHED (cut coedges), fragments inside the other solid's
/// On band, and fragments adjacent to an On-classified fragment (fate
/// flips along On-region boundaries, so On fates never propagate).
/// Everything else inherits its fate across shared boundary-coedge
/// midpoints; conflicting inheritance aborts loudly, and components with
/// no decided member classify one representative.
fn side_keep_decisions(
    fragments: &[FaceFragmentRecord],
    classifier: &SolidClassifier,
    first_operand: bool,
    operation: BooleanOperation,
    tolerance: f64,
    debug: bool,
    barrier_edges: &HashSet<(u8, u64)>,
) -> Result<Vec<bool>, KernelRefusal> {
    let decide = |fragment: &FaceFragmentRecord,
                  classification: &crate::PointClassification|
     -> Result<(bool, bool), KernelRefusal> {
        if debug {
            eprintln!(
                "frag {} src_face={} test=({:.6},{:.6},{:.6}) class={:?}",
                if first_operand { "A" } else { "B" },
                fragment.source_face_id,
                fragment.test_point.x,
                fragment.test_point.y,
                fragment.test_point.z,
                classification.class,
            );
        }
        let propagatable = classification.class != PointClass::On;
        let keep = if first_operand {
            match classification.class {
                PointClass::On => {
                    let same = classification
                        .on_normal
                        .ok_or_else(|| {
                            "boolean selection: boundary classification lacks normal".to_string()
                        }).or_refuse(KernelStage::Select, "csg.boolean.select")?
                        .dot(face_normal(fragment)?)
                        > 0.0;
                    match operation {
                        BooleanOperation::Subtract => !same,
                        BooleanOperation::Union | BooleanOperation::Intersect => same,
                    }
                }
                PointClass::In => matches!(operation, BooleanOperation::Intersect),
                PointClass::Out => !matches!(operation, BooleanOperation::Intersect),
            }
        } else {
            match classification.class {
                PointClass::On => false,
                PointClass::Out => matches!(operation, BooleanOperation::Union),
                PointClass::In => matches!(
                    operation,
                    BooleanOperation::Intersect | BooleanOperation::Subtract
                ),
            }
        };
        Ok((keep, propagatable))
    };

    let mut keep: Vec<Option<bool>> = vec![None; fragments.len()];
    let mut propagatable: Vec<bool> = vec![false; fragments.len()];
    for (index, fragment) in fragments.iter().enumerate() {
        let touched = fragment
            .loops
            .iter()
            .flat_map(|loop_record| &loop_record.coedges)
            .any(|coedge| !matches!(coedge.source, FragmentEdgeSource::Boundary { .. }));
        if touched || classifier.near_surface(fragment.test_point).or_refuse(KernelStage::Select, "near_surface")? {
            let classification = classify_fragment(classifier, fragment, debug)?;
            let (value, source) = decide(fragment, &classification)?;
            keep[index] = Some(value);
            propagatable[index] = source;
        }
    }

    let quantum = tolerance.max(1e-5) * 10.0;
    let mut edge_fragments: HashMap<(u64, [i64; 3]), Vec<usize>> = HashMap::default();
    for (index, fragment) in fragments.iter().enumerate() {
        for coedge in fragment
            .loops
            .iter()
            .flat_map(|loop_record| &loop_record.coedges)
        {
            if let FragmentEdgeSource::Boundary { edge_id, .. } = coedge.source {
                // A BARRIER edge carries the other operand's coincident
                // section (a shared ring: the inscribed sphere's equator IS
                // this operand's cap edge). Fate flips exactly there — the
                // wall is Outside while the cap disc lies Inside the other
                // solid — so adjacency inheritance must not flood across it;
                // isolated fragments then classify directly (equator-tangent:
                // the bottom cap wrongly inherited keep from the wall).
                let fragment_operand = if first_operand { 0u8 } else { 1u8 };
                if barrier_edges.contains(&(fragment_operand, edge_id)) {
                    continue;
                }
                if let Some(key) = boundary_coedge_key(fragment, edge_id, &coedge.pcurve, quantum) {
                    let entry = edge_fragments.entry(key).or_default();
                    if !entry.contains(&index) {
                        entry.push(index);
                    }
                }
            }
        }
    }

    // Fate flips along On-region boundaries: neighbors of On fragments
    // classify directly instead of inheriting.
    let mut on_adjacent: Vec<bool> = vec![false; fragments.len()];
    for neighbors in edge_fragments.values() {
        if neighbors
            .iter()
            .any(|&index| keep[index].is_some() && !propagatable[index])
        {
            for &index in neighbors {
                on_adjacent[index] = true;
            }
        }
    }
    for index in 0..fragments.len() {
        if on_adjacent[index] && keep[index].is_none() {
            let classification = classify_fragment(classifier, &fragments[index], debug)?;
            let (value, source) = decide(&fragments[index], &classification)?;
            keep[index] = Some(value);
            propagatable[index] = source;
        }
    }

    loop {
        let mut progressed = false;
        for neighbors in edge_fragments.values() {
            let mut fate: Option<(bool, usize)> = None;
            for &index in neighbors {
                if !propagatable[index] {
                    continue;
                }
                if let Some(value) = keep[index] {
                    if let Some((known, source)) = fate {
                        if known != value {
                            // Tolerance-band geometry (near-coincident caps,
                            // tangency lines) can flip fate across pieces the
                            // guards cannot fully characterize.  Propagation
                            // is an optimization: fall back to classifying
                            // every fragment directly.
                            if debug {
                                eprintln!(
                                    "frag {} propagation conflict (faces {} vs {}) — \
                                     falling back to direct classification",
                                    if first_operand { "A" } else { "B" },
                                    fragments[source].source_face_id,
                                    fragments[index].source_face_id,
                                );
                            }
                            let mut direct = Vec::with_capacity(fragments.len());
                            for fragment in fragments {
                                let classification =
                                    classify_fragment(classifier, fragment, debug)?;
                                direct.push(decide(fragment, &classification)?.0);
                            }
                            return Ok(direct);
                        }
                    } else {
                        fate = Some((value, index));
                    }
                }
            }
            if let Some((value, _)) = fate {
                for &index in neighbors {
                    if keep[index].is_none() {
                        keep[index] = Some(value);
                        propagatable[index] = true;
                        if debug {
                            eprintln!(
                                "frag {} src_face={} inherited keep={value} by adjacency",
                                if first_operand { "A" } else { "B" },
                                fragments[index].source_face_id,
                            );
                        }
                        progressed = true;
                    }
                }
            }
        }
        if !progressed {
            match keep.iter().position(Option::is_none) {
                Some(index) => {
                    let classification = classify_fragment(classifier, &fragments[index], debug)?;
                    let (value, source) = decide(&fragments[index], &classification)?;
                    keep[index] = Some(value);
                    propagatable[index] = source;
                }
                None => break,
            }
        }
    }
    Ok(keep
        .into_iter()
        .map(|value| value.unwrap_or(false))
        .collect())
}

pub(super) fn select_fragments(
    fragments_a: Vec<FaceFragmentRecord>,
    fragments_b: Vec<FaceFragmentRecord>,
    pristine_a: &BrepSolid,
    pristine_b: &BrepSolid,
    operation: BooleanOperation,
    tolerance: f64,
    barrier_edges: &HashSet<(u8, u64)>,
) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
    let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
    let mut selected = Vec::new();
    let classifier_b = SolidClassifier::new(pristine_b, tolerance).or_refuse(KernelStage::Select, "new")?;
    let classifier_a = SolidClassifier::new(pristine_a, tolerance).or_refuse(KernelStage::Select, "new")?;
    let keep_a = side_keep_decisions(
        &fragments_a,
        &classifier_b,
        true,
        operation,
        tolerance,
        debug,
        barrier_edges,
    )?;
    for (fragment, keep) in fragments_a.into_iter().zip(keep_a) {
        if keep {
            selected.push(fragment);
        }
    }
    let keep_b = side_keep_decisions(
        &fragments_b,
        &classifier_a,
        false,
        operation,
        tolerance,
        debug,
        barrier_edges,
    )?;
    for (mut fragment, keep) in fragments_b.into_iter().zip(keep_b) {
        if !keep {
            continue;
        }
        if matches!(operation, BooleanOperation::Subtract) {
            fragment.same_sense = !fragment.same_sense;
            for loop_record in &mut fragment.loops {
                loop_record.coedges.reverse();
                for coedge in &mut loop_record.coedges {
                    coedge.forward = !coedge.forward;
                    coedge.pcurve = coedge.pcurve.reversed().or_refuse(KernelStage::Select, "reversed")?;
                }
            }
        }
        selected.push(fragment);
    }
    Ok(selected)
}

/// The verdict for one fragment in the n-ary selection.
enum NaryKeep {
    Drop,
    AsIs,
    Reversed,
}

/// Generalized per-fragment keep decision: "vs the SET of other solids".
///
/// `classifiers[k]` classifies a point against pristine operand `k`; `owner` is
/// the fragment's own operand index.  Every classification uses the shared
/// `classify_fragment` helper (coincident-On rescue + interior-vote), so a
/// coincident shared wall reads `On` with the other solid's outward normal.
/// The rules below reduce EXACTLY to the binary `side_keep_decisions` `decide`
/// closure when there is a single other solid, so N=2 reproduces the binary
/// selection; coincident walls are kept once (from the lowest-indexed operand,
/// oriented outward) by the `owner < other` / normal-agreement guards.
fn nary_keep(
    classifiers: &[SolidClassifier],
    owner: usize,
    fragment: &FaceFragmentRecord,
    operation: BooleanOperation,
    debug: bool,
) -> Result<NaryKeep, KernelRefusal> {
    let n = classifiers.len();
    // Cached outward normal for the On (coincident) orientation tests.
    let outward = |fragment: &FaceFragmentRecord| face_normal(fragment);

    match operation {
        BooleanOperation::Union => {
            // Keep a fragment iff it is OUTSIDE every OTHER operand (not buried);
            // a coincident shared wall is kept once, from the lower-indexed
            // operand, oriented outward.
            for other in 0..n {
                if other == owner {
                    continue;
                }
                let class = classify_fragment(&classifiers[other], fragment, debug)?;
                match class.class {
                    PointClass::In => return Ok(NaryKeep::Drop),
                    PointClass::On => {
                        if other < owner {
                            return Ok(NaryKeep::Drop);
                        }
                        let same = class
                            .on_normal
                            .ok_or_else(|| {
                                "n-ary selection: On classification lacks normal".to_string()
                            }).or_refuse(KernelStage::Select, "csg.boolean.select")?
                            .dot(outward(fragment)?)
                            > 0.0;
                        if !same {
                            return Ok(NaryKeep::Drop);
                        }
                    }
                    PointClass::Out => {}
                }
            }
            Ok(NaryKeep::AsIs)
        }
        BooleanOperation::Intersect => {
            // Keep a fragment iff it is INSIDE every OTHER operand; coincident
            // shared walls kept once, lower operand, oriented outward.
            for other in 0..n {
                if other == owner {
                    continue;
                }
                let class = classify_fragment(&classifiers[other], fragment, debug)?;
                match class.class {
                    PointClass::Out => return Ok(NaryKeep::Drop),
                    PointClass::On => {
                        if other < owner {
                            return Ok(NaryKeep::Drop);
                        }
                        let same = class
                            .on_normal
                            .ok_or_else(|| {
                                "n-ary selection: On classification lacks normal".to_string()
                            }).or_refuse(KernelStage::Select, "csg.boolean.select")?
                            .dot(outward(fragment)?)
                            > 0.0;
                        if !same {
                            return Ok(NaryKeep::Drop);
                        }
                    }
                    PointClass::In => {}
                }
            }
            Ok(NaryKeep::AsIs)
        }
        BooleanOperation::Subtract => {
            // operands[0] minus the union of operands[1..].
            if owner == 0 {
                // Keep base fragments OUTSIDE every cutter (as-is).  A wall
                // coincident with a cutter is kept only when the normals oppose
                // (the cutter lies on the far side), matching binary A-Subtract.
                for cutter in 1..n {
                    let class = classify_fragment(&classifiers[cutter], fragment, debug)?;
                    match class.class {
                        PointClass::In => return Ok(NaryKeep::Drop),
                        PointClass::On => {
                            let same = class
                                .on_normal
                                .ok_or_else(|| {
                                    "n-ary selection: On classification lacks normal".to_string()
                                }).or_refuse(KernelStage::Select, "csg.boolean.select")?
                                .dot(outward(fragment)?)
                                > 0.0;
                            if same {
                                return Ok(NaryKeep::Drop);
                            }
                        }
                        PointClass::Out => {}
                    }
                }
                Ok(NaryKeep::AsIs)
            } else {
                // A cutter contributes its INWARD-facing wall where it lies
                // inside the base AND outside every OTHER cutter, reversed.
                let base = classify_fragment(&classifiers[0], fragment, debug)?;
                match base.class {
                    // Outside the base cuts nothing; a wall coincident with the
                    // base boundary is owned by the base fragment (binary B-On
                    // drops), so both non-In verdicts drop here.
                    PointClass::Out | PointClass::On => return Ok(NaryKeep::Drop),
                    PointClass::In => {}
                }
                for other in 1..n {
                    if other == owner {
                        continue;
                    }
                    let class = classify_fragment(&classifiers[other], fragment, debug)?;
                    match class.class {
                        PointClass::In => return Ok(NaryKeep::Drop),
                        PointClass::On => {
                            // Shared wall between two cutters inside the base:
                            // the union of cutters keeps it once, lower operand,
                            // outward — then it is reversed like any cutter wall.
                            if other < owner {
                                return Ok(NaryKeep::Drop);
                            }
                            let same = class
                                .on_normal
                                .ok_or_else(|| {
                                    "n-ary selection: On classification lacks normal".to_string()
                                }).or_refuse(KernelStage::Select, "csg.boolean.select")?
                                .dot(outward(fragment)?)
                                > 0.0;
                            if !same {
                                return Ok(NaryKeep::Drop);
                            }
                        }
                        PointClass::Out => {}
                    }
                }
                Ok(NaryKeep::Reversed)
            }
        }
    }
}

/// One-pass n-ary fragment selection against the SET of pristine operands.
pub(super) fn select_fragments_nary(
    fragments: &[Vec<FaceFragmentRecord>],
    pristine: &[BrepSolid],
    operation: BooleanOperation,
    tolerance: f64,
    debug: bool,
) -> Result<Vec<FaceFragmentRecord>, KernelRefusal> {
    let classifiers = pristine
        .iter()
        .map(|solid| SolidClassifier::new(solid, tolerance))
        .collect::<Result<Vec<_>, _>>().or_refuse(KernelStage::Select, "csg.boolean.select")?;
    let mut selected = Vec::new();
    for (owner, owner_fragments) in fragments.iter().enumerate() {
        for fragment in owner_fragments {
            match nary_keep(&classifiers, owner, fragment, operation, debug)? {
                NaryKeep::Drop => {}
                NaryKeep::AsIs => selected.push(fragment.clone()),
                NaryKeep::Reversed => {
                    let mut reversed = fragment.clone();
                    reverse_fragment(&mut reversed)?;
                    selected.push(reversed);
                }
            }
        }
    }
    Ok(selected)
}