ferrocad_occt 0.1.5

OCCT geometry backend for FerroCAD: implements the ferrocad_geom GeometryBackend
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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
//! # FerroCAD OCCT backend (`ferrocad_occt`)
//!
//! The real geometry kernel behind the [`ferrocad_geom`] seam. It implements
//! [`GeometryBackend`](ferrocad_geom::GeometryBackend) with OCCT, through the
//! [`ferrocad_occt_cxx`](https://github.com/ferrocad/ferrocad_occt_cxx) fork of
//! `opencascade-sys`.
//!
//! What stays here is the FreeCAD/`Part` semantics: what a shape operation means,
//! how elements are named and tracked, and how kernel failures become
//! `Part.OCCError`. FreeCAD's `TopoShape` policy is Rust, in `src/policy.rs`.
//!
//! **This crate contains no C++.** Every OCCT call is a generic binding in
//! `opencascade-sys`, composed into Part/FreeCAD behaviour here.
//!
//! The seam means nothing below the application depends on this crate: the document
//! core talks to a `dyn GeometryBackend`, and the application installs
//! [`OcctBackend`] at startup. See `docs/developer/architecture/occt-integration.md`.
//!
//! # Building
//!
//! This crate needs OCCT 7.8+ and is **not** in the workspace's `default-members`,
//! so an ordinary `cargo build`/`cargo test` does not require a kernel. The workspace
//! `.cargo/config.toml` points at `.occt/prefix` automatically; with a custom prefix,
//! export (see `docs/developer/architecture/occt-bundling.md`):
//!
//! ```sh
//! export OCCT_INCLUDE_DIR=<prefix>/include/opencascade   # for build.rs
//! export OpenCASCADE_DIR=<prefix>/lib/cmake/opencascade  # for opencascade-sys
//! export LD_LIBRARY_PATH=<prefix>/lib:$LD_LIBRARY_PATH   # for running tests
//! cargo test -p ferrocad_occt
//! ```
//!
//! # Example
//!
//! ```ignore
//! use ferrocad_geom::GeometryBackend;
//! use ferrocad_occt::OcctBackend;
//!
//! let backend = OcctBackend::new();
//! let a = backend.make_box(10.0, 10.0, 10.0).unwrap();
//! let b = backend.make_box(10.0, 10.0, 10.0).unwrap();
//! let fused = backend.fuse(&a, &b, 0.0).unwrap();
//! assert!(backend.resolve(&fused.shape, "Face1").is_some());
//! ```

mod backend;
pub mod chfi2d;
mod curve;
mod error;
mod history;
mod shape;
pub mod part_ops;
mod policy;
pub mod shapefix;
mod shape_ops;
mod stl;
pub mod surface_ops;
mod surface_frame;
mod topology;

pub use backend::OcctBackend;
pub use curve::BsplineState;
pub use error::OcctError;
pub use shape::{read_brep, write_brep, OcctShape};

/// The OCCT release this backend was compiled against, e.g. `"7.8.1"`.
///
/// Read from `OCC_VERSION_COMPLETE` in the headers `build.rs` located, so it
/// cannot drift from the kernel that is actually linked. The Python surface
/// reports it as `Part.OCC_VERSION`, which upstream's Draft reads to decide
/// whether hidden-line removal is available.
pub const OCC_VERSION: &str = env!("FERROCAD_OCC_VERSION");

#[cfg(test)]
mod tests {
    use super::*;
    use ferrocad_geom::{
        Capabilities, Continuity, ElementKind, FailureKind, GeometryBackend, InvalidReason,
        MassProperties, Shape, TessellationOptions,
    };

    #[test]
    fn make_box_has_six_faces() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        assert!(backend.resolve(&cube, "Face1").is_some());
        assert!(backend.resolve(&cube, "Face6").is_some());
        assert!(backend.resolve(&cube, "Face7").is_none());
    }

    #[test]
    fn a_box_tessellates_with_part_identity() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let mesh = backend
            .tessellate(&cube, &TessellationOptions::default())
            .unwrap();

        assert_eq!(mesh.parts.len(), 6 + 12 + 8);
        assert_eq!(mesh.triangle_count(), 12);
        assert_eq!(mesh.triangle_parts.len(), 12);
        assert!(mesh.triangle_parts.iter().all(|part| *part < 6));

        // Each box edge samples to two points, so one segment per edge.
        assert_eq!(mesh.segment_count(), 12);
        assert!(mesh.segment_parts.iter().all(|part| (6..18).contains(part)));

        assert_eq!(mesh.vertices.len(), 8);
        assert_eq!(mesh.vertex_parts.len(), 8);
        assert!(mesh.vertex_parts.iter().all(|part| (18..26).contains(part)));

        assert_eq!(mesh.part_name(0), Some("Face1"));
        assert_eq!(mesh.part_name(6), Some("Edge1"));
        assert_eq!(mesh.part_name(18), Some("Vertex1"));
        assert!(mesh.normals.is_empty(), "the mesh is flat-shaded");

        let positions = mesh.positions.len();
        assert!(
            mesh.triangles
                .iter()
                .all(|index| (*index as usize) < positions)
        );
        assert!(mesh.edges.iter().all(|index| (*index as usize) < positions));
        assert!(
            mesh.vertices
                .iter()
                .all(|index| (*index as usize) < positions)
        );

        assert!(
            backend
                .capabilities()
                .contains(Capabilities::TESSELLATION | Capabilities::TOPOLOGY)
        );
    }

    #[test]
    fn element_names_round_trip_through_resolve() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();

        for kind in [
            ElementKind::Solid,
            ElementKind::Shell,
            ElementKind::Face,
            ElementKind::Edge,
            ElementKind::Vertex,
        ] {
            let elements = backend.elements(&cube, kind);
            assert!(!elements.is_empty(), "{kind:?} has elements");
            for (index, element) in elements.iter().enumerate() {
                assert_eq!(element.name, format!("{}{}", kind.prefix(), index + 1));
                let resolved = backend
                    .resolve(&cube, &element.name)
                    .unwrap_or_else(|| panic!("{} resolves", element.name));
                let expected = crate::shape::downcast(&element.shape).unwrap();
                let actual = crate::shape::downcast(&resolved).unwrap();
                let expected = expected.borrow();
                let actual = actual.borrow();
                assert!(
                    expected.as_ref().unwrap().IsEqual(actual.as_ref().unwrap()),
                    "{} names the same sub-shape",
                    element.name
                );
            }
        }
    }

    #[test]
    fn ancestors_work_in_both_directions() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let edges = backend.elements(&cube, ElementKind::Edge);
        let faces = backend.elements(&cube, ElementKind::Face);
        assert_eq!(edges.len(), 12);
        assert_eq!(faces.len(), 6);

        for edge in &edges {
            assert_eq!(
                backend.ancestors(&cube, edge, ElementKind::Face).len(),
                2,
                "{} has two adjacent faces",
                edge.name
            );
        }
        for face in &faces {
            assert_eq!(
                backend.ancestors(&cube, face, ElementKind::Edge).len(),
                4,
                "{} has four boundary edges",
                face.name
            );
        }
    }

    #[test]
    fn a_box_corner_is_c0() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let face = backend.elements(&cube, ElementKind::Face)[0].clone();
        let edges = backend.ancestors(&cube, &face, ElementKind::Edge);
        assert_eq!(edges.len(), 4);

        // A rectangle's four sides meet at four corners; opposite pairs share no
        // vertex and report `None`.
        let mut corners = 0;
        for i in 0..edges.len() {
            for j in (i + 1)..edges.len() {
                if let Some(continuity) = backend.continuity(&cube, &edges[i], &edges[j]) {
                    assert_eq!(continuity, Continuity::C0);
                    corners += 1;
                }
            }
        }
        assert_eq!(corners, 4, "four adjacent edge pairs");
    }

    #[test]
    fn chamfer_reports_lineage() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let edge = backend.elements(&cube, ElementKind::Edge)[0].clone();

        let out = backend
            .chamfer(&cube, std::slice::from_ref(&edge), 1.0, None)
            .unwrap();
        assert_eq!(backend.elements(&out.shape, ElementKind::Face).len(), 7);
        assert!(!out.history.is_empty(), "a chamfer changes the topology");
        assert!(
            out.history
                .deleted
                .iter()
                .any(|deleted| deleted.name == edge.name),
            "the seeded edge is consumed"
        );
        assert!(backend.capabilities().contains(Capabilities::CHAMFER));
    }

    #[test]
    fn a_box_edge_has_no_tangent_chain() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let edge = backend.elements(&cube, ElementKind::Edge)[0].clone();
        // Every box edge meets its neighbours at a sharp corner.
        let chain = ferrocad_geom::tangent_chain(&backend, &cube, &edge);
        assert_eq!(chain.len(), 1);
        assert_eq!(chain[0].name, edge.name);
    }

    #[test]
    fn a_fillet_leaves_a_tangent_chain_at_its_boundary() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let edge = backend.elements(&cube, ElementKind::Edge)[0].clone();
        let out = backend
            .fillet(&cube, std::slice::from_ref(&edge), 2.0)
            .unwrap()
            .shape;
        let edges = backend.elements(&out, ElementKind::Edge);

        // The new cylindrical face meets the trimmed planes tangentially, so at least
        // one adjacent edge pair is `G1`.
        let mut tangent = None;
        for i in 0..edges.len() {
            for j in (i + 1)..edges.len() {
                if backend.continuity(&out, &edges[i], &edges[j]) == Some(Continuity::G1) {
                    tangent = Some((i, j));
                }
            }
        }
        let (i, j) = tangent.expect("the fillet boundary is tangent");

        let chain = ferrocad_geom::tangent_chain(&backend, &out, &edges[i]);
        assert!(
            chain.iter().any(|chained| chained.name == edges[j].name),
            "the smooth neighbour joins the chain"
        );
    }

    #[test]
    fn asymmetric_chamfer_builds() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let edge = backend.elements(&cube, ElementKind::Edge)[0].clone();
        let out = backend
            .chamfer(&cube, std::slice::from_ref(&edge), 1.0, Some(2.0))
            .unwrap();
        assert_eq!(backend.elements(&out.shape, ElementKind::Face).len(), 7);
    }

    #[test]
    fn fillet_reports_generated_faces() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let edge = backend.elements(&cube, ElementKind::Edge)[0].clone();
        let out = backend
            .fillet(&cube, std::slice::from_ref(&edge), 1.0)
            .unwrap();
        assert_eq!(backend.elements(&out.shape, ElementKind::Face).len(), 7);
        assert!(
            out.history
                .generated
                .iter()
                .any(|(input, _)| input.name == edge.name),
            "the fillet face is generated from the edge"
        );
        assert!(
            out.history
                .deleted
                .iter()
                .any(|deleted| deleted.name == edge.name)
        );
    }

    #[test]
    fn an_impossible_fillet_reports_not_done_instead_of_aborting() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let edge = backend.elements(&cube, ElementKind::Edge)[0].clone();
        // A radius far larger than the box cannot be built. OCCT's `Shape()` raises
        // `StdFail_NotDone` in this situation, so the seam has to `Build()` and check
        // `IsDone()` first; calling `Shape()` first aborted the process.
        let error = backend
            .fillet(&cube, std::slice::from_ref(&edge), 1.0e6)
            .expect_err("an impossible fillet is an error, not a crash");
        assert!(
            error.to_string().contains("fillet"),
            "the error names the operation: {error}"
        );
    }

    /// A cheap, deterministic fingerprint for non-destructiveness checks.
    fn fingerprint(
        backend: &OcctBackend,
        shape: &Shape,
    ) -> (MassProperties, (usize, usize, usize)) {
        let mass = backend
            .mass_properties(shape)
            .expect("a box has mass properties");
        let faces = backend.elements(shape, ElementKind::Face).len();
        let edges = backend.elements(shape, ElementKind::Edge).len();
        let vertices = backend.elements(shape, ElementKind::Vertex).len();
        (mass, (faces, edges, vertices))
    }

    #[test]
    fn a_foreign_edge_is_rejected_before_the_kernel() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let other = backend.make_box(5.0, 5.0, 5.0).unwrap();
        // An edge that is not part of `cube`. Ownership validation now rejects it
        // up front; without it `Build()` raises `Standard_Failure` ("There are no
        // suitable edges for chamfer or fillet"), and on some OCCT versions a
        // foreign edge can even produce a wrong shape instead of throwing.
        let foreign = backend.elements(&other, ElementKind::Edge)[0].clone();

        let errors = [
            (
                "fillet edge is not part of the shape",
                backend
                    .fillet(&cube, std::slice::from_ref(&foreign), 1.0)
                    .expect_err("a foreign fillet edge is an error, not a crash"),
            ),
            (
                "chamfer edge is not part of the shape",
                backend
                    .chamfer(&cube, std::slice::from_ref(&foreign), 1.0, None)
                    .expect_err("a foreign chamfer edge is an error, not a crash"),
            ),
        ];

        for (what, error) in errors {
            let occt = error
                .downcast_ref::<crate::error::OcctError>()
                .expect("the error is an OcctError");
            assert!(
                matches!(
                    occt,
                    crate::error::OcctError::InvalidInput { what: got } if *got == what
                ),
                "expected early invalid-input rejection, got {occt:?}"
            );
        }
    }

    #[test]
    fn a_non_positive_radius_or_distance_is_invalid_input() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let edge = backend.elements(&cube, ElementKind::Edge)[0].clone();

        for radius in [0.0, -1.0, f64::NAN, f64::INFINITY] {
            let error = backend
                .fillet(&cube, std::slice::from_ref(&edge), radius)
                .expect_err("a non-positive/non-finite radius is invalid input");
            assert!(matches!(
                error.downcast_ref::<crate::error::OcctError>(),
                Some(crate::error::OcctError::InvalidInput { .. })
            ));
        }

        for d1 in [0.0, -1.0, f64::NAN, f64::INFINITY] {
            let error = backend
                .chamfer(&cube, std::slice::from_ref(&edge), d1, None)
                .expect_err("a non-positive/non-finite distance is invalid input");
            assert!(matches!(
                error.downcast_ref::<crate::error::OcctError>(),
                Some(crate::error::OcctError::InvalidInput { .. })
            ));
        }

        // The two-distance form validates the second distance as well.
        for d2 in [0.0, -1.0, f64::NAN, f64::INFINITY] {
            let error = backend
                .chamfer(&cube, std::slice::from_ref(&edge), 1.0, Some(d2))
                .expect_err("a non-positive/non-finite d2 is invalid input");
            assert!(matches!(
                error.downcast_ref::<crate::error::OcctError>(),
                Some(crate::error::OcctError::InvalidInput { .. })
            ));
        }
    }

    #[test]
    fn a_non_positive_fillet_radius_classifies_as_invalid() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let edge = backend.elements(&cube, ElementKind::Edge)[0].clone();

        let error = backend
            .fillet(&cube, std::slice::from_ref(&edge), 0.0)
            .expect_err("a zero radius is invalid input");
        assert_eq!(
            backend.classify(&error),
            FailureKind::Invalid {
                reason: InvalidReason::NonPositiveValue,
                message: error.to_string(),
            }
        );
    }

    #[test]
    fn a_foreign_fillet_edge_classifies_as_invalid() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let other = backend.make_box(5.0, 5.0, 5.0).unwrap();
        let foreign = backend.elements(&other, ElementKind::Edge)[0].clone();

        let error = backend
            .fillet(&cube, std::slice::from_ref(&foreign), 1.0)
            .expect_err("a foreign fillet edge is invalid input");
        assert_eq!(
            backend.classify(&error),
            FailureKind::Invalid {
                reason: InvalidReason::EdgeNotOnShape,
                message: error.to_string(),
            }
        );
    }

    #[test]
    fn a_fillet_refused_by_the_kernel_classifies_as_a_kernel_failure() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let edge = backend.elements(&cube, ElementKind::Edge)[0].clone();

        // A radius far larger than the box gets past this backend's own validation
        // and fails inside the kernel (`Build()` raises, or `IsDone()` is false).
        // That is the kernel failing to execute, not a bad input, so it must be
        // reportable rather than presented as the user's mistake.
        let error = backend
            .fillet(&cube, std::slice::from_ref(&edge), 1.0e6)
            .expect_err("an impossible fillet is an error, not a crash");
        match backend.classify(&error) {
            FailureKind::Kernel { operation, .. } => assert_eq!(operation, "fillet"),
            other => panic!("a kernel refusal must not blame the user, got {other}"),
        }
    }

    #[test]
    fn a_failed_fillet_leaves_the_input_shape_unchanged() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let edge = backend.elements(&cube, ElementKind::Edge)[0].clone();

        let before = fingerprint(&backend, &cube);

        // A radius far larger than the box cannot be built. The operation must
        // fail without mutating the input handle.
        let error = backend
            .fillet(&cube, std::slice::from_ref(&edge), 1.0e6)
            .expect_err("an impossible fillet is an error, not a crash");
        assert!(!error.to_string().is_empty());

        let after = fingerprint(&backend, &cube);
        assert_eq!(before, after, "the failed fillet must not mutate its input");
    }

    #[test]
    fn a_general_transform_applies_a_non_uniform_scale() {
        use ferrocad_types::Matrix4;

        let backend = OcctBackend::new();
        let cube = backend.make_box(1.0, 1.0, 1.0).unwrap();
        let matrix = Matrix4 {
            m: [
                2.0, 0.0, 0.0, 0.0, //
                0.0, 3.0, 0.0, 0.0, //
                0.0, 0.0, 4.0, 0.0, //
                0.0, 0.0, 0.0, 1.0,
            ],
        };

        let out = backend.general_transform(&cube, &matrix).unwrap();
        assert_eq!(backend.elements(&out, ElementKind::Face).len(), 6);
        let props = backend.mass_properties(&out).expect("mass properties");
        assert!(
            (props.volume - 24.0).abs() < 1e-6,
            "a 1x1x1 box scaled by 2,3,4 has volume 24, got {}",
            props.volume
        );
    }

    #[test]
    fn a_placed_box_tessellates_at_its_location() {
        use ferrocad_types::{Placement, Rotation, Vector3};
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let moved = backend
            .place(
                &cube,
                &Placement {
                    base: Vector3::new(10.0, 0.0, 0.0),
                    rotation: Rotation::identity(),
                },
            )
            .unwrap();
        let mesh = backend
            .tessellate(&moved, &TessellationOptions::absolute(0.5))
            .unwrap();
        let min_x = mesh
            .positions
            .iter()
            .map(|position| position[0])
            .fold(f32::INFINITY, f32::min);
        assert!(
            (min_x - 10.0).abs() < 1e-3,
            "location applied: min x = {min_x}"
        );
    }

    #[test]
    fn a_moved_box_carries_its_geometry_as_a_location() {
        use ferrocad_types::{Placement, Rotation, Vector3};
        let backend = OcctBackend::new();
        let cube = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let placed = Placement {
            base: Vector3::new(10.0, 0.0, 0.0),
            rotation: Rotation::identity(),
        };
        let moved = backend.moved(&cube, &placed).unwrap();

        // A distinct handle, and the same body: a placement write must not turn into an
        // edit of the geometry (the memo keys on the handle, so a new identity is what
        // keeps them apart).
        assert!(!cube.is_same(&moved));
        assert_eq!(
            backend.elements(&moved, ElementKind::Face).len(),
            backend.elements(&cube, ElementKind::Face).len(),
            "a move keeps the faces"
        );
        let volume = backend.mass_properties(&moved).expect("mass").volume;
        let original = backend.mass_properties(&cube).expect("mass").volume;
        assert!((volume - original).abs() < 1e-6, "a rigid move keeps the volume");

        // Tessellation applies the location, so the mesh is the placed body — this is what
        // makes the representation invisible to everything downstream.
        let mesh = backend
            .tessellate(&moved, &TessellationOptions::absolute(0.5))
            .unwrap();
        let min_x = mesh
            .positions
            .iter()
            .map(|position| position[0])
            .fold(f32::INFINITY, f32::min);
        assert!(
            (min_x - 10.0).abs() < 1e-3,
            "the mesh is the placed body: min x = {min_x}"
        );
    }

    #[test]
    fn fuse_reports_face_lineage() {
        let backend = OcctBackend::new();
        let a = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let b = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let out = backend.fuse(&a, &b, 0.0).unwrap();
        assert!(!out.history.is_empty());
        assert!(out.history.deleted.is_empty());
    }

    #[test]
    fn cut_removes_material() {
        let backend = OcctBackend::new();
        let a = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let b = backend.make_box(10.0, 10.0, 10.0).unwrap();
        let out = backend.cut(&a, &b, 0.0).unwrap();
        assert!(!out.history.is_empty());
    }

    #[test]
    fn place_and_resolve() {
        use ferrocad_types::{Placement, Rotation, Vector3};
        let backend = OcctBackend::new();
        let cube = backend.make_box(1.0, 1.0, 1.0).unwrap();
        let moved = backend
            .place(
                &cube,
                &Placement {
                    base: Vector3::new(5.0, 0.0, 0.0),
                    rotation: Rotation::identity(),
                },
            )
            .unwrap();
        assert!(backend.resolve(&moved, "Face1").is_some());
        assert!(!cube.is_same(&moved));
    }

    #[test]
    fn rejects_a_foreign_shape() {
        use ferrocad_geom::NullBackend;
        let occt = OcctBackend::new();
        let foreign = NullBackend.make_box(1.0, 1.0, 1.0).unwrap();
        assert_eq!(occt.resolve(&foreign, "Face1"), None);
    }

    #[test]
    fn a_line_segment_makes_an_edge_and_reports_its_basis_line() {
        use ferrocad_curves::{EdgeCurve, LineSegment, Vector3};
        let backend = OcctBackend::new();
        let segment = EdgeCurve::LineSegment(
            LineSegment::new(Vector3::new(1.0, 2.0, 3.0), Vector3::new(4.0, 2.0, 3.0)).unwrap(),
        );
        let edge = backend.make_edge(&segment).unwrap();
        let curve = backend.curve_of(&edge).unwrap();
        let EdgeCurve::Line(line) = curve else {
            panic!("a segment's basis curve is a line, got {curve:?}");
        };
        assert!(line.distance_to(Vector3::new(1.0, 2.0, 3.0)) < 1e-9);
        assert!(line.distance_to(Vector3::new(4.0, 2.0, 3.0)) < 1e-9);
        assert!((line.direction().sub(&Vector3::new(1.0, 0.0, 0.0))).length() < 1e-9);
    }

    #[test]
    fn a_circle_round_trips_through_an_edge() {
        use ferrocad_curves::{Circle, EdgeCurve, Vector3};
        let backend = OcctBackend::new();
        let circle = Circle::new(
            Vector3::new(1.0, 2.0, 3.0),
            Vector3::new(0.0, 0.0, 1.0),
            5.0,
        )
        .unwrap();
        let edge = backend.make_edge(&EdgeCurve::Circle(circle)).unwrap();
        let EdgeCurve::Circle(back) = backend.curve_of(&edge).unwrap() else {
            panic!("a full circle edge is a circle");
        };
        assert!((back.center().sub(&circle.center())).length() < 1e-9);
        assert!((back.radius() - 5.0).abs() < 1e-9);
        assert!((back.normal().sub(&Vector3::new(0.0, 0.0, 1.0))).length() < 1e-9);
    }

    #[test]
    fn an_arc_round_trips_with_its_sweep_and_endpoints() {
        use ferrocad_curves::{Arc, Circle, EdgeCurve, Vector3};
        use std::f64::consts::FRAC_PI_2;
        let backend = OcctBackend::new();
        let circle = Circle::new(Vector3::zero(), Vector3::new(0.0, 0.0, 1.0), 2.0).unwrap();
        let arc = Arc::new(circle, 0.0, FRAC_PI_2).unwrap();
        let edge = backend.make_edge(&EdgeCurve::Arc(arc)).unwrap();
        let EdgeCurve::Arc(back) = backend.curve_of(&edge).unwrap() else {
            panic!("a trimmed arc edge is an arc");
        };
        assert!((back.circle().radius() - 2.0).abs() < 1e-9);
        assert!((back.sweep().abs() - FRAC_PI_2).abs() < 1e-9);
        assert!(back.start().distance(&arc.start()) < 1e-9);
        assert!(back.end().distance(&arc.end()) < 1e-9);
    }

    #[test]
    fn make_edge_builds_the_bounded_kinds_and_rejects_an_infinite_line() {
        use ferrocad_curves::{EdgeCurve, Ellipse, Line, Vector3};
        let backend = OcctBackend::new();
        let line =
            EdgeCurve::Line(Line::new(Vector3::zero(), Vector3::new(1.0, 0.0, 0.0)).unwrap());
        assert!(backend.make_edge(&line).is_err());
        let ellipse = EdgeCurve::Ellipse(
            Ellipse::new(Vector3::zero(), Vector3::new(0.0, 0.0, 1.0), 3.0, 1.0).unwrap(),
        );
        let edge = backend
            .make_edge(&ellipse)
            .expect("an ellipse now has an exact gp_Elips edge");
        let EdgeCurve::Ellipse(back) = backend.curve_of(&edge).unwrap() else {
            panic!("an elliptical edge reports its basis ellipse");
        };
        assert!((back.major_radius() - 3.0).abs() < 1e-9);
        assert!((back.minor_radius() - 1.0).abs() < 1e-9);
    }

    #[test]
    fn an_elliptical_arc_round_trips_with_its_bounds() {
        use ferrocad_curves::{EdgeCurve, Ellipse, Vector3};
        let backend = OcctBackend::new();
        let ellipse = Ellipse::with_axis(
            Vector3::new(1.0, 2.0, 3.0),
            Vector3::new(0.0, 0.0, 1.0),
            Vector3::new(1.0, 0.0, 0.0),
            3.0,
            1.0,
        )
        .unwrap();
        let arc = ellipse.trim(0.25, 1.5).unwrap();
        let edge = backend.make_edge(&EdgeCurve::EllipticalArc(arc)).unwrap();
        let EdgeCurve::EllipticalArc(back) = backend.curve_of(&edge).unwrap() else {
            panic!("a trimmed ellipse edge is an elliptical arc");
        };
        assert!((back.first() - 0.25).abs() < 1e-9);
        assert!((back.last() - 1.5).abs() < 1e-9);
        assert!((back.ellipse().major_radius() - 3.0).abs() < 1e-9);
        assert!((back.ellipse().minor_radius() - 1.0).abs() < 1e-9);
        assert!(back.start().distance(&arc.start()) < 1e-9);
        assert!(back.end().distance(&arc.end()) < 1e-9);
    }

    #[test]
    fn a_hyperbola_arc_round_trips_with_its_frame_and_bounds() {
        use ferrocad_curves::{ArcOfHyperbola, EdgeCurve, Hyperbola, Vector3};
        let backend = OcctBackend::new();
        let hyperbola = Hyperbola::with_axis(
            Vector3::new(1.0, 2.0, 3.0),
            Vector3::new(0.0, 0.0, 1.0),
            Vector3::new(1.0, 0.0, 0.0),
            2.0,
            1.0,
        )
        .unwrap();
        let arc = ArcOfHyperbola::new(hyperbola, -0.5, 0.75).unwrap();
        let edge = backend.make_edge(&EdgeCurve::ArcOfHyperbola(arc)).unwrap();
        let EdgeCurve::ArcOfHyperbola(back) = backend.curve_of(&edge).unwrap() else {
            panic!("a trimmed hyperbola edge is an arc of hyperbola");
        };
        assert!((back.first() - -0.5).abs() < 1e-9);
        assert!((back.last() - 0.75).abs() < 1e-9);
        assert!((back.hyperbola().major_radius() - 2.0).abs() < 1e-9);
        assert!((back.hyperbola().minor_radius() - 1.0).abs() < 1e-9);
        assert!(back.start().distance(&arc.start()) < 1e-9);
        assert!(back.end().distance(&arc.end()) < 1e-9);
    }

    #[test]
    fn a_parabola_arc_round_trips_with_its_frame_and_bounds() {
        use ferrocad_curves::{ArcOfParabola, EdgeCurve, Parabola, Vector3};
        let backend = OcctBackend::new();
        let parabola = Parabola::with_axis(
            Vector3::new(1.0, 2.0, 3.0),
            Vector3::new(0.0, 0.0, 1.0),
            Vector3::new(1.0, 0.0, 0.0),
            0.5,
        )
        .unwrap();
        let arc = ArcOfParabola::new(parabola, -1.0, 2.0).unwrap();
        let edge = backend.make_edge(&EdgeCurve::ArcOfParabola(arc)).unwrap();
        let EdgeCurve::ArcOfParabola(back) = backend.curve_of(&edge).unwrap() else {
            panic!("a trimmed parabola edge is an arc of parabola");
        };
        assert!((back.first() - -1.0).abs() < 1e-9);
        assert!((back.last() - 2.0).abs() < 1e-9);
        assert!((back.parabola().focal() - 0.5).abs() < 1e-9);
        assert!(back.start().distance(&arc.start()) < 1e-9);
        assert!(back.end().distance(&arc.end()) < 1e-9);
    }

    #[test]
    fn a_bezier_edge_round_trips_with_poles_weights_and_bounds() {
        use ferrocad_curves::{BezierCurve, EdgeCurve, Vector3};
        let backend = OcctBackend::new();
        let poles = vec![
            Vector3::new(0.0, 0.0, 0.0),
            Vector3::new(1.0, 2.0, 0.0),
            Vector3::new(2.0, 0.0, 0.0),
        ];
        let bezier = BezierCurve::new(poles.clone(), vec![1.0, 1.0, 1.0]).unwrap();
        let edge = backend.make_edge(&EdgeCurve::BezierCurve(bezier.clone())).unwrap();
        let EdgeCurve::BezierCurve(back) = backend.curve_of(&edge).unwrap() else {
            panic!("a Bezier edge reports a Bezier curve");
        };
        assert_eq!(back.poles(), poles.as_slice());
        assert_eq!(back.weights(), &[1.0, 1.0, 1.0]);
        assert!((back.first() - 0.0).abs() < 1e-12);
        assert!((back.last() - 1.0).abs() < 1e-12);
        for parameter in [0.0, 0.25, 0.5, 0.75, 1.0] {
            assert!(back.point_at(parameter).distance(&bezier.point_at(parameter)) < 1e-9);
        }
    }

    #[test]
    fn a_rational_bspline_edge_round_trips_with_its_data_and_bounds() {
        use ferrocad_curves::{EdgeCurve, NurbsCurve, Vector3};
        let backend = OcctBackend::new();
        let curve = NurbsCurve::new(
            2,
            vec![0.0, 2.0],
            vec![3, 3],
            vec![
                Vector3::new(0.0, 0.0, 0.0),
                Vector3::new(1.0, 1.0, 0.0),
                Vector3::new(2.0, 0.0, 0.0),
            ],
            vec![1.0, 0.5, 1.0],
        )
        .unwrap();
        let edge = backend.make_edge(&EdgeCurve::BSplineCurve(curve.clone())).unwrap();
        let EdgeCurve::BSplineCurve(back) = backend.curve_of(&edge).unwrap() else {
            panic!("a B-spline edge reports a B-spline curve");
        };
        assert_eq!(back.degree(), 2);
        assert_eq!(back.poles(), curve.poles());
        assert_eq!(back.weights(), curve.weights());
        assert_eq!(back.knots(), &[0.0, 2.0]);
        assert!((back.first() - 0.0).abs() < 1e-12);
        assert!((back.last() - 2.0).abs() < 1e-12);
        for parameter in [0.0, 0.5, 1.0, 1.5, 2.0] {
            assert!(back.point_at(parameter).unwrap().distance(&curve.point_at(parameter).unwrap()) < 1e-9);
        }
    }

    #[test]
    fn a_trimmed_bspline_edge_keeps_the_trim_range() {
        use ferrocad_curves::{EdgeCurve, NurbsCurve, Vector3};
        let backend = OcctBackend::new();
        let curve = NurbsCurve::new(
            2,
            vec![0.0, 2.0],
            vec![3, 3],
            vec![
                Vector3::new(0.0, 0.0, 0.0),
                Vector3::new(1.0, 1.0, 0.0),
                Vector3::new(2.0, 0.0, 0.0),
            ],
            vec![1.0, 1.0, 1.0],
        )
        .unwrap();
        let edge = backend
            .make_edge(&EdgeCurve::BSplineCurve(curve))
            .unwrap();
        let pieces = backend.split_edge(&edge, &[0.7, 1.3]).unwrap();
        let edges = backend.elements(&pieces, ElementKind::Edge);
        assert_eq!(edges.len(), 3);
        let EdgeCurve::BSplineCurve(back) = backend.curve_of(&edges[1].shape).unwrap() else {
            panic!("a trimmed B-spline edge still reports a B-spline");
        };
        assert!((back.first() - 0.7).abs() < 1e-9, "first was {}", back.first());
        assert!((back.last() - 1.3).abs() < 1e-9, "last was {}", back.last());
    }

    #[test]
    fn an_offset_curve_edge_round_trips_with_its_basis_and_offset() {
        use ferrocad_curves::{Circle, EdgeCurve, OffsetCurve, Vector3};
        let backend = OcctBackend::new();
        let circle = Circle::new(Vector3::zero(), Vector3::new(0.0, 0.0, 1.0), 2.0).unwrap();
        let basis = EdgeCurve::Circle(circle);
        let offset = OffsetCurve::new(
            basis.clone(),
            0.5,
            Vector3::new(0.0, 0.0, 1.0),
            0.0,
            std::f64::consts::TAU,
        )
        .unwrap();
        let edge = backend.make_edge(&EdgeCurve::OffsetCurve(offset.clone())).unwrap();
        let EdgeCurve::OffsetCurve(back) = backend.curve_of(&edge).unwrap() else {
            panic!("an offset edge reports an offset curve");
        };
        assert!((back.offset() - 0.5).abs() < 1e-9);
        assert!(back.direction().sub(&Vector3::new(0.0, 0.0, 1.0)).length() < 1e-9);
        assert_eq!(back.basis().kind(), "Circle");
        assert!((back.first() - 0.0).abs() < 1e-9);
        assert!((back.last() - std::f64::consts::TAU).abs() < 1e-9);
        assert!((back.point_at(0.0).length() - 2.5).abs() < 1e-9);
    }

    #[test]
    fn curve_of_a_non_edge_is_unsupported() {
        let backend = OcctBackend::new();
        let cube = backend.make_box(1.0, 1.0, 1.0).unwrap();
        assert!(backend.curve_of(&cube).is_err());
    }
}