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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
use std::{
    collections::HashMap,
    sync::{Arc, Mutex},
    time::Duration,
};

use bevy::prelude::*;

mod animations;
mod plugins;
mod types;

pub use animations::*;
pub use plugins::*;
pub use types::*;

pub mod prelude {
    pub use crate::animations::{
        LinearTimedAnimation, LinearTransformAnimation, SingleFrameAnimation, TimedAnimation,
        TransformAnimation,
    };
    pub use crate::plugins::AnimationsPlugin;
    pub use crate::types::{
        Animation, AnimationDirection, AnimationDirectionIndexes, AnimationEvent, AnimationName,
        AnimationType, Animator, FXAnimationEvent, FXBasedDirection, FlipBasedDirection,
        IndexBasedDirection, NewAnimation, ResetAnimationEvent, YIndex,
    };
    pub use crate::{Animations, AnimationsConfig};
}

#[derive(Component, Clone)]
struct FXAnimation;

#[derive(Debug, Resource, Default)]
pub struct AnimationsConfig {
    pixels_per_meter: f32,
}

#[derive(Debug, Resource, Default)]
pub struct EntitesToRemove(Vec<Entity>);

#[derive(Component, Deref, DerefMut, Clone, Debug, Default)]
pub struct AnimationTimer(pub Timer);

#[derive(Debug)]
pub struct AnimatingEntity {
    pub entity: Entity,
    pub in_blocking_animation: bool,
    pub animations: HashMap<AnimationName, Arc<Mutex<AnimationType>>>,
    pub curr_animation: Arc<Mutex<AnimationType>>,
    pub curr_direction: AnimationDirection,
    pub last_valid_direction: AnimationDirection,
    pub curr_animation_called: bool,
    pub fx_animation: bool,
}

#[derive(Default, Resource, Debug)]
pub struct Animations {
    entities: HashMap<Entity, AnimatingEntity>,
    animations: HashMap<AnimationName, Animation>,
    fx_animations: HashMap<AnimationName, Animation>,
}

impl Animations {
    /// Adds a new animation to the animation pool.
    ///
    /// Can optionally add an entity to the animation.
    ///
    /// # Panics
    /// When an animation with the same name already exists
    pub fn insert_animation(
        &mut self,
        animation: NewAnimation,
        entity: Option<Entity>,
    ) -> &mut Self {
        let name = animation.animation.get_name();
        let animation = Animation {
            handle: animation.handle,
            animation: Arc::new(Mutex::new(animation.animation)),
        };
        let new_animation = Arc::clone(&animation.animation);
        let animation = animation;
        if self.animations.get_mut(&name).is_none() {
            self.animations.insert(name, animation);
        }
        if let Some(entity) = entity {
            if let Some(animating_entity) = self.entities.get_mut(&entity) {
                animating_entity
                    .animations
                    .insert(name, Arc::clone(&new_animation));
            } else {
                let mut map = HashMap::new();
                map.insert(name, Arc::clone(&new_animation));
                self.entities.insert(
                    entity,
                    AnimatingEntity {
                        entity,
                        animations: map,
                        curr_animation: new_animation,
                        curr_direction: AnimationDirection::Still,
                        last_valid_direction: AnimationDirection::default(),
                        in_blocking_animation: false,
                        curr_animation_called: false,
                        fx_animation: false,
                    },
                );
            }
        }
        self
    }

    /// Add an [Entity] to the pool without a current animation specified
    ///
    /// Returns [Result<(), String>] an [Err(String)] if the entity already exists in the pool
    pub fn insert_entity(&mut self, entity: Entity) -> Result<(), String> {
        if self.entities.contains_key(&entity) {
            return Err(format!(
                "Entity {:?} already exists in `Animations`",
                entity
            ));
        }
        self.entities.insert(
            entity,
            AnimatingEntity {
                entity,
                animations: HashMap::new(),
                curr_animation: Arc::new(Mutex::new(AnimationType::default())),
                curr_direction: AnimationDirection::Still,
                last_valid_direction: AnimationDirection::default(),
                in_blocking_animation: false,
                curr_animation_called: false,
                fx_animation: false,
            },
        );
        Ok(())
    }

    /// Add an animation to an [Entity]
    ///
    /// Returns [Result<(), String>] an [Err(String)] if the animation already exists on the entity specified
    pub fn add_animation_to_entity(
        &mut self,
        animation_name: AnimationName,
        entity: Entity,
    ) -> Result<(), String> {
        if let Some(animation) = self.animations.get_mut(&animation_name) {
            let ac_animation = Arc::new(Mutex::new(animation.animation.lock().unwrap().clone()));
            if let Some(entity) = self.entities.get_mut(&entity) {
                if entity.animations.contains_key(&animation_name) {
                    return Err(format!(
                        "Animation {:?} already exists on entity {:?}",
                        animation_name, entity.entity
                    ));
                }
                if entity.curr_animation.lock().unwrap().is_none() {
                    entity.curr_animation = Arc::clone(&ac_animation);
                }
                entity.animations.insert(animation_name, ac_animation);
            } else {
                let mut map = HashMap::new();
                map.insert(animation_name, Arc::clone(&ac_animation));
                self.entities.insert(
                    entity,
                    AnimatingEntity {
                        entity,
                        animations: map,
                        curr_animation: ac_animation,
                        curr_direction: AnimationDirection::Still,
                        last_valid_direction: AnimationDirection::default(),
                        in_blocking_animation: false,
                        curr_animation_called: false,
                        fx_animation: false,
                    },
                );
            }
        }
        Ok(())
    }

    /// Gets a clone of the `TextureAtlasLayout` handle for the animation specified
    pub fn get_handle(&self, animation_name: AnimationName) -> Option<Handle<TextureAtlasLayout>> {
        if let Some(animation) = self.animations.get(&animation_name) {
            return Some(animation.handle.clone());
        }
        None
    }

    /// Gets a clone of the `TextureAtlasLayout` handle for the fx_animation specified
    ///
    /// Returns [None] if the animation does not exist
    pub fn get_fx_handle(
        &self,
        animation_name: AnimationName,
    ) -> Option<Handle<TextureAtlasLayout>> {
        if let Some(animation) = self.fx_animations.get(&animation_name) {
            return Some(animation.handle.clone());
        }
        None
    }

    /// Gets the animating entity from the entity specified
    ///
    /// Returns [None] if the entity does not exist in the pool
    pub fn get_entity(&mut self, entity: &Entity) -> Option<&mut AnimatingEntity> {
        if let Some(animating_entity) = self.entities.get_mut(entity) {
            return Some(animating_entity);
        }
        None
    }

    /// Checks if the animation specified is not animating on the entity specified currently
    ///
    /// Returns [None] if the entity does not exist in the pool
    pub fn is_new_animation(&self, animation_name: AnimationName, entity: &Entity) -> Option<bool> {
        if let Some(animating_entity) = self.entities.get(entity) {
            if animating_entity.curr_animation.lock().unwrap().get_name() != animation_name {
                return Some(true);
            }
            return Some(false);
        }
        None
    }

    /// If the entity specified exists in the pool
    pub fn has_entity(&self, entity: &Entity) -> bool {
        if self.entities.contains_key(entity) {
            return true;
        }
        false
    }

    /// Insert an FX animation this. In order to start the FX animation send it through an [EventWriter(FXAnimationEvent(AnimationName))]
    pub fn insert_fx_animation(&mut self, value: NewAnimation) -> &mut Self {
        let key = value.animation.get_name();
        if self.fx_animations.contains_key(key) {
            self
        } else {
            let animation = Animation {
                handle: value.handle,
                animation: Arc::new(Mutex::new(value.animation)),
            };
            self.fx_animations.insert(key, animation);
            self
        }
    }

    /// Add an FX animation to a new [AnimatingEntity]. This will start the animation specified.
    ///
    /// # Note
    ///
    /// This method is used for the backend and shouldn't be called directly. If you need to start an fx animation use [FXAnimationEvent] instead.
    pub fn start_fx_animation(
        &mut self,
        key: Entity,
        animation: AnimationName,
        pos: Vec3,
    ) -> Result<SpriteSheetBundle, ()> {
        let name = animation;
        let Some(animation) = self.fx_animations.get(animation) else {
            return Err(());
        };
        let mut animation = animation.animation.lock().unwrap().clone();

        // Grab the atlas from the animations and spawn a new entity with the atlas at the specified pos
        let mut atlas: TextureAtlas = self
            .get_fx_handle(name)
            .unwrap_or_else(|| panic!("There was a problem starting FX animation {}", name))
            .into();
        atlas.index = if let Some(timed_animation) = animation.timed_animation() {
            timed_animation.sprite_index(&AnimationDirection::default())
        } else if let Some(transform_animation) = animation.transform_animation() {
            transform_animation.sprite_index(&AnimationDirection::default())
        } else if let Some(linear_timed_animation) = animation.linear_timed_animation() {
            linear_timed_animation.sprite_index(&AnimationDirection::default())
        } else if let Some(linear_transform_animation) = animation.linear_transform_animation() {
            linear_transform_animation.sprite_index(&AnimationDirection::default())
        } else if let Some(single_frame_animation) = animation.single_frame_animation() {
            single_frame_animation.sprite_index(&AnimationDirection::default())
        } else {
            panic!("Something Went Terribly Wrong Starting FX Animation");
        };
        // Add the animation and entity to a new AnimatingEntity to be animated
        self.entities.insert(
            key,
            AnimatingEntity {
                entity: key,
                in_blocking_animation: false,
                animations: HashMap::new(),
                curr_animation: Arc::new(Mutex::new(animation)),
                curr_direction: AnimationDirection::default(),
                last_valid_direction: AnimationDirection::default(),
                curr_animation_called: true,
                fx_animation: true,
            },
        );
        Ok(SpriteSheetBundle {
            atlas,
            transform: Transform::from_translation(pos),
            ..Default::default()
        })
    }

    /// if the animation exists in the pool
    pub fn has_animation(&self, animation_name: AnimationName) -> bool {
        if self.animations.contains_key(animation_name) {
            return true;
        }
        false
    }

    /// Returns [Some(())] if the animation already exists on the entity specified
    ///
    /// Returns [None] if the entity was not found in the pool
    ///
    /// Returns [None] if the animation was not found on the entity specified
    pub fn entity_has_animation(
        &self,
        animation_name: &AnimationName,
        entity: Entity,
    ) -> Option<()> {
        if let Some(animating_entity) = self.entities.get(&entity) {
            if animating_entity.animations.contains_key(animation_name) {
                return Some(());
            }
            return None;
        }
        None
    }

    /// Returns [Some(bool)] if the entity exists and [Some(true)] if the entity is in a blocking animation
    ///
    /// Returns [None] if the entity was not found
    ///
    /// usefull to determine for example whether or not to move an entity
    pub fn in_blocking_animation(&self, entity: Entity) -> Option<bool> {
        self.entities
            .get(&entity)
            .map(|animating_entity| animating_entity.in_blocking_animation)
    }

    /// Returns [Some(bool)] if the entity exists and [Some(true)] if the entity is in an animation
    ///
    /// Returns [None] if the entity was not found
    ///
    /// useful for determining for example whether or not to initate another animation
    pub fn in_animation(&self, entity: Entity) -> Option<bool> {
        self.entities
            .get(&entity)
            .map(|animating_entity| animating_entity.curr_animation_called)
    }

    /// Returns [Some(bool)] if the entity exists and [Some(true)] if the entity is in the animation specified
    ///
    /// Returns [None] if the entity was not found
    ///
    /// useful for determining for example whether or not to initate another animation
    pub fn doing_animation(&self, entity: Entity, animation_name: AnimationName) -> Option<bool> {
        self.entities.get(&entity).map(|animating_entity| {
            animating_entity.curr_animation_called
                && animating_entity.curr_animation.lock().unwrap().get_name() == animation_name
        })
    }

    /// Returns `true` if the [Entity] exists in the [Animations] map
    pub fn is_inserted(&self, key: &Entity) -> bool {
        if self.entities.contains_key(key) {
            return true;
        }
        false
    }

    /// Mainly for debug purposes to see the map. Not reccomended to change item.
    pub fn get_mut_map(&mut self) -> &mut HashMap<Entity, AnimatingEntity> {
        &mut self.entities
    }

    /// Mainly for debug purposes to see the map. Not reccomended to change item.
    pub fn get_map(&self) -> &HashMap<Entity, AnimatingEntity> {
        &self.entities
    }
}