mgui-core 0.4.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
//! 属性轨道(独立属性动画一期)—— 呈现值轨道,**不经过 Signal / rebuild**。
//!
//! 与 [`crate::animation::AnimationController`] 的分工:
//! - `AnimationController` 是标量 `0..1` 控制器,靠 `Signal::set → mark_dirty →
//!   rebuild_signal_dirty` 驱动,会逐帧重建 Widget —— 用于"值参与 build"的场景。
//! - 本模块的 [`PropertyTrack<T>`] 直接产出**呈现值** `T`,由 `State::tick` 推进、
//!   `apply_to_ro` 就地写进 RO 字段,合成阶段 `layer_effect()` 每帧实时读。
//!   全程不 mount/update、不 create_render_object → `FrameStats.rebuilt == false`。
//!
//! 设计约束(与 `AnimationController` 一致,避免两套时间语义):
//! - **锚点模型**:`anchor_ms` 时刻呈现值 = `anchor_value`,之后按曲线向 `target`
//!   推进。`retarget`/`reverse` 在任意时刻重新锚定到当前呈现值 → 中断/反向连续。
//! - **无外部时钟**:所有方法接收 `now_ms`,由 `run_frame` 传入(Headless 下即
//!   `ManualClock`),因此同一 `now_ms` 序列逐位可重放。
//! - **纯逻辑、零副作用**:不订阅、不标脏、不写 RO;这些由 State 层负责。

use crate::{Color, Curve, Point, Size, Transform2D};
use std::cell::RefCell;
use std::fmt::Debug;
use std::rc::Rc;

/// 可在两个值之间线性插值。
///
/// 为属性动画实现:`f32`(opacity/corner)、`Point`(offset)、`Transform2D`(scale)、
/// `Color`(color)。采用分量线性插值;旋转用最短弧处理,避免跨 ±π 时绕远路。
/// `Color` 连 alpha 一起插值,保证淡入淡出与颜色变化同源。
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 {
        // sRGB 编码空间的分量线性插值,alpha 同权 —— 与 PaintCommand 直接消费的
        // Color 语义一致(paint 不做事后 gamma 转换),淡入淡出与颜色过渡同源。
        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 {
        // 旋转取最短弧:把差值折叠到 (-π, π],避免 170° → -170° 走 340° 远路。
        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),
        }
    }
}

/// 单属性的呈现值轨道。
///
/// 典型用法(State 内):
/// ```ignore
/// struct AnimatedOpacityState {
///     track: PropertyTrack<f32>,
///     widget: WidgetNode,
/// }
/// fn tick(&mut self, now_ms: u64) {
///     self.track.tick(now_ms); // 推进锚点,呈现值存在 track 里
/// }
/// fn is_animating(&self) -> bool { self.track.is_animating() }
/// fn apply_to_ro(&mut self, ro: &mut dyn RenderObject) -> StateApply {
///     ro.apply_state(self.as_any_mut())
/// }
/// ```
#[derive(Clone, Debug)]
pub struct PropertyTrack<T: Lerp> {
    /// 锚点时刻(ms):此刻呈现值 = `anchor_value`
    anchor_ms: u64,
    /// 锚点呈现值
    anchor_value: T,
    /// 目标呈现值
    target: T,
    /// 动画时长(ms)
    duration_ms: u64,
    /// 缓动曲线
    curve: Curve,
    /// 是否正在推进
    animating: bool,
    /// 缓存的最新呈现值(供无时钟查询与 retarget 起点)
    presented: T,
}

impl<T: Lerp> PropertyTrack<T> {
    /// 以 `initial` 为初始呈现值创建静止轨道。
    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
    }

    /// 从当前呈现值起,在 `now_ms` 时刻开始向 `target` 推进。
    ///
    /// 关键:**先按 now_ms 结算当前呈现值,再以此为新锚点** —— 这就是中断/反向
    /// 连续的来源:中途改目标不会出现跳变。
    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;
    }

    /// 推进到 `now_ms`,返回结算后的呈现值。
    ///
    /// 必须在 `State::tick` 里每帧调用一次;只改内部锚点与缓存,不产生副作用。
    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
    }

    /// 无状态查询 `now_ms` 时刻的呈现值(不推进、不改状态)。
    ///
    /// 供 hit_test、语义快照等"立即读当前位置"的路径使用,与 paint 同源。
    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)
        }
    }
}

// =====================================================================
// Spring retarget —— 带速度的弹簧轨道(路线图 9.3 "随后再扩 spring retarget")
// =====================================================================

/// 弹簧参数:刚度与阻尼。
///
/// - `stiffness`(k)越大,回目标越快;
/// - `damping`(c)越小,过冲/回弹越明显。
///   `c²` 与 `4k`:`c² < 4k` 欠阻尼(过冲),`= 4k` 临界(最快无过冲),
///   `> 4k` 过阻尼(缓慢无过冲)。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Spring {
    pub stiffness: f32,
    pub damping: f32,
}

impl Spring {
    /// 欠阻尼默认配置:刚度 180、阻尼 18 → `c²=324 < 4k=720`,可见过冲回弹。
    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)
    }
}

/// 弹簧属性轨道:保存当前呈现值、**速度**、目标值,用弹簧物理推进。
///
/// 与 [`PropertyTrack`](时长 + 曲线、到点即停)互补:弹簧在**进度空间**维护
/// `position`(0=起点、1=目标,可越过 1 再回弹)与 `velocity`(进度速度,1/s),
/// 呈现值 = `T::lerp(from, to, position)`。这样任意 `Lerp` 类型(含旋转走
/// 最短弧的 `Transform2D`)都能用同一套弹簧,不必给每种类型定义向量空间。
///
/// **中断连续**:`retarget` 先结算当前呈现值与速度,以当前值为新 `from`、
/// **保留速度**,再朝新目标推进 —— 中途改向不会瞬间归零或跳变。
///
/// **确定性**:进度用固定子步长 `SPRING_STEP_S` 半隐式欧拉积分,积分步数只由
/// `now_ms` 决定,与帧率/调用间隔无关;同一 `now_ms` 序列逐位可重放。
#[derive(Clone, Debug)]
pub struct SpringTrack<T: Lerp> {
    from: T,
    to: T,
    position: f32,
    velocity: f32,
    spring: Spring,
    anchor_ms: u64,
    /// 从 `anchor_ms` 起已积分的**整步数**。积分只认整步、不认残步,
    /// 因此逐帧 tick 与跳帧 tick 推进的是同一串步长,结果与帧率严格无关。
    integrated_steps: u64,
    animating: bool,
    presented: T,
}

/// 固定积分步长(秒)。选 1/120 让 60fps 下每帧恰好两步,低帧率也按同步长补步。
const SPRING_STEP_S: f32 = 1.0 / 120.0;
/// 固定步长的毫秒表示,用于把 `now_ms` 量化到整步编号(避免浮点残步)。
const SPRING_STEP_MS: f64 = SPRING_STEP_S as f64 * 1000.0;
/// 收敛判定:位置与速度同时进入容差才吸附到目标,避免"位置到了但还在冲"。
const SPRING_EPS: f32 = 1e-3;

impl<T: Lerp> SpringTrack<T> {
    /// 以 `initial` 为初始呈现值创建静止轨道。
    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
    }

    /// 当前进度速度(1/s);供观测"retarget 保留速度"。
    pub fn velocity(&self) -> f32 {
        self.velocity
    }

    /// 从当前呈现值起,在 `now_ms` 时刻重定向到 `target`,**保留速度**。
    ///
    /// 先按 now_ms 结算当前呈现值与速度,再以当前值为新 `from` —— 与
    /// [`PropertyTrack::retarget`] 同为中断连续的来源,只是多带一份速度。
    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;
        }
    }

    /// 推进到 `now_ms`,返回结算后的呈现值。在 `State::tick` 里每帧调用一次。
    pub fn tick(&mut self, now_ms: u64) -> T {
        self.advance(now_ms);
        self.presented
    }

    /// 半隐式欧拉:先按当前位移/速度算加速度,再更新速度,最后用新速度更新位移。
    ///
    /// **绝对步编号**:目标步数 = `floor((now_ms - anchor_ms) / STEP_MS)`,只补
    /// `target - integrated_steps` 个整步,每步严格 `SPRING_STEP_S`。
    /// `anchor_ms` 只在 `retarget` 时重置,`advance` 永不改写 —— 于是不足一步的
    /// 时间余数留在总 elapsed 里累积:逐帧 30×10ms 与跳帧 1×300ms 得到同一串
    /// 整步,结果逐位相同(回放确定、与调用帧率无关)。
    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);
        }
    }
}

// =====================================================================
// Track —— 两种轨道的统一抽象(框架体系:同一套 widget 吃任意轨道实现)
// =====================================================================

/// 属性轨道的统一契约。
///
/// [`PropertyTrack`](时长 + 曲线、到点即停)与 [`SpringTrack`](带速度、可过冲)
/// 都实现它,widget/state 只依赖句柄 [`SharedTrack<T>`],不再为每种轨道复制
/// 一套 `AnimatedXxxWidget` —— 消灭"轨道类型 × 属性"的 N×M 样板。
///
/// `value_at`(无状态查询未来值)刻意不进 trait:只有曲线轨道有,弹簧按固定
/// 步积分、无法无状态预知;需要"立即读当前值"的路径统一走 `presented`。
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;
}

/// 统一轨道句柄:widget/state 只持有这个类型,底层是曲线轨道还是弹簧轨道
/// 由工厂函数决定,调用方无感。`Rc<RefCell<...>>` 与旧的共享句柄语义一致 —
/// widget 构造时创建、外部持有 clone 以在运行时 retarget。
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::*;

    /// 采样 spring 在 now_ms 序列上的 presented 值。
    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() {
        // 欠阻尼:c²=18²=324 < 4k=4×180=720 → 应越过目标再回弹。
        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() {
        // 临界阻尼:c = 2√k = 2√225 = 30 → c²=900=4k,不应过冲。
        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, "中途应有非零速度");

        // 在 t=300 反向:起点=当前呈现值,速度保留。
        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(), "带速度反向后仍在动");

        // 继续走会先凭惯性越过起点,再被弹簧拉回 0 —— 最终收敛。
        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() {
        // 细粒度逐帧 tick vs 一次性跳到终点:固定子步长从锚点重算,终点必须相同。
        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() {
        // 泛型:Point 分量各自弹簧。
        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);

        // Color 含 alpha 一起弹簧,过冲后收敛。
        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() {
        // 0 → 1,跑到 0.5 时改目标为 0.4:新段必须从 0.5 起,不能跳回 0.0。
        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 起点必须是当前呈现值");
        // 新段 500→1500 从 0.5 走向 0.4;1000ms 时走到一半 = 0.45
        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);
        // 3 → -3 最短弧是 +0.283...,中点 ≈ 3.14159(π),不是 0(绕远路)
        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);
        // 远超时长:必须钳制在 target,不 overshoot
        assert_eq!(track.tick(10_000), 1.0);
        assert!(!track.is_animating());
    }
}