From d47b59879a595fca84bd9995babf200faa94325f Mon Sep 17 00:00:00 2001 From: Ivan Molodetskikh Date: Thu, 13 Feb 2025 08:45:23 +0300 Subject: animation/spring: Add a check for from = to in duration() The overdamped code below was dividing by zero in this case and triggering a panic. --- src/animation/spring.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/animation/spring.rs b/src/animation/spring.rs index 226d7cc2..f7bcb1e4 100644 --- a/src/animation/spring.rs +++ b/src/animation/spring.rs @@ -54,6 +54,10 @@ impl Spring { return Duration::MAX; } + if (self.to - self.from).abs() <= f64::EPSILON { + return Duration::ZERO; + } + let omega0 = (self.params.stiffness / self.params.mass).sqrt(); // As first ansatz for the overdamped solution, @@ -166,3 +170,21 @@ impl Spring { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn overdamped_spring_equal_from_to_nan() { + let spring = Spring { + from: 0., + to: 0., + initial_velocity: 0., + params: SpringParams::new(1.15, 850., 0.0001), + }; + let _ = spring.duration(); + let _ = spring.clamped_duration(); + let _ = spring.value_at(Duration::ZERO); + } +} -- cgit