brepkit-operations 3.2.22

CAD modeling operations (booleans, fillets, extrusions) for brepkit
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
//! Boolean operation edge case tests.
//!
//! Verifies correct behavior on dangerous geometric configurations:
//! tangent solids, kissing faces, thin features, degenerate results,
//! sequential operations, mixed surfaces, and vertex/edge contact.

#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::no_effect_underscore_binding,
    clippy::single_match,
    clippy::single_match_else
)]

use std::f64::consts::PI;

use brepkit_math::mat::Mat4;
use brepkit_operations::boolean::{BooleanOp, BooleanOptions, boolean, boolean_with_options};
use brepkit_operations::measure::solid_volume;
use brepkit_operations::primitives::{make_box, make_cone, make_cylinder, make_sphere};
use brepkit_operations::transform::transform_solid;
use brepkit_topology::Topology;
use brepkit_topology::solid::SolidId;
use brepkit_topology::validation::validate_shell_manifold;

const DEFLECTION: f64 = 0.1;

fn vol(topo: &Topology, solid: SolidId) -> f64 {
    solid_volume(topo, solid, DEFLECTION).unwrap()
}

fn check_manifold(topo: &Topology, solid: SolidId) {
    let s = topo.solid(solid).unwrap();
    let sh = topo.shell(s.outer_shell()).unwrap();
    validate_shell_manifold(sh, topo).expect("result should be manifold");
}

// ── Tangent solids ──────────────────────────────────────────────────

#[test]
fn test_sphere_tangent_to_plane() {
    // Sphere radius 1 at origin. Box from (-5,-5,-5) to (5,5,-1).
    // The box top face at z=-1 is exactly tangent to the sphere bottom.
    let mut topo = Topology::new();
    let sphere = make_sphere(&mut topo, 1.0, 16).unwrap();
    let bx = make_box(&mut topo, 10.0, 10.0, 4.0).unwrap();
    transform_solid(&mut topo, bx, &Mat4::translation(-5.0, -5.0, -5.0)).unwrap();

    let result = boolean(&mut topo, BooleanOp::Fuse, sphere, bx);
    match result {
        Ok(fused) => {
            let expected = 4.0 * PI / 3.0 + 400.0;
            let v = vol(&topo, fused);
            let rel = (v - expected).abs() / expected;
            assert!(rel < 0.05, "volume {v:.2} not near expected {expected:.2}");
            check_manifold(&topo, fused);
        }
        Err(e) => panic!("tangent fuse failed: {e}"),
    }
}

#[test]
fn test_cylinder_tangent_to_plane() {
    // Cylinder radius 1, height 2 at origin. Box with right face at x=-1.
    let mut topo = Topology::new();
    let cyl = make_cylinder(&mut topo, 1.0, 2.0).unwrap();
    let bx = make_box(&mut topo, 4.0, 10.0, 10.0).unwrap();
    transform_solid(&mut topo, bx, &Mat4::translation(-5.0, -5.0, -5.0)).unwrap();

    let result = boolean(&mut topo, BooleanOp::Fuse, cyl, bx);
    match result {
        Ok(fused) => {
            check_manifold(&topo, fused);
        }
        Err(e) => panic!("tangent cylinder-plane fuse failed: {e}"),
    }
}

#[test]
fn test_two_spheres_tangent() {
    // Two spheres radius 1, touching at (1,0,0).
    let mut topo = Topology::new();
    let s1 = make_sphere(&mut topo, 1.0, 16).unwrap();
    let s2 = make_sphere(&mut topo, 1.0, 16).unwrap();
    transform_solid(&mut topo, s2, &Mat4::translation(2.0, 0.0, 0.0)).unwrap();

    let result = boolean(&mut topo, BooleanOp::Fuse, s1, s2);
    match result {
        Ok(fused) => {
            let expected = 2.0 * 4.0 * PI / 3.0;
            let v = vol(&topo, fused);
            let rel = (v - expected).abs() / expected;
            assert!(rel < 0.05, "volume {v:.2} not near expected {expected:.2}");
            check_manifold(&topo, fused);
        }
        Err(e) => panic!("tangent spheres fuse failed: {e}"),
    }
}

// ── Kissing solids ──────────────────────────────────────────────────

#[test]
fn test_kissing_boxes_fuse() {
    // Two unit boxes sharing a face at x=1.
    let mut topo = Topology::new();
    let a = make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
    let b = make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
    transform_solid(&mut topo, b, &Mat4::translation(1.0, 0.0, 0.0)).unwrap();

    let fused = boolean(&mut topo, BooleanOp::Fuse, a, b).unwrap();
    let v = vol(&topo, fused);
    let rel = (v - 2.0).abs() / 2.0;
    assert!(rel < 0.01, "fused volume {v:.4} not near 2.0");
    check_manifold(&topo, fused);
}

#[test]
fn test_kissing_boxes_cut() {
    // Two unit boxes sharing a face at x=1. Cut A - B should leave A unchanged.
    let mut topo = Topology::new();
    let a = make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
    let b = make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
    transform_solid(&mut topo, b, &Mat4::translation(1.0, 0.0, 0.0)).unwrap();

    let result = boolean(&mut topo, BooleanOp::Cut, a, b);
    match result {
        Ok(cut) => {
            let v = vol(&topo, cut);
            let rel = (v - 1.0).abs();
            assert!(rel < 0.01, "cut volume {v:.4} not near 1.0");
            check_manifold(&topo, cut);
        }
        Err(_) => {
            // Also acceptable: error if the engine treats face-contact as degenerate
        }
    }
}

#[test]
fn test_kissing_cylinder_box() {
    // Cylinder radius 1, height 2. Box with left face tangent at x=1.
    let mut topo = Topology::new();
    let cyl = make_cylinder(&mut topo, 1.0, 2.0).unwrap();
    let bx = make_box(&mut topo, 4.0, 10.0, 2.0).unwrap();
    transform_solid(&mut topo, bx, &Mat4::translation(1.0, -5.0, 0.0)).unwrap();

    let result = boolean(&mut topo, BooleanOp::Fuse, cyl, bx);
    match result {
        Ok(fused) => {
            let cyl_vol = PI * 1.0 * 1.0 * 2.0;
            let box_vol = 4.0 * 10.0 * 2.0;
            let expected = cyl_vol + box_vol;
            let v = vol(&topo, fused);
            // Volume should be close to sum (tangent, no overlap)
            let rel = (v - expected).abs() / expected;
            assert!(rel < 0.05, "volume {v:.2} not near expected {expected:.2}");
            check_manifold(&topo, fused);
        }
        Err(e) => panic!("kissing cylinder-box fuse failed: {e}"),
    }
}

// ── Thin features ───────────────────────────────────────────────────

#[test]
fn test_boolean_thin_slab() {
    // Box A: 10x10x10. Box B: 10x10x10 offset by (0,0,9.999). Cut A - B.
    let mut topo = Topology::new();
    let a = make_box(&mut topo, 10.0, 10.0, 10.0).unwrap();
    let b = make_box(&mut topo, 10.0, 10.0, 10.0).unwrap();
    transform_solid(&mut topo, b, &Mat4::translation(0.0, 0.0, 9.999)).unwrap();

    let result = boolean(&mut topo, BooleanOp::Cut, a, b);
    match result {
        Ok(cut) => {
            let expected = 10.0 * 10.0 * 9.999;
            let v = vol(&topo, cut);
            let rel = (v - expected).abs() / expected;
            assert!(rel < 0.01, "volume {v:.4} not near expected {expected:.4}");
            check_manifold(&topo, cut);
        }
        Err(e) => panic!("thin slab cut failed: {e}"),
    }
}

#[test]
fn test_boolean_near_tangent() {
    // Two boxes with tiny overlap: A (0,0,0)-(1,1,1), B (0.999,0,0)-(2,1,1).
    let mut topo = Topology::new();
    let a = make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
    let b = make_box(&mut topo, 1.001, 1.0, 1.0).unwrap();
    transform_solid(&mut topo, b, &Mat4::translation(0.999, 0.0, 0.0)).unwrap();

    let result = boolean(&mut topo, BooleanOp::Intersect, a, b);
    match result {
        Ok(inter) => {
            let v = vol(&topo, inter);
            assert!(v > 0.0, "intersection should have positive volume, got {v}");
            assert!(v < 0.01, "intersection should be tiny, got {v}");
            check_manifold(&topo, inter);
        }
        Err(_) => {
            // Acceptable: engine may treat near-tangent as no intersection
        }
    }
}

// ── Degenerate results ──────────────────────────────────────────────

#[test]
fn test_cut_removes_all() {
    // Box A: 1x1x1. Box B: 2x2x2 covering A entirely.
    let mut topo = Topology::new();
    let a = make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
    let b = make_box(&mut topo, 2.0, 2.0, 2.0).unwrap();
    transform_solid(&mut topo, b, &Mat4::translation(-0.5, -0.5, -0.5)).unwrap();

    let result = boolean(&mut topo, BooleanOp::Cut, a, b);
    assert!(result.is_err(), "cutting away everything should return Err");
}

#[test]
fn test_intersect_disjoint() {
    // Two disjoint boxes with no overlap — the intersection is the empty
    // set, returned as a successful zero-face, zero-volume result.
    let mut topo = Topology::new();
    let a = make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
    let b = make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
    transform_solid(&mut topo, b, &Mat4::translation(5.0, 5.0, 5.0)).unwrap();

    let result = boolean(&mut topo, BooleanOp::Intersect, a, b).unwrap();
    assert_eq!(
        brepkit_topology::explorer::solid_faces(&topo, result)
            .unwrap()
            .len(),
        0,
        "disjoint intersect should produce zero faces"
    );
    let vol = solid_volume(&topo, result, 0.05).unwrap();
    assert!(
        vol <= 1e-6,
        "disjoint intersect volume should be ~0, got {vol}"
    );
}

// ── Sequential booleans ─────────────────────────────────────────────

#[test]
fn test_sequential_cuts_volume() {
    // Start with 10x10x10 box. Cut 5 columns (1x1x10 each) at different positions.
    let mut topo = Topology::new();
    let mut current = make_box(&mut topo, 10.0, 10.0, 10.0).unwrap();

    for i in 0..5 {
        let cutter = make_box(&mut topo, 1.0, 1.0, 10.0).unwrap();
        let x = i as f64 * 2.0; // positions 0, 2, 4, 6, 8
        transform_solid(&mut topo, cutter, &Mat4::translation(x, 0.0, 0.0)).unwrap();
        current = boolean(&mut topo, BooleanOp::Cut, current, cutter).unwrap();
    }

    let expected = 1000.0 - 5.0 * 10.0;
    let v = vol(&topo, current);
    let rel = (v - expected).abs() / expected;
    // 2% tolerance: coplanar edge injection for contained faces can
    // slightly change chord-split fragment shapes, affecting volume by ~1%.
    assert!(
        rel < 0.02,
        "sequential cuts volume {v:.2} not near expected {expected:.2}"
    );
    check_manifold(&topo, current);
}

#[test]
fn test_sequential_boolean_vertex_drift() {
    // Perform 10 fuse+cut cycles. Volume should return to original each time.
    let mut topo = Topology::new();
    let base = make_box(&mut topo, 5.0, 5.0, 5.0).unwrap();
    let original_vol = vol(&topo, base);
    let mut current = base;

    for i in 0..10 {
        let addon = make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
        let x = 5.0 + (i as f64) * 0.01; // slightly different each time
        transform_solid(&mut topo, addon, &Mat4::translation(x, 0.0, 0.0)).unwrap();

        let fused = boolean(&mut topo, BooleanOp::Fuse, current, addon).unwrap();

        let cutter = make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
        transform_solid(&mut topo, cutter, &Mat4::translation(x, 0.0, 0.0)).unwrap();

        current = boolean(&mut topo, BooleanOp::Cut, fused, cutter).unwrap();
    }

    let final_vol = vol(&topo, current);
    let drift = (final_vol - original_vol).abs() / original_vol;
    assert!(
        drift < 0.05,
        "vertex drift after 10 cycles: {drift:.4} (original={original_vol:.4}, final={final_vol:.4})"
    );
}

#[test]
fn test_alternating_union_cut() {
    // A|B - C pattern.
    // A: (0-2, 0-1, 0-1), B: (1-3, 0-1, 0-1), C: (1-2, 0-1, 0-1).
    // Use unify_faces=false — this test exercises chord-clipping precision
    // on fuse results; face merging alters intermediate polygon boundaries.
    let no_unify = BooleanOptions {
        unify_faces: false,
        ..Default::default()
    };
    let mut topo = Topology::new();
    let a = make_box(&mut topo, 2.0, 1.0, 1.0).unwrap();
    let b = make_box(&mut topo, 2.0, 1.0, 1.0).unwrap();
    transform_solid(&mut topo, b, &Mat4::translation(1.0, 0.0, 0.0)).unwrap();

    let fused = boolean_with_options(&mut topo, BooleanOp::Fuse, a, b, no_unify).unwrap();
    let fused_vol = vol(&topo, fused);
    let rel_fused = (fused_vol - 3.0).abs() / 3.0;
    assert!(rel_fused < 0.01, "fused volume {fused_vol:.4} not near 3.0");

    let c = make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
    transform_solid(&mut topo, c, &Mat4::translation(1.0, 0.0, 0.0)).unwrap();

    let result = boolean_with_options(&mut topo, BooleanOp::Cut, fused, c, no_unify).unwrap();
    let v = vol(&topo, result);
    let rel = (v - 2.0).abs() / 2.0;
    assert!(rel < 0.01, "A|B - C volume {v:.4} not near 2.0");
    check_manifold(&topo, result);
}

// ── Mixed surfaces ──────────────────────────────────────────────────

#[test]
fn test_boolean_sphere_cylinder() {
    // Sphere radius 2. Cylinder radius 0.5, height 6 through center.
    let mut topo = Topology::new();
    let sphere = make_sphere(&mut topo, 2.0, 16).unwrap();
    let cyl = make_cylinder(&mut topo, 0.5, 6.0).unwrap();
    transform_solid(&mut topo, cyl, &Mat4::translation(0.0, 0.0, -3.0)).unwrap();

    let result = boolean(&mut topo, BooleanOp::Cut, sphere, cyl);
    match result {
        Ok(drilled) => {
            let sphere_vol = 4.0 * PI * 8.0 / 3.0;
            // Cylinder intersection with sphere: height inside sphere = 4.0 (from -2 to 2)
            let cyl_inside_vol = PI * 0.25 * 4.0;
            let expected = sphere_vol - cyl_inside_vol;
            let v = vol(&topo, drilled);
            let rel = (v - expected).abs() / expected;
            assert!(
                rel < 0.10,
                "drilled sphere volume {v:.2} not near expected {expected:.2} (rel={rel:.4})"
            );
            check_manifold(&topo, drilled);
        }
        Err(e) => panic!("sphere-cylinder cut failed: {e}"),
    }
}

#[test]
fn test_boolean_cone_box() {
    // Cone r_bottom=2, r_top=0, height=3. Box 4x4x3.
    let mut topo = Topology::new();
    let cone = make_cone(&mut topo, 2.0, 0.0, 3.0).unwrap();
    let bx = make_box(&mut topo, 4.0, 4.0, 3.0).unwrap();
    transform_solid(&mut topo, bx, &Mat4::translation(-2.0, -2.0, 0.0)).unwrap();

    let result = boolean(&mut topo, BooleanOp::Fuse, cone, bx);
    match result {
        Ok(fused) => {
            let _cone_vol = PI * 4.0 * 3.0 / 3.0; // pi * r^2 * h / 3
            let box_vol = 48.0;
            let v = vol(&topo, fused);
            // Cone is fully inside the box, so fuse volume = box volume
            assert!(
                v > box_vol * 0.95,
                "fused volume {v:.2} should be at least box_vol {box_vol:.2}"
            );
            check_manifold(&topo, fused);
        }
        Err(e) => panic!("cone-box fuse failed: {e}"),
    }
}

#[test]
fn test_boolean_cone_cylinder() {
    // Cone r_bottom=2, r_top=1, height=3. Cylinder radius 0.5, height 3.
    let mut topo = Topology::new();
    let cone = make_cone(&mut topo, 2.0, 1.0, 3.0).unwrap();
    let cyl = make_cylinder(&mut topo, 0.5, 3.0).unwrap();

    let result = boolean(&mut topo, BooleanOp::Cut, cone, cyl);
    match result {
        Ok(cut) => {
            let cone_vol = PI * 3.0 / 3.0 * (4.0 + 2.0 + 1.0); // pi*h/3*(R^2+Rr+r^2)
            let cyl_vol = PI * 0.25 * 3.0;
            let expected = cone_vol - cyl_vol;
            let v = vol(&topo, cut);
            let rel = (v - expected).abs() / expected;
            assert!(
                rel < 0.10,
                "cone-cylinder cut volume {v:.2} not near expected {expected:.2} (rel={rel:.4})"
            );
            check_manifold(&topo, cut);
        }
        Err(e) => panic!("cone-cylinder cut failed: {e}"),
    }
}

// ── Edge/vertex contact ─────────────────────────────────────────────

#[test]
fn test_boolean_shared_edge() {
    // Box A: (0,0,0)-(1,1,1). Box B: (1,1,0)-(2,2,1). Share edge (1,1,0)-(1,1,1).
    let mut topo = Topology::new();
    let a = make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
    let b = make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
    transform_solid(&mut topo, b, &Mat4::translation(1.0, 1.0, 0.0)).unwrap();

    let result = boolean(&mut topo, BooleanOp::Fuse, a, b);
    match result {
        Ok(fused) => {
            let v = vol(&topo, fused);
            let rel = (v - 2.0).abs() / 2.0;
            assert!(rel < 0.01, "fused volume {v:.4} not near 2.0");
            check_manifold(&topo, fused);
        }
        Err(e) => panic!("shared-edge fuse failed: {e}"),
    }
}

#[test]
fn test_boolean_shared_vertex() {
    // Box A: (0,0,0)-(1,1,1). Box B: (1,1,1)-(2,2,2). Share vertex (1,1,1).
    let mut topo = Topology::new();
    let a = make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
    let b = make_box(&mut topo, 1.0, 1.0, 1.0).unwrap();
    transform_solid(&mut topo, b, &Mat4::translation(1.0, 1.0, 1.0)).unwrap();

    let result = boolean(&mut topo, BooleanOp::Fuse, a, b);
    match result {
        Ok(fused) => {
            let v = vol(&topo, fused);
            let rel = (v - 2.0).abs() / 2.0;
            assert!(rel < 0.01, "fused volume {v:.4} not near 2.0");
            check_manifold(&topo, fused);
        }
        Err(e) => panic!("shared-vertex fuse failed: {e}"),
    }
}