axiolid-construct 0.2.0

Solid generation: profiles, lofts, sweeps, revolutions and half-space clipping
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
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
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
//! Exact analytic linear-extrusion constructors.

use std::f64::consts::TAU;

use axiolid_brep::{EdgeName, ExactBRep, ExactBRepBuilder, FaceName, SweptFace};
use axiolid_contracts::{GeomError, GeomResult, Operation};
use axiolid_core::{Frame2, Frame3, Interval, Point2, Point3, Scalar, Tolerance, Vec2, Vec3};
use axiolid_curve::{Circle2, Circle3, Curve2, Curve3, Ellipse2, Ellipse3, Line2, Line3};
use axiolid_profile::{CircleProfile, ContourProfile, EllipseProfile, Profile, RectangleProfile};
use axiolid_surface::{Cylinder, EllipticalCylinder, Plane, Surface};
use axiolid_topology::{
    audit_brep, Edge, EdgeId, EdgeUse, Face, FaceBound, FaceId, Loop, LoopId, Orientation, Shell,
    Solid, Vertex, VertexId,
};

use crate::center_line_exact::center_line_contour;
use crate::contour_lower::{contour_to_arc_ring, orient_arc_ring};
use crate::extrude_arc::extrude_arc_rings;
use crate::profile_lower::{lower_composite, lower_derived};
use crate::section_lower::section_contour;
use crate::BACKEND_ID;

#[derive(Debug)]
pub(crate) struct RingTopology {
    bottom_edges: Vec<EdgeId>,
    top_edges: Vec<EdgeId>,
    vertical_edges: Vec<EdgeId>,
    bottom_points: Vec<Point3>,
}

/// Extrude a supported profile into an exact, closed analytic B-rep.
///
/// Initial exact families are deliberately narrow: sharp filled/hollow
/// rectangles under a forward non-coplanar linear extrusion, and filled circles
/// along the positive profile normal. Every other family returns a typed refusal
/// instead of taking the existing tessellation path.
pub fn extrude_profile_exact(
    profile: &Profile,
    direction: Vec3,
    depth: Scalar,
    tolerance: Tolerance,
) -> GeomResult<ExactBRep> {
    let offset = extrusion_offset(direction, depth, tolerance)?;
    match profile {
        Profile::Rectangle(rectangle) => extrude_rectangle(rectangle, offset, tolerance),
        Profile::Circle(circle) => extrude_circle(circle, offset),
        Profile::Ellipse(ellipse) => extrude_ellipse(ellipse, offset),
        Profile::Section(section) => {
            let contour = section_contour(section)?;
            extrude_contour(&contour, offset, tolerance)
        }
        Profile::Contour(contour) => extrude_contour(contour, offset, tolerance),
        Profile::Derived { basis, transform } => {
            // Lower to a concrete profile, then extrude that. Recursing on
            // the LOWERED profile (not the basis) keeps one code path for
            // each shape kind instead of a transform-aware variant of each.
            let lowered = lower_derived(basis, transform, tolerance)?;
            extrude_profile_exact(&lowered, direction, depth, tolerance)
        }
        Profile::Composite(members) => extrude_composite(members, offset, tolerance),
        Profile::CenterLine(center_line) => {
            // Offsetting produces a contour, which the contour path already
            // extrudes exactly -- including the arc walls.
            let contour = center_line_contour(center_line, tolerance)?;
            extrude_contour(&contour, offset, tolerance)
        }
        _ => Err(unsupported("unknown profile extrusion")),
    }
}

fn normalize_direction(direction: Vec3) -> Option<Vec3> {
    if !direction.is_finite() {
        return None;
    }

    // Scaling first avoids underflow/overflow in the squared norm while
    // preserving every finite nonzero direction, including subnormals.
    let scale = direction.abs().max_element();
    if scale == 0.0 {
        return None;
    }
    let scaled = direction / scale;
    Some(scaled / scaled.length())
}

// Compare IEEE-754 magnitudes so underflow cannot be optimized as real arithmetic.
const MAGNITUDE_BITS: u64 = 0x7fff_ffff_ffff_ffff;

fn loses_nonzero_component(input: Vec3, output: Vec3) -> bool {
    (input.x.to_bits() & MAGNITUDE_BITS != 0 && output.x.to_bits() & MAGNITUDE_BITS == 0)
        || (input.y.to_bits() & MAGNITUDE_BITS != 0 && output.y.to_bits() & MAGNITUDE_BITS == 0)
        || (input.z.to_bits() & MAGNITUDE_BITS != 0 && output.z.to_bits() & MAGNITUDE_BITS == 0)
}

fn extrusion_offset(direction: Vec3, depth: Scalar, tolerance: Tolerance) -> GeomResult<Vec3> {
    if !depth.is_finite() || depth <= 0.0 {
        return Err(GeomError::InvalidInput(format!(
            "exact extrusion depth must be positive and finite, got {depth}"
        )));
    }
    let normalized = normalize_direction(direction).ok_or_else(|| {
        GeomError::InvalidInput("exact extrusion direction must be finite and non-zero".to_owned())
    })?;
    if loses_nonzero_component(direction, normalized) {
        return Err(GeomError::Degenerate(
            "exact extrusion direction cannot be normalized without losing a nonzero component"
                .to_owned(),
        ));
    }
    let offset = normalized * depth;
    if !offset.is_finite() || loses_nonzero_component(normalized, offset) {
        return Err(GeomError::Degenerate(
            "exact extrusion direction could not be scaled without range loss".to_owned(),
        ));
    }
    if offset.z <= tolerance.linear() {
        return Err(unsupported("non-forward planar extrusion"));
    }
    Ok(offset)
}

fn extrude_rectangle(
    rectangle: &RectangleProfile,
    offset: Vec3,
    tolerance: Tolerance,
) -> GeomResult<ExactBRep> {
    if rectangle.outer_radius.is_some() || rectangle.inner_radius.is_some() {
        return Err(unsupported("rounded rectangle extrusion"));
    }
    if !rectangle.x.is_finite()
        || !rectangle.y.is_finite()
        || rectangle.x <= 0.0
        || rectangle.y <= 0.0
    {
        return Err(GeomError::InvalidInput(format!(
            "exact rectangle profile must have positive finite extents, got {} x {}",
            rectangle.x, rectangle.y
        )));
    }

    let (hx, hy) = (rectangle.x / 2.0, rectangle.y / 2.0);
    let mut rings = vec![vec![
        Point2::new(-hx, -hy),
        Point2::new(hx, -hy),
        Point2::new(hx, hy),
        Point2::new(-hx, hy),
    ]];
    if let Some(thickness) = rectangle.thickness {
        if !thickness.is_finite()
            || thickness <= 0.0
            || 2.0 * thickness >= rectangle.x
            || 2.0 * thickness >= rectangle.y
        {
            return Err(GeomError::InvalidInput(format!(
                "exact hollow rectangle wall thickness {thickness} does not fit inside {} x {}",
                rectangle.x, rectangle.y
            )));
        }
        let (ix, iy) = (hx - thickness, hy - thickness);
        if tolerance.eq(ix, 0.0) || tolerance.eq(iy, 0.0) {
            return Err(GeomError::Degenerate(
                "exact hollow rectangle has a collapsed inner ring".to_owned(),
            ));
        }
        // Clockwise inner ring: its side normals point into the through-passage.
        rings.push(vec![
            Point2::new(-ix, -iy),
            Point2::new(-ix, iy),
            Point2::new(ix, iy),
            Point2::new(ix, -iy),
        ]);
    }

    extrude_polygon_rings(&rings, offset)
}

/// Extrude closed polygon rings into an exact prism.
///
/// The ring-to-B-rep assembly is general over polygon rings, so it is shared
/// rather than duplicated: a chamfered box is a prism over a pentagon, and a
/// filleted one differs only in that an edge becomes an arc. Ring 0 is the
/// outer boundary; any further rings are through-holes.
pub(crate) fn extrude_polygon_rings(rings: &[Vec<Point2>], offset: Vec3) -> GeomResult<ExactBRep> {
    extrude_polygon_rings_named(rings, offset, &mut |_| None)
}

/// Extrude polygon rings, naming each side wall from its own geometry.
///
/// `name_side` receives the wall's two base corners and returns the name
/// that wall should carry, or `None` to leave it unnamed. Passing the
/// geometry rather than an index is deliberate: the caller recovering
/// provenance from a boolean has no index to match against, only position.
pub(crate) fn extrude_polygon_rings_named(
    rings: &[Vec<Point2>],
    offset: Vec3,
    name_side: &mut dyn FnMut((Point2, Point2)) -> Option<FaceName>,
) -> GeomResult<ExactBRep> {
    let ring_count = rings.len();
    let edge_count = ring_count * 12;
    let pcurve_count = ring_count * 24;
    let face_count = 2 + ring_count * 4;
    let mut builder = ExactBRepBuilder::default();
    reserve(
        &mut builder,
        ring_count * 8,
        edge_count,
        2 * ring_count + 4 * ring_count,
        face_count,
        edge_count,
        pcurve_count,
        face_count,
    )?;

    let ring_topology = rings
        .iter()
        .map(|ring| add_polygon_ring(&mut builder, ring.as_slice(), offset))
        .collect::<GeomResult<Vec<_>>>()?;

    let bottom_surface = builder.add_surface(Surface::Plane(Plane {
        frame: identity_frame3(Vec3::ZERO),
    }));
    let top_surface = builder.add_surface(Surface::Plane(Plane {
        frame: identity_frame3(offset),
    }));

    let mut bottom_bounds = Vec::with_capacity(ring_count);
    let mut top_bounds = Vec::with_capacity(ring_count);
    for (ring_index, ring) in ring_topology.iter().enumerate() {
        let bottom_loop = add_cap_loop(&mut builder, &ring.bottom_edges, &ring.bottom_points);
        let top_loop = add_cap_loop(&mut builder, &ring.top_edges, &ring.bottom_points);
        bottom_bounds.push(FaceBound {
            loop_id: bottom_loop,
            orientation: Orientation::Forward,
            outer: ring_index == 0,
        });
        top_bounds.push(FaceBound {
            loop_id: top_loop,
            orientation: Orientation::Forward,
            outer: ring_index == 0,
        });
    }

    let bottom_face = builder.topology_mut().add_face(Face {
        surface: Some(bottom_surface),
        bounds: bottom_bounds,
        orientation: Orientation::Reversed,
    });
    let top_face = builder.topology_mut().add_face(Face {
        surface: Some(top_surface),
        bounds: top_bounds,
        orientation: Orientation::Forward,
    });

    let mut faces = vec![bottom_face, top_face];
    for (ring_index, ring) in ring_topology.iter().enumerate() {
        let source = &rings[ring_index];
        for edge_index in 0..ring.bottom_edges.len() {
            let face = add_planar_side(&mut builder, ring, edge_index, offset)?;
            // The wall's own base corners are what the caller matches
            // against its inputs, so they are what gets handed over.
            let start = source[edge_index];
            let end = source[(edge_index + 1) % source.len()];
            if let Some(name) = name_side((start, end)) {
                builder.set_face_name(face, name);
            }
            faces.push(face);
        }
    }
    finish_closed(builder, faces)
}

fn add_polygon_ring(
    builder: &mut ExactBRepBuilder,
    ring: &[Point2],
    offset: Vec3,
) -> GeomResult<RingTopology> {
    add_polygon_ring_with_blends(builder, ring, offset, &[])
}

/// Build ring topology where some edges are blend arcs rather than chords.
///
/// A blend edge MUST carry a `Circle3`, not the straight chord between its
/// tangent points. The blend face attaches an arc pcurve to that same edge,
/// so a chord here makes the face boundary and the edge disagree by the
/// sagitta -- a defect no topological check can see, since the loop still
/// closes and every handle still resolves.
pub(crate) fn add_polygon_ring_with_blends(
    builder: &mut ExactBRepBuilder,
    ring: &[Point2],
    offset: Vec3,
    blends: &[Option<(BlendCorner, Scalar)>],
) -> GeomResult<RingTopology> {
    let bottom_points: Vec<_> = ring
        .iter()
        .map(|point| Point3::new(point.x, point.y, 0.0))
        .collect();
    let top_points: Vec<_> = bottom_points.iter().map(|point| *point + offset).collect();
    let bottom_vertices: Vec<_> = bottom_points
        .iter()
        .map(|&position| builder.topology_mut().add_vertex(Vertex { position }))
        .collect();
    let top_vertices: Vec<_> = top_points
        .iter()
        .map(|&position| builder.topology_mut().add_vertex(Vertex { position }))
        .collect();

    let mut bottom_edges = Vec::with_capacity(ring.len());
    let mut top_edges = Vec::with_capacity(ring.len());
    let mut vertical_edges = Vec::with_capacity(ring.len());
    for index in 0..ring.len() {
        let next = (index + 1) % ring.len();
        // A blend edge follows its arc; every other edge is a chord.
        if let Some(Some((blend, radius))) = blends.get(index) {
            let (bottom_edge, top_edge) = add_blend_arc_edges(
                builder,
                blend,
                *radius,
                (bottom_vertices[index], bottom_vertices[next]),
                (top_vertices[index], top_vertices[next]),
                offset,
            );
            bottom_edges.push(bottom_edge);
            top_edges.push(top_edge);
        } else {
            bottom_edges.push(add_line_edge(
                builder,
                bottom_vertices[index],
                bottom_vertices[next],
                bottom_points[index],
                bottom_points[next] - bottom_points[index],
            ));
            top_edges.push(add_line_edge(
                builder,
                top_vertices[index],
                top_vertices[next],
                top_points[index],
                top_points[next] - top_points[index],
            ));
        }
        vertical_edges.push(add_line_edge(
            builder,
            bottom_vertices[index],
            top_vertices[index],
            bottom_points[index],
            offset,
        ));
    }
    Ok(RingTopology {
        bottom_edges,
        top_edges,
        vertical_edges,
        bottom_points,
    })
}

pub(crate) fn add_line_edge(
    builder: &mut ExactBRepBuilder,
    start: VertexId,
    end: VertexId,
    origin: Point3,
    direction: Vec3,
) -> EdgeId {
    let curve = builder.add_curve3(Curve3::Line(Line3 { origin, direction }));
    let edge = builder.topology_mut().add_edge(Edge {
        start,
        end,
        curve: Some(curve),
    });
    builder.set_edge_interval(edge, Interval::UNIT);
    edge
}

fn add_cap_loop(builder: &mut ExactBRepBuilder, edges: &[EdgeId], points: &[Point3]) -> LoopId {
    add_cap_loop_with_blends(builder, edges, points, &[])
}

/// A cap loop whose pcurves follow blend arcs where the ring has them.
///
/// The cap surface is the z-plane, so parameter space IS the cross-section
/// plane and a straight edge maps to a `Line2`. A blend edge must map to a
/// `Circle2`: using the chord would make the cap boundary disagree with both
/// the blend face and the edge's own 3D curve, by the sagitta. The loop would
/// still close and every handle would still resolve, so only a geometric
/// audit can see the difference.
fn add_cap_loop_with_blends(
    builder: &mut ExactBRepBuilder,
    edges: &[EdgeId],
    points: &[Point3],
    blends: &[Option<(BlendCorner, Scalar)>],
) -> LoopId {
    let mut uses = Vec::with_capacity(edges.len());
    let mut intervals = Vec::with_capacity(edges.len());
    for (index, &edge) in edges.iter().enumerate() {
        let next = (index + 1) % edges.len();
        let (pcurve, interval) = match blends.get(index) {
            Some(Some((blend, radius))) => {
                let start = blend.start - blend.centre;
                let length = start.length();
                let x = if length == 0.0 {
                    Vec2::X
                } else {
                    start / length
                };
                let curve = Curve2::Circle(Circle2 {
                    frame: Frame2 {
                        origin: Vec2::new(blend.centre.x, blend.centre.y),
                        x,
                        y: Vec2::new(-x.y, x.x),
                    },
                    radius: *radius,
                });
                (curve, Interval::new(0.0, blend.sweep))
            }
            _ => {
                let origin = points[index].truncate();
                let direction = (points[next] - points[index]).truncate();
                (Curve2::Line(Line2 { origin, direction }), Interval::UNIT)
            }
        };
        let pcurve = builder.add_curve2(pcurve);
        uses.push(EdgeUse {
            edge,
            orientation: Orientation::Forward,
            pcurve: Some(pcurve),
        });
        intervals.push(interval);
    }
    add_loop(builder, uses, intervals)
}

fn add_planar_side(
    builder: &mut ExactBRepBuilder,
    ring: &RingTopology,
    index: usize,
    offset: Vec3,
) -> GeomResult<FaceId> {
    let next = (index + 1) % ring.bottom_edges.len();
    let origin = ring.bottom_points[index];
    let edge_vector = ring.bottom_points[next] - origin;
    let x = edge_vector.normalize();
    let z = edge_vector.cross(offset).normalize();
    let y = z.cross(x);
    if !(x.is_finite() && y.is_finite() && z.is_finite()) {
        return Err(GeomError::Degenerate(
            "exact rectangle extrusion produced a degenerate side plane".to_owned(),
        ));
    }
    let surface = builder.add_surface(Surface::Plane(Plane {
        frame: Frame3 { origin, x, y, z },
    }));
    let edge_length = edge_vector.length();
    let offset_uv = Vec2::new(offset.dot(x), offset.dot(y));
    let pcurves = [
        Curve2::Line(Line2 {
            origin: Vec2::ZERO,
            direction: Vec2::new(edge_length, 0.0),
        }),
        Curve2::Line(Line2 {
            origin: Vec2::new(edge_length, 0.0),
            direction: offset_uv,
        }),
        Curve2::Line(Line2 {
            origin: offset_uv,
            direction: Vec2::new(edge_length, 0.0),
        }),
        Curve2::Line(Line2 {
            origin: Vec2::ZERO,
            direction: offset_uv,
        }),
    ];
    let edge_uses = [
        (ring.bottom_edges[index], Orientation::Forward),
        (ring.vertical_edges[next], Orientation::Forward),
        (ring.top_edges[index], Orientation::Reversed),
        (ring.vertical_edges[index], Orientation::Reversed),
    ];
    let mut uses = Vec::with_capacity(4);
    let mut intervals = Vec::with_capacity(4);
    for ((edge, orientation), pcurve) in edge_uses.into_iter().zip(pcurves) {
        let pcurve = builder.add_curve2(pcurve);
        uses.push(EdgeUse {
            edge,
            orientation,
            pcurve: Some(pcurve),
        });
        intervals.push(match orientation {
            Orientation::Forward => Interval::UNIT,
            Orientation::Reversed => Interval::new(1.0, 0.0),
        });
    }
    let loop_id = add_loop(builder, uses, intervals);
    Ok(builder.topology_mut().add_face(Face {
        surface: Some(surface),
        bounds: vec![FaceBound {
            loop_id,
            orientation: Orientation::Forward,
            outer: true,
        }],
        orientation: Orientation::Forward,
    }))
}

fn extrude_circle(circle: &CircleProfile, offset: Vec3) -> GeomResult<ExactBRep> {
    if circle.thickness.is_some() {
        return Err(unsupported("annular circle extrusion"));
    }
    if !circle.radius.is_finite() || circle.radius <= 0.0 {
        return Err(GeomError::InvalidInput(format!(
            "exact circle profile radius must be positive and finite, got {}",
            circle.radius
        )));
    }
    if offset.x != 0.0 || offset.y != 0.0 {
        return Err(unsupported("oblique circle extrusion"));
    }

    let depth = offset.z;
    let frame_bottom = identity_frame3(Vec3::ZERO);
    let frame_top = identity_frame3(offset);
    let frame2 = Frame2 {
        origin: Vec2::ZERO,
        x: Vec2::X,
        y: Vec2::Y,
    };
    let bottom_point = Vec3::new(circle.radius, 0.0, 0.0);
    let top_point = bottom_point + offset;

    let mut builder = ExactBRepBuilder::default();
    reserve(&mut builder, 2, 3, 3, 3, 3, 8, 3)?;
    let bottom_vertex = builder.topology_mut().add_vertex(Vertex {
        position: bottom_point,
    });
    let top_vertex = builder.topology_mut().add_vertex(Vertex {
        position: top_point,
    });

    let bottom_curve = builder.add_curve3(Curve3::Circle(Circle3 {
        frame: frame_bottom,
        radius: circle.radius,
    }));
    let bottom_edge = builder.topology_mut().add_edge(Edge {
        start: bottom_vertex,
        end: bottom_vertex,
        curve: Some(bottom_curve),
    });
    builder.set_edge_interval(bottom_edge, Interval::new(0.0, TAU));

    let top_curve = builder.add_curve3(Curve3::Circle(Circle3 {
        frame: frame_top,
        radius: circle.radius,
    }));
    let top_edge = builder.topology_mut().add_edge(Edge {
        start: top_vertex,
        end: top_vertex,
        curve: Some(top_curve),
    });
    builder.set_edge_interval(top_edge, Interval::new(0.0, TAU));

    let seam_curve = builder.add_curve3(Curve3::Line(Line3 {
        origin: bottom_point,
        direction: offset,
    }));
    let seam_edge = builder.topology_mut().add_edge(Edge {
        start: bottom_vertex,
        end: top_vertex,
        curve: Some(seam_curve),
    });
    builder.set_edge_interval(seam_edge, Interval::UNIT);

    let bottom_loop = add_circle_cap_loop(&mut builder, bottom_edge, frame2, circle.radius);
    let top_loop = add_circle_cap_loop(&mut builder, top_edge, frame2, circle.radius);

    let side_curves = [
        Curve2::Line(Line2 {
            origin: Vec2::ZERO,
            direction: Vec2::X,
        }),
        Curve2::Line(Line2 {
            origin: Vec2::new(TAU, 0.0),
            direction: Vec2::new(0.0, depth),
        }),
        Curve2::Line(Line2 {
            origin: Vec2::new(0.0, depth),
            direction: Vec2::X,
        }),
        Curve2::Line(Line2 {
            origin: Vec2::ZERO,
            direction: Vec2::new(0.0, depth),
        }),
    ];
    let side_edges = [
        (bottom_edge, Orientation::Forward, Interval::new(0.0, TAU)),
        (seam_edge, Orientation::Forward, Interval::UNIT),
        (top_edge, Orientation::Reversed, Interval::new(TAU, 0.0)),
        (seam_edge, Orientation::Reversed, Interval::new(1.0, 0.0)),
    ];
    let mut side_uses = Vec::with_capacity(4);
    let mut side_intervals = Vec::with_capacity(4);
    for ((edge, orientation, interval), curve) in side_edges.into_iter().zip(side_curves) {
        let pcurve = builder.add_curve2(curve);
        side_uses.push(EdgeUse {
            edge,
            orientation,
            pcurve: Some(pcurve),
        });
        side_intervals.push(interval);
    }
    let side_loop = add_loop(&mut builder, side_uses, side_intervals);

    let bottom_surface = builder.add_surface(Surface::Plane(Plane {
        frame: frame_bottom,
    }));
    let top_surface = builder.add_surface(Surface::Plane(Plane { frame: frame_top }));
    let side_surface = builder.add_surface(Surface::Cylinder(Cylinder {
        frame: frame_bottom,
        radius: circle.radius,
    }));
    let bottom_face = add_single_bound_face(
        &mut builder,
        bottom_surface,
        bottom_loop,
        Orientation::Reversed,
    );
    let top_face = add_single_bound_face(&mut builder, top_surface, top_loop, Orientation::Forward);
    let side_face =
        add_single_bound_face(&mut builder, side_surface, side_loop, Orientation::Forward);
    finish_closed(builder, vec![bottom_face, top_face, side_face])
}

fn add_circle_cap_loop(
    builder: &mut ExactBRepBuilder,
    edge: EdgeId,
    frame: Frame2,
    radius: Scalar,
) -> LoopId {
    let pcurve = builder.add_curve2(Curve2::Circle(Circle2 { frame, radius }));
    add_loop(
        builder,
        vec![EdgeUse {
            edge,
            orientation: Orientation::Forward,
            pcurve: Some(pcurve),
        }],
        vec![Interval::new(0.0, TAU)],
    )
}

pub(crate) fn add_single_bound_face(
    builder: &mut ExactBRepBuilder,
    surface: axiolid_brep::SurfaceId,
    loop_id: LoopId,
    orientation: Orientation,
) -> FaceId {
    builder.topology_mut().add_face(Face {
        surface: Some(surface),
        bounds: vec![FaceBound {
            loop_id,
            orientation: Orientation::Forward,
            outer: true,
        }],
        orientation,
    })
}

pub(crate) fn add_loop(
    builder: &mut ExactBRepBuilder,
    uses: Vec<EdgeUse<axiolid_brep::Curve2Id>>,
    intervals: Vec<Interval>,
) -> LoopId {
    debug_assert_eq!(uses.len(), intervals.len());
    let loop_id = builder.topology_mut().add_loop(Loop { edges: uses });
    for (use_index, interval) in intervals.into_iter().enumerate() {
        builder.set_pcurve_interval(loop_id, use_index, interval);
    }
    loop_id
}

pub(crate) fn finish_closed(
    mut builder: ExactBRepBuilder,
    faces: Vec<FaceId>,
) -> GeomResult<ExactBRep> {
    let shell = builder.topology_mut().add_shell(Shell {
        faces: faces
            .into_iter()
            .map(|face| (face, Orientation::Forward))
            .collect(),
        closed: true,
    });
    builder.topology_mut().add_solid(Solid {
        outer: shell,
        voids: Vec::new(),
    });
    let exact = builder
        .finish()
        .map_err(|error| GeomError::BackendContractViolation {
            backend: BACKEND_ID,
            detail: format!("exact extrusion assembly failed: {error}"),
        })?;
    let health = audit_brep(exact.topology());
    if !health.is_closed_manifold() {
        return Err(GeomError::BackendContractViolation {
            backend: BACKEND_ID,
            detail: format!("exact extrusion is not a closed manifold: {health:?}"),
        });
    }
    Ok(exact)
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn reserve(
    builder: &mut ExactBRepBuilder,
    vertices: usize,
    edges: usize,
    loops: usize,
    faces: usize,
    curves3: usize,
    curves2: usize,
    surfaces: usize,
) -> GeomResult<()> {
    builder
        .topology_mut()
        .try_reserve(vertices, edges, loops, faces, 1, 1)
        .map_err(|_| GeomError::BudgetExceeded { resource: "memory" })?;
    builder
        .try_reserve(curves3, curves2, surfaces, edges, curves2)
        .map_err(|_| GeomError::BudgetExceeded { resource: "memory" })
}

pub(crate) fn identity_frame3(origin: Point3) -> Frame3 {
    Frame3 {
        origin,
        x: Vec3::X,
        y: Vec3::Y,
        z: Vec3::Z,
    }
}

fn unsupported(input: &'static str) -> GeomError {
    GeomError::UnsupportedInput {
        backend: BACKEND_ID,
        operation: Operation::Sweep,
        input,
    }
}

/// Extrude a ring where one side is a cylindrical blend instead of a plane.
///
/// Mirrors `extrude_polygon_rings` for the planar walls and caps, then adds
/// the blend as a single face whose surface is `Surface::Cylinder`. The two
/// vertical edges bounding it are shared with the neighbouring planar walls,
/// which is what makes the shell closed and the blend tangent: same edges,
/// same vertices, no seam.
pub(crate) use crate::feature::BlendCorner;

pub(crate) fn extrude_with_cylindrical_blend(
    ring: &[Point2],
    offset: Vec3,
    blend_index: usize,
    blend: &BlendCorner,
    radius: Scalar,
) -> GeomResult<ExactBRep> {
    let mut blends: Vec<Option<(BlendCorner, Scalar)>> = (0..ring.len()).map(|_| None).collect();
    blends[blend_index] = Some((
        BlendCorner {
            centre: blend.centre,
            start: blend.start,
            end: blend.end,
            sweep: blend.sweep,
        },
        radius,
    ));
    extrude_with_cylindrical_blends(ring, offset, &blends)
}

/// Extrude a ring where any subset of edges is a cylindrical blend.
///
/// `blends[i]` is `Some` when edge `i` of the ring is a blend arc rather than
/// a straight wall. Taking a table rather than one index is what lets several
/// corners be filleted in a single solid without a second traversal.
pub(crate) fn extrude_with_cylindrical_blends(
    ring: &[Point2],
    offset: Vec3,
    blends: &[Option<(BlendCorner, Scalar)>],
) -> GeomResult<ExactBRep> {
    let mut builder = ExactBRepBuilder::default();
    let n = ring.len();
    reserve(
        &mut builder,
        n * 2,
        n * 3,
        2 + n,
        2 + n,
        n * 3,
        n * 6,
        2 + n,
    )?;

    // Blend edges must be arcs, so the table has to reach ring construction.
    let topology = add_polygon_ring_with_blends(&mut builder, ring, offset, blends)?;

    let bottom_surface = builder.add_surface(Surface::Plane(Plane {
        frame: identity_frame3(Vec3::ZERO),
    }));
    let top_surface = builder.add_surface(Surface::Plane(Plane {
        frame: identity_frame3(offset),
    }));
    let bottom_loop = add_cap_loop_with_blends(
        &mut builder,
        &topology.bottom_edges,
        &topology.bottom_points,
        blends,
    );
    let top_loop = add_cap_loop_with_blends(
        &mut builder,
        &topology.top_edges,
        &topology.bottom_points,
        blends,
    );

    let bottom_face = builder.topology_mut().add_face(Face {
        surface: Some(bottom_surface),
        bounds: vec![FaceBound {
            loop_id: bottom_loop,
            orientation: Orientation::Forward,
            outer: true,
        }],
        orientation: Orientation::Reversed,
    });
    let top_face = builder.topology_mut().add_face(Face {
        surface: Some(top_surface),
        bounds: vec![FaceBound {
            loop_id: top_loop,
            orientation: Orientation::Forward,
            outer: true,
        }],
        orientation: Orientation::Forward,
    });
    builder.set_face_name(bottom_face, FaceName::swept(SweptFace::StartCap));
    builder.set_face_name(top_face, FaceName::swept(SweptFace::EndCap));

    let mut faces = vec![bottom_face, top_face];
    let side_count = topology.bottom_edges.len();
    for edge_index in 0..side_count {
        // `edge_index` is the profile edge ordinal this wall was swept from.
        // It survives a rebuild with a different face count, which is exactly
        // what an arena index does not.
        let ordinal = u32::try_from(edge_index).map_err(|_| {
            GeomError::Degenerate("profile edge count exceeds u32 capacity".to_owned())
        })?;
        if let Some((blend, radius)) = blends.get(edge_index).and_then(Option::as_ref) {
            let face =
                add_cylindrical_blend(&mut builder, &topology, edge_index, offset, blend, *radius)?;
            // The blend replaced the edge between the two walls it is tangent
            // to. Naming it after that edge -- rather than after its own
            // position -- is what lets the same fillet be re-applied after an
            // upstream edit: the edge name is still derivable from the profile.
            let previous = (edge_index + side_count - 1) % side_count;
            let previous_ordinal = u32::try_from(previous).map_err(|_| {
                GeomError::Degenerate("profile edge count exceeds u32 capacity".to_owned())
            })?;
            builder.set_face_name(
                face,
                FaceName::blend(EdgeName::between(
                    FaceName::swept(SweptFace::Side(previous_ordinal)),
                    FaceName::swept(SweptFace::Side(ordinal)),
                )),
            );
            faces.push(face);
        } else {
            let face = add_planar_side(&mut builder, &topology, edge_index, offset)?;
            builder.set_face_name(face, FaceName::swept(SweptFace::Side(ordinal)));
            faces.push(face);
        }
    }
    finish_closed(builder, faces)
}

/// The blend face: a cylinder tangent to both neighbouring walls.
///
/// The cylinder's axis is the blend centre extruded along the offset, and its
/// radius is the fillet radius. Tangency holds because the centre was placed
/// at the perpendicular distance `radius` from each adjacent wall -- it is a
/// property of the construction, not something verified here.
///
/// The face is bounded by the same four edges a planar wall would use, so the
/// blend shares vertices and edges with its neighbours and the shell closes.
fn add_cylindrical_blend(
    builder: &mut ExactBRepBuilder,
    ring: &RingTopology,
    index: usize,
    offset: Vec3,
    blend: &BlendCorner,
    radius: Scalar,
) -> GeomResult<FaceId> {
    let next = (index + 1) % ring.bottom_edges.len();
    let centre = Point3::new(blend.centre.x, blend.centre.y, 0.0);
    // Frame x-axis points at the arc start, so the surface parameter u is the
    // angle measured from there and the pcurve intervals are the sweep.
    let start = ring.bottom_points[index];
    let x = (start - centre).normalize();
    let z = offset.normalize();
    let y = z.cross(x);
    if !(x.is_finite() && y.is_finite() && z.is_finite()) {
        return Err(GeomError::Degenerate(
            "fillet blend produced a degenerate cylinder frame".to_owned(),
        ));
    }
    let surface = builder.add_surface(Surface::Cylinder(Cylinder {
        frame: Frame3 {
            origin: centre,
            x,
            y,
            z,
        },
        radius,
    }));

    let height = offset.length();
    let pcurves = [
        // Bottom arc: u sweeps the blend angle at v = 0.
        Curve2::Line(Line2 {
            origin: Vec2::ZERO,
            direction: Vec2::new(blend.sweep, 0.0),
        }),
        Curve2::Line(Line2 {
            origin: Vec2::new(blend.sweep, 0.0),
            direction: Vec2::new(0.0, height),
        }),
        Curve2::Line(Line2 {
            origin: Vec2::new(0.0, height),
            direction: Vec2::new(blend.sweep, 0.0),
        }),
        Curve2::Line(Line2 {
            origin: Vec2::ZERO,
            direction: Vec2::new(0.0, height),
        }),
    ];
    let edge_uses = [
        (ring.bottom_edges[index], Orientation::Forward),
        (ring.vertical_edges[next], Orientation::Forward),
        (ring.top_edges[index], Orientation::Reversed),
        (ring.vertical_edges[index], Orientation::Reversed),
    ];

    let mut uses = Vec::with_capacity(4);
    let mut intervals = Vec::with_capacity(4);
    for ((edge, orientation), pcurve) in edge_uses.into_iter().zip(pcurves) {
        let pcurve = builder.add_curve2(pcurve);
        uses.push(EdgeUse {
            edge,
            orientation,
            pcurve: Some(pcurve),
        });
        intervals.push(match orientation {
            Orientation::Forward => Interval::UNIT,
            Orientation::Reversed => Interval::new(1.0, 0.0),
        });
    }
    let loop_id = add_loop(builder, uses, intervals);
    Ok(builder.topology_mut().add_face(Face {
        surface: Some(surface),
        bounds: vec![FaceBound {
            loop_id,
            orientation: Orientation::Forward,
            outer: true,
        }],
        orientation: Orientation::Forward,
    }))
}

/// The bottom and top arc edges of one cylindrical blend.
///
/// Both lie on the blend cylinder, so each is a `Circle3` whose frame x-axis
/// points at the arc start -- the same convention `add_cylindrical_blend`
/// uses, which is what lets the edge interval be the sweep itself.
fn add_blend_arc_edges(
    builder: &mut ExactBRepBuilder,
    blend: &BlendCorner,
    radius: Scalar,
    bottom: (VertexId, VertexId),
    top: (VertexId, VertexId),
    offset: Vec3,
) -> (EdgeId, EdgeId) {
    let centre = Point3::new(blend.centre.x, blend.centre.y, 0.0);
    let start = Point3::new(blend.start.x, blend.start.y, 0.0);
    let x = (start - centre).normalize_or_zero();
    let z = offset.normalize_or_zero();
    let y = z.cross(x);

    let mut arc_edge = |origin: Point3, ends: (VertexId, VertexId)| {
        let curve = builder.add_curve3(Curve3::Circle(Circle3 {
            frame: Frame3 { origin, x, y, z },
            radius,
        }));
        let edge = builder.topology_mut().add_edge(Edge {
            start: ends.0,
            end: ends.1,
            curve: Some(curve),
        });
        // The circle is parameterised by angle from the frame x-axis, which
        // points at the arc start, so the interval IS the sweep.
        builder.set_edge_interval(edge, Interval::new(0.0, blend.sweep));
        edge
    };

    let bottom_edge = arc_edge(centre, bottom);
    let top_edge = arc_edge(centre + offset, top);
    (bottom_edge, top_edge)
}

/// Extrude an arbitrary exact contour.
///
/// Lowers the contour onto the arc-ring extruder, which already builds exact
/// planar walls for straight segments and cylindrical walls for circular
/// ones. Curve kinds it cannot carry exactly are refused by the lowering
/// rather than sampled into chords.
///
/// Holes are refused: the arc cap-loop builder emits a single bound, so a
/// hole would be silently dropped from the caps while still appearing in the
/// walls -- a solid that closes and is wrong.
fn extrude_contour(
    contour: &ContourProfile,
    offset: Vec3,
    tolerance: Tolerance,
) -> GeomResult<ExactBRep> {
    // Outer runs counter-clockwise, holes clockwise, so every ring's wall
    // normals point out of the material. Orienting here rather than demanding
    // it of the caller means an imported contour with either winding builds
    // the same solid.
    let outer = orient_arc_ring(&contour_to_arc_ring(&contour.outer, tolerance)?, true)?;
    let mut rings = Vec::with_capacity(1 + contour.holes.len());
    rings.push(outer);
    for hole in &contour.holes {
        rings.push(orient_arc_ring(
            &contour_to_arc_ring(hole, tolerance)?,
            false,
        )?);
    }

    // A section of only straight segments is a polygon, and the polygon path
    // carries face naming the arc path does not. Routing it there keeps one
    // behaviour for one shape.
    if rings
        .iter()
        .all(|ring| ring.vertices.iter().all(|vertex| vertex.bulge == 0.0))
    {
        let polygons: Vec<Vec<Point2>> = rings
            .iter()
            .map(|ring| ring.vertices.iter().map(|vertex| vertex.point).collect())
            .collect();
        return extrude_polygon_rings(&polygons, offset);
    }
    extrude_arc_rings(&rings, offset)
}

/// Extrude a composite profile: union the members, then extrude the result.
fn extrude_composite(
    members: &[Profile],
    offset: Vec3,
    tolerance: Tolerance,
) -> GeomResult<ExactBRep> {
    let (outer, holes) = lower_composite(members, tolerance)?;
    // Ring 0 is the outer boundary and the rest are through-holes, which is
    // exactly the shape `extrude_polygon_rings` already expects.
    let mut rings = Vec::with_capacity(1 + holes.len());
    rings.push(outer);
    rings.extend(holes);
    extrude_polygon_rings(&rings, offset)
}

/// Extrude an ellipse profile into an elliptical-cylinder prism.
///
/// Mirrors `extrude_circle`: one seam edge, two closed cap edges, a single
/// curved wall. The wall is a genuine `EllipticalCylinder`, not a spline
/// approximation, and the cap pcurve is an `Ellipse2` whose parameter matches
/// the wall's `u` -- both use `(a cos t, b sin t)`, which is what lets the
/// cap boundary and the wall boundary agree exactly on the shared edge.
fn extrude_ellipse(ellipse: &EllipseProfile, offset: Vec3) -> GeomResult<ExactBRep> {
    let (a, b) = (ellipse.semi_axis_x, ellipse.semi_axis_y);
    if !a.is_finite() || !b.is_finite() || a <= 0.0 || b <= 0.0 {
        return Err(GeomError::InvalidInput(format!(
            "exact ellipse profile semi-axes must be positive and finite, got {a} x {b}"
        )));
    }
    if offset.x != 0.0 || offset.y != 0.0 {
        return Err(unsupported("oblique ellipse extrusion"));
    }

    let frame_bottom = identity_frame3(Vec3::ZERO);
    let frame_top = identity_frame3(offset);
    let frame2 = Frame2 {
        origin: Vec2::ZERO,
        x: Vec2::X,
        y: Vec2::Y,
    };
    // The seam sits at t = 0, which is (a, 0) for this parameterisation.
    let bottom_point = Vec3::new(a, 0.0, 0.0);
    let top_point = bottom_point + offset;

    let mut builder = ExactBRepBuilder::default();
    reserve(&mut builder, 2, 3, 3, 3, 3, 8, 3)?;
    let bottom_vertex = builder.topology_mut().add_vertex(Vertex {
        position: bottom_point,
    });
    let top_vertex = builder.topology_mut().add_vertex(Vertex {
        position: top_point,
    });

    let bottom_curve = builder.add_curve3(Curve3::Ellipse(Ellipse3 {
        frame: frame_bottom,
        semi_axis_x: a,
        semi_axis_y: b,
    }));
    let bottom_edge = builder.topology_mut().add_edge(Edge {
        start: bottom_vertex,
        end: bottom_vertex,
        curve: Some(bottom_curve),
    });
    builder.set_edge_interval(bottom_edge, Interval::new(0.0, TAU));

    let top_curve = builder.add_curve3(Curve3::Ellipse(Ellipse3 {
        frame: frame_top,
        semi_axis_x: a,
        semi_axis_y: b,
    }));
    let top_edge = builder.topology_mut().add_edge(Edge {
        start: top_vertex,
        end: top_vertex,
        curve: Some(top_curve),
    });
    builder.set_edge_interval(top_edge, Interval::new(0.0, TAU));

    let seam_curve = builder.add_curve3(Curve3::Line(Line3 {
        origin: bottom_point,
        direction: offset,
    }));
    let seam_edge = builder.topology_mut().add_edge(Edge {
        start: bottom_vertex,
        end: top_vertex,
        curve: Some(seam_curve),
    });
    builder.set_edge_interval(seam_edge, Interval::UNIT);

    let bottom_loop = add_ellipse_cap_loop(&mut builder, bottom_edge, frame2, a, b);
    let top_loop = add_ellipse_cap_loop(&mut builder, top_edge, frame2, a, b);

    // The wall's parameter domain is u in [0, TAU] by v in [0, depth], so the
    // trim rectangle is the same as the circular case: only the SURFACE
    // differs, because both parameterise u the same way.
    let depth = offset.z;
    let side_curves = [
        Curve2::Line(Line2 {
            origin: Vec2::ZERO,
            direction: Vec2::X,
        }),
        Curve2::Line(Line2 {
            origin: Vec2::new(TAU, 0.0),
            direction: Vec2::new(0.0, depth),
        }),
        Curve2::Line(Line2 {
            origin: Vec2::new(0.0, depth),
            direction: Vec2::X,
        }),
        Curve2::Line(Line2 {
            origin: Vec2::ZERO,
            direction: Vec2::new(0.0, depth),
        }),
    ];
    let side_edges = [
        (bottom_edge, Orientation::Forward, Interval::new(0.0, TAU)),
        (seam_edge, Orientation::Forward, Interval::UNIT),
        (top_edge, Orientation::Reversed, Interval::new(TAU, 0.0)),
        (seam_edge, Orientation::Reversed, Interval::new(1.0, 0.0)),
    ];
    let mut side_uses = Vec::with_capacity(4);
    let mut side_intervals = Vec::with_capacity(4);
    for ((edge, orientation, interval), curve) in side_edges.into_iter().zip(side_curves) {
        let pcurve = builder.add_curve2(curve);
        side_uses.push(EdgeUse {
            edge,
            orientation,
            pcurve: Some(pcurve),
        });
        side_intervals.push(interval);
    }
    let side_loop = add_loop(&mut builder, side_uses, side_intervals);

    let bottom_surface = builder.add_surface(Surface::Plane(Plane {
        frame: frame_bottom,
    }));
    let top_surface = builder.add_surface(Surface::Plane(Plane { frame: frame_top }));
    let side_surface = builder.add_surface(Surface::EllipticalCylinder(EllipticalCylinder {
        frame: frame_bottom,
        semi_axis_x: a,
        semi_axis_y: b,
    }));
    let bottom_face = add_single_bound_face(
        &mut builder,
        bottom_surface,
        bottom_loop,
        Orientation::Reversed,
    );
    let top_face = add_single_bound_face(&mut builder, top_surface, top_loop, Orientation::Forward);
    let side_face =
        add_single_bound_face(&mut builder, side_surface, side_loop, Orientation::Forward);
    finish_closed(builder, vec![bottom_face, top_face, side_face])
}

/// A closed cap loop whose single edge is trimmed by an ellipse pcurve.
fn add_ellipse_cap_loop(
    builder: &mut ExactBRepBuilder,
    edge: EdgeId,
    frame: Frame2,
    semi_axis_x: Scalar,
    semi_axis_y: Scalar,
) -> LoopId {
    let pcurve = builder.add_curve2(Curve2::Ellipse(Ellipse2 {
        frame,
        semi_axis_x,
        semi_axis_y,
    }));
    add_loop(
        builder,
        vec![EdgeUse {
            edge,
            orientation: Orientation::Forward,
            pcurve: Some(pcurve),
        }],
        vec![Interval::new(0.0, TAU)],
    )
}

/// Lower a contour-shaped profile to its `ContourProfile`.
///
/// Shared by extrusion and revolution so the two cannot disagree about what
/// a `Section`, `CenterLine`, `Derived` or `Composite` actually denotes: a
/// second copy of this mapping is exactly how one sweep starts building a
/// different shape from the other.
pub fn profile_to_contour(profile: &Profile, tolerance: Tolerance) -> GeomResult<ContourProfile> {
    match profile {
        Profile::Contour(contour) => Ok(contour.clone()),
        Profile::Section(section) => section_contour(section),
        Profile::CenterLine(center_line) => center_line_contour(center_line, tolerance),
        Profile::Derived { basis, transform } => {
            let lowered = lower_derived(basis, transform, tolerance)?;
            profile_to_contour(&lowered, tolerance)
        }
        // `lower_composite` unions its members into POINT rings, because the
        // union operates on polygons. Those rings have already lost their
        // segment kinds, so rebuilding a contour from them would fabricate
        // straight edges where the members had arcs. Refused rather than
        // silently re-approximated; the extrusion path consumes the rings
        // directly and does not need this.
        Profile::Composite(_) => Err(unsupported(
            "composite profile does not lower to an exact contour",
        )),
        _ => Err(unsupported("profile does not lower to a contour")),
    }
}