-
Notifications
You must be signed in to change notification settings - Fork 4
/
mod.rs
389 lines (351 loc) · 14.3 KB
/
mod.rs
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
pub mod fragments;
mod strings;
use core::fmt::{Debug, Error, Formatter};
use nom::bytes::complete::take;
use nom::multi::count;
use nom::number::complete::le_u32;
use nom::sequence::tuple;
use nom::IResult;
pub use fragments::*;
use strings::{StringHash, StringReference};
#[derive(Debug)]
pub struct WldDoc {
header: WldHeader,
strings: StringHash,
fragments: Vec<Box<FragmentType>>,
}
impl Debug for dyn Fragment + 'static {
fn fmt(&self, _f: &mut Formatter<'_>) -> Result<(), Error> {
Ok(())
}
}
impl WldDoc {
pub fn parse(input: &[u8]) -> IResult<&[u8], WldDoc> {
let (i, header) = WldHeader::parse(input)?;
let (remaining, (string_hash_data, fragment_headers)) = tuple((
take(header.string_hash_size),
count(FragmentHeader::parse, header.fragment_count as usize),
))(i)?;
let strings = StringHash::new(string_hash_data);
//use std::fs::File;
//use std::io::prelude::*;
//for (i, header) in fragment_headers.iter().enumerate() {
// let mut file = File::create(format!(
// "fixtures/fragments/gfaydark_obj/{:04}-{:#04x}.frag",
// i, header.fragment_type
// ))
// .unwrap();
// file.write_all(header.field_data).unwrap();
//}
let fragments = fragment_headers.iter().map(|h| h.parse_body()).collect();
Ok((
remaining,
WldDoc {
header,
strings,
fragments,
},
))
}
/// Get a string given a string reference
pub fn get_string(&self, string_reference: StringReference) -> Option<&str> {
self.strings.get(string_reference)
}
/// Get a fragment given a fragment reference.
pub fn get<T: 'static + Fragment>(&self, fragment_ref: &FragmentRef<T>) -> Option<&T> {
match fragment_ref {
FragmentRef::Name(_, _) => self.get_by_name_ref(fragment_ref),
FragmentRef::Index(_, _) => self.get_by_index_ref(fragment_ref),
}
}
/// Get a fragment given an index
pub fn at(&self, idx: usize) -> Option<&FragmentType> {
self.fragments.get(idx).map(|f| f.as_ref())
}
/// Iterate over all fragments of a specific type
pub fn fragment_iter<'a, T: 'static + Fragment>(&'a self) -> impl Iterator<Item = &'a T> + '_ {
self.fragments
.iter()
.filter_map(|f| f.as_any().downcast_ref::<T>())
}
/// Iterate over all fragments
pub fn iter<'a>(&'a self) -> impl Iterator<Item = &'a Box<FragmentType>> + '_ {
self.fragments.iter()
}
fn get_by_index_ref<T: 'static + Fragment>(&self, fragment_ref: &FragmentRef<T>) -> Option<&T> {
let idx = if let FragmentRef::Index(idx, _) = fragment_ref {
idx
} else {
return None;
};
self.fragments
.get((idx - 1) as usize)?
.as_any()
.downcast_ref()
}
fn get_by_name_ref<T: 'static + Fragment>(&self, fragment_ref: &FragmentRef<T>) -> Option<&T> {
let name_ref = if let FragmentRef::Name(name_ref, _) = fragment_ref {
*name_ref
} else {
return None;
};
if let Some(target_name) = self.strings.get(name_ref) {
self.fragments
.iter()
.find(|f| self.strings.get(*f.name_ref()) == Some(target_name))?
.as_any()
.downcast_ref()
} else {
None
}
}
pub fn fragment_count(&self) -> usize {
self.fragments.len()
}
pub fn serialize(&self) -> Vec<u8> {
[
self.header.serialize(),
self.strings.serialize(),
self.fragments.iter().flat_map(|f| f.serialize()).collect(),
]
.concat()
}
}
/// This header is present at the beginning of every .wld file.
#[derive(Debug)]
struct WldHeader {
/// The file signature that signals that this is a .wld file.
magic: u32,
/// Two known versions of .wld file exist.
/// * The old format - `0x00015500`
/// * The new format - `0x1000C800`
version: u32,
/// The number of fragments in the .wld file minus 1
fragment_count: u32,
/// Believed to contain the number of 0x22 BSP region fragments in the file
header_3: u32,
/// _Unknown_ - Usually contains `0x000680D4`.
header_4: u32,
/// The size of the string hash in bytes.
string_hash_size: u32,
/// _Unknown_ - Possibly contains the number of fragments in the file minus the
/// number of 0x03 fragments, minus 6
header_6: u32,
}
impl WldHeader {
fn parse(input: &[u8]) -> IResult<&[u8], WldHeader> {
let (
remaining,
(magic, version, fragment_count, header_3, header_4, string_hash_size, header_6),
) = tuple((le_u32, le_u32, le_u32, le_u32, le_u32, le_u32, le_u32))(input)?;
Ok((
remaining,
WldHeader {
magic,
version,
fragment_count,
header_3,
header_4,
string_hash_size,
header_6,
},
))
}
pub fn serialize(&self) -> Vec<u8> {
[
&self.magic.to_le_bytes()[..],
&self.version.to_le_bytes()[..],
&self.fragment_count.to_le_bytes()[..],
&self.header_3.to_le_bytes()[..],
&self.header_4.to_le_bytes()[..],
&self.string_hash_size.to_le_bytes()[..],
&self.header_6.to_le_bytes()[..],
]
.concat()
}
}
type FragmentTypeId = u32;
#[derive(Debug)]
/// All fragments begin with the following header
pub struct FragmentHeader<'a> {
/// The size of the fragment in bytes. All fragments are padded such that `size`
/// is evenly divisible by 4 and Size should reflect the padded value.
pub size: u32,
/// The fragment type. This will typically be a value in the
/// range 0x03 to 0x37 and tells the file reader which specific kind of fragment
/// it is. Some fragment types are plain fragments and some are reference
/// fragments, the type determines which.
pub fragment_type: FragmentTypeId,
/// Each fragment may have a string name, stored in encoded form in the .wld
/// file string hash. `name_reference` provides a way to retrieve that name.
/// If the fragment has a string name, `name_reference` will contain the
/// negative value of the string’s index in the string hash.
///
/// For example, if the string is at position 31 in the string hash, then
/// `name_reference` should contain –31. Values greater than 0 mean that the
/// fragment doesn’t have a string name. Effectively, a value of 0 also means
/// that the fragment doesn’t have a string name, and the first byte in the string
/// hash is always preallocated to reflect this (it’s a null character that is
/// encoded along with everything else).
///
/// All fragments without a name will have a `name_reference` of 0.
/// The one exception being the 0x35 fragment which will always reference 0xFF000000.
pub field_data: &'a [u8],
}
impl<'a> FragmentHeader<'a> {
pub fn parse(input: &[u8]) -> IResult<&[u8], FragmentHeader> {
let (i, (size, fragment_type)) = tuple((le_u32, le_u32))(input)?;
let (remaining, field_data) = take(size)(i)?;
Ok((
remaining,
FragmentHeader {
size,
fragment_type,
field_data,
},
))
}
fn parse_body(&self) -> Box<FragmentType> {
match self.fragment_type {
AlternateMeshFragment::TYPE_ID => Box::new(FragmentType::AlternateMesh(
AlternateMeshFragment::parse(&self.field_data).unwrap().1,
)),
VertexColorReferenceFragment::TYPE_ID => Box::new(FragmentType::VertexColorReference(
VertexColorReferenceFragment::parse(&self.field_data)
.unwrap()
.1,
)),
VertexColorFragment::TYPE_ID => Box::new(FragmentType::VertexColor(
VertexColorFragment::parse(&self.field_data).unwrap().1,
)),
MeshAnimatedVerticesFragment::TYPE_ID => Box::new(FragmentType::MeshAnimatedVertices(
MeshAnimatedVerticesFragment::parse(&self.field_data)
.unwrap()
.1,
)),
MeshAnimatedVerticesReferenceFragment::TYPE_ID => {
Box::new(FragmentType::MeshAnimatedVerticesReference(
MeshAnimatedVerticesReferenceFragment::parse(&self.field_data)
.unwrap()
.1,
))
}
AmbientLightFragment::TYPE_ID => Box::new(FragmentType::AmbientLight(
AmbientLightFragment::parse(&self.field_data).unwrap().1,
)),
RegionFlagFragment::TYPE_ID => Box::new(FragmentType::RegionFlag(
RegionFlagFragment::parse(&self.field_data).unwrap().1,
)),
LightInfoFragment::TYPE_ID => Box::new(FragmentType::LightInfo(
LightInfoFragment::parse(&self.field_data).unwrap().1,
)),
LightSourceReferenceFragment::TYPE_ID => Box::new(FragmentType::LightSourceReference(
LightSourceReferenceFragment::parse(&self.field_data)
.unwrap()
.1,
)),
LightSourceFragment::TYPE_ID => Box::new(FragmentType::LightSource(
LightSourceFragment::parse(&self.field_data).unwrap().1,
)),
PolygonAnimationReferenceFragment::TYPE_ID => {
Box::new(FragmentType::PolygonAnimationReference(
PolygonAnimationReferenceFragment::parse(&self.field_data)
.unwrap()
.1,
))
}
PolygonAnimationFragment::TYPE_ID => Box::new(FragmentType::PolygonAnimation(
PolygonAnimationFragment::parse(&self.field_data).unwrap().1,
)),
FirstFragment::TYPE_ID => Box::new(FragmentType::First(
FirstFragment::parse(&self.field_data).unwrap().1,
)),
ZoneUnknownFragment::TYPE_ID => Box::new(FragmentType::ZoneUnknown(
ZoneUnknownFragment::parse(&self.field_data).unwrap().1,
)),
SkeletonTrackSetReferenceFragment::TYPE_ID => {
Box::new(FragmentType::SkeletonTrackSetReference(
SkeletonTrackSetReferenceFragment::parse(&self.field_data)
.unwrap()
.1,
))
}
CameraReferenceFragment::TYPE_ID => Box::new(FragmentType::CameraReference(
CameraReferenceFragment::parse(&self.field_data).unwrap().1,
)),
CameraFragment::TYPE_ID => Box::new(FragmentType::Camera(
CameraFragment::parse(&self.field_data).unwrap().1,
)),
TwoDimensionalObjectReferenceFragment::TYPE_ID => {
Box::new(FragmentType::TwoDimensionalObjectReference(
TwoDimensionalObjectReferenceFragment::parse(&self.field_data)
.unwrap()
.1,
))
}
TwoDimensionalObjectFragment::TYPE_ID => Box::new(FragmentType::TwoDimensionalObject(
TwoDimensionalObjectFragment::parse(&self.field_data)
.unwrap()
.1,
)),
ObjectLocationFragment::TYPE_ID => Box::new(FragmentType::ObjectLocation(
ObjectLocationFragment::parse(&self.field_data).unwrap().1,
)),
MobSkeletonPieceTrackReferenceFragment::TYPE_ID => {
Box::new(FragmentType::MobSkeletonPieceTrackReference(
MobSkeletonPieceTrackReferenceFragment::parse(&self.field_data)
.unwrap()
.1,
))
}
MobSkeletonPieceTrackFragment::TYPE_ID => {
Box::new(FragmentType::MobSkeletonPieceTrack(
MobSkeletonPieceTrackFragment::parse(&self.field_data)
.unwrap()
.1,
))
}
SkeletonTrackSetFragment::TYPE_ID => Box::new(FragmentType::SkeletonTrackSet(
SkeletonTrackSetFragment::parse(&self.field_data).unwrap().1,
)),
ModelFragment::TYPE_ID => Box::new(FragmentType::Model(
ModelFragment::parse(&self.field_data).unwrap().1,
)),
BspTreeFragment::TYPE_ID => Box::new(FragmentType::BspTree(
BspTreeFragment::parse(&self.field_data).unwrap().1,
)),
BspRegionFragment::TYPE_ID => Box::new(FragmentType::BspRegion(
BspRegionFragment::parse(&self.field_data).unwrap().1,
)),
MeshFragment::TYPE_ID => Box::new(FragmentType::Mesh(
MeshFragment::parse(&self.field_data).unwrap().1,
)),
MaterialListFragment::TYPE_ID => Box::new(FragmentType::MaterialList(
MaterialListFragment::parse(&self.field_data).unwrap().1,
)),
MaterialFragment::TYPE_ID => Box::new(FragmentType::Material(
MaterialFragment::parse(&self.field_data).unwrap().1,
)),
TextureReferenceFragment::TYPE_ID => Box::new(FragmentType::TextureReference(
TextureReferenceFragment::parse(&self.field_data).unwrap().1,
)),
MeshReferenceFragment::TYPE_ID => Box::new(FragmentType::MeshReference(
MeshReferenceFragment::parse(&self.field_data).unwrap().1,
)),
TextureFragment::TYPE_ID => Box::new(FragmentType::Texture(
TextureFragment::parse(&self.field_data).unwrap().1,
)),
TextureImagesFragment::TYPE_ID => Box::new(FragmentType::TextureImages(
TextureImagesFragment::parse(&self.field_data).unwrap().1,
)),
_ => panic!("Unknown fragment type"),
}
}
pub fn serialize(&self) -> Vec<u8> {
[
&self.size.to_le_bytes()[..],
&self.fragment_type.to_le_bytes()[..],
]
.concat()
}
}