ifc-lite-geometry 5.0.0

Geometry processing and mesh generation for IFC models
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

    use super::*;
    use super::geom::*;
    use crate::Mesh;

    /// AABB tuple in the shape `get_opening_item_bounds_with_direction` returns.
    fn aabb(
        min: (f64, f64, f64),
        max: (f64, f64, f64),
    ) -> (Point3<f64>, Point3<f64>, Option<Vector3<f64>>) {
        (
            Point3::new(min.0, min.1, min.2),
            Point3::new(max.0, max.1, max.2),
            None,
        )
    }

    #[test]
    fn spatial_clusters_separate_window_row_split_per_body() {
        // Issue #1367: a row of window voids under one IfcOpeningElement, each
        // separated by a solid pillar -> one cluster per body (subtract per item).
        let boxes: Vec<_> = (0..4)
            .map(|i| {
                let x0 = i as f64 * 2.0;
                aabb((x0, 0.0, 0.0), (x0 + 1.0, 0.3, 1.9))
            })
            .collect();
        assert_eq!(spatial_cluster_count(&boxes), 4);
    }

    #[test]
    fn spatial_clusters_touching_wall_leaf_halves_stay_merged() {
        // FZK-Haus: one window void split into adjacent inner/outer wall-leaf
        // halves (same X/Z footprint, abutting in Y) -> a single cluster (keep
        // merged, so the gable watertightness guard is not regressed).
        let inner = aabb((0.0, 0.0, 0.0), (1.0, 0.485, 0.9));
        let outer = aabb((0.0, 0.485, 0.0), (1.0, 0.9, 0.9));
        assert_eq!(spatial_cluster_count(&[inner, outer]), 1);
    }

    #[test]
    fn spatial_clusters_single_or_empty() {
        assert_eq!(spatial_cluster_count(&[]), 0);
        assert_eq!(
            spatial_cluster_count(&[aabb((0.0, 0.0, 0.0), (1.0, 1.0, 1.0))]),
            1
        );
    }

    fn make_framed_box_mesh(
        origin: Point3<f64>,
        depth_axis: Vector3<f64>,
        cross_a: Vector3<f64>,
        cross_b: Vector3<f64>,
        depth: (f64, f64),
        a: (f64, f64),
        b: (f64, f64),
    ) -> Mesh {
        let point =
            |d: f64, av: f64, bv: f64| origin + depth_axis * d + cross_a * av + cross_b * bv;

        let corners = [
            point(depth.0, a.0, b.0),
            point(depth.1, a.0, b.0),
            point(depth.1, a.1, b.0),
            point(depth.0, a.1, b.0),
            point(depth.0, a.0, b.1),
            point(depth.1, a.0, b.1),
            point(depth.1, a.1, b.1),
            point(depth.0, a.1, b.1),
        ];

        let mut m = Mesh::with_capacity(24, 36);
        let faces: [[usize; 4]; 6] = [
            // Parity-sweep fix: [0, 2, 1, 3] was a crossed (bowtie) quad —
            // see `synthesis::make_box_mesh` for the full rationale.
            [0, 3, 2, 1],
            [4, 5, 6, 7],
            [0, 1, 5, 4],
            [2, 3, 7, 6],
            [0, 4, 7, 3],
            [1, 2, 6, 5],
        ];

        for idx in &faces {
            let edge1 = corners[idx[1]] - corners[idx[0]];
            let edge2 = corners[idx[2]] - corners[idx[0]];
            let normal = edge1
                .cross(&edge2)
                .try_normalize(1e-10)
                .unwrap_or(Vector3::new(0.0, 0.0, 1.0));
            let b = m.vertex_count() as u32;
            m.add_vertex(corners[idx[0]], normal);
            m.add_vertex(corners[idx[1]], normal);
            m.add_vertex(corners[idx[2]], normal);
            m.add_vertex(corners[idx[3]], normal);
            m.add_triangle(b, b + 1, b + 2);
            m.add_triangle(b, b + 2, b + 3);
        }

        m
    }

    /// Build a Z-extruded L-shaped prism. The six vertical walls share the
    /// same ±X/±Y normals as a box but sit at three different X (or Y)
    /// offsets, so a box detector that only counts axes would misclassify it.
    fn make_l_shape_prism_mesh() -> Mesh {
        // Footprint corners CCW in XY plane:
        // (0,0) -> (4,0) -> (4,2) -> (2,2) -> (2,4) -> (0,4) -> back to (0,0)
        let z0 = 0.0;
        let z1 = 1.0;
        let footprint = [
            (0.0_f64, 0.0_f64),
            (4.0, 0.0),
            (4.0, 2.0),
            (2.0, 2.0),
            (2.0, 4.0),
            (0.0, 4.0),
        ];

        let mut m = Mesh::new();
        let n = footprint.len();

        // Vertical walls — each footprint edge becomes one rectangular face.
        for i in 0..n {
            let (x0, y0) = footprint[i];
            let (x1, y1) = footprint[(i + 1) % n];
            let edge = Vector3::new(x1 - x0, y1 - y0, 0.0);
            let z_up = Vector3::new(0.0, 0.0, 1.0);
            let normal = edge
                .cross(&z_up)
                .try_normalize(1e-10)
                .unwrap_or(Vector3::new(1.0, 0.0, 0.0));
            let p0 = Point3::new(x0, y0, z0);
            let p1 = Point3::new(x1, y1, z0);
            let p2 = Point3::new(x1, y1, z1);
            let p3 = Point3::new(x0, y0, z1);
            let b = m.vertex_count() as u32;
            m.add_vertex(p0, normal);
            m.add_vertex(p1, normal);
            m.add_vertex(p2, normal);
            m.add_vertex(p3, normal);
            m.add_triangle(b, b + 1, b + 2);
            m.add_triangle(b, b + 2, b + 3);
        }

        // Caps: fan-triangulate the L footprint at top and bottom.
        let bottom_n = Vector3::new(0.0, 0.0, -1.0);
        let top_n = Vector3::new(0.0, 0.0, 1.0);
        let bottom_base = m.vertex_count() as u32;
        for &(x, y) in &footprint {
            m.add_vertex(Point3::new(x, y, z0), bottom_n);
        }
        let top_base = m.vertex_count() as u32;
        for &(x, y) in &footprint {
            m.add_vertex(Point3::new(x, y, z1), top_n);
        }
        for i in 1..(n as u32 - 1) {
            // Bottom cap winds clockwise so its normal points -Z.
            m.add_triangle(bottom_base, bottom_base + i + 1, bottom_base + i);
            m.add_triangle(top_base, top_base + i, top_base + i + 1);
        }

        m
    }

    #[test]
    fn test_rectangular_box_detector_accepts_clean_box() {
        let opening = make_framed_box_mesh(
            Point3::new(0.0, 0.0, 0.0),
            Vector3::new(0.0, 1.0, 0.0),
            Vector3::new(1.0, 0.0, 0.0),
            Vector3::new(0.0, 0.0, 1.0),
            (-0.15, 0.15),
            (-1.0, 1.0),
            (0.0, 2.0),
        );
        assert!(is_rectangular_box_mesh(&opening));
    }

    #[test]
    fn test_rectangular_box_detector_rejects_l_shape() {
        // An L-shaped vertical shaft has only three face-normal axes
        // (±X, ±Y, ±Z) — the same as a box — but its ±X / ±Y walls sit at
        // three different offsets. Without a per-axis plane-count check the
        // detector would misclassify it as a box and the rectangular cutter
        // would over-cut the AABB of the L.
        let opening = make_l_shape_prism_mesh();
        assert!(
            !is_rectangular_box_mesh(&opening),
            "rectilinear non-box footprints must fall through to NonRectangular CSG"
        );
    }

    /// Regression for #547: a trapezoid extrusion has exactly 3 face-normal
    /// axes after anti-parallel merging (front/back, top/bottom, and the two
    /// slanted sides which merge into one axis), but two of those axes are
    /// not perpendicular. Without an orthogonality check the detector would
    /// classify it as a box and the AABB cutter would over-cut the host wall.
    #[test]
    fn test_rectangular_box_detector_rejects_trapezoid_extrusion() {
        // Trapezoid extruded along +Y: narrow at z=0 (x ∈ [-0.3, 0.3]),
        // wide at z=2 (x ∈ [-0.5, 0.5]), thickness 0.6 in y.
        let mut positions: Vec<f32> = Vec::new();
        let mut indices: Vec<u32> = Vec::new();
        let push_v = |positions: &mut Vec<f32>, x: f32, y: f32, z: f32| {
            positions.extend_from_slice(&[x, y, z]);
        };
        // 8 corners: 4 of trapezoid at y=0, 4 at y=0.6.
        // Order: bl, br, tr, tl on each face (b=bottom narrow, t=top wide).
        push_v(&mut positions, -0.3, 0.0, 0.0); // 0
        push_v(&mut positions, 0.3, 0.0, 0.0); // 1
        push_v(&mut positions, 0.5, 0.0, 2.0); // 2
        push_v(&mut positions, -0.5, 0.0, 2.0); // 3
        push_v(&mut positions, -0.3, 0.6, 0.0); // 4
        push_v(&mut positions, 0.3, 0.6, 0.0); // 5
        push_v(&mut positions, 0.5, 0.6, 2.0); // 6
        push_v(&mut positions, -0.5, 0.6, 2.0); // 7
        // Front (y=0): 0,1,2 + 0,2,3
        indices.extend_from_slice(&[0, 1, 2, 0, 2, 3]);
        // Back (y=0.6): 5,4,7 + 5,7,6
        indices.extend_from_slice(&[5, 4, 7, 5, 7, 6]);
        // Bottom narrow (z=0): 4,5,1 + 4,1,0
        indices.extend_from_slice(&[4, 5, 1, 4, 1, 0]);
        // Top wide (z=2): 3,2,6 + 3,6,7
        indices.extend_from_slice(&[3, 2, 6, 3, 6, 7]);
        // Right slanted: 1,5,6 + 1,6,2
        indices.extend_from_slice(&[1, 5, 6, 1, 6, 2]);
        // Left slanted: 4,0,3 + 4,3,7
        indices.extend_from_slice(&[4, 0, 3, 4, 3, 7]);

        let mut mesh = Mesh::new();
        mesh.positions = positions;
        mesh.indices = indices;
        assert!(
            !is_rectangular_box_mesh(&mesh),
            "trapezoid extrusion must be rejected — its slanted-side axis is \
             not perpendicular to the top/bottom axis, so the AABB cutter would \
             over-cut the host"
        );
    }

    /// A "box" whose top face is beveled by ~20° at one corner (face-normal
    /// dot with the true +Z axis ≈ 0.94). The axis-merge tolerance in
    /// `is_rectangular_box_mesh` must stay tight (0.98, ≈11.5°) so this
    /// bevel is recognised as a genuinely distinct 4th face-normal axis and
    /// rejected — not silently folded into the top face's axis group. Both
    /// triangles share the same first vertex, so the plane-offset check
    /// (1 mm) cannot discriminate: only the merge-tolerance threshold can.
    #[test]
    fn test_rectangular_box_detector_rejects_beveled_corner() {
        let t = 0.363_f64; // dot(tilted normal, +Z) ≈ 0.94: between 0.80 and 0.98
        let n_up = Vector3::new(0.0, 0.0, 1.0);
        let n_down = Vector3::new(0.0, 0.0, -1.0);
        let mut m = Mesh::new();

        // Top: one flat triangle establishing the true +Z axis, plus one
        // beveled triangle sharing the same first vertex.
        let b0 = Point3::new(0.0, 0.0, 1.0);
        let b1 = Point3::new(1.0, 0.0, 1.0);
        let b2 = Point3::new(1.0, 1.0, 1.0);
        let b3 = Point3::new(0.0, 1.0, 1.0);
        let e = Point3::new(1.0, 1.0, 1.0 + t);
        let vb = m.vertex_count() as u32;
        m.add_vertex(b0, n_up);
        m.add_vertex(b1, n_up);
        m.add_vertex(b2, n_up);
        m.add_vertex(b3, n_up);
        m.add_vertex(e, n_up);
        m.add_triangle(vb, vb + 1, vb + 2); // flat: normal exactly +Z
        m.add_triangle(vb, vb + 4, vb + 3); // beveled: normal ≈ 20° off +Z

        // Bottom: flat, normal -Z.
        let a0 = Point3::new(0.0, 0.0, 0.0);
        let a1 = Point3::new(1.0, 0.0, 0.0);
        let a2 = Point3::new(1.0, 1.0, 0.0);
        let a3 = Point3::new(0.0, 1.0, 0.0);
        let va = m.vertex_count() as u32;
        m.add_vertex(a0, n_down);
        m.add_vertex(a1, n_down);
        m.add_vertex(a2, n_down);
        m.add_vertex(a3, n_down);
        m.add_triangle(va, va + 2, va + 1);
        m.add_triangle(va, va + 3, va + 2);

        // Four sides, each a flat quad (±X, ±Y).
        let sides: [[Point3<f64>; 4]; 4] = [
            [
                Point3::new(0.0, 0.0, 0.0),
                Point3::new(0.0, 1.0, 0.0),
                Point3::new(0.0, 1.0, 1.0),
                Point3::new(0.0, 0.0, 1.0),
            ], // x = 0
            [
                Point3::new(1.0, 0.0, 0.0),
                Point3::new(1.0, 1.0, 0.0),
                Point3::new(1.0, 1.0, 1.0),
                Point3::new(1.0, 0.0, 1.0),
            ], // x = 1
            [
                Point3::new(0.0, 0.0, 0.0),
                Point3::new(1.0, 0.0, 0.0),
                Point3::new(1.0, 0.0, 1.0),
                Point3::new(0.0, 0.0, 1.0),
            ], // y = 0
            [
                Point3::new(0.0, 1.0, 0.0),
                Point3::new(1.0, 1.0, 0.0),
                Point3::new(1.0, 1.0, 1.0),
                Point3::new(0.0, 1.0, 1.0),
            ], // y = 1
        ];
        for quad in &sides {
            let edge1 = quad[1] - quad[0];
            let edge2 = quad[3] - quad[0];
            let normal = edge1
                .cross(&edge2)
                .try_normalize(1e-10)
                .unwrap_or(Vector3::new(1.0, 0.0, 0.0));
            let vs = m.vertex_count() as u32;
            m.add_vertex(quad[0], normal);
            m.add_vertex(quad[1], normal);
            m.add_vertex(quad[2], normal);
            m.add_vertex(quad[3], normal);
            m.add_triangle(vs, vs + 1, vs + 2);
            m.add_triangle(vs, vs + 2, vs + 3);
        }

        assert!(
            !is_rectangular_box_mesh(&m),
            "a beveled corner (~20° face-normal tilt) must NOT merge into the \
             top face's axis group — it is a genuinely distinct 4th axis, so \
             the mesh is not a clean box"
        );
    }

    /// A box rotated 45° around Z should still be classified as a box: its
    /// three face-normal axes are mutually orthogonal even though none align
    /// with world axes. The diagonal cutter then handles the rotation.
    #[test]
    fn test_rectangular_box_detector_accepts_rotated_box() {
        let opening = make_framed_box_mesh(
            Point3::new(0.0, 0.0, 0.0),
            Vector3::new(0.7071067811865476, 0.7071067811865476, 0.0),
            Vector3::new(-0.7071067811865476, 0.7071067811865476, 0.0),
            Vector3::new(0.0, 0.0, 1.0),
            (-0.15, 0.15),
            (-1.0, 1.0),
            (0.0, 2.0),
        );
        assert!(
            is_rectangular_box_mesh(&opening),
            "axis-rotated boxes must still be detected — rotation alone does \
             not make them non-rectangular"
        );
    }

    #[test]
    fn test_infers_sloped_brep_opening_frame() {
        // Roof openings exported as BReps do not expose an extrusion direction.
        // The frame must be inferred from the box faces so reveal generation
        // preserves the roof pitch/roll instead of falling back to world axes.
        let depth_axis = Vector3::new(0.0, -0.5, 0.8660254037844386);
        let cross_a = Vector3::new(1.0, 0.0, 0.0);
        let cross_b = depth_axis.cross(&cross_a).normalize();
        let opening = make_framed_box_mesh(
            Point3::new(10.0, 20.0, 5.0),
            depth_axis,
            cross_a,
            cross_b,
            (-0.2, 0.2),
            (-0.8, 0.8),
            (-0.4, 0.4),
        );

        let frame = infer_opening_frame(&opening, None).unwrap();

        assert!(
            frame.depth.dot(&depth_axis).abs() > 0.99,
            "shortest inferred axis should be the sloped roof-window depth"
        );
        assert!(
            frame.cross_a.dot(&cross_a).abs() > 0.99 || frame.cross_b.dot(&cross_a).abs() > 0.99,
            "inferred frame should preserve the opening roll axis"
        );
        assert!(
            !frame.is_axis_aligned(),
            "sloped BRep opening should use the diagonal frame path"
        );
    }

    /// Round-26 mutation-audit fixture for `infer_opening_frame`'s anti-parallel
    /// merge tolerance (geom.rs:703, `normal.dot(axis).abs() > 0.98`, the sibling
    /// of the already-pinned `is_rectangular_box_mesh` tolerance at geom.rs:622).
    ///
    /// Four raw triangles, each its own "face" (one triangle = one normal, no
    /// closed mesh required — `infer_opening_frame` never checks closedness):
    ///   T1: normal = +Z exactly, weight 1.0 (establishes the Z axis group).
    ///   T2: normal tilted from +Z by angle theta (`cos(theta)` = `dot`),
    ///       weight 1.0 — merges into T1's axis via WEIGHTED re-averaging
    ///       when `dot > 0.98`, else becomes its own 4th axis.
    ///   T3: normal = +X exactly.  T4: normal = +Y exactly.
    /// With `extrusion_dir = +Z`, `depth_index` always picks the axis with
    /// the largest `|dot(dir)|`:
    ///   * merged (dot=0.981): only 3 axes exist (mergedZ, X, Y); mergedZ is
    ///     the *average* of Z and the tilted T2 normal, so it is measurably
    ///     tilted away from pure +Z (`frame.depth.z` distinctly < 1.0).
    ///   * NOT merged (dot=0.979): 4 axes exist (Z, X, Y, tilted-T2); T2's
    ///     axis (dot 0.979 with +Z) loses to T1's pure Z axis (dot 1.0), so
    ///     `depth_index` picks T1 UNCONTAMINATED — `frame.depth` is (0,0,1)
    ///     to float precision, `frame.depth.z` is ~1.0, not merely < 1.0.
    ///
    /// A mutant that shifts the 0.98 boundary flips which case a `dot` of
    /// 0.981/0.979 falls into, changing `frame.depth.z` from "clearly < 1"
    /// to "~1" or vice versa.
    fn face_triangle(origin: Point3<f64>, e_a: Vector3<f64>, e_b: Vector3<f64>) -> [Point3<f64>; 3] {
        [origin, origin + e_a, origin + e_b]
    }

    fn tilted_axis_frame_mesh(cos_t: f64, sin_t: f64) -> Mesh {
        let mut m = Mesh::with_capacity(12, 12);
        let n = Vector3::new(0.0, 0.0, 1.0);
        // T1: pure +Z, via e_a=(1,0,0), e_b=(0,1,0).
        let t1 = face_triangle(
            Point3::new(0.0, 0.0, 0.0),
            Vector3::new(1.0, 0.0, 0.0),
            Vector3::new(0.0, 1.0, 0.0),
        );
        // T2: tilted by theta from +Z (dot = cos_t), via
        // e_a=(cos_t,0,-sin_t), e_b=(0,1,0) -> cross = (sin_t,0,cos_t).
        let t2 = face_triangle(
            Point3::new(100.0, 0.0, 0.0),
            Vector3::new(cos_t, 0.0, -sin_t),
            Vector3::new(0.0, 1.0, 0.0),
        );
        // T3: pure +X, via e_a=(0,1,0), e_b=(0,0,1).
        let t3 = face_triangle(
            Point3::new(200.0, 0.0, 0.0),
            Vector3::new(0.0, 1.0, 0.0),
            Vector3::new(0.0, 0.0, 1.0),
        );
        // T4: pure +Y, via e_a=(0,0,1), e_b=(1,0,0).
        let t4 = face_triangle(
            Point3::new(300.0, 0.0, 0.0),
            Vector3::new(0.0, 0.0, 1.0),
            Vector3::new(1.0, 0.0, 0.0),
        );
        for tri in [t1, t2, t3, t4] {
            let b = m.vertex_count() as u32;
            m.add_vertex(tri[0], n);
            m.add_vertex(tri[1], n);
            m.add_vertex(tri[2], n);
            m.add_triangle(b, b + 1, b + 2);
        }
        m
    }

    #[test]
    fn infer_opening_frame_merges_axis_just_inside_098_tolerance() {
        // cos(theta) = 0.981 > 0.98 -> T2 merges into T1's axis; the merged
        // (weighted-average) depth is measurably tilted away from pure +Z.
        let cos_t = 0.981_f64;
        let sin_t = (1.0 - cos_t * cos_t).sqrt();
        let mesh = tilted_axis_frame_mesh(cos_t, sin_t);
        let dir = Vector3::new(0.0, 0.0, 1.0);
        let frame = infer_opening_frame(&mesh, Some(&dir)).expect("3-axis mesh must infer a frame");
        assert!(
            frame.depth.z < 0.999,
            "dot=0.981 must merge T2 into the Z axis, tilting the weighted-average \
             depth measurably away from pure +Z, got depth.z = {}",
            frame.depth.z
        );
    }

    #[test]
    fn infer_opening_frame_keeps_axis_separate_just_outside_098_tolerance() {
        // cos(theta) = 0.979 < 0.98 -> T2 stays a separate 4th axis; T1's
        // pure +Z axis (dot 1.0) beats T2's axis (dot 0.979) for depth_index,
        // so the inferred depth stays UNCONTAMINATED at pure +Z.
        let cos_t = 0.979_f64;
        let sin_t = (1.0 - cos_t * cos_t).sqrt();
        let mesh = tilted_axis_frame_mesh(cos_t, sin_t);
        let dir = Vector3::new(0.0, 0.0, 1.0);
        let frame = infer_opening_frame(&mesh, Some(&dir)).expect("4-axis mesh must infer a frame");
        assert!(
            frame.depth.z > 0.999999,
            "dot=0.979 must NOT merge T2 into the Z axis; the pure T1 axis \
             should win depth_index uncontaminated, got depth.z = {}",
            frame.depth.z
        );
    }

    #[test]
    fn test_perpendicular_corner_openings_do_not_merge() {
        // Issue #1337: FreeCAD/brep openings carry no extrusion direction
        // (dir = None). A window on one wall and a garage-door opening on the
        // PERPENDICULAR wall have AABBs that cross at the building corner —
        // overlapping on all three axes but coinciding on NONE. Collapsing them
        // into one bounding box punches a phantom hole through both walls (the
        // reported corner over-cut). They must stay separate.
        let window = OpeningType::Rectangular(
            Point3::new(1.5, -1.2, 0.9),
            Point3::new(2.7, 1.2, 2.1),
            None,
        );
        let door = OpeningType::Rectangular(
            Point3::new(-2.4, 0.55, 0.0),
            Point3::new(2.4, 2.95, 2.2),
            None,
        );
        let merged = GeometryRouter::merge_rectangular_openings(&[window, door]);
        assert_eq!(
            merged.len(),
            2,
            "perpendicular corner openings (overlap-all-axes, coincide-none) must not merge"
        );
    }

    #[test]
    fn test_deep_box_opening_penetration_axis_is_transversal() {
        // Issue #1337 follow-up: a FreeCAD window cutter is a box 1.2 wide (x),
        // 2.4 DEEP (y, through-wall), 1.2 tall (z). Its thinnest axis is x/z, but
        // it penetrates along y — it pokes past the host's y-bounds. The depth
        // axis for the through-host cap-flush extension must be y, else the push
        // runs vertically and latches onto a neighbouring void's reveal facet
        // (all windows share z[0.9,2.1]), over-cutting the wall.
        let dir = infer_box_penetration_dir(
            &Point3::new(1.5, -1.2, 0.9),
            &Point3::new(2.7, 1.2, 2.1),
            &Point3::new(0.0, 0.0, 0.0),
            &Point3::new(8.4, 6.2, 3.93),
        );
        assert!(dir.y.abs() > 0.99, "deep cutter penetrates along y, got {dir:?}");
    }

    #[test]
    fn test_flush_box_opening_falls_back_to_thinnest_axis() {
        // A flush cutter sized to the wall thickness sits inside the host on
        // every axis -> classic thinnest-axis (the wall normal). Unchanged.
        let dir = infer_box_penetration_dir(
            &Point3::new(1.5, 0.0, 0.9),
            &Point3::new(2.7, 0.4, 2.1),
            &Point3::new(0.0, 0.0, 0.0),
            &Point3::new(8.4, 6.2, 3.93),
        );
        assert!(dir.y.abs() > 0.99, "flush cutter -> thinnest (y), got {dir:?}");
    }

    #[test]
    fn test_aligned_stacked_openings_still_merge() {
        // The merge still collapses the O(2^N) case it exists for: openings that
        // tile a wall coincide on two axes per pair (here X and Y) and are
        // adjacent on the third (Z), so bbox(A,B) == A ∪ B with no phantom volume.
        let lower = OpeningType::Rectangular(
            Point3::new(1.0, 0.0, 0.0),
            Point3::new(2.0, 0.4, 1.0),
            None,
        );
        let upper = OpeningType::Rectangular(
            Point3::new(1.0, 0.0, 1.0),
            Point3::new(2.0, 0.4, 2.0),
            None,
        );
        let merged = GeometryRouter::merge_rectangular_openings(&[lower, upper]);
        assert_eq!(merged.len(), 1, "aligned stacked openings should still merge");
        match &merged[0] {
            OpeningType::Rectangular(mn, mx, _) => {
                assert!(mn.z.abs() < 1e-9 && (mx.z - 2.0).abs() < 1e-9, "merged Z span");
            }
            _ => panic!("expected a merged Rectangular opening"),
        }
    }

    #[test]
    fn test_extend_opening_pads_past_wall_on_exact_match() {
        // Regression test for issue #604: when an opening's depth exactly matches
        // its wall's depth along the extrusion axis, the extended bounds must NOT
        // sit exactly on the wall faces — that produces 0-thickness CSG/clip
        // artifacts. The extension should always overshoot the wall slightly.
        let router = crate::router::GeometryRouter::new();

        // Wall: 0.2 m thick along Y
        let wall_min = Point3::new(0.0, 0.0, 0.0);
        let wall_max = Point3::new(10.0, 0.2, 3.0);
        // Opening exactly fills the wall in Y (0.0..0.2) — the failing case
        let open_min = Point3::new(4.0, 0.0, 1.0);
        let open_max = Point3::new(6.0, 0.2, 2.5);
        let dir = Vector3::new(0.0, 1.0, 0.0);

        let (new_min, new_max) =
            router.extend_opening_along_direction(open_min, open_max, wall_min, wall_max, dir);

        // Both faces must overshoot the wall, not sit exactly on it
        assert!(
            new_min.y < wall_min.y,
            "extended opening min Y {} must be strictly below wall min Y {}",
            new_min.y,
            wall_min.y,
        );
        assert!(
            new_max.y > wall_max.y,
            "extended opening max Y {} must be strictly above wall max Y {}",
            new_max.y,
            wall_max.y,
        );
        // Padding must stay imperceptibly small (<< 1 mm for a 0.2 m wall)
        let back_pad = wall_min.y - new_min.y;
        let fwd_pad = new_max.y - wall_max.y;
        assert!(back_pad > 0.0 && back_pad < 1e-3);
        assert!(fwd_pad > 0.0 && fwd_pad < 1e-3);
        // Cross-axis bounds untouched
        assert_eq!(new_min.x, open_min.x);
        assert_eq!(new_max.x, open_max.x);
        assert_eq!(new_min.z, open_min.z);
        assert_eq!(new_max.z, open_max.z);
    }

    #[test]
    fn test_extend_opening_skipped_when_opening_pokes_past_wall() {
        // Regression for issue #832: a 1×1×0.2 m opening offset so its
        // 0.2 m extrusion depth pokes 0.1 m past the wall's +X face. The
        // Revit "extend to reach the opposite wall face" heuristic would
        // stretch the opening through the wall thickness and the AABB
        // clip would remove BOTH the +X (touched) and -X (un-touched)
        // wall faces — the "punched-through slot" the user reported.
        // The extension must bail out and return the authored bounds.
        let router = crate::router::GeometryRouter::new();

        // Wall: 0.2 m thick along X, 3 m × 3 m face.
        let wall_min = Point3::new(7.9, 0.0, 0.0);
        let wall_max = Point3::new(8.1, 3.0, 3.0);
        // Opening starts inside the wall (x=8.0) and pokes past +X (x=8.2).
        let open_min = Point3::new(8.0, 0.5, 1.0);
        let open_max = Point3::new(8.2, 1.5, 2.0);
        let dir = Vector3::new(1.0, 0.0, 0.0);

        let (new_min, new_max) =
            router.extend_opening_along_direction(open_min, open_max, wall_min, wall_max, dir);

        // Authored bounds must come back UNCHANGED — no extension, no pad.
        assert_eq!(new_min, open_min, "X-poke-out: extension must not change min");
        assert_eq!(new_max, open_max, "X-poke-out: extension must not change max");

        // Same shape mirrored: opening pokes past -X face, extrusion -X.
        let wall_min = Point3::new(5.9, 0.0, 0.0);
        let wall_max = Point3::new(6.1, 3.0, 3.0);
        let open_min = Point3::new(5.8, 0.5, 1.0);
        let open_max = Point3::new(6.0, 1.5, 2.0);
        let dir = Vector3::new(-1.0, 0.0, 0.0);

        let (new_min, new_max) =
            router.extend_opening_along_direction(open_min, open_max, wall_min, wall_max, dir);

        assert_eq!(new_min, open_min, "-X-poke-out: extension must not change min");
        assert_eq!(new_max, open_max, "-X-poke-out: extension must not change max");
    }

    /// Round-26 mutation-audit fixture for `face_align_tol` (synthesis.rs:545,
    /// `(wall_max_proj - wall_min_proj).abs() * 1e-5`, the RECESS/pocket
    /// coplanarity-pad tolerance, issue #853). Existing recess fixtures are
    /// exactly flush (offset = 0), which pins the branch logic but not the
    /// 1e-5 magnitude itself: any nonzero tolerance would still pass them.
    ///
    /// Wall thickness D = 1.0 along Y -> `face_align_tol` = 1.0 * 1e-5 =
    /// 1e-5 exactly. The opening's near face sits at `wall_min.y + offset`;
    /// its far face sits well inside the wall (0.5, far past the tolerance
    /// pad), so `far_inside_max` is true regardless of `offset` and only
    /// `near_at_min_face` (hence `is_recess`) depends on the boundary.
    ///   * offset = 0.9e-5 < face_align_tol -> RECESS -> bounds returned
    ///     UNCHANGED (bit-exact, no extension).
    ///   * offset = 1.1e-5 > face_align_tol -> NOT a recess -> the
    ///     Revit-heuristic extension applies -> `new_min.y` is pulled below
    ///     `open_min.y` (extended past the wall face).
    ///
    /// A mutant that scales `1e-5` by 10,000x (to ~0.1, i.e. 10% of wall
    /// thickness) would misclassify BOTH cases as a recess.
    #[test]
    fn test_extend_opening_recess_face_align_tol_boundary() {
        let router = crate::router::GeometryRouter::new();
        let wall_min = Point3::new(0.0, 0.0, 0.0);
        let wall_max = Point3::new(10.0, 1.0, 3.0); // Y thickness D = 1.0
        let dir = Vector3::new(0.0, 1.0, 0.0);

        // Just INSIDE face_align_tol (1e-5): recess -> unchanged bounds.
        let offset_in = 0.9e-5;
        let open_min_in = Point3::new(0.0, offset_in, 1.0);
        let open_max_in = Point3::new(2.0, 0.5, 1.1);
        let (new_min_in, new_max_in) = router.extend_opening_along_direction(
            open_min_in,
            open_max_in,
            wall_min,
            wall_max,
            dir,
        );
        assert_eq!(
            new_min_in, open_min_in,
            "offset 0.9e-5 < face_align_tol (1e-5): must be read as a recess and left unchanged"
        );
        assert_eq!(new_max_in, open_max_in);

        // Just OUTSIDE face_align_tol (1e-5): not a recess -> extension applies.
        let offset_out = 1.1e-5;
        let open_min_out = Point3::new(0.0, offset_out, 1.0);
        let open_max_out = Point3::new(2.0, 0.5, 1.1);
        let (new_min_out, _new_max_out) = router.extend_opening_along_direction(
            open_min_out,
            open_max_out,
            wall_min,
            wall_max,
            dir,
        );
        assert!(
            new_min_out.y < open_min_out.y,
            "offset 1.1e-5 > face_align_tol (1e-5): must NOT be read as a recess; the \
             extension heuristic should pull the near face below its authored position, \
             got new_min.y = {} vs open_min.y = {}",
            new_min_out.y,
            open_min_out.y,
        );
    }

    #[test]
    fn test_extend_opening_skipped_for_recess_pocket() {
        // Regression coverage for issue #853's RECESS/POCKET pattern: the
        // opening starts exactly on the wall's near face (y=0) but ends well
        // short of the far face (y=0.1 of a 0.2 m-thick wall) — a partial-depth
        // bite authored from one side, not a through-hole. Extending it would
        // silently convert the pocket into a through-hole. This path
        // (`is_recess`) had ZERO unit coverage before this test — neutering it
        // entirely (`let is_recess = false;`) left the full suite green.
        let router = crate::router::GeometryRouter::new();

        let wall_min = Point3::new(0.0, 0.0, 0.0);
        let wall_max = Point3::new(10.0, 0.2, 3.0);
        // Flush with the near (min) face, ends at 0.1 -- well inside, not
        // touching the far face at 0.2.
        let open_min = Point3::new(4.0, 0.0, 1.0);
        let open_max = Point3::new(6.0, 0.1, 2.5);
        let dir = Vector3::new(0.0, 1.0, 0.0);

        let (new_min, new_max) =
            router.extend_opening_along_direction(open_min, open_max, wall_min, wall_max, dir);

        assert_eq!(
            new_min, open_min,
            "a recess's authored min bound must be left unchanged"
        );
        assert_eq!(
            new_max, open_max,
            "a recess must NOT be extended to reach the wall's far face"
        );

        // Mirrored: flush with the FAR face, floats short of the near face.
        let open_min = Point3::new(4.0, 0.1, 1.0);
        let open_max = Point3::new(6.0, 0.2, 2.5);
        let (new_min, new_max) =
            router.extend_opening_along_direction(open_min, open_max, wall_min, wall_max, dir);
        assert_eq!(
            new_min, open_min,
            "a far-flush recess must not be extended toward the near face"
        );
        assert_eq!(new_max, open_max, "a far-flush recess's max bound must be left unchanged");
    }

    /// DETERMINISM (CI-safe, no fixture): the parametric cut on a rotated, building-scale
    /// wall must FIRE, be watertight, emit a local-frame mesh (small positions + origin),
    /// and produce BIT-IDENTICAL output across runs. Bit-identical-across-runs + the
    /// FMA-free f64 arithmetic (`rotate_point`, snap grid) is the native==wasm contract:
    /// every operation is a deterministic f64 op with a single f32 store, so the two
    /// targets cannot diverge.
    #[test]
    fn param_cut_is_deterministic_watertight_and_local_framed() {
        let router = GeometryRouter::new();
        // 37° about Z, right-handed frame (cross_b = depth × cross_a).
        let yaw = 37.0_f64.to_radians();
        let (c, s) = (yaw.cos(), yaw.sin());
        let cross_a = Vector3::new(c, s, 0.0); // wall length axis
        let depth = Vector3::new(-s, c, 0.0); // wall thickness axis
        let cross_b = depth.cross(&cross_a); // wall height axis
        // The cut path sees RTC-rebased (small) coordinates — a national-grid model is
        // re-based to near origin before meshing, so the host f32 mesh is precise. (An
        // un-rebased building-scale mesh correctly FAILS host reconciliation and defers.)
        let center = Point3::new(3.0, 2.0, 5.0);

        // World rotated wall: 4 m (cross_a) × 3 m (cross_b) × 0.3 m thick (depth).
        let host_world = make_framed_box_mesh(
            center, depth, cross_a, cross_b, (-0.15, 0.15), (-2.0, 2.0), (-1.5, 1.5),
        );
        let host = RectParam {
            r: Matrix3::from_columns(&[cross_a, cross_b, depth]),
            center,
            half: [2.0, 1.5, 0.15],
        };
        // A centred window, over-spanning the thickness (through-cut) and well within
        // the wall in-face — fires all the gates.
        let opening = RectParam {
            r: host.r,
            center,
            half: [0.5, 0.5, 0.25],
        };
        let ctx = VoidContext {
            openings: Vec::new(),
            merged_openings: Vec::new(),
            param: Some(ParamRectCut {
                host,
                openings: vec![opening],
            }),
            bool2d: None,
        };

        let out1 = router
            .try_param_rect_cut(&host_world, &ctx)
            .expect("parametric cut must fire on a clean rotated wall");
        let out2 = router
            .try_param_rect_cut(&host_world, &ctx)
            .expect("parametric cut must fire on a clean rotated wall");

        // Bit-identical across runs (⇒ native==wasm by the FMA-free construction).
        assert_eq!(out1.positions, out2.positions, "positions must be deterministic");
        assert_eq!(out1.indices, out2.indices, "indices must be deterministic");
        assert_eq!(out1.normals, out2.normals, "normals must be deterministic");
        assert_eq!(out1.origin, out2.origin, "origin must be deterministic");

        // Local-frame output: origin = wall centre, positions stay SMALL (near 0) so the
        // f32 store survives at national-grid magnitude.
        assert_eq!(out1.origin, [center.x, center.y, center.z]);
        let max_abs = out1
            .positions
            .iter()
            .fold(0.0f32, |m, &v| m.max(v.abs()));
        assert!(max_abs < 10.0, "local-frame positions must stay small (got {max_abs})");

        assert!(param_cut_watertight(&out1), "cut must be watertight");
        assert!(out1.triangle_count() > 12, "the opening must add faces");
    }