From cc3105daed8e94897469b9585ab40700a817a7ae Mon Sep 17 00:00:00 2001 From: Alex Saveau <saveau.alexandre@gmail.com> Date: Mon, 13 Jun 2022 23:14:03 -0700 Subject: [PATCH] Reformat all comments using rustfmt (#29) --- examples/sequence.rs | 14 ++-- src/lens.rs | 100 ++++++++++++++----------- src/lib.rs | 131 +++++++++++++++++++-------------- src/plugin.rs | 27 ++++--- src/tweenable.rs | 170 ++++++++++++++++++++++++++----------------- 5 files changed, 257 insertions(+), 185 deletions(-) diff --git a/examples/sequence.rs b/examples/sequence.rs index 161676b..f09d9a0 100644 --- a/examples/sequence.rs +++ b/examples/sequence.rs @@ -118,7 +118,8 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { end: pair[1] - center, }, ) - .with_completed_event(true, index as u64) // Get an event after each segment + // Get an event after each segment + .with_completed_event(true, index as u64) })); commands @@ -133,8 +134,8 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { .insert(RedSprite) .insert(Animator::new(seq)); - // First move from left to right, then rotate around self 180 degrees while scaling - // size at the same time. + // First move from left to right, then rotate around self 180 degrees while + // scaling size at the same time. let tween_move = Tween::new( EaseFunction::QuadraticInOut, TweeningType::Once, @@ -163,10 +164,11 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) { end: Vec3::splat(2.0), }, ); - // Build parallel tracks executing two tweens at the same time : rotate and scale. + // Build parallel tracks executing two tweens at the same time: rotate and + // scale. let tracks = Tracks::new([tween_rotate, tween_scale]); - // Build a sequence from an heterogeneous list of tweenables by casting them manually - // to a boxed Tweenable<Transform> : first move, then { rotate + scale }. + // Build a sequence from an heterogeneous list of tweenables by casting them + // manually to a BoxedTweenable: first move, then { rotate + scale }. let seq2 = Sequence::new([Box::new(tween_move) as BoxedTweenable<_>, tracks.into()]); commands diff --git a/src/lens.rs b/src/lens.rs index a8eb345..368b740 100644 --- a/src/lens.rs +++ b/src/lens.rs @@ -2,9 +2,10 @@ //! //! # Predefined lenses //! -//! This module contains predefined lenses for common use cases. Those lenses are -//! entirely optional. They can be used if they fit your use case, to save some time, -//! but are not treated any differently from a custom user-provided lens. +//! This module contains predefined lenses for common use cases. Those lenses +//! are entirely optional. They can be used if they fit your use case, to save +//! some time, but are not treated any differently from a custom user-provided +//! lens. //! //! # Rotations //! @@ -12,19 +13,19 @@ //! //! ## Shortest-path rotation //! -//! The [`TransformRotationLens`] animates the [`rotation`] field of a [`Transform`] -//! component using [`Quat::slerp()`]. It inherits the properties of that method, and -//! in particular the fact it always finds the "shortest path" from start to end. This -//! is well suited for animating a rotation between two given directions, but will -//! provide unexpected results if you try to make an entity rotate around a given axis -//! for more than half a turn, as [`Quat::slerp()`] will then try to move "the other -//! way around". +//! The [`TransformRotationLens`] animates the [`rotation`] field of a +//! [`Transform`] component using [`Quat::slerp()`]. It inherits the properties +//! of that method, and in particular the fact it always finds the "shortest +//! path" from start to end. This is well suited for animating a rotation +//! between two given directions, but will provide unexpected results if you try +//! to make an entity rotate around a given axis for more than half a turn, as +//! [`Quat::slerp()`] will then try to move "the other way around". //! //! ## Angle-focused rotations //! -//! Conversely, for cases where the rotation direction is important, like when trying -//! to do a full 360-degree turn, a series of angle-based interpolation lenses is -//! provided: +//! Conversely, for cases where the rotation direction is important, like when +//! trying to do a full 360-degree turn, a series of angle-based interpolation +//! lenses is provided: //! - [`TransformRotateXLens`] //! - [`TransformRotateYLens`] //! - [`TransformRotateZLens`] @@ -38,9 +39,10 @@ use bevy::prelude::*; /// A lens over a subset of a component. /// -/// The lens takes a `target` component or asset from a query, as a mutable reference, -/// and animates (tweens) a subset of the fields of the component/asset based on the -/// linear ratio `ratio` in \[0:1\], already sampled from the easing curve. +/// The lens takes a `target` component or asset from a query, as a mutable +/// reference, and animates (tweens) a subset of the fields of the +/// component/asset based on the linear ratio `ratio` in \[0:1\], already +/// sampled from the easing curve. /// /// # Example /// @@ -63,16 +65,17 @@ use bevy::prelude::*; /// } /// } /// ``` -/// pub trait Lens<T> { - /// Perform a linear interpolation (lerp) over the subset of fields of a component - /// or asset the lens focuses on, based on the linear ratio `ratio`. The `target` - /// component or asset is mutated in place. The implementation decides which fields - /// are interpolated, and performs the animation in-place, overwriting the target. + /// Perform a linear interpolation (lerp) over the subset of fields of a + /// component or asset the lens focuses on, based on the linear ratio + /// `ratio`. The `target` component or asset is mutated in place. The + /// implementation decides which fields are interpolated, and performs + /// the animation in-place, overwriting the target. fn lerp(&mut self, target: &mut T, ratio: f32); } -/// A lens to manipulate the [`color`] field of a section of a [`Text`] component. +/// A lens to manipulate the [`color`] field of a section of a [`Text`] +/// component. /// /// [`color`]: https://docs.rs/bevy/0.7.0/bevy/text/struct.TextStyle.html#structfield.color /// [`Text`]: https://docs.rs/bevy/0.7.0/bevy/text/struct.Text.html @@ -90,7 +93,8 @@ pub struct TextColorLens { #[cfg(feature = "bevy_ui")] impl Lens<Text> for TextColorLens { fn lerp(&mut self, target: &mut Text, ratio: f32) { - // Note: Add<f32> for Color affects alpha, but not Mul<f32>. So use Vec4 for consistency. + // Note: Add<f32> for Color affects alpha, but not Mul<f32>. So use Vec4 for + // consistency. let start: Vec4 = self.start.into(); let end: Vec4 = self.end.into(); let value = start.lerp(end, ratio); @@ -120,13 +124,15 @@ impl Lens<Transform> for TransformPositionLens { /// A lens to manipulate the [`rotation`] field of a [`Transform`] component. /// /// This lens interpolates the [`rotation`] field of a [`Transform`] component -/// from a `start` value to an `end` value using the spherical linear interpolation -/// provided by [`Quat::slerp()`]. This means the rotation always uses the shortest -/// path from `start` to `end`. In particular, this means it cannot make entities -/// do a full 360 degrees turn. Instead use [`TransformRotateXLens`] and similar -/// to interpolate the rotation angle around a given axis. +/// from a `start` value to an `end` value using the spherical linear +/// interpolation provided by [`Quat::slerp()`]. This means the rotation always +/// uses the shortest path from `start` to `end`. In particular, this means it +/// cannot make entities do a full 360 degrees turn. Instead use +/// [`TransformRotateXLens`] and similar to interpolate the rotation angle +/// around a given axis. /// -/// See the [top-level `lens` module documentation] for a comparison of rotation lenses. +/// See the [top-level `lens` module documentation] for a comparison of rotation +/// lenses. /// /// [`rotation`]: https://docs.rs/bevy/0.7.0/bevy/transform/components/struct.Transform.html#structfield.rotation /// [`Transform`]: https://docs.rs/bevy/0.7.0/bevy/transform/components/struct.Transform.html @@ -150,10 +156,11 @@ impl Lens<Transform> for TransformRotationLens { /// /// This lens interpolates the rotation angle of a [`Transform`] component from /// a `start` value to an `end` value, for a rotation around the X axis. Unlike -/// [`TransformRotationLens`], it can produce an animation that rotates the entity -/// any number of turns around its local X axis. +/// [`TransformRotationLens`], it can produce an animation that rotates the +/// entity any number of turns around its local X axis. /// -/// See the [top-level `lens` module documentation] for a comparison of rotation lenses. +/// See the [top-level `lens` module documentation] for a comparison of rotation +/// lenses. /// /// [`Transform`]: https://docs.rs/bevy/0.7.0/bevy/transform/components/struct.Transform.html /// [top-level `lens` module documentation]: crate::lens @@ -176,10 +183,11 @@ impl Lens<Transform> for TransformRotateXLens { /// /// This lens interpolates the rotation angle of a [`Transform`] component from /// a `start` value to an `end` value, for a rotation around the Y axis. Unlike -/// [`TransformRotationLens`], it can produce an animation that rotates the entity -/// any number of turns around its local Y axis. +/// [`TransformRotationLens`], it can produce an animation that rotates the +/// entity any number of turns around its local Y axis. /// -/// See the [top-level `lens` module documentation] for a comparison of rotation lenses. +/// See the [top-level `lens` module documentation] for a comparison of rotation +/// lenses. /// /// [`Transform`]: https://docs.rs/bevy/0.7.0/bevy/transform/components/struct.Transform.html /// [top-level `lens` module documentation]: crate::lens @@ -202,10 +210,11 @@ impl Lens<Transform> for TransformRotateYLens { /// /// This lens interpolates the rotation angle of a [`Transform`] component from /// a `start` value to an `end` value, for a rotation around the Z axis. Unlike -/// [`TransformRotationLens`], it can produce an animation that rotates the entity -/// any number of turns around its local Z axis. +/// [`TransformRotationLens`], it can produce an animation that rotates the +/// entity any number of turns around its local Z axis. /// -/// See the [top-level `lens` module documentation] for a comparison of rotation lenses. +/// See the [top-level `lens` module documentation] for a comparison of rotation +/// lenses. /// /// [`Transform`]: https://docs.rs/bevy/0.7.0/bevy/transform/components/struct.Transform.html /// [top-level `lens` module documentation]: crate::lens @@ -227,11 +236,12 @@ impl Lens<Transform> for TransformRotateZLens { /// A lens to rotate a [`Transform`] component around a given fixed axis. /// /// This lens interpolates the rotation angle of a [`Transform`] component from -/// a `start` value to an `end` value, for a rotation around a given axis. Unlike -/// [`TransformRotationLens`], it can produce an animation that rotates the entity -/// any number of turns around that axis. +/// a `start` value to an `end` value, for a rotation around a given axis. +/// Unlike [`TransformRotationLens`], it can produce an animation that rotates +/// the entity any number of turns around that axis. /// -/// See the [top-level `lens` module documentation] for a comparison of rotation lenses. +/// See the [top-level `lens` module documentation] for a comparison of rotation +/// lenses. /// /// # Panics /// @@ -327,7 +337,8 @@ pub struct ColorMaterialColorLens { #[cfg(feature = "bevy_sprite")] impl Lens<ColorMaterial> for ColorMaterialColorLens { fn lerp(&mut self, target: &mut ColorMaterial, ratio: f32) { - // Note: Add<f32> for Color affects alpha, but not Mul<f32>. So use Vec4 for consistency. + // Note: Add<f32> for Color affects alpha, but not Mul<f32>. So use Vec4 for + // consistency. let start: Vec4 = self.start.into(); let end: Vec4 = self.end.into(); let value = start.lerp(end, ratio); @@ -351,7 +362,8 @@ pub struct SpriteColorLens { #[cfg(feature = "bevy_sprite")] impl Lens<Sprite> for SpriteColorLens { fn lerp(&mut self, target: &mut Sprite, ratio: f32) { - // Note: Add<f32> for Color affects alpha, but not Mul<f32>. So use Vec4 for consistency. + // Note: Add<f32> for Color affects alpha, but not Mul<f32>. So use Vec4 for + // consistency. let start: Vec4 = self.start.into(); let end: Vec4 = self.end.into(); let value = start.lerp(end, ratio); diff --git a/src/lib.rs b/src/lib.rs index f05d268..55a104c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,9 +12,11 @@ //! Tweening animation plugin for the Bevy game engine //! -//! 🃠Bevy Tweening provides interpolation-based animation between ("tweening") two values, for Bevy components -//! and assets. Each field of a component or asset can be animated via a collection or predefined easing functions, -//! or providing a custom animation curve. Custom components and assets are also supported. +//! 🃠Bevy Tweening provides interpolation-based animation between ("tweening") +//! two values, for Bevy components and assets. Each field of a component or +//! asset can be animated via a collection or predefined easing functions, +//! or providing a custom animation curve. Custom components and assets are also +//! supported. //! //! # Example //! @@ -66,17 +68,20 @@ //! //! # Tweenables //! -//! 🃠Bevy Tweening supports several types of _tweenables_, building blocks that can be combined to form complex -//! animations. A tweenable is a type implementing the [`Tweenable`] trait. +//! 🃠Bevy Tweening supports several types of _tweenables_, building blocks +//! that can be combined to form complex animations. A tweenable is a type +//! implementing the [`Tweenable`] trait. //! //! - [`Tween`] - A simple tween (easing) animation between two values. -//! - [`Sequence`] - A series of tweenables executing in series, one after the other. +//! - [`Sequence`] - A series of tweenables executing in series, one after the +//! other. //! - [`Tracks`] - A collection of tweenables executing in parallel. //! - [`Delay`] - A time delay. //! //! ## Chaining animations //! -//! Most tweenables can be chained with the `then()` operator to produce a [`Sequence`] tweenable: +//! Most tweenables can be chained with the `then()` operator to produce a +//! [`Sequence`] tweenable: //! //! ``` //! # use bevy::prelude::*; @@ -108,35 +113,40 @@ //! //! # Animators and lenses //! -//! Bevy components and assets are animated with tweening _animator_ components, which take a tweenable and -//! apply it to another component on the same [`Entity`]. Those animators determine that other component and -//! its fields to animate using a _lens_. +//! Bevy components and assets are animated with tweening _animator_ components, +//! which take a tweenable and apply it to another component on the same +//! [`Entity`]. Those animators determine that other component and its fields to +//! animate using a _lens_. //! //! ## Components animation //! -//! Components are animated with the [`Animator`] component, which is generic over the type of component -//! it animates. This is a restriction imposed by Bevy, to access the animated component as a mutable -//! reference via a [`Query`] and comply with the ECS rules. +//! Components are animated with the [`Animator`] component, which is generic +//! over the type of component it animates. This is a restriction imposed by +//! Bevy, to access the animated component as a mutable reference via a +//! [`Query`] and comply with the ECS rules. //! -//! The [`Animator`] itself is not generic over the subset of fields of the components it animates. -//! This limits the proliferation of generic types when animating e.g. both the position and rotation -//! of an entity. +//! The [`Animator`] itself is not generic over the subset of fields of the +//! components it animates. This limits the proliferation of generic types when +//! animating e.g. both the position and rotation of an entity. //! //! ## Assets animation //! -//! Assets are animated in a similar way to component, via the [`AssetAnimator`] component. +//! Assets are animated in a similar way to component, via the [`AssetAnimator`] +//! component. //! -//! Because assets are typically shared, and the animation applies to the asset itself, all users of the asset -//! see the animation. For example, animating the color of a [`ColorMaterial`] will change the color of all the +//! Because assets are typically shared, and the animation applies to the asset +//! itself, all users of the asset see the animation. For example, animating the +//! color of a [`ColorMaterial`] will change the color of all the //! 2D meshes using that material. //! //! ## Lenses //! -//! Both [`Animator`] and [`AssetAnimator`] access the field(s) to animate via a lens, a type that implements -//! the [`Lens`] trait. +//! Both [`Animator`] and [`AssetAnimator`] access the field(s) to animate via a +//! lens, a type that implements the [`Lens`] trait. //! -//! Several predefined lenses are provided in the [`lens`] module for the most commonly animated fields, like the -//! components of a [`Transform`]. A custom lens can also be created by implementing the trait, allowing to animate +//! Several predefined lenses are provided in the [`lens`] module for the most +//! commonly animated fields, like the components of a [`Transform`]. A custom +//! lens can also be created by implementing the trait, allowing to animate //! virtually any field of any Bevy component or asset. //! //! [`Transform::translation`]: https://docs.rs/bevy/0.7.0/bevy/transform/components/struct.Transform.html#structfield.translation @@ -150,8 +160,7 @@ use bevy::{asset::Asset, prelude::*}; use std::time::Duration; use interpolation::Ease as IEase; -pub use interpolation::EaseFunction; -pub use interpolation::Lerp; +pub use interpolation::{EaseFunction, Lerp}; pub mod lens; mod plugin; @@ -170,11 +179,13 @@ pub use tweenable::{ pub enum TweeningType { /// Run the animation once from start to end only. Once, - /// Loop the animation indefinitely, restarting from the start each time the end is reached. + /// Loop the animation indefinitely, restarting from the start each time the + /// end is reached. Loop, - /// Loop the animation back and forth, changing direction each time an endpoint is reached. - /// A complete cycle start -> end -> start always counts as 2 loop iterations for the various - /// operations where looping matters. + /// Loop the animation back and forth, changing direction each time an + /// endpoint is reached. A complete cycle start -> end -> start always + /// counts as 2 loop iterations for the various operations where looping + /// matters. PingPong, } @@ -256,17 +267,20 @@ impl From<EaseFunction> for EaseMethod { /// Direction a tweening animation is playing. /// -/// When playing a tweenable forward, the progress values `0` and `1` are respectively mapped to -/// the start and end bounds of the lens(es) being used. Conversely, when playing backward, this -/// mapping is reversed, such that a progress value of `0` corresponds to the state of the target -/// at the end bound of the lens, while a progress value of `1` corresponds to the state of that -/// target at the start bound of the lens, effectively making the animation play backward. +/// When playing a tweenable forward, the progress values `0` and `1` are +/// respectively mapped to the start and end bounds of the lens(es) being used. +/// Conversely, when playing backward, this mapping is reversed, such that a +/// progress value of `0` corresponds to the state of the target at the end +/// bound of the lens, while a progress value of `1` corresponds to the state of +/// that target at the start bound of the lens, effectively making the animation +/// play backward. /// -/// For all but [`TweeningType::PingPong`] this is always [`TweeningDirection::Forward`], unless -/// manually configured with [`Tween::set_direction()`] in which case the value is constant equal -/// to the value set. For the [`TweeningType::PingPong`] tweening type, this is either forward -/// (from start to end; ping) or backward (from end to start; pong), depending on the current -/// iteration of the loop. +/// For all but [`TweeningType::PingPong`] this is always +/// [`TweeningDirection::Forward`], unless manually configured with +/// [`Tween::set_direction()`] in which case the value is constant equal +/// to the value set. For the [`TweeningType::PingPong`] tweening type, this is +/// either forward (from start to end; ping) or backward (from end to start; +/// pong), depending on the current iteration of the loop. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TweeningDirection { /// Animation playing from start to end. @@ -315,7 +329,8 @@ macro_rules! animator_impl { self } - /// Set the initial speed of the animator. See [`Animator::set_speed`] for details. + /// Set the initial speed of the animator. See [`Animator::set_speed`] for + /// details. #[must_use] pub fn with_speed(mut self, speed: f32) -> Self { self.speed = speed; @@ -324,8 +339,8 @@ macro_rules! animator_impl { /// Set the animation speed. Defaults to 1. /// - /// A speed of 2 means the animation will run twice as fast while a speed of 0.1 will result in - /// a 10x slowed animation. + /// A speed of 2 means the animation will run twice as fast while a speed of 0.1 + /// will result in a 10x slowed animation. pub fn set_speed(&mut self, speed: f32) { self.speed = speed; } @@ -366,21 +381,26 @@ macro_rules! animator_impl { } } - /// Get the current progress in \[0:1\] (non-looping) or \[0:1\[ (looping) of the animation. + /// Get the current progress in \[0:1\] (non-looping) or \[0:1\[ (looping) of + /// the animation. /// - /// For looping animations, this reports the progress of the current iteration, in the current direction: - /// - [`TweeningType::Loop`] is 0 at start and 1 at end. The exact value 1.0 is never reached, - /// since the tweenable loops over to 0.0 immediately. - /// - [`TweeningType::PingPong`] is 0 at the source endpoint and 1 and the destination one, - /// which are respectively the start/end for [`TweeningDirection::Forward`], or the end/start - /// for [`TweeningDirection::Backward`]. The exact value 1.0 is never reached, since the tweenable - /// loops over to 0.0 immediately when it changes direction at either endpoint. + /// For looping animations, this reports the progress of the current iteration, + /// in the current direction: + /// - [`TweeningType::Loop`] is 0 at start and 1 at end. The exact value 1.0 is + /// never reached, since the tweenable loops over to 0.0 immediately. + /// - [`TweeningType::PingPong`] is 0 at the source endpoint and 1 and the + /// destination one, which are respectively the start/end for + /// [`TweeningDirection::Forward`], or the end/start for + /// [`TweeningDirection::Backward`]. The exact value 1.0 is never reached, + /// since the tweenable loops over to 0.0 immediately when it changes + /// direction at either endpoint. /// - /// For sequences, the progress is measured over the entire sequence, from 0 at the start of the first - /// child tweenable to 1 at the end of the last one. + /// For sequences, the progress is measured over the entire sequence, from 0 at + /// the start of the first child tweenable to 1 at the end of the last one. /// - /// For tracks (parallel execution), the progress is measured like a sequence over the longest "path" of - /// child tweenables. In other words, this is the current elapsed time over the total tweenable duration. + /// For tracks (parallel execution), the progress is measured like a sequence + /// over the longest "path" of child tweenables. In other words, this is the + /// current elapsed time over the total tweenable duration. #[must_use] pub fn progress(&self) -> f32 { if let Some(tweenable) = &self.tweenable { @@ -407,7 +427,8 @@ macro_rules! animator_impl { /// Stop animation playback and rewind the animation. /// - /// This changes the animator state to [`AnimatorState::Paused`] and rewind its tweenable. + /// This changes the animator state to [`AnimatorState::Paused`] and rewind its + /// tweenable. pub fn stop(&mut self) { self.state = AnimatorState::Paused; self.rewind(); diff --git a/src/plugin.rs b/src/plugin.rs index 10f0c07..70cbe3e 100644 --- a/src/plugin.rs +++ b/src/plugin.rs @@ -4,24 +4,26 @@ use crate::{Animator, AnimatorState, AssetAnimator, TweenCompleted}; /// Plugin to add systems related to tweening of common components and assets. /// -/// This plugin adds systems for a predefined set of components and assets, to allow their -/// respective animators to be updated each frame: +/// This plugin adds systems for a predefined set of components and assets, to +/// allow their respective animators to be updated each frame: /// - [`Transform`] /// - [`Text`] /// - [`Style`] /// - [`Sprite`] /// - [`ColorMaterial`] /// -/// This ensures that all predefined lenses work as intended, as well as any custom lens -/// animating the same component or asset type. +/// This ensures that all predefined lenses work as intended, as well as any +/// custom lens animating the same component or asset type. /// -/// For other components and assets, including custom ones, the relevant system needs to be -/// added manually by the application: -/// - For components, add [`component_animator_system::<T>`] where `T: Component` +/// For other components and assets, including custom ones, the relevant system +/// needs to be added manually by the application: +/// - For components, add [`component_animator_system::<T>`] where `T: +/// Component` /// - For assets, add [`asset_animator_system::<T>`] where `T: Asset` /// -/// This plugin is entirely optional. If you want more control, you can instead add manually -/// the relevant systems for the exact set of components and assets actually animated. +/// This plugin is entirely optional. If you want more control, you can instead +/// add manually the relevant systems for the exact set of components and assets +/// actually animated. /// /// [`Transform`]: https://docs.rs/bevy/0.7.0/bevy/transform/components/struct.Transform.html /// [`Text`]: https://docs.rs/bevy/0.7.0/bevy/text/struct.Text.html @@ -58,8 +60,8 @@ pub enum AnimationSystem { /// Animator system for components. /// -/// This system extracts all components of type `T` with an `Animator<T>` attached to the same entity, -/// and tick the animator to animate the component. +/// This system extracts all components of type `T` with an `Animator<T>` +/// attached to the same entity, and tick the animator to animate the component. pub fn component_animator_system<T: Component>( time: Res<Time>, mut query: Query<(Entity, &mut T, &mut Animator<T>)>, @@ -74,7 +76,8 @@ pub fn component_animator_system<T: Component>( /// Animator system for assets. /// -/// This system ticks all `AssetAnimator<T>` components to animate their associated asset. +/// This system ticks all `AssetAnimator<T>` components to animate their +/// associated asset. pub fn asset_animator_system<T: Asset>( time: Res<Time>, mut assets: ResMut<Assets<T>>, diff --git a/src/tweenable.rs b/src/tweenable.rs index 2169709..af38123 100644 --- a/src/tweenable.rs +++ b/src/tweenable.rs @@ -6,8 +6,8 @@ use crate::{EaseMethod, Lens, TweeningDirection, TweeningType}; /// The dynamic tweenable type. /// -/// When creating lists of tweenables, you will need to box them to create a homogeneous -/// array like so: +/// When creating lists of tweenables, you will need to box them to create a +/// homogeneous array like so: /// ```no_run /// # use bevy::prelude::Transform; /// # use bevy_tweening::{BoxedTweenable, Delay, Sequence, Tween}; @@ -18,7 +18,8 @@ use crate::{EaseMethod, Lens, TweeningDirection, TweeningType}; /// Sequence::new([Box::new(delay) as BoxedTweenable<Transform>, tween.into()]); /// ``` /// -/// When using your own [`Tweenable`] types, APIs will be easier to use if you implement [`From`]: +/// When using your own [`Tweenable`] types, APIs will be easier to use if you +/// implement [`From`]: /// ```no_run /// # use std::time::Duration; /// # use bevy::prelude::{Entity, EventWriter, Transform}; @@ -51,36 +52,44 @@ pub type BoxedTweenable<T> = Box<dyn Tweenable<T> + Send + Sync + 'static>; /// Playback state of a [`Tweenable`]. /// -/// This is returned by [`Tweenable::tick()`] to allow the caller to execute some logic based on the -/// updated state of the tweenable, like advanding a sequence to its next child tweenable. +/// This is returned by [`Tweenable::tick()`] to allow the caller to execute +/// some logic based on the updated state of the tweenable, like advanding a +/// sequence to its next child tweenable. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TweenState { /// The tweenable is still active, and did not reach its end state yet. Active, - /// Animation reached its end state. The tweenable is idling at its latest time. This can only happen - /// for [`TweeningType::Once`], since other types loop indefinitely. + /// Animation reached its end state. The tweenable is idling at its latest + /// time. This can only happen for [`TweeningType::Once`], since other + /// types loop indefinitely. Completed, } /// Event raised when a tween completed. /// -/// This event is raised when a tween completed. For non-looping tweens, this is raised once at the -/// end of the animation. For looping animations, this is raised once per iteration. In case the animation -/// direction changes ([`TweeningType::PingPong`]), an iteration corresponds to a single progress from -/// one endpoint to the other, whatever the direction. Therefore a complete cycle start -> end -> start -/// counts as 2 iterations and raises 2 events (one when reaching the end, one when reaching back the start). +/// This event is raised when a tween completed. For non-looping tweens, this is +/// raised once at the end of the animation. For looping animations, this is +/// raised once per iteration. In case the animation direction changes +/// ([`TweeningType::PingPong`]), an iteration corresponds to a single progress +/// from one endpoint to the other, whatever the direction. Therefore a complete +/// cycle start -> end -> start counts as 2 iterations and raises 2 events (one +/// when reaching the end, one when reaching back the start). /// /// # Note /// -/// The semantic is slightly different from [`TweenState::Completed`], which indicates that the tweenable -/// has finished ticking and do not need to be updated anymore, a state which is never reached for looping -/// animation. Here the [`TweenCompleted`] event instead marks the end of a single loop iteration. +/// The semantic is slightly different from [`TweenState::Completed`], which +/// indicates that the tweenable has finished ticking and do not need to be +/// updated anymore, a state which is never reached for looping animation. Here +/// the [`TweenCompleted`] event instead marks the end of a single loop +/// iteration. #[derive(Copy, Clone)] pub struct TweenCompleted { - /// The [`Entity`] the tween which completed and its animator are attached to. + /// The [`Entity`] the tween which completed and its animator are attached + /// to. pub entity: Entity, - /// An opaque value set by the user when activating event raising, used to identify the particular - /// tween which raised this event. The value is passed unmodified from a call to [`with_completed_event()`] + /// An opaque value set by the user when activating event raising, used to + /// identify the particular tween which raised this event. The value is + /// passed unmodified from a call to [`with_completed_event()`] /// or [`set_completed_event()`]. /// /// [`with_completed_event()`]: Tween::with_completed_event @@ -148,18 +157,20 @@ impl AnimClock { pub trait Tweenable<T>: Send + Sync { /// Get the total duration of the animation. /// - /// For non-looping tweenables ([`TweeningType::Once`]), this is the total animation duration. - /// For looping ones, this is the duration of a single iteration, since the total animation - /// duration is infinite. + /// For non-looping tweenables ([`TweeningType::Once`]), this is the total + /// animation duration. For looping ones, this is the duration of a + /// single iteration, since the total animation duration is infinite. /// - /// Note that for [`TweeningType::PingPong`], this is the duration of a single way, either from - /// start to end or back from end to start. The total "loop" duration start -> end -> start to - /// reach back the same state in this case is the double of the returned value. + /// Note that for [`TweeningType::PingPong`], this is the duration of a + /// single way, either from start to end or back from end to start. The + /// total "loop" duration start -> end -> start to reach back the same + /// state in this case is the double of the returned value. fn duration(&self) -> Duration; /// Return `true` if the animation is looping. /// - /// Looping tweenables are of type [`TweeningType::Loop`] or [`TweeningType::PingPong`]. + /// Looping tweenables are of type [`TweeningType::Loop`] or + /// [`TweeningType::PingPong`]. fn is_looping(&self) -> bool; /// Set the current animation playback progress. @@ -169,27 +180,35 @@ pub trait Tweenable<T>: Send + Sync { /// [`progress()`]: Tweenable::progress fn set_progress(&mut self, progress: f32); - /// Get the current progress in \[0:1\] (non-looping) or \[0:1\[ (looping) of the animation. + /// Get the current progress in \[0:1\] (non-looping) or \[0:1\[ (looping) + /// of the animation. /// - /// For looping animations, this reports the progress of the current iteration, in the current - /// direction: - /// - [`TweeningType::Loop`] is `0` at start and `1` at end. The exact value `1.0` is never reached, - /// since the tweenable loops over to `0.0` immediately. - /// - [`TweeningType::PingPong`] is `0` at the source endpoint and `1` and the destination one, - /// which are respectively the start/end for [`TweeningDirection::Forward`], or the end/start - /// for [`TweeningDirection::Backward`]. The exact value `1.0` is never reached, since the tweenable - /// loops over to `0.0` immediately when it changes direction at either endpoint. + /// For looping animations, this reports the progress of the current + /// iteration, in the current direction: + /// - [`TweeningType::Loop`] is `0` at start and `1` at end. The exact value + /// `1.0` is never reached, since the tweenable loops over to `0.0` + /// immediately. + /// - [`TweeningType::PingPong`] is `0` at the source endpoint and `1` and + /// the destination one, which are respectively the start/end for + /// [`TweeningDirection::Forward`], or the end/start for + /// [`TweeningDirection::Backward`]. The exact value `1.0` is never + /// reached, since the tweenable loops over to `0.0` immediately when it + /// changes direction at either endpoint. fn progress(&self) -> f32; - /// Tick the animation, advancing it by the given delta time and mutating the given target component or asset. + /// Tick the animation, advancing it by the given delta time and mutating + /// the given target component or asset. /// - /// This returns [`TweenState::Active`] if the tweenable didn't reach its final state yet (progress < `1.0`), - /// or [`TweenState::Completed`] if the tweenable completed this tick. Only non-looping tweenables return + /// This returns [`TweenState::Active`] if the tweenable didn't reach its + /// final state yet (progress < `1.0`), or [`TweenState::Completed`] if + /// the tweenable completed this tick. Only non-looping tweenables return /// a completed state, since looping ones continue forever. /// - /// Calling this method with a duration of [`Duration::ZERO`] is valid, and updates the target to the current - /// state of the tweenable without actually modifying the tweenable state. This is useful after certain operations - /// like [`rewind()`] or [`set_progress()`] whose effect is otherwise only visible on target on next frame. + /// Calling this method with a duration of [`Duration::ZERO`] is valid, and + /// updates the target to the current state of the tweenable without + /// actually modifying the tweenable state. This is useful after certain + /// operations like [`rewind()`] or [`set_progress()`] whose effect is + /// otherwise only visible on target on next frame. /// /// [`rewind()`]: Tweenable::rewind /// [`set_progress()`]: Tweenable::set_progress @@ -203,15 +222,18 @@ pub trait Tweenable<T>: Send + Sync { /// Get the number of times this tweenable completed. /// - /// For looping animations, this returns the number of times a single playback was completed. In the - /// case of [`TweeningType::PingPong`] this corresponds to a playback in a single direction, so tweening - /// from start to end and back to start counts as two completed times (one forward, one backward). + /// For looping animations, this returns the number of times a single + /// playback was completed. In the case of [`TweeningType::PingPong`] + /// this corresponds to a playback in a single direction, so tweening + /// from start to end and back to start counts as two completed times (one + /// forward, one backward). fn times_completed(&self) -> u32; /// Rewind the animation to its starting state. /// - /// Note that the starting state depends on the current direction. For [`TweeningDirection::Forward`] - /// this is the start point of the lens, whereas for [`TweeningDirection::Backward`] this is the end one. + /// Note that the starting state depends on the current direction. For + /// [`TweeningDirection::Forward`] this is the start point of the lens, + /// whereas for [`TweeningDirection::Backward`] this is the end one. fn rewind(&mut self); } @@ -257,7 +279,8 @@ pub struct Tween<T> { } impl<T: 'static> Tween<T> { - /// Chain another [`Tweenable`] after this tween, making a [`Sequence`] with the two. + /// Chain another [`Tweenable`] after this tween, making a [`Sequence`] with + /// the two. /// /// # Example /// ``` @@ -332,8 +355,9 @@ impl<T> Tween<T> { /// Enable or disable raising a completed event. /// - /// If enabled, the tween will raise a [`TweenCompleted`] event when the animation completed. - /// This is similar to the [`set_completed()`] callback, but uses Bevy events instead. + /// If enabled, the tween will raise a [`TweenCompleted`] event when the + /// animation completed. This is similar to the [`set_completed()`] + /// callback, but uses Bevy events instead. /// /// # Example /// ``` @@ -369,15 +393,17 @@ impl<T> Tween<T> { /// Set the playback direction of the tween. /// - /// The playback direction influences the mapping of the progress ratio (in \[0:1\]) to the - /// actual ratio passed to the lens. [`TweeningDirection::Forward`] maps the `0` value of - /// progress to the `0` value of the lens ratio. Conversely, [`TweeningDirection::Backward`] - /// reverses the mapping, which effectively makes the tween play reversed, going from end to - /// start. + /// The playback direction influences the mapping of the progress ratio (in + /// \[0:1\]) to the actual ratio passed to the lens. + /// [`TweeningDirection::Forward`] maps the `0` value of progress to the + /// `0` value of the lens ratio. Conversely, [`TweeningDirection::Backward`] + /// reverses the mapping, which effectively makes the tween play reversed, + /// going from end to start. /// - /// Changing the direction doesn't change any target state, nor any progress of the tween. Only - /// the direction of animation from this moment potentially changes. To force a target state - /// change, call [`Tweenable::tick()`] with a zero delta (`Duration::ZERO`). + /// Changing the direction doesn't change any target state, nor any progress + /// of the tween. Only the direction of animation from this moment + /// potentially changes. To force a target state change, call + /// [`Tweenable::tick()`] with a zero delta (`Duration::ZERO`). pub fn set_direction(&mut self, direction: TweeningDirection) { self.direction = direction; } @@ -401,8 +427,9 @@ impl<T> Tween<T> { /// Set a callback invoked when the animation completed. /// - /// The callback when invoked receives as parameters the [`Entity`] on which the target and the - /// animator are, as well as a reference to the current [`Tween`]. + /// The callback when invoked receives as parameters the [`Entity`] on which + /// the target and the animator are, as well as a reference to the + /// current [`Tween`]. /// /// Only non-looping tweenables can complete. pub fn set_completed<C>(&mut self, callback: C) @@ -419,8 +446,9 @@ impl<T> Tween<T> { /// Enable or disable raising a completed event. /// - /// If enabled, the tween will raise a [`TweenCompleted`] event when the animation completed. - /// This is similar to the [`set_completed()`] callback, but uses Bevy events instead. + /// If enabled, the tween will raise a [`TweenCompleted`] event when the + /// animation completed. This is similar to the [`set_completed()`] + /// callback, but uses Bevy events instead. /// /// See [`with_completed_event()`] for details. /// @@ -472,7 +500,8 @@ impl<T> Tweenable<T> for Tween<T> { }; let progress = self.clock.progress(); - // Apply the lens, even if the animation finished, to ensure the state is consistent + // Apply the lens, even if the animation finished, to ensure the state is + // consistent let mut factor = progress; if self.direction.is_backward() { factor = 1. - factor; @@ -674,7 +703,8 @@ pub struct Tracks<T> { } impl<T> Tracks<T> { - /// Create a new [`Tracks`] from an iterator over a collection of [`Tweenable`]. + /// Create a new [`Tracks`] from an iterator over a collection of + /// [`Tweenable`]. #[must_use] pub fn new(items: impl IntoIterator<Item = impl Into<BoxedTweenable<T>>>) -> Self { let tracks: Vec<_> = items.into_iter().map(Into::into).collect(); @@ -753,9 +783,10 @@ impl<T> Tweenable<T> for Tracks<T> { /// A time delay that doesn't animate anything. /// -/// This is generally useful for combining with other tweenables into sequences and tracks, -/// for example to delay the start of a tween in a track relative to another track. The `menu` -/// example (`examples/menu.rs`) uses this technique to delay the animation of its buttons. +/// This is generally useful for combining with other tweenables into sequences +/// and tracks, for example to delay the start of a tween in a track relative to +/// another track. The `menu` example (`examples/menu.rs`) uses this technique +/// to delay the animation of its buttons. pub struct Delay { timer: Timer, } @@ -769,7 +800,8 @@ impl Delay { } } - /// Chain another [`Tweenable`] after this tween, making a sequence with the two. + /// Chain another [`Tweenable`] after this tween, making a sequence with the + /// two. #[must_use] pub fn then<T>(self, tween: impl Tweenable<T> + Send + Sync + 'static) -> Sequence<T> { Sequence::with_capacity(2).then(self).then(tween) @@ -829,8 +861,10 @@ impl<T> Tweenable<T> for Delay { #[cfg(test)] mod tests { - use std::sync::{Arc, Mutex}; - use std::time::Duration; + use std::{ + sync::{Arc, Mutex}, + time::Duration, + }; use bevy::ecs::{event::Events, system::SystemState}; -- GitLab