Skip to main content

ferroui_base/animation/easings/
spring_easing.rs

1use crate::animation::easings::IEasing;
2use crate::utilities::spring_solver::SpringSolver;
3use crate::animation::Spring;
4
5/// Eases a value using a user-defined spring formula.
6pub struct SpringEasing {
7    internal_spring: Spring,
8}
9
10impl SpringEasing {
11    /// Creates a spring easing with all parameters zero.
12    pub fn new() -> Self {
13        Self { internal_spring: Spring::new() }
14    }
15
16    /// Creates a spring easing with the given parameters.
17    pub fn with_values(mass: f64, stiffness: f64, damping: f64, initial_velocity: f64) -> Self {
18        Self { internal_spring: Spring::with_values(mass, stiffness, damping, initial_velocity) }
19    }
20
21    /// The spring mass.
22    pub fn mass(&self) -> f64 {
23        self.internal_spring.mass()
24    }
25
26    pub fn set_mass(&self, value: f64) {
27        self.internal_spring.set_mass(value)
28    }
29
30    /// The spring stiffness.
31    pub fn stiffness(&self) -> f64 {
32        self.internal_spring.stiffness()
33    }
34
35    pub fn set_stiffness(&self, value: f64) {
36        self.internal_spring.set_stiffness(value)
37    }
38
39    /// The spring damping.
40    pub fn damping(&self) -> f64 {
41        self.internal_spring.damping()
42    }
43
44    pub fn set_damping(&self, value: f64) {
45        self.internal_spring.set_damping(value)
46    }
47
48    /// The spring initial velocity.
49    pub fn initial_velocity(&self) -> f64 {
50        self.internal_spring.initial_velocity()
51    }
52
53    pub fn set_initial_velocity(&self, value: f64) {
54        self.internal_spring.set_initial_velocity(value)
55    }
56}
57
58impl Default for SpringEasing {
59    fn default() -> Self {
60        Self::new()
61    }
62}
63
64impl IEasing for SpringEasing {
65    fn to_shared(&self) -> std::sync::Arc<crate::animation::easings::SharedEasing> {
66        let spring = &self.internal_spring;
67        std::sync::Arc::new(SharedSpringEasing(SpringSolver::new(
68            spring.mass(),
69            spring.stiffness(),
70            spring.damping(),
71            spring.initial_velocity(),
72        )))
73    }
74
75    fn ease(&self, progress: f64) -> f64 {
76        self.internal_spring.get_spring_progress(progress)
77    }
78}
79
80/// A spring easing with the parameters it had when it was shared.
81struct SharedSpringEasing(SpringSolver);
82
83impl IEasing for SharedSpringEasing {
84    fn to_shared(&self) -> std::sync::Arc<crate::animation::easings::SharedEasing> {
85        std::sync::Arc::new(SharedSpringEasing(self.0))
86    }
87
88    fn ease(&self, progress: f64) -> f64 {
89        self.0.solve(progress)
90    }
91}