diff --git a/CMakeLists.txt b/CMakeLists.txt index 6e13560..08aaf9f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -41,12 +41,23 @@ add_executable(game target_include_directories(game PRIVATE src external/stb external/linalg) target_link_libraries(game PRIVATE glad stb_image glfw) +# glTF/GLBの中身を表示する道具。GPUもウィンドウも使わないのでGLFWとGLADは要らない +# A tool that prints what is inside glTF/GLB files. It uses no GPU and no window, so no GLFW and no GLAD +add_executable(gltf_dump + src/gltf_dump.cc + src/gltf.cc + src/json.cc + src/file_util.cc) +target_include_directories(gltf_dump PRIVATE src external/linalg) + # 警告を有効にする(自分のコードだけ) / enable warnings (our own code only) -if(MSVC) - target_compile_options(game PRIVATE /W4 /utf-8) -else() - target_compile_options(game PRIVATE -Wall -Wextra) -endif() +foreach(target game gltf_dump) + if(MSVC) + target_compile_options(${target} PRIVATE /W4 /utf-8) + else() + target_compile_options(${target} PRIVATE -Wall -Wextra) + endif() +endforeach() # シェーダーとアセットは作業ディレクトリからの相対パスで読む。 # Visual Studioではプロジェクトのルートを作業ディレクトリにする。Unixではルートから ./build/game を実行。 diff --git a/README.md b/README.md index 68cf1a1..4644691 100644 --- a/README.md +++ b/README.md @@ -41,5 +41,11 @@ build\Debug\game.exe または `build\opengl_tutorial.sln` を開いてF5(作業ディレクトリはプロジェクトのルートに設定済み)。 Or open `build\opengl_tutorial.sln` and press F5 (the working directory is already set to the project root). +glTF/GLBファイルの中身を表示する道具(第13章から) / a tool that prints what is inside a glTF/GLB file (from chapter 13): + +```sh +./build/gltf_dump assets/models/diorama.glb # Windows: build\Debug\gltf_dump.exe assets\models\diorama.glb +``` + シェーダーとアセットは作業ディレクトリからの相対パスで読み込むので、必ずプロジェクトのルートから実行すること。 Shaders and assets are loaded relative to the working directory, so always run from the project root. diff --git a/assets/LICENSE.txt b/assets/LICENSE.txt index 520234a..11531cd 100644 --- a/assets/LICENSE.txt +++ b/assets/LICENSE.txt @@ -7,3 +7,5 @@ textures/crate.png 木箱 / wooden crate textures/floor.png 石の床 / stone floor tiles textures/crate_specular.png 木箱の鏡面反射マップ / crate specular map textures/crate_emission.png 木箱の発光マップ / crate emission map +models/crate.glb 木箱のモデル / crate model +models/diorama.glb 小さな場面 / a small diorama scene diff --git a/assets/models/crate.glb b/assets/models/crate.glb new file mode 100644 index 0000000..889c68e Binary files /dev/null and b/assets/models/crate.glb differ diff --git a/assets/models/diorama.glb b/assets/models/diorama.glb new file mode 100644 index 0000000..dcdfeb1 Binary files /dev/null and b/assets/models/diorama.glb differ diff --git a/src/file_util.cc b/src/file_util.cc index 8bf1201..7fb3857 100644 --- a/src/file_util.cc +++ b/src/file_util.cc @@ -1,6 +1,7 @@ #include "file_util.hh" #include +#include #include std::optional readTextFile(const std::string &path) { @@ -11,3 +12,9 @@ std::optional readTextFile(const std::string &path) { text << file.rdbuf(); return text.str(); } + +std::optional> readBinaryFile(const std::string &path) { + std::ifstream file(path, std::ios::binary); + if (!file) return std::nullopt; + return std::vector(std::istreambuf_iterator(file), std::istreambuf_iterator()); +} diff --git a/src/file_util.hh b/src/file_util.hh index c7bd487..02de5e2 100644 --- a/src/file_util.hh +++ b/src/file_util.hh @@ -1,9 +1,15 @@ // ファイルの読み込み / reading files #pragma once +#include #include #include +#include // ファイル全体を文字列として読む。開けなければstd::nullopt。 // Reads a whole file into a string. std::nullopt if it cannot be opened. std::optional readTextFile(const std::string &path); + +// ファイル全体をバイト列として読む(GLBや画像用)。開けなければstd::nullopt。 +// Reads a whole file as bytes (for GLB files and images). std::nullopt if it cannot be opened. +std::optional> readBinaryFile(const std::string &path); diff --git a/src/gltf.cc b/src/gltf.cc new file mode 100644 index 0000000..c71a35f --- /dev/null +++ b/src/gltf.cc @@ -0,0 +1,758 @@ +#include "gltf.hh" + +#include "file_util.hh" +#include "json.hh" + +#include +#include + +//------------------------------------------ +// 小さな補助関数 / small helpers +//------------------------------------------ + +const char *gltfComponentTypeName(int componentType) { + switch (componentType) { + case kGltfByte: return "BYTE"; + case kGltfUnsignedByte: return "UNSIGNED_BYTE"; + case kGltfShort: return "SHORT"; + case kGltfUnsignedShort: return "UNSIGNED_SHORT"; + case kGltfUnsignedInt: return "UNSIGNED_INT"; + case kGltfFloat: return "FLOAT"; + default: return "?"; + } +} + +size_t gltfComponentSize(int componentType) { + switch (componentType) { + case kGltfByte: + case kGltfUnsignedByte: return 1; + case kGltfShort: + case kGltfUnsignedShort: return 2; + case kGltfUnsignedInt: + case kGltfFloat: return 4; + default: return 0; + } +} + +static int componentCount(const std::string &type) { + if (type == "SCALAR") return 1; + if (type == "VEC2") return 2; + if (type == "VEC3") return 3; + if (type == "VEC4") return 4; + if (type == "MAT2") return 4; + if (type == "MAT3") return 9; + if (type == "MAT4") return 16; + return 0; +} + +// 行列の列の長さ(MAT以外は0) / the column length of a matrix type (0 if not a matrix) +static int matrixColumns(const GltfAccessor &a) { + if (a.type == "MAT2") return 2; + if (a.type == "MAT3") return 3; + if (a.type == "MAT4") return 4; + return 0; +} + +// 1〜2バイトの成分の行列は、列ごとに4バイト境界へ詰め物がある(glTFの仕様 3.6.2.4) +// Matrices of 1- or 2-byte components pad every column to 4 bytes (glTF spec 3.6.2.4) +static size_t columnStride(const GltfAccessor &a) { + size_t n = static_cast(matrixColumns(a)); + size_t bytes = n * gltfComponentSize(a.componentType); + return (bytes + 3) / 4 * 4; +} + +// 要素一つのバイト数 / bytes of one element +static size_t elementSize(const GltfAccessor &a) { + int n = matrixColumns(a); + if (n > 0 && gltfComponentSize(a.componentType) < 4) return static_cast(n) * columnStride(a); + return static_cast(a.components) * gltfComponentSize(a.componentType); +} + +// 要素の先頭から成分cまでのバイト数 / bytes from the start of an element to component c +static size_t componentOffset(const GltfAccessor &a, int c) { + int n = matrixColumns(a); + size_t size = gltfComponentSize(a.componentType); + if (n > 0 && size < 4) return static_cast(c / n) * columnStride(a) + static_cast(c % n) * size; + return static_cast(c) * size; +} + +// 成分一つをdoubleとして読む。memcpyなので境界が揃っていなくても良い(リトルエンディアンを前提) +// Reads one component as a double. memcpy works even when unaligned (assumes a little-endian CPU) +static double readComponent(const std::uint8_t *p, int componentType, bool normalized) { + switch (componentType) { + case kGltfByte: { + std::int8_t v; + std::memcpy(&v, p, 1); + return normalized ? (v / 127.0 < -1.0 ? -1.0 : v / 127.0) : v; + } + case kGltfUnsignedByte: { + std::uint8_t v; + std::memcpy(&v, p, 1); + return normalized ? v / 255.0 : v; + } + case kGltfShort: { + std::int16_t v; + std::memcpy(&v, p, 2); + return normalized ? (v / 32767.0 < -1.0 ? -1.0 : v / 32767.0) : v; + } + case kGltfUnsignedShort: { + std::uint16_t v; + std::memcpy(&v, p, 2); + return normalized ? v / 65535.0 : v; + } + case kGltfUnsignedInt: { + std::uint32_t v; + std::memcpy(&v, p, 4); + return normalized ? v / 4294967295.0 : v; + } + default: { + float v; + std::memcpy(&v, p, 4); + return v; + } + } +} + +static std::uint32_t readU32(const std::uint8_t *p) { + std::uint32_t v; + std::memcpy(&v, p, 4); + return v; +} + +// data: URIのbase64を復号する / decodes the base64 part of a data: URI +static bool decodeBase64(std::string_view in, std::vector &out) { + auto value = [](char c) -> int { + if (c >= 'A' && c <= 'Z') return c - 'A'; + if (c >= 'a' && c <= 'z') return c - 'a' + 26; + if (c >= '0' && c <= '9') return c - '0' + 52; + if (c == '+' || c == '-') return 62; + if (c == '/' || c == '_') return 63; + return -1; + }; + unsigned bits = 0; + int count = 0; + for (char c : in) { + if (c == '=') break; + int v = value(c); + if (v < 0) return false; + bits = (bits << 6) | static_cast(v); + count += 6; + if (count >= 8) { + count -= 8; + out.push_back(static_cast((bits >> count) & 0xFF)); + } + } + return true; +} + +// URIの「%20」などを元に戻す(Blenderはファイル名の空白をこう書く) +// Undoes "%20" and friends in a URI (Blender writes spaces in file names like this) +static std::string percentDecode(std::string_view uri) { + std::string out; + for (size_t i = 0; i < uri.size(); ++i) { + auto hex = [](char c) -> int { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; + }; + if (uri[i] == '%' && i + 2 < uri.size() && hex(uri[i + 1]) >= 0 && hex(uri[i + 2]) >= 0) { + out += static_cast(hex(uri[i + 1]) * 16 + hex(uri[i + 2])); + i += 2; + } else { + out += uri[i]; + } + } + return out; +} + +// URIの中身を読む:data: URI、またはglTFファイルからの相対パス +// Loads what a URI points to: a data: URI, or a path relative to the glTF file +static bool loadUri(const std::string &gltfPath, const std::string &uri, std::vector &out, + std::string &error) { + if (uri.rfind("data:", 0) == 0) { + size_t comma = uri.find(','); + if (comma == std::string::npos || uri.rfind(";base64", comma) == std::string::npos) { + error = "base64でないdata: URIは未対応 / only base64 data: URIs are supported"; + return false; + } + if (!decodeBase64(std::string_view(uri).substr(comma + 1), out)) { + error = "data: URIのbase64が壊れている / broken base64 in a data: URI"; + return false; + } + return true; + } + if (uri.find("://") != std::string::npos) { + error = "ネット上のファイルは読めない / cannot load remote files: " + uri; + return false; + } + size_t slash = gltfPath.find_last_of("/\\"); + std::string dir = slash == std::string::npos ? std::string() : gltfPath.substr(0, slash + 1); + std::string file = dir + percentDecode(uri); + std::optional> data = readBinaryFile(file); + if (!data) { + error = "開けない / cannot open " + file; + return false; + } + out = std::move(*data); + return true; +} + +int GltfPrimitive::attribute(std::string_view name) const { + for (const GltfAttribute &a : attributes) + if (a.name == name) return a.accessor; + return -1; +} + +Mat4 GltfNode::localTransform() const { + if (hasMatrix) return matrix; + // 拡大縮小 → 回転 → 平行移動の順に効く / applied as scale, then rotation, then translation + return translate(translation) * toMat4(rotation) * ::scale(scale); +} + +//------------------------------------------ +// JSONから構造体へ / from JSON to the structs +//------------------------------------------ + +namespace { + +// 読み込み中の状態とエラー / the state and the error while loading +struct Loader { + Gltf &g; + std::string error; + + bool fail(const std::string &message) { + if (error.empty()) error = message; + return false; + } + + // 番号(0以上の整数)を読む。キーがなければそのまま(既定値)。範囲はcountで調べる + // Reads an index (an integer ≥ 0). Leaves out unchanged if the key is absent. count = valid range + bool index(const Json &object, const char *key, int &out, size_t count, const std::string &where) { + const Json *v = object.find(key); + if (!v) return true; + long long i = v->integer(-1); + if (i < 0 || static_cast(i) >= count) + return fail(where + "." + key + ": 範囲外の番号 / index out of range"); + out = static_cast(i); + return true; + } + + // 0以上の整数(バイト数など) / a non-negative integer (byte counts etc.) + bool size(const Json &object, const char *key, size_t &out, const std::string &where, bool required = false) { + const Json *v = object.find(key); + if (!v) return required ? fail(where + "." + key + ": 必須 / required") : true; + long long i = v->integer(-1); + if (i < 0) return fail(where + "." + key + ": 0以上の整数が必要 / must be an integer >= 0"); + out = static_cast(i); + return true; + } + + // n個の数の配列 / an array of n numbers + bool numbers(const Json &object, const char *key, float *out, size_t n, const std::string &where) { + const Json *v = object.find(key); + if (!v) return true; + if (!v->isArray() || v->size() != n) + return fail(where + "." + key + ": 数が" + std::to_string(n) + "個必要 / needs " + std::to_string(n) + " numbers"); + for (size_t i = 0; i < n; ++i) { + if (!(*v)[i].isNumber()) return fail(where + "." + key + ": 数でない / not a number"); + out[i] = (*v)[i].numberf(); + } + return true; + } + + bool textureRef(const Json &object, const char *key, GltfTextureRef &ref, const std::string &where) { + const Json *t = object.find(key); + if (!t) return true; + std::string w = where + "." + key; + if (!index(*t, "index", ref.index, g.textures.size(), w)) return false; + if (ref.index < 0) return fail(w + ".index: 必須 / required"); + ref.texCoord = static_cast((*t)["texCoord"].integer(0)); + if (ref.texCoord < 0) return fail(w + ".texCoord: 負の値 / negative"); + ref.scale = (*t)["scale"].numberf((*t)["strength"].numberf(1.0f)); // normalはscale、occlusionはstrength + return true; + } + + bool parse(const Json &root); + bool parseBuffers(const Json &root, const std::vector *glbBin); + bool validate(); +}; + +bool Loader::parse(const Json &root) { + if (!root.isObject()) return fail("JSONの一番外側がオブジェクトでない / the top level JSON value is not an object"); + + const Json &asset = root["asset"]; + g.version = asset["version"].string(); + g.generator = asset["generator"].string(); + g.copyright = asset["copyright"].string(); + if (g.version.rfind("2.", 0) != 0) + return fail("glTF 2.xではない / not glTF 2.x (asset.version = \"" + g.version + "\")"); + + for (const Json &e : root["extensionsUsed"].items()) g.extensionsUsed.push_back(e.string()); + for (const Json &e : root["extensionsRequired"].items()) { + g.extensionsRequired.push_back(e.string()); + // 必須の拡張を理解できなければ、正しく表示できない / if we do not understand a required extension we cannot display it + if (e.string() != "KHR_mesh_quantization" && e.string() != "KHR_materials_emissive_strength") + return fail("未対応の必須拡張 / unsupported required extension: " + e.string()); + } + + // 番号の範囲を調べられるように、先に配列の大きさを決める / size the arrays first, so index ranges can be checked + g.buffers.resize(root["buffers"].size()); + g.bufferViews.resize(root["bufferViews"].size()); + g.accessors.resize(root["accessors"].size()); + g.meshes.resize(root["meshes"].size()); + g.nodes.resize(root["nodes"].size()); + g.materials.resize(root["materials"].size()); + g.textures.resize(root["textures"].size()); + g.images.resize(root["images"].size()); + g.samplers.resize(root["samplers"].size()); + g.scenes.resize(root["scenes"].size()); + g.skinCount = root["skins"].size(); + g.animationCount = root["animations"].size(); + g.cameraCount = root["cameras"].size(); + + for (size_t i = 0; i < g.bufferViews.size(); ++i) { + const Json &j = root["bufferViews"][i]; + GltfBufferView &v = g.bufferViews[i]; + std::string w = "bufferViews[" + std::to_string(i) + "]"; + if (!j.has("buffer")) return fail(w + ".buffer: 必須 / required"); + if (!index(j, "buffer", v.buffer, g.buffers.size(), w) || !size(j, "byteOffset", v.byteOffset, w) || + !size(j, "byteLength", v.byteLength, w, true) || !size(j, "byteStride", v.byteStride, w)) + return false; + if (v.byteStride != 0 && (v.byteStride < 4 || v.byteStride > 252 || v.byteStride % 4 != 0)) + return fail(w + ".byteStride: 4〜252の4の倍数が必要 / must be a multiple of 4 in 4..252"); + v.target = static_cast(j["target"].integer(0)); + } + + for (size_t i = 0; i < g.accessors.size(); ++i) { + const Json &j = root["accessors"][i]; + GltfAccessor &a = g.accessors[i]; + std::string w = "accessors[" + std::to_string(i) + "]"; + a.name = j["name"].string(); + if (!index(j, "bufferView", a.bufferView, g.bufferViews.size(), w) || !size(j, "byteOffset", a.byteOffset, w) || + !size(j, "count", a.count, w, true)) + return false; + a.componentType = static_cast(j["componentType"].integer(0)); + if (gltfComponentSize(a.componentType) == 0) return fail(w + ".componentType: 不正 / invalid"); + a.normalized = j["normalized"].boolean(false); + a.type = j["type"].string(); + a.components = componentCount(a.type); + if (a.components == 0) return fail(w + ".type: 不正 / invalid (\"" + a.type + "\")"); + if (a.count == 0) return fail(w + ".count: 1以上が必要 / must be >= 1"); + for (const Json &n : j["min"].items()) a.min.push_back(n.number()); + for (const Json &n : j["max"].items()) a.max.push_back(n.number()); + if (const Json *s = j.find("sparse")) { + std::string ws = w + ".sparse"; + if (!size(*s, "count", a.sparseCount, ws, true)) return false; + const Json &si = (*s)["indices"]; + const Json &sv = (*s)["values"]; + if (!si.has("bufferView") || !sv.has("bufferView")) return fail(ws + ": bufferViewが必須 / bufferView required"); + if (!index(si, "bufferView", a.sparseIndicesView, g.bufferViews.size(), ws + ".indices") || + !size(si, "byteOffset", a.sparseIndicesOffset, ws + ".indices") || + !index(sv, "bufferView", a.sparseValuesView, g.bufferViews.size(), ws + ".values") || + !size(sv, "byteOffset", a.sparseValuesOffset, ws + ".values")) + return false; + a.sparseIndicesType = static_cast(si["componentType"].integer(0)); + if (a.sparseIndicesType != kGltfUnsignedByte && a.sparseIndicesType != kGltfUnsignedShort && + a.sparseIndicesType != kGltfUnsignedInt) + return fail(ws + ".indices.componentType: 不正 / invalid"); + } + } + + for (size_t i = 0; i < g.meshes.size(); ++i) { + const Json &j = root["meshes"][i]; + GltfMesh &m = g.meshes[i]; + std::string w = "meshes[" + std::to_string(i) + "]"; + m.name = j["name"].string(); + m.primitives.resize(j["primitives"].size()); + if (m.primitives.empty()) return fail(w + ".primitives: 空 / empty"); + for (size_t k = 0; k < m.primitives.size(); ++k) { + const Json &pj = j["primitives"][k]; + GltfPrimitive &p = m.primitives[k]; + std::string wp = w + ".primitives[" + std::to_string(k) + "]"; + for (const JsonMember &attr : pj["attributes"].members()) { + GltfAttribute a; + a.name = attr.key; + long long acc = attr.value.integer(-1); + if (acc < 0 || static_cast(acc) >= g.accessors.size()) + return fail(wp + ".attributes." + attr.key + ": 範囲外の番号 / index out of range"); + a.accessor = static_cast(acc); + p.attributes.push_back(a); + } + if (!index(pj, "indices", p.indices, g.accessors.size(), wp) || + !index(pj, "material", p.material, g.materials.size(), wp)) + return false; + p.mode = static_cast(pj["mode"].integer(kGltfTriangles)); + if (p.mode < 0 || p.mode > 6) return fail(wp + ".mode: 不正 / invalid"); + p.hasMorphTargets = pj.has("targets"); + } + } + + for (size_t i = 0; i < g.nodes.size(); ++i) { + const Json &j = root["nodes"][i]; + GltfNode &n = g.nodes[i]; + std::string w = "nodes[" + std::to_string(i) + "]"; + n.name = j["name"].string(); + if (!index(j, "mesh", n.mesh, g.meshes.size(), w)) return false; + for (const Json &c : j["children"].items()) { + long long child = c.integer(-1); + if (child < 0 || static_cast(child) >= g.nodes.size()) + return fail(w + ".children: 範囲外の番号 / index out of range"); + n.children.push_back(static_cast(child)); + } + if (j.has("matrix")) { + // 列優先の16個:最初の4個が1列目 / 16 numbers, column-major: the first 4 are column 0 + float m[16]; + if (!numbers(j, "matrix", m, 16, w)) return false; + for (int c = 0; c < 4; ++c) n.matrix.c[c] = {m[c * 4 + 0], m[c * 4 + 1], m[c * 4 + 2], m[c * 4 + 3]}; + n.hasMatrix = true; + } + float t[3] = {0, 0, 0}, r[4] = {0, 0, 0, 1}, s[3] = {1, 1, 1}; + if (!numbers(j, "translation", t, 3, w) || !numbers(j, "rotation", r, 4, w) || !numbers(j, "scale", s, 3, w)) + return false; + n.translation = {t[0], t[1], t[2]}; + // ファイルは x, y, z, w の順、linalgのQuatは w, x, y, z / the file stores x, y, z, w; linalg's Quat is w, x, y, z + Quat q{r[3], r[0], r[1], r[2]}; + bool zero = q.w * q.w + q.x * q.x + q.y * q.y + q.z * q.z < 1e-12f; // 0で割らないように / avoid dividing by 0 + n.rotation = zero ? Quat{} : normalize(q); + n.scale = {s[0], s[1], s[2]}; + n.hasSkin = j.has("skin"); + } + + for (size_t i = 0; i < g.images.size(); ++i) { + const Json &j = root["images"][i]; + GltfImage &im = g.images[i]; + std::string w = "images[" + std::to_string(i) + "]"; + im.name = j["name"].string(); + im.mimeType = j["mimeType"].string(); + im.uri = j["uri"].string(); + if (!index(j, "bufferView", im.bufferView, g.bufferViews.size(), w)) return false; + if (im.bufferView < 0 && im.uri.empty()) return fail(w + ": uriもbufferViewもない / neither uri nor bufferView"); + } + + for (size_t i = 0; i < g.samplers.size(); ++i) { + const Json &j = root["samplers"][i]; + GltfSampler &s = g.samplers[i]; + std::string w = "samplers[" + std::to_string(i) + "]"; + s.magFilter = static_cast(j["magFilter"].integer(0)); + s.minFilter = static_cast(j["minFilter"].integer(0)); + s.wrapS = static_cast(j["wrapS"].integer(10497)); + s.wrapT = static_cast(j["wrapT"].integer(10497)); + // GLにそのまま渡すので、許された値だけを通す / these go straight to GL, so only allowed values pass + auto wrapOk = [](int v) { return v == 33071 || v == 33648 || v == 10497; }; + if (s.magFilter != 0 && s.magFilter != 9728 && s.magFilter != 9729) return fail(w + ".magFilter: 不正 / invalid"); + if (s.minFilter != 0 && s.minFilter != 9728 && s.minFilter != 9729 && (s.minFilter < 9984 || s.minFilter > 9987)) + return fail(w + ".minFilter: 不正 / invalid"); + if (!wrapOk(s.wrapS) || !wrapOk(s.wrapT)) return fail(w + ".wrapS/wrapT: 不正 / invalid"); + } + + for (size_t i = 0; i < g.textures.size(); ++i) { + const Json &j = root["textures"][i]; + std::string w = "textures[" + std::to_string(i) + "]"; + // sourceがない(拡張の画像だけ)テクスチャは-1のまま=白として扱う / no source (extension images only) stays -1 = white + if (!index(j, "source", g.textures[i].source, g.images.size(), w) || + !index(j, "sampler", g.textures[i].sampler, g.samplers.size(), w)) + return false; + } + + for (size_t i = 0; i < g.materials.size(); ++i) { + const Json &j = root["materials"][i]; + GltfMaterial &m = g.materials[i]; + std::string w = "materials[" + std::to_string(i) + "]"; + m.name = j["name"].string(); + const Json &pbr = j["pbrMetallicRoughness"]; + float base[4] = {1, 1, 1, 1}, emissive[3] = {0, 0, 0}; + if (!numbers(pbr, "baseColorFactor", base, 4, w + ".pbrMetallicRoughness") || + !numbers(j, "emissiveFactor", emissive, 3, w)) + return false; + m.baseColorFactor = {base[0], base[1], base[2], base[3]}; + m.emissiveFactor = {emissive[0], emissive[1], emissive[2]}; + m.metallicFactor = pbr["metallicFactor"].numberf(1.0f); + m.roughnessFactor = pbr["roughnessFactor"].numberf(1.0f); + if (!textureRef(pbr, "baseColorTexture", m.baseColorTexture, w) || + !textureRef(pbr, "metallicRoughnessTexture", m.metallicRoughnessTexture, w) || + !textureRef(j, "normalTexture", m.normalTexture, w) || + !textureRef(j, "occlusionTexture", m.occlusionTexture, w) || + !textureRef(j, "emissiveTexture", m.emissiveTexture, w)) + return false; + m.emissiveStrength = j["extensions"]["KHR_materials_emissive_strength"]["emissiveStrength"].numberf(1.0f); + const std::string &mode = j["alphaMode"].string(); + m.alphaMode = mode == "MASK" ? GltfAlphaMode::Mask : mode == "BLEND" ? GltfAlphaMode::Blend : GltfAlphaMode::Opaque; + m.alphaCutoff = j["alphaCutoff"].numberf(0.5f); + m.doubleSided = j["doubleSided"].boolean(false); + } + + for (size_t i = 0; i < g.scenes.size(); ++i) { + const Json &j = root["scenes"][i]; + g.scenes[i].name = j["name"].string(); + for (const Json &n : j["nodes"].items()) { + long long node = n.integer(-1); + if (node < 0 || static_cast(node) >= g.nodes.size()) + return fail("scenes[" + std::to_string(i) + "].nodes: 範囲外の番号 / index out of range"); + g.scenes[i].nodes.push_back(static_cast(node)); + } + } + return index(root, "scene", g.scene, g.scenes.size(), "glTF"); +} + +bool Loader::parseBuffers(const Json &root, const std::vector *glbBin) { + for (size_t i = 0; i < g.buffers.size(); ++i) { + const Json &j = root["buffers"][i]; + std::string w = "buffers[" + std::to_string(i) + "]"; + size_t byteLength = 0; + if (!size(j, "byteLength", byteLength, w, true)) return false; + const std::string &uri = j["uri"].string(); + std::vector &data = g.buffers[i]; + if (!uri.empty()) { + std::string message; + if (!loadUri(g.path, uri, data, message)) return fail(w + ": " + message); + } else if (i == 0 && glbBin) { + data = *glbBin; // GLBの最初のバッファ=BINチャンク / the first buffer of a GLB = the BIN chunk + } else { + return fail(w + ": uriがなく、GLBのBINチャンクもない / no uri and no GLB BIN chunk"); + } + // BINチャンクは4バイト境界まで詰め物があるので、byteLength以上あれば良い + // the BIN chunk is padded to 4 bytes, so at least byteLength is enough + if (data.size() < byteLength) return fail(w + ": データがbyteLengthより短い / data shorter than byteLength"); + data.resize(byteLength); + } + return true; +} + +// バッファの範囲を超えて読むことがないよう、全部の範囲を先に確かめる +// Check every range up front, so that reading can never go past the end of a buffer +// bufferViewのないアクセサー(全部0)の上限、64 MiB / limit for accessors without a bufferView (all zeros), 64 MiB +static constexpr size_t kMaxZeroAccessorBytes = size_t{64} << 20; + +bool Loader::validate() { + for (size_t i = 0; i < g.bufferViews.size(); ++i) { + const GltfBufferView &v = g.bufferViews[i]; + size_t size = g.buffers[static_cast(v.buffer)].size(); + if (v.byteOffset > size || v.byteLength > size - v.byteOffset) + return fail("bufferViews[" + std::to_string(i) + "]: バッファをはみ出す / exceeds the buffer"); + } + + for (size_t i = 0; i < g.accessors.size(); ++i) { + const GltfAccessor &a = g.accessors[i]; + std::string w = "accessors[" + std::to_string(i) + "]"; + size_t elem = elementSize(a); + if (a.bufferView >= 0) { + const GltfBufferView &v = g.bufferViews[static_cast(a.bufferView)]; + size_t stride = v.byteStride ? v.byteStride : elem; + if (stride < elem) return fail(w + ": byteStrideが要素より小さい / byteStride smaller than an element"); + // 最後の要素の終わり = byteOffset + stride × (count − 1) + elem / end of the last element + if (a.byteOffset > v.byteLength || (a.count - 1) > (v.byteLength - a.byteOffset) / stride || + a.byteOffset + stride * (a.count - 1) + elem > v.byteLength) + return fail(w + ": bufferViewをはみ出す / exceeds its bufferView"); + } else if (a.count > kMaxZeroAccessorBytes / elem) { + // bufferViewがないと全部0の配列を確保する。巨大なcountでメモリを使い果たさないように + // Without a bufferView we allocate an array of zeros; don't let a huge count exhaust memory + return fail(w + ": bufferViewなしでcountが大き過ぎる / count too large without a bufferView"); + } + if (a.sparseCount > 0) { + if (a.sparseCount > a.count) return fail(w + ".sparse.count: countより大きい / larger than count"); + const GltfBufferView &iv = g.bufferViews[static_cast(a.sparseIndicesView)]; + const GltfBufferView &vv = g.bufferViews[static_cast(a.sparseValuesView)]; + size_t indexBytes = a.sparseCount * gltfComponentSize(a.sparseIndicesType); + size_t valueBytes = a.sparseCount * elem; + if (a.sparseIndicesOffset > iv.byteLength || indexBytes > iv.byteLength - a.sparseIndicesOffset || + a.sparseValuesOffset > vv.byteLength || valueBytes > vv.byteLength - a.sparseValuesOffset) + return fail(w + ".sparse: bufferViewをはみ出す / exceeds its bufferView"); + } + } + + for (size_t i = 0; i < g.meshes.size(); ++i) { + for (size_t k = 0; k < g.meshes[i].primitives.size(); ++k) { + const GltfPrimitive &p = g.meshes[i].primitives[k]; + std::string w = "meshes[" + std::to_string(i) + "].primitives[" + std::to_string(k) + "]"; + size_t count = 0; + for (const GltfAttribute &a : p.attributes) { + size_t c = g.accessors[static_cast(a.accessor)].count; + if (count != 0 && c != count) return fail(w + ": 属性の数がそろっていない / attributes have different counts"); + count = c; + } + if (p.indices >= 0) { + const GltfAccessor &ia = g.accessors[static_cast(p.indices)]; + if (ia.components != 1 || (ia.componentType != kGltfUnsignedByte && ia.componentType != kGltfUnsignedShort && + ia.componentType != kGltfUnsignedInt)) + return fail(w + ".indices: 符号なし整数のSCALARが必要 / must be unsigned integer SCALARs"); + } + } + } + + // ノードの親は一つだけ、輪になってはいけない / every node has at most one parent and there are no cycles + for (size_t i = 0; i < g.nodes.size(); ++i) { + for (int child : g.nodes[i].children) { + GltfNode &c = g.nodes[static_cast(child)]; + if (c.parent != -1 || static_cast(child) == i) + return fail("nodes[" + std::to_string(child) + "]: 親が二つある / has two parents (or is its own child)"); + c.parent = static_cast(i); + } + } + for (size_t i = 0; i < g.nodes.size(); ++i) { + int n = static_cast(i); + for (size_t steps = 0; n != -1; ++steps) { + if (steps > g.nodes.size()) return fail("nodes: 階層が輪になっている / the hierarchy contains a cycle"); + n = g.nodes[static_cast(n)].parent; + } + } + for (size_t i = 0; i < g.scenes.size(); ++i) + for (int n : g.scenes[i].nodes) + if (g.nodes[static_cast(n)].parent != -1) + return fail("scenes[" + std::to_string(i) + "]: ルートでないノード / a node that is not a root"); + return true; +} + +} // namespace + +//------------------------------------------ +// 読み込み / loading +//------------------------------------------ + +std::optional Gltf::load(const std::string &path) { + std::optional> file = readBinaryFile(path); + if (!file) { + fprintf(stderr, "%s: 開けない / cannot open (プロジェクトのルートから実行した? / running from the project root?)\n", + path.c_str()); + return std::nullopt; + } + Gltf g; + g.path = path; + Loader loader{g, {}}; + auto failed = [&](const std::string &message) { + fprintf(stderr, "%s: %s\n", path.c_str(), message.c_str()); + return std::nullopt; + }; + + const std::vector &bytes = *file; + std::string_view jsonText; + std::vector bin; + bool hasBin = false; + + // GLB:12バイトのヘッダー(magic "glTF"、version、全体の長さ)+チャンク(長さ、種類、中身)の並び + // GLB: a 12-byte header (magic "glTF", version, total length) + chunks (length, type, data) + if (bytes.size() >= 4 && readU32(bytes.data()) == 0x46546C67) { + if (bytes.size() < 12) return failed("GLBのヘッダーが途中で切れている / truncated GLB header"); + g.isGlb = true; + std::uint32_t version = readU32(bytes.data() + 4); + g.glbLength = readU32(bytes.data() + 8); + if (version != 2) return failed("GLBのバージョンが2でない / GLB version is not 2: " + std::to_string(version)); + if (g.glbLength > bytes.size()) return failed("ファイルが途中で切れている / the file is truncated"); + size_t offset = 12; + int chunkIndex = 0; + while (offset + 8 <= g.glbLength) { + std::uint32_t length = readU32(bytes.data() + offset); + std::uint32_t type = readU32(bytes.data() + offset + 4); + offset += 8; + if (length > g.glbLength - offset) return failed("チャンクがファイルをはみ出す / a chunk exceeds the file"); + const std::uint8_t *data = bytes.data() + offset; + if (chunkIndex == 0) { + if (type != 0x4E4F534A) return failed("最初のチャンクがJSONでない / the first chunk is not JSON"); + g.jsonChunkLength = length; + jsonText = std::string_view(reinterpret_cast(data), length); + // 空白で埋めるべき所を0で埋めるツールがある / some tools pad with zeros instead of spaces + while (!jsonText.empty() && jsonText.back() == '\0') jsonText.remove_suffix(1); + } else if (type == 0x004E4942 && !hasBin) { + g.binChunkLength = length; + bin.assign(data, data + length); + hasBin = true; + } // 知らない種類のチャンクは読み飛ばす / unknown chunk types are skipped + offset += length; + ++chunkIndex; + } + if (chunkIndex == 0) return failed("JSONチャンクがない / no JSON chunk"); + } else { + // .gltf:ファイル全体がJSON / .gltf: the whole file is JSON + jsonText = std::string_view(reinterpret_cast(bytes.data()), bytes.size()); + } + + std::string jsonError; + std::optional root = Json::parse(jsonText, &jsonError); + if (!root) return failed("JSON " + jsonError); + if (!loader.parse(*root) || !loader.parseBuffers(*root, hasBin ? &bin : nullptr) || !loader.validate()) + return failed(loader.error); + return g; +} + +//------------------------------------------ +// アクセサーを読む / reading accessors +//------------------------------------------ + +// 要素を一つずつ、成分ごとにTへ変換して読む。疎なアクセサーも処理する +// Reads element by element, converting each component to T. Handles sparse accessors too +template +static bool readAccessor(const Gltf &g, const GltfAccessor &a, std::vector &out) { + size_t n = static_cast(a.components); + size_t elem = elementSize(a); + out.assign(a.count * n, T{}); // bufferViewがなければ全部0 / all zeros without a bufferView + if (a.bufferView >= 0) { + const GltfBufferView &v = g.bufferViews[static_cast(a.bufferView)]; + const std::uint8_t *base = g.buffers[static_cast(v.buffer)].data() + v.byteOffset + a.byteOffset; + size_t stride = v.byteStride ? v.byteStride : elem; // 0 = 詰まっている / 0 = tightly packed + for (size_t e = 0; e < a.count; ++e) + for (size_t c = 0; c < n; ++c) + out[e * n + c] = static_cast( + readComponent(base + e * stride + componentOffset(a, static_cast(c)), a.componentType, a.normalized)); + } + if (a.sparseCount > 0) { + const GltfBufferView &iv = g.bufferViews[static_cast(a.sparseIndicesView)]; + const GltfBufferView &vv = g.bufferViews[static_cast(a.sparseValuesView)]; + const std::uint8_t *indices = g.buffers[static_cast(iv.buffer)].data() + iv.byteOffset + a.sparseIndicesOffset; + const std::uint8_t *values = g.buffers[static_cast(vv.buffer)].data() + vv.byteOffset + a.sparseValuesOffset; + size_t indexSize = gltfComponentSize(a.sparseIndicesType); + for (size_t k = 0; k < a.sparseCount; ++k) { + size_t e = static_cast(readComponent(indices + k * indexSize, a.sparseIndicesType, false)); + if (e >= a.count) { + fprintf(stderr, "%s: 疎なアクセサーの番号が範囲外 / sparse index out of range\n", g.path.c_str()); + return false; + } + for (size_t c = 0; c < n; ++c) + out[e * n + c] = static_cast( + readComponent(values + k * elem + componentOffset(a, static_cast(c)), a.componentType, a.normalized)); + } + } + return true; +} + +std::optional> Gltf::readFloats(int accessor) const { + if (accessor < 0 || static_cast(accessor) >= accessors.size()) return std::nullopt; + std::vector out; + if (!readAccessor(*this, accessors[static_cast(accessor)], out)) return std::nullopt; + return out; +} + +std::optional> Gltf::readIndices(int accessor) const { + if (accessor < 0 || static_cast(accessor) >= accessors.size()) return std::nullopt; + const GltfAccessor &a = accessors[static_cast(accessor)]; + if (a.components != 1 || a.normalized || a.componentType == kGltfFloat || a.componentType == kGltfByte || + a.componentType == kGltfShort) + return std::nullopt; + std::vector out; + if (!readAccessor(*this, a, out)) return std::nullopt; + return out; +} + +std::optional> Gltf::imageData(int image) const { + if (image < 0 || static_cast(image) >= images.size()) return std::nullopt; + const GltfImage &im = images[static_cast(image)]; + if (im.bufferView >= 0) { + const GltfBufferView &v = bufferViews[static_cast(im.bufferView)]; + const std::uint8_t *p = buffers[static_cast(v.buffer)].data() + v.byteOffset; + return std::vector(p, p + v.byteLength); + } + std::vector data; + std::string error; + if (!loadUri(path, im.uri, data, error)) { + fprintf(stderr, "%s: images[%d]: %s\n", path.c_str(), image, error.c_str()); + return std::nullopt; + } + return data; +} + +std::vector Gltf::rootNodes() const { + if (!scenes.empty()) return scenes[scene >= 0 ? static_cast(scene) : 0].nodes; + std::vector roots; + for (size_t i = 0; i < nodes.size(); ++i) + if (nodes[i].parent == -1) roots.push_back(static_cast(i)); + return roots; +} diff --git a/src/gltf.hh b/src/gltf.hh new file mode 100644 index 0000000..8bb2386 --- /dev/null +++ b/src/gltf.hh @@ -0,0 +1,201 @@ +// glTF 2.0の読み込み(.glbと.gltf)。GPUには触らない:ファイルの中身を構造体にするだけ。 +// Reading glTF 2.0 (.glb and .gltf). It does not touch the GPU: it only turns the file into structs. +// +// 対応 / supported: 静的なメッシュ、PBRマテリアル、テクスチャ・画像・サンプラー、ノードの階層(TRSまたは行列)、 +// GLBのBINチャンク・外部の.bin・data: URI、疎なアクセサー、KHR_mesh_quantization、KHR_materials_emissive_strength +// static meshes, PBR materials, textures/images/samplers, the node hierarchy (TRS or matrix), +// GLB BIN chunk / external .bin / data: URIs, sparse accessors, KHR_mesh_quantization, KHR_materials_emissive_strength +// 対象外 / not supported: スキン、アニメーション、モーフターゲット(読み飛ばす)、Draco・meshoptの圧縮 +// skins, animations, morph targets (skipped), Draco / meshopt compression +#pragma once + +#include "mathx.hh" + +#include +#include +#include +#include +#include +#include + +// componentType:値はOpenGLのenumと同じ(GL_FLOAT = 5126…)。このファイルはGLに依存しないので自分で定義する +// componentType: the values equal the OpenGL enums (GL_FLOAT = 5126, ...). This file does not depend on GL, +// so we define them ourselves +constexpr int kGltfByte = 5120; +constexpr int kGltfUnsignedByte = 5121; +constexpr int kGltfShort = 5122; +constexpr int kGltfUnsignedShort = 5123; +constexpr int kGltfUnsignedInt = 5125; +constexpr int kGltfFloat = 5126; + +// プリミティブのmode(GL_POINTS = 0 … GL_TRIANGLE_FAN = 6と同じ) / primitive modes (same as GL_POINTS = 0 ... GL_TRIANGLE_FAN = 6) +constexpr int kGltfTriangles = 4; + +// バッファの一部分 / a slice of a buffer +struct GltfBufferView { + int buffer = -1; + size_t byteOffset = 0; + size_t byteLength = 0; + size_t byteStride = 0; // 0 = 要素が詰まって並ぶ / 0 = elements are tightly packed + int target = 0; // 34962 = 頂点、34963 = インデックス(ヒントだけ) / 34962 = vertices, 34963 = indices (just a hint) +}; + +// 型付きの配列:bufferViewのどこに、どの型の要素がいくつあるか +// A typed array: where in a bufferView, which type, how many elements +struct GltfAccessor { + std::string name; + int bufferView = -1; // -1 = 全部0(疎な値だけを持つアクセサー) / -1 = all zeros (an accessor with only sparse values) + size_t byteOffset = 0; // bufferViewの先頭から / from the start of the bufferView + int componentType = kGltfFloat; + bool normalized = false; // 整数を0〜1(符号付きは-1〜1)にする / map integers to 0..1 (signed: -1..1) + size_t count = 0; // 要素の数 / number of elements + std::string type; // "SCALAR"、"VEC2"、"VEC3"、"VEC4"、"MAT2"、"MAT3"、"MAT4" + int components = 0; // typeの成分数 / number of components of type + std::vector min, max; + + // 疎なアクセサー:一部の要素だけを別の値で上書きする / sparse accessor: overrides some elements with other values + size_t sparseCount = 0; // 0 = 疎でない / 0 = not sparse + int sparseIndicesView = -1; + size_t sparseIndicesOffset = 0; + int sparseIndicesType = kGltfUnsignedInt; + int sparseValuesView = -1; + size_t sparseValuesOffset = 0; +}; + +struct GltfAttribute { + std::string name; // "POSITION"、"NORMAL"、"TEXCOORD_0"、"TANGENT"… + int accessor = -1; +}; + +// 一回の描画呼び出しの単位:属性+インデックス+マテリアル / one draw call: attributes + indices + material +struct GltfPrimitive { + std::vector attributes; + int indices = -1; // -1 = インデックスなし(glDrawArrays) / -1 = no indices (glDrawArrays) + int material = -1; // -1 = 既定のマテリアル / -1 = the default material + int mode = kGltfTriangles; + bool hasMorphTargets = false; // 読み飛ばした / skipped + + int attribute(std::string_view name) const; // アクセサーの番号、なければ-1 / accessor index, -1 if absent +}; + +struct GltfMesh { + std::string name; + std::vector primitives; +}; + +// シーングラフのノード:変換と、メッシュ(任意)と、子ノード +// A scene graph node: a transform, an optional mesh, and child nodes +struct GltfNode { + std::string name; + int mesh = -1; + int parent = -1; // 読み込み時に子の一覧から求める / computed from the children lists when loading + std::vector children; + // ローカル変換:行列か、平行移動・回転・拡大縮小(TRS)のどちらか + // Local transform: either a matrix or translation / rotation / scale (TRS) + bool hasMatrix = false; + Mat4 matrix = Mat4::identity(); + Vec3 translation = {0.0f, 0.0f, 0.0f}; + Quat rotation; // 単位クォータニオン(ファイルでは x, y, z, w の順) / unit quaternion (x, y, z, w in the file) + Vec3 scale = {1.0f, 1.0f, 1.0f}; + bool hasSkin = false; // 読み飛ばした / skipped + + // 親から見たこのノードの変換:matrix、または T × R × S / this node's transform relative to its parent + Mat4 localTransform() const; +}; + +// マテリアルからテクスチャへの参照 / a reference from a material to a texture +struct GltfTextureRef { + int index = -1; // texturesの番号、-1 = なし / index into textures, -1 = none + int texCoord = 0; // どのTEXCOORD_nを使うか / which TEXCOORD_n to use + float scale = 1.0f; // normalTextureのscale、occlusionTextureのstrength +}; + +enum class GltfAlphaMode { Opaque, Mask, Blend }; + +// PBR(金属・粗さ)マテリアル。ファイルにない値はglTFの既定値 / PBR (metallic-roughness) material; glTF defaults +struct GltfMaterial { + std::string name; + Vec4 baseColorFactor = {1.0f, 1.0f, 1.0f, 1.0f}; + GltfTextureRef baseColorTexture; + float metallicFactor = 1.0f; + float roughnessFactor = 1.0f; + GltfTextureRef metallicRoughnessTexture; // G = 粗さ / roughness、B = 金属度 / metallic + GltfTextureRef normalTexture; + GltfTextureRef occlusionTexture; + GltfTextureRef emissiveTexture; + Vec3 emissiveFactor = {0.0f, 0.0f, 0.0f}; + float emissiveStrength = 1.0f; // KHR_materials_emissive_strength + GltfAlphaMode alphaMode = GltfAlphaMode::Opaque; + float alphaCutoff = 0.5f; + bool doubleSided = false; +}; + +struct GltfTexture { + int source = -1; // imagesの番号 / index into images + int sampler = -1; // -1 = 既定(繰り返し、線型+ミップマップ) / -1 = default (repeat, linear + mipmaps) +}; + +struct GltfImage { + std::string name; + std::string mimeType; // "image/png"、"image/jpeg" + std::string uri; // ファイル名かdata: URI(bufferViewがなければ) / a file name or a data: URI (if no bufferView) + int bufferView = -1; +}; + +// 値はOpenGLのenumと同じ。0 = ファイルに書かれていない / values are the OpenGL enums; 0 = not given in the file +struct GltfSampler { + int magFilter = 0; + int minFilter = 0; + int wrapS = 10497; // GL_REPEAT + int wrapT = 10497; +}; + +struct GltfScene { + std::string name; + std::vector nodes; // ルートノード / the root nodes +}; + +// ファイル一つ分のglTF / one glTF file +struct Gltf { + std::string path; + + // 入れ物の情報(表示用) / container information (for printing) + bool isGlb = false; + std::uint32_t glbLength = 0, jsonChunkLength = 0, binChunkLength = 0; + + std::string version, generator, copyright; + std::vector extensionsUsed, extensionsRequired; + + std::vector> buffers; // 中身を読み込んだバッファ / the loaded buffer contents + std::vector bufferViews; + std::vector accessors; + std::vector meshes; + std::vector nodes; + std::vector materials; + std::vector textures; + std::vector images; + std::vector samplers; + std::vector scenes; + int scene = -1; // 既定のシーン、-1 = 指定なし / the default scene, -1 = not specified + size_t skinCount = 0, animationCount = 0, cameraCount = 0; // 数だけ数える / only counted + + // .glbまたは.gltfを読んで全部を検査する。失敗したらエラーを表示してstd::nullopt。 + // Loads a .glb or .gltf and validates everything. On failure prints the error and returns std::nullopt. + static std::optional load(const std::string &path); + + // アクセサーを読み、count × components個のfloatにする(どのcomponentTypeでも、正規化も処理する) + // Reads an accessor into count × components floats (any componentType, normalization handled) + std::optional> readFloats(int accessor) const; + // インデックスを読み、u8・u16・u32をすべてu32にする / reads indices; u8, u16 and u32 all become u32 + std::optional> readIndices(int accessor) const; + // 画像ファイルのバイト列(PNG、JPEG…) / the bytes of an image file (PNG, JPEG, ...) + std::optional> imageData(int image) const; + + // 描くべきルートノード:既定のシーン、なければ最初のシーン、シーンがなければ親のないノード全部 + // The root nodes to draw: the default scene, else the first one, else every node without a parent + std::vector rootNodes() const; +}; + +// componentTypeの名前とバイト数 / name and byte size of a componentType +const char *gltfComponentTypeName(int componentType); +size_t gltfComponentSize(int componentType); diff --git a/src/gltf_dump.cc b/src/gltf_dump.cc new file mode 100644 index 0000000..d00be55 --- /dev/null +++ b/src/gltf_dump.cc @@ -0,0 +1,292 @@ +// glTF/GLBファイルの中身を表示する道具(第13章)。GPUもウィンドウも使わない。 +// A tool that prints what is inside a glTF/GLB file (chapter 13). Uses no GPU and no window. +// +// 使い方 / usage: gltf_dump [--all] file.glb [file2.gltf ...] +// --all bufferViewとアクセサーの一覧も表示する / also list every bufferView and accessor +// 最後に、全部のアクセサーを実際に読んで確かめる(min/max、インデックスの範囲)。 +// At the end, every accessor is actually read and checked (min/max, index ranges). +#ifdef _WIN32 +// SetConsoleOutputCPの為。GLADより先にインクルードする(APIENTRYの二重定義を防ぐ) +// For SetConsoleOutputCP. Include it before GLAD (so APIENTRY is not defined twice) +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include +#endif +#include "gltf.hh" + +#include +#include +#include +#include + +static const char *modeName(int mode) { + static const char *const kNames[] = {"POINTS", "LINES", "LINE_LOOP", "LINE_STRIP", + "TRIANGLES", "TRIANGLE_STRIP", "TRIANGLE_FAN"}; + return mode >= 0 && mode <= 6 ? kNames[mode] : "?"; +} + +static const char *targetName(int target) { + if (target == 34962) return ", ARRAY_BUFFER"; + if (target == 34963) return ", ELEMENT_ARRAY_BUFFER"; + return ""; +} + +static const char *nameOr(const std::string &name, const char *fallback) { return name.empty() ? fallback : name.c_str(); } + +static void printAccessor(const Gltf &g, int index) { + const GltfAccessor &a = g.accessors[static_cast(index)]; + printf("%-6s %-14s x %-5zu", a.type.c_str(), gltfComponentTypeName(a.componentType), a.count); + if (a.normalized) printf(" normalized"); + if (a.bufferView >= 0) { + const GltfBufferView &v = g.bufferViews[static_cast(a.bufferView)]; + printf(" view %d +%zu", a.bufferView, a.byteOffset); + if (v.byteStride) printf(" stride %zu", v.byteStride); + } else { + printf(" (no bufferView: zeros)"); + } + if (a.sparseCount) printf(", sparse %zu", a.sparseCount); +} + +static void printTexture(const Gltf &g, const char *label, const GltfTextureRef &t) { + if (t.index < 0) return; + const GltfTexture &tex = g.textures[static_cast(t.index)]; + printf("\n %s: texture %d (image %d", label, t.index, tex.source); + if (tex.source >= 0) printf(" \"%s\"", nameOr(g.images[static_cast(tex.source)].name, "")); + printf(")"); + if (t.texCoord != 0) printf(", TEXCOORD_%d", t.texCoord); +} + +static void printTransform(const GltfNode &n) { + if (n.hasMatrix) { + const Mat4 &m = n.matrix; + printf(" matrix T(%g, %g, %g)", m.c[3].x, m.c[3].y, m.c[3].z); + return; + } + const Vec3 &t = n.translation; + if (t.x != 0.0f || t.y != 0.0f || t.z != 0.0f) printf(" T(%g, %g, %g)", t.x, t.y, t.z); + const Quat &q = n.rotation; + if (q.w < 0.999999f) { + // 軸と角度で表示する方が読みやすい:q = (cos(θ/2), 軸 · sin(θ/2)) / easier to read as axis and angle + float angle = 2.0f * std::acos(q.w > 1.0f ? 1.0f : q.w); + float s = std::sin(angle * 0.5f); + auto clean = [](float v) { return std::fabs(v) < 5e-7f ? 0.0f : v; }; // -0を表示しない / do not print -0 + printf(" R(%.1f deg about %.3g, %.3g, %.3g)", degrees(angle), clean(q.x / s), clean(q.y / s), clean(q.z / s)); + } + const Vec3 &s = n.scale; + if (s.x != 1.0f || s.y != 1.0f || s.z != 1.0f) printf(" S(%g, %g, %g)", s.x, s.y, s.z); +} + +// ノードの木を「+-」と「|」で描く / draws the node tree with "+-" and "|" +static void printNode(const Gltf &g, int index, const std::string &prefix, bool last, bool root) { + const GltfNode &n = g.nodes[static_cast(index)]; + printf(" %s%s%s", prefix.c_str(), root ? "" : "+- ", nameOr(n.name, "(unnamed)")); + if (n.mesh >= 0) printf(" [mesh %d \"%s\"]", n.mesh, g.meshes[static_cast(n.mesh)].name.c_str()); + printTransform(n); + if (n.hasSkin) printf(" (skin ignored)"); + printf("\n"); + std::string childPrefix = root ? prefix : prefix + (last ? " " : "| "); + for (size_t i = 0; i < n.children.size(); ++i) + printNode(g, n.children[i], childPrefix, i + 1 == n.children.size(), false); +} + +// 全部のプリミティブを読んでみる。問題の数を返す / reads every primitive; returns the number of problems +static int verify(const Gltf &g, size_t &primitiveCount) { + int problems = 0; + primitiveCount = 0; + for (size_t m = 0; m < g.meshes.size(); ++m) { + for (size_t k = 0; k < g.meshes[m].primitives.size(); ++k) { + const GltfPrimitive &p = g.meshes[m].primitives[k]; + ++primitiveCount; + size_t vertexCount = 0; + for (const GltfAttribute &attr : p.attributes) { + const GltfAccessor &a = g.accessors[static_cast(attr.accessor)]; + std::optional> data = g.readFloats(attr.accessor); + if (!data) { + printf(" ! mesh %zu prim %zu %s: cannot read\n", m, k, attr.name.c_str()); + ++problems; + continue; + } + vertexCount = a.count; + // ファイルのmin/maxと、実際に読んだ値を比べる / compare the file's min/max with the values actually read + if (a.min.size() == static_cast(a.components) && a.max.size() == a.min.size()) { + for (size_t c = 0; c < a.min.size(); ++c) { + float lo = 1e30f, hi = -1e30f; + for (size_t e = 0; e < a.count; ++e) { + float v = (*data)[e * a.min.size() + c]; + lo = v < lo ? v : lo; + hi = v > hi ? v : hi; + } + double tolerance = 1e-4 * (1.0 + std::fabs(a.max[c] - a.min[c])); + if (std::fabs(lo - a.min[c]) > tolerance || std::fabs(hi - a.max[c]) > tolerance) { + printf(" ! mesh %zu prim %zu %s: min/max (%g..%g) differ from the data (%g..%g)\n", m, k, + attr.name.c_str(), a.min[c], a.max[c], static_cast(lo), static_cast(hi)); + ++problems; + } + } + } + } + if (p.indices >= 0) { + std::optional> indices = g.readIndices(p.indices); + if (!indices) { + printf(" ! mesh %zu prim %zu: cannot read the indices\n", m, k); + ++problems; + continue; + } + for (std::uint32_t i : *indices) { + if (i >= vertexCount) { + printf(" ! mesh %zu prim %zu: index %u >= vertex count %zu\n", m, k, i, vertexCount); + ++problems; + break; + } + } + } + if (p.attribute("POSITION") < 0) { + printf(" ! mesh %zu prim %zu: no POSITION (will not be drawn)\n", m, k); + ++problems; + } + } + } + return problems; +} + +static bool dump(const std::string &path, bool all) { + std::optional loaded = Gltf::load(path); + if (!loaded) return false; + const Gltf &g = *loaded; + + printf("== %s ==\n", path.c_str()); + if (g.isGlb) + printf("GLB version 2, %u bytes: JSON chunk %u bytes, BIN chunk %u bytes\n", g.glbLength, g.jsonChunkLength, + g.binChunkLength); + else + printf("glTF (JSON text)\n"); + printf("asset: glTF %s, generator \"%s\"\n", g.version.c_str(), g.generator.c_str()); + for (const std::string &e : g.extensionsUsed) printf("extension used: %s\n", e.c_str()); + for (const std::string &e : g.extensionsRequired) printf("extension required: %s\n", e.c_str()); + if (g.skinCount || g.animationCount || g.cameraCount) + printf("ignored: %zu skins, %zu animations, %zu cameras\n", g.skinCount, g.animationCount, g.cameraCount); + + printf("buffers (%zu)\n", g.buffers.size()); + for (size_t i = 0; i < g.buffers.size(); ++i) printf(" [%zu] %zu bytes\n", i, g.buffers[i].size()); + + printf("bufferViews (%zu), accessors (%zu)\n", g.bufferViews.size(), g.accessors.size()); + if (all) { + for (size_t i = 0; i < g.bufferViews.size(); ++i) { + const GltfBufferView &v = g.bufferViews[i]; + printf(" view [%zu] buffer %d, offset %zu, %zu bytes", i, v.buffer, v.byteOffset, v.byteLength); + if (v.byteStride) printf(", stride %zu", v.byteStride); + printf("%s\n", targetName(v.target)); + } + for (size_t i = 0; i < g.accessors.size(); ++i) { + printf(" accessor [%zu] ", i); + printAccessor(g, static_cast(i)); + printf("\n"); + } + } + + printf("meshes (%zu)\n", g.meshes.size()); + for (size_t i = 0; i < g.meshes.size(); ++i) { + const GltfMesh &m = g.meshes[i]; + printf(" [%zu] \"%s\": %zu primitive%s\n", i, m.name.c_str(), m.primitives.size(), + m.primitives.size() == 1 ? "" : "s"); + for (size_t k = 0; k < m.primitives.size(); ++k) { + const GltfPrimitive &p = m.primitives[k]; + printf(" #%zu %s, material ", k, modeName(p.mode)); + if (p.material >= 0) printf("%d \"%s\"", p.material, g.materials[static_cast(p.material)].name.c_str()); + else printf("(default)"); + if (p.indices >= 0) { + const GltfAccessor &ia = g.accessors[static_cast(p.indices)]; + printf(", %zu indices (%s)", ia.count, gltfComponentTypeName(ia.componentType)); + } else { + printf(", no indices"); + } + if (p.hasMorphTargets) printf(", morph targets ignored"); + printf("\n"); + for (const GltfAttribute &a : p.attributes) { + printf(" %-11s ", a.name.c_str()); + printAccessor(g, a.accessor); + printf("\n"); + } + } + } + + printf("materials (%zu)\n", g.materials.size()); + for (size_t i = 0; i < g.materials.size(); ++i) { + const GltfMaterial &m = g.materials[i]; + const Vec4 &b = m.baseColorFactor; + printf(" [%zu] \"%s\": base colour (%g, %g, %g, %g), metallic %g, roughness %g", i, m.name.c_str(), b.x, b.y, b.z, + b.w, m.metallicFactor, m.roughnessFactor); + if (m.emissiveFactor.x > 0.0f || m.emissiveFactor.y > 0.0f || m.emissiveFactor.z > 0.0f) + printf(", emissive (%g, %g, %g) x %g", m.emissiveFactor.x, m.emissiveFactor.y, m.emissiveFactor.z, + m.emissiveStrength); + if (m.alphaMode != GltfAlphaMode::Opaque) printf(", alpha %s", m.alphaMode == GltfAlphaMode::Mask ? "MASK" : "BLEND"); + if (m.doubleSided) printf(", double-sided"); + printTexture(g, "baseColorTexture", m.baseColorTexture); + printTexture(g, "metallicRoughnessTexture", m.metallicRoughnessTexture); + printTexture(g, "normalTexture", m.normalTexture); + printTexture(g, "occlusionTexture", m.occlusionTexture); + printTexture(g, "emissiveTexture", m.emissiveTexture); + printf("\n"); + } + + printf("textures (%zu), images (%zu), samplers (%zu)\n", g.textures.size(), g.images.size(), g.samplers.size()); + for (size_t i = 0; i < g.textures.size(); ++i) { + const GltfTexture &t = g.textures[i]; + printf(" texture [%zu] image %d, ", i, t.source); + if (t.sampler < 0) { + printf("default sampler\n"); + } else { + const GltfSampler &s = g.samplers[static_cast(t.sampler)]; + printf("sampler %d (mag %d, min %d, wrap %d/%d)\n", t.sampler, s.magFilter, s.minFilter, s.wrapS, s.wrapT); + } + } + for (size_t i = 0; i < g.images.size(); ++i) { + const GltfImage &im = g.images[i]; + printf(" image [%zu] \"%s\" %s, ", i, im.name.c_str(), nameOr(im.mimeType, "(no mimeType)")); + if (im.bufferView >= 0) + printf("%zu bytes in bufferView %d\n", g.bufferViews[static_cast(im.bufferView)].byteLength, im.bufferView); + else + printf("uri %.60s\n", im.uri.c_str()); + } + + printf("nodes (%zu), scenes (%zu)\n", g.nodes.size(), g.scenes.size()); + std::vector roots = g.rootNodes(); + if (!g.scenes.empty()) { + int s = g.scene >= 0 ? g.scene : 0; + printf("scene %d \"%s\"%s:\n", s, g.scenes[static_cast(s)].name.c_str(), g.scene >= 0 ? " (default)" : ""); + } else { + printf("no scenes: all root nodes:\n"); + } + for (size_t i = 0; i < roots.size(); ++i) printNode(g, roots[i], "", i + 1 == roots.size(), true); + + size_t primitives = 0; + int problems = verify(g, primitives); + if (problems == 0) + printf("check: read %zu primitive%s, all accessors and indices OK\n", primitives, primitives == 1 ? "" : "s"); + else + printf("check: %d problem%s\n", problems, problems == 1 ? "" : "s"); + return true; +} + +int main(int argc, char **argv) { +#ifdef _WIN32 + // コンソールの出力をUTF-8にする(日本語のメッセージが文字化けしない様に) + // switch the console output to UTF-8 (so the Japanese messages are not garbled) + SetConsoleOutputCP(CP_UTF8); +#endif + bool all = false; + int files = 0, failures = 0; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--all") == 0) { + all = true; + continue; + } + if (files++ > 0) printf("\n"); + if (!dump(argv[i], all)) ++failures; + } + if (files == 0) { + fprintf(stderr, "使い方 / usage: gltf_dump [--all] file.glb [file2.gltf ...]\n"); + return 2; + } + return failures == 0 ? 0 : 1; +} diff --git a/src/json.cc b/src/json.cc new file mode 100644 index 0000000..9176837 --- /dev/null +++ b/src/json.cc @@ -0,0 +1,301 @@ +#include "json.hh" + +#include +#include +#include + +// 見つからないときに返すnull / the null returned when something is not found +static const Json kNullJson; +static const std::string kEmptyString; + +const std::string &Json::string() const { return kind == Type::String ? text : kEmptyString; } + +long long Json::integer(long long fallback) const { + // 2^53までのdoubleは整数を正確に表せる / a double represents integers exactly up to 2^53 + if (kind != Type::Number || num != std::floor(num) || std::fabs(num) > 9007199254740992.0) return fallback; + return static_cast(num); +} + +size_t Json::size() const { + if (kind == Type::Array) return array.size(); + if (kind == Type::Object) return object.size(); + return 0; +} + +const Json &Json::operator[](size_t index) const { + return kind == Type::Array && index < array.size() ? array[index] : kNullJson; +} + +const Json *Json::find(std::string_view key) const { + if (kind != Type::Object) return nullptr; + // glTFのオブジェクトは小さいので順番に探せば十分 / glTF objects are small: a linear search is enough + for (const JsonMember &m : object) + if (m.key == key) return &m.value; + return nullptr; +} + +const Json &Json::operator[](std::string_view key) const { + const Json *v = find(key); + return v ? *v : kNullJson; +} + +//------------------------------------------ +// パーサー(再帰下降) / the parser (recursive descent) +//------------------------------------------ + +class JsonParser { +public: + explicit JsonParser(std::string_view source) : s(source) {} + + bool parseDocument(Json &out) { + // UTF-8のBOMは読み飛ばす(glTFでは禁止だが、付けるツールがある) / skip a UTF-8 BOM (forbidden in glTF, but some tools add one) + if (s.substr(0, 3) == "\xEF\xBB\xBF") pos = 3; + skipSpace(); + if (!parseValue(out)) return false; + skipSpace(); + if (pos != s.size()) return fail("値の後に余分な文字 / unexpected characters after the value"); + return true; + } + + // 「行:列: 理由」 / "line:column: reason" + std::string errorMessage() const { + int line = 1, column = 1; + for (size_t i = 0; i < errorPos && i < s.size(); ++i) { + if (s[i] == '\n') { + ++line; + column = 1; + } else { + ++column; + } + } + return std::to_string(line) + ":" + std::to_string(column) + ": " + error; + } + +private: + static constexpr int kMaxDepth = 512; // 深すぎる入れ子でスタックが溢れないように / so deep nesting cannot overflow the stack + + bool fail(const char *message) { + if (error.empty()) { + error = message; + errorPos = pos; + } + return false; + } + + bool atEnd() const { return pos >= s.size(); } + char peek() const { return atEnd() ? '\0' : s[pos]; } + + void skipSpace() { + while (!atEnd() && (s[pos] == ' ' || s[pos] == '\t' || s[pos] == '\n' || s[pos] == '\r')) ++pos; + } + + bool literal(std::string_view word) { + if (s.substr(pos, word.size()) != word) return fail("不正な値 / invalid value"); + pos += word.size(); + return true; + } + + bool parseValue(Json &out) { + switch (peek()) { + case '{': return parseObject(out); + case '[': return parseArray(out); + case '"': out.kind = Json::Type::String; return parseString(out.text); + case 't': out.kind = Json::Type::Bool; out.flag = true; return literal("true"); + case 'f': out.kind = Json::Type::Bool; out.flag = false; return literal("false"); + case 'n': out.kind = Json::Type::Null; return literal("null"); + default: + if (peek() == '-' || (peek() >= '0' && peek() <= '9')) return parseNumber(out); + return fail(atEnd() ? "途中で終わっている / unexpected end of input" : "不正な値 / invalid value"); + } + } + + bool parseObject(Json &out) { + if (++depth > kMaxDepth) return fail("入れ子が深すぎる / nesting too deep"); + out.kind = Json::Type::Object; + ++pos; // '{' + skipSpace(); + if (peek() == '}') { + ++pos; + --depth; + return true; + } + while (true) { + skipSpace(); + if (peek() != '"') return fail("キー(文字列)が必要 / expected a key (string)"); + JsonMember member; + if (!parseString(member.key)) return false; + skipSpace(); + if (peek() != ':') return fail("「:」が必要 / expected ':'"); + ++pos; + skipSpace(); + if (!parseValue(member.value)) return false; + out.object.push_back(std::move(member)); + skipSpace(); + if (peek() == ',') { + ++pos; + continue; + } + if (peek() == '}') { + ++pos; + --depth; + return true; + } + return fail("「,」か「}」が必要 / expected ',' or '}'"); + } + } + + bool parseArray(Json &out) { + if (++depth > kMaxDepth) return fail("入れ子が深すぎる / nesting too deep"); + out.kind = Json::Type::Array; + ++pos; // '[' + skipSpace(); + if (peek() == ']') { + ++pos; + --depth; + return true; + } + while (true) { + skipSpace(); + Json item; + if (!parseValue(item)) return false; + out.array.push_back(std::move(item)); + skipSpace(); + if (peek() == ',') { + ++pos; + continue; + } + if (peek() == ']') { + ++pos; + --depth; + return true; + } + return fail("「,」か「]」が必要 / expected ',' or ']'"); + } + } + + // 16進数4桁(\uXXXXのXXXX) / four hex digits (the XXXX of \uXXXX) + bool hex4(unsigned &value) { + value = 0; + for (int i = 0; i < 4; ++i) { + char c = peek(); + unsigned digit; + if (c >= '0' && c <= '9') digit = static_cast(c - '0'); + else if (c >= 'a' && c <= 'f') digit = static_cast(c - 'a' + 10); + else if (c >= 'A' && c <= 'F') digit = static_cast(c - 'A' + 10); + else return fail("\\uの後に16進数4桁が必要 / expected 4 hex digits after \\u"); + value = value * 16 + digit; + ++pos; + } + return true; + } + + // コードポイントをUTF-8で書く / write a code point as UTF-8 + static void appendUtf8(std::string &out, unsigned cp) { + if (cp < 0x80) { + out += static_cast(cp); + } else if (cp < 0x800) { + out += static_cast(0xC0 | (cp >> 6)); + out += static_cast(0x80 | (cp & 0x3F)); + } else if (cp < 0x10000) { + out += static_cast(0xE0 | (cp >> 12)); + out += static_cast(0x80 | ((cp >> 6) & 0x3F)); + out += static_cast(0x80 | (cp & 0x3F)); + } else { + out += static_cast(0xF0 | (cp >> 18)); + out += static_cast(0x80 | ((cp >> 12) & 0x3F)); + out += static_cast(0x80 | ((cp >> 6) & 0x3F)); + out += static_cast(0x80 | (cp & 0x3F)); + } + } + + bool parseString(std::string &out) { + ++pos; // '"' + while (true) { + if (atEnd()) return fail("文字列が閉じていない / unterminated string"); + char c = s[pos++]; + if (c == '"') return true; + if (static_cast(c) < 0x20) return fail("文字列の中に制御文字 / control character in a string"); + if (c != '\\') { + out += c; // UTF-8のバイトはそのまま / UTF-8 bytes are copied as they are + continue; + } + if (atEnd()) return fail("文字列が閉じていない / unterminated string"); + char e = s[pos++]; + switch (e) { + case '"': out += '"'; break; + case '\\': out += '\\'; break; + case '/': out += '/'; break; + case 'b': out += '\b'; break; + case 'f': out += '\f'; break; + case 'n': out += '\n'; break; + case 'r': out += '\r'; break; + case 't': out += '\t'; break; + case 'u': { + unsigned cp = 0; + if (!hex4(cp)) return false; + // U+10000以上は「サロゲートペア」二つの\uで書かれる / U+10000 and above are written as a surrogate pair + if (cp >= 0xD800 && cp <= 0xDBFF) { + unsigned low = 0; + if (s.substr(pos, 2) != "\\u") return fail("サロゲートペアの後半がない / missing low surrogate"); + pos += 2; + if (!hex4(low)) return false; + if (low < 0xDC00 || low > 0xDFFF) return fail("不正なサロゲートペア / invalid surrogate pair"); + cp = 0x10000 + ((cp - 0xD800) << 10) + (low - 0xDC00); + } else if (cp >= 0xDC00 && cp <= 0xDFFF) { + return fail("不正なサロゲートペア / invalid surrogate pair"); + } + appendUtf8(out, cp); + break; + } + default: --pos; return fail("不正なエスケープ / invalid escape sequence"); + } + } + } + + bool digits() { + if (!(peek() >= '0' && peek() <= '9')) return fail("数字が必要 / expected a digit"); + while (peek() >= '0' && peek() <= '9') ++pos; + return true; + } + + // JSONの数の文法を確かめてから、strtodで変換する(strtodは「C」ロケールで小数点が「.」) + // Check JSON's number grammar first, then convert with strtod (in the "C" locale its decimal point is '.') + bool parseNumber(Json &out) { + size_t start = pos; + if (peek() == '-') ++pos; + if (peek() == '0') { + ++pos; // 先頭の0の後に数字は続けられない / no digits after a leading 0 + } else if (!digits()) { + return false; + } + if (peek() == '.') { + ++pos; + if (!digits()) return false; + } + if (peek() == 'e' || peek() == 'E') { + ++pos; + if (peek() == '+' || peek() == '-') ++pos; + if (!digits()) return false; + } + std::string token(s.substr(start, pos - start)); // strtodには0終端の文字列が要る / strtod needs a 0-terminated string + out.kind = Json::Type::Number; + out.num = std::strtod(token.c_str(), nullptr); + return true; + } + + std::string_view s; + size_t pos = 0; + int depth = 0; + std::string error; + size_t errorPos = 0; +}; + +std::optional Json::parse(std::string_view text, std::string *error) { + JsonParser parser(text); + Json root; + if (!parser.parseDocument(root)) { + if (error) *error = parser.errorMessage(); + return std::nullopt; + } + return root; +} diff --git a/src/json.hh b/src/json.hh new file mode 100644 index 0000000..ce2e984 --- /dev/null +++ b/src/json.hh @@ -0,0 +1,67 @@ +// 小さなJSONパーサー(glTFを読むため) / a small JSON parser (for reading glTF) +#pragma once + +#include +#include +#include +#include +#include + +struct JsonMember; + +// JSONの値一つ:null・真偽値・数・文字列・配列・オブジェクトのどれか。 +// 読むだけ(書き出しはしない)。見つからない要素を取り出すとnullが返るので、 +// json["a"]["b"][0] のように確認なしで辿れる。 +// One JSON value: null, a boolean, a number, a string, an array or an object. +// Read-only (no writing). Looking up something that does not exist gives null, so +// json["a"]["b"][0] can be chained without checks. +class Json { +public: + enum class Type { Null, Bool, Number, String, Array, Object }; + + // テキスト全体を読む。失敗したらerrorに「行:列: 理由」を入れてstd::nullopt。 + // Parses a whole text. On failure stores "line:column: reason" in error and returns std::nullopt. + static std::optional parse(std::string_view text, std::string *error = nullptr); + + Type type() const { return kind; } + bool isNull() const { return kind == Type::Null; } + bool isBool() const { return kind == Type::Bool; } + bool isNumber() const { return kind == Type::Number; } + bool isString() const { return kind == Type::String; } + bool isArray() const { return kind == Type::Array; } + bool isObject() const { return kind == Type::Object; } + + // 値を取り出す。型が違えばfallback / get the value; fallback if the type is different + bool boolean(bool fallback = false) const { return kind == Type::Bool ? flag : fallback; } + double number(double fallback = 0.0) const { return kind == Type::Number ? num : fallback; } + float numberf(float fallback = 0.0f) const { return kind == Type::Number ? static_cast(num) : fallback; } + const std::string &string() const; // 文字列でなければ空 / empty if not a string + + // 整数として読む。整数でない・範囲外ならfallback(glTFの番号はすべて0以上の整数) + // Reads an integer. fallback if it is not an integer or out of range (all glTF indices are integers ≥ 0) + long long integer(long long fallback = -1) const; + + // 配列の要素数、またはオブジェクトのメンバー数 / number of array elements or object members + size_t size() const; + const Json &operator[](size_t index) const; // 配列の要素(なければnull) / array element (null if none) + const Json &operator[](std::string_view key) const; // オブジェクトのメンバー(なければnull) / object member (null if none) + const Json *find(std::string_view key) const; // メンバー、なければnullptr / member, nullptr if none + bool has(std::string_view key) const { return find(key) != nullptr; } + + const std::vector &items() const { return array; } // 配列の要素 / array elements + const std::vector &members() const { return object; } // オブジェクトのメンバー(書かれた順) / members, in file order + +private: + friend class JsonParser; + Type kind = Type::Null; + bool flag = false; + double num = 0.0; + std::string text; + std::vector array; + std::vector object; // 不完全型のvectorはC++17から使える / a vector of an incomplete type is fine since C++17 +}; + +struct JsonMember { + std::string key; + Json value; +}; diff --git a/src/main.cc b/src/main.cc index d88b925..9a4535f 100644 --- a/src/main.cc +++ b/src/main.cc @@ -1,5 +1,5 @@ -// 第12章:光源と複数のライト -// Chapter 12: light casters and multiple lights +// 第13章:glTFとGLB:ファイルの読み込み(このプログラムは第12章と同じ。新しいのは gltf_dump) +// Chapter 13: glTF and GLB: reading the file (this program is the same as in chapter 12; the new part is gltf_dump) // // 操作 / Controls: // WASD 前後左右に移動 / move forward, back, left, right @@ -98,7 +98,7 @@ static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specu int main() { Window window; - if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 12")) return 1; + if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 13")) return 1; std::optional phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); std::optional unlit = Shader::load("shaders/unlit.vert", "shaders/unlit.frag");