Skip to main content

alpha2_geometry/
spatial.rs

1//! Motion along spatial curves. A position keyframed with tangents travels along the cubic
2//! between keyframes by arc length, at the speed its timing curve sets.
3
4use crate::arclen;
5use kurbo::{CubicBez, PathSeg, Point, Vec2};
6
7/// The point `amount` of the arc length along the cubic from `from` (control `from +
8/// out_tangent`) to `to` (control `to + in_tangent`), in a space scaled to screen proportions.
9///
10/// An `amount` outside `0..=1` continues straight along the end tangent, or along the chord when
11/// that tangent is zero.
12#[must_use]
13pub fn point_along(
14    from: Point,
15    out_tangent: Vec2,
16    in_tangent: Vec2,
17    to: Point,
18    amount: f64,
19) -> Point {
20    let curve = CubicBez::new(from, from + out_tangent, to + in_tangent, to);
21    let segment = PathSeg::Cubic(curve);
22    // Relative to the curve, since positions are normalized while `ACCURACY` is in pixels.
23    let tolerance = 1e-7 * arclen::gauss(&segment, 0.0, 1.0);
24    let total = arclen::length_within(&segment, 0.0, 1.0, tolerance);
25    if total <= 0.0 {
26        return from;
27    }
28    if amount < 0.0 {
29        let direction = unit(from - (from + out_tangent), from - to);
30        return from + direction * (-amount * total);
31    }
32    if amount > 1.0 {
33        let direction = unit(to - (to + in_tangent), to - from);
34        return to + direction * ((amount - 1.0) * total);
35    }
36    let t = arclen::parameter_within(&segment, amount * total, total, tolerance);
37    arclen::point_at(&segment, t)
38}
39
40/// The unit direction of the cubic of [`point_along`] where `amount` (clamped to `0..=1`) of
41/// its arc length lies: the curve's tangent there, the next control leg where the tangent
42/// vanishes at an end, and the chord's direction when both tangents are zero. `None` for a
43/// segment of no length.
44#[must_use]
45pub fn direction_along(
46    from: Point,
47    out_tangent: Vec2,
48    in_tangent: Vec2,
49    to: Point,
50    amount: f64,
51) -> Option<Vec2> {
52    let curve = CubicBez::new(from, from + out_tangent, to + in_tangent, to);
53    let segment = PathSeg::Cubic(curve);
54    let tolerance = 1e-7 * arclen::gauss(&segment, 0.0, 1.0);
55    let total = arclen::length_within(&segment, 0.0, 1.0, tolerance);
56    if total <= 0.0 {
57        return None;
58    }
59    let t = arclen::parameter_within(&segment, amount.clamp(0.0, 1.0) * total, total, tolerance);
60    Some(direction_at(&curve, t))
61}
62
63fn direction_at(curve: &CubicBez, t: f64) -> Vec2 {
64    let derivative = kurbo::ParamCurveDeriv::deriv(curve);
65    let tangent = kurbo::ParamCurve::eval(&derivative, t).to_vec2();
66    let length = crate::affine::length(tangent);
67    if length > 1e-9 * crate::affine::length(curve.p3 - curve.p0).max(f64::MIN_POSITIVE) {
68        return tangent / length;
69    }
70    let here = kurbo::ParamCurve::eval(curve, t);
71    let legs = if t < 0.5 {
72        [curve.p1 - here, curve.p2 - here, curve.p3 - here]
73    } else {
74        [here - curve.p2, here - curve.p1, here - curve.p0]
75    };
76    legs.into_iter()
77        .map(|leg| (leg, crate::affine::length(leg)))
78        .find(|(_, length)| *length > 0.0)
79        .map_or(Vec2::ZERO, |(leg, length)| leg / length)
80}
81
82/// The point `fraction` of the arc length along `segments`, which join end to end, and the
83/// path's unit direction there. `fraction` is taken modulo 1 when `closed`, else clamped to
84/// `0..=1`. A path of no length gives its first point and no direction (zero).
85#[must_use]
86pub fn along_path(segments: &[PathSeg], closed: bool, fraction: f64) -> (Point, Vec2) {
87    let Some(first) = segments.first() else {
88        return (Point::ZERO, Vec2::ZERO);
89    };
90    let start = kurbo::ParamCurve::eval(first, 0.0);
91    let (lengths, tolerance) = path_lengths(segments);
92    let total: f64 = lengths.iter().sum();
93    if total.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) || !fraction.is_finite() {
94        return (start, Vec2::ZERO);
95    }
96    let fraction = if closed {
97        fraction.rem_euclid(1.0)
98    } else {
99        fraction.clamp(0.0, 1.0)
100    };
101    let mut target = fraction * total;
102    let last = lengths
103        .iter()
104        .rposition(|length| *length > 0.0)
105        .unwrap_or(0);
106    for (index, (segment, length)) in segments.iter().zip(&lengths).enumerate() {
107        if *length <= 0.0 || (target > *length && index < last) {
108            target -= *length;
109            continue;
110        }
111        let t = arclen::parameter_within(segment, target.min(*length), *length, tolerance);
112        let cubic = segment.to_cubic();
113        return (arclen::point_at(segment, t), direction_at(&cubic, t));
114    }
115    (start, Vec2::ZERO)
116}
117
118fn path_lengths(segments: &[PathSeg]) -> (Vec<f64>, f64) {
119    let scale: f64 = segments
120        .iter()
121        .map(|segment| arclen::gauss(segment, 0.0, 1.0))
122        .sum();
123    let tolerance = 1e-7 * scale;
124    let lengths = segments
125        .iter()
126        .map(|segment| arclen::length_within(segment, 0.0, 1.0, tolerance))
127        .collect();
128    (lengths, tolerance)
129}
130
131/// Where each of `segments`, which join end to end, starts and where the last ends, as fractions
132/// of the arc length [`along_path`] measures: one more value than segments, from 0 to 1. Empty
133/// for a path of no length.
134#[must_use]
135pub fn segment_fractions(segments: &[PathSeg]) -> Vec<f64> {
136    let (lengths, _) = path_lengths(segments);
137    let total: f64 = lengths.iter().sum();
138    if total.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) {
139        return Vec::new();
140    }
141    let mut travelled = 0.0;
142    let mut fractions = vec![0.0];
143    for length in &lengths {
144        travelled += length;
145        fractions.push((travelled / total).min(1.0));
146    }
147    if let Some(last) = fractions.last_mut() {
148        *last = 1.0;
149    }
150    fractions
151}
152
153/// The two halves of a spatial segment cut at one point.
154#[derive(Copy, Clone, Debug, PartialEq)]
155pub struct SpatialCut {
156    /// Where the path is cut.
157    pub point: Point,
158    /// The first half's control point after `from`, relative to `from`.
159    pub from_out: Vec2,
160    /// The first half's control point before the cut, relative to the cut.
161    pub cut_in: Vec2,
162    /// The second half's control point after the cut, relative to the cut.
163    pub cut_out: Vec2,
164    /// The second half's control point before `to`, relative to `to`.
165    pub to_in: Vec2,
166}
167
168/// The cubic of [`point_along`] cut where `amount` (in `0..=1`) of its arc length lies, by de
169/// Casteljau subdivision, so the two halves trace the same path. A segment of no length is cut
170/// at `from`.
171#[must_use]
172pub fn cut_along(
173    from: Point,
174    out_tangent: Vec2,
175    in_tangent: Vec2,
176    to: Point,
177    amount: f64,
178) -> SpatialCut {
179    let controls = [from, from + out_tangent, to + in_tangent, to];
180    let segment = PathSeg::Cubic(CubicBez::new(
181        controls[0],
182        controls[1],
183        controls[2],
184        controls[3],
185    ));
186    let tolerance = 1e-7 * arclen::gauss(&segment, 0.0, 1.0);
187    let total = arclen::length_within(&segment, 0.0, 1.0, tolerance);
188    let t = if total > 0.0 {
189        arclen::parameter_within(&segment, amount.clamp(0.0, 1.0) * total, total, tolerance)
190    } else {
191        0.0
192    };
193    let lerp = |a: Point, b: Point| a + (b - a) * t;
194    let first = [
195        lerp(controls[0], controls[1]),
196        lerp(controls[1], controls[2]),
197        lerp(controls[2], controls[3]),
198    ];
199    let second = [lerp(first[0], first[1]), lerp(first[1], first[2])];
200    let point = lerp(second[0], second[1]);
201    SpatialCut {
202        point,
203        from_out: first[0] - from,
204        cut_in: second[0] - point,
205        cut_out: second[1] - point,
206        to_in: first[2] - to,
207    }
208}
209
210/// `primary` normalized, else `fallback` normalized, else zero.
211fn unit(primary: Vec2, fallback: Vec2) -> Vec2 {
212    for vector in [primary, fallback] {
213        let length = crate::affine::length(vector);
214        if length > 0.0 {
215            return vector / length;
216        }
217    }
218    Vec2::ZERO
219}
220
221/// The motion path between keyframe values as a polyline with `samples` points per segment.
222#[must_use]
223pub fn motion_polyline(keys: &[(Point, Vec2, Vec2)], samples: u32) -> Vec<Point> {
224    let mut points = Vec::new();
225    let Some(first) = keys.first() else {
226        return points;
227    };
228    points.push(first.0);
229    let samples = samples.max(1);
230    for pair in keys.windows(2) {
231        let (from, out_tangent, _) = pair[0];
232        let (to, _, in_tangent) = pair[1];
233        let curve = CubicBez::new(from, from + out_tangent, to + in_tangent, to);
234        for step in 1..=samples {
235            points.push(kurbo::ParamCurve::eval(
236                &curve,
237                f64::from(step) / f64::from(samples),
238            ));
239        }
240    }
241    points
242}