5#include "hellfire/graphics/Vertex.h"
10#include "hellfire/utilities/SerializerUtils.h"
14 std::ofstream file(filepath, std::ios::binary);
16 std::cerr <<
"MeshSerializer: Cannot open file for writing: " << filepath << std::endl;
29 write_vertex_vector(file, mesh.vertices);
32 write_binary_vector(file, mesh.indices);
38 std::ifstream file(filepath, std::ios::binary);
40 std::cerr <<
"MeshSerializer: Cannot open file: " << filepath << std::endl;
46 if (!read_and_validate_header(file,
MAGIC,
VERSION, version)) {
47 std::cerr <<
"MeshSerializer: Invalid file header: " << filepath << std::endl;
51 auto mesh = std::make_shared<
Mesh>();
54 if (!read_binary(file, mesh->is_wireframe)) {
59 if (!read_vertex_vector(file, mesh->vertices)) {
64 if (!read_binary_vector(file, mesh->indices)) {
78 auto &verts = j[
"vertices"];
79 for (
const auto &v: mesh.vertices) {
81 {
"position", vec3_to_json(v.position)},
82 {
"normal", vec3_to_json(v.normal)},
83 {
"texCoords", vec2_to_json(v.texCoords)},
84 {
"color", vec3_to_json(v.color)},
85 {
"tangent", vec3_to_json(v.tangent)},
86 {
"bitangent", vec3_to_json(v.bitangent)}
90 j[
"indices"] = mesh.indices;
92 std::ofstream file(filepath);
93 if (!file)
return false;
100 std::ifstream file(filepath);
101 if (!file)
return nullptr;
107 auto mesh = std::make_shared<
Mesh>();
108 mesh->is_wireframe = j.value(
"is_wireframe",
false);
110 for (
const auto &v: j[
"vertices"]) {
113 if (
auto pos = json_get_vec3(v,
"position")) vert.position = *pos;
114 if (
auto norm = json_get_vec3(v,
"normal")) vert.normal = *norm;
115 if (
auto tex = json_get_vec2(v,
"texCoords")) vert.texCoords = *tex;
116 if (
auto col = json_get_vec3(v,
"color")) vert.color = *col;
117 if (
auto tan = json_get_vec3(v,
"tangent")) vert.tangent = *tan;
118 if (
auto bitan = json_get_vec3(v,
"bitangent")) vert.bitangent = *bitan;
120 mesh->vertices.push_back(vert);
123 mesh->indices = j[
"indices"].get<std::vector<
unsigned int> >();
126 }
catch (
const std::exception &e) {
127 std::cerr <<
"MeshSerializer: JSON parse error: " << e.what() << std::endl;
static bool save_json(const std::filesystem::path &filepath, const Mesh &mesh)
static constexpr uint32_t MAGIC
static constexpr uint32_t VERSION
static std::shared_ptr< Mesh > load_json(const std::filesystem::path &filepath)
static bool save(const std::filesystem::path &filepath, const Mesh &mesh)
static std::shared_ptr< Mesh > load(const std::filesystem::path &filepath)