| 1 | #[derive(Debug, Clone, Copy)] |
| 2 | pub struct RubberBand { |
| 3 | pub stiffness: f64, |
| 4 | pub limit: f64, |
| 5 | } |
| 6 | |
| 7 | impl RubberBand { |
| 8 | pub fn band(&self, x: f64) -> f64 { |
| 9 | let c = self.stiffness; |
| 10 | let d = self.limit; |
| 11 | |
| 12 | (1. - (1. / (x * c / d + 1.))) * d |
| 13 | } |
| 14 | |
| 15 | pub fn derivative(&self, x: f64) -> f64 { |
| 16 | let c = self.stiffness; |
| 17 | let d = self.limit; |
| 18 | |
| 19 | c * d * d / (c * x + d).powi(2) |
| 20 | } |
| 21 | |
| 22 | pub fn clamp(&self, min: f64, max: f64, x: f64) -> f64 { |
| 23 | let clamped = x.clamp(min, max); |
| 24 | let sign = if x < clamped { -1. } else { 1. }; |
| 25 | let diff = (x - clamped).abs(); |
| 26 | |
| 27 | clamped + sign * self.band(diff) |
| 28 | } |
| 29 | |
| 30 | pub fn clamp_derivative(&self, min: f64, max: f64, x: f64) -> f64 { |
| 31 | if min <= x && x <= max { |
| 32 | return 1.; |
| 33 | } |
| 34 | |
| 35 | let clamped = x.clamp(min, max); |
| 36 | let diff = (x - clamped).abs(); |
| 37 | self.derivative(diff) |
| 38 | } |
| 39 | } |