wow-wdt 0.7.0

Parser, validator, and converter for World of Warcraft WDT (World Data Table) files
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! WDT chunk implementations

use crate::error::{Error, Result};
use std::io::{Read, Write};

pub mod maid;
pub mod mphd;

// Re-export chunk types
pub use maid::MaidChunk;
pub use mphd::{MphdChunk, MphdFlags};

/// WDT file version (always 18)
pub const WDT_VERSION: u32 = 18;

/// Map dimensions (64x64 grid)
pub const WDT_MAP_SIZE: usize = 64;

/// Total number of tiles
pub const WDT_TILE_COUNT: usize = WDT_MAP_SIZE * WDT_MAP_SIZE;

/// Chunk header size (magic + size)
pub const CHUNK_HEADER_SIZE: usize = 8;

/// Common trait for all chunks
pub trait Chunk: Sized {
    /// Get the chunk magic bytes
    fn magic() -> &'static [u8; 4];

    /// Get the expected chunk size (None for variable-sized chunks)
    fn expected_size() -> Option<usize> {
        None
    }

    /// Read chunk data from a reader (after magic and size have been read)
    fn read(reader: &mut impl Read, size: usize) -> Result<Self>;

    /// Write chunk data to a writer
    fn write(&self, writer: &mut impl Write) -> Result<()>;

    /// Get the size of the chunk data (excluding header)
    fn size(&self) -> usize;

    /// Write the complete chunk including header
    fn write_chunk(&self, writer: &mut impl Write) -> Result<()> {
        writer.write_all(Self::magic())?;
        writer.write_all(&(self.size() as u32).to_le_bytes())?;
        self.write(writer)?;
        Ok(())
    }
}

/// MVER chunk - Version information
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MverChunk {
    pub version: u32,
}

impl MverChunk {
    pub fn new() -> Self {
        Self {
            version: WDT_VERSION,
        }
    }
}

impl Default for MverChunk {
    fn default() -> Self {
        Self::new()
    }
}

impl Chunk for MverChunk {
    fn magic() -> &'static [u8; 4] {
        b"REVM" // 'MVER' reversed
    }

    fn expected_size() -> Option<usize> {
        Some(4)
    }

    fn read(reader: &mut impl Read, size: usize) -> Result<Self> {
        if size != 4 {
            return Err(Error::InvalidChunkSize {
                chunk: "MVER".to_string(),
                expected: 4,
                found: size,
            });
        }

        let mut buf = [0u8; 4];
        reader.read_exact(&mut buf)?;
        let version = u32::from_le_bytes(buf);
        if version != WDT_VERSION {
            return Err(Error::InvalidVersion(version));
        }

        Ok(Self { version })
    }

    fn write(&self, writer: &mut impl Write) -> Result<()> {
        writer.write_all(&self.version.to_le_bytes())?;
        Ok(())
    }

    fn size(&self) -> usize {
        4
    }
}

/// MAIN chunk entry - Tile information
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MainEntry {
    pub flags: u32,
    pub area_id: u32,
}

impl MainEntry {
    pub fn new() -> Self {
        Self {
            flags: 0,
            area_id: 0,
        }
    }

    /// Check if this tile has ADT data
    pub fn has_adt(&self) -> bool {
        (self.flags & 0x0001) != 0
    }

    /// Set whether this tile has ADT data
    pub fn set_has_adt(&mut self, has_adt: bool) {
        if has_adt {
            self.flags |= 0x0001;
        } else {
            self.flags &= !0x0001;
        }
    }
}

impl Default for MainEntry {
    fn default() -> Self {
        Self::new()
    }
}

/// MAIN chunk - Map tile information
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MainChunk {
    pub entries: Vec<Vec<MainEntry>>,
}

impl MainChunk {
    pub fn new() -> Self {
        let mut entries = Vec::with_capacity(WDT_MAP_SIZE);
        for _ in 0..WDT_MAP_SIZE {
            let mut row = Vec::with_capacity(WDT_MAP_SIZE);
            for _ in 0..WDT_MAP_SIZE {
                row.push(MainEntry::new());
            }
            entries.push(row);
        }
        Self { entries }
    }

    /// Get entry at coordinates
    pub fn get(&self, x: usize, y: usize) -> Option<&MainEntry> {
        self.entries.get(y).and_then(|row| row.get(x))
    }

    /// Get mutable entry at coordinates
    pub fn get_mut(&mut self, x: usize, y: usize) -> Option<&mut MainEntry> {
        self.entries.get_mut(y).and_then(|row| row.get_mut(x))
    }

    /// Count tiles with ADT data
    pub fn count_existing_tiles(&self) -> usize {
        self.entries
            .iter()
            .flat_map(|row| row.iter())
            .filter(|entry| entry.has_adt())
            .count()
    }
}

impl Default for MainChunk {
    fn default() -> Self {
        Self::new()
    }
}

impl Chunk for MainChunk {
    fn magic() -> &'static [u8; 4] {
        b"NIAM" // 'MAIN' reversed
    }

    fn expected_size() -> Option<usize> {
        Some(WDT_TILE_COUNT * 8)
    }

    fn read(reader: &mut impl Read, size: usize) -> Result<Self> {
        let expected = WDT_TILE_COUNT * 8;
        if size != expected {
            return Err(Error::InvalidChunkSize {
                chunk: "MAIN".to_string(),
                expected,
                found: size,
            });
        }

        let mut entries = Vec::with_capacity(WDT_MAP_SIZE);
        for _y in 0..WDT_MAP_SIZE {
            let mut row = Vec::with_capacity(WDT_MAP_SIZE);
            for _x in 0..WDT_MAP_SIZE {
                let mut buf = [0u8; 4];
                reader.read_exact(&mut buf)?;
                let flags = u32::from_le_bytes(buf);
                reader.read_exact(&mut buf)?;
                let area_id = u32::from_le_bytes(buf);
                row.push(MainEntry { flags, area_id });
            }
            entries.push(row);
        }

        Ok(Self { entries })
    }

    fn write(&self, writer: &mut impl Write) -> Result<()> {
        for row in &self.entries {
            for entry in row {
                writer.write_all(&entry.flags.to_le_bytes())?;
                writer.write_all(&entry.area_id.to_le_bytes())?;
            }
        }
        Ok(())
    }

    fn size(&self) -> usize {
        WDT_TILE_COUNT * 8
    }
}

/// MWMO chunk - World Map Object filenames
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MwmoChunk {
    pub filenames: Vec<String>,
}

impl MwmoChunk {
    pub fn new() -> Self {
        Self {
            filenames: Vec::new(),
        }
    }

    /// Add a WMO filename
    pub fn add_filename(&mut self, filename: String) {
        self.filenames.push(filename);
    }

    /// Check if chunk is empty
    pub fn is_empty(&self) -> bool {
        self.filenames.is_empty()
    }
}

impl Default for MwmoChunk {
    fn default() -> Self {
        Self::new()
    }
}

impl Chunk for MwmoChunk {
    fn magic() -> &'static [u8; 4] {
        b"OMWM" // 'MWMO' reversed
    }

    fn read(reader: &mut impl Read, size: usize) -> Result<Self> {
        if size == 0 {
            return Ok(Self::new());
        }

        // Read all data
        let mut data = vec![0u8; size];
        reader.read_exact(&mut data)?;

        // Split by null terminators
        let mut filenames = Vec::new();
        let mut current = Vec::new();

        for &byte in &data {
            if byte == 0 {
                if !current.is_empty() {
                    let filename =
                        String::from_utf8(current.clone()).map_err(|e| Error::StringError {
                            context: "MWMO filename".to_string(),
                            message: e.to_string(),
                        })?;
                    filenames.push(filename);
                    current.clear();
                }
            } else {
                current.push(byte);
            }
        }

        // Handle case where data doesn't end with null
        if !current.is_empty() {
            let filename = String::from_utf8(current).map_err(|e| Error::StringError {
                context: "MWMO filename".to_string(),
                message: e.to_string(),
            })?;
            filenames.push(filename);
        }

        Ok(Self { filenames })
    }

    fn write(&self, writer: &mut impl Write) -> Result<()> {
        for filename in &self.filenames {
            writer.write_all(filename.as_bytes())?;
            writer.write_all(&[0])?; // Null terminator
        }
        Ok(())
    }

    fn size(&self) -> usize {
        self.filenames
            .iter()
            .map(|f| f.len() + 1) // +1 for null terminator
            .sum()
    }
}

/// MODF entry - Map Object Definition
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ModfEntry {
    pub id: u32,
    pub unique_id: u32,
    pub position: [f32; 3],
    pub rotation: [f32; 3],
    pub lower_bounds: [f32; 3],
    pub upper_bounds: [f32; 3],
    pub flags: u16,
    pub doodad_set: u16,
    pub name_set: u16,
    pub scale: u16,
}

impl ModfEntry {
    pub fn new() -> Self {
        Self {
            id: 0,
            unique_id: 0xFFFFFFFF, // -1, common in early versions
            position: [0.0; 3],
            rotation: [0.0; 3],
            lower_bounds: [0.0; 3],
            upper_bounds: [0.0; 3],
            flags: 0,
            doodad_set: 0,
            name_set: 0,
            scale: 0, // 0 in early versions, 1024 (1.0) in later
        }
    }
}

impl Default for ModfEntry {
    fn default() -> Self {
        Self::new()
    }
}

/// MODF chunk - Map Object Definitions
#[derive(Debug, Clone, PartialEq)]
pub struct ModfChunk {
    pub entries: Vec<ModfEntry>,
}

impl ModfChunk {
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }

    /// Add an entry
    pub fn add_entry(&mut self, entry: ModfEntry) {
        self.entries.push(entry);
    }
}

impl Default for ModfChunk {
    fn default() -> Self {
        Self::new()
    }
}

impl Chunk for ModfChunk {
    fn magic() -> &'static [u8; 4] {
        b"FDOM" // 'MODF' reversed
    }

    fn read(reader: &mut impl Read, size: usize) -> Result<Self> {
        if !size.is_multiple_of(64) {
            return Err(Error::InvalidChunkData {
                chunk: "MODF".to_string(),
                message: format!("Size {size} is not a multiple of 64"),
            });
        }

        let count = size / 64;
        let mut entries = Vec::with_capacity(count);

        for _ in 0..count {
            let mut buf = [0u8; 4];
            reader.read_exact(&mut buf)?;
            let id = u32::from_le_bytes(buf);
            reader.read_exact(&mut buf)?;
            let unique_id = u32::from_le_bytes(buf);

            let mut position = [0.0f32; 3];
            for item in &mut position {
                let mut buf = [0u8; 4];
                reader.read_exact(&mut buf)?;
                *item = f32::from_le_bytes(buf);
            }

            let mut rotation = [0.0f32; 3];
            for item in &mut rotation {
                let mut buf = [0u8; 4];
                reader.read_exact(&mut buf)?;
                *item = f32::from_le_bytes(buf);
            }

            let mut lower_bounds = [0.0f32; 3];
            for item in &mut lower_bounds {
                let mut buf = [0u8; 4];
                reader.read_exact(&mut buf)?;
                *item = f32::from_le_bytes(buf);
            }

            let mut upper_bounds = [0.0f32; 3];
            for item in &mut upper_bounds {
                let mut buf = [0u8; 4];
                reader.read_exact(&mut buf)?;
                *item = f32::from_le_bytes(buf);
            }

            let mut buf2 = [0u8; 2];
            reader.read_exact(&mut buf2)?;
            let flags = u16::from_le_bytes(buf2);
            reader.read_exact(&mut buf2)?;
            let doodad_set = u16::from_le_bytes(buf2);
            reader.read_exact(&mut buf2)?;
            let name_set = u16::from_le_bytes(buf2);
            reader.read_exact(&mut buf2)?;
            let scale = u16::from_le_bytes(buf2);

            entries.push(ModfEntry {
                id,
                unique_id,
                position,
                rotation,
                lower_bounds,
                upper_bounds,
                flags,
                doodad_set,
                name_set,
                scale,
            });
        }

        Ok(Self { entries })
    }

    fn write(&self, writer: &mut impl Write) -> Result<()> {
        for entry in &self.entries {
            writer.write_all(&entry.id.to_le_bytes())?;
            writer.write_all(&entry.unique_id.to_le_bytes())?;

            for &v in &entry.position {
                writer.write_all(&v.to_le_bytes())?;
            }

            for &v in &entry.rotation {
                writer.write_all(&v.to_le_bytes())?;
            }

            for &v in &entry.lower_bounds {
                writer.write_all(&v.to_le_bytes())?;
            }

            for &v in &entry.upper_bounds {
                writer.write_all(&v.to_le_bytes())?;
            }

            writer.write_all(&entry.flags.to_le_bytes())?;
            writer.write_all(&entry.doodad_set.to_le_bytes())?;
            writer.write_all(&entry.name_set.to_le_bytes())?;
            writer.write_all(&entry.scale.to_le_bytes())?;
        }
        Ok(())
    }

    fn size(&self) -> usize {
        self.entries.len() * 64
    }
}