Skip to main content

blit/
animation.rs

1use crate::*;
2
3/// target motion using a tween or a spring
4#[derive(Clone, Copy, Debug, PartialEq)]
5pub enum Animation {
6    Tween(Tween),
7    Spring(Spring),
8}
9
10impl Default for Animation {
11    fn default() -> Self {
12        Self::Tween(Tween::default())
13    }
14}
15
16impl From<Tween> for Animation {
17    fn from(tween: Tween) -> Self {
18        Self::Tween(tween)
19    }
20}
21
22impl From<Spring> for Animation {
23    fn from(spring: Spring) -> Self {
24        Self::Spring(spring)
25    }
26}
27
28builder! {
29    /// controls how scalar motion starts and retargets
30    #[derive(Clone, Copy, Debug, PartialEq)]
31    pub struct AnimationOptions {
32        new(),
33        /// starting value when first registered with `Ui::animate`
34        #[into]
35        initial: Option<f32> = None,
36        /// discards carried velocity when retargeting
37        restart: bool = false,
38        /// initial spring speed or fading tween momentum in coordinate units per second
39        /// `None` carries the current velocity unless restarting
40        /// `Some(v)` overrides it even when `v` is zero or `restart` is true
41        /// zero removes carried momentum but a tween still follows its easing
42        #[into]
43        velocity: Option<f32> = None,
44        /// seconds to hold the current value before moving toward a new target
45        /// starts from rest unless `velocity` is set
46        /// ignored by zero duration animations
47        delay: f32 = 0.0,
48    }
49}
50
51builder! {
52    /// an easing curve with a duration specifying the time to reach the target
53    #[derive(Clone, Copy, Debug, Default, PartialEq)]
54    pub struct Tween {
55        new(
56            /// seconds to reach the target
57            duration: f32,
58            easing: Easing,
59        ),
60    }
61}
62
63builder! {
64    /// a linear spring tuned by duration and bounce
65    #[derive(Clone, Copy, Debug, PartialEq)]
66    pub struct Spring {
67        new(
68            /// undamped period in seconds controlling the response speed
69            duration: f32,
70            /// positive overshoots, zero is critically damped and negative is overdamped
71            bounce: f32,
72        ),
73        rest_distance: f32 = 0.001,
74        rest_speed: f32 = 0.001,
75    }
76}
77
78impl Spring {
79    /// stop when both distance and speed fall within these absolute tolerances
80    pub const fn rest(mut self, distance: f32, speed: f32) -> Self {
81        self.rest_distance = distance;
82        self.rest_speed = speed;
83        self
84    }
85}
86
87builder! {
88    /// applies an animation to selected layout properties
89    #[derive(Clone, Copy, Debug, PartialEq)]
90    pub struct Motion {
91        new(#[into] animation: Animation),
92        properties: MotionProps = MotionProps::NONE,
93        /// discards carried velocity when retargeting
94        restart: bool = false,
95        /// seconds to hold the current layout before moving toward a new one from rest
96        /// ignored by zero duration animations
97        delay: f32 = 0.0,
98        /// while moving to a new parent or anchor, paints above everything under this target,
99        /// which is ignored unless it was built before the node
100        #[into]
101        lift: Option<Id> = None,
102    }
103}
104
105impl Motion {
106    /// animate during window resize instead of snapping to the new layout
107    pub fn resize(mut self) -> Self {
108        self.properties |= MotionProps::RESIZE;
109        self
110    }
111
112    pub fn x(mut self) -> Self {
113        self.properties |= MotionProps::X;
114        self
115    }
116
117    pub fn y(mut self) -> Self {
118        self.properties |= MotionProps::Y;
119        self
120    }
121
122    pub fn width(mut self) -> Self {
123        self.properties |= MotionProps::WIDTH;
124        self
125    }
126
127    pub fn height(mut self) -> Self {
128        self.properties |= MotionProps::HEIGHT;
129        self
130    }
131
132    pub fn position(mut self) -> Self {
133        self.properties |= MotionProps::POSITION;
134        self
135    }
136
137    pub fn size(mut self) -> Self {
138        self.properties |= MotionProps::SIZE;
139        self
140    }
141
142    pub fn layout(mut self) -> Self {
143        self.properties |= MotionProps::LAYOUT;
144        self
145    }
146}
147
148#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
149pub struct MotionProps(u8);
150
151impl MotionProps {
152    pub const NONE: Self = Self(0);
153    pub const X: Self = Self(1 << 0);
154    pub const Y: Self = Self(1 << 1);
155    pub const WIDTH: Self = Self(1 << 2);
156    pub const HEIGHT: Self = Self(1 << 3);
157    pub const RESIZE: Self = Self(1 << 4);
158    pub const POSITION: Self = Self(Self::X.0 | Self::Y.0);
159    pub const SIZE: Self = Self(Self::WIDTH.0 | Self::HEIGHT.0);
160    pub const LAYOUT: Self = Self(Self::POSITION.0 | Self::SIZE.0);
161
162    pub const fn intersects(self, other: Self) -> bool {
163        self.0 & other.0 != 0
164    }
165
166    pub const fn intersection(self, other: Self) -> Self {
167        Self(self.0 & other.0)
168    }
169
170    pub const fn is_empty(self) -> bool {
171        self.0 == 0
172    }
173}
174
175impl BitOr for MotionProps {
176    type Output = Self;
177
178    fn bitor(self, other: Self) -> Self {
179        Self(self.0 | other.0)
180    }
181}
182
183impl BitOrAssign for MotionProps {
184    fn bitor_assign(&mut self, other: Self) {
185        self.0 |= other.0;
186    }
187}
188
189/// easing as a cubic bezier or a function
190#[derive(Clone, Copy, Debug)]
191pub enum Easing {
192    /// control points `[x1, y1, x2, y2]`
193    /// x coordinates are between zero and one and y may overshoot
194    Bezier([f32; 4]),
195    /// receives progress in `0..=1` and returns `(value, slope)`
196    /// value must start at zero and end at one
197    /// slope is the derivative with respect to progress
198    Function(fn(f32) -> (f32, f32)),
199}
200
201impl Easing {
202    pub const LINEAR: Self = Self::Bezier([0.0, 0.0, 1.0, 1.0]);
203    pub const EASE_IN_QUAD: Self = Self::Bezier([1.0 / 3.0, 0.0, 2.0 / 3.0, 1.0 / 3.0]);
204    pub const EASE_OUT_QUAD: Self = Self::Bezier([1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0, 1.0]);
205    pub const EASE: Self = Self::Bezier([0.25, 0.1, 0.25, 1.0]);
206    pub const EASE_IN: Self = Self::Bezier([0.42, 0.0, 1.0, 1.0]);
207    pub const EASE_OUT: Self = Self::Bezier([0.0, 0.0, 0.58, 1.0]);
208    pub const EASE_IN_OUT: Self = Self::Bezier([0.42, 0.0, 0.58, 1.0]);
209    pub const EASE_IN_CUBIC: Self = Self::Bezier([0.32, 0.0, 0.67, 0.0]);
210    pub const EASE_OUT_CUBIC: Self = Self::Bezier([0.33, 1.0, 0.68, 1.0]);
211    pub const EASE_IN_OUT_CUBIC: Self = Self::Bezier([0.65, 0.0, 0.35, 1.0]);
212    pub const EASE_OUT_EXPO: Self = Self::Bezier([0.16, 1.0, 0.3, 1.0]);
213
214    /// returns the eased value and its derivative
215    /// bezier slopes are capped at 1000 in either direction
216    #[inline]
217    pub fn sample(self, value: f32) -> (f32, f32) {
218        const MAX_SLOPE: f64 = 1000.0;
219
220        let [x1, y1, x2, y2] = match self {
221            Self::Bezier(points) => points,
222            Self::Function(sample) => return sample(value),
223        };
224        if x1 == y1 && x2 == y2 {
225            return (value, 1.0);
226        }
227        let [y1, y2] = [y1, y2].map(f64::from);
228        let value = value as f64;
229        let cy = 3.0 * y1;
230        let by = 3.0 * (y2 - y1) - cy;
231        let ay = 1.0 - cy - by;
232        if x1 == 1.0 / 3.0 && x2 == 2.0 / 3.0 {
233            // a linear time axis needs no inversion
234            let amount = if value <= 0.0 {
235                0.0
236            } else if value >= 1.0 {
237                1.0
238            } else {
239                ((ay * value + by) * value + cy) * value
240            };
241            let slope = ((3.0 * ay * value + 2.0 * by) * value + cy).clamp(-MAX_SLOPE, MAX_SLOPE);
242            return (amount as f32, slope as f32);
243        }
244        let [x1, x2] = [x1, x2].map(f64::from);
245        let cx = 3.0 * x1;
246        let bx = 3.0 * (x2 - x1) - cx;
247        let ax = 1.0 - cx - bx;
248        let mut low = 0.0;
249        let mut high = 1.0;
250        let mut t = value.clamp(0.0, 1.0);
251        for _ in 0..32 {
252            let error = ((ax * t + bx) * t + cx) * t - value;
253            let derivative = (3.0 * ax * t + 2.0 * bx) * t + cx;
254            if error.abs() <= derivative.abs() * 1e-10 {
255                break;
256            }
257            if error < 0.0 {
258                low = t;
259            } else {
260                high = t;
261            }
262            let next = t - error / derivative;
263            t = if next > low && next < high {
264                next
265            } else {
266                (low + high) * 0.5
267            };
268        }
269        let dx = (3.0 * ax * t + 2.0 * bx) * t + cx;
270        let dy = (3.0 * ay * t + 2.0 * by) * t + cy;
271        let slope = if dx > 0.0 {
272            dy / dx
273        } else if t == 0.0 && y1 == 0.0 && x2 > 0.0 {
274            y2 / x2
275        } else if t == 1.0 && y2 == 1.0 && x1 < 1.0 {
276            (1.0 - y1) / (1.0 - x1)
277        } else if dy == 0.0 {
278            0.0
279        } else {
280            dy.signum() * MAX_SLOPE
281        }
282        .clamp(-MAX_SLOPE, MAX_SLOPE);
283        let amount = if value <= 0.0 {
284            0.0
285        } else if value >= 1.0 {
286            1.0
287        } else {
288            ((ay * t + by) * t + cy) * t
289        };
290        (amount as f32, slope as f32)
291    }
292}
293
294impl PartialEq for Easing {
295    fn eq(&self, other: &Self) -> bool {
296        match (self, other) {
297            (Self::Bezier(a), Self::Bezier(b)) => a == b,
298            (Self::Function(a), Self::Function(b)) => core::ptr::fn_addr_eq(*a, *b),
299            _ => false,
300        }
301    }
302}
303
304impl Default for Easing {
305    fn default() -> Self {
306        Self::LINEAR
307    }
308}
309
310//
311// internals
312//
313
314pub struct AnimationState {
315    pub call: Call,
316    pub playback: Playback,
317    pub seen: bool,
318}
319
320impl AnimationState {
321    pub fn update(animations: &mut Vec<Self>, mut call: Call, initial: f32) -> &mut Self {
322        let index = loop {
323            match animations.binary_search_by_key(&call, |animation| animation.call) {
324                Ok(index) if animations[index].seen => call.repeat += 1,
325                Ok(index) => break index,
326                Err(index) => {
327                    animations.insert(
328                        index,
329                        Self {
330                            call,
331                            playback: Playback::Target(Animator::new([initial], Animation::default())),
332                            seen: false,
333                        },
334                    );
335                    break index;
336                }
337            }
338        };
339        let animation = &mut animations[index];
340        animation.seen = true;
341        animation
342    }
343
344    pub fn is_active(&self) -> bool {
345        match &self.playback {
346            Playback::Target(animator) => animator.is_active(),
347            Playback::Loop { .. } => true,
348        }
349    }
350}
351
352pub enum Playback {
353    Target(Animator<f32, 1>),
354    Loop { tween: Tween, time: f64, value: f32 },
355}
356
357pub struct MotionState<T: Scalar> {
358    pub id: Id,
359    pub animator: Animator<T, 4>,
360    pub properties: MotionProps,
361    pub node: NodeId,
362    pub initialized: bool,
363    pub seen: bool,
364    // moved to another reference and still settling
365    pub flying: bool,
366}
367
368impl<T: Scalar> MotionState<T> {
369    pub fn new(id: Id, node: NodeId) -> Self {
370        Self {
371            id,
372            animator: Animator::new([T::ZERO; 4], Animation::default()),
373            properties: MotionProps::NONE,
374            node,
375            initialized: false,
376            seen: true,
377            flying: false,
378        }
379    }
380
381    pub fn is_active(&self) -> bool {
382        self.animator.is_active()
383    }
384
385    pub fn advance(
386        &mut self,
387        target: Rect<T>,
388        config: Motion,
389        now: Duration,
390        resized: bool,
391        commit: bool,
392    ) -> ([T; 4], MotionProps) {
393        let targets = [target.x, target.y, target.width, target.height];
394        let options = AnimationOptions {
395            initial: None,
396            restart: config.restart,
397            velocity: None,
398            delay: config.delay,
399        };
400        if !self.initialized || (resized && !config.properties.intersects(MotionProps::RESIZE)) {
401            if commit {
402                self.animator = Animator::new(targets, config.animation);
403                self.initialized = true;
404            }
405            return (targets, MotionProps::NONE);
406        }
407        let properties = [MotionProps::X, MotionProps::Y, MotionProps::WIDTH, MotionProps::HEIGHT];
408        let (mut values, active) = self.animator.advance(
409            targets,
410            properties.map(|p| config.properties.intersects(p)),
411            config.animation,
412            options,
413            now,
414            commit,
415        );
416        for (i, value) in values.iter_mut().enumerate().skip(2) {
417            if *value < T::ZERO {
418                *value = T::ZERO;
419                if commit {
420                    self.animator.clamp(i, T::ZERO, T::UNBOUNDED, now);
421                }
422            }
423        }
424        let mut animated = MotionProps::NONE;
425        for (i, property) in properties.into_iter().enumerate() {
426            if active[i] {
427                animated |= property;
428            }
429        }
430        (values, animated)
431    }
432}