iw4x-client/src/Components/Modules/StringTable.cpp

93 lines
2.2 KiB
C++
Raw Normal View History

2016-01-12 15:17:55 -05:00
#include "STDInclude.hpp"
namespace Components
{
2016-06-08 11:28:58 -04:00
Utils::Memory::Allocator StringTable::MemAllocator;
2016-01-12 15:17:55 -05:00
std::map<std::string, Game::StringTable*> StringTable::StringTableMap;
int StringTable::Hash(const char* data)
{
int hash = 0;
while (*data != 0)
{
hash = tolower(*data) + (31 * hash);
data++;
}
return hash;
}
Game::StringTable* StringTable::LoadObject(std::string filename)
2016-01-12 15:17:55 -05:00
{
Game::StringTable* table = nullptr;
FileSystem::File rawTable(filename);
if (rawTable.Exists())
{
Utils::CSV parsedTable(rawTable.GetBuffer(), false, false);
2016-01-12 15:17:55 -05:00
2016-06-08 11:28:58 -04:00
table = StringTable::MemAllocator.AllocateArray<Game::StringTable>(1);
2016-01-12 15:17:55 -05:00
if (table)
{
2016-06-08 11:28:58 -04:00
table->name = StringTable::MemAllocator.DuplicateString(filename);
2016-01-12 15:17:55 -05:00
table->columnCount = parsedTable.GetColumns();
table->rowCount = parsedTable.GetRows();
2016-06-08 11:28:58 -04:00
table->values = StringTable::MemAllocator.AllocateArray<Game::StringTableCell>(table->columnCount * table->rowCount);
2016-01-12 15:17:55 -05:00
if (!table->values)
{
return nullptr;
}
2016-01-24 13:58:13 -05:00
for (int i = 0; i < table->rowCount; ++i)
2016-01-12 15:17:55 -05:00
{
2016-01-24 13:58:13 -05:00
for (int j = 0; j < table->columnCount; ++j)
2016-01-12 15:17:55 -05:00
{
Game::StringTableCell* cell = &table->values[i * table->columnCount + j];
cell->hash = StringTable::Hash(parsedTable.GetElementAt(i, j).data());
2016-06-08 11:28:58 -04:00
cell->string = StringTable::MemAllocator.DuplicateString(parsedTable.GetElementAt(i, j));
2016-01-12 15:17:55 -05:00
//if (!cell->string) cell->string = ""; // We have to assume it allocated successfully
}
}
StringTable::StringTableMap[filename] = table;
}
}
else
{
StringTable::StringTableMap[filename] = nullptr;
}
return table;
}
StringTable::StringTable()
{
AssetHandler::OnFind(Game::XAssetType::ASSET_TYPE_STRINGTABLE, [] (Game::XAssetType, std::string filename)
2016-01-12 15:17:55 -05:00
{
Game::XAssetHeader header = { 0 };
if (StringTable::StringTableMap.find(filename) != StringTable::StringTableMap.end())
{
header.stringTable = StringTable::StringTableMap[filename];
}
else
{
header.stringTable = StringTable::LoadObject(filename);
}
return header;
});
}
StringTable::~StringTable()
{
StringTable::StringTableMap.clear();
2016-06-08 11:28:58 -04:00
StringTable::MemAllocator.Free();
2016-01-12 15:17:55 -05:00
}
}