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
use crate::mesh::rig::{
    control::RigControl,
    deformer::Deformer,
    skeleton::{Skeleton, SkeletonError, SkeletonHierarchy},
    Rig,
};
use core::{
    assets::protocol::{AssetLoadResult, AssetProtocol},
    scripting::{
        intuicio::core::registry::Registry, ScriptFunctionReference, ScriptStructReference,
    },
};
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, str::from_utf8};

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RigAssetError {
    Skeleton(SkeletonError),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RigAssetControl {
    pub struct_type: ScriptStructReference,
    pub init_function: Option<ScriptFunctionReference>,
    pub solve_function: Option<ScriptFunctionReference>,
    /// {field name: field string value}
    pub bindings: HashMap<String, String>,
}

impl RigAssetControl {
    pub fn new(struct_type: ScriptStructReference) -> Self {
        Self {
            struct_type,
            init_function: None,
            solve_function: None,
            bindings: Default::default(),
        }
    }

    pub fn init_function(mut self, function: ScriptFunctionReference) -> Self {
        self.init_function = Some(function);
        self
    }

    pub fn solve_function(mut self, function: ScriptFunctionReference) -> Self {
        self.solve_function = Some(function);
        self
    }

    pub fn binding(mut self, field_name: impl ToString, field_value: impl ToString) -> Self {
        self.bindings
            .insert(field_name.to_string(), field_value.to_string());
        self
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RigAsset {
    skeleton: SkeletonHierarchy,
    #[serde(default)]
    deformer: Deformer,
    #[serde(default)]
    controls: Vec<RigAssetControl>,
}

impl RigAsset {
    pub fn new(
        skeleton: SkeletonHierarchy,
        deformer: Deformer,
        controls: Vec<RigAssetControl>,
    ) -> Self {
        Self {
            skeleton,
            deformer,
            controls,
        }
    }

    pub fn skeleton(&self) -> &SkeletonHierarchy {
        &self.skeleton
    }

    pub fn deformer(&self) -> &Deformer {
        &self.deformer
    }

    pub fn controls(&self) -> &[RigAssetControl] {
        &self.controls
    }

    pub fn build_skeleton(&self) -> Result<Skeleton, RigAssetError> {
        self.skeleton
            .to_owned()
            .try_into()
            .map_err(RigAssetError::Skeleton)
    }

    pub fn build_controls(&self, registry: &Registry) -> Vec<RigControl> {
        self.controls
            .iter()
            .filter_map(|control| {
                let struct_type = registry.find_struct(control.struct_type.query())?;
                let init_function = control
                    .init_function
                    .as_ref()
                    .and_then(|function| registry.find_function(function.query()))
                    .or_else(|| registry.find_function(control.struct_type.method("init").query()));
                let solve_function = control
                    .solve_function
                    .as_ref()
                    .and_then(|function| registry.find_function(function.query()))
                    .or_else(|| {
                        registry.find_function(control.struct_type.method("solve").query())
                    })?;
                Some(RigControl {
                    struct_type,
                    init_function,
                    solve_function,
                    bindings: control.bindings.to_owned(),
                })
            })
            .collect()
    }

    pub fn build_rig(&self, registry: &Registry) -> Result<Rig, RigAssetError> {
        Ok(Rig {
            skeleton: self.build_skeleton()?,
            deformer: self.deformer.to_owned(),
            controls: self.build_controls(registry),
        })
    }
}

pub struct RigAssetProtocol;

impl AssetProtocol for RigAssetProtocol {
    fn name(&self) -> &str {
        "rig"
    }

    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::<RigAsset>(data).unwrap()
        } else {
            bincode::deserialize::<RigAsset>(&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!()
    }
}