From 4f1902d2871ac466719ed138a9d2d8be5e59dc40 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:31:06 +0000 Subject: [PATCH] feat(math): add monotone, natural, Catmull-Rom and Bezier splines Fritsch-Carlson monotone cubic Hermite (evaluate, derivative, inverse), natural cubic spline, Catmull-Rom with uniform/centripetal/chordal knots (Barry-Goldman pyramid) and cubic Bezier curves plus CSS-style easing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Math/CatmullRom.cs | 92 +++++++++ src/Titano.Core/Math/CubicBezier.cs | 95 +++++++++ src/Titano.Core/Math/MonotoneSpline.cs | 177 +++++++++++++++++ src/Titano.Core/Math/NaturalCubicSpline.cs | 88 +++++++++ src/Titano.Core/Math/Point2.cs | 19 ++ tests/Titano.Core.Tests/Math/SplineTests.cs | 202 ++++++++++++++++++++ 6 files changed, 673 insertions(+) create mode 100644 src/Titano.Core/Math/CatmullRom.cs create mode 100644 src/Titano.Core/Math/CubicBezier.cs create mode 100644 src/Titano.Core/Math/MonotoneSpline.cs create mode 100644 src/Titano.Core/Math/NaturalCubicSpline.cs create mode 100644 src/Titano.Core/Math/Point2.cs create mode 100644 tests/Titano.Core.Tests/Math/SplineTests.cs diff --git a/src/Titano.Core/Math/CatmullRom.cs b/src/Titano.Core/Math/CatmullRom.cs new file mode 100644 index 00000000..d0d4bd51 --- /dev/null +++ b/src/Titano.Core/Math/CatmullRom.cs @@ -0,0 +1,92 @@ +namespace Titano.Core.Mathematics; + +/// Knot spacing of a Catmull–Rom spline: |Pᵢ₊₁ − Pᵢ|^α with α = 0, ½ or 1. +public enum CatmullRomParameterization +{ + /// α = 0: the classic spline; can cusp or self-intersect on uneven spacing. + Uniform, + + /// α = ½: no cusps or self-intersections within a segment (Yuksel, Schaefer & Keyser 2011). + Centripetal, + + /// α = 1: follows the chord lengths; smoothest on evenly sampled paths. + Chordal, +} + +/// +/// Catmull–Rom interpolating splines evaluated with the Barry–Goldman pyramid, so non-uniform (centripetal, +/// chordal) knots are exact. The parameter t ∈ [0, n − 1] selects segment ⌊t⌋; end segments use reflected +/// phantom points (P₋₁ = 2P₀ − P₁). +/// +public static class CatmullRom +{ + /// Scalar spline through (values treated as 1-D points for the knot spacing). + public static double Evaluate(ReadOnlySpan values, double t, CatmullRomParameterization kind = CatmullRomParameterization.Uniform) + { + if (values.IsEmpty) throw new ArgumentException("No control values.", nameof(values)); + if (values.Length == 1) return values[0]; + var (i, u) = Segment(values.Length, t); + var p1 = values[i]; + var p2 = values[i + 1]; + var p0 = i > 0 ? values[i - 1] : 2 * p1 - p2; + var p3 = i + 2 < values.Length ? values[i + 2] : 2 * p2 - p1; + return Pyramid(new Point2(p0, 0), new Point2(p1, 0), new Point2(p2, 0), new Point2(p3, 0), u, Alpha(kind)).X; + } + + /// Planar spline through . + public static Point2 Evaluate(ReadOnlySpan points, double t, CatmullRomParameterization kind = CatmullRomParameterization.Centripetal) + { + if (points.IsEmpty) throw new ArgumentException("No control points.", nameof(points)); + if (points.Length == 1) return points[0]; + var (i, u) = Segment(points.Length, t); + var p1 = points[i]; + var p2 = points[i + 1]; + var p0 = i > 0 ? points[i - 1] : 2 * p1 - p2; + var p3 = i + 2 < points.Length ? points[i + 2] : 2 * p2 - p1; + return Pyramid(p0, p1, p2, p3, u, Alpha(kind)); + } + + private static double Alpha(CatmullRomParameterization kind) => kind switch + { + CatmullRomParameterization.Uniform => 0, + CatmullRomParameterization.Centripetal => 0.5, + CatmullRomParameterization.Chordal => 1, + _ => throw new ArgumentOutOfRangeException(nameof(kind)), + }; + + private static (int Index, double Local) Segment(int count, double t) + { + if (double.IsNaN(t)) throw new ArgumentOutOfRangeException(nameof(t)); + t = Math.Clamp(t, 0, count - 1); + var i = Math.Min((int)t, count - 2); + return (i, t - i); + } + + /// Barry–Goldman recursive evaluation of the segment P1→P2 at local parameter u ∈ [0, 1]. + private static Point2 Pyramid(Point2 p0, Point2 p1, Point2 p2, Point2 p3, double u, double alpha) + { + if (u <= 0) return p1; + if (u >= 1) return p2; + var d1 = Knot(p0, p1, alpha); + var d2 = Knot(p1, p2, alpha); + var d3 = Knot(p2, p3, alpha); + double t0 = 0, t1 = d1, t2 = t1 + d2, t3 = t2 + d3; + var t = t1 + u * d2; + var a1 = Mix(p0, p1, t0, t1, t); + var a2 = Mix(p1, p2, t1, t2, t); + var a3 = Mix(p2, p3, t2, t3, t); + var b1 = Mix(a1, a2, t0, t2, t); + var b2 = Mix(a2, a3, t1, t3, t); + return Mix(b1, b2, t1, t2, t); + } + + private static Point2 Mix(Point2 a, Point2 b, double ta, double tb, double t) => ((tb - t) * a + (t - ta) * b) * (1 / (tb - ta)); + + /// Knot interval; coincident points fall back to a unit interval so the pyramid stays finite. + private static double Knot(Point2 a, Point2 b, double alpha) + { + if (alpha == 0) return 1; + var d = Math.Pow(Point2.Distance(a, b), alpha); + return d > 1e-12 ? d : 1; + } +} diff --git a/src/Titano.Core/Math/CubicBezier.cs b/src/Titano.Core/Math/CubicBezier.cs new file mode 100644 index 00000000..a210b02f --- /dev/null +++ b/src/Titano.Core/Math/CubicBezier.cs @@ -0,0 +1,95 @@ +namespace Titano.Core.Mathematics; + +/// Planar cubic Bézier curve in Bernstein form; t ∈ [0, 1]. +public readonly record struct CubicBezier(Point2 P0, Point2 P1, Point2 P2, Point2 P3) +{ + public Point2 Evaluate(double t) + { + var s = 1 - t; + return s * s * s * P0 + 3 * s * s * t * P1 + 3 * s * t * t * P2 + t * t * t * P3; + } + + public Point2 Derivative(double t) + { + var s = 1 - t; + return 3 * s * s * (P1 - P0) + 6 * s * t * (P2 - P1) + 3 * t * t * (P3 - P2); + } +} + +/// +/// CSS-style timing function cubic-bezier(x1, y1, x2, y2) with end points (0, 0) and (1, 1). x(t) is +/// monotone because x1, x2 ∈ [0, 1]; it is inverted with Newton's method guarded by bisection. +/// +public readonly record struct CubicBezierEasing +{ + public CubicBezierEasing(double x1, double y1, double x2, double y2) + { + if (!(x1 >= 0 && x1 <= 1)) throw new ArgumentOutOfRangeException(nameof(x1), "x1 must lie in [0, 1]."); + if (!(x2 >= 0 && x2 <= 1)) throw new ArgumentOutOfRangeException(nameof(x2), "x2 must lie in [0, 1]."); + if (!double.IsFinite(y1)) throw new ArgumentOutOfRangeException(nameof(y1)); + if (!double.IsFinite(y2)) throw new ArgumentOutOfRangeException(nameof(y2)); + X1 = x1; + Y1 = y1; + X2 = x2; + Y2 = y2; + } + + public double X1 { get; } + public double Y1 { get; } + public double X2 { get; } + public double Y2 { get; } + + public static CubicBezierEasing Linear { get; } = new(0, 0, 1, 1); + public static CubicBezierEasing Ease { get; } = new(0.25, 0.1, 0.25, 1); + public static CubicBezierEasing EaseIn { get; } = new(0.42, 0, 1, 1); + public static CubicBezierEasing EaseOut { get; } = new(0, 0, 0.58, 1); + public static CubicBezierEasing EaseInOut { get; } = new(0.42, 0, 0.58, 1); + + /// Eased progress for input progress (clamped to [0, 1]). + public double Evaluate(double x) => Component(Y1, Y2, SolveT(x)); + + /// Curve parameter t with x(t) = . + public double SolveT(double x) + { + if (!(x > 0)) return 0; + if (x >= 1) return 1; + var t = x; + for (var i = 0; i < 8; i++) + { + var error = Component(X1, X2, t) - x; + if (Math.Abs(error) < 1e-12) return t; + var slope = ComponentDerivative(X1, X2, t); + if (Math.Abs(slope) < 1e-9) break; + t -= error / slope; + if (t is < 0 or > 1) break; + } + double lo = 0, hi = 1; + t = x; + for (var i = 0; i < 64; i++) + { + var value = Component(X1, X2, t); + if (Math.Abs(value - x) < 1e-12) break; + if (value < x) lo = t; + else hi = t; + t = 0.5 * (lo + hi); + } + return t; + } + + /// One coordinate of the curve with P0 = 0 and P3 = 1: ((a·t + b)·t + c)·t. + private static double Component(double p1, double p2, double t) + { + var c = 3 * p1; + var b = 3 * (p2 - p1) - c; + var a = 1 - c - b; + return ((a * t + b) * t + c) * t; + } + + private static double ComponentDerivative(double p1, double p2, double t) + { + var c = 3 * p1; + var b = 3 * (p2 - p1) - c; + var a = 1 - c - b; + return (3 * a * t + 2 * b) * t + c; + } +} diff --git a/src/Titano.Core/Math/MonotoneSpline.cs b/src/Titano.Core/Math/MonotoneSpline.cs new file mode 100644 index 00000000..718e4918 --- /dev/null +++ b/src/Titano.Core/Math/MonotoneSpline.cs @@ -0,0 +1,177 @@ +namespace Titano.Core.Mathematics; + +/// +/// Monotone piecewise cubic Hermite interpolant (Fritsch & Carlson 1980): three-point tangents limited to the +/// circle α² + β² ≤ 9 so the curve never overshoots monotone data. Outside the knot range the value is clamped +/// to the end values (derivative 0), which keeps time remaps monotone. +/// +public sealed class MonotoneSpline +{ + private readonly double[] _x; + private readonly double[] _y; + private readonly double[] _m; + + /// Strictly increasing, finite knot positions (at least one). + /// Finite knot values. + public MonotoneSpline(ReadOnlySpan x, ReadOnlySpan y) + { + SplineInput.Validate(x, y, minimum: 1); + _x = x.ToArray(); + _y = y.ToArray(); + _m = new double[_x.Length]; + var n = _x.Length; + if (n == 1) return; + + var delta = new double[n - 1]; + var increasing = true; + var decreasing = true; + for (var k = 0; k < n - 1; k++) + { + delta[k] = (_y[k + 1] - _y[k]) / (_x[k + 1] - _x[k]); + increasing &= delta[k] >= 0; + decreasing &= delta[k] <= 0; + } + IsMonotone = increasing || decreasing; + + _m[0] = delta[0]; + _m[n - 1] = delta[n - 2]; + for (var k = 1; k < n - 1; k++) + { + if (delta[k - 1] * delta[k] <= 0) + { + _m[k] = 0; + continue; + } + // Three-point derivative for non-uniform spacing (exact for quadratics). + var h0 = _x[k] - _x[k - 1]; + var h1 = _x[k + 1] - _x[k]; + _m[k] = (h1 * delta[k - 1] + h0 * delta[k]) / (h0 + h1); + } + + for (var k = 0; k < n - 1; k++) + { + if (delta[k] == 0) + { + _m[k] = 0; + _m[k + 1] = 0; + continue; + } + var alpha = _m[k] / delta[k]; + var beta = _m[k + 1] / delta[k]; + if (alpha < 0) _m[k] = alpha = 0; + if (beta < 0) _m[k + 1] = beta = 0; + var s = alpha * alpha + beta * beta; + if (s > 9) + { + var tau = 3 / Math.Sqrt(s); + _m[k] = tau * alpha * delta[k]; + _m[k + 1] = tau * beta * delta[k]; + } + } + } + + public int Count => _x.Length; + + public double MinX => _x[0]; + + public double MaxX => _x[^1]; + + /// True when the knot values are entirely non-decreasing or non-increasing (required by ). + public bool IsMonotone { get; } = true; + + public double Evaluate(double x) + { + if (!(x > _x[0])) return _y[0]; + if (x >= _x[^1]) return _y[^1]; + var k = Interval(x); + var h = _x[k + 1] - _x[k]; + var t = (x - _x[k]) / h; + var t2 = t * t; + var t3 = t2 * t; + // Increment form: rounding scales with the interval's rise, so flat intervals stay exactly flat. + return _y[k] + (_y[k + 1] - _y[k]) * (3 * t2 - 2 * t3) + h * ((t3 - 2 * t2 + t) * _m[k] + (t3 - t2) * _m[k + 1]); + } + + public double Derivative(double x) + { + if (!(x > _x[0]) || x >= _x[^1]) return 0; + var k = Interval(x); + var h = _x[k + 1] - _x[k]; + var t = (x - _x[k]) / h; + var t2 = t * t; + return ((6 * t2 - 6 * t) * _y[k] + + (3 * t2 - 4 * t + 1) * h * _m[k] + + (-6 * t2 + 6 * t) * _y[k + 1] + + (3 * t2 - 2 * t) * h * _m[k + 1]) / h; + } + + /// + /// The x at which the spline reaches (values outside the range clamp to the end knots; + /// on a flat stretch the first x is returned). Safeguarded Newton iteration inside the bracketing interval. + /// + /// The knot values are not monotone. + public double Inverse(double y) + { + if (!IsMonotone) throw new InvalidOperationException("Inverse requires monotone knot values."); + var n = _x.Length; + var sign = _y[^1] >= _y[0] ? 1.0 : -1.0; + var target = sign * y; + if (n == 1 || !(target > sign * _y[0])) return _x[0]; + if (target >= sign * _y[^1]) return FirstAtEnd(); + + int lo = 0, hi = n - 1; + while (hi - lo > 1) + { + var mid = (lo + hi) >> 1; + if (sign * _y[mid] < target) lo = mid; + else hi = mid; + } + if (sign * _y[hi] == target) + { + while (hi > 0 && _y[hi - 1] == _y[hi]) hi--; + return _x[hi]; + } + + double a = _x[lo], b = _x[hi]; + var x = a + (b - a) * (target - sign * _y[lo]) / (sign * (_y[hi] - _y[lo])); + for (var i = 0; i < 100 && b - a > 1e-14 * (1 + Math.Abs(a)); i++) + { + var f = sign * Evaluate(x) - target; + if (f == 0) return x; + if (f < 0) a = x; + else b = x; + var d = sign * Derivative(x); + var next = d > 0 ? x - f / d : double.NaN; + x = next > a && next < b ? next : 0.5 * (a + b); + } + return x; + } + + private double FirstAtEnd() + { + var i = _x.Length - 1; + while (i > 0 && _y[i - 1] == _y[i]) i--; + return _x[i]; + } + + private int Interval(double x) + { + var i = Array.BinarySearch(_x, x); + if (i < 0) i = ~i - 1; + return Math.Clamp(i, 0, _x.Length - 2); + } +} + +internal static class SplineInput +{ + public static void Validate(ReadOnlySpan x, ReadOnlySpan y, int minimum) + { + if (x.Length != y.Length) throw new ArgumentException("x and y lengths differ.", nameof(y)); + if (x.Length < minimum) throw new ArgumentException($"At least {minimum} knot(s) required.", nameof(x)); + for (var i = 0; i < x.Length; i++) + { + if (!double.IsFinite(x[i]) || !double.IsFinite(y[i])) throw new ArgumentException("Knots must be finite.", nameof(x)); + if (i > 0 && !(x[i] > x[i - 1])) throw new ArgumentException("x must be strictly increasing.", nameof(x)); + } + } +} diff --git a/src/Titano.Core/Math/NaturalCubicSpline.cs b/src/Titano.Core/Math/NaturalCubicSpline.cs new file mode 100644 index 00000000..363f572f --- /dev/null +++ b/src/Titano.Core/Math/NaturalCubicSpline.cs @@ -0,0 +1,88 @@ +namespace Titano.Core.Mathematics; + +/// +/// Interpolating cubic spline with natural end conditions (zero second derivative), second derivatives solved +/// with the Thomas tridiagonal algorithm. C² inside the knot range; extrapolates linearly with the end slopes. +/// +public sealed class NaturalCubicSpline +{ + private readonly double[] _x; + private readonly double[] _y; + private readonly double[] _m; + + /// Strictly increasing, finite knot positions (at least one). + /// Finite knot values. + public NaturalCubicSpline(ReadOnlySpan x, ReadOnlySpan y) + { + SplineInput.Validate(x, y, minimum: 1); + _x = x.ToArray(); + _y = y.ToArray(); + var n = _x.Length; + _m = new double[n]; + if (n < 3) return; + + // Interior equations: h[i-1]·M[i-1] + 2(h[i-1]+h[i])·M[i] + h[i]·M[i+1] = 6(δ[i] − δ[i-1]). + var c = new double[n]; + var d = new double[n]; + for (var i = 1; i < n - 1; i++) + { + var h0 = _x[i] - _x[i - 1]; + var h1 = _x[i + 1] - _x[i]; + var rhs = 6 * ((_y[i + 1] - _y[i]) / h1 - (_y[i] - _y[i - 1]) / h0); + var diag = 2 * (h0 + h1) - h0 * c[i - 1]; + c[i] = h1 / diag; + d[i] = (rhs - h0 * d[i - 1]) / diag; + } + for (var i = n - 2; i >= 1; i--) _m[i] = d[i] - c[i] * _m[i + 1]; + } + + public int Count => _x.Length; + + public double Evaluate(double x) + { + var n = _x.Length; + if (n == 1) return _y[0]; + if (x < _x[0]) return _y[0] + Slope(0, atEnd: false) * (x - _x[0]); + if (x > _x[^1]) return _y[^1] + Slope(n - 2, atEnd: true) * (x - _x[^1]); + var k = Interval(x); + var h = _x[k + 1] - _x[k]; + var a = (_x[k + 1] - x) / h; + var b = 1 - a; + return a * _y[k] + b * _y[k + 1] + ((a * a * a - a) * _m[k] + (b * b * b - b) * _m[k + 1]) * h * h / 6; + } + + public double Derivative(double x) + { + var n = _x.Length; + if (n == 1) return 0; + if (x < _x[0]) return Slope(0, atEnd: false); + if (x > _x[^1]) return Slope(n - 2, atEnd: true); + var k = Interval(x); + var h = _x[k + 1] - _x[k]; + var a = (_x[k + 1] - x) / h; + var b = 1 - a; + return (_y[k + 1] - _y[k]) / h - (3 * a * a - 1) / 6 * h * _m[k] + (3 * b * b - 1) / 6 * h * _m[k + 1]; + } + + public double SecondDerivative(double x) + { + if (_x.Length == 1 || x <= _x[0] || x >= _x[^1]) return 0; + var k = Interval(x); + var a = (_x[k + 1] - x) / (_x[k + 1] - _x[k]); + return a * _m[k] + (1 - a) * _m[k + 1]; + } + + private double Slope(int k, bool atEnd) + { + var h = _x[k + 1] - _x[k]; + var secant = (_y[k + 1] - _y[k]) / h; + return atEnd ? secant + h * (_m[k] + 2 * _m[k + 1]) / 6 : secant - h * (2 * _m[k] + _m[k + 1]) / 6; + } + + private int Interval(double x) + { + var i = Array.BinarySearch(_x, x); + if (i < 0) i = ~i - 1; + return Math.Clamp(i, 0, _x.Length - 2); + } +} diff --git a/src/Titano.Core/Math/Point2.cs b/src/Titano.Core/Math/Point2.cs new file mode 100644 index 00000000..848095ae --- /dev/null +++ b/src/Titano.Core/Math/Point2.cs @@ -0,0 +1,19 @@ +namespace Titano.Core.Mathematics; + +/// A point or vector in the plane, double precision. +public readonly record struct Point2(double X, double Y) +{ + public static Point2 operator +(Point2 a, Point2 b) => new(a.X + b.X, a.Y + b.Y); + + public static Point2 operator -(Point2 a, Point2 b) => new(a.X - b.X, a.Y - b.Y); + + public static Point2 operator *(Point2 a, double s) => new(a.X * s, a.Y * s); + + public static Point2 operator *(double s, Point2 a) => new(a.X * s, a.Y * s); + + public double Length => Math.Sqrt(X * X + Y * Y); + + public static double Distance(Point2 a, Point2 b) => (a - b).Length; + + public static Point2 Lerp(Point2 a, Point2 b, double t) => new(a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t); +} diff --git a/tests/Titano.Core.Tests/Math/SplineTests.cs b/tests/Titano.Core.Tests/Math/SplineTests.cs new file mode 100644 index 00000000..669ae785 --- /dev/null +++ b/tests/Titano.Core.Tests/Math/SplineTests.cs @@ -0,0 +1,202 @@ +using Titano.Core.Mathematics; +using Titano.Testing; + +namespace Titano.Core.Tests.Mathematics; + +public sealed class SplineTests +{ + // Monotone data with a plateau and a sharp rise: the classic overshoot trap for C² splines. + private static readonly double[] StepX = [0, 1, 2, 3, 4, 5, 6]; + private static readonly double[] StepY = [0, 0, 0, 1, 1, 1, 1]; + + [Test] + public void MonotoneSplineInterpolatesKnots() + { + var spline = new MonotoneSpline(StepX, StepY); + for (var i = 0; i < StepX.Length; i++) Assert.Equal(StepY[i], spline.Evaluate(StepX[i])); + Assert.Equal(0.0, spline.Evaluate(-5)); + Assert.Equal(1.0, spline.Evaluate(50)); + } + + [Test] + public void MonotoneSplineNeverOvershootsWhileNaturalSplineDoes() + { + var monotone = new MonotoneSpline(StepX, StepY); + var natural = new NaturalCubicSpline(StepX, StepY); + var samples = Enumerable.Range(0, 601).Select(i => monotone.Evaluate(i / 100.0)).ToList(); + Assert.Monotonic(samples); + Assert.InRange(samples.Min(), 0, 0); + Assert.InRange(samples.Max(), 1, 1); + var naturalMax = Enumerable.Range(0, 601).Max(i => natural.Evaluate(i / 100.0)); + Assert.Greater(naturalMax, 1.01); + } + + [Test] + public void MonotoneSplineOnRandomMonotoneDataIsMonotoneAndBounded() + { + var random = new Random(5); + for (var trial = 0; trial < 50; trial++) + { + var n = 2 + random.Next(20); + var x = new double[n]; + var y = new double[n]; + for (var i = 1; i < n; i++) + { + x[i] = x[i - 1] + 0.01 + random.NextDouble() * 3; + y[i] = y[i - 1] + (random.NextDouble() < 0.3 ? 0 : random.NextDouble() * random.NextDouble() * 10); + } + var spline = new MonotoneSpline(x, y); + Assert.True(spline.IsMonotone); + var values = Enumerable.Range(0, 400).Select(i => spline.Evaluate(x[^1] * i / 399.0)).ToList(); + Assert.True(values.All(double.IsFinite)); + Assert.Monotonic(values, message: $"trial {trial}"); + for (var k = 0; k < n - 1; k++) + { + var mid = spline.Evaluate(0.5 * (x[k] + x[k + 1])); + Assert.InRange(mid, y[k], y[k + 1], $"interval {k} of trial {trial}"); + } + } + } + + [Test] + public void MonotoneSplineDerivativeMatchesFiniteDifference() + { + double[] x = [0, 0.5, 2, 3, 5]; + double[] y = [1, 1.5, 2.2, 4, 4.5]; + var spline = new MonotoneSpline(x, y); + foreach (var at in new[] { 0.2, 0.9, 2.5, 4.1 }) + { + const double h = 1e-6; + var numeric = (spline.Evaluate(at + h) - spline.Evaluate(at - h)) / (2 * h); + Assert.Approximately(numeric, spline.Derivative(at), 1e-6); + } + } + + [Test] + public void MonotoneSplineInverseRoundTrips() + { + double[] x = [0, 1, 2.5, 4, 6]; + double[] y = [10, 8, 8, 3, -1]; + var spline = new MonotoneSpline(x, y); + for (var i = 0; i <= 120; i++) + { + var at = i * 0.05; + var value = spline.Evaluate(at); + var back = spline.Inverse(value); + Assert.Approximately(value, spline.Evaluate(back), 1e-10); + } + Assert.Equal(1.0, spline.Inverse(8)); + Assert.Equal(0.0, spline.Inverse(99)); + Assert.Equal(6.0, spline.Inverse(-99)); + Assert.Throws(() => new MonotoneSpline([0, 1, 2], [0, 1, 0]).Inverse(0.5)); + } + + [Test] + public void SplinesRejectInvalidKnots() + { + Assert.Throws(() => new MonotoneSpline([0, 0], [1, 2])); + Assert.Throws(() => new NaturalCubicSpline([0, 1], [1, double.NaN])); + Assert.Throws(() => new MonotoneSpline([], [])); + } + + [Test] + public void NaturalSplineReproducesLinesAndHasFreeEnds() + { + double[] x = [0, 1, 3, 4, 7]; + var line = new NaturalCubicSpline(x, x.Select(v => 2 - 0.5 * v).ToArray()); + foreach (var at in new[] { -2.0, 0.3, 2.2, 6.9, 9 }) Assert.Approximately(2 - 0.5 * at, line.Evaluate(at), 1e-12); + + var sine = new NaturalCubicSpline(Enumerable.Range(0, 21).Select(i => i * Math.PI / 10).ToArray(), + Enumerable.Range(0, 21).Select(i => Math.Sin(i * Math.PI / 10)).ToArray()); + Assert.Approximately(0, sine.SecondDerivative(1e-9), 1e-6); + for (var i = 0; i < 100; i++) + { + var at = 0.3 + i * 0.055; + Assert.Approximately(Math.Sin(at), sine.Evaluate(at), 2e-4); + Assert.Approximately(Math.Cos(at), sine.Derivative(at), 5e-3); + } + } + + [Test] + public void CatmullRomPassesThroughControlPoints() + { + Point2[] points = [new(0, 0), new(1, 2), new(3, 3), new(4, 1), new(6, 0)]; + foreach (var kind in Enum.GetValues()) + { + for (var i = 0; i < points.Length; i++) + { + var p = CatmullRom.Evaluate(points, i, kind); + Assert.Within(points[i].X, points[i].Y, p.X, p.Y, 1e-12); + } + } + } + + [Test] + public void UniformScalarCatmullRomMatchesClosedForm() + { + double[] v = [1, 4, 2, 5, 3]; + for (var i = 0; i <= 40; i++) + { + var t = 1 + i * 0.025; + var u = t - 1; + double p0 = v[0], p1 = v[1], p2 = v[2], p3 = v[3]; + var expected = 0.5 * (2 * p1 + (-p0 + p2) * u + (2 * p0 - 5 * p1 + 4 * p2 - p3) * u * u + (-p0 + 3 * p1 - 3 * p2 + p3) * u * u * u); + Assert.Approximately(expected, CatmullRom.Evaluate(v, t), 1e-12); + } + } + + [Test] + public void CentripetalCatmullRomDoesNotBacktrackOnUnevenSpacing() + { + // Collinear points with a very short middle segment: the uniform spline overshoots past 10.1 and + // turns back; the centripetal one stays monotone along the line. + Point2[] points = [new(0, 0), new(10, 0), new(10.1, 0), new(20, 0)]; + double MaxX(CatmullRomParameterization kind) => Enumerable.Range(0, 101).Max(i => CatmullRom.Evaluate(points, 1 + i / 100.0, kind).X); + Assert.Greater(MaxX(CatmullRomParameterization.Uniform), 10.15); + var centripetal = Enumerable.Range(0, 101).Select(i => CatmullRom.Evaluate(points, 1 + i / 100.0, CatmullRomParameterization.Centripetal).X).ToList(); + Assert.Monotonic(centripetal); + Assert.LessOrEqual(centripetal.Max(), 10.1 + 1e-12); + } + + [Test] + public void BezierEndpointsAndDerivative() + { + var curve = new CubicBezier(new(0, 0), new(1, 2), new(3, 2), new(4, 0)); + Assert.Equal(new Point2(0, 0), curve.Evaluate(0)); + Assert.Equal(new Point2(4, 0), curve.Evaluate(1)); + var d0 = curve.Derivative(0); + Assert.Within(3, 6, d0.X, d0.Y, 1e-12); + var mid = curve.Evaluate(0.5); + Assert.Within(2, 1.5, mid.X, mid.Y, 1e-12); + } + + [Theory] + [Case("ease", 0.5, 0.802403387585)] + [Case("ease-in", 0.5, 0.315356812573)] + [Case("ease-out", 0.25, 0.378138130825)] + [Case("ease-in-out", 0.5, 0.5)] + [Case("linear", 0.37, 0.37)] + public void CssEasingMatchesReference(string name, double x, double expected) + { + var easing = name switch + { + "ease" => CubicBezierEasing.Ease, + "ease-in" => CubicBezierEasing.EaseIn, + "ease-out" => CubicBezierEasing.EaseOut, + "ease-in-out" => CubicBezierEasing.EaseInOut, + _ => CubicBezierEasing.Linear, + }; + Assert.Approximately(expected, easing.Evaluate(x), 1e-9); + } + + [Test] + public void EasingIsMonotoneAndClamped() + { + var easing = new CubicBezierEasing(0.9, -0.2, 0.1, 1.2); + Assert.Equal(0.0, easing.Evaluate(-1)); + Assert.Equal(1.0, easing.Evaluate(2)); + var ts = Enumerable.Range(0, 201).Select(i => easing.SolveT(i / 200.0)).ToList(); + Assert.Monotonic(ts); + Assert.Throws(() => new CubicBezierEasing(1.5, 0, 0.5, 1)); + } +}