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
//! Tessellation, element enumeration, adjacency and fillet/chamfer lineage over OCCT.
//!
//! The neutral types live in [`ferrocad_geom`]; this module is the OCCT reading of
//! them. Two OCCT behaviours drive the implementation:
//!
//! - enumerate sub-shapes with `TopExp::MapShapes`, not `TopExp_Explorer` (the
//!   explorer visits a shared edge once per adjacent face);
//! - `TopExp::MapShapesAndAncestors` is ancestor-only: it maps a sub-shape to its
//!   containing elements, so the descendant direction needs an explorer.

use cxx::UniquePtr;
use ferrocad_geom::{
    Continuity, ElementKind, ElementRef, GeomError, History, OpResult, Shape, Tessellation,
    TessellationOptions,
};
use opencascade_sys as ffi;

use ffi::top_abs::{TopAbs_Orientation, TopAbs_ShapeEnum};
use ffi::top_tools::TopTools_IndexedMapOfShape;
use ffi::topo_ds::{TopoDS, TopoDS_Shape};

use crate::error::OcctError;
use crate::history;
use crate::shape::{downcast, erase, find_index_same, new_map, sub_shape_map};

type Map = TopTools_IndexedMapOfShape;

/// The OCCT enumeration for a neutral element kind.
fn shape_enum(kind: ElementKind) -> TopAbs_ShapeEnum {
    match kind {
        ElementKind::Solid => TopAbs_ShapeEnum::TopAbs_SOLID,
        ElementKind::Shell => TopAbs_ShapeEnum::TopAbs_SHELL,
        ElementKind::Face => TopAbs_ShapeEnum::TopAbs_FACE,
        ElementKind::Wire => TopAbs_ShapeEnum::TopAbs_WIRE,
        ElementKind::Edge => TopAbs_ShapeEnum::TopAbs_EDGE,
        ElementKind::Vertex => TopAbs_ShapeEnum::TopAbs_VERTEX,
    }
}

/// The neutral kind of an OCCT sub-shape, when it has one.
fn kind_of(shape: &TopoDS_Shape) -> Option<ElementKind> {
    match shape.ShapeType() {
        TopAbs_ShapeEnum::TopAbs_SOLID => Some(ElementKind::Solid),
        TopAbs_ShapeEnum::TopAbs_SHELL => Some(ElementKind::Shell),
        TopAbs_ShapeEnum::TopAbs_FACE => Some(ElementKind::Face),
        TopAbs_ShapeEnum::TopAbs_WIRE => Some(ElementKind::Wire),
        TopAbs_ShapeEnum::TopAbs_EDGE => Some(ElementKind::Edge),
        TopAbs_ShapeEnum::TopAbs_VERTEX => Some(ElementKind::Vertex),
        _ => None,
    }
}

/// Coarsest to finest. Used to decide which way an adjacency query must go.
fn rank(kind: ElementKind) -> u8 {
    match kind {
        ElementKind::Solid => 0,
        ElementKind::Shell => 1,
        ElementKind::Face => 2,
        ElementKind::Wire => 3,
        ElementKind::Edge => 4,
        ElementKind::Vertex => 5,
    }
}

/// The `index`-th (1-based) element of `map`, named after its kind and position.
fn element_ref(map: &Map, index: i32, kind: ElementKind) -> ElementRef {
    ElementRef {
        shape: erase(map.FindKey(index)),
        name: format!("{}{index}", kind.prefix()),
    }
}

/// The index of `shape` in `map`, ignoring orientation, or `None`.
fn index_in(map: &Map, shape: &TopoDS_Shape) -> Option<i32> {
    let index = find_index_same(map, shape);
    (index > 0).then_some(index)
}

/// The bounding-box diagonal, for a scale-derived tessellation deflection.
fn bounding_diagonal(shape: &TopoDS_Shape) -> f64 {
    let mut bbox = ffi::bnd::Bnd_Box_new();
    ffi::b_rep_bnd_lib::BRepBndLib::Add(shape, bbox.pin_mut(), false);
    if bbox.IsVoid() {
        return 0.0;
    }
    let (mut x_min, mut y_min, mut z_min) = (0.0, 0.0, 0.0);
    let (mut x_max, mut y_max, mut z_max) = (0.0, 0.0, 0.0);
    bbox.Get(
        &mut x_min, &mut y_min, &mut z_min, &mut x_max, &mut y_max, &mut z_max,
    );
    ((x_max - x_min).powi(2) + (y_max - y_min).powi(2) + (z_max - z_min).powi(2)).sqrt()
}

/// The linear deflection `options` asks for, in model units.
fn deflection(s: &TopoDS_Shape, options: &TessellationOptions) -> f64 {
    let diagonal = bounding_diagonal(s);
    match options.linear_deflection {
        Some(d) if options.relative => d * diagonal.max(1e-9),
        Some(d) => d,
        None => (diagonal * 1e-3).max(1e-6),
    }
}

/// The validated `(linear, angular)` deflections for OCCT's mesher.
///
/// OCCT takes a linear chord deflection and a maximum angular deviation; both
/// decide the triangle count. Passing the linear value alone would leave OCCT's
/// default angular deflection (0.5 rad) in charge, which is why a sphere keeps the
/// same mesh for every coarse linear value.
fn mesh_deflections(
    s: &TopoDS_Shape,
    options: &TessellationOptions,
) -> Result<(f64, f64), GeomError> {
    let linear = deflection(s, options);
    let angular = options.angular_deflection;
    if !linear.is_finite() || linear <= 0.0 {
        return Err(OcctError::InvalidInput {
            what: "linear deflection must be positive and finite",
        }
        .into());
    }
    if !angular.is_finite() || angular <= 0.0 || angular >= std::f64::consts::PI {
        return Err(OcctError::InvalidInput {
            what: "angular deflection must be in (0, pi) radians",
        }
        .into());
    }
    Ok((linear, angular))
}

/// Tessellate `shape` into one mesh whose triangles, segments and vertices carry
/// their sub-element part id.
///
/// The mesh is flat-shaded (`normals` is empty): positions from faces, edges and
/// vertices share one array, so per-vertex normals would have to cover all three.
pub(crate) fn tessellate(
    shape: &Shape,
    options: &TessellationOptions,
) -> Result<Tessellation, GeomError> {
    let occt = downcast(shape)?;
    let guard = occt.borrow();
    let s = guard
        .as_ref()
        .ok_or(OcctError::InvalidInput { what: "null shape" })?;

    let (linear, angular) = mesh_deflections(s, options)?;
    let mesh = ffi::b_rep_mesh::IncrementalMesh_new_parallel(s, linear, false, angular, true);
    if !mesh.IsDone() {
        return Err(OcctError::NotDone {
            operation: "tessellate",
        }
        .into());
    }

    let faces = sub_shape_map(s, TopAbs_ShapeEnum::TopAbs_FACE);
    let edges = sub_shape_map(s, TopAbs_ShapeEnum::TopAbs_EDGE);
    let vertices = sub_shape_map(s, TopAbs_ShapeEnum::TopAbs_VERTEX);
    let face_count = faces.Extent() as u32;
    let edge_count = edges.Extent() as u32;

    let mut out = Tessellation::default();
    for index in 1..=face_count as i32 {
        out.parts.push(format!("Face{index}"));
    }
    for index in 1..=edge_count as i32 {
        out.parts.push(format!("Edge{index}"));
    }
    for index in 1..=vertices.Extent() {
        out.parts.push(format!("Vertex{index}"));
    }

    // Faces: each face's triangulation is flattened into the shared arrays, so the
    // per-face vertex duplication the picker needs is preserved.
    for face_index in 1..=faces.Extent() {
        let face_shape = faces.FindKey(face_index);
        let face = TopoDS::Face(face_shape);
        let mut location = ffi::top_loc::Location_new();
        let handle = ffi::b_rep::BRep_Tool_Triangulation(face, location.pin_mut());
        if handle.IsNull() {
            continue;
        }
        let triangulation = ffi::poly::Handle_Poly_Triangulation_Get(&handle).map_err(|_| {
            OcctError::InvalidInput {
                what: "null triangulation",
            }
        })?;
        let trsf = ffi::top_loc::TopLoc_Location_Transformation(&location);
        let reversed = matches!(
            face_shape.Orientation(),
            TopAbs_Orientation::TopAbs_REVERSED
        );

        let base = out.positions.len() as u32;
        for node in 1..=triangulation.NbNodes() {
            let mut point = ffi::poly::Poly_Triangulation_Node(triangulation, node);
            point.pin_mut().Transform(&trsf);
            out.positions
                .push([point.X() as f32, point.Y() as f32, point.Z() as f32]);
        }
        for triangle_index in 1..=triangulation.NbTriangles() {
            let triangle = triangulation.Triangle(triangle_index);
            let a = base + (triangle.Value(1) - 1) as u32;
            let b = base + (triangle.Value(2) - 1) as u32;
            let c = base + (triangle.Value(3) - 1) as u32;
            // OCCT stores the face orientation separately; flip the winding so the
            // renderer's flat normal points out of the solid.
            if reversed {
                out.triangles.extend([a, c, b]);
            } else {
                out.triangles.extend([a, b, c]);
            }
            out.triangle_parts.push((face_index - 1) as u32);
        }
    }

    // Edges: one polyline per topological edge, sampled from its curve rather than
    // from the face triangulations (which duplicate shared edges).
    for edge_index in 1..=edges.Extent() {
        let edge = TopoDS::Edge(edges.FindKey(edge_index));
        let curve = ffi::b_rep_adaptor::BRepAdaptor_Curve_new(edge);
        let sampler =
            ffi::gc_pnts::TangentialDeflection_new(&curve, angular, linear);
        let points = sampler.NbPoints();
        if points < 2 {
            continue;
        }
        let base = out.positions.len() as u32;
        for point_index in 1..=points {
            let point = ffi::gc_pnts::GCPnts_TangentialDeflection_Value(&sampler, point_index);
            out.positions
                .push([point.X() as f32, point.Y() as f32, point.Z() as f32]);
        }
        for segment in 0..(points - 1) {
            out.edges.push(base + segment as u32);
            out.edges.push(base + segment as u32 + 1);
            out.segment_parts.push(face_count + (edge_index - 1) as u32);
        }
    }

    // Vertices: one position each, so a vertex pick has geometry.
    for vertex_index in 1..=vertices.Extent() {
        let vertex = TopoDS::Vertex(vertices.FindKey(vertex_index));
        let point = ffi::b_rep::BRep_Tool_Pnt(vertex);
        out.positions
            .push([point.X() as f32, point.Y() as f32, point.Z() as f32]);
        out.vertices.push((out.positions.len() - 1) as u32);
        out.vertex_parts
            .push(face_count + edge_count + (vertex_index - 1) as u32);
    }

    Ok(out)
}

/// The face triangulations of `shape` in double precision (`Shape.tessellate`).
///
/// [`tessellate`] narrows its positions to `f32` because they feed the viewport;
/// the Python API promises upstream's `Base.Vector` precision, so this reads the
/// same `Poly_Triangulation` nodes without narrowing them. Positions stay per
/// face (duplicated along shared edges), exactly as the display mesh has them;
/// the caller welds them.
pub(crate) fn tessellate_points(
    shape: &Shape,
    options: &TessellationOptions,
) -> Result<(Vec<[f64; 3]>, Vec<u32>), GeomError> {
    let occt = downcast(shape)?;
    let guard = occt.borrow();
    let s = guard
        .as_ref()
        .ok_or(OcctError::InvalidInput { what: "null shape" })?;

    let (linear, angular) = mesh_deflections(s, options)?;
    let mesh = ffi::b_rep_mesh::IncrementalMesh_new_parallel(s, linear, false, angular, true);
    if !mesh.IsDone() {
        return Err(OcctError::NotDone {
            operation: "tessellate",
        }
        .into());
    }

    let faces = sub_shape_map(s, TopAbs_ShapeEnum::TopAbs_FACE);
    let mut positions: Vec<[f64; 3]> = Vec::new();
    let mut triangles: Vec<u32> = Vec::new();
    for face_index in 1..=faces.Extent() {
        let face_shape = faces.FindKey(face_index);
        let face = TopoDS::Face(face_shape);
        let mut location = ffi::top_loc::Location_new();
        let handle = ffi::b_rep::BRep_Tool_Triangulation(face, location.pin_mut());
        if handle.IsNull() {
            continue;
        }
        let triangulation = ffi::poly::Handle_Poly_Triangulation_Get(&handle).map_err(|_| {
            OcctError::InvalidInput {
                what: "null triangulation",
            }
        })?;
        let trsf = ffi::top_loc::TopLoc_Location_Transformation(&location);
        let reversed = matches!(
            face_shape.Orientation(),
            TopAbs_Orientation::TopAbs_REVERSED
        );
        let base = positions.len() as u32;
        for node in 1..=triangulation.NbNodes() {
            let mut point = ffi::poly::Poly_Triangulation_Node(triangulation, node);
            point.pin_mut().Transform(&trsf);
            positions.push([point.X(), point.Y(), point.Z()]);
        }
        for triangle_index in 1..=triangulation.NbTriangles() {
            let triangle = triangulation.Triangle(triangle_index);
            let a = base + (triangle.Value(1) - 1) as u32;
            let b = base + (triangle.Value(2) - 1) as u32;
            let c = base + (triangle.Value(3) - 1) as u32;
            // As in [`tessellate`]: OCCT keeps the face orientation separately.
            if reversed {
                triangles.extend([a, c, b]);
            }
            else {
                triangles.extend([a, b, c]);
            }
        }
    }
    Ok((positions, triangles))
}

/// Enumerate the sub-elements of `kind`, in the kernel's own order.
pub(crate) fn elements(shape: &Shape, kind: ElementKind) -> Vec<ElementRef> {
    let Ok(occt) = downcast(shape) else {
        return Vec::new();
    };
    let guard = occt.borrow();
    let Some(s) = guard.as_ref() else {
        return Vec::new();
    };
    let map = sub_shape_map(s, shape_enum(kind));
    (1..=map.Extent())
        .map(|index| element_ref(&map, index, kind))
        .collect()
}

/// The elements of `kind` related to `element`.
///
/// Coarser targets use `MapShapesAndAncestors` (which only walks upwards); finer
/// targets use an explorer over the element itself.
pub(crate) fn ancestors(shape: &Shape, element: &ElementRef, kind: ElementKind) -> Vec<ElementRef> {
    let Ok(occt) = downcast(shape) else {
        return Vec::new();
    };
    let guard = occt.borrow();
    let Some(s) = guard.as_ref() else {
        return Vec::new();
    };
    let Ok(element_occt) = downcast(&element.shape) else {
        return Vec::new();
    };
    let element_guard = element_occt.borrow();
    let Some(source_shape) = element_guard.as_ref() else {
        return Vec::new();
    };
    let Some(source_kind) = kind_of(source_shape) else {
        return Vec::new();
    };

    let target_map = sub_shape_map(s, shape_enum(kind));

    if rank(kind) >= rank(source_kind) {
        let sub = sub_shape_map(source_shape, shape_enum(kind));
        (1..=sub.Extent())
            .filter_map(|index| index_in(&target_map, sub.FindKey(index)))
            .map(|index| element_ref(&target_map, index, kind))
            .collect()
    } else {
        let mut data = ffi::top_tools::new_indexed_data_map_of_shape_list_of_shape();
        ffi::top_exp::TopExp::MapShapesAndAncestors(
            s,
            shape_enum(source_kind),
            shape_enum(kind),
            data.pin_mut(),
        );
        let index = (1..=data.Extent())
            .find(|index| data.FindKey(*index).IsSame(source_shape))
            .unwrap_or(0);
        if index == 0 {
            return Vec::new();
        }
        let list = data.FindFromIndex(index);
        let vec = ffi::topo_ds::shape_list_to_vector(list);
        vec.iter()
            .filter_map(|ancestor| {
                index_in(&target_map, ancestor).map(|index| element_ref(&target_map, index, kind))
            })
            .collect()
    }
}

/// The continuity between two adjacent edges, when they share a vertex.
///
/// OCCT answers this with the tangents at the shared vertex: equal (up to sign)
/// tangents are [`Continuity::G1`], anything else is [`Continuity::C0`]. Higher
/// orders (C1/G2/C2) are not distinguished; fillet propagation only needs G1.
pub(crate) fn continuity(_shape: &Shape, a: &ElementRef, b: &ElementRef) -> Option<Continuity> {
    let a_occt = downcast(&a.shape).ok()?;
    let b_occt = downcast(&b.shape).ok()?;
    let a_guard = a_occt.borrow();
    let b_guard = b_occt.borrow();
    let edge_a = a_guard.as_ref()?;
    let edge_b = b_guard.as_ref()?;
    if kind_of(edge_a) != Some(ElementKind::Edge) || kind_of(edge_b) != Some(ElementKind::Edge) {
        return None;
    }

    let mut vertex = ffi::topo_ds::TopoDS_Vertex_new();
    if !ffi::top_exp::TopExp::CommonVertex(
        TopoDS::Edge(edge_a),
        TopoDS::Edge(edge_b),
        vertex.pin_mut(),
    ) {
        return None;
    }

    let mut tangents = Vec::with_capacity(6);
    for edge in [edge_a, edge_b] {
        let curve = ffi::b_rep_adaptor::BRepAdaptor_Curve_new(TopoDS::Edge(edge));
        let u = ffi::b_rep::BRep_Tool_Parameter_edge(vertex.as_ref().unwrap(), TopoDS::Edge(edge));
        let mut point = ffi::gp::new_point(0.0, 0.0, 0.0);
        let mut derivative = ffi::gp::new_vec(0.0, 0.0, 0.0);
        ffi::b_rep_adaptor::BRepAdaptor_Curve_d1(&curve, u, point.pin_mut(), derivative.pin_mut());
        let magnitude = derivative.Magnitude();
        if magnitude < 1e-12 {
            return None;
        }
        tangents.extend_from_slice(&[
            derivative.X() / magnitude,
            derivative.Y() / magnitude,
            derivative.Z() / magnitude,
        ]);
    }
    let dot = tangents[0] * tangents[3] + tangents[1] * tangents[4] + tangents[2] * tangents[5];
    // `abs`: the two edges may be oriented towards or away from the shared vertex.
    Some(if dot.abs() >= 0.999_999 {
        Continuity::G1
    } else {
        Continuity::C0
    })
}

/// A `FaceN` reference into `map`.
fn face_ref(map: &Map, index: i32) -> ElementRef {
    ElementRef {
        shape: erase(map.FindKey(index)),
        name: format!("Face{index}"),
    }
}

/// Build the lineage of one input edge from an operation's history.
fn edge_lineage<F>(
    input: &ElementRef,
    input_shape: &TopoDS_Shape,
    out_faces: &Map,
    mut probe: F,
) -> History
where
    F: FnMut(&TopoDS_Shape, &mut UniquePtr<Map>, &mut UniquePtr<Map>) -> bool,
{
    let mut modified = new_map();
    let mut generated = new_map();
    let deleted = probe(input_shape, &mut modified, &mut generated);

    let mut history = History::default();
    for entry in 1..=modified.Extent() {
        let out = modified.FindKey(entry);
        let index = out_faces.FindIndex(out);
        if index > 0 {
            history
                .modified
                .push((input.clone(), face_ref(out_faces, index)));
        }
    }
    for entry in 1..=generated.Extent() {
        let out = generated.FindKey(entry);
        let index = out_faces.FindIndex(out);
        if index > 0 {
            history
                .generated
                .push((input.clone(), face_ref(out_faces, index)));
        }
    }
    // An input can be both consumed and the ancestor of a generated element: a
    // filleted edge is deleted while the fillet face is generated from it. Record
    // both; the element map retires the name and the generated pair says where the
    // new face came from.
    if deleted {
        history.deleted.push(input.clone());
    }
    history
}

fn merge_into(into: &mut History, from: History) {
    into.generated.extend(from.generated);
    into.modified.extend(from.modified);
    into.deleted.extend(from.deleted);
}

/// Round `edges` and report the generated faces.
pub(crate) fn fillet(
    shape: &Shape,
    edges: &[ElementRef],
    radius: f64,
) -> Result<OpResult, GeomError> {
    if edges.is_empty() {
        return Err(OcctError::InvalidInput {
            what: "fillet needs at least one edge",
        }
        .into());
    }
    if !radius.is_finite() || radius <= 0.0 {
        return Err(OcctError::InvalidInput {
            what: "fillet radius must be positive and finite",
        }
        .into());
    }
    let occt = downcast(shape)?;
    let guard = occt.borrow();
    let s = guard
        .as_ref()
        .ok_or(OcctError::InvalidInput { what: "null shape" })?;

    // Reject a foreign edge before the kernel: on some OCCT versions a foreign
    // edge can produce a wrong shape instead of raising, so `Build()` alone must
    // not be the guard. Build the edge map once and require every requested edge
    // to be one of the shape's own.
    let edge_map = sub_shape_map(s, TopAbs_ShapeEnum::TopAbs_EDGE);
    for edge in edges {
        let edge_occt = downcast(&edge.shape)?;
        let edge_guard = edge_occt.borrow();
        let edge_shape = edge_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null edge" })?;
        if find_index_same(&edge_map, edge_shape) == 0 {
            return Err(OcctError::InvalidInput {
                what: "fillet edge is not part of the shape",
            }
            .into());
        }
    }

    let mut op = ffi::b_rep_fillet_api::BRepFilletAPI_MakeFillet_new(s);
    for edge in edges {
        let edge_occt = downcast(&edge.shape)?;
        let edge_guard = edge_occt.borrow();
        let edge_shape = edge_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null edge" })?;
        if let Err(e) = ffi::b_rep_fillet_api::BRepFilletAPI_MakeFillet_add_edge_checked(
            op.pin_mut(),
            radius,
            TopoDS::Edge(edge_shape),
        ) {
            return Err(OcctError::Exception {
                operation: "fillet",
                message: e.what().to_string(),
            }
            .into());
        }
    }
    // `Build()` runs the algorithm without `Shape()`'s `Check()`. It can also
    // raise `Standard_Failure` (OCCT 7.x does not derive it from
    // `std::exception`), which is translated in C++ and delivered here as a
    // `Result`. `IsDone()` is only meaningful afterwards.
    if let Err(e) = ffi::b_rep_fillet_api::BRepFilletAPI_MakeFillet_build(op.pin_mut()) {
        return Err(OcctError::Exception {
            operation: "fillet",
            message: e.what().to_string(),
        }
        .into());
    }
    if !op.IsDone() {
        return Err(OcctError::NotDone {
            operation: "fillet",
        }
        .into());
    }

    let out_faces = {
        let built = op.pin_mut().Shape();
        sub_shape_map(built, TopAbs_ShapeEnum::TopAbs_FACE)
    };
    let mut history = History::default();
    for edge in edges {
        let edge_occt = downcast(&edge.shape)?;
        let edge_guard = edge_occt.borrow();
        let edge_shape = edge_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null edge" })?;
        let lineage = edge_lineage(
            edge,
            edge_shape,
            &out_faces,
            |shape, modified, generated| {
                history::collect(op.pin_mut().Modified(shape), modified);
                history::collect(op.pin_mut().Generated(shape), generated);
                op.pin_mut().IsDeleted(shape)
            },
        );
        merge_into(&mut history, lineage);
    }

    let result = {
        let built = op.pin_mut().Shape();
        erase(built)
    };
    Ok(OpResult::new(result, history))
}

/// Chamfer `edges`; `d2` selects the two-distance form.
pub(crate) fn chamfer(
    shape: &Shape,
    edges: &[ElementRef],
    d1: f64,
    d2: Option<f64>,
) -> Result<OpResult, GeomError> {
    if edges.is_empty() {
        return Err(OcctError::InvalidInput {
            what: "chamfer needs at least one edge",
        }
        .into());
    }
    if !d1.is_finite() || d1 <= 0.0 {
        return Err(OcctError::InvalidInput {
            what: "chamfer distance must be positive and finite",
        }
        .into());
    }
    if let Some(d2) = d2 {
        if !d2.is_finite() || d2 <= 0.0 {
            return Err(OcctError::InvalidInput {
                what: "chamfer distance must be positive and finite",
            }
            .into());
        }
    }
    let occt = downcast(shape)?;
    let guard = occt.borrow();
    let s = guard
        .as_ref()
        .ok_or(OcctError::InvalidInput { what: "null shape" })?;

    // Same early ownership rejection as the fillet above.
    let edge_map = sub_shape_map(s, TopAbs_ShapeEnum::TopAbs_EDGE);
    for edge in edges {
        let edge_occt = downcast(&edge.shape)?;
        let edge_guard = edge_occt.borrow();
        let edge_shape = edge_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null edge" })?;
        if find_index_same(&edge_map, edge_shape) == 0 {
            return Err(OcctError::InvalidInput {
                what: "chamfer edge is not part of the shape",
            }
            .into());
        }
    }

    let mut op = ffi::b_rep_fillet_api::BRepFilletAPI_MakeChamfer_new(s);
    for edge in edges {
        let edge_occt = downcast(&edge.shape)?;
        let edge_guard = edge_occt.borrow();
        let edge_shape = edge_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null edge" })?;
        match d2 {
            Some(d2) => {
                let face = ancestors(shape, edge, ElementKind::Face)
                    .into_iter()
                    .next()
                    .ok_or(OcctError::InvalidInput {
                        what: "asymmetric chamfer needs an adjacent face",
                    })?;
                let face_occt = downcast(&face.shape)?;
                let face_guard = face_occt.borrow();
                let face_shape = face_guard
                    .as_ref()
                    .ok_or(OcctError::InvalidInput { what: "null face" })?;
                if let Err(e) = ffi::b_rep_fillet_api::BRepFilletAPI_MakeChamfer_add_asym_checked(
                    op.pin_mut(),
                    d1,
                    d2,
                    TopoDS::Edge(edge_shape),
                    TopoDS::Face(face_shape),
                ) {
                    return Err(OcctError::Exception {
                        operation: "chamfer",
                        message: e.what().to_string(),
                    }
                    .into());
                }
            }
            None => {
                if let Err(e) = ffi::b_rep_fillet_api::BRepFilletAPI_MakeChamfer_add_edge_checked(
                    op.pin_mut(),
                    d1,
                    TopoDS::Edge(edge_shape),
                ) {
                    return Err(OcctError::Exception {
                        operation: "chamfer",
                        message: e.what().to_string(),
                    }
                    .into());
                }
            }
        }
    }
    // Same checked build as the fillet above.
    if let Err(e) = ffi::b_rep_fillet_api::BRepFilletAPI_MakeChamfer_build(op.pin_mut()) {
        return Err(OcctError::Exception {
            operation: "chamfer",
            message: e.what().to_string(),
        }
        .into());
    }
    if !op.IsDone() {
        return Err(OcctError::NotDone {
            operation: "chamfer",
        }
        .into());
    }

    let out_faces = {
        let built = op.pin_mut().Shape();
        sub_shape_map(built, TopAbs_ShapeEnum::TopAbs_FACE)
    };
    let mut history = History::default();
    for edge in edges {
        let edge_occt = downcast(&edge.shape)?;
        let edge_guard = edge_occt.borrow();
        let edge_shape = edge_guard
            .as_ref()
            .ok_or(OcctError::InvalidInput { what: "null edge" })?;
        let lineage = edge_lineage(
            edge,
            edge_shape,
            &out_faces,
            |shape, modified, generated| {
                history::collect(op.pin_mut().Modified(shape), modified);
                history::collect(op.pin_mut().Generated(shape), generated);
                op.pin_mut().IsDeleted(shape)
            },
        );
        merge_into(&mut history, lineage);
    }

    let result = {
        let built = op.pin_mut().Shape();
        erase(built)
    };
    Ok(OpResult::new(result, history))
}