use crate::{Color, Curve, Point, Size, Transform2D};
use std::cell::RefCell;
use std::fmt::Debug;
use std::rc::Rc;
pub trait Lerp: Copy + Debug + PartialEq {
fn lerp(a: Self, b: Self, t: f32) -> Self;
}
impl Lerp for f32 {
#[inline]
fn lerp(a: Self, b: Self, t: f32) -> Self {
a + (b - a) * t
}
}
impl Lerp for Point {
#[inline]
fn lerp(a: Self, b: Self, t: f32) -> Self {
Point::new(f32::lerp(a.x, b.x, t), f32::lerp(a.y, b.y, t))
}
}
impl Lerp for Size {
#[inline]
fn lerp(a: Self, b: Self, t: f32) -> Self {
Size::new(f32::lerp(a.width, b.width, t), f32::lerp(a.height, b.height, t))
}
}
impl Lerp for Color {
#[inline]
fn lerp(a: Self, b: Self, t: f32) -> Self {
Color::rgba(f32::lerp(a.r, b.r, t), f32::lerp(a.g, b.g, t), f32::lerp(a.b, b.b, t), f32::lerp(a.a, b.a, t))
}
}
impl Lerp for Transform2D {
fn lerp(a: Self, b: Self, t: f32) -> Self {
let mut d = b.rotation - a.rotation;
while d > std::f32::consts::PI {
d -= std::f32::consts::TAU;
}
while d <= -std::f32::consts::PI {
d += std::f32::consts::TAU;
}
Transform2D {
rotation: a.rotation + d * t,
scale_x: f32::lerp(a.scale_x, b.scale_x, t),
scale_y: f32::lerp(a.scale_y, b.scale_y, t),
translate: Point::lerp(a.translate, b.translate, t),
}
}
}
#[derive(Clone, Debug)]
pub struct PropertyTrack<T: Lerp> {
anchor_ms: u64,
anchor_value: T,
target: T,
duration_ms: u64,
curve: Curve,
animating: bool,
presented: T,
}
impl<T: Lerp> PropertyTrack<T> {
pub fn new(initial: T, duration_ms: u64) -> Self {
Self {
anchor_ms: 0,
anchor_value: initial,
target: initial,
duration_ms: duration_ms.max(1),
curve: Curve::default(),
animating: false,
presented: initial,
}
}
pub fn with_curve(mut self, curve: Curve) -> Self {
self.curve = curve;
self
}
pub fn target(&self) -> T {
self.target
}
pub fn presented(&self) -> T {
self.presented
}
pub fn is_animating(&self) -> bool {
self.animating
}
pub fn is_settled(&self) -> bool {
self.presented == self.target
}
pub fn retarget(&mut self, target: T, now_ms: u64) {
let current = self.value_at(now_ms);
self.anchor_value = current;
self.anchor_ms = now_ms;
self.target = target;
self.presented = current;
self.animating = current != target;
}
pub fn tick(&mut self, now_ms: u64) -> T {
self.presented = self.value_at(now_ms);
if self.presented == self.target {
self.animating = false;
}
self.presented
}
pub fn value_at(&self, now_ms: u64) -> T {
if !self.animating {
return self.presented;
}
let elapsed = now_ms.saturating_sub(self.anchor_ms) as f32;
let linear = (elapsed / self.duration_ms as f32).clamp(0.0, 1.0);
let t = self.curve.transform(linear);
if t >= 1.0 {
self.target
} else {
T::lerp(self.anchor_value, self.target, t)
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Spring {
pub stiffness: f32,
pub damping: f32,
}
impl Spring {
pub const DEFAULT_STIFFNESS: f32 = 180.0;
pub const DEFAULT_DAMPING: f32 = 18.0;
pub fn new(stiffness: f32, damping: f32) -> Self {
Self { stiffness: stiffness.max(0.0), damping: damping.max(0.0) }
}
}
impl Default for Spring {
fn default() -> Self {
Self::new(Self::DEFAULT_STIFFNESS, Self::DEFAULT_DAMPING)
}
}
#[derive(Clone, Debug)]
pub struct SpringTrack<T: Lerp> {
from: T,
to: T,
position: f32,
velocity: f32,
spring: Spring,
anchor_ms: u64,
integrated_steps: u64,
animating: bool,
presented: T,
}
const SPRING_STEP_S: f32 = 1.0 / 120.0;
const SPRING_STEP_MS: f64 = SPRING_STEP_S as f64 * 1000.0;
const SPRING_EPS: f32 = 1e-3;
impl<T: Lerp> SpringTrack<T> {
pub fn new(initial: T, spring: Spring) -> Self {
Self {
from: initial,
to: initial,
position: 0.0,
velocity: 0.0,
spring,
anchor_ms: 0,
integrated_steps: 0,
animating: false,
presented: initial,
}
}
pub fn with_spring(mut self, spring: Spring) -> Self {
self.spring = spring;
self
}
pub fn presented(&self) -> T {
self.presented
}
pub fn target(&self) -> T {
self.to
}
pub fn is_animating(&self) -> bool {
self.animating
}
pub fn is_settled(&self) -> bool {
!self.animating && self.presented == self.to
}
pub fn velocity(&self) -> f32 {
self.velocity
}
pub fn retarget(&mut self, target: T, now_ms: u64) {
self.advance(now_ms);
self.from = self.presented;
self.to = target;
self.position = 0.0;
self.anchor_ms = now_ms;
self.integrated_steps = 0;
self.animating = self.from != self.to || self.velocity.abs() > SPRING_EPS;
if !self.animating {
self.presented = self.to;
}
}
pub fn tick(&mut self, now_ms: u64) -> T {
self.advance(now_ms);
self.presented
}
fn advance(&mut self, now_ms: u64) {
if !self.animating {
return;
}
let elapsed_ms = now_ms.saturating_sub(self.anchor_ms) as f64;
let target_steps = (elapsed_ms / SPRING_STEP_MS) as u64;
while self.integrated_steps < target_steps {
let accel = -self.spring.stiffness * (self.position - 1.0) - self.spring.damping * self.velocity;
self.velocity += accel * SPRING_STEP_S;
self.position += self.velocity * SPRING_STEP_S;
self.integrated_steps += 1;
}
if (self.position - 1.0).abs() < SPRING_EPS && self.velocity.abs() < SPRING_EPS {
self.position = 1.0;
self.velocity = 0.0;
self.animating = false;
self.presented = self.to;
} else {
self.presented = T::lerp(self.from, self.to, self.position);
}
}
}
pub trait Track<T: Lerp>: Debug {
fn presented(&self) -> T;
fn target(&self) -> T;
fn tick(&mut self, now_ms: u64) -> T;
fn retarget(&mut self, target: T, now_ms: u64);
fn is_animating(&self) -> bool;
fn is_settled(&self) -> bool;
}
pub type SharedTrack<T> = Rc<RefCell<dyn Track<T>>>;
impl<T: Lerp> Track<T> for PropertyTrack<T> {
fn presented(&self) -> T {
PropertyTrack::presented(self)
}
fn target(&self) -> T {
PropertyTrack::target(self)
}
fn tick(&mut self, now_ms: u64) -> T {
PropertyTrack::tick(self, now_ms)
}
fn retarget(&mut self, target: T, now_ms: u64) {
PropertyTrack::retarget(self, target, now_ms)
}
fn is_animating(&self) -> bool {
PropertyTrack::is_animating(self)
}
fn is_settled(&self) -> bool {
PropertyTrack::is_settled(self)
}
}
impl<T: Lerp> Track<T> for SpringTrack<T> {
fn presented(&self) -> T {
SpringTrack::presented(self)
}
fn target(&self) -> T {
SpringTrack::target(self)
}
fn tick(&mut self, now_ms: u64) -> T {
SpringTrack::tick(self, now_ms)
}
fn retarget(&mut self, target: T, now_ms: u64) {
SpringTrack::retarget(self, target, now_ms)
}
fn is_animating(&self) -> bool {
SpringTrack::is_animating(self)
}
fn is_settled(&self) -> bool {
SpringTrack::is_settled(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample(track: &mut SpringTrack<f32>, steps: &[u64]) -> Vec<f32> {
steps.iter().map(|&ms| track.tick(ms)).collect()
}
#[test]
fn spring_underdamped_overshoots_and_settles() {
let mut track = SpringTrack::new(0.0f32, Spring::new(180.0, 18.0));
track.retarget(1.0, 0);
let values = sample(&mut track, &(0..=1500).step_by(10).collect::<Vec<_>>());
let peak = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);
assert!(peak > 1.02, "欠阻尼应过冲,实际峰值 {peak}");
assert!((values.last().copied().unwrap() - 1.0).abs() < 1e-3, "最终收敛到目标");
assert!(track.is_settled() && !track.is_animating(), "收敛后必须停");
assert_eq!(track.velocity(), 0.0, "收敛后速度归零");
}
#[test]
fn spring_critically_damped_has_no_overshoot() {
let mut track = SpringTrack::new(0.0f32, Spring::new(225.0, 30.0));
track.retarget(1.0, 0);
let values = sample(&mut track, &(0..=1500).step_by(10).collect::<Vec<_>>());
let peak = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);
assert!(peak <= 1.0 + 1e-3, "临界阻尼不得过冲,实际峰值 {peak}");
assert!((values.last().copied().unwrap() - 1.0).abs() < 1e-3);
}
#[test]
fn spring_retarget_preserves_velocity_and_start_value() {
let mut track = SpringTrack::new(0.0f32, Spring::default());
track.retarget(1.0, 0);
sample(&mut track, &[100, 200, 300]);
let v_before = track.velocity();
let value_before = track.presented();
assert!(v_before.abs() > 1e-4, "中途应有非零速度");
track.retarget(0.0, 300);
assert!((track.presented() - value_before).abs() < 1e-6, "retarget 起点不得跳变");
assert!((track.velocity() - v_before).abs() < 1e-6, "retarget 必须保留速度(带惯性的反向)");
assert!(track.is_animating(), "带速度反向后仍在动");
let values = sample(&mut track, &(310..=2000).step_by(10).collect::<Vec<_>>());
assert!((values.last().copied().unwrap() - 0.0).abs() < 1e-3, "最终收敛到新目标 0");
}
#[test]
fn spring_replay_is_bit_identical() {
let script: Vec<u64> = (0..=200).map(|i| i * 8).collect();
let run = || {
let mut track = SpringTrack::new(0.0f32, Spring::new(180.0, 18.0));
track.retarget(1.0, 0);
script.iter().map(|&ms| track.tick(ms).to_bits()).collect::<Vec<_>>()
};
assert_eq!(run(), run(), "同一 now_ms 序列两次弹簧回放必须逐位相等");
}
#[test]
fn spring_frame_rate_independent_at_same_timestamps() {
let mut fine = SpringTrack::new(0.0f32, Spring::new(180.0, 18.0));
fine.retarget(1.0, 0);
for ms in (10..=300).step_by(10) {
fine.tick(ms);
}
let fine_end = fine.presented();
let fine_vel = fine.velocity();
let mut coarse = SpringTrack::new(0.0f32, Spring::new(180.0, 18.0));
coarse.retarget(1.0, 0);
let coarse_end = coarse.tick(300);
assert!((fine_end - coarse_end).abs() < 1e-6, "逐帧 {fine_end} vs 跳帧 {coarse_end}");
assert!((fine_vel - coarse.velocity()).abs() < 1e-6, "速度也应与调用帧率无关");
}
#[test]
fn spring_works_for_point_and_color() {
let mut pt = SpringTrack::new(Point::new(0.0, 10.0), Spring::new(180.0, 18.0));
pt.retarget(Point::new(100.0, -10.0), 0);
let values = sample_points(&mut pt, &(0..=1500).step_by(10).collect::<Vec<_>>());
let peak_x = values.iter().map(|p| p.x).fold(f32::NEG_INFINITY, f32::max);
assert!(peak_x > 102.0, "Point 也应过冲: {peak_x}");
assert!((values.last().unwrap().x - 100.0).abs() < 1e-3);
assert!((values.last().unwrap().y - (-10.0)).abs() < 1e-3);
let mut color = SpringTrack::new(Color::BLACK, Spring::new(180.0, 18.0));
color.retarget(Color::WHITE, 0);
let c = color.tick(1500);
assert!((c.r - 1.0).abs() < 1e-3 && (c.a - 1.0).abs() < 1e-3, "Color 弹簧应收敛到 WHITE");
}
fn sample_points(track: &mut SpringTrack<Point>, steps: &[u64]) -> Vec<Point> {
steps.iter().map(|&ms| track.tick(ms)).collect()
}
#[test]
fn f32_track_advances_and_settles() {
let mut track = PropertyTrack::new(0.0f32, 1000).with_curve(Curve::Linear);
track.retarget(1.0, 0);
assert!(track.is_animating());
assert_eq!(track.tick(0), 0.0);
assert!((track.tick(500) - 0.5).abs() < 1e-6);
assert_eq!(track.tick(1000), 1.0);
assert!(!track.is_animating(), "到目标后必须停,驱动 request_redraw 收敛");
assert!(track.is_settled());
}
#[test]
fn retarget_midflight_is_continuous() {
let mut track = PropertyTrack::new(0.0f32, 1000).with_curve(Curve::Linear);
track.retarget(1.0, 0);
let at_500 = track.value_at(500);
assert!((at_500 - 0.5).abs() < 1e-6);
track.retarget(0.4, 500);
assert!((track.presented() - at_500).abs() < 1e-6, "retarget 起点必须是当前呈现值");
assert!((track.value_at(1000) - 0.45).abs() < 1e-6);
assert_eq!(track.value_at(1500), 0.4);
}
#[test]
fn reverse_midflight_has_no_jump() {
let mut track = PropertyTrack::new(0.0f32, 1000).with_curve(Curve::Linear);
track.retarget(1.0, 0);
let at_300 = track.value_at(300);
track.retarget(0.0, 300);
let immediately = track.value_at(300);
assert!((immediately - at_300).abs() < 1e-6, "反向瞬间不得跳变");
let at_600 = track.value_at(600);
assert!(at_600 < at_300, "反向后值必须持续下降");
assert_eq!(track.value_at(1300), 0.0);
}
#[test]
fn deterministic_replay_is_bit_identical() {
let script: Vec<u64> = (0..=40).map(|i| i * 25).collect();
let run = || {
let mut track = PropertyTrack::new(0.0f32, 1000).with_curve(Curve::EaseInOut);
track.retarget(1.0, 0);
script.iter().map(|&ms| track.tick(ms).to_bits()).collect::<Vec<_>>()
};
assert_eq!(run(), run(), "同一 now_ms 序列两次回放必须逐位相等");
}
#[test]
fn color_lerp_interpolates_all_channels_including_alpha() {
let mid = <Color as Lerp>::lerp(Color::rgba(0.0, 0.0, 0.0, 0.0), Color::rgba(1.0, 0.5, 0.25, 1.0), 0.5);
assert!((mid.r - 0.5).abs() < 1e-6);
assert!((mid.g - 0.25).abs() < 1e-6);
assert!((mid.b - 0.125).abs() < 1e-6);
assert!((mid.a - 0.5).abs() < 1e-6, "alpha 必须一起插值,否则淡入淡出会跳变");
let mut track = PropertyTrack::new(Color::BLACK, 1000).with_curve(Curve::Linear);
track.retarget(Color::WHITE, 0);
assert_eq!(track.tick(500), Color::rgba(0.5, 0.5, 0.5, 1.0));
assert_eq!(track.tick(1000), Color::WHITE);
assert!(!track.is_animating());
}
#[test]
fn size_lerp_interpolates_width_and_height() {
let mid = <Size as Lerp>::lerp(Size::new(20.0, 40.0), Size::new(60.0, 100.0), 0.5);
assert!((mid.width - 40.0).abs() < 1e-6);
assert!((mid.height - 70.0).abs() < 1e-6);
let mut track = PropertyTrack::new(Size::new(20.0, 20.0), 1000).with_curve(Curve::Linear);
track.retarget(Size::new(100.0, 60.0), 0);
assert_eq!(track.tick(500), Size::new(60.0, 40.0));
assert_eq!(track.tick(1000), Size::new(100.0, 60.0));
assert!(!track.is_animating());
}
#[test]
fn point_and_transform_lerp() {
let p = <Point as Lerp>::lerp(Point::new(0.0, 10.0), Point::new(100.0, 20.0), 0.25);
assert!((p.x - 25.0).abs() < 1e-6 && (p.y - 12.5).abs() < 1e-6);
let a = Transform2D::rotate(3.0);
let b = Transform2D::rotate(-3.0);
let mid = <Transform2D as Lerp>::lerp(a, b, 0.5);
assert!(mid.rotation.abs() > 3.0, "旋转插值必须走最短弧,实际 {rotation}", rotation = mid.rotation);
}
#[test]
fn point_track_retarget() {
let mut track = PropertyTrack::new(Point::ZERO, 1000).with_curve(Curve::Linear);
track.retarget(Point::new(100.0, 50.0), 0);
let mid = track.tick(500);
assert!((mid.x - 50.0).abs() < 1e-6 && (mid.y - 25.0).abs() < 1e-6);
track.retarget(Point::new(0.0, 50.0), 500);
let after = track.value_at(1000);
assert!((after.x - 25.0).abs() < 1e-6, "x 从 50 反向到 0,中点 25");
assert!(
(after.y - 37.5).abs() < 1e-6,
"y 从退靶时的 25 继续朝新目标 50 走,中点 37.5(退靶重启整段,不是保持旧值)",
);
}
#[test]
fn settle_before_duration_does_not_overshoot() {
let mut track = PropertyTrack::new(0.0f32, 100).with_curve(Curve::Linear);
track.retarget(1.0, 0);
assert_eq!(track.tick(10_000), 1.0);
assert!(!track.is_animating());
}
}