forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB9ff2f83Ivan Molodetskikh1 year ago2099 commits

spring.rs209 lines, 6.3 KiBHistoryRawDownload
1use std::time::Duration;
2
3#[derive(Debug, Clone, Copy)]
4pub struct SpringParams {
5 pub damping: f64,
6 pub mass: f64,
7 pub stiffness: f64,
8 pub epsilon: f64,
9}
10
11#[derive(Debug, Clone, Copy)]
12pub struct Spring {
13 pub from: f64,
14 pub to: f64,
15 pub initial_velocity: f64,
16 pub params: SpringParams,
17}
18
19impl SpringParams {
20 pub fn new(damping_ratio: f64, stiffness: f64, epsilon: f64) -> Self {
21 let damping_ratio = damping_ratio.max(0.);
22 let stiffness = stiffness.max(0.);
23 let epsilon = epsilon.max(0.);
24
25 let mass = 1.;
26 let critical_damping = 2. * (mass * stiffness).sqrt();
27 let damping = damping_ratio * critical_damping;
28
29 Self {
30 damping,
31 mass,
32 stiffness,
33 epsilon,
34 }
35 }
36}
37
38impl Spring {
39 pub fn value_at(&self, t: Duration) -> f64 {
40 self.oscillate(t.as_secs_f64())
41 }
42
43 // Based on libadwaita (LGPL-2.1-or-later):
44 // https://gitlab.gnome.org/GNOME/libadwaita/-/blob/1.4.4/src/adw-spring-animation.c,
45 // which itself is based on (MIT):
46 // https://github.com/robb/RBBAnimation/blob/master/RBBAnimation/RBBSpringAnimation.m
47 /// Computes and returns the duration until the spring is at rest.
48 pub fn duration(&self) -> Duration {
49 const DELTA: f64 = 0.001;
50
51 let beta = self.params.damping / (2. * self.params.mass);
52
53 if beta.abs() <= f64::EPSILON || beta < 0. {
54 return Duration::MAX;
55 }
56
57 if (self.to - self.from).abs() <= f64::EPSILON {
58 return Duration::ZERO;
59 }
60
61 let omega0 = (self.params.stiffness / self.params.mass).sqrt();
62
63 // As first ansatz for the overdamped solution,
64 // and general estimation for the oscillating ones
65 // we take the value of the envelope when it's < epsilon.
66 let mut x0 = -self.params.epsilon.ln() / beta;
67
68 // f64::EPSILON is too small for this specific comparison, so we use
69 // f32::EPSILON even though it's doubles.
70 if (beta - omega0).abs() <= f64::from(f32::EPSILON) || beta < omega0 {
71 return Duration::from_secs_f64(x0);
72 }
73
74 // Since the overdamped solution decays way slower than the envelope
75 // we need to use the value of the oscillation itself.
76 // Newton's root finding method is a good candidate in this particular case:
77 // https://en.wikipedia.org/wiki/Newton%27s_method
78 let mut y0 = self.oscillate(x0);
79 let m = (self.oscillate(x0 + DELTA) - y0) / DELTA;
80
81 let mut x1 = (self.to - y0 + m * x0) / m;
82 let mut y1 = self.oscillate(x1);
83
84 let mut i = 0;
85 while (self.to - y1).abs() > self.params.epsilon {
86 if i > 1000 {
87 return Duration::ZERO;
88 }
89
90 x0 = x1;
91 y0 = y1;
92
93 let m = (self.oscillate(x0 + DELTA) - y0) / DELTA;
94
95 x1 = (self.to - y0 + m * x0) / m;
96 y1 = self.oscillate(x1);
97
98 // Overdamped springs have some numerical stability issues...
99 if !y1.is_finite() {
100 return Duration::from_secs_f64(x0);
101 }
102
103 i += 1;
104 }
105
106 Duration::from_secs_f64(x1)
107 }
108
109 /// Computes and returns the duration until the spring reaches its target position.
110 pub fn clamped_duration(&self) -> Option<Duration> {
111 let beta = self.params.damping / (2. * self.params.mass);
112
113 if beta.abs() <= f64::EPSILON || beta < 0. {
114 return Some(Duration::MAX);
115 }
116
117 if (self.to - self.from).abs() <= f64::EPSILON {
118 return Some(Duration::ZERO);
119 }
120
121 // The first frame is not that important and we avoid finding the trivial 0 for in-place
122 // animations.
123 let mut i = 1u16;
124 let mut y = self.oscillate(f64::from(i) / 1000.);
125
126 while (self.to - self.from > f64::EPSILON && self.to - y > self.params.epsilon)
127 || (self.from - self.to > f64::EPSILON && y - self.to > self.params.epsilon)
128 {
129 if i > 3000 {
130 return None;
131 }
132
133 i += 1;
134 y = self.oscillate(f64::from(i) / 1000.);
135 }
136
137 Some(Duration::from_millis(u64::from(i)))
138 }
139
140 /// Returns the spring position at a given time in seconds.
141 fn oscillate(&self, t: f64) -> f64 {
142 let b = self.params.damping;
143 let m = self.params.mass;
144 let k = self.params.stiffness;
145 let v0 = self.initial_velocity;
146
147 let beta = b / (2. * m);
148 let omega0 = (k / m).sqrt();
149
150 let x0 = self.from - self.to;
151
152 let envelope = (-beta * t).exp();
153
154 // Solutions of the form C1*e^(lambda1*x) + C2*e^(lambda2*x)
155 // for the differential equation m*ẍ+b*ẋ+kx = 0
156
157 // f64::EPSILON is too small for this specific comparison, so we use
158 // f32::EPSILON even though it's doubles.
159 if (beta - omega0).abs() <= f64::from(f32::EPSILON) {
160 // Critically damped.
161 self.to + envelope * (x0 + (beta * x0 + v0) * t)
162 } else if beta < omega0 {
163 // Underdamped.
164 let omega1 = ((omega0 * omega0) - (beta * beta)).sqrt();
165
166 self.to
167 + envelope
168 * (x0 * (omega1 * t).cos() + ((beta * x0 + v0) / omega1) * (omega1 * t).sin())
169 } else {
170 // Overdamped.
171 let omega2 = ((beta * beta) - (omega0 * omega0)).sqrt();
172
173 self.to
174 + envelope
175 * (x0 * (omega2 * t).cosh() + ((beta * x0 + v0) / omega2) * (omega2 * t).sinh())
176 }
177 }
178}
179
180#[cfg(test)]
181mod tests {
182 use super::*;
183
184 #[test]
185 fn overdamped_spring_equal_from_to_nan() {
186 let spring = Spring {
187 from: 0.,
188 to: 0.,
189 initial_velocity: 0.,
190 params: SpringParams::new(1.15, 850., 0.0001),
191 };
192 let _ = spring.duration();
193 let _ = spring.clamped_duration();
194 let _ = spring.value_at(Duration::ZERO);
195 }
196
197 #[test]
198 fn overdamped_spring_duration_panic() {
199 let spring = Spring {
200 from: 0.,
201 to: 1.,
202 initial_velocity: 0.,
203 params: SpringParams::new(6., 1200., 0.0001),
204 };
205 let _ = spring.duration();
206 let _ = spring.clamped_duration();
207 let _ = spring.value_at(Duration::ZERO);
208 }
209}