Skip to main content

rust_glass/
animation.rs

1//! Springs. Everything that moves in the framework runs on a spring, so a
2//! motion can be interrupted or retargeted at any time without a jump.
3//!
4//! Most code animates through [`Context::animate`](crate::Context::animate),
5//! which stores the spring for you. Use [`Spring`] directly when you keep the
6//! state yourself.
7
8use crate::geometry::{Rect, Vec2, vec2};
9
10/// How a spring moves, in the SwiftUI convention.
11///
12/// `response` is the period of the undamped spring in seconds: smaller is
13/// faster. `damping` is the damping ratio: 1 arrives without overshoot, lower
14/// values bounce.
15#[derive(Clone, Copy, Debug, PartialEq)]
16pub struct Tuning {
17    /// Period of the undamped spring, in seconds.
18    pub response: f32,
19    /// Damping ratio. 1 is critically damped.
20    pub damping: f32,
21}
22
23impl Tuning {
24    /// Creates a tuning from a response in seconds and a damping ratio.
25    pub const fn new(response: f32, damping: f32) -> Self {
26        Self { response, damping }
27    }
28    /// Fast and without overshoot. For color and opacity.
29    pub const SNAP: Tuning = Tuning::new(0.22, 1.0);
30    /// The default for position and size.
31    pub const SMOOTH: Tuning = Tuning::new(0.38, 0.86);
32    /// Lifts, presses and stretches.
33    pub const PRESS: Tuning = Tuning::new(0.36, 0.62);
34    /// A clear wobble, for menus and drops.
35    pub const BOUNCY: Tuning = Tuning::new(0.48, 0.68);
36}
37
38/// A value that follows its target like a damped spring.
39///
40/// # Examples
41///
42/// ```
43/// use rust_glass::prelude::*;
44///
45/// let mut width = Spring::new(100.0);
46/// // Called once per frame with the frame time.
47/// let moving = width.step(240.0, Tuning::SMOOTH, 1.0 / 60.0);
48/// assert!(moving && width.value > 100.0);
49/// ```
50#[derive(Clone, Copy, Debug, Default, PartialEq)]
51pub struct Spring {
52    /// Current value.
53    pub value: f32,
54    /// Current velocity, in units per second.
55    pub velocity: f32,
56    started: bool,
57}
58
59impl Spring {
60    /// Creates a spring resting at `value`.
61    pub fn new(value: f32) -> Self {
62        Self { value, velocity: 0.0, started: true }
63    }
64
65    /// Moves towards `target` by `dt` seconds and returns `true` while still
66    /// moving.
67    ///
68    /// The first step of a [`Default`] spring jumps straight to the target,
69    /// so a widget never animates in from zero by accident.
70    ///
71    /// The step uses the exact solution of the damped oscillator, so the
72    /// result is the same at any frame rate and a long frame cannot make it
73    /// unstable.
74    pub fn step(&mut self, target: f32, tuning: Tuning, dt: f32) -> bool {
75        if !self.started {
76            *self = Spring::new(target);
77            return false;
78        }
79        let w = std::f32::consts::TAU / tuning.response.max(0.01);
80        let z = tuning.damping.clamp(0.05, 1.0);
81        let x0 = self.value - target;
82        let v0 = self.velocity;
83        let (x, v) = if z > 0.999 {
84            let c = v0 + w * x0;
85            let e = (-w * dt).exp();
86            ((x0 + c * dt) * e, (v0 - w * c * dt) * e)
87        } else {
88            let wd = w * (1.0 - z * z).sqrt();
89            let e = (-z * w * dt).exp();
90            let (s, c) = (wd * dt).sin_cos();
91            let b = (v0 + z * w * x0) / wd;
92            (e * (x0 * c + b * s), e * (v0 * c - (z * w * b + wd * x0) * s))
93        };
94        self.value = target + x;
95        self.velocity = v;
96        let scale = 1.0 + target.abs() * 0.02;
97        if x.abs() < 0.0008 * scale && v.abs() < 0.01 * scale {
98            self.value = target;
99            self.velocity = 0.0;
100            return false;
101        }
102        true
103    }
104
105    /// Jumps to `value` and stops.
106    pub fn set(&mut self, value: f32) {
107        *self = Spring::new(value);
108    }
109}
110
111/// Two springs, one per axis.
112#[derive(Clone, Copy, Debug, Default, PartialEq)]
113pub struct Spring2d {
114    /// Spring of the x axis.
115    pub x: Spring,
116    /// Spring of the y axis.
117    pub y: Spring,
118}
119
120impl Spring2d {
121    /// Creates a spring resting at `value`.
122    pub fn new(value: Vec2) -> Self {
123        Self { x: Spring::new(value.x), y: Spring::new(value.y) }
124    }
125    /// Current value.
126    pub fn value(&self) -> Vec2 {
127        vec2(self.x.value, self.y.value)
128    }
129    /// Current velocity, in units per second.
130    pub fn velocity(&self) -> Vec2 {
131        vec2(self.x.velocity, self.y.velocity)
132    }
133    /// Moves towards `target` and returns `true` while still moving. See
134    /// [`Spring::step`].
135    pub fn step(&mut self, target: Vec2, tuning: Tuning, dt: f32) -> bool {
136        self.x.step(target.x, tuning, dt) | self.y.step(target.y, tuning, dt)
137    }
138    /// Jumps to `value` and stops.
139    pub fn set(&mut self, value: Vec2) {
140        *self = Self::new(value);
141    }
142}
143
144/// A rectangle whose center and size move on separate springs. Surfaces that
145/// change shape use it, which gives them their liquid look.
146#[derive(Clone, Copy, Debug, Default)]
147pub struct SpringRect {
148    /// Spring of the center.
149    pub center: Spring2d,
150    /// Spring of the size.
151    pub size: Spring2d,
152}
153
154impl SpringRect {
155    /// Creates a spring resting at `rect`.
156    pub fn new(rect: Rect) -> Self {
157        Self { center: Spring2d::new(rect.center()), size: Spring2d::new(rect.size()) }
158    }
159    /// Moves towards `target` and returns `true` while still moving.
160    pub fn step(&mut self, target: Rect, center: Tuning, size: Tuning, dt: f32) -> bool {
161        self.center.step(target.center(), center, dt) | self.size.step(target.size(), size, dt)
162    }
163    /// Current rectangle.
164    pub fn rect(&self) -> Rect {
165        Rect::from_center_size(self.center.value(), self.size.value().max(Vec2::splat(1.0)))
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    #[test]
174    fn first_step_snaps() {
175        let mut s = Spring::default();
176        assert!(!s.step(5.0, Tuning::PRESS, 0.016));
177        assert_eq!(s.value, 5.0);
178    }
179
180    #[test]
181    fn frame_rate_independent() {
182        let run = |dt: f32, n: usize| {
183            let mut s = Spring::new(0.0);
184            for _ in 0..n {
185                s.step(1.0, Tuning::PRESS, dt);
186            }
187            s.value
188        };
189        assert!((run(1.0 / 60.0, 12) - run(1.0 / 240.0, 48)).abs() < 1e-3);
190    }
191
192    #[test]
193    fn settles_and_overshoots_only_when_underdamped() {
194        let peak = |t: Tuning| {
195            let mut s = Spring::new(0.0);
196            let mut peak: f32 = 0.0;
197            for _ in 0..400 {
198                s.step(1.0, t, 1.0 / 120.0);
199                peak = peak.max(s.value);
200            }
201            assert_eq!(s.value, 1.0);
202            peak
203        };
204        assert!(peak(Tuning::PRESS) > 1.02);
205        assert!(peak(Tuning::SNAP) <= 1.0001);
206    }
207
208    #[test]
209    fn survives_huge_frames() {
210        let mut s = Spring::new(0.0);
211        s.step(100.0, Tuning::BOUNCY, 5.0);
212        assert!((s.value - 100.0).abs() < 1.0);
213    }
214}