quake-tools/source/quam/pak.cc

94 lines
1.9 KiB
C++
Raw Normal View History

2019-09-27 00:09:09 -07:00
#include "common.h"
#include "quam/pak.h"
struct PakHeader {
quint32 dirOffset;
quint32 dirNum;
};
struct PakEntry {
std::string name;
2019-09-27 23:09:51 -07:00
PakFile data;
2019-09-27 00:09:09 -07:00
};
static constexpr quint32 sizeOfPakEntry = 64;
static PakHeader readPakHeader(std::istream &st) {
auto magic = readBytes<4>(st);
if(magic != std::array{'P', 'A', 'C', 'K'}) {
throw std::runtime_error("not a pak file (invalid magic number)");
}
auto dirOffset = readLE<quint32>(st);
auto dirSize = readLE<quint32>(st);
if(dirSize % sizeOfPakEntry != 0) {
throw std::runtime_error("invalid directory size");
}
PakHeader hdr;
hdr.dirOffset = dirOffset;
hdr.dirNum = dirSize / sizeOfPakEntry;
return hdr;
}
static PakEntry readPakEntry(std::istream &st) {
auto entName = readBytes<56>(st);
auto entOffset = readLE<quint32>(st);
auto entSize = readLE<quint32>(st);
auto pos = st.tellg();
st.seekg(entOffset);
2019-09-27 23:09:51 -07:00
PakFile bytes;
2019-09-27 00:09:09 -07:00
bytes.resize(entSize);
st.read(bytes.data(), entSize);
st.seekg(pos);
auto zero = std::find(entName.cbegin(), entName.cend(), '\0');
2019-09-27 23:09:51 -07:00
std::string name;
std::copy(entName.cbegin(), zero, std::back_inserter(name));
if(name.front() == '/') {
2019-09-28 01:17:55 -07:00
throw std::runtime_error("empty root directory name");
2019-09-27 23:09:51 -07:00
}
2019-09-27 00:09:09 -07:00
PakEntry ent;
2019-09-27 23:09:51 -07:00
ent.name = std::move(name);
2019-09-27 00:09:09 -07:00
ent.data = std::move(bytes);
return ent;
}
2019-09-27 23:09:51 -07:00
void insertFile(PakDir &dir, std::string name, PakFile file) {
if(auto slash = name.find('/'); slash != std::string::npos) {
auto folder = name.substr(0, slash);
auto next = name.substr(slash + 1);
2019-09-28 01:17:55 -07:00
dir[folder] = PakNode{PakDir{}};
insertFile(std::get<PakDir>(dir[folder]),
2019-09-27 23:09:51 -07:00
std::move(next),
std::move(file));
} else {
2019-09-28 01:17:55 -07:00
dir[name] = PakNode{std::move(file)};
2019-09-27 23:09:51 -07:00
}
}
PakDir readPak(std::istream &st) {
2019-09-27 00:09:09 -07:00
auto hdr = readPakHeader(st);
st.seekg(hdr.dirOffset);
2019-09-27 23:09:51 -07:00
PakDir root;
2019-09-27 00:09:09 -07:00
for(quint32 i = 0; i < hdr.dirNum; i++) {
auto ent = readPakEntry(st);
2019-09-27 23:09:51 -07:00
insertFile(root, std::move(ent.name), std::move(ent.data));
2019-09-27 00:09:09 -07:00
}
2019-09-27 23:09:51 -07:00
return root;
2019-09-27 00:09:09 -07:00
}
// EOF