-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathfilesystem.cpp
1485 lines (1261 loc) · 38.6 KB
/
filesystem.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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
** filesystem.cpp
**
**---------------------------------------------------------------------------
** Copyright 1998-2009 Randy Heit
** Copyright 2005-2020 Christoph Oelckers
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**---------------------------------------------------------------------------
**
**
*/
// HEADER FILES ------------------------------------------------------------
#include <miniz.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <inttypes.h>
#include "resourcefile.h"
#include "fs_filesystem.h"
#include "fs_findfile.h"
#include "md5.hpp"
#include "fs_stringpool.h"
namespace FileSys {
// MACROS ------------------------------------------------------------------
#define NULL_INDEX (0xffffffff)
static void UpperCopy(char* to, const char* from)
{
int i;
for (i = 0; i < 8 && from[i]; i++)
to[i] = toupper(from[i]);
for (; i < 8; i++)
to[i] = 0;
}
//djb2
static uint32_t MakeHash(const char* str, size_t length = SIZE_MAX)
{
uint32_t hash = 5381;
uint32_t c;
while (length-- > 0 && (c = *str++)) hash = hash * 33 + (c | 32);
return hash;
}
static void md5Hash(FileReader& reader, uint8_t* digest)
{
using namespace md5;
md5_state_t state;
md5_init(&state);
md5_byte_t buffer[4096];
while (auto len = reader.Read(buffer, 4096))
{
md5_append(&state, buffer, len);
}
md5_finish(&state, digest);
}
struct FileSystem::LumpRecord
{
FResourceFile *resfile;
LumpShortName shortName;
const char* LongName;
int resindex;
int16_t rfnum; // this is not necessarily the same as resfile's index!
int16_t Namespace;
int resourceId;
int flags;
void SetFromLump(FResourceFile* file, int fileindex, int filenum, StringPool* sp, const char* name = nullptr)
{
resfile = file;
resindex = fileindex;
rfnum = filenum;
flags = 0;
auto lflags = file->GetEntryFlags(fileindex);
if (!name) name = file->getName(fileindex);
if (lflags & RESFF_SHORTNAME)
{
UpperCopy(shortName.String, name);
shortName.String[8] = 0;
LongName = "";
Namespace = file->GetEntryNamespace(fileindex);
resourceId = -1;
}
else if ((lflags & RESFF_EMBEDDED) || !name || !*name)
{
shortName.qword = 0;
LongName = "";
Namespace = ns_hidden;
resourceId = -1;
}
else
{
LongName = name;
resourceId = file->GetEntryResourceID(fileindex);
// Map some directories to WAD namespaces.
// Note that some of these namespaces don't exist in WADS.
// CheckNumForName will handle any request for these namespaces accordingly.
Namespace = !strncmp(LongName, "flats/", 6) ? ns_flats :
!strncmp(LongName, "textures/", 9) ? ns_newtextures :
!strncmp(LongName, "hires/", 6) ? ns_hires :
!strncmp(LongName, "sprites/", 8) ? ns_sprites :
!strncmp(LongName, "voxels/", 7) ? ns_voxels :
!strncmp(LongName, "colormaps/", 10) ? ns_colormaps :
!strncmp(LongName, "acs/", 4) ? ns_acslibrary :
!strncmp(LongName, "voices/", 7) ? ns_strifevoices :
!strncmp(LongName, "patches/", 8) ? ns_patches :
!strncmp(LongName, "graphics/", 9) ? ns_graphics :
!strncmp(LongName, "sounds/", 7) ? ns_sounds :
!strncmp(LongName, "music/", 6) ? ns_music :
!strchr(LongName, '/') ? ns_global :
ns_hidden;
if (Namespace == ns_hidden) shortName.qword = 0;
else if (strstr(LongName, ".{"))
{
std::string longName = LongName;
ptrdiff_t encodedResID = longName.find_last_of(".{");
if (resourceId == -1 && (size_t)encodedResID != std::string::npos)
{
const char* p = LongName + encodedResID;
char* q;
int id = (int)strtoull(p + 2, &q, 10); // only decimal numbers allowed here.
if (q[0] == '}' && (q[1] == '.' || q[1] == 0))
{
longName.erase(longName.begin() + encodedResID, longName.begin() + (q - p) + 1);
resourceId = id;
}
LongName = sp->Strdup(longName.c_str());
}
}
auto slash = strrchr(LongName, '/');
std::string base = slash ? (slash + 1) : LongName;
auto dot = base.find_last_of('.');
if (dot != std::string::npos) base.resize(dot);
UpperCopy(shortName.String, base.c_str());
// Since '\' can't be used as a file name's part inside a ZIP
// we have to work around this for sprites because it is a valid
// frame character.
if (Namespace == ns_sprites || Namespace == ns_voxels || Namespace == ns_hires)
{
char* c;
while ((c = (char*)memchr(shortName.String, '^', 8)))
{
*c = '\\';
}
}
}
}
};
// PUBLIC FUNCTION PROTOTYPES ----------------------------------------------
// PRIVATE FUNCTION PROTOTYPES ---------------------------------------------
static void PrintLastError (FileSystemMessageFunc Printf);
// PUBLIC DATA DEFINITIONS -------------------------------------------------
// CODE --------------------------------------------------------------------
FileSystem::FileSystem()
{
}
FileSystem::~FileSystem ()
{
DeleteAll();
}
void FileSystem::DeleteAll ()
{
Hashes.clear();
NumEntries = 0;
FileInfo.clear();
for (int i = (int)Files.size() - 1; i >= 0; --i)
{
delete Files[i];
}
Files.clear();
if (stringpool != nullptr) delete stringpool;
stringpool = nullptr;
}
//==========================================================================
//
// InitMultipleFiles
//
// Pass a null terminated list of files to use. All files are optional,
// but at least one file must be found. File names can appear multiple
// times. The name searcher looks backwards, so a later file can
// override an earlier one.
//
//==========================================================================
bool FileSystem::InitSingleFile(const char* filename, FileSystemMessageFunc Printf)
{
std::vector<std::string> filenames = { filename };
return InitMultipleFiles(filenames, nullptr, Printf);
}
bool FileSystem::InitMultipleFiles (std::vector<std::string>& filenames, LumpFilterInfo* filter, FileSystemMessageFunc Printf, bool allowduplicates)
{
int numfiles;
// the first call here will designate a main thread which may use shared file readers. All other thewads have to open new file handles.
SetMainThread();
// open all the files, load headers, and count lumps
DeleteAll();
numfiles = 0;
stringpool = new StringPool(true);
stringpool->shared = true; // will be used by all owned resource files.
// first, check for duplicates
if (!allowduplicates)
{
for (size_t i=0;i<filenames.size(); i++)
{
for (size_t j=i+1;j<filenames.size(); j++)
{
if (filenames[i] == filenames[j])
{
filenames.erase(filenames.begin() + j);
j--;
}
}
}
}
for(size_t i=0;i<filenames.size(); i++)
{
AddFile(filenames[i].c_str(), nullptr, filter, Printf);
if (i == (unsigned)MaxIwadIndex) MoveLumpsInFolder("after_iwad/");
std::string path = "filter/%s";
path += Files.back()->GetHash();
MoveLumpsInFolder(path.c_str());
}
NumEntries = (uint32_t)FileInfo.size();
if (NumEntries == 0)
{
return false;
}
if (filter && filter->postprocessFunc) filter->postprocessFunc();
// [RH] Set up hash table
InitHashChains ();
return true;
}
//==========================================================================
//
// AddFromBuffer
//
// Adds an in-memory resource to the virtual directory
//
//==========================================================================
int FileSystem::AddFromBuffer(const char* name, char* data, int size, int id, int flags)
{
FileReader fr;
FileData blob(data, size);
fr.OpenMemoryArray(blob);
// wrap this into a single lump resource file (should be done a little better later.)
auto rf = new FResourceFile(name, fr, stringpool);
auto Entries = rf->AllocateEntries(1);
Entries[0].FileName = rf->NormalizeFileName(ExtractBaseName(name, true).c_str());
Entries[0].ResourceID = -1;
Entries[0].Length = size;
Files.push_back(rf);
FileInfo.resize(FileInfo.size() + 1);
FileSystem::LumpRecord* lump_p = &FileInfo.back();
lump_p->SetFromLump(rf, 0, (int)Files.size() - 1, stringpool);
return (int)FileInfo.size() - 1;
}
//==========================================================================
//
// AddFile
//
// Files with a .wad extension are wadlink files with multiple lumps,
// other files are single lumps with the base filename for the lump name.
//
// [RH] Removed reload hack
//==========================================================================
void FileSystem::AddFile (const char *filename, FileReader *filer, LumpFilterInfo* filter, FileSystemMessageFunc Printf)
{
int startlump;
bool isdir = false;
FileReader filereader;
if (filer == nullptr)
{
// Does this exist? If so, is it a directory?
if (!FS_DirEntryExists(filename, &isdir))
{
if (Printf)
{
Printf(FSMessageLevel::Error, "%s: File or Directory not found\n", filename);
PrintLastError(Printf);
}
return;
}
if (!isdir)
{
if (!filereader.OpenFile(filename))
{ // Didn't find file
if (Printf)
{
Printf(FSMessageLevel::Error, "%s: File not found\n", filename);
PrintLastError(Printf);
}
return;
}
}
}
else filereader = std::move(*filer);
startlump = NumEntries;
FResourceFile *resfile;
if (!isdir)
resfile = FResourceFile::OpenResourceFile(filename, filereader, false, filter, Printf, stringpool);
else
resfile = FResourceFile::OpenDirectory(filename, filter, Printf, stringpool);
if (resfile != NULL)
{
if (Printf)
Printf(FSMessageLevel::Message, "adding %s, %d lumps\n", filename, resfile->EntryCount());
uint32_t lumpstart = (uint32_t)FileInfo.size();
resfile->SetFirstLump(lumpstart);
Files.push_back(resfile);
for (int i = 0; i < resfile->EntryCount(); i++)
{
FileInfo.resize(FileInfo.size() + 1);
FileSystem::LumpRecord* lump_p = &FileInfo.back();
lump_p->SetFromLump(resfile, i, (int)Files.size() - 1, stringpool);
}
for (int i = 0; i < resfile->EntryCount(); i++)
{
int flags = resfile->GetEntryFlags(i);
if (flags & RESFF_EMBEDDED)
{
std::string path = filename;
path += ':';
path += resfile->getName(i);
auto embedded = resfile->GetEntryReader(i, READER_CACHED);
AddFile(path.c_str(), &embedded, filter, Printf);
}
}
return;
}
}
//==========================================================================
//
// CheckIfResourceFileLoaded
//
// Returns true if the specified file is loaded, false otherwise.
// If a fully-qualified path is specified, then the file must match exactly.
// Otherwise, any file with that name will work, whatever its path.
// Returns the file's index if found, or -1 if not.
//
//==========================================================================
int FileSystem::CheckIfResourceFileLoaded (const char *name) noexcept
{
unsigned int i;
if (strrchr (name, '/') != NULL)
{
for (i = 0; i < (unsigned)Files.size(); ++i)
{
if (stricmp (GetResourceFileFullName (i), name) == 0)
{
return i;
}
}
}
else
{
for (i = 0; i < (unsigned)Files.size(); ++i)
{
auto pth = ExtractBaseName(GetResourceFileName(i), true);
if (stricmp (pth.c_str(), name) == 0)
{
return i;
}
}
}
return -1;
}
//==========================================================================
//
// CheckNumForName
//
// Returns -1 if name not found. The version with a third parameter will
// look exclusively in the specified wad for the lump.
//
// [RH] Changed to use hash lookup ala BOOM instead of a linear search
// and namespace parameter
//==========================================================================
int FileSystem::CheckNumForName (const char *name, int space) const
{
union
{
char uname[8];
uint64_t qname;
};
uint32_t i;
if (name == NULL)
{
return -1;
}
// Let's not search for names that are longer than 8 characters and contain path separators
// They are almost certainly full path names passed to this function.
if (strlen(name) > 8 && strpbrk(name, "/."))
{
return -1;
}
UpperCopy (uname, name);
i = FirstLumpIndex[MakeHash(uname, 8) % NumEntries];
while (i != NULL_INDEX)
{
if (FileInfo[i].shortName.qword == qname)
{
auto &lump = FileInfo[i];
if (lump.Namespace == space) break;
// If the lump is from one of the special namespaces exclusive to Zips
// the check has to be done differently:
// If we find a lump with this name in the global namespace that does not come
// from a Zip return that. WADs don't know these namespaces and single lumps must
// work as well.
auto lflags = lump.resfile->GetEntryFlags(lump.resindex);
if (space > ns_specialzipdirectory && lump.Namespace == ns_global &&
!((lflags ^lump.flags) & RESFF_FULLPATH)) break;
}
i = NextLumpIndex[i];
}
return i != NULL_INDEX ? i : -1;
}
int FileSystem::CheckNumForName (const char *name, int space, int rfnum, bool exact) const
{
union
{
char uname[8];
uint64_t qname;
};
uint32_t i;
if (rfnum < 0)
{
return CheckNumForName (name, space);
}
UpperCopy (uname, name);
i = FirstLumpIndex[MakeHash (uname, 8) % NumEntries];
// If exact is true if will only find lumps in the same WAD, otherwise
// also those in earlier WADs.
while (i != NULL_INDEX &&
(FileInfo[i].shortName.qword != qname || FileInfo[i].Namespace != space ||
(exact? (FileInfo[i].rfnum != rfnum) : (FileInfo[i].rfnum > rfnum)) ))
{
i = NextLumpIndex[i];
}
return i != NULL_INDEX ? i : -1;
}
//==========================================================================
//
// GetNumForName
//
// Calls CheckNumForName, but bombs out if not found.
//
//==========================================================================
int FileSystem::GetNumForName (const char *name, int space) const
{
int i;
i = CheckNumForName (name, space);
if (i == -1)
throw FileSystemException("GetNumForName: %s not found!", name);
return i;
}
//==========================================================================
//
// CheckNumForFullName
//
// Same as above but looks for a fully qualified name from a .zip
// These don't care about namespaces though because those are part
// of the path.
//
//==========================================================================
int FileSystem::CheckNumForFullName (const char *name, bool trynormal, int namespc, bool ignoreext) const
{
uint32_t i;
if (name == NULL)
{
return -1;
}
if (*name == '/') name++; // ignore leading slashes in file names.
uint32_t *fli = ignoreext ? FirstLumpIndex_NoExt : FirstLumpIndex_FullName;
uint32_t *nli = ignoreext ? NextLumpIndex_NoExt : NextLumpIndex_FullName;
auto len = strlen(name);
for (i = fli[MakeHash(name) % NumEntries]; i != NULL_INDEX; i = nli[i])
{
if (strnicmp(name, FileInfo[i].LongName, len)) continue;
if (FileInfo[i].LongName[len] == 0) break; // this is a full match
if (ignoreext && FileInfo[i].LongName[len] == '.')
{
// is this the last '.' in the last path element, indicating that the remaining part of the name is only an extension?
if (strpbrk(FileInfo[i].LongName + len + 1, "./") == nullptr) break;
}
}
if (i != NULL_INDEX) return i;
if (trynormal && strlen(name) <= 8 && !strpbrk(name, "./"))
{
return CheckNumForName(name, namespc);
}
return -1;
}
int FileSystem::CheckNumForFullName (const char *name, int rfnum) const
{
uint32_t i;
if (rfnum < 0)
{
return CheckNumForFullName (name);
}
i = FirstLumpIndex_FullName[MakeHash (name) % NumEntries];
while (i != NULL_INDEX &&
(stricmp(name, FileInfo[i].LongName) || FileInfo[i].rfnum != rfnum))
{
i = NextLumpIndex_FullName[i];
}
return i != NULL_INDEX ? i : -1;
}
//==========================================================================
//
// GetNumForFullName
//
// Calls CheckNumForFullName, but bombs out if not found.
//
//==========================================================================
int FileSystem::GetNumForFullName (const char *name) const
{
int i;
i = CheckNumForFullName (name);
if (i == -1)
throw FileSystemException("GetNumForFullName: %s not found!", name);
return i;
}
//==========================================================================
//
// FindFile
//
// Looks up a file by name, either with or without path and extension
//
//==========================================================================
int FileSystem::FindFileWithExtensions(const char* name, const char *const *exts, int count) const
{
uint32_t i;
if (name == NULL)
{
return -1;
}
if (*name == '/') name++; // ignore leading slashes in file names.
uint32_t* fli = FirstLumpIndex_NoExt;
uint32_t* nli = NextLumpIndex_NoExt;
auto len = strlen(name);
for (i = fli[MakeHash(name) % NumEntries]; i != NULL_INDEX; i = nli[i])
{
if (strnicmp(name, FileInfo[i].LongName, len)) continue;
if (FileInfo[i].LongName[len] != '.') continue; // we are looking for extensions but this file doesn't have one.
auto cp = FileInfo[i].LongName + len + 1;
// is this the last '.' in the last path element, indicating that the remaining part of the name is only an extension?
if (strpbrk(cp, "./") != nullptr) continue; // No, so it cannot be a valid entry.
for (int j = 0; j < count; j++)
{
if (!stricmp(cp, exts[j])) return i; // found a match
}
}
return -1;
}
//==========================================================================
//
// FindResource
//
// Looks for content based on Blood resource IDs.
//
//==========================================================================
int FileSystem::FindResource (int resid, const char *type, int filenum) const noexcept
{
uint32_t i;
if (type == NULL || resid < 0)
{
return -1;
}
uint32_t* fli = FirstLumpIndex_ResId;
uint32_t* nli = NextLumpIndex_ResId;
for (i = fli[resid % NumEntries]; i != NULL_INDEX; i = nli[i])
{
if (filenum > 0 && FileInfo[i].rfnum != filenum) continue;
if (FileInfo[i].resourceId != resid) continue;
auto extp = strrchr(FileInfo[i].LongName, '.');
if (!extp) continue;
if (!stricmp(extp + 1, type)) return i;
}
return -1;
}
//==========================================================================
//
// GetResource
//
// Calls GetResource, but bombs out if not found.
//
//==========================================================================
int FileSystem::GetResource (int resid, const char *type, int filenum) const
{
int i;
i = FindResource (resid, type, filenum);
if (i == -1)
{
throw FileSystemException("GetResource: %d of type %s not found!", resid, type);
}
return i;
}
//==========================================================================
//
// FileLength
//
// Returns the buffer size needed to load the given lump.
//
//==========================================================================
ptrdiff_t FileSystem::FileLength (int lump) const
{
if ((size_t)lump >= NumEntries)
{
return -1;
}
const auto &lump_p = FileInfo[lump];
return (int)lump_p.resfile->Length(lump_p.resindex);
}
//==========================================================================
//
//
//
//==========================================================================
int FileSystem::GetFileFlags (int lump)
{
if ((size_t)lump >= NumEntries)
{
return 0;
}
const auto& lump_p = FileInfo[lump];
return lump_p.resfile->GetEntryFlags(lump_p.resindex) ^ lump_p.flags;
}
//==========================================================================
//
// InitHashChains
//
// Prepares the lumpinfos for hashing.
// (Hey! This looks suspiciously like something from Boom! :-)
//
//==========================================================================
void FileSystem::InitHashChains (void)
{
unsigned int i, j;
NumEntries = (uint32_t)FileInfo.size();
Hashes.resize(8 * NumEntries);
// Mark all buckets as empty
memset(Hashes.data(), -1, Hashes.size() * sizeof(Hashes[0]));
FirstLumpIndex = &Hashes[0];
NextLumpIndex = &Hashes[NumEntries];
FirstLumpIndex_FullName = &Hashes[NumEntries * 2];
NextLumpIndex_FullName = &Hashes[NumEntries * 3];
FirstLumpIndex_NoExt = &Hashes[NumEntries * 4];
NextLumpIndex_NoExt = &Hashes[NumEntries * 5];
FirstLumpIndex_ResId = &Hashes[NumEntries * 6];
NextLumpIndex_ResId = &Hashes[NumEntries * 7];
// Now set up the chains
for (i = 0; i < (unsigned)NumEntries; i++)
{
j = MakeHash (FileInfo[i].shortName.String, 8) % NumEntries;
NextLumpIndex[i] = FirstLumpIndex[j];
FirstLumpIndex[j] = i;
// Do the same for the full paths
if (FileInfo[i].LongName[0] != 0)
{
j = MakeHash(FileInfo[i].LongName) % NumEntries;
NextLumpIndex_FullName[i] = FirstLumpIndex_FullName[j];
FirstLumpIndex_FullName[j] = i;
std::string nameNoExt = FileInfo[i].LongName;
auto dot = nameNoExt.find_last_of('.');
auto slash = nameNoExt.find_last_of('/');
if ((dot > slash || slash == std::string::npos) && dot != std::string::npos) nameNoExt.resize(dot);
j = MakeHash(nameNoExt.c_str()) % NumEntries;
NextLumpIndex_NoExt[i] = FirstLumpIndex_NoExt[j];
FirstLumpIndex_NoExt[j] = i;
j = FileInfo[i].resourceId % NumEntries;
NextLumpIndex_ResId[i] = FirstLumpIndex_ResId[j];
FirstLumpIndex_ResId[j] = i;
}
}
FileInfo.shrink_to_fit();
Files.shrink_to_fit();
}
//==========================================================================
//
// should only be called before the hash chains are set up.
// If done later this needs rehashing.
//
//==========================================================================
LumpShortName& FileSystem::GetShortName(int i)
{
if ((unsigned)i >= NumEntries) throw FileSystemException("GetShortName: Invalid index");
return FileInfo[i].shortName;
}
void FileSystem::RenameFile(int num, const char* newfn)
{
if ((unsigned)num >= NumEntries) throw FileSystemException("RenameFile: Invalid index");
FileInfo[num].LongName = stringpool->Strdup(newfn);
// This does not alter the short name - call GetShortname to do that!
}
//==========================================================================
//
// MoveLumpsInFolder
//
// Moves all content from the given subfolder of the internal
// resources to the current end of the directory.
// Used to allow modifying content in the base files, this is needed
// so that Hacx and Harmony can override some content that clashes
// with localization, and to inject modifying data into mods, in case
// this is needed for some compatibility requirement.
//
//==========================================================================
void FileSystem::MoveLumpsInFolder(const char *path)
{
if (FileInfo.size() == 0)
{
return;
}
auto len = strlen(path);
auto rfnum = FileInfo.back().rfnum;
size_t i;
for (i = 0; i < FileInfo.size(); i++)
{
auto& li = FileInfo[i];
if (li.rfnum >= GetIwadNum()) break;
if (strnicmp(li.LongName, path, len) == 0)
{
auto lic = li; // make a copy before pushing.
FileInfo.push_back(lic);
li.LongName = ""; //nuke the name of the old record.
li.shortName.qword = 0;
auto &ln = FileInfo.back();
ln.SetFromLump(li.resfile, li.resindex, rfnum, stringpool, ln.LongName + len);
}
}
}
//==========================================================================
//
// W_FindLump
//
// Find a named lump. Specifically allows duplicates for merging of e.g.
// SNDINFO lumps.
//
//==========================================================================
int FileSystem::FindLump (const char *name, int *lastlump, bool anyns)
{
if ((size_t)*lastlump >= FileInfo.size()) return -1;
union
{
char name8[8];
uint64_t qname;
};
UpperCopy (name8, name);
assert(lastlump != NULL && *lastlump >= 0);
const LumpRecord * last = FileInfo.data() + FileInfo.size();
LumpRecord * lump_p = FileInfo.data() + *lastlump;
while (lump_p < last)
{
if ((anyns || lump_p->Namespace == ns_global) && lump_p->shortName.qword == qname)
{
int lump = int(lump_p - FileInfo.data());
*lastlump = lump + 1;
return lump;
}
lump_p++;
}
*lastlump = NumEntries;
return -1;
}
//==========================================================================
//
// W_FindLumpMulti
//
// Find a named lump. Specifically allows duplicates for merging of e.g.
// SNDINFO lumps. Returns everything having one of the passed names.
//
//==========================================================================
int FileSystem::FindLumpMulti (const char **names, int *lastlump, bool anyns, int *nameindex)
{
assert(lastlump != NULL && *lastlump >= 0);
const LumpRecord * last = FileInfo.data() + FileInfo.size();
LumpRecord * lump_p = FileInfo.data() + *lastlump;
while (lump_p < last)
{
if (anyns || lump_p->Namespace == ns_global)
{
for(const char **name = names; *name != NULL; name++)
{
if (!strnicmp(*name, lump_p->shortName.String, 8))
{
int lump = int(lump_p - FileInfo.data());
*lastlump = lump + 1;
if (nameindex != NULL) *nameindex = int(name - names);
return lump;
}
}
}
lump_p++;
}
*lastlump = NumEntries;
return -1;
}
//==========================================================================
//
// W_FindLump
//
// Find a named lump. Specifically allows duplicates for merging of e.g.
// SNDINFO lumps.
//
//==========================================================================
int FileSystem::FindLumpFullName(const char* name, int* lastlump, bool noext)
{
assert(lastlump != NULL && *lastlump >= 0);
const LumpRecord * last = FileInfo.data() + FileInfo.size();
LumpRecord * lump_p = FileInfo.data() + *lastlump;
if (!noext)
{
while (lump_p < last)
{
if (!stricmp(name, lump_p->LongName))
{
int lump = int(lump_p - FileInfo.data());
*lastlump = lump + 1;
return lump;
}
lump_p++;
}
}
else
{
auto len = strlen(name);
while (lump_p <= &FileInfo.back())
{
auto res = strnicmp(name, lump_p->LongName, len);
if (res == 0)
{