zng_var/
animation.rs

1//! Var animation types and functions.
2
3use std::{any::Any, fmt, sync::Arc, time::Duration};
4
5use parking_lot::Mutex;
6use smallbox::SmallBox;
7use zng_app_context::context_local;
8use zng_handle::{Handle, HandleOwner, WeakHandle};
9use zng_time::{DInstant, Deadline};
10use zng_unit::Factor;
11
12use crate::{
13    Var, VarHandle, VarHandlerOwner, VarValue,
14    animation::easing::{EasingStep, EasingTime},
15};
16
17pub mod easing;
18pub use zng_var_proc_macros::Transitionable;
19
20/// View on an app loop timer.
21pub trait AnimationTimer {
22    /// Returns `true` if the `deadline` has elapsed, `false` if the `deadline` was
23    /// registered for future waking.
24    fn elapsed(&mut self, deadline: Deadline) -> bool;
25
26    /// Register the future `deadline` for waking.
27    fn register(&mut self, deadline: Deadline);
28
29    /// Frame timestamp.
30    fn now(&self) -> DInstant;
31}
32
33/// Animations controller.
34///
35/// See [`VARS.with_animation_controller`] for more details.
36///
37/// [`VARS.with_animation_controller`]: crate::VARS::with_animation_controller
38pub trait AnimationController: Send + Sync + Any {
39    /// Called for each `animation` that starts in the controller context.
40    ///
41    /// Note that this handler itself is not called inside the controller context.
42    fn on_start(&self, animation: &Animation) {
43        let _ = animation;
44    }
45
46    /// Called for each `animation` that ends in the controller context.
47    ///
48    /// Note that this handler itself is not called inside the controller context.
49    fn on_stop(&self, animation: &Animation) {
50        let _ = animation;
51    }
52}
53
54impl AnimationController for () {}
55
56/// An [`AnimationController`] that forces animations to run even if animations are not enabled.
57pub struct ForceAnimationController;
58impl AnimationController for ForceAnimationController {
59    fn on_start(&self, animation: &Animation) {
60        animation.force_enable();
61    }
62}
63
64context_local! {
65    pub(crate) static VARS_ANIMATION_CTRL_CTX: Box<dyn AnimationController> = {
66        let r: Box<dyn AnimationController> = Box::new(());
67        r
68    };
69}
70
71/// Represents an animation in its closure.
72///
73/// See the [`VARS.animate`] method for more details.
74///
75/// [`VARS.animate`]: crate::VARS::animate
76#[derive(Clone)]
77pub struct Animation(Arc<Mutex<AnimationData>>);
78struct AnimationData {
79    start_time: DInstant,
80    restarted_count: usize,
81    stop: bool,
82    sleep: Option<Deadline>,
83    restart_next: bool,
84    animations_enabled: bool,
85    force_enabled: bool,
86    now: DInstant,
87    time_scale: Factor,
88}
89
90impl Animation {
91    pub(super) fn new(animations_enabled: bool, now: DInstant, time_scale: Factor) -> Self {
92        Animation(Arc::new(Mutex::new(AnimationData {
93            start_time: now,
94            restarted_count: 0,
95            stop: false,
96            now,
97            sleep: None,
98            restart_next: false,
99            animations_enabled,
100            force_enabled: false,
101            time_scale,
102        })))
103    }
104
105    /// The instant this animation (re)started.
106    pub fn start_time(&self) -> DInstant {
107        self.0.lock().start_time
108    }
109
110    /// The instant the current animation update started.
111    ///
112    /// Use this value instead of [`INSTANT.now`], animations update sequentially, but should behave as if
113    /// they are updating exactly in parallel, using this timestamp ensures that.
114    ///
115    /// [`INSTANT.now`]: zng_time::INSTANT::now
116    pub fn now(&self) -> DInstant {
117        self.0.lock().now
118    }
119
120    /// Global time scale for animations.
121    pub fn time_scale(&self) -> Factor {
122        self.0.lock().time_scale
123    }
124
125    pub(crate) fn reset_state(&self, enabled: bool, now: DInstant, time_scale: Factor) {
126        let mut m = self.0.lock();
127        if !m.force_enabled {
128            m.animations_enabled = enabled;
129        }
130        m.now = now;
131        m.time_scale = time_scale;
132        m.sleep = None;
133
134        if std::mem::take(&mut m.restart_next) {
135            m.start_time = now;
136            m.restarted_count += 1;
137        }
138    }
139
140    pub(crate) fn reset_sleep(&self) {
141        self.0.lock().sleep = None;
142    }
143
144    /// Set the duration to the next animation update. The animation will *sleep* until `duration` elapses.
145    ///
146    /// The animation awakes in the next [`VARS.frame_duration`] after the `duration` elapses. The minimum
147    /// possible `duration` is the frame duration, shorter durations behave the same as if not set.
148    ///
149    /// Set `restart` to restart the animation after the `duration` elapses.
150    ///
151    /// [`VARS.frame_duration`]: crate::VARS::frame_duration
152    pub fn sleep(&self, duration: Duration, restart: bool) {
153        let mut me = self.0.lock();
154        me.sleep = Some(Deadline(me.now + duration));
155        me.restart_next = restart;
156    }
157
158    pub(crate) fn sleep_deadline(&self) -> Option<Deadline> {
159        self.0.lock().sleep
160    }
161
162    /// Returns a value that indicates if animations are enabled in the operating system.
163    ///
164    /// If `false` all animations must be skipped to the end, users with photo-sensitive epilepsy disable animations system wide.
165    pub fn animations_enabled(&self) -> bool {
166        self.0.lock().animations_enabled
167    }
168
169    /// Set [`animations_enabled`] to `true`.
170    ///
171    /// This should only be used for animations that are component of an app feature, cosmetic animations must not force enable.
172    ///
173    /// [`animations_enabled`]: crate::VARS::animations_enabled
174    pub fn force_enable(&self) {
175        let mut me = self.0.lock();
176        me.force_enabled = true;
177        me.animations_enabled = true;
178    }
179
180    /// Compute the time elapsed from [`start_time`] to [`now`].
181    ///
182    /// [`start_time`]: Self::start_time
183    /// [`now`]: Self::now
184    pub fn elapsed_dur(&self) -> Duration {
185        let me = self.0.lock();
186        me.now - me.start_time
187    }
188
189    /// Compute the elapsed [`EasingTime`], in the span of the total `duration`, if [`animations_enabled`].
190    ///
191    /// If animations are disabled, returns [`EasingTime::end`], the returned time is scaled.
192    ///
193    /// [`animations_enabled`]: Self::animations_enabled
194    pub fn elapsed(&self, duration: Duration) -> EasingTime {
195        let me = self.0.lock();
196        if me.animations_enabled {
197            EasingTime::elapsed(duration, me.now - me.start_time, me.time_scale)
198        } else {
199            EasingTime::end()
200        }
201    }
202
203    /// Compute the elapsed [`EasingTime`], if the time [`is_end`] requests animation stop.
204    ///
205    /// [`is_end`]: EasingTime::is_end
206    pub fn elapsed_stop(&self, duration: Duration) -> EasingTime {
207        let t = self.elapsed(duration);
208        if t.is_end() {
209            self.stop()
210        }
211        t
212    }
213
214    /// Compute the elapsed [`EasingTime`], if the time [`is_end`] restarts the animation.
215    ///
216    /// [`is_end`]: EasingTime::is_end
217    pub fn elapsed_restart(&self, duration: Duration) -> EasingTime {
218        let t = self.elapsed(duration);
219        if t.is_end() {
220            self.restart()
221        }
222        t
223    }
224
225    /// Compute the elapsed [`EasingTime`], if the time [`is_end`] restarts the animation, repeats until has
226    /// restarted `max_restarts` inclusive, then stops the animation.
227    ///
228    /// [`is_end`]: EasingTime::is_end
229    pub fn elapsed_restart_stop(&self, duration: Duration, max_restarts: usize) -> EasingTime {
230        let t = self.elapsed(duration);
231        if t.is_end() {
232            if self.count() < max_restarts {
233                self.restart();
234            } else {
235                self.stop();
236            }
237        }
238        t
239    }
240
241    /// Drop the animation after applying the current update.
242    pub fn stop(&self) {
243        self.0.lock().stop = true;
244    }
245
246    /// If the animation will be dropped after applying the update.
247    pub fn stop_requested(&self) -> bool {
248        self.0.lock().stop
249    }
250
251    /// Set the animation start time to now.
252    pub fn restart(&self) {
253        let mut me = self.0.lock();
254        me.start_time = me.now;
255        me.restarted_count += 1;
256    }
257
258    #[doc(hidden)]
259    #[deprecated = "use  `count`"]
260    pub fn restart_count(&self) -> usize {
261        self.0.lock().restarted_count
262    }
263
264    /// Number of times the animation time restarted.
265    pub fn count(&self) -> usize {
266        self.0.lock().restarted_count
267    }
268
269    /// Change the start time to an arbitrary value.
270    ///
271    /// Note that this does not affect the restart count.
272    pub fn set_start_time(&self, instant: DInstant) {
273        self.0.lock().start_time = instant;
274    }
275
276    /// Change the start to an instant that computes the `elapsed` for the `duration` at the moment
277    /// this method is called.
278    ///
279    /// Note that this does not affect the restart count.
280    pub fn set_elapsed(&self, elapsed: EasingTime, duration: Duration) {
281        let now = self.0.lock().now;
282        self.set_start_time(now.checked_sub(duration * elapsed.fct()).unwrap());
283    }
284
285    /// Change the restart count to an arbitrary value.
286    pub fn set_count(&self, count: usize) {
287        self.0.lock().restarted_count = count;
288    }
289}
290
291/// Represents the current *modify* operation when it is applying.
292#[derive(Clone)]
293pub struct ModifyInfo {
294    pub(crate) handle: Option<WeakAnimationHandle>,
295    pub(crate) importance: usize,
296}
297impl ModifyInfo {
298    /// Initial value, is always of lowest importance.
299    pub fn never() -> Self {
300        ModifyInfo {
301            handle: None,
302            importance: 0,
303        }
304    }
305
306    /// Indicates the *override* importance of the operation, when two animations target
307    /// a variable only the newer one must apply, and all running animations are *overridden* by
308    /// a later modify/set operation.
309    ///
310    /// Variables ignore modify requests from lower importance closures.
311    pub fn importance(&self) -> usize {
312        self.importance
313    }
314
315    /// Indicates if the *modify* request was made from inside an animation, if `true` the [`importance`]
316    /// is for that animation, even if the modify request is from the current frame.
317    ///
318    /// You can clone this info to track this animation, when it stops or is dropped this returns `false`. Note
319    /// that sleeping animations still count as animating.
320    ///
321    /// [`importance`]: Self::importance
322    pub fn is_animating(&self) -> bool {
323        self.handle.as_ref().map(|h| h.upgrade().is_some()).unwrap_or(false)
324    }
325
326    /// Returns `true` if `self` and `other` have the same animation or are both not animating.
327    pub fn animation_eq(&self, other: &Self) -> bool {
328        self.handle == other.handle
329    }
330
331    /// Register a `handler` to be called once when the current animation stops.
332    ///
333    /// [`importance`]: Self::importance
334    pub fn hook_animation_stop(&self, handler: AnimationStopFn) -> VarHandle {
335        if let Some(h) = &self.handle
336            && let Some(h) = h.upgrade()
337        {
338            return h.hook_animation_stop(handler);
339        }
340        VarHandle::dummy()
341    }
342}
343impl fmt::Debug for ModifyInfo {
344    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
345        f.debug_struct("ModifyInfo")
346            .field("is_animating()", &self.is_animating())
347            .field("importance()", &self.importance)
348            .finish()
349    }
350}
351
352pub(crate) type AnimationStopFn = SmallBox<dyn FnMut() + Send + 'static, smallbox::space::S4>;
353
354#[derive(Default)]
355pub(super) struct AnimationHandleData {
356    on_drop: Mutex<Vec<(AnimationStopFn, VarHandlerOwner)>>,
357}
358impl Drop for AnimationHandleData {
359    fn drop(&mut self) {
360        for (mut f, h) in self.on_drop.get_mut().drain(..) {
361            if h.is_alive() {
362                f()
363            }
364        }
365    }
366}
367/// Represents a running animation.
368///
369/// Drop all clones of this handle to stop the animation, or call [`perm`] to drop the handle
370/// but keep the animation alive until it is stopped from the inside.
371///
372/// [`perm`]: AnimationHandle::perm
373#[derive(Clone, PartialEq, Eq, Hash, Debug)]
374#[repr(transparent)]
375#[must_use = "the animation stops if the handle is dropped"]
376pub struct AnimationHandle(Handle<AnimationHandleData>);
377impl Default for AnimationHandle {
378    /// `dummy`.
379    fn default() -> Self {
380        Self::dummy()
381    }
382}
383impl AnimationHandle {
384    pub(super) fn new() -> (HandleOwner<AnimationHandleData>, Self) {
385        let (owner, handle) = Handle::new(AnimationHandleData::default());
386        (owner, AnimationHandle(handle))
387    }
388
389    /// Create dummy handle that is always in the *stopped* state.
390    ///
391    /// Note that `Option<AnimationHandle>` takes up the same space as `AnimationHandle` and avoids an allocation.
392    pub fn dummy() -> Self {
393        AnimationHandle(Handle::dummy(AnimationHandleData::default()))
394    }
395
396    /// Drops the handle but does **not** stop.
397    ///
398    /// The animation stays in memory for the duration of the app or until another handle calls [`stop`](Self::stop).
399    pub fn perm(self) {
400        self.0.perm();
401    }
402
403    /// If another handle has called [`perm`](Self::perm).
404    ///
405    /// If `true` the animation will stay active until the app exits, unless [`stop`](Self::stop) is called.
406    pub fn is_permanent(&self) -> bool {
407        self.0.is_permanent()
408    }
409
410    /// Drops the handle and forces the animation to drop.
411    pub fn stop(self) {
412        self.0.force_drop();
413    }
414
415    /// If another handle has called [`stop`](Self::stop).
416    ///
417    /// The animation is already dropped or will be dropped in the next app update, this is irreversible.
418    pub fn is_stopped(&self) -> bool {
419        self.0.is_dropped()
420    }
421
422    /// Create a weak handle.
423    pub fn downgrade(&self) -> WeakAnimationHandle {
424        WeakAnimationHandle(self.0.downgrade())
425    }
426
427    /// Register a `handler` to be called once when the animation stops.
428    ///
429    /// Returns the `handler` if the animation has already stopped.
430    ///
431    /// [`importance`]: ModifyInfo::importance
432    pub fn hook_animation_stop(&self, handler: AnimationStopFn) -> VarHandle {
433        if !self.is_stopped() {
434            let (owner, handle) = VarHandle::new();
435            self.0.data().on_drop.lock().push((handler, owner));
436            handle
437        } else {
438            VarHandle::dummy()
439        }
440    }
441}
442
443/// Weak [`AnimationHandle`].
444#[derive(Clone, PartialEq, Eq, Hash, Default, Debug)]
445pub struct WeakAnimationHandle(pub(super) WeakHandle<AnimationHandleData>);
446impl WeakAnimationHandle {
447    /// New weak handle that does not upgrade.
448    pub fn new() -> Self {
449        Self(WeakHandle::new())
450    }
451
452    /// Get the animation handle if it is still animating.
453    pub fn upgrade(&self) -> Option<AnimationHandle> {
454        self.0.upgrade().map(AnimationHandle)
455    }
456}
457
458/// Represents a type that can be animated between two values.
459///
460/// This trait is auto-implemented for all [`Copy`] types that can add, subtract and multiply by [`Factor`], [`Clone`]
461/// only types must implement this trait manually.
462///
463/// [`Factor`]: zng_unit::Factor
464pub trait Transitionable: VarValue {
465    /// Sample the linear interpolation from `self` -> `to` by `step`.  
466    fn lerp(self, to: &Self, step: EasingStep) -> Self;
467}
468
469/// Represents a simple transition between two values.
470#[non_exhaustive]
471pub struct Transition<T> {
472    /// Value sampled at the `0.fct()` step.
473    pub from: T,
474    ///
475    /// Value sampled at the `1.fct()` step.
476    pub to: T,
477}
478impl<T> Transition<T>
479where
480    T: Transitionable,
481{
482    /// New transition.
483    pub fn new(from: T, to: T) -> Self {
484        Self { from, to }
485    }
486
487    /// Compute the transition value at the `step`.
488    pub fn sample(&self, step: EasingStep) -> T {
489        self.from.clone().lerp(&self.to, step)
490    }
491}
492
493/// Represents a transition across multiple keyed values that can be sampled using [`EasingStep`].
494#[derive(Clone, Debug)]
495pub struct TransitionKeyed<T> {
496    keys: Vec<(Factor, T)>,
497}
498impl<T> TransitionKeyed<T>
499where
500    T: Transitionable,
501{
502    /// New transition.
503    ///
504    /// Returns `None` if `keys` is empty.
505    pub fn new(mut keys: Vec<(Factor, T)>) -> Option<Self> {
506        if keys.is_empty() {
507            return None;
508        }
509
510        // correct backtracking keyframes.
511        for i in 1..keys.len() {
512            if keys[i].0 < keys[i - 1].0 {
513                keys[i].0 = keys[i - 1].0;
514            }
515        }
516
517        Some(TransitionKeyed { keys })
518    }
519
520    /// Keyed values.
521    pub fn keys(&self) -> &[(Factor, T)] {
522        &self.keys
523    }
524
525    /// Compute the transition value at the `step`.
526    pub fn sample(&self, step: EasingStep) -> T {
527        if let Some(i) = self.keys.iter().position(|(f, _)| *f > step) {
528            if i == 0 {
529                // step before first
530                self.keys[0].1.clone()
531            } else {
532                let (from_step, from_value) = self.keys[i - 1].clone();
533                if from_step == step {
534                    // step exact key
535                    from_value
536                } else {
537                    // linear interpolate between steps
538
539                    let (_, to_value) = &self.keys[i];
540                    let step = step - from_step;
541
542                    from_value.lerp(to_value, step)
543                }
544            }
545        } else {
546            // step is after last
547            self.keys[self.keys.len() - 1].1.clone()
548        }
549    }
550}
551
552/// Represents the editable final value of a [`Var::chase`] animation.
553pub struct ChaseAnimation<T: VarValue + Transitionable> {
554    pub(super) target: T,
555    pub(super) var: Var<T>,
556    pub(super) handle: AnimationHandle,
557}
558impl<T> fmt::Debug for ChaseAnimation<T>
559where
560    T: VarValue + Transitionable,
561{
562    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
563        f.debug_struct("ChaseAnimation")
564            .field("target", &self.target)
565            .finish_non_exhaustive()
566    }
567}
568impl<T> ChaseAnimation<T>
569where
570    T: VarValue + Transitionable,
571{
572    /// Current animation target.
573    pub fn target(&self) -> &T {
574        &self.target
575    }
576
577    /// Modify the chase target, replaces the animation with a new one from the current value to the modified target.
578    pub fn modify(&mut self, modify: impl FnOnce(&mut T), duration: Duration, easing: impl Fn(EasingTime) -> EasingStep + Send + 'static) {
579        if self.handle.is_stopped() {
580            // re-sync target
581            self.target = self.var.get();
582        }
583        modify(&mut self.target);
584        self.handle = self.var.ease(self.target.clone(), duration, easing);
585    }
586
587    /// Replace the chase target, replaces the animation with a new one from the current value to the modified target.
588    pub fn set(&mut self, value: impl Into<T>, duration: Duration, easing: impl Fn(EasingTime) -> EasingStep + Send + 'static) {
589        self.target = value.into();
590        self.handle = self.var.ease(self.target.clone(), duration, easing);
591    }
592}
593
594/// Spherical linear interpolation sampler.
595///
596/// Animates rotations over the shortest change between angles by modulo wrapping.
597/// A transition from 358º to 1º goes directly to 361º (modulo normalized to 1º).
598///
599/// Types that support this use the [`is_slerp_enabled`] function inside [`Transitionable::lerp`] to change
600/// mode, types that don't support this use the normal linear interpolation. All angle and transform units
601/// implement this.
602///
603/// Samplers can be set in animations using the `Var::easing_with` method.
604pub fn slerp_sampler<T: Transitionable>(t: &Transition<T>, step: EasingStep) -> T {
605    slerp_enabled(true, || t.sample(step))
606}
607
608/// Gets if slerp mode is enabled in the context.
609///
610/// See [`slerp_sampler`] for more details.
611pub fn is_slerp_enabled() -> bool {
612    SLERP_ENABLED.get_clone()
613}
614
615/// Calls `f` with [`is_slerp_enabled`] set to `enabled`.
616///
617/// See [`slerp_sampler`] for a way to enable in animations.
618pub fn slerp_enabled<R>(enabled: bool, f: impl FnOnce() -> R) -> R {
619    SLERP_ENABLED.with_context(&mut Some(Arc::new(enabled)), f)
620}
621
622context_local! {
623    static SLERP_ENABLED: bool = false;
624}
625
626/// API for app implementers to replace the transitionable implementation for foreign types.
627#[expect(non_camel_case_types)]
628pub struct TRANSITIONABLE_APP;