File: reader.cpp

package info (click to toggle)
openmw 0.49.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 33,992 kB
  • sloc: cpp: 372,479; xml: 2,149; sh: 1,403; python: 797; makefile: 26
file content (966 lines) | stat: -rw-r--r-- 35,124 bytes parent folder | download
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
/*
  Copyright (C) 2015-2021 cc9cii

  This software is provided 'as-is', without any express or implied
  warranty.  In no event will the authors be held liable for any damages
  arising from the use of this software.

  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgment in the product documentation would be
     appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.

  cc9cii cc9c@iinet.net.au

*/
#include "reader.hpp"

#undef DEBUG_GROUPSTACK

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <optional>
#include <span>
#include <sstream>
#include <stdexcept>

#include <zlib.h>

#include <components/bsa/memorystream.hpp>
#include <components/debug/debuglog.hpp>
#include <components/esm/refid.hpp>
#include <components/files/constrainedfilestream.hpp>
#include <components/files/conversion.hpp>
#include <components/misc/strings/lower.hpp>
#include <components/to_utf8/to_utf8.hpp>
#include <components/vfs/manager.hpp>

#include "grouptype.hpp"

namespace ESM4
{
    namespace
    {
        using FormId = ESM::FormId;
        using FormId32 = ESM::FormId32;

        std::string getError(const std::string& header, const int errorCode, const char* msg)
        {
            return header + ": code " + std::to_string(errorCode) + ", " + std::string(msg != nullptr ? msg : "(null)");
        }

        std::u8string_view getStringsSuffix(LocalizedStringType type)
        {
            switch (type)
            {
                case LocalizedStringType::Strings:
                    return u8".STRINGS";
                case LocalizedStringType::ILStrings:
                    return u8".ILSTRINGS";
                case LocalizedStringType::DLStrings:
                    return u8".DLSTRINGS";
            }

            throw std::logic_error("Unsupported LocalizedStringType: " + std::to_string(static_cast<int>(type)));
        }

        struct InflateEnd
        {
            void operator()(z_stream* stream) const { inflateEnd(stream); }
        };

        std::optional<std::string> tryDecompressAll(std::span<char> compressed, std::span<char> decompressed)
        {
            z_stream stream{};

            stream.next_in = reinterpret_cast<Bytef*>(compressed.data());
            stream.next_out = reinterpret_cast<Bytef*>(decompressed.data());
            stream.avail_in = static_cast<uInt>(compressed.size());
            stream.avail_out = static_cast<uInt>(decompressed.size());

            if (const int ec = inflateInit(&stream); ec != Z_OK)
                return getError("inflateInit error", ec, stream.msg);

            const std::unique_ptr<z_stream, InflateEnd> streamPtr(&stream);

            if (const int ec = inflate(&stream, Z_NO_FLUSH); ec != Z_STREAM_END)
                return getError("inflate error", ec, stream.msg);

            return std::nullopt;
        }

        std::optional<std::string> tryDecompressByBlock(
            std::span<char> compressed, std::span<char> decompressed, std::size_t blockSize)
        {
            z_stream stream{};

            if (const int ec = inflateInit(&stream); ec != Z_OK)
                return getError("inflateInit error", ec, stream.msg);

            const std::unique_ptr<z_stream, InflateEnd> streamPtr(&stream);

            while (!compressed.empty() && !decompressed.empty())
            {
                const auto prevTotalIn = stream.total_in;
                const auto prevTotalOut = stream.total_out;
                stream.next_in = reinterpret_cast<Bytef*>(compressed.data());
                stream.avail_in = static_cast<uInt>(std::min(blockSize, compressed.size()));
                stream.next_out = reinterpret_cast<Bytef*>(decompressed.data());
                stream.avail_out = static_cast<uInt>(std::min(blockSize, decompressed.size()));
                const int ec = inflate(&stream, Z_NO_FLUSH);
                if (ec == Z_STREAM_END)
                    break;
                if (ec != Z_OK)
                    return getError(
                        "inflate error after reading " + std::to_string(stream.total_in) + " bytes", ec, stream.msg);
                compressed = compressed.subspan(stream.total_in - prevTotalIn);
                decompressed = decompressed.subspan(stream.total_out - prevTotalOut);
            }

            return std::nullopt;
        }

        std::unique_ptr<Bsa::MemoryInputStream> decompress(
            std::streamoff position, std::span<char> compressed, std::uint32_t uncompressedSize)
        {
            auto result = std::make_unique<Bsa::MemoryInputStream>(uncompressedSize);

            const std::span decompressed(result->getRawData(), uncompressedSize);

            const auto allError = tryDecompressAll(compressed, decompressed);
            if (!allError.has_value())
                return result;

            Log(Debug::Warning) << "Failed to decompress record data at 0x" << std::hex << position
                                << std::resetiosflags(std::ios_base::hex) << " compressed size = " << compressed.size()
                                << " uncompressed size = " << uncompressedSize << ": " << *allError
                                << ". Trying to decompress by block...";

            std::memset(result->getRawData(), 0, uncompressedSize);

            constexpr std::size_t blockSize = 4;
            const auto blockError = tryDecompressByBlock(compressed, decompressed, blockSize);
            if (!blockError.has_value())
                return result;

            std::ostringstream s;
            s << "Failed to decompress record data by block of " << blockSize << " bytes at 0x" << std::hex << position
              << std::resetiosflags(std::ios_base::hex) << " compressed size = " << compressed.size()
              << " uncompressed size = " << uncompressedSize << ": " << *blockError;
            throw std::runtime_error(s.str());
        }
    }

    ReaderContext::ReaderContext()
        : modIndex(0)
        , recHeaderSize(sizeof(RecordHeader))
        , filePos(0)
        , fileRead(0)
        , recordRead(0)
        , currWorld({ 0, 0 })
        , currCell({ 0, 0 })
        , currCellGrid(FormId{ 0, 0 })
        , cellGridValid(false)
    {
        recordHeader = {};
        subRecordHeader = {};
    }

    Reader::Reader(Files::IStreamPtr&& esmStream, const std::filesystem::path& filename, VFS::Manager const* vfs,
        const ToUTF8::StatelessUtf8Encoder* encoder, bool ignoreMissingLocalizedStrings)
        : mVFS(vfs)
        , mEncoder(encoder)
        , mFileSize(0)
        , mStream(std::move(esmStream))
        , mIgnoreMissingLocalizedStrings(ignoreMissingLocalizedStrings)
    {
        // used by ESMReader only?
        mCtx.filename = filename;

        mCtx.fileRead = 0;
        mStream->seekg(0, mStream->end);
        mFileSize = mStream->tellg();
        mStream->seekg(20); // go to the start but skip the "TES4" record header

        mSavedStream.reset();

        // determine header size
        std::uint32_t subRecName = 0;
        mStream->read((char*)&subRecName, sizeof(subRecName));
        if (subRecName == 0x52444548) // "HEDR"
            mCtx.recHeaderSize = sizeof(RecordHeader) - 4; // TES4 header size is 4 bytes smaller than TES5 header
        else
            mCtx.recHeaderSize = sizeof(RecordHeader);

        // restart from the beginning (i.e. "TES4" record header)
        mStream->seekg(0, mStream->beg);
        getRecordHeader();
        if (mCtx.recordHeader.record.typeId == REC_TES4)
        {
            mHeader.load(*this);
            mCtx.fileRead += mCtx.recordHeader.record.dataSize;

            buildLStringIndex(); // for localised strings in Skyrim
        }
        else
            fail("Unknown file format");
    }

    Reader::~Reader()
    {
        close();
    }

    // Since the record data may have been compressed, it is not always possible to use seek() to
    // go to a position of a sub record.
    //
    // The record header needs to be saved in the context or the header needs to be re-loaded after
    // restoring the context. The latter option was chosen.
    ReaderContext Reader::getContext()
    {
        mCtx.filePos = mStream->tellg();
        if (mCtx.filePos == std::streampos(-1))
            return mCtx;
        mCtx.filePos -= mCtx.recHeaderSize; // update file position
        return mCtx;
    }

    // NOTE: Assumes that the caller has reopened the file if necessary
    bool Reader::restoreContext(const ReaderContext& ctx)
    {
        if (mSavedStream) // TODO: doesn't seem to ever happen
        {
            mStream = std::move(mSavedStream);
        }

        mCtx.groupStack.clear(); // probably not necessary since it will be overwritten
        mCtx = ctx;
        mStream->seekg(ctx.filePos); // update file position

        return getRecordHeader();
    }

    void Reader::close()
    {
        mStream.reset();
        // clearCtx();
        // mHeader.blank();
    }

    void Reader::openRaw(Files::IStreamPtr&& stream, const std::filesystem::path& filename)
    {
        close();

        mStream = std::move(stream);
        mCtx.filename = filename;
        mCtx.fileRead = 0;
        mStream->seekg(0, mStream->end);
        mFileSize = mStream->tellg();
        mStream->seekg(0, mStream->beg);
    }

    void Reader::open(Files::IStreamPtr&& stream, const std::filesystem::path& filename)
    {
        openRaw(std::move(stream), filename);

        // should at least have the size of ESM3 record header (20 or 24 bytes for ESM4)
        if (mFileSize < 16)
            throw std::runtime_error("File too small");
        std::uint32_t modVer = 0;
        if (getExact(modVer)) // get the first 4 bytes of the record header only
        {
            // FIXME: need to setup header/context
            if (modVer == REC_TES4)
            {
            }
            else
            {
            }
        }

        throw std::runtime_error("Unknown file format"); // can't yet use fail() as mCtx is not setup
    }

    void Reader::open(const std::filesystem::path& filename)
    {
        open(Files::openConstrainedFileStream(filename), filename);
    }

    void Reader::setRecHeaderSize(const std::size_t size)
    {
        mCtx.recHeaderSize = size;
    }

    void Reader::buildLStringIndex()
    {
        if ((mHeader.mFlags & Rec_ESM) == 0 || (mHeader.mFlags & Rec_Localized) == 0)
            return;

        const std::u8string prefix = mCtx.filename.stem().filename().u8string();

        buildLStringIndex(LocalizedStringType::Strings, prefix);
        buildLStringIndex(LocalizedStringType::ILStrings, prefix);
        buildLStringIndex(LocalizedStringType::DLStrings, prefix);
    }

    void Reader::buildLStringIndex(LocalizedStringType stringType, const std::u8string& prefix)
    {
        static const std::filesystem::path strings("Strings");
        const std::u8string language(u8"_En");
        const std::u8string altLanguage(u8"_English");
        const std::u8string suffix(getStringsSuffix(stringType));
        std::filesystem::path path = strings / (prefix + language + suffix);
        if (mVFS != nullptr)
        {
            VFS::Path::Normalized vfsPath(Files::pathToUnicodeString(path));
            Files::IStreamPtr stream = mVFS->find(vfsPath);

            if (stream == nullptr)
            {
                path = strings / (prefix + altLanguage + suffix);
                vfsPath = VFS::Path::Normalized(Files::pathToUnicodeString(path));
                stream = mVFS->find(vfsPath);
            }

            if (stream != nullptr)
            {
                buildLStringIndex(stringType, *stream);
                return;
            }

            if (mIgnoreMissingLocalizedStrings)
            {
                Log(Debug::Warning) << "Ignore missing VFS strings file: " << vfsPath;
                return;
            }
        }

        std::filesystem::path fsPath = mCtx.filename.parent_path() / path;
        if (!std::filesystem::exists(fsPath))
        {
            path = strings / (prefix + altLanguage + suffix);
            fsPath = mCtx.filename.parent_path() / path;
        }

        if (std::filesystem::exists(fsPath))
        {
            const Files::IStreamPtr stream = Files::openConstrainedFileStream(fsPath);
            buildLStringIndex(stringType, *stream);
            return;
        }

        if (mIgnoreMissingLocalizedStrings)
            Log(Debug::Warning) << "Ignore missing strings file: " << fsPath;
    }

    void Reader::buildLStringIndex(LocalizedStringType stringType, std::istream& stream)
    {
        stream.seekg(0, std::ios::end);
        const std::istream::pos_type fileSize = stream.tellg();
        stream.seekg(0, std::ios::beg);

        std::uint32_t numEntries = 0;
        stream.read(reinterpret_cast<char*>(&numEntries), sizeof(numEntries));

        std::uint32_t dataSize = 0;
        stream.read(reinterpret_cast<char*>(&dataSize), sizeof(dataSize));

        const std::istream::pos_type dataStart = fileSize - static_cast<std::istream::pos_type>(dataSize);

        struct LocalizedString
        {
            std::uint32_t mOffset = 0;
            std::uint32_t mStringId = 0;
        };

        std::vector<LocalizedString> strings;
        strings.reserve(numEntries);

        for (std::uint32_t i = 0; i < numEntries; ++i)
        {
            LocalizedString string;

            stream.read(reinterpret_cast<char*>(&string.mStringId), sizeof(string.mStringId));
            stream.read(reinterpret_cast<char*>(&string.mOffset), sizeof(string.mOffset));

            strings.push_back(string);
        }

        std::sort(strings.begin(), strings.end(),
            [](const LocalizedString& l, const LocalizedString& r) { return l.mOffset < r.mOffset; });

        std::uint32_t lastOffset = 0;
        std::string_view lastValue;

        for (const LocalizedString& string : strings)
        {
            if (string.mOffset == lastOffset)
            {
                mLStringIndex.emplace(FormId::fromUint32(string.mStringId), lastValue);
                continue;
            }

            const std::istream::pos_type offset = string.mOffset + dataStart;
            const std::istream::pos_type pos = stream.tellg();
            if (pos != offset)
            {
                char buffer[4096];
                if (pos < offset && offset - pos < static_cast<std::istream::pos_type>(sizeof(buffer)))
                    stream.read(buffer, offset - pos);
                else
                    stream.seekg(offset);
            }

            const auto it
                = mLStringIndex.emplace(FormId::fromUint32(string.mStringId), readLocalizedString(stringType, stream))
                      .first;
            lastOffset = string.mOffset;
            lastValue = it->second;
        }
    }

    std::string Reader::readLocalizedString(LocalizedStringType type, std::istream& stream)
    {
        if (type == LocalizedStringType::Strings)
        {
            std::string data;

            while (true)
            {
                char ch = 0;
                stream.read(&ch, sizeof(ch));
                if (ch == 0)
                    break;
                data.push_back(ch);
            }

            return data;
        }

        std::uint32_t size = 0;
        stream.read(reinterpret_cast<char*>(&size), sizeof(size));

        std::string result;
        getStringImpl(result, size, stream, true); // expect null terminated string
        return result;
    }

    void Reader::getLocalizedString(std::string& str)
    {
        if (!hasLocalizedStrings())
            return (void)getZString(str);

        std::uint32_t stringId; // FormId
        get(stringId);
        if (stringId) // TES5 FoxRace, BOOK
            getLocalizedStringImpl(FormId::fromUint32(stringId), str);
    }

    // FIXME: very messy and probably slow/inefficient
    void Reader::getLocalizedStringImpl(const FormId stringId, std::string& str)
    {
        const auto it = mLStringIndex.find(stringId);

        if (it == mLStringIndex.end())
        {
            if (mIgnoreMissingLocalizedStrings)
                return;
            throw std::runtime_error("ESM4::Reader::getLocalizedString localized string not found for "
                + ESM::RefId(stringId).toDebugString());
        }

        str = it->second;
    }

    bool Reader::getRecordHeader()
    {
        // FIXME: this seems very hacky but we may have skipped subrecords from within an inflated data block
        if (/*mStream->eof() && */ mSavedStream)
        {
            mStream = std::move(mSavedStream);
        }

        mStream->read((char*)&mCtx.recordHeader, mCtx.recHeaderSize);
        std::size_t bytesRead = (std::size_t)mStream->gcount();

        // keep track of data left to read from the file
        mCtx.fileRead += mCtx.recHeaderSize;

        mCtx.recordRead = 0; // for keeping track of sub records

        // After reading the record header we can cache a WRLD or CELL formId for convenient access later.
        // FIXME: currently currWorld and currCell are set manually when loading the WRLD and CELL records

        // HACK: mCtx.groupStack.back() is updated before the record data are read/skipped
        //       N.B. the data must be fully read/skipped for this to work
        if (mCtx.recordHeader.record.typeId != REC_GRUP && !mCtx.groupStack.empty())
        {
            mCtx.groupStack.back().second += (std::uint32_t)mCtx.recHeaderSize + mCtx.recordHeader.record.dataSize;

            // keep track of data left to read from the file
            mCtx.fileRead += mCtx.recordHeader.record.dataSize;
        }

        return bytesRead == mCtx.recHeaderSize;
    }

    void Reader::getRecordData(bool dump)
    {
        std::uint32_t uncompressedSize = 0;

        if ((mCtx.recordHeader.record.flags & Rec_Compressed) != 0)
        {
            mStream->read(reinterpret_cast<char*>(&uncompressedSize), sizeof(std::uint32_t));

            const std::streamoff position = mStream->tellg();

            const std::uint32_t recordSize = mCtx.recordHeader.record.dataSize - sizeof(std::uint32_t);
            std::vector<char> compressed(recordSize);
            mStream->read(compressed.data(), recordSize);
            mSavedStream = std::move(mStream);

            mCtx.recordHeader.record.dataSize = uncompressedSize - sizeof(uncompressedSize);

            auto memoryStreamPtr = decompress(position, compressed, uncompressedSize);

            // For debugging only
            // #if 0
            if (dump)
            {
                std::ostringstream ss;
                char* data = memoryStreamPtr->getRawData();
                for (unsigned int i = 0; i < uncompressedSize; ++i)
                {
                    if (data[i] > 64 && data[i] < 91)
                        ss << (char)(data[i]) << " ";
                    else
                        ss << std::setfill('0') << std::setw(2) << std::hex << (int)(data[i]);
                    if ((i & 0x000f) == 0xf)
                        ss << "\n";
                    else if (i < uncompressedSize - 1)
                        ss << " ";
                }
                std::cout << ss.str() << std::endl;
            }
            // #endif
            mStream = std::make_unique<Files::StreamWithBuffer<Bsa::MemoryInputStream>>(std::move(memoryStreamPtr));
        }
    }

    void Reader::skipRecordData()
    {
        if (mCtx.recordRead > mCtx.recordHeader.record.dataSize)
            throw std::runtime_error("Skipping after reading more than available");
        mStream->ignore(mCtx.recordHeader.record.dataSize - mCtx.recordRead);
        mCtx.recordRead = mCtx.recordHeader.record.dataSize; // for getSubRecordHeader()
    }

    bool Reader::getSubRecordHeader()
    {
        bool result = false;
        // NOTE: some SubRecords have 0 dataSize (e.g. SUB_RDSD in one of REC_REGN records in Oblivion.esm).
        if (mCtx.recordHeader.record.dataSize - mCtx.recordRead >= sizeof(mCtx.subRecordHeader))
        {
            result = getExact(mCtx.subRecordHeader);
            // HACK: below assumes sub-record data will be read or skipped in full;
            //       this hack aims to avoid updating mCtx.recordRead each time anything is read
            mCtx.recordRead += (sizeof(mCtx.subRecordHeader) + mCtx.subRecordHeader.dataSize);
        }
        else if (mCtx.recordRead > mCtx.recordHeader.record.dataSize)
        {
            // try to correct any overshoot, seek to the end of the expected data
            // this will only work if mCtx.subRecordHeader.dataSize was fully read or skipped
            // (i.e. it will only correct mCtx.subRecordHeader.dataSize being incorrect)
            // TODO: not tested
            std::uint32_t overshoot = (std::uint32_t)mCtx.recordRead - mCtx.recordHeader.record.dataSize;

            std::size_t pos = mStream->tellg();
            mStream->seekg(pos - overshoot);

            return false;
        }

        // Extended storage subrecord redefines the following subrecord's size.
        // Would need to redesign the loader to support that, so skip over both subrecords.
        if (result && mCtx.subRecordHeader.typeId == ESM::fourCC("XXXX"))
        {
            std::uint32_t extDataSize;
            get(extDataSize);
            if (!getSubRecordHeader())
                return false;

            skipSubRecordData(extDataSize);
            mCtx.recordRead += extDataSize - mCtx.subRecordHeader.dataSize;
            return getSubRecordHeader();
        }

        return result;
    }

    void Reader::skipSubRecordData()
    {
        mStream->ignore(mCtx.subRecordHeader.dataSize);
    }

    void Reader::skipSubRecordData(std::uint32_t size)
    {
        mStream->ignore(size);
    }

    void Reader::enterGroup()
    {
#ifdef DEBUG_GROUPSTACK
        std::string padding; // FIXME: debugging only
        padding.insert(0, mCtx.groupStack.size() * 2, ' ');
        std::cout << padding << "Starting record group "
                  << printLabel(mCtx.recordHeader.group.label, mCtx.recordHeader.group.type) << std::endl;
#endif
        // empty group if the group size is same as the header size
        if (mCtx.recordHeader.group.groupSize == (std::uint32_t)mCtx.recHeaderSize)
        {
#ifdef DEBUG_GROUPSTACK
            std::cout << padding << "Ignoring record group " // FIXME: debugging only
                      << printLabel(mCtx.recordHeader.group.label, mCtx.recordHeader.group.type) << " (empty)"
                      << std::endl;
#endif
            if (!mCtx.groupStack.empty()) // top group may be empty (e.g. HAIR in Skyrim)
            {
                // don't put on the stack, exitGroupCheck() may not get called before recursing into this method
                mCtx.groupStack.back().second += mCtx.recordHeader.group.groupSize;
                exitGroupCheck();
            }

            return; // don't push an empty group, just return
        }

        // push group
        mCtx.groupStack.push_back(std::make_pair(mCtx.recordHeader.group, (std::uint32_t)mCtx.recHeaderSize));
    }

    void Reader::exitGroupCheck()
    {
        if (mCtx.groupStack.empty())
            return;

        // pop finished groups (note reading too much is allowed here)
        std::uint32_t lastGroupSize = mCtx.groupStack.back().first.groupSize;
        while (mCtx.groupStack.back().second >= lastGroupSize)
        {
#ifdef DEBUG_GROUPSTACK
            GroupTypeHeader grp = mCtx.groupStack.back().first; // FIXME: grp is for debugging only
#endif
            // try to correct any overshoot
            // TODO: not tested
            std::uint32_t overshoot = mCtx.groupStack.back().second - lastGroupSize;
            if (overshoot > 0)
            {
                std::size_t pos = mStream->tellg();
                mStream->seekg(pos - overshoot);
            }

            mCtx.groupStack.pop_back();
#ifdef DEBUG_GROUPSTACK
            std::string padding; // FIXME: debugging only
            padding.insert(0, mCtx.groupStack.size() * 2, ' ');
            std::cout << padding << "Finished record group " << printLabel(grp.label, grp.type) << std::endl;
#endif
            // if the previous group was the final one no need to do below
            if (mCtx.groupStack.empty())
                return;

            mCtx.groupStack.back().second += lastGroupSize;
            lastGroupSize = mCtx.groupStack.back().first.groupSize;

            if (lastGroupSize < mCtx.groupStack.back().second)
                throw std::runtime_error("Read more records than available");

            // #if 0
            if (mCtx.groupStack.back().second > lastGroupSize) // FIXME: debugging only
                std::cerr << printLabel(mCtx.groupStack.back().first.label, mCtx.groupStack.back().first.type)
                          << " read more records than available" << std::endl;
            // #endif
        }
    }

    // WARNING: this method should be used after first calling enterGroup()
    // else the method may try to dereference an element that does not exist
    const GroupTypeHeader& Reader::grp(std::size_t pos) const
    {
        if (mCtx.groupStack.size() == 0)
            throw std::runtime_error("ESM4::Reader::grp mCtx.groupStack.size is zero");
        if (pos > mCtx.groupStack.size() - 1)
            throw std::runtime_error("ESM4::Reader::grp - exceeded stack depth");

        return (*(mCtx.groupStack.end() - pos - 1)).first;
    }

    void Reader::skipGroupData()
    {
        if (mCtx.groupStack.empty())
            throw std::runtime_error("Skipping group with an empty stack");

        // subtract what was already read/skipped
        std::uint32_t skipSize = mCtx.groupStack.back().first.groupSize - mCtx.groupStack.back().second;

        mStream->ignore(skipSize);

        // keep track of data left to read from the file
        mCtx.fileRead += skipSize;

        mCtx.groupStack.back().second = mCtx.groupStack.back().first.groupSize;
    }

    void Reader::skipGroup()
    {
#ifdef DEBUG_GROUPSTACK
        std::string padding; // FIXME: debugging only
        padding.insert(0, mCtx.groupStack.size() * 2, ' ');
        std::cout << padding << "Skipping record group "
                  << printLabel(mCtx.recordHeader.group.label, mCtx.recordHeader.group.type) << std::endl;
#endif
        // subtract the size of header already read before skipping
        std::uint32_t skipSize = mCtx.recordHeader.group.groupSize - (std::uint32_t)mCtx.recHeaderSize;
        mStream->ignore(skipSize);

        // keep track of data left to read from the file
        mCtx.fileRead += skipSize;

        // NOTE: mCtx.groupStack.back().second already has mCtx.recHeaderSize from enterGroup()
        if (!mCtx.groupStack.empty())
            mCtx.groupStack.back().second += mCtx.recordHeader.group.groupSize;
    }

    const CellGrid& Reader::currCellGrid() const
    {
        if (!mCtx.cellGridValid)
            throw std::runtime_error("Attempt to use an invalid cell grid");

        return mCtx.currCellGrid;
    }

    void Reader::updateModIndices(const std::map<std::string, int>& fileToModIndex)
    {
        mCtx.parentFileIndices.resize(mHeader.mMaster.size());
        for (unsigned int i = 0; i < mHeader.mMaster.size(); ++i)
        {
            // locate the position of the dependency in already loaded files
            auto it = fileToModIndex.find(Misc::StringUtils::lowerCase(mHeader.mMaster[i].name));
            if (it != fileToModIndex.end())
                mCtx.parentFileIndices[i] = it->second;
            else
                throw std::runtime_error(
                    "ESM4::Reader::updateModIndices required dependency '" + mHeader.mMaster[i].name + "' not found");
        }
    }

    // ModIndex adjusted formId according to master file dependencies
    // (see http://www.uesp.net/wiki/Tes4Mod:FormID_Fixup)
    // NOTE: need to update modindex to parentFileIndices.size() before saving
    //
    // FIXME: probably should add a parameter to check for mCtx.header::mOverrides
    //        (ACHR, LAND, NAVM, PGRE, PHZD, REFR), but not sure what exactly overrides mean
    //        i.e. use the modindx of its master?
    // FIXME: Apparently ModIndex '00' in an ESP means the object is defined in one of its masters.
    //        This means we may need to search multiple times to get the correct id.
    //        (see https://www.uesp.net/wiki/Tes4Mod:Formid#ModIndex_Zero)
    void Reader::adjustFormId(FormId& id) const
    {
        if (id.hasContentFile() && id.mContentFile < static_cast<int>(mCtx.parentFileIndices.size()))
            id.mContentFile = mCtx.parentFileIndices[id.mContentFile];
        else
            id.mContentFile = mCtx.modIndex;
    }

    void Reader::adjustFormId(FormId32& id) const
    {
        FormId formId = FormId::fromUint32(id);
        adjustFormId(formId);
        id = formId.toUint32();
    }

    bool Reader::getFormId(FormId& id)
    {
        FormId32 v;
        if (!getExact(v))
            return false;
        id = FormId::fromUint32(v);

        adjustFormId(id);
        return true;
    }

    ESM::FormId Reader::getFormIdFromHeader() const
    {
        FormId formId = hdr().record.getFormId();
        adjustFormId(formId);
        return formId;
    }

    void Reader::adjustGRUPFormId()
    {
        adjustFormId(mCtx.recordHeader.group.label.value);
    }

    [[noreturn]] void Reader::fail(const std::string& msg)
    {
        std::stringstream ss;

        ss << "ESM Error: " << msg;
        ss << "\n  File: " << Files::pathToUnicodeString(mCtx.filename);
        ss << "\n  Record: " << ESM::printName(mCtx.recordHeader.record.typeId);
        ss << "\n  Subrecord: " << ESM::printName(mCtx.subRecordHeader.typeId);
        if (mStream.get())
            ss << "\n  Offset: 0x" << std::hex << mStream->tellg();

        throw std::runtime_error(ss.str());
    }

    bool Reader::getStringImpl(std::string& str, std::size_t size, std::istream& stream, bool hasNull)
    {
        std::size_t newSize = size;

        if (mEncoder != nullptr)
        {
            std::string input(size, '\0');
            stream.read(input.data(), size);
            if (stream.gcount() == static_cast<std::streamsize>(size))
            {
                const std::string_view result
                    = mEncoder->getUtf8(input, ToUTF8::BufferAllocationPolicy::FitToRequiredSize, str);
                if (str.empty() && !result.empty())
                {
                    str = std::move(input);
                    str.resize(result.size());
                }
                return true;
            }
        }
        else
        {
            if (hasNull)
                newSize -= 1; // don't read the null terminator yet

            str.resize(newSize); // assumed C++11
            stream.read(str.data(), newSize);
            if (static_cast<std::size_t>(stream.gcount()) == newSize)
            {
                if (hasNull)
                {
                    char ch;
                    stream.read(&ch, 1); // read the null terminator
                    if (ch != '\0')
                        throw std::runtime_error("ESM4::Reader::getString string is not terminated with a null");
                }
#if 0
            else
            {
                // NOTE: normal ESMs don't but omwsave has locals or spells with null terminator
                assert (str[newSize - 1] != '\0'
                        && "ESM4::Reader::getString string is unexpectedly terminated with a null");
            }
#endif
                return true;
            }
        }

        str.clear();
        return false; // FIXME: throw instead?
    }

    bool Reader::getZeroTerminatedStringArray(std::vector<std::string>& values)
    {
        const std::size_t size = mCtx.subRecordHeader.dataSize;
        std::string input(size, '\0');
        mStream->read(input.data(), size);

        if (mStream->gcount() != static_cast<std::streamsize>(size))
            return false;

        std::string_view inputView(input.data(), input.size());
        std::string buffer;
        while (true)
        {
            std::string_view value(inputView.data());
            const std::size_t next = inputView.find_first_not_of('\0', value.size());
            if (mEncoder != nullptr)
                value = mEncoder->getUtf8(value, ToUTF8::BufferAllocationPolicy::UseGrowFactor, buffer);
            values.emplace_back(value);
            if (next == std::string_view::npos)
                break;
            inputView = inputView.substr(next);
        }

        return true;
    }

    namespace
    {
        constexpr std::string_view sGroupType[] = {
            "Record Type",
            "World Child",
            "Interior Cell",
            "Interior Sub Cell",
            "Exterior Cell",
            "Exterior Sub Cell",
            "Cell Child",
            "Topic Child",
            "Cell Persistent Child",
            "Cell Temporary Child",
            "Cell Visible Dist Child",
            "Unknown",
        };
    }

    std::string printLabel(const GroupLabel& label, const std::uint32_t type)
    {
        std::ostringstream ss;
        ss << sGroupType[std::min<std::size_t>(type, std::size(sGroupType))]; // avoid out of range

        switch (type)
        {
            case ESM4::Grp_RecordType:
            {
                ss << ": " << std::string((char*)label.recordType, 4);
                break;
            }
            case ESM4::Grp_ExteriorCell:
            case ESM4::Grp_ExteriorSubCell:
            {
                // short x, y;
                // y = label & 0xff;
                // x = (label >> 16) & 0xff;
                ss << ": grid (x, y) " << std::dec << label.grid[1] << ", " << label.grid[0];

                break;
            }
            case ESM4::Grp_InteriorCell:
            case ESM4::Grp_InteriorSubCell:
            {
                ss << ": block 0x" << std::hex << label.value;
                break;
            }
            case ESM4::Grp_WorldChild:
            case ESM4::Grp_CellChild:
            case ESM4::Grp_TopicChild:
            case ESM4::Grp_CellPersistentChild:
            case ESM4::Grp_CellTemporaryChild:
            case ESM4::Grp_CellVisibleDistChild:
            {
                ss << ": " << ESM::RefId(FormId::fromUint32(label.value));
                break;
            }
            default:
                break;
        }

        return ss.str();
    }
}