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
use std::result;
use std::convert;
use std::error;
use std::fmt::{self, Display, Formatter, Debug};
use std::ffi::CStr;
use object::{Object, List, ListIter};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Endianness{
    LittleEndian,
    BigEndian,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u16)]
pub enum ObjectType{
    Empty     = 0,
    Mesh      = 1,
    Curve     = 2,
    Surf      = 3,
    Font      = 4,
    MBall     = 5,

    Lamp      = 10,
    Camera    = 11,

    Wave      = 21,
    Lattice   = 22,
    Armature  = 25,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum PropertyType{
	String           = 0,
	Int              = 1,
	Float            = 2,
	Array            = 5,
	Group            = 6,
	Id               = 7,
	Double           = 8,
	IdArray          = 9,
	NumTypes         = 10,
}

#[derive(Debug, Clone)]
pub enum IdProperty<'a>{
    String(Object<'a>),
    Int(Object<'a>),
    Float(Object<'a>),
    Array(Object<'a>),
    Group(Object<'a>),
    Id(Object<'a>),
    Double(Object<'a>),
    IdArray(Object<'a>),
}

impl<'a> IdProperty<'a>{
    fn new(obj: Object<'a>) -> Result<IdProperty<'a>>{
        if obj.structure().name() != "IDProperty"{
            return Err(Error::from("Object is not an IDProperty".to_owned()))
        }else{
            let p = match obj.get::<PropertyType>("type").unwrap(){
                PropertyType::String => IdProperty::String(obj),
                PropertyType::Int => IdProperty::Int(obj),
                PropertyType::Float => IdProperty::Float(obj),
                PropertyType::Array => IdProperty::Array(obj),
                PropertyType::Group => IdProperty::Group(obj),
                PropertyType::Id => IdProperty::Id(obj),
                PropertyType::Double => IdProperty::Double(obj),
                PropertyType::IdArray => IdProperty::IdArray(obj),
                PropertyType::NumTypes => return Err(Error("Invalid IDProperty type".to_string())),
            };

            Ok(p)
        }
    }
}

impl<'a> IdProperty<'a>{
    pub fn ty(&self) -> PropertyType{
        match self{
            IdProperty::String(_) => PropertyType::String,
            IdProperty::Int(_) => PropertyType::Int,
            IdProperty::Float(_) => PropertyType::Float,
            IdProperty::Array(_) => PropertyType::Array,
            IdProperty::Group(_) => PropertyType::Group,
            IdProperty::Id(_) => PropertyType::Id,
            IdProperty::Double(_) => PropertyType::Double,
            IdProperty::IdArray(_) => PropertyType::IdArray,
        }
    }

    pub fn name(&self) -> &str {
        match self{
            IdProperty::String(o) => o.name().unwrap(),
            IdProperty::Int(o) => o.name().unwrap(),
            IdProperty::Float(o) => o.name().unwrap(),
            IdProperty::Array(o) => o.name().unwrap(),
            IdProperty::Group(o) => o.name().unwrap(),
            IdProperty::Id(o) => o.name().unwrap(),
            IdProperty::Double(o) => o.name().unwrap(),
            IdProperty::IdArray(o) => o.name().unwrap(),
        }
    }

    pub fn value(&self) -> IdPropertyValue<'a>{
        match self{
            IdProperty::String(obj) => {
                let subtype = *obj.get::<u8>("subtype").unwrap();
                if subtype != 0 { // UTF8 string
                    unimplemented!()
                }
                let len = *obj.get::<i32>("len").unwrap() as usize;
                let value = obj.get_object("data")
                    .and_then(|d| d.get_data_slice::<u8>("pointer", len))
                    .and_then(|d| CStr::from_bytes_with_nul(d).map_err(|e| ::Error::from(format!("{}", e))))
                    .and_then(|s| s.to_str().map_err(|e| ::Error::from(format!("{}", e))))
                    .unwrap();
                IdPropertyValue::String(value)
            }

            IdProperty::Int(obj) => {
                let val = obj.get_object("data")
                    .and_then(|d| d.get::<i32>("val"))
                    .unwrap();
                IdPropertyValue::Int(*val)
            }

            IdProperty::Float(obj) => {
                let val = obj.get_object("data")
                    .and_then(|d| d.get::<f32>("val"))
                    .unwrap();
                IdPropertyValue::Float(*val)
            }

            IdProperty::Double(obj) => {
                let val = unsafe{ obj.get_object("data")
                    .and_then(|d| d.get_contiguous::<f64>("val"))
                    .unwrap() };

                IdPropertyValue::Double(*val)
            }

            IdProperty::Group(obj) => {
                let list = obj.get_object("data").and_then(|d| d.get_list("group")).unwrap();
                IdPropertyValue::Group(Group{ list })
            }

            IdProperty::Array(obj) => {
                let subtype = *obj.get::<PropertyType>("subtype").unwrap();
                let len = *obj.get::<i32>("len").unwrap() as usize;
                match subtype {
                    PropertyType::Int => {
                        let a = obj.get_object("data")
                            .and_then(|d| d.get_data_slice::<i32>("pointer", len))
                            .unwrap();
                        IdPropertyValue::ArrayInt(a)
                    }
                    PropertyType::Float => {
                        let a = obj.get_object("data")
                            .and_then(|d| d.get_data_slice::<f32>("pointer", len))
                            .unwrap();
                        IdPropertyValue::ArrayFloat(a)
                    }
                    PropertyType::Double => {
                        let a = obj.get_object("data")
                            .and_then(|d| d.get_data_slice::<f64>("pointer", len))
                            .unwrap();
                        IdPropertyValue::ArrayDouble(a)
                    }

                    _ => unimplemented!()
                }
            }

            _ => IdPropertyValue::Id()
        }
    }
}

#[derive(Debug, Clone)]
pub enum IdPropertyValue<'a>{
    String(&'a str),
    Int(i32),
    Float(f32),
    ArrayInt(&'a [i32]),
    ArrayFloat(&'a [f32]),
    ArrayDouble(&'a [f64]),
    // ArrayGroup(ArrayGroup<'a, AddressType>),
    Group(Group<'a>),
    Id(),
    Double(f64),
    IdArray(),
}

#[derive(Clone)]
pub struct Group<'a>{
    pub(crate) list: List<'a>
}

impl<'a> Group<'a>{
    pub fn iter(&self) -> GroupIter<'a>{
        GroupIter{
            iter: self.list.iter()
        }
    }
}

impl<'a> Debug for Group<'a>{
    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        fmt.write_str("Group")
    }
}

pub struct GroupIter<'a> {
    pub(crate) iter: ListIter<'a>
}

impl<'a> Iterator for GroupIter<'a>{
    type Item = IdProperty<'a>;

    fn next(&mut self) -> Option<IdProperty<'a>>{
        self.iter.next().and_then(|obj| IdProperty::new(obj).ok())
    }
}

// pub struct ArrayGroup<'a, AddressType: 'a>{
//     addresses: &'a [AddressType],
//     array: Object<'a>,
// }

// impl<'a, AddressType: 'a + ToPrimitive> ArrayGroup<'a, AddressType>{
//     pub fn get(&self, pos: usize) -> Option<Group<'a>>{
//         self.addresses.get(pos)
//             .and_then(|addr| self.array.object_by_addr(addr.to_u64().unwrap()))
//             .map(|object| Group{list: List{ object }})
//     }
// }

#[derive(Debug,Clone,Eq,PartialEq,Ord,PartialOrd,Hash)]
pub struct Error(pub String);

pub type Result<T> = result::Result<T,Error>;

impl convert::From<String> for Error{
    fn from(msg: String) -> Error{
        Error(msg)
    }
}

impl Error {
    pub fn msg(&self) -> String{
        self.0.clone()
    }
}

impl Display for Error{
    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result{
        fmt.write_str(&self.0)
    }
}

impl error::Error for Error{
    fn description(&self) -> &str{
        &self.0
    }
}