bevy_tnua/animating_helper.rs
1use std::marker::PhantomData;
2use std::mem::discriminant;
3
4use bevy::prelude::*;
5
6/// Utility for deciding which animation to play.
7///
8/// Add `TnuaAnimatingState<State>` as a component, where `State` is a data type - usually an
9/// `enum` - that determines which animation to play. Each frame, decide (with the help of
10/// [`TnuaController`](crate::prelude::TnuaController)) which animation should
11/// be played and the animation's parameters (like speed) and feed it to the `TnuaAnimatingState`.
12/// Use the emitted [`TnuaAnimatingStateDirective`] to determine if this is a new animation or an
13/// existing one (possibly with different parameters), and use that information to work the actual
14/// animation player.
15///
16/// ```
17/// # use bevy::prelude::*;
18/// # use bevy_tnua::prelude::*;
19/// # use bevy_tnua::{TnuaAnimatingState, TnuaAnimatingStateDirective};
20/// # use bevy_tnua::math::Float;
21/// # #[derive(Resource)]
22/// # struct AnimationNodes {
23/// # standing: AnimationNodeIndex,
24/// # running: AnimationNodeIndex,
25/// # }
26/// # #[derive(bevy_tnua::TnuaScheme)] #[scheme(basis = bevy_tnua::builtins::TnuaBuiltinWalk)] enum ControlScheme {}
27/// enum AnimationState {
28/// Standing,
29/// Running(Float),
30/// }
31///
32/// fn animating_system(
33/// mut query: &mut Query<(
34/// &mut TnuaAnimatingState<AnimationState>,
35/// &TnuaController<ControlScheme>,
36/// &mut AnimationPlayer,
37/// )>,
38/// animation_nodes: Res<AnimationNodes>,
39/// ) {
40/// for (mut animating_state, controller, mut animation_player) in query.iter_mut() {
41/// match animating_state.update_by_discriminant({
42/// let speed = controller.basis_memory.running_velocity.length();
43/// if 0.01 < speed {
44/// AnimationState::Running(speed)
45/// } else {
46/// AnimationState::Standing
47/// }
48/// }) {
49/// TnuaAnimatingStateDirective::Maintain { state } => {
50/// if let AnimationState::Running(speed) = state {
51/// if let Some(active_animation) = animation_player.animation_mut(animation_nodes.running) {
52/// active_animation.set_speed(*speed);
53/// }
54/// }
55/// }
56/// TnuaAnimatingStateDirective::Alter {
57/// // We don't need the old state here, but it's available for transition
58/// // animations.
59/// old_state: _,
60/// state,
61/// } => {
62/// animation_player.stop_all();
63/// match state {
64/// AnimationState::Standing => {
65/// animation_player
66/// .start(animation_nodes.standing)
67/// .set_speed(1.0)
68/// .repeat();
69/// }
70/// AnimationState::Running(speed) => {
71/// animation_player
72/// .start(animation_nodes.running)
73/// .set_speed(*speed)
74/// .repeat();
75/// }
76/// }
77/// }
78/// }
79/// }
80/// }
81/// ```
82#[derive(Component, Reflect)]
83pub struct TnuaAnimatingState<State> {
84 state: Option<State>,
85}
86
87impl<State> Default for TnuaAnimatingState<State> {
88 fn default() -> Self {
89 Self { state: None }
90 }
91}
92
93impl<State> FromTemplate for TnuaAnimatingState<State> {
94 type Template = TnuaAnimatingStateTemplate<State>;
95}
96
97pub struct TnuaAnimatingStateTemplate<State> {
98 _phantom: PhantomData<State>,
99}
100
101impl<State> Template for TnuaAnimatingStateTemplate<State> {
102 type Output = TnuaAnimatingState<State>;
103
104 fn build_template(&self, _: &mut bevy::ecs::template::TemplateContext) -> Result<Self::Output> {
105 Ok(TnuaAnimatingState::default())
106 }
107
108 fn clone_template(&self) -> Self {
109 Self {
110 _phantom: PhantomData,
111 }
112 }
113}
114
115impl<State> Default for TnuaAnimatingStateTemplate<State> {
116 fn default() -> Self {
117 Self {
118 _phantom: PhantomData,
119 }
120 }
121}
122
123pub enum TnuaAnimatingStateDirective<'a, State> {
124 /// The animation to play remains the same - possibly with different parameters.
125 Maintain { state: &'a State },
126 /// A different animation needs to be played.
127 ///
128 /// Also returned (with `old_state: None`) if this is the first animation to be played.
129 Alter {
130 old_state: Option<State>,
131 state: &'a State,
132 },
133}
134
135impl<State> TnuaAnimatingState<State> {
136 /// Consider a new animation to play.
137 ///
138 /// The comparison function decides if its the same animation (possibly with different
139 /// parameters) or a different animation.
140 pub fn update_by(
141 &'_ mut self,
142 new_state: State,
143 comparison: impl FnOnce(&State, &State) -> bool,
144 ) -> TnuaAnimatingStateDirective<'_, State> {
145 let is_same = self
146 .state
147 .as_ref()
148 .is_some_and(|old_state| comparison(old_state, &new_state));
149 let old_state = self.state.replace(new_state);
150 if is_same {
151 TnuaAnimatingStateDirective::Maintain {
152 state: self.state.as_ref().expect("state was just placed there"),
153 }
154 } else {
155 TnuaAnimatingStateDirective::Alter {
156 old_state,
157 state: self.state.as_ref().expect("state was just placed there"),
158 }
159 }
160 }
161
162 /// Consider a new animation to play.
163 ///
164 /// The new animation is considered the same if and only if it is equal to the old animation.
165 pub fn update_by_value(&'_ mut self, new_state: State) -> TnuaAnimatingStateDirective<'_, State>
166 where
167 State: PartialEq,
168 {
169 self.update_by(new_state, |a, b| a == b)
170 }
171
172 /// Consider a new animation to play.
173 ///
174 /// The new animation is considered the same if it is the same variant of the enum as the old
175 /// animation.
176 ///
177 /// If the `State` is not an `enum`, using this method will not result in undefined behavior,
178 /// but the behavior is unspecified.
179 pub fn update_by_discriminant(
180 &'_ mut self,
181 new_state: State,
182 ) -> TnuaAnimatingStateDirective<'_, State> {
183 self.update_by(new_state, |a, b| discriminant(a) == discriminant(b))
184 }
185
186 /// Get the current state.
187 ///
188 /// Can provide no information about the previous state.
189 pub fn get(&self) -> Option<&State> {
190 self.state.as_ref()
191 }
192}