1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
use std::time::Duration;

use bevy_app_07::prelude::*;
use bevy_asset_07::prelude::*;
#[cfg(feature = "load-from-file")]
use bevy_asset_07::{AssetLoader, BoxedFuture, LoadContext, LoadedAsset};
use bevy_core_07::prelude::*;
use bevy_ecs_07::{
    component::{SparseStorage, TableStorage},
    prelude::*,
    system::Resource,
};
use bevy_reflect_07::{TypeUuid, Uuid};
use bevy_sprite_07::prelude::*;

use crate::{Play, PlaySpeedMultiplier, SpriteSheetAnimation, SpriteSheetAnimationState};

impl Component for Play {
    type Storage = SparseStorage;
}

impl Component for PlaySpeedMultiplier {
    type Storage = SparseStorage;
}

impl Component for SpriteSheetAnimationState {
    type Storage = TableStorage;
}

trait TimeResource: Resource {
    fn delta_time(&self) -> Duration;
}

impl TimeResource for Time {
    fn delta_time(&self) -> Duration {
        self.delta()
    }
}

impl Plugin for crate::AnimationPlugin {
    fn build(&self, app: &mut App) {
        install::<Time>(app);
    }
}

fn install<T: TimeResource>(app: &mut App) {
    app.add_asset::<SpriteSheetAnimation>()
        .add_system_set_to_stage(CoreStage::PreUpdate, auto_insert_state())
        .add_system_to_stage(CoreStage::Update, animate::<T>);

    #[cfg(feature = "load-from-file")]
    app.init_asset_loader::<crate::animation::load::SpriteSheetAnimationLoader>();
}

/// Systems to automatically insert (and remove) the state component
fn auto_insert_state() -> SystemSet {
    SystemSet::new()
        .with_system(insert_state)
        .with_system(remove_state)
}

fn insert_state(
    mut commands: Commands<'_, '_>,
    query: Query<
        '_,
        '_,
        Entity,
        (
            With<Handle<SpriteSheetAnimation>>,
            Without<SpriteSheetAnimationState>,
        ),
    >,
) {
    for entity in query.iter() {
        commands
            .entity(entity)
            .insert(SpriteSheetAnimationState::default());
    }
}

fn remove_state(
    mut commands: Commands<'_, '_>,
    removed: RemovedComponents<'_, Handle<SpriteSheetAnimation>>,
) {
    for entity in removed.iter() {
        commands
            .entity(entity)
            .remove::<SpriteSheetAnimationState>();
    }
}

type AnimationSystemQuery<'a> = (
    Entity,
    &'a mut TextureAtlasSprite,
    &'a Handle<SpriteSheetAnimation>,
    &'a mut SpriteSheetAnimationState,
    Option<&'a PlaySpeedMultiplier>,
);

fn animate<T: TimeResource>(
    mut commands: Commands<'_, '_>,
    time: Res<'_, T>,
    animation_defs: Res<'_, Assets<SpriteSheetAnimation>>,
    mut animations: Query<'_, '_, AnimationSystemQuery<'_>, With<Play>>,
) {
    for (entity, mut sprite, animation, mut state, speed_multiplier) in
        animations.iter_mut().filter_map(
            |(entity, sprite, anim_handle, state, optional_speed_multiplier)| {
                animation_defs
                    .get(anim_handle)
                    .filter(|anim| anim.has_frames())
                    .map(|anim| (entity, sprite, anim, state, optional_speed_multiplier))
            },
        )
    {
        let delta = speed_multiplier
            .copied()
            .unwrap_or_default()
            .transform(time.delta_time());

        state.update(animation, delta);
        sprite.index = state.sprite_frame_index();
        if state.is_ended() {
            commands.entity(entity).remove::<Play>();
        }
    }
}

impl TypeUuid for SpriteSheetAnimation {
    const TYPE_UUID: Uuid = Uuid::from_bytes([
        0x63, 0x78, 0xe9, 0xc2, 0xec, 0xd1, 0x40, 0x29, 0x9c, 0xd5, 0x80, 0x1c, 0xaf, 0x68, 0x51,
        0x7c,
    ]);
}

#[cfg(feature = "load-from-file")]
impl AssetLoader for crate::animation::load::SpriteSheetAnimationLoader {
    fn load<'a>(
        &'a self,
        bytes: &'a [u8],
        load_context: &'a mut LoadContext<'_>,
    ) -> BoxedFuture<'a, Result<(), anyhow::Error>> {
        Box::pin(async move {
            let custom_asset = self.load(
                load_context.path().extension().unwrap().to_str().unwrap(),
                bytes,
            )?;
            load_context.set_default_asset(LoadedAsset::new(custom_asset));
            Ok(())
        })
    }

    fn extensions(&self) -> &[&str] {
        self.supported_extensions()
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use bevy_asset_07::AssetPlugin;
    use bevy_core_07::CorePlugin;

    use super::*;

    #[rstest]
    fn updates_sprite_atlas(mut app: App) {
        set_delta_time_per_update(&mut app, Duration::from_secs(1));
        let animation = add_animation(
            &mut app,
            SpriteSheetAnimation::from_range(0..=2, Duration::from_secs(1)),
        );
        let entity = spawn(&mut app, (TextureAtlasSprite::new(0), animation, Play));

        app.update();

        assert_eq!(
            app.world.get::<TextureAtlasSprite>(entity).unwrap().index,
            1
        );
    }

    #[rstest]
    fn does_not_update_without_play_component(mut app: App) {
        set_delta_time_per_update(&mut app, Duration::from_secs(1));
        let animation = add_animation(
            &mut app,
            SpriteSheetAnimation::from_range(0..=2, Duration::from_secs(1)),
        );
        let entity = spawn(&mut app, (TextureAtlasSprite::new(0), animation));

        app.update();

        assert_eq!(
            app.world.get::<TextureAtlasSprite>(entity).unwrap().index,
            0
        );
    }

    #[rstest]
    fn removes_play_at_end_of_animation(mut app: App) {
        set_delta_time_per_update(&mut app, Duration::from_secs(2));
        let animation = add_animation(
            &mut app,
            SpriteSheetAnimation::from_range(0..=1, Duration::from_secs(1)).once(),
        );
        let entity = spawn(&mut app, (TextureAtlasSprite::new(0), animation, Play));

        app.update();

        assert!(app.world.get::<Play>(entity).is_none());
    }

    #[rstest]
    fn speed_is_affected_by_playbackspeed_component(mut app: App) {
        set_delta_time_per_update(&mut app, Duration::from_secs(1));
        let animation = add_animation(
            &mut app,
            SpriteSheetAnimation::from_range(0..=3, Duration::from_secs(1)).once(),
        );
        let entity = spawn(
            &mut app,
            (
                TextureAtlasSprite::new(0),
                animation,
                Play,
                PlaySpeedMultiplier::from(2.0),
            ),
        );

        app.update();

        assert_eq!(
            app.world.get::<TextureAtlasSprite>(entity).unwrap().index,
            2
        );
    }

    #[cfg(all(feature = "load-from-file", feature = "yaml"))]
    #[rstest]
    fn load_asset_file(mut app: App) {
        let handle: Handle<SpriteSheetAnimation> = app
            .world
            .resource::<AssetServer>()
            .load("coin.animation.yml");

        app.update();
        let mut loops = 0;
        while !matches!(
            app.world.resource::<AssetServer>().get_load_state(&handle),
            bevy_asset_07::LoadState::Loaded
        ) {
            assert!(loops < 100);
            loops += 1;
            std::thread::sleep(Duration::from_millis(50));
            app.update();
        }
        assert_eq!(
            app.world.resource::<AssetServer>().get_load_state(&handle),
            bevy_asset_07::LoadState::Loaded
        );
        assert!(app
            .world
            .resource::<Assets<SpriteSheetAnimation>>()
            .get(&handle)
            .is_some());
    }

    #[fixture]
    fn app() -> App {
        let mut app = App::new();
        app.add_plugin(CorePlugin).add_plugin(AssetPlugin);
        app.world.insert_resource(Duration::ZERO);
        install::<Duration>(&mut app);
        app
    }

    fn set_delta_time_per_update(app: &mut App, delta: Duration) {
        app.world.insert_resource(delta);
    }

    fn spawn(app: &mut App, bundle: impl Bundle) -> Entity {
        app.world.spawn().insert_bundle(bundle).id()
    }

    fn add_animation(
        app: &mut App,
        animation: SpriteSheetAnimation,
    ) -> Handle<SpriteSheetAnimation> {
        app.world
            .resource_mut::<Assets<SpriteSheetAnimation>>()
            .add(animation)
    }

    impl TimeResource for Duration {
        fn delta_time(&self) -> Duration {
            *self
        }
    }
}