1use crate::{Color, Curve, Point, Size, Transform2D};
18use std::cell::RefCell;
19use std::fmt::Debug;
20use std::rc::Rc;
21
22pub trait Lerp: Copy + Debug + PartialEq {
28 fn lerp(a: Self, b: Self, t: f32) -> Self;
29}
30
31impl Lerp for f32 {
32 #[inline]
33 fn lerp(a: Self, b: Self, t: f32) -> Self {
34 a + (b - a) * t
35 }
36}
37
38impl Lerp for Point {
39 #[inline]
40 fn lerp(a: Self, b: Self, t: f32) -> Self {
41 Point::new(f32::lerp(a.x, b.x, t), f32::lerp(a.y, b.y, t))
42 }
43}
44
45impl Lerp for Size {
46 #[inline]
47 fn lerp(a: Self, b: Self, t: f32) -> Self {
48 Size::new(f32::lerp(a.width, b.width, t), f32::lerp(a.height, b.height, t))
49 }
50}
51
52impl Lerp for Color {
53 #[inline]
54 fn lerp(a: Self, b: Self, t: f32) -> Self {
55 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))
58 }
59}
60
61impl Lerp for Transform2D {
62 fn lerp(a: Self, b: Self, t: f32) -> Self {
63 let mut d = b.rotation - a.rotation;
65 while d > std::f32::consts::PI {
66 d -= std::f32::consts::TAU;
67 }
68 while d <= -std::f32::consts::PI {
69 d += std::f32::consts::TAU;
70 }
71 Transform2D {
72 rotation: a.rotation + d * t,
73 scale_x: f32::lerp(a.scale_x, b.scale_x, t),
74 scale_y: f32::lerp(a.scale_y, b.scale_y, t),
75 translate: Point::lerp(a.translate, b.translate, t),
76 }
77 }
78}
79
80#[derive(Clone, Debug)]
97pub struct PropertyTrack<T: Lerp> {
98 anchor_ms: u64,
100 anchor_value: T,
102 target: T,
104 duration_ms: u64,
106 curve: Curve,
108 animating: bool,
110 presented: T,
112}
113
114impl<T: Lerp> PropertyTrack<T> {
115 pub fn new(initial: T, duration_ms: u64) -> Self {
117 Self {
118 anchor_ms: 0,
119 anchor_value: initial,
120 target: initial,
121 duration_ms: duration_ms.max(1),
122 curve: Curve::default(),
123 animating: false,
124 presented: initial,
125 }
126 }
127
128 pub fn with_curve(mut self, curve: Curve) -> Self {
129 self.curve = curve;
130 self
131 }
132
133 pub fn target(&self) -> T {
134 self.target
135 }
136
137 pub fn presented(&self) -> T {
139 self.presented
140 }
141
142 pub fn is_animating(&self) -> bool {
143 self.animating
144 }
145
146 pub fn is_settled(&self) -> bool {
148 self.presented == self.target
149 }
150
151 pub fn retarget(&mut self, target: T, now_ms: u64) {
156 let current = self.value_at(now_ms);
157 self.anchor_value = current;
158 self.anchor_ms = now_ms;
159 self.target = target;
160 self.presented = current;
161 self.animating = current != target;
162 }
163
164 pub fn tick(&mut self, now_ms: u64) -> T {
168 self.presented = self.value_at(now_ms);
169 if self.presented == self.target {
170 self.animating = false;
171 }
172 self.presented
173 }
174
175 pub fn value_at(&self, now_ms: u64) -> T {
179 if !self.animating {
180 return self.presented;
181 }
182 let elapsed = now_ms.saturating_sub(self.anchor_ms) as f32;
183 let linear = (elapsed / self.duration_ms as f32).clamp(0.0, 1.0);
184 let t = self.curve.transform(linear);
185 if t >= 1.0 {
186 self.target
187 } else {
188 T::lerp(self.anchor_value, self.target, t)
189 }
190 }
191}
192
193#[derive(Clone, Copy, Debug, PartialEq)]
204pub struct Spring {
205 pub stiffness: f32,
206 pub damping: f32,
207}
208
209impl Spring {
210 pub const DEFAULT_STIFFNESS: f32 = 180.0;
212 pub const DEFAULT_DAMPING: f32 = 18.0;
213
214 pub fn new(stiffness: f32, damping: f32) -> Self {
215 Self { stiffness: stiffness.max(0.0), damping: damping.max(0.0) }
216 }
217}
218
219impl Default for Spring {
220 fn default() -> Self {
221 Self::new(Self::DEFAULT_STIFFNESS, Self::DEFAULT_DAMPING)
222 }
223}
224
225#[derive(Clone, Debug)]
238pub struct SpringTrack<T: Lerp> {
239 from: T,
240 to: T,
241 position: f32,
242 velocity: f32,
243 spring: Spring,
244 anchor_ms: u64,
245 integrated_steps: u64,
248 animating: bool,
249 presented: T,
250}
251
252const SPRING_STEP_S: f32 = 1.0 / 120.0;
254const SPRING_STEP_MS: f64 = SPRING_STEP_S as f64 * 1000.0;
256const SPRING_EPS: f32 = 1e-3;
258
259impl<T: Lerp> SpringTrack<T> {
260 pub fn new(initial: T, spring: Spring) -> Self {
262 Self {
263 from: initial,
264 to: initial,
265 position: 0.0,
266 velocity: 0.0,
267 spring,
268 anchor_ms: 0,
269 integrated_steps: 0,
270 animating: false,
271 presented: initial,
272 }
273 }
274
275 pub fn with_spring(mut self, spring: Spring) -> Self {
276 self.spring = spring;
277 self
278 }
279
280 pub fn presented(&self) -> T {
281 self.presented
282 }
283
284 pub fn target(&self) -> T {
285 self.to
286 }
287
288 pub fn is_animating(&self) -> bool {
289 self.animating
290 }
291
292 pub fn is_settled(&self) -> bool {
293 !self.animating && self.presented == self.to
294 }
295
296 pub fn velocity(&self) -> f32 {
298 self.velocity
299 }
300
301 pub fn retarget(&mut self, target: T, now_ms: u64) {
306 self.advance(now_ms);
307 self.from = self.presented;
308 self.to = target;
309 self.position = 0.0;
310 self.anchor_ms = now_ms;
311 self.integrated_steps = 0;
312 self.animating = self.from != self.to || self.velocity.abs() > SPRING_EPS;
313 if !self.animating {
314 self.presented = self.to;
315 }
316 }
317
318 pub fn tick(&mut self, now_ms: u64) -> T {
320 self.advance(now_ms);
321 self.presented
322 }
323
324 fn advance(&mut self, now_ms: u64) {
332 if !self.animating {
333 return;
334 }
335 let elapsed_ms = now_ms.saturating_sub(self.anchor_ms) as f64;
336 let target_steps = (elapsed_ms / SPRING_STEP_MS) as u64;
337 while self.integrated_steps < target_steps {
338 let accel = -self.spring.stiffness * (self.position - 1.0) - self.spring.damping * self.velocity;
339 self.velocity += accel * SPRING_STEP_S;
340 self.position += self.velocity * SPRING_STEP_S;
341 self.integrated_steps += 1;
342 }
343
344 if (self.position - 1.0).abs() < SPRING_EPS && self.velocity.abs() < SPRING_EPS {
345 self.position = 1.0;
346 self.velocity = 0.0;
347 self.animating = false;
348 self.presented = self.to;
349 } else {
350 self.presented = T::lerp(self.from, self.to, self.position);
351 }
352 }
353}
354
355pub trait Track<T: Lerp>: Debug {
368 fn presented(&self) -> T;
369 fn target(&self) -> T;
370 fn tick(&mut self, now_ms: u64) -> T;
371 fn retarget(&mut self, target: T, now_ms: u64);
372 fn is_animating(&self) -> bool;
373 fn is_settled(&self) -> bool;
374}
375
376pub type SharedTrack<T> = Rc<RefCell<dyn Track<T>>>;
380
381impl<T: Lerp> Track<T> for PropertyTrack<T> {
382 fn presented(&self) -> T {
383 PropertyTrack::presented(self)
384 }
385 fn target(&self) -> T {
386 PropertyTrack::target(self)
387 }
388 fn tick(&mut self, now_ms: u64) -> T {
389 PropertyTrack::tick(self, now_ms)
390 }
391 fn retarget(&mut self, target: T, now_ms: u64) {
392 PropertyTrack::retarget(self, target, now_ms)
393 }
394 fn is_animating(&self) -> bool {
395 PropertyTrack::is_animating(self)
396 }
397 fn is_settled(&self) -> bool {
398 PropertyTrack::is_settled(self)
399 }
400}
401
402impl<T: Lerp> Track<T> for SpringTrack<T> {
403 fn presented(&self) -> T {
404 SpringTrack::presented(self)
405 }
406 fn target(&self) -> T {
407 SpringTrack::target(self)
408 }
409 fn tick(&mut self, now_ms: u64) -> T {
410 SpringTrack::tick(self, now_ms)
411 }
412 fn retarget(&mut self, target: T, now_ms: u64) {
413 SpringTrack::retarget(self, target, now_ms)
414 }
415 fn is_animating(&self) -> bool {
416 SpringTrack::is_animating(self)
417 }
418 fn is_settled(&self) -> bool {
419 SpringTrack::is_settled(self)
420 }
421}
422
423#[cfg(test)]
424mod tests {
425 use super::*;
426
427 fn sample(track: &mut SpringTrack<f32>, steps: &[u64]) -> Vec<f32> {
429 steps.iter().map(|&ms| track.tick(ms)).collect()
430 }
431
432 #[test]
433 fn spring_underdamped_overshoots_and_settles() {
434 let mut track = SpringTrack::new(0.0f32, Spring::new(180.0, 18.0));
436 track.retarget(1.0, 0);
437 let values = sample(&mut track, &(0..=1500).step_by(10).collect::<Vec<_>>());
438 let peak = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);
439 assert!(peak > 1.02, "欠阻尼应过冲,实际峰值 {peak}");
440 assert!((values.last().copied().unwrap() - 1.0).abs() < 1e-3, "最终收敛到目标");
441 assert!(track.is_settled() && !track.is_animating(), "收敛后必须停");
442 assert_eq!(track.velocity(), 0.0, "收敛后速度归零");
443 }
444
445 #[test]
446 fn spring_critically_damped_has_no_overshoot() {
447 let mut track = SpringTrack::new(0.0f32, Spring::new(225.0, 30.0));
449 track.retarget(1.0, 0);
450 let values = sample(&mut track, &(0..=1500).step_by(10).collect::<Vec<_>>());
451 let peak = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);
452 assert!(peak <= 1.0 + 1e-3, "临界阻尼不得过冲,实际峰值 {peak}");
453 assert!((values.last().copied().unwrap() - 1.0).abs() < 1e-3);
454 }
455
456 #[test]
457 fn spring_retarget_preserves_velocity_and_start_value() {
458 let mut track = SpringTrack::new(0.0f32, Spring::default());
459 track.retarget(1.0, 0);
460 sample(&mut track, &[100, 200, 300]);
461 let v_before = track.velocity();
462 let value_before = track.presented();
463 assert!(v_before.abs() > 1e-4, "中途应有非零速度");
464
465 track.retarget(0.0, 300);
467 assert!((track.presented() - value_before).abs() < 1e-6, "retarget 起点不得跳变");
468 assert!((track.velocity() - v_before).abs() < 1e-6, "retarget 必须保留速度(带惯性的反向)");
469 assert!(track.is_animating(), "带速度反向后仍在动");
470
471 let values = sample(&mut track, &(310..=2000).step_by(10).collect::<Vec<_>>());
473 assert!((values.last().copied().unwrap() - 0.0).abs() < 1e-3, "最终收敛到新目标 0");
474 }
475
476 #[test]
477 fn spring_replay_is_bit_identical() {
478 let script: Vec<u64> = (0..=200).map(|i| i * 8).collect();
479 let run = || {
480 let mut track = SpringTrack::new(0.0f32, Spring::new(180.0, 18.0));
481 track.retarget(1.0, 0);
482 script.iter().map(|&ms| track.tick(ms).to_bits()).collect::<Vec<_>>()
483 };
484 assert_eq!(run(), run(), "同一 now_ms 序列两次弹簧回放必须逐位相等");
485 }
486
487 #[test]
488 fn spring_frame_rate_independent_at_same_timestamps() {
489 let mut fine = SpringTrack::new(0.0f32, Spring::new(180.0, 18.0));
491 fine.retarget(1.0, 0);
492 for ms in (10..=300).step_by(10) {
493 fine.tick(ms);
494 }
495 let fine_end = fine.presented();
496 let fine_vel = fine.velocity();
497
498 let mut coarse = SpringTrack::new(0.0f32, Spring::new(180.0, 18.0));
499 coarse.retarget(1.0, 0);
500 let coarse_end = coarse.tick(300);
501
502 assert!((fine_end - coarse_end).abs() < 1e-6, "逐帧 {fine_end} vs 跳帧 {coarse_end}");
503 assert!((fine_vel - coarse.velocity()).abs() < 1e-6, "速度也应与调用帧率无关");
504 }
505
506 #[test]
507 fn spring_works_for_point_and_color() {
508 let mut pt = SpringTrack::new(Point::new(0.0, 10.0), Spring::new(180.0, 18.0));
510 pt.retarget(Point::new(100.0, -10.0), 0);
511 let values = sample_points(&mut pt, &(0..=1500).step_by(10).collect::<Vec<_>>());
512 let peak_x = values.iter().map(|p| p.x).fold(f32::NEG_INFINITY, f32::max);
513 assert!(peak_x > 102.0, "Point 也应过冲: {peak_x}");
514 assert!((values.last().unwrap().x - 100.0).abs() < 1e-3);
515 assert!((values.last().unwrap().y - (-10.0)).abs() < 1e-3);
516
517 let mut color = SpringTrack::new(Color::BLACK, Spring::new(180.0, 18.0));
519 color.retarget(Color::WHITE, 0);
520 let c = color.tick(1500);
521 assert!((c.r - 1.0).abs() < 1e-3 && (c.a - 1.0).abs() < 1e-3, "Color 弹簧应收敛到 WHITE");
522 }
523
524 fn sample_points(track: &mut SpringTrack<Point>, steps: &[u64]) -> Vec<Point> {
525 steps.iter().map(|&ms| track.tick(ms)).collect()
526 }
527
528 #[test]
529 fn f32_track_advances_and_settles() {
530 let mut track = PropertyTrack::new(0.0f32, 1000).with_curve(Curve::Linear);
531 track.retarget(1.0, 0);
532 assert!(track.is_animating());
533 assert_eq!(track.tick(0), 0.0);
534 assert!((track.tick(500) - 0.5).abs() < 1e-6);
535 assert_eq!(track.tick(1000), 1.0);
536 assert!(!track.is_animating(), "到目标后必须停,驱动 request_redraw 收敛");
537 assert!(track.is_settled());
538 }
539
540 #[test]
541 fn retarget_midflight_is_continuous() {
542 let mut track = PropertyTrack::new(0.0f32, 1000).with_curve(Curve::Linear);
544 track.retarget(1.0, 0);
545 let at_500 = track.value_at(500);
546 assert!((at_500 - 0.5).abs() < 1e-6);
547 track.retarget(0.4, 500);
548 assert!((track.presented() - at_500).abs() < 1e-6, "retarget 起点必须是当前呈现值");
549 assert!((track.value_at(1000) - 0.45).abs() < 1e-6);
551 assert_eq!(track.value_at(1500), 0.4);
552 }
553
554 #[test]
555 fn reverse_midflight_has_no_jump() {
556 let mut track = PropertyTrack::new(0.0f32, 1000).with_curve(Curve::Linear);
557 track.retarget(1.0, 0);
558 let at_300 = track.value_at(300);
559 track.retarget(0.0, 300);
561 let immediately = track.value_at(300);
562 assert!((immediately - at_300).abs() < 1e-6, "反向瞬间不得跳变");
563 let at_600 = track.value_at(600);
564 assert!(at_600 < at_300, "反向后值必须持续下降");
565 assert_eq!(track.value_at(1300), 0.0);
566 }
567
568 #[test]
569 fn deterministic_replay_is_bit_identical() {
570 let script: Vec<u64> = (0..=40).map(|i| i * 25).collect();
571 let run = || {
572 let mut track = PropertyTrack::new(0.0f32, 1000).with_curve(Curve::EaseInOut);
573 track.retarget(1.0, 0);
574 script.iter().map(|&ms| track.tick(ms).to_bits()).collect::<Vec<_>>()
575 };
576 assert_eq!(run(), run(), "同一 now_ms 序列两次回放必须逐位相等");
577 }
578
579 #[test]
580 fn color_lerp_interpolates_all_channels_including_alpha() {
581 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);
582 assert!((mid.r - 0.5).abs() < 1e-6);
583 assert!((mid.g - 0.25).abs() < 1e-6);
584 assert!((mid.b - 0.125).abs() < 1e-6);
585 assert!((mid.a - 0.5).abs() < 1e-6, "alpha 必须一起插值,否则淡入淡出会跳变");
586
587 let mut track = PropertyTrack::new(Color::BLACK, 1000).with_curve(Curve::Linear);
588 track.retarget(Color::WHITE, 0);
589 assert_eq!(track.tick(500), Color::rgba(0.5, 0.5, 0.5, 1.0));
590 assert_eq!(track.tick(1000), Color::WHITE);
591 assert!(!track.is_animating());
592 }
593
594 #[test]
595 fn size_lerp_interpolates_width_and_height() {
596 let mid = <Size as Lerp>::lerp(Size::new(20.0, 40.0), Size::new(60.0, 100.0), 0.5);
597 assert!((mid.width - 40.0).abs() < 1e-6);
598 assert!((mid.height - 70.0).abs() < 1e-6);
599
600 let mut track = PropertyTrack::new(Size::new(20.0, 20.0), 1000).with_curve(Curve::Linear);
601 track.retarget(Size::new(100.0, 60.0), 0);
602 assert_eq!(track.tick(500), Size::new(60.0, 40.0));
603 assert_eq!(track.tick(1000), Size::new(100.0, 60.0));
604 assert!(!track.is_animating());
605 }
606
607 #[test]
608 fn point_and_transform_lerp() {
609 let p = <Point as Lerp>::lerp(Point::new(0.0, 10.0), Point::new(100.0, 20.0), 0.25);
610 assert!((p.x - 25.0).abs() < 1e-6 && (p.y - 12.5).abs() < 1e-6);
611
612 let a = Transform2D::rotate(3.0);
613 let b = Transform2D::rotate(-3.0);
614 let mid = <Transform2D as Lerp>::lerp(a, b, 0.5);
615 assert!(mid.rotation.abs() > 3.0, "旋转插值必须走最短弧,实际 {rotation}", rotation = mid.rotation);
617 }
618
619 #[test]
620 fn point_track_retarget() {
621 let mut track = PropertyTrack::new(Point::ZERO, 1000).with_curve(Curve::Linear);
622 track.retarget(Point::new(100.0, 50.0), 0);
623 let mid = track.tick(500);
624 assert!((mid.x - 50.0).abs() < 1e-6 && (mid.y - 25.0).abs() < 1e-6);
625 track.retarget(Point::new(0.0, 50.0), 500);
626 let after = track.value_at(1000);
627 assert!((after.x - 25.0).abs() < 1e-6, "x 从 50 反向到 0,中点 25");
628 assert!(
629 (after.y - 37.5).abs() < 1e-6,
630 "y 从退靶时的 25 继续朝新目标 50 走,中点 37.5(退靶重启整段,不是保持旧值)",
631 );
632 }
633
634 #[test]
635 fn settle_before_duration_does_not_overshoot() {
636 let mut track = PropertyTrack::new(0.0f32, 100).with_curve(Curve::Linear);
637 track.retarget(1.0, 0);
638 assert_eq!(track.tick(10_000), 1.0);
640 assert!(!track.is_animating());
641 }
642}