Skip to main content

waft_animation/
curves.rs

1//! Flutter counterpart: `animation/curves.dart`.
2
3use std::any::Any;
4use std::f64::consts::PI;
5use std::fmt::{self, Debug};
6use std::rc::Rc;
7
8use waft_embedder::{Offset, clamp_double, lerp_double};
9
10/// An parametric animation easing curve, i.e. a mapping of the unit interval to
11/// the unit interval.
12///
13/// Easing curves are used to adjust the rate of change of an animation over
14/// time, allowing them to speed up and slow down, rather than moving at a
15/// constant rate.
16///
17/// A [`Curve`] must map t=0.0 to 0.0 and t=1.0 to 1.0.
18///
19/// See also:
20///
21///  * [`Curves`], a collection of common animation easing curves.
22///  * `CurveTween`, which can be used to apply a [`Curve`] to an `Animation`.
23///  * `Animatable`, for a more flexible interface that maps fractions to
24///    arbitrary values.
25///
26/// # Implementing a curve
27///
28/// Override [`transform_internal`](Curve::transform_internal). Its default
29/// panics, matching the `UnimplementedError` Dart throws, because a curve may
30/// instead override [`transform`](Curve::transform) whole — [`Split`] does.
31pub trait Curve: Any + Debug {
32    /// Returns the value of the curve at point `t`.
33    ///
34    /// This function must ensure the following:
35    /// - The value of `t` must be between 0.0 and 1.0
36    /// - Values of `t`=0.0 and `t`=1.0 must be mapped to 0.0 and 1.0,
37    ///   respectively.
38    ///
39    /// It is recommended that implementors override
40    /// [`transform_internal`](Curve::transform_internal) instead of this
41    /// function, as the above cases are already handled in the default
42    /// implementation of [`transform`](Curve::transform), which delegates the
43    /// remaining logic to [`transform_internal`](Curve::transform_internal).
44    fn transform(&self, t: f64) -> f64 {
45        if t == 0.0 || t == 1.0 {
46            return t;
47        }
48        debug_assert!(
49            (0.0..=1.0).contains(&t),
50            "parametric value {t} is outside of [0, 1] range."
51        );
52        self.transform_internal(t)
53    }
54
55    /// Returns the value of the curve at point `t`.
56    ///
57    /// The given parametric value `t` will be between 0.0 and 1.0, inclusive.
58    fn transform_internal(&self, _t: f64) -> f64 {
59        unimplemented!()
60    }
61}
62
63impl dyn Curve {
64    /// Returns a new curve that is the reversed inversion of this one.
65    ///
66    /// This is often useful with `CurvedAnimation.reverseCurve`.
67    ///
68    /// See also:
69    ///
70    ///  * [`FlippedCurve`], the class that is used to implement this getter.
71    ///  * `ReverseAnimation`, which reverses an `Animation` rather than a
72    ///    [`Curve`].
73    ///  * `CurvedAnimation`, which can take a separate curve and reverse curve.
74    pub fn flipped(self: Rc<dyn Curve>) -> FlippedCurve {
75        FlippedCurve::new(self)
76    }
77}
78
79/// The identity map over the unit interval.
80///
81/// See [`Curves::linear`] for an instance of this class.
82#[derive(Debug)]
83struct Linear;
84
85impl Curve for Linear {
86    fn transform_internal(&self, t: f64) -> f64 {
87        t
88    }
89}
90
91/// A sawtooth curve that repeats a given number of times over the unit interval.
92///
93/// The curve rises linearly from 0.0 to 1.0 and then falls discontinuously back
94/// to 0.0 each iteration.
95pub struct SawTooth {
96    count: i64,
97}
98
99impl SawTooth {
100    /// Creates a sawtooth curve.
101    pub const fn new(count: i64) -> SawTooth {
102        SawTooth { count }
103    }
104
105    /// The number of repetitions of the sawtooth pattern in the unit interval.
106    pub const fn count(&self) -> i64 {
107        self.count
108    }
109}
110
111impl Curve for SawTooth {
112    fn transform_internal(&self, t: f64) -> f64 {
113        let t = t * self.count as f64;
114        t - t.trunc()
115    }
116}
117
118impl Debug for SawTooth {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        write!(f, "SawTooth({})", self.count)
121    }
122}
123
124/// A curve that is 0.0 until [`begin`](Interval::begin), then curved (according
125/// to [`curve`](Interval::curve)) from 0.0 at [`begin`](Interval::begin) to 1.0
126/// at [`end`](Interval::end), then remains 1.0 past [`end`](Interval::end).
127///
128/// An [`Interval`] can be used to delay an animation. For example, a six second
129/// animation that uses an [`Interval`] with its [`begin`](Interval::begin) set
130/// to 0.5 and its [`end`](Interval::end) set to 1.0 will essentially become a
131/// three-second animation that starts three seconds later.
132pub struct Interval {
133    begin: f64,
134    end: f64,
135    curve: Rc<dyn Curve>,
136}
137
138impl Interval {
139    /// Creates an interval curve.
140    ///
141    /// Dart defaults `curve` to [`Curves::linear`].
142    pub fn new(begin: f64, end: f64, curve: Rc<dyn Curve>) -> Interval {
143        Interval { begin, end, curve }
144    }
145
146    /// The largest value for which this interval is 0.0.
147    ///
148    /// From t=0.0 to t=[`begin`](Interval::begin), the interval's value is 0.0.
149    pub const fn begin(&self) -> f64 {
150        self.begin
151    }
152
153    /// The smallest value for which this interval is 1.0.
154    ///
155    /// From t=[`end`](Interval::end) to t=1.0, the interval's value is 1.0.
156    pub const fn end(&self) -> f64 {
157        self.end
158    }
159
160    /// The curve to apply between [`begin`](Interval::begin) and
161    /// [`end`](Interval::end).
162    pub fn curve(&self) -> &Rc<dyn Curve> {
163        &self.curve
164    }
165}
166
167impl Curve for Interval {
168    fn transform_internal(&self, t: f64) -> f64 {
169        debug_assert!(self.begin >= 0.0);
170        debug_assert!(self.begin <= 1.0);
171        debug_assert!(self.end >= 0.0);
172        debug_assert!(self.end <= 1.0);
173        debug_assert!(self.end >= self.begin);
174        let t = clamp_double((t - self.begin) / (self.end - self.begin), 0.0, 1.0);
175        if t == 0.0 || t == 1.0 {
176            return t;
177        }
178        self.curve.transform(t)
179    }
180}
181
182impl Debug for Interval {
183    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184        if (&*self.curve as &dyn Any)
185            .downcast_ref::<Linear>()
186            .is_none()
187        {
188            return write!(
189                f,
190                "Interval({:?}\u{22ef}{:?})\u{27a9}{:?}",
191                self.begin, self.end, self.curve
192            );
193        }
194        write!(f, "Interval({:?}\u{22ef}{:?})", self.begin, self.end)
195    }
196}
197
198/// A curve that progresses according to [`begin_curve`](Split::begin_curve)
199/// until [`split`](Split::split), then according to
200/// [`end_curve`](Split::end_curve).
201///
202/// Split curves are useful in situations where a widget must track the user's
203/// finger (which requires a linear animation), but can also be flung using a
204/// curve specified with the [`end_curve`](Split::end_curve) argument, after the
205/// finger is released. In such a case, the value of [`split`](Split::split)
206/// would be the progress of the animation at the time when the finger was
207/// released.
208///
209/// For example, if [`split`](Split::split) is set to 0.5,
210/// [`begin_curve`](Split::begin_curve) is [`Curves::linear`], and
211/// [`end_curve`](Split::end_curve) is [`Curves::ease_out_cubic`], then the
212/// bottom-left quarter of the curve will be a straight line, and the top-right
213/// quarter will contain the entire [`Curves::ease_out_cubic`] curve.
214pub struct Split {
215    split: f64,
216    begin_curve: Rc<dyn Curve>,
217    end_curve: Rc<dyn Curve>,
218}
219
220impl Split {
221    /// Creates a split curve.
222    ///
223    /// Dart defaults `begin_curve` to [`Curves::linear`] and `end_curve` to
224    /// [`Curves::ease_out_cubic`].
225    pub fn new(split: f64, begin_curve: Rc<dyn Curve>, end_curve: Rc<dyn Curve>) -> Split {
226        Split {
227            split,
228            begin_curve,
229            end_curve,
230        }
231    }
232
233    /// The progress value separating [`begin_curve`](Split::begin_curve) from
234    /// [`end_curve`](Split::end_curve).
235    ///
236    /// The value before which the curve progresses according to
237    /// [`begin_curve`](Split::begin_curve) and after which the curve progresses
238    /// according to [`end_curve`](Split::end_curve).
239    ///
240    /// When t is exactly `split`, the curve has the value `split`.
241    ///
242    /// Must be between 0 and 1.0, inclusively.
243    pub const fn split(&self) -> f64 {
244        self.split
245    }
246
247    /// The curve to use before [`split`](Split::split) is reached.
248    pub fn begin_curve(&self) -> &Rc<dyn Curve> {
249        &self.begin_curve
250    }
251
252    /// The curve to use after [`split`](Split::split) is reached.
253    pub fn end_curve(&self) -> &Rc<dyn Curve> {
254        &self.end_curve
255    }
256}
257
258impl Curve for Split {
259    fn transform(&self, t: f64) -> f64 {
260        debug_assert!((0.0..=1.0).contains(&t));
261        debug_assert!((0.0..=1.0).contains(&self.split));
262
263        if t == 0.0 || t == 1.0 {
264            return t;
265        }
266
267        if t == self.split {
268            return self.split;
269        }
270
271        if t < self.split {
272            let curve_progress = t / self.split;
273            let transformed = self.begin_curve.transform(curve_progress);
274            lerp_double(Some(0.0), Some(self.split), transformed).unwrap()
275        } else {
276            let curve_progress = (t - self.split) / (1.0 - self.split);
277            let transformed = self.end_curve.transform(curve_progress);
278            lerp_double(Some(self.split), Some(1.0), transformed).unwrap()
279        }
280    }
281}
282
283impl Debug for Split {
284    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285        // Dart leads with `describeIdentity`, which appends an identity hash we
286        // have no counterpart for: see `PORTING.md`.
287        write!(
288            f,
289            "Split({:?}, {:?}, {:?})",
290            self.split, self.begin_curve, self.end_curve
291        )
292    }
293}
294
295/// A curve that is 0.0 until it hits the threshold, then it jumps to 1.0.
296pub struct Threshold {
297    threshold: f64,
298}
299
300impl Threshold {
301    /// Creates a threshold curve.
302    pub const fn new(threshold: f64) -> Threshold {
303        Threshold { threshold }
304    }
305
306    /// The value before which the curve is 0.0 and after which the curve is 1.0.
307    ///
308    /// When t is exactly [`threshold`](Threshold::threshold), the curve has the
309    /// value 1.0.
310    pub const fn threshold(&self) -> f64 {
311        self.threshold
312    }
313}
314
315impl Curve for Threshold {
316    fn transform_internal(&self, t: f64) -> f64 {
317        debug_assert!(self.threshold >= 0.0);
318        debug_assert!(self.threshold <= 1.0);
319        if t < self.threshold { 0.0 } else { 1.0 }
320    }
321}
322
323impl Debug for Threshold {
324    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325        // Dart declares no `toString`, so it inherits `ParametricCurve`'s, which
326        // prints the runtime type alone and never the threshold.
327        f.write_str("Threshold")
328    }
329}
330
331/// A cubic polynomial mapping of the unit interval.
332///
333/// The [`Curves`] class contains some commonly used cubic curves, such as
334/// [`Curves::ease`], [`Curves::ease_in`], [`Curves::ease_out`] and
335/// [`Curves::ease_in_out`].
336///
337/// The [`Cubic`] class implements third-order Bézier curves.
338///
339/// See also:
340///
341///  * [`Curves`], where many more predefined curves are available.
342///  * `CatmullRomCurve`, a curve which passes through specific values.
343pub struct Cubic {
344    a: f64,
345    b: f64,
346    c: f64,
347    d: f64,
348}
349
350impl Cubic {
351    /// Creates a cubic curve.
352    ///
353    /// Rather than creating a new instance, consider using one of the common
354    /// cubic curves in [`Curves`].
355    pub const fn new(a: f64, b: f64, c: f64, d: f64) -> Cubic {
356        Cubic { a, b, c, d }
357    }
358
359    /// The x coordinate of the first control point.
360    ///
361    /// The line through the point (0, 0) and the first control point is tangent
362    /// to the curve at the point (0, 0).
363    pub const fn a(&self) -> f64 {
364        self.a
365    }
366
367    /// The y coordinate of the first control point.
368    ///
369    /// The line through the point (0, 0) and the first control point is tangent
370    /// to the curve at the point (0, 0).
371    pub const fn b(&self) -> f64 {
372        self.b
373    }
374
375    /// The x coordinate of the second control point.
376    ///
377    /// The line through the point (1, 1) and the second control point is tangent
378    /// to the curve at the point (1, 1).
379    pub const fn c(&self) -> f64 {
380        self.c
381    }
382
383    /// The y coordinate of the second control point.
384    ///
385    /// The line through the point (1, 1) and the second control point is tangent
386    /// to the curve at the point (1, 1).
387    pub const fn d(&self) -> f64 {
388        self.d
389    }
390
391    const CUBIC_ERROR_BOUND: f64 = 0.001;
392
393    fn evaluate_cubic(a: f64, b: f64, m: f64) -> f64 {
394        3.0 * a * (1.0 - m) * (1.0 - m) * m + 3.0 * b * (1.0 - m) * m * m + m * m * m
395    }
396}
397
398impl Curve for Cubic {
399    fn transform_internal(&self, t: f64) -> f64 {
400        assert!(!t.is_nan(), "t: must not be NaN");
401        if t <= 0.0 {
402            return 0.0;
403        }
404        if t >= 1.0 {
405            return 1.0;
406        }
407        let mut start = 0.0;
408        let mut end = 1.0;
409        loop {
410            let midpoint = (start + end) / 2.0;
411            let estimate = Cubic::evaluate_cubic(self.a, self.c, midpoint);
412            if (t - estimate).abs() < Cubic::CUBIC_ERROR_BOUND {
413                return Cubic::evaluate_cubic(self.b, self.d, midpoint);
414            }
415            if estimate < t {
416                start = midpoint;
417            } else {
418                end = midpoint;
419            }
420        }
421    }
422}
423
424impl Debug for Cubic {
425    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
426        write!(
427            f,
428            "Cubic({:.2}, {:.2}, {:.2}, {:.2})",
429            self.a, self.b, self.c, self.d
430        )
431    }
432}
433
434/// A cubic polynomial composed of two curves that share a common center point.
435///
436/// The curve runs through three points: (0,0), the
437/// [`midpoint`](ThreePointCubic::midpoint), and (1,1).
438///
439/// The [`Curves`] class contains a curve defined with this class:
440/// [`Curves::ease_in_out_cubic_emphasized`].
441///
442/// The [`ThreePointCubic`] class implements third-order Bézier curves, where two
443/// curves share an interior [`midpoint`](ThreePointCubic::midpoint) that the
444/// curve passes through. If the control points surrounding the middle point
445/// ([`b1`](ThreePointCubic::b1), and [`a2`](ThreePointCubic::a2)) are not
446/// collinear with the middle point, then the curve's derivative will have a
447/// discontinuity (a cusp) at the shared middle point.
448///
449/// See also:
450///
451///  * [`Curves`], where many more predefined curves are available.
452///  * [`Cubic`], which defines a single cubic polynomial.
453///  * `CatmullRomCurve`, a curve which passes through specific values.
454pub struct ThreePointCubic {
455    a1: Offset,
456    b1: Offset,
457    midpoint: Offset,
458    a2: Offset,
459    b2: Offset,
460}
461
462impl ThreePointCubic {
463    /// Creates two cubic curves that share a common control point.
464    ///
465    /// Rather than creating a new instance, consider using one of the common
466    /// three-point cubic curves in [`Curves`].
467    ///
468    /// The arguments correspond to the control points for the two curves,
469    /// including the [`midpoint`](ThreePointCubic::midpoint), but do not include
470    /// the two implied end points at (0,0) and (1,1), which are fixed.
471    pub const fn new(
472        a1: Offset,
473        b1: Offset,
474        midpoint: Offset,
475        a2: Offset,
476        b2: Offset,
477    ) -> ThreePointCubic {
478        ThreePointCubic {
479            a1,
480            b1,
481            midpoint,
482            a2,
483            b2,
484        }
485    }
486
487    /// The coordinates of the first control point of the first curve.
488    ///
489    /// The line through the point (0, 0) and this control point is tangent to
490    /// the curve at the point (0, 0).
491    pub const fn a1(&self) -> Offset {
492        self.a1
493    }
494
495    /// The coordinates of the second control point of the first curve.
496    ///
497    /// The line through the [`midpoint`](ThreePointCubic::midpoint) and this
498    /// control point is tangent to the curve approaching the
499    /// [`midpoint`](ThreePointCubic::midpoint).
500    pub const fn b1(&self) -> Offset {
501        self.b1
502    }
503
504    /// The coordinates of the middle shared point.
505    ///
506    /// The curve will go through this point. If the control points surrounding
507    /// this middle point ([`b1`](ThreePointCubic::b1), and
508    /// [`a2`](ThreePointCubic::a2)) are not colinear with this point, then the
509    /// curve's derivative will have a discontinuity (a cusp) at this point.
510    pub const fn midpoint(&self) -> Offset {
511        self.midpoint
512    }
513
514    /// The coordinates of the first control point of the second curve.
515    ///
516    /// The line through the [`midpoint`](ThreePointCubic::midpoint) and this
517    /// control point is tangent to the curve approaching the
518    /// [`midpoint`](ThreePointCubic::midpoint).
519    pub const fn a2(&self) -> Offset {
520        self.a2
521    }
522
523    /// The coordinates of the second control point of the second curve.
524    ///
525    /// The line through the point (1, 1) and this control point is tangent to
526    /// the curve at (1, 1).
527    pub const fn b2(&self) -> Offset {
528        self.b2
529    }
530}
531
532impl Curve for ThreePointCubic {
533    fn transform_internal(&self, t: f64) -> f64 {
534        let first_curve = t < self.midpoint.dx();
535        let scale_x = if first_curve {
536            self.midpoint.dx()
537        } else {
538            1.0 - self.midpoint.dx()
539        };
540        let scale_y = if first_curve {
541            self.midpoint.dy()
542        } else {
543            1.0 - self.midpoint.dy()
544        };
545        let scaled_t = (t - if first_curve { 0.0 } else { self.midpoint.dx() }) / scale_x;
546        if first_curve {
547            Cubic::new(
548                self.a1.dx() / scale_x,
549                self.a1.dy() / scale_y,
550                self.b1.dx() / scale_x,
551                self.b1.dy() / scale_y,
552            )
553            .transform(scaled_t)
554                * scale_y
555        } else {
556            Cubic::new(
557                (self.a2.dx() - self.midpoint.dx()) / scale_x,
558                (self.a2.dy() - self.midpoint.dy()) / scale_y,
559                (self.b2.dx() - self.midpoint.dx()) / scale_x,
560                (self.b2.dy() - self.midpoint.dy()) / scale_y,
561            )
562            .transform(scaled_t)
563                * scale_y
564                + self.midpoint.dy()
565        }
566    }
567}
568
569impl Debug for ThreePointCubic {
570    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
571        // `curves.dart:522` passes the whole interpolated string as
572        // `objectRuntimeType`'s release fallback rather than as the result, so
573        // the control points never reach a debug build's output — only the
574        // runtime type does, followed by the trailing space in the Dart.
575        f.write_str("ThreePointCubic ")
576    }
577}
578
579/// A curve that is the reversed inversion of its given curve.
580///
581/// This curve evaluates the given curve in reverse (i.e. from 1.0 to 0.0 as t
582/// increases from 0.0 to 1.0) and returns the inverse of the given curve's
583/// value (i.e. 1.0 minus the given curve's value).
584pub struct FlippedCurve {
585    curve: Rc<dyn Curve>,
586}
587
588impl FlippedCurve {
589    /// Creates a flipped curve.
590    pub fn new(curve: Rc<dyn Curve>) -> FlippedCurve {
591        FlippedCurve { curve }
592    }
593
594    /// The curve that is being flipped.
595    pub fn curve(&self) -> &Rc<dyn Curve> {
596        &self.curve
597    }
598}
599
600impl Curve for FlippedCurve {
601    fn transform_internal(&self, t: f64) -> f64 {
602        1.0 - self.curve.transform(1.0 - t)
603    }
604}
605
606impl Debug for FlippedCurve {
607    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
608        write!(f, "FlippedCurve({:?})", self.curve)
609    }
610}
611
612/// A curve where the rate of change starts out quickly and then decelerates; an
613/// upside-down `f(t) = t²` parabola.
614///
615/// This is equivalent to the Android `DecelerateInterpolator` class with a unit
616/// factor (the default factor).
617///
618/// See [`Curves::decelerate`] for an instance of this class.
619#[derive(Debug)]
620struct DecelerateCurve;
621
622impl Curve for DecelerateCurve {
623    fn transform_internal(&self, t: f64) -> f64 {
624        // Intended to match the behavior of:
625        // https://android.googlesource.com/platform/frameworks/base/+/main/core/java/android/view/animation/DecelerateInterpolator.java
626        // ...as of December 2016.
627        let t = 1.0 - t;
628        1.0 - t * t
629    }
630}
631
632// BOUNCE CURVES
633
634fn bounce(t: f64) -> f64 {
635    if t < 1.0 / 2.75 {
636        return 7.5625 * t * t;
637    } else if t < 2.0 / 2.75 {
638        let t = t - 1.5 / 2.75;
639        return 7.5625 * t * t + 0.75;
640    } else if t < 2.5 / 2.75 {
641        let t = t - 2.25 / 2.75;
642        return 7.5625 * t * t + 0.9375;
643    }
644    let t = t - 2.625 / 2.75;
645    7.5625 * t * t + 0.984375
646}
647
648/// An oscillating curve that grows in magnitude.
649///
650/// See [`Curves::bounce_in`] for an instance of this class.
651#[derive(Debug)]
652struct BounceInCurve;
653
654impl Curve for BounceInCurve {
655    fn transform_internal(&self, t: f64) -> f64 {
656        1.0 - bounce(1.0 - t)
657    }
658}
659
660/// An oscillating curve that shrink in magnitude.
661///
662/// See [`Curves::bounce_out`] for an instance of this class.
663#[derive(Debug)]
664struct BounceOutCurve;
665
666impl Curve for BounceOutCurve {
667    fn transform_internal(&self, t: f64) -> f64 {
668        bounce(t)
669    }
670}
671
672/// An oscillating curve that first grows and then shrink in magnitude.
673///
674/// See [`Curves::bounce_in_out`] for an instance of this class.
675#[derive(Debug)]
676struct BounceInOutCurve;
677
678impl Curve for BounceInOutCurve {
679    fn transform_internal(&self, t: f64) -> f64 {
680        if t < 0.5 {
681            (1.0 - bounce(1.0 - t * 2.0)) * 0.5
682        } else {
683            bounce(t * 2.0 - 1.0) * 0.5 + 0.5
684        }
685    }
686}
687
688// ELASTIC CURVES
689
690/// An oscillating curve that grows in magnitude while overshooting its bounds.
691///
692/// An instance of this class using the default period of 0.4 is available as
693/// [`Curves::elastic_in`].
694pub struct ElasticInCurve {
695    period: f64,
696}
697
698impl ElasticInCurve {
699    /// Creates an elastic-in curve.
700    ///
701    /// Rather than creating a new instance, consider using
702    /// [`Curves::elastic_in`]. Dart defaults `period` to 0.4.
703    pub const fn new(period: f64) -> ElasticInCurve {
704        ElasticInCurve { period }
705    }
706
707    /// The duration of the oscillation.
708    pub const fn period(&self) -> f64 {
709        self.period
710    }
711}
712
713impl Curve for ElasticInCurve {
714    fn transform_internal(&self, t: f64) -> f64 {
715        let s = self.period / 4.0;
716        let t = t - 1.0;
717        -(2.0_f64.powf(10.0 * t)) * ((t - s) * (PI * 2.0) / self.period).sin()
718    }
719}
720
721impl Debug for ElasticInCurve {
722    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
723        write!(f, "ElasticInCurve({:?})", self.period)
724    }
725}
726
727/// An oscillating curve that shrinks in magnitude while overshooting its bounds.
728///
729/// An instance of this class using the default period of 0.4 is available as
730/// [`Curves::elastic_out`].
731pub struct ElasticOutCurve {
732    period: f64,
733}
734
735impl ElasticOutCurve {
736    /// Creates an elastic-out curve.
737    ///
738    /// Rather than creating a new instance, consider using
739    /// [`Curves::elastic_out`]. Dart defaults `period` to 0.4.
740    pub const fn new(period: f64) -> ElasticOutCurve {
741        ElasticOutCurve { period }
742    }
743
744    /// The duration of the oscillation.
745    pub const fn period(&self) -> f64 {
746        self.period
747    }
748}
749
750impl Curve for ElasticOutCurve {
751    fn transform_internal(&self, t: f64) -> f64 {
752        let s = self.period / 4.0;
753        2.0_f64.powf(-10.0 * t) * ((t - s) * (PI * 2.0) / self.period).sin() + 1.0
754    }
755}
756
757impl Debug for ElasticOutCurve {
758    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
759        write!(f, "ElasticOutCurve({:?})", self.period)
760    }
761}
762
763/// An oscillating curve that grows and then shrinks in magnitude while
764/// overshooting its bounds.
765///
766/// An instance of this class using the default period of 0.4 is available as
767/// [`Curves::elastic_in_out`].
768pub struct ElasticInOutCurve {
769    period: f64,
770}
771
772impl ElasticInOutCurve {
773    /// Creates an elastic-in-out curve.
774    ///
775    /// Rather than creating a new instance, consider using
776    /// [`Curves::elastic_in_out`]. Dart defaults `period` to 0.4.
777    pub const fn new(period: f64) -> ElasticInOutCurve {
778        ElasticInOutCurve { period }
779    }
780
781    /// The duration of the oscillation.
782    pub const fn period(&self) -> f64 {
783        self.period
784    }
785}
786
787impl Curve for ElasticInOutCurve {
788    fn transform_internal(&self, t: f64) -> f64 {
789        let s = self.period / 4.0;
790        let t = 2.0 * t - 1.0;
791        if t < 0.0 {
792            -0.5 * 2.0_f64.powf(10.0 * t) * ((t - s) * (PI * 2.0) / self.period).sin()
793        } else {
794            2.0_f64.powf(-10.0 * t) * ((t - s) * (PI * 2.0) / self.period).sin() * 0.5 + 1.0
795        }
796    }
797}
798
799impl Debug for ElasticInOutCurve {
800    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
801        write!(f, "ElasticInOutCurve({:?})", self.period)
802    }
803}
804
805// PREDEFINED CURVES
806
807/// A collection of common animation curves.
808///
809/// See also:
810///
811///  * [`Curve`], the interface implemented by the curves available from the
812///    [`Curves`] class.
813///
814/// # Why these are functions
815///
816/// Dart's are `static const` fields, which the language canonicalizes: every
817/// mention of `Curves.easeIn` is the *same* object, which is what makes
818/// Flutter's `widget.curve != oldWidget.curve` checks answer "unchanged".
819/// Rust has no const canonicalization, so each accessor hands out a clone of one
820/// process-local [`Rc`] and [`Rc::ptr_eq`] reproduces that comparison.
821pub enum Curves {}
822
823macro_rules! predefined_curves {
824    ($( $(#[$doc:meta])* $name:ident = $value:expr; )*) => {
825        impl Curves {
826            $(
827                $(#[$doc])*
828                pub fn $name() -> Rc<dyn Curve> {
829                    thread_local! {
830                        static CURVE: Rc<dyn Curve> = Rc::new($value);
831                    }
832                    CURVE.with(Rc::clone)
833                }
834            )*
835        }
836    };
837}
838
839predefined_curves! {
840    /// A linear animation curve.
841    ///
842    /// This is the identity map over the unit interval: its
843    /// [`Curve::transform`] method returns its input unmodified. This is useful
844    /// as a default curve for cases where a [`Curve`] is required but no actual
845    /// curve is desired.
846    linear = Linear;
847
848    /// A curve where the rate of change starts out quickly and then
849    /// decelerates; an upside-down `f(t) = t²` parabola.
850    ///
851    /// This is equivalent to the Android `DecelerateInterpolator` class with a
852    /// unit factor (the default factor).
853    decelerate = DecelerateCurve;
854
855    /// A curve that is very steep and linear at the beginning, but quickly
856    /// flattens out and very slowly eases in.
857    ///
858    /// By default is the curve used to animate pages on iOS back to their
859    /// original position if a swipe gesture is ended midway through a swipe.
860    fast_linear_to_slow_ease_in = Cubic::new(0.18, 1.0, 0.04, 1.0);
861
862    /// A curve that starts slowly, speeds up very quickly, and then ends slowly.
863    ///
864    /// This curve is used by default to animate page transitions used by
865    /// `CupertinoPageRoute`.
866    ///
867    /// It has been derived from plots of native iOS 16.3 animation frames on
868    /// iPhone 14 Pro Max. Specifically, transition animation positions were
869    /// measured every frame and plotted against time. Then, a cubic curve was
870    /// strictly fit to the measured data points.
871    fast_ease_in_to_slow_ease_out = ThreePointCubic::new(
872        Offset::new(0.056, 0.024),
873        Offset::new(0.108, 0.3085),
874        Offset::new(0.198, 0.541),
875        Offset::new(0.3655, 1.0),
876        Offset::new(0.5465, 0.989),
877    );
878
879    /// A cubic animation curve that speeds up quickly and ends slowly.
880    ///
881    /// This is the same as the CSS easing function `ease`.
882    ease = Cubic::new(0.25, 0.1, 0.25, 1.0);
883
884    /// A cubic animation curve that starts slowly and ends quickly.
885    ///
886    /// This is the same as the CSS easing function `ease-in`.
887    ease_in = Cubic::new(0.42, 0.0, 1.0, 1.0);
888
889    /// A cubic animation curve that starts slowly and ends linearly.
890    ///
891    /// The symmetric animation to [`Curves::linear_to_ease_out`].
892    ease_in_to_linear = Cubic::new(0.67, 0.03, 0.65, 0.09);
893
894    /// A cubic animation curve that starts slowly and ends quickly. This is
895    /// similar to [`Curves::ease_in`], but with sinusoidal easing for a slightly
896    /// less abrupt beginning and end. Nonetheless, the result is quite gentle
897    /// and is hard to distinguish from [`Curves::linear`] at a glance.
898    ///
899    /// Derived from Robert Penner’s easing functions.
900    ease_in_sine = Cubic::new(0.47, 0.0, 0.745, 0.715);
901
902    /// A cubic animation curve that starts slowly and ends quickly. Based on a
903    /// quadratic equation where `f(t) = t²`, this is effectively the inverse of
904    /// [`Curves::decelerate`].
905    ///
906    /// Compared to [`Curves::ease_in_sine`], this curve is slightly steeper.
907    ///
908    /// Derived from Robert Penner’s easing functions.
909    ease_in_quad = Cubic::new(0.55, 0.085, 0.68, 0.53);
910
911    /// A cubic animation curve that starts slowly and ends quickly. This curve
912    /// is based on a cubic equation where `f(t) = t³`. The result is a safe
913    /// sweet spot when choosing a curve for widgets animating off the viewport.
914    ///
915    /// Compared to [`Curves::ease_in_quad`], this curve is slightly steeper.
916    ///
917    /// Derived from Robert Penner’s easing functions.
918    ease_in_cubic = Cubic::new(0.55, 0.055, 0.675, 0.19);
919
920    /// A cubic animation curve that starts slowly and ends quickly. This curve
921    /// is based on a quartic equation where `f(t) = t⁴`.
922    ///
923    /// Animations using this curve or steeper curves will benefit from a longer
924    /// duration to avoid motion feeling unnatural.
925    ///
926    /// Compared to [`Curves::ease_in_cubic`], this curve is slightly steeper.
927    ///
928    /// Derived from Robert Penner’s easing functions.
929    ease_in_quart = Cubic::new(0.895, 0.03, 0.685, 0.22);
930
931    /// A cubic animation curve that starts slowly and ends quickly. This curve
932    /// is based on a quintic equation where `f(t) = t⁵`.
933    ///
934    /// Compared to [`Curves::ease_in_quart`], this curve is slightly steeper.
935    ///
936    /// Derived from Robert Penner’s easing functions.
937    ease_in_quint = Cubic::new(0.755, 0.05, 0.855, 0.06);
938
939    /// A cubic animation curve that starts slowly and ends quickly. This curve
940    /// is based on an exponential equation where `f(t) = 2¹⁰⁽ᵗ⁻¹⁾`.
941    ///
942    /// Using this curve can give your animations extra flare, but a longer
943    /// duration may need to be used to compensate for the steepness of the
944    /// curve.
945    ///
946    /// Compared to [`Curves::ease_in_quint`], this curve is slightly steeper.
947    ///
948    /// Derived from Robert Penner’s easing functions.
949    ease_in_expo = Cubic::new(0.95, 0.05, 0.795, 0.035);
950
951    /// A cubic animation curve that starts slowly and ends quickly. This curve
952    /// is effectively the bottom-right quarter of a circle.
953    ///
954    /// Like [`Curves::ease_in_expo`], this curve is fairly dramatic and will
955    /// reduce the clarity of an animation if not given a longer duration.
956    ///
957    /// Derived from Robert Penner’s easing functions.
958    ease_in_circ = Cubic::new(0.6, 0.04, 0.98, 0.335);
959
960    /// A cubic animation curve that starts slowly and ends quickly. This curve
961    /// is similar to `Curves.elasticIn` in that it overshoots its bounds before
962    /// reaching its end. Instead of repeated swinging motions before ascending,
963    /// though, this curve overshoots once, then continues to ascend.
964    ///
965    /// Derived from Robert Penner’s easing functions.
966    ease_in_back = Cubic::new(0.6, -0.28, 0.735, 0.045);
967
968    /// A cubic animation curve that starts quickly and ends slowly.
969    ///
970    /// This is the same as the CSS easing function `ease-out`.
971    ease_out = Cubic::new(0.0, 0.0, 0.58, 1.0);
972
973    /// A cubic animation curve that starts linearly and ends slowly.
974    ///
975    /// A symmetric animation to [`Curves::ease_in_to_linear`].
976    linear_to_ease_out = Cubic::new(0.35, 0.91, 0.33, 0.97);
977
978    /// A cubic animation curve that starts quickly and ends slowly. This is
979    /// similar to [`Curves::ease_out`], but with sinusoidal easing for a
980    /// slightly less abrupt beginning and end. Nonetheless, the result is quite
981    /// gentle and is hard to distinguish from [`Curves::linear`] at a glance.
982    ///
983    /// Derived from Robert Penner’s easing functions.
984    ease_out_sine = Cubic::new(0.39, 0.575, 0.565, 1.0);
985
986    /// A cubic animation curve that starts quickly and ends slowly. This is
987    /// effectively the same as [`Curves::decelerate`], only simulated using a
988    /// cubic bezier function.
989    ///
990    /// Compared to [`Curves::ease_out_sine`], this curve is slightly steeper.
991    ///
992    /// Derived from Robert Penner’s easing functions.
993    ease_out_quad = Cubic::new(0.25, 0.46, 0.45, 0.94);
994
995    /// A cubic animation curve that starts quickly and ends slowly. This curve
996    /// is a flipped version of [`Curves::ease_in_cubic`].
997    ///
998    /// The result is a safe sweet spot when choosing a curve for animating a
999    /// widget's position entering or already inside the viewport.
1000    ///
1001    /// Compared to [`Curves::ease_out_quad`], this curve is slightly steeper.
1002    ///
1003    /// Derived from Robert Penner’s easing functions.
1004    ease_out_cubic = Cubic::new(0.215, 0.61, 0.355, 1.0);
1005
1006    /// A cubic animation curve that starts quickly and ends slowly. This curve
1007    /// is a flipped version of [`Curves::ease_in_quart`].
1008    ///
1009    /// Animations using this curve or steeper curves will benefit from a longer
1010    /// duration to avoid motion feeling unnatural.
1011    ///
1012    /// Compared to [`Curves::ease_out_cubic`], this curve is slightly steeper.
1013    ///
1014    /// Derived from Robert Penner’s easing functions.
1015    ease_out_quart = Cubic::new(0.165, 0.84, 0.44, 1.0);
1016
1017    /// A cubic animation curve that starts quickly and ends slowly. This curve
1018    /// is a flipped version of [`Curves::ease_in_quint`].
1019    ///
1020    /// Compared to [`Curves::ease_out_quart`], this curve is slightly steeper.
1021    ///
1022    /// Derived from Robert Penner’s easing functions.
1023    ease_out_quint = Cubic::new(0.23, 1.0, 0.32, 1.0);
1024
1025    /// A cubic animation curve that starts quickly and ends slowly. This curve
1026    /// is a flipped version of [`Curves::ease_in_expo`]. Using this curve can
1027    /// give your animations extra flare, but a longer duration may need to be
1028    /// used to compensate for the steepness of the curve.
1029    ///
1030    /// Derived from Robert Penner’s easing functions.
1031    ease_out_expo = Cubic::new(0.19, 1.0, 0.22, 1.0);
1032
1033    /// A cubic animation curve that starts quickly and ends slowly. This curve
1034    /// is effectively the top-left quarter of a circle.
1035    ///
1036    /// Like [`Curves::ease_out_expo`], this curve is fairly dramatic and will
1037    /// reduce the clarity of an animation if not given a longer duration.
1038    ///
1039    /// Derived from Robert Penner’s easing functions.
1040    ease_out_circ = Cubic::new(0.075, 0.82, 0.165, 1.0);
1041
1042    /// A cubic animation curve that starts quickly and ends slowly. This curve
1043    /// is similar to `Curves.elasticOut` in that it overshoots its bounds before
1044    /// reaching its end. Instead of repeated swinging motions after ascending,
1045    /// though, this curve only overshoots once.
1046    ///
1047    /// Derived from Robert Penner’s easing functions.
1048    ease_out_back = Cubic::new(0.175, 0.885, 0.32, 1.275);
1049
1050    /// A cubic animation curve that starts slowly, speeds up, and then ends
1051    /// slowly.
1052    ///
1053    /// This is the same as the CSS easing function `ease-in-out`.
1054    ease_in_out = Cubic::new(0.42, 0.0, 0.58, 1.0);
1055
1056    /// A cubic animation curve that starts slowly, speeds up, and then ends
1057    /// slowly. This is similar to [`Curves::ease_in_out`], but with sinusoidal
1058    /// easing for a slightly less abrupt beginning and end.
1059    ///
1060    /// Derived from Robert Penner’s easing functions.
1061    ease_in_out_sine = Cubic::new(0.445, 0.05, 0.55, 0.95);
1062
1063    /// A cubic animation curve that starts slowly, speeds up, and then ends
1064    /// slowly. This curve can be imagined as [`Curves::ease_in_quad`] as the
1065    /// first half, and [`Curves::ease_out_quad`] as the second.
1066    ///
1067    /// Compared to [`Curves::ease_in_out_sine`], this curve is slightly steeper.
1068    ///
1069    /// Derived from Robert Penner’s easing functions.
1070    ease_in_out_quad = Cubic::new(0.455, 0.03, 0.515, 0.955);
1071
1072    /// A cubic animation curve that starts slowly, speeds up, and then ends
1073    /// slowly. This curve can be imagined as [`Curves::ease_in_cubic`] as the
1074    /// first half, and [`Curves::ease_out_cubic`] as the second.
1075    ///
1076    /// The result is a safe sweet spot when choosing a curve for a widget whose
1077    /// initial and final positions are both within the viewport.
1078    ///
1079    /// Compared to [`Curves::ease_in_out_quad`], this curve is slightly steeper.
1080    ///
1081    /// Derived from Robert Penner’s easing functions.
1082    ease_in_out_cubic = Cubic::new(0.645, 0.045, 0.355, 1.0);
1083
1084    /// A cubic animation curve that starts slowly, speeds up shortly
1085    /// thereafter, and then ends slowly. This curve can be imagined as a steeper
1086    /// version of [`Curves::ease_in_out_cubic`].
1087    ///
1088    /// The result is a more emphasized eased curve when choosing a curve for a
1089    /// widget whose initial and final positions are both within the viewport.
1090    ///
1091    /// Compared to [`Curves::ease_in_out_cubic`], this curve is slightly
1092    /// steeper.
1093    ease_in_out_cubic_emphasized = ThreePointCubic::new(
1094        Offset::new(0.05, 0.0),
1095        Offset::new(0.133333, 0.06),
1096        Offset::new(0.166666, 0.4),
1097        Offset::new(0.208333, 0.82),
1098        Offset::new(0.25, 1.0),
1099    );
1100
1101    /// A cubic animation curve that starts slowly, speeds up, and then ends
1102    /// slowly. This curve can be imagined as [`Curves::ease_in_quart`] as the
1103    /// first half, and [`Curves::ease_out_quart`] as the second.
1104    ///
1105    /// Animations using this curve or steeper curves will benefit from a longer
1106    /// duration to avoid motion feeling unnatural.
1107    ///
1108    /// Compared to [`Curves::ease_in_out_cubic`], this curve is slightly
1109    /// steeper.
1110    ///
1111    /// Derived from Robert Penner’s easing functions.
1112    ease_in_out_quart = Cubic::new(0.77, 0.0, 0.175, 1.0);
1113
1114    /// A cubic animation curve that starts slowly, speeds up, and then ends
1115    /// slowly. This curve can be imagined as [`Curves::ease_in_quint`] as the
1116    /// first half, and [`Curves::ease_out_quint`] as the second.
1117    ///
1118    /// Compared to [`Curves::ease_in_out_quart`], this curve is slightly
1119    /// steeper.
1120    ///
1121    /// Derived from Robert Penner’s easing functions.
1122    ease_in_out_quint = Cubic::new(0.86, 0.0, 0.07, 1.0);
1123
1124    /// A cubic animation curve that starts slowly, speeds up, and then ends
1125    /// slowly.
1126    ///
1127    /// Since this curve is arrived at with an exponential function, the midpoint
1128    /// is exceptionally steep. Extra consideration should be taken when
1129    /// designing an animation using this.
1130    ///
1131    /// Compared to [`Curves::ease_in_out_quint`], this curve is slightly
1132    /// steeper.
1133    ///
1134    /// Derived from Robert Penner’s easing functions.
1135    ease_in_out_expo = Cubic::new(1.0, 0.0, 0.0, 1.0);
1136
1137    /// A cubic animation curve that starts slowly, speeds up, and then ends
1138    /// slowly. This curve can be imagined as [`Curves::ease_in_circ`] as the
1139    /// first half, and [`Curves::ease_out_circ`] as the second.
1140    ///
1141    /// Like [`Curves::ease_in_out_expo`], this curve is fairly dramatic and will
1142    /// reduce the clarity of an animation if not given a longer duration.
1143    ///
1144    /// Compared to [`Curves::ease_in_out_expo`], this curve is slightly steeper.
1145    ///
1146    /// Derived from Robert Penner’s easing functions.
1147    ease_in_out_circ = Cubic::new(0.785, 0.135, 0.15, 0.86);
1148
1149    /// A cubic animation curve that starts slowly, speeds up, and then ends
1150    /// slowly. This curve can be imagined as [`Curves::ease_in_back`] as the
1151    /// first half, and [`Curves::ease_out_back`] as the second.
1152    ///
1153    /// Since two curves are used as a basis for this curve, the resulting
1154    /// animation will overshoot its bounds twice before reaching its end - first
1155    /// by exceeding its lower bound, then exceeding its upper bound and finally
1156    /// descending to its final position.
1157    ///
1158    /// Derived from Robert Penner’s easing functions.
1159    ease_in_out_back = Cubic::new(0.68, -0.55, 0.265, 1.55);
1160
1161    /// A curve that starts quickly and eases into its final position.
1162    ///
1163    /// Over the course of the animation, the object spends more time near its
1164    /// final destination. As a result, the user isn’t left waiting for the
1165    /// animation to finish, and the negative effects of motion are minimized.
1166    ///
1167    /// See also:
1168    ///
1169    ///  * `Easing.legacy`, the name for this curve in the Material
1170    ///    specification.
1171    fast_out_slow_in = Cubic::new(0.4, 0.0, 0.2, 1.0);
1172
1173    /// A cubic animation curve that starts quickly, slows down, and then ends
1174    /// quickly.
1175    slow_middle = Cubic::new(0.15, 0.85, 0.85, 0.15);
1176
1177    /// An oscillating curve that grows in magnitude.
1178    bounce_in = BounceInCurve;
1179
1180    /// An oscillating curve that first grows and then shrink in magnitude.
1181    bounce_out = BounceOutCurve;
1182
1183    /// An oscillating curve that first grows and then shrink in magnitude.
1184    bounce_in_out = BounceInOutCurve;
1185
1186    /// An oscillating curve that grows in magnitude while overshooting its
1187    /// bounds.
1188    elastic_in = ElasticInCurve::new(0.4);
1189
1190    /// An oscillating curve that shrinks in magnitude while overshooting its
1191    /// bounds.
1192    elastic_out = ElasticOutCurve::new(0.4);
1193
1194    /// An oscillating curve that grows and then shrinks in magnitude while
1195    /// overshooting its bounds.
1196    elastic_in_out = ElasticInOutCurve::new(0.4);
1197}
1198
1199#[cfg(test)]
1200mod tests {
1201    use super::*;
1202
1203    /// Flutter's `curves_test.dart` helper of the same name.
1204    fn assert_maps_zero_to_zero_and_one_to_one(curve: &dyn Curve) {
1205        assert_eq!(curve.transform(0.0), 0.0, "{curve:?}");
1206        assert_eq!(curve.transform(1.0), 1.0, "{curve:?}");
1207    }
1208
1209    #[test]
1210    fn every_predefined_curve_maps_the_endpoints_to_themselves() {
1211        for curve in [
1212            Curves::linear(),
1213            Curves::decelerate(),
1214            Curves::fast_linear_to_slow_ease_in(),
1215            Curves::fast_ease_in_to_slow_ease_out(),
1216            Curves::ease(),
1217            Curves::ease_in(),
1218            Curves::ease_in_to_linear(),
1219            Curves::ease_in_sine(),
1220            Curves::ease_in_quad(),
1221            Curves::ease_in_cubic(),
1222            Curves::ease_in_quart(),
1223            Curves::ease_in_quint(),
1224            Curves::ease_in_expo(),
1225            Curves::ease_in_circ(),
1226            Curves::ease_in_back(),
1227            Curves::ease_out(),
1228            Curves::linear_to_ease_out(),
1229            Curves::ease_out_sine(),
1230            Curves::ease_out_quad(),
1231            Curves::ease_out_cubic(),
1232            Curves::ease_out_quart(),
1233            Curves::ease_out_quint(),
1234            Curves::ease_out_expo(),
1235            Curves::ease_out_circ(),
1236            Curves::ease_out_back(),
1237            Curves::ease_in_out(),
1238            Curves::ease_in_out_sine(),
1239            Curves::ease_in_out_quad(),
1240            Curves::ease_in_out_cubic(),
1241            Curves::ease_in_out_cubic_emphasized(),
1242            Curves::ease_in_out_quart(),
1243            Curves::ease_in_out_quint(),
1244            Curves::ease_in_out_expo(),
1245            Curves::ease_in_out_circ(),
1246            Curves::ease_in_out_back(),
1247            Curves::fast_out_slow_in(),
1248            Curves::slow_middle(),
1249            Curves::bounce_in(),
1250            Curves::bounce_out(),
1251            Curves::bounce_in_out(),
1252            Curves::elastic_in(),
1253            Curves::elastic_out(),
1254            Curves::elastic_in_out(),
1255        ] {
1256            assert_maps_zero_to_zero_and_one_to_one(&*curve);
1257        }
1258    }
1259
1260    #[test]
1261    fn a_predefined_curve_is_one_object_so_two_reads_compare_equal() {
1262        assert!(Rc::ptr_eq(&Curves::ease_in(), &Curves::ease_in()));
1263        assert!(!Rc::ptr_eq(&Curves::ease_in(), &Curves::ease_out()));
1264        // What a freshly built curve gives, matching Dart's non-const case.
1265        assert!(!Rc::ptr_eq(
1266            &(Rc::new(Cubic::new(0.42, 0.0, 1.0, 1.0)) as Rc<dyn Curve>),
1267            &Curves::ease_in()
1268        ));
1269    }
1270
1271    #[test]
1272    fn linear_returns_its_input() {
1273        let linear = Curves::linear();
1274        for t in [0.0, 0.25, 0.5, 0.75, 1.0] {
1275            assert_eq!(linear.transform(t), t);
1276        }
1277    }
1278
1279    #[test]
1280    fn a_sawtooth_repeats_and_drops_back_to_zero() {
1281        let curve = SawTooth::new(3);
1282        assert_eq!(curve.transform(0.0), 0.0);
1283        assert!((curve.transform(0.5 / 3.0) - 0.5).abs() < 1e-9);
1284        assert!(curve.transform(0.999 / 3.0) > 0.99);
1285        assert!(curve.transform(1.001 / 3.0) < 0.01);
1286        assert_eq!(curve.transform(1.0), 1.0);
1287    }
1288
1289    #[test]
1290    fn an_interval_is_flat_outside_its_bounds() {
1291        let curve = Interval::new(0.25, 0.75, Curves::linear());
1292        assert_eq!(curve.transform(0.0), 0.0);
1293        assert_eq!(curve.transform(0.25), 0.0);
1294        assert_eq!(curve.transform(0.5), 0.5);
1295        assert_eq!(curve.transform(0.75), 1.0);
1296        assert_eq!(curve.transform(1.0), 1.0);
1297    }
1298
1299    #[test]
1300    fn a_split_runs_each_half_over_its_own_curve() {
1301        let curve = Split::new(0.5, Curves::linear(), Curves::linear());
1302        assert_eq!(curve.transform(0.0), 0.0);
1303        assert_eq!(curve.transform(0.25), 0.25);
1304        assert_eq!(curve.transform(0.5), 0.5);
1305        assert_eq!(curve.transform(0.75), 0.75);
1306        assert_eq!(curve.transform(1.0), 1.0);
1307    }
1308
1309    #[test]
1310    fn a_threshold_jumps_once() {
1311        let curve = Threshold::new(0.5);
1312        assert_eq!(curve.transform(0.0), 0.0);
1313        assert_eq!(curve.transform(0.25), 0.0);
1314        assert_eq!(curve.transform(0.5), 1.0);
1315        assert_eq!(curve.transform(0.75), 1.0);
1316        assert_eq!(curve.transform(1.0), 1.0);
1317    }
1318
1319    #[test]
1320    fn a_flipped_curve_reverses_and_inverts_its_curve() {
1321        let decelerate = Curves::decelerate();
1322        let flipped = FlippedCurve::new(Rc::clone(&decelerate));
1323        for t in [0.1, 0.3, 0.5, 0.7, 0.9] {
1324            let expected = 1.0 - decelerate.transform(1.0 - t);
1325            assert!((flipped.transform(t) - expected).abs() < 1e-12);
1326        }
1327    }
1328
1329    #[test]
1330    fn flipped_on_an_erased_curve_wraps_it() {
1331        let flipped = Curves::decelerate().flipped();
1332        assert!(
1333            (flipped.transform(0.25) - (1.0 - Curves::decelerate().transform(0.75))).abs() < 1e-12
1334        );
1335    }
1336
1337    #[test]
1338    fn a_cubic_stays_inside_the_unit_interval() {
1339        let curve = Curves::ease_in_out();
1340        let mut previous = 0.0;
1341        for step in 0..=100 {
1342            let value = curve.transform(step as f64 / 100.0);
1343            assert!((0.0..=1.0).contains(&value), "{value} at step {step}");
1344            assert!(value >= previous, "{value} < {previous} at step {step}");
1345            previous = value;
1346        }
1347    }
1348
1349    #[test]
1350    fn a_three_point_cubic_passes_through_its_midpoint() {
1351        let curve = ThreePointCubic::new(
1352            Offset::new(0.05, 0.0),
1353            Offset::new(0.133333, 0.06),
1354            Offset::new(0.166666, 0.4),
1355            Offset::new(0.208333, 0.82),
1356            Offset::new(0.25, 1.0),
1357        );
1358        assert!((curve.transform(0.166666) - 0.4).abs() < 0.01);
1359    }
1360
1361    #[test]
1362    fn the_elastic_curves_overshoot_between_the_endpoints() {
1363        // One period is 0.4, so the first swing past the bound is a quarter of
1364        // that either side of the end it starts from.
1365        assert!(Curves::elastic_out().transform(0.15) > 1.0);
1366        assert!(Curves::elastic_in().transform(0.85) < 0.0);
1367    }
1368
1369    #[test]
1370    fn debug_matches_flutter_to_string() {
1371        assert_eq!(format!("{:?}", SawTooth::new(3)), "SawTooth(3)");
1372        assert_eq!(
1373            format!("{:?}", Cubic::new(0.42, 0.0, 1.0, 1.0)),
1374            "Cubic(0.42, 0.00, 1.00, 1.00)"
1375        );
1376        assert_eq!(
1377            format!("{:?}", Interval::new(0.0, 0.5, Curves::linear())),
1378            "Interval(0.0\u{22ef}0.5)"
1379        );
1380        assert_eq!(
1381            format!("{:?}", Interval::new(0.0, 0.5, Curves::ease())),
1382            "Interval(0.0\u{22ef}0.5)\u{27a9}Cubic(0.25, 0.10, 0.25, 1.00)"
1383        );
1384        assert_eq!(
1385            format!("{:?}", ElasticInCurve::new(0.4)),
1386            "ElasticInCurve(0.4)"
1387        );
1388        // Dart's is `_Linear`; the skill drops the underscore from the name.
1389        assert_eq!(
1390            format!("{:?}", FlippedCurve::new(Curves::linear())),
1391            "FlippedCurve(Linear)"
1392        );
1393        // Neither prints its fields, because neither Dart class declares a
1394        // `toString` that reaches them.
1395        assert_eq!(format!("{:?}", Threshold::new(0.5)), "Threshold");
1396        assert_eq!(
1397            format!("{:?}", Curves::ease_in_out_cubic_emphasized()),
1398            "ThreePointCubic "
1399        );
1400    }
1401}