Skip to main content

nativeview_physics/
spring.rs

1//! Closed-form, unconditionally stable damped harmonic oscillator spring physics
2//! ([`SpringSpec`], [`SpringState`]).
3//!
4//! All three physical damping regimes (under-damped, critically-damped, over-damped) are solved
5//! analytically in `f64` so arbitrary frame deltas (`1ms`, `8.3ms`, `16.6ms`, or a `250ms` hitch)
6//! never diverge, explode, or drift, while mid-flight [`SpringState::retarget`] preserves exact
7//! live velocity.
8
9use std::f64::consts::TAU;
10
11use crate::{non_negative_or, positive_or};
12
13/// Default positional threshold below which a spring is considered settled.
14pub const DEFAULT_REST_DISPLACEMENT: f32 = 1e-3;
15/// Default velocity threshold (units/sec) below which a spring is considered settled.
16pub const DEFAULT_REST_VELOCITY: f32 = 1e-3;
17
18const MIN_MASS: f64 = 1e-4;
19const MIN_STIFFNESS: f64 = 1e-4;
20const MIN_OMEGA: f64 = 1e-2;
21const MAX_OMEGA: f64 = 1e18;
22const MIN_RESPONSE_S: f64 = 0.01;
23const MAX_RESPONSE_S: f64 = 600.0;
24const MAX_DAMPING_RATIO: f64 = 1e10;
25const CRITICAL_EPS: f64 = 1e-6;
26
27/// Physical spring parameters for an interruptible damped harmonic oscillator.
28#[derive(Debug, Clone, Copy, PartialEq)]
29pub struct SpringSpec {
30    pub stiffness: f32,
31    pub damping: f32,
32    pub mass: f32,
33    pub rest_displacement: f32,
34    pub rest_velocity: f32,
35}
36
37impl Default for SpringSpec {
38    #[inline]
39    fn default() -> Self {
40        Self::snappy()
41    }
42}
43
44impl SpringSpec {
45    /// Creates a sanitized [`SpringSpec`] with default settle thresholds.
46    #[inline]
47    pub fn new(stiffness: f32, damping: f32, mass: f32) -> Self {
48        Self {
49            stiffness: positive_or(stiffness, 400.0),
50            damping: non_negative_or(damping, 30.0),
51            mass: positive_or(mass, 1.0),
52            rest_displacement: DEFAULT_REST_DISPLACEMENT,
53            rest_velocity: DEFAULT_REST_VELOCITY,
54        }
55    }
56
57    /// Compile-time constructor for static/const spring presets using default rest thresholds.
58    ///
59    /// Invalid or non-finite values are still sanitized on evaluation by [`SpringState::step`].
60    #[inline]
61    pub const fn from_raw(stiffness: f32, damping: f32, mass: f32) -> Self {
62        Self {
63            stiffness,
64            damping,
65            mass,
66            rest_displacement: DEFAULT_REST_DISPLACEMENT,
67            rest_velocity: DEFAULT_REST_VELOCITY,
68        }
69    }
70
71    /// Configures custom position and velocity settle thresholds.
72    #[inline]
73    pub fn with_rest_thresholds(mut self, displacement: f32, velocity: f32) -> Self {
74        self.rest_displacement = positive_or(displacement, DEFAULT_REST_DISPLACEMENT);
75        self.rest_velocity = positive_or(velocity, DEFAULT_REST_VELOCITY);
76        self
77    }
78
79    /// Crisp, responsive UI spring (slight underdamping, `zeta ~ 0.75`).
80    #[inline]
81    pub const fn snappy() -> Self {
82        Self::from_raw(400.0, 30.0, 1.0)
83    }
84
85    /// Smooth, low-overshoot spring for larger layout or sheet transitions (`zeta ~ 0.91`).
86    #[inline]
87    pub const fn gentle() -> Self {
88        Self::from_raw(120.0, 20.0, 1.0)
89    }
90
91    /// Expressive, bouncy spring with pronounced overshoot (`zeta ~ 0.39`).
92    #[inline]
93    pub const fn bouncy() -> Self {
94        Self::from_raw(320.0, 14.0, 1.0)
95    }
96
97    /// Fast, nearly critically damped spring with virtually zero overshoot (`zeta ~ 0.98`).
98    #[inline]
99    pub const fn stiff() -> Self {
100        Self::from_raw(600.0, 48.0, 1.0)
101    }
102
103    /// Critically damped spring (`zeta = 1.0`, `mass = 1.0`) from natural angular frequency
104    /// `omega` in rad/s (`stiffness = omega^2`, `damping = 2 * omega`, clamped to
105    /// `[1e-2, 1e18]` so `stiffness` never overflows `f32` or underflows `MIN_STIFFNESS`).
106    #[inline]
107    pub fn from_omega(omega: f32) -> Self {
108        let w = f64::from(positive_or(omega, 20.0)).clamp(MIN_OMEGA, MAX_OMEGA);
109        Self {
110            stiffness: (w * w) as f32,
111            damping: (2.0 * w) as f32,
112            mass: 1.0,
113            rest_displacement: DEFAULT_REST_DISPLACEMENT,
114            rest_velocity: DEFAULT_REST_VELOCITY,
115        }
116    }
117
118    /// Parameterizes a unit-mass spring from dimensionless `damping_ratio` (`zeta`, where `1.0` is
119    /// critically damped, `< 1.0` under-damped, `> 1.0` over-damped) and undamped natural period
120    /// `response_s` in seconds (clamped to `[0.01, 600.0]`).
121    #[inline]
122    pub fn from_damping_ratio(damping_ratio: f32, response_s: f32) -> Self {
123        let response = if response_s.is_finite() && response_s > 0.0 {
124            f64::from(response_s).clamp(MIN_RESPONSE_S, MAX_RESPONSE_S)
125        } else {
126            0.35
127        };
128        let zeta = f64::from(non_negative_or(damping_ratio, 1.0)).min(MAX_DAMPING_RATIO);
129        let omega0 = TAU / response;
130        Self {
131            stiffness: (omega0 * omega0) as f32,
132            damping: (2.0 * zeta * omega0) as f32,
133            mass: 1.0,
134            rest_displacement: DEFAULT_REST_DISPLACEMENT,
135            rest_velocity: DEFAULT_REST_VELOCITY,
136        }
137    }
138
139    /// Apple SwiftUI-style intuitive spring parameterization:
140    ///
141    /// - `duration_s`: perceptual settle duration in seconds (clamped to `[0.01, 600.0]`).
142    /// - `bounce`: bounciness in `[-1.0, 1.0]` (`0.0` = critically damped, `> 0.0` = underdamped
143    ///   with overshoot, `< 0.0` = overdamped). Clamped internally to `[-0.95, 0.99]` so damping
144    ///   stays strictly positive and finite.
145    pub fn from_duration_bounce(duration_s: f32, bounce: f32) -> Self {
146        let duration = if duration_s.is_finite() && duration_s > 0.0 {
147            f64::from(duration_s).clamp(MIN_RESPONSE_S, MAX_RESPONSE_S)
148        } else {
149            0.35
150        };
151        let b = if bounce.is_finite() {
152            f64::from(bounce).clamp(-0.95, 0.99)
153        } else {
154            0.0
155        };
156        let omega0 = TAU / duration;
157        let stiffness = omega0 * omega0;
158        let damping = if b >= 0.0 {
159            2.0 * omega0 * (1.0 - b)
160        } else {
161            2.0 * omega0 / (1.0 + b)
162        };
163        Self {
164            stiffness: stiffness as f32,
165            damping: damping as f32,
166            mass: 1.0,
167            rest_displacement: DEFAULT_REST_DISPLACEMENT,
168            rest_velocity: DEFAULT_REST_VELOCITY,
169        }
170    }
171
172    /// Sanitized physical `(mass, stiffness, damping)` in `f64` — the single source every derived
173    /// quantity and [`SpringState::step`] use (invalid/non-finite values fall back to
174    /// [`SpringSpec::new`]'s [`SpringSpec::snappy`] defaults).
175    #[inline]
176    fn physical(&self) -> (f64, f64, f64) {
177        (
178            f64::from(positive_or(self.mass, 1.0)).max(MIN_MASS),
179            f64::from(positive_or(self.stiffness, 400.0)).max(MIN_STIFFNESS),
180            f64::from(non_negative_or(self.damping, 30.0)),
181        )
182    }
183
184    /// Natural angular frequency `omega_0 = sqrt(stiffness / mass)` in rad/s.
185    #[inline]
186    pub fn angular_frequency(&self) -> f32 {
187        let (m, k, _) = self.physical();
188        (k / m).sqrt() as f32
189    }
190
191    /// Dimensionless damping ratio `zeta = damping / (2 * sqrt(stiffness * mass))`.
192    /// `< 1` is underdamped, `== 1` is critically damped, `> 1` is overdamped.
193    #[inline]
194    pub fn damping_ratio(&self) -> f32 {
195        let (m, k, c) = self.physical();
196        (c / (2.0 * (k * m).sqrt())) as f32
197    }
198
199    /// Time in seconds for a step response envelope to stay within `0.1 %` (`1e-3`) of its
200    /// target, continuous across all damping ratios `zeta` (including `zeta == 1`) and clamped
201    /// to `[0.01, 10]`.
202    pub fn settle_duration_s(&self) -> f32 {
203        const LN_1E3: f64 = 6.907_755_278_982_137;
204        const MIN_SECS: f64 = 0.01;
205        const MAX_SECS: f64 = 10.0;
206        let (m, k, c) = self.physical();
207        let omega = (k / m).sqrt();
208        let zeta = c / (2.0 * (k * m).sqrt());
209        if zeta <= 0.0 {
210            return MAX_SECS as f32;
211        }
212        let max_tau = MAX_SECS * omega;
213        let tau = if zeta < 1.0 {
214            // Smooth, globally log-concave upper envelope matching `(1 + tau) e^-tau` at
215            // `zeta -> 1-` with near-matched slope:
216            // `E(tau) = e^(-zeta * tau) * (1 + zeta * tau / sqrt(1 + 0.5 * (1 - zeta^2) * tau^2))`.
217            let tau0 = LN_1E3 / zeta;
218            if tau0 >= max_tau {
219                return MAX_SECS as f32;
220            }
221            let d2 = 0.5 * (1.0 - zeta * zeta);
222            let mut tau = tau0;
223            for _ in 0..8 {
224                let denom = (1.0 + d2 * tau * tau).sqrt();
225                let q = zeta * tau / denom;
226                let g = -zeta * tau + (1.0 + q).ln() + LN_1E3;
227                if g.abs() < 1e-12 {
228                    break;
229                }
230                let dq = zeta / (denom * denom * denom);
231                let dg = -zeta + dq / (1.0 + q);
232                if !dg.is_finite() || dg >= 0.0 {
233                    break;
234                }
235                tau -= g / dg;
236            }
237            tau
238        } else {
239            // Exact overdamped / critically damped step response magnitude:
240            // `f(tau) = e^(-r1 * tau) * (0.5 * (1 + e^(-2 s tau)) + zeta * tau * phi(2 s tau))`
241            // with `s = sqrt(zeta^2 - 1)`, `r1 = 1 / (zeta + s)`, `phi(u) = (1 - e^-u) / u`.
242            let s = (zeta * zeta - 1.0).sqrt();
243            let r1 = 1.0 / (zeta + s);
244            let tau0 = LN_1E3 / r1;
245            if tau0 >= max_tau {
246                return MAX_SECS as f32;
247            }
248            let mut tau = tau0;
249            for _ in 0..8 {
250                let u = 2.0 * s * tau;
251                let exp_neg_u = (-u).exp();
252                let phi = if u > 1e-12 { -(-u).exp_m1() / u } else { 1.0 - 0.5 * u };
253                let amp = 0.5 * (1.0 + exp_neg_u) + zeta * tau * phi;
254                let g = -r1 * tau + amp.ln() + LN_1E3;
255                if g.abs() < 1e-12 {
256                    break;
257                }
258                let dg = -(tau * phi) / amp;
259                if !dg.is_finite() || dg >= 0.0 {
260                    break;
261                }
262                tau -= g / dg;
263            }
264            tau
265        };
266        (tau / omega).clamp(MIN_SECS, MAX_SECS) as f32
267    }
268}
269
270/// Live scalar spring state (`value`, `velocity`, `target`).
271#[derive(Debug, Clone, Copy, Default, PartialEq)]
272pub struct SpringState {
273    pub value: f32,
274    pub velocity: f32,
275    pub target: f32,
276}
277
278impl SpringState {
279    /// Creates an already-settled spring at `value` (`velocity = 0.0`, `target = value`).
280    #[inline]
281    pub const fn settled(value: f32) -> Self {
282        Self {
283            value,
284            velocity: 0.0,
285            target: value,
286        }
287    }
288
289    /// Creates a spring starting at `value` with zero initial velocity moving toward `target`.
290    #[inline]
291    pub const fn new(value: f32, target: f32) -> Self {
292        Self {
293            value,
294            velocity: 0.0,
295            target,
296        }
297    }
298
299    /// Creates a spring with explicit initial `value`, `velocity`, and `target`.
300    #[inline]
301    pub const fn with_velocity(value: f32, velocity: f32, target: f32) -> Self {
302        Self {
303            value,
304            velocity,
305            target,
306        }
307    }
308
309    /// Retargets this spring mid-flight to `new_target` while preserving exact `value` and
310    /// `velocity` (zero jump, full physical momentum conservation).
311    #[inline]
312    pub fn retarget(&mut self, new_target: f32) {
313        if new_target.is_finite() {
314            self.target = new_target;
315        }
316    }
317
318    /// Snaps immediately to `target` with zero velocity.
319    #[inline]
320    pub fn snap_to_target(&mut self) {
321        if !self.target.is_finite() {
322            self.target = 0.0;
323        }
324        self.value = self.target;
325        self.velocity = 0.0;
326    }
327
328    /// Returns `true` when displacement from `target` and velocity are both within `spec`'s
329    /// rest thresholds, allowing hosts/display-links to drop to 0% idle CPU/GPU.
330    #[inline]
331    pub fn is_settled(&self, spec: &SpringSpec) -> bool {
332        if !self.value.is_finite() || !self.velocity.is_finite() || !self.target.is_finite() {
333            return true;
334        }
335        let rest_d = positive_or(spec.rest_displacement, DEFAULT_REST_DISPLACEMENT);
336        let rest_v = positive_or(spec.rest_velocity, DEFAULT_REST_VELOCITY);
337        (self.value - self.target).abs() <= rest_d && self.velocity.abs() <= rest_v
338    }
339
340    /// Evaluates the closed-form displacement `(x, v)` relative to `target` at elapsed time `t`
341    /// in `f64`, returning `(displacement, velocity, omega0)`.
342    #[inline]
343    fn evaluate_f64(spec: &SpringSpec, x0: f64, v0: f64, t: f64) -> (f64, f64, f64) {
344        let (m, k, c) = spec.physical();
345        let omega0 = (k / m).sqrt();
346        let zeta = c / (2.0 * (k * m).sqrt());
347
348        let (x, v) = if zeta < 1.0 - CRITICAL_EPS {
349            // Underdamped: decaying sinusoid.
350            let alpha = zeta * omega0;
351            let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
352            let decay = (-alpha * t).exp();
353            let a = x0;
354            let b = (v0 + alpha * x0) / omega_d;
355            let (sin_wt, cos_wt) = (omega_d * t).sin_cos();
356            let x = decay * (a * cos_wt + b * sin_wt);
357            let v = decay
358                * ((b * omega_d - a * alpha) * cos_wt - (a * omega_d + b * alpha) * sin_wt);
359            (x, v)
360        } else if (zeta - 1.0).abs() <= CRITICAL_EPS {
361            // Critically damped: fastest monotonic settle with zero oscillation.
362            let decay = (-omega0 * t).exp();
363            let a = x0;
364            let b = v0 + omega0 * x0;
365            let x = decay * (a + b * t);
366            let v = decay * (b - omega0 * (a + b * t));
367            (x, v)
368        } else {
369            // Overdamped: sum of two strictly negative real exponentials.
370            // Rationalize r1 to avoid catastrophic cancellation at high damping ratios.
371            let sqrt_term = (zeta * zeta - 1.0).sqrt();
372            let gamma = omega0 * sqrt_term;
373            let r1 = -omega0 / (zeta + sqrt_term);
374            let r2 = -omega0 * (zeta + sqrt_term);
375            let inv_2gamma = 0.5 / gamma;
376            let c1 = (v0 - r2 * x0) * inv_2gamma;
377            let c2 = (r1 * x0 - v0) * inv_2gamma;
378            let e1 = (r1 * t).exp();
379            let e2 = (r2 * t).exp();
380            let x = c1 * e1 + c2 * e2;
381            let v = c1 * r1 * e1 + c2 * r2 * e2;
382            (x, v)
383        };
384        (x, v, omega0)
385    }
386
387    /// Evaluates `(value, velocity)` after `dt_s` seconds without mutating `self`.
388    #[inline]
389    pub fn evaluate(&self, spec: &SpringSpec, dt_s: f32) -> (f32, f32) {
390        let target = if self.target.is_finite() { self.target } else { 0.0 };
391        if !self.value.is_finite() || !self.velocity.is_finite() {
392            return (target, 0.0);
393        }
394        if !dt_s.is_finite() || dt_s <= 0.0 {
395            return (self.value, self.velocity);
396        }
397        let target_f64 = f64::from(target);
398        let x0 = f64::from(self.value) - target_f64;
399        let v0 = f64::from(self.velocity);
400        let (x, v, _) = Self::evaluate_f64(spec, x0, v0, f64::from(dt_s));
401        let next_val = (target_f64 + x) as f32;
402        let next_vel = v as f32;
403        if !next_val.is_finite() || !next_vel.is_finite() {
404            (target, 0.0)
405        } else {
406            (next_val, next_vel)
407        }
408    }
409
410    /// Advances the spring analytically by `dt_s` seconds under `spec`, snapping cleanly to
411    /// `(target, 0.0)` once settled. Returns `true` when settled after this step.
412    pub fn step(&mut self, spec: &SpringSpec, dt_s: f32) -> bool {
413        if !self.target.is_finite() {
414            self.target = 0.0;
415        }
416        if !self.value.is_finite() || !self.velocity.is_finite() {
417            self.snap_to_target();
418            return true;
419        }
420        if self.is_settled(spec) {
421            self.snap_to_target();
422            return true;
423        }
424        if !dt_s.is_finite() || dt_s <= 0.0 {
425            return false;
426        }
427
428        let target = f64::from(self.target);
429        let x0 = f64::from(self.value) - target;
430        let v0 = f64::from(self.velocity);
431        let (x, v, omega0) = Self::evaluate_f64(spec, x0, v0, f64::from(dt_s));
432
433        let prev_val = self.value;
434        let next_val = (target + x) as f32;
435        let next_vel = v as f32;
436        if !next_val.is_finite() || !next_vel.is_finite() {
437            self.snap_to_target();
438            return true;
439        }
440        self.value = next_val;
441        self.velocity = next_vel;
442
443        // Guard against f32 ULP limit cycles at high target magnitudes + tiny `dt` (e.g. 1000Hz)
444        // where `v * dt` rounds below half an ULP while the analytic spring is decaying toward
445        // `target` within `max(rest_displacement, 64 * eps * |target|)`.
446        let rest_d = positive_or(spec.rest_displacement, DEFAULT_REST_DISPLACEMENT);
447        let ulp_tol = rest_d.max(self.target.abs() * f32::EPSILON * 64.0);
448        let ulp_stalled = next_val == prev_val
449            && x.abs() <= x0.abs()
450            && (next_val - self.target).abs() <= ulp_tol
451            && (f64::from(next_vel).abs() / omega0) <= f64::from(ulp_tol);
452
453        if self.is_settled(spec) || ulp_stalled {
454            self.snap_to_target();
455            true
456        } else {
457            false
458        }
459    }
460
461    /// Convenience helper: snaps immediately to `target` when `instant` is `true` (e.g. reduced
462    /// motion active), otherwise advances via [`Self::step`].
463    #[inline]
464    pub fn step_or_snap(&mut self, spec: &SpringSpec, dt_s: f32, instant: bool) -> bool {
465        if instant {
466            self.snap_to_target();
467            true
468        } else {
469            self.step(spec, dt_s)
470        }
471    }
472}
473
474#[cfg(test)]
475mod tests {
476    use super::*;
477
478    #[test]
479    fn from_omega_and_from_damping_ratio_produce_expected_regimes() {
480        let crit = SpringSpec::from_omega(18.0);
481        assert!((crit.angular_frequency() - 18.0).abs() < 1e-4);
482        assert!((crit.damping_ratio() - 1.0).abs() < 1e-5);
483
484        let under = SpringSpec::from_damping_ratio(0.5, 0.4);
485        assert!((under.damping_ratio() - 0.5).abs() < 1e-4);
486        let over = SpringSpec::from_damping_ratio(1.8, 0.4);
487        assert!((over.damping_ratio() - 1.8).abs() < 1e-4);
488    }
489
490    #[test]
491    fn all_three_regimes_are_step_size_invariant_and_converge() {
492        let specs = [
493            SpringSpec::bouncy(),
494            SpringSpec::from_omega(20.0),
495            SpringSpec::from_damping_ratio(2.0, 0.35),
496        ];
497        for spec in specs {
498            let mut fine = SpringState::with_velocity(10.0, 45.0, 100.0);
499            for _ in 0..10 {
500                fine.step(&spec, 0.016);
501            }
502            let mut coarse = SpringState::with_velocity(10.0, 45.0, 100.0);
503            coarse.step(&spec, 0.16);
504            assert!((fine.value - coarse.value).abs() < 1e-3);
505            assert!((fine.velocity - coarse.velocity).abs() < 1e-2);
506
507            for _ in 0..2000 {
508                if fine.step(&spec, 1.0 / 60.0) {
509                    break;
510                }
511            }
512            assert!(fine.is_settled(&spec));
513            assert_eq!(fine.value, 100.0);
514            assert_eq!(fine.velocity, 0.0);
515        }
516    }
517
518    #[test]
519    fn step_or_snap_handles_instant_and_non_finite_inputs() {
520        let spec = SpringSpec::snappy();
521        let mut s = SpringState::new(0.0, 42.0);
522        assert!(s.step_or_snap(&spec, 0.001, true));
523        assert_eq!(s.value, 42.0);
524        assert_eq!(s.velocity, 0.0);
525
526        let mut bad = SpringState::with_velocity(f32::NAN, f32::INFINITY, 12.0);
527        assert!(bad.step(&spec, 0.016));
528        assert_eq!(bad.value, 12.0);
529        assert_eq!(bad.velocity, 0.0);
530    }
531}