Skip to main content

brep_geometry/geometry/
n_sided.rs

1//! N-sided filling (Golovanov §3.5): a smooth sheet of `N` four-sided patches
2//! spanning a closed loop of 3 to 6 boundary curves.
3//!
4//! # Construction
5//!
6//! Each side is cut at its parameter midpoint `M_i`. A centre point `Q` is
7//! chosen inside the loop, and a cubic *spoke* runs from every midpoint to the
8//! centre. Patch `k` is the Coons patch ([`crate::coons_with_ribbons`]) of
9//! the four curves round corner `P_k`: the second half of side `k − 1`, the
10//! first half of side `k`, and the two spokes between them. Its parameters run
11//! `u` along side `k` and `v` from side `k − 1`'s half towards the centre:
12//! `(0, 0) = P_k`, `(1, 0) = M_k`, `(1, 1) = Q`, `(0, 1) = M_{k−1}`.
13//!
14//! Every patch is given all four cross-boundary derivative fields (ribbons):
15//!
16//! - **Across a side** the ribbon is the derivative into the fill. Without a
17//!   prescribed tangent it is the linear blend of the derivatives the patch's
18//!   corners already have there. With one it stays in the plane of the side's
19//!   tangent and the prescribed direction, which is what makes the fill meet
20//!   the neighbouring face tangentially.
21//! - **Across a spoke** the two patches it divides share one tangent plane:
22//!   the ribbon of the second is `λ(v) r(v) + μ(v) S'(v)`, a combination of the
23//!   first's ribbon `r` and the spoke's own tangent `S'`. The spokes arrive at
24//!   the centre in one plane, so the patches meet there in it as well.
25//!
26//! The Coons patch interpolates the ribbons up to the corner twists, which in
27//! general disagree and of which it carries the mean. With prescribed tangent
28//! planes the disagreement across the planes at a corner P_k is geometry (the
29//! two planes turn unlike along the two sides: a vertex blend of fillets),
30//! and the mean would leave each side's derivative out of its plane along the
31//! whole half side; Gregory's direction-dependent corner twist is added
32//! instead, as a spline graded toward the corner (exact along both sides but
33//! in a span of 2⁻¹⁰ at the corner; zero with zero slope at the spokes). The
34//! joins are still not claimed to be G1. They are measured: [`NSidedReport::spoke_normal_angle`] is
35//! the worst angle between the normals of two patches across a spoke, and
36//! [`NSidedReport::tangent_normal_angle`] the worst angle between a patch's
37//! normal and the prescribed tangent plane along the sides (both as
38//! `atan2(|n × m|, n · m)`).
39//!
40//! # Re-entrant corners
41//!
42//! A corner where the loop turns away from its interior (an L shape's inner
43//! corner) cannot be a patch corner: a Coons patch whose corner angle passes
44//! 180° folds there, wherever the centre is. Such a corner becomes a spoke
45//! point instead: its two sides are taken as one side cut at the corner, the
46//! spoke leaves the corner along the bisector of its angle (or towards the
47//! centre, when that stays clear of both sides) and the patches either side
48//! of it have convex corners there. The centre is aimed at a point of the
49//! loop's kernel, the points from which all of the loop is in sight (Newell's
50//! normal fixes the plane; chords of 32 points to a side bound it): the one
51//! that leaves every patch's outline most convex, at the midpoints' mean's
52//! height (refused when none leaves them all convex). Refused by name: two re-entrant corners
53//! side by side ([`NSidedRefusal::AdjacentReentrant`]), a loop with no kernel
54//! (not star-shaped, [`NSidedRefusal::Centre`]), and a tangent fill across a
55//! re-entrant corner ([`NSidedRefusal::ReentrantTangent`]). Up to 12 sides are
56//! taken when the loop has 3 to 6 once each re-entrant corner's two sides
57//! count as one.
58//!
59//! # Rational sides
60//!
61//! The ribbon constructor is polynomial only, so a rational side (a circular
62//! arc) is replaced by the cubic interpolant of evenly spaced samples along
63//! it, as many as hold it within 1e-8 model units ([`STAND_IN_DEVIATION`]); the patch
64//! edges are then that interpolant, not the arc, and
65//! [`NSidedReport::boundary_deviation`] is the largest distance between the two
66//! measured at the quarter points between the samples; a side whose stand-in
67//! cannot be held within that bound is refused. A prescribed tangent field is
68//! sampled in the same way (only its direction is used).
69//!
70//! # Refusals
71//!
72//! Fewer than 3 or more than 6 sides (counting a re-entrant corner's two
73//! sides as one); two adjacent re-entrant corners, a loop that is not
74//! star-shaped, or a tangent fill across a re-entrant corner; a corner whose two sides miss each other
75//! by more than [`CORNER_FRACTION`] of the loop's size; a side with no length; a tangent field
76//! over a domain not its side's, or one along its side where it should cross
77//! it; and any refusal of a patch's Coons construction, verbatim.
78
79use crate::coons::compat::normalise_domain;
80use crate::coons::{coons_with_ribbons, CoonsRefusal};
81use crate::fit::interpolate_curve;
82use crate::{model_scale, NurbsCurve, NurbsSurface, Vec3, Vec4};
83
84/// Samples of a rational side or a field for its cubic stand-in, to start
85/// with; a side's sampling doubles until its stand-in is within
86/// [`STAND_IN_DEVIATION`] of it, up to [`FIT_SAMPLES_MOST`].
87const FIT_SAMPLES: usize = 257;
88const FIT_SAMPLES_MOST: usize = 16385;
89/// The absolute distance (model units) a rational side's polynomial stand-in
90/// is held within, at any size, so a pcurve of the true side on the patch
91/// stays far inside the kernel's 1e-7 pcurve floor.
92pub const STAND_IN_DEVIATION: f64 = 1e-8;
93/// Two consecutive sides meet within this fraction of the loop's size: a
94/// band relative to the loop, so it is as tight for a small corner as for a
95/// large one (the feature joins picks within the same fraction).
96pub const CORNER_FRACTION: f64 = 1e-5;
97/// A side with a knot of its own this close to its parameter midpoint (in
98/// its [0, 1]) is cut at that knot: a cut beside a knot leaves a half with a
99/// sliver span at its end (5.7e-9 on a fitted fillet rib), and a Coons patch
100/// reads its edge derivatives across that sliver, amplifying its net's
101/// rounding (a ribbon missed by 12.8 against a scale of 2.6). The knot is
102/// carried onto the midpoint by an exact reparameterisation of the side and
103/// its field together ([`knot_onto_midpoint`]).
104pub const MIDPOINT_KNOT_BAND: f64 = 1e-7;
105/// The least angle (radians, 15 degrees) the retry construction lets a spoke
106/// leave a side with a prescribed tangent at.
107const SPOKE_LEAST_LEAVE: f64 = 0.2617993877991494;
108/// The share of the field's own across component a shortened bump keeps.
109const BUMP_ACROSS_KEPT: f64 = 0.25;
110/// The reaches tried: 0.5 down by BUMP_REACH_STEP, BUMP_REACH_STEPS of them,
111/// BUMP_REACH_LEAST when none keeps the across component.
112const BUMP_REACH_STEP: f64 = 0.05;
113const BUMP_REACH_STEPS: usize = 10;
114const BUMP_REACH_LEAST: f64 = 0.05;
115/// Samples over a reach where the across component is read.
116const BUMP_REACH_SAMPLES: usize = 64;
117/// Samples along each join where its normals are compared.
118const JOIN_SAMPLES: usize = 33;
119/// `|w − 1|` below which a curve counts as polynomial.
120const POLYNOMIAL_BAND: f64 = 1e-12;
121
122/// Why an N-sided fill was refused.
123#[derive(Debug, Clone, PartialEq)]
124pub enum NSidedRefusal {
125    /// The loop has `sides` sides; 3 to 6 are filled.
126    SideCount { sides: usize },
127    /// The tangent fields are not one per side.
128    TangentCount { sides: usize, tangents: usize },
129    /// Side `side` has no length.
130    DegenerateSide { side: usize, extent: f64 },
131    /// The end of side `side` misses the next side by `gap` (band `band`).
132    CornerGap { side: usize, gap: f64, band: f64 },
133    /// Side `side`'s tangent field is over another domain than the side.
134    TangentDomain { side: usize },
135    /// Side `side`'s tangent field runs along the side at its midpoint (the
136    /// sine of its angle to the side is `sine`), so it gives no direction
137    /// across it.
138    TangentAlongSide { side: usize, sine: f64 },
139    /// The centre the spokes meet at is not a point the patches can share.
140    Centre { detail: String },
141    /// Corners `corner` and the next are both re-entrant: the side between
142    /// them would be a patch with no convex corner.
143    AdjacentReentrant { corner: usize },
144    /// A tangent fill across a loop with a re-entrant corner (`corner`).
145    ReentrantTangent { corner: usize },
146    /// Patch `patch`'s Coons construction refused.
147    Patch { patch: usize, refusal: CoonsRefusal },
148    /// Side `side` is rational and no cubic stand-in within
149    /// [`STAND_IN_DEVIATION`] was found (the best was `deviation` off).
150    StandIn { side: usize, deviation: f64 },
151    /// A curve operation failed (verbatim).
152    Geometry { detail: String },
153}
154
155impl std::fmt::Display for NSidedRefusal {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        match self {
158            Self::SideCount { sides } => write!(f, "N-sided fill: the loop has {sides} sides; 3 to 6 are filled"),
159            Self::TangentCount { sides, tangents } => {
160                write!(f, "N-sided fill: {tangents} tangent fields for {sides} sides; give one per side")
161            }
162            Self::DegenerateSide { side, extent } => {
163                write!(f, "N-sided fill: side {side} has no length (extent {extent:.3e})")
164            }
165            Self::CornerGap { side, gap, band } => write!(
166                f,
167                "N-sided fill: the end of side {side} misses the next side by {gap:.3e} (corner band {band:.3e})"
168            ),
169            Self::TangentDomain { side } => {
170                write!(f, "N-sided fill: the tangent field of side {side} is not over the side's own domain")
171            }
172            Self::TangentAlongSide { side, sine } => write!(
173                f,
174                "N-sided fill: the tangent field of side {side} runs along the side at its midpoint (sine {sine:.3e}), so it gives no direction across it"
175            ),
176            Self::Centre { detail } => write!(f, "N-sided fill: no centre point: {detail}"),
177            Self::AdjacentReentrant { corner } => write!(
178                f,
179                "N-sided fill: corners {corner} and {} are both re-entrant; the side between them has no convex corner to fill from",
180                corner + 1
181            ),
182            Self::ReentrantTangent { corner } => write!(
183                f,
184                "N-sided fill: corner {corner} is re-entrant; a tangent fill across a re-entrant corner is not built (fill in position)"
185            ),
186            Self::Patch { patch, refusal } => write!(f, "N-sided fill: patch {patch}: {refusal}"),
187            Self::StandIn { side, deviation } => write!(
188                f,
189                "N-sided fill: side {side} is rational and its best cubic stand-in is {deviation:.3e} off it (bound {STAND_IN_DEVIATION:.0e})"
190            ),
191            Self::Geometry { detail } => write!(f, "N-sided fill: {detail}"),
192        }
193    }
194}
195
196impl std::error::Error for NSidedRefusal {}
197
198fn geometry(detail: impl std::fmt::Display) -> NSidedRefusal {
199    NSidedRefusal::Geometry { detail: detail.to_string() }
200}
201
202/// What an N-sided fill built and measured.
203#[derive(Debug, Clone)]
204pub struct NSidedReport {
205    pub sides: usize,
206    /// Which sides were reversed to run head to tail from side 0.
207    pub reversed: Vec<bool>,
208    /// The worst corner gap between consecutive sides as given.
209    pub corner_gap: f64,
210    /// The corner band the gaps were admitted within.
211    pub corner_band: f64,
212    /// The centre point all patches share.
213    pub centre: Vec3,
214    /// The re-entrant corners (corner `k` is where side `k` starts), each
215    /// taken as a spoke point with its two sides whole patch edges.
216    pub reentrant_corners: Vec<usize>,
217    /// Largest distance between a rational side and its polynomial stand-in
218    /// (0 when every side is polynomial).
219    pub boundary_deviation: f64,
220    /// Worst normal angle (radians) between the two patches across a spoke.
221    pub spoke_normal_angle: f64,
222    /// Worst normal angle (radians) between a patch and the prescribed tangent
223    /// plane along the sides; `None` without tangent fields.
224    pub tangent_normal_angle: Option<f64>,
225    /// Worst corner-twist disagreement any patch carried the mean of.
226    pub twist_discrepancy: f64,
227    /// Worst cross-derivative residual of any patch against its ribbons.
228    pub cross_derivative_residual: f64,
229    /// Where each side (as given, in its own parameter) was cut at its
230    /// midpoint: its parameter midpoint, or a knot of its own within
231    /// [`MIDPOINT_KNOT_BAND`] of it; `None` for a side taken whole (one of a
232    /// re-entrant corner's two sides). A caller splitting the side's edge
233    /// for the patches cuts it here.
234    pub split_parameters: Vec<Option<f64>>,
235}
236
237/// Fill the closed loop `sides` (3 to 6 curves, in order round the loop,
238/// either way along each) with `N` four-sided patches.
239///
240/// `tangents`, when given, holds one vector-valued curve per side, over that
241/// side's own parameter domain: at each parameter, a direction ACROSS the side
242/// in the tangent plane the fill is to meet (the neighbouring face's plane);
243/// only its direction matters, and its sign does not (the fill lies on the
244/// side of the loop its interior is on). The patches come in corner order,
245/// patch `k` at the start of side `k` (after orientation).
246pub fn n_sided_fill(
247    sides: &[NurbsCurve],
248    tangents: Option<&[NurbsCurve]>,
249) -> Result<(Vec<NurbsSurface>, NSidedReport), NSidedRefusal> {
250    fill(sides, tangents, false, false)
251}
252
253/// [`n_sided_fill`] with each corner-twist bump along a side with a
254/// prescribed tangent reaching only as far as keeps the field's own across
255/// component (see `fill`): the retry for a fill whose patch folds beside a
256/// side where the two twists at its corner disagree by far more than that
257/// component.
258pub fn n_sided_fill_shortening_reach(
259    sides: &[NurbsCurve],
260    tangents: &[NurbsCurve],
261) -> Result<(Vec<NurbsSurface>, NSidedReport), NSidedRefusal> {
262    fill(sides, Some(tangents), true, false)
263}
264
265/// [`n_sided_fill_shortening_reach`] with each spoke also leaving a side with
266/// a prescribed tangent at least 15 degrees off it: the second retry, for a
267/// fill whose patches part beside a spoke that leaves nearly along its side.
268pub fn n_sided_fill_shortening_reach_spokes_off_sides(
269    sides: &[NurbsCurve],
270    tangents: &[NurbsCurve],
271) -> Result<(Vec<NurbsSurface>, NSidedReport), NSidedRefusal> {
272    fill(sides, Some(tangents), true, true)
273}
274
275fn fill(
276    sides: &[NurbsCurve],
277    tangents: Option<&[NurbsCurve]>,
278    shorten_reach: bool,
279    spokes_off_sides: bool,
280) -> Result<(Vec<NurbsSurface>, NSidedReport), NSidedRefusal> {
281    let count = sides.len();
282    if !(3..=12).contains(&count) {
283        return Err(NSidedRefusal::SideCount { sides: count });
284    }
285    if let Some(fields) = tangents {
286        if fields.len() != count {
287            return Err(NSidedRefusal::TangentCount { sides: count, tangents: fields.len() });
288        }
289    }
290    let ends = |curve: &NurbsCurve| -> Result<(Vec3, Vec3), NSidedRefusal> {
291        let [t0, t1] = curve.domain().map_err(geometry)?;
292        Ok((curve.evaluate(t0).map_err(geometry)?, curve.evaluate(t1).map_err(geometry)?))
293    };
294    let mut points = Vec::new();
295    for curve in sides {
296        let (a, b) = ends(curve)?;
297        points.push(a);
298        points.push(b);
299    }
300    let scale = model_scale(points.iter().copied());
301    let band = CORNER_FRACTION * scale;
302
303    // Orient head to tail from side 0 as given; domains onto [0, 1].
304    let mut oriented: Vec<NurbsCurve> = Vec::with_capacity(count);
305    let mut fields: Vec<Option<NurbsCurve>> = Vec::with_capacity(count);
306    let mut reversed = Vec::with_capacity(count);
307    let mut corner_gap = 0.0_f64;
308    for (index, side) in sides.iter().enumerate() {
309        let (start, end) = ends(side)?;
310        if start.sub(end).length() <= band && polyline_extent(side)? <= band {
311            return Err(NSidedRefusal::DegenerateSide { side: index, extent: polyline_extent(side)? });
312        }
313        let flip = if index == 0 {
314            // side 0 sets the sense; it must still meet side 1 at its end
315            let (next_start, next_end) = ends(&sides[1])?;
316            let forward = end.sub(next_start).length().min(end.sub(next_end).length());
317            let backward = start.sub(next_start).length().min(start.sub(next_end).length());
318            backward < forward
319        } else {
320            let previous_end = ends(&oriented[index - 1])?.1;
321            start.sub(previous_end).length() > end.sub(previous_end).length()
322        };
323        let mut field = tangents.map(|all| all[index].clone());
324        if let Some(curve) = &field {
325            let [a0, a1] = side.domain().map_err(geometry)?;
326            let [b0, b1] = curve.domain().map_err(geometry)?;
327            let span = (a1 - a0).abs().max(1.0);
328            if (a0 - b0).abs() > 1e-9 * span || (a1 - b1).abs() > 1e-9 * span {
329                return Err(NSidedRefusal::TangentDomain { side: index });
330            }
331        }
332        let mut curve = side.clone();
333        if flip {
334            curve = curve.reversed().map_err(geometry)?;
335            if let Some(vector) = &field {
336                field = Some(vector.reversed().map_err(geometry)?);
337            }
338        }
339        let curve = normalise_domain(&curve).map_err(geometry)?.0;
340        let field = match field {
341            Some(vector) => Some(normalise_domain(&vector).map_err(geometry)?.0),
342            None => None,
343        };
344        if index > 0 {
345            let gap = ends(&oriented[index - 1])?.1.sub(ends(&curve)?.0).length();
346            corner_gap = corner_gap.max(gap);
347            if gap > band {
348                return Err(NSidedRefusal::CornerGap { side: index - 1, gap, band });
349            }
350        }
351        oriented.push(curve);
352        fields.push(field);
353        reversed.push(flip);
354    }
355    let closing = ends(&oriented[count - 1])?.1.sub(ends(&oriented[0])?.0).length();
356    corner_gap = corner_gap.max(closing);
357    if closing > band {
358        return Err(NSidedRefusal::CornerGap { side: count - 1, gap: closing, band });
359    }
360
361    // Polynomial stand-ins for rational sides and fields.
362    let mut boundary_deviation = 0.0_f64;
363    for (index, curve) in oriented.iter_mut().enumerate() {
364        if is_rational(curve) {
365            let (fitted, deviation) = polynomial_stand_in(curve, true)?;
366            if deviation > STAND_IN_DEVIATION {
367                return Err(NSidedRefusal::StandIn { side: index, deviation });
368            }
369            boundary_deviation = boundary_deviation.max(deviation);
370            *curve = fitted;
371        }
372    }
373    for field in fields.iter_mut().flatten() {
374        if is_rational(field) {
375            *field = polynomial_stand_in(field, false)?.0;
376        }
377    }
378
379    // Halves: A_i = side i over [0, 1/2], B_i over [1/2, 1], each on [0, 1]
380    // (both scaled alike, so A_i'(1) = B_i'(0)).
381    //
382    // A re-entrant corner (the loop turns away from its interior there) is
383    // no patch corner: a Coons patch with a corner angle past 180° folds at
384    // it, wherever the centre is. It becomes a spoke point instead: its two
385    // sides are taken as one side whose halves are the two sides whole, so
386    // the spoke leaves the corner into the interior and splits its angle
387    // between two convex patch corners. The centre is then chosen in the
388    // loop's kernel (the points that see all of it), which a loop with a
389    // re-entrant corner needs and the midpoints' mean need not lie in.
390    let (reentrant, loop_normal) = reentrant_corners_oriented(&oriented)?;
391    let mut groups: Vec<(usize, Option<usize>)> = (0..count).map(|index| (index, None)).collect();
392    let mut kernel = None;
393    if let Some(corner) = reentrant.iter().position(|is| *is) {
394        if tangents.is_some() {
395            return Err(NSidedRefusal::ReentrantTangent { corner });
396        }
397        if let Some(corner) = (0..count).find(|&k| reentrant[k] && reentrant[(k + 1) % count]) {
398            return Err(NSidedRefusal::AdjacentReentrant { corner });
399        }
400        let start = (0..count).find(|&k| !reentrant[k]).expect("no two re-entrant corners are adjacent");
401        groups.clear();
402        let mut step = 0;
403        while step < count {
404            let index = (start + step) % count;
405            if reentrant[(index + 1) % count] {
406                groups.push((index, Some((index + 1) % count)));
407                step += 2;
408            } else {
409                groups.push((index, None));
410                step += 1;
411            }
412        }
413        kernel = Some(star_kernel(&oriented, loop_normal, scale)?);
414    }
415    let count = groups.len();
416    if !(3..=6).contains(&count) {
417        return Err(NSidedRefusal::SideCount { sides: count });
418    }
419    let kinked: Vec<bool> = groups.iter().map(|(_, joined)| joined.is_some()).collect();
420    let mut first = Vec::with_capacity(count);
421    let mut second = Vec::with_capacity(count);
422    let mut split_parameters: Vec<Option<f64>> = vec![None; sides.len()];
423    // per side (in loop order) its second half's speed at the cut over its
424    // first half's: 1 at a cut at the midpoint, (1 − cut) / cut at a knot
425    let mut speed_ratio: Vec<f64> = Vec::with_capacity(groups.len());
426    for &(index, joined) in &groups {
427        match joined {
428            None => {
429                // A knot of the side's own within the band of its midpoint is
430                // carried onto the midpoint: raised to full multiplicity
431                // (exact) and each half's parameter mapped affinely, the
432                // side and its field alike, so the curve and the plane it
433                // reads at every point are unchanged and every half reads
434                // the side at 0.5 as before; the cut is then that knot.
435                // `BREP_N_SIDED_SLIVER_KNOTS`: a second knot beside the one
436                // nearest the midpoint (a fitted rib carries one within 6e-9
437                // of it) would leave a sliver span beside the cut whatever
438                // the cut; it is removed where the curve is unchanged without
439                // it (within SLIVER_KNOT_TOLERANCE of its size), side and
440                // field alike (a field with a zero pole keeps its knots).
441                if sliver_knots_on() {
442                    let size = polyline_extent(&oriented[index])?.max(f64::MIN_POSITIVE);
443                    oriented[index] = without_sliver_knots(&oriented[index], SLIVER_KNOT_TOLERANCE * size);
444                    if let Some(field) = &fields[index] {
445                        // relative to the field's smallest pole: the field's
446                        // size is arbitrary, its directions are what counts
447                        let least = field
448                            .control_points
449                            .iter()
450                            .map(|pole| (pole.x * pole.x + pole.y * pole.y + pole.z * pole.z).sqrt())
451                            .fold(f64::INFINITY, f64::min);
452                        if least.is_finite() && least > 0.0 {
453                            fields[index] = Some(without_sliver_knots(field, SLIVER_KNOT_TOLERANCE * least));
454                        }
455                    }
456                }
457                let near = oriented[index]
458                    .knots
459                    .iter()
460                    .copied()
461                    .filter(|knot| *knot > 0.0 && *knot < 1.0 && (knot - 0.5).abs() <= MIDPOINT_KNOT_BAND)
462                    .min_by(|a, b| (a - 0.5).abs().total_cmp(&(b - 0.5).abs()));
463                let cut = match near {
464                    Some(knot) if knot != 0.5 => {
465                        oriented[index] = knot_onto_midpoint(&oriented[index], knot)?;
466                        if let Some(field) = &fields[index] {
467                            fields[index] = Some(knot_onto_midpoint(field, knot)?);
468                        }
469                        knot
470                    }
471                    _ => 0.5,
472                };
473                speed_ratio.push((1.0 - cut) / cut);
474                let [t0, t1] = sides[index].domain().map_err(geometry)?;
475                split_parameters[index] = Some(if reversed[index] { t1 - cut * (t1 - t0) } else { t0 + cut * (t1 - t0) });
476                let (a, b) = oriented[index].split(0.5).map_err(geometry)?;
477                first.push(normalise_domain(&a).map_err(geometry)?.0);
478                second.push(normalise_domain(&b).map_err(geometry)?.0);
479            }
480            Some(next) => {
481                speed_ratio.push(1.0);
482                first.push(oriented[index].clone());
483                second.push(oriented[next].clone());
484            }
485        }
486    }
487    // A joined side is its first curve here (its start and, with no tangent
488    // fields, nothing else is read from it); its end is `second`'s.
489    let oriented: Vec<NurbsCurve> = groups.iter().map(|(index, _)| oriented[*index].clone()).collect();
490    let fields: Vec<Option<NurbsCurve>> = groups.iter().map(|(index, _)| fields[*index].clone()).collect();
491    let at = |curve: &NurbsCurve, t: f64| curve.evaluate(t).map_err(geometry);
492    let slope = |curve: &NurbsCurve, t: f64| curve.deriv1(t).map(|(_, d)| d).map_err(geometry);
493    let field_half = |field: &NurbsCurve, half: usize, s: f64| field.evaluate(0.5 * (s + half as f64)).map_err(geometry);
494    let end_slope = |index: usize| -> Result<Vec3, NSidedRefusal> {
495        if kinked[index] { slope(&second[index], 1.0) } else { slope(&oriented[index], 1.0) }
496    };
497
498    // Midpoints, side tangents there and the directions into the fill: in
499    // the tangent plane at the midpoint (the prescribed one, or the plane of
500    // the side and the bisector of its neighbours' directions), towards the
501    // midpoints' mean. On a regular loop that is square to the side; on a
502    // skewed one it is the way the surface's own cross curves run (a saddle's
503    // rulings, which leave a side at a slant).
504    let middle: Vec<Vec3> = first.iter().map(|half| at(half, 1.0)).collect::<Result<_, _>>()?;
505    let mean = middle.iter().fold(Vec3::new(0.0, 0.0, 0.0), |sum, point| sum.add(*point)).scale(1.0 / count as f64);
506    // With a re-entrant corner the centre is aimed at the point of the
507    // loop's kernel that leaves every patch's corners most convex, at the
508    // midpoints' mean's height above the loop's plane.
509    let mean = match &kernel {
510        Some(kernel) => {
511            let corners: Vec<Vec3> = first.iter().map(|half| at(half, 0.0)).collect::<Result<_, _>>()?;
512            kernel.best_centre(&corners, &middle, mean)?
513        }
514        None => mean,
515    };
516    let mut across = Vec::with_capacity(count);
517    for index in 0..count {
518        let along = slope(&first[index], 1.0)?;
519        let unit = along.normalized().map_err(|_| NSidedRefusal::DegenerateSide { side: index, extent: 0.0 })?;
520        let raw = match &fields[index] {
521            Some(field) => {
522                let g = field.evaluate(0.5).map_err(geometry)?;
523                let off = g.sub(unit.scale(g.dot(unit)));
524                let sine = off.length() / g.length().max(f64::MIN_POSITIVE);
525                if !(sine > 1e-6) {
526                    return Err(NSidedRefusal::TangentAlongSide { side: index, sine });
527                }
528                // the sense into the loop: towards the other sides
529                let previous = end_slope((index + count - 1) % count)?.scale(-1.0);
530                let next = slope(&oriented[(index + 1) % count], 0.0)?;
531                let inward = previous.normalized().map_err(geometry)?.add(next.normalized().map_err(geometry)?);
532                if off.dot(inward) < 0.0 { off.scale(-1.0) } else { off }
533            }
534            None if kinked[index] => {
535                // into the interior at a re-entrant corner: the bisector of
536                // its angle past 180°
537                let out = slope(&second[index], 0.0)?.normalized().map_err(geometry)?;
538                unit.sub(out)
539            }
540            None => {
541                let previous = end_slope((index + count - 1) % count)?.scale(-1.0);
542                let next = slope(&oriented[(index + 1) % count], 0.0)?;
543                let sum = previous.normalized().map_err(geometry)?.add(next.normalized().map_err(geometry)?);
544                sum.sub(unit.scale(sum.dot(unit)))
545            }
546        };
547        let square = raw.normalized().map_err(|_| NSidedRefusal::Centre {
548            detail: format!("side {index} gives no direction into the loop at its midpoint"),
549        })?;
550        let plane_normal = unit.cross(square);
551        let toward = mean.sub(middle[index]);
552        let in_plane_toward = toward.sub(plane_normal.scale(toward.dot(plane_normal)));
553        // At a re-entrant corner the spoke must leave into the interior
554        // past both sides (a convex corner each side of it).
555        let inside_both = |direction: Vec3| -> Result<bool, NSidedRefusal> {
556            if !kinked[index] {
557                return Ok(true);
558            }
559            let out = slope(&second[index], 0.0)?.normalized().map_err(geometry)?;
560            Ok(unit.cross(direction).dot(loop_normal) > 1e-3 && out.cross(direction).dot(loop_normal) > 1e-3)
561        };
562        let direction = match in_plane_toward.normalized() {
563            Ok(direction) if direction.dot(square) > 1e-3 && inside_both(direction)? => direction,
564            _ => square,
565        };
566        // `spokes_off_sides`: a spoke leaving a side with a prescribed
567        // tangent at least SPOKE_LEAST_LEAVE off the side. A spoke leaving
568        // nearly along its side (7 degrees, at a star whose rounds meet at
569        // radii 0.9 against 3) splits the plane at the midpoint between
570        // directions that hardly differ, and the two patches beside it part
571        // there by 1e-4 rad.
572        let direction = if spokes_off_sides && fields[index].is_some() && !kinked[index] {
573            let along = direction.dot(unit);
574            if along.abs() > SPOKE_LEAST_LEAVE.cos() {
575                unit.scale(along.signum() * SPOKE_LEAST_LEAVE.cos()).add(square.scale(SPOKE_LEAST_LEAVE.sin()))
576            } else {
577                direction
578            }
579        } else {
580            direction
581        };
582        across.push(direction);
583    }
584    let reach: Vec<f64> = middle.iter().map(|point| mean.sub(*point).length()).collect();
585    if reach.iter().any(|length| !(*length > band)) {
586        return Err(NSidedRefusal::Centre { detail: "a side's midpoint is at the loop's centre".into() });
587    }
588    // Two estimates of the centre that err on opposite sides of a curved
589    // fill by the same second-order amount: the midpoints' mean (on their
590    // chords, inside a dome) and each midpoint shot along its tangent `across`
591    // until it has come as far towards that mean as the mean is from it (on
592    // the tangents, outside). For a paraboloid of revolution their mean is
593    // exactly its vertex; on a plane both are the same point.
594    let mut shot = Vec3::new(0.0, 0.0, 0.0);
595    for index in 0..count {
596        let toward = mean.sub(middle[index]);
597        let unit = toward.scale(1.0 / reach[index]);
598        let pace = across[index].dot(unit);
599        if !(pace > 1e-3) {
600            return Err(NSidedRefusal::Centre {
601                detail: format!("side {index} turns away from the loop's centre at its midpoint"),
602            });
603        }
604        shot = shot.add(middle[index].add(across[index].scale(reach[index] / pace)));
605    }
606    let shot = shot.scale(1.0 / count as f64);
607    let centre = mean.add(shot).scale(0.5);
608    let normal = (0..count)
609        .fold(Vec3::new(0.0, 0.0, 0.0), |sum, index| {
610            let along = slope(&first[index], 1.0).unwrap_or(Vec3::new(0.0, 0.0, 0.0));
611            sum.add(along.cross(across[index]).normalized().unwrap_or(Vec3::new(0.0, 0.0, 0.0)))
612        })
613        .normalized()
614        .map_err(|_| NSidedRefusal::Centre { detail: "the sides' normals cancel".into() })?;
615
616    // Spokes: cubic from M_i (leaving along `across`) to Q (arriving in the
617    // centre's tangent plane).
618    let mut spokes = Vec::with_capacity(count);
619    let mut spoke_bends = Vec::with_capacity(count);
620    for index in 0..count {
621        let toward = centre.sub(middle[index]);
622        let arrive = toward.sub(normal.scale(toward.dot(normal))).normalized().map_err(|_| NSidedRefusal::Centre {
623            detail: format!("the spoke from side {index} arrives along the centre's normal"),
624        })?;
625        let length = toward.length();
626        let poles = [
627            middle[index],
628            middle[index].add(across[index].scale(length / 3.0)),
629            centre.sub(arrive.scale(length / 3.0)),
630            centre,
631        ];
632        spoke_bends.push(poles[1].sub(poles[2].scale(2.0)).add(poles[3]).scale(6.0));
633        spokes.push(bezier(&poles)?);
634    }
635
636    // The field of derivatives into the fill along each whole side, `F_i(t)`
637    // in the halves' parameter scale: at the side's start the derivative
638    // along the side before it (reversed), at its midpoint the spoke's start,
639    // at its end the derivative along the side after it. Without a prescribed
640    // tangent it is the quadratic through those three; with one it is
641    // `a(t) g(t) + b(t) T(t)` in the prescribed plane, `(a, b)` quadratic
642    // through the three values' fits, plus each corner's misfit faded out by
643    // the midpoint. One smooth field per side gives the two patches beside a
644    // midpoint the same corner twist there.
645    let raw_value = |index: usize, t: f64| -> Result<Vec3, NSidedRefusal> {
646        let previous = (index + count - 1) % count;
647        let next = (index + 1) % count;
648        let values = [
649            slope(&second[previous], 1.0)?.scale(-1.0),
650            slope(&spokes[index], 0.0)?,
651            slope(&first[next], 0.0)?,
652        ];
653        let lagrange = [2.0 * (t - 0.5) * (t - 1.0), -4.0 * t * (t - 1.0), 2.0 * t * (t - 0.5)];
654        match &fields[index] {
655            None => Ok(values
656                .iter()
657                .zip(lagrange)
658                .fold(Vec3::new(0.0, 0.0, 0.0), |sum, (value, weight)| sum.add(value.scale(weight)))),
659            Some(field) => {
660                let along = |t: f64| slope(&oriented[index], t);
661                let mut fit = [(0.0, 0.0); 3];
662                let mut misfit = [Vec3::new(0.0, 0.0, 0.0); 3];
663                for (k, at_t) in [0.0, 0.5, 1.0].into_iter().enumerate() {
664                    let (g, d) = (field.evaluate(at_t).map_err(geometry)?, along(at_t)?);
665                    fit[k] = in_plane(values[k], g, d)?;
666                    misfit[k] = values[k].sub(g.scale(fit[k].0).add(d.scale(fit[k].1)));
667                }
668                let a = (0..3).map(|k| fit[k].0 * lagrange[k]).sum::<f64>();
669                let b = (0..3).map(|k| fit[k].1 * lagrange[k]).sum::<f64>();
670                let fade = |x: f64| if x > 0.0 { x * x } else { 0.0 };
671                Ok(field
672                    .evaluate(t)
673                    .map_err(geometry)?
674                    .scale(a)
675                    .add(along(t)?.scale(b))
676                    .add(misfit[0].scale(fade(1.0 - 2.0 * t)))
677                    .add(misfit[2].scale(fade(2.0 * t - 1.0)))
678                    .add(misfit[1].scale(1.0 - fade(1.0 - 2.0 * t) - fade(2.0 * t - 1.0))))
679            }
680        }
681    };
682    // A field's derivative in t, by second-order differences (central inside,
683    // one-sided at the ends).
684    const STEP: f64 = 1e-4;
685    let raw_slope = |index: usize, t: f64| -> Result<Vec3, NSidedRefusal> {
686        let f = |x: f64| raw_value(index, x);
687        if t <= 0.0 {
688            Ok(f(0.0)?.scale(-3.0).add(f(STEP)?.scale(4.0)).sub(f(2.0 * STEP)?).scale(0.5 / STEP))
689        } else if t >= 1.0 {
690            Ok(f(1.0)?.scale(3.0).sub(f(1.0 - STEP)?.scale(4.0)).add(f(1.0 - 2.0 * STEP)?).scale(0.5 / STEP))
691        } else {
692            Ok(f(t + STEP)?.sub(f(t - STEP)?).scale(0.5 / STEP))
693        }
694    };
695    // The corner twists. At P_k the patch has one twist from side k's field
696    // (`F_k'(0)`) and one from side k − 1's (`−F_{k−1}'(1)`); both are moved to
697    // their mean by a bump that is zero, with zero slope, at the midpoint, so
698    // the midpoint twists stay. With a prescribed tangent the bump is the
699    // move's part in the prescribed plane, carried along in the plane (`x g(t)
700    // + y T(t)`), so the field never leaves it; what remains of the twists'
701    // disagreement is their part across the plane.
702    let mut fixes: Vec<[Vec3; 2]> = vec![[Vec3::new(0.0, 0.0, 0.0); 2]; count];
703    for k in 0..count {
704        let previous = (k + count - 1) % count;
705        let (start, end) = (raw_slope(k, 0.0)?, raw_slope(previous, 1.0)?);
706        let mean = start.sub(end).scale(0.5);
707        fixes[k][0] = mean.sub(start);
708        fixes[previous][1] = mean.scale(-1.0).sub(end);
709    }
710    let mut plane_fixes: Vec<[(f64, f64); 2]> = vec![[(0.0, 0.0); 2]; count];
711    for index in 0..count {
712        if let Some(field) = &fields[index] {
713            for (end, t) in [(0usize, 0.0), (1usize, 1.0)] {
714                let (g, d) = (field.evaluate(t).map_err(geometry)?, slope(&oriented[index], t)?);
715                plane_fixes[index][end] = in_plane(fixes[index][end], g, d)?;
716            }
717        }
718    }
719    // The bump's reach from each end of a side with a prescribed tangent: half
720    // the side, or (`shorten_reach`) the longest of 0.5, 0.45, …,
721    // 0.05 over which the in-plane move leaves at least BUMP_ACROSS_KEPT of
722    // the field's own across component, in its own sense. Where the two
723    // twists at a corner disagree by far more than the field's across size
724    // (a long rib against a short one: a box corner of radii r, r and R for
725    // about 0.293 R < r < 0.35 R), the move over half the side cancels the
726    // across component and the patch folds beside the side; a shorter reach
727    // carries the same twist to the corner, keeps the plane, and stays clear
728    // of the fold. A reach that has to shorten on one side alone leaves every
729    // other side as it was.
730    let mut reaches: Vec<[f64; 2]> = vec![[0.5, 0.5]; count];
731    if shorten_reach {
732        for index in 0..count {
733            let Some(field) = &fields[index] else { continue };
734            for end in 0..2 {
735                let move_across = plane_fixes[index][end].0;
736                let sense = if end == 0 { 1.0 } else { -1.0 };
737                let mut reach = BUMP_REACH_LEAST;
738                for step in 0..BUMP_REACH_STEPS {
739                    let candidate = 0.5 - BUMP_REACH_STEP * step as f64;
740                    let mut kept = true;
741                    for j in 1..BUMP_REACH_SAMPLES {
742                        let r = candidate * j as f64 / BUMP_REACH_SAMPLES as f64;
743                        let t = if end == 0 { r } else { 1.0 - r };
744                        let (g, d) = (field.evaluate(t).map_err(geometry)?, slope(&oriented[index], t)?);
745                        let own = in_plane(raw_value(index, t)?, g, d)?.0;
746                        let shape = r * (1.0 - r / candidate) * (1.0 - r / candidate);
747                        let total = own + move_across * sense * shape;
748                        if !(total * own > 0.0 && total.abs() >= BUMP_ACROSS_KEPT * own.abs()) {
749                            kept = false;
750                            break;
751                        }
752                    }
753                    if kept {
754                        reach = candidate;
755                        break;
756                    }
757                }
758                reaches[index][end] = reach;
759            }
760        }
761    }
762    let field_value = |index: usize, t: f64| -> Result<Vec3, NSidedRefusal> {
763        // φ(0) = 0, φ'(0) = 1, φ(w) = φ'(w) = 0 for the reach w (½ unless
764        // shortened above); ψ the same at t = 1
765        let [w0, w1] = reaches[index];
766        let phi = if w0 == 0.5 {
767            if t < 0.5 { t * (1.0 - 2.0 * t) * (1.0 - 2.0 * t) } else { 0.0 }
768        } else if t < w0 {
769            t * (1.0 - t / w0) * (1.0 - t / w0)
770        } else {
771            0.0
772        };
773        let psi = if w1 == 0.5 {
774            if t > 0.5 { -(1.0 - t) * (2.0 * t - 1.0) * (2.0 * t - 1.0) } else { 0.0 }
775        } else if t > 1.0 - w1 {
776            -(1.0 - t) * (1.0 - (1.0 - t) / w1) * (1.0 - (1.0 - t) / w1)
777        } else {
778            0.0
779        };
780        let value = raw_value(index, t)?;
781        Ok(match &fields[index] {
782            None => value.add(fixes[index][0].scale(phi)).add(fixes[index][1].scale(psi)),
783            Some(field) => {
784                let (g, d) = (field.evaluate(t).map_err(geometry)?, slope(&oriented[index], t)?);
785                let [(x0, y0), (x1, y1)] = plane_fixes[index];
786                value.add(g.scale(x0 * phi + x1 * psi)).add(d.scale(y0 * phi + y1 * psi))
787            }
788        })
789    };
790    let hermite = |p0: Vec3, d0: Vec3, p1: Vec3, d1: Vec3, s: f64| {
791        let (s2, s3) = (s * s, s * s * s);
792        p0.scale(2.0 * s3 - 3.0 * s2 + 1.0)
793            .add(d0.scale(s3 - 2.0 * s2 + s))
794            .add(p1.scale(-2.0 * s3 + 3.0 * s2))
795            .add(d1.scale(s3 - s2))
796    };
797    let scalar_hermite = |p0: f64, d0: f64, p1: f64, d1: f64, s: f64| {
798        let (s2, s3) = (s * s, s * s * s);
799        p0 * (2.0 * s3 - 3.0 * s2 + 1.0) + d0 * (s3 - 2.0 * s2 + s) + p1 * (-2.0 * s3 + 3.0 * s2) + d1 * (s3 - s2)
800    };
801
802    // The centre twists. Patch k's ribbon across spoke k − 1 is
803    // `R_k = λ_k r_{k−1} + μ_k S'_{k−1}` (see below); at Q its twist from that
804    // side is `R_k'(1) = λ_k'(1) S'_{k−2}(1) + λ_k(1) w_{k−1} + μ_k'(1)
805    // S'_{k−1}(1) + μ_k(1) S''_{k−1}(1)` and from its own spoke ribbon `w_k =
806    // r_k'(1)`. The `w`, `λ'(1)` and `μ'(1)` that make the two agree round all
807    // N patches are one small linear system, solved by least squares near the
808    // plain choices (the ribbons' chords), which agree only by chance.
809    let arrive_at = |k: usize| slope(&spokes[k], 1.0);
810    let mut coefficients = Vec::with_capacity(count);
811    for k in 0..count {
812        let (previous, before) = ((k + count - 1) % count, (k + count - 2) % count);
813        coefficients.push(in_plane(arrive_at(k)?, arrive_at(before)?, arrive_at(previous)?)?);
814    }
815    let unknowns = 5 * count;
816    let mut rows: Vec<Vec<f64>> = Vec::with_capacity(3 * count);
817    let mut rhs: Vec<f64> = Vec::with_capacity(3 * count);
818    for k in 0..count {
819        let (previous, before) = ((k + count - 1) % count, (k + count - 2) % count);
820        let (lambda, mu) = coefficients[k];
821        let (sb, sp) = (arrive_at(before)?, arrive_at(previous)?);
822        let bend = spoke_bends[previous];
823        for axis in 0..3 {
824            let pick = |v: Vec3| [v.x, v.y, v.z][axis];
825            let mut row = vec![0.0; unknowns];
826            row[3 * k + axis] = 1.0;
827            row[3 * previous + axis] -= lambda;
828            row[3 * count + k] = -pick(sb);
829            row[4 * count + k] = -pick(sp);
830            rows.push(row);
831            rhs.push(mu * pick(bend));
832        }
833    }
834    let mut plain = vec![0.0; unknowns];
835    for k in 0..count {
836        let previous = (k + count - 1) % count;
837        let chord = arrive_at(previous)?.sub(slope(&first[k], 1.0)?);
838        plain[3 * k] = chord.x;
839        plain[3 * k + 1] = chord.y;
840        plain[3 * k + 2] = chord.z;
841        plain[3 * count + k] = coefficients[k].0 + 1.0;
842        plain[4 * count + k] = coefficients[k].1;
843    }
844    let mut normal_matrix = vec![vec![0.0; unknowns]; unknowns];
845    let mut normal_rhs = vec![0.0; unknowns];
846    for (row, value) in rows.iter().zip(&rhs) {
847        for i in 0..unknowns {
848            if row[i] == 0.0 {
849                continue;
850            }
851            normal_rhs[i] += row[i] * value;
852            for j in 0..unknowns {
853                normal_matrix[i][j] += row[i] * row[j];
854            }
855        }
856    }
857    let size = normal_matrix.iter().enumerate().map(|(i, row)| row[i]).fold(0.0_f64, f64::max).max(1.0);
858    let regular = 1e-10 * size;
859    for i in 0..unknowns {
860        normal_matrix[i][i] += regular;
861        normal_rhs[i] += regular * plain[i];
862    }
863    let solved = crate::solve_dense(normal_matrix, normal_rhs).map_err(geometry)?;
864    let centre_twist = |k: usize| Vec3::new(solved[3 * k], solved[3 * k + 1], solved[3 * k + 2]);
865    let lambda_slope = |k: usize| solved[3 * count + k];
866    let mu_slope = |k: usize| solved[4 * count + k];
867
868    // The spoke ribbon of each patch (dS/du on u = 1, v from M_k to Q): from
869    // the side's midpoint derivative to the previous spoke's arrival, leaving
870    // M_k with the side field's own twist and reaching Q with the solved one.
871    let mut spoke_ribbons = Vec::with_capacity(count);
872    for k in 0..count {
873        let previous = (k + count - 1) % count;
874        let start = slope(&first[k], 1.0)?;
875        let end = slope(&spokes[previous], 1.0)?;
876        let twist = raw_slope(k, 0.5)?.scale(0.5);
877        let reach_twist = centre_twist(k);
878        // on the knots of the side half the spoke's patch has across from
879        // it (second[k − 1], run from M_{k−1} to P_k: mirrored in v)
880        spoke_ribbons.push(sampled_on(|v| Ok(hermite(start, twist, end, reach_twist, v)), &interior_knots(&second[previous], true))?);
881    }
882    let mut patches = Vec::with_capacity(count);
883    let mut twist_discrepancy = 0.0_f64;
884    let mut cross_derivative_residual = 0.0_f64;
885    for k in 0..count {
886        let previous = (k + count - 1) % count;
887        let before = (k + count - 2) % count;
888        let a = &first[k];
889        let b = &second[previous];
890        let spoke = &spokes[k];
891        let back = &spokes[previous];
892        // r0 across side k's first half (dS/dv at v = 0), s along u; r3
893        // across side k − 1's second half (dS/du at u = 0), s from M_{k−1} to
894        // P_k: the two halves of the side fields.
895        let r0 = sampled_on(|s| field_value(k, 0.5 * s), &interior_knots(a, false))?;
896        let r3 = sampled_on(|s| field_value(previous, 0.5 * (s + 1.0)), &interior_knots(b, false))?;
897        let r1 = spoke_ribbons[k].clone();
898        // r2 across spoke k − 1 (dS/dv at v = 1), over the reversed spoke, s = 0
899        // at Q. In the spoke's own v = 1 − s it is λ(v) r1^{k−1}(v) +
900        // μ(v) S'_{k−1}(v): in the plane of the other patch's ribbon and the
901        // spoke, so the two patches share their tangent plane along it; −r1 at
902        // M_{k−1} with no twist of its own there, and S'_k(1) at Q.
903        let other = &spoke_ribbons[previous];
904        let target = slope(spoke, 1.0)?;
905        let _ = (target, before);
906        let (lambda, mu) = coefficients[k];
907        let (lambda_end, mu_end) = (lambda_slope(k), mu_slope(k));
908        let kink = if kinked[previous] {
909            Some((slope(&first[previous], 1.0)?, slope(&second[previous], 0.0)?))
910        } else {
911            None
912        };
913        // over the reversed spoke: the patch runs u = 1 − s along it
914        let r2 = sampled_on(|s| {
915            let v = 1.0 - s;
916            // at M_{k−1} the ribbon is the boundary's own derivative, the
917            // second half's: the first half's times their speed ratio
918            let l = scalar_hermite(-speed_ratio[previous], 0.0, lambda, lambda_end, v);
919            let m = scalar_hermite(0.0, 0.0, mu, mu_end, v);
920            let ribbon = other.evaluate(v).map_err(geometry)?.scale(l).add(slope(back, v)?.scale(m));
921            Ok(match kink {
922                // at a re-entrant corner the side leaves along `out`, not on
923                // along `into`: the ribbon meets it there and fades back to
924                // the shared-plane form with zero slope
925                Some((into, out)) => ribbon.add(into.sub(out).scale(scalar_hermite(1.0, 0.0, 0.0, 0.0, v))),
926                None => ribbon,
927            })
928        }, &interior_knots(a, true))?;
929        let top = back.reversed().map_err(geometry)?;
930        let top = normalise_domain(&top).map_err(geometry)?.0;
931        let (surface, report) = coons_with_ribbons(
932            [a.clone(), spoke.clone(), top, b.clone()],
933            [Some(r0), Some(r1), Some(r2), Some(r3)],
934        )
935        .map_err(|refusal| NSidedRefusal::Patch { patch: k, refusal })?;
936        if let Some(ribbons) = &report.ribbons {
937            twist_discrepancy = twist_discrepancy.max(ribbons.twist_discrepancy);
938            cross_derivative_residual = cross_derivative_residual.max(ribbons.cross_derivative_residual);
939        }
940        patches.push(surface);
941    }
942
943    // Corner twists across the prescribed planes. Along a side with a
944    // prescribed tangent plane the patch's derivative into the fill must stay
945    // in that plane, and how fast the plane turns along each side fixes the
946    // twist's component across it: at a corner the two sides ask for two
947    // different twists wherever the two planes turn unlike (the vertex blend
948    // of three fillets: one turns about the corner, its neighbour hardly at
949    // all), and a patch smooth at the corner has one. The Coons patch carries
950    // their mean, which leaves each side's derivative out of its plane by a
951    // cubic bump `H1(u) = u (1 − u)²` times the difference, largest a third of
952    // the way along the half side. Gregory's patch meets both with the
953    // direction-dependent twist `(u t_v + v t_u) / (u + v)`; its term is added
954    // here as a spline on knots graded toward the corner, exact along both
955    // sides but in the corner's first span (2⁻¹⁰ of the patch), zero with zero
956    // slope along the spokes, so the joins between patches are untouched.
957    if fields.iter().any(Option::is_some) {
958        for k in 0..count {
959            let previous = (k + count - 1) % count;
960            let along_v0 = fields[k].as_ref().map(|field| (&oriented[k], field));
961            let along_u0 = fields[previous].as_ref().map(|field| (&oriented[previous], field));
962            patches[k] = corner_twist_corrected(&patches[k], along_v0, along_u0)?;
963        }
964    }
965
966    // Measure the joins.
967    let mut spoke_normal_angle = 0.0_f64;
968    for k in 0..count {
969        let next = (k + 1) % count;
970        for index in 0..JOIN_SAMPLES {
971            let v = index as f64 / (JOIN_SAMPLES - 1) as f64;
972            // patch k at (1, v), patch k + 1 at (v, 1): the same point of spoke k
973            let one = unit_normal(&patches[k], 1.0, v)?;
974            let two = unit_normal(&patches[next], v, 1.0)?;
975            if let (Some(one), Some(two)) = (one, two) {
976                spoke_normal_angle = spoke_normal_angle.max(angle(one, two));
977            }
978        }
979    }
980    let tangent_normal_angle = if fields.iter().any(Option::is_some) {
981        let mut worst = 0.0_f64;
982        for k in 0..count {
983            let previous = (k + count - 1) % count;
984            for index in 0..JOIN_SAMPLES {
985                let s = index as f64 / (JOIN_SAMPLES - 1) as f64;
986                if let Some(field) = &fields[k] {
987                    let plane = slope(&first[k], s)?.cross(field_half(field, 0, s)?);
988                    if let (Some(n), Ok(m)) = (unit_normal(&patches[k], s, 0.0)?, plane.normalized()) {
989                        worst = worst.max(line_angle(n, m));
990                    }
991                }
992                if let Some(field) = &fields[previous] {
993                    let plane = slope(&second[previous], s)?.cross(field_half(field, 1, s)?);
994                    if let (Some(n), Ok(m)) = (unit_normal(&patches[k], 0.0, 1.0 - s)?, plane.normalized()) {
995                        worst = worst.max(line_angle(n, m));
996                    }
997                }
998            }
999        }
1000        Some(worst)
1001    } else {
1002        None
1003    };
1004
1005    Ok((
1006        patches,
1007        NSidedReport {
1008            sides: count,
1009            reversed,
1010            corner_gap,
1011            corner_band: band,
1012            centre,
1013            reentrant_corners: reentrant.iter().enumerate().filter(|(_, is)| **is).map(|(k, _)| k).collect(),
1014            boundary_deviation,
1015            spoke_normal_angle,
1016            tangent_normal_angle,
1017            twist_discrepancy,
1018            cross_derivative_residual,
1019            split_parameters,
1020        },
1021    ))
1022}
1023
1024/// Halvings toward the corner of the knots that carry the corner-twist term
1025/// (after them, spans of 1/8). Ten levels, not more: every knot of the term
1026/// is a knot of the patch it is added to, and finer spans (2⁻²⁰, spans of
1027/// 1/32) made a tangent fill of arc sides take 44 s to build into a sheet
1028/// for no reading the 1e-4 rad bar can see.
1029const GRADED_LEVELS: i32 = 10;
1030
1031/// The clamped cubic knots of the corner-twist term on [0, 1]: halving toward
1032/// the corner (0) down to 2⁻¹⁰, spans of 1/8 after. The term vanishes with
1033/// its slope at the far end (the midpoint), so it needs no grading there:
1034/// the seven knots it had toward 1 went into every patch for nothing the
1035/// 1e-4 rad bars read.
1036fn twist_knots() -> Vec<f64> {
1037    let mut interior: Vec<f64> = (4..=GRADED_LEVELS).rev().map(|level| 0.5_f64.powi(level)).collect();
1038    interior.extend((1..8).map(|k| k as f64 / 8.0));
1039    let mut knots = vec![0.0; 4];
1040    knots.extend(interior);
1041    knots.extend([1.0; 4]);
1042    knots
1043}
1044
1045/// The cubic B-spline basis functions on `knots` at `x` (all of them).
1046fn cubic_basis(knots: &[f64], x: f64) -> Vec<f64> {
1047    let n = knots.len() - 4;
1048    let x = x.clamp(knots[3], knots[n]);
1049    let span = (3..n).rev().find(|&i| knots[i] <= x).unwrap_or(3).min(n - 1);
1050    let mut values = vec![0.0; knots.len() - 1];
1051    values[span] = 1.0;
1052    for degree in 1..=3 {
1053        let mut next = vec![0.0; knots.len() - 1 - degree];
1054        for i in 0..next.len() {
1055            let mut value = 0.0;
1056            if knots[i + degree] > knots[i] {
1057                value += (x - knots[i]) / (knots[i + degree] - knots[i]) * values[i];
1058            }
1059            if knots[i + degree + 1] > knots[i + 1] {
1060                value += (knots[i + degree + 1] - x) / (knots[i + degree + 1] - knots[i + 1]) * values[i + 1];
1061            }
1062            next[i] = value;
1063        }
1064        values = next;
1065    }
1066    values.truncate(n);
1067    values
1068}
1069
1070/// `patch` with Gregory's corner-twist term added at its corner (0, 0) (see
1071/// the corner-twist notes in [`n_sided_fill`]). `along_v0` is the side and
1072/// field whose first half is the patch's `v = 0` edge (side parameter
1073/// `t = u / 2`), `along_u0` those whose second half is its `u = 0` edge
1074/// (`t = 1 − v / 2`). Along each the patch's derivative into it misses the
1075/// prescribed plane by `E(x) = (D · n) n`; that miss, fitted as a spline
1076/// on [`twist_knots`] vanishing at both ends (and in slope at the far one),
1077/// is what the term takes away. A rational patch is returned as it is.
1078fn corner_twist_corrected(
1079    patch: &NurbsSurface,
1080    along_v0: Option<(&NurbsCurve, &NurbsCurve)>,
1081    along_u0: Option<(&NurbsCurve, &NurbsCurve)>,
1082) -> Result<NurbsSurface, NSidedRefusal> {
1083    if patch.control_points.iter().flatten().any(|pole| (pole.w - 1.0).abs() > POLYNOMIAL_BAND) {
1084        return Ok(patch.clone());
1085    }
1086    let [u0, u1] = patch.domain_u().map_err(geometry)?;
1087    let [v0, v1] = patch.domain_v().map_err(geometry)?;
1088    let knots = twist_knots();
1089    let n = knots.len() - 4;
1090    let plane_normal = |side: &NurbsCurve, field: &NurbsCurve, t: f64| -> Result<Option<Vec3>, NSidedRefusal> {
1091        let tangent = side.deriv1(t).map_err(geometry)?.1;
1092        Ok(tangent.cross(field.evaluate(t).map_err(geometry)?).normalized().ok())
1093    };
1094    // the miss across the plane along an edge, as spline coefficients
1095    // e_1 .. e_{n−3} (e_0 = e_{n−2} = e_{n−1} = 0), least squares over three
1096    // points in every knot span
1097    let miss = |edge: Option<(&NurbsCurve, &NurbsCurve)>, on_v0: bool| -> Result<Vec<Vec3>, NSidedRefusal> {
1098        let zero = Vec3::new(0.0, 0.0, 0.0);
1099        let Some((side, field)) = edge else { return Ok(vec![zero; n]) };
1100        let free = n - 3;
1101        let mut matrix = vec![vec![0.0; free]; free];
1102        let mut rhs = [vec![0.0; free], vec![0.0; free], vec![0.0; free]];
1103        for span in 3..n {
1104            let (a, b) = (knots[span], knots[span + 1]);
1105            if !(b > a) {
1106                continue;
1107            }
1108            for fraction in [0.2, 0.5, 0.8] {
1109                let x = a + (b - a) * fraction;
1110                let (derivative, t) = if on_v0 {
1111                    let (_, _, sv) = patch.deriv1(u0 + (u1 - u0) * x, v0).map_err(geometry)?;
1112                    (sv.scale(v1 - v0), 0.5 * x)
1113                } else {
1114                    let (_, su, _) = patch.deriv1(u0, v0 + (v1 - v0) * x).map_err(geometry)?;
1115                    (su.scale(u1 - u0), 1.0 - 0.5 * x)
1116                };
1117                let Some(normal) = plane_normal(side, field, t)? else { continue };
1118                let value = normal.scale(derivative.dot(normal));
1119                // weight a span by its length, so the graded spans do not
1120                // swamp the fit
1121                let weight = b - a;
1122                let basis = cubic_basis(&knots, x);
1123                for i in 0..free {
1124                    let bi = basis[i + 1];
1125                    if bi == 0.0 {
1126                        continue;
1127                    }
1128                    rhs[0][i] += weight * bi * value.x;
1129                    rhs[1][i] += weight * bi * value.y;
1130                    rhs[2][i] += weight * bi * value.z;
1131                    for j in 0..free {
1132                        matrix[i][j] += weight * bi * basis[j + 1];
1133                    }
1134                }
1135            }
1136        }
1137        let size = (0..free).map(|i| matrix[i][i]).fold(0.0_f64, f64::max);
1138        for (i, row) in matrix.iter_mut().enumerate() {
1139            row[i] += 1e-14 * size;
1140        }
1141        let mut solved = Vec::with_capacity(3);
1142        for axis in &rhs {
1143            solved.push(crate::solve_dense(matrix.clone(), axis.clone()).map_err(geometry)?);
1144        }
1145        let mut out = vec![zero; n];
1146        for i in 0..free {
1147            out[i + 1] = Vec3::new(solved[0][i], solved[1][i], solved[2][i]);
1148        }
1149        Ok(out)
1150    };
1151    let (a, b) = (miss(along_v0, true)?, miss(along_u0, false)?);
1152    if a.iter().chain(&b).all(|e| e.length() == 0.0) {
1153        return Ok(patch.clone());
1154    }
1155    let term = gregory_twist_term(&knots, &a, &b, [u0, u1], [v0, v1])?;
1156    add_polynomial_surfaces(patch, &term)
1157}
1158
1159/// A bicubic spline `G` on `domain_u × domain_v` (normalised `x, y ∈ [0, 1]`,
1160/// knots `knots` each way) that is zero along all four edges, zero in slope
1161/// across the far two, and has `∂G/∂y (x, 0) = −E(x)` and
1162/// `∂G/∂x (0, y) = −F(y)` exactly but in the corner's first knot span, for
1163/// the splines `E`, `F` with coefficients `a`, `b`: Gregory's corner term
1164/// `−(E(x) W(y) x + F(y) W(x) y) / (x + y)`, `W(t) = t (1 − t)²`, its two
1165/// edge rows set exactly and its inside sampled at the Greville points.
1166fn gregory_twist_term(
1167    knots: &[f64],
1168    a: &[Vec3],
1169    b: &[Vec3],
1170    domain_u: [f64; 2],
1171    domain_v: [f64; 2],
1172) -> Result<NurbsSurface, NSidedRefusal> {
1173    let n = knots.len() - 4;
1174    // ∂/∂y at y = 0 is κ (c_1 − c_0) on a clamped cubic
1175    let kappa = 3.0 / knots[4];
1176    let greville = |i: usize| (knots[i + 1] + knots[i + 2] + knots[i + 3]) / 3.0;
1177    let spline = |coefficients: &[Vec3], x: f64| {
1178        cubic_basis(knots, x).iter().zip(coefficients).fold(Vec3::new(0.0, 0.0, 0.0), |sum, (w, c)| sum.add(c.scale(*w)))
1179    };
1180    let w = |t: f64| t * (1.0 - t) * (1.0 - t);
1181    let zero = Vec3::new(0.0, 0.0, 0.0);
1182    let mut rows = Vec::with_capacity(n);
1183    for i in 0..n {
1184        let mut row = Vec::with_capacity(n);
1185        for j in 0..n {
1186            let value = if i == 0 || j == 0 || i + 2 >= n || j + 2 >= n {
1187                zero
1188            } else if i == 1 && j == 1 {
1189                a[1].add(b[1]).scale(-0.5 / kappa)
1190            } else if j == 1 {
1191                a[i].scale(-1.0 / kappa)
1192            } else if i == 1 {
1193                b[j].scale(-1.0 / kappa)
1194            } else {
1195                let (x, y) = (greville(i), greville(j));
1196                spline(a, x).scale(w(y) * x).add(spline(b, y).scale(w(x) * y)).scale(-1.0 / (x + y))
1197            };
1198            row.push(Vec4::from_point(value, 1.0));
1199        }
1200        rows.push(row);
1201    }
1202    let map = |domain: [f64; 2]| knots.iter().map(|k| domain[0] + (domain[1] - domain[0]) * k).collect::<Vec<f64>>();
1203    NurbsSurface::new(3, 3, map(domain_u), map(domain_v), rows).map_err(geometry)
1204}
1205
1206/// The sum of two polynomial surfaces over one domain, on a common degree
1207/// and knot vector (both refined exactly).
1208fn add_polynomial_surfaces(first: &NurbsSurface, second: &NurbsSurface) -> Result<NurbsSurface, NSidedRefusal> {
1209    use crate::KnotDirection;
1210    let (pu, pv) = (first.degree_u.max(second.degree_u), first.degree_v.max(second.degree_v));
1211    let lift = |surface: &NurbsSurface| -> Result<NurbsSurface, NSidedRefusal> {
1212        let mut out = surface.clone();
1213        if out.degree_u < pu {
1214            out = out.elevate_degree(KnotDirection::U, pu).map_err(geometry)?;
1215        }
1216        if out.degree_v < pv {
1217            out = out.elevate_degree(KnotDirection::V, pv).map_err(geometry)?;
1218        }
1219        Ok(out)
1220    };
1221    let (mut a, mut b) = (lift(first)?, lift(second)?);
1222    // the knots one vector lacks against the other, with multiplicity; two
1223    // knots within the identity tolerance are one knot, as `refine_knots`
1224    // snaps them
1225    let same_knot = |a: f64, b: f64| (a - b).abs() <= crate::curve::KNOT_IDENTITY_TOL;
1226    let missing = |have: &[f64], want: &[f64]| -> Vec<f64> {
1227        let mut out = Vec::new();
1228        let mut index = 0;
1229        while index < want.len() {
1230            let value = want[index];
1231            let wanted = want.iter().filter(|k| same_knot(**k, value)).count();
1232            let held = have.iter().filter(|k| same_knot(**k, value)).count();
1233            out.extend(std::iter::repeat_n(value, wanted.saturating_sub(held)));
1234            index += wanted.max(1);
1235        }
1236        out
1237    };
1238    for direction in [KnotDirection::U, KnotDirection::V] {
1239        let (ka, kb) = match direction {
1240            KnotDirection::U => (a.knots_u.clone(), b.knots_u.clone()),
1241            KnotDirection::V => (a.knots_v.clone(), b.knots_v.clone()),
1242        };
1243        a = a.refine_knots(direction, &missing(&ka, &kb)).map_err(geometry)?;
1244        b = b.refine_knots(direction, &missing(&kb, &ka)).map_err(geometry)?;
1245    }
1246    let same = |x: &[f64], y: &[f64]| x.len() == y.len() && x.iter().zip(y).all(|(p, q)| (p - q).abs() <= 1e-9);
1247    if !same(&a.knots_u, &b.knots_u) || !same(&a.knots_v, &b.knots_v) {
1248        return Err(geometry("the corner-twist term does not share the patch's knots"));
1249    }
1250    let poles = a
1251        .control_points
1252        .iter()
1253        .zip(&b.control_points)
1254        .map(|(row_a, row_b)| {
1255            row_a.iter().zip(row_b).map(|(p, q)| Vec4 { x: p.x + q.x, y: p.y + q.y, z: p.z + q.z, w: 1.0 }).collect()
1256        })
1257        .collect();
1258    NurbsSurface::new(pu, pv, a.knots_u.clone(), a.knots_v.clone(), poles).map_err(geometry)
1259}
1260
1261/// The re-entrant corners of the loop `sides` (each over [0, 1], head to
1262/// tail; corner `k` is where side `k` starts) and the loop's normal (Newell's,
1263/// of points along every side; zero for a loop with no area, which then has
1264/// no re-entrant corner). A corner is re-entrant where the loop turns away
1265/// from its interior, `(T_in × T_out) · n < −1e-6` of the unit tangents.
1266fn reentrant_corners_oriented(sides: &[NurbsCurve]) -> Result<(Vec<bool>, Vec3), NSidedRefusal> {
1267    const PER_SIDE: usize = 16;
1268    let mut points = Vec::with_capacity(sides.len() * PER_SIDE);
1269    for side in sides {
1270        for k in 0..PER_SIDE {
1271            points.push(side.evaluate(k as f64 / PER_SIDE as f64).map_err(geometry)?);
1272        }
1273    }
1274    // about the first point (so a loop far from the origin sums no large
1275    // cancelling terms), and judged against the loop's own size (so a small
1276    // loop is not taken for one with no area)
1277    let origin = points[0];
1278    let local: Vec<Vec3> = points.iter().map(|point| point.sub(origin)).collect();
1279    let newell = (0..local.len()).fold(Vec3::new(0.0, 0.0, 0.0), |sum, k| sum.add(local[k].cross(local[(k + 1) % local.len()])));
1280    let extent = local.iter().map(|point| point.length()).fold(0.0_f64, f64::max);
1281    let length = newell.length();
1282    if !(length > 1e-12 * extent * extent) || !length.is_finite() {
1283        return Ok((vec![false; sides.len()], Vec3::new(0.0, 0.0, 0.0)));
1284    }
1285    let normal = newell.scale(1.0 / length);
1286    let count = sides.len();
1287    let mut reentrant = Vec::with_capacity(count);
1288    for k in 0..count {
1289        let into = sides[(k + count - 1) % count].deriv1(1.0).map_err(geometry)?.1.normalized();
1290        let out = sides[k].deriv1(0.0).map_err(geometry)?.1.normalized();
1291        reentrant.push(match (into, out) {
1292            (Ok(into), Ok(out)) => into.cross(out).dot(normal) < -1e-6,
1293            _ => false,
1294        });
1295    }
1296    Ok((reentrant, normal))
1297}
1298
1299/// The re-entrant corners of a loop of 3 to 12 curves given in order round
1300/// it, either way along each (corner `k` is where side `k` starts, after
1301/// orienting head to tail from side 0). A boundary fill uses it to send a
1302/// four-sided loop with a re-entrant corner to [`n_sided_fill`].
1303pub fn reentrant_corners(sides: &[NurbsCurve]) -> Result<Vec<usize>, NSidedRefusal> {
1304    if sides.len() < 3 {
1305        return Ok(Vec::new());
1306    }
1307    let ends = |curve: &NurbsCurve| -> Result<(Vec3, Vec3), NSidedRefusal> {
1308        let [t0, t1] = curve.domain().map_err(geometry)?;
1309        Ok((curve.evaluate(t0).map_err(geometry)?, curve.evaluate(t1).map_err(geometry)?))
1310    };
1311    let mut oriented: Vec<NurbsCurve> = Vec::with_capacity(sides.len());
1312    for (index, side) in sides.iter().enumerate() {
1313        let (start, end) = ends(side)?;
1314        let flip = if index == 0 {
1315            let (next_start, next_end) = ends(&sides[1])?;
1316            let forward = end.sub(next_start).length().min(end.sub(next_end).length());
1317            let backward = start.sub(next_start).length().min(start.sub(next_end).length());
1318            backward < forward
1319        } else {
1320            let previous_end = ends(&oriented[index - 1])?.1;
1321            start.sub(previous_end).length() > end.sub(previous_end).length()
1322        };
1323        let curve = if flip { side.reversed().map_err(geometry)? } else { side.clone() };
1324        oriented.push(normalise_domain(&curve).map_err(geometry)?.0);
1325    }
1326    let (reentrant, _) = reentrant_corners_oriented(&oriented)?;
1327    Ok(reentrant.iter().enumerate().filter(|(_, is)| **is).map(|(k, _)| k).collect())
1328}
1329
1330/// The kernel of a loop in its plane: the convex polygon of points that see
1331/// every point of the loop (the intersection of the half planes left of each
1332/// chord of 32 points to a side), in the frame `(e1, e2)` of the plane square
1333/// to `normal`.
1334struct Kernel {
1335    origin: Vec3,
1336    e1: Vec3,
1337    e2: Vec3,
1338    polygon: Vec<[f64; 2]>,
1339}
1340
1341impl Kernel {
1342    /// The point of the kernel, placed in the plane through `through` (so a
1343    /// point above the loop's plane keeps its height), that makes the patch
1344    /// outlines `corners[k], middle[k], Q, middle[k − 1]` most convex: the
1345    /// largest least sine of their turns, over the kernel's centroid and a
1346    /// 24 x 24 grid of its points. Refused when no point leaves every outline
1347    /// convex (the patches would fold).
1348    fn best_centre(&self, corners: &[Vec3], middle: &[Vec3], through: Vec3) -> Result<Vec3, NSidedRefusal> {
1349        let flat = |p: Vec3| [p.sub(self.origin).dot(self.e1), p.sub(self.origin).dot(self.e2)];
1350        let corners: Vec<[f64; 2]> = corners.iter().map(|p| flat(*p)).collect();
1351        let middle: Vec<[f64; 2]> = middle.iter().map(|p| flat(*p)).collect();
1352        let count = corners.len();
1353        let score = |q: [f64; 2]| {
1354            let mut least = f64::INFINITY;
1355            for k in 0..count {
1356                let outline = [corners[k], middle[k], q, middle[(k + count - 1) % count]];
1357                for index in 0..4 {
1358                    let (a, b, c) = (outline[index], outline[(index + 1) % 4], outline[(index + 2) % 4]);
1359                    let (d1, d2) = ([b[0] - a[0], b[1] - a[1]], [c[0] - b[0], c[1] - b[1]]);
1360                    let size = (d1[0].hypot(d1[1]) * d2[0].hypot(d2[1])).max(f64::MIN_POSITIVE);
1361                    least = least.min((d1[0] * d2[1] - d1[1] * d2[0]) / size);
1362                }
1363            }
1364            least
1365        };
1366        let inside = |q: [f64; 2]| {
1367            (0..self.polygon.len()).all(|k| {
1368                let (a, b) = (self.polygon[k], self.polygon[(k + 1) % self.polygon.len()]);
1369                (b[0] - a[0]) * (q[1] - a[1]) - (b[1] - a[1]) * (q[0] - a[0]) > 0.0
1370            })
1371        };
1372        let (mut low, mut high) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
1373        for point in &self.polygon {
1374            for axis in 0..2 {
1375                low[axis] = low[axis].min(point[axis]);
1376                high[axis] = high[axis].max(point[axis]);
1377            }
1378        }
1379        let mut best = (self.centroid(), score(self.centroid()));
1380        const GRID: usize = 24;
1381        for i in 1..GRID {
1382            for j in 1..GRID {
1383                let q = [
1384                    low[0] + (high[0] - low[0]) * i as f64 / GRID as f64,
1385                    low[1] + (high[1] - low[1]) * j as f64 / GRID as f64,
1386                ];
1387                if inside(q) {
1388                    let value = score(q);
1389                    if value > best.1 {
1390                        best = (q, value);
1391                    }
1392                }
1393            }
1394        }
1395        if !(best.1 > 1e-3) {
1396            return Err(NSidedRefusal::Centre {
1397                detail: "no point inside the loop leaves every patch convex round it".into(),
1398            });
1399        }
1400        let ([x, y], [x0, y0]) = (best.0, flat(through));
1401        Ok(through.add(self.e1.scale(x - x0)).add(self.e2.scale(y - y0)))
1402    }
1403
1404    /// The kernel polygon's centroid.
1405    fn centroid(&self) -> [f64; 2] {
1406        let (mut area, mut cx, mut cy) = (0.0, 0.0, 0.0);
1407        for k in 0..self.polygon.len() {
1408            let (a, b) = (self.polygon[k], self.polygon[(k + 1) % self.polygon.len()]);
1409            let cross = a[0] * b[1] - b[0] * a[1];
1410            area += cross;
1411            cx += (a[0] + b[0]) * cross;
1412            cy += (a[1] + b[1]) * cross;
1413        }
1414        [cx / (3.0 * area), cy / (3.0 * area)]
1415    }
1416}
1417
1418fn star_kernel(sides: &[NurbsCurve], normal: Vec3, scale: f64) -> Result<Kernel, NSidedRefusal> {
1419    const PER_SIDE: usize = 32;
1420    let not_star = || NSidedRefusal::Centre {
1421        detail: "the loop is not star-shaped: no point inside it sees all of its boundary".into(),
1422    };
1423    let helper = if normal.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) };
1424    let e1 = helper.sub(normal.scale(helper.dot(normal))).normalized().map_err(|_| not_star())?;
1425    let e2 = normal.cross(e1);
1426    // in the plane's frame about the loop's first point, so a loop far from
1427    // the origin clips and measures without cancellation
1428    let origin = sides[0].evaluate(0.0).map_err(geometry)?;
1429    let mut points: Vec<[f64; 2]> = Vec::with_capacity(sides.len() * PER_SIDE);
1430    for side in sides {
1431        for k in 0..PER_SIDE {
1432            let point = side.evaluate(k as f64 / PER_SIDE as f64).map_err(geometry)?.sub(origin);
1433            points.push([point.dot(e1), point.dot(e2)]);
1434        }
1435    }
1436    let (mut low, mut high) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
1437    for point in &points {
1438        for axis in 0..2 {
1439            low[axis] = low[axis].min(point[axis]);
1440            high[axis] = high[axis].max(point[axis]);
1441        }
1442    }
1443    let pad = (high[0] - low[0]).max(high[1] - low[1]);
1444    let mut polygon =
1445        vec![[low[0] - pad, low[1] - pad], [high[0] + pad, low[1] - pad], [high[0] + pad, high[1] + pad], [low[0] - pad, high[1] + pad]];
1446    // keep the side of each chord the interior is on (left, the loop running
1447    // counter-clockwise about its Newell normal)
1448    for k in 0..points.len() {
1449        let (a, b) = (points[k], points[(k + 1) % points.len()]);
1450        let side = |p: [f64; 2]| (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]);
1451        let mut clipped = Vec::with_capacity(polygon.len() + 1);
1452        for index in 0..polygon.len() {
1453            let (p, q) = (polygon[index], polygon[(index + 1) % polygon.len()]);
1454            let (sp, sq) = (side(p), side(q));
1455            if sp >= 0.0 {
1456                clipped.push(p);
1457            }
1458            if (sp >= 0.0) != (sq >= 0.0) {
1459                let t = sp / (sp - sq);
1460                clipped.push([p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t]);
1461            }
1462        }
1463        polygon = clipped;
1464        if polygon.len() < 3 {
1465            return Err(not_star());
1466        }
1467    }
1468    let area = 0.5
1469        * (0..polygon.len())
1470            .map(|k| {
1471                let (a, b) = (polygon[k], polygon[(k + 1) % polygon.len()]);
1472                a[0] * b[1] - b[0] * a[1]
1473            })
1474            .sum::<f64>();
1475    if !(area > 1e-6 * scale * scale) {
1476        return Err(not_star());
1477    }
1478    Ok(Kernel { origin, e1, e2, polygon })
1479}
1480
1481/// The length of a curve's control polygon (zero only for a point).
1482fn polyline_extent(curve: &NurbsCurve) -> Result<f64, NSidedRefusal> {
1483    let points: Vec<Vec3> = curve
1484        .control_points
1485        .iter()
1486        .map(|pole| Vec3::new(pole.x / pole.w, pole.y / pole.w, pole.z / pole.w))
1487        .collect();
1488    Ok(points.windows(2).map(|pair| pair[1].sub(pair[0]).length()).sum())
1489}
1490
1491fn is_rational(curve: &NurbsCurve) -> bool {
1492    curve.control_points.iter().any(|pole| (pole.w - 1.0).abs() > POLYNOMIAL_BAND)
1493}
1494
1495/// The cubic interpolant of points of `curve` (domain [0, 1]) at their own
1496/// parameters, and its largest distance from the curve at the three quarter
1497/// points between them. The points are spread over every knot span of the
1498/// curve alike (`per` to a span, at least [`FIT_SAMPLES`] in all), so a
1499/// feature the curve has in a short span is sampled as finely as a long
1500/// span; with `adaptive` the count doubles until the distance is within
1501/// [`STAND_IN_DEVIATION`] or [`FIT_SAMPLES_MOST`] points are reached (the
1502/// distance is reported either way). A direction field (`adaptive` off)
1503/// takes the first sampling.
1504fn polynomial_stand_in(curve: &NurbsCurve, adaptive: bool) -> Result<(NurbsCurve, f64), NSidedRefusal> {
1505    let mut breaks: Vec<f64> = curve.knots.iter().copied().filter(|knot| (0.0..=1.0).contains(knot)).collect();
1506    breaks.dedup_by(|a, b| (*a - *b).abs() <= 1e-12);
1507    if breaks.first().is_none_or(|first| *first > 0.0) {
1508        breaks.insert(0, 0.0);
1509    }
1510    if breaks.last().is_none_or(|last| *last < 1.0) {
1511        breaks.push(1.0);
1512    }
1513    let spans = breaks.len() - 1;
1514    let mut per = FIT_SAMPLES.div_ceil(spans).max(4);
1515    loop {
1516        // one interpolant per knot span (an interpolant across spans of very
1517        // different lengths rings), joined end to end with a triple knot
1518        let mut parameters = Vec::with_capacity(spans * per + 1);
1519        let mut knots: Vec<f64> = Vec::new();
1520        let mut poles: Vec<Vec4> = Vec::new();
1521        for (index, pair) in breaks.windows(2).enumerate() {
1522            let local: Vec<f64> = (0..=per).map(|k| pair[0] + (pair[1] - pair[0]) * k as f64 / per as f64).collect();
1523            let points: Vec<Vec3> = local.iter().map(|t| curve.evaluate(*t)).collect::<Result<_, _>>().map_err(geometry)?;
1524            let piece = interpolate_curve(&points, 3, &local).map_err(geometry)?;
1525            let interior = &piece.knots[4..piece.knots.len() - 4];
1526            if index == 0 {
1527                knots.extend([pair[0]; 4]);
1528                poles.extend(piece.control_points.iter().copied());
1529            } else {
1530                knots.extend([pair[0]; 3]);
1531                poles.extend(piece.control_points.iter().skip(1).copied());
1532            }
1533            knots.extend(interior.iter().copied());
1534            parameters.extend(local[..per].iter().copied());
1535        }
1536        knots.extend([1.0; 4]);
1537        parameters.push(1.0);
1538        let fitted = NurbsCurve::new(3, knots, poles).map_err(geometry)?;
1539        let mut deviation = 0.0_f64;
1540        for pair in parameters.windows(2) {
1541            for fraction in [0.25, 0.5, 0.75] {
1542                let t = pair[0] + (pair[1] - pair[0]) * fraction;
1543                let gap = fitted.evaluate(t).map_err(geometry)?.sub(curve.evaluate(t).map_err(geometry)?).length();
1544                deviation = deviation.max(gap);
1545            }
1546        }
1547        if !adaptive || deviation <= STAND_IN_DEVIATION || parameters.len() >= FIT_SAMPLES_MOST {
1548            return Ok((fitted, deviation));
1549        }
1550        per *= 2;
1551    }
1552}
1553
1554/// A single Bézier curve on [0, 1] through `poles`.
1555fn bezier(poles: &[Vec3]) -> Result<NurbsCurve, NSidedRefusal> {
1556    let degree = poles.len() - 1;
1557    let mut knots = vec![0.0; degree + 1];
1558    knots.extend(std::iter::repeat_n(1.0, degree + 1));
1559    NurbsCurve::new(degree, knots, poles.iter().map(|pole| Vec4::from_point(*pole, 1.0)).collect()).map_err(geometry)
1560}
1561
1562/// The cubic interpolant over [0, 1] of the vector field `f` on the knots
1563/// of the boundary it travels with (`hint`, interior knots in the ribbon's
1564/// own parameter; the eighths when there are fewer than seven of them),
1565/// interpolating at the Greville points, with its end derivatives made `f`'s
1566/// own (rows of the interpolation in place of the second and second-to-last
1567/// Greville points). A Coons patch carries the union of its boundaries' and
1568/// ribbons' knots, so a ribbon on its boundary's knots adds none; a 33-point
1569/// ribbon added up to 31 to every patch (60 knots a direction on a fillet
1570/// star, most of a box's build in tessellating them). Read against `f` at
1571/// 513 even points and its spans' quarter points; when it misses by more
1572/// than 1e-9 of `f`'s size and by more than half again what the 33-point
1573/// ribbon ([`sampled`]) misses there, it gives way to that ribbon, as it does
1574/// for a boundary with more than 64 interior knots (its solve is dense).
1575fn sampled_on(f: impl Fn(f64) -> Result<Vec3, NSidedRefusal>, hint: &[f64]) -> Result<NurbsCurve, NSidedRefusal> {
1576    let mut interior: Vec<f64> = hint.iter().copied().filter(|knot| *knot > 1e-9 && *knot < 1.0 - 1e-9).collect();
1577    interior.sort_by(f64::total_cmp);
1578    interior.dedup_by(|a, b| (*a - *b).abs() <= 1e-9);
1579    if interior.len() < 7 {
1580        interior = (1..8).map(|k| k as f64 / 8.0).collect();
1581    }
1582    // a boundary refined past the 33-point ribbon's own size gains nothing
1583    // from its knots and would make the dense solve below its cost
1584    if interior.len() > 64 {
1585        return sampled(f);
1586    }
1587    let mut knots = vec![0.0; 4];
1588    knots.extend(interior);
1589    knots.extend([1.0; 4]);
1590    let n = knots.len() - 4;
1591    let greville: Vec<f64> = (0..n).map(|i| (knots[i + 1] + knots[i + 2] + knots[i + 3]) / 3.0).collect();
1592    // values at the Greville points but the second and the second-to-last,
1593    // whose rows carry the end derivatives instead
1594    let (start, end) = end_derivatives(&f)?;
1595    let mut matrix: Vec<Vec<f64>> = Vec::with_capacity(n);
1596    let mut rows: Vec<Vec3> = Vec::with_capacity(n);
1597    for (i, t) in greville.iter().enumerate() {
1598        if i == 1 {
1599            let c = 3.0 / (knots[4] - knots[1]);
1600            let mut row = vec![0.0; n];
1601            row[0] = -c;
1602            row[1] = c;
1603            matrix.push(row);
1604            rows.push(start);
1605        } else if i == n - 2 {
1606            let c = 3.0 / (knots[n + 2] - knots[n - 1]);
1607            let mut row = vec![0.0; n];
1608            row[n - 2] = -c;
1609            row[n - 1] = c;
1610            matrix.push(row);
1611            rows.push(end);
1612        } else {
1613            matrix.push(cubic_basis(&knots, *t));
1614            rows.push(f(*t)?);
1615        }
1616    }
1617    let mut axes = Vec::with_capacity(3);
1618    for axis in 0..3 {
1619        let rhs: Vec<f64> = rows.iter().map(|v| [v.x, v.y, v.z][axis]).collect();
1620        axes.push(crate::solve_dense(matrix.clone(), rhs).map_err(geometry)?);
1621    }
1622    let poles: Vec<Vec4> = (0..n).map(|i| Vec4::from_point(Vec3::new(axes[0][i], axes[1][i], axes[2][i]), 1.0)).collect();
1623    let curve = NurbsCurve::new(3, knots.clone(), poles).map_err(geometry)?;
1624    let values: Vec<Vec3> = greville.iter().map(|t| f(*t)).collect::<Result<_, _>>()?;
1625    // read against `f` at 513 even points and the quarter points of its
1626    // spans, and against what the 33-point ribbon misses there
1627    let size = values.iter().map(|v| v.length()).fold(0.0_f64, f64::max).max(f64::MIN_POSITIVE);
1628    let mut points: Vec<f64> = (0..=512).map(|i| i as f64 / 512.0).collect();
1629    for span in 3..n {
1630        let (a, b) = (knots[span], knots[span + 1]);
1631        if b > a {
1632            points.extend([0.25, 0.5, 0.75].map(|fraction| a + (b - a) * fraction));
1633        }
1634    }
1635    let worst = |candidate: &NurbsCurve| -> Result<f64, NSidedRefusal> {
1636        let mut worst = 0.0_f64;
1637        for t in &points {
1638            worst = worst.max(candidate.evaluate(*t).map_err(geometry)?.sub(f(*t)?).length());
1639        }
1640        Ok(worst)
1641    };
1642    let thinned = worst(&curve)?;
1643    if thinned <= 1e-9 * size {
1644        return Ok(curve);
1645    }
1646    let dense = sampled(&f)?;
1647    if thinned <= 1.5 * worst(&dense)? {
1648        Ok(curve)
1649    } else {
1650        Ok(dense)
1651    }
1652}
1653
1654/// The interior knots of `curve` (over [0, 1]), mirrored (`1 − t`) when the
1655/// ribbon runs the other way along it.
1656fn interior_knots(curve: &NurbsCurve, mirrored: bool) -> Vec<f64> {
1657    let p = curve.degree;
1658    let knots = &curve.knots[p + 1..curve.knots.len() - p - 1];
1659    knots.iter().map(|knot| if mirrored { 1.0 - knot } else { *knot }).collect()
1660}
1661
1662/// `BREP_N_SIDED_SLIVER_KNOTS` (on by default; `=0` keeps every knot): see
1663/// `without_sliver_knots`.
1664pub fn sliver_knots_on() -> bool {
1665    crate::switch!(live "BREP_N_SIDED_SLIVER_KNOTS", true)
1666}
1667
1668/// How near (in a side's [0, 1]) two knots by its midpoint leave a sliver
1669/// span between them, and how far (relative to a side's size, or to a
1670/// field's smallest pole) the curve may move when one of them is removed.
1671const SLIVER_KNOT_WINDOW: f64 = 1e-6;
1672const SLIVER_KNOT_TOLERANCE: f64 = 1e-12;
1673
1674/// `curve` (on [0, 1]) with as few simple interior knots within
1675/// SLIVER_KNOT_WINDOW of 0.5 as it can keep unchanged: each such knot is
1676/// removed where that moves the curve by at most `tolerance` (Piegl and
1677/// Tiller's single knot removal, A5.8, on the homogeneous poles), while at
1678/// least one stays; a knot that would move it more stays.
1679fn without_sliver_knots(curve: &NurbsCurve, tolerance: f64) -> NurbsCurve {
1680    let mut current = curve.clone();
1681    let mut kept: Vec<f64> = Vec::new();
1682    loop {
1683        let knots = &current.knots;
1684        // farthest from the midpoint first: the knot a fitted side carries
1685        // by its midpoint stays where another can go
1686        let mut band: Vec<usize> = (current.degree + 1..knots.len() - current.degree - 1)
1687            .filter(|&r| (knots[r] - 0.5).abs() <= SLIVER_KNOT_WINDOW && knots.iter().filter(|other| **other == knots[r]).count() == 1)
1688            .collect();
1689        band.sort_by(|&a, &b| (knots[b] - 0.5).abs().total_cmp(&(knots[a] - 0.5).abs()));
1690        if band.len() < 2 {
1691            return current;
1692        }
1693        let Some(&r) = band.iter().find(|&&r| !kept.contains(&knots[r])) else { return current };
1694        match remove_simple_knot(&current, r, tolerance) {
1695            Some(removed) => current = removed,
1696            None => kept.push(current.knots[r]),
1697        }
1698    }
1699}
1700
1701/// `curve` without its simple knot `knots[r]`, if that moves it by at most
1702/// `tolerance` (A5.8 with one removal; the check is on the homogeneous poles).
1703fn remove_simple_knot(curve: &NurbsCurve, r: usize, tolerance: f64) -> Option<NurbsCurve> {
1704    let p = curve.degree;
1705    let knots = &curve.knots;
1706    let poles = &curve.control_points;
1707    let u = knots[r];
1708    let (first, last) = (r - p, r - 1);
1709    let off = first - 1;
1710    let lerp = |a: Vec4, b: Vec4, ta: f64, tb: f64| Vec4 { x: a.x * ta + b.x * tb, y: a.y * ta + b.y * tb, z: a.z * ta + b.z * tb, w: a.w * ta + b.w * tb };
1711    let mut temp = vec![Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 }; 2 * p + 1];
1712    temp[0] = poles[off];
1713    temp[last + 1 - off] = poles[last + 1];
1714    let (mut i, mut j) = (first, last);
1715    let (mut ii, mut jj) = (1usize, last - off);
1716    while j > i {
1717        let alfi = (u - knots[i]) / (knots[i + p + 1] - knots[i]);
1718        let alfj = (u - knots[j]) / (knots[j + p + 1] - knots[j]);
1719        if !(alfi.abs() > 0.0) || !((1.0 - alfj).abs() > 0.0) {
1720            return None;
1721        }
1722        temp[ii] = lerp(poles[i], temp[ii - 1], 1.0 / alfi, -(1.0 - alfi) / alfi);
1723        temp[jj] = lerp(poles[j], temp[jj + 1], 1.0 / (1.0 - alfj), -alfj / (1.0 - alfj));
1724        i += 1;
1725        ii += 1;
1726        j -= 1;
1727        jj -= 1;
1728    }
1729    let distance = |a: Vec4, b: Vec4| ((a.x - b.x).powi(2) + (a.y - b.y).powi(2) + (a.z - b.z).powi(2) + (a.w - b.w).powi(2)).sqrt();
1730    let off_by = if j < i {
1731        distance(temp[ii - 1], temp[jj + 1])
1732    } else {
1733        let alfi = (u - knots[i]) / (knots[i + p + 1] - knots[i]);
1734        distance(poles[i], lerp(temp[ii + 1], temp[ii - 1], alfi, 1.0 - alfi))
1735    };
1736    if !(off_by <= tolerance) {
1737        return None;
1738    }
1739    let mut new_poles = poles.clone();
1740    let (mut i, mut j) = (first, last);
1741    while j > i {
1742        new_poles[i] = temp[i - off];
1743        new_poles[j] = temp[j - off];
1744        i += 1;
1745        j -= 1;
1746    }
1747    let fout = (2 * r - 1 - p) / 2;
1748    new_poles.remove(fout);
1749    let mut new_knots = knots.clone();
1750    new_knots.remove(r);
1751    NurbsCurve::new(p, new_knots, new_poles).ok()
1752}
1753
1754/// `curve` over [0, 1] with its knot `knot` carried onto 0.5: the knot
1755/// raised to full multiplicity (exact), then [0, knot] mapped onto [0, ½]
1756/// and [knot, 1] onto [½, 1]. The same points in the same order; only the
1757/// speeds of the two halves change, by `knot / ½` and `(1 − knot) / ½`.
1758fn knot_onto_midpoint(curve: &NurbsCurve, knot: f64) -> Result<NurbsCurve, NSidedRefusal> {
1759    let present = curve.knots.iter().filter(|value| **value == knot).count();
1760    let full = if present < curve.degree { curve.insert_knot(knot, curve.degree - present).map_err(geometry)? } else { curve.clone() };
1761    let knots: Vec<f64> = full
1762        .knots
1763        .iter()
1764        .map(|value| if *value <= knot { value * 0.5 / knot } else { 0.5 + (value - knot) * 0.5 / (1.0 - knot) })
1765        .collect();
1766    NurbsCurve::new(full.degree, knots, full.control_points.clone()).map_err(geometry)
1767}
1768
1769/// The cubic interpolant over [0, 1] of the vector field `f`, sampled at 33
1770/// even parameters, with its end derivatives made `f`'s own (read by
1771/// third-order one-sided differences): exact for a field of degree three or
1772/// less. A ribbon's end derivative is a corner twist of the patch it is
1773/// handed to; the interpolant's own missed it by its interpolation error,
1774/// which on a fast-turning field (a fillet star whose rounds meet at radii
1775/// 0.9 against 3) left the two patches beside a spoke's midpoint end with
1776/// twists 7e-4 apart and their normals 3.2e-4 rad apart across the spoke.
1777fn sampled(f: impl Fn(f64) -> Result<Vec3, NSidedRefusal>) -> Result<NurbsCurve, NSidedRefusal> {
1778    const SAMPLES: usize = 33;
1779    let parameters: Vec<f64> = (0..SAMPLES).map(|index| index as f64 / (SAMPLES - 1) as f64).collect();
1780    let values: Vec<Vec3> = parameters.iter().map(|t| f(*t)).collect::<Result<_, _>>()?;
1781    let curve = interpolate_curve(&values, 3, &parameters).map_err(geometry)?;
1782    with_end_derivatives(curve, &f)
1783}
1784
1785/// `f`'s derivatives at 0 and 1 by third-order one-sided differences, exact
1786/// for a cubic field.
1787fn end_derivatives(f: &impl Fn(f64) -> Result<Vec3, NSidedRefusal>) -> Result<(Vec3, Vec3), NSidedRefusal> {
1788    const STEP: f64 = 1e-4;
1789    let (first_value, last_value) = (f(0.0)?, f(1.0)?);
1790    let start = f(STEP)?
1791        .scale(18.0)
1792        .sub(f(2.0 * STEP)?.scale(9.0))
1793        .add(f(3.0 * STEP)?.scale(2.0))
1794        .sub(first_value.scale(11.0))
1795        .scale(1.0 / (6.0 * STEP));
1796    let end = last_value
1797        .scale(11.0)
1798        .sub(f(1.0 - STEP)?.scale(18.0))
1799        .add(f(1.0 - 2.0 * STEP)?.scale(9.0))
1800        .sub(f(1.0 - 3.0 * STEP)?.scale(2.0))
1801        .scale(1.0 / (6.0 * STEP));
1802    Ok((start, end))
1803}
1804
1805/// `curve` (a clamped cubic over [0, 1] interpolating `f`) with its end
1806/// derivatives made `f`'s own, read by third-order one-sided differences
1807/// (exact for a cubic field, whose interpolant they then leave as it is):
1808/// the second and second-to-last poles moved along them.
1809fn with_end_derivatives(curve: NurbsCurve, f: &impl Fn(f64) -> Result<Vec3, NSidedRefusal>) -> Result<NurbsCurve, NSidedRefusal> {
1810    let (start, end) = end_derivatives(f)?;
1811    // a clamped cubic leaves P0 along 3 (P1 - P0) / (u4 - u1) and reaches
1812    // P(n-1) along 3 (P(n-1) - P(n-2)) / (u(n+2) - u(n-1))
1813    let (degree, knots) = (curve.degree, curve.knots.clone());
1814    let mut poles = curve.control_points.clone();
1815    let n = poles.len();
1816    if degree != 3 || n < 4 || poles.iter().any(|pole| (pole.w - 1.0).abs() > POLYNOMIAL_BAND) {
1817        return Ok(curve);
1818    }
1819    let point = |pole: &Vec4| Vec3::new(pole.x, pole.y, pole.z);
1820    let first = point(&poles[0]).add(start.scale((knots[4] - knots[1]) / 3.0));
1821    let last = point(&poles[n - 1]).sub(end.scale((knots[n + 2] - knots[n - 1]) / 3.0));
1822    poles[1] = Vec4::from_point(first, 1.0);
1823    poles[n - 2] = Vec4::from_point(last, 1.0);
1824    NurbsCurve::new(degree, knots, poles).map_err(geometry)
1825}
1826
1827/// The least-squares `(λ, μ)` with `λ p + μ q` nearest `target`.
1828fn in_plane(target: Vec3, p: Vec3, q: Vec3) -> Result<(f64, f64), NSidedRefusal> {
1829    let (pp, pq, qq) = (p.dot(p), p.dot(q), q.dot(q));
1830    let (tp, tq) = (target.dot(p), target.dot(q));
1831    let determinant = pp * qq - pq * pq;
1832    if !(determinant > 1e-24 * pp * qq) || !(determinant.is_finite()) {
1833        return Err(NSidedRefusal::Centre { detail: "two directions that should span a plane are parallel".into() });
1834    }
1835    Ok(((tp * qq - tq * pq) / determinant, (tq * pp - tp * pq) / determinant))
1836}
1837
1838/// The unit normal `∂S/∂u × ∂S/∂v`, `None` where it vanishes.
1839fn unit_normal(surface: &NurbsSurface, u: f64, v: f64) -> Result<Option<Vec3>, NSidedRefusal> {
1840    let (_, su, sv) = surface.deriv1(u, v).map_err(geometry)?;
1841    let normal = su.cross(sv);
1842    if !(normal.length() > 1e-12 * su.length() * sv.length()) {
1843        return Ok(None);
1844    }
1845    Ok(normal.normalized().ok())
1846}
1847
1848/// The angle between two unit vectors, `atan2(|a × b|, a · b)`.
1849fn angle(a: Vec3, b: Vec3) -> f64 {
1850    a.cross(b).length().atan2(a.dot(b))
1851}
1852
1853/// The angle between two lines (unit vectors, sign ignored).
1854fn line_angle(a: Vec3, b: Vec3) -> f64 {
1855    a.cross(b).length().atan2(a.dot(b).abs())
1856}
1857