project-wormhole-esm 0.1.0

ESM file format parser for Project Wormhole
Documentation
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
use crate::dev::*;


// TODO: Verify data, just because it parses doesn't mean it's correct!
#[derive(Debug)]
pub struct VirtualMachineAdapter {
    pub version: i16,
    pub object_format: i16,
    pub script_count: u16,
    pub scripts: Vec<VMADScriptEntry>
}


impl Parse<&[u8]> for VirtualMachineAdapter {
    fn parse(i: &[u8]) -> IResult<&[u8], Self, nom::error::Error<&[u8]>> {
        let (i, version) = le_i16(i)?;

        #[cfg(debug_assertions)]
        {
            if version < 4 {
                println!("Parsing VMAD with version {}", version);
            }
        }


        let (i, object_format) = le_i16(i)?;
        let (i, script_count) = le_u16(i)?;
        
        let mut loop_count = 0;
        let mut scripts = Vec::new();
        let mut remaining = i;
        let mut depth = 0;

        // for debugging
        // if script_count > 0 {
        //     println!("VMAD Header: version: {}, format: {}, script_count: {}", version, object_format, script_count);
        // }

        depth += 1;

        while loop_count < script_count {
            let (i_new, script) = VMADScriptEntry::parse_versioned(remaining, version)?;
            scripts.push(script);
            loop_count += 1;
            remaining = i_new;
        }

        Ok((remaining, VirtualMachineAdapter { version, object_format, script_count, scripts }))
    }
}


#[derive(Debug)]
pub struct VMADScriptEntry {
    pub script_name: SizedString16,
    pub flags: VMADScriptFlags,
    pub property_count: u16,
    pub properties: Vec<VMADPropertyEntry>,
    pub fragments: Vec<u8>
}

impl ParseVersioned<i16> for VMADScriptEntry {
    fn parse_versioned(i: &[u8], version: i16) -> IResult<&[u8], Self, nom::error::Error<&[u8]>> {
        let (i, script_name) = SizedString16::parse(i)?;
        //println!("Parsed VMAD script name: {}", script_name);
        let (i, flags) = if version >= 4 {
            VMADScriptFlags::parse(i)?
        } else {
            (i, VMADScriptFlags::empty())
        };
        let (i, property_count) = le_u16(i)?;
        if property_count == 0 {
            return Ok((i, VMADScriptEntry { script_name, flags, property_count, properties: Vec::new(), fragments: Vec::new() }) )
        }
        let (i, properties) = nom::multi::count(VMADPropertyEntry::parse, property_count as usize)(i)?;

        Ok((i, VMADScriptEntry { script_name, flags, property_count, properties, fragments: Vec::new() }) )
    }

    fn parse_versioned_depth(i: &[u8], version: i16, mut depth: u8) -> IResult<&[u8], Self, nom::error::Error<&[u8]>> {
        let (i, script_name) = SizedString16::parse(i)?;

        let (i, flags) = if version >= 4 {
            VMADScriptFlags::parse(i)?
        } else {
            (i, VMADScriptFlags::empty())
        };
        

        let (i, property_count) = le_u16(i)?;

        println!("{}VMAD Script Entry: name: {}, flags: {:?}, property_count: {}", depth_to_space(depth), script_name, flags, property_count);

        depth += 1;

        if property_count == 0 {
            return Ok((i, VMADScriptEntry { script_name, flags, property_count, properties: Vec::new(), fragments: Vec::new() }) )
        }

        let mut loop_count = 0;
        let mut properties = Vec::new();
        let mut remaining = i;
        while loop_count < property_count {
            let (i_new, property) = VMADPropertyEntry::parse(remaining)?;
            properties.push(property);
            loop_count += 1;
            remaining = i_new;
        }

        Ok((remaining, VMADScriptEntry { script_name, flags, property_count, properties, fragments: Vec::new() }) )
    }
}


// impl Parse<&[u8]> for VMADScriptEntry {
//     fn parse(i: &[u8]) -> IResult<&[u8], Self, nom::error::Error<&[u8]>> {
//         let (i, script_name) = SizedString16::parse(i)?;
//         //println!("Parsed VMAD script name: {}", script_name);
//         let (i, status) = le_u8(i)?;
//         let (i, property_count) = le_u16(i)?;
//         let (i, properties) = nom::multi::count(VMADPropertyEntry::parse, property_count as usize)(i)?;

//         Ok((i, VMADScriptEntry { script_name, status, property_count, properties, fragments: Vec::new() }) )
//     }
// }

#[derive(Debug)]
pub struct VMADPropertyEntry {
    pub name: SizedString16,
    pub type_: VMADPropertyType,
    pub flags: u8,
    pub value: VMADPropertyValue
}


impl Parse<&[u8]> for VMADPropertyEntry {
    fn parse(i: &[u8]) -> IResult<&[u8], Self, nom::error::Error<&[u8]>> {
        let (i, name) = SizedString16::parse(i)?;
        let (i, type_) = VMADPropertyType::parse(i)?;
        let (i, flags) = le_u8(i)?;

        match type_ {
            VMADPropertyType::Null => {
                // Null
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::Null }))
            }
            VMADPropertyType::Object => {
                // Object
                let (i, v1) = le_u16(i)?;
                let (i, v2) = le_u16(i)?;
                let (i, v3) = FormId::parse(i)?;
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::Object(VMADObjectRef::V2((v1, v2, v3))) }))
            },
            VMADPropertyType::String => {
                // String
                let (i, value) = SizedString16::parse(i)?;
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::String(value) }))
            },
            VMADPropertyType::Int => {
                // Int
                let (i, value) = le_i32(i)?;
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::Int(value) }))
            },
            VMADPropertyType::Float => {
                // Float
                let (i, value) = le_f32(i)?;
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::Float(value) }))
            },
            VMADPropertyType::Bool => {
                // Bool
                let (i, value) = le_u8(i)?;
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::Bool(value != 0) }))
            },
            // 6 => {
            //     // Null
            //     Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::Null }))
            // },
            VMADPropertyType::Struct => {
                // Unsupported
                let (i, value) = VMADPropertyEntry::parse(i)?;
                println!("{:?}", value);
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::Struct(Box::new(value)) }))
            }
            VMADPropertyType::ObjectArray => {
                // Object Array
                let (i, item_count) = le_u32(i)?;
                let (i, values) = nom::multi::count(FormId::parse, item_count as usize)(i)?;
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::ObjectArray(values) }))
            },
            VMADPropertyType::StringArray => {
                // String Array
                let (i, item_count) = le_u32(i)?;
                let (i, values) = nom::multi::count(SizedString16::parse, item_count as usize)(i)?;
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::StringArray(values) }))
            },
            VMADPropertyType::IntArray => {
                // Int Array
                let (i, item_count) = le_u32(i)?;
                let (i, values) = nom::multi::count(le_i32, item_count as usize)(i)?;
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::IntArray(values) }))
            },
            VMADPropertyType::FloatArray => {
                // Float Array
                let (i, item_count) = le_u32(i)?;
                let (i, values) = nom::multi::count(le_f32, item_count as usize)(i)?;
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::FloatArray(values) }))
            },
            VMADPropertyType::BoolArray => {
                // Bool Array
                let (i, item_count) = le_u32(i)?;
                let (i, raw_values) = nom::multi::count(le_u8, item_count as usize)(i)?;
                let values: Vec<bool> = raw_values.iter().map(|&b| b != 0).collect();
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::BoolArray(values) }))
            },
            VMADPropertyType::VarArray => {
                // Var Array
                panic!("VarArray parsing not implemented yet!");
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::VarArray}))
            },
            VMADPropertyType::StructArray => {
                // Struct Array
                let (i, item_count) = le_u32(i)?;
                let (i, values) = nom::multi::count(SubStruct::parse, item_count as usize)(i)?;
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::StructArray(values)}))
            }
            _ => {

                #[cfg(debug_assertions)]
                {
                    println!("Encountered unsupported VMAD property type: {:?} for {}", type_, name);
                }


                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::Unsupported}))
            }
            
        }

    }
}

impl ParseVersioned<i16> for VMADPropertyEntry {
    fn parse_versioned(i: &[u8], version: i16) -> IResult<&[u8], Self, nom::error::Error<&[u8]>> {
        todo!()
    }

    fn parse_versioned_depth(i: &[u8], version: i16, mut depth: u8) -> IResult<&[u8], Self, nom::error::Error<&[u8]>> {
        let (i, name) = SizedString16::parse(i)?;
        let (i, type_) = VMADPropertyType::parse(i)?;
        let (i, flags) = le_u8(i)?;

        println!("{}VMAD property name: {}, type: {:?}, flags: {}", depth_to_space(depth), name, type_, flags);
        depth += 1;

        match type_ {
            VMADPropertyType::Null => {
                // Null
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::Null }))
            }
            VMADPropertyType::Object => {
                // Object
                let (i, v1) = le_u16(i)?;
                let (i, v2) = le_u16(i)?;
                let (i, v3) = FormId::parse_le(i)?;
                
                println!("{}VMAD property object ref: ({}, {}, {})", depth_to_space(depth), v1, v2, v3);

                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::Object(VMADObjectRef::V2((v1, v2, v3))) }))
            },
            VMADPropertyType::String => {
                // String
                let (i, value) = SizedString16::parse(i)?;
                println!("{}VMAD property string: {}", depth_to_space(depth), value);
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::String(value) }))
            },
            VMADPropertyType::Int => {
                // Int
                let (i, value) = le_i32(i)?;
                println!("{}VMAD property int: {}", depth_to_space(depth), value);
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::Int(value) }))
            },
            VMADPropertyType::Float => {
                // Float
                let (i, value) = le_f32(i)?;
                println!("{}VMAD property float: {}", depth_to_space(depth), value);
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::Float(value) }))
            },
            VMADPropertyType::Bool => {
                // Bool
                let (i, value) = le_u8(i)?;
                println!("{}VMAD property bool: {}", depth_to_space(depth), value != 0);
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::Bool(value != 0) }))
            },
            // 6 => {
            //     // Null
            //     Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::Null }))
            // },
            VMADPropertyType::Struct => {
                // Unsupported
                let (i, value) = VMADPropertyEntry::parse(i)?;
                println!("{}{:?}", depth_to_space(depth), value);
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::Struct(Box::new(value)) }))
            }
            VMADPropertyType::ObjectArray => {
                // Object Array
                let (i, item_count) = le_u32(i)?;
                let (i, values) = nom::multi::count(FormId::parse, item_count as usize)(i)?;
                println!("{}VMAD property object array of count {}", depth_to_space(depth), item_count);
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::ObjectArray(values) }))
            },
            VMADPropertyType::StringArray => {
                // String Array
                let (i, item_count) = le_u32(i)?;
                let (i, values) = nom::multi::count(SizedString16::parse, item_count as usize)(i)?;
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::StringArray(values) }))
            },
            VMADPropertyType::IntArray => {
                // Int Array
                let (i, item_count) = le_u32(i)?;
                let (i, values) = nom::multi::count(le_i32, item_count as usize)(i)?;
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::IntArray(values) }))
            },
            VMADPropertyType::FloatArray => {
                // Float Array
                let (i, item_count) = le_u32(i)?;
                let (i, values) = nom::multi::count(le_f32, item_count as usize)(i)?;
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::FloatArray(values) }))
            },
            VMADPropertyType::BoolArray => {
                // Bool Array
                let (i, item_count) = le_u32(i)?;
                let (i, raw_values) = nom::multi::count(le_u8, item_count as usize)(i)?;
                let values: Vec<bool> = raw_values.iter().map(|&b| b != 0).collect();
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::BoolArray(values) }))
            },
            VMADPropertyType::VarArray => {
                // Var Array
                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::VarArray}))
            },
            VMADPropertyType::StructArray => {
                // Struct Array
                let (i, item_count) = le_u32(i)?;
                println!("{}VMAD property struct array count {}", depth_to_space(depth), item_count);

                // let (i, sub_count) = le_u32(i)?;
                // println!("{}VMAD property struct array sub-count {}", depth_to_space(depth), sub_count);

                // let (i, st) = SizedString16::parse(i)?;
                // println!("{}VMAD property struct array type name: {}", depth_to_space(depth), st);

                // todo!()
                if let Ok((i, values)) = nom::multi::count(SubStruct::parse, item_count as usize)(i) {
                    println!("{}{:?}", depth_to_space(depth), values);
                    Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::StructArray(values)}))    
                } else {
                    panic!("{}Failed to parse struct array items!", depth_to_space(depth));
                    Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::StructArray(Vec::new())}))
                }
            }
            _ => {

                #[cfg(debug_assertions)]
                {
                    println!("Encountered unsupported VMAD property type: {:?} for {}", type_, name);
                }


                Ok((i, VMADPropertyEntry { name, type_, flags, value: VMADPropertyValue::Unsupported}))
            }
        }
    }
}


// ====================================================================================================

#[derive(Debug)]
pub enum VMADPropertyValue {
    Null, // 0, 6
    Object(VMADObjectRef), // 1
    String(SizedString16), // 2
    Int(i32), // 3
    Float(f32), // 4
    Bool(bool), // 5
    Struct(Box<VMADPropertyEntry>), // 7
    ObjectArray(Vec<FormId>), // 11
    StringArray(Vec<SizedString16>), // 12
    IntArray(Vec<i32>), // 13
    FloatArray(Vec<f32>), // 14
    BoolArray(Vec<bool>), // 15
    VarArray, // 16
    StructArray(Vec<SubStruct>), // 17
    Unsupported
}

// ====================================================================================================

#[derive(Debug, NomLE)]
#[repr(u8)]
pub enum VMADPropertyType {
    // Singles
    Null = 0,
    Object = 1,
    String = 2,
    Int = 3,
    Float = 4,
    Bool = 5,
    Struct = 7,
    Var = 8,
    // Lists
    ObjectArray = 11,
    StringArray = 12,
    IntArray = 13,
    FloatArray = 14,
    BoolArray = 15,
    VarArray = 16,
    StructArray = 17,
    Unsupported
}

// ====================================================================================================

#[derive(Debug)]
pub enum VMADObjectRef {
    V1((FormId, u16, u16)),
    V2((u16, u16, FormId))
}


pub fn depth_to_space(depth: u8) -> String {
    let mut s = String::new();
    for _ in 0..depth {
        s.push_str("  ");
    }
    s
}


bitflags::bitflags! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct VMADScriptFlags: u8 {
        const NONE = 0x00;
        const EDITED = 0x01;
        const UNKNOWN1 = 0x02;
        const REMOVED = 0x04;
    }
}

impl Parse<&[u8]> for VMADScriptFlags {
    fn parse(i: &[u8]) -> IResult<&[u8], Self, nom::error::Error<&[u8]>> {
        let (i, raw) = le_u8(i)?;
        Ok((i, VMADScriptFlags::from_bits_truncate(raw)))
    }
}


// ====================================================================================================

#[derive(Debug, NomLE)]
pub struct SubStruct {
    #[nom(LengthCount = "le_u32")]
    pub values: Vec<VMADPropertyEntry>
}