From 0e7d3a73b6c4935e642887549aaddd8f746f8ac1 Mon Sep 17 00:00:00 2001 From: "Quentin E. / iDeath" Date: Thu, 20 Oct 2022 00:50:24 +0200 Subject: [PATCH] persist car: add safety so that old json files work fine (#485) * persist car: add safety so that old json files work fine * remove unused include --- BigBaseV2/src/core/data/model_attachment.hpp | 42 +++++++++++++++----- 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/BigBaseV2/src/core/data/model_attachment.hpp b/BigBaseV2/src/core/data/model_attachment.hpp index c7e13eca..28acddaf 100644 --- a/BigBaseV2/src/core/data/model_attachment.hpp +++ b/BigBaseV2/src/core/data/model_attachment.hpp @@ -14,7 +14,9 @@ namespace big bool is_invincible; }; - static void to_json(nlohmann::json& j, const model_attachment& attachment) { + + static void to_json(nlohmann::json& j, const model_attachment& attachment) + { j = nlohmann::json{ {"model_hash", attachment.model_hash}, {"position_x", attachment.position.x}, {"position_y", attachment.position.y}, {"position_z", attachment.position.z}, @@ -25,12 +27,34 @@ namespace big }; }; - static void from_json(const nlohmann::json& j, model_attachment& attachment) { - j.at("model_hash").get_to(attachment.model_hash); - j.at("position_x").get_to(attachment.position.x); j.at("position_y").get_to(attachment.position.y); j.at("position_z").get_to(attachment.position.z); - j.at("rotation_x").get_to(attachment.rotation.x); j.at("rotation_y").get_to(attachment.rotation.y); j.at("rotation_z").get_to(attachment.rotation.z); - j.at("has_collision").get_to(attachment.has_collision); - j.at("is_visible").get_to(attachment.is_visible); - j.at("is_invincible").get_to(attachment.is_invincible); + + template + static void set_from_key_or_default(const nlohmann::json& j, const char* key, ValueType& value, ValueType default_value = {}) + { + if (j.contains(key)) + { + j.at(key).get_to(value); + } + else + { + value = default_value; + } } -}; \ No newline at end of file + + static void from_json(const nlohmann::json& j, model_attachment& attachment) + { + set_from_key_or_default(j, "model_hash", attachment.model_hash); + + set_from_key_or_default(j, "position_x", attachment.position.x); + set_from_key_or_default(j, "position_y", attachment.position.y); + set_from_key_or_default(j, "position_z", attachment.position.z); + + set_from_key_or_default(j, "rotation_x", attachment.rotation.x); + set_from_key_or_default(j, "rotation_y", attachment.rotation.y); + set_from_key_or_default(j, "rotation_z", attachment.rotation.z); + + set_from_key_or_default(j, "has_collision", attachment.has_collision); + set_from_key_or_default(j, "is_visible", attachment.is_visible, true); + set_from_key_or_default(j, "is_invincible", attachment.is_invincible); + } +};