alpha2-geometry 0.9.0

Deterministic vector geometry and coverage rasterization for alpha2 shapes.
Documentation
//! Motion along spatial curves. A position keyframed with tangents travels along the cubic
//! between keyframes by arc length, at the speed its timing curve sets.

use crate::arclen;
use kurbo::{CubicBez, PathSeg, Point, Vec2};

/// The point `amount` of the arc length along the cubic from `from` (control `from +
/// out_tangent`) to `to` (control `to + in_tangent`), in a space scaled to screen proportions.
///
/// An `amount` outside `0..=1` continues straight along the end tangent, or along the chord when
/// that tangent is zero.
#[must_use]
pub fn point_along(
    from: Point,
    out_tangent: Vec2,
    in_tangent: Vec2,
    to: Point,
    amount: f64,
) -> Point {
    let curve = CubicBez::new(from, from + out_tangent, to + in_tangent, to);
    let segment = PathSeg::Cubic(curve);
    // Relative to the curve, since positions are normalized while `ACCURACY` is in pixels.
    let tolerance = 1e-7 * arclen::gauss(&segment, 0.0, 1.0);
    let total = arclen::length_within(&segment, 0.0, 1.0, tolerance);
    if total <= 0.0 {
        return from;
    }
    if amount < 0.0 {
        let direction = unit(from - (from + out_tangent), from - to);
        return from + direction * (-amount * total);
    }
    if amount > 1.0 {
        let direction = unit(to - (to + in_tangent), to - from);
        return to + direction * ((amount - 1.0) * total);
    }
    let t = arclen::parameter_within(&segment, amount * total, total, tolerance);
    arclen::point_at(&segment, t)
}

/// The unit direction of the cubic of [`point_along`] where `amount` (clamped to `0..=1`) of
/// its arc length lies: the curve's tangent there, the next control leg where the tangent
/// vanishes at an end, and the chord's direction when both tangents are zero. `None` for a
/// segment of no length.
#[must_use]
pub fn direction_along(
    from: Point,
    out_tangent: Vec2,
    in_tangent: Vec2,
    to: Point,
    amount: f64,
) -> Option<Vec2> {
    let curve = CubicBez::new(from, from + out_tangent, to + in_tangent, to);
    let segment = PathSeg::Cubic(curve);
    let tolerance = 1e-7 * arclen::gauss(&segment, 0.0, 1.0);
    let total = arclen::length_within(&segment, 0.0, 1.0, tolerance);
    if total <= 0.0 {
        return None;
    }
    let t = arclen::parameter_within(&segment, amount.clamp(0.0, 1.0) * total, total, tolerance);
    Some(direction_at(&curve, t))
}

fn direction_at(curve: &CubicBez, t: f64) -> Vec2 {
    let derivative = kurbo::ParamCurveDeriv::deriv(curve);
    let tangent = kurbo::ParamCurve::eval(&derivative, t).to_vec2();
    let length = crate::affine::length(tangent);
    if length > 1e-9 * crate::affine::length(curve.p3 - curve.p0).max(f64::MIN_POSITIVE) {
        return tangent / length;
    }
    let here = kurbo::ParamCurve::eval(curve, t);
    let legs = if t < 0.5 {
        [curve.p1 - here, curve.p2 - here, curve.p3 - here]
    } else {
        [here - curve.p2, here - curve.p1, here - curve.p0]
    };
    legs.into_iter()
        .map(|leg| (leg, crate::affine::length(leg)))
        .find(|(_, length)| *length > 0.0)
        .map_or(Vec2::ZERO, |(leg, length)| leg / length)
}

/// The point `fraction` of the arc length along `segments`, which join end to end, and the
/// path's unit direction there. `fraction` is taken modulo 1 when `closed`, else clamped to
/// `0..=1`. A path of no length gives its first point and no direction (zero).
#[must_use]
pub fn along_path(segments: &[PathSeg], closed: bool, fraction: f64) -> (Point, Vec2) {
    let Some(first) = segments.first() else {
        return (Point::ZERO, Vec2::ZERO);
    };
    let start = kurbo::ParamCurve::eval(first, 0.0);
    let (lengths, tolerance) = path_lengths(segments);
    let total: f64 = lengths.iter().sum();
    if total.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) || !fraction.is_finite() {
        return (start, Vec2::ZERO);
    }
    let fraction = if closed {
        fraction.rem_euclid(1.0)
    } else {
        fraction.clamp(0.0, 1.0)
    };
    let mut target = fraction * total;
    let last = lengths
        .iter()
        .rposition(|length| *length > 0.0)
        .unwrap_or(0);
    for (index, (segment, length)) in segments.iter().zip(&lengths).enumerate() {
        if *length <= 0.0 || (target > *length && index < last) {
            target -= *length;
            continue;
        }
        let t = arclen::parameter_within(segment, target.min(*length), *length, tolerance);
        let cubic = segment.to_cubic();
        return (arclen::point_at(segment, t), direction_at(&cubic, t));
    }
    (start, Vec2::ZERO)
}

fn path_lengths(segments: &[PathSeg]) -> (Vec<f64>, f64) {
    let scale: f64 = segments
        .iter()
        .map(|segment| arclen::gauss(segment, 0.0, 1.0))
        .sum();
    let tolerance = 1e-7 * scale;
    let lengths = segments
        .iter()
        .map(|segment| arclen::length_within(segment, 0.0, 1.0, tolerance))
        .collect();
    (lengths, tolerance)
}

/// Where each of `segments`, which join end to end, starts and where the last ends, as fractions
/// of the arc length [`along_path`] measures: one more value than segments, from 0 to 1. Empty
/// for a path of no length.
#[must_use]
pub fn segment_fractions(segments: &[PathSeg]) -> Vec<f64> {
    let (lengths, _) = path_lengths(segments);
    let total: f64 = lengths.iter().sum();
    if total.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) {
        return Vec::new();
    }
    let mut travelled = 0.0;
    let mut fractions = vec![0.0];
    for length in &lengths {
        travelled += length;
        fractions.push((travelled / total).min(1.0));
    }
    if let Some(last) = fractions.last_mut() {
        *last = 1.0;
    }
    fractions
}

/// The two halves of a spatial segment cut at one point.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct SpatialCut {
    /// Where the path is cut.
    pub point: Point,
    /// The first half's control point after `from`, relative to `from`.
    pub from_out: Vec2,
    /// The first half's control point before the cut, relative to the cut.
    pub cut_in: Vec2,
    /// The second half's control point after the cut, relative to the cut.
    pub cut_out: Vec2,
    /// The second half's control point before `to`, relative to `to`.
    pub to_in: Vec2,
}

/// The cubic of [`point_along`] cut where `amount` (in `0..=1`) of its arc length lies, by de
/// Casteljau subdivision, so the two halves trace the same path. A segment of no length is cut
/// at `from`.
#[must_use]
pub fn cut_along(
    from: Point,
    out_tangent: Vec2,
    in_tangent: Vec2,
    to: Point,
    amount: f64,
) -> SpatialCut {
    let controls = [from, from + out_tangent, to + in_tangent, to];
    let segment = PathSeg::Cubic(CubicBez::new(
        controls[0],
        controls[1],
        controls[2],
        controls[3],
    ));
    let tolerance = 1e-7 * arclen::gauss(&segment, 0.0, 1.0);
    let total = arclen::length_within(&segment, 0.0, 1.0, tolerance);
    let t = if total > 0.0 {
        arclen::parameter_within(&segment, amount.clamp(0.0, 1.0) * total, total, tolerance)
    } else {
        0.0
    };
    let lerp = |a: Point, b: Point| a + (b - a) * t;
    let first = [
        lerp(controls[0], controls[1]),
        lerp(controls[1], controls[2]),
        lerp(controls[2], controls[3]),
    ];
    let second = [lerp(first[0], first[1]), lerp(first[1], first[2])];
    let point = lerp(second[0], second[1]);
    SpatialCut {
        point,
        from_out: first[0] - from,
        cut_in: second[0] - point,
        cut_out: second[1] - point,
        to_in: first[2] - to,
    }
}

/// `primary` normalized, else `fallback` normalized, else zero.
fn unit(primary: Vec2, fallback: Vec2) -> Vec2 {
    for vector in [primary, fallback] {
        let length = crate::affine::length(vector);
        if length > 0.0 {
            return vector / length;
        }
    }
    Vec2::ZERO
}

/// The motion path between keyframe values as a polyline with `samples` points per segment.
#[must_use]
pub fn motion_polyline(keys: &[(Point, Vec2, Vec2)], samples: u32) -> Vec<Point> {
    let mut points = Vec::new();
    let Some(first) = keys.first() else {
        return points;
    };
    points.push(first.0);
    let samples = samples.max(1);
    for pair in keys.windows(2) {
        let (from, out_tangent, _) = pair[0];
        let (to, _, in_tangent) = pair[1];
        let curve = CubicBez::new(from, from + out_tangent, to + in_tangent, to);
        for step in 1..=samples {
            points.push(kurbo::ParamCurve::eval(
                &curve,
                f64::from(step) / f64::from(samples),
            ));
        }
    }
    points
}