Skip to main content

brep_kernel/construction/sweep_topology/
draft.rs

1use super::*;
2
3/// Straight extrude of a LINE/ARC profile loop with a draft (taper) angle,
4/// built DIRECTLY as a BREP: every wall is the EXACT drafted surface of its
5/// segment — a tilted plane for a line, a cone patch (rational ruled surface
6/// between the source arc and its concentric offset, over one shared angular
7/// window) for a circular arc — and every junction edge is the EXACT
8/// intersection curve of the two adjacent walls.  Because all drafted walls
9/// shrink linearly at the same rate, any two of them intersect in a straight
10/// line (plane∧plane, or a tangent-junction ruling) or a CONIC (plane∧cone and
11/// cone∧cone both reduce to a plane section of a cone — the z² terms of the
12/// squared implicits cancel), so the junction edges are exact rational
13/// quadratics: no lofted approximation anywhere.
14///
15/// Positive `draft_angle_rad` tapers the section INWARD with height (smaller
16/// far cap); negative widens it; 0 reproduces a straight prism.  The far
17/// section is the exact in-plane miter offset of the profile by
18/// d = distance·tan(draft): line segments re-intersect at their offset
19/// corners, arcs shrink/grow concentrically, and mixed junctions re-join at
20/// the offset primitives' intersection.  An offset that exceeds the local
21/// feature size (a collapsed arc, offsets that no longer meet) is a clear Err.
22/// Face order: [walls in INPUT curve order…, START cap (profile plane), END
23/// cap (offset section at +distance)] — the naming contract callers stamp on.
24pub fn extrude_profile_brep_draft(
25    profile: &[NurbsCurve],
26    direction: Vec3,
27    distance: f64,
28    draft_angle_rad: f64,
29    name: Option<&str>,
30) -> Result<BrepSolid, KernelRefusal> {
31    // The builder carries no face names; accept `name` for ABI symmetry with
32    // the other builders (the app stamps names onto the emitted face order).
33    let _ = name;
34    let tolerance = 1e-6;
35    if profile.len() < 2 {
36        return Err(KernelRefusal::input(
37            KernelStage::Collect,
38            "profile_count",
39            "draftExtrude: profile needs at least 2 curves forming a closed loop",
40        ));
41    }
42    if distance.abs() <= 1e-12 {
43        return Err(KernelRefusal::input(
44            KernelStage::Collect,
45            "distance",
46            "draftExtrude: distance must be non-zero",
47        ));
48    }
49    let axis = direction.normalized().map_err(|_| {
50        KernelRefusal::input(
51            KernelStage::Collect,
52            "direction",
53            "draftExtrude: direction is degenerate",
54        )
55    })?;
56
57    // --- 1. Validate the profile: closed + planar; derive origin O + normal np.
58    let mut samples = Vec::new();
59    for (index, curve) in profile.iter().enumerate() {
60        let [start, end] = curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
61        let next = &profile[(index + 1) % profile.len()];
62        let next_start = next.domain().or_refuse(KernelStage::Fragment, "domain")?[0];
63        if curve
64            .evaluate(end).or_refuse(KernelStage::Fragment, "evaluate")?
65            .sub(next.evaluate(next_start).or_refuse(KernelStage::Fragment, "evaluate")?)
66            .length()
67            > tolerance
68        {
69            return Err(KernelRefusal::input(
70                KernelStage::Collect,
71                "profile_closed",
72                format!("draftExtrude: profile is not closed at curve {index}"),
73            ));
74        }
75        for sample in 0..16 {
76            samples.push(curve.evaluate(start + (end - start) * sample as f64 / 16.0).or_refuse(KernelStage::Fragment, "evaluate")?);
77        }
78    }
79    let normal = crate::polygon::newell_normal(&samples);
80    let centroid = samples.iter().fold(Vec3::default(), |sum, &point| sum.add(point));
81    let np = normal.normalized().map_err(|_| {
82        KernelRefusal::input(
83            KernelStage::Collect,
84            "profile_area",
85            "draftExtrude: profile is degenerate (zero enclosed area)",
86        )
87    })?;
88    let origin = centroid.scale(1.0 / samples.len() as f64);
89    if samples
90        .iter()
91        .any(|point| point.sub(origin).dot(np).abs() > tolerance * 100.0)
92    {
93        return Err(KernelRefusal::input(
94            KernelStage::Collect,
95            "profile_planar",
96            "draftExtrude: profile is not planar",
97        ));
98    }
99    // A straight draft-extrude runs along the profile normal.
100    if np.dot(axis).abs() < 0.999 {
101        return Err(KernelRefusal::unsupported(
102            KernelStage::Classify,
103            "oblique_draft",
104            "draftExtrude: extrude direction must be parallel to the profile normal",
105        ));
106    }
107
108    // --- 2. Normalize the loop CCW about the EXTRUDE direction and derive the
109    //     signed in-plane offset d = distance·tan(draft).  In the CCW frame the
110    //     per-segment offset normal zh×t points INWARD, so positive d shrinks
111    //     the far section — algebraically identical to the historical
112    //     winding·distance·tanθ law about the Newell normal, for either profile
113    //     winding and either extrude side.
114    let displacement = axis.scale(distance);
115    let zh = displacement.normalized().or_refuse(KernelStage::Fragment, "normalized")?;
116    let height = displacement.length();
117    let x_axis = zh.perpendicular().or_refuse(KernelStage::Fragment, "perpendicular")?;
118    let y_axis = zh.cross(x_axis).normalized().or_refuse(KernelStage::Fragment, "normalized")?;
119    let mut curves: Vec<NurbsCurve> = profile.to_vec();
120    let reversed_winding = profile_area(&curves, origin, x_axis, y_axis).or_refuse(KernelStage::Fragment, "profile_area")? < 0.0;
121    if reversed_winding {
122        curves = curves
123            .iter()
124            .rev()
125            .map(NurbsCurve::reversed)
126            .collect::<Result<_, _>>().or_refuse(KernelStage::Fragment, "collect")?;
127    }
128    let signed_d = distance * draft_angle_rad.tan();
129
130    // --- 3. Classify segments and compute the exact junction stations: the
131    //     original vertices (offset 0), the mid-height offsets (d/2, the conic
132    //     shoulder witnesses), and the far offsets (d, raised by the extrude
133    //     vector).  Every station is an exact offset-primitive intersection.
134    let segs = classify_profile_segments(&curves, zh)
135        .map_err(|e| e.with_message(|e| format!("draftExtrude: {e}")))?;
136    let count = segs.len();
137    let mut bottom_junctions = Vec::with_capacity(count);
138    let mut top_junctions = Vec::with_capacity(count);
139    let mut mid_junctions = Vec::with_capacity(count);
140    for index in 0..count {
141        let prev = &segs[(index + count - 1) % count];
142        let next = &segs[index];
143        bottom_junctions.push(
144            offset_junction(prev, next, zh, 0.0)
145                .map_err(|e| e.with_message(|e| format!("draftExtrude: {e}")))?,
146        );
147        top_junctions.push(
148            offset_junction(prev, next, zh, signed_d)
149                .map_err(|e| e.with_message(|e| format!("draftExtrude: {e}")))?
150                .add(displacement),
151        );
152        mid_junctions.push(
153            offset_junction(prev, next, zh, signed_d * 0.5)
154                .map_err(|e| e.with_message(|e| format!("draftExtrude: {e}")))?
155                .add(displacement.scale(0.5)),
156        );
157    }
158
159    // --- 4. Junction (side) edges: the EXACT wall∧wall intersection curve — a
160    //     straight line where the mid-height witness is collinear (plane∧plane
161    //     miters, tangent-junction rulings), otherwise the exact conic through
162    //     both endpoints with the analytic surface-gradient end tangents.
163    let mut side_curves = Vec::with_capacity(count);
164    for index in 0..count {
165        side_curves.push(junction_edge_curve(
166            &segs[(index + count - 1) % count],
167            &segs[index],
168            bottom_junctions[index],
169            mid_junctions[index],
170            top_junctions[index],
171            zh,
172            height,
173            signed_d,
174        )?);
175    }
176
177    // --- 5. Per-segment wall geometry: bottom/top boundary curves + the exact
178    //     wall surface.  Arc walls share ONE angular window between the two
179    //     rows so the ruled surface is the exact cone; their boundary edges are
180    //     SUBRANGES of the rows (identical parameterization → parameter-line
181    //     pcurves are pointwise exact).
182    enum WallSurface {
183        /// Affine plane patch + its frame (pcurves = exact plane projection).
184        Plane { origin: Vec3, ex: Vec3, ey: Vec3 },
185        /// Exact cone patch (pcurves for side edges are fitted on-surface).
186        Cone,
187    }
188    let mut wall_surfaces = Vec::with_capacity(count);
189    let mut wall_kinds = Vec::with_capacity(count);
190    let mut bottom_curves = Vec::with_capacity(count);
191    let mut top_curves = Vec::with_capacity(count);
192    for index in 0..count {
193        let next_index = (index + 1) % count;
194        let a0 = bottom_junctions[index];
195        let a1 = bottom_junctions[next_index];
196        let b0 = top_junctions[index];
197        let b1 = top_junctions[next_index];
198        match &segs[index] {
199            SegGeom::Line { dir, .. } => {
200                let up = b0.sub(a0);
201                let ey = up
202                    .sub(dir.scale(up.dot(*dir)))
203                    .normalized()
204                    .map_err(|_| {
205                        KernelRefusal::internal(
206                            KernelStage::Fragment,
207                            "wall_frame",
208                            "draftExtrude: wall plane frame is degenerate",
209                        )
210                    })?;
211                // Patch extent: the four junctions plus BOTH side curves'
212                // control points (a conic bulges past its chord; the control
213                // polygon's convex hull bounds it).
214                let mut points = vec![a0, a1, b0, b1];
215                for side in [&side_curves[index], &side_curves[next_index]] {
216                    for control in &side.control_points {
217                        points.push(control.point().or_refuse(KernelStage::Fragment, "control_point")?);
218                    }
219                }
220                let mut min_x = f64::INFINITY;
221                let mut min_y = f64::INFINITY;
222                let mut max_x = f64::NEG_INFINITY;
223                let mut max_y = f64::NEG_INFINITY;
224                for point in &points {
225                    let delta = point.sub(a0);
226                    min_x = min_x.min(delta.dot(*dir));
227                    max_x = max_x.max(delta.dot(*dir));
228                    min_y = min_y.min(delta.dot(ey));
229                    max_y = max_y.max(delta.dot(ey));
230                }
231                let padding = (max_x - min_x).max(max_y - min_y) * 0.05 + 1e-6;
232                let patch_origin = a0
233                    .add(dir.scale(min_x - padding))
234                    .add(ey.scale(min_y - padding));
235                wall_surfaces.push(make_plane(
236                    patch_origin,
237                    *dir,
238                    ey,
239                    max_x - min_x + 2.0 * padding,
240                    max_y - min_y + 2.0 * padding,
241                ).or_refuse(KernelStage::Fragment, "make_plane")?);
242                wall_kinds.push(WallSurface::Plane {
243                    origin: patch_origin,
244                    ex: *dir,
245                    ey,
246                });
247                bottom_curves.push(make_line(a0, a1).or_refuse(KernelStage::Fragment, "make_line")?);
248                top_curves.push(make_line(b0, b1).or_refuse(KernelStage::Fragment, "make_line")?);
249            }
250            SegGeom::Arc {
251                center,
252                radius,
253                turn,
254                arc_normal,
255                ..
256            } => {
257                let in_plane = |p: Vec3| {
258                    let rel = p.sub(*center);
259                    rel.sub(zh.scale(rel.dot(zh)))
260                };
261                let ax = in_plane(a0).normalized().or_refuse(KernelStage::Fragment, "normalized")?;
262                let ay = arc_normal.cross(ax).normalized().or_refuse(KernelStage::Fragment, "normalized")?;
263                let angle_near = |p: Vec3, near: f64| {
264                    let ve = in_plane(p);
265                    let mut angle = ve.dot(ay).atan2(ve.dot(ax));
266                    while angle < near - std::f64::consts::PI {
267                        angle += std::f64::consts::TAU;
268                    }
269                    while angle > near + std::f64::consts::PI {
270                        angle -= std::f64::consts::TAU;
271                    }
272                    angle
273                };
274                let mut sweep = in_plane(a1).dot(ay).atan2(in_plane(a1).dot(ax));
275                if sweep <= 1e-9 {
276                    sweep += std::f64::consts::TAU;
277                }
278                let phi0 = angle_near(b0, 0.0);
279                let phi1 = angle_near(b1, sweep);
280                let theta_lo = 0.0_f64.min(phi0);
281                let theta_hi = sweep.max(phi1);
282                if theta_hi - theta_lo > std::f64::consts::TAU {
283                    return Err(KernelRefusal::internal(
284                        KernelStage::Fragment,
285                        "arc_window",
286                        "draftExtrude: a drafted arc's trimmed window exceeds a full circle",
287                    ));
288                }
289                let r_offset = radius - signed_d * turn;
290                if r_offset <= tolerance {
291                    return Err(KernelRefusal::input(
292                        KernelStage::Classify,
293                        "arc_collapse",
294                        "draftExtrude: offset: distance is too large — a concave arc collapses",
295                    ));
296                }
297                let row_bottom = make_arc(*center, ax, ay, *radius, theta_lo, theta_hi).or_refuse(KernelStage::Fragment, "make_arc")?;
298                let row_top =
299                    make_arc(center.add(displacement), ax, ay, r_offset, theta_lo, theta_hi).or_refuse(KernelStage::Fragment, "make_arc")?;
300                wall_surfaces.push(ruled_between(&row_bottom, &row_top)?);
301                wall_kinds.push(WallSurface::Cone);
302                bottom_curves.push(arc_window_subrange(&row_bottom, a0, a1)?);
303                top_curves.push(arc_window_subrange(&row_top, b0, b1)?);
304            }
305        }
306    }
307
308    // --- 5b. The far section must still be the profile's own offset. Past the
309    //     taper that closes a part of the section (a rectangle's short side
310    //     shrunk to nothing, an L's arm pinched shut) the junction stations
311    //     above are still computed, but they describe a loop that has turned
312    //     a segment end over end or crossed itself, and the solid assembled
313    //     from them passes through itself while its incidences stay sound.
314    far_section_survives(&bottom_curves, &top_curves, x_axis, y_axis, tolerance)?;
315
316    // --- 6. Assemble the BREP: shared vertices/edges, wall faces with exact
317    //     pcurves (plane projection on plane walls, parameter lines for cone
318    //     row edges, on-surface fits for cone side edges), and the two planar
319    //     caps — the same topology the straight extrude emits.
320    let mut vertices = Vec::with_capacity(2 * count);
321    for (index, point) in bottom_junctions.iter().enumerate() {
322        vertices.push(VertexRecord {
323            id: index as u64 + 1,
324            point: *point,
325        });
326    }
327    for (index, point) in top_junctions.iter().enumerate() {
328        vertices.push(VertexRecord {
329            id: (count + index) as u64 + 1,
330            point: *point,
331        });
332    }
333    let mut edges = Vec::with_capacity(3 * count);
334    for index in 0..count {
335        let [b_start, b_end] = bottom_curves[index].domain().or_refuse(KernelStage::Fragment, "domain")?;
336        edges.push(EdgeRecord {
337            id: 10 + index as u64,
338            curve: bottom_curves[index].clone(),
339            t0: b_start,
340            t1: b_end,
341            start_vertex_id: index as u64 + 1,
342            end_vertex_id: ((index + 1) % count) as u64 + 1,
343            degenerate: false,
344            name: None,
345        });
346        let [t_start, t_end] = top_curves[index].domain().or_refuse(KernelStage::Fragment, "domain")?;
347        edges.push(EdgeRecord {
348            id: 10 + count as u64 + index as u64,
349            curve: top_curves[index].clone(),
350            t0: t_start,
351            t1: t_end,
352            start_vertex_id: (count + index) as u64 + 1,
353            end_vertex_id: (count + (index + 1) % count) as u64 + 1,
354            degenerate: false,
355            name: None,
356        });
357        let [s_start, s_end] = side_curves[index].domain().or_refuse(KernelStage::Fragment, "domain")?;
358        edges.push(EdgeRecord {
359            id: 10 + 2 * count as u64 + index as u64,
360            curve: side_curves[index].clone(),
361            t0: s_start,
362            t1: s_end,
363            start_vertex_id: index as u64 + 1,
364            end_vertex_id: (count + index) as u64 + 1,
365            degenerate: false,
366            name: None,
367        });
368    }
369
370    let mut next_id = 1000_u64;
371    let mut faces = Vec::with_capacity(count + 2);
372    for index in 0..count {
373        let next_index = (index + 1) % count;
374        let surface = &wall_surfaces[index];
375        // Traversal-order pcurves for [bottom fwd, side_next up, top rev,
376        // side_this down] on this wall's surface.
377        let (pc_bottom, pc_side_up, pc_top, pc_side_down) = match &wall_kinds[index] {
378            WallSurface::Plane { origin, ex, ey } => (
379                curve_to_plane_parameters(&bottom_curves[index], *origin, *ex, *ey).or_refuse(KernelStage::Fragment, "plane_parameters")?,
380                curve_to_plane_parameters(&side_curves[next_index], *origin, *ex, *ey).or_refuse(KernelStage::Fragment, "plane_parameters")?,
381                curve_to_plane_parameters(&top_curves[index], *origin, *ex, *ey).or_refuse(KernelStage::Fragment, "plane_parameters")?.reversed().or_refuse(KernelStage::Fragment, "reversed")?,
382                curve_to_plane_parameters(&side_curves[index], *origin, *ex, *ey).or_refuse(KernelStage::Fragment, "plane_parameters")?.reversed().or_refuse(KernelStage::Fragment, "reversed")?,
383            ),
384            WallSurface::Cone => {
385                let [b0, b1] = bottom_curves[index].domain().or_refuse(KernelStage::Fragment, "domain")?;
386                let [t0, t1] = top_curves[index].domain().or_refuse(KernelStage::Fragment, "domain")?;
387                (
388                    parameter_line(b0, 0.0, b1, 0.0).or_refuse(KernelStage::Fragment, "parameter_line")?,
389                    build_pcurve_on_surface(surface, &side_curves[next_index]).or_refuse(KernelStage::Fragment, "pcurve")?,
390                    parameter_line(t1, 1.0, t0, 1.0).or_refuse(KernelStage::Fragment, "parameter_line")?,
391                    build_pcurve_on_surface(surface, &side_curves[index]).or_refuse(KernelStage::Fragment, "pcurve")?.reversed().or_refuse(KernelStage::Fragment, "reversed")?,
392                )
393            }
394        };
395        let coedges = vec![
396            CoedgeRecord {
397                id: next_id,
398                edge_id: 10 + index as u64,
399                forward: true,
400                pcurve: pc_bottom,
401            },
402            CoedgeRecord {
403                id: next_id + 1,
404                edge_id: 10 + 2 * count as u64 + next_index as u64,
405                forward: true,
406                pcurve: pc_side_up,
407            },
408            CoedgeRecord {
409                id: next_id + 2,
410                edge_id: 10 + count as u64 + index as u64,
411                forward: false,
412                pcurve: pc_top,
413            },
414            CoedgeRecord {
415                id: next_id + 3,
416                edge_id: 10 + 2 * count as u64 + index as u64,
417                forward: false,
418                pcurve: pc_side_down,
419            },
420        ];
421        next_id += 4;
422        faces.push(FaceRecord {
423            id: next_id + 1,
424            surface: wall_surfaces[index].clone(),
425            same_sense: true,
426            loops: vec![LoopRecord {
427                id: next_id,
428                coedges,
429            }],
430            name: None,
431        });
432        next_id += 2;
433    }
434    if reversed_winding {
435        // The winding normalization reversed the curve loop above; callers
436        // stamp wall names by INPUT-curve order — emit walls in input order.
437        faces.reverse();
438    }
439
440    // Caps: planar bbox patches over each section's own footprint.
441    let cap = |curves: &[NurbsCurve],
442                   edge_base: u64,
443                   forward: bool,
444                   next_id: &mut u64|
445     -> Result<FaceRecord, KernelRefusal> {
446        let mut min_x = f64::INFINITY;
447        let mut min_y = f64::INFINITY;
448        let mut max_x = f64::NEG_INFINITY;
449        let mut max_y = f64::NEG_INFINITY;
450        let mut plane_point = None;
451        for curve in curves {
452            let [start, end] = curve.domain().or_refuse(KernelStage::Fragment, "domain")?;
453            for sample in 0..=16 {
454                let point = curve.evaluate(start + (end - start) * sample as f64 / 16.0).or_refuse(KernelStage::Fragment, "evaluate")?;
455                let anchor = *plane_point.get_or_insert(point);
456                let delta = point.sub(anchor);
457                min_x = min_x.min(delta.dot(x_axis));
458                max_x = max_x.max(delta.dot(x_axis));
459                min_y = min_y.min(delta.dot(y_axis));
460                max_y = max_y.max(delta.dot(y_axis));
461            }
462        }
463        let anchor = plane_point.ok_or_else(|| {
464            KernelRefusal::internal(
465                KernelStage::Fragment,
466                "cap_samples",
467                "draftExtrude: cap has no boundary samples",
468            )
469        })?;
470        let padding = (max_x - min_x).max(max_y - min_y) * 0.05 + 1e-6;
471        let cap_origin = anchor
472            .add(x_axis.scale(min_x - padding))
473            .add(y_axis.scale(min_y - padding));
474        let mut coedges = Vec::with_capacity(curves.len());
475        if forward {
476            for (index, curve) in curves.iter().enumerate() {
477                coedges.push(CoedgeRecord {
478                    id: *next_id,
479                    edge_id: edge_base + index as u64,
480                    forward: true,
481                    pcurve: curve_to_plane_parameters(curve, cap_origin, x_axis, y_axis).or_refuse(KernelStage::Fragment, "plane_parameters")?,
482                });
483                *next_id += 1;
484            }
485        } else {
486            for index in (0..curves.len()).rev() {
487                coedges.push(CoedgeRecord {
488                    id: *next_id,
489                    edge_id: edge_base + index as u64,
490                    forward: false,
491                    pcurve: curve_to_plane_parameters(&curves[index], cap_origin, x_axis, y_axis).or_refuse(KernelStage::Fragment, "plane_parameters")?
492                        .reversed().or_refuse(KernelStage::Fragment, "reversed")?,
493                });
494                *next_id += 1;
495            }
496        }
497        let loop_id = *next_id;
498        let face_id = *next_id + 1;
499        *next_id += 2;
500        Ok(FaceRecord {
501            id: face_id,
502            surface: make_plane(
503                cap_origin,
504                x_axis,
505                y_axis,
506                max_x - min_x + 2.0 * padding,
507                max_y - min_y + 2.0 * padding,
508            ).or_refuse(KernelStage::Fragment, "make_plane")?,
509            same_sense: forward,
510            loops: vec![LoopRecord {
511                id: loop_id,
512                coedges,
513            }],
514            name: None,
515        })
516    };
517    faces.push(cap(&bottom_curves, 10, false, &mut next_id)?);
518    faces.push(cap(&top_curves, 10 + count as u64, true, &mut next_id)?);
519
520    let solid = BrepSolid {
521        mass_properties_cache: Default::default(),
522        cells: Default::default(),
523        id: next_id + 1,
524        vertices,
525        edges,
526        shells: vec![ShellRecord { id: next_id, faces }],
527        genus: 0,
528        kind: crate::BodyKind::Solid,
529    };
530    let issues = solid.validate();
531    if issues.is_empty() {
532        Ok(solid)
533    } else {
534        Err(KernelRefusal::internal(
535            KernelStage::Validate,
536            "validate",
537            format!("Rust draft-extrude builder produced invalid topology: {issues:?}"),
538        ))
539    }
540}
541
542/// Whether the far section of a drafted extrude is still the profile's offset:
543/// every segment runs the way its source does and has not shrunk to nothing,
544/// and no two segments that are not neighbours cross. Offsets grow linearly
545/// with height, so a section sound at both ends is sound at every height
546/// between. Refuses by name (`draft_section_closes`) otherwise.
547fn far_section_survives(
548    bottom: &[NurbsCurve],
549    top: &[NurbsCurve],
550    x_axis: Vec3,
551    y_axis: Vec3,
552    tolerance: f64,
553) -> Result<(), KernelRefusal> {
554    const STEPS: usize = 16;
555    let closes = |what: String| {
556        KernelRefusal::input(
557            KernelStage::Classify,
558            "draft_section_closes",
559            format!(
560                "draftExtrude: the taper closes the section before the far end ({what}); \
561                 the drafted walls would pass through each other — refusing"
562            ),
563        )
564    };
565    let sampled = |curve: &NurbsCurve| -> Result<Vec<Vec3>, KernelRefusal> {
566        let [start, end] = curve.domain().or_refuse(KernelStage::Classify, "domain")?;
567        (0..=STEPS)
568            .map(|k| curve.evaluate(start + (end - start) * k as f64 / STEPS as f64).or_refuse(KernelStage::Classify, "evaluate"))
569            .collect()
570    };
571    let mut loops: Vec<Vec<[f64; 2]>> = Vec::with_capacity(top.len());
572    for (index, (low, high)) in bottom.iter().zip(top).enumerate() {
573        let (low, high) = (sampled(low)?, sampled(high)?);
574        let (mut along, mut length) = (0.0, 0.0);
575        for k in 0..STEPS {
576            let step = high[k + 1].sub(high[k]);
577            along += step.dot(low[k + 1].sub(low[k]));
578            length += step.length();
579        }
580        if length <= tolerance || along <= 0.0 {
581            return Err(closes(format!("segment {index} of the far section has shrunk to nothing or turned round")));
582        }
583        loops.push(high.iter().map(|q| [q.dot(x_axis), q.dot(y_axis)]).collect());
584    }
585    let side = |a: [f64; 2], b: [f64; 2], c: [f64; 2]| (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
586    let count = loops.len();
587    for i in 0..count {
588        for j in i + 2..count {
589            if i == 0 && j == count - 1 {
590                continue;
591            }
592            for a in loops[i].windows(2) {
593                for b in loops[j].windows(2) {
594                    let (d1, d2) = (side(b[0], b[1], a[0]), side(b[0], b[1], a[1]));
595                    let (d3, d4) = (side(a[0], a[1], b[0]), side(a[0], a[1], b[1]));
596                    if d1 * d2 < 0.0 && d3 * d4 < 0.0 {
597                        return Err(closes(format!("segments {i} and {j} of the far section cross")));
598                    }
599                }
600            }
601        }
602    }
603    Ok(())
604}