animato-spring 1.7.1

Physics-based spring animations for the Animato animation library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! 1D [`Spring`] — damped harmonic oscillator.

use crate::config::SpringConfig;
use animato_core::{
    AnimationIntrospection, AnimationKind, Inspectable, Playable, PlaybackState, Update,
};

/// Integration method for the spring ODE.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Integrator {
    /// Semi-implicit Euler — fast, stable, default choice for animation.
    SemiImplicitEuler,
    /// 4th-order Runge-Kutta — more accurate for high-stiffness springs.
    RungeKutta4,
}

/// A 1D damped harmonic oscillator spring.
///
/// Stack-allocated and `no_std`-compatible. Use [`SpringN<T>`](crate::SpringN)
/// for multi-dimensional animation.
///
/// # Example
///
/// ```rust
/// use animato_spring::{Spring, SpringConfig};
/// use animato_core::Update;
///
/// let mut s = Spring::new(SpringConfig::stiff());
/// s.set_target(100.0);
/// for _ in 0..300 {
///     s.update(1.0 / 60.0);
/// }
/// assert!((s.position() - 100.0).abs() < 0.01);
/// ```
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Spring {
    /// The spring configuration (stiffness, damping, mass, epsilon).
    pub config: SpringConfig,
    position: f32,
    velocity: f32,
    target: f32,
    integrator: Integrator,
    previous_displacement: f32,
    overshoot_count: u32,
}

impl Spring {
    /// Create a new spring at position `0.0` with target `0.0`.
    pub fn new(config: SpringConfig) -> Self {
        Self {
            config,
            position: 0.0,
            velocity: 0.0,
            target: 0.0,
            integrator: Integrator::SemiImplicitEuler,
            previous_displacement: 0.0,
            overshoot_count: 0,
        }
    }

    /// Create a spring at `initial`, moving with `velocity`, toward `target`.
    ///
    /// This is useful for fling-to-snap gestures where the release velocity
    /// should carry into the settling animation.
    pub fn from_velocity(initial: f32, velocity: f32, target: f32, config: SpringConfig) -> Self {
        let mut spring = Self::new(config);
        spring.position = initial;
        spring.velocity = if velocity.is_finite() { velocity } else { 0.0 };
        spring.target = target;
        spring.previous_displacement = initial - target;
        spring
    }

    /// Set the target position the spring moves toward.
    pub fn set_target(&mut self, target: f32) {
        self.target = target;
        self.previous_displacement = self.position - self.target;
        self.overshoot_count = 0;
    }

    /// Current position of the spring.
    pub fn position(&self) -> f32 {
        self.position
    }

    /// Current velocity of the spring.
    pub fn velocity(&self) -> f32 {
        self.velocity
    }

    /// `true` when the spring has come to rest within `epsilon` of the target.
    pub fn is_settled(&self) -> bool {
        let eps = self.config.epsilon;
        (self.position - self.target).abs() < eps && self.velocity.abs() < eps
    }

    /// Current kinetic plus potential energy.
    ///
    /// This is useful for diagnostics and settle visualization. The units are
    /// simulation-relative rather than renderer-specific.
    pub fn energy(&self) -> f32 {
        let displacement = self.position - self.target;
        0.5 * self.config.mass * self.velocity * self.velocity
            + 0.5 * self.config.stiffness * displacement * displacement
    }

    /// Number of times the spring has crossed its target since the last target change.
    pub fn overshoot_count(&self) -> u32 {
        self.overshoot_count
    }

    /// Teleport to `pos` instantly — no animation, velocity zeroed.
    pub fn snap_to(&mut self, pos: f32) {
        self.position = pos;
        self.velocity = 0.0;
        self.target = pos;
        self.previous_displacement = 0.0;
        self.overshoot_count = 0;
    }

    /// Switch to RK4 integration (more accurate for high-stiffness springs).
    pub fn use_rk4(mut self, yes: bool) -> Self {
        self.integrator = if yes {
            Integrator::RungeKutta4
        } else {
            Integrator::SemiImplicitEuler
        };
        self
    }

    // ── Integration ──────────────────────────────────────────────────────────

    #[inline]
    fn acceleration(&self, position: f32, velocity: f32) -> f32 {
        let displacement = position - self.target;
        let spring_force = -self.config.stiffness * displacement;
        let damping_force = -self.config.damping * velocity;
        (spring_force + damping_force) / self.config.mass
    }

    fn step_euler(&mut self, dt: f32) {
        let acc = self.acceleration(self.position, self.velocity);
        self.velocity += acc * dt;
        self.position += self.velocity * dt;
    }

    fn step_rk4(&mut self, dt: f32) {
        // Classic RK4 for the coupled ODEs:
        //   dx/dt = v
        //   dv/dt = acceleration(x, v)
        let p0 = self.position;
        let v0 = self.velocity;

        let k1v = self.acceleration(p0, v0);
        let k1p = v0;

        let k2v = self.acceleration(p0 + k1p * dt / 2.0, v0 + k1v * dt / 2.0);
        let k2p = v0 + k1v * dt / 2.0;

        let k3v = self.acceleration(p0 + k2p * dt / 2.0, v0 + k2v * dt / 2.0);
        let k3p = v0 + k2v * dt / 2.0;

        let k4v = self.acceleration(p0 + k3p * dt, v0 + k3v * dt);
        let k4p = v0 + k3v * dt;

        self.position += (dt / 6.0) * (k1p + 2.0 * k2p + 2.0 * k3p + k4p);
        self.velocity += (dt / 6.0) * (k1v + 2.0 * k2v + 2.0 * k3v + k4v);
    }

    fn track_overshoot(&mut self) {
        let displacement = self.position - self.target;
        let eps = self.config.epsilon.max(0.0);
        if self.previous_displacement.abs() > eps
            && displacement.abs() > eps
            && self.previous_displacement.signum() != displacement.signum()
        {
            self.overshoot_count = self.overshoot_count.saturating_add(1);
        }
        self.previous_displacement = displacement;
    }
}

impl Update for Spring {
    /// Advance the spring by `dt` seconds.
    ///
    /// Returns `false` when settled, `true` while still moving.
    /// Negative `dt` is treated as `0.0`.
    fn update(&mut self, dt: f32) -> bool {
        let dt = dt.max(0.0);
        if dt == 0.0 || self.is_settled() {
            return !self.is_settled();
        }
        // Guard against degenerate config
        if self.config.stiffness <= 0.0 {
            self.position = self.target;
            self.velocity = 0.0;
            return false;
        }
        match self.integrator {
            Integrator::SemiImplicitEuler => self.step_euler(dt),
            Integrator::RungeKutta4 => self.step_rk4(dt),
        }
        self.track_overshoot();
        !self.is_settled()
    }
}

impl Inspectable for Spring {
    fn introspect(&self) -> AnimationIntrospection {
        AnimationIntrospection::new(
            AnimationKind::Spring,
            if self.is_settled() { 1.0 } else { 0.0 },
            0.0,
            None,
            if self.is_settled() {
                PlaybackState::Complete
            } else {
                PlaybackState::Playing
            },
            None,
        )
    }
}

impl Playable for Spring {
    fn duration(&self) -> f32 {
        // Springs have no finite duration — they settle asymptotically.
        f32::INFINITY
    }

    fn reset(&mut self) {
        // Reset to the initial position (current target becomes the new start).
        let target = self.target;
        self.snap_to(0.0);
        self.target = target;
    }

    fn seek_to(&mut self, _progress: f32) {
        // Springs don't support meaningful seeking; snap to target at progress=1.0.
        if _progress >= 1.0 {
            let target = self.target;
            self.snap_to(target);
        }
    }

    fn is_complete(&self) -> bool {
        self.is_settled()
    }

    fn as_any(&self) -> &dyn core::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn core::any::Any {
        self
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// Tests
// ──────────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    const DT: f32 = 1.0 / 60.0;
    const MAX_STEPS: usize = 10_000;

    fn run_to_settle(spring: &mut Spring) -> usize {
        let mut steps = 0;
        while !spring.is_settled() {
            spring.update(DT);
            steps += 1;
            assert!(
                steps < MAX_STEPS,
                "Spring did not settle within {} steps",
                MAX_STEPS
            );
        }
        steps
    }

    #[test]
    fn gentle_settles_to_target() {
        let mut s = Spring::new(SpringConfig::gentle());
        s.set_target(100.0);
        run_to_settle(&mut s);
        assert!((s.position() - 100.0).abs() < 0.01);
    }

    #[test]
    fn wobbly_settles_to_target() {
        let mut s = Spring::new(SpringConfig::wobbly());
        s.set_target(50.0);
        run_to_settle(&mut s);
        assert!((s.position() - 50.0).abs() < 0.01);
    }

    #[test]
    fn stiff_settles_to_target() {
        let mut s = Spring::new(SpringConfig::stiff());
        s.set_target(-30.0);
        run_to_settle(&mut s);
        assert!((s.position() - (-30.0)).abs() < 0.01);
    }

    #[test]
    fn slow_settles_to_target() {
        let mut s = Spring::new(SpringConfig::slow());
        s.set_target(1.0);
        run_to_settle(&mut s);
        assert!((s.position() - 1.0).abs() < 0.01);
    }

    #[test]
    fn snappy_settles_to_target() {
        let mut s = Spring::new(SpringConfig::snappy());
        s.set_target(200.0);
        run_to_settle(&mut s);
        assert!((s.position() - 200.0).abs() < 0.01);
    }

    #[test]
    fn snappy_settles_faster_than_slow() {
        let mut fast = Spring::new(SpringConfig::snappy());
        fast.set_target(100.0);
        let fast_steps = run_to_settle(&mut fast);

        let mut slow = Spring::new(SpringConfig::slow());
        slow.set_target(100.0);
        let slow_steps = run_to_settle(&mut slow);

        assert!(
            fast_steps < slow_steps,
            "snappy={} slow={}",
            fast_steps,
            slow_steps
        );
    }

    #[test]
    fn zero_damping_oscillates() {
        let cfg = SpringConfig {
            stiffness: 100.0,
            damping: 0.0,
            mass: 1.0,
            epsilon: 0.001,
        };
        let mut s = Spring::new(cfg);
        s.set_target(1.0);
        // Run 10,000 steps — should never settle with zero damping
        for _ in 0..10_000 {
            s.update(DT);
        }
        assert!(!s.is_settled());
    }

    #[test]
    fn snap_to_teleports() {
        let mut s = Spring::new(SpringConfig::default());
        s.set_target(100.0);
        s.snap_to(100.0);
        assert_eq!(s.position(), 100.0);
        assert_eq!(s.velocity(), 0.0);
        assert!(s.is_settled());
    }

    #[test]
    fn rk4_also_settles() {
        let mut s = Spring::new(SpringConfig::wobbly()).use_rk4(true);
        s.set_target(100.0);
        run_to_settle(&mut s);
        assert!((s.position() - 100.0).abs() < 0.01);
    }

    #[test]
    fn zero_stiffness_snaps_immediately() {
        let cfg = SpringConfig {
            stiffness: 0.0,
            ..SpringConfig::default()
        };
        let mut s = Spring::new(cfg);
        s.set_target(42.0);
        s.update(DT);
        assert_eq!(s.position(), 42.0);
        assert!(s.is_settled());
    }

    #[test]
    fn negative_dt_is_noop() {
        let mut s = Spring::new(SpringConfig::default());
        s.set_target(100.0);
        let pos_before = s.position();
        s.update(-1.0);
        assert_eq!(s.position(), pos_before);
    }

    #[test]
    fn from_velocity_reaches_target_and_loses_energy() {
        let mut s = Spring::from_velocity(0.0, 300.0, 100.0, SpringConfig::stiff());
        let start_energy = s.energy();
        run_to_settle(&mut s);
        assert!((s.position() - 100.0).abs() < 0.01);
        assert!(s.energy() < start_energy);
    }

    #[test]
    fn damping_modes_order_damping() {
        let critical = SpringConfig::critically_damped(100.0);
        let over = SpringConfig::overdamped(100.0, 1.5);
        let under = SpringConfig::underdamped(100.0, 0.5);
        assert!(under.damping < critical.damping);
        assert!(over.damping > critical.damping);
    }

    #[test]
    fn overshoot_count_tracks_target_crossings() {
        let mut s = Spring::from_velocity(0.0, 0.0, 1.0, SpringConfig::underdamped(120.0, 0.2));
        for _ in 0..240 {
            s.update(DT);
        }
        assert!(s.overshoot_count() > 0);
    }

    // ── Playable impl tests ─────────────────────────────────────────────────

    #[test]
    fn playable_duration_is_infinite() {
        let s = Spring::new(SpringConfig::snappy());
        assert!(Playable::duration(&s).is_infinite());
    }

    #[test]
    fn playable_is_complete_when_settled() {
        let mut s = Spring::new(SpringConfig::snappy());
        s.set_target(100.0);
        assert!(!Playable::is_complete(&s));
        run_to_settle(&mut s);
        assert!(Playable::is_complete(&s));
    }

    #[test]
    fn playable_seek_to_one_snaps_to_target() {
        let mut s = Spring::new(SpringConfig::snappy());
        s.set_target(100.0);
        Playable::seek_to(&mut s, 1.0);
        assert!(s.is_settled());
        assert!((s.position() - 100.0).abs() < 0.01);
    }

    #[test]
    fn playable_seek_to_zero_does_not_snap() {
        let mut s = Spring::new(SpringConfig::snappy());
        s.set_target(100.0);
        Playable::seek_to(&mut s, 0.0);
        assert!(!s.is_settled());
    }

    #[test]
    fn playable_reset_zeroes_position() {
        let mut s = Spring::new(SpringConfig::snappy());
        s.set_target(100.0);
        run_to_settle(&mut s);
        assert!((s.position() - 100.0).abs() < 0.01);
        Playable::reset(&mut s);
        assert_eq!(s.position(), 0.0);
    }

    #[test]
    fn playable_as_any_downcasts() {
        let s = Spring::new(SpringConfig::default());
        assert!(Playable::as_any(&s).is::<Spring>());
        let mut s = s;
        assert!(Playable::as_any_mut(&mut s).is::<Spring>());
    }
}