summaryrefslogtreecommitdiffstats
path: root/src/WorldStorage/StatisticsSerializer.cpp
blob: 2e68188a29f717ec53eb3f775a377a647b9c3a67 (plain) (blame)
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

// StatisticsSerializer.cpp


#include "Globals.h"
#include "StatisticsManager.h"
#include "StatisticsSerializer.h"
#include "NamespaceSerializer.h"

#include <json/json.h>





static auto MakeStatisticsDirectory(const std::string & WorldPath, std::string && FileName)
{
	// Even though stats are shared between worlds, they are (usually) saved
	// inside the folder of the default world.

	// Path to the world's statistics folder.
	const auto Path = WorldPath + cFile::GetPathSeparator() + "stats";

	// Ensure that the directory exists.
	cFile::CreateFolder(Path);

	return Path + cFile::GetPathSeparator() + std::move(FileName) + ".json";
}





static void SaveStatToJSON(const StatisticsManager & Manager, Json::Value & a_Out)
{
	if (Manager.Custom.empty())
	{
		// Avoid saving "custom": null to disk:
		return;
	}

	auto & Custom = a_Out["custom"];
	for (const auto & [Statistic, Value] : Manager.Custom)
	{
		Custom[NamespaceSerializer::From(Statistic).data()] = Value;
	}
}





static void LoadCustomStatFromJSON(StatisticsManager & Manager, const Json::Value & a_In)
{
	for (auto it = a_In.begin(); it != a_In.end(); ++it)
	{
		const auto & Key = it.key().asString();
		const auto & [Namespace, Name] = NamespaceSerializer::SplitNamespacedID(Key);

		if (Namespace == NamespaceSerializer::Namespace::Unknown)
		{
			// Ignore non-Vanilla, non-Cuberite namespaces for now:
			continue;
		}

		Manager.Custom[NamespaceSerializer::ToCustomStatistic(Name)] = it->asUInt();
	}
}





void StatisticsSerializer::Load(StatisticsManager & Manager, const std::string & WorldPath, std::string && FileName)
{
	Json::Value Root;
	InputFileStream(MakeStatisticsDirectory(WorldPath, std::move(FileName))) >> Root;

	LoadCustomStatFromJSON(Manager, Root["stats"]["custom"]);
}





void StatisticsSerializer::Save(
	const StatisticsManager & Manager,
	const std::string & WorldPath,
	std::string && FileName
)
{
	Json::Value Root;

	SaveStatToJSON(Manager, Root["stats"]);
	Root["DataVersion"] = NamespaceSerializer::DataVersion();

	OutputFileStream(MakeStatisticsDirectory(WorldPath, std::move(FileName))) << Root;
}