Skip to main content

brep_blend/blending/
law.rs

1//! Composable radius laws over a chain's cumulative arc-length abscissa for
2//! our variable-radius fillet lane — the OCCT `Law_Composite` /
3//! `Law_Constant` / `Law_S` / `Law_Interpol` model, in which the marcher
4//! evaluates `ray = Law(t)` at each station so that ONE chain carries
5//! per-edge/per-vertex radii and mixed constant/variable segments joined by
6//! smooth transitions.
7//!
8//! A [`RadiusLaw`] is built from user segments (constant, linear, interpolated
9//! point sets) laid end to end on the abscissa.  Wherever two adjacent
10//! segments meet with a value or slope mismatch, the builder inserts a smooth
11//! S-transition: a quintic Hermite bridge that matches the neighbouring
12//! segments' value and first derivative at the window boundaries and carries
13//! ZERO second derivative there.  Constant and linear segments also have zero
14//! second derivative, so the composite is C2 at every constructed joint (the
15//! C1 contract with headroom); interpolated segments are C1 monotone
16//! (Fritsch–Carlson PCHIP), so joints against them are C1.
17//!
18//! Transition-window sizing is derived from the adjoining segment GEOMETRY,
19//! not a tolerance: each junction claims exactly HALF of each adjoining
20//! segment.  Half is the largest window that can never collide with the
21//! neighbouring junction's window — two windows meeting inside one segment
22//! meet exactly at its midpoint, where both evaluate the underlying segment
23//! itself, so coverage stays contiguous and C1 by construction.
24//!
25//! Endpoint radii are met EXACTLY: no window ever reaches past a segment's
26//! midpoint, so the law's first and last values are the untouched user values.
27//! Evaluation is a binary search plus one Horner evaluation of a degree ≤ 5
28//! polynomial — cheap enough to call per march station.
29
30use crate::{KernelRefusal, KernelStage};
31
32/// One user segment of a composite radius law, spanning `length` of abscissa.
33#[derive(Clone, Debug)]
34pub enum LawSegment {
35    /// Constant radius over `length` (OCCT `Law_Constant`).
36    Constant { length: f64, radius: f64 },
37    /// Linear ramp from `start_radius` to `end_radius` over `length`
38    /// (OCCT `Law_Linear`).
39    Linear {
40        length: f64,
41        start_radius: f64,
42        end_radius: f64,
43    },
44    /// Monotone C1 interpolation through `(abscissa_offset, radius)` points
45    /// (OCCT `Law_Interpol`).  Offsets are measured from the segment start;
46    /// the first must be exactly `0.0`, offsets strictly increase, and the
47    /// last offset is the segment length.  Interpolation is shape-preserving
48    /// (Fritsch–Carlson PCHIP): the law never overshoots the point radii, so
49    /// positive inputs stay positive.
50    Interpolated { points: Vec<(f64, f64)> },
51}
52
53/// One polynomial piece of the composite: `radius(s)` for `s ∈ [s0, s1]`,
54/// evaluated as a degree ≤ 5 polynomial in the normalized `u = (s−s0)/(s1−s0)`.
55#[derive(Clone, Debug)]
56struct Piece {
57    s0: f64,
58    s1: f64,
59    /// Power-basis coefficients `c0 + c1·u + … + c5·u⁵`.
60    coeffs: [f64; 6],
61}
62
63impl Piece {
64    fn width(&self) -> f64 {
65        self.s1 - self.s0
66    }
67
68    fn evaluate(&self, s: f64) -> f64 {
69        let u = ((s - self.s0) / self.width()).clamp(0.0, 1.0);
70        poly_eval(&self.coeffs, u)
71    }
72}
73
74/// A composable radius law over cumulative abscissa `[0, total_length]`.
75///
76/// Construction validates every input (refuse-or-exact: non-positive radii,
77/// non-positive lengths, and non-monotone interpolation abscissas are named
78/// errors); a constructed law is deterministic and cheap to evaluate.
79#[derive(Clone, Debug)]
80pub struct RadiusLaw {
81    pieces: Vec<Piece>,
82    total: f64,
83}
84
85impl RadiusLaw {
86    /// A constant law: `radius` everywhere on `[0, length]`.
87    pub fn constant(length: f64, radius: f64) -> Result<Self, KernelRefusal> {
88        Self::from_segments(&[LawSegment::Constant { length, radius }])
89    }
90
91    /// The per-vertex chain model: radius `vertex_radii[i]` at chain vertex
92    /// `i`, smoothly interpolated along the chain.  `edge_lengths[k]` is the
93    /// arc length of chain edge `k`, so the abscissa breakpoints sit at the
94    /// chain's edge junctions; `vertex_radii` needs exactly one entry per
95    /// vertex (`edge_lengths.len() + 1`).  Interpolation is monotone C1
96    /// (PCHIP): every vertex radius is met exactly and the law never
97    /// overshoots the given radii.
98    pub fn from_vertex_radii(edge_lengths: &[f64], vertex_radii: &[f64]) -> Result<Self, KernelRefusal> {
99        if edge_lengths.is_empty() {
100            return Err(KernelRefusal::input(
101                KernelStage::Collect,
102                "chain_edges",
103                "radius_law: at least one chain edge length is required",
104            ));
105        }
106        if vertex_radii.len() != edge_lengths.len() + 1 {
107            return Err(KernelRefusal::input(
108                KernelStage::Collect,
109                "vertex_radii_count",
110                format!(
111                    "radius_law: need exactly one radius per chain vertex (edges + 1): \
112                     {} edges need {} radii, got {}",
113                    edge_lengths.len(),
114                    edge_lengths.len() + 1,
115                    vertex_radii.len()
116                ),
117            ));
118        }
119        for length in edge_lengths {
120            if !(length.is_finite() && *length > 0.0) {
121                return Err(segment_length_refusal());
122            }
123        }
124        let mut points = Vec::with_capacity(vertex_radii.len());
125        let mut abscissa = 0.0;
126        points.push((0.0, vertex_radii[0]));
127        for (length, radius) in edge_lengths.iter().zip(vertex_radii[1..].iter()) {
128            abscissa += length;
129            points.push((abscissa, *radius));
130        }
131        Self::from_segments(&[LawSegment::Interpolated { points }])
132    }
133
134    /// Compose a law from consecutive segments with smooth junction
135    /// transitions (see the module docs for the transition model).
136    pub fn from_segments(segments: &[LawSegment]) -> Result<Self, KernelRefusal> {
137        if segments.is_empty() {
138            return Err(KernelRefusal::input(
139                KernelStage::Collect,
140                "segments",
141                "radius_law: at least one segment is required",
142            ));
143        }
144        // 1. Validate and normalize each segment into an evaluator with an
145        //    absolute abscissa span.
146        let mut evals: Vec<SegmentEval> = Vec::with_capacity(segments.len());
147        let mut cursor = 0.0_f64;
148        for segment in segments {
149            let eval = SegmentEval::build(segment, cursor)?;
150            cursor = eval.s_end();
151            evals.push(eval);
152        }
153        let total = cursor;
154        // A nought radius only at the law's own ends: a round may vanish at an
155        // edge's end, never inside it.
156        for (index, eval) in evals.iter().enumerate() {
157            if let SegmentEval::Linear { r0, r1, .. } = eval {
158                if (*r0 == 0.0 && index != 0) || (*r1 == 0.0 && index + 1 != evals.len()) {
159                    return Err(KernelRefusal::input(
160                        KernelStage::Collect,
161                        "radius",
162                        "radius_law: a radius may be nought only at the law's start or end",
163                    ));
164                }
165            }
166        }
167
168        // 2. Decide which junctions need a smooth transition: exact value AND
169        //    slope agreement passes through untouched (already C1); any
170        //    mismatch gets the quintic bridge.
171        let mut needs_transition = vec![false; evals.len().saturating_sub(1)];
172        for i in 0..needs_transition.len() {
173            let s_j = evals[i].s_end();
174            let (vl, dl) = evals[i].value_slope(s_j);
175            let (vr, dr) = evals[i + 1].value_slope(s_j);
176            needs_transition[i] = vl != vr || dl != dr;
177        }
178
179        // 3. Emit pieces: each segment keeps its span minus the half-segment
180        //    windows claimed by transitions at its junctions; each transition
181        //    spans from the left segment's midpoint boundary to the right
182        //    segment's midpoint boundary (window per side = half the adjoining
183        //    segment — the maximal size that can never overlap the next
184        //    junction's window).
185        let mut pieces: Vec<Piece> = Vec::new();
186        for i in 0..evals.len() {
187            let left_trim = i > 0 && needs_transition[i - 1];
188            let right_trim = i < needs_transition.len() && needs_transition[i];
189            let mid = evals[i].s_start() + evals[i].length() * 0.5;
190            let keep_from = if left_trim { mid } else { evals[i].s_start() };
191            let keep_to = if right_trim { mid } else { evals[i].s_end() };
192            if keep_to > keep_from {
193                evals[i].emit_pieces(keep_from, keep_to, &mut pieces);
194            }
195            if right_trim {
196                let a_s = evals[i].s_start() + evals[i].length() * 0.5;
197                let b_s = evals[i + 1].s_start() + evals[i + 1].length() * 0.5;
198                let (a, da) = evals[i].value_slope(a_s);
199                let (b, db) = evals[i + 1].value_slope(b_s);
200                pieces.push(quintic_bridge(a_s, b_s, a, da, b, db));
201            }
202        }
203        debug_assert!(pieces
204            .windows(2)
205            .all(|pair| (pair[0].s1 - pair[1].s0).abs() == 0.0));
206        Ok(Self { pieces, total })
207    }
208
209    /// `(radius at the start, radius at the end)` when the law is one straight
210    /// ramp over its whole length: every piece of degree at most one, and every
211    /// piece's ends on the chord between the law's own ends. `None` for any
212    /// other law (a bulge between linear pieces included).
213    pub fn linear_ends(&self) -> Option<(f64, f64)> {
214        let (r0, r1) = (self.radius_at(0.0), self.radius_at(self.total));
215        let scale = r0.abs().max(r1.abs());
216        let chord = |s: f64| r0 + (r1 - r0) * (s / self.total);
217        let straight = self.pieces.iter().all(|piece| {
218            piece.coeffs[2..].iter().all(|c| *c == 0.0)
219                && (self.radius_at(piece.s0) - chord(piece.s0)).abs() <= 1e-12 * scale
220                && (self.radius_at(piece.s1) - chord(piece.s1)).abs() <= 1e-12 * scale
221        });
222        (self.total > 0.0 && straight).then_some((r0, r1))
223    }
224
225    /// Total abscissa length of the law's domain.
226    pub fn total_length(&self) -> f64 {
227        self.total
228    }
229
230    /// Evaluate the radius at abscissa `s` (clamped into `[0, total_length]`).
231    pub fn radius_at(&self, s: f64) -> f64 {
232        debug_assert!(s.is_finite(), "radius_law: abscissa must be finite");
233        let s = s.clamp(0.0, self.total);
234        // First piece whose end reaches s.
235        let index = self
236            .pieces
237            .partition_point(|piece| piece.s1 < s)
238            .min(self.pieces.len() - 1);
239        self.pieces[index].evaluate(s)
240    }
241
242    /// Evaluate at normalized abscissa `fraction ∈ [0, 1]` of the domain.
243    pub fn radius_at_fraction(&self, fraction: f64) -> f64 {
244        self.radius_at(fraction * self.total)
245    }
246
247    /// Upper bound of `|d²radius/ds²|` over `[s_a, s_b]`, used by callers to
248    /// derive a sampling density from the law's curvature (piecewise-linear
249    /// interpolation error of a C1, piecewise-C2 function over step `h` is at
250    /// most `h²·max|r''|/8`).  Per piece the bound is exact-family: the second
251    /// derivative of a degree ≤ 5 piece is a cubic, and the maximum absolute
252    /// value of a polynomial is bounded by the maximum absolute Bernstein
253    /// coefficient (convex-hull property).  Pieces partially overlapping the
254    /// query span use their whole-piece bound (conservative).
255    pub fn max_second_derivative(&self, s_a: f64, s_b: f64) -> f64 {
256        let lo = s_a.min(s_b).clamp(0.0, self.total);
257        let hi = s_a.max(s_b).clamp(0.0, self.total);
258        let mut bound = 0.0_f64;
259        for piece in &self.pieces {
260            if piece.s1 < lo || piece.s0 > hi {
261                continue;
262            }
263            // d²/du²: degree ≤ 3 in u.
264            let c = &piece.coeffs;
265            let dd = [2.0 * c[2], 6.0 * c[3], 12.0 * c[4], 20.0 * c[5]];
266            // Power → Bernstein (degree 3): b_j = Σ_{k≤j} a_k·C(j,k)/C(3,k).
267            let b0 = dd[0];
268            let b1 = dd[0] + dd[1] / 3.0;
269            let b2 = dd[0] + 2.0 * dd[1] / 3.0 + dd[2] / 3.0;
270            let b3 = dd[0] + dd[1] + dd[2] + dd[3];
271            let max_u = b0.abs().max(b1.abs()).max(b2.abs()).max(b3.abs());
272            let width = piece.width();
273            if width > 0.0 {
274                bound = bound.max(max_u / (width * width));
275            }
276        }
277        bound
278    }
279}
280
281/// Validated per-segment evaluator on an absolute abscissa span.
282enum SegmentEval {
283    Constant {
284        s0: f64,
285        length: f64,
286        radius: f64,
287    },
288    Linear {
289        s0: f64,
290        length: f64,
291        r0: f64,
292        r1: f64,
293    },
294    Interpolated {
295        s0: f64,
296        /// Absolute abscissas of the interpolation points.
297        xs: Vec<f64>,
298        ys: Vec<f64>,
299        /// PCHIP slopes at the points (radius per abscissa).
300        ds: Vec<f64>,
301    },
302}
303
304fn check_radius(radius: f64) -> Result<(), KernelRefusal> {
305    if !(radius.is_finite() && radius > 0.0) {
306        return Err(KernelRefusal::input(
307            KernelStage::Collect,
308            "radius",
309            "radius_law: every radius must be positive and finite",
310        ));
311    }
312    Ok(())
313}
314
315/// The one refusal every segment kind shares: a span that is not a positive
316/// finite length.  Minted once so the three sites carry one class and slug.
317fn segment_length_refusal() -> KernelRefusal {
318    KernelRefusal::input(
319        KernelStage::Collect,
320        "segment_length",
321        "radius_law: segment length must be positive and finite",
322    )
323}
324
325impl SegmentEval {
326    fn build(segment: &LawSegment, s0: f64) -> Result<Self, KernelRefusal> {
327        match segment {
328            LawSegment::Constant { length, radius } => {
329                if !(length.is_finite() && *length > 0.0) {
330                    return Err(segment_length_refusal());
331                }
332                check_radius(*radius)?;
333                Ok(Self::Constant {
334                    s0,
335                    length: *length,
336                    radius: *radius,
337                })
338            }
339            LawSegment::Linear {
340                length,
341                start_radius,
342                end_radius,
343            } => {
344                if !(length.is_finite() && *length > 0.0) {
345                    return Err(segment_length_refusal());
346                }
347                // One end may be nought (a round that vanishes there); the
348                // law as a whole must still start or end there (below).
349                if *start_radius == 0.0 || *end_radius == 0.0 {
350                    check_radius(start_radius.max(*end_radius))?;
351                } else {
352                    check_radius(*start_radius)?;
353                    check_radius(*end_radius)?;
354                }
355                Ok(Self::Linear {
356                    s0,
357                    length: *length,
358                    r0: *start_radius,
359                    r1: *end_radius,
360                })
361            }
362            LawSegment::Interpolated { points } => {
363                if points.len() < 2 {
364                    return Err(KernelRefusal::input(
365                        KernelStage::Collect,
366                        "interpolation_points",
367                        "radius_law: an interpolated segment needs at least two points",
368                    ));
369                }
370                if points[0].0 != 0.0 {
371                    return Err(KernelRefusal::input(
372                        KernelStage::Collect,
373                        "interpolation_start",
374                        "radius_law: interpolation abscissas must start at exactly 0",
375                    ));
376                }
377                for pair in points.windows(2) {
378                    if !(pair[1].0.is_finite() && pair[1].0 > pair[0].0) {
379                        return Err(KernelRefusal::input(
380                            KernelStage::Collect,
381                            "interpolation_monotone",
382                            "radius_law: interpolation abscissas must be strictly increasing",
383                        ));
384                    }
385                }
386                for (_, radius) in points {
387                    check_radius(*radius)?;
388                }
389                let xs: Vec<f64> = points.iter().map(|(x, _)| s0 + x).collect();
390                let ys: Vec<f64> = points.iter().map(|(_, y)| *y).collect();
391                let ds = pchip_slopes(&xs, &ys);
392                Ok(Self::Interpolated { s0, xs, ys, ds })
393            }
394        }
395    }
396
397    fn s_start(&self) -> f64 {
398        match self {
399            Self::Constant { s0, .. } | Self::Linear { s0, .. } | Self::Interpolated { s0, .. } => {
400                *s0
401            }
402        }
403    }
404
405    fn length(&self) -> f64 {
406        match self {
407            Self::Constant { length, .. } | Self::Linear { length, .. } => *length,
408            Self::Interpolated { s0, xs, .. } => xs[xs.len() - 1] - s0,
409        }
410    }
411
412    fn s_end(&self) -> f64 {
413        match self {
414            Self::Constant { s0, length, .. } | Self::Linear { s0, length, .. } => s0 + length,
415            Self::Interpolated { xs, .. } => xs[xs.len() - 1],
416        }
417    }
418
419    /// Value and first derivative (radius per abscissa) of the ORIGINAL
420    /// segment at `s` — junction windows take their boundary conditions from
421    /// here, so consecutive windows meeting at a segment midpoint agree
422    /// exactly.
423    fn value_slope(&self, s: f64) -> (f64, f64) {
424        match self {
425            Self::Constant { radius, .. } => (*radius, 0.0),
426            Self::Linear {
427                s0,
428                length,
429                r0,
430                r1,
431            } => {
432                let slope = (r1 - r0) / length;
433                (r0 + slope * (s - s0), slope)
434            }
435            Self::Interpolated { xs, ys, ds, .. } => {
436                let i = interval_index(xs, s);
437                let h = xs[i + 1] - xs[i];
438                let coeffs = hermite_cubic(ys[i], ds[i] * h, ys[i + 1], ds[i + 1] * h);
439                let u = ((s - xs[i]) / h).clamp(0.0, 1.0);
440                let deriv = poly_eval(&poly_derivative(&coeffs), u) / h;
441                (poly_eval(&coeffs, u), deriv)
442            }
443        }
444    }
445
446    /// Append this segment's polynomial pieces restricted to `[from, to]`.
447    fn emit_pieces(&self, from: f64, to: f64, out: &mut Vec<Piece>) {
448        match self {
449            Self::Constant { radius, .. } => out.push(Piece {
450                s0: from,
451                s1: to,
452                coeffs: [*radius, 0.0, 0.0, 0.0, 0.0, 0.0],
453            }),
454            Self::Linear { .. } => {
455                let (va, slope) = self.value_slope(from);
456                out.push(Piece {
457                    s0: from,
458                    s1: to,
459                    coeffs: [va, slope * (to - from), 0.0, 0.0, 0.0, 0.0],
460                });
461            }
462            Self::Interpolated { xs, ys, ds, .. } => {
463                for i in 0..xs.len() - 1 {
464                    let (x0, x1) = (xs[i], xs[i + 1]);
465                    let (a, b) = (x0.max(from), x1.min(to));
466                    if b <= a {
467                        continue;
468                    }
469                    let h = x1 - x0;
470                    let cubic = hermite_cubic(ys[i], ds[i] * h, ys[i + 1], ds[i + 1] * h);
471                    let coeffs = poly_restrict(&cubic, (a - x0) / h, (b - x0) / h);
472                    out.push(Piece {
473                        s0: a,
474                        s1: b,
475                        coeffs,
476                    });
477                }
478            }
479        }
480    }
481}
482
483/// The quintic Hermite S-bridge over `[a_s, b_s]`: matches value and first
484/// derivative of the neighbouring segments at the window boundaries and
485/// carries zero second derivative there (so joints against constant/linear
486/// segments are C2).  With flat sides (`da = db = 0`) it degenerates to the
487/// classic monotone smoothstep `10u³ − 15u⁴ + 6u⁵` scaled between the two
488/// values — the OCCT `Law_S` shape with no overshoot.
489fn quintic_bridge(a_s: f64, b_s: f64, a: f64, da: f64, b: f64, db: f64) -> Piece {
490    let w = b_s - a_s;
491    // End conditions in normalized u: q(0)=a, q'(0)=A1, q''(0)=0,
492    // q(1)=b, q'(1)=B1, q''(1)=0, with slopes scaled by the window width.
493    let a1 = da * w;
494    let b1 = db * w;
495    let d = b - a - a1;
496    let e = b1 - a1;
497    // Solving the three remaining equations for c3..c5 gives:
498    //   c3 = 10D − 4E,  c4 = 7E − 15D,  c5 = 6D − 3E.
499    Piece {
500        s0: a_s,
501        s1: b_s,
502        coeffs: [
503            a,
504            a1,
505            0.0,
506            10.0 * d - 4.0 * e,
507            7.0 * e - 15.0 * d,
508            6.0 * d - 3.0 * e,
509        ],
510    }
511}
512
513/// Horner evaluation of a degree ≤ 5 power-basis polynomial.
514fn poly_eval(coeffs: &[f64; 6], u: f64) -> f64 {
515    let mut value = coeffs[5];
516    for k in (0..5).rev() {
517        value = value * u + coeffs[k];
518    }
519    value
520}
521
522/// Coefficients of the derivative (in `u`) of a degree ≤ 5 polynomial.
523fn poly_derivative(coeffs: &[f64; 6]) -> [f64; 6] {
524    let mut out = [0.0; 6];
525    for k in 1..6 {
526        out[k - 1] = coeffs[k] * k as f64;
527    }
528    out
529}
530
531/// Coefficients of `p(x0 + (x1 − x0)·t)` for `t ∈ [0, 1]` — restricting a
532/// normalized polynomial piece to a sub-interval of its own domain.
533fn poly_restrict(coeffs: &[f64; 6], x0: f64, x1: f64) -> [f64; 6] {
534    let h = x1 - x0;
535    let mut result = [0.0; 6];
536    // power = (x0 + h·t)^k, maintained iteratively.
537    let mut power = [0.0; 6];
538    power[0] = 1.0;
539    for k in 0..6 {
540        for j in 0..6 {
541            result[j] += coeffs[k] * power[j];
542        }
543        if k < 5 {
544            // power ← power · (x0 + h·t)
545            let mut next = [0.0; 6];
546            for j in 0..6 {
547                next[j] += power[j] * x0;
548                if j + 1 < 6 {
549                    next[j + 1] += power[j] * h;
550                }
551            }
552            power = next;
553        }
554    }
555    result
556}
557
558/// Cubic Hermite power coefficients on `u ∈ [0, 1]` from end values and end
559/// derivatives already scaled by the interval width.
560fn hermite_cubic(y0: f64, d0: f64, y1: f64, d1: f64) -> [f64; 6] {
561    let delta = y1 - y0;
562    [
563        y0,
564        d0,
565        3.0 * delta - 2.0 * d0 - d1,
566        -2.0 * delta + d0 + d1,
567        0.0,
568        0.0,
569    ]
570}
571
572/// Index of the interpolation interval containing `s` (clamped to the ends).
573fn interval_index(xs: &[f64], s: f64) -> usize {
574    let mut i = xs.partition_point(|x| *x <= s);
575    i = i.clamp(1, xs.len() - 1);
576    i - 1
577}
578
579/// Shape-preserving (Fritsch–Carlson PCHIP) slopes: C1, monotone on monotone
580/// data, never overshooting the input values.  Deterministic.
581fn pchip_slopes(xs: &[f64], ys: &[f64]) -> Vec<f64> {
582    let n = xs.len();
583    debug_assert!(n >= 2);
584    let m = n - 1;
585    let h: Vec<f64> = (0..m).map(|i| xs[i + 1] - xs[i]).collect();
586    let secant: Vec<f64> = (0..m).map(|i| (ys[i + 1] - ys[i]) / h[i]).collect();
587    let mut d = vec![0.0_f64; n];
588    if n == 2 {
589        d[0] = secant[0];
590        d[1] = secant[0];
591        return d;
592    }
593    // Interior: weighted harmonic mean where the secants agree in sign
594    // (Fritsch–Carlson), zero at local extrema — this is what prevents
595    // overshoot.
596    for i in 1..m {
597        let (s0, s1) = (secant[i - 1], secant[i]);
598        if s0 * s1 > 0.0 {
599            let w1 = 2.0 * h[i] + h[i - 1];
600            let w2 = h[i] + 2.0 * h[i - 1];
601            d[i] = (w1 + w2) / (w1 / s0 + w2 / s1);
602        }
603    }
604    // Ends: the standard shape-preserving three-point estimate, clamped so
605    // the end interval stays monotone.
606    d[0] = end_slope(h[0], h[1], secant[0], secant[1]);
607    d[n - 1] = end_slope(h[m - 1], h[m - 2], secant[m - 1], secant[m - 2]);
608    d
609}
610
611/// One-sided three-point end-slope estimate with the Fritsch–Carlson
612/// monotonicity clamps.
613fn end_slope(h0: f64, h1: f64, s0: f64, s1: f64) -> f64 {
614    let mut d = ((2.0 * h0 + h1) * s0 - h0 * s1) / (h0 + h1);
615    if d * s0 <= 0.0 {
616        d = 0.0;
617    } else if s0 * s1 < 0.0 && d.abs() > 3.0 * s0.abs() {
618        d = 3.0 * s0;
619    }
620    d
621}
622