70 lines
2.0 KiB
C++
70 lines
2.0 KiB
C++
#include <functional>
|
|
#include <ostream>
|
|
#pragma once
|
|
#include "ecs.h"
|
|
|
|
#include "io/write.h"
|
|
#include "io/read.h"
|
|
|
|
#include <iostream>
|
|
|
|
namespace ecs::serial {
|
|
namespace internal {
|
|
extern std::unordered_map<size_t, std::tuple<std::function<void(std::ostream&, ecs::Component*)>, std::function<void(std::istream&, ecs::Component*)>, std::function<ecs::Component*()>>> functions;
|
|
}
|
|
|
|
template <typename T>
|
|
void serialize_member(std::ostream&, T*) {
|
|
// We reached the end
|
|
}
|
|
|
|
template <typename T, typename M, typename... Args>
|
|
void serialize_member(std::ostream& os, T* t, M T::*m, Args... args) {
|
|
io::write<M>(os, t->*m);
|
|
|
|
serialize_member(os, t, args...);
|
|
}
|
|
|
|
template <typename T>
|
|
void deserialize_member(std::istream&, T*) {
|
|
// We reached the end
|
|
}
|
|
|
|
template <typename T, typename M, typename... Args>
|
|
void deserialize_member(std::istream& is, T* t, M T::*m, Args... args) {
|
|
t->*m = io::read<M>(is);
|
|
|
|
deserialize_member(is, t, args...);
|
|
}
|
|
|
|
// @todo Allow for custom serializers and deserializers (maybe for this we do need a difference between update and new)
|
|
template <typename T, typename... Args>
|
|
void register_component(Args... args) {
|
|
// Serialize component
|
|
auto serialize = [args...] (std::ostream& os, ecs::Component* component) {
|
|
T* t = static_cast<T*>(component);
|
|
serialize_member(os, t, args...);
|
|
};
|
|
|
|
// Deserialize component
|
|
auto deserialize = [args...] (std::istream& is, ecs::Component* component) {
|
|
T* t = static_cast<T*>(component);
|
|
deserialize_member(is, t, args...);
|
|
};
|
|
|
|
auto create = [] () -> Component* {
|
|
return new T();
|
|
};
|
|
|
|
internal::functions.insert({ComponentID::id<T>, {serialize, deserialize, create}});
|
|
}
|
|
|
|
void register_component_custom(size_t id, std::function<void(std::ostream&, ecs::Component*)> serialize, std::function<void(std::istream&, Component*)> deserialize, std::function<ecs::Component*()> create);
|
|
|
|
void serialize(std::ostream& os, Entity* entity);
|
|
void deserialize(std::istream& is, Manager& manager);
|
|
|
|
void serialize_ids(std::ostream& os);
|
|
void deserialize_ids(std::istream& is);
|
|
}
|