13. glTFとGLB:ファイルの読み込み

此れまで描いて来た物は全てC++で作りました。
makeCube()、makeSphere()、makePlane()、そして位置の表です。
木箱なら其れで十分ですが、キャラクターや風車を頂点座標の打ち込みでモデリングする人は居ません。
実際のプロジェクトでは、メッシュはBlenderの様なモデリングソフトから来ます。
そして今、殆ど誰もが合意しているファイル形式がglTF 2.0です。

此の章と次の章は2つで1組です。
此の章ではglTFファイルの構成を学び、其れを普通のC++の構造体に読み込むコードを書きます。
バッファの終わりを超えて読む事が絶対に無い様に、全てを慎重に検査します。
第14章で其の構造体をGPUにアップロードして描きます。
従って此の章にはOpenGLが殆ど出て来ません。
ゲームはウィンドウのタイトル以外、第12章と同じです。
新しいのはJSONパーサー、glTF/GLBリーダー、そしてモデルファイルの中身を表示する小さなコンソールツールgltf_dumpです。

13.1 此の章で作る物

此の章に付いている木箱のモデルにgltf_dump --allを実行すると、此うなります:

木箱のモデルにダンプツールを--all付きで実行した全出力。GLBのヘッダー、7つのbufferView、5つのアクセサー、POSITION・NORMAL・TEXCOORD 0・TANGENTを持つメッシュ1つ、テクスチャ2枚のマテリアル、ノードの木

入れ物(74,512バイトのGLBファイル)、バイナリデータの全ての切れ端、4つの頂点属性を持つメッシュ、マテリアルと其の2枚のテクスチャ、ノードの木が表示されています。
一番大事なのは最後の行です。
ツールが全てのアクセサーと全てのインデックスを実際に読み、何の問題も見つけなかった事を示しています。
此の章を読み終われば、此の出力の全ての行が分かる様になります。

第12章からの変更:

  • src/json.hhとsrc/json.cc(新規):小さなJSONパーサー
  • src/gltf.hhとsrc/gltf.cc(新規):glTF/GLBリーダー。データだけで、GLは使わない
  • src/gltf_dump.cc(新規):コンソールツール
  • src/file_util.hhとsrc/file_util.cc:readBinaryFile()
  • assets/models/crate.glbとassets/models/diorama.glb(新規)、及びassets/LICENSE.txtの2行(完成したファイルは章のZIPとアセットのZIPのch13/に入っています)
  • CMakeLists.txt:2つ目の実行ファイルgltf_dump
  • src/main.cc:ウィンドウのタイトルと先頭のコメント
  • README.md:gltf_dumpの実行方法

main.ccの変更はタイトルだけです:

  if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 13")) return 1;

GLBファイルはバイナリなので、file_utilにはreadTextFile()の兄弟として、生のバイト列を返す関数が増えます:

// ファイル全体をバイト列として読む(GLBや画像用)。開けなければstd::nullopt。
// Reads a whole file as bytes (for GLB files and images). std::nullopt if it cannot be opened.
std::optional<std::vector<std::uint8_t>> readBinaryFile(const std::string &path);

std::optional<std::vector<std::uint8_t>> readBinaryFile(const std::string &path) {
  std::ifstream file(path, std::ios::binary);
  if (!file) return std::nullopt;
  return std::vector<std::uint8_t>(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
}

std::ios::binaryはWindowsで重要です。
テキストモードでは、C++のライブラリが0x0D 0x0Aのバイトの組を全て0x0A 1つに変えてしまいます。
バイナリファイルでは其のバイトが何処にでも現れ得ます。

2つ目の実行ファイル

gltf_dumpはウィンドウを開かないので、GLFWもGLADも要りません。
CMakeLists.txtで独自のターゲットを持ち、警告フラグはループで両方のターゲットに設定する様になります:

# 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)
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()

何時も通りにビルドし、プロジェクトのルートから実行します。
LinuxとFreeBSDでは:

./build/gltf_dump assets/models/crate.glb
./build/gltf_dump --all assets/models/crate.glb assets/models/diorama.glb

WindowsのVisual Studioでは、実行ファイルはbuild\Debug\(又はbuild\Release\)に出来ます:

build\Debug\gltf_dump.exe assets\models\diorama.glb

Visual Studioではgltf_dumpをスタートアッププロジェクトにして、プロパティの「デバッグ」→「コマンド引数」に引数を設定する事も出来ます。
全てのファイルを読み込めれば終了コードは0、そうでなければ1なので、スクリプトからも使えます。

13.2 何故glTFなのか

OBJは単純なテキスト形式ですが、ノードの階層が無く、マテリアルもごく基本的な物だけです。
FBXはAutodeskの所有で、仕様が公開されておらず、公式にはクローズドソースのSDKでしか読めません。
glTF 2.0(Khronos Group、2017年。ISO/IEC 12113として標準化もされています)はオープンで仕様が公開されており、配布の為に設計されました。
つまり、エンジンがモデルを読み込む直前の最後の段階の為の形式です。
Khronosは其れを「3DのJPEG」と呼んでいます。

glTFの鍵となる考え方は、バイナリデータが最初からGPUの欲しい形に並んでいる事です。
頂点の位置は32ビットのfloatで、glNamedBufferDataに渡すのと全く同じバイトの並びで保存されています。
インデックスは8・16・32ビットの符号なし整数で、glDrawElementsが受け付ける物其のものです。
JSONの部分はデータを説明するだけです。
どのバイトが位置か、幾つあるか、メッシュがどのマテリアルを使うか。
glTFファイルの読み込みの殆どは、JSONの説明を読んでバイト配列の切れ端をコピーする事です。

glTFのモデルには2つの形があります:

  • .gltf:JSONのテキストファイル。バイナリデータは別のファイル(model.bin、texture.png)にあって相対URIで参照されるか、data: URIにbase64で埋め込まれる。
  • .glb:1つのバイナリファイル。同じJSONの後に、同じファイルの中でバイナリデータが続く。殆どのツールが書き出す形で、あたし達のアセットも此の形。

Blenderは両方を書き出せます(ファイル→エクスポート→glTF 2.0)。
他の殆どの3Dツールも同様です。

13.3 glTFのオブジェクトモデル

glTFファイルは、トップレベルに幾つかの配列を持つJSONのオブジェクトです。
scenes、nodes、meshes、accessors、bufferViews、buffers、materials、textures、images、samplers等です。
此れらのオブジェクトが別の種類のオブジェクトを中に持つ事はありません。
小さなリレーショナルデータベースの様に、其れらの配列への番号(インデックス)で互いを参照します:

glTFのオブジェクトの関係図。sceneはnodeを、nodeは子とmeshを、meshはprimitiveを、primitiveはattributesとindicesでaccessorを、そしてmaterialを参照する。accessorはbufferViewを、bufferViewはbufferを参照する。materialはtextureを、textureはimageとsamplerを、imageはbufferViewを参照する

矢印のラベルは、番号を入れるJSONのキーです。
左の列がシーングラフ、下の行がジオメトリのデータ、オレンジの箱が見た目です。
点線の矢印は任意です。
画像はbufferViewに入っている(GLBファイルの場合)か、URIから読み込まれるかの何方かです。

一番単純なcrate.glbのJSONを見てみましょう。
ファイルでは1行で保存されています。
此処では改行を入れ、配列を図の順に並べ、マテリアルは後回しにしました:

{
  "asset": {"version": "2.0", "generator": "OpenGL tutorial (technicalsuwako)"},
  "scene": 0,
  "scenes": [{"name": "Scene", "nodes": [0]}],
  "nodes": [{"name": "Crate", "mesh": 0}],
  "meshes": [{
    "name": "Crate",
    "primitives": [{
      "attributes": {"POSITION": 0, "NORMAL": 1, "TEXCOORD_0": 2, "TANGENT": 3},
      "indices": 4, "material": 0, "mode": 4
    }]
  }],
  "accessors": [
    {"bufferView": 2, "componentType": 5126, "count": 24, "type": "VEC3",
     "min": [-0.5, 0.0, -0.5], "max": [0.5, 1.0, 0.5]},
    {"bufferView": 3, "componentType": 5126, "count": 24, "type": "VEC3"},
    {"bufferView": 4, "componentType": 5126, "count": 24, "type": "VEC2"},
    {"bufferView": 5, "componentType": 5126, "count": 24, "type": "VEC4"},
    {"bufferView": 6, "componentType": 5121, "count": 36, "type": "SCALAR"}
  ],
  "bufferViews": [
    {"buffer": 0, "byteOffset": 0, "byteLength": 71253},
    {"buffer": 0, "byteOffset": 71256, "byteLength": 450},
    {"buffer": 0, "byteOffset": 71708, "byteLength": 288, "target": 34962},
    {"buffer": 0, "byteOffset": 71996, "byteLength": 288, "target": 34962},
    {"buffer": 0, "byteOffset": 72284, "byteLength": 192, "target": 34962},
    {"buffer": 0, "byteOffset": 72476, "byteLength": 384, "target": 34962},
    {"buffer": 0, "byteOffset": 72860, "byteLength": 36, "target": 34963}
  ],
  "buffers": [{"byteLength": 72896}]
}

上から矢印を辿って行きましょう。

asset

トップレベルで必須のプロパティはasset.versionだけです。
値は"2.0"(又は其れ以降の2.x)でなければなりません。
glTF 1.0のファイルは見た目が似ていますが別の形式で、あたし達のローダーは分かり易いメッセージで拒否します。
generatorはファイルを書いたプログラムの名前で、エクスポーターのバグを追う時に役立ちます。

シーンとノード

scenesはシーンの一覧で、各シーンはルートノードの一覧を持ちます。
sceneは既定で表示するシーンです。
殆どのファイルはシーンを丁度1つ持っています。

ノードはシーングラフの1つの要素です。
名前、mesh(meshesへの番号)、children(nodesへの番号)、そして親から見たローカル変換を持てます。
変換の保存方法は2通りです:

  • translation(数3つ)、rotation(単位クォータニオン、数4つ)、scale(数3つ)。何れも省略可能。ローカル行列は𝐓𝐑𝐒で、第7章と全く同じ順番(先に拡大縮小、次に回転、最後に平行移動)。
  • matrix:16個の数で列優先。linalg.hhのMat4と同じメモリの並び(線型代数シリーズの第6章)。平行移動は12、13、14番目の要素。

何方も無いノードの変換は単位行列です。
回転は線型代数シリーズの第13章のクォータニオンですが、1つ罠があります。
glTFはx, y, z, wの順、つまり実部を最後に保存しますが、あたし達のQuat構造体は{w, x, y, z}です。
4つの数をファイルの順番の儘コピーすると、全く違う回転になります。

ノードのワールド変換は、親のワールド変換に自分のローカル変換を掛けた物で、其れをルートまで繰り返します。
glTFが保存していない物に注意して下さい。
ノードは自分の子を知っていますが、親は知りません。
又、nodes配列の順番には意味がありません。
diorama.glbでは羽根が最初に来て、ルートが最後に来ます。
ノードの親は1つまでで、階層に輪があってはいけません。
両方とも検査します。

メッシュとプリミティブ

メッシュはプリミティブの一覧です。
プリミティブは1回の描画呼び出しで描く物です:

  • attributes:属性の名前からアクセサーの番号への対応を表すオブジェクト。標準の名前はPOSITION(VEC3)、NORMAL(VEC3)、TANGENT(VEC4、wは向き、第22章)、TEXCOORD_0、TEXCOORD_1…(VEC2)、COLOR_0、スキニング用のJOINTS_0/WEIGHTS_0。
  • indices:インデックスバッファのアクセサー。無ければ其のプリミティブはglDrawArraysで描く。
  • material:materialsへの番号。無ければglTFの既定のマテリアル(白、metallic 1、roughness 1)。第14章では代わりに灰色のプラスチックを使う。
  • mode:プリミティブの種類。GLの定数と同じ番号で、0 = GL_POINTS … 4 = GL_TRIANGLES(既定) … 6 = GL_TRIANGLE_FAN。

何故1つのメッシュに複数のプリミティブがあるのでしょうか?
1回の描画呼び出しはマテリアルを1つしか持てないからです。
ジオラマの風車の塔は、白い漆喰の壁と赤い瓦屋根の2つのプリミティブを持つ1つのメッシュです。
又、複数のノードが同じメッシュを使う事も出来ます。
ジオラマには木箱が4つと風車の羽根が4枚ありますが、各メッシュは1回しか保存されていません。

13.4 アクセサー・bufferView・バッファ

此処がglTFの心臓部で、一番間違え易い所なので、ゆっくり進みましょう。
バイナリデータは3つの段階で記述されます:

  • バッファ(buffer)は生のバイトの塊。byteLengthと、uri(.gltfファイルの場合)を持つか、何も持たない(GLBファイルの最初のバッファはBINチャンク)。
  • bufferViewはバッファの切れ端。buffer、byteOffset(バッファの先頭から)、byteLength、そして任意でbyteStrideとtarget。
  • アクセサー(accessor)はbufferViewの中の型付きの配列。bufferView、byteOffset(bufferViewの先頭から)、componentType、normalized、count、type、min/max。

bufferViewはOpenGLのバッファ1つとしてアップロードする物、アクセサーはglVertexArrayAttribFormatで記述する物に当たります。
targetはヒントに過ぎません。
34962はGL_ARRAY_BUFFER(頂点データ)、34963はGL_ELEMENT_ARRAY_BUFFER(インデックス)です。

componentTypeとtype

アクセサーの1つの要素はtype個の成分から成り、各成分の型がcomponentTypeです。
componentTypeの番号はOpenGLのenumの値です。
此れは偶然ではなく、glTFは元々OpenGLの為に設計されました:

componentType GLの定数 バイト数 C++の型
5120 GL_BYTE 1 int8_t
5121 GL_UNSIGNED_BYTE 1 uint8_t
5122 GL_SHORT 2 int16_t
5123 GL_UNSIGNED_SHORT 2 uint16_t
5125 GL_UNSIGNED_INT 4 uint32_t
5126 GL_FLOAT 4 float

(5124のGL_INTはglTFでは使えません。)
typeは1つの要素が幾つの成分から成るかを表します:

type 成分の数 主な用途
SCALAR 1 インデックス
VEC2 2 テクスチャ座標
VEC3 3 位置、法線
VEC4 4 接線、色、クォータニオン
MAT2 4 殆ど使われない
MAT3 9 殆ど使われない
MAT4 16 逆バインド行列(スキニング)

従って木箱のアクセサー0(VEC3、5126、count 24)は、floatが3つの頂点が24個です。
24 × 12 = 288バイトで、bufferView 2のbyteLengthと丁度同じです。
アクセサー4(SCALAR、5121、count 36)は1バイトのインデックスが36個、つまり三角形が12個(箱の各面に2つ)です。
木箱の頂点は24個しか無いので、1バイトで足ります。
OpenGLはGL_UNSIGNED_BYTEのインデックスを描けますが、全てのGPUがハードウェアで対応している訳ではありません(Direct3Dには8ビットのインデックスが全く無く、Vulkanでも拡張で後から加わり、Vulkan 1.4でやっとコアになりました)。
其の場合はドライバーが裏で変換する事になります。
第14章で全てのインデックスを32ビットに変換する理由の1つは其れです。

minとmaxは各成分の最小値と最大値です。
POSITIONでは必須なので、バウンディングボックスがただで手に入ります。
木箱は(−0.5,0,−0.5)から(0.5,1,0.5)まで、原点が床にある1 mの箱です。

byteOffsetとbyteStride

木箱の様に頂点属性が別々のbufferViewに順に保存されている場合、各要素は前の要素の直後に続きます。
でも頂点はインターリーブする事も出来ます(第4章)。
頂点0の全ての属性、次に頂点1の全ての属性、と言う並びです。
其の場合、複数のアクセサーが1つのbufferViewを共有し、其々が自分のbyteOffsetを持ちます。
そしてbufferViewのbyteStrideが、1つの頂点から次の頂点まで何バイト跳ぶかを表します。
diorama.glbの風車の塔は此の形で保存されています:

ジオラマのバッファ0とbufferView 13の位置。拡大図では48バイトの頂点が2つインターリーブされ、POSITIONが0バイト目、NORMALが12、TEXCOORD 0が24、TANGENTが32にある。アクセサー10〜13が其処を指す。頂点1のNORMALは97616 + 12 + 1 × 48 = 97676から始まる

アクセサーの要素iは、バッファの次のバイトから始まります:

start(i)=bufferView.byteOffset+accessor.byteOffset+i⋅stride

ストライドは、bufferViewにbyteStrideがあれば其の値、無ければ要素1つの大きさです。
byteStrideが無いのは「詰まって並んでいる」と言う意味で、「ストライド0」ではありません。
オフセットは足し算です。
アクセサーのbyteOffsetはbufferViewからの相対値で、bufferViewのbyteOffsetはバッファからの相対値です。
何方か片方を忘れるのが、glTFで一番良くあるバグです。

ファイルの数字で計算してみましょう。
bufferView 13はbyteOffset 97616、byteLength 1920、byteStride 48です。
NORMALのアクセサー(アクセサー11)はbyteOffset 12、count 40です。
頂点1の法線の開始位置は:

97616+12+1⋅48=97676

頂点2の法線は97616+12+2⋅48=97724からです。
最後の要素は収まっているでしょうか?
TANGENTのアクセサー(オフセット32、要素1つが16バイト)の最後の要素は、bufferViewの先頭から32+39⋅48+16=1920バイト目で終わります。
丁度byteLengthと同じです。
「最後の要素の終わりがbufferViewの中にある」と言う此の検査を、あたし達のローダーは1バイトも読む前に全てのアクセサーで行います。

ストライドの規則:4〜252の4の倍数でなければならず、頂点データにだけ使え、インデックスには使えません。
byteOffsetは成分の大きさの倍数でなければならないので、floatは必ずバッファの中で4バイト境界から始まります。

normalized

整数のアクセサーは正規化(normalized)出来ます。
其の場合、整数は0〜1(符号なし)又は−1〜1(符号付き)の範囲に写されます。
glVertexArrayAttribFormatのGL_TRUEと同じ規則です。
nビットの成分と、保存されている整数cについて:

f=c2n−1(符号なし),f=max(c2n−1−1,−1)(符号付き)

UNSIGNED_BYTEでは、255は255/255=1に、128は128/255≈0.502になります。
符号付きのBYTEでは、127が1に、−127が−1になります。
−128は−128/127≈−1.008になってしまうので、maxで−1に抑えます。
normalizedが無ければ、整数は其の儘使われます(UNSIGNED_BYTEの200は200.0)。

誰が此れを使うのでしょうか?
色は正規化されたUNSIGNED_BYTEで保存される事が多く、拡張のKHR_mesh_quantizationではファイルを小さくする為に位置・法線・UVをSHORTやBYTEで保存出来ます。
あたし達のリーダーは全ての組み合わせを扱えるので、其の様なファイルも其の儘動きます。

疎なアクセサー

疎な(sparse)アクセサーは、普通のデータ(bufferViewが無ければ全部0)から始めて、幾つかの要素だけを置き換えます。
sparse.count、置き換える要素の番号が入ったindicesのbufferView、新しい値が入ったvaluesのbufferViewを持ちます。
エクスポーターが此れを使うのは主にモーフターゲットで、一部の頂点だけが動く場合です。
静的なモデルでは珍しいのですが、コアの仕様の一部で、コードも数行なので対応します。

13.5 マテリアル・テクスチャ・画像・サンプラー

次はオブジェクトの関係図のオレンジの半分です。
先程後回しにしたcrate.glbのマテリアル:

"materials": [{
  "name": "Crate",
  "pbrMetallicRoughness": {
    "baseColorFactor": [1.0, 1.0, 1.0, 1.0],
    "metallicFactor": 1.0,
    "roughnessFactor": 1.0,
    "baseColorTexture": {"index": 0},
    "metallicRoughnessTexture": {"index": 1}
  },
  "extras": {"note": "\u6728\u7bb1 / wooden crate"}
}],
"textures": [{"source": 0}, {"source": 1}],
"images": [
  {"bufferView": 0, "mimeType": "image/png", "name": "crate_basecolor"},
  {"bufferView": 1, "mimeType": "image/png", "name": "crate_metallic_roughness"}
]

マテリアル

glTFのマテリアルは金属・粗さ(metallic-roughness)モデルの物理ベース(PBR)です。
此のモデルは第24章でちゃんと実装します。
其れまでは、第14章で此れをあたし達のBlinn-Phongのマテリアルに変換します。
プロパティと、省略された時の既定値:

プロパティ 既定値 意味
baseColorFactor (1, 1, 1, 1) 表面の色(RGBA)。baseColorTextureと掛け合わせる
metallicFactor 1 0 = 誘電体(プラスチック、木、石)、1 = 金属
roughnessFactor 1 0 = 鏡の様に滑らか、1 = 完全に粗い
metallicRoughnessTexture 無し Gチャンネル = 粗さ、Bチャンネル = 金属度。係数と掛け合わせる
normalTexture 無し 接空間の法線マップ(第22章)、scale付き
occlusionTexture 無し Rチャンネルのアンビエントオクルージョン、strength付き
emissiveTexture、emissiveFactor 無し、(0, 0, 0) 表面が自分で出す光
alphaMode、alphaCutoff OPAQUE、0.5 OPAQUE、MASK(閾値未満を切り抜く)又はBLEND(第16章)
doubleSided false 裏面も描く(カリングしない)

驚く人が多い点が2つあります。
metallicFactorの既定値は1です。
つまり、此のプロパティの無いマテリアルは金属です。
又、係数はテクスチャと掛け合わされるので、テクスチャがある時は係数は普通1です。
あたし達の木箱が正にそうです(Blenderもテクスチャを繋ぐと此う書き出します)。

KHR_materials_emissive_strengthは発光色に掛ける小さな拡張です。
emissiveFactorは1を超えられないからです。
ジオラマのランタンのガラスが強さ2で使っています。

テクスチャ・画像・サンプラー

テクスチャはただの組です。
source(画像)とsamplerです。
画像はmimeType(image/png又はimage/jpeg)付きのbufferViewか、uriの何方かです。
GLBファイルではPNGファイルがバイト単位で其の儘bufferViewに入っているので、デコードする必要があります。
第14章で其のバイト列をstbi_load_from_memoryに渡します。

サンプラーはフィルタリングとラップモードを持ち、此方もGLのenumの値を使います:

値 定数
9728、9729 GL_NEAREST、GL_LINEAR
9984 … 9987 GL_NEAREST_MIPMAP_NEAREST … GL_LINEAR_MIPMAP_LINEAR(minFilterのみ)
33071 GL_CLAMP_TO_EDGE
33648 GL_MIRRORED_REPEAT
10497 GL_REPEAT(既定のラップモード)

サンプラーの無いテクスチャはREPEATを使い、フィルタリングはアプリケーションに任されます。
フィルターだけ省略する事も出来、GltfSamplerの「0 = 書かれていない」は其の為です。

マテリアルは{"index": 0, "texCoord": 0}の様な小さなオブジェクトでテクスチャを指します。
texCoordはどのUVの組を使うかを選びます。
0はTEXCOORD_0です。

第14章の前に知っておくべき決まりがもう1つあります。
glTFのUVの原点は画像の左上です。
第6章では読み込み時に全ての画像を反転しました。
OpenGLは最初にアップロードした行をv=0にするので、v=0を絵の下にしたかったからです。
glTFのUVは上から始まる画像を前提に作られているので、デコードした行を其の儘(最初の行をv=0に)アップロードすれば全て合います。
glTFのテクスチャは決して反転しないで下さい。

拡張

glTFは拡張出来ます。
extensionsUsedはファイルが使う拡張の一覧で、extensionsRequiredは正しく表示する為に理解しなければならない拡張の一覧です。
extensionsRequiredに知らない拡張があれば、ローダーはファイルを拒否しなければなりません(例えばDracoやmeshoptの圧縮では、デコーダー無しではbufferViewが読めません)。
extensionsUsedの知らない拡張は、追加の情報(ライト、テクスチャの変換、クリアコート等)が失われるだけです。
あたし達のローダーは必須の拡張としてKHR_mesh_quantizationとKHR_materials_emissive_strengthを受け付け、其れ以外は全て拒否します。
スキン、アニメーション、モーフターゲット、カメラは数えるだけで読み飛ばします。

13.6 GLBコンテナ

GLBファイルはJSONとバイナリのバッファを1つのファイルにまとめた物です。
構造は短いので、全部を示せます:

crate.glbのGLBの構造。magicがglTF、versionが2、lengthが74512の12バイトのヘッダー。chunkLengthが1588、chunkTypeがJSONで、空白で埋められたJSONテキストを持つチャンク0。chunkLengthが72896、chunkTypeがBINで、0で埋められたバイナリのバッファを持つチャンク1

  • ヘッダー:32ビットの符号なし整数が3つ。magicは4バイトのglTF、versionは2、lengthはファイル全体の大きさ。
  • 其の後にチャンクが続く。各チャンクは32ビット整数2つのヘッダー、chunkLength(此の8バイトのヘッダーを除いたデータの大きさ)とchunkTypeを持ち、其の後にデータが続く。
  • 最初のチャンクはJSONでなければならない(種類は0x4E4F534A、バイトではJSON)。データは空白で4バイトの倍数まで埋められる。
  • 2つ目のチャンクがあれば、其れはBIN(種類は0x004E4942、バイトではBINと0)。データは0で埋められる。此れがbuffers[0]、つまりuriの無いバッファになる。
  • 知らない種類のチャンクは読み飛ばさなければならない。其の為、将来の版がチャンクを追加しても古いリーダーは壊れない。

数は全てリトルエンディアンです。
つまり、一番下の桁のバイトが最初に来ます。
x86とARMのバイト順なので、あたし達が対象とする全てのプラットフォームで、バイトを其の儘uint32_tにコピー出来ます。
crate.glbの最初の32バイトです(od -A d -t x1z -N 32。Windowsでは何かの16進エディタで同じ物が見られます):

0000000 67 6c 54 46 02 00 00 00 10 23 01 00 34 06 00 00  >glTF.....#..4...<
0000016 4a 53 4f 4e 7b 22 61 73 73 65 74 22 3a 7b 22 76  >JSON{"asset":{"v<

リトルエンディアンの32ビットの数として読むと:

  • 0〜3バイト目、67 6c 54 46:文字のg l T F。数としては0x46546C67で、コードが比べる定数は此れ。
  • 4〜7バイト目、02 00 00 00:バージョン2。
  • 8〜11バイト目、10 23 01 00:0x00012310 = 1⋅65536+0x23⋅256+0x10=65536+8960+16=74512バイト、ファイルの大きさ。
  • 12〜15バイト目、34 06 00 00:0x634 = 6⋅256+0x34=1536+52=1588バイトのJSON。
  • 16〜19バイト目、4a 53 4f 4e:JSON。
  • 20バイト目から:{"asset":{"v…、JSONのテキスト。

BINチャンクのヘッダーは20+1588=1608から、データは1616から始まります。
72896バイトのデータで、ファイルは1616+72896=74512で終わり、ヘッダーと一致します。

何故全てが4の倍数なのか

チャンクが4の倍数から始まるのは、中のデータの境界を揃える為です。
floatは4の倍数のバイトオフセットから始まらなければなりません。
ヘッダーは12バイト、チャンクのヘッダーは8バイトで、全てのチャンクは埋められているので、BINのデータは必ずファイルの中で4の倍数から始まります。
従って、バッファの中で4の倍数のbufferViewのオフセットは、ファイルの中でも4の倍数です。
木箱のバッファの中でも同じ規則が見られます。
ベースカラーのPNG(bufferView 0)は71253バイトですが、次のbufferViewは3バイトの埋め草の後の71256から始まります。

埋め草には、ローダーにとって1つの結果があります。
BINチャンクはbuffers[0].byteLengthより最大3バイト長くなり得ます。
其れは正しいファイルで、エラーになるのは短い場合だけです。
JSONチャンクの最後には最大3つの空白がありますが、JSONパーサーは何れにしても読み飛ばします。
空白ではなく0のバイトでJSONを埋めるエクスポーターもあります。
仕様違反ですが、あたし達は最後の0を切り落として許容します。

注意: あたし達のコードはリトルエンディアンのCPUを前提にしています(x86-64とARM64のWindows、Linux、FreeBSDは全てそうです)。ビッグエンディアンのマシンでは、ファイルの複数バイトの値を全てバイトスワップする必要があります。読む時はmemcpyを使うので、境界の揃っていないデータは、揃っていないワードを読めないCPUでも問題になりません。

13.7 小さなJSONパーサー

glTFを読む前に、JSONが必要です。
優れたライブラリ(nlohmann/json、RapidJSON、simdjson)がありますが、glTFファイルにはJSONの読み込みの部分しか要らず、コードは短く、パーサーを自分で書くのは全てのプログラマーが一度はやるべき練習です。
C++でJSONライブラリをゼロから作る話はブログの記事に書きました。
此処の版は其れより小さく、読み込み専用で、glTFのローダーの使い方に合わせて設計してあります。

JSONの値は6種類です。
null、true/false、数、文字列、配列[…]、オブジェクト{"key": value, …}。
其れだけです。
コメントも、最後のカンマも、シングルクォートも無く、数は全て10進数の浮動小数点数です。

Jsonクラス

ヘッダーの全体です:

// 小さなJSONパーサー(glTFを読むため) / a small JSON parser (for reading glTF)
#pragma once

#include <cstddef>
#include <optional>
#include <string>
#include <string_view>
#include <vector>

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<Json> 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<float>(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<Json> &items() const { return array; }          // 配列の要素 / array elements
  const std::vector<JsonMember> &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<Json> array;
  std::vector<JsonMember> object; // 不完全型のvectorはC++17から使える / a vector of an incomplete type is fine since C++17
};

struct JsonMember {
  std::string key;
  Json value;
};

Jsonは1つの値です。
unionやstd::variantではなく、種類毎にフィールドを単純に持っていて、kindに合う物だけを使います。
値毎に数バイト無駄になりますが、コードが分かり易くなり、glTFのJSONの値は多くても数千個です。

オブジェクトはstd::mapではなく、ファイルの順のstd::vector<JsonMember>です。
glTFのオブジェクトのキーは数個なので、5つの文字列を順番に探す方が木より速く、表示の為にファイルの順も残り、ハッシュも要りません。
JsonMemberはJsonを持ち、JsonはJsonMemberのvectorを持つので、何方かを片方が不完全な内に宣言しなければなりません。
C++17からは、使う前に完全になっていれば、std::vectorの要素に不完全型を使う事が正式に認められています。
先頭のstruct JsonMember;だけで足りるのは其の為です。

失敗しない取り出し

一番大事な設計上の判断は、値の読み方にあります。
glTFのローダーはroot["accessors"][3]["sparse"]["indices"]["bufferView"]の様な物を読み、殆どのプロパティは省略可能です。
各段階が失敗し得るなら、ローダーはifの森になってしまいます。
其処で、全ての取り出しが有効な参照を返し、「無い」はnullの値で表します:

// 見つからないときに返す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<long long>(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;
}

数に["key"]を聞いても、オブジェクトに[5]を聞いても、無いキーを聞いても、全て同じ静的なkNullJsonが返ります。
nullは数ではないのでnumber(fallback)はfallbackを返し、配列でもないのでsize()は0、items()は空です。
fallbackは正にglTFの既定値の考え方と同じです。
glTFのローダーはマテリアルの金属度をpbr["metallicFactor"].numberf(1.0f)で読みます。
キーが無くても、pbrMetallicRoughnessのオブジェクト自体が無くても、結果はglTFの既定値の1です。

返される参照は木の中(又は共有のconstのnull)を指すので、ルートのJsonが生きている限り有効です。

integer()はもう少し詳しく見ておきましょう。
glTFの番号やバイト数は整数ですが、JSONには数の型が1つしか無く、あたし達は其れをdoubleで保存します。
doubleの仮数部は53ビットなので、253=9007199254740992までの全ての整数を正確に表せますが、其れを超えると表せない整数が出て来ます。
integer()は、其の範囲の整数でない物(2.5、1e300、"3"、null等)にはfallback(既定では−1)を返します。
glTFの番号は全て0以上なので、−1は常に「無い又は不正」を意味し、ローダーは其れをエラーメッセージにします。

再帰下降

パーサーは古典的な再帰下降パーサーです。
値の種類毎に関数が1つあり、配列やオブジェクトの中の値の為に再びparseValueを呼びます。
再帰がJSONの入れ子の形を其の儘なぞります。
パーサーは独自のクラスJsonParserにあり、privateのフィールドを埋められる様にJsonのfriendになっています。
状態はテキスト、位置、最初のエラーだけです:

  std::string_view s;
  size_t pos = 0;
  int depth = 0;
  std::string error;
  size_t errorPos = 0;

補助関数はとても小さいです:

  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;
  }

failは最初のエラーと其の位置だけを記録し、常にfalseを返すので、全ての関数でreturn fail("…")と書けます。
peek()はテキストの終わりで'\0'を返します。
此れはパーサーが探すどの文字とも一致しないので、殆どの関数で終わりの検査を別に書く必要がありません。
深さの制限は大事です。
入れ子の[1つ毎にスタックフレームが1つ増えるので、[が100万個ある悪意のあるファイルは、制限が無ければスタックオーバーフローでプログラムを落とします。
512段はどんなglTFにも十分過ぎます(実際のファイルの入れ子は6段程度です)。

文書全体は、前後に省略可能な空白がある1つの値です:

  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;
  }

parseValueは1文字だけを見て、次に何が来るかを決めます。
JSONでは値の種類毎に最初の文字が違うので、其れが出来ます:

  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");
    }
  }

オブジェクトは{の後に、}か、カンマで区切られた"key": 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 '}'");
    }
  }

parseArrayは[と]でキーの無い同じループです。
ループが何を拒否するかに注目して下さい。
値の後には,か閉じ括弧が無ければならず、,の後には次のキーが無ければなりません。
従って{"a": 1,}(最後のカンマ)は「キー(文字列)が必要」で失敗します。
重複したキーはvectorに残り、findは最初に一致した物を返すので、最初のキーが勝ちます。

エラーはエラーの位置から数えた行と列を報告します:

  // 「行:列: 理由」 / "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;
  }

壊れたファイルではmodel.gltf: JSON 12:5: 「,」か「}」が必要 / expected ',' or '}'の様なメッセージが出るので、エディタで其の場所を直ぐに見つけられます。

文字列・エスケープ・サロゲートペア

JSONの文字列は二重引用符で囲まれたUTF-8のテキストです。
殆どのバイトは其の儘コピーされ、バックスラッシュはエスケープの始まりです:

  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<unsigned char>(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");
      }
    }
  }

単純なエスケープ(\"、\\、\/、\b、\f、\n、\r、\t)は其々1文字になります。
生の制御文字(本物の改行の様な0x20未満のバイト)は文字列の中では使えず、エスケープしなければなりません。

面白いのは\uXXXXです。
4桁の16進数がUnicodeのコードポイントを表し、其れをUTF-8でstd::stringに書かなければなりません。
あたし達の木箱のファイルが此れを使っています。
マテリアルの注記"\u6728\u7bb1 / wooden crate"は、木箱です。
hex4が4桁を読み、appendUtf8がコードポイントを符号化します:

  // コードポイントをUTF-8で書く / write a code point as UTF-8
  static void appendUtf8(std::string &out, unsigned cp) {
    if (cp < 0x80) {
      out += static_cast<char>(cp);
    } else if (cp < 0x800) {
      out += static_cast<char>(0xC0 | (cp >> 6));
      out += static_cast<char>(0x80 | (cp & 0x3F));
    } else if (cp < 0x10000) {
      out += static_cast<char>(0xE0 | (cp >> 12));
      out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
      out += static_cast<char>(0x80 | (cp & 0x3F));
    } else {
      out += static_cast<char>(0xF0 | (cp >> 18));
      out += static_cast<char>(0x80 | ((cp >> 12) & 0x3F));
      out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
      out += static_cast<char>(0x80 | (cp & 0x3F));
    }
  }

UTF-8はコードポイントの大きさに応じて1〜4バイトを使います。
「木」はU+6728(0x800〜0xFFFFの間)なので、3バイト必要です:

  • 1バイト目:0xE0 | (0x6728 >> 12) = 0xE0 | 0x6 = 0xE6
  • 2バイト目:0x80 | ((0x6728 >> 6) & 0x3F) = 0x80 | 0x1C = 0x9C
  • 3バイト目:0x80 | (0x6728 & 0x3F) = 0x80 | 0x28 = 0xA8

E6 9C A8は確かにUTF-8の「木」です。

4桁の16進数ではU+FFFFまでしか届きません。
絵文字の様に其れより上の文字はサロゲートペア、つまり2つ続いた\uのエスケープで書かれます。
0xD800〜0xDBFFの上位サロゲートと、0xDC00〜0xDFFFの下位サロゲートです(此れはUTF-16から来ていて、JSONのエスケープは其処から来ています)。
半分ずつが10ビットを運びます:

cp=0x10000+(high−0xD800)⋅1024+(low−0xDC00)

コードでは1024の掛け算を<< 10と書いています。
\uD83D\uDE00と書かれる😀では、0x10000+0x3D⋅1024+0x200=0x10000+0xF400+0x200=0x1F600で、appendUtf8が其れを4バイトのF0 9F 98 80に符号化します。
下位の無い上位サロゲートや、単独の下位サロゲートはエラーです。
其れでもUTF-8に書くと、不正なテキストが出来てしまいます。

ノードやマテリアルの名前はどんな言語でもあり得るので、此れは机上の話ではありません。
UTF-8を其の儘書くエクスポーターもあれば、ASCIIより上を全てエスケープするエクスポーターもあり、ローダーは両方に対応しなければなりません。

数

JSONの数の文法は、Cのstrtodが受け付ける物より厳しいです:

number   = [ "-" ] integer [ fraction ] [ exponent ]
integer  = "0" | digit1-9 { digit }
fraction = "." digit { digit }
exponent = ( "e" | "E" ) [ "+" | "-" ] digit { digit }

strtodは+1、.5、1.、0x1A、inf、nan、007の様な先頭の0も受け付けますが、何れもJSONとしては不正です。
其処で、先ず文法に従って文字を辿り、見つけた部分だけをstrtodに変換させます:

  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;
  }

先頭の0の後に数字は続けられないので、007は最初の0で止まり、呼び出し側が続く0で失敗します。
1e999の様にdoubleには大き過ぎる数は無限大になりますが、後でinteger()が拒否するので無害です。

strtodには1つ罠があります。
Cロケールの小数点を使うのです。
プログラムは「C」ロケールで始まり、其処での小数点は.です。
でもプログラムがユーザーの言語設定を使う為にsetlocale(LC_ALL, "")を呼ぶと、ドイツ語やフランス語のシステムでは小数点が,になり、strtod("0.5")は点で止まって0を返します。
突然全てのマテリアルが黒くなり、しかも一部のコンピューターでだけです。
あたし達はsetlocaleを呼ばないので安全です。
呼ぶプログラムで此のパーサーを使うなら、代わりに<charconv>のstd::from_charsで変換して下さい。
其れはロケールを一切見ません(但し、浮動小数点版が標準ライブラリにあるか確かめて下さい。対応が遅かったライブラリもあります)。

最後に、公開の入口がパーサーを作り、木かstd::nulloptを返します:

std::optional<Json> 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;
}

パーサーは此れで全部で、コメント込みで約300行です。
例外も、木其のもの以外のメモリ確保も無く、壊れた入力には必ず位置付きのエラーメッセージが1つ出ます。

13.8 JSONから構造体へ

src/gltf.hhは、glTFのオブジェクトを其の儘写した普通の構造体を、同じ名前とglTFの既定値で宣言します。
リーダーはGLのヘッダーを一切インクルードしません。
ファイルをデータにするだけで、其れ以外は何もしません。
其の為、ツール(gltf_dump等)、テスト、そして後で第25章のエンジンのライブラリからも使えます。
GLを使わないので、GLと同じ値の定数を自分で定義します:

// 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;

構造体

データの部分は13.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<double> 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<GltfAttribute> 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
};

番号は全てintで−1が「無し」、大きさは全てsize_tです。
componentsは読み込み時にtypeから一度だけ計算するので、読み込みのコードは内側のループで文字列を比べません。

ノードは変換を両方の形で持ち、更にparentを持ちます。
此れはファイルにはありませんが、読み込み時に計算します:

// シーングラフのノード:変換と、メッシュ(任意)と、子ノード
// 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<int> 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;
};

localTransform()は1行です:

Mat4 GltfNode::localTransform() const {
  if (hasMatrix) return matrix;
  // 拡大縮小 → 回転 → 平行移動の順に効く / applied as scale, then rotation, then translation
  return translate(translation) * toMat4(rotation) * ::scale(scale);
}

scaleの前の::が必要なのは、GltfNodeのメンバー関数の中ではscaleと言う名前がメンバー変数を指し、linalg.hhの関数を隠してしまうからです。
第14章では此のローカル行列をルートから掛けて行き、各ノードのワールド行列を求めます。

マテリアル関係の構造体(GltfTextureRef、GltfMaterial、GltfTexture、GltfImage、GltfSampler、GltfScene)は、13.5節のフィールドを既定値付きで持っています。
ダウンロードのgltf.hhを見て下さい。
全てをまとめるのがGltfです:

// ファイル一つ分の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<std::string> extensionsUsed, extensionsRequired;

  std::vector<std::vector<std::uint8_t>> buffers; // 中身を読み込んだバッファ / the loaded buffer contents
  std::vector<GltfBufferView> bufferViews;
  std::vector<GltfAccessor> accessors;
  std::vector<GltfMesh> meshes;
  std::vector<GltfNode> nodes;
  std::vector<GltfMaterial> materials;
  std::vector<GltfTexture> textures;
  std::vector<GltfImage> images;
  std::vector<GltfSampler> samplers;
  std::vector<GltfScene> 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<Gltf> load(const std::string &path);

  // アクセサーを読み、count × components個のfloatにする(どのcomponentTypeでも、正規化も処理する)
  // Reads an accessor into count × components floats (any componentType, normalization handled)
  std::optional<std::vector<float>> readFloats(int accessor) const;
  // インデックスを読み、u8・u16・u32をすべてu32にする / reads indices; u8, u16 and u32 all become u32
  std::optional<std::vector<std::uint32_t>> readIndices(int accessor) const;
  // 画像ファイルのバイト列(PNG、JPEG…) / the bytes of an image file (PNG, JPEG, ...)
  std::optional<std::vector<std::uint8_t>> imageData(int image) const;

  // 描くべきルートノード:既定のシーン、なければ最初のシーン、シーンがなければ親のないノード全部
  // The root nodes to draw: the default scene, else the first one, else every node without a parent
  std::vector<int> rootNodes() const;
};

APIは小さいです。
loadはファイル全体か(理由を表示した上で)std::nulloptを返し、3つのread…関数はアクセサーや画像をvectorにします。
数はJSONの木ではdouble、此れらの構造体ではfloatで、何れにしてもGPUが受け取るのはfloatです。

ファイルを読み込む

Gltf::loadはファイル全体をメモリに読み込み、最初の4バイトを見ます。
其れがGLBのmagicならチャンクを辿り、そうでなければファイル全体がJSON(.gltf)です:

  // 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<const char *>(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<const char *>(bytes.data()), bytes.size());
  }

ファイルから来た長さは全て、使う前に検査します。
glbLengthは実際に読んだバイト数より大きくてはいけません(途中で切れたダウンロード)。
各チャンクは残りの中に収まらなければなりません。
比較のlength > g.glbLength - offsetは、負にならない引き算で書いています(ループの条件でoffset + 8 <= glbLengthが保証されています)。
offset + length > g.glbLengthと書くと、32ビットのビルドでは232近くの悪意のあるlengthで値が一周してしまう可能性があります。
此れは以下の全ての範囲検査で使うパターンです。

JSONチャンクはコピーしません。
jsonTextはファイルのバイト列を指すstd::string_viewです。
BINチャンクは最初のバッファになるのでbinにコピーします。

JSONのパースの後に3つの段階が続き、何れもメッセージ付きで失敗し得ます。
parseがJSONから構造体を埋め、parseBuffersがバッファの中身(BINチャンク、外部ファイル又はdata: URI)を読み込み、validateが全ての範囲を検査します。
何れも小さなLoader構造体に属していて、此れが埋めている途中のGltfと最初のエラーを持ちます。

先に大きさを決め、其れから埋める

番号の検査を簡単にする小技です。
parseはどのオブジェクトを読むよりも前に、JSONから全ての配列の大きさを決めます:

  // 番号の範囲を調べられるように、先に配列の大きさを決める / 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();

此れで、ファイルの中で配列がどんな順番で出て来ても、メッシュを読む時にはg.accessors.size()が、マテリアルを読む時にはg.textures.size()が分かっています。
全ての番号は、1つの補助関数で読んだ瞬間に範囲を検査されます:

  // 番号(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<size_t>(i) >= count)
      return fail(where + "." + key + ": 範囲外の番号 / index out of range");
    out = static_cast<int>(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<size_t>(i);
    return true;
  }

キーが無ければ既定値の儘で、あれば範囲内の正しい整数でなければなりません。
メッセージは問題の場所を正確に示します。
例えばaccessors[3].bufferView: 範囲外の番号 / index out of rangeです。

bufferViewの読み込みが此のパターンの例で、13.4節のストライドの規則も入っています:

  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<int>(j["target"].integer(0));
  }

そしてノードのクォータニオンの変換と、x, y, z, wの罠:

    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]};

ファイルには単位クォータニオンが入っている筈ですが、エクスポーターは数を丸めるので正規化します。
全部0のクォータニオンは正規化出来ず(0で割る事になります)、意味のある回転も無いので、単位クォータニオンにします。

バージョンと必須の拡張は、他の何よりも先に検査します:

  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());
  }

溢れない範囲検査

parseの後、全ての番号は存在するオブジェクトを指していますが、バイトの範囲はまだ検査されていません。
validateは、どの読み込みもバッファの終わりを決して超えない事を保証します:

// バッファの範囲を超えて読むことがないよう、全部の範囲を先に確かめる
// 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<size_t>(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<size_t>(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");
    }

(関数は此の後、疎なアクセサーの2つのbufferViewについて同じ検査を続けます。)

bufferViewはバッファの中に、アクセサーの最後の要素はbufferViewの中に収まらなければなりません。
アクセサーの検査の素直な書き方は、3つ目の条件だけ、a.byteOffset + stride * (a.count - 1) + elem > v.byteLengthでしょう。
危ないのは、countがファイルから来る事です。
size_tの計算は黙って一周します。
32ビットのビルド(其処ではsize_tは32ビット)で、count = 230+1、ストライド4のファイルだと、4⋅230=232が一周して0になります。
検査はとても小さな終わりの位置を見て通ってしまい、リーダーはバッファの終わりを遥かに超えて読み進みます。
64ビットのビルドでは整数の53ビットの制限のお陰で偶々此の和は範囲に収まりますが、偶然で安全なコードは安全ではありません。

対策は、溢れ得る値を決して計算しない事です。
先ずオフセットがbufferViewの中にあるかを確かめ、次に掛け算の代わりに割り算をします:

count−1≤⌊byteLength−byteOffsetstride⌋

大きい値から小さい値を引く引き算と割り算は溢れません。
此れが成り立てばstride⋅(count−1)は最大でもbyteLength−byteOffsetなので、3つ目の検査の和は最大でもbyteLength+elemで、此れも溢れません。
「先に引いてから比べる」と言う同じ考え方が、上のGLBのチャンクのループも含め、ローダーの全ての検査に通っています。

bufferViewの無いアクセサーもglTFでは正しく、「全部0」の意味です(大抵は其の上に疎な値が乗ります)。
其の為readAccessorはcount個の0の要素を確保します。
ファイルの中には其のcountを制限する物が何も無いので、"count": 4000000000000と書いただけの3行の.gltfで確保がstd::bad_allocを投げ、プログラムが終わってしまいます。
else ifは、其の様なアクセサーを0で64 MiBまでに制限します。
実際のモデルに必要な量よりずっと多いです。

validateの残りは、プリミティブの属性の数が揃っている事、インデックスのアクセサーが符号なしのSCALARである事、そして階層を検査します:

  // ノードの親は一つだけ、輪になってはいけない / 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<size_t>(child)];
      if (c.parent != -1 || static_cast<size_t>(child) == i)
        return fail("nodes[" + std::to_string(child) + "]: 親が二つある / has two parents (or is its own child)");
      c.parent = static_cast<int>(i);
    }
  }
  for (size_t i = 0; i < g.nodes.size(); ++i) {
    int n = static_cast<int>(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<size_t>(n)].parent;
    }
  }
  for (size_t i = 0; i < g.scenes.size(); ++i)
    for (int n : g.scenes[i].nodes)
      if (g.nodes[static_cast<size_t>(n)].parent != -1)
        return fail("scenes[" + std::to_string(i) + "]: ルートでないノード / a node that is not a root");
  return true;
}

最初のループは子の一覧からparentを埋め、或るノードが子として2回現れたら(親が2つ)、又は自分自身の子なら失敗します。
親が1つまでなら、輪はA → B → C → Aの様な形しかあり得ないので、2つ目のループは全てのノードから上に辿り、ノードの数より多く辿ったら失敗します。
最後に、シーンに並んだノードはルートでなければなりません。
此の後は、階層を辿るコード(ダンプの木の表示や第14章の描画)が無限ループの心配無しに再帰出来ます。

ファイルとdata: URIからのバッファ

.gltfファイルでは、parseBuffersが各バッファのuriを読み込みます。
data:application/octet-stream;base64,AAAA…の様なdata: URIは其の場でbase64から復号し、其れ以外は.gltfファイルからの相対のファイル名です。
URIはパーセントエンコードされています。
Blenderはmy model.binと言う名前のファイルをmy%20model.binと書くので、ファイルを開く前に%20を空白に戻します(gltf.ccのpercentDecode)。
://の付いたURI(ウェブのアドレス)は拒否します。
モデルのローダーが黙ってインターネットに出掛けるべきではありません。
各バッファは最低でもbyteLengthバイト必要で、余分なバイト(BINチャンクの埋め草)は切り落とします。

13.9 アクセサーを読む

全てを検査済みなので、アクセサーの読み込みは簡単で速いです。
先ず成分1つ:

// 成分一つを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;
  }
  }
}

13.4節の正規化の式を、型毎に書き出した物です。
ポインタをキャストする(*reinterpret_cast<const float *>(p))代わりにmemcpyで読みます。
本当はfloatのオブジェクトではないデータに対するキャストはC++では未定義動作で、境界の揃った読み込みが必要なCPUでは落ちるからです。
コンパイラは4バイトのmemcpyを1つのロード命令にするので、コストはありません。

次にアクセサー全体を、要素毎に:

// 要素を一つずつ、成分ごとにTへ変換して読む。疎なアクセサーも処理する
// Reads element by element, converting each component to T. Handles sparse accessors too
template <typename T>
static bool readAccessor(const Gltf &g, const GltfAccessor &a, std::vector<T> &out) {
  size_t n = static_cast<size_t>(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<size_t>(a.bufferView)];
    const std::uint8_t *base = g.buffers[static_cast<size_t>(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<T>(
            readComponent(base + e * stride + componentOffset(a, static_cast<int>(c)), a.componentType, a.normalized));
  }
  if (a.sparseCount > 0) {
    const GltfBufferView &iv = g.bufferViews[static_cast<size_t>(a.sparseIndicesView)];
    const GltfBufferView &vv = g.bufferViews[static_cast<size_t>(a.sparseValuesView)];
    const std::uint8_t *indices = g.buffers[static_cast<size_t>(iv.buffer)].data() + iv.byteOffset + a.sparseIndicesOffset;
    const std::uint8_t *values = g.buffers[static_cast<size_t>(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<size_t>(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<T>(
            readComponent(values + k * elem + componentOffset(a, static_cast<int>(c)), a.componentType, a.normalized));
    }
  }
  return true;
}

テンプレートなので、同じコードが頂点データにはfloatを、インデックスにはuint32_tを作ります。
成分のアドレスは正に13.4節の式です。
baseにはbufferViewとアクセサーのオフセットが既に入っていて、e * strideで要素に、componentOffsetで成分に進みます。
validateが最後の要素の終わりを検査したので、base + e * stride + componentOffset(...)は常にバッファの中です。

componentOffsetは、ベクトルならただのc * sizeです。
行列の型には仕様の規則がもう1つあります。
1バイトと2バイトの成分では、各列が4バイト境界から始まるのです。
BYTEのMAT3は9バイトではなく12バイトになります。
3バイトの各列が4バイトに埋められるからです。
gltf.ccのelementSizeとcomponentOffsetが其れを処理します。
珍しい場合ですが、間違えると黙ってゴミを読みます。

疎の部分は、置き換える番号を1つずつ読み、要素を1つ上書きします。
番号はvalidateでは検査しない(データを二度読む事になる)ので、此処で範囲を検査します。
範囲外の番号があれば、vectorの外に書く代わりに、読み込み全体を失敗させます。

公開の関数は薄い包みです:

std::optional<std::vector<float>> Gltf::readFloats(int accessor) const {
  if (accessor < 0 || static_cast<size_t>(accessor) >= accessors.size()) return std::nullopt;
  std::vector<float> out;
  if (!readAccessor(*this, accessors[static_cast<size_t>(accessor)], out)) return std::nullopt;
  return out;
}

std::optional<std::vector<std::uint32_t>> Gltf::readIndices(int accessor) const {
  if (accessor < 0 || static_cast<size_t>(accessor) >= accessors.size()) return std::nullopt;
  const GltfAccessor &a = accessors[static_cast<size_t>(accessor)];
  if (a.components != 1 || a.normalized || a.componentType == kGltfFloat || a.componentType == kGltfByte ||
      a.componentType == kGltfShort)
    return std::nullopt;
  std::vector<std::uint32_t> out;
  if (!readAccessor(*this, a, out)) return std::nullopt;
  return out;
}

readIndicesはインデックスになれないアクセサー(符号付き、float、正規化)を拒否し、全ての型をuint32_tに広げます。
其の為、第14章が扱うインデックスの型は1つだけです。
imageDataは埋め込み又は外部の画像ファイルのバイト列を返し、rootNodesは描くべきノードを返します。
既定のシーン、無ければ最初のシーン、其れも無ければ親の無い全てのノードです(シーンの無いファイルも正しいファイルです)。

13.10 gltf_dump

gltf_dump.ccは上のAPIを使ってファイルを表示します。
此れから作る全てのモデルを確かめる為のツールです。
殆どはprintfですが、2箇所は見ておく価値があります。
ノードの木はASCIIの枝で再帰的に表示します:

// ノードの木を「+-」と「|」で描く / 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<size_t>(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<size_t>(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);
}

prefixは、下に兄弟がある子では"| "だけ、最後の子では" "だけ伸びます。
其れで縦の線が正しい場所に描かれます。
回転は軸と角度で表示します(θ=2arccosw、軸は(x,y,z)/sin(θ/2)、線型代数シリーズの第13章)。
「25.0 deg about 0, 1, 0」なら読めますが、生のクォータニオンは読めないからです。

最後にverifyが、全ての属性とインデックスのバッファをreadFloatsとreadIndicesで読み、データをアクセサーのmin/maxと比べ、全てのインデックスが頂点の数より小さい事を確かめます:

        // ファイルのmin/maxと、実際に読んだ値を比べる / compare the file's min/max with the values actually read
        if (a.min.size() == static_cast<size_t>(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<double>(lo), static_cast<double>(hi));
              ++problems;
            }
          }
        }

インデックスと頂点の数の比較にはインデックスのデータ自体が必要なので、ローダーは其れを検査しません。
第14章のModelがアップロードの前に改めて検査します。
頂点バッファの終わりを超えるインデックスは、バッファの外のGPUのメモリを読み得るからです。

ジオラマ

diorama.glbは第14章で描くシーンです。
風車、ランプ、木箱、木、岩のある小さな風景です。
メッシュの部分には、インターリーブされたデータ(塔のstride 48)、全てのインデックスの型(UNSIGNED_BYTE、UNSIGNED_SHORT、UNSIGNED_INT)、POSITIONとNORMALだけのプリミティブ(ランタンのガラス)、そしてPOSITIONだけでインデックスも無いプリミティブ(岩)が見えます:

ジオラマにダンプツールを実行した出力の前半。JSONチャンク13144バイト、BINチャンク146444バイトのGLBのヘッダー、使っている拡張、8つのメッシュとプリミティブ、インデックスの型、属性。ストライド48でインターリーブされたTowerと、POSITIONだけでインデックスの無いRockもある

残りの部分にはマテリアル、テクスチャ、ノードの木が出ます:

ジオラマにダンプツールを実行した出力の後半。ベースカラー・金属度・粗さ・テクスチャを持つ11のマテリアル、サンプラー付きの4つのテクスチャ、埋め込まれた4枚のPNG画像、平行移動・回転・拡大縮小付きのシーンのノードの木、最後の検査

どちらのモデルも、あたしの小さなPythonスクリプトで生成しました(スクリプトはダウンロードに含まれません)。
メッシュ、PNGのテクスチャ、ノードの木を作るGLBのライターです(assets/LICENSE.txtに載っていて、自由に使えます)。
ジオラマは、実際のエクスポーターがローダーに投げ付けて来そうな物を全て試す様に、わざと意地悪に作ってあります:

  • インターリーブされた頂点:塔の2つのプリミティブは、其々byteStride 48のbufferViewを1つずつ使う。
  • 全てのインデックスの型:小さいメッシュはu8、塔はu16、木はu32。
  • 欠けた属性:ランタンのガラスはNORMALはあるがUVと接線が無い。岩はPOSITIONだけでインデックスも無いので、第14章でフラットな法線を計算する必要がある。
  • 行列のノード:ランプはTRSではなくmatrixで置かれている(ダンプではmatrix T(2.2, 0.12, 1.6)。行列はY軸周りに−30°の回転も含む)。
  • 共有されるメッシュ:木箱のメッシュは4つのノードが使い、其の内1つは(1.6, 0.45, 0.8)の一様でない拡大縮小。第10章の法線行列が効いて来る場合。羽根のメッシュはZ軸周りに0°、90°、180°、270°回した4つのノードが使う。
  • 本物の階層:4枚の羽根とハブはRotorの下にあり、RotorはWindmillの下にある。RotorをローカルのZ軸周りに回すと車輪全体が回り、第14章で其れをアニメーションさせる。
  • 空のノード:LanternLightにはメッシュが無い。階層の中の名前の付いた点、つまりソケットで、第14章で其処に点光源を置く。ゲームでは同じ技を銃口、手、カメラの支点に使う。
  • サンプラー:草はREPEAT、帆の布はCLAMP_TO_EDGEを使い、木箱のテクスチャにはサンプラーが全く無い。
  • 親より先に子:nodes配列は羽根で始まりルートで終わるので、親が先に来ると決め付けたコードは壊れる。
  • 拡張:ランタンのガラスにKHR_materials_emissive_strength。

crate.glbは単純な方ですが、此方にもu8のインデックス、metallicRoughnessTexture(粗い木と、其れより滑らかな金属の枠)、そしてextrasに\uのエスケープで書いた日本語の注記があります。

プラットフォーム毎の注意

  • Windowsのコンソール: ノードの名前にはASCII以外の文字もあり得ます(例えばBlenderは日本語の名前を其の儘残します)。gltf_dumpはUTF-8で表示します。Windows Terminalなら正しく表示されますが、古いコンソールウィンドウでは先にchcp 65001が必要かも知れません。でないと木箱の代わりに文字化けが見えます。
  • Debian 12等の古いディストリビューション: 第12章のstd::formatの要件(GCC 13)はgameには引き続き当てはまります。gltf_dumpはstd::formatを使わないので、どのC++20コンパイラでもビルド出来ます。

13.11 本物のエンジンではどうしているか

  • ライブラリを使う。 殆どのエンジンは、cgltf(Cのヘッダー1つ)やtinygltf(C++)の様な小さく良くテストされたライブラリ、又は数十の形式を読めるAssimpでglTFを読みます。自作は学ぶ為でした。此の3つは何れも、あたし達のと同じ事に加えてもっと多く(アニメーション、スキン、殆どの拡張)をこなします。此れで其の中身が分かった訳です。
  • 読み込むのではなく、インポートする。 Unity、Unreal、Godotの様なエンジンは実行時にglTFを読みません。エディタのインポーターがファイルを一度だけ読み、エンジン独自のバイナリ形式(圧縮済み、ミップマップ済み、GPU毎の頂点形式)に変換し、ゲームは其れだけを読み込みます。glTFはツールの間の交換形式で、出荷される物とは限りません。
  • パーサーをファズする。 外から来るファイルを読むコードは全て攻撃の対象です。MODやダウンロードしたアセットの悪意のあるモデルファイルは、プログラムに入り込む古典的な方法です。あたし達のローダーは全ての範囲を検査し、あたしは壊れたファイルやランダムに壊したファイル192個をAddressSanitizerの下で読ませましたが、一度も落ちませんでした。libFuzzerの様なツールは其の種のテストを自動化します。
  • 公式のツールで検証する。 KhronosはglTF Validatorを公開していて、ファイルを仕様全体に照らして検査出来ます。モデルがおかしく見えたら、先ずバリデーターに掛けて、誰のバグなのかを突き止めましょう。

13.12 まとめ

  • glTF 2.0は3Dモデルの標準の配布形式で、JSONの説明とGPU向けに並んだバイナリデータから成る。.gltfは外部又はdata: URIを使うJSON、.glbは全てを1つのファイルにまとめた物。
  • オブジェクトは番号で互いを参照する:scene → node → mesh → primitive → accessor → bufferView → buffer、及びprimitive → material → texture → imageとsampler。
  • ノードはTRS(T·R·S、クォータニオンはx, y, z, wの順)か列優先のmatrixを持つ。子は保存されるが、親は保存されない。
  • アクセサーは型付きの配列:componentType(GLのenumの値)、type(SCALAR … MAT4)、count、normalized。要素iの開始位置はbufferViewのオフセット + アクセサーのオフセット + i × ストライド。byteStrideが無いのは詰まって並んでいるという意味。
  • GLB:12バイトのヘッダー(glTF、2、長さ)の後に、長さと種類を持つチャンクが続く。JSON(空白で埋める)とBIN(0で埋める)。全てリトルエンディアンで、全て4バイト境界。
  • あたし達のJSONパーサーは再帰下降で、取り出しが失敗せず(無い=null=既定値)、エスケープとサロゲートペアに完全に対応し、strtodの前に厳密な数の文法を確かめ、深さの制限と行:列のエラーを持つ。
  • ローダーは先に全ての配列の大きさを決め、パース中に全ての番号の範囲を検査し、何かを読む前に溢れない計算で全てのバイトの範囲を検証する。リーダーはどの成分の型もfloatかuint32_tに変換する。
  • gltf_dumpはファイルを表示して検証する。新しいモデルには必ず使う事。

13.13 課題

  1. ★ Blenderの既定の立方体をglTF Binaryで書き出し(ファイル→エクスポート→glTF 2.0)、gltf_dump --allを実行して下さい。頂点24個(法線が違うので、各角が面毎に3回)のメッシュ1つ、UNSIGNED_SHORTのインデックス、metallic 0、roughness 0.5の「Material」と言うマテリアルが見えるはずです。TANGENTの属性はあるでしょうか? 書き出しの設定で「タンジェント」にチェックを入れた場合だけです。
  2. ★ gltf_dumpで各ノードのワールド位置を表示して下さい。parentの鎖をルートまで辿ってlocalTransform()を親のワールド行列と掛け合わせ、平行移動の列(c[3])を表示します。ジオラマではBlade.0が約(−1.05, 2.42, −0.44)、風車の前面にあるはずです。
  3. ★ メッシュ毎の三角形の数を数えて下さい。インデックスのあるプリミティブはインデックスの数 / 3、無い物は頂点の数 / 3で、プリミティブ全部を足します。岩は80個、木箱は12個のはずです。
  4. ★★ JSONチャンクを字下げ付きで綺麗に表示する--jsonオプションを付けて下さい。Jsonの為の小さな再帰的な表示関数を書きます(文字列はエスケープを戻す必要があります)。crate.glbの出力は13.3節のJSONの様になり、注記はエスケープの仕方次第で木箱か\u6728\u7bb1と表示されるはずです。
  5. ★★ わざとファイルを壊して下さい。crate.glbをコピーして、コピーを途中で切る(Linux/FreeBSDではhead -c 30000 crate.glb > cut.glb)か、16進エディタで開いて最初の"count":24を"count":99に変え(長さが同じなのでJSONチャンクは壊れません)、エラーを読みます。切ったファイルでは「ファイルが途中で切れている / the file is truncated」、countを変えたファイルではaccessors[0]: bufferViewをはみ出す / exceeds its bufferViewが出るはずです。プログラムは決して落ちてはいけません。
  6. ★★ 短いPythonスクリプトでジオラマを.gltfと.binの組にして下さい。GLBをJSONとBINのチャンクに分け、BINをdiorama.binに書き、buffers[0].uriを"diorama.bin"にして、JSONをdiorama.gltfに書きます。gltf_dumpはヘッダーに「glTF (JSON text)」と出る以外、同じメッシュ・マテリアル・木を表示するはずです。次にファイル名をmy diorama.binにして、URIをmy%20diorama.binにしてみて下さい。
  7. ★★★ ダンプでKHR_texture_transformに対応して下さい。テクスチャの参照にextensions.KHR_texture_transformがあれば、其のoffset、scale、rotationを表示します。テスト用のファイルを手で書けば(又はスクリプトで木箱のJSONを書き換えれば)、テクスチャの下にoffset (0.5, 0), scale (2, 2)の様な行が見えるはずです。第14章では何処で其れを適用する必要があるか(シェーダーの中の3×3のUV行列)も考えてみて下さい。

DIFFをダウンロード

プロジェクトをダウンロード(ZIP)

ファイル: a/CMakeLists.txt | b/CMakeLists.txt

前新
@@ -41,12 +41,23 @@ add_executable(game
41 target_include_directories(game PRIVATE src external/stb external/linalg) 41 target_include_directories(game PRIVATE src external/stb external/linalg)
42 target_link_libraries(game PRIVATE glad stb_image glfw) 42 target_link_libraries(game PRIVATE glad stb_image glfw)
43   43  
    44 # glTF/GLBの中身を表示する道具。GPUもウィンドウも使わないのでGLFWとGLADは要らない
    45 # A tool that prints what is inside glTF/GLB files. It uses no GPU and no window, so no GLFW and no GLAD
    46 add_executable(gltf_dump
    47 src/gltf_dump.cc
    48 src/gltf.cc
    49 src/json.cc
    50 src/file_util.cc)
    51 target_include_directories(gltf_dump PRIVATE src external/linalg)
    52  
44 # 警告を有効にする(自分のコードだけ) / enable warnings (our own code only) 53 # 警告を有効にする(自分のコードだけ) / enable warnings (our own code only)
45 if(MSVC) 54 foreach(target game gltf_dump)
46 target_compile_options(game PRIVATE /W4 /utf-8) 55 if(MSVC)
47 else() 56 target_compile_options(${target} PRIVATE /W4 /utf-8)
48 target_compile_options(game PRIVATE -Wall -Wextra) 57 else()
49 endif() 58 target_compile_options(${target} PRIVATE -Wall -Wextra)
    59 endif()
    60 endforeach()
50   61  
51 # シェーダーとアセットは作業ディレクトリからの相対パスで読む。 62 # シェーダーとアセットは作業ディレクトリからの相対パスで読む。
52 # Visual Studioではプロジェクトのルートを作業ディレクトリにする。Unixではルートから ./build/game を実行。 63 # Visual Studioではプロジェクトのルートを作業ディレクトリにする。Unixではルートから ./build/game を実行。

ファイル: a/README.md | b/README.md

前新
@@ -41,5 +41,11 @@ build\Debug\game.exe
41 または `build\opengl_tutorial.sln` を開いてF5(作業ディレクトリはプロジェクトのルートに設定済み)。 41 または `build\opengl_tutorial.sln` を開いてF5(作業ディレクトリはプロジェクトのルートに設定済み)。
42 Or open `build\opengl_tutorial.sln` and press F5 (the working directory is already set to the project root). 42 Or open `build\opengl_tutorial.sln` and press F5 (the working directory is already set to the project root).
43   43  
    44 glTF/GLBファイルの中身を表示する道具(第13章から) / a tool that prints what is inside a glTF/GLB file (from chapter 13):
    45  
    46 ```sh
    47 ./build/gltf_dump assets/models/diorama.glb # Windows: build\Debug\gltf_dump.exe assets\models\diorama.glb
    48 ```
    49  
44 シェーダーとアセットは作業ディレクトリからの相対パスで読み込むので、必ずプロジェクトのルートから実行すること。 50 シェーダーとアセットは作業ディレクトリからの相対パスで読み込むので、必ずプロジェクトのルートから実行すること。
45 Shaders and assets are loaded relative to the working directory, so always run from the project root. 51 Shaders and assets are loaded relative to the working directory, so always run from the project root.

ファイル: a/assets/LICENSE.txt | b/assets/LICENSE.txt

前新
@@ -7,3 +7,5 @@ textures/crate.png 木箱 / wooden crate
7 textures/floor.png 石の床 / stone floor tiles 7 textures/floor.png 石の床 / stone floor tiles
8 textures/crate_specular.png 木箱の鏡面反射マップ / crate specular map 8 textures/crate_specular.png 木箱の鏡面反射マップ / crate specular map
9 textures/crate_emission.png 木箱の発光マップ / crate emission map 9 textures/crate_emission.png 木箱の発光マップ / crate emission map
    10 models/crate.glb 木箱のモデル / crate model
    11 models/diorama.glb 小さな場面 / a small diorama scene

ファイル: /dev/null | b/assets/models/crate.glb

新しいファイル:100644 / バイナリファイル

ファイル: /dev/null | b/assets/models/diorama.glb

新しいファイル:100644 / バイナリファイル

ファイル: a/src/file_util.cc | b/src/file_util.cc

前新
@@ -1,6 +1,7 @@
1 #include "file_util.hh" 1 #include "file_util.hh"
2   2  
3 #include <fstream> 3 #include <fstream>
    4 #include <iterator>
4 #include <sstream> 5 #include <sstream>
5   6  
6 std::optional<std::string> readTextFile(const std::string &path) { 7 std::optional<std::string> readTextFile(const std::string &path) {
@@ -11,3 +12,9 @@ std::optional<std::string> readTextFile(const std::string &path) {
11 text << file.rdbuf(); 12 text << file.rdbuf();
12 return text.str(); 13 return text.str();
13 } 14 }
    15  
    16 std::optional<std::vector<std::uint8_t>> readBinaryFile(const std::string &path) {
    17 std::ifstream file(path, std::ios::binary);
    18 if (!file) return std::nullopt;
    19 return std::vector<std::uint8_t>(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
    20 }

ファイル: a/src/file_util.hh | b/src/file_util.hh

前新
@@ -1,9 +1,15 @@
1 // ファイルの読み込み / reading files 1 // ファイルの読み込み / reading files
2 #pragma once 2 #pragma once
3   3  
    4 #include <cstdint>
4 #include <optional> 5 #include <optional>
5 #include <string> 6 #include <string>
    7 #include <vector>
6   8  
7 // ファイル全体を文字列として読む。開けなければstd::nullopt。 9 // ファイル全体を文字列として読む。開けなければstd::nullopt。
8 // Reads a whole file into a string. std::nullopt if it cannot be opened. 10 // Reads a whole file into a string. std::nullopt if it cannot be opened.
9 std::optional<std::string> readTextFile(const std::string &path); 11 std::optional<std::string> readTextFile(const std::string &path);
    12  
    13 // ファイル全体をバイト列として読む(GLBや画像用)。開けなければstd::nullopt。
    14 // Reads a whole file as bytes (for GLB files and images). std::nullopt if it cannot be opened.
    15 std::optional<std::vector<std::uint8_t>> readBinaryFile(const std::string &path);

ファイル: /dev/null | b/src/gltf.cc

前新
@@ -0,0 +1,758 @@
    1 #include "gltf.hh"
    2  
    3 #include "file_util.hh"
    4 #include "json.hh"
    5  
    6 #include <cstdio>
    7 #include <cstring>
    8  
    9 //------------------------------------------
    10 // 小さな補助関数 / small helpers
    11 //------------------------------------------
    12  
    13 const char *gltfComponentTypeName(int componentType) {
    14 switch (componentType) {
    15 case kGltfByte: return "BYTE";
    16 case kGltfUnsignedByte: return "UNSIGNED_BYTE";
    17 case kGltfShort: return "SHORT";
    18 case kGltfUnsignedShort: return "UNSIGNED_SHORT";
    19 case kGltfUnsignedInt: return "UNSIGNED_INT";
    20 case kGltfFloat: return "FLOAT";
    21 default: return "?";
    22 }
    23 }
    24  
    25 size_t gltfComponentSize(int componentType) {
    26 switch (componentType) {
    27 case kGltfByte:
    28 case kGltfUnsignedByte: return 1;
    29 case kGltfShort:
    30 case kGltfUnsignedShort: return 2;
    31 case kGltfUnsignedInt:
    32 case kGltfFloat: return 4;
    33 default: return 0;
    34 }
    35 }
    36  
    37 static int componentCount(const std::string &type) {
    38 if (type == "SCALAR") return 1;
    39 if (type == "VEC2") return 2;
    40 if (type == "VEC3") return 3;
    41 if (type == "VEC4") return 4;
    42 if (type == "MAT2") return 4;
    43 if (type == "MAT3") return 9;
    44 if (type == "MAT4") return 16;
    45 return 0;
    46 }
    47  
    48 // 行列の列の長さ(MAT以外は0) / the column length of a matrix type (0 if not a matrix)
    49 static int matrixColumns(const GltfAccessor &a) {
    50 if (a.type == "MAT2") return 2;
    51 if (a.type == "MAT3") return 3;
    52 if (a.type == "MAT4") return 4;
    53 return 0;
    54 }
    55  
    56 // 1〜2バイトの成分の行列は、列ごとに4バイト境界へ詰め物がある(glTFの仕様 3.6.2.4)
    57 // Matrices of 1- or 2-byte components pad every column to 4 bytes (glTF spec 3.6.2.4)
    58 static size_t columnStride(const GltfAccessor &a) {
    59 size_t n = static_cast<size_t>(matrixColumns(a));
    60 size_t bytes = n * gltfComponentSize(a.componentType);
    61 return (bytes + 3) / 4 * 4;
    62 }
    63  
    64 // 要素一つのバイト数 / bytes of one element
    65 static size_t elementSize(const GltfAccessor &a) {
    66 int n = matrixColumns(a);
    67 if (n > 0 && gltfComponentSize(a.componentType) < 4) return static_cast<size_t>(n) * columnStride(a);
    68 return static_cast<size_t>(a.components) * gltfComponentSize(a.componentType);
    69 }
    70  
    71 // 要素の先頭から成分cまでのバイト数 / bytes from the start of an element to component c
    72 static size_t componentOffset(const GltfAccessor &a, int c) {
    73 int n = matrixColumns(a);
    74 size_t size = gltfComponentSize(a.componentType);
    75 if (n > 0 && size < 4) return static_cast<size_t>(c / n) * columnStride(a) + static_cast<size_t>(c % n) * size;
    76 return static_cast<size_t>(c) * size;
    77 }
    78  
    79 // 成分一つをdoubleとして読む。memcpyなので境界が揃っていなくても良い(リトルエンディアンを前提)
    80 // Reads one component as a double. memcpy works even when unaligned (assumes a little-endian CPU)
    81 static double readComponent(const std::uint8_t *p, int componentType, bool normalized) {
    82 switch (componentType) {
    83 case kGltfByte: {
    84 std::int8_t v;
    85 std::memcpy(&v, p, 1);
    86 return normalized ? (v / 127.0 < -1.0 ? -1.0 : v / 127.0) : v;
    87 }
    88 case kGltfUnsignedByte: {
    89 std::uint8_t v;
    90 std::memcpy(&v, p, 1);
    91 return normalized ? v / 255.0 : v;
    92 }
    93 case kGltfShort: {
    94 std::int16_t v;
    95 std::memcpy(&v, p, 2);
    96 return normalized ? (v / 32767.0 < -1.0 ? -1.0 : v / 32767.0) : v;
    97 }
    98 case kGltfUnsignedShort: {
    99 std::uint16_t v;
    100 std::memcpy(&v, p, 2);
    101 return normalized ? v / 65535.0 : v;
    102 }
    103 case kGltfUnsignedInt: {
    104 std::uint32_t v;
    105 std::memcpy(&v, p, 4);
    106 return normalized ? v / 4294967295.0 : v;
    107 }
    108 default: {
    109 float v;
    110 std::memcpy(&v, p, 4);
    111 return v;
    112 }
    113 }
    114 }
    115  
    116 static std::uint32_t readU32(const std::uint8_t *p) {
    117 std::uint32_t v;
    118 std::memcpy(&v, p, 4);
    119 return v;
    120 }
    121  
    122 // data: URIのbase64を復号する / decodes the base64 part of a data: URI
    123 static bool decodeBase64(std::string_view in, std::vector<std::uint8_t> &out) {
    124 auto value = [](char c) -> int {
    125 if (c >= 'A' && c <= 'Z') return c - 'A';
    126 if (c >= 'a' && c <= 'z') return c - 'a' + 26;
    127 if (c >= '0' && c <= '9') return c - '0' + 52;
    128 if (c == '+' || c == '-') return 62;
    129 if (c == '/' || c == '_') return 63;
    130 return -1;
    131 };
    132 unsigned bits = 0;
    133 int count = 0;
    134 for (char c : in) {
    135 if (c == '=') break;
    136 int v = value(c);
    137 if (v < 0) return false;
    138 bits = (bits << 6) | static_cast<unsigned>(v);
    139 count += 6;
    140 if (count >= 8) {
    141 count -= 8;
    142 out.push_back(static_cast<std::uint8_t>((bits >> count) & 0xFF));
    143 }
    144 }
    145 return true;
    146 }
    147  
    148 // URIの「%20」などを元に戻す(Blenderはファイル名の空白をこう書く)
    149 // Undoes "%20" and friends in a URI (Blender writes spaces in file names like this)
    150 static std::string percentDecode(std::string_view uri) {
    151 std::string out;
    152 for (size_t i = 0; i < uri.size(); ++i) {
    153 auto hex = [](char c) -> int {
    154 if (c >= '0' && c <= '9') return c - '0';
    155 if (c >= 'a' && c <= 'f') return c - 'a' + 10;
    156 if (c >= 'A' && c <= 'F') return c - 'A' + 10;
    157 return -1;
    158 };
    159 if (uri[i] == '%' && i + 2 < uri.size() && hex(uri[i + 1]) >= 0 && hex(uri[i + 2]) >= 0) {
    160 out += static_cast<char>(hex(uri[i + 1]) * 16 + hex(uri[i + 2]));
    161 i += 2;
    162 } else {
    163 out += uri[i];
    164 }
    165 }
    166 return out;
    167 }
    168  
    169 // URIの中身を読む:data: URI、またはglTFファイルからの相対パス
    170 // Loads what a URI points to: a data: URI, or a path relative to the glTF file
    171 static bool loadUri(const std::string &gltfPath, const std::string &uri, std::vector<std::uint8_t> &out,
    172 std::string &error) {
    173 if (uri.rfind("data:", 0) == 0) {
    174 size_t comma = uri.find(',');
    175 if (comma == std::string::npos || uri.rfind(";base64", comma) == std::string::npos) {
    176 error = "base64でないdata: URIは未対応 / only base64 data: URIs are supported";
    177 return false;
    178 }
    179 if (!decodeBase64(std::string_view(uri).substr(comma + 1), out)) {
    180 error = "data: URIのbase64が壊れている / broken base64 in a data: URI";
    181 return false;
    182 }
    183 return true;
    184 }
    185 if (uri.find("://") != std::string::npos) {
    186 error = "ネット上のファイルは読めない / cannot load remote files: " + uri;
    187 return false;
    188 }
    189 size_t slash = gltfPath.find_last_of("/\\");
    190 std::string dir = slash == std::string::npos ? std::string() : gltfPath.substr(0, slash + 1);
    191 std::string file = dir + percentDecode(uri);
    192 std::optional<std::vector<std::uint8_t>> data = readBinaryFile(file);
    193 if (!data) {
    194 error = "開けない / cannot open " + file;
    195 return false;
    196 }
    197 out = std::move(*data);
    198 return true;
    199 }
    200  
    201 int GltfPrimitive::attribute(std::string_view name) const {
    202 for (const GltfAttribute &a : attributes)
    203 if (a.name == name) return a.accessor;
    204 return -1;
    205 }
    206  
    207 Mat4 GltfNode::localTransform() const {
    208 if (hasMatrix) return matrix;
    209 // 拡大縮小 → 回転 → 平行移動の順に効く / applied as scale, then rotation, then translation
    210 return translate(translation) * toMat4(rotation) * ::scale(scale);
    211 }
    212  
    213 //------------------------------------------
    214 // JSONから構造体へ / from JSON to the structs
    215 //------------------------------------------
    216  
    217 namespace {
    218  
    219 // 読み込み中の状態とエラー / the state and the error while loading
    220 struct Loader {
    221 Gltf &g;
    222 std::string error;
    223  
    224 bool fail(const std::string &message) {
    225 if (error.empty()) error = message;
    226 return false;
    227 }
    228  
    229 // 番号(0以上の整数)を読む。キーがなければそのまま(既定値)。範囲はcountで調べる
    230 // Reads an index (an integer ≥ 0). Leaves out unchanged if the key is absent. count = valid range
    231 bool index(const Json &object, const char *key, int &out, size_t count, const std::string &where) {
    232 const Json *v = object.find(key);
    233 if (!v) return true;
    234 long long i = v->integer(-1);
    235 if (i < 0 || static_cast<size_t>(i) >= count)
    236 return fail(where + "." + key + ": 範囲外の番号 / index out of range");
    237 out = static_cast<int>(i);
    238 return true;
    239 }
    240  
    241 // 0以上の整数(バイト数など) / a non-negative integer (byte counts etc.)
    242 bool size(const Json &object, const char *key, size_t &out, const std::string &where, bool required = false) {
    243 const Json *v = object.find(key);
    244 if (!v) return required ? fail(where + "." + key + ": 必須 / required") : true;
    245 long long i = v->integer(-1);
    246 if (i < 0) return fail(where + "." + key + ": 0以上の整数が必要 / must be an integer >= 0");
    247 out = static_cast<size_t>(i);
    248 return true;
    249 }
    250  
    251 // n個の数の配列 / an array of n numbers
    252 bool numbers(const Json &object, const char *key, float *out, size_t n, const std::string &where) {
    253 const Json *v = object.find(key);
    254 if (!v) return true;
    255 if (!v->isArray() || v->size() != n)
    256 return fail(where + "." + key + ": 数が" + std::to_string(n) + "個必要 / needs " + std::to_string(n) + " numbers");
    257 for (size_t i = 0; i < n; ++i) {
    258 if (!(*v)[i].isNumber()) return fail(where + "." + key + ": 数でない / not a number");
    259 out[i] = (*v)[i].numberf();
    260 }
    261 return true;
    262 }
    263  
    264 bool textureRef(const Json &object, const char *key, GltfTextureRef &ref, const std::string &where) {
    265 const Json *t = object.find(key);
    266 if (!t) return true;
    267 std::string w = where + "." + key;
    268 if (!index(*t, "index", ref.index, g.textures.size(), w)) return false;
    269 if (ref.index < 0) return fail(w + ".index: 必須 / required");
    270 ref.texCoord = static_cast<int>((*t)["texCoord"].integer(0));
    271 if (ref.texCoord < 0) return fail(w + ".texCoord: 負の値 / negative");
    272 ref.scale = (*t)["scale"].numberf((*t)["strength"].numberf(1.0f)); // normalはscale、occlusionはstrength
    273 return true;
    274 }
    275  
    276 bool parse(const Json &root);
    277 bool parseBuffers(const Json &root, const std::vector<std::uint8_t> *glbBin);
    278 bool validate();
    279 };
    280  
    281 bool Loader::parse(const Json &root) {
    282 if (!root.isObject()) return fail("JSONの一番外側がオブジェクトでない / the top level JSON value is not an object");
    283  
    284 const Json &asset = root["asset"];
    285 g.version = asset["version"].string();
    286 g.generator = asset["generator"].string();
    287 g.copyright = asset["copyright"].string();
    288 if (g.version.rfind("2.", 0) != 0)
    289 return fail("glTF 2.xではない / not glTF 2.x (asset.version = \"" + g.version + "\")");
    290  
    291 for (const Json &e : root["extensionsUsed"].items()) g.extensionsUsed.push_back(e.string());
    292 for (const Json &e : root["extensionsRequired"].items()) {
    293 g.extensionsRequired.push_back(e.string());
    294 // 必須の拡張を理解できなければ、正しく表示できない / if we do not understand a required extension we cannot display it
    295 if (e.string() != "KHR_mesh_quantization" && e.string() != "KHR_materials_emissive_strength")
    296 return fail("未対応の必須拡張 / unsupported required extension: " + e.string());
    297 }
    298  
    299 // 番号の範囲を調べられるように、先に配列の大きさを決める / size the arrays first, so index ranges can be checked
    300 g.buffers.resize(root["buffers"].size());
    301 g.bufferViews.resize(root["bufferViews"].size());
    302 g.accessors.resize(root["accessors"].size());
    303 g.meshes.resize(root["meshes"].size());
    304 g.nodes.resize(root["nodes"].size());
    305 g.materials.resize(root["materials"].size());
    306 g.textures.resize(root["textures"].size());
    307 g.images.resize(root["images"].size());
    308 g.samplers.resize(root["samplers"].size());
    309 g.scenes.resize(root["scenes"].size());
    310 g.skinCount = root["skins"].size();
    311 g.animationCount = root["animations"].size();
    312 g.cameraCount = root["cameras"].size();
    313  
    314 for (size_t i = 0; i < g.bufferViews.size(); ++i) {
    315 const Json &j = root["bufferViews"][i];
    316 GltfBufferView &v = g.bufferViews[i];
    317 std::string w = "bufferViews[" + std::to_string(i) + "]";
    318 if (!j.has("buffer")) return fail(w + ".buffer: 必須 / required");
    319 if (!index(j, "buffer", v.buffer, g.buffers.size(), w) || !size(j, "byteOffset", v.byteOffset, w) ||
    320 !size(j, "byteLength", v.byteLength, w, true) || !size(j, "byteStride", v.byteStride, w))
    321 return false;
    322 if (v.byteStride != 0 && (v.byteStride < 4 || v.byteStride > 252 || v.byteStride % 4 != 0))
    323 return fail(w + ".byteStride: 4〜252の4の倍数が必要 / must be a multiple of 4 in 4..252");
    324 v.target = static_cast<int>(j["target"].integer(0));
    325 }
    326  
    327 for (size_t i = 0; i < g.accessors.size(); ++i) {
    328 const Json &j = root["accessors"][i];
    329 GltfAccessor &a = g.accessors[i];
    330 std::string w = "accessors[" + std::to_string(i) + "]";
    331 a.name = j["name"].string();
    332 if (!index(j, "bufferView", a.bufferView, g.bufferViews.size(), w) || !size(j, "byteOffset", a.byteOffset, w) ||
    333 !size(j, "count", a.count, w, true))
    334 return false;
    335 a.componentType = static_cast<int>(j["componentType"].integer(0));
    336 if (gltfComponentSize(a.componentType) == 0) return fail(w + ".componentType: 不正 / invalid");
    337 a.normalized = j["normalized"].boolean(false);
    338 a.type = j["type"].string();
    339 a.components = componentCount(a.type);
    340 if (a.components == 0) return fail(w + ".type: 不正 / invalid (\"" + a.type + "\")");
    341 if (a.count == 0) return fail(w + ".count: 1以上が必要 / must be >= 1");
    342 for (const Json &n : j["min"].items()) a.min.push_back(n.number());
    343 for (const Json &n : j["max"].items()) a.max.push_back(n.number());
    344 if (const Json *s = j.find("sparse")) {
    345 std::string ws = w + ".sparse";
    346 if (!size(*s, "count", a.sparseCount, ws, true)) return false;
    347 const Json &si = (*s)["indices"];
    348 const Json &sv = (*s)["values"];
    349 if (!si.has("bufferView") || !sv.has("bufferView")) return fail(ws + ": bufferViewが必須 / bufferView required");
    350 if (!index(si, "bufferView", a.sparseIndicesView, g.bufferViews.size(), ws + ".indices") ||
    351 !size(si, "byteOffset", a.sparseIndicesOffset, ws + ".indices") ||
    352 !index(sv, "bufferView", a.sparseValuesView, g.bufferViews.size(), ws + ".values") ||
    353 !size(sv, "byteOffset", a.sparseValuesOffset, ws + ".values"))
    354 return false;
    355 a.sparseIndicesType = static_cast<int>(si["componentType"].integer(0));
    356 if (a.sparseIndicesType != kGltfUnsignedByte && a.sparseIndicesType != kGltfUnsignedShort &&
    357 a.sparseIndicesType != kGltfUnsignedInt)
    358 return fail(ws + ".indices.componentType: 不正 / invalid");
    359 }
    360 }
    361  
    362 for (size_t i = 0; i < g.meshes.size(); ++i) {
    363 const Json &j = root["meshes"][i];
    364 GltfMesh &m = g.meshes[i];
    365 std::string w = "meshes[" + std::to_string(i) + "]";
    366 m.name = j["name"].string();
    367 m.primitives.resize(j["primitives"].size());
    368 if (m.primitives.empty()) return fail(w + ".primitives: 空 / empty");
    369 for (size_t k = 0; k < m.primitives.size(); ++k) {
    370 const Json &pj = j["primitives"][k];
    371 GltfPrimitive &p = m.primitives[k];
    372 std::string wp = w + ".primitives[" + std::to_string(k) + "]";
    373 for (const JsonMember &attr : pj["attributes"].members()) {
    374 GltfAttribute a;
    375 a.name = attr.key;
    376 long long acc = attr.value.integer(-1);
    377 if (acc < 0 || static_cast<size_t>(acc) >= g.accessors.size())
    378 return fail(wp + ".attributes." + attr.key + ": 範囲外の番号 / index out of range");
    379 a.accessor = static_cast<int>(acc);
    380 p.attributes.push_back(a);
    381 }
    382 if (!index(pj, "indices", p.indices, g.accessors.size(), wp) ||
    383 !index(pj, "material", p.material, g.materials.size(), wp))
    384 return false;
    385 p.mode = static_cast<int>(pj["mode"].integer(kGltfTriangles));
    386 if (p.mode < 0 || p.mode > 6) return fail(wp + ".mode: 不正 / invalid");
    387 p.hasMorphTargets = pj.has("targets");
    388 }
    389 }
    390  
    391 for (size_t i = 0; i < g.nodes.size(); ++i) {
    392 const Json &j = root["nodes"][i];
    393 GltfNode &n = g.nodes[i];
    394 std::string w = "nodes[" + std::to_string(i) + "]";
    395 n.name = j["name"].string();
    396 if (!index(j, "mesh", n.mesh, g.meshes.size(), w)) return false;
    397 for (const Json &c : j["children"].items()) {
    398 long long child = c.integer(-1);
    399 if (child < 0 || static_cast<size_t>(child) >= g.nodes.size())
    400 return fail(w + ".children: 範囲外の番号 / index out of range");
    401 n.children.push_back(static_cast<int>(child));
    402 }
    403 if (j.has("matrix")) {
    404 // 列優先の16個:最初の4個が1列目 / 16 numbers, column-major: the first 4 are column 0
    405 float m[16];
    406 if (!numbers(j, "matrix", m, 16, w)) return false;
    407 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]};
    408 n.hasMatrix = true;
    409 }
    410 float t[3] = {0, 0, 0}, r[4] = {0, 0, 0, 1}, s[3] = {1, 1, 1};
    411 if (!numbers(j, "translation", t, 3, w) || !numbers(j, "rotation", r, 4, w) || !numbers(j, "scale", s, 3, w))
    412 return false;
    413 n.translation = {t[0], t[1], t[2]};
    414 // ファイルは 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
    415 Quat q{r[3], r[0], r[1], r[2]};
    416 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
    417 n.rotation = zero ? Quat{} : normalize(q);
    418 n.scale = {s[0], s[1], s[2]};
    419 n.hasSkin = j.has("skin");
    420 }
    421  
    422 for (size_t i = 0; i < g.images.size(); ++i) {
    423 const Json &j = root["images"][i];
    424 GltfImage &im = g.images[i];
    425 std::string w = "images[" + std::to_string(i) + "]";
    426 im.name = j["name"].string();
    427 im.mimeType = j["mimeType"].string();
    428 im.uri = j["uri"].string();
    429 if (!index(j, "bufferView", im.bufferView, g.bufferViews.size(), w)) return false;
    430 if (im.bufferView < 0 && im.uri.empty()) return fail(w + ": uriもbufferViewもない / neither uri nor bufferView");
    431 }
    432  
    433 for (size_t i = 0; i < g.samplers.size(); ++i) {
    434 const Json &j = root["samplers"][i];
    435 GltfSampler &s = g.samplers[i];
    436 std::string w = "samplers[" + std::to_string(i) + "]";
    437 s.magFilter = static_cast<int>(j["magFilter"].integer(0));
    438 s.minFilter = static_cast<int>(j["minFilter"].integer(0));
    439 s.wrapS = static_cast<int>(j["wrapS"].integer(10497));
    440 s.wrapT = static_cast<int>(j["wrapT"].integer(10497));
    441 // GLにそのまま渡すので、許された値だけを通す / these go straight to GL, so only allowed values pass
    442 auto wrapOk = [](int v) { return v == 33071 || v == 33648 || v == 10497; };
    443 if (s.magFilter != 0 && s.magFilter != 9728 && s.magFilter != 9729) return fail(w + ".magFilter: 不正 / invalid");
    444 if (s.minFilter != 0 && s.minFilter != 9728 && s.minFilter != 9729 && (s.minFilter < 9984 || s.minFilter > 9987))
    445 return fail(w + ".minFilter: 不正 / invalid");
    446 if (!wrapOk(s.wrapS) || !wrapOk(s.wrapT)) return fail(w + ".wrapS/wrapT: 不正 / invalid");
    447 }
    448  
    449 for (size_t i = 0; i < g.textures.size(); ++i) {
    450 const Json &j = root["textures"][i];
    451 std::string w = "textures[" + std::to_string(i) + "]";
    452 // sourceがない(拡張の画像だけ)テクスチャは-1のまま=白として扱う / no source (extension images only) stays -1 = white
    453 if (!index(j, "source", g.textures[i].source, g.images.size(), w) ||
    454 !index(j, "sampler", g.textures[i].sampler, g.samplers.size(), w))
    455 return false;
    456 }
    457  
    458 for (size_t i = 0; i < g.materials.size(); ++i) {
    459 const Json &j = root["materials"][i];
    460 GltfMaterial &m = g.materials[i];
    461 std::string w = "materials[" + std::to_string(i) + "]";
    462 m.name = j["name"].string();
    463 const Json &pbr = j["pbrMetallicRoughness"];
    464 float base[4] = {1, 1, 1, 1}, emissive[3] = {0, 0, 0};
    465 if (!numbers(pbr, "baseColorFactor", base, 4, w + ".pbrMetallicRoughness") ||
    466 !numbers(j, "emissiveFactor", emissive, 3, w))
    467 return false;
    468 m.baseColorFactor = {base[0], base[1], base[2], base[3]};
    469 m.emissiveFactor = {emissive[0], emissive[1], emissive[2]};
    470 m.metallicFactor = pbr["metallicFactor"].numberf(1.0f);
    471 m.roughnessFactor = pbr["roughnessFactor"].numberf(1.0f);
    472 if (!textureRef(pbr, "baseColorTexture", m.baseColorTexture, w) ||
    473 !textureRef(pbr, "metallicRoughnessTexture", m.metallicRoughnessTexture, w) ||
    474 !textureRef(j, "normalTexture", m.normalTexture, w) ||
    475 !textureRef(j, "occlusionTexture", m.occlusionTexture, w) ||
    476 !textureRef(j, "emissiveTexture", m.emissiveTexture, w))
    477 return false;
    478 m.emissiveStrength = j["extensions"]["KHR_materials_emissive_strength"]["emissiveStrength"].numberf(1.0f);
    479 const std::string &mode = j["alphaMode"].string();
    480 m.alphaMode = mode == "MASK" ? GltfAlphaMode::Mask : mode == "BLEND" ? GltfAlphaMode::Blend : GltfAlphaMode::Opaque;
    481 m.alphaCutoff = j["alphaCutoff"].numberf(0.5f);
    482 m.doubleSided = j["doubleSided"].boolean(false);
    483 }
    484  
    485 for (size_t i = 0; i < g.scenes.size(); ++i) {
    486 const Json &j = root["scenes"][i];
    487 g.scenes[i].name = j["name"].string();
    488 for (const Json &n : j["nodes"].items()) {
    489 long long node = n.integer(-1);
    490 if (node < 0 || static_cast<size_t>(node) >= g.nodes.size())
    491 return fail("scenes[" + std::to_string(i) + "].nodes: 範囲外の番号 / index out of range");
    492 g.scenes[i].nodes.push_back(static_cast<int>(node));
    493 }
    494 }
    495 return index(root, "scene", g.scene, g.scenes.size(), "glTF");
    496 }
    497  
    498 bool Loader::parseBuffers(const Json &root, const std::vector<std::uint8_t> *glbBin) {
    499 for (size_t i = 0; i < g.buffers.size(); ++i) {
    500 const Json &j = root["buffers"][i];
    501 std::string w = "buffers[" + std::to_string(i) + "]";
    502 size_t byteLength = 0;
    503 if (!size(j, "byteLength", byteLength, w, true)) return false;
    504 const std::string &uri = j["uri"].string();
    505 std::vector<std::uint8_t> &data = g.buffers[i];
    506 if (!uri.empty()) {
    507 std::string message;
    508 if (!loadUri(g.path, uri, data, message)) return fail(w + ": " + message);
    509 } else if (i == 0 && glbBin) {
    510 data = *glbBin; // GLBの最初のバッファ=BINチャンク / the first buffer of a GLB = the BIN chunk
    511 } else {
    512 return fail(w + ": uriがなく、GLBのBINチャンクもない / no uri and no GLB BIN chunk");
    513 }
    514 // BINチャンクは4バイト境界まで詰め物があるので、byteLength以上あれば良い
    515 // the BIN chunk is padded to 4 bytes, so at least byteLength is enough
    516 if (data.size() < byteLength) return fail(w + ": データがbyteLengthより短い / data shorter than byteLength");
    517 data.resize(byteLength);
    518 }
    519 return true;
    520 }
    521  
    522 // バッファの範囲を超えて読むことがないよう、全部の範囲を先に確かめる
    523 // Check every range up front, so that reading can never go past the end of a buffer
    524 // bufferViewのないアクセサー(全部0)の上限、64 MiB / limit for accessors without a bufferView (all zeros), 64 MiB
    525 static constexpr size_t kMaxZeroAccessorBytes = size_t{64} << 20;
    526  
    527 bool Loader::validate() {
    528 for (size_t i = 0; i < g.bufferViews.size(); ++i) {
    529 const GltfBufferView &v = g.bufferViews[i];
    530 size_t size = g.buffers[static_cast<size_t>(v.buffer)].size();
    531 if (v.byteOffset > size || v.byteLength > size - v.byteOffset)
    532 return fail("bufferViews[" + std::to_string(i) + "]: バッファをはみ出す / exceeds the buffer");
    533 }
    534  
    535 for (size_t i = 0; i < g.accessors.size(); ++i) {
    536 const GltfAccessor &a = g.accessors[i];
    537 std::string w = "accessors[" + std::to_string(i) + "]";
    538 size_t elem = elementSize(a);
    539 if (a.bufferView >= 0) {
    540 const GltfBufferView &v = g.bufferViews[static_cast<size_t>(a.bufferView)];
    541 size_t stride = v.byteStride ? v.byteStride : elem;
    542 if (stride < elem) return fail(w + ": byteStrideが要素より小さい / byteStride smaller than an element");
    543 // 最後の要素の終わり = byteOffset + stride × (count − 1) + elem / end of the last element
    544 if (a.byteOffset > v.byteLength || (a.count - 1) > (v.byteLength - a.byteOffset) / stride ||
    545 a.byteOffset + stride * (a.count - 1) + elem > v.byteLength)
    546 return fail(w + ": bufferViewをはみ出す / exceeds its bufferView");
    547 } else if (a.count > kMaxZeroAccessorBytes / elem) {
    548 // bufferViewがないと全部0の配列を確保する。巨大なcountでメモリを使い果たさないように
    549 // Without a bufferView we allocate an array of zeros; don't let a huge count exhaust memory
    550 return fail(w + ": bufferViewなしでcountが大き過ぎる / count too large without a bufferView");
    551 }
    552 if (a.sparseCount > 0) {
    553 if (a.sparseCount > a.count) return fail(w + ".sparse.count: countより大きい / larger than count");
    554 const GltfBufferView &iv = g.bufferViews[static_cast<size_t>(a.sparseIndicesView)];
    555 const GltfBufferView &vv = g.bufferViews[static_cast<size_t>(a.sparseValuesView)];
    556 size_t indexBytes = a.sparseCount * gltfComponentSize(a.sparseIndicesType);
    557 size_t valueBytes = a.sparseCount * elem;
    558 if (a.sparseIndicesOffset > iv.byteLength || indexBytes > iv.byteLength - a.sparseIndicesOffset ||
    559 a.sparseValuesOffset > vv.byteLength || valueBytes > vv.byteLength - a.sparseValuesOffset)
    560 return fail(w + ".sparse: bufferViewをはみ出す / exceeds its bufferView");
    561 }
    562 }
    563  
    564 for (size_t i = 0; i < g.meshes.size(); ++i) {
    565 for (size_t k = 0; k < g.meshes[i].primitives.size(); ++k) {
    566 const GltfPrimitive &p = g.meshes[i].primitives[k];
    567 std::string w = "meshes[" + std::to_string(i) + "].primitives[" + std::to_string(k) + "]";
    568 size_t count = 0;
    569 for (const GltfAttribute &a : p.attributes) {
    570 size_t c = g.accessors[static_cast<size_t>(a.accessor)].count;
    571 if (count != 0 && c != count) return fail(w + ": 属性の数がそろっていない / attributes have different counts");
    572 count = c;
    573 }
    574 if (p.indices >= 0) {
    575 const GltfAccessor &ia = g.accessors[static_cast<size_t>(p.indices)];
    576 if (ia.components != 1 || (ia.componentType != kGltfUnsignedByte && ia.componentType != kGltfUnsignedShort &&
    577 ia.componentType != kGltfUnsignedInt))
    578 return fail(w + ".indices: 符号なし整数のSCALARが必要 / must be unsigned integer SCALARs");
    579 }
    580 }
    581 }
    582  
    583 // ノードの親は一つだけ、輪になってはいけない / every node has at most one parent and there are no cycles
    584 for (size_t i = 0; i < g.nodes.size(); ++i) {
    585 for (int child : g.nodes[i].children) {
    586 GltfNode &c = g.nodes[static_cast<size_t>(child)];
    587 if (c.parent != -1 || static_cast<size_t>(child) == i)
    588 return fail("nodes[" + std::to_string(child) + "]: 親が二つある / has two parents (or is its own child)");
    589 c.parent = static_cast<int>(i);
    590 }
    591 }
    592 for (size_t i = 0; i < g.nodes.size(); ++i) {
    593 int n = static_cast<int>(i);
    594 for (size_t steps = 0; n != -1; ++steps) {
    595 if (steps > g.nodes.size()) return fail("nodes: 階層が輪になっている / the hierarchy contains a cycle");
    596 n = g.nodes[static_cast<size_t>(n)].parent;
    597 }
    598 }
    599 for (size_t i = 0; i < g.scenes.size(); ++i)
    600 for (int n : g.scenes[i].nodes)
    601 if (g.nodes[static_cast<size_t>(n)].parent != -1)
    602 return fail("scenes[" + std::to_string(i) + "]: ルートでないノード / a node that is not a root");
    603 return true;
    604 }
    605  
    606 } // namespace
    607  
    608 //------------------------------------------
    609 // 読み込み / loading
    610 //------------------------------------------
    611  
    612 std::optional<Gltf> Gltf::load(const std::string &path) {
    613 std::optional<std::vector<std::uint8_t>> file = readBinaryFile(path);
    614 if (!file) {
    615 fprintf(stderr, "%s: 開けない / cannot open (プロジェクトのルートから実行した? / running from the project root?)\n",
    616 path.c_str());
    617 return std::nullopt;
    618 }
    619 Gltf g;
    620 g.path = path;
    621 Loader loader{g, {}};
    622 auto failed = [&](const std::string &message) {
    623 fprintf(stderr, "%s: %s\n", path.c_str(), message.c_str());
    624 return std::nullopt;
    625 };
    626  
    627 const std::vector<std::uint8_t> &bytes = *file;
    628 std::string_view jsonText;
    629 std::vector<std::uint8_t> bin;
    630 bool hasBin = false;
    631  
    632 // GLB:12バイトのヘッダー(magic "glTF"、version、全体の長さ)+チャンク(長さ、種類、中身)の並び
    633 // GLB: a 12-byte header (magic "glTF", version, total length) + chunks (length, type, data)
    634 if (bytes.size() >= 4 && readU32(bytes.data()) == 0x46546C67) {
    635 if (bytes.size() < 12) return failed("GLBのヘッダーが途中で切れている / truncated GLB header");
    636 g.isGlb = true;
    637 std::uint32_t version = readU32(bytes.data() + 4);
    638 g.glbLength = readU32(bytes.data() + 8);
    639 if (version != 2) return failed("GLBのバージョンが2でない / GLB version is not 2: " + std::to_string(version));
    640 if (g.glbLength > bytes.size()) return failed("ファイルが途中で切れている / the file is truncated");
    641 size_t offset = 12;
    642 int chunkIndex = 0;
    643 while (offset + 8 <= g.glbLength) {
    644 std::uint32_t length = readU32(bytes.data() + offset);
    645 std::uint32_t type = readU32(bytes.data() + offset + 4);
    646 offset += 8;
    647 if (length > g.glbLength - offset) return failed("チャンクがファイルをはみ出す / a chunk exceeds the file");
    648 const std::uint8_t *data = bytes.data() + offset;
    649 if (chunkIndex == 0) {
    650 if (type != 0x4E4F534A) return failed("最初のチャンクがJSONでない / the first chunk is not JSON");
    651 g.jsonChunkLength = length;
    652 jsonText = std::string_view(reinterpret_cast<const char *>(data), length);
    653 // 空白で埋めるべき所を0で埋めるツールがある / some tools pad with zeros instead of spaces
    654 while (!jsonText.empty() && jsonText.back() == '\0') jsonText.remove_suffix(1);
    655 } else if (type == 0x004E4942 && !hasBin) {
    656 g.binChunkLength = length;
    657 bin.assign(data, data + length);
    658 hasBin = true;
    659 } // 知らない種類のチャンクは読み飛ばす / unknown chunk types are skipped
    660 offset += length;
    661 ++chunkIndex;
    662 }
    663 if (chunkIndex == 0) return failed("JSONチャンクがない / no JSON chunk");
    664 } else {
    665 // .gltf:ファイル全体がJSON / .gltf: the whole file is JSON
    666 jsonText = std::string_view(reinterpret_cast<const char *>(bytes.data()), bytes.size());
    667 }
    668  
    669 std::string jsonError;
    670 std::optional<Json> root = Json::parse(jsonText, &jsonError);
    671 if (!root) return failed("JSON " + jsonError);
    672 if (!loader.parse(*root) || !loader.parseBuffers(*root, hasBin ? &bin : nullptr) || !loader.validate())
    673 return failed(loader.error);
    674 return g;
    675 }
    676  
    677 //------------------------------------------
    678 // アクセサーを読む / reading accessors
    679 //------------------------------------------
    680  
    681 // 要素を一つずつ、成分ごとにTへ変換して読む。疎なアクセサーも処理する
    682 // Reads element by element, converting each component to T. Handles sparse accessors too
    683 template <typename T>
    684 static bool readAccessor(const Gltf &g, const GltfAccessor &a, std::vector<T> &out) {
    685 size_t n = static_cast<size_t>(a.components);
    686 size_t elem = elementSize(a);
    687 out.assign(a.count * n, T{}); // bufferViewがなければ全部0 / all zeros without a bufferView
    688 if (a.bufferView >= 0) {
    689 const GltfBufferView &v = g.bufferViews[static_cast<size_t>(a.bufferView)];
    690 const std::uint8_t *base = g.buffers[static_cast<size_t>(v.buffer)].data() + v.byteOffset + a.byteOffset;
    691 size_t stride = v.byteStride ? v.byteStride : elem; // 0 = 詰まっている / 0 = tightly packed
    692 for (size_t e = 0; e < a.count; ++e)
    693 for (size_t c = 0; c < n; ++c)
    694 out[e * n + c] = static_cast<T>(
    695 readComponent(base + e * stride + componentOffset(a, static_cast<int>(c)), a.componentType, a.normalized));
    696 }
    697 if (a.sparseCount > 0) {
    698 const GltfBufferView &iv = g.bufferViews[static_cast<size_t>(a.sparseIndicesView)];
    699 const GltfBufferView &vv = g.bufferViews[static_cast<size_t>(a.sparseValuesView)];
    700 const std::uint8_t *indices = g.buffers[static_cast<size_t>(iv.buffer)].data() + iv.byteOffset + a.sparseIndicesOffset;
    701 const std::uint8_t *values = g.buffers[static_cast<size_t>(vv.buffer)].data() + vv.byteOffset + a.sparseValuesOffset;
    702 size_t indexSize = gltfComponentSize(a.sparseIndicesType);
    703 for (size_t k = 0; k < a.sparseCount; ++k) {
    704 size_t e = static_cast<size_t>(readComponent(indices + k * indexSize, a.sparseIndicesType, false));
    705 if (e >= a.count) {
    706 fprintf(stderr, "%s: 疎なアクセサーの番号が範囲外 / sparse index out of range\n", g.path.c_str());
    707 return false;
    708 }
    709 for (size_t c = 0; c < n; ++c)
    710 out[e * n + c] = static_cast<T>(
    711 readComponent(values + k * elem + componentOffset(a, static_cast<int>(c)), a.componentType, a.normalized));
    712 }
    713 }
    714 return true;
    715 }
    716  
    717 std::optional<std::vector<float>> Gltf::readFloats(int accessor) const {
    718 if (accessor < 0 || static_cast<size_t>(accessor) >= accessors.size()) return std::nullopt;
    719 std::vector<float> out;
    720 if (!readAccessor(*this, accessors[static_cast<size_t>(accessor)], out)) return std::nullopt;
    721 return out;
    722 }
    723  
    724 std::optional<std::vector<std::uint32_t>> Gltf::readIndices(int accessor) const {
    725 if (accessor < 0 || static_cast<size_t>(accessor) >= accessors.size()) return std::nullopt;
    726 const GltfAccessor &a = accessors[static_cast<size_t>(accessor)];
    727 if (a.components != 1 || a.normalized || a.componentType == kGltfFloat || a.componentType == kGltfByte ||
    728 a.componentType == kGltfShort)
    729 return std::nullopt;
    730 std::vector<std::uint32_t> out;
    731 if (!readAccessor(*this, a, out)) return std::nullopt;
    732 return out;
    733 }
    734  
    735 std::optional<std::vector<std::uint8_t>> Gltf::imageData(int image) const {
    736 if (image < 0 || static_cast<size_t>(image) >= images.size()) return std::nullopt;
    737 const GltfImage &im = images[static_cast<size_t>(image)];
    738 if (im.bufferView >= 0) {
    739 const GltfBufferView &v = bufferViews[static_cast<size_t>(im.bufferView)];
    740 const std::uint8_t *p = buffers[static_cast<size_t>(v.buffer)].data() + v.byteOffset;
    741 return std::vector<std::uint8_t>(p, p + v.byteLength);
    742 }
    743 std::vector<std::uint8_t> data;
    744 std::string error;
    745 if (!loadUri(path, im.uri, data, error)) {
    746 fprintf(stderr, "%s: images[%d]: %s\n", path.c_str(), image, error.c_str());
    747 return std::nullopt;
    748 }
    749 return data;
    750 }
    751  
    752 std::vector<int> Gltf::rootNodes() const {
    753 if (!scenes.empty()) return scenes[scene >= 0 ? static_cast<size_t>(scene) : 0].nodes;
    754 std::vector<int> roots;
    755 for (size_t i = 0; i < nodes.size(); ++i)
    756 if (nodes[i].parent == -1) roots.push_back(static_cast<int>(i));
    757 return roots;
    758 }

ファイル: /dev/null | b/src/gltf.hh

前新
@@ -0,0 +1,201 @@
    1 // glTF 2.0の読み込み(.glbと.gltf)。GPUには触らない:ファイルの中身を構造体にするだけ。
    2 // Reading glTF 2.0 (.glb and .gltf). It does not touch the GPU: it only turns the file into structs.
    3 //
    4 // 対応 / supported: 静的なメッシュ、PBRマテリアル、テクスチャ・画像・サンプラー、ノードの階層(TRSまたは行列)、
    5 // GLBのBINチャンク・外部の.bin・data: URI、疎なアクセサー、KHR_mesh_quantization、KHR_materials_emissive_strength
    6 // static meshes, PBR materials, textures/images/samplers, the node hierarchy (TRS or matrix),
    7 // GLB BIN chunk / external .bin / data: URIs, sparse accessors, KHR_mesh_quantization, KHR_materials_emissive_strength
    8 // 対象外 / not supported: スキン、アニメーション、モーフターゲット(読み飛ばす)、Draco・meshoptの圧縮
    9 // skins, animations, morph targets (skipped), Draco / meshopt compression
    10 #pragma once
    11  
    12 #include "mathx.hh"
    13  
    14 #include <cstddef>
    15 #include <cstdint>
    16 #include <optional>
    17 #include <string>
    18 #include <string_view>
    19 #include <vector>
    20  
    21 // componentType:値はOpenGLのenumと同じ(GL_FLOAT = 5126…)。このファイルはGLに依存しないので自分で定義する
    22 // componentType: the values equal the OpenGL enums (GL_FLOAT = 5126, ...). This file does not depend on GL,
    23 // so we define them ourselves
    24 constexpr int kGltfByte = 5120;
    25 constexpr int kGltfUnsignedByte = 5121;
    26 constexpr int kGltfShort = 5122;
    27 constexpr int kGltfUnsignedShort = 5123;
    28 constexpr int kGltfUnsignedInt = 5125;
    29 constexpr int kGltfFloat = 5126;
    30  
    31 // プリミティブのmode(GL_POINTS = 0 … GL_TRIANGLE_FAN = 6と同じ) / primitive modes (same as GL_POINTS = 0 ... GL_TRIANGLE_FAN = 6)
    32 constexpr int kGltfTriangles = 4;
    33  
    34 // バッファの一部分 / a slice of a buffer
    35 struct GltfBufferView {
    36 int buffer = -1;
    37 size_t byteOffset = 0;
    38 size_t byteLength = 0;
    39 size_t byteStride = 0; // 0 = 要素が詰まって並ぶ / 0 = elements are tightly packed
    40 int target = 0; // 34962 = 頂点、34963 = インデックス(ヒントだけ) / 34962 = vertices, 34963 = indices (just a hint)
    41 };
    42  
    43 // 型付きの配列:bufferViewのどこに、どの型の要素がいくつあるか
    44 // A typed array: where in a bufferView, which type, how many elements
    45 struct GltfAccessor {
    46 std::string name;
    47 int bufferView = -1; // -1 = 全部0(疎な値だけを持つアクセサー) / -1 = all zeros (an accessor with only sparse values)
    48 size_t byteOffset = 0; // bufferViewの先頭から / from the start of the bufferView
    49 int componentType = kGltfFloat;
    50 bool normalized = false; // 整数を0〜1(符号付きは-1〜1)にする / map integers to 0..1 (signed: -1..1)
    51 size_t count = 0; // 要素の数 / number of elements
    52 std::string type; // "SCALAR"、"VEC2"、"VEC3"、"VEC4"、"MAT2"、"MAT3"、"MAT4"
    53 int components = 0; // typeの成分数 / number of components of type
    54 std::vector<double> min, max;
    55  
    56 // 疎なアクセサー:一部の要素だけを別の値で上書きする / sparse accessor: overrides some elements with other values
    57 size_t sparseCount = 0; // 0 = 疎でない / 0 = not sparse
    58 int sparseIndicesView = -1;
    59 size_t sparseIndicesOffset = 0;
    60 int sparseIndicesType = kGltfUnsignedInt;
    61 int sparseValuesView = -1;
    62 size_t sparseValuesOffset = 0;
    63 };
    64  
    65 struct GltfAttribute {
    66 std::string name; // "POSITION"、"NORMAL"、"TEXCOORD_0"、"TANGENT"…
    67 int accessor = -1;
    68 };
    69  
    70 // 一回の描画呼び出しの単位:属性+インデックス+マテリアル / one draw call: attributes + indices + material
    71 struct GltfPrimitive {
    72 std::vector<GltfAttribute> attributes;
    73 int indices = -1; // -1 = インデックスなし(glDrawArrays) / -1 = no indices (glDrawArrays)
    74 int material = -1; // -1 = 既定のマテリアル / -1 = the default material
    75 int mode = kGltfTriangles;
    76 bool hasMorphTargets = false; // 読み飛ばした / skipped
    77  
    78 int attribute(std::string_view name) const; // アクセサーの番号、なければ-1 / accessor index, -1 if absent
    79 };
    80  
    81 struct GltfMesh {
    82 std::string name;
    83 std::vector<GltfPrimitive> primitives;
    84 };
    85  
    86 // シーングラフのノード:変換と、メッシュ(任意)と、子ノード
    87 // A scene graph node: a transform, an optional mesh, and child nodes
    88 struct GltfNode {
    89 std::string name;
    90 int mesh = -1;
    91 int parent = -1; // 読み込み時に子の一覧から求める / computed from the children lists when loading
    92 std::vector<int> children;
    93 // ローカル変換:行列か、平行移動・回転・拡大縮小(TRS)のどちらか
    94 // Local transform: either a matrix or translation / rotation / scale (TRS)
    95 bool hasMatrix = false;
    96 Mat4 matrix = Mat4::identity();
    97 Vec3 translation = {0.0f, 0.0f, 0.0f};
    98 Quat rotation; // 単位クォータニオン(ファイルでは x, y, z, w の順) / unit quaternion (x, y, z, w in the file)
    99 Vec3 scale = {1.0f, 1.0f, 1.0f};
    100 bool hasSkin = false; // 読み飛ばした / skipped
    101  
    102 // 親から見たこのノードの変換:matrix、または T × R × S / this node's transform relative to its parent
    103 Mat4 localTransform() const;
    104 };
    105  
    106 // マテリアルからテクスチャへの参照 / a reference from a material to a texture
    107 struct GltfTextureRef {
    108 int index = -1; // texturesの番号、-1 = なし / index into textures, -1 = none
    109 int texCoord = 0; // どのTEXCOORD_nを使うか / which TEXCOORD_n to use
    110 float scale = 1.0f; // normalTextureのscale、occlusionTextureのstrength
    111 };
    112  
    113 enum class GltfAlphaMode { Opaque, Mask, Blend };
    114  
    115 // PBR(金属・粗さ)マテリアル。ファイルにない値はglTFの既定値 / PBR (metallic-roughness) material; glTF defaults
    116 struct GltfMaterial {
    117 std::string name;
    118 Vec4 baseColorFactor = {1.0f, 1.0f, 1.0f, 1.0f};
    119 GltfTextureRef baseColorTexture;
    120 float metallicFactor = 1.0f;
    121 float roughnessFactor = 1.0f;
    122 GltfTextureRef metallicRoughnessTexture; // G = 粗さ / roughness、B = 金属度 / metallic
    123 GltfTextureRef normalTexture;
    124 GltfTextureRef occlusionTexture;
    125 GltfTextureRef emissiveTexture;
    126 Vec3 emissiveFactor = {0.0f, 0.0f, 0.0f};
    127 float emissiveStrength = 1.0f; // KHR_materials_emissive_strength
    128 GltfAlphaMode alphaMode = GltfAlphaMode::Opaque;
    129 float alphaCutoff = 0.5f;
    130 bool doubleSided = false;
    131 };
    132  
    133 struct GltfTexture {
    134 int source = -1; // imagesの番号 / index into images
    135 int sampler = -1; // -1 = 既定(繰り返し、線型+ミップマップ) / -1 = default (repeat, linear + mipmaps)
    136 };
    137  
    138 struct GltfImage {
    139 std::string name;
    140 std::string mimeType; // "image/png"、"image/jpeg"
    141 std::string uri; // ファイル名かdata: URI(bufferViewがなければ) / a file name or a data: URI (if no bufferView)
    142 int bufferView = -1;
    143 };
    144  
    145 // 値はOpenGLのenumと同じ。0 = ファイルに書かれていない / values are the OpenGL enums; 0 = not given in the file
    146 struct GltfSampler {
    147 int magFilter = 0;
    148 int minFilter = 0;
    149 int wrapS = 10497; // GL_REPEAT
    150 int wrapT = 10497;
    151 };
    152  
    153 struct GltfScene {
    154 std::string name;
    155 std::vector<int> nodes; // ルートノード / the root nodes
    156 };
    157  
    158 // ファイル一つ分のglTF / one glTF file
    159 struct Gltf {
    160 std::string path;
    161  
    162 // 入れ物の情報(表示用) / container information (for printing)
    163 bool isGlb = false;
    164 std::uint32_t glbLength = 0, jsonChunkLength = 0, binChunkLength = 0;
    165  
    166 std::string version, generator, copyright;
    167 std::vector<std::string> extensionsUsed, extensionsRequired;
    168  
    169 std::vector<std::vector<std::uint8_t>> buffers; // 中身を読み込んだバッファ / the loaded buffer contents
    170 std::vector<GltfBufferView> bufferViews;
    171 std::vector<GltfAccessor> accessors;
    172 std::vector<GltfMesh> meshes;
    173 std::vector<GltfNode> nodes;
    174 std::vector<GltfMaterial> materials;
    175 std::vector<GltfTexture> textures;
    176 std::vector<GltfImage> images;
    177 std::vector<GltfSampler> samplers;
    178 std::vector<GltfScene> scenes;
    179 int scene = -1; // 既定のシーン、-1 = 指定なし / the default scene, -1 = not specified
    180 size_t skinCount = 0, animationCount = 0, cameraCount = 0; // 数だけ数える / only counted
    181  
    182 // .glbまたは.gltfを読んで全部を検査する。失敗したらエラーを表示してstd::nullopt。
    183 // Loads a .glb or .gltf and validates everything. On failure prints the error and returns std::nullopt.
    184 static std::optional<Gltf> load(const std::string &path);
    185  
    186 // アクセサーを読み、count × components個のfloatにする(どのcomponentTypeでも、正規化も処理する)
    187 // Reads an accessor into count × components floats (any componentType, normalization handled)
    188 std::optional<std::vector<float>> readFloats(int accessor) const;
    189 // インデックスを読み、u8・u16・u32をすべてu32にする / reads indices; u8, u16 and u32 all become u32
    190 std::optional<std::vector<std::uint32_t>> readIndices(int accessor) const;
    191 // 画像ファイルのバイト列(PNG、JPEG…) / the bytes of an image file (PNG, JPEG, ...)
    192 std::optional<std::vector<std::uint8_t>> imageData(int image) const;
    193  
    194 // 描くべきルートノード:既定のシーン、なければ最初のシーン、シーンがなければ親のないノード全部
    195 // The root nodes to draw: the default scene, else the first one, else every node without a parent
    196 std::vector<int> rootNodes() const;
    197 };
    198  
    199 // componentTypeの名前とバイト数 / name and byte size of a componentType
    200 const char *gltfComponentTypeName(int componentType);
    201 size_t gltfComponentSize(int componentType);

ファイル: /dev/null | b/src/gltf_dump.cc

前新
@@ -0,0 +1,292 @@
    1 // glTF/GLBファイルの中身を表示する道具(第13章)。GPUもウィンドウも使わない。
    2 // A tool that prints what is inside a glTF/GLB file (chapter 13). Uses no GPU and no window.
    3 //
    4 // 使い方 / usage: gltf_dump [--all] file.glb [file2.gltf ...]
    5 // --all bufferViewとアクセサーの一覧も表示する / also list every bufferView and accessor
    6 // 最後に、全部のアクセサーを実際に読んで確かめる(min/max、インデックスの範囲)。
    7 // At the end, every accessor is actually read and checked (min/max, index ranges).
    8 #ifdef _WIN32
    9 // SetConsoleOutputCPの為。GLADより先にインクルードする(APIENTRYの二重定義を防ぐ)
    10 // For SetConsoleOutputCP. Include it before GLAD (so APIENTRY is not defined twice)
    11 #define WIN32_LEAN_AND_MEAN
    12 #define NOMINMAX
    13 #include <windows.h>
    14 #endif
    15 #include "gltf.hh"
    16  
    17 #include <cmath>
    18 #include <cstdio>
    19 #include <cstring>
    20 #include <string>
    21  
    22 static const char *modeName(int mode) {
    23 static const char *const kNames[] = {"POINTS", "LINES", "LINE_LOOP", "LINE_STRIP",
    24 "TRIANGLES", "TRIANGLE_STRIP", "TRIANGLE_FAN"};
    25 return mode >= 0 && mode <= 6 ? kNames[mode] : "?";
    26 }
    27  
    28 static const char *targetName(int target) {
    29 if (target == 34962) return ", ARRAY_BUFFER";
    30 if (target == 34963) return ", ELEMENT_ARRAY_BUFFER";
    31 return "";
    32 }
    33  
    34 static const char *nameOr(const std::string &name, const char *fallback) { return name.empty() ? fallback : name.c_str(); }
    35  
    36 static void printAccessor(const Gltf &g, int index) {
    37 const GltfAccessor &a = g.accessors[static_cast<size_t>(index)];
    38 printf("%-6s %-14s x %-5zu", a.type.c_str(), gltfComponentTypeName(a.componentType), a.count);
    39 if (a.normalized) printf(" normalized");
    40 if (a.bufferView >= 0) {
    41 const GltfBufferView &v = g.bufferViews[static_cast<size_t>(a.bufferView)];
    42 printf(" view %d +%zu", a.bufferView, a.byteOffset);
    43 if (v.byteStride) printf(" stride %zu", v.byteStride);
    44 } else {
    45 printf(" (no bufferView: zeros)");
    46 }
    47 if (a.sparseCount) printf(", sparse %zu", a.sparseCount);
    48 }
    49  
    50 static void printTexture(const Gltf &g, const char *label, const GltfTextureRef &t) {
    51 if (t.index < 0) return;
    52 const GltfTexture &tex = g.textures[static_cast<size_t>(t.index)];
    53 printf("\n %s: texture %d (image %d", label, t.index, tex.source);
    54 if (tex.source >= 0) printf(" \"%s\"", nameOr(g.images[static_cast<size_t>(tex.source)].name, ""));
    55 printf(")");
    56 if (t.texCoord != 0) printf(", TEXCOORD_%d", t.texCoord);
    57 }
    58  
    59 static void printTransform(const GltfNode &n) {
    60 if (n.hasMatrix) {
    61 const Mat4 &m = n.matrix;
    62 printf(" matrix T(%g, %g, %g)", m.c[3].x, m.c[3].y, m.c[3].z);
    63 return;
    64 }
    65 const Vec3 &t = n.translation;
    66 if (t.x != 0.0f || t.y != 0.0f || t.z != 0.0f) printf(" T(%g, %g, %g)", t.x, t.y, t.z);
    67 const Quat &q = n.rotation;
    68 if (q.w < 0.999999f) {
    69 // 軸と角度で表示する方が読みやすい:q = (cos(θ/2), 軸 · sin(θ/2)) / easier to read as axis and angle
    70 float angle = 2.0f * std::acos(q.w > 1.0f ? 1.0f : q.w);
    71 float s = std::sin(angle * 0.5f);
    72 auto clean = [](float v) { return std::fabs(v) < 5e-7f ? 0.0f : v; }; // -0を表示しない / do not print -0
    73 printf(" R(%.1f deg about %.3g, %.3g, %.3g)", degrees(angle), clean(q.x / s), clean(q.y / s), clean(q.z / s));
    74 }
    75 const Vec3 &s = n.scale;
    76 if (s.x != 1.0f || s.y != 1.0f || s.z != 1.0f) printf(" S(%g, %g, %g)", s.x, s.y, s.z);
    77 }
    78  
    79 // ノードの木を「+-」と「|」で描く / draws the node tree with "+-" and "|"
    80 static void printNode(const Gltf &g, int index, const std::string &prefix, bool last, bool root) {
    81 const GltfNode &n = g.nodes[static_cast<size_t>(index)];
    82 printf(" %s%s%s", prefix.c_str(), root ? "" : "+- ", nameOr(n.name, "(unnamed)"));
    83 if (n.mesh >= 0) printf(" [mesh %d \"%s\"]", n.mesh, g.meshes[static_cast<size_t>(n.mesh)].name.c_str());
    84 printTransform(n);
    85 if (n.hasSkin) printf(" (skin ignored)");
    86 printf("\n");
    87 std::string childPrefix = root ? prefix : prefix + (last ? " " : "| ");
    88 for (size_t i = 0; i < n.children.size(); ++i)
    89 printNode(g, n.children[i], childPrefix, i + 1 == n.children.size(), false);
    90 }
    91  
    92 // 全部のプリミティブを読んでみる。問題の数を返す / reads every primitive; returns the number of problems
    93 static int verify(const Gltf &g, size_t &primitiveCount) {
    94 int problems = 0;
    95 primitiveCount = 0;
    96 for (size_t m = 0; m < g.meshes.size(); ++m) {
    97 for (size_t k = 0; k < g.meshes[m].primitives.size(); ++k) {
    98 const GltfPrimitive &p = g.meshes[m].primitives[k];
    99 ++primitiveCount;
    100 size_t vertexCount = 0;
    101 for (const GltfAttribute &attr : p.attributes) {
    102 const GltfAccessor &a = g.accessors[static_cast<size_t>(attr.accessor)];
    103 std::optional<std::vector<float>> data = g.readFloats(attr.accessor);
    104 if (!data) {
    105 printf(" ! mesh %zu prim %zu %s: cannot read\n", m, k, attr.name.c_str());
    106 ++problems;
    107 continue;
    108 }
    109 vertexCount = a.count;
    110 // ファイルのmin/maxと、実際に読んだ値を比べる / compare the file's min/max with the values actually read
    111 if (a.min.size() == static_cast<size_t>(a.components) && a.max.size() == a.min.size()) {
    112 for (size_t c = 0; c < a.min.size(); ++c) {
    113 float lo = 1e30f, hi = -1e30f;
    114 for (size_t e = 0; e < a.count; ++e) {
    115 float v = (*data)[e * a.min.size() + c];
    116 lo = v < lo ? v : lo;
    117 hi = v > hi ? v : hi;
    118 }
    119 double tolerance = 1e-4 * (1.0 + std::fabs(a.max[c] - a.min[c]));
    120 if (std::fabs(lo - a.min[c]) > tolerance || std::fabs(hi - a.max[c]) > tolerance) {
    121 printf(" ! mesh %zu prim %zu %s: min/max (%g..%g) differ from the data (%g..%g)\n", m, k,
    122 attr.name.c_str(), a.min[c], a.max[c], static_cast<double>(lo), static_cast<double>(hi));
    123 ++problems;
    124 }
    125 }
    126 }
    127 }
    128 if (p.indices >= 0) {
    129 std::optional<std::vector<std::uint32_t>> indices = g.readIndices(p.indices);
    130 if (!indices) {
    131 printf(" ! mesh %zu prim %zu: cannot read the indices\n", m, k);
    132 ++problems;
    133 continue;
    134 }
    135 for (std::uint32_t i : *indices) {
    136 if (i >= vertexCount) {
    137 printf(" ! mesh %zu prim %zu: index %u >= vertex count %zu\n", m, k, i, vertexCount);
    138 ++problems;
    139 break;
    140 }
    141 }
    142 }
    143 if (p.attribute("POSITION") < 0) {
    144 printf(" ! mesh %zu prim %zu: no POSITION (will not be drawn)\n", m, k);
    145 ++problems;
    146 }
    147 }
    148 }
    149 return problems;
    150 }
    151  
    152 static bool dump(const std::string &path, bool all) {
    153 std::optional<Gltf> loaded = Gltf::load(path);
    154 if (!loaded) return false;
    155 const Gltf &g = *loaded;
    156  
    157 printf("== %s ==\n", path.c_str());
    158 if (g.isGlb)
    159 printf("GLB version 2, %u bytes: JSON chunk %u bytes, BIN chunk %u bytes\n", g.glbLength, g.jsonChunkLength,
    160 g.binChunkLength);
    161 else
    162 printf("glTF (JSON text)\n");
    163 printf("asset: glTF %s, generator \"%s\"\n", g.version.c_str(), g.generator.c_str());
    164 for (const std::string &e : g.extensionsUsed) printf("extension used: %s\n", e.c_str());
    165 for (const std::string &e : g.extensionsRequired) printf("extension required: %s\n", e.c_str());
    166 if (g.skinCount || g.animationCount || g.cameraCount)
    167 printf("ignored: %zu skins, %zu animations, %zu cameras\n", g.skinCount, g.animationCount, g.cameraCount);
    168  
    169 printf("buffers (%zu)\n", g.buffers.size());
    170 for (size_t i = 0; i < g.buffers.size(); ++i) printf(" [%zu] %zu bytes\n", i, g.buffers[i].size());
    171  
    172 printf("bufferViews (%zu), accessors (%zu)\n", g.bufferViews.size(), g.accessors.size());
    173 if (all) {
    174 for (size_t i = 0; i < g.bufferViews.size(); ++i) {
    175 const GltfBufferView &v = g.bufferViews[i];
    176 printf(" view [%zu] buffer %d, offset %zu, %zu bytes", i, v.buffer, v.byteOffset, v.byteLength);
    177 if (v.byteStride) printf(", stride %zu", v.byteStride);
    178 printf("%s\n", targetName(v.target));
    179 }
    180 for (size_t i = 0; i < g.accessors.size(); ++i) {
    181 printf(" accessor [%zu] ", i);
    182 printAccessor(g, static_cast<int>(i));
    183 printf("\n");
    184 }
    185 }
    186  
    187 printf("meshes (%zu)\n", g.meshes.size());
    188 for (size_t i = 0; i < g.meshes.size(); ++i) {
    189 const GltfMesh &m = g.meshes[i];
    190 printf(" [%zu] \"%s\": %zu primitive%s\n", i, m.name.c_str(), m.primitives.size(),
    191 m.primitives.size() == 1 ? "" : "s");
    192 for (size_t k = 0; k < m.primitives.size(); ++k) {
    193 const GltfPrimitive &p = m.primitives[k];
    194 printf(" #%zu %s, material ", k, modeName(p.mode));
    195 if (p.material >= 0) printf("%d \"%s\"", p.material, g.materials[static_cast<size_t>(p.material)].name.c_str());
    196 else printf("(default)");
    197 if (p.indices >= 0) {
    198 const GltfAccessor &ia = g.accessors[static_cast<size_t>(p.indices)];
    199 printf(", %zu indices (%s)", ia.count, gltfComponentTypeName(ia.componentType));
    200 } else {
    201 printf(", no indices");
    202 }
    203 if (p.hasMorphTargets) printf(", morph targets ignored");
    204 printf("\n");
    205 for (const GltfAttribute &a : p.attributes) {
    206 printf(" %-11s ", a.name.c_str());
    207 printAccessor(g, a.accessor);
    208 printf("\n");
    209 }
    210 }
    211 }
    212  
    213 printf("materials (%zu)\n", g.materials.size());
    214 for (size_t i = 0; i < g.materials.size(); ++i) {
    215 const GltfMaterial &m = g.materials[i];
    216 const Vec4 &b = m.baseColorFactor;
    217 printf(" [%zu] \"%s\": base colour (%g, %g, %g, %g), metallic %g, roughness %g", i, m.name.c_str(), b.x, b.y, b.z,
    218 b.w, m.metallicFactor, m.roughnessFactor);
    219 if (m.emissiveFactor.x > 0.0f || m.emissiveFactor.y > 0.0f || m.emissiveFactor.z > 0.0f)
    220 printf(", emissive (%g, %g, %g) x %g", m.emissiveFactor.x, m.emissiveFactor.y, m.emissiveFactor.z,
    221 m.emissiveStrength);
    222 if (m.alphaMode != GltfAlphaMode::Opaque) printf(", alpha %s", m.alphaMode == GltfAlphaMode::Mask ? "MASK" : "BLEND");
    223 if (m.doubleSided) printf(", double-sided");
    224 printTexture(g, "baseColorTexture", m.baseColorTexture);
    225 printTexture(g, "metallicRoughnessTexture", m.metallicRoughnessTexture);
    226 printTexture(g, "normalTexture", m.normalTexture);
    227 printTexture(g, "occlusionTexture", m.occlusionTexture);
    228 printTexture(g, "emissiveTexture", m.emissiveTexture);
    229 printf("\n");
    230 }
    231  
    232 printf("textures (%zu), images (%zu), samplers (%zu)\n", g.textures.size(), g.images.size(), g.samplers.size());
    233 for (size_t i = 0; i < g.textures.size(); ++i) {
    234 const GltfTexture &t = g.textures[i];
    235 printf(" texture [%zu] image %d, ", i, t.source);
    236 if (t.sampler < 0) {
    237 printf("default sampler\n");
    238 } else {
    239 const GltfSampler &s = g.samplers[static_cast<size_t>(t.sampler)];
    240 printf("sampler %d (mag %d, min %d, wrap %d/%d)\n", t.sampler, s.magFilter, s.minFilter, s.wrapS, s.wrapT);
    241 }
    242 }
    243 for (size_t i = 0; i < g.images.size(); ++i) {
    244 const GltfImage &im = g.images[i];
    245 printf(" image [%zu] \"%s\" %s, ", i, im.name.c_str(), nameOr(im.mimeType, "(no mimeType)"));
    246 if (im.bufferView >= 0)
    247 printf("%zu bytes in bufferView %d\n", g.bufferViews[static_cast<size_t>(im.bufferView)].byteLength, im.bufferView);
    248 else
    249 printf("uri %.60s\n", im.uri.c_str());
    250 }
    251  
    252 printf("nodes (%zu), scenes (%zu)\n", g.nodes.size(), g.scenes.size());
    253 std::vector<int> roots = g.rootNodes();
    254 if (!g.scenes.empty()) {
    255 int s = g.scene >= 0 ? g.scene : 0;
    256 printf("scene %d \"%s\"%s:\n", s, g.scenes[static_cast<size_t>(s)].name.c_str(), g.scene >= 0 ? " (default)" : "");
    257 } else {
    258 printf("no scenes: all root nodes:\n");
    259 }
    260 for (size_t i = 0; i < roots.size(); ++i) printNode(g, roots[i], "", i + 1 == roots.size(), true);
    261  
    262 size_t primitives = 0;
    263 int problems = verify(g, primitives);
    264 if (problems == 0)
    265 printf("check: read %zu primitive%s, all accessors and indices OK\n", primitives, primitives == 1 ? "" : "s");
    266 else
    267 printf("check: %d problem%s\n", problems, problems == 1 ? "" : "s");
    268 return true;
    269 }
    270  
    271 int main(int argc, char **argv) {
    272 #ifdef _WIN32
    273 // コンソールの出力をUTF-8にする(日本語のメッセージが文字化けしない様に)
    274 // switch the console output to UTF-8 (so the Japanese messages are not garbled)
    275 SetConsoleOutputCP(CP_UTF8);
    276 #endif
    277 bool all = false;
    278 int files = 0, failures = 0;
    279 for (int i = 1; i < argc; ++i) {
    280 if (std::strcmp(argv[i], "--all") == 0) {
    281 all = true;
    282 continue;
    283 }
    284 if (files++ > 0) printf("\n");
    285 if (!dump(argv[i], all)) ++failures;
    286 }
    287 if (files == 0) {
    288 fprintf(stderr, "使い方 / usage: gltf_dump [--all] file.glb [file2.gltf ...]\n");
    289 return 2;
    290 }
    291 return failures == 0 ? 0 : 1;
    292 }

ファイル: /dev/null | b/src/json.cc

前新
@@ -0,0 +1,301 @@
    1 #include "json.hh"
    2  
    3 #include <cmath>
    4 #include <cstdlib>
    5 #include <string>
    6  
    7 // 見つからないときに返すnull / the null returned when something is not found
    8 static const Json kNullJson;
    9 static const std::string kEmptyString;
    10  
    11 const std::string &Json::string() const { return kind == Type::String ? text : kEmptyString; }
    12  
    13 long long Json::integer(long long fallback) const {
    14 // 2^53までのdoubleは整数を正確に表せる / a double represents integers exactly up to 2^53
    15 if (kind != Type::Number || num != std::floor(num) || std::fabs(num) > 9007199254740992.0) return fallback;
    16 return static_cast<long long>(num);
    17 }
    18  
    19 size_t Json::size() const {
    20 if (kind == Type::Array) return array.size();
    21 if (kind == Type::Object) return object.size();
    22 return 0;
    23 }
    24  
    25 const Json &Json::operator[](size_t index) const {
    26 return kind == Type::Array && index < array.size() ? array[index] : kNullJson;
    27 }
    28  
    29 const Json *Json::find(std::string_view key) const {
    30 if (kind != Type::Object) return nullptr;
    31 // glTFのオブジェクトは小さいので順番に探せば十分 / glTF objects are small: a linear search is enough
    32 for (const JsonMember &m : object)
    33 if (m.key == key) return &m.value;
    34 return nullptr;
    35 }
    36  
    37 const Json &Json::operator[](std::string_view key) const {
    38 const Json *v = find(key);
    39 return v ? *v : kNullJson;
    40 }
    41  
    42 //------------------------------------------
    43 // パーサー(再帰下降) / the parser (recursive descent)
    44 //------------------------------------------
    45  
    46 class JsonParser {
    47 public:
    48 explicit JsonParser(std::string_view source) : s(source) {}
    49  
    50 bool parseDocument(Json &out) {
    51 // UTF-8のBOMは読み飛ばす(glTFでは禁止だが、付けるツールがある) / skip a UTF-8 BOM (forbidden in glTF, but some tools add one)
    52 if (s.substr(0, 3) == "\xEF\xBB\xBF") pos = 3;
    53 skipSpace();
    54 if (!parseValue(out)) return false;
    55 skipSpace();
    56 if (pos != s.size()) return fail("値の後に余分な文字 / unexpected characters after the value");
    57 return true;
    58 }
    59  
    60 // 「行:列: 理由」 / "line:column: reason"
    61 std::string errorMessage() const {
    62 int line = 1, column = 1;
    63 for (size_t i = 0; i < errorPos && i < s.size(); ++i) {
    64 if (s[i] == '\n') {
    65 ++line;
    66 column = 1;
    67 } else {
    68 ++column;
    69 }
    70 }
    71 return std::to_string(line) + ":" + std::to_string(column) + ": " + error;
    72 }
    73  
    74 private:
    75 static constexpr int kMaxDepth = 512; // 深すぎる入れ子でスタックが溢れないように / so deep nesting cannot overflow the stack
    76  
    77 bool fail(const char *message) {
    78 if (error.empty()) {
    79 error = message;
    80 errorPos = pos;
    81 }
    82 return false;
    83 }
    84  
    85 bool atEnd() const { return pos >= s.size(); }
    86 char peek() const { return atEnd() ? '\0' : s[pos]; }
    87  
    88 void skipSpace() {
    89 while (!atEnd() && (s[pos] == ' ' || s[pos] == '\t' || s[pos] == '\n' || s[pos] == '\r')) ++pos;
    90 }
    91  
    92 bool literal(std::string_view word) {
    93 if (s.substr(pos, word.size()) != word) return fail("不正な値 / invalid value");
    94 pos += word.size();
    95 return true;
    96 }
    97  
    98 bool parseValue(Json &out) {
    99 switch (peek()) {
    100 case '{': return parseObject(out);
    101 case '[': return parseArray(out);
    102 case '"': out.kind = Json::Type::String; return parseString(out.text);
    103 case 't': out.kind = Json::Type::Bool; out.flag = true; return literal("true");
    104 case 'f': out.kind = Json::Type::Bool; out.flag = false; return literal("false");
    105 case 'n': out.kind = Json::Type::Null; return literal("null");
    106 default:
    107 if (peek() == '-' || (peek() >= '0' && peek() <= '9')) return parseNumber(out);
    108 return fail(atEnd() ? "途中で終わっている / unexpected end of input" : "不正な値 / invalid value");
    109 }
    110 }
    111  
    112 bool parseObject(Json &out) {
    113 if (++depth > kMaxDepth) return fail("入れ子が深すぎる / nesting too deep");
    114 out.kind = Json::Type::Object;
    115 ++pos; // '{'
    116 skipSpace();
    117 if (peek() == '}') {
    118 ++pos;
    119 --depth;
    120 return true;
    121 }
    122 while (true) {
    123 skipSpace();
    124 if (peek() != '"') return fail("キー(文字列)が必要 / expected a key (string)");
    125 JsonMember member;
    126 if (!parseString(member.key)) return false;
    127 skipSpace();
    128 if (peek() != ':') return fail("「:」が必要 / expected ':'");
    129 ++pos;
    130 skipSpace();
    131 if (!parseValue(member.value)) return false;
    132 out.object.push_back(std::move(member));
    133 skipSpace();
    134 if (peek() == ',') {
    135 ++pos;
    136 continue;
    137 }
    138 if (peek() == '}') {
    139 ++pos;
    140 --depth;
    141 return true;
    142 }
    143 return fail("「,」か「}」が必要 / expected ',' or '}'");
    144 }
    145 }
    146  
    147 bool parseArray(Json &out) {
    148 if (++depth > kMaxDepth) return fail("入れ子が深すぎる / nesting too deep");
    149 out.kind = Json::Type::Array;
    150 ++pos; // '['
    151 skipSpace();
    152 if (peek() == ']') {
    153 ++pos;
    154 --depth;
    155 return true;
    156 }
    157 while (true) {
    158 skipSpace();
    159 Json item;
    160 if (!parseValue(item)) return false;
    161 out.array.push_back(std::move(item));
    162 skipSpace();
    163 if (peek() == ',') {
    164 ++pos;
    165 continue;
    166 }
    167 if (peek() == ']') {
    168 ++pos;
    169 --depth;
    170 return true;
    171 }
    172 return fail("「,」か「]」が必要 / expected ',' or ']'");
    173 }
    174 }
    175  
    176 // 16進数4桁(\uXXXXのXXXX) / four hex digits (the XXXX of \uXXXX)
    177 bool hex4(unsigned &value) {
    178 value = 0;
    179 for (int i = 0; i < 4; ++i) {
    180 char c = peek();
    181 unsigned digit;
    182 if (c >= '0' && c <= '9') digit = static_cast<unsigned>(c - '0');
    183 else if (c >= 'a' && c <= 'f') digit = static_cast<unsigned>(c - 'a' + 10);
    184 else if (c >= 'A' && c <= 'F') digit = static_cast<unsigned>(c - 'A' + 10);
    185 else return fail("\\uの後に16進数4桁が必要 / expected 4 hex digits after \\u");
    186 value = value * 16 + digit;
    187 ++pos;
    188 }
    189 return true;
    190 }
    191  
    192 // コードポイントをUTF-8で書く / write a code point as UTF-8
    193 static void appendUtf8(std::string &out, unsigned cp) {
    194 if (cp < 0x80) {
    195 out += static_cast<char>(cp);
    196 } else if (cp < 0x800) {
    197 out += static_cast<char>(0xC0 | (cp >> 6));
    198 out += static_cast<char>(0x80 | (cp & 0x3F));
    199 } else if (cp < 0x10000) {
    200 out += static_cast<char>(0xE0 | (cp >> 12));
    201 out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
    202 out += static_cast<char>(0x80 | (cp & 0x3F));
    203 } else {
    204 out += static_cast<char>(0xF0 | (cp >> 18));
    205 out += static_cast<char>(0x80 | ((cp >> 12) & 0x3F));
    206 out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
    207 out += static_cast<char>(0x80 | (cp & 0x3F));
    208 }
    209 }
    210  
    211 bool parseString(std::string &out) {
    212 ++pos; // '"'
    213 while (true) {
    214 if (atEnd()) return fail("文字列が閉じていない / unterminated string");
    215 char c = s[pos++];
    216 if (c == '"') return true;
    217 if (static_cast<unsigned char>(c) < 0x20) return fail("文字列の中に制御文字 / control character in a string");
    218 if (c != '\\') {
    219 out += c; // UTF-8のバイトはそのまま / UTF-8 bytes are copied as they are
    220 continue;
    221 }
    222 if (atEnd()) return fail("文字列が閉じていない / unterminated string");
    223 char e = s[pos++];
    224 switch (e) {
    225 case '"': out += '"'; break;
    226 case '\\': out += '\\'; break;
    227 case '/': out += '/'; break;
    228 case 'b': out += '\b'; break;
    229 case 'f': out += '\f'; break;
    230 case 'n': out += '\n'; break;
    231 case 'r': out += '\r'; break;
    232 case 't': out += '\t'; break;
    233 case 'u': {
    234 unsigned cp = 0;
    235 if (!hex4(cp)) return false;
    236 // U+10000以上は「サロゲートペア」二つの\uで書かれる / U+10000 and above are written as a surrogate pair
    237 if (cp >= 0xD800 && cp <= 0xDBFF) {
    238 unsigned low = 0;
    239 if (s.substr(pos, 2) != "\\u") return fail("サロゲートペアの後半がない / missing low surrogate");
    240 pos += 2;
    241 if (!hex4(low)) return false;
    242 if (low < 0xDC00 || low > 0xDFFF) return fail("不正なサロゲートペア / invalid surrogate pair");
    243 cp = 0x10000 + ((cp - 0xD800) << 10) + (low - 0xDC00);
    244 } else if (cp >= 0xDC00 && cp <= 0xDFFF) {
    245 return fail("不正なサロゲートペア / invalid surrogate pair");
    246 }
    247 appendUtf8(out, cp);
    248 break;
    249 }
    250 default: --pos; return fail("不正なエスケープ / invalid escape sequence");
    251 }
    252 }
    253 }
    254  
    255 bool digits() {
    256 if (!(peek() >= '0' && peek() <= '9')) return fail("数字が必要 / expected a digit");
    257 while (peek() >= '0' && peek() <= '9') ++pos;
    258 return true;
    259 }
    260  
    261 // JSONの数の文法を確かめてから、strtodで変換する(strtodは「C」ロケールで小数点が「.」)
    262 // Check JSON's number grammar first, then convert with strtod (in the "C" locale its decimal point is '.')
    263 bool parseNumber(Json &out) {
    264 size_t start = pos;
    265 if (peek() == '-') ++pos;
    266 if (peek() == '0') {
    267 ++pos; // 先頭の0の後に数字は続けられない / no digits after a leading 0
    268 } else if (!digits()) {
    269 return false;
    270 }
    271 if (peek() == '.') {
    272 ++pos;
    273 if (!digits()) return false;
    274 }
    275 if (peek() == 'e' || peek() == 'E') {
    276 ++pos;
    277 if (peek() == '+' || peek() == '-') ++pos;
    278 if (!digits()) return false;
    279 }
    280 std::string token(s.substr(start, pos - start)); // strtodには0終端の文字列が要る / strtod needs a 0-terminated string
    281 out.kind = Json::Type::Number;
    282 out.num = std::strtod(token.c_str(), nullptr);
    283 return true;
    284 }
    285  
    286 std::string_view s;
    287 size_t pos = 0;
    288 int depth = 0;
    289 std::string error;
    290 size_t errorPos = 0;
    291 };
    292  
    293 std::optional<Json> Json::parse(std::string_view text, std::string *error) {
    294 JsonParser parser(text);
    295 Json root;
    296 if (!parser.parseDocument(root)) {
    297 if (error) *error = parser.errorMessage();
    298 return std::nullopt;
    299 }
    300 return root;
    301 }

ファイル: /dev/null | b/src/json.hh

前新
@@ -0,0 +1,67 @@
    1 // 小さなJSONパーサー(glTFを読むため) / a small JSON parser (for reading glTF)
    2 #pragma once
    3  
    4 #include <cstddef>
    5 #include <optional>
    6 #include <string>
    7 #include <string_view>
    8 #include <vector>
    9  
    10 struct JsonMember;
    11  
    12 // JSONの値一つ:null・真偽値・数・文字列・配列・オブジェクトのどれか。
    13 // 読むだけ(書き出しはしない)。見つからない要素を取り出すとnullが返るので、
    14 // json["a"]["b"][0] のように確認なしで辿れる。
    15 // One JSON value: null, a boolean, a number, a string, an array or an object.
    16 // Read-only (no writing). Looking up something that does not exist gives null, so
    17 // json["a"]["b"][0] can be chained without checks.
    18 class Json {
    19 public:
    20 enum class Type { Null, Bool, Number, String, Array, Object };
    21  
    22 // テキスト全体を読む。失敗したらerrorに「行:列: 理由」を入れてstd::nullopt。
    23 // Parses a whole text. On failure stores "line:column: reason" in error and returns std::nullopt.
    24 static std::optional<Json> parse(std::string_view text, std::string *error = nullptr);
    25  
    26 Type type() const { return kind; }
    27 bool isNull() const { return kind == Type::Null; }
    28 bool isBool() const { return kind == Type::Bool; }
    29 bool isNumber() const { return kind == Type::Number; }
    30 bool isString() const { return kind == Type::String; }
    31 bool isArray() const { return kind == Type::Array; }
    32 bool isObject() const { return kind == Type::Object; }
    33  
    34 // 値を取り出す。型が違えばfallback / get the value; fallback if the type is different
    35 bool boolean(bool fallback = false) const { return kind == Type::Bool ? flag : fallback; }
    36 double number(double fallback = 0.0) const { return kind == Type::Number ? num : fallback; }
    37 float numberf(float fallback = 0.0f) const { return kind == Type::Number ? static_cast<float>(num) : fallback; }
    38 const std::string &string() const; // 文字列でなければ空 / empty if not a string
    39  
    40 // 整数として読む。整数でない・範囲外ならfallback(glTFの番号はすべて0以上の整数)
    41 // Reads an integer. fallback if it is not an integer or out of range (all glTF indices are integers ≥ 0)
    42 long long integer(long long fallback = -1) const;
    43  
    44 // 配列の要素数、またはオブジェクトのメンバー数 / number of array elements or object members
    45 size_t size() const;
    46 const Json &operator[](size_t index) const; // 配列の要素(なければnull) / array element (null if none)
    47 const Json &operator[](std::string_view key) const; // オブジェクトのメンバー(なければnull) / object member (null if none)
    48 const Json *find(std::string_view key) const; // メンバー、なければnullptr / member, nullptr if none
    49 bool has(std::string_view key) const { return find(key) != nullptr; }
    50  
    51 const std::vector<Json> &items() const { return array; } // 配列の要素 / array elements
    52 const std::vector<JsonMember> &members() const { return object; } // オブジェクトのメンバー(書かれた順) / members, in file order
    53  
    54 private:
    55 friend class JsonParser;
    56 Type kind = Type::Null;
    57 bool flag = false;
    58 double num = 0.0;
    59 std::string text;
    60 std::vector<Json> array;
    61 std::vector<JsonMember> object; // 不完全型のvectorはC++17から使える / a vector of an incomplete type is fine since C++17
    62 };
    63  
    64 struct JsonMember {
    65 std::string key;
    66 Json value;
    67 };

ファイル: a/src/main.cc | b/src/main.cc

前新
@@ -1,5 +1,5 @@
1 // 第12章:光源と複数のライト 1 // 第13章:glTFとGLB:ファイルの読み込み(このプログラムは第12章と同じ。新しいのは gltf_dump)
2 // Chapter 12: light casters and multiple lights 2 // Chapter 13: glTF and GLB: reading the file (this program is the same as in chapter 12; the new part is gltf_dump)
3 // 3 //
4 // 操作 / Controls: 4 // 操作 / Controls:
5 // WASD 前後左右に移動 / move forward, back, left, right 5 // WASD 前後左右に移動 / move forward, back, left, right
@@ -98,7 +98,7 @@ static const char *const kViewModeNames[] = {"all", "ambient", "diffuse", "specu
98   98  
99 int main() { 99 int main() {
100 Window window; 100 Window window;
101 if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 12")) return 1; 101 if (!window.create(1280, 720, "OpenGL Tutorial - Chapter 13")) return 1;
102   102  
103 std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag"); 103 std::optional<Shader> phong = Shader::load("shaders/phong.vert", "shaders/phong.frag");
104 std::optional<Shader> unlit = Shader::load("shaders/unlit.vert", "shaders/unlit.frag"); 104 std::optional<Shader> unlit = Shader::load("shaders/unlit.vert", "shaders/unlit.frag");


コメント(0)

まだコメントはありません。