1
0
cuberite-2a/src/WorldStorage/StatSerializer.cpp
peterbell10 e6634ed26c
Update submodules (#4727)
Closes #4708

This updates jsoncpp, mbedtls, TCLAP and SQLiteCpp to their latest stable release. A few additional changes were needed:

* jsoncpp deprecated Reader, FastWriter and StyledWriter which I've replaced
  with some helper functions in JsonUtils.cpp

* SQLiteCpp changed how it builds with external sqlite libraries, now expecting
  them to be installed. The simplest path was to remove sqlite from cuberite's
  submodule and just use SQLiteCpp's internal version.
2020-05-09 15:51:15 +01:00

151 lines
2.5 KiB
C++

// StatSerializer.cpp
#include "Globals.h"
#include "StatSerializer.h"
#include "../Statistics.h"
#include "../JsonUtils.h"
cStatSerializer::cStatSerializer(const AString & a_WorldName, const AString & a_PlayerName, const AString & a_FileName, cStatManager * a_Manager)
: m_Manager(a_Manager)
{
// Even though stats are shared between worlds, they are (usually) saved
// inside the folder of the default world.
AString StatsPath;
Printf(StatsPath, "%s%cstats", a_WorldName.c_str(), cFile::PathSeparator());
m_LegacyPath = StatsPath + "/" + a_PlayerName + ".json";
m_Path = StatsPath + "/" + a_FileName + ".json";
// Ensure that the directory exists.
cFile::CreateFolder(StatsPath);
}
bool cStatSerializer::Load(void)
{
AString Data = cFile::ReadWholeFile(m_Path);
if (Data.empty())
{
Data = cFile::ReadWholeFile(m_LegacyPath);
if (Data.empty())
{
return false;
}
}
Json::Value Root;
if (JsonUtils::ParseString(Data, Root))
{
return LoadStatFromJSON(Root);
}
return false;
}
bool cStatSerializer::Save(void)
{
Json::Value Root;
SaveStatToJSON(Root);
cFile File;
if (!File.Open(m_Path, cFile::fmWrite))
{
return false;
}
AString JsonData = JsonUtils::WriteStyledString(Root);
File.Write(JsonData.data(), JsonData.size());
File.Close();
return true;
}
void cStatSerializer::SaveStatToJSON(Json::Value & a_Out)
{
for (unsigned int i = 0; i < static_cast<unsigned int>(statCount); ++i)
{
StatValue Value = m_Manager->GetValue(static_cast<eStatistic>(i));
if (Value != 0)
{
const AString & StatName = cStatInfo::GetName(static_cast<eStatistic>(i));
a_Out[StatName] = Value;
}
// TODO 2014-05-11 xdot: Save "progress"
}
}
bool cStatSerializer::LoadStatFromJSON(const Json::Value & a_In)
{
m_Manager->Reset();
for (Json::Value::const_iterator it = a_In.begin() ; it != a_In.end() ; ++it)
{
AString StatName = it.key().asString();
eStatistic StatType = cStatInfo::GetType(StatName);
if (StatType == statInvalid)
{
LOGWARNING("Invalid statistic type \"%s\"", StatName.c_str());
continue;
}
const Json::Value & Node = *it;
if (Node.isInt())
{
m_Manager->SetValue(StatType, Node.asInt());
}
else if (Node.isObject())
{
StatValue Value = Node.get("value", 0).asInt();
// TODO 2014-05-11 xdot: Load "progress"
m_Manager->SetValue(StatType, Value);
}
else
{
LOGWARNING("Invalid statistic value for type \"%s\"", StatName.c_str());
}
}
return true;
}