src/mesh/io/gltf.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // SPDX-License-Identifier: BSD-3-Clause | ||
| 2 | |||
| 3 | #include "mesh/io/formats.h" | ||
| 4 | |||
| 5 | #define CGLTF_IMPLEMENTATION | ||
| 6 | #define CGLTF_WRITE_IMPLEMENTATION | ||
| 7 | #pragma GCC diagnostic push | ||
| 8 | #pragma GCC diagnostic ignored "-Wformat-truncation" | ||
| 9 | #include <cgltf_write.h> | ||
| 10 | #pragma GCC diagnostic pop | ||
| 11 | |||
| 12 | #include <algorithm> | ||
| 13 | #include <cstring> | ||
| 14 | #include <deque> | ||
| 15 | #include <limits> | ||
| 16 | #include <memory> | ||
| 17 | #include <stdexcept> | ||
| 18 | #include <string> | ||
| 19 | |||
| 20 | namespace terraingen::detail { | ||
| 21 | |||
| 22 | 178 | std::array<double, 4> RotationQuaternion(const std::array<double, 9>& r) { | |
| 23 | 178 | const double trace = r[0] + r[4] + r[8]; | |
| 24 | 178 | if (trace > 0.0) { | |
| 25 | 134 | const double s = 2.0 * std::sqrt(1.0 + trace); | |
| 26 | 134 | return {(r[7] - r[5]) / s, (r[2] - r[6]) / s, (r[3] - r[1]) / s, 0.25 * s}; | |
| 27 | } | ||
| 28 | 44 | if (r[0] > r[4] && r[0] > r[8]) { | |
| 29 | 1 | const double s = 2.0 * std::sqrt(1.0 + r[0] - r[4] - r[8]); | |
| 30 | 1 | return {0.25 * s, (r[1] + r[3]) / s, (r[2] + r[6]) / s, (r[7] - r[5]) / s}; | |
| 31 | } | ||
| 32 | 43 | if (r[4] > r[8]) { | |
| 33 | 42 | const double s = 2.0 * std::sqrt(1.0 + r[4] - r[0] - r[8]); | |
| 34 | 42 | return {(r[1] + r[3]) / s, 0.25 * s, (r[5] + r[7]) / s, (r[2] - r[6]) / s}; | |
| 35 | } | ||
| 36 | 1 | const double s = 2.0 * std::sqrt(1.0 + r[8] - r[0] - r[4]); | |
| 37 | 1 | return {(r[2] + r[6]) / s, (r[5] + r[7]) / s, 0.25 * s, (r[3] - r[1]) / s}; | |
| 38 | } | ||
| 39 | |||
| 40 | namespace { | ||
| 41 | |||
| 42 | /// The cgltf document of a scene: every array sized before any pointer into it is taken, and the | ||
| 43 | /// binary buffer every accessor reads. | ||
| 44 | class GltfDocument { | ||
| 45 | public: | ||
| 46 | 26 | GltfDocument(const std::vector<SceneMesh>& meshes, const std::vector<SceneNode>& nodes) | |
| 47 | 26 | : m_views(ViewCount(meshes)), m_accessors(m_views.size()), m_attributes(2 * meshes.size()), | |
| 48 | 26 | m_materials(meshes.size()), m_primitives(meshes.size()), m_meshes(meshes.size()), | |
| 49 | 52 | m_nodes(nodes.size()), m_roots(nodes.size()) { | |
| 50 | 26 | std::size_t view = 0; | |
| 51 | 176 | for (std::size_t m = 0; m < meshes.size(); ++m) { | |
| 52 | 150 | AddMesh(m, meshes[m], view); | |
| 53 | } | ||
| 54 | 199 | for (std::size_t n = 0; n < nodes.size(); ++n) { | |
| 55 | 173 | AddNode(n, nodes[n]); | |
| 56 | } | ||
| 57 | 26 | } | |
| 58 | |||
| 59 | /// Writes the document as .glb (`binary`), or as .gltf with its buffer in a .bin beside it. | ||
| 60 | 26 | void Write(const std::filesystem::path& path, bool binary) { | |
| 61 | 26 | cgltf_buffer buffer{}; | |
| 62 | 26 | buffer.size = m_binary.size(); | |
| 63 | 26 | std::string bin; | |
| 64 | 26 | if (!binary) { | |
| 65 | 3 | std::filesystem::path binPath = path; | |
| 66 | 3 | binPath.replace_extension(".bin"); | |
| 67 | 3 | WriteFile(binPath, m_binary); | |
| 68 | 6 | bin = binPath.filename().string(); | |
| 69 | 3 | buffer.uri = bin.data(); | |
| 70 | 3 | } | |
| 71 | 463 | for (cgltf_buffer_view& view : m_views) { | |
| 72 | 437 | view.buffer = &buffer; | |
| 73 | } | ||
| 74 | 26 | cgltf_scene scene{}; | |
| 75 | 26 | scene.nodes = m_roots.data(); | |
| 76 | 26 | scene.nodes_count = m_roots.size(); | |
| 77 | 26 | cgltf_data data{}; | |
| 78 | 27 | std::string version = "2.0"; | |
| 79 | 27 | std::string generator = "TerrainGen"; | |
| 80 | 26 | data.asset.version = version.data(); | |
| 81 | 26 | data.asset.generator = generator.data(); | |
| 82 | 26 | data.buffers = &buffer; | |
| 83 | 26 | data.buffers_count = 1; | |
| 84 | 26 | data.buffer_views = m_views.data(); | |
| 85 | 26 | data.buffer_views_count = m_views.size(); | |
| 86 | 26 | data.accessors = m_accessors.data(); | |
| 87 | 26 | data.accessors_count = m_accessors.size(); | |
| 88 | 26 | data.materials = m_materials.data(); | |
| 89 | 26 | data.materials_count = m_materials.size(); | |
| 90 | 26 | data.meshes = m_meshes.data(); | |
| 91 | 26 | data.meshes_count = m_meshes.size(); | |
| 92 | 26 | data.nodes = m_nodes.data(); | |
| 93 | 26 | data.nodes_count = m_nodes.size(); | |
| 94 | 26 | data.scenes = &scene; | |
| 95 | 26 | data.scenes_count = 1; | |
| 96 | 26 | data.scene = &scene; | |
| 97 | 26 | if (binary) { | |
| 98 | 23 | data.bin = m_binary.data(); | |
| 99 | 23 | data.bin_size = m_binary.size(); | |
| 100 | } | ||
| 101 | 26 | cgltf_options options{}; | |
| 102 | 26 | options.type = binary ? cgltf_file_type_glb : cgltf_file_type_gltf; | |
| 103 | 27 | if (cgltf_write_file(&options, path.string().c_str(), &data) != cgltf_result_success) { | |
| 104 | 3 | throw std::runtime_error("Cannot write " + path.string()); | |
| 105 | } | ||
| 106 | 27 | } | |
| 107 | |||
| 108 | private: | ||
| 109 | 26 | static std::size_t ViewCount(const std::vector<SceneMesh>& meshes) { | |
| 110 | 26 | std::size_t count = 0; | |
| 111 | 176 | for (const SceneMesh& scene : meshes) { | |
| 112 | 287 | count += scene.normals.empty() ? 2u : 3u; | |
| 113 | } | ||
| 114 | 26 | return count; | |
| 115 | } | ||
| 116 | |||
| 117 | 437 | char* Name(const std::string& name) { | |
| 118 | 437 | return m_names.emplace_back(name).data(); | |
| 119 | } | ||
| 120 | |||
| 121 | /// Ends a view and its accessor at `view` over the bytes added since `start`. | ||
| 122 | 437 | cgltf_accessor* AddAccessor(std::size_t& view, std::size_t start, cgltf_buffer_view_type type, | |
| 123 | cgltf_component_type component, cgltf_type kind, | ||
| 124 | std::size_t count) { | ||
| 125 | 437 | cgltf_buffer_view& v = m_views[view]; | |
| 126 | 437 | v.offset = start; | |
| 127 | 437 | v.size = m_binary.size() - start; | |
| 128 | 437 | v.type = type; | |
| 129 | 437 | cgltf_accessor& a = m_accessors[view]; | |
| 130 | 437 | a.component_type = component; | |
| 131 | 437 | a.type = kind; | |
| 132 | 437 | a.count = count; | |
| 133 | 437 | a.buffer_view = &v; | |
| 134 | 437 | ++view; | |
| 135 | 437 | return &a; | |
| 136 | } | ||
| 137 | |||
| 138 | 287 | cgltf_accessor* AddVectors(std::size_t& view, const std::vector<Vec3d>& vectors, bool bounds) { | |
| 139 | 287 | const std::size_t start = m_binary.size(); | |
| 140 | 287 | constexpr float kInf = std::numeric_limits<float>::infinity(); | |
| 141 | 287 | std::array<float, 3> low{kInf, kInf, kInf}; | |
| 142 | 287 | std::array<float, 3> high{-kInf, -kInf, -kInf}; | |
| 143 | 650709 | for (const Vec3d& vector : vectors) { | |
| 144 | 650422 | const Vec3d p = YUp(vector); | |
| 145 | 650422 | const std::array<float, 3> stored{static_cast<float>(p.x), static_cast<float>(p.y), | |
| 146 | 650422 | static_cast<float>(p.z)}; | |
| 147 | 2601688 | for (std::size_t c = 0; c < 3; ++c) { | |
| 148 | 1951266 | Put(m_binary, stored[c]); | |
| 149 | 1963293 | low[c] = std::min(low[c], stored[c]); | |
| 150 | 1972750 | high[c] = std::max(high[c], stored[c]); | |
| 151 | } | ||
| 152 | } | ||
| 153 | 287 | cgltf_accessor* accessor = | |
| 154 | 287 | AddAccessor(view, start, cgltf_buffer_view_type_vertices, cgltf_component_type_r_32f, | |
| 155 | cgltf_type_vec3, vectors.size()); | ||
| 156 | 287 | if (bounds) { | |
| 157 | 150 | accessor->has_min = accessor->has_max = 1; | |
| 158 | 150 | std::copy(low.begin(), low.end(), accessor->min); | |
| 159 | 150 | std::copy(high.begin(), high.end(), accessor->max); | |
| 160 | } | ||
| 161 | 287 | return accessor; | |
| 162 | } | ||
| 163 | |||
| 164 | 150 | void AddMesh(std::size_t m, const SceneMesh& scene, std::size_t& view) { | |
| 165 | 150 | cgltf_attribute* attributes = &m_attributes[2 * m]; | |
| 166 | 300 | attributes[0] = {Name("POSITION"), cgltf_attribute_type_position, 0, | |
| 167 | 150 | AddVectors(view, scene.mesh.positions, true)}; | |
| 168 | 150 | std::size_t count = 1; | |
| 169 | 150 | if (!scene.normals.empty()) { | |
| 170 | 274 | attributes[1] = {Name("NORMAL"), cgltf_attribute_type_normal, 0, | |
| 171 | 137 | AddVectors(view, scene.normals, false)}; | |
| 172 | 137 | count = 2; | |
| 173 | } | ||
| 174 | 150 | const std::size_t start = m_binary.size(); | |
| 175 | 835474 | for (const auto& t : scene.mesh.triangles) { | |
| 176 | 3341296 | for (const std::uint32_t v : t) { | |
| 177 | 2505972 | Put(m_binary, v); | |
| 178 | } | ||
| 179 | } | ||
| 180 | 150 | cgltf_material& material = m_materials[m]; | |
| 181 | 150 | material.name = Name(scene.material.name); | |
| 182 | 150 | material.has_pbr_metallic_roughness = 1; | |
| 183 | 150 | auto& pbr = material.pbr_metallic_roughness; | |
| 184 | 600 | for (std::size_t c = 0; c < 3; ++c) { | |
| 185 | 450 | pbr.base_color_factor[c] = static_cast<float>(scene.material.color[c]); | |
| 186 | } | ||
| 187 | 150 | pbr.base_color_factor[3] = 1.0f; | |
| 188 | 150 | pbr.metallic_factor = 0.0f; | |
| 189 | 150 | pbr.roughness_factor = 1.0f; | |
| 190 | 150 | cgltf_primitive& primitive = m_primitives[m]; | |
| 191 | 150 | primitive.type = cgltf_primitive_type_triangles; | |
| 192 | 300 | primitive.indices = | |
| 193 | 150 | AddAccessor(view, start, cgltf_buffer_view_type_indices, cgltf_component_type_r_32u, | |
| 194 | 150 | cgltf_type_scalar, 3 * scene.mesh.triangles.size()); | |
| 195 | 150 | primitive.material = &material; | |
| 196 | 150 | primitive.attributes = attributes; | |
| 197 | 150 | primitive.attributes_count = count; | |
| 198 | 150 | m_meshes[m].primitives = &primitive; | |
| 199 | 150 | m_meshes[m].primitives_count = 1; | |
| 200 | 150 | } | |
| 201 | |||
| 202 | 173 | void AddNode(std::size_t n, const SceneNode& node) { | |
| 203 | 173 | cgltf_node& out = m_nodes[n]; | |
| 204 | 173 | out.mesh = &m_meshes[node.mesh]; | |
| 205 | 173 | const auto q = RotationQuaternion(YUp(node.pose.rotation)); | |
| 206 | 173 | const Vec3d t = YUp(node.pose.translation); | |
| 207 | 173 | out.has_translation = out.has_rotation = out.has_scale = 1; | |
| 208 | 173 | const std::array<double, 3> translation{t.x, t.y, t.z}; | |
| 209 | 173 | const std::array<double, 3> scale{node.scale.x, node.scale.z, node.scale.y}; | |
| 210 | 692 | for (std::size_t c = 0; c < 3; ++c) { | |
| 211 | 519 | out.translation[c] = static_cast<float>(translation[c]); | |
| 212 | 519 | out.scale[c] = static_cast<float>(scale[c]); | |
| 213 | } | ||
| 214 | 865 | for (std::size_t c = 0; c < 4; ++c) { | |
| 215 | 692 | out.rotation[c] = static_cast<float>(q[c]); | |
| 216 | } | ||
| 217 | 173 | m_roots[n] = &out; | |
| 218 | 173 | } | |
| 219 | |||
| 220 | std::string m_binary; | ||
| 221 | std::deque<std::string> m_names; | ||
| 222 | std::vector<cgltf_buffer_view> m_views; | ||
| 223 | std::vector<cgltf_accessor> m_accessors; | ||
| 224 | std::vector<cgltf_attribute> m_attributes; | ||
| 225 | std::vector<cgltf_material> m_materials; | ||
| 226 | std::vector<cgltf_primitive> m_primitives; | ||
| 227 | std::vector<cgltf_mesh> m_meshes; | ||
| 228 | std::vector<cgltf_node> m_nodes; | ||
| 229 | std::vector<cgltf_node*> m_roots; | ||
| 230 | }; | ||
| 231 | |||
| 232 | /// The position accessor of `primitive`, or null. | ||
| 233 | 74 | const cgltf_accessor* PositionAccessor(const cgltf_primitive& primitive) { | |
| 234 | 74 | const cgltf_accessor* positions = nullptr; | |
| 235 | 215 | for (std::size_t a = 0; a < primitive.attributes_count; ++a) { | |
| 236 | 141 | if (primitive.attributes[a].type == cgltf_attribute_type_position) { | |
| 237 | 74 | positions = primitive.attributes[a].data; | |
| 238 | } | ||
| 239 | } | ||
| 240 | 74 | return positions; | |
| 241 | } | ||
| 242 | |||
| 243 | /// Adds the vertices of `positions`, placed by the column-major `world` transform, and the | ||
| 244 | /// triangles of `primitive` to `read`. | ||
| 245 | 74 | void AppendPrimitive(const cgltf_primitive& primitive, const cgltf_accessor& positions, | |
| 246 | const cgltf_float (&world)[16], SceneMesh& read) { | ||
| 247 | 74 | const auto offset = static_cast<std::uint32_t>(read.mesh.positions.size()); | |
| 248 | 14710 | for (std::size_t v = 0; v < positions.count; ++v) { | |
| 249 | 14636 | cgltf_float q[3] = {}; | |
| 250 | 14636 | cgltf_accessor_read_float(&positions, v, q, 3); | |
| 251 | 58544 | const auto axis = [&](std::size_t c) { | |
| 252 | 43908 | return static_cast<double>(world[c] * q[0] + world[4 + c] * q[1] + world[8 + c] * q[2] + | |
| 253 | 43908 | world[12 + c]); | |
| 254 | 14636 | }; | |
| 255 | 14636 | read.mesh.positions.push_back(ZUp({axis(0), axis(1), axis(2)})); | |
| 256 | } | ||
| 257 | 74 | const std::size_t count = primitive.indices ? primitive.indices->count : positions.count; | |
| 258 | 24806 | for (std::size_t i = 0; i + 2 < count; i += 3) { | |
| 259 | 24732 | std::array<std::uint32_t, 3> triangle{}; | |
| 260 | 98928 | for (std::size_t c = 0; c < 3; ++c) { | |
| 261 | 74196 | const std::size_t index = | |
| 262 | 74196 | primitive.indices ? cgltf_accessor_read_index(primitive.indices, i + c) : i + c; | |
| 263 | 74196 | triangle[c] = offset + static_cast<std::uint32_t>(index); | |
| 264 | } | ||
| 265 | 24732 | read.mesh.triangles.push_back(triangle); | |
| 266 | } | ||
| 267 | 74 | } | |
| 268 | |||
| 269 | /// The name and base color of a glTF material. | ||
| 270 | 14 | MeshMaterial ReadMaterial(const cgltf_material& material) { | |
| 271 | 14 | MeshMaterial read; | |
| 272 | 28 | read.name = material.name ? material.name : "default"; | |
| 273 | 56 | for (std::size_t c = 0; c < 3; ++c) { | |
| 274 | 42 | read.color[c] = static_cast<double>(material.pbr_metallic_roughness.base_color_factor[c]); | |
| 275 | } | ||
| 276 | 14 | return read; | |
| 277 | } | ||
| 278 | |||
| 279 | /// Adds the triangles of `node` and its children, placed by their world transforms, to `read`. | ||
| 280 | 74 | void AppendNodeTriangles(const cgltf_node& node, SceneMesh& read) { | |
| 281 | 74 | if (node.mesh != nullptr) { | |
| 282 | 74 | cgltf_float world[16]; | |
| 283 | 74 | cgltf_node_transform_world(&node, world); | |
| 284 | 148 | for (std::size_t p = 0; p < node.mesh->primitives_count; ++p) { | |
| 285 | 74 | const cgltf_primitive& primitive = node.mesh->primitives[p]; | |
| 286 | 74 | const cgltf_accessor* positions = PositionAccessor(primitive); | |
| 287 | 74 | if (primitive.type != cgltf_primitive_type_triangles || positions == nullptr) { | |
| 288 | ✗ | continue; | |
| 289 | } | ||
| 290 | 74 | AppendPrimitive(primitive, *positions, world, read); | |
| 291 | 148 | if (primitive.material != nullptr && read.material == MeshMaterial{}) { | |
| 292 | 14 | read.material = ReadMaterial(*primitive.material); | |
| 293 | } | ||
| 294 | } | ||
| 295 | } | ||
| 296 | 74 | for (std::size_t c = 0; c < node.children_count; ++c) { | |
| 297 | ✗ | AppendNodeTriangles(*node.children[c], read); | |
| 298 | } | ||
| 299 | 74 | } | |
| 300 | |||
| 301 | } // namespace | ||
| 302 | |||
| 303 | 26 | void WriteGltf(const std::filesystem::path& path, bool binary, const std::vector<SceneMesh>& meshes, | |
| 304 | const std::vector<SceneNode>& nodes) { | ||
| 305 | 26 | GltfDocument(meshes, nodes).Write(path, binary); | |
| 306 | 25 | } | |
| 307 | |||
| 308 | 11 | SceneMesh ReadGltf(const std::filesystem::path& path) { | |
| 309 | 11 | const std::string file = path.string(); | |
| 310 | 11 | cgltf_options options{}; | |
| 311 | 11 | cgltf_data* parsed = nullptr; | |
| 312 | 11 | if (cgltf_parse_file(&options, file.c_str(), &parsed) != cgltf_result_success) { | |
| 313 | 2 | throw std::runtime_error("Cannot read glTF " + file); | |
| 314 | } | ||
| 315 | 10 | const std::unique_ptr<cgltf_data, decltype(&cgltf_free)> data(parsed, cgltf_free); | |
| 316 | 20 | if (cgltf_load_buffers(&options, data.get(), file.c_str()) != cgltf_result_success || | |
| 317 | 10 | cgltf_validate(data.get()) != cgltf_result_success) { | |
| 318 | ✗ | throw std::runtime_error("Cannot load the buffers of glTF " + file); | |
| 319 | } | ||
| 320 | 10 | SceneMesh read; | |
| 321 | 10 | if (data->scene != nullptr) { | |
| 322 | 84 | for (std::size_t n = 0; n < data->scene->nodes_count; ++n) { | |
| 323 | 74 | AppendNodeTriangles(*data->scene->nodes[n], read); | |
| 324 | } | ||
| 325 | } else { | ||
| 326 | ✗ | for (std::size_t n = 0; n < data->nodes_count; ++n) { | |
| 327 | ✗ | if (data->nodes[n].parent == nullptr) { | |
| 328 | ✗ | AppendNodeTriangles(data->nodes[n], read); | |
| 329 | } | ||
| 330 | } | ||
| 331 | } | ||
| 332 | 10 | return read; | |
| 333 | 10 | } | |
| 334 | |||
| 335 | } // namespace terraingen::detail | ||
| 336 |