/
wad.cpp
524 lines (441 loc) · 15.8 KB
/
wad.cpp
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
/**
* @file wadfile.cpp
* WAD archives. @ingroup fs
*
* @author Copyright © 2003-2012 Jaakko Keränen <jaakko.keranen@iki.fi>
* @author Copyright © 2006-2012 Daniel Swanson <danij@dengine.net>
* @author Copyright © 2006 Jamie Jones <jamie_jones_au@yahoo.com.au>
* @author Copyright © 1993-1996 by id Software, Inc.
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA</small>
*/
#include "de_base.h"
#include "de_filesys.h"
#include "lumpcache.h"
#include "pathdirectory.h"
#include "wad.h"
#include <vector>
#include <de/ByteOrder>
#include <de/Error>
#include <de/Log>
#include <de/memoryzone.h>
static QString invalidIndexMessage(int invalidIdx, int lastValidIdx);
namespace de {
/// The following structures are used to read data directly from WAD files.
#pragma pack(1)
typedef struct {
char identification[4];
int32_t lumpRecordsCount;
int32_t lumpRecordsOffset;
} wadheader_t;
typedef struct {
int32_t filePos;
int32_t size;
char name[8];
} wadlumprecord_t;
#pragma pack()
class WadFile : public File1
{
public:
WadFile::WadFile(FileHandle& hndl, char const* path, FileInfo const& info, File1* container)
: File1(path, hndl, info, container), crc_(0)
{}
uint crc() const { return crc_; }
/**
* Calculate a simple CRC for the lump.
*
* @note This algorithm should be replaced if the CRC is needed for anything
* critical/meaningful.
*
* @attention Calls back into the owning container instance to obtain the name.
*/
WadFile& updateCRC()
{
crc_ = uint(info_.size);
de::PathDirectoryNode const& node = container().lumpDirectoryNode(info_.lumpIdx);
ddstring_t const* name = node.pathFragment();
int const nameLen = Str_Length(name);
for(int k = 0; k < nameLen; ++k)
{
crc_ += Str_At(name, k);
}
return *this;
}
private:
uint crc_;
};
struct Wad::Instance
{
Wad* self;
/// Number of lump records in the archived wad.
int arcRecordsCount;
/// Offset to the lump record table in the archived wad.
size_t arcRecordsOffset;
/// Directory containing structure and info records for all lumps.
PathDirectory* lumpDirectory;
/// LUT which maps logical lump indices to PathDirectoryNodes.
typedef std::vector<PathDirectoryNode*> LumpNodeLut;
LumpNodeLut* lumpNodeLut;
/// Lump data cache.
LumpCache* lumpCache;
Instance(Wad* d, FileHandle& file, const char* path)
: self(d),
arcRecordsCount(0),
arcRecordsOffset(0),
lumpDirectory(0),
lumpNodeLut(0),
lumpCache(0)
{
// Seek to the start of the header.
file.seek(0, SeekSet);
wadheader_t hdr;
if(!readArchiveHeader(file, hdr))
throw Wad::FormatError("Wad::Wad", QString("File %1 does not appear to be a known WAD format").arg(path));
arcRecordsCount = hdr.lumpRecordsCount;
arcRecordsOffset = hdr.lumpRecordsOffset;
}
~Instance()
{
if(lumpDirectory)
{
PathDirectory_Iterate(reinterpret_cast<pathdirectory_s*>(lumpDirectory), PCF_NO_BRANCH,
NULL, PATHDIRECTORY_NOHASH, clearWadFileWorker);
delete lumpDirectory;
}
if(lumpNodeLut) delete lumpNodeLut;
if(lumpCache) delete lumpCache;
}
static int clearWadFileWorker(pathdirectorynode_s* _node, void* /*parameters*/)
{
PathDirectoryNode* node = reinterpret_cast<PathDirectoryNode*>(_node);
WadFile* lump = reinterpret_cast<WadFile*>(node->userData());
if(lump)
{
// Detach our user data from this node.
node->setUserData(0);
delete lump;
}
return 0; // Continue iteration.
}
/// @pre @a file is positioned at the start of the header.
static bool readArchiveHeader(FileHandle& file, wadheader_t& hdr)
{
size_t readBytes = file.read((uint8_t*)&hdr, sizeof(wadheader_t));
if(!(readBytes < sizeof(wadheader_t)))
{
hdr.lumpRecordsCount = littleEndianByteOrder.toNative(hdr.lumpRecordsCount);
hdr.lumpRecordsOffset = littleEndianByteOrder.toNative(hdr.lumpRecordsOffset);
return true;
}
return false;
}
/// @return Length of the archived lump name in characters.
static int nameLength(wadlumprecord_t const& lrec)
{
int nameLen = 0;
while(nameLen < LUMPNAME_T_LASTINDEX && lrec.name[nameLen])
{ nameLen++; }
return nameLen;
}
/// Perform all translations and encodings to the archived lump name and write
/// the result to @a normName.
static void normalizeName(wadlumprecord_t const& lrec, ddstring_t* normName)
{
LOG_AS("Wad");
if(!normName) return;
Str_Clear(normName);
int nameLen = nameLength(lrec);
for(int i = 0; i < nameLen; ++i)
{
/// The Hexen demo on Mac uses the 0x80 on some lumps, maybe has significance?
/// @todo Ensure that this doesn't break other IWADs. The 0x80-0xff
/// range isn't normally used in lump names, right??
char ch = lrec.name[i] & 0x7f;
Str_AppendChar(normName, ch);
}
// Lump names allow characters the file system does not. Therefore they
// will be percent-encoded here and later decoded if/when necessary.
if(!Str_IsEmpty(normName))
{
Str_PercentEncode(normName);
}
else
{
/// We do not consider zero-length names to be valid, so replace with
/// with _something_.
/// @todo fixme: Handle this more elegantly...
Str_Set(normName, "________");
}
// All lumps are ordained with an extension if they don't have one.
char const* ext = F_FindFileExtension(Str_Text(normName));
if(!(ext && Str_Length(normName) > ext - Str_Text(normName) + 1))
{
Str_Append(normName, !Str_CompareIgnoreCase(normName, "DEHACKED")? ".deh" : ".lmp");
}
}
void readLumpDirectory()
{
LOG_AS("Wad");
if(arcRecordsCount <= 0) return;
// Already been here?
if(lumpDirectory) return;
// We'll load the lump directory using one continous read into a temporary
// local buffer before we process it into our runtime representation.
wadlumprecord_t* arcRecords = new wadlumprecord_t[arcRecordsCount];
self->handle_->seek(arcRecordsOffset, SeekSet);
self->handle_->read((uint8_t*)arcRecords, arcRecordsCount * sizeof(*arcRecords));
// Reserve a small work buffer for processing archived lump names.
ddstring_t absPath;
Str_Reserve(Str_Init(&absPath), LUMPNAME_T_LASTINDEX + 4/*.lmp*/);
// Intialize the directory.
lumpDirectory = new PathDirectory(PDF_ALLOW_DUPLICATE_LEAF);
// Build our runtime representation from the archived lump directory.
wadlumprecord_t const* arcRecord = arcRecords;
for(int i = 0; i < arcRecordsCount; ++i, arcRecord++)
{
// Determine the name for this lump in the VFS.
normalizeName(*arcRecord, &absPath);
F_PrependBasePath(&absPath, &absPath); // Make it absolute.
WadFile* lump =
new WadFile(*FileHandleBuilder::fromFileLump(*self, i, true/*don't buffer*/),
Str_Text(&absPath),
FileInfo(self->lastModified(), // Inherited from the container (note recursion).
i,
littleEndianByteOrder.toNative(arcRecord->filePos),
littleEndianByteOrder.toNative(arcRecord->size),
littleEndianByteOrder.toNative(arcRecord->size)),
self);
PathDirectoryNode* node = lumpDirectory->insert(Str_Text(&absPath));
node->setUserData(lump);
}
Str_Free(&absPath);
// We are finished with the temporary lump directory records.
delete[] arcRecords;
}
static int buildLumpNodeLutWorker(pathdirectorynode_s* _node, void* parameters)
{
PathDirectoryNode* node = reinterpret_cast<PathDirectoryNode*>(_node);
Instance* wadInst = (Instance*)parameters;
WadFile* lump = reinterpret_cast<WadFile*>(node->userData());
DENG2_ASSERT(lump && wadInst->self->isValidIndex(lump->info().lumpIdx)); // Sanity check.
(*wadInst->lumpNodeLut)[lump->info().lumpIdx] = node;
return 0; // Continue iteration.
}
void buildLumpNodeLut()
{
LOG_AS("Wad");
// Been here already?
if(lumpNodeLut) return;
lumpNodeLut = new LumpNodeLut(self->lumpCount());
if(!lumpDirectory) return;
PathDirectory_Iterate2(reinterpret_cast<pathdirectory_s*>(lumpDirectory), PCF_NO_BRANCH,
NULL, PATHDIRECTORY_NOHASH, buildLumpNodeLutWorker, (void*)this);
}
};
Wad::Wad(FileHandle& hndl, char const* path, FileInfo const& info, File1* container)
: File1(path, hndl, info, container)
{
d = new Instance(this, hndl, path);
}
Wad::~Wad()
{
clearLumpCache();
delete d;
}
bool Wad::isValidIndex(int lumpIdx)
{
return lumpIdx >= 0 && lumpIdx < lumpCount();
}
int Wad::lastIndex()
{
return lumpCount() - 1;
}
int Wad::lumpCount()
{
d->readLumpDirectory();
return d->lumpDirectory? d->lumpDirectory->size() : 0;
}
bool Wad::empty()
{
return !lumpCount();
}
de::PathDirectoryNode& Wad::lumpDirectoryNode(int lumpIdx)
{
if(!isValidIndex(lumpIdx)) throw NotFoundError("Wad::lumpDirectoryNode", invalidIndexMessage(lumpIdx, lastIndex()));
d->buildLumpNodeLut();
return *((*d->lumpNodeLut)[lumpIdx]);
}
ddstring_t const* Wad::lumpName(int lumpIdx)
{
LOG_AS("Wad::lumpName");
return lumpDirectoryNode(lumpIdx).pathFragment();
}
AutoStr* Wad::composeLumpPath(int lumpIdx, char delimiter)
{
if(!isValidIndex(lumpIdx)) return AutoStr_NewStd();
PathDirectoryNode& node = lumpDirectoryNode(lumpIdx);
return node.composePath(AutoStr_NewStd(), NULL, delimiter);
}
File1& Wad::lump(int lumpIdx)
{
LOG_AS("Wad");
if(!isValidIndex(lumpIdx)) throw NotFoundError("Wad::lump", invalidIndexMessage(lumpIdx, lastIndex()));
d->buildLumpNodeLut();
return *reinterpret_cast<WadFile*>((*d->lumpNodeLut)[lumpIdx]->userData());
}
Wad& Wad::clearCachedLump(int lumpIdx, bool* retCleared)
{
LOG_AS("Wad::clearCachedLump");
if(retCleared) *retCleared = false;
if(isValidIndex(lumpIdx))
{
if(d->lumpCache)
{
d->lumpCache->remove(lumpIdx, retCleared);
}
else
{
LOG_DEBUG("LumpCache not in use, ignoring.");
}
}
else
{
QString msg = invalidIndexMessage(lumpIdx, lastIndex());
LOG_DEBUG(msg + ", ignoring.");
}
return *this;
}
Wad& Wad::clearLumpCache()
{
LOG_AS("Wad::clearLumpCache");
if(d->lumpCache) d->lumpCache->clear();
return *this;
}
uint8_t const* Wad::cacheLump(int lumpIdx)
{
LOG_AS("Wad::cacheLump");
if(!isValidIndex(lumpIdx)) throw NotFoundError("Wad::cacheLump", invalidIndexMessage(lumpIdx, lastIndex()));
File1 const& file = lump(lumpIdx);
LOG_TRACE("\"%s:%s\" (%lu bytes%s)")
<< F_PrettyPath(Str_Text(path()))
<< F_PrettyPath(Str_Text(composeLumpPath(lumpIdx, '/')))
<< (unsigned long) file.info().size
<< (file.info().isCompressed()? ", compressed" : "");
// Time to create the cache?
if(!d->lumpCache)
{
d->lumpCache = new LumpCache(lumpCount());
}
uint8_t const* data = d->lumpCache->data(lumpIdx);
if(data) return data;
uint8_t* region = (uint8_t*) Z_Malloc(file.info().size, PU_APPSTATIC, 0);
if(!region) throw Error("Wad::cacheLump", QString("Failed on allocation of %1 bytes for cache copy of lump #%2").arg(file.info().size).arg(lumpIdx));
readLump(lumpIdx, region, false);
d->lumpCache->insert(lumpIdx, region);
return region;
}
Wad& Wad::unlockLump(int lumpIdx)
{
LOG_AS("Wad::unlockLump");
LOG_TRACE("\"%s:%s\"")
<< F_PrettyPath(Str_Text(path())) << F_PrettyPath(Str_Text(composeLumpPath(lumpIdx, '/')));
if(isValidIndex(lumpIdx))
{
if(d->lumpCache)
{
d->lumpCache->unlock(lumpIdx);
}
else
{
LOG_DEBUG("LumpCache not in use, ignoring.");
}
}
else
{
QString msg = invalidIndexMessage(lumpIdx, lastIndex());
LOG_DEBUG(msg + ", ignoring.");
}
return *this;
}
size_t Wad::readLump(int lumpIdx, uint8_t* buffer, bool tryCache)
{
LOG_AS("Wad::readLump");
if(!isValidIndex(lumpIdx)) return 0;
return readLump(lumpIdx, buffer, 0, lump(lumpIdx).size(), tryCache);
}
size_t Wad::readLump(int lumpIdx, uint8_t* buffer, size_t startOffset,
size_t length, bool tryCache)
{
LOG_AS("Wad::readLump");
WadFile const& file = reinterpret_cast<WadFile&>(lump(lumpIdx));
LOG_TRACE("\"%s:%s\" (%lu bytes%s) [%lu +%lu]")
<< F_PrettyPath(Str_Text(path()))
<< F_PrettyPath(Str_Text(composeLumpPath(lumpIdx, '/')))
<< (unsigned long) file.size()
<< (file.isCompressed()? ", compressed" : "")
<< (unsigned long) startOffset
<< (unsigned long) length;
// Try to avoid a file system read by checking for a cached copy.
if(tryCache)
{
uint8_t const* data = d->lumpCache? d->lumpCache->data(lumpIdx) : 0;
LOG_DEBUG("Cache %s on #%i") << (data? "hit" : "miss") << lumpIdx;
if(data)
{
size_t readBytes = MIN_OF(file.size(), length);
memcpy(buffer, data + startOffset, readBytes);
return readBytes;
}
}
handle_->seek(file.info().baseOffset + startOffset, SeekSet);
size_t readBytes = handle_->read(buffer, length);
/// @todo Do not check the read length here.
if(readBytes < length)
throw Error("Wad::readLumpSection", QString("Only read %1 of %2 bytes of lump #%3").arg(readBytes).arg(length).arg(lumpIdx));
return readBytes;
}
uint Wad::calculateCRC()
{
uint crc = 0;
int const numLumps = lumpCount();
for(int i = 0; i < numLumps; ++i)
{
WadFile& file = reinterpret_cast<WadFile&>(lump(i));
file.updateCRC();
crc += file.crc();
}
return crc;
}
bool Wad::recognise(FileHandle& file)
{
wadheader_t hdr;
// Seek to the start of the header.
size_t initPos = file.tell();
file.seek(0, SeekSet);
bool readHeaderOk = Wad::Instance::readArchiveHeader(file, hdr);
// Return the stream to its original position.
file.seek(initPos, SeekSet);
if(!readHeaderOk) return false;
if(memcmp(hdr.identification, "IWAD", 4) && memcmp(hdr.identification, "PWAD", 4)) return false;
return true;
}
} // namespace de
static QString invalidIndexMessage(int invalidIdx, int lastValidIdx)
{
QString msg = QString("Invalid lump index %1 ").arg(invalidIdx);
if(lastValidIdx < 0) msg += "(file is empty)";
else msg += QString("(valid range: [0..%2])").arg(lastValidIdx);
return msg;
}