Skip to main content

velox_engine/motion/
spring.rs

1//! 二阶阻尼谐振子物理弹簧动画(`Spring` / `SpringConfig`,100% `#![no_std]`、零堆、`Copy`)。
2//!
3//! 相比固定时长缓动曲线([`super::Tween`]),物理弹簧在目标频繁变化或中途打断时
4//! **自动继承当前瞬时速度 `velocity`**,带来丝滑自然的物理回弹与阻尼手感。
5
6use crate::svg::math::abs_f32;
7
8/// 物理弹簧刚度、阻尼与质量参数配置。
9#[derive(Copy, Clone, Debug)]
10pub struct SpringConfig {
11    /// 弹簧刚度系数 `k`(越大响应越迅速,默认 `220.0`)。
12    pub stiffness: f32,
13    /// 阻尼系数 `c`(越大过冲越少,默认 `24.0`)。
14    pub damping: f32,
15    /// 振子质量 `m`(越大惯性越强,默认 `1.0`)。
16    pub mass: f32,
17    /// 静止收敛阈值(位移差与速度均小于此阈值后锁定在目标值并进入 0% CPU 休眠)。
18    pub rest_eps: f32,
19}
20
21impl SpringConfig {
22    /// 柔和舒缓(抽屉/弹窗展开)。
23    pub const GENTLE: Self = Self {
24        stiffness: 120.0,
25        damping: 18.0,
26        mass: 1.0,
27        rest_eps: 0.05,
28    };
29    /// 均衡默认(开关/按钮/卡片过渡)。
30    pub const DEFAULT: Self = Self {
31        stiffness: 220.0,
32        damping: 24.0,
33        mass: 1.0,
34        rest_eps: 0.05,
35    };
36    /// 干脆利落(高刷桌面跟手切换)。
37    pub const SNAPPY: Self = Self {
38        stiffness: 380.0,
39        damping: 32.0,
40        mass: 1.0,
41        rest_eps: 0.05,
42    };
43    /// 富有弹性回弹(微交互/通知气泡)。
44    pub const BOUNCY: Self = Self {
45        stiffness: 260.0,
46        damping: 14.0,
47        mass: 1.0,
48        rest_eps: 0.05,
49    };
50    /// 高刚度无明显过冲(精确控件复位)。
51    pub const STIFF: Self = Self {
52        stiffness: 500.0,
53        damping: 42.0,
54        mass: 1.0,
55        rest_eps: 0.05,
56    };
57
58    #[inline(always)]
59    pub const fn new(stiffness: f32, damping: f32, mass: f32) -> Self {
60        Self {
61            stiffness,
62            damping,
63            mass,
64            rest_eps: 0.05,
65        }
66    }
67}
68
69impl Default for SpringConfig {
70    #[inline(always)]
71    fn default() -> Self {
72        Self::DEFAULT
73    }
74}
75
76/// 单自由度物理弹簧状态机(`Copy`,可直接嵌入 `View` 状态字段)。
77#[derive(Copy, Clone, Debug)]
78pub struct Spring {
79    value: f32,
80    velocity: f32,
81    target: f32,
82    config: SpringConfig,
83    settled: bool,
84}
85
86impl Spring {
87    /// 创建一个初始静止在 `initial` 处的物理弹簧。
88    #[inline(always)]
89    pub const fn new(initial: f32, config: SpringConfig) -> Self {
90        Self {
91            value: initial,
92            velocity: 0.0,
93            target: initial,
94            config,
95            settled: true,
96        }
97    }
98
99    /// 获取当前实时浮点值。
100    #[inline(always)]
101    pub const fn value(&self) -> f32 {
102        self.value
103    }
104
105    /// 获取四舍五入后的整型值(便于直接传入坐标/宽高/偏移)。
106    #[inline(always)]
107    pub fn value_i32(&self) -> i32 {
108        if self.value >= 0.0 {
109            (self.value + 0.5) as i32
110        } else {
111            (self.value - 0.5) as i32
112        }
113    }
114
115    /// 获取当前瞬时速度(单位/秒)。
116    #[inline(always)]
117    pub const fn velocity(&self) -> f32 {
118        self.velocity
119    }
120
121    /// 获取当前目标值。
122    #[inline(always)]
123    pub const fn target(&self) -> f32 {
124        self.target
125    }
126
127    /// 弹簧是否已完全收敛静止(静止后可停止调用 `cx.request_frame()` 进入 0% CPU 休眠)。
128    #[inline(always)]
129    pub const fn is_settled(&self) -> bool {
130        self.settled
131    }
132
133    /// 弹簧是否仍在运动中。
134    #[inline(always)]
135    pub const fn is_running(&self) -> bool {
136        !self.settled
137    }
138
139    /// 平滑更改目标值(自动保留当前瞬时速度 `velocity`,打断进行中的动画绝不突变)。
140    #[inline]
141    pub fn animate_to(&mut self, target: f32) {
142        if abs_f32(target - self.target) <= 1e-6 && self.settled {
143            return;
144        }
145        self.target = target;
146        self.settled = false;
147    }
148
149    /// 对弹簧施加一个瞬时速度冲量(例如松手惯性甩动或弹性点击反馈)。
150    #[inline]
151    pub fn impulse(&mut self, delta_velocity: f32) {
152        self.velocity += delta_velocity;
153        if abs_f32(self.velocity) > self.config.rest_eps {
154            self.settled = false;
155        }
156    }
157
158    /// 直接设置瞬时速度(单位/秒)。
159    #[inline]
160    pub fn set_velocity(&mut self, velocity: f32) {
161        self.velocity = velocity;
162        if abs_f32(self.velocity) > self.config.rest_eps {
163            self.settled = false;
164        }
165    }
166
167    /// 动态更新弹簧物理参数(刚度、阻尼、质量),不打断当前位移与速度。
168    #[inline(always)]
169    pub fn set_config(&mut self, config: SpringConfig) {
170        self.config = config;
171    }
172
173    /// 立即跳转至指定值并清零速度。
174    #[inline(always)]
175    pub fn jump_to(&mut self, value: f32) {
176        self.value = value;
177        self.target = value;
178        self.velocity = 0.0;
179        self.settled = true;
180    }
181
182    /// 以毫秒步长 `dt_ms` 推进弹簧物理积分(内部自动拆分 `<= 4ms` 子步长保证高刚度数值绝对稳定)。
183    pub fn step(&mut self, dt_ms: u16) -> f32 {
184        if self.settled || dt_ms == 0 {
185            return self.value;
186        }
187        // 将大帧间隔钳位在 100ms 内,避免后台切回造成爆炸位移
188        let total_s = (dt_ms.min(100) as f32) * 0.001;
189        let max_sub_s = 0.004f32;
190        let sub_steps = ((total_s / max_sub_s) as u32).max(1);
191        let h = total_s / (sub_steps as f32);
192        let inv_m = 1.0 / self.config.mass.max(0.01);
193        let k = self.config.stiffness.max(1.0);
194        let c = self.config.damping.max(0.1);
195
196        for _ in 0..sub_steps {
197            let disp = self.value - self.target;
198            let accel = (-k * disp - c * self.velocity) * inv_m;
199            // 半隐式欧拉(Symplectic Euler):能量守恒性极佳,不会发散振荡
200            self.velocity += accel * h;
201            self.value += self.velocity * h;
202        }
203
204        let eps = self.config.rest_eps.max(1e-4);
205        if abs_f32(self.value - self.target) <= eps && abs_f32(self.velocity) <= eps * 10.0 {
206            self.value = self.target;
207            self.velocity = 0.0;
208            self.settled = true;
209        }
210        self.value
211    }
212}