#include "remorse/flex_archive.h" #include "remorse/file_system.h" namespace remorse { namespace { constexpr u32 flexCountOffset = 0x54; constexpr u32 flexTableOffset = 0x80; constexpr u32 flexEntrySize = 8; std::optional readU32Le(const std::vector& bytes, u32 offset) { if (offset + 4 > bytes.size()) { return std::nullopt; } return static_cast(bytes[offset]) | (static_cast(bytes[offset + 1]) << 8) | (static_cast(bytes[offset + 2]) << 16) | (static_cast(bytes[offset + 3]) << 24); } } // namespace std::optional loadFlexArchive(const std::filesystem::path& path) { auto bytes = readBinaryFile(path); if (!bytes) { return std::nullopt; } const auto entryCount = readU32Le(*bytes, flexCountOffset); if (!entryCount) { return std::nullopt; } const u32 tableEnd = flexTableOffset + (*entryCount * flexEntrySize); if (tableEnd > bytes->size()) { return std::nullopt; } FlexArchive archive; archive.entryCount = *entryCount; archive.bytes = *bytes; for (u32 index = 0; index < archive.entryCount; ++index) { const u32 tableOffset = flexTableOffset + (index * flexEntrySize); const auto dataOffset = readU32Le(archive.bytes, tableOffset); const auto dataSize = readU32Le(archive.bytes, tableOffset + 4); if (!dataOffset || !dataSize) { return std::nullopt; } if (*dataOffset == 0 && *dataSize == 0) { continue; } if (*dataOffset == 0 || *dataSize == 0) { continue; } if (*dataOffset > archive.bytes.size() || *dataSize > archive.bytes.size() - *dataOffset) { continue; } archive.populatedEntries.push_back(FlexEntry{index, *dataOffset, *dataSize}); } return archive; } std::optional> readFlexEntry(const FlexArchive& archive, u32 index) { for (const FlexEntry& entry : archive.populatedEntries) { if (entry.index == index) { const auto begin = archive.bytes.begin() + entry.offset; const auto end = begin + entry.size; return std::vector(begin, end); } } return std::nullopt; } } // namespace remorse