Skip to main content

waft_physics/
friction_simulation.rs

1//! Flutter counterpart: `physics/friction_simulation.dart`.
2
3use std::fmt::{self, Debug};
4
5use waft_embedder::clamp_double;
6
7use crate::{Simulation, Tolerance};
8
9/// Numerically determine the input value which produces output value `target`
10/// for a function `f`, given its first-derivative `df`.
11fn newtons_method(
12    initial_guess: f64,
13    target: f64,
14    f: impl Fn(f64) -> f64,
15    df: impl Fn(f64) -> f64,
16    iterations: i32,
17) -> f64 {
18    let mut guess = initial_guess;
19    for _ in 0..iterations {
20        guess -= (f(guess) - target) / df(guess);
21    }
22    guess
23}
24
25/// A simulation that applies a drag to slow a particle down.
26///
27/// Models a particle affected by fluid drag, e.g. air resistance.
28///
29/// The simulation ends when the velocity of the particle drops to zero (within
30/// the current velocity [`tolerance`](Simulation::tolerance)).
31pub struct FrictionSimulation {
32    drag: f64,
33    drag_log: f64,
34    x0: f64,
35    v0: f64,
36    constant_deceleration: f64,
37    /// The time at which the simulation should be stopped.
38    /// This is needed when constantDeceleration is not zero (on Desktop), when
39    /// using the pure friction simulation, acceleration naturally reduces to zero
40    /// and creates a stopping point.
41    final_time: f64,
42    /// How close to the actual end of the simulation a value at a particular
43    /// time must be before [`is_done`](Simulation::is_done) considers the
44    /// simulation to be "done".
45    pub tolerance: Tolerance,
46}
47
48impl FrictionSimulation {
49    /// Creates a [`FrictionSimulation`] with the given arguments, namely: the
50    /// fluid drag coefficient _cₓ_, a unitless value; the initial position
51    /// _x₀_, in the same length units as used for [`x`](Simulation::x); and the
52    /// initial velocity _dx₀_, in the same velocity units as used for
53    /// [`dx`](Simulation::dx).
54    pub fn new(drag: f64, position: f64, velocity: f64) -> FrictionSimulation {
55        FrictionSimulation::with_options(
56            drag,
57            position,
58            velocity,
59            Tolerance::DEFAULT_TOLERANCE,
60            0.0,
61        )
62    }
63
64    /// Dart's `tolerance` / `constantDeceleration` named arguments.
65    pub fn with_options(
66        drag: f64,
67        position: f64,
68        velocity: f64,
69        tolerance: Tolerance,
70        constant_deceleration: f64,
71    ) -> FrictionSimulation {
72        let constant_deceleration = constant_deceleration * velocity.signum();
73        let mut simulation = FrictionSimulation {
74            drag,
75            drag_log: drag.ln(),
76            x0: position,
77            v0: velocity,
78            constant_deceleration,
79            final_time: f64::INFINITY,
80            tolerance,
81        };
82        // Needs to be infinity for newtonsMethod call in constructor.
83        simulation.final_time = newtons_method(
84            0.0,
85            0.0,
86            |time| simulation.dx(time),
87            |time| {
88                (simulation.v0 * simulation.drag.powf(time) * simulation.drag_log)
89                    - simulation.constant_deceleration
90            },
91            10,
92        );
93        simulation
94    }
95
96    /// Creates a new friction simulation with its fluid drag coefficient (_cₓ_)
97    /// set so as to ensure that the simulation starts and ends at the specified
98    /// positions and velocities.
99    ///
100    /// The positions must use the same units as expected from [`x`](Simulation::x),
101    /// and the velocities must use the same units as expected from
102    /// [`dx`](Simulation::dx).
103    ///
104    /// The sign of the start and end velocities must be the same, the magnitude
105    /// of the start velocity must be greater than the magnitude of the end
106    /// velocity, and the velocities must be in the direction appropriate for the
107    /// particle to start from the start position and reach the end position.
108    pub fn through(
109        start_position: f64,
110        end_position: f64,
111        start_velocity: f64,
112        end_velocity: f64,
113    ) -> FrictionSimulation {
114        debug_assert!(
115            start_velocity == 0.0
116                || end_velocity == 0.0
117                || start_velocity.signum() == end_velocity.signum()
118        );
119        debug_assert!(start_velocity.abs() >= end_velocity.abs());
120        debug_assert!((end_position - start_position).signum() == start_velocity.signum());
121        FrictionSimulation::with_options(
122            drag_for(start_position, end_position, start_velocity, end_velocity),
123            start_position,
124            start_velocity,
125            Tolerance {
126                velocity: end_velocity.abs(),
127                ..Tolerance::DEFAULT_TOLERANCE
128            },
129            0.0,
130        )
131    }
132
133    /// The value of [`x`](Simulation::x) at `f64::INFINITY`.
134    pub fn final_x(&self) -> f64 {
135        if self.constant_deceleration == 0.0 {
136            self.x0 - self.v0 / self.drag_log
137        } else {
138            self.x(self.final_time)
139        }
140    }
141
142    /// The time at which the value of `x(time)` will equal `x`.
143    ///
144    /// Returns `f64::INFINITY` if the simulation will never reach `x`.
145    pub fn time_at_x(&self, x: f64) -> f64 {
146        if x == self.x0 {
147            return 0.0;
148        }
149        if self.v0 == 0.0
150            || (if self.v0 > 0.0 {
151                x < self.x0 || x > self.final_x()
152            } else {
153                x > self.x0 || x < self.final_x()
154            })
155        {
156            return f64::INFINITY;
157        }
158        newtons_method(0.0, x, |time| self.x(time), |time| self.dx(time), 10)
159    }
160}
161
162/// Return the drag value for a FrictionSimulation whose x() and dx() values
163/// pass through the specified start and end position/velocity values.
164///
165/// Total time to reach endVelocity is just: (log(endVelocity) / log(startVelocity)) / log(_drag)
166/// or (log(v1) - log(v0)) / log(D), given v = v0 * D^t per the dx() function below.
167/// Solving for D given x(time) is trickier. Algebra courtesy of Wolfram Alpha:
168/// x1 = x0 + (v0 * D^((log(v1) - log(v0)) / log(D))) / log(D) - v0 / log(D), find D
169fn drag_for(start_position: f64, end_position: f64, start_velocity: f64, end_velocity: f64) -> f64 {
170    ((start_velocity - end_velocity) / (start_position - end_position)).exp()
171}
172
173impl Simulation for FrictionSimulation {
174    fn x(&self, time: f64) -> f64 {
175        if time > self.final_time {
176            return self.final_x();
177        }
178        self.x0 + self.v0 * self.drag.powf(time) / self.drag_log
179            - self.v0 / self.drag_log
180            - ((self.constant_deceleration / 2.0) * time * time)
181    }
182
183    fn dx(&self, time: f64) -> f64 {
184        if time > self.final_time {
185            return 0.0;
186        }
187        self.v0 * self.drag.powf(time) - self.constant_deceleration * time
188    }
189
190    fn is_done(&self, time: f64) -> bool {
191        self.dx(time).abs() < self.tolerance.velocity
192    }
193
194    fn tolerance(&self) -> Tolerance {
195        self.tolerance
196    }
197
198    fn set_tolerance(&mut self, tolerance: Tolerance) {
199        self.tolerance = tolerance;
200    }
201}
202
203impl Debug for FrictionSimulation {
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        write!(
206            f,
207            "FrictionSimulation(cₓ: {:.1}, x₀: {:.1}, dx₀: {:.1})",
208            self.drag, self.x0, self.v0
209        )
210    }
211}
212
213/// A [`FrictionSimulation`] that clamps the modeled particle to a specific
214/// range of values.
215///
216/// Only the position is clamped. The velocity [`dx`](Simulation::dx) will
217/// continue to report unbounded simulated velocities once the particle has
218/// reached the bounds.
219pub struct BoundedFrictionSimulation {
220    inner: FrictionSimulation,
221    min_x: f64,
222    max_x: f64,
223}
224
225impl BoundedFrictionSimulation {
226    /// Creates a [`BoundedFrictionSimulation`] with the given arguments, namely:
227    /// the fluid drag coefficient _cₓ_, a unitless value; the initial position
228    /// _x₀_, in the same length units as used for [`x`](Simulation::x); the
229    /// initial velocity _dx₀_, in the same velocity units as used for
230    /// [`dx`](Simulation::dx), the minimum value for the position, and the
231    /// maximum value for the position. The minimum and maximum values must be
232    /// in the same units as the initial position, and the initial position must
233    /// be within the given range.
234    pub fn new(
235        drag: f64,
236        position: f64,
237        velocity: f64,
238        min_x: f64,
239        max_x: f64,
240    ) -> BoundedFrictionSimulation {
241        debug_assert!(clamp_double(position, min_x, max_x) == position);
242        BoundedFrictionSimulation {
243            inner: FrictionSimulation::new(drag, position, velocity),
244            min_x,
245            max_x,
246        }
247    }
248}
249
250impl Simulation for BoundedFrictionSimulation {
251    fn x(&self, time: f64) -> f64 {
252        clamp_double(self.inner.x(time), self.min_x, self.max_x)
253    }
254
255    fn dx(&self, time: f64) -> f64 {
256        self.inner.dx(time)
257    }
258
259    fn is_done(&self, time: f64) -> bool {
260        self.inner.is_done(time)
261            || (self.x(time) - self.min_x).abs() < self.tolerance().distance
262            || (self.x(time) - self.max_x).abs() < self.tolerance().distance
263    }
264
265    fn tolerance(&self) -> Tolerance {
266        self.inner.tolerance()
267    }
268
269    fn set_tolerance(&mut self, tolerance: Tolerance) {
270        self.inner.set_tolerance(tolerance);
271    }
272}
273
274impl Debug for BoundedFrictionSimulation {
275    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276        write!(
277            f,
278            "BoundedFrictionSimulation(cₓ: {:.1}, x₀: {:.1}, dx₀: {:.1}, x: {:.1}..{:.1})",
279            self.inner.drag, self.inner.x0, self.inner.v0, self.min_x, self.max_x
280        )
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287    use crate::Simulation;
288
289    fn approx(actual: f64, expected: f64, epsilon: f64) {
290        assert!(
291            (actual - expected).abs() <= epsilon,
292            "{actual} != {expected} ±{epsilon}"
293        );
294    }
295
296    #[test]
297    fn friction_simulation_positive_velocity() {
298        let friction = FrictionSimulation::new(0.135, 100.0, 100.0);
299
300        approx(friction.x(0.0), 100.0, 1e-10);
301        approx(friction.dx(0.0), 100.0, 1e-10);
302
303        approx(friction.x(0.1), 110.0, 1.0);
304        approx(friction.x(0.5), 131.0, 1.0);
305        approx(friction.x(2.0), 149.0, 1.0);
306
307        approx(friction.final_x(), 149.0, 1.0);
308
309        assert_eq!(friction.time_at_x(100.0), 0.0);
310        approx(friction.time_at_x(friction.x(0.1)), 0.1, 1e-10);
311        approx(friction.time_at_x(friction.x(0.5)), 0.5, 1e-10);
312        approx(friction.time_at_x(friction.x(2.0)), 2.0, 1e-10);
313
314        assert_eq!(friction.time_at_x(-1.0), f64::INFINITY);
315        assert_eq!(friction.time_at_x(200.0), f64::INFINITY);
316    }
317
318    #[test]
319    fn friction_simulation_negative_velocity() {
320        let friction = FrictionSimulation::new(0.135, 100.0, -100.0);
321
322        approx(friction.x(0.0), 100.0, 1e-10);
323        approx(friction.dx(0.0), -100.0, 1e-10);
324
325        approx(friction.x(0.1), 91.0, 1.0);
326        approx(friction.x(0.5), 68.0, 1.0);
327        approx(friction.x(2.0), 51.0, 1.0);
328
329        approx(friction.final_x(), 50.0, 1.0);
330
331        assert_eq!(friction.time_at_x(100.0), 0.0);
332        approx(friction.time_at_x(friction.x(0.1)), 0.1, 1e-10);
333        approx(friction.time_at_x(friction.x(0.5)), 0.5, 1e-10);
334        approx(friction.time_at_x(friction.x(2.0)), 2.0, 1e-10);
335
336        assert_eq!(friction.time_at_x(101.0), f64::INFINITY);
337        assert_eq!(friction.time_at_x(40.0), f64::INFINITY);
338    }
339
340    #[test]
341    fn friction_simulation_constant_deceleration() {
342        let friction = FrictionSimulation::with_options(
343            0.135,
344            100.0,
345            -100.0,
346            Tolerance::DEFAULT_TOLERANCE,
347            100.0,
348        );
349
350        approx(friction.x(0.0), 100.0, 1e-10);
351        approx(friction.dx(0.0), -100.0, 1e-10);
352
353        approx(friction.x(0.1), 91.0, 1.0);
354        approx(friction.x(0.5), 80.0, 1.0);
355        approx(friction.x(2.0), 80.0, 1.0);
356
357        approx(friction.final_x(), 80.0, 1.0);
358
359        assert_eq!(friction.time_at_x(100.0), 0.0);
360        approx(friction.time_at_x(friction.x(0.1)), 0.1, 1e-10);
361        approx(friction.time_at_x(friction.x(0.2)), 0.2, 1e-10);
362        approx(friction.time_at_x(friction.x(0.3)), 0.3, 1e-10);
363
364        assert_eq!(friction.time_at_x(101.0), f64::INFINITY);
365        assert_eq!(friction.time_at_x(40.0), f64::INFINITY);
366    }
367
368    #[test]
369    fn test_friction() {
370        let mut friction = FrictionSimulation::new(0.3, 100.0, 400.0);
371        friction.tolerance = Tolerance {
372            velocity: 1.0,
373            ..Tolerance::DEFAULT_TOLERANCE
374        };
375
376        assert!(!friction.is_done(0.0));
377        assert_eq!(friction.x(0.0), 100.0);
378        assert_eq!(friction.dx(0.0), 400.0);
379
380        assert!(friction.x(1.0) > 330.0 && friction.x(1.0) < 335.0);
381
382        assert_eq!(friction.dx(1.0), 120.0);
383        assert_eq!(friction.dx(2.0), 36.0);
384        approx(friction.dx(3.0), 10.8, 1e-10);
385        assert!(friction.dx(4.0) < 3.5);
386
387        assert!(friction.is_done(5.0));
388        assert!(friction.x(5.0) > 431.0 && friction.x(5.0) < 432.0);
389    }
390
391    #[test]
392    fn test_friction_through() {
393        let start_position = 10.0;
394        let start_velocity = 600.0;
395        let f = FrictionSimulation::new(0.025, start_position, start_velocity);
396        let end_position = f.x(1.0);
397        let end_velocity = f.dx(1.0);
398        assert!(end_position > start_position);
399        assert!(end_velocity < start_velocity);
400
401        let friction =
402            FrictionSimulation::through(start_position, end_position, start_velocity, end_velocity);
403        assert!(!friction.is_done(0.0));
404        assert_eq!(friction.x(0.0), 10.0);
405        assert_eq!(friction.dx(0.0), 600.0);
406
407        assert!(friction.is_done(1.0 + 1e-10));
408        approx(friction.x(1.0), end_position, 1e-10);
409        approx(friction.dx(1.0), end_velocity, 1e-10);
410
411        let start_position = 1000.0;
412        let start_velocity = -500.0;
413        let f = FrictionSimulation::new(0.025, 1000.0, -500.0);
414        let end_position = f.x(1.0);
415        let end_velocity = f.dx(1.0);
416        assert!(end_position < start_position);
417        assert!(end_velocity > start_velocity);
418
419        let friction =
420            FrictionSimulation::through(start_position, end_position, start_velocity, end_velocity);
421        assert!(friction.is_done(1.0 + 1e-10));
422        approx(friction.x(1.0), end_position, 1e-10);
423        approx(friction.dx(1.0), end_velocity, 1e-10);
424    }
425
426    #[test]
427    fn bounded_friction_simulation_control_test() {
428        let mut friction = BoundedFrictionSimulation::new(0.3, 100.0, 400.0, 50.0, 150.0);
429        friction.set_tolerance(Tolerance {
430            velocity: 1.0,
431            ..Tolerance::DEFAULT_TOLERANCE
432        });
433
434        assert!(!friction.is_done(0.0));
435        assert_eq!(friction.x(0.0), 100.0);
436        assert_eq!(friction.dx(0.0), 400.0);
437
438        assert_eq!(friction.x(1.0), 150.0);
439
440        assert!(friction.is_done(1.0));
441    }
442}