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
use crate::{components::transform::HaTransform, math::*};
use animation::phase::Phase;
use core::{
    assets::protocol::{AssetLoadResult, AssetProtocol},
    scripting::{intuicio::data::managed::DynamicManaged, ScriptingValue},
    Scalar,
};
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, ops::Range, str::from_utf8};

fn default_speed() -> Scalar {
    1.0
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RigAnimationCondition {
    Not(Box<Self>),
    And(Vec<Self>),
    Or(Vec<Self>),
    Bool(bool),
    IntegerEquals(i32),
    IntegerGreater(i32),
    IntegerLess(i32),
    /// (from inclusive, to inclusive)
    IntegerRange(i32, i32),
    /// (value, threshold)
    ScalarNearlyEquals(Scalar, Scalar),
    ScalarGreater(Scalar),
    ScalarLess(Scalar),
    /// (from inclusive, to inclusive)
    ScalarRange(Scalar, Scalar),
    StringEquals(String),
    StringContains(String),
    StringTagged {
        tag: String,
        separator: String,
    },
}

impl RigAnimationCondition {
    pub fn validate(&self, value: &DynamicManaged) -> bool {
        match self {
            RigAnimationCondition::Not(c) => {
                return !c.validate(value);
            }
            RigAnimationCondition::And(c) => {
                return c.iter().all(|c| c.validate(value));
            }
            RigAnimationCondition::Or(c) => {
                return c.iter().any(|c| c.validate(value));
            }
            RigAnimationCondition::Bool(c) => {
                if let Some(v) = value.read::<bool>() {
                    return *v == *c;
                }
            }
            RigAnimationCondition::IntegerEquals(c) => {
                if let Some(v) = value.read::<i32>() {
                    return *v == *c;
                }
            }
            RigAnimationCondition::IntegerGreater(c) => {
                if let Some(v) = value.read::<i32>() {
                    return *v > *c;
                }
            }
            RigAnimationCondition::IntegerLess(c) => {
                if let Some(v) = value.read::<i32>() {
                    return *v < *c;
                }
            }
            RigAnimationCondition::IntegerRange(a, b) => {
                if let Some(v) = value.read::<i32>() {
                    return *v >= *a && *v <= *b;
                }
            }
            RigAnimationCondition::ScalarNearlyEquals(c, t) => {
                if let Some(v) = value.read::<Scalar>() {
                    return (*c - *v).abs() < *t;
                }
            }
            RigAnimationCondition::ScalarGreater(c) => {
                if let Some(v) = value.read::<Scalar>() {
                    return *v > *c;
                }
            }
            RigAnimationCondition::ScalarLess(c) => {
                if let Some(v) = value.read::<Scalar>() {
                    return *v < *c;
                }
            }
            RigAnimationCondition::ScalarRange(a, b) => {
                if let Some(v) = value.read::<Scalar>() {
                    return *v >= *a && *v <= *b;
                }
            }
            RigAnimationCondition::StringEquals(c) => {
                if let Some(v) = value.read::<String>() {
                    return *v == *c;
                }
            }
            RigAnimationCondition::StringContains(c) => {
                if let Some(v) = value.read::<String>() {
                    return v.contains(c);
                }
            }
            RigAnimationCondition::StringTagged { tag, separator } => {
                if let Some(v) = value.read::<String>() {
                    return v.split(separator).any(|part| part == tag);
                }
            }
        }
        false
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RigAnimationBlendState {
    pub target_state: String,
    pub axis_values: Vec<Scalar>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RigAnimationRule {
    Single {
        target_state: String,
        #[serde(default)]
        conditions: HashMap<String, RigAnimationCondition>,
        #[serde(default)]
        change_time: Scalar,
    },
    BlendSpace {
        axis_scalars: Vec<String>,
        blend_states: Vec<RigAnimationBlendState>,
        #[serde(default)]
        conditions: HashMap<String, RigAnimationCondition>,
        #[serde(default)]
        change_time: Scalar,
    },
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct RigAnimationSignal {
    pub time: Scalar,
    pub id: String,
    #[serde(default)]
    pub params: HashMap<String, ScriptingValue>,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct RigAnimationSequenceBoneSheet {
    #[serde(default)]
    pub translation_x: Option<Phase>,
    #[serde(default)]
    pub translation_y: Option<Phase>,
    #[serde(default)]
    pub translation_z: Option<Phase>,
    #[serde(default)]
    pub rotation_yaw: Option<Phase>,
    #[serde(default)]
    pub rotation_pitch: Option<Phase>,
    #[serde(default)]
    pub rotation_roll: Option<Phase>,
    #[serde(default)]
    pub scale_x: Option<Phase>,
    #[serde(default)]
    pub scale_y: Option<Phase>,
    #[serde(default)]
    pub scale_z: Option<Phase>,
}

impl RigAnimationSequenceBoneSheet {
    pub fn time_frame(&self) -> Option<Range<Scalar>> {
        let mut result = None;
        Self::accumulate_time_frame(&self.translation_x, &mut result);
        Self::accumulate_time_frame(&self.translation_y, &mut result);
        Self::accumulate_time_frame(&self.translation_z, &mut result);
        Self::accumulate_time_frame(&self.rotation_yaw, &mut result);
        Self::accumulate_time_frame(&self.rotation_pitch, &mut result);
        Self::accumulate_time_frame(&self.rotation_roll, &mut result);
        Self::accumulate_time_frame(&self.scale_x, &mut result);
        Self::accumulate_time_frame(&self.scale_y, &mut result);
        Self::accumulate_time_frame(&self.scale_z, &mut result);
        result
    }

    pub fn sample(&self, time: Scalar, fallback: &HaTransform) -> HaTransform {
        HaTransform::new(
            vec3(
                self.translation_x
                    .as_ref()
                    .map(|phase| phase.sample(time))
                    .unwrap_or_else(|| fallback.get_translation().x),
                self.translation_y
                    .as_ref()
                    .map(|phase| phase.sample(time))
                    .unwrap_or_else(|| fallback.get_translation().y),
                self.translation_z
                    .as_ref()
                    .map(|phase| phase.sample(time))
                    .unwrap_or_else(|| fallback.get_translation().z),
            ),
            Eulers {
                yaw: self
                    .rotation_yaw
                    .as_ref()
                    .map(|phase| phase.sample(time))
                    .unwrap_or_else(|| fallback.get_rotation().eulers().yaw),
                pitch: self
                    .rotation_pitch
                    .as_ref()
                    .map(|phase| phase.sample(time))
                    .unwrap_or_else(|| fallback.get_rotation().eulers().pitch),
                roll: self
                    .rotation_roll
                    .as_ref()
                    .map(|phase| phase.sample(time))
                    .unwrap_or_else(|| fallback.get_rotation().eulers().roll),
            },
            vec3(
                self.scale_x
                    .as_ref()
                    .map(|phase| phase.sample(time))
                    .unwrap_or_else(|| fallback.get_scale().x),
                self.scale_y
                    .as_ref()
                    .map(|phase| phase.sample(time))
                    .unwrap_or_else(|| fallback.get_scale().y),
                self.scale_z
                    .as_ref()
                    .map(|phase| phase.sample(time))
                    .unwrap_or_else(|| fallback.get_scale().z),
            ),
        )
    }

    fn accumulate_time_frame(input: &Option<Phase>, output: &mut Option<Range<Scalar>>) {
        if let Some(phase) = input {
            let time_frame = phase.time_frame();
            if let Some(output) = output.as_mut() {
                output.start = output.start.min(time_frame.start);
                output.end = output.end.min(time_frame.end);
            } else {
                *output = Some(time_frame);
            }
        }
    }
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct RigAnimationSequence {
    #[serde(default = "default_speed")]
    pub speed: Scalar,
    #[serde(default)]
    pub looping: bool,
    #[serde(default)]
    pub bounce: bool,
    #[serde(default)]
    pub bone_sheets: HashMap<String, RigAnimationSequenceBoneSheet>,
    #[serde(default)]
    pub signals: Vec<RigAnimationSignal>,
}

impl RigAnimationSequence {
    pub fn time_frame(&self) -> Option<Range<Scalar>> {
        self.bone_sheets
            .values()
            .fold(None, |a, v| match (a, v.time_frame()) {
                (None, None) => None,
                (Some(a), None) => Some(a),
                (Some(a), Some(v)) => Some(a.start.min(v.start)..a.end.max(v.end)),
                (None, Some(v)) => Some(v),
            })
    }

    pub fn sample_bone(&self, name: &str, time: Scalar, fallback: &HaTransform) -> HaTransform {
        self.bone_sheets
            .get(name)
            .map(|sheet| sheet.sample(time, fallback))
            .unwrap_or_else(|| fallback.to_owned())
    }
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct RigAnimationBlendSpace {
    pub sequence: String,
    pub axis_values: Vec<Scalar>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RigAnimationStateSequences {
    Single(String),
    BlendSpace {
        axis_scalars: Vec<String>,
        sequences: Vec<RigAnimationBlendSpace>,
    },
}

impl Default for RigAnimationStateSequences {
    fn default() -> Self {
        Self::Single(Default::default())
    }
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct RigAnimationState {
    pub sequences: RigAnimationStateSequences,
    #[serde(default)]
    pub rules: Vec<RigAnimationRule>,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct RigAnimationAsset {
    #[serde(default)]
    pub default_state: Option<String>,
    #[serde(default = "default_speed")]
    pub speed: Scalar,
    #[serde(default)]
    pub sequences: HashMap<String, RigAnimationSequence>,
    #[serde(default)]
    pub states: HashMap<String, RigAnimationState>,
    #[serde(default)]
    pub rules: Vec<RigAnimationRule>,
}

pub struct RigAnimationAssetProtocol;

impl AssetProtocol for RigAnimationAssetProtocol {
    fn name(&self) -> &str {
        "riganim"
    }

    fn on_load_with_path(&mut self, path: &str, data: Vec<u8>) -> AssetLoadResult {
        let data = if path.ends_with(".json") {
            let data = from_utf8(&data).unwrap();
            serde_json::from_str::<RigAnimationAsset>(data).unwrap()
        } else {
            bincode::deserialize::<RigAnimationAsset>(&data).unwrap()
        };
        AssetLoadResult::Data(Box::new(data))
    }

    // on_load_with_path() handles loading so this is not needed, so we just make it unreachable.
    fn on_load(&mut self, _data: Vec<u8>) -> AssetLoadResult {
        unreachable!()
    }
}