Skip to main content

mgui_core/
property.rs

1//! 属性轨道(独立属性动画一期)—— 呈现值轨道,**不经过 Signal / rebuild**。
2//!
3//! 与 [`crate::animation::AnimationController`] 的分工:
4//! - `AnimationController` 是标量 `0..1` 控制器,靠 `Signal::set → mark_dirty →
5//!   rebuild_signal_dirty` 驱动,会逐帧重建 Widget —— 用于"值参与 build"的场景。
6//! - 本模块的 [`PropertyTrack<T>`] 直接产出**呈现值** `T`,由 `State::tick` 推进、
7//!   `apply_to_ro` 就地写进 RO 字段,合成阶段 `layer_effect()` 每帧实时读。
8//!   全程不 mount/update、不 create_render_object → `FrameStats.rebuilt == false`。
9//!
10//! 设计约束(与 `AnimationController` 一致,避免两套时间语义):
11//! - **锚点模型**:`anchor_ms` 时刻呈现值 = `anchor_value`,之后按曲线向 `target`
12//!   推进。`retarget`/`reverse` 在任意时刻重新锚定到当前呈现值 → 中断/反向连续。
13//! - **无外部时钟**:所有方法接收 `now_ms`,由 `run_frame` 传入(Headless 下即
14//!   `ManualClock`),因此同一 `now_ms` 序列逐位可重放。
15//! - **纯逻辑、零副作用**:不订阅、不标脏、不写 RO;这些由 State 层负责。
16
17use crate::{Color, Curve, Point, Size, Transform2D};
18use std::cell::RefCell;
19use std::fmt::Debug;
20use std::rc::Rc;
21
22/// 可在两个值之间线性插值。
23///
24/// 为属性动画实现:`f32`(opacity/corner)、`Point`(offset)、`Transform2D`(scale)、
25/// `Color`(color)。采用分量线性插值;旋转用最短弧处理,避免跨 ±π 时绕远路。
26/// `Color` 连 alpha 一起插值,保证淡入淡出与颜色变化同源。
27pub 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        // sRGB 编码空间的分量线性插值,alpha 同权 —— 与 PaintCommand 直接消费的
56        // Color 语义一致(paint 不做事后 gamma 转换),淡入淡出与颜色过渡同源。
57        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        // 旋转取最短弧:把差值折叠到 (-π, π],避免 170° → -170° 走 340° 远路。
64        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/// 单属性的呈现值轨道。
81///
82/// 典型用法(State 内):
83/// ```ignore
84/// struct AnimatedOpacityState {
85///     track: PropertyTrack<f32>,
86///     widget: WidgetNode,
87/// }
88/// fn tick(&mut self, now_ms: u64) {
89///     self.track.tick(now_ms); // 推进锚点,呈现值存在 track 里
90/// }
91/// fn is_animating(&self) -> bool { self.track.is_animating() }
92/// fn apply_to_ro(&mut self, ro: &mut dyn RenderObject) -> StateApply {
93///     ro.apply_state(self.as_any_mut())
94/// }
95/// ```
96#[derive(Clone, Debug)]
97pub struct PropertyTrack<T: Lerp> {
98    /// 锚点时刻(ms):此刻呈现值 = `anchor_value`
99    anchor_ms: u64,
100    /// 锚点呈现值
101    anchor_value: T,
102    /// 目标呈现值
103    target: T,
104    /// 动画时长(ms)
105    duration_ms: u64,
106    /// 缓动曲线
107    curve: Curve,
108    /// 是否正在推进
109    animating: bool,
110    /// 缓存的最新呈现值(供无时钟查询与 retarget 起点)
111    presented: T,
112}
113
114impl<T: Lerp> PropertyTrack<T> {
115    /// 以 `initial` 为初始呈现值创建静止轨道。
116    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    /// 当前呈现值(无副作用查询,不推进)。
138    pub fn presented(&self) -> T {
139        self.presented
140    }
141
142    pub fn is_animating(&self) -> bool {
143        self.animating
144    }
145
146    /// 是否已到达目标(呈现值与目标逐分量相等)。
147    pub fn is_settled(&self) -> bool {
148        self.presented == self.target
149    }
150
151    /// 从当前呈现值起,在 `now_ms` 时刻开始向 `target` 推进。
152    ///
153    /// 关键:**先按 now_ms 结算当前呈现值,再以此为新锚点** —— 这就是中断/反向
154    /// 连续的来源:中途改目标不会出现跳变。
155    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    /// 推进到 `now_ms`,返回结算后的呈现值。
165    ///
166    /// 必须在 `State::tick` 里每帧调用一次;只改内部锚点与缓存,不产生副作用。
167    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    /// 无状态查询 `now_ms` 时刻的呈现值(不推进、不改状态)。
176    ///
177    /// 供 hit_test、语义快照等"立即读当前位置"的路径使用,与 paint 同源。
178    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// =====================================================================
194// Spring retarget —— 带速度的弹簧轨道(路线图 9.3 "随后再扩 spring retarget")
195// =====================================================================
196
197/// 弹簧参数:刚度与阻尼。
198///
199/// - `stiffness`(k)越大,回目标越快;
200/// - `damping`(c)越小,过冲/回弹越明显。
201///   `c²` 与 `4k`:`c² < 4k` 欠阻尼(过冲),`= 4k` 临界(最快无过冲),
202///   `> 4k` 过阻尼(缓慢无过冲)。
203#[derive(Clone, Copy, Debug, PartialEq)]
204pub struct Spring {
205    pub stiffness: f32,
206    pub damping: f32,
207}
208
209impl Spring {
210    /// 欠阻尼默认配置:刚度 180、阻尼 18 → `c²=324 < 4k=720`,可见过冲回弹。
211    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/// 弹簧属性轨道:保存当前呈现值、**速度**、目标值,用弹簧物理推进。
226///
227/// 与 [`PropertyTrack`](时长 + 曲线、到点即停)互补:弹簧在**进度空间**维护
228/// `position`(0=起点、1=目标,可越过 1 再回弹)与 `velocity`(进度速度,1/s),
229/// 呈现值 = `T::lerp(from, to, position)`。这样任意 `Lerp` 类型(含旋转走
230/// 最短弧的 `Transform2D`)都能用同一套弹簧,不必给每种类型定义向量空间。
231///
232/// **中断连续**:`retarget` 先结算当前呈现值与速度,以当前值为新 `from`、
233/// **保留速度**,再朝新目标推进 —— 中途改向不会瞬间归零或跳变。
234///
235/// **确定性**:进度用固定子步长 `SPRING_STEP_S` 半隐式欧拉积分,积分步数只由
236/// `now_ms` 决定,与帧率/调用间隔无关;同一 `now_ms` 序列逐位可重放。
237#[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    /// 从 `anchor_ms` 起已积分的**整步数**。积分只认整步、不认残步,
246    /// 因此逐帧 tick 与跳帧 tick 推进的是同一串步长,结果与帧率严格无关。
247    integrated_steps: u64,
248    animating: bool,
249    presented: T,
250}
251
252/// 固定积分步长(秒)。选 1/120 让 60fps 下每帧恰好两步,低帧率也按同步长补步。
253const SPRING_STEP_S: f32 = 1.0 / 120.0;
254/// 固定步长的毫秒表示,用于把 `now_ms` 量化到整步编号(避免浮点残步)。
255const SPRING_STEP_MS: f64 = SPRING_STEP_S as f64 * 1000.0;
256/// 收敛判定:位置与速度同时进入容差才吸附到目标,避免"位置到了但还在冲"。
257const SPRING_EPS: f32 = 1e-3;
258
259impl<T: Lerp> SpringTrack<T> {
260    /// 以 `initial` 为初始呈现值创建静止轨道。
261    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    /// 当前进度速度(1/s);供观测"retarget 保留速度"。
297    pub fn velocity(&self) -> f32 {
298        self.velocity
299    }
300
301    /// 从当前呈现值起,在 `now_ms` 时刻重定向到 `target`,**保留速度**。
302    ///
303    /// 先按 now_ms 结算当前呈现值与速度,再以当前值为新 `from` —— 与
304    /// [`PropertyTrack::retarget`] 同为中断连续的来源,只是多带一份速度。
305    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    /// 推进到 `now_ms`,返回结算后的呈现值。在 `State::tick` 里每帧调用一次。
319    pub fn tick(&mut self, now_ms: u64) -> T {
320        self.advance(now_ms);
321        self.presented
322    }
323
324    /// 半隐式欧拉:先按当前位移/速度算加速度,再更新速度,最后用新速度更新位移。
325    ///
326    /// **绝对步编号**:目标步数 = `floor((now_ms - anchor_ms) / STEP_MS)`,只补
327    /// `target - integrated_steps` 个整步,每步严格 `SPRING_STEP_S`。
328    /// `anchor_ms` 只在 `retarget` 时重置,`advance` 永不改写 —— 于是不足一步的
329    /// 时间余数留在总 elapsed 里累积:逐帧 30×10ms 与跳帧 1×300ms 得到同一串
330    /// 整步,结果逐位相同(回放确定、与调用帧率无关)。
331    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
355// =====================================================================
356// Track —— 两种轨道的统一抽象(框架体系:同一套 widget 吃任意轨道实现)
357// =====================================================================
358
359/// 属性轨道的统一契约。
360///
361/// [`PropertyTrack`](时长 + 曲线、到点即停)与 [`SpringTrack`](带速度、可过冲)
362/// 都实现它,widget/state 只依赖句柄 [`SharedTrack<T>`],不再为每种轨道复制
363/// 一套 `AnimatedXxxWidget` —— 消灭"轨道类型 × 属性"的 N×M 样板。
364///
365/// `value_at`(无状态查询未来值)刻意不进 trait:只有曲线轨道有,弹簧按固定
366/// 步积分、无法无状态预知;需要"立即读当前值"的路径统一走 `presented`。
367pub 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
376/// 统一轨道句柄:widget/state 只持有这个类型,底层是曲线轨道还是弹簧轨道
377/// 由工厂函数决定,调用方无感。`Rc<RefCell<...>>` 与旧的共享句柄语义一致 —
378/// widget 构造时创建、外部持有 clone 以在运行时 retarget。
379pub 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    /// 采样 spring 在 now_ms 序列上的 presented 值。
428    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        // 欠阻尼:c²=18²=324 < 4k=4×180=720 → 应越过目标再回弹。
435        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        // 临界阻尼:c = 2√k = 2√225 = 30 → c²=900=4k,不应过冲。
448        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        // 在 t=300 反向:起点=当前呈现值,速度保留。
466        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        // 继续走会先凭惯性越过起点,再被弹簧拉回 0 —— 最终收敛。
472        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        // 细粒度逐帧 tick vs 一次性跳到终点:固定子步长从锚点重算,终点必须相同。
490        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        // 泛型:Point 分量各自弹簧。
509        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        // Color 含 alpha 一起弹簧,过冲后收敛。
518        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        // 0 → 1,跑到 0.5 时改目标为 0.4:新段必须从 0.5 起,不能跳回 0.0。
543        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        // 新段 500→1500 从 0.5 走向 0.4;1000ms 时走到一半 = 0.45
550        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        // 反向 = 把目标设回起点,从当前值继续
560        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        // 3 → -3 最短弧是 +0.283...,中点 ≈ 3.14159(π),不是 0(绕远路)
616        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        // 远超时长:必须钳制在 target,不 overshoot
639        assert_eq!(track.tick(10_000), 1.0);
640        assert!(!track.is_animating());
641    }
642}