use crate::{SampleContext, sample_scalar};
use alpha2_model::{
Animated, AnimatedPoint, CubicBezier, Extrapolation, Interpolation, Keyframe, MAX_KEYFRAMES,
PointKeyframe, ValueBezier, Vec2,
};
use alpha2_time::{MediaTime, TICKS_PER_SECOND, TimeRange};
mod materialize;
mod motion;
mod tangents;
mod wide;
mod within;
pub use materialize::materialize;
pub use motion::path_to_keys;
pub(crate) use tangents::tangents_of;
pub use tangents::{
AutoTangent, auto_tangents, contain, from_handle_points, from_slopes, from_speed_influence,
};
pub(crate) use wide::{WideKey, as_value_curve, part_keys, split_at, stepped};
pub(crate) use within::keys_within;
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum CurveError {
Empty,
NotKeyed,
OutsideKeys,
OnAKey,
LevelSegment,
TooManyKeys,
OffThePath,
}
impl std::fmt::Display for CurveError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(match self {
Self::Empty => "the value has no keyframes",
Self::NotKeyed => "the value is not keyframed",
Self::OutsideKeys => "the time lies outside the keyframes",
Self::OnAKey => "a keyframe already lies at the time",
Self::LevelSegment => "a part of the segment has no timing curve",
Self::TooManyKeys => "the result would hold too many keyframes",
Self::OffThePath => "the value is off the path between the keyframes at the time",
})
}
}
impl std::error::Error for CurveError {}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum SegmentKind {
Hold,
Linear,
Timing,
Value,
Steps,
Points,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct ControlSegment {
pub start: (i64, f64),
pub end: (i64, f64),
pub controls: Option<[(f64, f64); 2]>,
pub kind: SegmentKind,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct CurveSample {
pub value: f32,
pub velocity: f64,
}
#[expect(clippy::cast_precision_loss, reason = "a span of ticks as a length")]
fn span(left: MediaTime, right: MediaTime) -> f64 {
(i128::from(right.ticks()) - i128::from(left.ticks())) as f64
}
#[expect(clippy::cast_precision_loss, reason = "a tick as a coordinate")]
const fn coordinate(time: MediaTime) -> f64 {
time.ticks() as f64
}
#[expect(
clippy::cast_possible_truncation,
reason = "clamped to the range of f32"
)]
pub(crate) fn narrow(value: f64) -> f32 {
if value.is_nan() {
0.0
} else {
value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32
}
}
struct Cubic {
x1: f64,
x2: f64,
from: f64,
leave: f64,
arrive: f64,
to: f64,
}
impl Cubic {
fn of(left: &Keyframe<f32>, right: &Keyframe<f32>) -> Option<Self> {
let (from, to) = (f64::from(left.value), f64::from(right.value));
match left.interpolation {
Interpolation::Hold
| Interpolation::Linear
| Interpolation::Steps(_)
| Interpolation::Points { .. } => None,
Interpolation::CubicBezier(curve) => Some(Self {
x1: f64::from(curve.x1),
x2: f64::from(curve.x2),
from,
leave: f64::from(curve.y1) * (to - from),
arrive: (f64::from(curve.y2) - 1.0) * (to - from),
to,
}),
Interpolation::ValueBezier(curve) => {
let (x1, x2) = curve.weights().map_or((1.0 / 3.0, 2.0 / 3.0), |(x1, x2)| {
(f64::from(x1), f64::from(x2))
});
Some(Self {
x1,
x2,
from,
leave: f64::from(curve.leave),
arrive: f64::from(curve.arrive),
to,
})
}
}
}
fn progress_at(&self, u: f64) -> f64 {
let c = 3.0 * self.x1;
let b = 3.0 * (self.x2 - self.x1) - c;
let a = 1.0 - c - b;
((a * u + b) * u + c) * u
}
fn polynomial(&self) -> [f64; 3] {
let change = self.to - self.from;
let c = 3.0 * self.leave;
let b = 3.0 * (change + self.arrive - self.leave) - c;
[change - c - b, b, c]
}
fn value_at(&self, u: f64) -> f64 {
let [a, b, c] = self.polynomial();
self.from + ((a * u + b) * u + c) * u
}
fn turns(&self) -> impl Iterator<Item = f64> {
let [a, b, c] = self.polynomial();
let (qa, qb, qc) = (3.0 * a, 2.0 * b, c);
let mut roots = [None, None];
if qa.abs() <= f64::EPSILON {
if qb.abs() > f64::EPSILON {
roots[0] = Some(-qc / qb);
}
} else {
let discriminant = qb * qb - 4.0 * qa * qc;
if discriminant >= 0.0 {
let root = discriminant.sqrt();
roots = [
Some((-qb + root) / (2.0 * qa)),
Some((-qb - root) / (2.0 * qa)),
];
}
}
roots.into_iter().flatten().filter(|u| *u > 0.0 && *u < 1.0)
}
}
#[must_use]
pub fn segments(animation: &Animated<f32>) -> Vec<ControlSegment> {
let Animated::Keyframes { keyframes, .. } = animation else {
return Vec::new();
};
keyframes
.windows(2)
.map(|pair| {
let (left, right) = (&pair[0], &pair[1]);
let length = span(left.time, right.time);
let controls = Cubic::of(left, right).map(|cubic| {
[
(
coordinate(left.time) + cubic.x1 * length,
cubic.from + cubic.leave,
),
(
coordinate(left.time) + cubic.x2 * length,
cubic.to + cubic.arrive,
),
]
});
ControlSegment {
start: (left.time.ticks(), f64::from(left.value)),
end: (right.time.ticks(), f64::from(right.value)),
controls,
kind: match left.interpolation {
Interpolation::Hold => SegmentKind::Hold,
Interpolation::Linear => SegmentKind::Linear,
Interpolation::CubicBezier(_) => SegmentKind::Timing,
Interpolation::ValueBezier(_) => SegmentKind::Value,
Interpolation::Steps(_) => SegmentKind::Steps,
Interpolation::Points { .. } => SegmentKind::Points,
},
}
})
.collect()
}
#[must_use]
pub fn sample(animation: &Animated<f32>, times: &[MediaTime]) -> Vec<CurveSample> {
times
.iter()
.map(|time| CurveSample {
value: sample_scalar(animation, *time, &SampleContext::NONE),
velocity: match animation {
Animated::Keyframes {
keyframes,
before,
after,
} => velocity(keyframes, *before, *after, *time),
_ => 0.0,
},
})
.collect()
}
fn per_second(slope: f64, left: &Keyframe<f32>, right: &Keyframe<f32>) -> f64 {
let seconds = span(left.time, right.time) / span(MediaTime(0), MediaTime(TICKS_PER_SECOND));
let velocity = slope / seconds;
if velocity.is_nan() {
0.0
} else {
velocity.clamp(-f64::MAX, f64::MAX)
}
}
fn slope_at(left: &Keyframe<f32>, right: &Keyframe<f32>, progress: f64) -> f64 {
let change = f64::from(right.value) - f64::from(left.value);
let slope = match left.interpolation {
Interpolation::Hold | Interpolation::Steps(_) => 0.0,
Interpolation::Points { ref points } => {
alpha2_model::easing_points_slope(points, progress) * change
}
Interpolation::Linear => change,
Interpolation::CubicBezier(curve) => {
let slope = curve.slope(progress) * change;
if slope.is_nan() { 0.0 } else { slope }
}
Interpolation::ValueBezier(curve) => curve.slope(left.value, right.value, progress),
};
per_second(slope, left, right)
}
fn continued_slope(left: &Keyframe<f32>, right: &Keyframe<f32>, at_end: bool) -> f64 {
let change = f64::from(right.value) - f64::from(left.value);
let slope = match left.interpolation {
Interpolation::ValueBezier(curve) => curve.end_slope(left.value, right.value, at_end),
ref timing => timing.end_slope(at_end).unwrap_or(0.0) * change,
};
per_second(slope, left, right)
}
fn slope_before(keyframes: &[Keyframe<f32>], at: i128) -> f64 {
let right = keyframes.partition_point(|keyframe| i128::from(keyframe.time.ticks()) < at);
slope_in(&keyframes[right - 1], &keyframes[right], at)
}
fn slope_after(keyframes: &[Keyframe<f32>], at: i128) -> f64 {
let right = keyframes.partition_point(|keyframe| i128::from(keyframe.time.ticks()) <= at);
slope_in(&keyframes[right - 1], &keyframes[right], at)
}
#[expect(
clippy::cast_precision_loss,
reason = "ticks as a fraction of a segment"
)]
fn slope_in(left: &Keyframe<f32>, right: &Keyframe<f32>, at: i128) -> f64 {
let start = i128::from(left.time.ticks());
let progress = (at - start) as f64 / (i128::from(right.time.ticks()) - start) as f64;
slope_at(left, right, progress)
}
fn velocity(
keyframes: &[Keyframe<f32>],
before: Extrapolation,
after: Extrapolation,
time: MediaTime,
) -> f64 {
let [first, .., last] = keyframes else {
return 0.0;
};
let (start, end, at) = (
i128::from(first.time.ticks()),
i128::from(last.time.ticks()),
i128::from(time.ticks()),
);
let period = end - start;
let side = if at <= start {
before
} else if at > end {
after
} else {
return slope_before(keyframes, at);
};
match side {
Extrapolation::Hold => 0.0,
Extrapolation::Linear if at > end => {
continued_slope(&keyframes[keyframes.len() - 2], last, true)
}
Extrapolation::Linear => continued_slope(first, &keyframes[1], false),
Extrapolation::Repeat | Extrapolation::RepeatOffset => {
let offset = (at - start).rem_euclid(period);
slope_before(keyframes, start + if offset == 0 { period } else { offset })
}
Extrapolation::PingPong => {
let offset = (at - start).rem_euclid(2 * period);
if offset == 0 {
0.0 - slope_after(keyframes, start)
} else if offset <= period {
slope_before(keyframes, start + offset)
} else {
0.0 - slope_after(keyframes, start + 2 * period - offset)
}
}
}
}
struct Bounds([f64; 2]);
impl Bounds {
fn add(&mut self, value: f64) {
self.0 = [self.0[0].min(value), self.0[1].max(value)];
}
}
fn keyed_bounds(keyframes: &[Keyframe<f32>], from: i64, to: i64, bounds: &mut Bounds) {
for (index, left) in keyframes.iter().enumerate() {
let start = left.time.ticks();
if start > to {
break;
}
let Some(right) = keyframes.get(index + 1) else {
if start >= from {
bounds.add(f64::from(left.value));
}
break;
};
let end = right.time.ticks();
if end < from {
continue;
}
let held = matches!(left.interpolation, Interpolation::Hold);
if start >= from || (held && end > from) {
bounds.add(f64::from(left.value));
}
let length = span(left.time, right.time);
#[expect(clippy::cast_precision_loss, reason = "ticks as coordinates")]
let (low, high) = (from as f64, to as f64);
if let Interpolation::Points { points } = &left.interpolation {
let change = f64::from(right.value) - f64::from(left.value);
for point in points {
let time = coordinate(left.time) + f64::from(point.x) * length;
if time >= low && time <= high {
bounds.add(f64::from(left.value) + change * f64::from(point.y));
}
}
}
let Some(cubic) = Cubic::of(left, right) else {
continue;
};
for u in cubic.turns() {
let time = coordinate(left.time) + cubic.progress_at(u) * length;
if time >= low && time <= high {
bounds.add(cubic.value_at(u));
}
}
}
}
#[must_use]
pub fn range(animation: &Animated<f32>, range: TimeRange) -> [f64; 2] {
let from = range.start().ticks();
let to = range.end().ticks().saturating_sub(1).max(from);
let value = |tick: i64| {
f64::from(sample_scalar(
animation,
MediaTime(tick),
&SampleContext::NONE,
))
};
let mut bounds = Bounds([value(from); 2]);
bounds.add(value(to));
let Animated::Keyframes {
keyframes,
before,
after,
} = animation
else {
return bounds.0;
};
let [first, .., last] = keyframes.as_slice() else {
return bounds.0;
};
let mut spelled = animation.clone();
if materialize(&mut spelled, range).is_ok() {
if let Animated::Keyframes { keyframes, .. } = &spelled {
keyed_bounds(keyframes, from, to, &mut bounds);
}
return bounds.0;
}
let (start, end) = (first.time.ticks(), last.time.ticks());
if from <= end && to >= start {
keyed_bounds(keyframes, from.max(start), to.min(end), &mut bounds);
}
let mut whole = Bounds([f64::from(first.value); 2]);
keyed_bounds(keyframes, start, end, &mut whole);
let travel = f64::from(last.value) - f64::from(first.value);
let period = i128::from(end) - i128::from(start);
let pass = |tick: i64| (i128::from(tick) - i128::from(start)).div_euclid(period);
for (reached, side, passes) in [
(from < start, *before, [pass(from), -1]),
(to >= end, *after, [1, pass(to)]),
] {
if !reached {
continue;
}
match side {
Extrapolation::Hold | Extrapolation::Linear => {}
Extrapolation::Repeat | Extrapolation::PingPong => {
bounds.add(whole.0[0]);
bounds.add(whole.0[1]);
}
Extrapolation::RepeatOffset => {
for pass in passes {
#[expect(clippy::cast_precision_loss, reason = "a count of passes")]
let offset = pass as f64 * travel;
bounds.add(whole.0[0] + offset);
bounds.add(whole.0[1] + offset);
}
}
}
}
bounds.0
}
pub(crate) fn segment_value(left: &Keyframe<f32>, right: &Keyframe<f32>, tick: i64) -> f32 {
narrow(wide::curve_value(left, right, tick))
}
pub(crate) fn between_keys(
times: impl ExactSizeIterator<Item = MediaTime> + Clone,
time: MediaTime,
) -> Result<(usize, f64), CurveError> {
let count = times.len();
let (Some(first), Some(last)) = (times.clone().next(), times.clone().last()) else {
return Err(CurveError::Empty);
};
if time < first || time > last {
return Err(CurveError::OutsideKeys);
}
if count >= MAX_KEYFRAMES {
return Err(CurveError::TooManyKeys);
}
let mut left = 0;
let mut bounds = (first, last);
for (index, key) in times.enumerate() {
if key == time {
return Err(CurveError::OnAKey);
}
if key < time {
left = index;
bounds.0 = key;
} else {
bounds.1 = key;
break;
}
}
Ok((left, span(bounds.0, time) / span(bounds.0, bounds.1)))
}
pub fn insert_key(animation: &mut Animated<f32>, time: MediaTime) -> Result<(), CurveError> {
let Animated::Keyframes { keyframes, .. } = animation else {
return Err(CurveError::NotKeyed);
};
let (index, _) = between_keys(keyframes.iter().map(|key| key.time), time)?;
wide::split_at(keyframes, index, time)
}
fn timing_parts(
interpolation: &Interpolation,
progress: f64,
) -> Result<(Interpolation, Interpolation), CurveError> {
match interpolation {
Interpolation::Hold => Ok((Interpolation::Hold, Interpolation::Hold)),
Interpolation::Linear => Ok((Interpolation::Linear, Interpolation::Linear)),
Interpolation::CubicBezier(curve) => curve
.between(0.0, progress)
.zip(curve.between(progress, 1.0))
.map(|(leading, trailing)| {
(
Interpolation::CubicBezier(leading),
Interpolation::CubicBezier(trailing),
)
})
.ok_or(CurveError::LevelSegment),
Interpolation::Points { points } => {
let cut = alpha2_model::easing_points_at(points, progress);
let part = |start: f64, end: f64, low: f64, high: f64| {
let rise = high - low;
(rise != 0.0)
.then(|| {
alpha2_model::easing_points_between(points, start, end, |y| {
(y - low) / rise
})
})
.flatten()
.map(|points| Interpolation::Points { points })
};
part(0.0, progress, 0.0, cut)
.zip(part(progress, 1.0, cut, 1.0))
.ok_or(CurveError::LevelSegment)
}
Interpolation::ValueBezier(_) | Interpolation::Steps(_) => Err(CurveError::LevelSegment),
}
}
pub fn insert_eased_key<T>(
animation: &mut Animated<T>,
time: MediaTime,
value: T,
) -> Result<(), CurveError> {
let Animated::Keyframes { keyframes, .. } = animation else {
return Err(CurveError::NotKeyed);
};
let (index, progress) = between_keys(keyframes.iter().map(|key| key.time), time)?;
let (leading, trailing) = timing_parts(&keyframes[index].interpolation, progress)?;
keyframes[index].interpolation = leading;
keyframes.insert(
index + 1,
Keyframe {
time,
value,
interpolation: trailing,
},
);
Ok(())
}
pub fn insert_point_key(
animation: &mut AnimatedPoint,
time: MediaTime,
aspect: f64,
) -> Result<(), CurveError> {
let AnimatedPoint::Keyframes { keyframes, .. } = animation else {
return Err(CurveError::NotKeyed);
};
let (index, progress) = between_keys(keyframes.iter().map(|key| key.time), time)?;
let (left, right) = (&keyframes[index], &keyframes[index + 1]);
let amount = match left.interpolation {
Interpolation::Hold => {
let held = PointKeyframe {
time,
value: left.value,
interpolation: Interpolation::Hold,
out_tangent: Vec2::default(),
in_tangent: Vec2::default(),
};
keyframes.insert(index + 1, held);
return Ok(());
}
Interpolation::Linear => progress,
Interpolation::CubicBezier(curve) => curve.apply(progress),
Interpolation::Points { ref points } => alpha2_model::easing_points_at(points, progress),
Interpolation::ValueBezier(_) | Interpolation::Steps(_) => {
return Err(CurveError::LevelSegment);
}
};
if !(0.0..=1.0).contains(&amount) {
return Err(CurveError::OffThePath);
}
let (leading, trailing) = timing_parts(&left.interpolation, progress)?;
let straight = left.out_tangent.is_zero() && right.in_tangent.is_zero();
let aspect = if aspect.is_finite() && aspect > 0.0 {
aspect
} else {
1.0
};
let point = |value: Vec2| {
alpha2_geometry::kurbo::Point::new(f64::from(value.x) * aspect, f64::from(value.y))
};
let vector = |value: Vec2| {
alpha2_geometry::kurbo::Vec2::new(f64::from(value.x) * aspect, f64::from(value.y))
};
let cut = alpha2_geometry::spatial::cut_along(
point(left.value),
vector(left.out_tangent),
vector(right.in_tangent),
point(right.value),
amount,
);
let back = |x: f64, y: f64| Vec2::new(narrow(x / aspect), narrow(y));
let tangent = |tangent: alpha2_geometry::kurbo::Vec2| {
if straight {
Vec2::default()
} else {
back(tangent.x, tangent.y)
}
};
let added = PointKeyframe {
time,
value: back(cut.point.x, cut.point.y),
interpolation: trailing,
out_tangent: tangent(cut.cut_out),
in_tangent: tangent(cut.cut_in),
};
keyframes[index].interpolation = leading;
keyframes[index].out_tangent = tangent(cut.from_out);
keyframes[index + 1].in_tangent = tangent(cut.to_in);
keyframes.insert(index + 1, added);
Ok(())
}
pub fn to_value_curves(animation: &mut Animated<f32>) {
let Animated::Keyframes { keyframes, .. } = animation else {
return;
};
for index in 0..keyframes.len().saturating_sub(1) {
let (from, to) = (
f64::from(keyframes[index].value),
f64::from(keyframes[index + 1].value),
);
if let Some(curve) = as_value_curve(&keyframes[index].interpolation, from, to) {
keyframes[index].interpolation = Interpolation::ValueBezier(curve);
}
}
}
pub fn to_timing_curves(animation: &mut Animated<f32>) -> Result<(), CurveError> {
let Animated::Keyframes { keyframes, .. } = animation else {
return Ok(());
};
let mut rewritten = Vec::new();
for (index, pair) in keyframes.windows(2).enumerate() {
let Interpolation::ValueBezier(curve) = pair[0].interpolation else {
continue;
};
let change = f64::from(pair[1].value) - f64::from(pair[0].value);
let timing = timing_curve(curve, change).ok_or(CurveError::LevelSegment)?;
rewritten.push((index, Interpolation::CubicBezier(timing)));
}
for (index, interpolation) in rewritten {
keyframes[index].interpolation = interpolation;
}
Ok(())
}
fn timing_curve(curve: ValueBezier, change: f64) -> Option<CubicBezier> {
if change == 0.0 {
return None;
}
let (x1, x2) = curve.weights().unwrap_or((1.0 / 3.0, 2.0 / 3.0));
Some(CubicBezier::new(
x1,
narrow(f64::from(curve.leave) / change),
x2,
narrow(1.0 + f64::from(curve.arrive) / change),
))
}
#[cfg(test)]
#[path = "curves_tests.rs"]
mod tests;