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/// `primary` normalized, else `fallback` normalized, else zero.
41fn unit(primary: Vec2, fallback: Vec2) -> Vec2 {
42    for vector in [primary, fallback] {
43        let length = crate::affine::length(vector);
44        if length > 0.0 {
45            return vector / length;
46        }
47    }
48    Vec2::ZERO
49}
50
51/// The motion path between keyframe values as a polyline with `samples` points per segment.
52#[must_use]
53pub fn motion_polyline(keys: &[(Point, Vec2, Vec2)], samples: u32) -> Vec<Point> {
54    let mut points = Vec::new();
55    let Some(first) = keys.first() else {
56        return points;
57    };
58    points.push(first.0);
59    let samples = samples.max(1);
60    for pair in keys.windows(2) {
61        let (from, out_tangent, _) = pair[0];
62        let (to, _, in_tangent) = pair[1];
63        let curve = CubicBez::new(from, from + out_tangent, to + in_tangent, to);
64        for step in 1..=samples {
65            points.push(kurbo::ParamCurve::eval(
66                &curve,
67                f64::from(step) / f64::from(samples),
68            ));
69        }
70    }
71    points
72}