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
#![feature(seek_stream_len)]
//! # Nintendo parameter archive (AAMP) library in Rust
//!
//! A simple to use library for reading, writing, and converting Nintendo parameter archive (AAMP) files
//! in Rust. Supports only AAMP version 2, used in _The Legend of Zelda: Breath of the Wild_. Can
//! convert from AAMP to readable, editable YAML and back.
//!
//! ```rust
//! use aamp::ParameterIO;
//! let mut file = std::fs::File::open("test/Enemy_Lizalfos_Electric.bchemical").unwrap();
//! // Read an AAMP ParameterIO from any reader that implements Seek + Read
//! let pio = ParameterIO::from_binary(&mut file).unwrap();
//! for list in pio.lists.iter() {
//!     // Do stuff with lists
//! }
//! for obj in pio.objects.iter() {
//!     // Do stuff with objects
//! }
//! // Dumps YAML representation to a String
//! let yaml_dump: String = pio.to_text().unwrap();
//! ```
use crc::{crc32, Hasher32};
use indexmap::IndexMap;
pub mod names;
mod parse;
pub mod types;
mod write;
mod yaml;

#[derive(Debug, PartialEq, Clone)]
/// Represents a single AAMP parameter
pub enum Parameter {
    Bool(bool),
    F32(f32),
    Int(i32),
    Vec2(types::Vec2),
    Vec3(types::Vec3),
    Vec4(types::Vec4),
    Color(types::Color),
    String32(String),
    String64(String),
    Curve1(types::Curve1),
    Curve2(types::Curve2),
    Curve3(types::Curve3),
    Curve4(types::Curve4),
    BufferInt(types::BufferInt),
    BufferF32(types::BufferF32),
    String256(String),
    Quat(types::Quat),
    U32(u32),
    BufferU32(types::BufferU32),
    BufferBinary(types::BufferBinary),
    StringRef(String),
}

impl Parameter {
    #[inline]
    fn is_string(self: &Parameter) -> bool {
        matches!(
            self,
            Parameter::String32(_)
                | Parameter::String64(_)
                | Parameter::String256(_)
                | Parameter::StringRef(_)
        )
    }

    #[inline]
    fn is_buffer(self: &Parameter) -> bool {
        matches!(
            self,
            Parameter::BufferBinary(_)
                | Parameter::BufferF32(_)
                | Parameter::BufferInt(_)
                | Parameter::BufferU32(_)
        )
    }
}

#[derive(Debug, PartialEq, Clone)]
/// Represents a single AAMP parameter object, containing a map of parameters by hash
pub struct ParameterObject(IndexMap<u32, Parameter>);

impl ParameterObject {
    /// Attempt to get a `Parameter` by name, returns None if not found
    pub fn param(&self, name: &str) -> Option<&Parameter> {
        let mut digest = crc32::Digest::new(crc32::IEEE);
        digest.write(name.as_bytes());
        self.0.get(&digest.sum32())
    }

    /// Sets a parameter value
    pub fn set_param(&mut self, name: &str, value: Parameter) {
        let mut digest = crc32::Digest::new(crc32::IEEE);
        digest.write(name.as_bytes());
        self.0.insert(digest.sum32(), value);
    }
    /// Expose reference to underlying IndexMap
    pub fn params(&self) -> &IndexMap<u32, Parameter> {
        &self.0
    }

    /// Expose mutable reference to underlying IndexMap
    pub fn params_mut(&mut self) -> &mut IndexMap<u32, Parameter> {
        &mut self.0
    }
}

/// Represents a single AAMP parameter list, containing a hash map of parameter objects and
/// child parameter lists
#[derive(Debug, PartialEq, Clone)]
pub struct ParameterList {
    pub lists: IndexMap<u32, ParameterList>,
    pub objects: IndexMap<u32, ParameterObject>,
}

impl ParameterList {
    /// Attempt to get a `ParameterList` by name, returns None if not found
    pub fn list(&self, name: &str) -> Option<&ParameterList> {
        let mut digest = crc32::Digest::new(crc32::IEEE);
        digest.write(name.as_bytes());
        self.lists.get(&digest.sum32())
    }

    /// Attempt to get a `ParameterObject` by name, returns None if not found
    pub fn object(&self, name: &str) -> Option<&ParameterObject> {
        let mut digest = crc32::Digest::new(crc32::IEEE);
        digest.write(name.as_bytes());
        self.objects.get(&digest.sum32())
    }
}

#[derive(Debug, PartialEq, Clone)]
/// Represents a single AAMP parameter IO document
pub struct ParameterIO {
    /// The parameter IO version, required by the format but of no functional importance
    pub version: u32,
    /// The parameter IO type, required by the format but of no functional importance
    pub pio_type: String,
    /// The lists in the parameter IO root list (`param_root`)
    pub lists: IndexMap<u32, ParameterList>,
    /// The objects in the parameter IO root list (`param_root`)
    pub objects: IndexMap<u32, ParameterObject>,
}

impl ParameterIO {
    /// Attempt to get a `ParameterList` by name, returns None if not found
    pub fn list(&self, name: &str) -> Option<&ParameterList> {
        let mut digest = crc32::Digest::new(crc32::IEEE);
        digest.write(name.as_bytes());
        self.lists.get(&digest.sum32())
    }

    /// Attempt to get a `ParameterObject` by name, returns None if not found
    pub fn object(&self, name: &str) -> Option<&ParameterObject> {
        let mut digest = crc32::Digest::new(crc32::IEEE);
        digest.write(name.as_bytes());
        self.objects.get(&digest.sum32())
    }
}

#[cfg(test)]
mod tests {
    use super::ParameterIO;
    use glob::glob;
    use std::fs::File;
    use std::path::PathBuf;

    #[test]
    fn binary_roundtrip() {
        for file in glob("test/**/*.b*").unwrap() {
            let good_file: PathBuf = file.unwrap();
            let mut reader = File::open(&good_file).unwrap();
            let pio: ParameterIO = ParameterIO::from_binary(&mut reader).unwrap();
            let mut cur: std::io::Cursor<Vec<u8>> =
                std::io::Cursor::new(pio.clone().to_binary().unwrap());
            let pio2: ParameterIO = ParameterIO::from_binary(&mut cur).unwrap();
            assert_eq!(pio, pio2);
        }
    }

    #[test]
    fn dump_yaml() {
        for file in glob("test/*.b*").unwrap() {
            let good_file: PathBuf = file.unwrap();
            let mut reader = File::open(&good_file).unwrap();
            let pio: ParameterIO = ParameterIO::from_binary(&mut reader).unwrap();
            pio.to_text().unwrap();
        }
    }

    #[test]
    fn yaml_roundtrip() {
        for file in glob("test/*.b*").unwrap() {
            let good_file: PathBuf = file.unwrap();
            let mut reader = File::open(&good_file).unwrap();
            let pio: ParameterIO = ParameterIO::from_binary(&mut reader).unwrap();
            let new_text = pio.clone().to_text().unwrap();
            let new_pio = ParameterIO::from_text(&new_text).unwrap();
            if pio != new_pio {
                panic!(
                    "{:?} failed YAML roundtrip\n{:?}\n{:?}",
                    &good_file, pio, new_pio
                );
            }
        }
    }

    #[test]
    fn yaml_to_binary() {
        for file in glob("test/*.yml").unwrap().filter_map(|f| f.ok()) {
            let pio = ParameterIO::from_text(&std::fs::read_to_string(&file).unwrap()).unwrap();
            let binary = pio.to_binary().unwrap();
            assert_eq!(
                pio,
                ParameterIO::from_binary(&mut std::io::Cursor::new(binary)).unwrap()
            );
        }
    }
}