From edbf8f1772dad8eb69a99c808e87ac5835b6b81c Mon Sep 17 00:00:00 2001 From: iwubcode Date: Fri, 16 Feb 2024 22:13:20 -0600 Subject: [PATCH] Common: add json utility functions for Vec3 serialization --- Source/Core/Common/JsonUtil.cpp | 20 ++++++++++++++++++++ Source/Core/Common/JsonUtil.h | 20 +++++++++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 Source/Core/Common/JsonUtil.cpp diff --git a/Source/Core/Common/JsonUtil.cpp b/Source/Core/Common/JsonUtil.cpp new file mode 100644 index 0000000000..d16f37f4f3 --- /dev/null +++ b/Source/Core/Common/JsonUtil.cpp @@ -0,0 +1,20 @@ +// Copyright 2024 Dolphin Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "Common/JsonUtil.h" + +picojson::object ToJsonObject(const Common::Vec3& vec) +{ + picojson::object obj; + obj.emplace("x", vec.x); + obj.emplace("y", vec.y); + obj.emplace("z", vec.z); + return obj; +} + +void FromJson(const picojson::object& obj, Common::Vec3& vec) +{ + vec.x = ReadNumericOrDefault(obj, "x"); + vec.y = ReadNumericOrDefault(obj, "y"); + vec.z = ReadNumericOrDefault(obj, "z"); +} diff --git a/Source/Core/Common/JsonUtil.h b/Source/Core/Common/JsonUtil.h index 131eb941a8..cee52432ff 100644 --- a/Source/Core/Common/JsonUtil.h +++ b/Source/Core/Common/JsonUtil.h @@ -3,10 +3,13 @@ #pragma once -#include +#include #include +#include "Common/MathUtil.h" +#include "Common/Matrix.h" + // Ideally this would use a concept like, 'template ' to constrain it, // but unfortunately we'd need to require clang 15 for that, since the ranges library isn't // fully implemented until then, but this should suffice. @@ -24,3 +27,18 @@ picojson::array ToJsonArray(const Range& data) return result; } + +template +Type ReadNumericOrDefault(const picojson::object& obj, const std::string& key, + Type default_value = Type{}) +{ + const auto it = obj.find(key); + if (it == obj.end()) + return default_value; + if (!it->second.is()) + return default_value; + return MathUtil::SaturatingCast(it->second.get()); +} + +picojson::object ToJsonObject(const Common::Vec3& vec); +void FromJson(const picojson::object& obj, Common::Vec3& vec);