yoyo_physics/
threshold.rs

1//! Threshold traits and types that are used to stop a pending animation.
2
3use num_traits::Float;
4
5use super::Approximation;
6
7/// Implemented by types that can evaluate an approximation and determine if it
8/// is resting.
9pub trait Threshold {
10    /// The type of value that this threshold applies to.
11    type Value;
12
13    /// The type of velocity that this threshold applies to.
14    type Velocity;
15
16    /// This function should evaluate the given approximate and return a boolean
17    /// that indicates if the threshold for resting is met.
18    fn evaluate(&mut self, approximation: &Approximation<Self::Value, Self::Velocity>) -> bool;
19}
20
21/// This threshold evaluates to true if both of the given thresholds evaluate to
22/// true.
23pub struct And<A, B>(pub A, pub B)
24where
25    A: Threshold,
26    B: Threshold<Value = A::Value>;
27
28impl<A, B> Threshold for And<A, B>
29where
30    A: Threshold,
31    B: Threshold<Value = A::Value, Velocity = A::Velocity>,
32{
33    type Value = A::Value;
34    type Velocity = A::Velocity;
35
36    fn evaluate(&mut self, approximation: &Approximation<Self::Value, Self::Velocity>) -> bool {
37        self.0.evaluate(approximation) && self.1.evaluate(approximation)
38    }
39}
40
41/// This threshold evaluates to true if the displacement of a running animation
42/// drops below the given threshold value.
43pub struct DisplacementThreshold<T>
44where
45    T: Float,
46{
47    /// This is the target value of an animation.
48    pub target: T,
49
50    /// This is the sensitivity of this threshold.
51    pub sensitivity: T,
52}
53
54impl<T> Threshold for DisplacementThreshold<T>
55where
56    T: Float,
57{
58    type Value = T;
59    type Velocity = T;
60
61    fn evaluate(&mut self, approximation: &Approximation<Self::Value, Self::Velocity>) -> bool {
62        let displacement = approximation.value.sub(self.target);
63
64        displacement.abs() <= self.sensitivity
65    }
66}
67
68/// This threshold evaluates to true if the displacement of a running animation
69/// drops below the given threshold value.
70pub struct VelocityThreshold<T>(pub T);
71
72impl<T> Threshold for VelocityThreshold<T>
73where
74    T: Float,
75{
76    type Value = T;
77    type Velocity = T;
78
79    fn evaluate(&mut self, approximation: &Approximation<Self::Value, Self::Velocity>) -> bool {
80        approximation.velocity.abs() <= self.0
81    }
82}