Skip to main content

repose_core/
animation.rs

1use std::cell::{Cell, RefCell};
2use std::rc::Rc;
3use std::sync::atomic::{AtomicU32, Ordering};
4use web_time::{Duration, Instant};
5
6pub fn now() -> Instant {
7    let clock = CLOCK.with(|clock| clock.borrow().clone());
8    clock.now()
9}
10
11/// Process-wide animator duration scale, matching Android's
12/// `Settings.Global.ANIMATOR_DURATION_SCALE`: `0.0` disables animations,
13/// `0.5` runs them twice as fast, `2.0` twice as slow.
14static MOTION_DURATION_SCALE_BITS: AtomicU32 = AtomicU32::new(0x3F80_0000);
15
16thread_local! {
17    static MOTION_DURATION_SCALE_OVERRIDE: Cell<Option<f32>> = const { Cell::new(None) };
18}
19
20/// The animator duration scale in effect on this thread.
21///
22/// A scoped [`with_motion_duration_scale`] override wins; otherwise the
23/// process default set by [`set_motion_duration_scale`] applies.
24pub fn motion_duration_scale() -> f32 {
25    MOTION_DURATION_SCALE_OVERRIDE
26        .with(Cell::get)
27        .unwrap_or_else(|| f32::from_bits(MOTION_DURATION_SCALE_BITS.load(Ordering::Relaxed)))
28}
29
30/// Set the process-wide animator duration scale. Platforms call this when the
31/// system accessibility setting changes.
32pub fn set_motion_duration_scale(scale: f32) {
33    let scale = if scale.is_finite() {
34        scale.clamp(0.0, 10.0)
35    } else {
36        1.0
37    };
38    let previous = MOTION_DURATION_SCALE_BITS.swap(scale.to_bits(), Ordering::Relaxed);
39    if previous != scale.to_bits() {
40        crate::request_frame();
41    }
42}
43
44/// Run `f` with a scoped animator duration scale.
45pub fn with_motion_duration_scale<R>(scale: f32, f: impl FnOnce() -> R) -> R {
46    struct Guard(Option<f32>);
47    impl Drop for Guard {
48        fn drop(&mut self) {
49            MOTION_DURATION_SCALE_OVERRIDE.with(|override_| override_.set(self.0));
50        }
51    }
52    let scale = if scale.is_finite() {
53        scale.clamp(0.0, 10.0)
54    } else {
55        1.0
56    };
57    let previous = MOTION_DURATION_SCALE_OVERRIDE.with(|override_| override_.replace(Some(scale)));
58    let _guard = Guard(previous);
59    f()
60}
61
62/// Real elapsed time divided by the animator duration scale. `None` means
63/// animations are disabled and the caller should jump to its target.
64fn scaled_elapsed(elapsed: Duration) -> Option<Duration> {
65    let scale = motion_duration_scale();
66    if scale <= 0.0 {
67        return None;
68    }
69    Some(Duration::from_secs_f32(elapsed.as_secs_f32() / scale))
70}
71
72/// Physical spring parameters. Duration is emergent (determined by physics), not specified.
73#[derive(Clone, Copy, Debug)]
74pub struct SpringSpec {
75    /// Damping ratio ζ: 0 = undamped, <1 = underdamped (overshoot), 1 = critically damped,
76    /// >1 = overdamped.
77    pub damping_ratio: f32,
78    /// Stiffness k: higher = faster, snappier response.
79    pub stiffness: f32,
80    /// Progress threshold for settling: when `|progress - 1.0| < this`, the spring is
81    /// considered visually close enough to the target and stops. Default: 0.005 (0.5%).
82    pub settle_progress: f32,
83    /// Velocity threshold for settling (in progress-units/second). Default: 0.1.
84    pub settle_velocity: f32,
85}
86
87impl SpringSpec {
88    pub const fn new(damping_ratio: f32, stiffness: f32) -> Self {
89        Self {
90            damping_ratio,
91            stiffness,
92            settle_progress: 0.005,
93            settle_velocity: 0.1,
94        }
95    }
96    /// Gentle preset: low overshoot, moderate speed.
97    pub const fn gentle() -> Self {
98        Self::new(0.5, 200.0)
99    }
100    /// Bouncier preset: more overshoot, faster.
101    pub const fn bouncy() -> Self {
102        Self::new(0.2, 300.0)
103    }
104    /// Critically damped: no overshoot, fast settle.
105    pub const fn crit() -> Self {
106        Self::new(1.0, 200.0)
107    }
108    /// Snappy preset: high damping, high stiffness.
109    pub const fn stiff() -> Self {
110        Self::new(0.8, 600.0)
111    }
112
113    /// Set the settling threshold in progress units. Lower values = more precise settling.
114    /// For example, 0.001 means the spring stops when within 0.1% of the target.
115    pub const fn with_settle_progress(mut self, threshold: f32) -> Self {
116        self.settle_progress = threshold;
117        self
118    }
119
120    /// Set the velocity threshold for settling (progress-units/second).
121    pub const fn with_settle_velocity(mut self, threshold: f32) -> Self {
122        self.settle_velocity = threshold;
123        self
124    }
125}
126
127/// A cubic bezier curve with control points (p1x, p1y), (p2x, p2y).
128/// P0 = (0, 0) and P3 = (1, 1) are fixed.
129#[derive(Clone, Copy, Debug)]
130pub struct CubicBezier {
131    pub p1x: f32,
132    pub p1y: f32,
133    pub p2x: f32,
134    pub p2y: f32,
135}
136
137impl CubicBezier {
138    pub const fn new(p1x: f32, p1y: f32, p2x: f32, p2y: f32) -> Self {
139        Self { p1x, p1y, p2x, p2y }
140    }
141}
142
143/// Compose Material3 EmphasizedDecelerate: cubic-bezier(0.05, 0.7, 0.1, 1.0).
144pub const EASING_EMPHASIZED_DECELERATE: CubicBezier = CubicBezier::new(0.05, 0.7, 0.1, 1.0);
145/// Compose Material3 StandardDecelerate: cubic-bezier(0.2, 0.0, 0.0, 1.0).
146pub const EASING_STANDARD_DECELERATE: CubicBezier = CubicBezier::new(0.2, 0.0, 0.0, 1.0);
147
148#[derive(Clone, Copy, Debug)]
149#[non_exhaustive]
150pub enum Easing {
151    Linear,
152    EaseIn,
153    EaseOut,
154    EaseInOut,
155    /// Monotonic, critically-damped, y(t)=1-(1+ω t)e^{-ω t}, t∈[0,1].
156    SpringCrit {
157        omega: f32,
158    },
159    /// Underdamped, low-overshoot preset (ζ≈0.5, ω≈8)
160    SpringGentle,
161    /// Underdamped, bouncier preset (ζ≈0.2, ω≈12)
162    SpringBouncy,
163    /// Android FastOutSlowIn: cubic-bezier(0.4, 0.0, 0.2, 1.0).
164    /// Starts fast, decelerates through the middle, ends slow.
165    FastOutSlowIn,
166    /// Custom cubic-bezier easing with control points (p1x, p1y), (p2x, p2y).
167    Custom(CubicBezier),
168    // Godot-style transition families (TRANS_* × EASE_*), added for games
169    CubicIn,
170    CubicOut,
171    CubicInOut,
172    QuartIn,
173    QuartOut,
174    QuartInOut,
175    QuintIn,
176    QuintOut,
177    QuintInOut,
178    SineIn,
179    SineOut,
180    SineInOut,
181    ExpoIn,
182    ExpoOut,
183    ExpoInOut,
184    CircIn,
185    CircOut,
186    CircInOut,
187    /// Back overshoot preset (Godot default overshoot = 1.70158).
188    BackIn,
189    BackOut,
190    BackInOut,
191    /// Springy damped oscillation below/above the end value.
192    ElasticIn,
193    ElasticOut,
194    ElasticInOut,
195    BounceIn,
196    BounceOut,
197    BounceInOut,
198}
199
200/// Size/alpha curve over life, for games driving per-tick curves
201/// (particle size/alpha, gradient sampling) off the shared [`Easing`]
202/// family. `Default` is [`EaseKind::Linear`]; `serde` impls ride the
203/// crate `serde` feature (asset formats like `.fx.ron` enable it).
204#[derive(Clone, Copy, Debug, Default)]
205#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
206pub enum EaseKind {
207    #[default]
208    Linear,
209    QuadOut,
210    CubicOut,
211    BackOut,
212}
213
214impl EaseKind {
215    /// Ease life fraction 0..1 into curve value 0..1.
216    pub fn apply(self, t: f32) -> f32 {
217        let ease = match self {
218            EaseKind::Linear => Easing::Linear,
219            EaseKind::QuadOut => Easing::EaseOut,
220            EaseKind::CubicOut => Easing::CubicOut,
221            EaseKind::BackOut => Easing::BackOut,
222        };
223        ease.interpolate(t.clamp(0.0, 1.0))
224    }
225}
226
227impl Easing {
228    pub fn interpolate(&self, t: f32) -> f32 {
229        match self {
230            Easing::Linear => t,
231            Easing::EaseIn => t * t,
232            Easing::EaseOut => t * (2.0 - t),
233            Easing::EaseInOut => {
234                if t < 0.5 {
235                    2.0 * t * t
236                } else {
237                    -1.0 + (4.0 - 2.0 * t) * t
238                }
239            }
240            Easing::SpringCrit { omega } => {
241                let w = (*omega).max(0.0);
242                let tt = t.max(0.0);
243                // y = 1 - (1 + w t) e^{-w t}
244                1.0 - (1.0 + w * tt) * (-(w * tt)).exp()
245            }
246            Easing::SpringGentle => spring_underdamped_normalized(t, 0.5, 8.0),
247            Easing::SpringBouncy => spring_underdamped_normalized(t, 0.2, 12.0),
248            Easing::FastOutSlowIn => eval_cubic_bezier(0.4, 0.0, 0.2, 1.0, t),
249            Easing::Custom(cb) => eval_cubic_bezier(cb.p1x, cb.p1y, cb.p2x, cb.p2y, t),
250            Easing::CubicIn => t * t * t,
251            Easing::CubicOut => {
252                let u = t - 1.0;
253                u * u * u + 1.0
254            }
255            Easing::CubicInOut => {
256                if t < 0.5 {
257                    4.0 * t * t * t
258                } else {
259                    let u = 2.0 * t - 2.0;
260                    u * u * u / 2.0 + 1.0
261                }
262            }
263            Easing::QuartIn => t * t * t * t,
264            Easing::QuartOut => {
265                let u = t - 1.0;
266                1.0 - u * u * u * u
267            }
268            Easing::QuartInOut => {
269                if t < 0.5 {
270                    8.0 * t * t * t * t
271                } else {
272                    let u = -2.0 * t + 2.0;
273                    1.0 - u * u * u * u / 2.0
274                }
275            }
276            Easing::QuintIn => t * t * t * t * t,
277            Easing::QuintOut => {
278                let u = t - 1.0;
279                u * u * u * u * u + 1.0
280            }
281            Easing::QuintInOut => {
282                if t < 0.5 {
283                    16.0 * t * t * t * t * t
284                } else {
285                    let u = -2.0 * t + 2.0;
286                    1.0 - u * u * u * u * u / 2.0
287                }
288            }
289            Easing::SineIn => 1.0 - (t * std::f32::consts::FRAC_PI_2).cos(),
290            Easing::SineOut => (t * std::f32::consts::FRAC_PI_2).sin(),
291            Easing::SineInOut => 0.5 * (1.0 - (t * std::f32::consts::PI).cos()),
292            Easing::ExpoIn => {
293                if t <= 0.0 {
294                    0.0
295                } else {
296                    2.0f32.powf(10.0 * t - 10.0)
297                }
298            }
299            Easing::ExpoOut => {
300                if t >= 1.0 {
301                    1.0
302                } else {
303                    1.0 - 2.0f32.powf(-10.0 * t)
304                }
305            }
306            Easing::ExpoInOut => {
307                if t <= 0.0 {
308                    0.0
309                } else if t >= 1.0 {
310                    1.0
311                } else if t < 0.5 {
312                    2.0f32.powf(20.0 * t - 10.0) / 2.0
313                } else {
314                    (2.0 - 2.0f32.powf(-20.0 * t + 10.0)) / 2.0
315                }
316            }
317            Easing::CircIn => 1.0 - (1.0 - t * t).sqrt(),
318            Easing::CircOut => (1.0 - (t - 1.0) * (t - 1.0)).sqrt(),
319            Easing::CircInOut => {
320                if t < 0.5 {
321                    (1.0 - (1.0 - 4.0 * t * t).sqrt()) / 2.0
322                } else {
323                    ((1.0 - (-2.0 * t + 2.0) * (-2.0 * t + 2.0)).sqrt() + 1.0) / 2.0
324                }
325            }
326            Easing::BackIn => {
327                const C1: f32 = 1.70158;
328                const C3: f32 = C1 + 1.0;
329                C3 * t * t * t - C1 * t * t
330            }
331            Easing::BackOut => {
332                const C1: f32 = 1.70158;
333                const C3: f32 = C1 + 1.0;
334                let u = t - 1.0;
335                1.0 + C3 * u * u * u + C1 * u * u
336            }
337            Easing::BackInOut => {
338                const C1: f32 = 1.70158;
339                const C3: f32 = C1 + 1.0;
340                if t < 0.5 {
341                    let u = 2.0 * t;
342                    (C3 * u * u * u - C1 * u * u) / 2.0
343                } else {
344                    let u = 2.0 * t - 2.0;
345                    (C3 * u * u * u + C1 * u * u) / 2.0 + 1.0
346                }
347            }
348            Easing::ElasticIn => {
349                const C4: f32 = 2.0 * std::f32::consts::PI / 3.0;
350                if t <= 0.0 {
351                    0.0
352                } else if t >= 1.0 {
353                    1.0
354                } else {
355                    -(2.0f32.powf(10.0 * t - 10.0) * ((10.0 * t - 10.75) * C4).sin())
356                }
357            }
358            Easing::ElasticOut => {
359                const C4: f32 = 2.0 * std::f32::consts::PI / 3.0;
360                if t <= 0.0 {
361                    0.0
362                } else if t >= 1.0 {
363                    1.0
364                } else {
365                    2.0f32.powf(-10.0 * t) * ((10.0 * t - 0.75) * C4).sin() + 1.0
366                }
367            }
368            Easing::ElasticInOut => {
369                const C4: f32 = 2.0 * std::f32::consts::PI / 3.0;
370                if t <= 0.0 {
371                    0.0
372                } else if t >= 1.0 {
373                    1.0
374                } else if t < 0.5 {
375                    -(2.0f32.powf(20.0 * t - 10.0) * ((20.0 * t - 11.125) * C4).sin()) / 2.0
376                } else {
377                    2.0f32.powf(-20.0 * t + 10.0) * ((20.0 * t - 11.125) * C4).sin() / 2.0 + 1.0
378                }
379            }
380            Easing::BounceIn => 1.0 - bounce_out(1.0 - t),
381            Easing::BounceOut => bounce_out(t),
382            Easing::BounceInOut => {
383                if t < 0.5 {
384                    (1.0 - bounce_out(1.0 - 2.0 * t)) / 2.0
385                } else {
386                    (1.0 + bounce_out(2.0 * t - 1.0)) / 2.0
387                }
388            }
389        }
390    }
391}
392
393/// Classic ease-out bounce curve (Godot TRANS_BOUNCE EASE_OUT).
394fn bounce_out(t: f32) -> f32 {
395    const N1: f32 = 7.5625;
396    const D1: f32 = 2.75;
397    if t < 1.0 / D1 {
398        N1 * t * t
399    } else if t < 2.0 / D1 {
400        let t = t - 1.5 / D1;
401        N1 * t * t + 0.75
402    } else if t < 2.5 / D1 {
403        let t = t - 2.25 / D1;
404        N1 * t * t + 0.9375
405    } else {
406        let t = t - 2.625 / D1;
407        N1 * t * t + 0.984375
408    }
409}
410
411/// Evaluate a cubic bezier with control points P1=(p1x,p1y), P2=(p2x,p2y)
412/// (P0=(0,0) and P3=(1,1) are fixed). Uses Newton's method (5 iterations)
413/// to find `u` such that x(u) = t, then returns y(u).
414fn eval_cubic_bezier(p1x: f32, p1y: f32, p2x: f32, p2y: f32, t: f32) -> f32 {
415    let t = t.clamp(0.0, 1.0);
416    if t <= 0.0 {
417        return 0.0;
418    }
419    if t >= 1.0 {
420        return 1.0;
421    }
422    let mut u = t;
423    for _ in 0..6 {
424        let omu = 1.0 - u;
425        let x = 3.0 * omu * omu * u * p1x + 3.0 * omu * u * u * p2x + u * u * u;
426        let dx = 3.0 * omu * omu * p1x + 6.0 * omu * u * (p2x - p1x) + 3.0 * u * u * (1.0 - p2x);
427        if dx.abs() < 1e-10 {
428            break;
429        }
430        u -= (x - t) / dx;
431        u = u.clamp(0.0, 1.0);
432    }
433    let omu = 1.0 - u;
434    3.0 * omu * omu * u * p1y + 3.0 * omu * u * u * p2y + u * u * u
435}
436
437/// Cubic Hermite spline interpolation. Given interval width `h`, normalized
438/// position `x` in [0,1], endpoint values `y1,y2` and their tangents `t1,t2`,
439/// returns the interpolated value.
440///
441/// Factored to reduce operation count (adapted from Compose's MonoSpline).
442fn hermite_interpolate(h: f32, x: f32, y1: f32, y2: f32, t1: f32, t2: f32) -> f32 {
443    let x2 = x * x;
444    let x3 = x2 * x;
445    h * t1 * (x - 2.0 * x2 + x3) + h * t2 * (x3 - x2) + y1 - (3.0 * x2 - 2.0 * x3) * (y1 - y2)
446}
447
448/// Derivative of cubic Hermite spline at normalized position `x`.
449#[allow(dead_code)]
450fn hermite_differential(h: f32, x: f32, y1: f32, y2: f32, t1: f32, t2: f32) -> f32 {
451    let x2 = x * x;
452    h * (t1 - 2.0 * x * (2.0 * t1 + t2) + 3.0 * (t1 + t2) * x2) - 6.0 * (x - x2) * (y1 - y2)
453}
454
455/// A monotone cubic Hermite spline for C1-continuous interpolation of `f32` values.
456///
457/// Uses the Fritsch–Carlson method to compute tangents that preserve monotonicity
458/// and prevent overshoot. Based on Android Compose's `MonoSpline`.
459#[derive(Clone, Debug)]
460pub struct MonoSpline {
461    times: Vec<f32>,
462    values: Vec<f32>,
463    tangents: Vec<f32>,
464}
465
466impl MonoSpline {
467    /// Build a spline from keyframe times and values.
468    /// Times must be sorted ascending and have at least 2 entries.
469    /// Values must have the same length as times.
470    ///
471    /// Degenerate segments (duplicate/unsorted/non-finite times) are coerced
472    /// to zero slope instead of producing `inf`/`NaN` tangents: dividing by a
473    /// zero `dt` in `f32` arithmetic does not panic, it silently corrupts every
474    /// later evaluation, so the constructor sanitizes here.
475    pub fn new(times: Vec<f32>, values: Vec<f32>) -> Self {
476        assert!(times.len() >= 2, "MonoSpline requires at least 2 keyframes");
477        assert_eq!(times.len(), values.len());
478        assert!(
479            times.iter().all(|t| t.is_finite()),
480            "MonoSpline times must be finite"
481        );
482        assert!(
483            values.iter().all(|v| v.is_finite()),
484            "MonoSpline values must be finite"
485        );
486        if cfg!(debug_assertions) {
487            for w in times.windows(2) {
488                if w[1] <= w[0] {
489                    log::warn!(
490                        "MonoSpline: times not strictly ascending; degenerate segments coerce to zero slope"
491                    );
492                    break;
493                }
494            }
495        }
496        let n = times.len();
497        let mut tangents = vec![0.0; n];
498
499        // Compute slopes for each segment
500        let mut slopes = vec![0.0; n.saturating_sub(1)];
501        for i in 0..n - 1 {
502            let dt = times[i + 1] - times[i];
503            if dt > 0.0 {
504                slopes[i] = (values[i + 1] - values[i]) / dt;
505            } else {
506                log::warn!("MonoSpline: non-positive dt at segment {i}; coercing slope to 0");
507                slopes[i] = 0.0;
508            }
509        }
510
511        // Tangents at interior knots: average of adjacent slopes
512        tangents[0] = slopes[0];
513        for i in 1..n - 1 {
514            tangents[i] = (slopes[i - 1] + slopes[i]) * 0.5;
515        }
516        tangents[n - 1] = slopes[n - 2];
517
518        // Fritsch–Carlson monotonicity preservation
519        for i in 0..n - 1 {
520            if slopes[i] == 0.0 {
521                tangents[i] = 0.0;
522                tangents[i + 1] = 0.0;
523            } else {
524                let a = tangents[i] / slopes[i];
525                let b = tangents[i + 1] / slopes[i];
526                let h = (a * a + b * b).sqrt();
527                if h > 9.0 {
528                    let t = 3.0 / h;
529                    tangents[i] = t * a * slopes[i];
530                    tangents[i + 1] = t * b * slopes[i];
531                }
532            }
533        }
534
535        Self {
536            times,
537            values,
538            tangents,
539        }
540    }
541
542    /// Evaluate the spline at time `t`.
543    /// Clamps `t` to the spline's time range. Extrapolates using the endpoint tangent.
544    pub fn evaluate(&self, t: f32) -> f32 {
545        let n = self.times.len();
546        let first = self.times[0];
547        let last = self.times[n - 1];
548
549        if t <= first {
550            return self.values[0] + (t - first) * self.tangents[0];
551        }
552        if t >= last {
553            return self.values[n - 1] + (t - last) * self.tangents[n - 1];
554        }
555
556        for i in 0..n - 1 {
557            if t >= self.times[i] && t <= self.times[i + 1] {
558                let h = self.times[i + 1] - self.times[i];
559                let x = (t - self.times[i]) / h;
560                return hermite_interpolate(
561                    h,
562                    x,
563                    self.values[i],
564                    self.values[i + 1],
565                    self.tangents[i],
566                    self.tangents[i + 1],
567                );
568            }
569        }
570
571        self.values[n - 1] // fallback
572    }
573}
574
575/// Returns (progress, velocity) at time `t` with initial conditions (x0, v0).
576fn spring_analytical(zeta: f32, stiffness: f32, t: f32, x0: f32, v0: f32) -> (f32, f32) {
577    if t <= 0.0 {
578        return (x0, v0);
579    }
580
581    let omega = if stiffness > 0.0 {
582        stiffness.sqrt()
583    } else {
584        return (x0 + v0 * t, v0);
585    };
586
587    let zeta = zeta.max(0.0);
588    let exp = (-zeta * omega * t).exp();
589    let a = 1.0 - x0; // amplitude coefficient
590
591    if (zeta - 1.0).abs() < 1e-6 {
592        // Critically damped: x(t) = 1 - (A + B*t) * e^{-ωt}
593        let b = omega * a - v0;
594        let progress = 1.0 - (a + b * t) * exp;
595        let velocity = (a * omega - b + b * omega * t) * exp;
596        (progress, velocity)
597    } else if zeta < 1.0 {
598        // Underdamped: x(t) = 1 - e^{-ζωt}[A*cos(ωd*t) + C*sin(ωd*t)]
599        let wd = omega * (1.0 - zeta * zeta).sqrt();
600        let c = (zeta * omega * a - v0) / wd;
601        let cos_wd = (wd * t).cos();
602        let sin_wd = (wd * t).sin();
603        let env = a * cos_wd + c * sin_wd;
604        let progress = 1.0 - exp * env;
605        let velocity =
606            exp * ((zeta * omega * a - wd * c) * cos_wd + (zeta * omega * c + wd * a) * sin_wd);
607        (progress, velocity)
608    } else {
609        // Overdamped: x(t) = 1 - e^{-ζωt}[A*cosh(ωd'*t) + D*sinh(ωd'*t)]
610        let wd = omega * (zeta * zeta - 1.0).sqrt();
611        let d = (zeta * omega * a - v0) / wd;
612        let cosh_wd = (wd * t).cosh();
613        let sinh_wd = (wd * t).sinh();
614        let env = a * cosh_wd + d * sinh_wd;
615        let progress = 1.0 - exp * env;
616        let velocity =
617            exp * ((zeta * omega * a - wd * d) * cosh_wd + (zeta * omega * d - wd * a) * sinh_wd);
618        (progress, velocity)
619    }
620}
621
622fn spring_underdamped_normalized(t: f32, zeta: f32, omega: f32) -> f32 {
623    let tt = t.max(0.0);
624    let z = zeta.clamp(0.0, 0.999);
625    let w = omega.max(0.0);
626    let wd = w * (1.0 - z * z).sqrt();
627    let exp_term = (-z * w * tt).exp();
628    let cos_term = (wd * tt).cos();
629    let sin_term = (wd * tt).sin();
630    // Standard second-order underdamped unit-step response
631    let c = z / (1.0 - z * z).sqrt();
632    let y = 1.0 - exp_term * (cos_term + c * sin_term);
633    y.clamp(0.0, 1.0)
634}
635
636#[derive(Clone, Copy, Debug)]
637pub struct AnimationSpec {
638    pub duration: Duration,
639    pub easing: Easing,
640    pub delay: Duration,
641    /// If set, use true physical spring simulation (duration is ignored, emergent from physics).
642    pub spring: Option<SpringSpec>,
643    /// If set, wrap the animation in repeat behavior (n iterations, optional ping-pong).
644    pub repeat: Option<RepeatableSpec>,
645}
646
647impl Default for AnimationSpec {
648    fn default() -> Self {
649        Self {
650            duration: Duration::from_millis(300),
651            easing: Easing::EaseInOut,
652            delay: Duration::ZERO,
653            spring: None,
654            repeat: None,
655        }
656    }
657}
658
659impl AnimationSpec {
660    pub fn tween(duration: Duration, easing: Easing) -> Self {
661        Self {
662            duration,
663            easing,
664            delay: Duration::ZERO,
665            spring: None,
666            repeat: None,
667        }
668    }
669    /// True physical spring simulation - duration is emergent, no fixed duration needed.
670    pub fn spring(spring: SpringSpec) -> Self {
671        Self {
672            duration: Duration::ZERO,
673            easing: Easing::Linear,
674            delay: Duration::ZERO,
675            spring: Some(spring),
676            repeat: None,
677        }
678    }
679    /// Gentle underdamped preset (small overshoot). Uses true spring physics.
680    pub fn spring_gentle() -> Self {
681        Self::spring(SpringSpec::gentle())
682    }
683    /// Bouncier underdamped preset. Uses true spring physics.
684    pub fn spring_bouncy() -> Self {
685        Self::spring(SpringSpec::bouncy())
686    }
687    /// Critically damped spring with given omega (angular frequency). Uses true spring physics.
688    pub fn spring_crit(omega: f32) -> Self {
689        Self::spring(SpringSpec::new(1.0, omega * omega))
690    }
691
692    pub fn fast() -> Self {
693        Self {
694            duration: Duration::from_millis(150),
695            easing: Easing::EaseOut,
696            delay: Duration::ZERO,
697            spring: None,
698            repeat: None,
699        }
700    }
701
702    pub fn slow() -> Self {
703        Self {
704            duration: Duration::from_millis(600),
705            easing: Easing::EaseInOut,
706            delay: Duration::ZERO,
707            spring: None,
708            repeat: None,
709        }
710    }
711
712    /// Wrap this spec in a repeatable animation.
713    /// Pass `RepeatableSpec::infinite()` for infinite repeats.
714    pub fn repeated(mut self, repeat: RepeatableSpec) -> Self {
715        self.repeat = Some(repeat);
716        self
717    }
718}
719
720/// A keyframe animation specification.
721///
722/// Defines a sequence of keyframes at specific timestamps (0.0 to 1.0),
723/// with target values and optional easing between each pair.
724#[derive(Clone, Debug)]
725pub struct KeyframesSpec<T: Clone> {
726    /// Keyframes as (timestamp 0.0-1.0, value, optional easing between previous and this).
727    /// The first keyframe should be at t=0.0 and uses no easing.
728    pub keyframes: Vec<(f32, T, Option<Easing>)>,
729}
730
731impl<T: Clone + Interpolate> KeyframesSpec<T> {
732    pub fn new(keyframes: Vec<(f32, T)>) -> Self {
733        assert!(!keyframes.is_empty(), "KeyframesSpec must not be empty");
734        let with_easing = keyframes.into_iter().map(|(t, v)| (t, v, None)).collect();
735        Self {
736            keyframes: with_easing,
737        }
738    }
739
740    /// Add easing between the previous keyframe and this one.
741    pub fn with_easing(mut self, easing: Easing) -> Self {
742        if let Some(last) = self.keyframes.last_mut() {
743            last.2 = Some(easing);
744        }
745        self
746    }
747
748    pub fn evaluate(&self, t: f32) -> T {
749        let t = t.clamp(0.0, 1.0);
750        let kf = &self.keyframes;
751        if kf.is_empty() {
752            panic!("KeyframesSpec must have at least one keyframe");
753        }
754
755        // Linear interpolation (with per-segment easing)
756        for i in 0..kf.len() - 1 {
757            let (t0, _, _) = kf[i];
758            let (t1, ref v1, easing) = kf[i + 1];
759            if t >= t0 && t <= t1 {
760                let segment_t = if (t1 - t0).abs() < f32::EPSILON {
761                    1.0
762                } else {
763                    (t - t0) / (t1 - t0)
764                };
765                let eased_t = match easing {
766                    Some(e) => e.interpolate(segment_t),
767                    None => segment_t,
768                };
769                return kf[i].1.interpolate(v1, eased_t);
770            }
771        }
772        kf.last().unwrap().1.clone()
773    }
774}
775
776/// A keyframe animation specification with smooth cubic Hermite spline interpolation.
777///
778/// Provides C1 continuity (smooth derivatives at keyframe boundaries),
779/// unlike `KeyframesSpec` which uses C0 linear interpolation.
780///
781/// Uses the Fritsch–Carlson monotonicity-preserving Hermite spline
782#[derive(Clone, Debug)]
783pub struct SplineKeyframes {
784    spline: MonoSpline,
785}
786
787impl SplineKeyframes {
788    /// Build a spline keyframe from time/value pairs.
789    ///
790    /// Times should be in [0.0, 1.0] and sorted ascending.
791    /// At least 2 keyframes are required.
792    pub fn new(keyframes: Vec<(f32, f32)>) -> Self {
793        assert!(
794            keyframes.len() >= 2,
795            "SplineKeyframes requires at least 2 keyframes"
796        );
797        let times: Vec<f32> = keyframes.iter().map(|(t, _)| *t).collect();
798        let values: Vec<f32> = keyframes.iter().map(|(_, v)| *v).collect();
799        Self {
800            spline: MonoSpline::new(times, values),
801        }
802    }
803
804    /// Evaluate the spline at normalized time `t` (0.0 to 1.0).
805    pub fn evaluate(&self, t: f32) -> f32 {
806        self.spline.evaluate(t.clamp(0.0, 1.0))
807    }
808
809    /// Stable fingerprint of the keyframe times/values for change detection.
810    /// Used by `animate_spline_keyframes` to restart when keyframes change
811    /// without exposing the private spline internals.
812    pub fn fingerprint(&self) -> String {
813        format!("{:?}", self.spline)
814    }
815}
816
817/// A repeatable animation specification.
818///
819/// Wraps another animation spec and causes it to repeat.
820/// Default: infinite repeat with no reverse.
821#[derive(Clone, Copy, Debug)]
822pub struct RepeatableSpec {
823    /// Number of repetitions. `None` means infinite.
824    pub iterations: Option<u32>,
825    /// If true, alternate direction each iteration (forward, backward, forward...).
826    pub reverse: bool,
827    /// Delay between each iteration.
828    pub delay_between: Duration,
829}
830
831impl Default for RepeatableSpec {
832    fn default() -> Self {
833        Self {
834            iterations: None,
835            reverse: false,
836            delay_between: Duration::ZERO,
837        }
838    }
839}
840
841impl RepeatableSpec {
842    pub fn new(iterations: u32) -> Self {
843        Self {
844            iterations: Some(iterations),
845            reverse: false,
846            delay_between: Duration::ZERO,
847        }
848    }
849
850    pub fn infinite() -> Self {
851        Self {
852            iterations: None,
853            reverse: false,
854            delay_between: Duration::ZERO,
855        }
856    }
857
858    pub fn reverse(mut self) -> Self {
859        self.reverse = true;
860        self
861    }
862
863    pub fn delay_between(mut self, d: Duration) -> Self {
864        self.delay_between = d;
865        self
866    }
867}
868
869fn same_easing(a: Easing, b: Easing) -> bool {
870    match (a, b) {
871        (Easing::SpringCrit { omega: a }, Easing::SpringCrit { omega: b }) => {
872            a.to_bits() == b.to_bits()
873        }
874        (Easing::Custom(a), Easing::Custom(b)) => {
875            a.p1x.to_bits() == b.p1x.to_bits()
876                && a.p1y.to_bits() == b.p1y.to_bits()
877                && a.p2x.to_bits() == b.p2x.to_bits()
878                && a.p2y.to_bits() == b.p2y.to_bits()
879        }
880        (a, b) => std::mem::discriminant(&a) == std::mem::discriminant(&b),
881    }
882}
883
884fn same_spring(a: SpringSpec, b: SpringSpec) -> bool {
885    a.damping_ratio.to_bits() == b.damping_ratio.to_bits()
886        && a.stiffness.to_bits() == b.stiffness.to_bits()
887        && a.settle_progress.to_bits() == b.settle_progress.to_bits()
888        && a.settle_velocity.to_bits() == b.settle_velocity.to_bits()
889}
890
891fn same_repeat(a: Option<RepeatableSpec>, b: Option<RepeatableSpec>) -> bool {
892    match (a, b) {
893        (None, None) => true,
894        (Some(a), Some(b)) => {
895            a.iterations == b.iterations
896                && a.reverse == b.reverse
897                && a.delay_between == b.delay_between
898        }
899        _ => false,
900    }
901}
902
903fn same_animation_spec(a: &AnimationSpec, b: &AnimationSpec) -> bool {
904    a.duration == b.duration
905        && same_easing(a.easing, b.easing)
906        && a.delay == b.delay
907        && match (a.spring, b.spring) {
908            (None, None) => true,
909            (Some(a), Some(b)) => same_spring(a, b),
910            _ => false,
911        }
912        && same_repeat(a.repeat, b.repeat)
913}
914
915/// Decay animation configuration.
916///
917/// Models a damped decay (e.g., for fling-to-stop animations).
918#[derive(Clone, Copy, Debug)]
919pub struct DecayAnimationSpec {
920    /// How quickly the animation decelerates. Lower = faster stop.
921    pub friction: f32,
922    /// Minimum velocity threshold to stop.
923    pub stop_threshold: f32,
924}
925
926impl Default for DecayAnimationSpec {
927    fn default() -> Self {
928        Self {
929            friction: 0.8,
930            stop_threshold: 1.0,
931        }
932    }
933}
934
935impl DecayAnimationSpec {
936    pub fn new(friction: f32) -> Self {
937        Self {
938            friction: friction.clamp(0.01, 1.0),
939            stop_threshold: 1.0,
940        }
941    }
942}
943
944impl AnimatedValue<f32> {
945    pub fn set_target_with_velocity(&mut self, target: f32, velocity: f32) {
946        let start = self.current;
947        let distance = target - start;
948        if distance.abs() <= f32::EPSILON {
949            self.snap_to(target);
950            return;
951        }
952        self.set_target(target);
953        self.spring_v0 = if velocity.is_finite() {
954            velocity / distance
955        } else {
956            0.0
957        };
958        self.velocity = self.spring_v0;
959    }
960
961    pub fn current_velocity(&self) -> f32 {
962        if self.start_time.is_none() {
963            0.0
964        } else {
965            self.velocity * (self.target - self.start)
966        }
967    }
968
969    /// Tick the decay animation. Returns `true` if still animating.
970    pub fn update_decay(&mut self, friction: f32, stop_threshold: f32) -> bool {
971        let _start = match self.start_time {
972            Some(s) => s,
973            None => return false,
974        };
975
976        let now = now();
977        let raw_dt = match self.last_update {
978            Some(last) => now.saturating_duration_since(last),
979            None => Duration::ZERO,
980        };
981        self.last_update = Some(now);
982
983        let dt = match scaled_elapsed(raw_dt) {
984            Some(dt) => dt.as_secs_f32().min(0.05),
985            None => {
986                self.velocity = 0.0;
987                self.start_time = None;
988                return false;
989            }
990        };
991
992        if dt <= 0.0 {
993            return true;
994        }
995
996        if self.velocity.abs() < stop_threshold {
997            self.velocity = 0.0;
998            self.start_time = None;
999            return false;
1000        }
1001
1002        self.velocity *= friction.powf(dt * 60.0);
1003        let delta = self.velocity * dt;
1004        // We store the "current value" as a single f32 offset
1005        // that accumulates. But AnimatedValue<f32> stores explicit
1006        // start/target. For decay we just accumulate the current.
1007        // Because of the AnimatedValue structure, we use progress as
1008        // the accumulated value relative to start.
1009        let new_progress = self.progress + delta;
1010        self.progress = new_progress;
1011        // current = start + (target - start) * progress but target = ???.
1012        // For decay, progress IS the value (starting from 0).
1013        // We repurpose: current = start + progress (progress is offset from start).
1014        // Since T = f32, we can just set current directly.
1015        if self.progress.abs() < 0.001 && self.velocity.abs() < stop_threshold {
1016            self.progress = 0.0;
1017            self.velocity = 0.0;
1018            self.start_time = None;
1019            self.current = self.start;
1020            return false;
1021        }
1022
1023        // Clamp progress to avoid runaway extrapolation for non-f32 interpolations (shouldn't happen as this is f32-only).
1024        let clamped = self.progress.clamp(-1e6, 1e6);
1025        self.current = self.start + clamped;
1026        true
1027    }
1028}
1029
1030pub trait Interpolate {
1031    fn interpolate(&self, other: &Self, t: f32) -> Self;
1032}
1033
1034impl Interpolate for f32 {
1035    fn interpolate(&self, other: &Self, t: f32) -> Self {
1036        self + (other - self) * t
1037    }
1038}
1039
1040impl Interpolate for crate::Color {
1041    fn interpolate(&self, other: &Self, t: f32) -> Self {
1042        let lerp = |a: u8, b: u8| {
1043            (a as f32 + (b as f32 - a as f32) * t)
1044                .round()
1045                .clamp(0.0, 255.0) as u8
1046        };
1047        crate::Color(
1048            lerp(self.0, other.0),
1049            lerp(self.1, other.1),
1050            lerp(self.2, other.2),
1051            lerp(self.3, other.3),
1052        )
1053    }
1054}
1055
1056impl Interpolate for crate::Vec2 {
1057    fn interpolate(&self, other: &Self, t: f32) -> Self {
1058        crate::Vec2 {
1059            x: self.x.interpolate(&other.x, t),
1060            y: self.y.interpolate(&other.y, t),
1061        }
1062    }
1063}
1064
1065impl Interpolate for crate::Size {
1066    fn interpolate(&self, other: &Self, t: f32) -> Self {
1067        crate::Size {
1068            width: self.width.interpolate(&other.width, t),
1069            height: self.height.interpolate(&other.height, t),
1070        }
1071    }
1072}
1073
1074impl Interpolate for crate::Rect {
1075    fn interpolate(&self, other: &Self, t: f32) -> Self {
1076        crate::Rect {
1077            x: self.x.interpolate(&other.x, t),
1078            y: self.y.interpolate(&other.y, t),
1079            w: self.w.interpolate(&other.w, t),
1080            h: self.h.interpolate(&other.h, t),
1081        }
1082    }
1083}
1084
1085// Animation clock
1086pub trait Clock: Send + Sync + 'static {
1087    fn now(&self) -> Instant;
1088}
1089
1090pub struct SystemClock;
1091impl Clock for SystemClock {
1092    fn now(&self) -> Instant {
1093        Instant::now()
1094    }
1095}
1096
1097thread_local! {
1098    static CLOCK: RefCell<Rc<dyn Clock>> = RefCell::new(Rc::new(SystemClock));
1099}
1100
1101/// Install a per-thread animation clock.
1102pub fn set_clock(clock: Box<dyn Clock>) {
1103    let old = CLOCK.with(|slot| std::mem::replace(&mut *slot.borrow_mut(), Rc::from(clock)));
1104    drop(old);
1105}
1106/// Ensure a system clock is installed on this thread (always present since thread_local initializes it).
1107pub fn ensure_system_clock() {
1108    // Already initialized by thread_local default - no-op.
1109}
1110
1111/// A test clock you can drive deterministically.
1112#[derive(Clone)]
1113pub struct TestClock {
1114    pub t: Instant,
1115}
1116impl Clock for TestClock {
1117    fn now(&self) -> Instant {
1118        self.t
1119    }
1120}
1121
1122/// A shared clock whose time only moves when [`advance`](Self::advance) or
1123/// [`set`](Self::set) is called.
1124#[derive(Clone)]
1125pub struct ManualClock {
1126    now: std::sync::Arc<std::sync::Mutex<Instant>>,
1127}
1128
1129impl ManualClock {
1130    pub fn new(now: Instant) -> Self {
1131        Self {
1132            now: std::sync::Arc::new(std::sync::Mutex::new(now)),
1133        }
1134    }
1135
1136    pub fn now(&self) -> Instant {
1137        *self.now.lock().unwrap_or_else(|e| e.into_inner())
1138    }
1139
1140    pub fn set(&self, now: Instant) {
1141        *self.now.lock().unwrap_or_else(|e| e.into_inner()) = now;
1142    }
1143
1144    pub fn advance(&self, by: Duration) {
1145        let mut now = self.now.lock().unwrap_or_else(|e| e.into_inner());
1146        *now += by;
1147    }
1148}
1149
1150impl Clock for ManualClock {
1151    fn now(&self) -> Instant {
1152        ManualClock::now(self)
1153    }
1154}
1155
1156/// Animated value that transitions smoothly.
1157///
1158/// Supports two modes:
1159/// - **Tween** (when `spec.spring` is `None`): interpolates between `start` and `target`
1160///   over a fixed duration using an easing curve.
1161/// - **Spring** (when `spec.spring` is `Some`): analytically evaluates a physical spring ODE
1162///   (`x'' = -k·(x - target) - d·x'`) with emergent duration. When the target changes
1163///   mid-animation, the current value and velocity carry forward seamlessly.
1164pub struct AnimatedValue<T: Interpolate + Clone> {
1165    current: T,
1166    target: T,
1167    start: T,
1168    spec: AnimationSpec,
1169    keyframes: Option<KeyframesSpec<T>>,
1170    iteration: u32,
1171    start_time: Option<Instant>,
1172    // Spring simulation state (progress-based, works for any T: Interpolate)
1173    progress: f32,
1174    velocity: f32,
1175    /// Initial velocity for the current spring segment (carry-over from target changes).
1176    spring_v0: f32,
1177    last_update: Option<Instant>,
1178    delay_until: Option<Instant>,
1179    delay_applied: bool,
1180    reverse: bool,
1181}
1182
1183impl<T: Interpolate + Clone> AnimatedValue<T> {
1184    pub fn new(initial: T, spec: AnimationSpec) -> Self {
1185        Self {
1186            current: initial.clone(),
1187            target: initial.clone(),
1188            start: initial,
1189            spec,
1190            keyframes: None,
1191            iteration: 0,
1192            start_time: None,
1193            progress: 1.0,
1194            velocity: 0.0,
1195            spring_v0: 0.0,
1196            last_update: None,
1197            delay_until: None,
1198            delay_applied: false,
1199            reverse: false,
1200        }
1201    }
1202
1203    pub fn set_spec(&mut self, spec: AnimationSpec) {
1204        assert!(
1205            self.keyframes.is_none() || spec.spring.is_none(),
1206            "spring animations cannot use keyframes"
1207        );
1208        let changed = !same_animation_spec(&self.spec, &spec);
1209        self.spec = spec;
1210        if changed {
1211            self.iteration = 0;
1212            self.reverse = false;
1213            if self.start_time.is_some() || self.delay_until.is_some() {
1214                self.start = self.current.clone();
1215                self.start_time = Some(now());
1216                self.last_update = None;
1217                self.delay_until = None;
1218                self.delay_applied = false;
1219                self.progress = 0.0;
1220                self.spring_v0 = self.velocity;
1221            }
1222        }
1223    }
1224
1225    /// Set a keyframes spec for multi-stage animation.
1226    /// When set, `set_target` is ignored and the value is driven by the keyframe sequence.
1227    pub fn set_keyframes(&mut self, keyframes: KeyframesSpec<T>) {
1228        assert!(
1229            !keyframes.keyframes.is_empty(),
1230            "KeyframesSpec must not be empty"
1231        );
1232        assert!(
1233            self.spec.spring.is_none(),
1234            "spring animations cannot use keyframes"
1235        );
1236        self.keyframes = Some(keyframes);
1237        self.start_time = Some(now());
1238        self.last_update = None;
1239        self.delay_until = None;
1240        self.delay_applied = false;
1241        self.iteration = 0;
1242        self.reverse = false;
1243    }
1244
1245    pub fn set_target(&mut self, target: T) {
1246        // Don't call self.update() here -> self.spec may have been changed by the
1247        // caller before set_target (e.g. set_spec -> set_target). The driver's
1248        // tick() already advanced all animations before composition, so
1249        // self.current is already up to date.
1250        self.keyframes = None;
1251        self.start = self.current.clone();
1252        self.target = target;
1253        self.start_time = Some(now());
1254        self.last_update = None;
1255        self.delay_until = None;
1256        self.delay_applied = false;
1257        self.iteration = 0;
1258        self.reverse = false;
1259        if self.spec.spring.is_some() {
1260            // Spring mode: start progress at 0 (the current value), carry velocity forward
1261            self.progress = 0.0;
1262            self.spring_v0 = self.velocity;
1263        }
1264    }
1265
1266    /// Snap immediately to a value without animating.
1267    pub fn snap_to(&mut self, value: T) {
1268        self.current = value.clone();
1269        self.target = value.clone();
1270        self.start = value;
1271        self.keyframes = None;
1272        self.start_time = None;
1273        self.progress = 1.0;
1274        self.velocity = 0.0;
1275        self.spring_v0 = 0.0;
1276        self.last_update = None;
1277        self.delay_until = None;
1278        self.delay_applied = true;
1279        self.iteration = 0;
1280        self.reverse = false;
1281    }
1282
1283    pub fn update(&mut self) -> bool {
1284        if self.waiting_for_repeat() {
1285            return true;
1286        }
1287        let spring_spec = self.spec.spring;
1288        let mut still = if let Some(spring) = spring_spec {
1289            self.update_spring(&spring)
1290        } else if self.keyframes.is_some() {
1291            self.update_keyframes()
1292        } else {
1293            self.update_tween()
1294        };
1295
1296        if !still && let Some(repeat) = self.spec.repeat {
1297            let maxed = repeat
1298                .iterations
1299                .is_some_and(|max| self.iteration + 1 >= max);
1300            if !maxed {
1301                self.iteration += 1;
1302                self.start_time = None;
1303                self.last_update = None;
1304                self.progress = 0.0;
1305                self.velocity = 0.0;
1306                self.spring_v0 = 0.0;
1307                self.delay_applied = true;
1308                self.reverse = repeat.reverse && !self.reverse;
1309                if self.keyframes.is_none() && repeat.reverse {
1310                    std::mem::swap(&mut self.start, &mut self.target);
1311                }
1312                let start = now();
1313                if repeat.delay_between.is_zero() {
1314                    self.start_time = Some(start);
1315                } else {
1316                    self.delay_until = Some(start + repeat.delay_between);
1317                }
1318                still = true;
1319            }
1320        }
1321
1322        still
1323    }
1324
1325    fn waiting_for_repeat(&mut self) -> bool {
1326        let Some(until) = self.delay_until else {
1327            return false;
1328        };
1329        let current = now();
1330        if current < until {
1331            return true;
1332        }
1333        self.delay_until = None;
1334        self.start_time = Some(until);
1335        self.delay_applied = true;
1336        self.last_update = None;
1337        false
1338    }
1339
1340    fn update_keyframes(&mut self) -> bool {
1341        let start = match self.start_time {
1342            Some(s) => s,
1343            None => return false,
1344        };
1345        let elapsed = match scaled_elapsed(now().saturating_duration_since(start)) {
1346            Some(elapsed) => elapsed,
1347            None => {
1348                if let Some(ref kf) = self.keyframes {
1349                    self.current = kf.evaluate(if self.reverse { 0.0 } else { 1.0 });
1350                }
1351                self.start_time = None;
1352                return false;
1353            }
1354        };
1355        let delay = if self.delay_applied {
1356            Duration::ZERO
1357        } else {
1358            self.spec.delay
1359        };
1360        if elapsed < delay {
1361            return true;
1362        }
1363        self.delay_applied = true;
1364        let animation_time = elapsed - delay;
1365        if animation_time >= self.spec.duration || self.spec.duration.is_zero() {
1366            if let Some(ref kf) = self.keyframes {
1367                self.current = kf.evaluate(if self.reverse { 0.0 } else { 1.0 });
1368            }
1369            self.start_time = None;
1370            return false;
1371        }
1372        let t = (animation_time.as_secs_f32() / self.spec.duration.as_secs_f32()).clamp(0.0, 1.0);
1373        let eased_t = self.spec.easing.interpolate(t);
1374        if let Some(ref kf) = self.keyframes {
1375            let sample_t = if self.reverse { 1.0 - eased_t } else { eased_t };
1376            self.current = kf.evaluate(sample_t);
1377        }
1378        true
1379    }
1380
1381    fn update_spring(&mut self, spring: &SpringSpec) -> bool {
1382        let start = match self.start_time {
1383            Some(s) => s,
1384            None => return false,
1385        };
1386
1387        let elapsed = match scaled_elapsed(now().saturating_duration_since(start)) {
1388            Some(elapsed) => elapsed,
1389            None => {
1390                self.progress = 1.0;
1391                self.velocity = 0.0;
1392                self.spring_v0 = 0.0;
1393                self.current = self.target.clone();
1394                self.start_time = None;
1395                self.last_update = None;
1396                return false;
1397            }
1398        };
1399
1400        let delay = if self.delay_applied {
1401            Duration::ZERO
1402        } else {
1403            self.spec.delay
1404        };
1405        if elapsed < delay {
1406            return true;
1407        }
1408        self.delay_applied = true;
1409
1410        let t = (elapsed - delay).as_secs_f32().max(0.0);
1411        let (progress, velocity) = spring_analytical(
1412            spring.damping_ratio,
1413            spring.stiffness,
1414            t,
1415            0.0,
1416            self.spring_v0,
1417        );
1418        let progress = progress.clamp(-0.1, 2.0);
1419        if !progress.is_finite() || !velocity.is_finite() {
1420            self.progress = 1.0;
1421            self.velocity = 0.0;
1422            self.spring_v0 = 0.0;
1423            self.current = self.target.clone();
1424            self.start_time = None;
1425            self.last_update = None;
1426            return false;
1427        }
1428
1429        if (progress - 1.0).abs() < spring.settle_progress
1430            && velocity.abs() < spring.settle_velocity
1431        {
1432            self.progress = 1.0;
1433            self.velocity = 0.0;
1434            self.spring_v0 = 0.0;
1435            self.current = self.target.clone();
1436            self.start_time = None;
1437            self.last_update = None;
1438            return false;
1439        }
1440
1441        self.progress = progress;
1442        self.velocity = velocity;
1443        self.current = self.start.interpolate(&self.target, self.progress);
1444        true
1445    }
1446
1447    fn update_tween(&mut self) -> bool {
1448        if let Some(start) = self.start_time {
1449            let elapsed = match scaled_elapsed(now().saturating_duration_since(start)) {
1450                Some(elapsed) => elapsed,
1451                None => {
1452                    self.current = self.target.clone();
1453                    self.start_time = None;
1454                    return false;
1455                }
1456            };
1457            let delay = if self.delay_applied {
1458                Duration::ZERO
1459            } else {
1460                self.spec.delay
1461            };
1462
1463            if elapsed < delay {
1464                return true;
1465            }
1466            self.delay_applied = true;
1467
1468            let animation_time = elapsed - delay;
1469
1470            if animation_time >= self.spec.duration || self.spec.duration.is_zero() {
1471                self.current = self.target.clone();
1472                self.start_time = None;
1473                return false;
1474            }
1475
1476            let t =
1477                (animation_time.as_secs_f32() / self.spec.duration.as_secs_f32()).clamp(0.0, 1.0);
1478            let eased_t = self.spec.easing.interpolate(t);
1479
1480            self.current = self.start.interpolate(&self.target, eased_t);
1481            true
1482        } else {
1483            false
1484        }
1485    }
1486
1487    pub fn get(&self) -> &T {
1488        &self.current
1489    }
1490
1491    pub fn is_animating(&self) -> bool {
1492        self.start_time.is_some() || self.delay_until.is_some()
1493    }
1494
1495    pub fn has_keyframes(&self) -> bool {
1496        self.keyframes.is_some()
1497    }
1498}
1499
1500#[cfg(test)]
1501mod tests {
1502    use super::*;
1503
1504    fn assert_in_out(ease: Easing) {
1505        // All sane eases pass through (0,0) and (1,1).
1506        assert!((ease.interpolate(0.0) - 0.0).abs() < 1e-4, "{ease:?} in(0)");
1507        assert!((ease.interpolate(1.0) - 1.0).abs() < 1e-4, "{ease:?} in(1)");
1508    }
1509
1510    #[test]
1511    fn godot_eases_pass_through_endpoints() {
1512        use Easing::*;
1513        for ease in [
1514            CubicIn,
1515            CubicOut,
1516            CubicInOut,
1517            QuartIn,
1518            QuartOut,
1519            QuartInOut,
1520            QuintIn,
1521            QuintOut,
1522            QuintInOut,
1523            SineIn,
1524            SineOut,
1525            SineInOut,
1526            ExpoIn,
1527            ExpoOut,
1528            ExpoInOut,
1529            CircIn,
1530            CircOut,
1531            CircInOut,
1532            BackIn,
1533            BackOut,
1534            BackInOut,
1535            ElasticIn,
1536            ElasticOut,
1537            ElasticInOut,
1538            BounceIn,
1539            BounceOut,
1540            BounceInOut,
1541        ] {
1542            assert_in_out(ease);
1543        }
1544    }
1545
1546    #[test]
1547    fn easing_direction_is_sane() {
1548        use Easing::*;
1549        let mid = [CubicOut, QuartOut, QuintOut, SineOut, ExpoOut, CircOut];
1550        for e in mid {
1551            assert!(e.interpolate(0.5) <= 1.0, "{e:?} stays below 1 at mid");
1552            assert!(e.interpolate(0.5) > 0.5, "{e:?} is ease-out at mid");
1553        }
1554        for e in [CubicIn, QuartIn, QuintIn, SineIn, ExpoIn, CircIn] {
1555            assert!(e.interpolate(0.5) < 0.5, "{e:?} is ease-in at mid");
1556        }
1557        // Overshoot eases exceed the [0,1] band in the middle.
1558        for e in [BackOut, ElasticOut] {
1559            assert!(e.interpolate(0.5) > 1.0, "{e:?} overshoots");
1560        }
1561        for e in [BackIn, ElasticIn] {
1562            assert!(e.interpolate(0.5) < 0.0, "{e:?} undershoots");
1563        }
1564    }
1565
1566    #[test]
1567    fn ease_kind_endpoints_hold() {
1568        for ease in [
1569            EaseKind::Linear,
1570            EaseKind::QuadOut,
1571            EaseKind::CubicOut,
1572            EaseKind::BackOut,
1573        ] {
1574            assert!(ease.apply(0.0).abs() < 1e-4);
1575            assert!((ease.apply(1.0) - 1.0).abs() < 1e-4);
1576        }
1577        assert!(EaseKind::QuadOut.apply(0.5) > 0.5);
1578    }
1579
1580    #[test]
1581    fn bounce_matches_known_values() {
1582        use Easing::*;
1583        assert!((BounceOut.interpolate(0.0) - 0.0).abs() < 1e-4);
1584        assert!((BounceOut.interpolate(1.0) - 1.0).abs() < 1e-4);
1585        // Bounce out reaches its first apex (1.0) at t = 1/2.75, then settles.
1586        assert!((BounceOut.interpolate(1.0 / 2.75) - 1.0).abs() < 1e-4);
1587        assert!((BounceOut.interpolate(0.5) - 0.765625).abs() < 1e-4);
1588    }
1589
1590    #[test]
1591    fn monospline_duplicate_times_stay_finite() {
1592        // Regression: duplicate times divided by zero dt, yielding inf/NaN
1593        // tangents that silently corrupted every later evaluation.
1594        let s = MonoSpline::new(vec![0.0, 0.5, 0.5, 1.0], vec![0.0, 1.0, 1.0, 2.0]);
1595        for t in [0.0, 0.25, 0.5, 0.75, 1.0] {
1596            assert!(s.evaluate(t).is_finite(), "t={t}");
1597        }
1598    }
1599
1600    #[test]
1601    fn motion_duration_scale_scales_elapsed() {
1602        with_motion_duration_scale(2.0, || {
1603            let scaled = scaled_elapsed(Duration::from_millis(100)).expect("enabled");
1604            assert!((scaled.as_secs_f32() - 0.05).abs() < 1e-4);
1605        });
1606        with_motion_duration_scale(0.0, || {
1607            assert_eq!(scaled_elapsed(Duration::from_millis(100)), None);
1608        });
1609        with_motion_duration_scale(1.0, || {
1610            let scaled = scaled_elapsed(Duration::from_millis(100)).expect("enabled");
1611            assert!((scaled.as_secs_f32() - 0.1).abs() < 1e-4);
1612        });
1613    }
1614
1615    #[test]
1616    fn scroll_offset_sanitizes_nan() {
1617        // Regression: `off.clamp(0,max)` propagates NaN into the signal.
1618        let st = crate::scroll::ScrollState::new();
1619        st.set_viewport_height(100.0);
1620        st.set_content_height(1000.0);
1621        st.set_offset(f32::NAN);
1622        assert!(st.get().is_finite());
1623        assert_eq!(st.get(), 0.0);
1624        let leftover = st.scroll_immediate(f32::NAN);
1625        assert!(leftover.is_finite());
1626        assert!(st.get().is_finite());
1627    }
1628}