Skip to main content

mgui_core/
animation.rs

1//! 动画系统 —— 原 mgui-animation crate,已合入 mgui-core
2//!
3//! 分层:
4//! - **core(本模块)**: 纯逻辑的 `AnimationController` — 时间驱动、无时钟、
5//!   无副作用。app/runtime 提供 `now_ms`(winit 事件循环 / AboutToWait),
6//!   每帧调 `tick(now_ms)` 拿插值,写进 `Signal` 后由响应式系统触发 rebuild。
7//! - **runtime/app**: 持有 controller,在 `AboutToWait` 里 tick →
8//!   `Signal::set` → request_redraw(见 showcase 的自动旋转演示)。
9//!
10//! 设计取舍:
11//! - **不引入独立 Ticker trait** — winit 的 redraw 循环就是天然的 ticker,
12//!   controller 的 `is_animating()` 决定是否继续请求下一帧。
13//! - **状态机不依赖外部时钟源** — `forward(now_ms)` 记录起始时刻,
14//!   `tick(now_ms)` 按时间差推进,暂停/恢复语义清晰。
15//! - **曲线纯函数** — `Curve::transform(t)` 可独立单测。
16
17use std::fmt::Debug;
18
19/// 缓动曲线(输入输出均为 0..1)
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
21pub enum Curve {
22    /// 匀速
23    #[default]
24    Linear,
25    /// 先慢后快(二次)
26    EaseIn,
27    /// 先快后慢(二次)
28    EaseOut,
29    /// 慢-快-慢(平滑对称,3t²-2t³)
30    EaseInOut,
31}
32
33impl Curve {
34    /// 把线性进度 t(0..1)映射为缓动后进度(0..1)
35    ///
36    /// 输入会被 clamp 到 0..1,输出天然落在 0..1。
37    pub fn transform(&self, t: f32) -> f32 {
38        let t = t.clamp(0.0, 1.0);
39        match self {
40            Curve::Linear => t,
41            Curve::EaseIn => t * t,
42            Curve::EaseOut => 1.0 - (1.0 - t) * (1.0 - t),
43            Curve::EaseInOut => t * t * (3.0 - 2.0 * t),
44        }
45    }
46}
47
48/// 动画状态
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum AnimationStatus {
51    /// 未启动(值停在起始端)
52    Dismissed,
53    /// 正向播放中
54    Forward,
55    /// 反向播放中
56    Reverse,
57    /// 播放完成(值停在结束端)
58    Completed,
59}
60
61/// 重复模式
62#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
63pub enum Repeat {
64    /// 播一次就停(status → Completed)
65    #[default]
66    None,
67    /// 到头后从头再来(循环)
68    Loop,
69    /// 到头后反向播放(0→1→0→1…,适合呼吸/摆动效果)
70    PingPong,
71}
72
73/// `tick()` 的推进结果
74#[derive(Clone, Copy, Debug, PartialEq)]
75pub enum TickOutcome {
76    /// 产生新插值(controller 已按 now_ms 推进)
77    Value(f32),
78    /// 本轮(含重复)播放完成,不再产生新值
79    Finished,
80    /// 未在播放(Dismissed / Completed),无值
81    Idle,
82}
83
84/// 时间驱动的动画控制器
85///
86/// 纯逻辑:不持有时钟、不触发副作用。典型用法(runtime 侧):
87///
88/// ```ignore
89/// let mut ctrl = AnimationController::new(3000)
90///     .with_curve(Curve::EaseInOut)
91///     .with_repeat(Repeat::Loop);
92/// ctrl.forward(now_ms());
93/// // 每帧:
94/// if let TickOutcome::Value(t) = ctrl.tick(now_ms()) {
95///     hue.set(t);           // 响应式 → rebuild → 重画
96///     window.request_redraw();
97/// }
98/// ```
99///
100/// `value(now_ms)` 是无状态查询(不推进 status),适合 hit_test / 立即绘制。
101///
102/// 内部用 **锚点模型**:`anchor_ms` 时刻的线性进度为 `anchor_progress`,
103/// 之后按播放方向推进。forward/reverse 可在任意时刻无缝切换
104/// (切换即重新锚定到当前进度),不依赖可回退的时钟。
105pub struct AnimationController {
106    duration_ms: u64,
107    curve: Curve,
108    repeat: Repeat,
109    status: AnimationStatus,
110    /// 锚点时刻(ms):此刻的线性进度 = anchor_progress
111    anchor_ms: u64,
112    /// 锚点进度(正向语义 0..1)
113    anchor_progress: f32,
114    /// status 转换时的回调(可选,fire at every Forward/Reverse/Completed/Dismissed 切换)
115    on_status_changed: Option<Box<dyn FnMut(AnimationStatus)>>,
116}
117
118impl std::fmt::Debug for AnimationController {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        f.debug_struct("AnimationController")
121            .field("duration_ms", &self.duration_ms)
122            .field("curve", &self.curve)
123            .field("repeat", &self.repeat)
124            .field("status", &self.status)
125            .field("anchor_ms", &self.anchor_ms)
126            .field("anchor_progress", &self.anchor_progress)
127            .field("has_callback", &self.on_status_changed.is_some())
128            .finish()
129    }
130}
131
132impl AnimationController {
133    pub fn new(duration_ms: u64) -> Self {
134        Self {
135            duration_ms: duration_ms.max(1),
136            curve: Curve::default(),
137            repeat: Repeat::default(),
138            status: AnimationStatus::Dismissed,
139            anchor_ms: 0,
140            anchor_progress: 0.0,
141            on_status_changed: None,
142        }
143    }
144
145    pub fn with_curve(mut self, curve: Curve) -> Self {
146        self.curve = curve;
147        self
148    }
149
150    pub fn with_repeat(mut self, repeat: Repeat) -> Self {
151        self.repeat = repeat;
152        self
153    }
154
155    pub fn with_on_status_changed(mut self, cb: impl FnMut(AnimationStatus) + 'static) -> Self {
156        self.on_status_changed = Some(Box::new(cb));
157        self
158    }
159
160    /// 私有:统一 status 赋值入口。每次转换都 fire callback。
161    fn set_status(&mut self, new_status: AnimationStatus) {
162        if self.status != new_status {
163            self.status = new_status;
164            if let Some(cb) = self.on_status_changed.as_mut() {
165                cb(new_status);
166            }
167        }
168    }
169
170    pub fn status(&self) -> AnimationStatus {
171        self.status
172    }
173
174    /// 是否在播放(AboutToWait 里决定要不要 request_redraw)
175    pub fn is_animating(&self) -> bool {
176        matches!(self.status, AnimationStatus::Forward | AnimationStatus::Reverse)
177    }
178
179    pub fn curve(&self) -> Curve {
180        self.curve
181    }
182
183    pub fn repeat(&self) -> Repeat {
184        self.repeat
185    }
186
187    pub fn duration_ms(&self) -> u64 {
188        self.duration_ms
189    }
190
191    /// 从当前进度正向播放(Dismissed/Completed → 从 0 重新开始)
192    pub fn forward(&mut self, now_ms: u64) {
193        match self.status {
194            AnimationStatus::Reverse => self.reanchor(now_ms),
195            AnimationStatus::Dismissed | AnimationStatus::Completed => {
196                self.anchor_ms = now_ms;
197                self.anchor_progress = 0.0;
198            }
199            AnimationStatus::Forward => {}
200        }
201        self.set_status(AnimationStatus::Forward);
202    }
203
204    /// 从当前进度反向播放(Dismissed → 立即结束;Completed → 从 1 往回)
205    pub fn reverse(&mut self, now_ms: u64) {
206        match self.status {
207            AnimationStatus::Forward => self.reanchor(now_ms),
208            AnimationStatus::Completed => {
209                self.anchor_ms = now_ms;
210                self.anchor_progress = 1.0;
211            }
212            AnimationStatus::Dismissed | AnimationStatus::Reverse => {}
213        }
214        self.set_status(AnimationStatus::Reverse);
215    }
216
217    /// 立即停止;tick 之后返回 Idle(value 冻结在当前端点语义)
218    pub fn stop(&mut self) {
219        self.set_status(match self.status {
220            AnimationStatus::Completed => AnimationStatus::Completed,
221            _ => AnimationStatus::Dismissed,
222        });
223    }
224
225    /// 把锚点移到 now_ms,进度取当前原始进度(无缝换向的关键)
226    fn reanchor(&mut self, now_ms: u64) {
227        let p = self.raw_progress(now_ms);
228        // Repeat::None 的值域语义是 [0,1](linear_progress/value 均钳制);
229        // 若调用方未逐帧 tick,raw 会 overshoot(如 forward 后长时间未 tick),
230        // 不钳制会导致换向后的播放时长被放大(反向从 2.5 回到 0)。
231        // Loop/PingPong 保留原始进度以维持相位连续。
232        self.anchor_progress = if self.repeat == Repeat::None { p.clamp(0.0, 1.0) } else { p };
233        self.anchor_ms = now_ms;
234    }
235
236    /// 无状态查询当前插值(0..1,已过曲线;不播放时返回端点值)
237    pub fn value(&self, now_ms: u64) -> f32 {
238        if !self.is_animating() {
239            return match self.status {
240                AnimationStatus::Completed => 1.0,
241                _ => 0.0,
242            };
243        }
244        let linear = match self.repeat {
245            Repeat::None => self.linear_progress(now_ms),
246            Repeat::Loop => self.loop_phase(now_ms).rem_euclid(1.0),
247            Repeat::PingPong => {
248                let phase = self.loop_phase(now_ms).rem_euclid(2.0);
249                if phase <= 1.0 {
250                    phase
251                } else {
252                    2.0 - phase
253                }
254            }
255        };
256        self.curve.transform(linear)
257    }
258
259    /// 推进状态机到 now_ms,返回本轮结果。
260    pub fn tick(&mut self, now_ms: u64) -> TickOutcome {
261        if !self.is_animating() {
262            return TickOutcome::Idle;
263        }
264        let progress = self.raw_progress(now_ms);
265        match self.repeat {
266            Repeat::None => {
267                let done = if self.status == AnimationStatus::Forward { progress >= 1.0 } else { progress <= 0.0 };
268                if done {
269                    let terminal = if self.status == AnimationStatus::Forward {
270                        AnimationStatus::Completed
271                    } else {
272                        AnimationStatus::Dismissed
273                    };
274                    self.set_status(terminal);
275                    TickOutcome::Finished
276                } else {
277                    TickOutcome::Value(self.curve.transform(progress.clamp(0.0, 1.0)))
278                }
279            }
280            Repeat::Loop => {
281                // rem_euclid:Reverse 时 loop_phase 为负,fract() 也返回负数,
282                // 会被 curve.transform 的 clamp 吞成 0(反向循环永远停在起点)。
283                let phase = self.loop_phase(now_ms).rem_euclid(1.0);
284                TickOutcome::Value(self.curve.transform(phase))
285            }
286            Repeat::PingPong => {
287                let phase = self.loop_phase(now_ms).rem_euclid(2.0);
288                let p = if phase <= 1.0 { phase } else { 2.0 - phase };
289                TickOutcome::Value(self.curve.transform(p.clamp(0.0, 1.0)))
290            }
291        }
292    }
293
294    /// 循环模式的无界相位(轮数可 >1;Reverse 为负方向)
295    fn loop_phase(&self, now_ms: u64) -> f32 {
296        let dt = now_ms.saturating_sub(self.anchor_ms) as f32 / self.duration_ms as f32;
297        match self.status {
298            AnimationStatus::Reverse => self.anchor_progress - dt,
299            _ => self.anchor_progress + dt,
300        }
301    }
302
303    /// 原始线性进度(有符号;Reverse 时随时间递减)
304    fn raw_progress(&self, now_ms: u64) -> f32 {
305        let dt = now_ms.saturating_sub(self.anchor_ms) as f32 / self.duration_ms as f32;
306        match self.status {
307            AnimationStatus::Reverse => self.anchor_progress - dt,
308            AnimationStatus::Forward => self.anchor_progress + dt,
309            AnimationStatus::Dismissed => 0.0,
310            AnimationStatus::Completed => 1.0,
311        }
312    }
313
314    fn linear_progress(&self, now_ms: u64) -> f32 {
315        self.raw_progress(now_ms).clamp(0.0, 1.0)
316    }
317}
318
319// =================================================================
320// State 集成帮助:tick_animation(可选,一行代码让 State 自动推进)
321// =================================================================
322//
323// 框架已经在 `ElementTree::tick_states(root, now_ms)` 每帧调每个 State 的
324// `state.tick(now_ms)`,所以 State 里持有的 AnimationController 可以直接
325// 在 tick 里被推进。
326//
327// 用法示例:State 持有 controller + Signal
328// ```ignore
329// fn tick(&mut self, now_ms: u64) {
330//     tick_animation(&mut self.controller, now_ms, |t| { self.value.set(t); });
331// }
332// fn is_animating(&self) -> bool { self.controller.is_animating() }
333// ```
334//
335// `tick_animation` 同时返回 `controller.is_animating()`,方便 `is_animating()`
336// 实现直接 return:
337// ```ignore
338// fn tick(&mut self, now_ms: u64) -> bool {
339//     tick_animation(&mut self.controller, now_ms, |t| { self.value.set(t); })
340// }
341// ```
342
343/// 对一个 `AnimationController` 调 `tick(now_ms)`,
344/// 若产生 `Value(t)` 则把 t 传给 `on_value` 闭包(通常写 Signal)。
345///
346/// 返回值:`controller.is_animating()`(方便 `is_animating()` 实现直接 return)
347pub fn tick_animation(controller: &mut AnimationController, now_ms: u64, mut on_value: impl FnMut(f32)) -> bool {
348    if let TickOutcome::Value(t) = controller.tick(now_ms) {
349        on_value(t);
350    }
351    controller.is_animating()
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    /// Reverse + Loop:phase 变负时必须回绕(此前 fract() 负值被 clamp 成 0)
359    #[test]
360    fn reverse_loop_wraps_negative_phase() {
361        let mut c = AnimationController::new(1000).with_repeat(Repeat::Loop);
362        c.forward(0);
363        c.tick(500);
364        c.reverse(500);
365        // anchor_progress=0.5,1200ms 时 phase = 0.5 - 0.7 = -0.2 → 0.8
366        match c.tick(1200) {
367            TickOutcome::Value(v) => assert!((v - 0.8).abs() < 1e-4, "phase -0.2 应回绕到 0.8,实际 {v}"),
368            other => panic!("expected Value, got {other:?}"),
369        }
370        assert!((c.value(1200) - 0.8).abs() < 1e-4, "value() 也应回绕");
371    }
372
373    #[test]
374    fn ping_pong_reverse_wraps() {
375        let mut c = AnimationController::new(1000).with_repeat(Repeat::PingPong);
376        c.forward(0);
377        c.tick(500);
378        c.reverse(500);
379        // phase = -0.2 → rem_euclid(2) = 1.8 → 2-1.8 = 0.2
380        match c.tick(1200) {
381            TickOutcome::Value(v) => assert!((v - 0.2).abs() < 1e-4, "expected 0.2, got {v}"),
382            other => panic!("expected Value, got {other:?}"),
383        }
384    }
385}