added serialization

This commit is contained in:
2024-08-18 11:04:24 +03:00
parent 945fd7daa2
commit ee635b7f17
2 changed files with 63 additions and 2 deletions

View File

@@ -30,7 +30,8 @@ namespace omath::pathfinding
[[nodiscard]] [[nodiscard]]
const std::vector<Vector3>& GetNeighbors(const Vector3& vertex) const; const std::vector<Vector3>& GetNeighbors(const Vector3& vertex) const;
std::list<NavigationVertex> m_vertexes; [[nodiscard]] std::vector<uint8_t> Serialize() const;
void Deserialize(const std::vector<uint8_t>& raw);
std::unordered_map<Vector3, std::vector<Vector3>> m_verTextMap; std::unordered_map<Vector3, std::vector<Vector3>> m_verTextMap;
}; };

View File

@@ -3,6 +3,8 @@
// //
#include "omath/pathfinding/NavigationMesh.h" #include "omath/pathfinding/NavigationMesh.h"
#include <stdexcept>
namespace omath::pathfinding namespace omath::pathfinding
{ {
std::expected<Vector3, std::string> NavigationMesh::GetClossestVertex(const Vector3 &point) const std::expected<Vector3, std::string> NavigationMesh::GetClossestVertex(const Vector3 &point) const
@@ -23,4 +25,62 @@ namespace omath::pathfinding
{ {
return m_verTextMap.at(vertex); return m_verTextMap.at(vertex);
} }
std::vector<uint8_t> NavigationMesh::Serialize() const
{
auto dumpToVector =[]<typename T>(const T& t, std::vector<uint8_t>& vec){
for (size_t i = 0; i < sizeof(t); i++)
vec.push_back(*(reinterpret_cast<uint8_t*>(&t)+i));
};
std::vector<uint8_t> raw;
for (const auto& [vertex, neighbors] : m_verTextMap)
{
const uint16_t neighborsCount = neighbors.size();
dumpToVector(vertex, raw);
dumpToVector(neighborsCount, raw);
for (const auto& neighbor : neighbors)
dumpToVector(neighbor, raw);
}
return raw;
}
void NavigationMesh::Deserialize(const std::vector<uint8_t> &raw)
{
auto loadFromVector = [](const std::vector<uint8_t>& vec, size_t& offset, auto& value) {
if (offset + sizeof(value) > vec.size()) {
throw std::runtime_error("Deserialize: Invalid input data size.");
}
std::memcpy(&value, vec.data() + offset, sizeof(value));
offset += sizeof(value);
};
m_verTextMap.clear();
size_t offset = 0;
while (offset < raw.size()) {
Vector3 vertex;
loadFromVector(raw, offset, vertex);
uint16_t neighborsCount;
loadFromVector(raw, offset, neighborsCount);
std::vector<Vector3> neighbors;
neighbors.reserve(neighborsCount);
for (size_t i = 0; i < neighborsCount; ++i) {
Vector3 neighbor;
loadFromVector(raw, offset, neighbor);
neighbors.push_back(neighbor);
}
m_verTextMap.emplace(vertex, std::move(neighbors));
}
}
} }