vkmEngine 1.0.15
A C++ game engine · vkmengine.com
Loading...
Searching...
No Matches
reflect_json.h
1#pragma once
2
3#include <cstddef>
4#include <cstdint>
5#include <cstring>
6#include <string>
7#include <type_traits>
8#include <vector>
9
10#include <glm/glm.hpp>
11#include <glm/gtc/quaternion.hpp>
12#include <nlohmann/json.hpp>
13
14#include "logger.h"
15
16#include "core/reflect.h"
17#include "io/json_vec.h"
18#include "resource/resource_handle.h"
19
33
34// The leaves every field comes down to; a new field type adds a pair here.
35inline nlohmann::json leafToJson(bool v) { return v; }
36inline nlohmann::json leafToJson(int v) { return v; }
37inline nlohmann::json leafToJson(uint32_t v) { return v; }
38inline nlohmann::json leafToJson(float v) { return v; }
39inline nlohmann::json leafToJson(const std::string& s) { return s; }
40inline nlohmann::json leafToJson(const glm::vec2& v) { return detail::vec2ToJson(v); }
41inline nlohmann::json leafToJson(const glm::vec3& v) { return detail::vec3ToJson(v); }
42inline nlohmann::json leafToJson(const glm::vec4& v) { return detail::vec4ToJson(v); }
43inline nlohmann::json leafToJson(const glm::quat& q) { return detail::quatToJson(q); }
44
45inline void leafFromJson(const nlohmann::json& j, bool& v) { v = j.get<bool>(); }
46inline void leafFromJson(const nlohmann::json& j, int& v) { v = j.get<int>(); }
47inline void leafFromJson(const nlohmann::json& j, uint32_t& v) { v = j.get<uint32_t>(); }
48inline void leafFromJson(const nlohmann::json& j, float& v) { v = j.get<float>(); }
49inline void leafFromJson(const nlohmann::json& j, std::string& s) { s = j.get<std::string>(); }
50inline void leafFromJson(const nlohmann::json& j, glm::vec2& v) { v = detail::jsonToVec2(j, v); }
51inline void leafFromJson(const nlohmann::json& j, glm::vec3& v) { v = detail::jsonToVec3(j, v); }
52inline void leafFromJson(const nlohmann::json& j, glm::vec4& v) { v = detail::jsonToVec4(j, v); }
53inline void leafFromJson(const nlohmann::json& j, glm::quat& q) { q = detail::jsonToQuat(j, q); }
54
55// Fixed-size character buffers (Name::value).
56template<std::size_t N>
57inline nlohmann::json leafToJson(const char (&v)[N]) { return std::string(v); }
58template<std::size_t N>
59inline void leafFromJson(const nlohmann::json& j, char (&v)[N]) {
60 const std::string s = j.get<std::string>();
61 std::strncpy(v, s.c_str(), N - 1);
62 v[N - 1] = '\0';
63}
64
65// Scoped enums registered via VKM_ENUM_NAMES. The SFINAE leaves non-enum types to the overloads
66// above.
67template<typename E, typename = std::enable_if_t<std::is_enum_v<E>>>
68inline nlohmann::json leafToJson(E v) { return Reflect::enumName(v); }
69template<typename E, typename = std::enable_if_t<std::is_enum_v<E>>>
70inline void leafFromJson(const nlohmann::json& j, E& v) {
71 const std::string name = j.get<std::string>();
72 // An unknown name keeps the constructed default and warns, rather than becoming a
73 // valid-looking enumerator zero.
74 if (!Reflect::enumFromNameChecked(name, v)) {
75 LOG_WARNING_C(
76 "IO",
77 "No enumerator called '%s' in this build; leaving the field at its default",
78 name.c_str()
79 );
80 }
81}
82
83template<typename T> struct IsHandle : std::false_type {};
84template<typename A> struct IsHandle<Handle<A>> : std::true_type {};
85template<typename T> struct IsVector : std::false_type {};
86template<typename E, typename A> struct IsVector<std::vector<E, A>> : std::true_type {};
87
95struct PlainData {
96 static constexpr bool KEEPS_WRONG_FIELDS = false;
97};
98
101 static constexpr bool KEEPS_WRONG_FIELDS = true;
102};
103
104template<typename T, typename Ctx>
105nlohmann::json saveFields(const T& obj, const Ctx& ctx);
106template<typename T, typename Ctx>
107void loadFields(const nlohmann::json& j, T& obj, const Ctx& ctx, const char* path = nullptr);
108
116inline std::string childPath(const char* parent, const std::string& step) {
117 return (parent && *parent) ? std::string(parent) + "." + step : step;
118}
119
124template<typename V, typename Ctx>
125nlohmann::json valueToJson(const V& val, const Ctx& ctx) {
126 if constexpr (IsHandle<V>::value) {
127 static_assert(!std::is_base_of_v<PlainData, Ctx>, "a Handle<T> needs a context that names assets");
128 return ctx.handleToJson(val);
129 } else if constexpr (IsVector<V>::value) {
130 nlohmann::json arr = nlohmann::json::array();
131 for (const auto& element : val) arr.push_back(valueToJson(element, ctx));
132 return arr;
133 } else if constexpr (Reflect::IS_REFLECTED<V>) {
134 return saveFields(val, ctx);
135 } else {
136 return leafToJson(val);
137 }
138}
139
146template<typename V, typename Ctx>
147void valueFromJson(const nlohmann::json& j, V& val, const Ctx& ctx, const char* field) {
148 if constexpr (IsHandle<V>::value) {
149 static_assert(!std::is_base_of_v<PlainData, Ctx>, "a Handle<T> needs a context that names assets");
150 ctx.handleFromJson(j, val, field);
151 } else if constexpr (IsVector<V>::value && Ctx::KEEPS_WRONG_FIELDS) {
152 // Read aside, each element strictly, and kept whole: a list that is no list, or wrong
153 // anywhere inside - a value of the wrong type, an element that is no object - keeps the one
154 // there was rather than an element half its defaults. A glm value of the wrong shape, or
155 // an enumerator this build does not know, reads as its default with a warning, as anywhere.
156 V read;
157 const nlohmann::json::array_t& elements = j.get_ref<const nlohmann::json::array_t&>();
158 read.reserve(elements.size());
159 for (const nlohmann::json& element : elements) {
160 typename V::value_type item{};
161 valueFromJson(element, item, PlainData{}, nullptr);
162 read.push_back(std::move(item));
163 }
164 val = std::move(read);
165 } else if constexpr (IsVector<V>::value) {
166 // A list that is no list is a value of the wrong type, as any other.
167 const nlohmann::json::array_t& elements = j.get_ref<const nlohmann::json::array_t&>();
168 val.clear();
169 val.reserve(elements.size());
170 for (size_t i = 0; i < elements.size(); ++i) {
171 typename V::value_type item{};
172 valueFromJson(elements[i], item, ctx, childPath(field, std::to_string(i)).c_str());
173 val.push_back(std::move(item));
174 }
175 } else if constexpr (Reflect::IS_REFLECTED<V>) {
176 loadFields(j, val, ctx, field);
177 } else {
178 leafFromJson(j, val);
179 }
180}
181
182template<typename T, typename Ctx>
183nlohmann::json saveFields(const T& obj, const Ctx& ctx) {
184 nlohmann::json out = nlohmann::json::object();
185 Reflect::forEachField(obj, [&](std::string_view name, const auto& val) {
186 out[std::string(name)] = valueToJson(val, ctx);
187 });
188 return out;
189}
190
191template<typename T, typename Ctx>
192void loadFields(const nlohmann::json& j, T& obj, const Ctx& ctx, const char* path) {
193 if (!j.is_object()) {
194 // Wrong as any field of the wrong type is: kept in a project's own file, refused anywhere else.
195 if constexpr (Ctx::KEEPS_WRONG_FIELDS) {
196 LOG_WARNING_C("IO", "a struct holds no object; leaving it as it was");
197 } else {
198 (void)j.get_ref<const nlohmann::json::object_t&>();
199 }
200 return;
201 }
202 Reflect::forEachField(obj, [&](std::string_view name, auto& val) {
203 const std::string key(name);
204 const auto it = j.find(key);
205 if (it == j.end()) return;
206 const std::string field = childPath(path, key);
207 if constexpr (Ctx::KEEPS_WRONG_FIELDS) {
208 try {
209 valueFromJson(*it, val, ctx, field.c_str());
210 } catch (const nlohmann::json::exception&) {
211 LOG_WARNING_C(
212 "IO",
213 "'%s' holds a value of the wrong type; leaving the field as it was",
214 key.c_str()
215 );
216 }
217 } else {
218 valueFromJson(*it, val, ctx, field.c_str());
219 }
220 });
221}
222
229template<typename T>
230nlohmann::json toJson(const T& obj) {
231 return saveFields(obj, OwnFile{});
232}
233
240template<typename T>
241void fromJson(const nlohmann::json& j, T& obj) {
242 loadFields(j, obj, OwnFile{});
243}
244
245} // namespace Vkm::Engine::ReflectJson
A reflected struct to JSON and back, field by field, by its VKM_REFLECT names.
Definition reflect_json.h:32
void fromJson(const nlohmann::json &j, T &obj)
The fields j has written into obj; any it lacks, or holds wrongly, kept.
Definition reflect_json.h:241
nlohmann::json toJson(const T &obj)
A reflected struct of plain data as a JSON object, a key a field.
Definition reflect_json.h:230
void valueFromJson(const nlohmann::json &j, V &val, const Ctx &ctx, const char *field)
The same in the other direction.
Definition reflect_json.h:147
std::string childPath(const char *parent, const std::string &step)
Where step stands below parent, the steps joined by dots: "levels.2.mesh".
Definition reflect_json.h:116
nlohmann::json valueToJson(const V &val, const Ctx &ctx)
One value to JSON, whatever kind of value it is: a handle its name, a vector an array,...
Definition reflect_json.h:125
Opaque, type-safe handle for resources, distinguished by ResourceType.
Definition resource_handle.h:16
Plain data in a project's own file: a field of the wrong type keeps its value and warns.
Definition reflect_json.h:100
The context for plain data in a scene, which names no assets: a number, string, list or struct of the...
Definition reflect_json.h:95