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
use crate::{asset_protocols::sprite_animation::*, components::sprite_animation_instance::*};
use core::{
    app::AppLifeCycle,
    assets::{asset::AssetId, database::AssetsDatabase},
    ecs::{Comp, Universe, WorldRef},
    Scalar,
};
use std::collections::HashMap;

#[derive(Debug, Default)]
pub struct HaSpriteAnimationSystemCache {
    map: HashMap<String, (SpriteAnimationAsset, AssetId)>,
    table: HashMap<AssetId, String>,
}

pub type HaSpriteAnimationSystemResources<'a> = (
    WorldRef,
    &'a AppLifeCycle,
    &'a AssetsDatabase,
    &'a mut HaSpriteAnimationSystemCache,
    Comp<&'a mut HaSpriteAnimationInstance>,
);

macro_rules! select_state {
    ($animation: expr, $sprite: expr, $state: expr, $next: expr) => {
        $animation
            .rules
            .iter()
            .chain($state.rules.iter())
            .find_map(|rule| {
                match rule {
                    SpriteAnimationRule::Single {
                        target_state,
                        conditions,
                        region,
                    } => {
                        if region.contains($next)
                            && conditions.iter().all(|(k, c)| {
                                $sprite
                                    .values
                                    .get(k)
                                    .map(|v| c.validate(v))
                                    .unwrap_or_default()
                            })
                        {
                            return Some(target_state);
                        }
                    }
                    SpriteAnimationRule::BlendSpace {
                        conditions,
                        axis_scalars,
                        blend_states,
                    } => {
                        if conditions.iter().all(|(k, c)| {
                            $sprite
                                .values
                                .get(k)
                                .map(|v| c.validate(v))
                                .unwrap_or_default()
                        }) {
                            return blend_states
                                .iter()
                                .map(|state| {
                                    let result = state
                                        .axis_values
                                        .iter()
                                        .zip(axis_scalars.iter().map(|n| {
                                            $sprite
                                                .values
                                                .get(n)
                                                .and_then(|v| v.as_scalar())
                                                .unwrap_or_default()
                                        }))
                                        .map(|(a, b)| {
                                            let v = a - b;
                                            v * v
                                        })
                                        .fold(0.0, |a, v| a + v);
                                    (&state.target_state, result)
                                })
                                .min_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
                                .map(|(n, _)| n);
                        }
                    }
                }
                None
            })
    };
}

macro_rules! process_change {
    ($animation: expr, $active: expr, $sprite: expr, $dt: expr) => {
        if let Some(state) = $animation.states.get(&$active.state) {
            let length = state.frames.len() as Scalar;
            let delta = $sprite.speed * $animation.speed * state.speed * $dt;
            let prev = $active.frame as usize;
            let time_before = $active.frame;
            let end = if $active.bounced {
                $active.frame -= delta;
                $active.frame <= 0.0
            } else {
                $active.frame += delta;
                $active.frame >= length
            };
            let time_after = $active.frame;
            let time_range = time_before.min(time_after)..time_before.max(time_after);
            $sprite.signals.extend(
                state
                    .signals
                    .iter()
                    .filter(|signal| {
                        signal.time >= time_range.start && signal.time < time_range.end
                    })
                    .cloned(),
            );
            if end {
                if state.looping {
                    if state.bounce {
                        $active.bounced = !$active.bounced;
                    } else if $active.bounced {
                        $active.frame += length;
                    } else {
                        $active.frame -= length;
                    }
                } else {
                    $sprite.playing = false;
                }
            }
            $active.frame = $active.frame.max(0.0).min(length);
            let next = ($active.frame as usize).min(state.frames.len() - 1);
            let selected = select_state!($animation, $sprite, state, next);

            if let Some(selected) = selected {
                if &$active.state != selected {
                    $active.state = selected.to_owned();
                    $active.frame = 0.0;
                    $active.bounced = false;
                    $active.cached_frame = None;
                    true
                } else {
                    prev != next
                }
            } else {
                prev != next
            }
        } else {
            false
        }
    };
}

pub fn ha_sprite_animation(universe: &mut Universe) {
    let (world, lifecycle, assets, mut cache, ..) =
        universe.query_resources::<HaSpriteAnimationSystemResources>();

    for id in assets.lately_loaded_protocol("spriteanim") {
        if let Some(asset) = assets.asset_by_id(*id) {
            let path = asset.path();
            if let Some(asset) = asset.get::<SpriteAnimationAsset>() {
                cache.map.insert(path.to_owned(), (asset.to_owned(), *id));
                cache.table.insert(*id, path.to_owned());
            }
        }
    }
    for id in assets.lately_unloaded_protocol("spriteanim") {
        if let Some(name) = cache.table.remove(id) {
            cache.map.remove(&name);
        }
    }

    let dt = lifecycle.delta_time_seconds();
    for (_, sprite) in world.query::<&mut HaSpriteAnimationInstance>().iter() {
        sprite.frame_changed = false;
        sprite.signals.clear();

        if let Some((animation, _)) = cache.map.get(&sprite.animation) {
            if sprite.playing && sprite.active.is_none() {
                if let Some(name) = &animation.default_state {
                    sprite.play(name);
                }
            }

            if let (true, Some(active)) = (sprite.playing, sprite.active.as_mut()) {
                let change = process_change!(animation, active, sprite, dt);

                if let (true, Some(state)) = (change, animation.states.get(&active.state)) {
                    let index = (active.frame.max(0.0) as usize).min(state.frames.len() - 1);
                    if let Some(name) = state.frames.get(index) {
                        active.cached_frame = Some(name.to_owned());
                        sprite.frame_changed = true;
                    }
                }
            }
        }
    }
}