use super::{CurveError, coordinate, narrow, span};
use crate::animation::interpolation_amount;
use alpha2_model::{
CubicBezier, EasingPoint, Interpolation, Keyframe, MAX_KEYFRAMES, Steps, ValueBezier,
};
use alpha2_time::MediaTime;
pub(crate) trait WideKey: Clone {
fn time(&self) -> MediaTime;
fn value(&self) -> f64;
fn interpolation(&self) -> &Interpolation;
fn set_interpolation(&mut self, interpolation: Interpolation);
fn keyed(time: MediaTime, value: f64, interpolation: Interpolation) -> Self;
fn stored(value: f64) -> f64;
fn shown(left: &Self, right: &Self, tick: i64) -> f64 {
curve_value(left, right, tick)
}
fn keeps_timing(_curve: CubicBezier, _start: f64, _end: f64) -> bool {
true
}
}
impl WideKey for Keyframe<f32> {
fn time(&self) -> MediaTime {
self.time
}
fn value(&self) -> f64 {
f64::from(self.value)
}
fn interpolation(&self) -> &Interpolation {
&self.interpolation
}
fn set_interpolation(&mut self, interpolation: Interpolation) {
self.interpolation = interpolation;
}
fn keyed(time: MediaTime, value: f64, interpolation: Interpolation) -> Self {
Self {
time,
value: narrow(value),
interpolation,
}
}
fn stored(value: f64) -> f64 {
f64::from(narrow(value))
}
}
fn eased<K: WideKey>(from: f64, to: f64, progress: f64, amount: impl Fn(f64) -> f64) -> f64 {
if progress <= 0.0 {
from
} else if progress >= 1.0 {
to
} else {
K::stored(from + (to - from) * amount(progress))
}
}
pub(crate) fn curve_value<K: WideKey>(left: &K, right: &K, tick: i64) -> f64 {
let (start, end) = (left.time().ticks(), right.time().ticks());
if tick <= start {
return left.value();
}
if tick >= end {
return right.value();
}
let (from, to) = (left.value(), right.value());
let progress = interpolation_amount(left.time(), right.time(), MediaTime(tick));
match left.interpolation() {
Interpolation::Hold => from,
Interpolation::Linear => eased::<K>(from, to, progress, |progress| progress),
Interpolation::CubicBezier(curve) => {
eased::<K>(from, to, progress, |progress| curve.apply(progress))
}
Interpolation::ValueBezier(curve) => K::stored(curve.value_between(from, to, progress)),
Interpolation::Steps(steps) => {
let index = steps.index(i128::from(tick - start), i128::from(end - start));
K::stored(from + (to - from) * steps.amount(index))
}
Interpolation::Points { points } => eased::<K>(from, to, progress, |progress| {
alpha2_model::easing_points_at(points, progress)
}),
}
}
fn part<K: WideKey>(left: &K, right: &K, from: i64, to: i64) -> Option<K> {
let progress = |tick: i64| interpolation_amount(left.time(), right.time(), MediaTime(tick));
let (start, end) = (progress(from), progress(to));
let ends = (left.value(), right.value());
let part_ends = || (K::shown(left, right, from), K::shown(left, right, to));
let (value, interpolation) = match left.interpolation() {
Interpolation::Steps(_) | Interpolation::Points { .. } => return None,
Interpolation::Hold => (ends.0, Interpolation::Hold),
Interpolation::Linear => (part_ends().0, Interpolation::Linear),
Interpolation::ValueBezier(curve) => {
let part_ends = part_ends();
let part = curve.part_between(ends, (start, end), part_ends);
(part_ends.0, Interpolation::ValueBezier(part))
}
Interpolation::CubicBezier(curve) => {
let (low, high) = part_ends();
match curve.between(start, end) {
Some(part)
if low.to_bits() != high.to_bits() && K::keeps_timing(*curve, start, end) =>
{
(low, Interpolation::CubicBezier(part))
}
_ => {
let own = value_curve(*curve, ends.0, ends.1);
let own_ends = (
K::stored(own.value_between(ends.0, ends.1, start)),
K::stored(own.value_between(ends.0, ends.1, end)),
);
let part = own
.part_between(ends, (start, end), own_ends)
.rebased_between(own_ends, (low, high));
(low, Interpolation::ValueBezier(part))
}
}
}
};
Some(K::keyed(MediaTime(from), value, interpolation))
}
pub(crate) fn stepped<K: WideKey>(left: &K, right: &K, steps: Steps, from: i64, to: i64) -> Vec<K> {
let start = left.time().ticks();
let length = i128::from(right.time().ticks() - start);
let count = i128::from(steps.count);
let mut ticks = vec![from];
if from == start && to > start + 1 {
ticks.push(start + 1);
}
let first = steps.index(i128::from(from - start), length);
let last = steps.index(i128::from(to - 1 - start), length);
for index in first + 1..=last {
let rise = (index * length + count - 1).div_euclid(count);
let tick = start + i64::try_from(rise).unwrap_or_default();
if tick > from && tick < to {
ticks.push(tick);
}
}
ticks.sort_unstable();
ticks.dedup();
let mut keys: Vec<K> = Vec::new();
for tick in ticks {
let value = K::shown(left, right, tick);
if keys
.last()
.is_none_or(|key| key.value().to_bits() != value.to_bits())
{
keys.push(K::keyed(MediaTime(tick), value, Interpolation::Hold));
}
}
keys
}
fn table_part<K: WideKey>(
left: &K,
right: &K,
points: &[EasingPoint],
from: i64,
to: i64,
) -> Vec<K> {
let progress = |tick: i64| interpolation_amount(left.time(), right.time(), MediaTime(tick));
let (low, high) = (K::shown(left, right, from), K::shown(left, right, to));
let key = |tick: i64, interpolation: Interpolation| {
K::keyed(MediaTime(tick), K::shown(left, right, tick), interpolation)
};
let change = right.value() - left.value();
let rise = high - low;
let table = (low.to_bits() != high.to_bits())
.then(|| {
alpha2_model::easing_points_between(points, progress(from), progress(to), |y| {
(left.value() + change * y - low) / rise
})
})
.flatten();
if let Some(points) = table {
return vec![key(from, Interpolation::Points { points })];
}
let length = span(left.time(), right.time());
let mut ticks = vec![from];
for point in points {
#[expect(clippy::cast_possible_truncation, reason = "a time inside the segment")]
let tick = (coordinate(left.time()) + f64::from(point.x) * length).floor() as i64;
ticks.extend(
[tick, tick + 1]
.into_iter()
.filter(|tick| *tick > from && *tick < to),
);
}
ticks.sort_unstable();
ticks.dedup();
ticks
.into_iter()
.map(|tick| key(tick, Interpolation::Linear))
.collect()
}
pub(crate) fn part_keys<K: WideKey>(left: &K, right: &K, from: i64, to: i64) -> Vec<K> {
if from == left.time().ticks() && to == right.time().ticks() {
return vec![left.clone()];
}
match left.interpolation() {
Interpolation::Steps(steps) => stepped(left, right, *steps, from, to),
Interpolation::Points { points } => table_part(left, right, points, from, to),
_ => part(left, right, from, to).into_iter().collect(),
}
}
pub(crate) fn split_at<K: WideKey>(
keys: &mut Vec<K>,
index: usize,
time: MediaTime,
) -> Result<(), CurveError> {
let (left, right) = (&keys[index], &keys[index + 1]);
let mut parts = part_keys(left, right, left.time().ticks(), time.ticks());
parts.extend(part_keys(left, right, time.ticks(), right.time().ticks()));
if keys.len() - 1 + parts.len() > MAX_KEYFRAMES {
return Err(CurveError::TooManyKeys);
}
keys.splice(index..=index, parts);
Ok(())
}
pub(crate) fn value_curve(curve: CubicBezier, from: f64, to: f64) -> ValueBezier {
let change = to - from;
ValueBezier::weighted(
curve.x1,
narrow(f64::from(curve.y1) * change),
curve.x2,
narrow((f64::from(curve.y2) - 1.0) * change),
)
}
pub(crate) fn as_value_curve(
interpolation: &Interpolation,
from: f64,
to: f64,
) -> Option<ValueBezier> {
match interpolation {
Interpolation::Hold | Interpolation::Steps(_) | Interpolation::Points { .. } => None,
Interpolation::Linear => {
let third = (to - from) / 3.0;
Some(ValueBezier::unweighted(narrow(third), narrow(0.0 - third)))
}
Interpolation::CubicBezier(curve) => Some(value_curve(*curve, from, to)),
Interpolation::ValueBezier(curve) => Some(*curve),
}
}