Skip to main content

wde_animation/
player.rs

1use bevy::prelude::*;
2
3use crate::clip::AnimationClip;
4
5/// Rigid part of an animated model, posed by the [`AnimationPlayer`] of its closest ancestor.
6#[derive(Component, Clone, Debug, Reflect)]
7#[reflect(Component)]
8pub struct AnimationBone {
9    pub name: String,
10    /// Local transform when no clip animates the bone.
11    pub rest: Transform
12}
13
14/// Player animating a bone.
15#[derive(Component, Reflect)]
16#[reflect(Component)]
17pub(crate) struct BoneOf(Entity);
18
19/// A clip being played.
20#[derive(Clone, Debug, Reflect)]
21struct PlayingClip {
22    clip: Handle<AnimationClip>,
23    time: f32,
24    speed: f32,
25    /// Loops, or stops on its last pose.
26    repeat: bool,
27    finished: bool
28}
29impl PlayingClip {
30    fn new(clip: Handle<AnimationClip>, speed: f32, repeat: bool) -> Self {
31        Self {
32            clip,
33            time: 0.0,
34            speed,
35            repeat,
36            finished: false
37        }
38    }
39}
40
41/// Plays clips (looping, or once) on the [`AnimationBone`]s below its entity, blending smoothly
42/// from one clip to the next.
43#[derive(Component, Clone, Debug, Default, Reflect)]
44#[reflect(Component)]
45pub struct AnimationPlayer {
46    active: Option<PlayingClip>,
47    /// Previous clip, fading out.
48    #[reflect(ignore)]
49    previous: Option<PlayingClip>,
50    #[reflect(ignore)]
51    fade: f32,
52    #[reflect(ignore)]
53    fade_duration: f32
54}
55impl AnimationPlayer {
56    /// Plays `clip` right away, from its start.
57    pub fn play(&mut self, clip: Handle<AnimationClip>) -> &mut Self {
58        self.active = Some(PlayingClip::new(clip, 1.0, true));
59        self.previous = None;
60        self
61    }
62
63    /// Blends to `clip` over `fade` seconds and plays it once, from its start (even if it is
64    /// already playing), holding its last pose. See [`Self::is_finished`].
65    pub fn play_once(&mut self, clip: Handle<AnimationClip>, fade: f32) -> &mut Self {
66        self.previous = self.active.take();
67        self.active = Some(PlayingClip::new(clip, 1.0, false));
68        self.fade = 0.0;
69        self.fade_duration = fade;
70        self
71    }
72
73    /// Whether the clip played once is over.
74    pub fn is_finished(&self) -> bool {
75        self.active.as_ref().is_some_and(|a| a.finished)
76    }
77
78    /// Blends from the current clip to `clip` over `duration` seconds. Keeps playing if `clip`
79    /// is already the active clip.
80    pub fn crossfade(&mut self, clip: Handle<AnimationClip>, duration: f32) -> &mut Self {
81        if self.is_playing(&clip) {
82            return self;
83        }
84        let speed = self.active.as_ref().map_or(1.0, |a| a.speed);
85        self.previous = self.active.take();
86        self.active = Some(PlayingClip::new(clip, speed, true));
87        self.fade = 0.0;
88        self.fade_duration = duration;
89        self
90    }
91
92    /// Playback speed of the active clip (1 = authored speed).
93    pub fn set_speed(&mut self, speed: f32) -> &mut Self {
94        if let Some(active) = &mut self.active {
95            active.speed = speed;
96        }
97        self
98    }
99
100    /// Stops animating: the bones go back to their rest pose.
101    pub fn stop(&mut self) {
102        self.active = None;
103        self.previous = None;
104    }
105
106    pub fn is_playing(&self, clip: &Handle<AnimationClip>) -> bool {
107        self.active.as_ref().is_some_and(|a| a.clip == *clip)
108    }
109
110    /// Weight of the active clip against the previous one.
111    fn blend(&self) -> f32 {
112        match self.previous {
113            Some(_) => (self.fade / self.fade_duration.max(f32::EPSILON)).min(1.0),
114            None => 1.0
115        }
116    }
117}
118
119/// Links new bones to the player of their closest ancestor.
120pub(crate) fn link_bones(
121    mut commands: Commands,
122    bones: Query<Entity, (With<AnimationBone>, Without<BoneOf>)>,
123    parents: Query<&ChildOf>,
124    players: Query<(), With<AnimationPlayer>>
125) {
126    for bone in &bones {
127        if let Some(player) = parents.iter_ancestors(bone).find(|e| players.contains(*e)) {
128            commands.entity(bone).try_insert(BoneOf(player));
129        }
130    }
131}
132
133pub(crate) fn advance_players(
134    mut players: Query<&mut AnimationPlayer>,
135    clips: Res<Assets<AnimationClip>>,
136    time: Res<Time>
137) {
138    let dt = time.delta_secs();
139    for mut player in &mut players {
140        let player = player.as_mut();
141        for playing in [&mut player.active, &mut player.previous]
142            .into_iter()
143            .flatten()
144        {
145            let duration = clips.get(&playing.clip).map_or(0.0, |c| c.duration);
146            if duration <= 0.0 {
147                playing.time = 0.0;
148            } else if playing.repeat {
149                playing.time = (playing.time + dt * playing.speed).rem_euclid(duration);
150            } else {
151                playing.time = (playing.time + dt * playing.speed).min(duration);
152                playing.finished = playing.time >= duration;
153            }
154        }
155        if player.previous.is_some() {
156            player.fade += dt;
157            if player.fade >= player.fade_duration {
158                player.previous = None;
159            }
160        }
161    }
162}
163
164pub(crate) fn pose_bones(
165    mut bones: Query<(&AnimationBone, &BoneOf, &mut Transform)>,
166    players: Query<&AnimationPlayer>,
167    clips: Res<Assets<AnimationClip>>
168) {
169    for (bone, bone_of, mut transform) in &mut bones {
170        let Ok(player) = players.get(bone_of.0) else {
171            continue;
172        };
173        let pose = |playing: &Option<PlayingClip>| {
174            playing.as_ref().map(|p| {
175                clips
176                    .get(&p.clip)
177                    .and_then(|c| c.tracks.get(&bone.name))
178                    .map_or(bone.rest, |track| track.sample(p.time, &bone.rest))
179            })
180        };
181        let active = pose(&player.active).unwrap_or(bone.rest);
182        let posed = match pose(&player.previous) {
183            Some(previous) => {
184                let t = player.blend();
185                Transform {
186                    translation: previous.translation.lerp(active.translation, t),
187                    rotation: previous.rotation.slerp(active.rotation, t),
188                    scale: previous.scale.lerp(active.scale, t)
189                }
190            }
191            None => active
192        };
193        transform.set_if_neq(posed);
194    }
195}