36. TPS パート1:キャラクターとカメラ

RPGでパート6の2Dの半分が終わりました。
シリーズ最後のゲームは3Dに戻ります。
4章かけて作る小さな三人称シューティング(TPS)で、カメラが肩越しに見守る中、ライフルを持ってアリーナを走り回ります。
此の最初のパートでは、世界と其の中の体を作ります。
GLBの部品を並べるテキストファイルからアリーナを読み、パート4の影・PBR・後処理で描き、部品で出来た兵士を其処に置き、アニメーションのファイルではなくコードで動かし、決して壁の向こうを映さないカメラで追いかけます。

此の章には新しいOpenGLは殆どありません。
描くのは第19章のインスタンシング、第23章の影の地図、第24章のPBRとイメージベースドライティング、そして第25章のエンジンの部品です。
新しい呼び出しは、フラグメントを数える遮蔽クエリ1つだけです。
面白い所は幾何です。
視錐台カリング、レイと箱、レベルの中を滑らせる球、3次元の2本の骨のIK、そして「何が何処を向いているか」をたくさん考える事です。
コードは長いので、設計の判断を説明し、其れを担う部分だけを見せます。
残りはダウンロードにあります。

36.1 此の章で作る物

プログラムtpsは32 × 32 mのアリーナを開きます。
タイルの床、四隅に柱のある周りの壁、両端に階段のある真ん中の高い台、L字の壁2つ、低いコンクリートの遮蔽、木箱と樽です。
右肩越しに見た兵士を操作します:

兵士の右肩越しに見たアリーナ。光るランプの付いた高い柱2本の間にある、縞鋼板の階段の付いた真ん中の台へ歩いて行く。周りには青い帯の付いた壁、右に木箱と樽、雲のある青空、タイルの床に柔らかい影

動画では、後ろ向きに南の壁まで歩き(カメラが肩の方へ押し込まれます)、壁に沿って向きを変え、左肩に切り替え、其れから向きを変えながら東へ歩いて走ります:

操作:

  • W、A、S、D又は矢印キー:カメラの向きに対して移動。Shiftを押しながらで走る(前だけ)
  • マウス:見回す。Q:右肩と左肩を切り替える
  • B:当たり判定の箱とソケットを表示
  • C:カメラだけ回して、キャラクターを前から見る(移動と狙いは止まる)
  • K:カメラの当たり判定のオン・オフ。P:手続き的な姿勢のオン・オフ(読み込んだ儘の姿勢)
  • F3:時間と数。F4:視錐台カリングのオン・オフ
  • Tab:カーソルを放す・捕まえる。Esc:終了

キャラクターは未だ何にも当たりません。
壁を通り抜け、何も無い所を登ります。
当たり判定、重力、ジャンプ、階段は第37章、射撃と敵は第38章です。

全部新しく、games/tps/に入っています。
其のフォルダの外は何も変わりません:

  • CMakeLists.txt:実行ファイルtps
  • src/main.cc、src/game.hh:ウィンドウ、共有のGameデータ、フレーム
  • src/level.hh、src/level.cc:Level。レベルのファイルの読み込み、カリング付きのインスタンシングの描画
  • src/collision3d.hh、src/collision3d.cc:Aabb、レイ、rayAabb、raycast、sphereCast
  • src/frustum.hh、src/frustum.cc:Frustum。行列からの平面、球のテスト
  • src/renderer.hh、src/renderer.cc:Renderer。エンジンの部品で組んだパート4のフレームとFragmentCounter
  • src/character.hh、src/character.cc:CharacterRig、CharacterPose、手続き的な姿勢と腕のIK
  • src/third_person_camera.hh、src/third_person_camera.cc:ThirdPersonCamera
  • src/play_scene.hh、src/play_scene.cc:PlayScene。プレイヤーを動かしてフレームを描くシーン
  • shaders/instanced.vert:レベルの部品の頂点シェーダー
  • assets/models/:レベルの部品6つ、player.glb、rifle.glb。assets/levels/:arena.levelとpieces.level。assets/fonts/:ゲームのフォントのアトラス。LICENSE.txt(完成したファイルは章のZIPとアセットのZIPのch36/に入っています)
  • README.md:操作とファイル

36.2 ゲームのフォルダ

ビルドはどのゲームも使う雛形です(第27章で説明しました):

# 第36〜39章:三人称シューティング(TPS) / Chapters 36-39: the third-person shooter (TPS)
add_executable(tps
  src/main.cc
  src/collision3d.cc
  src/frustum.cc
  src/level.cc
  src/renderer.cc
  src/character.cc
  src/third_person_camera.cc
  src/play_scene.cc)
target_include_directories(tps PRIVATE src)
target_link_libraries(tps PRIVATE engine)
enable_warnings(tps)
set_working_directory(tps)

ウィンドウは1280 × 720で、RPGと同じくUIも其の解像度で描きます。
mainはレベル、2つのモデル、リグを読み、第25・26章の共有の物(スプライトバッチ、フォント、アクション付きのInput、固定ステップのGameLoop)を作ります:

  std::optional<Level> level = Level::load(argc > 1 ? argv[1] : "games/tps/assets/levels/arena.level");
  std::optional<Model> player = Model::load("games/tps/assets/models/player.glb");
  std::optional<Model> rifle = Model::load("games/tps/assets/models/rifle.glb");
  if (!level || !player || !rifle) return 1;
  std::optional<CharacterRig> playerRig = CharacterRig::find(*player);
  if (!playerRig) return 1;

フォントは、TPSの4章で要る漢字(移動、走る、肩など)を足したmono16のゲーム専用の写しで、第26章のアトラスと同じ生成器で作りました(もっと漢字が要る時は、アセットのZIPのextras/jis-level1-fonts/のmono16と入れ替えられます)。
RPGと同じく、共有のアトラスには触りません。

先に小さな修正を1つ。
SceneManager::pushはシーンを予約するだけで、予約は次のupdateで適用されます。
ゲームループの最初のフレームは普通、更新を1回も行いません(未だ時間が経っていない為)。
其の儘だと最初のフレームはシーンを描かず、真っ黒になります。
直ぐに予約を適用すれば直ります:

  SceneManager scenes;
  scenes.push(std::make_unique<PlayScene>(game));
  // pushは予約だけ:更新0回の最初のフレームも描けるように、ここで適用する(シーンの更新は呼ばれない)
  // push only queues the request: apply it now so that the first frame (which runs no update) has a scene to draw
  // (no scene's update is called)
  scenes.update(0.0f);

フレームのコールバックは、2Dのゲームと全く同じく、シーンを通して3Dの世界を描き、其の上にUIを描きます:

      [&](float alpha) {
        // 1. 3Dの世界(影 → 場面 → 後処理 → 画面) / 1. the 3D world (shadows → scene → post → screen)
        scenes.draw(alpha);
        // 2. UI:後処理の後の画面に、2Dの道具で(色はsRGBのまま、第25章) / 2. the UI: on top of the post-processed
        //    image with the 2D toolkit (colors stay sRGB, chapter 25)
        game.uiViewport = letterbox(window.width(), window.height(), game.screen.viewSize, false);
        game.uiViewport.apply();
        scenes.drawUi(alpha);
        scenes.drawFade(*batch, game.screen.matrix(), game.screen.viewSize);

scenes.drawは既定のフレームバッファに書く後処理のパスで終わります。
従って、UIを描く時には3Dの絵は既にトーンマッピングされ、sRGBに符号化されています。
UIの色は普通のsRGBの値で、第25章のスプライトバッチが期待する物です。

マウスと固定ステップ

カメラはマウスで固定ステップの更新の中で回ります。
移動の向き、キャラクターの向き、カメラの位置は全てシミュレーションの一部だからです。
でもwindow.mouseDelta()は前のpollEvents()からの動きで、其れは更新のステップごとではなくフレームごとに1回です。
1フレームに2ステップ走る時(30 fps)、両方のステップで使うとカメラは2倍回ってしまいます。
Gameは動きをフレームごとに1回だけ渡します:

  Vec2 unusedMouse = {0.0f, 0.0f}; // 更新のなかったフレームのマウスの動き / movement of frames that ran no update

  // このフレームのマウスの動き。1フレームに複数の更新ステップがあっても、最初のステップだけが受け取る
  // (window.mouseDelta()はフレームごとの値:ステップごとに使うと2回分回ってしまう)
  // This frame's mouse movement. With several update steps in one frame only the first step gets it
  // (window.mouseDelta() is per frame: using it in every step would turn twice as far)
  Vec2 takeMouseDelta() {
    if (lookFrame == frame || !window.cursorCaptured()) return {0.0f, 0.0f};
    lookFrame = frame;
    Vec2 delta = unusedMouse + window.mouseDelta();
    unusedMouse = {0.0f, 0.0f};
    return delta;
  }
  // 毎フレームの最後に呼ぶ:更新が1回もなかったフレーム(画面が60 Hzより速いと良くある)の動きを捨てずに、
  // 次のステップへ持ち越す
  // Call at the end of every frame: the movement of a frame that ran no update (common on screens faster than
  // 60 Hz) is carried over to the next step instead of being lost
  void keepUnusedMouse() {
    if (!window.cursorCaptured()) unusedMouse = {0.0f, 0.0f};
    else if (loop.stats().steps == 0) unusedMouse = unusedMouse + window.mouseDelta();
  }

frameは描いたフレームの数です。
フレームの最初のステップが動きを受け取ってフレームに印を付け、同じフレームの後のステップは0を受け取ります。
逆の場合も大事です。
60 Hzより速い画面では、更新のステップが1回も無いフレームがあり、其の動きが失われると、カメラはマウスを動かした分より少ししか回りません。
mainは毎フレームの最後にkeepUnusedMouseを呼び、ステップの無かったフレーム(loop.stats().steps == 0)の動きをunusedMouseに貯め、次に動きを受け取るステップに足します:

        game.keepUnusedMouse();

36.3 レベルのファイル

命令のファイル

アリーナはgames/tps/assets/levels/arena.levelに書いた、1行に1つの命令の並びです。
単位はメートル、+Yが上、北は−Zで、yaw 0のカメラが見る向きです。
最初に部品の種類を宣言します:

model floor    games/tps/assets/models/floor_tile.glb noshadow nocollide vary=0.06
model wall     games/tps/assets/models/wall.glb vary=0.05
model cover    games/tps/assets/models/cover.glb
model pillar   games/tps/assets/models/pillar.glb
model platform games/tps/assets/models/platform.glb
model stairs   games/tps/assets/models/stairs.glb
model crate    assets/models/crate.glb vary=0.12
model barrel   assets/models/barrel.glb

其れから置きます:

# 外壁(高さ3 m)と四隅の柱 / outer walls (3 m high) and corner pillars
row wall -14 0 -16.2 0 4 0 8
row wall -14 0 16.2 0 4 0 8
row wall -16.2 0 -14 90 0 4 8
row wall 16.2 0 -14 90 0 4 8
place pillar -16.2 0 -16.2 0
place pillar 16.2 0 -16.2 0
place pillar -16.2 0 16.2 0
place pillar 16.2 0 16.2 0

命令 意味
model name file.glb [noshadow] [nocollide] [vary=N] 部品の種類:1つのGLBで、インスタンシングで描く。オプションで影や当たり判定を切り、又は写しごとの明るさを最大Nだけ変える
box name x0 y0 z0 x1 y1 z1 部品のモデル座標の当たり判定の箱。何個でも良く、既定はモデルの箱
solid x0 y0 z0 x1 y1 z1 ワールド座標の見えない当たり判定の箱
place name x y z yaw 部品1つ
row name x y z yaw dx dz count count個の部品、1つ前から(dx, dz)ずつ
grid name x y z yaw step nx nz nx × nz個の部品、stepの間隔
spawn x y z yaw プレイヤーの出発点(yaw 0で北を向く)

アリーナ全体を上から見た物です。
同じファイルを同じ決まりで読むスクリプトで描きました:

上から見たアリーナ。−16から16 mまでの4 mの床のタイルが8 × 8、四辺に沿った壁と四隅の柱、真ん中に北と南に階段の付いた台と其の周りの柱4本、北西と南東にL字の壁2つ、低い遮蔽7つ、2つの角にまとまった木箱と台の近くの木箱、樽、そして南に北を向いた出発点。部品138個、当たり判定の箱85個

8種類の部品が138個です。
床のタイル64、壁38、柱10、台の半分2、階段2、遮蔽7、木箱9、樽6です。
6つのGLBは新しく(floor_tile、wall、cover、pillar、platform、stairs、あたしのスクリプトが作ります)、木箱と樽はassets/models/の共有の物です。
2つ目のファイルpieces.levelは各1つを並べるので、部品を見るのに便利です:./build/games/tps/tps games/tps/assets/levels/pieces.level。

pieces.levelのファイル。床のタイルの上の兵士の前に、青い帯の付いた壁、黄色と黒の危険の縞の付いた低い遮蔽、上にランプのある柱、縞鋼板の階段と黄色い縁の付いた台、木箱と樽

どの部品も共有のモデルの決まりに従い、原点は底面の真ん中にあるので、y = 0で床の上に置けます。
床のタイルだけは例外で、上面がy = 0です。
其の上面が歩く面だからです。
UVは面ごとにメートル単位で、第22章のmakeBoxと同じです。
従って、テクスチャは部品の大きさによらず、どの部品でも同じ大きさで繰り返します。

何故レベルエディタや、Blenderから書き出した大きなglTFの場面ではなく、テキストファイルなのでしょうか?
此の様なファイルは1分で読め、再コンパイルせずにエディタで変えられ、gitで差分を見られます。
第33章のRPGのマップのファイルと同じ理由で、多くのゲームも此処から始めます。
レベルはデータで、コードは部品しか知りません。

回すのは90°単位だけ

yawは90°の倍数でなければいけません。
手抜きではありません。
当たり判定の箱は軸に平行(AABB)で、Y軸周りに90°回した箱は、xとzが入れ替わるだけで、軸に平行な箱の儘です。
30°回すと傾いた箱になり、カメラのレイのテスト(と第37章のプレイヤーの当たり判定)は其れを扱えません。
モデル座標の箱を回すのは、角2つの回転と並べ直しです:

Aabb placeAabb(const Aabb &box, Vec3 position, int quarterTurns) {
  // rotateY(90°)は (x, z) → (z, −x)。角2つを回して並べ直せば良い / rotateY(90°) maps (x, z) → (z, −x): turn both
  // corners and sort them again
  Vec3 a = box.lo, b = box.hi;
  for (int i = 0; i < ((quarterTurns % 4) + 4) % 4; ++i) {
    a = {a.z, a.y, -a.x};
    b = {b.z, b.y, -b.x};
  }
  Vec3 lo = {std::fmin(a.x, b.x), std::fmin(a.y, b.y), std::fmin(a.z, b.z)};
  Vec3 hi = {std::fmax(a.x, b.x), std::fmax(a.y, b.y), std::fmax(a.z, b.z)};
  return {lo + position, hi + position};
}

rotateY(90°)は(x,z)を(z,−x)に写し、此れはplaceが描画に使う行列と全く同じなので、箱と絵は常に一致します。
((q % 4) + 4) % 4は、−90°を負の繰り返し回数ではなく、逆向きの1回(正の3回)にします。

読み込み

Level::loadは1行ずつ読み、RPGの読み込みと同じく、ファイルと行を付けてはっきり失敗します:

  auto fail = [&](const char *why) {
    fprintf(stderr, "%s:%d: %s\n", path.c_str(), lineNo, why);
    return std::nullopt;
  };
  // 部品を一つ置く(向きは90°単位) / places one piece (yaw in 90° steps)
  auto place = [&](int type, Vec3 p, float yawDegrees) -> bool {
    float q = yawDegrees / 90.0f;
    if (std::fabs(q - std::round(q)) > 1e-4f) return false;
    Piece piece;
    piece.type = type;
    piece.position = p;
    piece.quarterTurns = static_cast<int>(std::lround(q));
    piece.model = translate(p) * rotateY(radians(90.0f * static_cast<float>(piece.quarterTurns)));
    level.pieces.push_back(piece);
    return true;
  };

placeは3つの置く命令の全てが使い、rowとgridは其れをループで呼ぶだけです。
どの部品もモデル行列を読み込みの時に1回だけ作ります:𝐌=𝐓(𝐩)𝐑y(90°q)。
place wall 0 0 0 45という行があると、ゲームはgames/tps/assets/levels/arena.level:<行>: 向きは90°の倍数だけ / yaw must be a multiple of 90 degreesで止まります。

部品の箱から当たり判定

全部の行を読んだら、どの種類にも外接球と既定の箱を、どの部品にもワールド座標の箱を作ります:

  for (PieceType &type : level.types) {
    type.sphereCentre = 0.5f * (type.model->boundsMin + type.model->boundsMax);
    type.sphereRadius = length(0.5f * (type.model->boundsMax - type.model->boundsMin));
    if (type.boxes.empty()) type.boxes.push_back({type.model->boundsMin, type.model->boundsMax});
  }
  level.bounds = {{1e9f, 1e9f, 1e9f}, {-1e9f, -1e9f, -1e9f}};
  for (size_t i = 0; i < level.pieces.size(); ++i) {
    Piece &piece = level.pieces[i];
    PieceType &type = level.types[static_cast<size_t>(piece.type)];
    type.pieces.push_back(static_cast<int>(i));
    Vec4 c = piece.model * Vec4{type.sphereCentre.x, type.sphereCentre.y, type.sphereCentre.z, 1.0f};
    piece.sphereCentre = {c.x, c.y, c.z};
    piece.sphereRadius = type.sphereRadius;
    float shade = 1.0f + type.tintVariation * (2.0f * hash01(static_cast<std::uint32_t>(i) * 2654435761u) - 1.0f);
    piece.tint = {shade, shade, shade};
    for (const Aabb &b : type.boxes) {
      Aabb w = placeAabb(b, piece.position, piece.quarterTurns);
      if (type.collides) level.solids.push_back(w);
      level.bounds.lo = {std::fmin(level.bounds.lo.x, w.lo.x), std::fmin(level.bounds.lo.y, w.lo.y),
                         std::fmin(level.bounds.lo.z, w.lo.z)};
      level.bounds.hi = {std::fmax(level.bounds.hi.x, w.hi.x), std::fmax(level.bounds.hi.y, w.hi.y),
                         std::fmax(level.bounds.hi.z, w.hi.z)};
    }
  }

殆どの部品には、モデルの箱が良い当たり判定の形です。
壁は箱、木箱も箱、樽も十分近いです。
階段は違います。
階段の箱は高さ1.5 mの塊で、台の前の段がある筈の所に壁を作ってしまいます。
其の為arena.levelは階段に1段に1つ、6つの箱を与えます。
モデルを作るあたしのスクリプトが、作る時に表示する物です:

# 階段:段ごとの箱(モデルを作った時に表示した値) / the stairs: one box per step (printed when the model was made)
box stairs -1 0 -1.5 1 0.25 1.5
box stairs -1 0 -1.5 1 0.5 1
box stairs -1 0 -1.5 1 0.75 0.5
box stairs -1 0 -1.5 1 1 0
box stairs -1 0 -1.5 1 1.25 -0.5
box stairs -1 0 -1.5 1 1.5 -1

どの箱も階段の後ろ(z = −1.5、台の側)から其の段の前の縁まで伸び、1つ前より0.25 m高く、0.5 m短くなります。
床は逆です。
タイルはnocollideで、代わりに見えない厚い箱が1つあります:

# 床:8 × 8枚の4 mタイル(当たり判定は1枚の厚い箱:薄い箱は落ちる速さですり抜ける)
# floor: 8 × 8 tiles of 4 m (collision is one thick box: thin boxes can be tunnelled at falling speed)
grid floor -14 0 -14 0 4 8 8
solid -16 -1 -16 16 0 16

第37章で重力が付いた時、厚さ1 mの箱は0.2 mのタイルよりずっと通り抜けにくく、1つの箱は64個より安いです。
合計は85個です。
地面1、壁38、柱10、台の半分2、段12、遮蔽7、木箱9、樽6です。
プログラムは読み込む時に数を表示します:

games/tps/assets/levels/arena.level: 8 piece types, 138 pieces, 85 collision boxes

此の章ではレベルは箱を持っているだけで、最初に使うのはカメラです。

36.4 部品の種類ごとに描画1回

データ

PieceTypeは1つのGLBと其の種類に属する全てで、Pieceは置いた1つです:

// 部品の種類:一つのGLB / a piece type: one GLB
struct PieceType {
  std::string name;
  std::optional<Model> model;
  std::vector<Aabb> boxes;      // モデル座標の当たり判定(空ならモデルの箱) / model-space collision (empty = bounds)
  bool castsShadow = true;
  bool collides = true;
  float tintVariation = 0.0f;   // インスタンスごとの明るさのばらつき / per-instance brightness variation
  Vec3 sphereCentre;            // モデル座標の外接球 / model-space bounding sphere
  float sphereRadius = 0.0f;
  Buffer instances;             // InstanceData × 置いた数(GL_DYNAMIC_STORAGE_BIT) / InstanceData × placements
  std::vector<int> pieces;      // この種類の部品(Level::piecesの番号) / pieces of this type (indices)
};

// 置いた部品一つ / one placed piece
struct Piece {
  int type = 0;
  Vec3 position;
  int quarterTurns = 0; // Y軸周りに90°単位 / about Y in 90° steps
  Mat4 model;
  Vec3 tint = {1.0f, 1.0f, 1.0f};
  Vec3 sphereCentre;    // ワールドの外接球(カリング用) / world-space bounding sphere (for culling)
  float sphereRadius = 0.0f;
};

tintは写しごとに少しだけ明るさを変えます(vary=のオプション)。
部品の番号のハッシュから作るので、アリーナは毎回同じに見えます。
床のタイルは最大6 %、壁は5 %、木箱は12 %変わります。
同じタイルを並べた「コピー&ペースト」の見た目を、ただで崩せます。

種類ごとにインスタンスのバッファ1つ

138個の部品を1つずつ描くと、描画呼び出しは168回になります。
プリミティブを幾つか持つモデルがある為です(柱は3つ:柱其の物、鉄の笠、ランプ。台、階段、樽は2つずつ)。
第19章では、1つのメッシュの写しを1回の呼び出しでたくさん描く方法を見ました。
写しごとに行列と色を持つインスタンスのバッファと、glDrawElementsInstancedです。
レベルは正に其れを、種類ごとに1つのバッファで行います。
バッファは読み込みの時に1回、置いた数だけの大きさで作ります:

  for (PieceType &type : level.types) {
    if (type.pieces.empty()) continue;
    type.instances = Buffer(nullptr, static_cast<GLsizeiptr>(type.pieces.size() * sizeof(InstanceData)),
                            GL_DYNAMIC_STORAGE_BIT);
    type.model->setInstanceBuffer(type.instances, sizeof(InstanceData), kInstanceLayout);
  }

GL_DYNAMIC_STORAGE_BITで後からglNamedBufferSubDataが使え(第25章)、setInstanceBufferは第19章の配置でバッファを全てのプリミティブのVAOに繋ぎます。
行列は位置4〜7、色は8、除数は1です。
InstanceDataは76バイト(行列64、色12)なので、138個全部でも10,488バイトしかありません。

頂点シェーダー

エンジンにはインスタンシングの頂点シェーダーphong_instanced.vertがありますが、其れには未だ第19章の小惑星の公転が入っていて、全てのインスタンスを時間と共にY軸周りに回します。
ゲームは自分の物を持ちます。
phong.vertに2つのインスタンスの属性を足しただけの物です:

#version 460 core
// レベルの部品のインスタンシング(第19章):phong.vertにインスタンスの行列と色を足しただけ(第19章の小惑星の公転なし)。
// フラグメントシェーダーはエンジンのpbr.frag
// Instancing for the level pieces (chapter 19): phong.vert plus the per-instance matrix and color (without the
// chapter 19 asteroid orbit). Fragment shader: the engine's pbr.frag
layout(location = 0) in vec3 aPosition;
layout(location = 1) in vec3 aNormal;
layout(location = 2) in vec2 aUv;
layout(location = 3) in vec4 aTangent;       // 接線(第22章) / tangent (chapter 22)
layout(location = 4) in mat4 aInstanceModel; // 4〜7 / locations 4..7
layout(location = 8) in vec3 aInstanceColor; // pbr.fragがベースカラーに掛ける / pbr.frag multiplies the base color

// カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
// The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
layout(std140, binding = 0) uniform Camera {
  mat4 uView;
  mat4 uProj;
  vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
  float uTime;   // アニメーションの時間(秒) / animation time (seconds)
};

uniform mat4 uModel;        // モデルの中のノードの行列 / the node's matrix inside the model
uniform mat3 uNormalMatrix; // その法線行列 / its normal matrix

out vec3 vWorldPos;
out vec3 vNormal;
out vec2 vUv;
out vec4 vTangent;
out vec3 vTint;

void main() {
  mat4 model = aInstanceModel * uModel;
  vec4 world = model * vec4(aPosition, 1.0);
  vWorldPos = world.xyz;
  // 部品はY軸周りに回すだけ(拡大縮小なし)なので、法線は行列の3×3で回せば良い
  // Pieces are only turned about Y (no scaling), so the 3×3 part rotates the normal correctly
  vNormal = mat3(aInstanceModel) * (uNormalMatrix * aNormal);
  vUv = aUv;
  mat3 m = mat3(model);
  vTangent = vec4(m * aTangent.xyz, aTangent.w * (determinant(m) < 0.0 ? -1.0 : 1.0));
  vTint = aInstanceColor;
  gl_Position = uProj * uView * world;
}

uModelはモデルの中のノードの行列で(第19章の連鎖:インスタンス × ノード × 頂点)、vTintはpbr.fragがベースカラーに掛けるインスタンスごとの色です。
phong.vertは代わりにユニフォームuTintから其れを設定します。
法線はインスタンスの行列の左上の3 × 3で回します。
其れが正しいのは、部品を回すだけで決して拡大縮小しないからです。
不均一な拡大縮小があれば、第10章の様に逆行列の転置が要ります。
プログラムはエンジンのpbr.fragとリンクするので、部品は他の全てと同じマテリアル、影、IBLを受けます。

描く

毎フレーム、種類ごとに、見える部品をバッファに写し、プリミティブごとに1回のインスタンシングの呼び出しで描きます:

LevelDrawStats Level::draw(const Shader &shader, const Texture2D &white, const Frustum &view) {
  LevelDrawStats stats;
  // ファイルと逆の順:床(全部の後ろ)を最後に。GPUは手前の物が先に描かれていれば、隠れたフラグメントを
  // シェーダーの前に捨てられる(早い深度テスト) / reverse file order: the floor (behind everything) last. A GPU can
  // reject hidden fragments before shading them when nearer things were drawn first (early depth test)
  for (auto it = types.rbegin(); it != types.rend(); ++it) {
    PieceType &type = *it;
    scratch.clear();
    for (int i : type.pieces) {
      const Piece &piece = pieces[static_cast<size_t>(i)];
      ++stats.total;
      if (!view.sphereVisible(piece.sphereCentre, piece.sphereRadius)) continue;
      scratch.push_back({piece.model, piece.tint});
    }
    if (scratch.empty()) continue;
    stats.visible += static_cast<int>(scratch.size());
    stats.drawCalls += static_cast<int>(type.model->primitiveCount());
    type.instances.update(scratch.data(), static_cast<GLsizeiptr>(scratch.size() * sizeof(InstanceData)));
    type.model->drawInstanced(shader, white, static_cast<GLsizei>(scratch.size()), Shading::Pbr);
  }
  return stats;
}

全ての種類に見える部品が1つ以上あれば、レベル全体で1 + 1 + 1 + 3 + 2 + 2 + 1 + 2 = 13回の描画呼び出しで、168回ではありません。
Shading::PbrのdrawInstancedはプリミティブごとにPBRのマテリアルとテクスチャを設定します(第24章)。
シェーダーは先に繋いでおく必要があります。
Modelの描く関数は決してuse()を呼ばないので、第14章からの全ての描画と同じく、PlaySceneが先にr.pbrInstanced->use()を呼びます。

種類はファイルと逆の順に描くので、最初に宣言した床が最後になります。
床は画面の殆どを覆い、他の全ての後ろにあります。
其の前にある物が既に深度バッファに入っていれば、GPUは隠れた床のフラグメントを、フラグメントシェーダーを走らせる前に捨てられます(早い深度テスト、第8章)。
PBR、IBL、影のフィルタリングがあると、其のフラグメントシェーダーがフレームで一番高い物です。

影のパスは1つずつ

影のパスは同じ部品を太陽から描きますが、インスタンシングは使えません:

LevelDrawStats Level::drawShadows(const Shader &shadow, const Texture2D &white, const Frustum &lightBox) const {
  LevelDrawStats stats;
  for (const PieceType &type : types) {
    for (int i : type.pieces) {
      const Piece &piece = pieces[static_cast<size_t>(i)];
      ++stats.total;
      if (!type.castsShadow || !lightBox.sphereVisible(piece.sphereCentre, piece.sphereRadius)) continue;
      ++stats.visible;
      stats.drawCalls += static_cast<int>(type.model->primitiveCount());
      type.model->drawDepth(shadow, piece.model, white);
    }
  }
  return stats;
}

エンジンのModel::drawDepthにはインスタンシングの版が無く、エンジンのshadow.vertにもインスタンスの属性がありません。
影のプログラムでdrawInstancedを呼んでも駄目です。
影のプログラムに無いuMaterial.*のユニフォームを設定し、Shader::setが其の一つ一つに警告を表示します。
此れはエンジンの穴で、わざと残しました。
埋めるには、インスタンシングのshadow.vertと、インスタンスの数を受け取るdrawDepthが要ります。
良い練習になり、絵は変わりません(課題7)。
従って、影を落とす74個(noshadowの床のタイル以外の全て)は、影のパスで部品ごと・プリミティブごとに1回、104回の描画呼び出しになります。
床は影を落とす必要がありません。
其の下には何も無いからです。

36.5 視錐台カリング

レベルは動かないので、全てのインスタンスを1回だけ送り、画面の外の物はGPUに捨てさせる事も出来ます。
頂点シェーダーの後のクリッピングが、其れをただで行います。
CPUでのカリングは、見える筈の無い部品の頂点の仕事と三角形の準備を省き、考え方を目に見える物にします。
F3が描いた部品の数を表示します。

行列から平面

点が見えるのは、クリップ座標𝐜=𝐌𝐩(𝐌=𝐏𝐕)が−cw≤cx,cy,cz≤cwを満たす時です(線型代数 第12章)。
𝐌のi行目を𝐫iと書くと、cx=𝐫0⋅𝐩、cw=𝐫3⋅𝐩です。
すると左の平面cx≥−cwは

(𝐫3+𝐫0)⋅𝐩≥0

で、残りの5枚は𝐫3−𝐫0(右)、𝐫3±𝐫1(下、上)、𝐫3±𝐫2(手前、奥)です。
𝐩=(x,y,z,1)なら、どれもax+by+cz+d≥0と読めます。
法線(a,b,c)が視錐台の内側を向いた平面です。
行列から平面を直接読み取る此の方法は、Gribb–Hartmann法と呼ばれます:

Frustum Frustum::fromMatrix(const Mat4 &m) {
  // クリップ座標 c = M·p。視錐台の中は −w ≤ x, y, z ≤ w。例えば左の平面 x ≥ −w は (行3 + 行0)·p ≥ 0
  // Clip coordinates c = M·p. Inside the frustum −w ≤ x, y, z ≤ w. E.g. the left plane x ≥ −w is (row 3 + row 0)·p ≥ 0
  auto row = [&](int r) { return Vec4{m.at(r, 0), m.at(r, 1), m.at(r, 2), m.at(r, 3)}; };
  Vec4 r0 = row(0), r1 = row(1), r2 = row(2), r3 = row(3);
  Frustum f;
  f.planes[0] = r3 + r0; // 左 / left
  f.planes[1] = r3 - r0; // 右 / right
  f.planes[2] = r3 + r1; // 下 / bottom
  f.planes[3] = r3 - r1; // 上 / top
  f.planes[4] = r3 + r2; // 手前 / near
  f.planes[5] = r3 - r2; // 奥 / far
  for (Vec4 &p : f.planes) {
    float len = std::sqrt(p.x * p.x + p.y * p.y + p.z * p.z);
    p = (1.0f / len) * p; // 距離をメートルで比べられるように / so distances compare in meters
  }
  return f;
}

bool Frustum::sphereVisible(Vec3 c, float radius) const {
  for (const Vec4 &p : planes)
    if (p.x * c.x + p.y * c.y + p.z * c.z + p.w < -radius) return false;
  return true;
}

平面を法線の長さで割っても、点が平面のどちら側かは変わりません。
でも其れでax+by+cz+dがメートル単位の符号付きの距離になります(線型代数 第4章)。
すると球が見えないのは、中心がどれか1枚の平面から半径より遠く外にある時、丁度其の時です。
テストは控えめです。
視錐台の角のすぐ外にあり、2枚の平面の外に其々半径より少しだけ出ている球は、見えないのに通ります。
其の代償は少し余分に描く事で、部品が消える事は決してありません。
向きとしては正しい方です。

取り出し方はクリップ座標の定義しか使わないので、どんな投影でも使えます。
レンダラーは2回使います。
カメラと、影を落とす物をカリングする為の太陽の正射影の光の箱です。

外接球

種類ごとの球はモデル座標の箱を囲み(中心は真ん中、半径は対角線の半分)、部品ごとにモデル行列で中心を動かします。
回転は球を変えないので、90°の回転は全く関係ありません。
其れが球を使う理由です。
壁の球の半径は22+1.52+0.22≈2.51 mで、薄い壁其の物よりずっと大きいですが、球のテストは平面ごとに内積1回です。

出発点の後ろのカメラが北を見ると、138個の内100個が通ります。
南東の角に立って南西の壁の方を見ると41個だけ、南西の角からアリーナ全体を見渡すと130個です。
F4は、6枚の平面が全て(0,0,0,1)の視錐台を渡してカリングを切ります。
どの距離も1になり、どの球も通ります:

  // F4:カリングなし(全部の部品をインスタンスのバッファへ)と比べる。平面(0, 0, 0, 1)なら全部が内側
  // F4: compare with no culling (every piece goes into the instance buffers). Planes (0, 0, 0, 1) keep everything in
  Frustum everything;
  for (Vec4 &plane : everything.planes) plane = {0.0f, 0.0f, 0.0f, 1.0f};
  levelStats = g.level.draw(*r.pbrInstanced, r.white, culling ? r.viewFrustum() : everything);

絵は変わりません。
此れがカリングが動いている最初の確認です。

36.6 レンダラー:道具箱としてのパート4

設定

第25章でパート4のフレームはShadowMapとPostChainとしてエンジンに移りました。
ゲームのRendererは其れらを空、IBL、シェーダーと組み合わせます。
此のシリーズの全てはllvmpipeでも試すので、ソフトウェアのラスタライザーに合わせた設定を選びます:

// 速さと見た目の兼ね合い(llvmpipeでも動くように既定は軽め) / speed vs. quality (light defaults so that llvmpipe
// copes)
struct RenderSettings {
  int shadowMapSize = 2048;
  float shadowDistance = 20.0f;   // 影を付ける範囲(カメラからm) / shadows cover this far from the camera (m)
  bool shadows = true;
  // MSAAなし、R11F_G11F_B10F(RGBA16Fの半分の大きさ)、ブルーム3組 / no MSAA, R11F_G11F_B10F (half the size of
  // RGBA16F), 3 bloom pass pairs
  PostChainSettings post = {.samples = 0, .format = GL_R11F_G11F_B10F, .bloomPasses = 3};
};

MSAAなし、GL_R11F_G11F_B10F(3つの浮動小数点数を32ビットに詰めた物で、GL_RGBA16Fの半分の大きさ、第21章)のHDRのターゲット、ブルームのぼかしは3組です。
本物のGPUならMSAAを入れます。
此れらの設定の重さは第39章で測ります。

作る

createは全てのプログラムを読み、全てのユニフォームブロックをC++の構造体と比べます。
第19章からの決まりです:

  r->pbr = Shader::load("engine/shaders/phong.vert", "engine/shaders/pbr.frag");
  r->pbrInstanced = Shader::load("games/tps/shaders/instanced.vert", "engine/shaders/pbr.frag");
  r->shadow = Shader::load("engine/shaders/shadow.vert", "engine/shaders/shadow.frag");
  r->unlit = Shader::load("engine/shaders/unlit.vert", "engine/shaders/unlit.frag");
  r->skybox = Shader::load("engine/shaders/skybox.vert", "engine/shaders/skybox.frag");
  // 空は色の画像なのでsRGB(第21章) / the sky is a color image: sRGB (chapter 21)
  r->sky = Cubemap::loadDirectory("assets/textures/sky", ".png", true);
  if (!r->pbr || !r->pbrInstanced || !r->shadow || !r->unlit || !r->skybox || !r->sky) return nullptr;
  // 新しいプログラムも含めて、全部のブロックの大きさをC++の構造体と比べる(第19章からの決まり)
  // Check every block of every program (including the new one) against the C++ structs (the rule since chapter 19)
  for (const Shader *s : {&*r->pbr, &*r->pbrInstanced, &*r->shadow, &*r->unlit, &*r->skybox})
    if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)) ||
        !s->checkUniformBlock("Post", sizeof(PostBlock)) || !s->checkUniformBlock("Shadow", sizeof(ShadowBlock)))
      return nullptr;

  // IBLを作る前にシームレスなフィルタリング(第18・24章) / seamless filtering before building the IBL (ch. 18, 24)
  glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
  r->ibl = Ibl::build(*r->sky);
  r->shadowMap.emplace(settings.shadowMapSize);
  r->post = PostChain::create(width, height, settings.post);
  if (!r->ibl || !r->shadowMap->complete() || !r->post) return nullptr;

空は色の画像なのでsRGBとして読み、IBLの地図を作る前にシームレスなキューブマップのフィルタリングを入れ(第24章)、IBLは場面の後ろに描くのと同じ空から計算します。
Rendererはunique_ptrで返します。
中のGpuTimerとUniformBufferが移動出来ないからです。

パスに分けたフレーム

フレームはパスの順にレンダラーを呼び、PlaySceneは呼び出しの間で描きます:

  1. beginFrame(view, lights)はCameraとLightsのブロックを書き、カメラの視錐台を取り出し、露出とブルームの強さを設定します。
  2. beginShadows()は光の箱を合わせて深度のパスを始めます。ゲームは影を落とす物を描き、endShadows()を呼びます。
  3. beginScene()は深度の地図をユニット5に繋ぎ、HDRのフレームバッファに切り替えてクリアし、空(ユニット3)とIBL(ユニット9〜11)を繋ぎます。
  4. ゲームは不透明な物を描き、drawSky()とendScene()を呼びます。後者は解決とブルームのぼかしを行います。
  5. present()は第21章の後処理のパス(露出、トーンマッピング、sRGB)を既定のフレームバッファに走らせます。

光は第21・24章の昼です。
太陽は(−0.5,−1,−0.35)から色(2.6,2.45,2.2)で、他は全て空のIBLです。

影をカメラに合わせる

第23章では光の箱を、場面全体を囲む球か、Jでカメラの視錐台の手前数メートルを囲む球に合わせました。
エンジンのfrustumSphereは後者を行い、ゲームは手前20 mを頼みます:

bool Renderer::beginShadows() {
  // 光の箱をカメラの視錐台の0.1〜shadowDistance mを囲む球に合わせる(第23章のJ、エンジンのfrustumSphere)。
  // 球なのでカメラが回っても箱の大きさは同じ、中心はテクセル単位で動く → 影の縁がちらつかない
  // Fit the light box to the sphere around 0.1..shadowDistance m of the camera frustum (chapter 23's J, the engine's
  // frustumSphere). A sphere keeps the box size constant while the camera turns, and its center moves in whole texels:
  // shadow edges do not shimmer
  BoundingSphere fit = frustumSphere(current.eye, current.forward, current.fovY, current.aspect, current.nearPlane,
                                     settings.shadowDistance);
  shadowTimer.begin();
  bool draw = shadowMap->begin(sunDirection, fit, ShadowBias{}, ShadowFilter::Pcf3x3, settings.shadows);
  lightBox = Frustum::fromMatrix(shadowMap->block().lightSpace);
  if (draw) {
    shadow->use();
    shadow->set("uAlphaMask", 0);
  } else {
    shadowTimer.end();
  }
  return draw;
}

縦の視野角55°、16:9のウィンドウでの数字です。
20 mでの奥の長方形は、半分の高さが20tan27.5°=10.41 m、半分の幅が10.41⋅169=18.51 mです。
8つの角の平均は視線の上の0.1+202=10.05 mにあり、奥の角は其処から9.95 m先なので

r=18.512+10.412+9.952≈23.45 m,s=2⋅23.452048≈22.9 mm

此れがF3の帯の「shadow texel 22.9 mm」です。
カメラが動いても回っても半径は変わらないので、第23章のテクセルのスナップで、歩いている間も影の縁はじっとしています。

此のアリーナで其れが何をもたらすか、正直に言いましょう。
レベル全体を囲む球(箱はxとzで±16.66 m、yで−0.2〜3.6 mに届きます)の半径は16.662+16.662+1.92≈23.64 mで、テクセルは23.1 mmになります。
殆ど同じです。
アリーナが小さいので、視野の手前20 mで殆どが入ってしまいます。
其れでもゲームには視錐台に合わせるのが正しい選択です。
大きさがレベルに依らないからです。
10倍大きなレベルでも同じ22.9 mmのテクセルで、レベル全体の球なら10倍に育ちます。
20 mより先には影がありませんが、其の距離では殆ど見えません。
カスケード(課題5)は、最初の地図の後ろにもっと地図を置きます。

beginShadowsは光の行列も同じfromMatrixでFrustumにするので、影のパスは光の箱の外の物を飛ばせます。
此のアリーナでは箱が殆ど全てを覆います(36.12のF3の帯では74個全部が中にあります)。
もっと大きなレベルなら、殆どを飛ばすでしょう。

フラグメントを数える:GL_SAMPLES_PASSED

llvmpipeで測った時間は、CPUが他に何をしているかで大きく揺れるので、フレームの2つの版を比べるのには向きません。
「此のフレームはどれだけ仕事をしたか」のもっと良い目安は、深度テストを生き残ったフラグメントの数です。
OpenGLは其れを遮蔽クエリで数えられます:

FragmentCounter::FragmentCounter() { glCreateQueries(GL_SAMPLES_PASSED, kQueries, queries); }

FragmentCounter::~FragmentCounter() { glDeleteQueries(kQueries, queries); }

void FragmentCounter::begin() {
  if (pending[next]) return; // 前の結果がまだ:今回は数えない / previous result not read yet: skip
  glBeginQuery(GL_SAMPLES_PASSED, queries[next]);
  running = true;
}

void FragmentCounter::end() {
  if (!running) return;
  glEndQuery(GL_SAMPLES_PASSED);
  pending[next] = true;
  next = (next + 1) % kQueries;
  running = false;
}

long long FragmentCounter::latest() {
  for (int i = 0; i < kQueries; ++i) {
    int k = (next + i) % kQueries; // 古い順 / oldest first
    if (!pending[k]) continue;
    GLint ready = 0;
    glGetQueryObjectiv(queries[k], GL_QUERY_RESULT_AVAILABLE, &ready);
    if (!ready) continue;
    GLuint64 v = 0;
    glGetQueryObjectui64v(queries[k], GL_QUERY_RESULT, &v);
    value = static_cast<long long>(v);
    pending[k] = false;
  }
  return value;
}

ターゲットが違うだけで、第19章のGpuTimerと全く同じ仕組みです:

  • glCreateQueries(GL_SAMPLES_PASSED, 4, queries)はサンプルを数えるクエリのオブジェクトを4つ作ります。
  • glBeginQuery(GL_SAMPLES_PASSED, id)とglEndQuery(GL_SAMPLES_PASSED)で数える描画を挟みます。其の間に深度テストとステンシルテストを通った全てのサンプルが1ずつ足されます。MSAAが無ければサンプルはフラグメントです。
  • 1つのターゲットで同時に動けるクエリは1つだけですが、違うターゲットは重なっても構いません。場面のGpuTimer(GL_TIME_ELAPSED)とフラグメントの数は同時に動きます。
  • glGetQueryObjectiv(id, GL_QUERY_RESULT_AVAILABLE, &ready)は待たずに尋ねます。glGetQueryObjectui64v(id, GL_QUERY_RESULT, &v)は64ビットの数を読み、準備が出来ていなければ待つので、readyの後だけで呼びます。
  • 4つを順に使うので、CPUはGPUを決して待ちません。表示する値は数フレーム前の物です。

GL_ANY_SAMPLES_PASSEDははい・いいえの版で、本物のエンジンは遮蔽カリングに使います。
色と深度の書き込みを切って外接箱を描き、1つのサンプルも通らなければ次のフレームで其の物を飛ばします。
数えるのは場面のパス全体で、空とデバッグの線も含みます。
時間と違い、同じ視点なら値は毎回全く同じなので、llvmpipeでの正直なA/Bの目安になります。

36.7 キャラクター:階層の中の部品

何故スキンメッシュではないのか

ゲームのキャラクターは普通スキンメッシュです。
1つの繋がったメッシュで、どの頂点も骨格の幾つかの関節に重み付きで結び付けられ、関節の行列の一覧で頂点シェーダーの中で変形し、アニメーションの道具から書き出したクリップで動きます。
glTFは其の全て(スキン、関節、アニメーション)を持てますが、第13章と第14章のローダーはスキンとアニメーションを読み飛ばします。
スキニングには関節の番号と重みを持つ頂点シェーダーと、其れだけで1章が要ります。

其の為、兵士は第14章の風車と同じ作り方です。
ノードの階層の中の固い部品です。
どの部品も自分のノードの上の箱のメッシュで、コードはノードの平行移動と回転を書いて兵士を動かします。
代わりに関節は変形しません。
膝では2つの箱が互いに回るだけです。
四角い兵士には其れで十分で、アニメーションを全部読みやすい普通のコードに出来ます。
本物のエンジンはスキニング、アニメーションのクリップ、其の間のブレンドを使います。
SlangとVulkanのシリーズで、今ある物の上にスキニングを足せます。

player.glb

あたしのもう一つのスクリプトが兵士を作ります。
休みの姿勢(読み込んだ儘)では、腕を下ろして+Zを向いて立っています:

後ろから見たプレイヤーの休みの姿勢。関節は本当の位置の白い点で、0.95 mのHips、膝の付いた脚、Spine、Head、肩・肘・手、そしてソケットは菱形:CameraPivot、Weapon、両手。横にノードの木と、各ノードの親に対する平行移動。CharacterからHips、脚と膝、HeadとSpine、両腕とWeapon、ルートの上のCameraPivotまで

  • Characterがルートで、足元にあります。
  • (0, 0.95, 0)のHipsは骨盤を持ち、両脚と背骨の親です。
  • LegL/LegRは股関節で、其の0.44 m下にKneeL/KneeRがあります。Spineは腰のすぐ上にあり、其の下にHead、ShoulderL/ShoulderR、肘、手があります。
  • どの関節のノードも丁度其の回転の中心にあり、メッシュは其処から−Yに沿って垂れています。ノードを回すと、部品が関節の周りに回ります。

モデルはglTFの決まりで+Zを向くので、キャラクターの左は+Xです。
右手系で+Yを上にして+Zの方を見ると、+Xは左にあります。
どちら向きにも間違えやすいので、コードは大事な所で毎回「+Xはキャラクターの左」と書いています。

ソケット

4つのノードにはメッシュが全くありません。
ソケットで、第14章で街灯の光の為に紹介した空のノードです。
アートが決め、コードが名前で探す場所です。

  • CameraPivot(0, 1.55, 0)はルートの上にあり、カメラが周りを回る点です。腰ではなくルートの子なのはわざとで、歩いても揺れず、カメラが落ち着きます。
  • Weaponは背骨に対して(−0.08, 0.28, 0.32)で、ライフルを持つ場所です。胸の少し右の前です。背骨の上にあるので、狙いと一緒に上下します。
  • HandL、HandR:腕の先で、IKが動かす点です。
  • 原点がピストルグリップのrifle.glbには、第38章で弾が出るMuzzle(0, 0.05, 0.62)と、左手が行くForegrip(0, −0.01, 0.16)があります。

ソケットのワールドの位置は、モデルの変換 × モデルの中のノードの行列を原点に掛けた物です。
カメラの注視点なら:

Vec3 PlayScene::cameraPivot() const {
  // CameraPivotソケット(空のノード)のワールドの位置:モデル行列 × ノードの行列の原点
  // The world position of the CameraPivot socket (an empty node): model matrix × the node's matrix, origin
  Vec4 p = characterMatrix(position, heading) * g.player.nodeTransform(g.playerRig.cameraPivot) *
           Vec4{0.0f, 0.0f, 0.0f, 1.0f};
  return {p.x, p.y, p.z};
}

第14章から、nodeTransform(i)はルートからノードiまでの行列の積です。

リグ

CharacterRigは全ての関節を1回だけ探し、休みの姿勢の写しを持ちます:

// 関節のノード番号(findNodeで一度だけ探す)と、読み込んだときの姿勢(休みの姿勢)
// The joints' node indices (looked up once with findNode) and the pose as loaded (the rest pose)
struct CharacterRig {
  int hips = -1, spine = -1, head = -1, weapon = -1, cameraPivot = -1;
  int leg[2] = {-1, -1}, knee[2] = {-1, -1};               // [0] = 左 / left, [1] = 右 / right
  int shoulder[2] = {-1, -1}, elbow[2] = {-1, -1}, hand[2] = {-1, -1};
  std::vector<GltfNode> rest;

  // 全部の関節が見つかればリグを返す / returns the rig if every joint exists
  static std::optional<CharacterRig> find(const Model &model);
};

findは15個のノードの1つでも無ければメッセージを出して失敗します。
壊れた書き出しは、腕の無い兵士を作る代わりに、起動の時にゲームを止めます。

モデルを何処に置くか

ゲームはキャラクターの向きheadingをカメラの決まりで持ちます。
0で−Zを向き、正で右へ回ります。
モデルの正面は+Zなので、モデル行列はπ−hだけ回します:

Mat4 characterMatrix(Vec3 position, float heading) { return translate(position) * rotateY(PI - heading); }

線型代数 第8章のY軸周りの回転で確かめましょう。
正面(0,0,1)は(sinθ,0,cosθ)に写ります。
θ=π−hなら(sinh,0,−cosh)で、正にyaw hのカメラの水平の前です。
h=0でモデルは−Zを、h=90°で+Xを向きます。

36.8 コードで姿勢を作る

1つのModel、何人ものキャラクター

Model::nodesが姿勢です。
モデルは1回だけ読み込んで共有し、第38章では全ての敵が1つのenemy.glbを共有します。
従って、キャラクターは姿勢をノードの中に持てません。
姿勢はキャラクターごとの小さな値で、其のキャラクターを描く直前にノードに書きます:

// 一人分の姿勢のパラメーター(毎ステップ、ゲームの状態から作る) / one character's pose parameters (built from the
// game state every step)
struct CharacterPose {
  float walkPhase = 0.0f;  // 歩きの周期(ラジアン、進んだ距離に比例) / walk cycle (radians, ∝ distance traveled)
  float walkAmount = 0.0f; // 0 = 立つ、1 = 歩く・走る / 0 = standing, 1 = walking / running
  float stride = 1.0f;     // 足の振りの大きさ(走ると大きい) / leg swing size (bigger when running)
  float legYaw = 0.0f;     // 腰から下を移動の向きへ回す(ラジアン) / turns the legs towards the movement (radians)
  float aimPitch = 0.0f;   // 銃の上下(ラジアン、正 = 上) / the gun's pitch (radians, positive = up)
};

void PlayScene::drawCharacters(const Shader &shader, bool depthOnly, Vec3 eye) {
  // 前のステップと今のステップの間をdrawAlphaで補間(第26章) / interpolate between the last and the current step
  // with drawAlpha (chapter 26)
  Mat4 m = characterMatrix(lerp(prevPosition, position, drawAlpha), approachAngle(prevHeading, heading, drawAlpha));
  if (posing) applyPose(g.player, g.rifle, g.playerRig, pose);
  else g.player.nodes = g.playerRig.rest; // P:読み込んだままの姿勢 / P: the pose as loaded
  Mat4 w = weaponMatrix(g.player, g.playerRig, m);
  if (depthOnly) {
    g.player.drawDepth(shader, m, g.renderer.white);
    g.rifle.drawDepth(shader, w, g.renderer.white);
  } else {
    g.player.draw(shader, m, g.renderer.white, ModelPass::Opaque, eye, Shading::Pbr);
    g.rifle.draw(shader, w, g.renderer.white, ModelPass::Opaque, eye, Shading::Pbr);
  }
}

drawCharactersはフレームごとに2回、影のパスと場面のパスから呼ばれ、どちらも姿勢を適用します。
影のパスで適用しなければ、最後の描画がノードに残した姿勢、つまり前のフレームの姿勢を描きます。
影が体より1フレーム遅れてしまいます。
第38章では、銃口の位置も同じく姿勢を適用した後で探します。
PはapplyPoseを飛ばして休みの姿勢に戻します。
此の絵の最初の場面です:

前から見た4つの場面。読み込んだ儘の休みの姿勢:腕は垂れ、ライフルはWeaponソケットの胸の前に浮いている。手続き的な姿勢:両手がライフルの上、右手は握り、左手は前の握り、肘が曲がっている。Bでのソケット:肩の上のカメラの注視点に水色の箱、武器に紫、手に黄色、銃口に赤。斜めに歩く:脚は右前へ踏み出し、胸は狙いを向いた儘

歩きの周期は距離で進む

すぐに思い付く歩きの周期は、時間で位相を進めます。
すると足が滑ります。
ゆっくり歩いても脚は全速で振れ、走ると追い付きません。
此の周期は代わりに進んだ距離で進みます:

φ←φ+2πvΔtL

vは速さ、Lは周期の長さ(2歩)で、歩く時1.5 m、走る時2.4 mです。
歩く速さ3.2 m/sでは毎秒3.2/1.5=2.13周期、走る6 m/sでは6/2.4=2.5周期です。
其の間のどの速さでも、加速している間も、足は地面と一緒に動きます:

  // 歩きの周期は進んだ距離に比例:足が地面を滑らない / the walk cycle advances with distance: feet do not skate
  float run = std::clamp((speed - kWalkSpeed) / (kRunSpeed - kWalkSpeed), 0.0f, 1.0f);
  float cycleLength = 1.5f + 0.9f * run; // 1周期(2歩)のm / meters per cycle (two steps)
  pose.walkPhase = std::fmod(pose.walkPhase + direction * 2.0f * PI * speed * dt / cycleLength, 2.0f * PI);
  pose.walkAmount = std::clamp(speed / kWalkSpeed, 0.0f, 1.0f);
  pose.stride = 1.0f + 0.5f * run;

directionは後ろ歩きの時に−1です(次の節)。
walkAmountはキャラクターが止まる時に動き全体を0まで小さくするので、脚は歩く途中で固まらず、落ち着きます。
其れからapplyPoseが位相を関節の角度にします:

  float w = pose.walkAmount, phase = pose.walkPhase;

  // 腰:歩くと上下に揺れ、移動の向きへ回る(脚が進む向きを向く) / hips: bob while walking and turn towards the
  // movement (the legs point where they go)
  node(rig.hips).translation = rest(rig.hips).translation + Vec3{0.0f, w * (0.03f * std::cos(2.0f * phase) - 0.03f), 0.0f};
  node(rig.hips).rotation = rest(rig.hips).rotation * rotY(pose.legYaw);

  // 脚:太ももを前後に振り、前へ出ていく脚の膝を曲げる(足を持ち上げる) / legs: swing the thighs back and forth and
  // bend the knee of the leg that swings forward (lifting the foot)
  float swing = 0.5f * pose.stride * w * std::sin(phase);
  for (int s = 0; s < 2; ++s) {
    float sign = s == 0 ? 1.0f : -1.0f; // 左右は逆位相 / left and right are in opposite phase
    node(rig.leg[s]).rotation = rest(rig.leg[s]).rotation * rotX(-sign * swing);
    float forwardSwing = std::fmax(0.0f, sign * std::cos(phase)); // この脚が前へ動いている / this leg moves forward
    node(rig.knee[s]).rotation = rest(rig.knee[s]).rotation * rotX(w * pose.stride * (0.12f + 1.0f * forwardSwing));
  }

1.5 mの1周期の歩き。左の太ももは±28.6°の間で正弦波の様に振れ、右の太ももは逆の位相。どちらの膝も、其の太ももが前へ振れる間は64°まで曲がり、其れ以外は7°のまま

  • 太ももは歩く時±0.5 rad(28.6°)、走る時±0.75 rad(43°)振れ、2本の脚は逆の位相です。
  • 脚が前へ動くのは振れの角度が増えている間で、左脚ならcosφ>0の時です。其の時に膝が曲がり、歩く歩幅では0.12+1=1.12 rad(64°)まで曲がって、体の下を通る足を持ち上げます。もう一方の膝は0.12 rad(7°)で殆ど真っ直ぐです。
  • 腰は0.03(1−cos2φ) m、0〜6 cmだけ、1周期に2回、つまり1歩に1回下がります。

どれも関節の局所のX軸周りの回転です。
正の角度のrotX(a)は垂れた部品を後ろへ回す(−Yから−Zの方へ)ので、太ももはrotX(-swing)で左脚を前へ振り、膝の正の角度はすねを後ろへ折ります。

脚は移動の向きへ

キャラクターは常にカメラが見る方を向きます。
其処を狙うからです(36.11で詳しく)。
でもどの向きにも歩けるので、北を向いた儘東へ歩く体は、ムーンウォークをするか、脚を前後に振り乍ら横へすり足で進むかになってしまいます。
其の為、腰は移動の向きへ回り、背骨は同じ角度だけ戻り、胸は狙い続けます:

  float speed = length(Vec3{velocity.x, 0.0f, velocity.z});
  float legTarget = 0.0f, direction = 1.0f;
  if (speed > 0.2f) {
    // 速度をキャラクターの座標へ:+Zが前、+Xが左(右手系で+Zを向くと+Xは左) / velocity in character space: +Z is
    // forward, +X is LEFT (facing +Z in a right-handed system, +X is on the left)
    Vec3 fwd = {std::sin(heading), 0.0f, -std::cos(heading)}, rgt = {std::cos(heading), 0.0f, std::sin(heading)};
    float mz = dot(velocity, fwd), mx = -dot(velocity, rgt);
    legTarget = std::atan2(mx, mz);
    if (std::fabs(legTarget) > radians(100.0f)) { // 後ろ歩き:脚は前を向いたまま逆に回す / walking backwards
      legTarget = wrapAngle(legTarget - PI);
      direction = -1.0f;
    }
    legTarget = std::clamp(legTarget, radians(-70.0f), radians(70.0f));
  }
  pose.legYaw = approachAngle(pose.legYaw, legTarget, approach(10.0f, dt));

速度をキャラクターの前と右の軸に射影し(線型代数 第4章)、+Xがキャラクターの左なので右の成分は符号を反転し、atan2でキャラクターの座標での移動の角度を求めます。
100°を超えるとキャラクターは後ろ歩きです。
其の時は脚を逆に向け(πを引く)、周期を逆に回します(direction = -1)。
結果は±70°に制限します。
腰が壊れて見えずに回れる限界です:

上から見た3つの場合、胸は常に北向き。W + D、前と右:腰と脚は移動の方へ右に45°回り、周期は前へ。D、右へ横歩き:移動は右に90°、脚は上限の70°まで回る。S + A、後ろと左:脚は移動と逆の右前を−45°で向き、周期は逆へ

姿勢では、腰がrotY(legYaw)、背骨がrotY(-legYaw)を受けます。
背骨は腰の子なので、2つの回転は腰より上で打ち消し合います。
legYaw自身は目標へ毎秒10の割合で近づくので、向きを変えると腰はパッと変わらず、回り込みます。

狙いを分ける

ライフルはカメラが向く方、上は50°、下は60°までを向かなければいけません。
背骨を60°曲げると背中が折れた様に見え、体を真っ直ぐにしてライフルだけ回すとロボットの様に見えます。
其の為、上下の角度を分けます:

  // 上半身:腰の回転を打ち消して狙う向きを保つ。狙いの上下は背骨・頭・銃で分ける。走ると少し前かがみ
  // Upper body: undo the hips' turn so it keeps facing the aim. The aim pitch is split between the spine, the head and
  // the weapon. Lean forward a little when running
  float lean = 0.1f * w * pose.stride;
  node(rig.spine).rotation = rest(rig.spine).rotation * rotY(-pose.legYaw) * rotX(lean - 0.45f * pose.aimPitch);
  node(rig.head).rotation = rest(rig.head).rotation * rotX(-0.35f * pose.aimPitch - lean);
  // 銃は残りの上下を受け持つので、合計でちょうどaimPitch(前かがみも打ち消す) / the weapon takes the rest of the
  // pitch, so the total is exactly aimPitch (the lean is undone too)
  node(rig.weapon).rotation = rest(rig.weapon).rotation * rotX(-0.55f * pose.aimPitch - lean);

  • 背骨は上下の角度の45 %を受け持ちます。
  • 頭は背骨の上に更に35 %を受け持ち、合計80 %になります。目は胸より狙いに付いて行きます。
  • 武器のソケットは背骨の上に残りの55 %を受け持つので、ライフルは丁度100 %になります。
  • 走ると背骨はleanだけ前に傾きます。頭と武器は其れを引き戻すので、頭の見る向きもライフルも変わりません。

一番下の−60°では背骨は27°、頭は48°曲がり、怪我をした様にではなく「下を見ている」様に見えます。

36.9 3Dの2本の骨のIK

ライフルはWeaponソケットに掛かり、狙いと一緒に回ります。
手は其れに付いて行かなければいけません。
右手はピストルグリップ(ライフルの原点)、左手はForegripソケットです。
又インバースキネマティクスで、第30章の格闘家の脚と同じ2本の骨の問題ですが、3Dです。

2Dより1つ多い選択

2Dでは、余弦定理が肩の角A(目標への線と上腕の間)を与え、膝や肘は鏡に映した2つの場所のどちらかでした。
第30章は符号で1つを選びました。
3Dでは同じ角が、肩と目標を結ぶ線の周りの円錐を決めます。
其の線の周りの円の上のどの点も、正しい肘です。
円の上の点を選ぶ何かが要り、普通の道具はポールベクトルです。
肘を向けたい方向です。
ポールと肩・目標の線が平面、曲げる平面を張り、肘は円の上で其の平面の中、ポールの側にある点です。
平面の中では、問題は第30章の2Dの三角形です:

左:右腕を斜めから見た3Dの図。肩、握りにある目標、届く肘の全てを表す点線の円、ピンクのポールの矢印、ポールと肩・目標の線が張る緑の曲げる平面。選んだ肘は円の上で平面の中にある。右:平らにした曲げる平面。0.32 mの上腕と前腕、dは0.413 m、肩の角A、肘の曲げる角θ、上腕の局所の軸:Yは上腕の逆向き、Zは前腕の方、蝶番の軸Xは紙面の奥へ。cos Aは0.6459、Aは49.8°、θは99.5°

肩から目標への単位ベクトルを𝐭^、ポールを𝐩とすると、𝐭^に垂直な平面の中の向きは、ポールから𝐭^の成分を取り除いた物です(線型代数 第4章の射影):

𝐛^=𝐩−(𝐩⋅𝐭^)𝐭^‖𝐩−(𝐩⋅𝐭^)𝐭^‖,𝐮^=cosA𝐭^+sinA𝐛^

𝐮^は上腕の向きで、肘は肩からl1𝐮^の所です。
ポールはライフルを持つ人の様に選びます。
両肘とも下、自分の側の外、少し後ろです。
右腕のポールは背骨の軸で(−0.8,−1,−0.5)、キャラクターの右の外です。
もしポールが丁度𝐭^に沿っていたら、射影の後に何も残らないので、コードは真下に頼ります。

解く関数

static void solveArm(Model &model, const CharacterRig &rig, int s, Vec3 target, Vec3 pole) {
  GltfNode &shoulder = model.nodes[static_cast<size_t>(rig.shoulder[s])];
  GltfNode &elbow = model.nodes[static_cast<size_t>(rig.elbow[s])];
  const GltfNode &hand = model.nodes[static_cast<size_t>(rig.hand[s])];
  Mat4 parent = model.nodeTransform(shoulder.parent); // 背骨(もう姿勢が入っている) / the spine (already posed)
  Vec3 p0 = origin(parent * translate(shoulder.translation));
  float l1 = length(elbow.translation), l2 = length(hand.translation);

  // 余弦定理:肩の角A(目標への向きと上腕の間) / law of cosines: the shoulder angle A (between the target direction
  // and the upper arm)
  Vec3 d = target - p0;
  float dist = std::clamp(length(d), std::fabs(l1 - l2) + 0.01f, l1 + l2 - 0.001f);
  Vec3 t = normalize(d);
  float cosA = std::clamp((l1 * l1 + dist * dist - l2 * l2) / (2.0f * l1 * dist), -1.0f, 1.0f);
  // 曲げる平面:目標への向きとpoleで決まる / the bend plane: spanned by the target direction and the pole
  Vec3 b = pole - dot(pole, t) * t;
  b = length(b) > 1e-5f ? normalize(b) : Vec3{0.0f, -1.0f, 0.0f};
  Vec3 upper = cosA * t + std::sqrt(1.0f - cosA * cosA) * b; // 上腕の向き / upper arm direction
  Vec3 elbowPos = p0 + l1 * upper;
  Vec3 fore = normalize(p0 + dist * t - elbowPos);           // 前腕の向き / forearm direction

  // 上腕の局所の軸:Y = −上腕(腕は−Yに垂れる)、Z = 前腕が曲がっていく向き、X = Y × Z(肘の蝶番の軸)
  // The upper arm's local axes: Y = −upper (the arm hangs along −Y), Z = the way the forearm bends, X = Y × Z (the
  // elbow's hinge axis)
  Vec3 u = toLocal(parent, upper), f = toLocal(parent, fore);
  Vec3 z = f - dot(f, u) * u;
  z = length(z) > 1e-5f ? normalize(z) : normalize(cross(u, Vec3{1.0f, 0.0f, 0.0f}));
  Vec3 y = -u;
  Vec3 x = cross(y, z);
  shoulder.rotation = quatFromBasis(x, y, z);
  // 肘:Rx(−θ)で前腕が+Z(曲がる側)へ傾く。θ = 上腕と前腕の間の角 / the elbow: Rx(−θ) tilts the forearm towards +Z
  // (the bend side). θ = the angle between upper arm and forearm
  float theta = std::acos(std::clamp(dot(upper, fore), -1.0f, 1.0f));
  elbow.rotation = rotX(-theta);
}

殆どは2Dの解です。
距離dは届く範囲に制限し(届かない目標には、其の方を指す真っ直ぐな腕)、cosAは余弦定理から、前腕は肘から制限した目標までです。
新しいのは、2つの向きを2つの回転にする所です。
ノードが持つのは向きではなく回転だからです:

  • 回転は親(背骨)に対する局所の物なので、先に向きを背骨の座標に持って来ます。此処での背骨の行列は回転と平行移動だけ(拡大縮小なし)で、回転の逆行列は転置です(線型代数 第10章)。toLocalは其の列の一つ一つと内積を取ります。
  • 休みの姿勢では、腕は肩の局所の−Yに沿って垂れています。従って、姿勢を付けた肩のY軸は−𝐮^でなければいけません。
  • 肘は1つの軸、局所のX軸の周りに曲がります。其の軸は曲げる平面に垂直でなければいけないので、肩のZ軸を平面の中、前腕の方に選び(前腕から𝐮^の成分を取り除いた物)、XはY×Zとします(線型代数 第5章)。其れで右手系の座標系が揃います。
  • 垂直な3本の単位ベクトルは回転行列の列で、quatFromBasisは其の行列を標準的な方法でクォータニオン(線型代数 第13章)にします。トレースが正ならトレースから、其うでなければ一番大きな対角要素からで、平方根の中が0に近づくのを避けます。
  • 肘は其れからrotX(-θ)だけです。θは上腕と前腕の間の角です。垂れた前腕(0,−1,0)をX軸周りに−θ回すと(0,−cosθ,sinθ)になり、座標系を作った側の+Zの方へ傾きます。

計算の例

休み(立って、狙いは水平)では、右肩はモデル座標の(−0.27,1.49,0)、握りはWeaponソケットの(−0.08,1.31,0.32)です:

  • 𝐝=(0.19,−0.18,0.32)なので、d=0.0361+0.0324+0.1024=0.1709=0.4134 mで、届く長さ0.32+0.32=0.64 mの十分内側です。
  • 骨はどちらも0.32 mなので、余弦定理はcosA=d2l=0.41340.64=0.6459に縮み、A=49.8°です。
  • 二等辺三角形では肘の曲げはθ=2A=99.5°です。右腕は直角より少しだけ多く曲がっています。
  • ポール(−0.8,−1,−0.5)で、肘は凡そ(−0.29,1.19,0.11)に来ます。肩の0.30 m下、少し右の外、少し前です。

左手はずっと遠くへ行きます。
(0.27,1.49,0)から胸を横切って(−0.08,1.30,0.48)の前の握りまで、d=0.6237 m、A=13.0°、θ=25.9°で、殆ど真っ直ぐな腕です。
本当にライフルの前を持つ時の形です。

目標はソケット

applyPoseの最後の腕のコードは、どんな説明よりもソケットの意味を見せてくれます:

  // 腕:銃の握り(原点)と前の握り(Foregripソケット)へIKで手を届かせる。肘は下・外・少し後ろへ
  // Arms: IK puts the hands on the rifle's grip (its origin) and on its Foregrip socket. Elbows point down, out and a
  // little back
  Mat4 weaponM = model.nodeTransform(rig.weapon);
  Vec3 grip = origin(weaponM);
  int foregrip = weapon.findNode("Foregrip");
  Vec3 front = foregrip >= 0 ? origin(weaponM * weapon.nodeTransform(foregrip)) : grip;
  Mat4 spineM = model.nodeTransform(rig.spine);
  auto spineDir = [&](Vec3 v) {
    Vec3 r = v.x * column(spineM, 0) + v.y * column(spineM, 1) + v.z * column(spineM, 2);
    return r;
  };
  solveArm(model, rig, 0, front, spineDir({0.7f, -1.0f, -0.3f}));
  solveArm(model, rig, 1, grip, spineDir({-0.8f, -1.0f, -0.5f}));
}

ライフルは1つのソケットに付け、両手は其々のモデルの別の2つのソケットへ動かします。
モデリングの道具でForegripを動かせば左手が動きます。
握りの違う拳銃を持たせるには、ForegripのノードのあるGLBがあれば良いだけです。
そして背骨は腕より先に姿勢が付くので、IKは自動的に狙いと腰の逆回転に付いて行きます。

ライフル自身はweaponMatrix、キャラクターの行列 × Weaponのノードの行列で描きます。
Bのデバッグのマーカーもどのソケットでも同じ積を使います(上の3つ目の場面):

Mat4 weaponMatrix(const Model &model, const CharacterRig &rig, const Mat4 &characterTransform) {
  return characterTransform * model.nodeTransform(rig.weapon);
}

36.10 肩越しのカメラ

何故肩越しか

キャラクターの真後ろの追いかけるカメラは、キャラクターを丁度狙いたい所、画面の真ん中に置いてしまいます。
『バイオハザード4』や『Gears of War』以来のシューティングは、カメラを横にずらします。
キャラクターは画面の片側を占め、照準(第38章)には其の横を通る道が空きます。
此のカメラは、注視点の0.7 m右の点の3.6 m後ろに立ちます。
最初に試した3.2 mと0.55 mでは、未だキャラクターが絵の真ん中にいました。

角度とベクトル

  float yaw = 0.0f;                // ラジアン:0で−Zを向き、正で右へ回る(エンジンのCameraと同じ) / radians: 0 looks
                                   // down −Z, positive turns right (like the engine's Camera)
  float pitch = radians(-8.0f);    // 正で上を向く / positive looks up
  float sensitivity = 0.0025f;     // ラジアン毎ピクセル / radians per pixel
  float distance = 3.6f;           // 肩からの距離(何もなければ) / distance from the shoulder (when nothing is in the way)
  float shoulderOffset = 0.7f;     // 右へのずらし(m) / sideways offset (m)
  float shoulderSide = 1.0f;       // +1 = 右肩、−1 = 左肩(Q) / +1 = right shoulder, −1 = left (Q)
  float probeRadius = 0.2f;        // 飛ばす球の半径(ニアクリップ面より大きく) / cast sphere radius (> the near plane)
  float fovY = radians(55.0f);

void ThirdPersonCamera::look(float dxPixels, float dyPixels) {
  yaw += dxPixels * sensitivity;
  pitch = std::clamp(pitch - dyPixels * sensitivity, radians(-60.0f), radians(50.0f));
}

Vec3 ThirdPersonCamera::forward() const {
  return {std::cos(pitch) * std::sin(yaw), std::sin(pitch), -std::cos(pitch) * std::cos(yaw)};
}
Vec3 ThirdPersonCamera::flatForward() const { return {std::sin(yaw), 0.0f, -std::cos(yaw)}; }
Vec3 ThirdPersonCamera::right() const { return {std::cos(yaw), 0.0f, std::sin(yaw)}; }

yawとpitchの決まりは第9章のカメラと同じです。
yaw 0で−Zを見て、正のyawで右へ回り、正のpitchで上を見て、pitchは制限します(−60°〜50°)。
forwardは球面座標の向きで、flatForwardとrightは其の水平の部分です。
移動で使います。

4つの段階の1回の更新

void ThirdPersonCamera::update(Vec3 pivot, std::span<const Aabb> solids, float dt) {
  // 1. 注視点を追う:水平は速く、上下はゆっくり(ジャンプや段差でカメラが跳ねない)
  // 1. follow the pivot: quickly sideways, slowly up and down (jumps and steps do not jolt the camera)
  float kxz = approach(25.0f, dt), ky = approach(8.0f, dt);
  smoothPivot = {smoothPivot.x + (pivot.x - smoothPivot.x) * kxz, smoothPivot.y + (pivot.y - smoothPivot.y) * ky,
                 smoothPivot.z + (pivot.z - smoothPivot.z) * kxz};
  side += (shoulderSide - side) * approach(10.0f, dt);

  // 2. 肩へずらす。横に壁があればそこまで / 2. offset to the shoulder, but not into a wall at the side
  Vec3 offset = (shoulderOffset * side) * right();
  float offsetLength = length(offset);
  shoulderPos = smoothPivot + offset;
  if (offsetLength > 1e-4f) {
    Ray sideways{smoothPivot, offset / offsetLength};
    if (std::optional<RayHit> hit = sphereCast(sideways, probeRadius, solids, offsetLength))
      shoulderPos = smoothPivot + std::fmax(hit->t - 0.02f, 0.0f) * sideways.direction;
  }

  // 3. 肩から後ろへ球を飛ばす。当たったら、その手前までしか下がれない
  // 3. cast the sphere backwards from the shoulder. If it hits, the camera may only go back as far as the hit
  Ray back{shoulderPos, -forward()};
  float allowed = distance;
  std::optional<RayHit> hit = sphereCast(back, probeRadius, solids, distance);
  hitWall = hit.has_value();
  if (hit) allowed = std::fmax(hit->t - 0.05f, 0.0f);

  // 4. 寄るときはすぐ(壁の中を映さない)、離れるときはゆっくり(壁を回り込んだ後にカメラが飛ばない)
  // 4. move in immediately (never show the inside of a wall), move out slowly (no jump after rounding a corner)
  if (allowed < dist) dist = allowed;
  else dist += (allowed - dist) * approach(4.0f, dt);
  eyePos = shoulderPos + dist * back.direction;
}

左:上から見たカメラの仕組み。キャラクターの体の円の中の注視点、右へ0.7 mのピンクの横への球で肩へ、肩から南の壁の方へのオレンジの後ろへの球。壁は0.2 m大きくした箱と一緒に描いてある。球はt = 1.80で大きくした箱に当たり、目は望む3.6 mではなく1.75 mで止まる。右:壁がなくなった後のカメラの距離の時間変化。1.75 mから3.6 mへ上がり、0.75秒で95 %

1. 注視点を追います。
指数的に近づくので、毎ステップ、残りの道のk=1−e−λΔtの割合だけ動きます。
ステップごとに決まった割合と違い、ステップの長さによらず同じ動きになります。
Δtのステップ2回で残るのは隙間のe−2λΔtで、2Δtのステップ1回と全く同じです。
水平は毎秒25の割合なので、カメラは走りに付いて来ます。
上下は8なので、第37章のジャンプや階段でカメラが跳ねません。
肩の側は毎秒10の割合で±1に近づくので、Qでカメラは切り替わらずに横切ります。

2. 肩へずらします。
但し壁の中には入れません。
注視点から横へ球を飛ばし、当たったら肩の点は当たりの2 cm手前で止まります。
此れが無いと、右側を壁に付けて立つと肩の点が壁の中に入り、後ろへの球が毎回壁の中から始まってしまいます。

3. 後ろへ飛ばします。
肩から−forwardに沿ってdistanceまで飛ばします。
球が何かに当たったら、カメラは当たりの5 cm手前までしか下がれません。

4. 寄るのは一瞬、離れるのはゆっくり。
許される距離が今の距離より短い時、カメラはすぐに其処へ跳びます。
此処で滑らかにすると、数フレームの間壁の中が映ってしまいます。
長い時は、カメラは毎秒4の割合で下がります。
角を通り過ぎた後、カメラは1フレームで2 m跳ぶ代わりに、凡そln20/4=0.75秒(95 %)かけて戻ります。

其れから視点は目からforwardに沿って見ます。
注視点を見るのではありません。
カメラと注視点は横にずれているので、注視点を見ると距離が変わる度に視界が回ってしまいます。
forwardに沿って見れば、照準を置く画面の真ん中は、常にカメラの向く方です。

レイと箱:スラブ法

球を飛ばすのはレイのテストの上に作ります。
箱は3つのスラブ、軸ごとの2枚の平行な平面の間の空間の重なりです。
レイ𝐨+t𝐝^がxのスラブの中にいるのは、tが

tx0=xlo−oxdx,tx1=xhi−oxdx

の間の時で(dx<0なら入れ替え)、yとzも同じです。
箱の中にいるのは3つのスラブ全ての中にいる時で、一番遅い入りtenter=max(tx0,ty0,tz0)から一番早い出texit=min(tx1,ty1,tz1)までです。
tenter≤texitなら箱に当たります:

左:2Dのスラブ法。xが1と3、yが1と2.2の間の箱、点線の帯で描いたxのスラブとyのスラブ、0, 0.2のoから2, 1の向きのレイ。レイはt x0 = 1.118でxのスラブに、t y0 = 1.789でyのスラブに入り、3.354でxのスラブを、4.472でyのスラブを出る。当たりは遅い方の入りの1.789。右:箱、角の尖ったrだけ大きくした箱、角の丸い本当の形。角の近くを通るレイは、球が本当に箱に触れるより少し前に大きくした箱に入る

絵では𝐨=(0,0.2)、𝐝^=(2,1)/5=(0.894,0.447)で、tx0=1/0.894=1.118、tx1=3/0.894=3.354、ty0=0.8/0.447=1.789、ty1=2/0.447=4.472です。
入りはmax(1.118,1.789)=1.789、出はmin(3.354,4.472)=3.354なので、レイは当たり、yのスラブの下の平面から法線(0,−1)で入ります。
同じ点からのもっと急なレイ、𝐝^=(1,3)/10=(0.316,0.949)は、xのスラブにtx0=1/0.316=3.162で入る前に、ty1=2/0.949=2.108でyのスラブから出てしまいます。入りが出より後なので、外れです。

std::optional<RayHit> rayAabb(const Ray &ray, const Aabb &box, float maxT) {
  // スラブ法:軸ごとに、2枚の平面(スラブ)の間にいるtの区間を求め、3つの区間の重なりを取る。
  // 入る時刻tEnterの最大と、出る時刻tExitの最小。tEnter ≤ tExitなら当たり
  // The slab method: per axis, the interval of t during which the ray is between the two planes (the slab); the hit
  // is the overlap of the three intervals: the latest entry tEnter and the earliest exit tExit. Hit if tEnter ≤ tExit
  const float o[3] = {ray.origin.x, ray.origin.y, ray.origin.z};
  const float d[3] = {ray.direction.x, ray.direction.y, ray.direction.z};
  const float lo[3] = {box.lo.x, box.lo.y, box.lo.z};
  const float hi[3] = {box.hi.x, box.hi.y, box.hi.z};
  float tEnter = -1e30f, tExit = 1e30f;
  int enterAxis = -1;
  float enterSign = 0.0f;
  for (int axis = 0; axis < 3; ++axis) {
    if (std::fabs(d[axis]) < 1e-8f) {
      // 平面に平行:スラブの外なら絶対に当たらない / parallel to the planes: outside the slab means no hit at all
      if (o[axis] < lo[axis] || o[axis] > hi[axis]) return std::nullopt;
      continue;
    }
    float inv = 1.0f / d[axis];
    float t0 = (lo[axis] - o[axis]) * inv, t1 = (hi[axis] - o[axis]) * inv;
    // 負の向きに進むなら、先に当たるのはhiの面 / moving the negative way, the hi plane comes first
    float sign = -1.0f;
    if (t0 > t1) {
      std::swap(t0, t1);
      sign = 1.0f;
    }
    if (t0 > tEnter) {
      tEnter = t0;
      enterAxis = axis;
      enterSign = sign;
    }
    tExit = std::fmin(tExit, t1);
    if (tEnter > tExit) return std::nullopt;
  }
  if (tExit < 0.0f) return std::nullopt; // 箱は後ろ / the box is behind the ray
  if (tEnter < 0.0f) return RayHit{0.0f, {}, -1}; // 始点が箱の中 / the origin is inside
  if (tEnter > maxT) return std::nullopt;
  RayHit hit{tEnter, {}, -1};
  if (enterAxis == 0) hit.normal.x = enterSign;
  if (enterAxis == 1) hit.normal.y = enterSign;
  if (enterAxis == 2) hit.normal.z = enterSign;
  return hit;
}

  • 一番遅い入りの軸が当たった面で、法線は其の軸に沿ってレイに逆らう向きです。向きの成分が負なら高い方の平面が先に来るので、t0とt1を入れ替え、其の面の法線は−ではなく+を向きます。其れを覚えるのがsignです。第38章の火花は此の法線に沿って壁から飛びます。
  • スラブに平行なレイは決して其れに出入りしません。始点が外なら全く当たらず、中なら其の軸はtを制限しません。(IEEEの浮動小数点数では0で割ると±∞になり、其れに頼る実装も多いですが、始点が丁度平面の上にある時の0⋅∞ = NaNを、はっきりした判定で避けています。)
  • ループの中のtEnter > tExitは早い打ち切りです。区間が離れたら、残りの軸ではもう助かりません。レイの完全に後ろにある箱はtExit < 0になります。
  • 始点が箱の中ならt=0で法線は無しです。カメラは其れを「此処で塞がれた」と扱います。其の為、球の半径は体より小さくなければいけません。注視点が大きくした箱の中に入ってはいけないからです。
  • raycastは箱の並びにrayAabbを走らせて一番近い当たりを残し、其れまでの一番良いtを新しい上限として渡すので、遠い箱は早く弾かれます。

球を飛ばす

カメラは点ではありません。
ニアクリップ面は目の0.1 m前にあり、其の角は目から0.12+0.0522+0.0922≈0.146 m離れています(縦の視野角55°、16:9)。
レイで壁の5 cm手前に止めたカメラは其の角を壁に押し込み、壁の向こうが見えてしまいます。
其の為、0.146 mより大きい半径0.2 mの球を滑らせ、ニアクリップ面の長方形全体をどの壁からも出しておきます。

球が箱に当たるのは、中心が箱からr以内に来た時です。
其の中心の集まりは、辺と角が丸い、rだけ大きくした箱です(箱と球のミンコフスキー和)。
此のコードは代わりに角の尖った、rだけ大きくした箱を使います。
其れは只の箱なので、上のレイのテストが仕事をします:

std::optional<RayHit> sphereCast(const Ray &ray, float radius, std::span<const Aabb> boxes, float maxT) {
  std::optional<RayHit> best;
  for (size_t i = 0; i < boxes.size(); ++i) {
    std::optional<RayHit> hit = rayAabb(ray, boxes[i].expanded(radius), best ? best->t : maxT);
    if (hit && (!best || hit->t < best->t)) {
      best = hit;
      best->index = static_cast<int>(i);
    }
  }
  return best;
}

辺や角の近くでは尖った箱が丸い物より外にはみ出すので、球が本当に触れる少し前に当たりを報告します(絵の右半分)。
カメラには其れが安全な側です。
角の近くで数センチ早く止まり、誰も気付きません。
正確な接触が要る第37章のプレイヤーでは、もっと良くします。
85個の箱に飛ばすのは単純なループです。
数百個の箱でもCPUには何でもなく、何千個の時にエンジンがどうするかは第37章(37.11)で見ます。

カメラの絵が4つの場合を見せます。
Kで当たり判定を切ると、南の壁に背を向けたカメラはアリーナの外に出て、壁の裏を見ます:

4つの場面。右肩:兵士は画面の左の3分の1に立ち、前に階段。Qで左肩:カメラが反対側の同じ視界。Bで壁に背を向けた時:カメラは1.75 mまで引き寄せられ、兵士は左に大きく、当たり判定の箱が緑の線で描かれている。Kでカメラの当たり判定なし:視界には壁の外側だけが映り、ソケットのマーカーが透けて見える

36.11 カメラに対する移動

移動

三人称のゲームでは、Wは「北」ではなく「カメラから離れる方」です。
入力はカメラの水平の軸で向きになります:

  // 2. カメラに対する移動:入力(右, 前)を、カメラの水平の右と前に掛ける(ワールドの軸ではない)
  // 2. movement relative to the camera: the input (right, forward) times the camera's horizontal right and forward
  //    vectors (not the world axes)
  Vec2 stick = {in.axis("left", "right"), in.axis("back", "forward")};
  if (inspect) stick = {0.0f, 0.0f}; // C:キャラクターの周りを見るだけ / C: only look around the character
  Vec3 wish = stick.x * camera.right() + stick.y * camera.flatForward();
  float wishLength = length(wish);
  if (wishLength > 1.0f) wish = wish / wishLength; // 斜めでも同じ速さ / same speed diagonally
  bool running = in.actionHeld("run") && stick.y > 0.0f;
  Vec3 target = (running ? kRunSpeed : kWalkSpeed) * wish;
  velocity = velocity + approach(kAcceleration, dt) * (target - velocity);
  position = position + dt * velocity; // 第36章:まだ当たり判定なし / chapter 36: no collision yet

𝐰=sx𝐫+sy𝐟で、(sx,sy)はスティック、𝐫と𝐟はカメラの水平の右と前です。
WとDを一緒に押すと長さ2のベクトルになり、正規化するので斜めの移動が41 %速くなりません。
既に単位円の中に収まるアナログスティックは、途中の値の儘です。
速度は目標の速度にカメラと同じ指数的な近づき方で毎秒12の割合で近づくので、いきなり全速にならず、短く動き出して止まります。
速さは歩く時3.2 m/s、走る時6 m/sで、走れるのは前だけです。
後ろ向きに全力で走る兵士はいません。
未だ当たり判定が無いので、positionは単に動きます。
第37章が其の行を置き換えます。

向きはカメラに付いて行く

  // 3. キャラクターはカメラの向きを向く(肩越しの撃ち合いの決まり)。脚は移動の向きへ
  // 3. the character faces where the camera looks (the over-the-shoulder shooter convention); the legs turn towards
  //    the movement
  if (!inspect) heading = approachAngle(heading, camera.yaw, approach(14.0f, dt));

キャラクターは、どの方へ歩いても、毎秒14の割合でカメラのyawを向きます。
肩越しのシューティングの決まりです。
体は狙いを向き、歩く向きは脚(36.8)が受け持ちます。
もう1つのよくある決まりは、狙わないアクションアドベンチャーのゲームの物で、キャラクターは移動の向きへ回り、カメラは自由に其の周りを回れます。

approachAngleはwrapAngleを通して短い方を回ります。
170°から−170°へは340°ではなく20°の回転です。
同じ関数は描く時の向きの補間(第26章の、最後の2ステップの間の補間)にも使うので、キャラクターが2つのフレームの間で遠回りに回る事はありません。

体を隠す

カメラが後ろの壁でキャラクターの中へ押し込まれると、頭の内側が映ってしまいます。
すぐに思い付くテスト「カメラの距離が或る値より短い」は、此処では間違いです。
肩へずらしているので、肩の0.3 m後ろのカメラでも、体からは未だ0.7 m横にいます。
其の為、目と体の軸の水平の距離で決めます:

  // カメラが体の中に入ったら(壁際で寄せられて)自分を描かない:頭や胴の内側が映る。肩へずらしているので、
  // 距離が短いだけでは入らない:体の軸からの水平距離で決める
  // When the camera ends up inside the body (pulled in at a wall) do not draw the player: we would see the inside of
  // the head or torso. Thanks to the shoulder offset a short distance alone does not mean that: decide by the
  // horizontal distance from the body's axis
  Vec3 feet = lerp(prevPosition, position, alpha);
  float axisDistance = length(Vec3{view.eye.x - feet.x, 0.0f, view.eye.z - feet.z});
  bool drawPlayer = axisDistance > 0.5f || view.eye.y > feet.y + 2.0f;

0.5 mは体の半径(0.35 m、第37章のカプセル)に余裕を足した物です。
頭よりずっと高い目(低い壁越しに急に見下ろす時)なら隠しません。
影は其の儘描きます。
影のパスのdrawCharactersはdrawPlayerを見ないからです。

36.12 フレーム

PlayScene::drawはカメラを補間し、光を設定し、其れからパスごとにレンダラーを呼びます:

  // 1. 影 / 1. shadows
  if (r.beginShadows()) {
    shadowStats = g.level.drawShadows(*r.shadow, r.white, r.lightFrustum());
    drawCharacters(*r.shadow, true, view.eye);
    r.endShadows();
  }
  // 2. 場面 / 2. the scene
  r.beginScene();
  // 手前の物から:キャラクター → レベル(床は最後) / nearest first: the character → the level (floor last)
  r.pbr->use();
  if (drawPlayer) drawCharacters(*r.pbr, false, view.eye);
  r.pbrInstanced->use();
  // F4:カリングなし(全部の部品をインスタンスのバッファへ)と比べる。平面(0, 0, 0, 1)なら全部が内側
  // F4: compare with no culling (every piece goes into the instance buffers). Planes (0, 0, 0, 1) keep everything in
  Frustum everything;
  for (Vec4 &plane : everything.planes) plane = {0.0f, 0.0f, 0.0f, 1.0f};
  levelStats = g.level.draw(*r.pbrInstanced, r.white, culling ? r.viewFrustum() : everything);
  if (g.showBoxes) drawDebugBoxes();
  r.drawSky();
  r.endScene();
  // 3. 後処理 → 画面 / 3. post-processing → the screen
  r.present(g.window.width(), g.window.height());
}

  • 場面のパスでは、キャラクターをレベルより先に描きます。又手前から順で、レベルは床を最後に描きます。
  • Bのデバッグの箱はglPolygonMode(GL_FRONT_AND_BACK, GL_LINE)(第4章)と光らないシェーダーで、HDRの色で描きます。空の箱の前にGL_FILLに戻さないと、空もワイヤーフレームになってしまいます。ソケットのマーカーは体に隠れないように深度テストなしで描きます。
  • UIはpresentの後、既定のフレームバッファにスプライトバッチで描きます。batch.end()の後はブレンドがオン、深度テストとカリングがオフですが、害はありません。次のフレームの始めにShadowMap::beginとbeginSceneが要る物を全て設定するからです。

F3はフレームが何をしたかを見せます:

F3の帯。CPU frame 245.0 ms、壁時計。llvmpipeのラスタライズ:shadow 6.1、scene 186.1、post 19.2 ms。描いたレベルの部品は138個の内96個で描画呼び出し13回、影を落とす物74個で描画呼び出し104回、影のテクセル22.9 mm。カメラの距離3.60 m、当たり判定の箱85個、カリングはオン、場面のフラグメント105万

36.13 llvmpipeで測る

此のシリーズの数字は全て、2コアのVMでMesaのソフトウェアのラスタライザーllvmpipeでも測っています。
其の「GPUの時間」は、CPUが各パスのラスタライズに使った時間です。
仕事の量については何かを語りますが、本物のGPUについては何も語りません。
静かなマシンでは、アリーナの1フレームは凡そ115〜135 ms(7〜9 fps)です。
場面のパスが凡そ100〜118 ms、影のパスが凡そ5 ms、後処理が凡そ11 msです。
上のスクリーンショットは他の仕事がCPUを分け合っている時に撮ったので、245 msになっています。
llvmpipeでは時間が実行ごとに±50 %揺れる事があるので、プログラムは60フレームの平均を端末に表示します。

フラグメントの数は揺れません。
場面のパスは視点により凡そ101万〜109万のフラグメントに深度テストを通らせます。
画面は1280×720=921,600ピクセルなので、各ピクセルは凡そ1.1〜1.2回書かれます。
其の低い重ね描きは手前から順に描いた成果で、何かを変えた時(例えば描く順番)に比べる数です。

カリング(F4)が変えるのは頂点の仕事だけで、llvmpipeではフレームの時間の違いは揺れの中に埋もれます。
フレームの殆どはピクセルの陰影付けで、アリーナ全体の7,092個の三角形ではありません。
デスクトップのGPUなら同じフレームは1〜2 msで、もっと大きなレベルでは其処で描画呼び出しと頂点の仕事が効いて来ます。

36.14 動かす

今まで通りビルドし、プロジェクトのルートから./build/games/tps/tpsを動かします(Visual Studioではtpsのプロジェクトを開始します。作業ディレクトリは既にルートです)。
カーソルは始めから捕まえられていて、Tabで放します。
壁まで歩いて背を付けるとカメラが引き寄せられるのが見え、Kで比べ、Bで箱を見て、Cでカメラを前まで回して姿勢を見て下さい。
部品だけを見るには、もう1つのレベルを渡します:./build/games/tps/tps games/tps/assets/levels/pieces.level。

端末には起動の時にレベルの数が、其の後60フレームごとに平均が出ます:

games/tps/assets/levels/arena.level: 8 piece types, 138 pieces, 85 collision boxes

36.15 プラットフォームごとの注意

  • Windows(Visual Studio): 実行ファイルはbuild\games\tps\Debug\tps.exeで、set_working_directoryがVisual Studioにプロジェクトのルートで起動させます。windows.hはNOMINMAXが無いとminとmaxをマクロとして定義し、直接又はライブラリを通して其れを読むファイルでは、其の名前のメンバーが壊れます。Aabbが角をloとhiと呼ぶのは其の為です。
  • 全て: レベルのファイルは>>で読み、\rを空白として扱うので、Windowsの改行で保存したファイルも同じに読めます。
  • Linux、FreeBSD: カーソルの捕まえはGLFWのdisabledのカーソルモードで、X11でもWaylandでもカーソルを隠して制限の無い相対的な動きを与えます。
  • 全て: GL_SAMPLES_PASSEDのクエリはOpenGLのコアなので、フラグメントの数はllvmpipeを含めて何処でも動きます。

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

  • レベル: グリッドの上のモジュール式のキット。テキストファイルではなくエディタ(Unreal、Unity、Godot)で置きますが、同じ様にデータとして保存します。繰り返す部品はインスタンシングされた静的メッシュになり(UnrealのInstancedとHierarchical Instanced Static Meshのコンポーネント、UnityのGPUインスタンシング)、境界ボリュームの階層で塊ごとにカリングします。大きなエンジンは階層的な深度バッファで遮蔽カリングを足し、カリングをGPUに移します。
  • 影: 太陽にはカスケードシャドウマップで、カスケードは3つか4つが多いです。Unreal 5のバーチャルシャドウマップは更に進み、画面が必要とする所にテクセルを割り当てます。
  • キャラクター: スキンメッシュ、アニメーションのクリップ、そして歩き・走り・横歩きのクリップを速さと向きで混ぜるブレンドスペース。此の章の回る脚は、貧乏人の横歩きのブレンドです。狙いの上下を分けるのはUnrealでいうエイムオフセットで、腕のIKは標準のノードです(UnrealのTwo Bone IKの「joint target」が此のポール)。フットIKは同じ解き方で足を凸凹の地面に置きます。
  • カメラ: UnrealのSpring Armコンポーネントは此の段階1〜4を行います。世界に対して滑らせる探りの球、カメラの遅れ、肩越しにするソケットのずらしです。UnityのCinemachineには肩のずらしとカメラの当たり判定のある三人称の追従カメラがあります。カメラを動かす代わりに、カメラとキャラクターの間の物を透明にするゲームも多いです。

36.17 まとめ

  • レベルのファイル: model、box、solid、place、row、grid、spawnを1行ずつ読み、エラーはファイル:行付き。回した後もAABBがAABBの儘である様に、yawは90°単位だけ(placeAabb)。arena.levelは6つの新しいGLBと共有の木箱と樽から138個の部品を作ります。
  • 当たり判定の箱: 既定は部品ごとのモデルの箱、階段には明示した6つの箱、床には見えない厚い箱1つ。合計85個で、今はカメラが、第37章からはプレイヤーが使います。
  • インスタンシング: 部品の種類ごとにインスタンスのバッファ1つを、毎フレーム見える部品で書き直し(glNamedBufferSubData)、プリミティブごとにインスタンシングの描画1回。レベルは168回ではなく13回の描画呼び出し。ゲーム専用のinstanced.vert(エンジンの物には未だ小惑星の公転がある)とpbr.frag。床が最後になるようにファイルと逆の順で描きます。
  • 影: 影のパスは影を落とす物を1つずつ描き(エンジンの穴:インスタンシングの深度の描画が無い)、光の箱でカリングします。光の箱はfrustumSphere(…, 0.1, 20 m)に合わせ、半径23.45 m、2048²で22.9 mmのテクセル、カメラが回っても変わりません。
  • 視錐台カリング: 𝐏𝐕の行から6枚の平面(Gribb–Hartmann)、メートル単位の符号付きの距離に正規化し、部品ごとの外接球と比べます。F4で比べられます。
  • フラグメントを数える: 場面のパスの周りにGL_SAMPLES_PASSEDの遮蔽クエリ。4つを順に使い、決して待ちません。時間がCPUの時間で揺れるllvmpipeでの、信頼出来るA/Bの目安です。
  • キャラクター: スキンメッシュではなく、ノードの階層の中の固い部品(ローダーはスキンとアニメーションを読み飛ばす)。ソケット:ルートの上のCameraPivot、背骨の上のWeapon、両手、ライフルのMuzzleとForegrip。
  • 手続き的な姿勢: 1つのModelを何人ものキャラクターが共有するので、各自がCharacterPoseを持ち、影のパスも含めて、描く直前に毎回ノードに書きます。歩きの周期は距離で進み(歩く時1周期1.5 m、走る時2.4 m)、脚は移動の向きへ回り(±70°、後ろ歩きでは周期が逆)、背骨が逆に回ります。狙いの上下は背骨45 %、頭は更に35 %、武器55 %に分けます。
  • 3Dの腕のIK: 曲げる平面の中で第30章の余弦定理。平面は、届く肘の円の中からポールベクトルが選びます。肩の回転は正規直交基底(Yは上腕の逆向き、Xは肘の蝶番)から、肘はX軸周りの回転1つ。
  • カメラ: 注視点を指数的に追い、横への球で肩へずらし、後ろへ球を飛ばし(0.2 m大きくした箱へのレイ、スラブ法)、寄るのは一瞬で離れるのはゆっくり。Qで肩を切り替えます。体は目と体の軸の距離で隠します。
  • 移動: カメラの水平の右と前に対して、正規化して滑らかに。キャラクターはカメラのyawを向きます。

36.18 課題

  1. ★ arena.levelに1行で、アリーナを横切る5つの遮蔽の列を足して下さい。例えばrow cover -6 0 -8.5 0 3 0 5です。再コンパイルせずにゲームを起動し直すと現れ、端末は部品143個と当たり判定の箱90個を報告し、F3はレベルの描画呼び出しを13回の儘表示する筈です。インスタンシングは写しが幾つあっても気にしません。
  2. ★ ThirdPersonCameraでshoulderOffset = 0、distance = 6にして下さい。昔ながらの真ん中の追いかけるカメラになり、キャラクターが画面の真ん中を隠す筈です。丁度第38章の照準が来る所です。シューティングがカメラを肩越しにする理由です。
  3. ★ ThirdPersonCamera::updateの段階4から「寄るのは一瞬」を取り除き、両方向にゆっくりした近づき方を使って下さい。壁に背を付けると、カメラが追い付くまでの数フレーム、壁の中か其の後ろの空間が映る筈です。
  4. ★★ 段階3の球を飛ばすのを、普通のraycast(球の半径0)に置き換えて下さい。壁の近くで、ニアクリップ面が壁に食い込むのが見える筈です。画面の端に灰色の壁の三角形や外の景色が映ります。目は面の5 cm手前で止まりますが、ニアクリップ面の角は0.146 mまで届くからです。
  5. ★★ 影のカスケードを2つ足して下さい。0.1〜8 mを2048²、8〜40 mを1024²です。2つの光の行列と分ける距離を持つゲーム専用のpbr.fragの写しと、2つ目のShadowMapが要ります。キャラクターの足元の影はずっとくっきりし(23 mmではなく凡そ9 mmのテクセル)、遠くの壁にも又影が付く筈です(凡そ89 mmのテクセル)。
  6. ★★ レベルを毎フレームのカリングなしで描いて下さい。読み込みの時に1回、種類ごとのインスタンスのバッファを全ての部品で埋め、毎フレームのglNamedBufferSubDataを止めます。絵は全く同じで、F3は常に138個中138個を表示する筈です。自分のGPUでフレームの時間を比べて下さい。llvmpipeでは違いは揺れの中に消えます。
  7. ★★★ エンジンにインスタンシングの深度の描画を足して下さい。位置4〜7にインスタンスの行列を持つshadow_instanced.vertと、Model::drawDepthInstanced(shader, white, count)です。其れをLevel::drawShadowsで光の箱のカリングと一緒に使います。絵は同じ儘で、F3の影を落とす物の描画呼び出しは104回から12回(床以外の全ての種類)に減る筈です。

DIFFをダウンロード

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

ファイル: /dev/null | b/games/tps/CMakeLists.txt

前新
@@ -0,0 +1,14 @@
    1 # 第36〜39章:三人称シューティング(TPS) / Chapters 36-39: the third-person shooter (TPS)
    2 add_executable(tps
    3 src/main.cc
    4 src/collision3d.cc
    5 src/frustum.cc
    6 src/level.cc
    7 src/renderer.cc
    8 src/character.cc
    9 src/third_person_camera.cc
    10 src/play_scene.cc)
    11 target_include_directories(tps PRIVATE src)
    12 target_link_libraries(tps PRIVATE engine)
    13 enable_warnings(tps)
    14 set_working_directory(tps)

ファイル: /dev/null | b/games/tps/README.md

前新
@@ -0,0 +1,41 @@
    1 # TPS(三人称シューティング) / TPS (third-person shooter) — 第36〜39章 / chapters 36-39
    2  
    3 プロジェクトのルートから実行する / run from the project root:
    4  
    5 ```sh
    6 ./build/games/tps/tps # Windows: build\games\tps\Debug\tps.exe
    7 ./build/games/tps/tps games/tps/assets/levels/pieces.level # 部品を並べたレベル / every piece in a row
    8 ```
    9  
    10 ## 操作 / Controls(第36章 / chapter 36)
    11  
    12 | キー / key | |
    13 |---|---|
    14 | WASD / ↑↓←→ | カメラの向きに対して移動 / move relative to the camera |
    15 | マウス / mouse | 見回す / look around |
    16 | Shift | 走る(前へ) / run (forwards) |
    17 | Q | 右肩 ⇔ 左肩 / right ⇔ left shoulder |
    18 | B | 当たり判定の箱とソケット / collision boxes and sockets |
    19 | C | カメラだけ回す(キャラクターを前から見る) / turn only the camera (look at the character) |
    20 | K | カメラの当たり判定のオン・オフ / camera collision on / off |
    21 | P | 手続き的な姿勢のオン・オフ / procedural pose on / off |
    22 | F3 | 時間と描いた数 / timings and draw counts |
    23 | F4 | 視錐台カリングのオン・オフ / frustum culling on / off |
    24 | Tab | カーソルのキャプチャ / cursor capture |
    25 | Esc | 終了 / quit |
    26  
    27 ## ファイル / Files
    28  
    29 ```
    30 src/main.cc ウィンドウ、読み込み、ゲームループ / window, loading, game loop
    31 src/game.hh シーンが共有するデータ / data the scenes share
    32 src/play_scene.* 遊ぶシーン / the play scene
    33 src/level.* レベルのファイル、インスタンシング、カリング / level file, instancing, culling
    34 src/collision3d.* AABB、レイ、スフィアキャスト / AABBs, rays, sphere casts
    35 src/frustum.* 視錐台の平面 / frustum planes
    36 src/renderer.* 影 → 場面(PBR + IBL) → 後処理 / shadows → scene (PBR + IBL) → post
    37 src/character.* 関節の姿勢と腕のIK / joint poses and arm IK
    38 src/third_person_camera.* 肩越しのカメラ / the over-the-shoulder camera
    39 shaders/instanced.vert 部品のインスタンシング(フラグメントはengine/shaders/pbr.frag) / instanced pieces
    40 assets/ モデル・レベル・フォント(assets/LICENSE.txt) / models, levels, font
    41 ```

ファイル: /dev/null | b/games/tps/assets/LICENSE.txt

前新
@@ -0,0 +1,27 @@
    1 games/tps/assets/ のファイルはこのチュートリアルのために作者が自作したもの(作者のPythonのスクリプトで生成。スクリプトはこのプロジェクトには含まれない)。自由に使ってよい。
    2 The files in games/tps/assets/ were made for this tutorial by the author (generated with the author's own Python scripts, which are not part of this project). Free to use for any purpose.
    3  
    4 models/floor_tile.glb コンクリートの床タイル 4 × 4 m / a 4 × 4 m concrete floor tile (chapter 36)
    5 models/wall.glb コンクリートの壁 4 × 3 m / a 4 × 3 m concrete wall
    6 models/cover.glb 低い遮蔽(バリア) / low cover, a concrete barrier
    7 models/pillar.glb 柱と照明 / a pillar with a lamp
    8 models/platform.glb 台(縞鋼板の上面) / a platform with a diamond-plate top
    9 models/stairs.glb 階段 / stairs
    10 models/player.glb プレイヤー:部品の階層とソケット / the player: parts in a node hierarchy + sockets
    11 models/rifle.glb ライフル(Muzzle・Foregripソケット) / the rifle (Muzzle and Foregrip sockets)
    12 levels/arena.level レベル(手で書いたテキスト) / the level (hand-written text)
    13 levels/pieces.level 部品を並べた確認用のレベル / every piece in a row, for checking (hand-written text)
    14 fonts/mono16.png/.fnt 共有のmono16にこのゲームの漢字を足したもの / the shared mono16 plus this game's kanji
    15 (足した漢字 / added kanji: 移動走肩跳撃弾装填三称任務失敗破命中率照狙射銃戦闘)
    16  
    17 フォントの画像(fonts/mono16.png)について / About the font image (fonts/mono16.png):
    18 これらは次のフォントから文字を画像にしたもの(フォントのファイル自体は含まない) / it contains glyph images rasterized
    19 from these fonts (the font files themselves are not included):
    20 * ASCIIの文字 / ASCII characters: DejaVu Sans Mono (https://dejavu-fonts.github.io/).
    21 Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc.
    22 DejaVu changes are in public domain. Bitstream Vera Fonts license: the fonts may be used, copied, modified and
    23 distributed freely as long as the copyright notice is kept and modified fonts are not called "Bitstream" or
    24 "Vera" (full text: https://dejavu-fonts.github.io/License.html).
    25 * 日本語の文字(かな・カナ・漢字の一部) / Japanese characters (kana and a kanji subset): Noto Sans CJK JP
    26 (https://github.com/notofonts/noto-cjk). Copyright 2014-2021 Adobe (http://www.adobe.com/). Noto is a trademark
    27 of Google Inc. Licensed under the SIL Open Font License, Version 1.1 (https://openfontlicense.org).

ファイル: /dev/null | b/games/tps/assets/fonts/mono16.fnt

前新
@@ -0,0 +1,575 @@
    1 info face="DejaVu Sans Mono + Noto Sans CJK JP" size=16 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,1,1,1 spacing=2,2
    2 common lineHeight=20 base=15 scaleW=512 scaleH=512 pages=1 packed=0
    3 page id=0 file="mono16.png"
    4 chars count=571
    5 char id=32 x=1 y=1 width=0 height=0 xoffset=0 yoffset=15 xadvance=10 page=0 chnl=15
    6 char id=33 x=3 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    7 char id=34 x=15 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    8 char id=35 x=27 y=1 width=10 height=11 xoffset=0 yoffset=4 xadvance=10 page=0 chnl=15
    9 char id=36 x=39 y=1 width=10 height=14 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    10 char id=37 x=51 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    11 char id=38 x=63 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    12 char id=39 x=75 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    13 char id=40 x=87 y=1 width=10 height=14 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    14 char id=41 x=99 y=1 width=10 height=14 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    15 char id=42 x=111 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    16 char id=43 x=123 y=1 width=10 height=8 xoffset=0 yoffset=7 xadvance=10 page=0 chnl=15
    17 char id=44 x=135 y=1 width=10 height=5 xoffset=0 yoffset=13 xadvance=10 page=0 chnl=15
    18 char id=45 x=147 y=1 width=10 height=5 xoffset=0 yoffset=10 xadvance=10 page=0 chnl=15
    19 char id=46 x=159 y=1 width=10 height=2 xoffset=0 yoffset=13 xadvance=10 page=0 chnl=15
    20 char id=47 x=171 y=1 width=10 height=13 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    21 char id=48 x=183 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    22 char id=49 x=195 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    23 char id=50 x=207 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    24 char id=51 x=219 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    25 char id=52 x=231 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    26 char id=53 x=243 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    27 char id=54 x=255 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    28 char id=55 x=267 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    29 char id=56 x=279 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    30 char id=57 x=291 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    31 char id=58 x=303 y=1 width=10 height=8 xoffset=0 yoffset=7 xadvance=10 page=0 chnl=15
    32 char id=59 x=315 y=1 width=10 height=11 xoffset=0 yoffset=7 xadvance=10 page=0 chnl=15
    33 char id=60 x=327 y=1 width=10 height=9 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    34 char id=61 x=339 y=1 width=10 height=7 xoffset=0 yoffset=8 xadvance=10 page=0 chnl=15
    35 char id=62 x=351 y=1 width=10 height=9 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    36 char id=63 x=363 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    37 char id=64 x=375 y=1 width=10 height=14 xoffset=0 yoffset=4 xadvance=10 page=0 chnl=15
    38 char id=65 x=387 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    39 char id=66 x=399 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    40 char id=67 x=411 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    41 char id=68 x=423 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    42 char id=69 x=435 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    43 char id=70 x=447 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    44 char id=71 x=459 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    45 char id=72 x=471 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    46 char id=73 x=483 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    47 char id=74 x=495 y=1 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    48 char id=75 x=1 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    49 char id=76 x=13 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    50 char id=77 x=25 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    51 char id=78 x=37 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    52 char id=79 x=49 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    53 char id=80 x=61 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    54 char id=81 x=73 y=17 width=10 height=14 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    55 char id=82 x=85 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    56 char id=83 x=97 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    57 char id=84 x=109 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    58 char id=85 x=121 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    59 char id=86 x=133 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    60 char id=87 x=145 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    61 char id=88 x=157 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    62 char id=89 x=169 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    63 char id=90 x=181 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    64 char id=91 x=193 y=17 width=10 height=14 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    65 char id=92 x=205 y=17 width=10 height=13 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    66 char id=93 x=217 y=17 width=10 height=14 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    67 char id=94 x=229 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    68 char id=95 x=241 y=17 width=10 height=4 xoffset=0 yoffset=15 xadvance=10 page=0 chnl=15
    69 char id=96 x=253 y=17 width=10 height=13 xoffset=0 yoffset=2 xadvance=10 page=0 chnl=15
    70 char id=97 x=265 y=17 width=10 height=9 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    71 char id=98 x=277 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    72 char id=99 x=289 y=17 width=10 height=9 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    73 char id=100 x=301 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    74 char id=101 x=313 y=17 width=10 height=9 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    75 char id=102 x=325 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    76 char id=103 x=337 y=17 width=10 height=12 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    77 char id=104 x=349 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    78 char id=105 x=361 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    79 char id=106 x=373 y=17 width=10 height=15 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    80 char id=107 x=385 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    81 char id=108 x=397 y=17 width=10 height=12 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    82 char id=109 x=409 y=17 width=10 height=9 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    83 char id=110 x=421 y=17 width=10 height=9 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    84 char id=111 x=433 y=17 width=10 height=9 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    85 char id=112 x=445 y=17 width=10 height=12 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    86 char id=113 x=457 y=17 width=10 height=12 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    87 char id=114 x=469 y=17 width=10 height=9 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    88 char id=115 x=481 y=17 width=10 height=9 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    89 char id=116 x=493 y=17 width=10 height=11 xoffset=0 yoffset=4 xadvance=10 page=0 chnl=15
    90 char id=117 x=1 y=34 width=10 height=9 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    91 char id=118 x=13 y=34 width=10 height=9 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    92 char id=119 x=25 y=34 width=10 height=9 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    93 char id=120 x=37 y=34 width=10 height=9 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    94 char id=121 x=49 y=34 width=10 height=12 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    95 char id=122 x=61 y=34 width=10 height=9 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    96 char id=123 x=73 y=34 width=10 height=15 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    97 char id=124 x=85 y=34 width=10 height=16 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    98 char id=125 x=97 y=34 width=10 height=15 xoffset=0 yoffset=3 xadvance=10 page=0 chnl=15
    99 char id=126 x=109 y=34 width=10 height=6 xoffset=0 yoffset=9 xadvance=10 page=0 chnl=15
    100 char id=12353 x=121 y=34 width=16 height=12 xoffset=0 yoffset=4 xadvance=16 page=0 chnl=15
    101 char id=12354 x=139 y=34 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    102 char id=12355 x=157 y=34 width=16 height=11 xoffset=0 yoffset=5 xadvance=16 page=0 chnl=15
    103 char id=12356 x=175 y=34 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    104 char id=12357 x=193 y=34 width=16 height=13 xoffset=0 yoffset=4 xadvance=16 page=0 chnl=15
    105 char id=12358 x=211 y=34 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    106 char id=12359 x=229 y=34 width=16 height=13 xoffset=0 yoffset=4 xadvance=16 page=0 chnl=15
    107 char id=12360 x=247 y=34 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    108 char id=12361 x=265 y=34 width=16 height=13 xoffset=0 yoffset=4 xadvance=16 page=0 chnl=15
    109 char id=12362 x=283 y=34 width=16 height=15 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    110 char id=12363 x=301 y=34 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    111 char id=12364 x=319 y=34 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    112 char id=12365 x=337 y=34 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    113 char id=12366 x=355 y=34 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    114 char id=12367 x=373 y=34 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    115 char id=12368 x=391 y=34 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    116 char id=12369 x=409 y=34 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    117 char id=12370 x=427 y=34 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    118 char id=12371 x=445 y=34 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    119 char id=12372 x=463 y=34 width=16 height=15 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    120 char id=12373 x=481 y=34 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    121 char id=12374 x=1 y=52 width=16 height=17 xoffset=0 yoffset=0 xadvance=16 page=0 chnl=15
    122 char id=12375 x=19 y=52 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    123 char id=12376 x=37 y=52 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    124 char id=12377 x=55 y=52 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    125 char id=12378 x=73 y=52 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    126 char id=12379 x=91 y=52 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    127 char id=12380 x=109 y=52 width=16 height=15 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    128 char id=12381 x=127 y=52 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    129 char id=12382 x=145 y=52 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    130 char id=12383 x=163 y=52 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    131 char id=12384 x=181 y=52 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    132 char id=12385 x=199 y=52 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    133 char id=12386 x=217 y=52 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    134 char id=12387 x=235 y=52 width=16 height=10 xoffset=0 yoffset=6 xadvance=16 page=0 chnl=15
    135 char id=12388 x=253 y=52 width=16 height=12 xoffset=0 yoffset=4 xadvance=16 page=0 chnl=15
    136 char id=12389 x=271 y=52 width=16 height=15 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    137 char id=12390 x=289 y=52 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    138 char id=12391 x=307 y=52 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    139 char id=12392 x=325 y=52 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    140 char id=12393 x=343 y=52 width=16 height=15 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    141 char id=12394 x=361 y=52 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    142 char id=12395 x=379 y=52 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    143 char id=12396 x=397 y=52 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    144 char id=12397 x=415 y=52 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    145 char id=12398 x=433 y=52 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    146 char id=12399 x=451 y=52 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    147 char id=12400 x=469 y=52 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    148 char id=12401 x=487 y=52 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    149 char id=12402 x=1 y=71 width=16 height=14 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    150 char id=12403 x=19 y=71 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    151 char id=12404 x=37 y=71 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    152 char id=12405 x=55 y=71 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    153 char id=12406 x=73 y=71 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    154 char id=12407 x=91 y=71 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    155 char id=12408 x=109 y=71 width=16 height=11 xoffset=0 yoffset=4 xadvance=16 page=0 chnl=15
    156 char id=12409 x=127 y=71 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    157 char id=12410 x=145 y=71 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    158 char id=12411 x=163 y=71 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    159 char id=12412 x=181 y=71 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    160 char id=12413 x=199 y=71 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    161 char id=12414 x=217 y=71 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    162 char id=12415 x=235 y=71 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    163 char id=12416 x=253 y=71 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    164 char id=12417 x=271 y=71 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    165 char id=12418 x=289 y=71 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    166 char id=12419 x=307 y=71 width=16 height=13 xoffset=0 yoffset=4 xadvance=16 page=0 chnl=15
    167 char id=12420 x=325 y=71 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    168 char id=12421 x=343 y=71 width=16 height=13 xoffset=0 yoffset=4 xadvance=16 page=0 chnl=15
    169 char id=12422 x=361 y=71 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    170 char id=12423 x=379 y=71 width=16 height=13 xoffset=0 yoffset=4 xadvance=16 page=0 chnl=15
    171 char id=12424 x=397 y=71 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    172 char id=12425 x=415 y=71 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    173 char id=12426 x=433 y=71 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    174 char id=12427 x=451 y=71 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    175 char id=12428 x=469 y=71 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    176 char id=12429 x=487 y=71 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    177 char id=12430 x=1 y=89 width=16 height=13 xoffset=0 yoffset=4 xadvance=16 page=0 chnl=15
    178 char id=12431 x=19 y=89 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    179 char id=12432 x=37 y=89 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    180 char id=12433 x=55 y=89 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    181 char id=12434 x=73 y=89 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    182 char id=12435 x=91 y=89 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    183 char id=12436 x=109 y=89 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    184 char id=12437 x=127 y=89 width=16 height=12 xoffset=0 yoffset=5 xadvance=16 page=0 chnl=15
    185 char id=12438 x=145 y=89 width=16 height=12 xoffset=0 yoffset=5 xadvance=16 page=0 chnl=15
    186 char id=12445 x=163 y=89 width=16 height=11 xoffset=0 yoffset=4 xadvance=16 page=0 chnl=15
    187 char id=12446 x=181 y=89 width=16 height=12 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    188 char id=12449 x=199 y=89 width=16 height=12 xoffset=0 yoffset=5 xadvance=16 page=0 chnl=15
    189 char id=12450 x=217 y=89 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    190 char id=12451 x=235 y=89 width=16 height=12 xoffset=0 yoffset=5 xadvance=16 page=0 chnl=15
    191 char id=12452 x=253 y=89 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    192 char id=12453 x=271 y=89 width=16 height=12 xoffset=0 yoffset=5 xadvance=16 page=0 chnl=15
    193 char id=12454 x=289 y=89 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    194 char id=12455 x=307 y=89 width=16 height=10 xoffset=0 yoffset=6 xadvance=16 page=0 chnl=15
    195 char id=12456 x=325 y=89 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    196 char id=12457 x=343 y=89 width=16 height=12 xoffset=0 yoffset=5 xadvance=16 page=0 chnl=15
    197 char id=12458 x=361 y=89 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    198 char id=12459 x=379 y=89 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    199 char id=12460 x=397 y=89 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    200 char id=12461 x=415 y=89 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    201 char id=12462 x=433 y=89 width=16 height=15 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    202 char id=12463 x=451 y=89 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    203 char id=12464 x=469 y=89 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    204 char id=12465 x=487 y=89 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    205 char id=12466 x=1 y=107 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    206 char id=12467 x=19 y=107 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    207 char id=12468 x=37 y=107 width=16 height=17 xoffset=0 yoffset=0 xadvance=16 page=0 chnl=15
    208 char id=12469 x=55 y=107 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    209 char id=12470 x=73 y=107 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    210 char id=12471 x=91 y=107 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    211 char id=12472 x=109 y=107 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    212 char id=12473 x=127 y=107 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    213 char id=12474 x=145 y=107 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    214 char id=12475 x=163 y=107 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    215 char id=12476 x=181 y=107 width=16 height=15 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    216 char id=12477 x=199 y=107 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    217 char id=12478 x=217 y=107 width=16 height=15 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    218 char id=12479 x=235 y=107 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    219 char id=12480 x=253 y=107 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    220 char id=12481 x=271 y=107 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    221 char id=12482 x=289 y=107 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    222 char id=12483 x=307 y=107 width=16 height=11 xoffset=0 yoffset=6 xadvance=16 page=0 chnl=15
    223 char id=12484 x=325 y=107 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    224 char id=12485 x=343 y=107 width=16 height=15 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    225 char id=12486 x=361 y=107 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    226 char id=12487 x=379 y=107 width=16 height=17 xoffset=0 yoffset=0 xadvance=16 page=0 chnl=15
    227 char id=12488 x=397 y=107 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    228 char id=12489 x=415 y=107 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    229 char id=12490 x=433 y=107 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    230 char id=12491 x=451 y=107 width=16 height=11 xoffset=0 yoffset=4 xadvance=16 page=0 chnl=15
    231 char id=12492 x=469 y=107 width=16 height=14 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    232 char id=12493 x=487 y=107 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    233 char id=12494 x=1 y=126 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    234 char id=12495 x=19 y=126 width=16 height=12 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    235 char id=12496 x=37 y=126 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    236 char id=12497 x=55 y=126 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    237 char id=12498 x=73 y=126 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    238 char id=12499 x=91 y=126 width=16 height=15 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    239 char id=12500 x=109 y=126 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    240 char id=12501 x=127 y=126 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    241 char id=12502 x=145 y=126 width=16 height=17 xoffset=0 yoffset=0 xadvance=16 page=0 chnl=15
    242 char id=12503 x=163 y=126 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    243 char id=12504 x=181 y=126 width=16 height=11 xoffset=0 yoffset=4 xadvance=16 page=0 chnl=15
    244 char id=12505 x=199 y=126 width=16 height=12 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    245 char id=12506 x=217 y=126 width=16 height=12 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    246 char id=12507 x=235 y=126 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    247 char id=12508 x=253 y=126 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    248 char id=12509 x=271 y=126 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    249 char id=12510 x=289 y=126 width=16 height=14 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    250 char id=12511 x=307 y=126 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    251 char id=12512 x=325 y=126 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    252 char id=12513 x=343 y=126 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    253 char id=12514 x=361 y=126 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    254 char id=12515 x=379 y=126 width=16 height=12 xoffset=0 yoffset=5 xadvance=16 page=0 chnl=15
    255 char id=12516 x=397 y=126 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    256 char id=12517 x=415 y=126 width=16 height=10 xoffset=0 yoffset=6 xadvance=16 page=0 chnl=15
    257 char id=12518 x=433 y=126 width=16 height=12 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    258 char id=12519 x=451 y=126 width=16 height=12 xoffset=0 yoffset=5 xadvance=16 page=0 chnl=15
    259 char id=12520 x=469 y=126 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    260 char id=12521 x=487 y=126 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    261 char id=12522 x=1 y=145 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    262 char id=12523 x=19 y=145 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    263 char id=12524 x=37 y=145 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    264 char id=12525 x=55 y=145 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    265 char id=12526 x=73 y=145 width=16 height=12 xoffset=0 yoffset=5 xadvance=16 page=0 chnl=15
    266 char id=12527 x=91 y=145 width=16 height=14 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    267 char id=12528 x=109 y=145 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    268 char id=12529 x=127 y=145 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    269 char id=12530 x=145 y=145 width=16 height=14 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    270 char id=12531 x=163 y=145 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    271 char id=12532 x=181 y=145 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    272 char id=12533 x=199 y=145 width=16 height=12 xoffset=0 yoffset=5 xadvance=16 page=0 chnl=15
    273 char id=12534 x=217 y=145 width=16 height=12 xoffset=0 yoffset=5 xadvance=16 page=0 chnl=15
    274 char id=12535 x=235 y=145 width=16 height=17 xoffset=0 yoffset=0 xadvance=16 page=0 chnl=15
    275 char id=12536 x=253 y=145 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    276 char id=12537 x=271 y=145 width=16 height=15 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    277 char id=12538 x=289 y=145 width=16 height=17 xoffset=0 yoffset=0 xadvance=16 page=0 chnl=15
    278 char id=12540 x=307 y=145 width=16 height=8 xoffset=0 yoffset=7 xadvance=16 page=0 chnl=15
    279 char id=12541 x=325 y=145 width=16 height=9 xoffset=0 yoffset=6 xadvance=16 page=0 chnl=15
    280 char id=12542 x=343 y=145 width=16 height=12 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    281 char id=12289 x=361 y=145 width=16 height=5 xoffset=0 yoffset=12 xadvance=16 page=0 chnl=15
    282 char id=12290 x=379 y=145 width=16 height=6 xoffset=0 yoffset=11 xadvance=16 page=0 chnl=15
    283 char id=12539 x=397 y=145 width=16 height=8 xoffset=0 yoffset=7 xadvance=16 page=0 chnl=15
    284 char id=12300 x=415 y=145 width=16 height=14 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    285 char id=12301 x=433 y=145 width=16 height=12 xoffset=0 yoffset=5 xadvance=16 page=0 chnl=15
    286 char id=12302 x=451 y=145 width=16 height=14 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    287 char id=12303 x=469 y=145 width=16 height=12 xoffset=0 yoffset=5 xadvance=16 page=0 chnl=15
    288 char id=65288 x=487 y=145 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    289 char id=65289 x=1 y=164 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    290 char id=12304 x=19 y=164 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    291 char id=12305 x=37 y=164 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    292 char id=12316 x=55 y=164 width=16 height=9 xoffset=0 yoffset=6 xadvance=16 page=0 chnl=15
    293 char id=8230 x=73 y=164 width=16 height=7 xoffset=0 yoffset=8 xadvance=16 page=0 chnl=15
    294 char id=65281 x=91 y=164 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    295 char id=65311 x=109 y=164 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    296 char id=65306 x=127 y=164 width=16 height=12 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    297 char id=65291 x=145 y=164 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    298 char id=65293 x=163 y=164 width=16 height=7 xoffset=0 yoffset=8 xadvance=16 page=0 chnl=15
    299 char id=215 x=181 y=164 width=10 height=9 xoffset=0 yoffset=6 xadvance=10 page=0 chnl=15
    300 char id=247 x=193 y=164 width=10 height=8 xoffset=0 yoffset=7 xadvance=10 page=0 chnl=15
    301 char id=65309 x=205 y=164 width=16 height=9 xoffset=0 yoffset=6 xadvance=16 page=0 chnl=15
    302 char id=65285 x=223 y=164 width=16 height=12 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    303 char id=65286 x=241 y=164 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    304 char id=65283 x=259 y=164 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    305 char id=65290 x=277 y=164 width=16 height=13 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    306 char id=12288 x=295 y=164 width=0 height=0 xoffset=0 yoffset=15 xadvance=16 page=0 chnl=15
    307 char id=38283 x=297 y=164 width=16 height=16 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    308 char id=22987 x=315 y=164 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    309 char id=32066 x=333 y=164 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    310 char id=20102 x=351 y=164 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    311 char id=19968 x=369 y=164 width=16 height=7 xoffset=0 yoffset=8 xadvance=16 page=0 chnl=15
    312 char id=26178 x=387 y=164 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    313 char id=20572 x=405 y=164 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    314 char id=27490 x=423 y=164 width=16 height=15 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    315 char id=20877 x=441 y=164 width=16 height=16 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    316 char id=32154 x=459 y=164 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    317 char id=34892 x=477 y=164 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    318 char id=24471 x=495 y=164 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    319 char id=28857 x=1 y=183 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    320 char id=26368 x=19 y=183 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    321 char id=39640 x=37 y=183 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    322 char id=27531 x=55 y=183 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    323 char id=27231 x=73 y=183 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    324 char id=20307 x=91 y=183 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    325 char id=21147 x=109 y=183 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    326 char id=21629 x=127 y=183 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    327 char id=21213 x=145 y=183 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    328 char id=21033 x=163 y=183 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    329 char id=25943 x=181 y=183 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    330 char id=21271 x=199 y=183 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    331 char id=24341 x=217 y=183 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    332 char id=20998 x=235 y=183 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    333 char id=27425 x=253 y=183 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    334 char id=38754 x=271 y=183 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    335 char id=25147 x=289 y=183 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    336 char id=36984 x=307 y=183 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    337 char id=25246 x=325 y=183 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    338 char id=27770 x=343 y=183 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    339 char id=23450 x=361 y=183 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    340 char id=35373 x=379 y=183 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    341 char id=38899 x=397 y=183 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    342 char id=37327 x=415 y=183 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    343 char id=36895 x=433 y=183 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    344 char id=24230 x=451 y=183 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    345 char id=38291 x=469 y=183 width=16 height=16 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    346 char id=31186 x=487 y=183 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    347 char id=22238 x=1 y=202 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    348 char id=20154 x=19 y=202 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    349 char id=25973 x=37 y=202 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    350 char id=21619 x=55 y=202 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    351 char id=26041 x=73 y=202 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    352 char id=23453 x=91 y=202 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    353 char id=31665 x=109 y=202 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    354 char id=37749 x=127 y=202 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    355 char id=25161 x=145 y=202 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    356 char id=26449 x=163 y=202 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    357 char id=30010 x=181 y=202 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    358 char id=26862 x=199 y=202 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    359 char id=36947 x=217 y=202 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    360 char id=22478 x=235 y=202 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    361 char id=29579 x=253 y=202 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    362 char id=23019 x=271 y=202 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    363 char id=21191 x=289 y=202 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    364 char id=32773 x=307 y=202 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    365 char id=21091 x=325 y=202 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    366 char id=30462 x=343 y=202 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    367 char id=24339 x=361 y=202 width=16 height=16 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    368 char id=30690 x=379 y=202 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    369 char id=34220 x=397 y=202 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    370 char id=33609 x=415 y=202 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    371 char id=37329 x=433 y=202 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    372 char id=37504 x=451 y=202 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    373 char id=37509 x=469 y=202 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    374 char id=30707 x=487 y=202 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    375 char id=26408 x=1 y=221 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    376 char id=27700 x=19 y=221 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    377 char id=28779 x=37 y=221 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    378 char id=39080 x=55 y=221 width=16 height=16 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    379 char id=22303 x=73 y=221 width=16 height=15 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    380 char id=20809 x=91 y=221 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    381 char id=38343 x=109 y=221 width=16 height=16 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    382 char id=25915 x=127 y=221 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    383 char id=25731 x=145 y=221 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    384 char id=38450 x=163 y=221 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    385 char id=24481 x=181 y=221 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    386 char id=39764 x=199 y=221 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    387 char id=27861 x=217 y=221 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    388 char id=25216 x=235 y=221 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    389 char id=24517 x=253 y=221 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    390 char id=27578 x=271 y=221 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    391 char id=24489 x=289 y=221 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    392 char id=27602 x=307 y=221 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    393 char id=30496 x=325 y=221 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    394 char id=27494 x=343 y=221 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    395 char id=22120 x=361 y=221 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    396 char id=20855 x=379 y=221 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    397 char id=25345 x=397 y=221 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    398 char id=29289 x=415 y=221 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    399 char id=35013 x=433 y=221 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    400 char id=20633 x=451 y=221 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    401 char id=36023 x=469 y=221 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    402 char id=22770 x=487 y=221 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    403 char id=24215 x=1 y=240 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    404 char id=23487 x=19 y=240 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    405 char id=23627 x=37 y=240 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    406 char id=35441 x=55 y=240 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    407 char id=32862 x=73 y=240 width=16 height=16 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    408 char id=35211 x=91 y=240 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    409 char id=26469 x=109 y=240 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    410 char id=20837 x=127 y=240 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    411 char id=20986 x=145 y=240 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    412 char id=19978 x=163 y=240 width=16 height=15 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    413 char id=19979 x=181 y=240 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    414 char id=24038 x=199 y=240 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    415 char id=21491 x=217 y=240 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    416 char id=21069 x=235 y=240 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    417 char id=24460 x=253 y=240 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    418 char id=26481 x=271 y=240 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    419 char id=35199 x=289 y=240 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    420 char id=21335 x=307 y=240 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    421 char id=25276 x=325 y=240 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    422 char id=38626 x=343 y=240 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    423 char id=25163 x=361 y=240 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    424 char id=36275 x=379 y=240 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    425 char id=38957 x=397 y=240 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    426 char id=30446 x=415 y=240 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    427 char id=21475 x=433 y=240 width=16 height=14 xoffset=0 yoffset=3 xadvance=16 page=0 chnl=15
    428 char id=32819 x=451 y=240 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    429 char id=24515 x=469 y=240 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    430 char id=27671 x=487 y=240 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    431 char id=20803 x=1 y=259 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    432 char id=22825 x=19 y=259 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    433 char id=22320 x=37 y=259 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    434 char id=23665 x=55 y=259 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    435 char id=24029 x=73 y=259 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    436 char id=28023 x=91 y=259 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    437 char id=31354 x=109 y=259 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    438 char id=26143 x=127 y=259 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    439 char id=26376 x=145 y=259 width=16 height=16 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    440 char id=26085 x=163 y=259 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    441 char id=24180 x=181 y=259 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    442 char id=20170 x=199 y=259 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    443 char id=26397 x=217 y=259 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    444 char id=26172 x=235 y=259 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    445 char id=22812 x=253 y=259 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    446 char id=36196 x=271 y=259 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    447 char id=38738 x=289 y=259 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    448 char id=40644 x=307 y=259 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    449 char id=32209 x=325 y=259 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    450 char id=30333 x=343 y=259 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    451 char id=40658 x=361 y=259 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    452 char id=33394 x=379 y=259 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    453 char id=22823 x=397 y=259 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    454 char id=23567 x=415 y=259 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    455 char id=20302 x=433 y=259 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    456 char id=38263 x=451 y=259 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    457 char id=30701 x=469 y=259 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    458 char id=26032 x=487 y=259 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    459 char id=21476 x=1 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    460 char id=22810 x=19 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    461 char id=23569 x=37 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    462 char id=26089 x=55 y=278 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    463 char id=36933 x=73 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    464 char id=24375 x=91 y=278 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    465 char id=24369 x=109 y=278 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    466 char id=37325 x=127 y=278 width=16 height=15 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    467 char id=36605 x=145 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    468 char id=33391 x=163 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    469 char id=24746 x=181 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    470 char id=27491 x=199 y=278 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    471 char id=20840 x=217 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    472 char id=37096 x=235 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    473 char id=21322 x=253 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    474 char id=25968 x=271 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    475 char id=23383 x=289 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    476 char id=25991 x=307 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    477 char id=35501 x=325 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    478 char id=26360 x=343 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    479 char id=35328 x=361 y=278 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    480 char id=35486 x=379 y=278 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    481 char id=33521 x=397 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    482 char id=26412 x=415 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    483 char id=20013 x=433 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    484 char id=22269 x=451 y=278 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    485 char id=21517 x=469 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    486 char id=30058 x=487 y=278 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    487 char id=21495 x=1 y=297 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    488 char id=31532 x=19 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    489 char id=31456 x=37 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    490 char id=35352 x=55 y=297 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    491 char id=37682 x=73 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    492 char id=20445 x=91 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    493 char id=23384 x=109 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    494 char id=36796 x=127 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    495 char id=21066 x=145 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    496 char id=38500 x=163 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    497 char id=30011 x=181 y=297 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    498 char id=34920 x=199 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    499 char id=31034 x=217 y=297 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    500 char id=25805 x=235 y=297 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    501 char id=20316 x=253 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    502 char id=35500 x=271 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    503 char id=26126 x=289 y=297 width=16 height=16 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    504 char id=36938 x=307 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    505 char id=38627 x=325 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    506 char id=26131 x=343 y=297 width=16 height=16 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    507 char id=26222 x=361 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    508 char id=36890 x=379 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    509 char id=31777 x=397 y=297 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    510 char id=21336 x=415 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    511 char id=32244 x=433 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    512 char id=32722 x=451 y=297 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    513 char id=23550 x=469 y=297 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    514 char id=25126 x=487 y=297 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    515 char id=35430 x=1 y=316 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    516 char id=21512 x=19 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    517 char id=36000 x=37 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    518 char id=28310 x=55 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    519 char id=23436 x=73 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    520 char id=25104 x=91 y=316 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    521 char id=21151 x=109 y=316 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    522 char id=22833 x=127 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    523 char id=24565 x=145 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    524 char id=27515 x=163 y=316 width=16 height=16 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    525 char id=29983 x=181 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    526 char id=30772 x=199 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    527 char id=20498 x=217 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    528 char id=24618 x=235 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    529 char id=20027 x=253 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    530 char id=20844 x=271 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    531 char id=20210 x=289 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    532 char id=26053 x=307 y=316 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    533 char id=20882 x=325 y=316 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    534 char id=38522 x=343 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    535 char id=19990 x=361 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    536 char id=30028 x=379 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    537 char id=22259 x=397 y=316 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    538 char id=37489 x=415 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    539 char id=27934 x=433 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    540 char id=31391 x=451 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    541 char id=22612 x=469 y=316 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    542 char id=38272 x=487 y=316 width=16 height=16 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    543 char id=27211 x=1 y=335 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    544 char id=23478 x=19 y=335 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    545 char id=23460 x=37 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    546 char id=38542 x=55 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    547 char id=27573 x=73 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    548 char id=31348 x=91 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    549 char id=33853 x=109 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    550 char id=25342 x=127 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    551 char id=20351 x=145 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    552 char id=25448 x=163 y=335 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    553 char id=21463 x=181 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    554 char id=28193 x=199 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    555 char id=25506 x=217 y=335 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    556 char id=35519 x=235 y=335 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    557 char id=38598 x=253 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    558 char id=24403 x=271 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    559 char id=31227 x=289 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    560 char id=21205 x=307 y=335 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    561 char id=36208 x=325 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    562 char id=32937 x=343 y=335 width=16 height=15 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    563 char id=36339 x=361 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    564 char id=24382 x=379 y=335 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    565 char id=22635 x=397 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    566 char id=19977 x=415 y=335 width=16 height=14 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15
    567 char id=31216 x=433 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    568 char id=20219 x=451 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    569 char id=21209 x=469 y=335 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    570 char id=29575 x=487 y=335 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    571 char id=29031 x=1 y=354 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    572 char id=29401 x=19 y=354 width=16 height=16 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    573 char id=23556 x=37 y=354 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    574 char id=37507 x=55 y=354 width=16 height=17 xoffset=0 yoffset=1 xadvance=16 page=0 chnl=15
    575 char id=38360 x=73 y=354 width=16 height=16 xoffset=0 yoffset=2 xadvance=16 page=0 chnl=15

ファイル: /dev/null | b/games/tps/assets/fonts/mono16.png

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

ファイル: /dev/null | b/games/tps/assets/levels/arena.level

前新
@@ -0,0 +1,87 @@
    1 # arena.level — the TPS level (chapter 36). Units: metres, +Y up, north = -Z. yaw in degrees (multiples of 90).
    2 # Commands (one per line, # starts a comment):
    3 # model <name> <file.glb> [noshadow] [nocollide] [vary=N] a piece type (one GLB, drawn instanced)
    4 # box <name> x0 y0 z0 x1 y1 z1 collision box in the piece's model space (any number; default = its bounds)
    5 # solid x0 y0 z0 x1 y1 z1 an invisible world-space collision box
    6 # place <name> x y z yaw one piece
    7 # row <name> x y z yaw dx dz count count pieces, (dx, dz) apart
    8 # grid <name> x y z yaw step nx nz nx × nz pieces, step apart
    9 # spawn x y z yaw the player's start (yaw 0 = facing north, -Z)
    10  
    11 model floor games/tps/assets/models/floor_tile.glb noshadow nocollide vary=0.06
    12 model wall games/tps/assets/models/wall.glb vary=0.05
    13 model cover games/tps/assets/models/cover.glb
    14 model pillar games/tps/assets/models/pillar.glb
    15 model platform games/tps/assets/models/platform.glb
    16 model stairs games/tps/assets/models/stairs.glb
    17 model crate assets/models/crate.glb vary=0.12
    18 model barrel assets/models/barrel.glb
    19  
    20 # 階段:段ごとの箱(モデルを作った時に表示した値) / the stairs: one box per step (printed when the model was made)
    21 box stairs -1 0 -1.5 1 0.25 1.5
    22 box stairs -1 0 -1.5 1 0.5 1
    23 box stairs -1 0 -1.5 1 0.75 0.5
    24 box stairs -1 0 -1.5 1 1 0
    25 box stairs -1 0 -1.5 1 1.25 -0.5
    26 box stairs -1 0 -1.5 1 1.5 -1
    27  
    28 # 床:8 × 8枚の4 mタイル(当たり判定は1枚の厚い箱:薄い箱は落ちる速さですり抜ける)
    29 # floor: 8 × 8 tiles of 4 m (collision is one thick box: thin boxes can be tunnelled at falling speed)
    30 grid floor -14 0 -14 0 4 8 8
    31 solid -16 -1 -16 16 0 16
    32  
    33 # 外壁(高さ3 m)と四隅の柱 / outer walls (3 m high) and corner pillars
    34 row wall -14 0 -16.2 0 4 0 8
    35 row wall -14 0 16.2 0 4 0 8
    36 row wall -16.2 0 -14 90 0 4 8
    37 row wall 16.2 0 -14 90 0 4 8
    38 place pillar -16.2 0 -16.2 0
    39 place pillar 16.2 0 -16.2 0
    40 place pillar -16.2 0 16.2 0
    41 place pillar 16.2 0 16.2 0
    42  
    43 # 中央の台(4 × 8 m、高さ1.5 m)と両端の階段 / the central platform (4 × 8 m, 1.5 m high) with stairs at both ends
    44 place platform 0 0 -2 0
    45 place platform 0 0 2 0
    46 place stairs 0 0 5.5 0
    47 place stairs 0 0 -5.5 180
    48 place pillar -3.2 0 -5 0
    49 place pillar 3.2 0 -5 0
    50 place pillar -3.2 0 5 0
    51 place pillar 3.2 0 5 0
    52  
    53 # 西と東の壁(L字の遮蔽) / west and east walls (L-shaped cover)
    54 row wall -9 0 -8 90 0 4 2
    55 place wall -11 0 -10.2 0
    56 row wall 9 0 4 90 0 4 2
    57 place wall 11 0 10.2 0
    58 place pillar -9 0 -10.2 0
    59 place pillar 9 0 10.2 0
    60  
    61 # 低い遮蔽 / low cover
    62 place cover -5 0 9.5 0
    63 place cover 5.5 0 10 0
    64 place cover -12 0 2 90
    65 place cover 12 0 -2 90
    66 place cover -5 0 -11 0
    67 place cover 5 0 -10.5 0
    68 place cover 0 0 -13 0
    69  
    70 # 箱と樽(共有のassets/models) / crates and barrels (the shared assets/models)
    71 place crate -13.5 0 13.5 0
    72 place crate -12.4 0 13.6 90
    73 place crate -13.4 0 12.4 0
    74 place crate -13.4 1 13.4 90
    75 place crate 12.5 0 -13.5 0
    76 place crate 13.6 0 -13.4 0
    77 place crate 13.5 0 -12.3 90
    78 place crate 6 0 0 0
    79 place crate -6.5 0 -1 0
    80 place barrel 13.2 0 13 0
    81 place barrel 12.4 0 13.5 90
    82 place barrel 13.4 0 12.1 180
    83 place barrel -13 0 -13.2 0
    84 place barrel -12.2 0 -13.6 90
    85 place barrel 6.9 0 0.3 0
    86  
    87 spawn 0 0 11.5 0

ファイル: /dev/null | b/games/tps/assets/levels/pieces.level

前新
@@ -0,0 +1,19 @@
    1 # pieces.level — every level piece in a row, for looking at them (./build/games/tps/tps games/tps/assets/levels/pieces.level)
    2 model floor games/tps/assets/models/floor_tile.glb noshadow nocollide
    3 model wall games/tps/assets/models/wall.glb
    4 model cover games/tps/assets/models/cover.glb
    5 model pillar games/tps/assets/models/pillar.glb
    6 model platform games/tps/assets/models/platform.glb
    7 model stairs games/tps/assets/models/stairs.glb
    8 model crate assets/models/crate.glb
    9 model barrel assets/models/barrel.glb
    10 grid floor -10 0 -6 0 4 6 4
    11 solid -12 -1 -8 12 0 8
    12 place wall -9 0 -4 0
    13 place cover -4.5 0 -3 0
    14 place pillar -1.5 0 -3.5 0
    15 place platform 2.5 0 -4 0
    16 place stairs 2.5 0 -0.5 0
    17 place crate 6.5 0 -3 0
    18 place barrel 8 0 -3 0
    19 spawn 0 0 4 0

ファイル: /dev/null | b/games/tps/assets/models/cover.glb

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

ファイル: /dev/null | b/games/tps/assets/models/floor_tile.glb

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

ファイル: /dev/null | b/games/tps/assets/models/pillar.glb

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

ファイル: /dev/null | b/games/tps/assets/models/platform.glb

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

ファイル: /dev/null | b/games/tps/assets/models/player.glb

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

ファイル: /dev/null | b/games/tps/assets/models/rifle.glb

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

ファイル: /dev/null | b/games/tps/assets/models/stairs.glb

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

ファイル: /dev/null | b/games/tps/assets/models/wall.glb

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

ファイル: /dev/null | b/games/tps/shaders/instanced.vert

前新
@@ -0,0 +1,43 @@
    1 #version 460 core
    2 // レベルの部品のインスタンシング(第19章):phong.vertにインスタンスの行列と色を足しただけ(第19章の小惑星の公転なし)。
    3 // フラグメントシェーダーはエンジンのpbr.frag
    4 // Instancing for the level pieces (chapter 19): phong.vert plus the per-instance matrix and color (without the
    5 // chapter 19 asteroid orbit). Fragment shader: the engine's pbr.frag
    6 layout(location = 0) in vec3 aPosition;
    7 layout(location = 1) in vec3 aNormal;
    8 layout(location = 2) in vec2 aUv;
    9 layout(location = 3) in vec4 aTangent; // 接線(第22章) / tangent (chapter 22)
    10 layout(location = 4) in mat4 aInstanceModel; // 4〜7 / locations 4..7
    11 layout(location = 8) in vec3 aInstanceColor; // pbr.fragがベースカラーに掛ける / pbr.frag multiplies the base color
    12  
    13 // カメラ(ユニフォームバッファ、結合点0、std140)。使う全部のシェーダーで同じ宣言(C++ではCameraBlock)
    14 // The camera (uniform buffer, binding 0, std140). The same declaration in every shader that uses it (CameraBlock in C++)
    15 layout(std140, binding = 0) uniform Camera {
    16 mat4 uView;
    17 mat4 uProj;
    18 vec3 uViewPos; // カメラの位置(ワールド座標) / camera position (world space)
    19 float uTime; // アニメーションの時間(秒) / animation time (seconds)
    20 };
    21  
    22 uniform mat4 uModel; // モデルの中のノードの行列 / the node's matrix inside the model
    23 uniform mat3 uNormalMatrix; // その法線行列 / its normal matrix
    24  
    25 out vec3 vWorldPos;
    26 out vec3 vNormal;
    27 out vec2 vUv;
    28 out vec4 vTangent;
    29 out vec3 vTint;
    30  
    31 void main() {
    32 mat4 model = aInstanceModel * uModel;
    33 vec4 world = model * vec4(aPosition, 1.0);
    34 vWorldPos = world.xyz;
    35 // 部品はY軸周りに回すだけ(拡大縮小なし)なので、法線は行列の3×3で回せば良い
    36 // Pieces are only turned about Y (no scaling), so the 3×3 part rotates the normal correctly
    37 vNormal = mat3(aInstanceModel) * (uNormalMatrix * aNormal);
    38 vUv = aUv;
    39 mat3 m = mat3(model);
    40 vTangent = vec4(m * aTangent.xyz, aTangent.w * (determinant(m) < 0.0 ? -1.0 : 1.0));
    41 vTint = aInstanceColor;
    42 gl_Position = uProj * uView * world;
    43 }

ファイル: /dev/null | b/games/tps/src/character.cc

前新
@@ -0,0 +1,155 @@
    1 #include "character.hh"
    2  
    3 #include <algorithm>
    4 #include <cmath>
    5 #include <cstdio>
    6 #include <string>
    7  
    8 std::optional<CharacterRig> CharacterRig::find(const Model &model) {
    9 CharacterRig rig;
    10 rig.hips = model.findNode("Hips");
    11 rig.spine = model.findNode("Spine");
    12 rig.head = model.findNode("Head");
    13 rig.weapon = model.findNode("Weapon");
    14 rig.cameraPivot = model.findNode("CameraPivot");
    15 const char *side[2] = {"L", "R"};
    16 for (int s = 0; s < 2; ++s) {
    17 rig.leg[s] = model.findNode(std::string("Leg") + side[s]);
    18 rig.knee[s] = model.findNode(std::string("Knee") + side[s]);
    19 rig.shoulder[s] = model.findNode(std::string("Shoulder") + side[s]);
    20 rig.elbow[s] = model.findNode(std::string("Elbow") + side[s]);
    21 rig.hand[s] = model.findNode(std::string("Hand") + side[s]);
    22 }
    23 for (int n : {rig.hips, rig.spine, rig.head, rig.weapon, rig.cameraPivot, rig.leg[0], rig.leg[1], rig.knee[0],
    24 rig.knee[1], rig.shoulder[0], rig.shoulder[1], rig.elbow[0], rig.elbow[1], rig.hand[0], rig.hand[1]})
    25 if (n < 0) {
    26 fprintf(stderr, "キャラクターの関節が足りない / a character joint is missing\n");
    27 return std::nullopt;
    28 }
    29 rig.rest = model.nodes;
    30 return rig;
    31 }
    32  
    33 Mat4 characterMatrix(Vec3 position, float heading) { return translate(position) * rotateY(PI - heading); }
    34  
    35 // X軸周りの回転 / rotation about X
    36 static Quat rotX(float a) { return Quat::fromAxisAngle({1.0f, 0.0f, 0.0f}, a); }
    37 static Quat rotY(float a) { return Quat::fromAxisAngle({0.0f, 1.0f, 0.0f}, a); }
    38  
    39 // 回転行列の列(3本の直交する単位ベクトル)からクォータニオンへ / rotation matrix columns (three orthonormal unit
    40 // vectors) → quaternion
    41 static Quat quatFromBasis(Vec3 x, Vec3 y, Vec3 z) {
    42 float m00 = x.x, m01 = y.x, m02 = z.x, m10 = x.y, m11 = y.y, m12 = z.y, m20 = x.z, m21 = y.z, m22 = z.z;
    43 float trace = m00 + m11 + m22;
    44 Quat q;
    45 if (trace > 0.0f) {
    46 float s = 2.0f * std::sqrt(trace + 1.0f);
    47 q = {0.25f * s, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s};
    48 } else if (m00 > m11 && m00 > m22) {
    49 float s = 2.0f * std::sqrt(1.0f + m00 - m11 - m22);
    50 q = {(m21 - m12) / s, 0.25f * s, (m01 + m10) / s, (m02 + m20) / s};
    51 } else if (m11 > m22) {
    52 float s = 2.0f * std::sqrt(1.0f + m11 - m00 - m22);
    53 q = {(m02 - m20) / s, (m01 + m10) / s, 0.25f * s, (m12 + m21) / s};
    54 } else {
    55 float s = 2.0f * std::sqrt(1.0f + m22 - m00 - m11);
    56 q = {(m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, 0.25f * s};
    57 }
    58 return normalize(q);
    59 }
    60  
    61 static Vec3 origin(const Mat4 &m) { return {m.c[3].x, m.c[3].y, m.c[3].z}; }
    62 static Vec3 column(const Mat4 &m, int i) { return {m.c[i].x, m.c[i].y, m.c[i].z}; }
    63 // 回転だけの行列の逆で向きを戻す(転置を掛ける) / undo a pure rotation (multiply by its transpose)
    64 static Vec3 toLocal(const Mat4 &m, Vec3 v) { return {dot(v, column(m, 0)), dot(v, column(m, 1)), dot(v, column(m, 2))}; }
    65  
    66 // 2本の骨のIK:肩から手先をtargetへ届かせる。腕は休みの姿勢で−Yに垂れ、肘は局所X軸の周りに曲がる。
    67 // poleは肘を向けたい方向(モデル座標)。肩と肘の局所の回転を書く
    68 // Two-bone IK: makes the arm reach target from the shoulder. In the rest pose the arm hangs along −Y and the elbow bends
    69 // about its local X axis. pole = where the elbow should point (model space). Writes the shoulder's and the elbow's local
    70 // rotations
    71 static void solveArm(Model &model, const CharacterRig &rig, int s, Vec3 target, Vec3 pole) {
    72 GltfNode &shoulder = model.nodes[static_cast<size_t>(rig.shoulder[s])];
    73 GltfNode &elbow = model.nodes[static_cast<size_t>(rig.elbow[s])];
    74 const GltfNode &hand = model.nodes[static_cast<size_t>(rig.hand[s])];
    75 Mat4 parent = model.nodeTransform(shoulder.parent); // 背骨(もう姿勢が入っている) / the spine (already posed)
    76 Vec3 p0 = origin(parent * translate(shoulder.translation));
    77 float l1 = length(elbow.translation), l2 = length(hand.translation);
    78  
    79 // 余弦定理:肩の角A(目標への向きと上腕の間) / law of cosines: the shoulder angle A (between the target direction
    80 // and the upper arm)
    81 Vec3 d = target - p0;
    82 float dist = std::clamp(length(d), std::fabs(l1 - l2) + 0.01f, l1 + l2 - 0.001f);
    83 Vec3 t = normalize(d);
    84 float cosA = std::clamp((l1 * l1 + dist * dist - l2 * l2) / (2.0f * l1 * dist), -1.0f, 1.0f);
    85 // 曲げる平面:目標への向きとpoleで決まる / the bend plane: spanned by the target direction and the pole
    86 Vec3 b = pole - dot(pole, t) * t;
    87 b = length(b) > 1e-5f ? normalize(b) : Vec3{0.0f, -1.0f, 0.0f};
    88 Vec3 upper = cosA * t + std::sqrt(1.0f - cosA * cosA) * b; // 上腕の向き / upper arm direction
    89 Vec3 elbowPos = p0 + l1 * upper;
    90 Vec3 fore = normalize(p0 + dist * t - elbowPos); // 前腕の向き / forearm direction
    91  
    92 // 上腕の局所の軸:Y = −上腕(腕は−Yに垂れる)、Z = 前腕が曲がっていく向き、X = Y × Z(肘の蝶番の軸)
    93 // The upper arm's local axes: Y = −upper (the arm hangs along −Y), Z = the way the forearm bends, X = Y × Z (the
    94 // elbow's hinge axis)
    95 Vec3 u = toLocal(parent, upper), f = toLocal(parent, fore);
    96 Vec3 z = f - dot(f, u) * u;
    97 z = length(z) > 1e-5f ? normalize(z) : normalize(cross(u, Vec3{1.0f, 0.0f, 0.0f}));
    98 Vec3 y = -u;
    99 Vec3 x = cross(y, z);
    100 shoulder.rotation = quatFromBasis(x, y, z);
    101 // 肘:Rx(−θ)で前腕が+Z(曲がる側)へ傾く。θ = 上腕と前腕の間の角 / the elbow: Rx(−θ) tilts the forearm towards +Z
    102 // (the bend side). θ = the angle between upper arm and forearm
    103 float theta = std::acos(std::clamp(dot(upper, fore), -1.0f, 1.0f));
    104 elbow.rotation = rotX(-theta);
    105 }
    106  
    107 void applyPose(Model &model, const Model &weapon, const CharacterRig &rig, const CharacterPose &pose) {
    108 auto node = [&](int i) -> GltfNode & { return model.nodes[static_cast<size_t>(i)]; };
    109 auto rest = [&](int i) -> const GltfNode & { return rig.rest[static_cast<size_t>(i)]; };
    110 float w = pose.walkAmount, phase = pose.walkPhase;
    111  
    112 // 腰:歩くと上下に揺れ、移動の向きへ回る(脚が進む向きを向く) / hips: bob while walking and turn towards the
    113 // movement (the legs point where they go)
    114 node(rig.hips).translation = rest(rig.hips).translation + Vec3{0.0f, w * (0.03f * std::cos(2.0f * phase) - 0.03f), 0.0f};
    115 node(rig.hips).rotation = rest(rig.hips).rotation * rotY(pose.legYaw);
    116  
    117 // 脚:太ももを前後に振り、前へ出ていく脚の膝を曲げる(足を持ち上げる) / legs: swing the thighs back and forth and
    118 // bend the knee of the leg that swings forward (lifting the foot)
    119 float swing = 0.5f * pose.stride * w * std::sin(phase);
    120 for (int s = 0; s < 2; ++s) {
    121 float sign = s == 0 ? 1.0f : -1.0f; // 左右は逆位相 / left and right are in opposite phase
    122 node(rig.leg[s]).rotation = rest(rig.leg[s]).rotation * rotX(-sign * swing);
    123 float forwardSwing = std::fmax(0.0f, sign * std::cos(phase)); // この脚が前へ動いている / this leg moves forward
    124 node(rig.knee[s]).rotation = rest(rig.knee[s]).rotation * rotX(w * pose.stride * (0.12f + 1.0f * forwardSwing));
    125 }
    126  
    127 // 上半身:腰の回転を打ち消して狙う向きを保つ。狙いの上下は背骨・頭・銃で分ける。走ると少し前かがみ
    128 // Upper body: undo the hips' turn so it keeps facing the aim. The aim pitch is split between the spine, the head and
    129 // the weapon. Lean forward a little when running
    130 float lean = 0.1f * w * pose.stride;
    131 node(rig.spine).rotation = rest(rig.spine).rotation * rotY(-pose.legYaw) * rotX(lean - 0.45f * pose.aimPitch);
    132 node(rig.head).rotation = rest(rig.head).rotation * rotX(-0.35f * pose.aimPitch - lean);
    133 // 銃は残りの上下を受け持つので、合計でちょうどaimPitch(前かがみも打ち消す) / the weapon takes the rest of the
    134 // pitch, so the total is exactly aimPitch (the lean is undone too)
    135 node(rig.weapon).rotation = rest(rig.weapon).rotation * rotX(-0.55f * pose.aimPitch - lean);
    136  
    137 // 腕:銃の握り(原点)と前の握り(Foregripソケット)へIKで手を届かせる。肘は下・外・少し後ろへ
    138 // Arms: IK puts the hands on the rifle's grip (its origin) and on its Foregrip socket. Elbows point down, out and a
    139 // little back
    140 Mat4 weaponM = model.nodeTransform(rig.weapon);
    141 Vec3 grip = origin(weaponM);
    142 int foregrip = weapon.findNode("Foregrip");
    143 Vec3 front = foregrip >= 0 ? origin(weaponM * weapon.nodeTransform(foregrip)) : grip;
    144 Mat4 spineM = model.nodeTransform(rig.spine);
    145 auto spineDir = [&](Vec3 v) {
    146 Vec3 r = v.x * column(spineM, 0) + v.y * column(spineM, 1) + v.z * column(spineM, 2);
    147 return r;
    148 };
    149 solveArm(model, rig, 0, front, spineDir({0.7f, -1.0f, -0.3f}));
    150 solveArm(model, rig, 1, grip, spineDir({-0.8f, -1.0f, -0.5f}));
    151 }
    152  
    153 Mat4 weaponMatrix(const Model &model, const CharacterRig &rig, const Mat4 &characterTransform) {
    154 return characterTransform * model.nodeTransform(rig.weapon);
    155 }

ファイル: /dev/null | b/games/tps/src/character.hh

前新
@@ -0,0 +1,46 @@
    1 // キャラクター(第36章):部品の階層でできたGLBを、ノードのTRSをコードで書き換えて動かす。
    2 // glTFのスキンとアニメーションは私たちのローダーが読み飛ばす(第13・14章)ので、歩き・狙い・腕は手続き的に作る
    3 // Characters (chapter 36): a GLB made of parts in a node hierarchy, animated by rewriting the nodes' TRS in code.
    4 // Our loader skips glTF skins and animations (chapters 13-14), so walking, aiming and the arms are procedural
    5 #pragma once
    6  
    7 #include "engine/model.hh"
    8 #include "engine/shader.hh"
    9 #include "engine/texture.hh"
    10  
    11 #include <optional>
    12  
    13 // 関節のノード番号(findNodeで一度だけ探す)と、読み込んだときの姿勢(休みの姿勢)
    14 // The joints' node indices (looked up once with findNode) and the pose as loaded (the rest pose)
    15 struct CharacterRig {
    16 int hips = -1, spine = -1, head = -1, weapon = -1, cameraPivot = -1;
    17 int leg[2] = {-1, -1}, knee[2] = {-1, -1}; // [0] = 左 / left, [1] = 右 / right
    18 int shoulder[2] = {-1, -1}, elbow[2] = {-1, -1}, hand[2] = {-1, -1};
    19 std::vector<GltfNode> rest;
    20  
    21 // 全部の関節が見つかればリグを返す / returns the rig if every joint exists
    22 static std::optional<CharacterRig> find(const Model &model);
    23 };
    24  
    25 // 一人分の姿勢のパラメーター(毎ステップ、ゲームの状態から作る) / one character's pose parameters (built from the
    26 // game state every step)
    27 struct CharacterPose {
    28 float walkPhase = 0.0f; // 歩きの周期(ラジアン、進んだ距離に比例) / walk cycle (radians, ∝ distance traveled)
    29 float walkAmount = 0.0f; // 0 = 立つ、1 = 歩く・走る / 0 = standing, 1 = walking / running
    30 float stride = 1.0f; // 足の振りの大きさ(走ると大きい) / leg swing size (bigger when running)
    31 float legYaw = 0.0f; // 腰から下を移動の向きへ回す(ラジアン) / turns the legs towards the movement (radians)
    32 float aimPitch = 0.0f; // 銃の上下(ラジアン、正 = 上) / the gun's pitch (radians, positive = up)
    33 };
    34  
    35 // ゲームの中の位置と向き → モデル行列。headingはカメラのyawと同じ決まり(0 = −Zを向く、正 = 右へ回る)で、
    36 // モデルの正面は+Z(第14章の決まり)なので rotateY(π − heading)
    37 // Position and heading in the game → model matrix. heading uses the camera's yaw convention (0 = facing −Z, positive
    38 // turns right); the model's front is +Z (chapter 14's convention), hence rotateY(π − heading)
    39 Mat4 characterMatrix(Vec3 position, float heading);
    40  
    41 // 姿勢をモデルのノードに書く。同じModelを何人もが使うので、描く直前に毎回呼ぶ
    42 // Writes the pose into the model's nodes. Several characters share one Model, so call this right before drawing each
    43 void applyPose(Model &model, const Model &weapon, const CharacterRig &rig, const CharacterPose &pose);
    44  
    45 // 銃をWeaponソケットに付けて描く行列 / the matrix the weapon is drawn with, attached to the Weapon socket
    46 Mat4 weaponMatrix(const Model &model, const CharacterRig &rig, const Mat4 &characterTransform);

ファイル: /dev/null | b/games/tps/src/collision3d.cc

前新
@@ -0,0 +1,91 @@
    1 #include "collision3d.hh"
    2  
    3 #include <algorithm>
    4 #include <cmath>
    5 #include <utility>
    6  
    7 Aabb placeAabb(const Aabb &box, Vec3 position, int quarterTurns) {
    8 // rotateY(90°)は (x, z) → (z, −x)。角2つを回して並べ直せば良い / rotateY(90°) maps (x, z) → (z, −x): turn both
    9 // corners and sort them again
    10 Vec3 a = box.lo, b = box.hi;
    11 for (int i = 0; i < ((quarterTurns % 4) + 4) % 4; ++i) {
    12 a = {a.z, a.y, -a.x};
    13 b = {b.z, b.y, -b.x};
    14 }
    15 Vec3 lo = {std::fmin(a.x, b.x), std::fmin(a.y, b.y), std::fmin(a.z, b.z)};
    16 Vec3 hi = {std::fmax(a.x, b.x), std::fmax(a.y, b.y), std::fmax(a.z, b.z)};
    17 return {lo + position, hi + position};
    18 }
    19  
    20 bool overlaps(const Aabb &a, const Aabb &b) {
    21 return a.lo.x < b.hi.x && b.lo.x < a.hi.x && a.lo.y < b.hi.y && b.lo.y < a.hi.y && a.lo.z < b.hi.z &&
    22 b.lo.z < a.hi.z;
    23 }
    24  
    25 std::optional<RayHit> rayAabb(const Ray &ray, const Aabb &box, float maxT) {
    26 // スラブ法:軸ごとに、2枚の平面(スラブ)の間にいるtの区間を求め、3つの区間の重なりを取る。
    27 // 入る時刻tEnterの最大と、出る時刻tExitの最小。tEnter ≤ tExitなら当たり
    28 // The slab method: per axis, the interval of t during which the ray is between the two planes (the slab); the hit
    29 // is the overlap of the three intervals: the latest entry tEnter and the earliest exit tExit. Hit if tEnter ≤ tExit
    30 const float o[3] = {ray.origin.x, ray.origin.y, ray.origin.z};
    31 const float d[3] = {ray.direction.x, ray.direction.y, ray.direction.z};
    32 const float lo[3] = {box.lo.x, box.lo.y, box.lo.z};
    33 const float hi[3] = {box.hi.x, box.hi.y, box.hi.z};
    34 float tEnter = -1e30f, tExit = 1e30f;
    35 int enterAxis = -1;
    36 float enterSign = 0.0f;
    37 for (int axis = 0; axis < 3; ++axis) {
    38 if (std::fabs(d[axis]) < 1e-8f) {
    39 // 平面に平行:スラブの外なら絶対に当たらない / parallel to the planes: outside the slab means no hit at all
    40 if (o[axis] < lo[axis] || o[axis] > hi[axis]) return std::nullopt;
    41 continue;
    42 }
    43 float inv = 1.0f / d[axis];
    44 float t0 = (lo[axis] - o[axis]) * inv, t1 = (hi[axis] - o[axis]) * inv;
    45 // 負の向きに進むなら、先に当たるのはhiの面 / moving the negative way, the hi plane comes first
    46 float sign = -1.0f;
    47 if (t0 > t1) {
    48 std::swap(t0, t1);
    49 sign = 1.0f;
    50 }
    51 if (t0 > tEnter) {
    52 tEnter = t0;
    53 enterAxis = axis;
    54 enterSign = sign;
    55 }
    56 tExit = std::fmin(tExit, t1);
    57 if (tEnter > tExit) return std::nullopt;
    58 }
    59 if (tExit < 0.0f) return std::nullopt; // 箱は後ろ / the box is behind the ray
    60 if (tEnter < 0.0f) return RayHit{0.0f, {}, -1}; // 始点が箱の中 / the origin is inside
    61 if (tEnter > maxT) return std::nullopt;
    62 RayHit hit{tEnter, {}, -1};
    63 if (enterAxis == 0) hit.normal.x = enterSign;
    64 if (enterAxis == 1) hit.normal.y = enterSign;
    65 if (enterAxis == 2) hit.normal.z = enterSign;
    66 return hit;
    67 }
    68  
    69 std::optional<RayHit> raycast(const Ray &ray, std::span<const Aabb> boxes, float maxT) {
    70 std::optional<RayHit> best;
    71 for (size_t i = 0; i < boxes.size(); ++i) {
    72 std::optional<RayHit> hit = rayAabb(ray, boxes[i], best ? best->t : maxT);
    73 if (hit && (!best || hit->t < best->t)) {
    74 best = hit;
    75 best->index = static_cast<int>(i);
    76 }
    77 }
    78 return best;
    79 }
    80  
    81 std::optional<RayHit> sphereCast(const Ray &ray, float radius, std::span<const Aabb> boxes, float maxT) {
    82 std::optional<RayHit> best;
    83 for (size_t i = 0; i < boxes.size(); ++i) {
    84 std::optional<RayHit> hit = rayAabb(ray, boxes[i].expanded(radius), best ? best->t : maxT);
    85 if (hit && (!best || hit->t < best->t)) {
    86 best = hit;
    87 best->index = static_cast<int>(i);
    88 }
    89 }
    90 return best;
    91 }

ファイル: /dev/null | b/games/tps/src/collision3d.hh

前新
@@ -0,0 +1,51 @@
    1 // 3Dの当たり判定(第36章):軸に平行な箱(AABB)と、レイ・球を飛ばすテスト。カメラが壁にめり込まないために使う
    2 // 3D collision (chapter 36): axis-aligned boxes (AABBs) and ray / sphere casts. The camera uses them to stay out of
    3 // the walls
    4 #pragma once
    5  
    6 #include "engine/mathx.hh"
    7  
    8 #include <optional>
    9 #include <span>
    10  
    11 // 軸に平行な箱。lo = 小さい方の角、hi = 大きい方の角(min/maxという名前はWindowsのマクロとぶつかる)
    12 // An axis-aligned box. lo = the smaller corner, hi = the larger one (the names min/max clash with Windows macros)
    13 struct Aabb {
    14 Vec3 lo, hi;
    15  
    16 Vec3 centre() const { return 0.5f * (lo + hi); }
    17 Vec3 halfSize() const { return 0.5f * (hi - lo); }
    18 // 全方向にrだけ大きくした箱 / the box grown by r in every direction
    19 Aabb expanded(float r) const { return {lo - Vec3{r, r, r}, hi + Vec3{r, r, r}}; }
    20 };
    21  
    22 // モデル座標の箱を、Y軸周りに90°×quarterTurns回して、positionへ動かす。90°単位なら箱は箱のまま
    23 // Turns a model-space box by quarterTurns × 90° about Y and moves it to position. In 90° steps a box stays a box
    24 Aabb placeAabb(const Aabb &box, Vec3 position, int quarterTurns);
    25  
    26 // 2つの箱が重なるか(触れているだけなら重ならない) / do two boxes overlap (touching does not count)?
    27 bool overlaps(const Aabb &a, const Aabb &b);
    28  
    29 // 半直線:origin + t·direction(directionは単位ベクトル、t ≥ 0) / a ray: origin + t·direction (unit direction, t ≥ 0)
    30 struct Ray {
    31 Vec3 origin;
    32 Vec3 direction;
    33 };
    34  
    35 // レイが当たった所:距離t、面の法線、何番目の箱か / where a ray hit: distance t, the surface normal, which box
    36 struct RayHit {
    37 float t = 0.0f;
    38 Vec3 normal;
    39 int index = -1;
    40 };
    41  
    42 // レイと箱(スラブ法)。maxTより遠い当たりは無視。始点が箱の中ならt = 0、法線 = 0
    43 // Ray against a box (the slab method). Hits farther than maxT are ignored. If the origin is inside: t = 0, normal 0
    44 std::optional<RayHit> rayAabb(const Ray &ray, const Aabb &box, float maxT);
    45 // 箱の並びの中で一番近い当たり / the nearest hit among a list of boxes
    46 std::optional<RayHit> raycast(const Ray &ray, std::span<const Aabb> boxes, float maxT);
    47 // 半径radiusの球を飛ばす:箱をradiusだけ大きくしてレイを当てる(角は本当は丸いので、角の近くでは少し手前で止まる。
    48 // カメラには安全側で十分)
    49 // Casts a sphere of the given radius: a ray against the boxes grown by the radius (the real Minkowski sum has rounded
    50 // corners, so near corners this stops a little early, which is the safe side for a camera)
    51 std::optional<RayHit> sphereCast(const Ray &ray, float radius, std::span<const Aabb> boxes, float maxT);

ファイル: /dev/null | b/games/tps/src/frustum.cc

前新
@@ -0,0 +1,28 @@
    1 #include "frustum.hh"
    2  
    3 #include <cmath>
    4  
    5 Frustum Frustum::fromMatrix(const Mat4 &m) {
    6 // クリップ座標 c = M·p。視錐台の中は −w ≤ x, y, z ≤ w。例えば左の平面 x ≥ −w は (行3 + 行0)·p ≥ 0
    7 // Clip coordinates c = M·p. Inside the frustum −w ≤ x, y, z ≤ w. E.g. the left plane x ≥ −w is (row 3 + row 0)·p ≥ 0
    8 auto row = [&](int r) { return Vec4{m.at(r, 0), m.at(r, 1), m.at(r, 2), m.at(r, 3)}; };
    9 Vec4 r0 = row(0), r1 = row(1), r2 = row(2), r3 = row(3);
    10 Frustum f;
    11 f.planes[0] = r3 + r0; // 左 / left
    12 f.planes[1] = r3 - r0; // 右 / right
    13 f.planes[2] = r3 + r1; // 下 / bottom
    14 f.planes[3] = r3 - r1; // 上 / top
    15 f.planes[4] = r3 + r2; // 手前 / near
    16 f.planes[5] = r3 - r2; // 奥 / far
    17 for (Vec4 &p : f.planes) {
    18 float len = std::sqrt(p.x * p.x + p.y * p.y + p.z * p.z);
    19 p = (1.0f / len) * p; // 距離をメートルで比べられるように / so distances compare in meters
    20 }
    21 return f;
    22 }
    23  
    24 bool Frustum::sphereVisible(Vec3 c, float radius) const {
    25 for (const Vec4 &p : planes)
    26 if (p.x * c.x + p.y * c.y + p.z * c.z + p.w < -radius) return false;
    27 return true;
    28 }

ファイル: /dev/null | b/games/tps/src/frustum.hh

前新
@@ -0,0 +1,19 @@
    1 // 視錐台カリング(第36章):画面に映らない部品は描かない / frustum culling (chapter 36): pieces the camera cannot see
    2 // are not drawn
    3 #pragma once
    4  
    5 #include "engine/mathx.hh"
    6  
    7 // 視錐台の6枚の平面。法線は内向き:dot(n, p) + d ≥ 0 なら内側
    8 // The six planes of a view frustum. The normals point inwards: dot(n, p) + d ≥ 0 means inside
    9 struct Frustum {
    10 Vec4 planes[6]; // (n.x, n.y, n.z, d)、nは単位ベクトル / n is a unit vector
    11  
    12 // 投影 × ビュー行列から取り出す(Gribb-Hartmann法)。正射影の行列(影の光の箱)でも使える
    13 // Extracts the planes from projection × view (the Gribb-Hartmann method). Works for orthographic matrices too (the
    14 // shadow light box)
    15 static Frustum fromMatrix(const Mat4 &viewProjection);
    16 // 球が少しでも中にあるか(6枚のどれかの完全に外側なら見えない) / is any part of the sphere inside? (completely
    17 // outside one plane = invisible)
    18 bool sphereVisible(Vec3 centre, float radius) const;
    19 };

ファイル: /dev/null | b/games/tps/src/game.hh

前新
@@ -0,0 +1,57 @@
    1 // TPS全体で一つの共有データ。mainが作り、シーンは参照で持つ(第26章のデモと同じ形)
    2 // The data the whole TPS shares. main creates it and the scenes keep a reference (the same shape as chapter 26's demo)
    3 #pragma once
    4  
    5 #include "character.hh"
    6 #include "level.hh"
    7 #include "renderer.hh"
    8  
    9 #include "engine/camera2d.hh"
    10 #include "engine/font.hh"
    11 #include "engine/game_loop.hh"
    12 #include "engine/input.hh"
    13 #include "engine/model.hh"
    14 #include "engine/sprite_batch.hh"
    15 #include "engine/window.hh"
    16  
    17 struct Game {
    18 Window &window;
    19 Input &input;
    20 GameLoop &loop;
    21 Renderer &renderer;
    22 SpriteBatch &batch;
    23 const Font &ui; // mono16
    24 Level &level;
    25 Model &player; // player.glb(姿勢を書き込むので非const) / non-const: poses are written into it
    26 Model &rifle;
    27 const CharacterRig &playerRig;
    28 Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI
    29 Viewport uiViewport;
    30 int frame = 0; // 描いたフレームの数 / frames drawn so far
    31 int lookFrame = -1; // マウスの動きを最後に使ったフレーム / the frame whose mouse movement was last used
    32 bool showBoxes = false; // B:当たり判定の箱 / collision boxes
    33 bool showStats = false; // F3:時間と描いた数 / timings and draw counts
    34 double frameMs = 0.0; // 1フレームのCPUの時間(壁時計、表示だけ) / CPU time per frame (wall clock, display only)
    35  
    36 Vec2 unusedMouse = {0.0f, 0.0f}; // 更新のなかったフレームのマウスの動き / movement of frames that ran no update
    37  
    38 // このフレームのマウスの動き。1フレームに複数の更新ステップがあっても、最初のステップだけが受け取る
    39 // (window.mouseDelta()はフレームごとの値:ステップごとに使うと2回分回ってしまう)
    40 // This frame's mouse movement. With several update steps in one frame only the first step gets it
    41 // (window.mouseDelta() is per frame: using it in every step would turn twice as far)
    42 Vec2 takeMouseDelta() {
    43 if (lookFrame == frame || !window.cursorCaptured()) return {0.0f, 0.0f};
    44 lookFrame = frame;
    45 Vec2 delta = unusedMouse + window.mouseDelta();
    46 unusedMouse = {0.0f, 0.0f};
    47 return delta;
    48 }
    49 // 毎フレームの最後に呼ぶ:更新が1回もなかったフレーム(画面が60 Hzより速いと良くある)の動きを捨てずに、
    50 // 次のステップへ持ち越す
    51 // Call at the end of every frame: the movement of a frame that ran no update (common on screens faster than
    52 // 60 Hz) is carried over to the next step instead of being lost
    53 void keepUnusedMouse() {
    54 if (!window.cursorCaptured()) unusedMouse = {0.0f, 0.0f};
    55 else if (loop.stats().steps == 0) unusedMouse = unusedMouse + window.mouseDelta();
    56 }
    57 };

ファイル: /dev/null | b/games/tps/src/level.cc

前新
@@ -0,0 +1,203 @@
    1 #include "level.hh"
    2  
    3 #include "engine/file_util.hh"
    4  
    5 #include <algorithm>
    6 #include <cmath>
    7 #include <cstdint>
    8 #include <cstdio>
    9 #include <sstream>
    10  
    11 // 部品の番号から作る決まった乱数(インスタンスの色のばらつき用) / a fixed pseudo-random number from a piece's index
    12 // (for the per-instance tint)
    13 static float hash01(std::uint32_t x) {
    14 x ^= x >> 16;
    15 x *= 0x7feb352du;
    16 x ^= x >> 15;
    17 x *= 0x846ca68bu;
    18 x ^= x >> 16;
    19 return static_cast<float>(x >> 8) / 16777216.0f;
    20 }
    21  
    22 int Level::findType(const std::string &name) const {
    23 for (size_t i = 0; i < types.size(); ++i)
    24 if (types[i].name == name) return static_cast<int>(i);
    25 return -1;
    26 }
    27  
    28 std::optional<Level> Level::load(const std::string &path) {
    29 std::optional<std::string> text = readTextFile(path);
    30 if (!text) {
    31 fprintf(stderr, "%s: 開けない / cannot open\n", path.c_str());
    32 return std::nullopt;
    33 }
    34 Level level;
    35 std::istringstream lines(*text);
    36 std::string line;
    37 int lineNo = 0;
    38 auto fail = [&](const char *why) {
    39 fprintf(stderr, "%s:%d: %s\n", path.c_str(), lineNo, why);
    40 return std::nullopt;
    41 };
    42 // 部品を一つ置く(向きは90°単位) / places one piece (yaw in 90° steps)
    43 auto place = [&](int type, Vec3 p, float yawDegrees) -> bool {
    44 float q = yawDegrees / 90.0f;
    45 if (std::fabs(q - std::round(q)) > 1e-4f) return false;
    46 Piece piece;
    47 piece.type = type;
    48 piece.position = p;
    49 piece.quarterTurns = static_cast<int>(std::lround(q));
    50 piece.model = translate(p) * rotateY(radians(90.0f * static_cast<float>(piece.quarterTurns)));
    51 level.pieces.push_back(piece);
    52 return true;
    53 };
    54  
    55 while (std::getline(lines, line)) {
    56 ++lineNo;
    57 if (size_t hash = line.find('#'); hash != std::string::npos) line.erase(hash);
    58 std::istringstream in(line);
    59 std::string command;
    60 if (!(in >> command)) continue; // 空行 / empty line
    61 if (command == "model") {
    62 // model <名前> <GLB> [noshadow] [nocollide] [vary=0.1]
    63 PieceType type;
    64 std::string file, option;
    65 if (!(in >> type.name >> file)) return fail("model <name> <file.glb> [noshadow] [nocollide] [vary=N]");
    66 while (in >> option) {
    67 if (option == "noshadow") type.castsShadow = false;
    68 else if (option == "nocollide") type.collides = false;
    69 else if (option.rfind("vary=", 0) == 0) type.tintVariation = std::strtof(option.c_str() + 5, nullptr);
    70 else return fail("知らないオプション / unknown option");
    71 }
    72 if (level.findType(type.name) >= 0) return fail("同じ名前の部品 / duplicate piece name");
    73 type.model = Model::load(file);
    74 if (!type.model) return fail("GLBを読めない / cannot load the GLB");
    75 level.types.push_back(std::move(type));
    76 } else if (command == "box") {
    77 // box <部品> x0 y0 z0 x1 y1 z1:モデル座標の当たり判定(何個でも) / model-space collision box (any number)
    78 std::string name;
    79 Aabb b;
    80 if (!(in >> name >> b.lo.x >> b.lo.y >> b.lo.z >> b.hi.x >> b.hi.y >> b.hi.z))
    81 return fail("box <piece> x0 y0 z0 x1 y1 z1");
    82 int t = level.findType(name);
    83 if (t < 0) return fail("先にmodelで部品を宣言する / declare the piece with model first");
    84 level.types[static_cast<size_t>(t)].boxes.push_back(b);
    85 } else if (command == "solid") {
    86 // solid x0 y0 z0 x1 y1 z1:見えないワールドの箱(地面、見えない壁) / an invisible world box (ground, walls)
    87 Aabb b;
    88 if (!(in >> b.lo.x >> b.lo.y >> b.lo.z >> b.hi.x >> b.hi.y >> b.hi.z)) return fail("solid x0 y0 z0 x1 y1 z1");
    89 level.solids.push_back(b);
    90 } else if (command == "place" || command == "row" || command == "grid") {
    91 // place <部品> x y z yaw
    92 // row <部品> x y z yaw dx dz count (count個、(dx, dz)ずつずらす / count pieces, (dx, dz) apart)
    93 // grid <部品> x y z yaw step nx nz (nx × nz個、stepの間隔 / nx × nz pieces, step apart)
    94 std::string name;
    95 Vec3 p;
    96 float yaw = 0.0f;
    97 if (!(in >> name >> p.x >> p.y >> p.z >> yaw)) return fail("place/row/grid <piece> x y z yaw ...");
    98 int t = level.findType(name);
    99 if (t < 0) return fail("先にmodelで部品を宣言する / declare the piece with model first");
    100 bool ok = true;
    101 if (command == "place") {
    102 ok = place(t, p, yaw);
    103 } else if (command == "row") {
    104 float dx = 0, dz = 0;
    105 int count = 0;
    106 if (!(in >> dx >> dz >> count) || count < 1) return fail("row <piece> x y z yaw dx dz count");
    107 for (int i = 0; i < count && ok; ++i)
    108 ok = place(t, p + Vec3{dx * static_cast<float>(i), 0.0f, dz * static_cast<float>(i)}, yaw);
    109 } else {
    110 float step = 0;
    111 int nx = 0, nz = 0;
    112 if (!(in >> step >> nx >> nz) || nx < 1 || nz < 1) return fail("grid <piece> x y z yaw step nx nz");
    113 for (int i = 0; i < nz && ok; ++i)
    114 for (int j = 0; j < nx && ok; ++j)
    115 ok = place(t, p + Vec3{step * static_cast<float>(j), 0.0f, step * static_cast<float>(i)}, yaw);
    116 }
    117 if (!ok) return fail("向きは90°の倍数だけ / yaw must be a multiple of 90 degrees");
    118 } else if (command == "spawn") {
    119 float yaw = 0.0f;
    120 if (!(in >> level.spawn.x >> level.spawn.y >> level.spawn.z >> yaw)) return fail("spawn x y z yaw");
    121 level.spawnYaw = radians(yaw);
    122 } else {
    123 return fail("知らない命令 / unknown command");
    124 }
    125 }
    126  
    127 // 種類ごとの外接球と、置いた部品のワールドの箱・球・色 / per type: bounding sphere; per piece: world boxes, sphere,
    128 // tint
    129 for (PieceType &type : level.types) {
    130 type.sphereCentre = 0.5f * (type.model->boundsMin + type.model->boundsMax);
    131 type.sphereRadius = length(0.5f * (type.model->boundsMax - type.model->boundsMin));
    132 if (type.boxes.empty()) type.boxes.push_back({type.model->boundsMin, type.model->boundsMax});
    133 }
    134 level.bounds = {{1e9f, 1e9f, 1e9f}, {-1e9f, -1e9f, -1e9f}};
    135 for (size_t i = 0; i < level.pieces.size(); ++i) {
    136 Piece &piece = level.pieces[i];
    137 PieceType &type = level.types[static_cast<size_t>(piece.type)];
    138 type.pieces.push_back(static_cast<int>(i));
    139 Vec4 c = piece.model * Vec4{type.sphereCentre.x, type.sphereCentre.y, type.sphereCentre.z, 1.0f};
    140 piece.sphereCentre = {c.x, c.y, c.z};
    141 piece.sphereRadius = type.sphereRadius;
    142 float shade = 1.0f + type.tintVariation * (2.0f * hash01(static_cast<std::uint32_t>(i) * 2654435761u) - 1.0f);
    143 piece.tint = {shade, shade, shade};
    144 for (const Aabb &b : type.boxes) {
    145 Aabb w = placeAabb(b, piece.position, piece.quarterTurns);
    146 if (type.collides) level.solids.push_back(w);
    147 level.bounds.lo = {std::fmin(level.bounds.lo.x, w.lo.x), std::fmin(level.bounds.lo.y, w.lo.y),
    148 std::fmin(level.bounds.lo.z, w.lo.z)};
    149 level.bounds.hi = {std::fmax(level.bounds.hi.x, w.hi.x), std::fmax(level.bounds.hi.y, w.hi.y),
    150 std::fmax(level.bounds.hi.z, w.hi.z)};
    151 }
    152 }
    153 // インスタンスのバッファ:種類ごとに置いた数だけ。毎フレーム見える分を先頭から書き直す
    154 // Instance buffers: one per type, as large as its placements. Each frame the visible ones are rewritten from the
    155 // start
    156 for (PieceType &type : level.types) {
    157 if (type.pieces.empty()) continue;
    158 type.instances = Buffer(nullptr, static_cast<GLsizeiptr>(type.pieces.size() * sizeof(InstanceData)),
    159 GL_DYNAMIC_STORAGE_BIT);
    160 type.model->setInstanceBuffer(type.instances, sizeof(InstanceData), kInstanceLayout);
    161 }
    162 printf("%s: %zu piece types, %zu pieces, %zu collision boxes\n", path.c_str(), level.types.size(),
    163 level.pieces.size(), level.solids.size());
    164 return level;
    165 }
    166  
    167 LevelDrawStats Level::draw(const Shader &shader, const Texture2D &white, const Frustum &view) {
    168 LevelDrawStats stats;
    169 // ファイルと逆の順:床(全部の後ろ)を最後に。GPUは手前の物が先に描かれていれば、隠れたフラグメントを
    170 // シェーダーの前に捨てられる(早い深度テスト) / reverse file order: the floor (behind everything) last. A GPU can
    171 // reject hidden fragments before shading them when nearer things were drawn first (early depth test)
    172 for (auto it = types.rbegin(); it != types.rend(); ++it) {
    173 PieceType &type = *it;
    174 scratch.clear();
    175 for (int i : type.pieces) {
    176 const Piece &piece = pieces[static_cast<size_t>(i)];
    177 ++stats.total;
    178 if (!view.sphereVisible(piece.sphereCentre, piece.sphereRadius)) continue;
    179 scratch.push_back({piece.model, piece.tint});
    180 }
    181 if (scratch.empty()) continue;
    182 stats.visible += static_cast<int>(scratch.size());
    183 stats.drawCalls += static_cast<int>(type.model->primitiveCount());
    184 type.instances.update(scratch.data(), static_cast<GLsizeiptr>(scratch.size() * sizeof(InstanceData)));
    185 type.model->drawInstanced(shader, white, static_cast<GLsizei>(scratch.size()), Shading::Pbr);
    186 }
    187 return stats;
    188 }
    189  
    190 LevelDrawStats Level::drawShadows(const Shader &shadow, const Texture2D &white, const Frustum &lightBox) const {
    191 LevelDrawStats stats;
    192 for (const PieceType &type : types) {
    193 for (int i : type.pieces) {
    194 const Piece &piece = pieces[static_cast<size_t>(i)];
    195 ++stats.total;
    196 if (!type.castsShadow || !lightBox.sphereVisible(piece.sphereCentre, piece.sphereRadius)) continue;
    197 ++stats.visible;
    198 stats.drawCalls += static_cast<int>(type.model->primitiveCount());
    199 type.model->drawDepth(shadow, piece.model, white);
    200 }
    201 }
    202 return stats;
    203 }

ファイル: /dev/null | b/games/tps/src/level.hh

前新
@@ -0,0 +1,75 @@
    1 // レベル:GLBの部品をテキストファイルの通りに並べる(第36章)。部品の種類ごとにインスタンシングで描き(第19章)、
    2 // 当たり判定の箱は部品の大きさ(またはファイルに書いた箱)から作る
    3 // The level: GLB pieces placed as a text file says (chapter 36). Each piece type is drawn with instancing (chapter
    4 // 19); the collision boxes come from the pieces' bounds (or from boxes written in the file)
    5 #pragma once
    6  
    7 #include "collision3d.hh"
    8 #include "frustum.hh"
    9  
    10 #include "engine/buffer.hh"
    11 #include "engine/model.hh"
    12 #include "engine/shader.hh"
    13 #include "engine/texture.hh"
    14  
    15 #include <optional>
    16 #include <string>
    17 #include <vector>
    18  
    19 // 部品の種類:一つのGLB / a piece type: one GLB
    20 struct PieceType {
    21 std::string name;
    22 std::optional<Model> model;
    23 std::vector<Aabb> boxes; // モデル座標の当たり判定(空ならモデルの箱) / model-space collision (empty = bounds)
    24 bool castsShadow = true;
    25 bool collides = true;
    26 float tintVariation = 0.0f; // インスタンスごとの明るさのばらつき / per-instance brightness variation
    27 Vec3 sphereCentre; // モデル座標の外接球 / model-space bounding sphere
    28 float sphereRadius = 0.0f;
    29 Buffer instances; // InstanceData × 置いた数(GL_DYNAMIC_STORAGE_BIT) / InstanceData × placements
    30 std::vector<int> pieces; // この種類の部品(Level::piecesの番号) / pieces of this type (indices)
    31 };
    32  
    33 // 置いた部品一つ / one placed piece
    34 struct Piece {
    35 int type = 0;
    36 Vec3 position;
    37 int quarterTurns = 0; // Y軸周りに90°単位 / about Y in 90° steps
    38 Mat4 model;
    39 Vec3 tint = {1.0f, 1.0f, 1.0f};
    40 Vec3 sphereCentre; // ワールドの外接球(カリング用) / world-space bounding sphere (for culling)
    41 float sphereRadius = 0.0f;
    42 };
    43  
    44 // 描いた数(画面の数字とNOTES用) / how much was drawn (for the overlay and the notes)
    45 struct LevelDrawStats {
    46 int visible = 0, total = 0, drawCalls = 0;
    47 };
    48  
    49 class Level {
    50 public:
    51 // レベルのファイルを読み、使う部品のGLBも読む。失敗したら「ファイル:行: 理由」を表示してstd::nullopt
    52 // Reads a level file and the GLBs it uses. On failure prints "file:line: reason" and returns std::nullopt
    53 static std::optional<Level> load(const std::string &path);
    54  
    55 // カメラのパス:見える部品だけを種類ごとにインスタンスのバッファへ書き、1種類=プリミティブごとに1回の描画で描く。
    56 // shaderはinstanced.vert + pbr.frag
    57 // Camera pass: writes only the visible pieces of each type into its instance buffer and draws each type with one
    58 // draw call per primitive. shader = instanced.vert + pbr.frag
    59 LevelDrawStats draw(const Shader &shader, const Texture2D &white, const Frustum &view);
    60 // 影のパス:光の箱に入る部品だけを、一つずつdrawDepthで(エンジンのModelにインスタンシングの深度描画がないため)
    61 // Shadow pass: only the pieces inside the light box, one drawDepth each (the engine's Model has no instanced depth
    62 // drawing)
    63 LevelDrawStats drawShadows(const Shader &shadow, const Texture2D &white, const Frustum &lightBox) const;
    64  
    65 std::vector<PieceType> types;
    66 std::vector<Piece> pieces;
    67 std::vector<Aabb> solids; // ワールドの当たり判定の箱 / world-space collision boxes
    68 Vec3 spawn; // プレイヤーの出発点 / the player's start
    69 float spawnYaw = 0.0f; // ラジアン、0 = −Zを向く / radians, 0 = facing −Z
    70 Aabb bounds; // 全部を囲む箱 / box around everything
    71  
    72 private:
    73 int findType(const std::string &name) const;
    74 std::vector<InstanceData> scratch; // 毎フレーム使い回す / reused every frame
    75 };

ファイル: /dev/null | b/games/tps/src/main.cc

前新
@@ -0,0 +1,109 @@
    1 // 第36〜39章:三人称シューティング(TPS)。第36章:レベル、キャラクター、三人称カメラ
    2 // Chapters 36-39: the third-person shooter (TPS). Chapter 36: the level, the character and the third-person camera
    3 //
    4 // 操作 / Controls:
    5 // WASD カメラの向きに対して移動 / move relative to the camera
    6 // マウス / mouse 見回す / look around
    7 // Shift 走る(前へ) / run (forwards)
    8 // Q 右肩 ⇔ 左肩 / right ⇔ left shoulder
    9 // B 当たり判定の箱 / collision boxes
    10 // F3 時間と描いた数 / timings and draw counts
    11 // F4 視錐台カリングのオン・オフ / frustum culling on / off
    12 // C カメラだけ回す(キャラクターを前から見る) / turn only the camera (look at the character)
    13 // K カメラの当たり判定のオン・オフ / camera collision on / off
    14 // P 手続き的な姿勢のオン・オフ(読み込んだままの姿勢) / procedural pose on / off (the pose as loaded)
    15 // Tab カーソルのキャプチャ / cursor capture
    16 // Esc 終了 / quit
    17 // 実行はプロジェクトのルートから:./build/games/tps/tps / run from the project root: ./build/games/tps/tps
    18 #include "game.hh"
    19 #include "play_scene.hh"
    20  
    21 #include "engine/scene.hh"
    22  
    23 #include <chrono>
    24 #include <cstdio>
    25 #include <memory>
    26 #include <optional>
    27  
    28 int main(int argc, char **argv) {
    29 Window window;
    30 if (!window.create(1280, 720, "OpenGL Tutorial - TPS")) return 1;
    31  
    32 std::unique_ptr<Renderer> renderer = Renderer::create(window.width(), window.height());
    33 if (!renderer) return 1;
    34 window.onResize = [&](int width, int height) { renderer->resize(width, height); };
    35  
    36 // 引数でほかのレベルも読める(例:部品を並べたpieces.level) / another level can be given as an argument (e.g.
    37 // pieces.level, which lines up every piece)
    38 std::optional<Level> level = Level::load(argc > 1 ? argv[1] : "games/tps/assets/levels/arena.level");
    39 std::optional<Model> player = Model::load("games/tps/assets/models/player.glb");
    40 std::optional<Model> rifle = Model::load("games/tps/assets/models/rifle.glb");
    41 if (!level || !player || !rifle) return 1;
    42 std::optional<CharacterRig> playerRig = CharacterRig::find(*player);
    43 if (!playerRig) return 1;
    44  
    45 // HUDと文字(第25・26章の2Dの道具を3Dの絵の上に) / HUD and text (the chapter 25-26 2D toolkit over the 3D image)
    46 std::optional<SpriteBatch> batch = SpriteBatch::create();
    47 // このゲームの文字のアトラス:共有のmono16にゲームで使う漢字を足したもの(同じ作り方)
    48 // This game's font atlas: the shared mono16 plus the kanji the game uses (made the same way)
    49 std::optional<Font> ui = Font::load("games/tps/assets/fonts/mono16.fnt");
    50 if (!batch || !ui) return 1;
    51  
    52 Input input;
    53 input.attach(window);
    54 input.bind("forward", {InputBinding::key(GLFW_KEY_W), InputBinding::key(GLFW_KEY_UP)});
    55 input.bind("back", {InputBinding::key(GLFW_KEY_S), InputBinding::key(GLFW_KEY_DOWN)});
    56 input.bind("left", {InputBinding::key(GLFW_KEY_A), InputBinding::key(GLFW_KEY_LEFT)});
    57 input.bind("right", {InputBinding::key(GLFW_KEY_D), InputBinding::key(GLFW_KEY_RIGHT)});
    58 input.bind("run", {InputBinding::key(GLFW_KEY_LEFT_SHIFT)});
    59  
    60 GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5});
    61 Game game{.window = window, .input = input, .loop = loop, .renderer = *renderer, .batch = *batch, .ui = *ui,
    62 .level = *level, .player = *player, .rifle = *rifle, .playerRig = *playerRig,
    63 .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}};
    64  
    65 SceneManager scenes;
    66 scenes.push(std::make_unique<PlayScene>(game));
    67 // pushは予約だけ:更新0回の最初のフレームも描けるように、ここで適用する(シーンの更新は呼ばれない)
    68 // push only queues the request: apply it now so that the first frame (which runs no update) has a scene to draw
    69 // (no scene's update is called)
    70 scenes.update(0.0f);
    71  
    72 auto last = std::chrono::steady_clock::now();
    73 double sum[5] = {};
    74 loop.run(
    75 window, input,
    76 [&](float dt) {
    77 scenes.update(dt);
    78 if (scenes.empty()) window.close();
    79 },
    80 [&](float alpha) {
    81 // 1. 3Dの世界(影 → 場面 → 後処理 → 画面) / 1. the 3D world (shadows → scene → post → screen)
    82 scenes.draw(alpha);
    83 // 2. UI:後処理の後の画面に、2Dの道具で(色はsRGBのまま、第25章) / 2. the UI: on top of the post-processed
    84 // image with the 2D toolkit (colors stay sRGB, chapter 25)
    85 game.uiViewport = letterbox(window.width(), window.height(), game.screen.viewSize, false);
    86 game.uiViewport.apply();
    87 scenes.drawUi(alpha);
    88 scenes.drawFade(*batch, game.screen.matrix(), game.screen.viewSize);
    89 // 表示用の時間だけ壁時計で測る(ゲームの中身には使わない) / the wall clock is only for the displayed time
    90 auto now = std::chrono::steady_clock::now();
    91 game.frameMs = std::chrono::duration<double, std::milli>(now - last).count();
    92 last = now;
    93 // 60フレームの平均を標準出力へ(llvmpipeの数字は揺れるので平均で比べる) / the average of 60 frames to stdout
    94 // (llvmpipe numbers are noisy: compare averages)
    95 sum[0] += game.frameMs;
    96 sum[1] += renderer->timings.shadowMs;
    97 sum[2] += renderer->timings.sceneMs;
    98 sum[3] += renderer->timings.postMs;
    99 sum[4] += static_cast<double>(renderer->timings.sceneFragments);
    100 game.keepUnusedMouse();
    101 if (++game.frame % 60 == 0) {
    102 printf("frames %d-%d: CPU %.1f ms/frame, llvmpipe raster shadow %.1f / scene %.1f / post %.1f ms, "
    103 "scene fragments %.2f M\n",
    104 game.frame - 59, game.frame, sum[0] / 60, sum[1] / 60, sum[2] / 60, sum[3] / 60, sum[4] / 60e6);
    105 for (double &v : sum) v = 0.0;
    106 }
    107 });
    108 return 0;
    109 }

ファイル: /dev/null | b/games/tps/src/play_scene.cc

前新
@@ -0,0 +1,240 @@
    1 #include "play_scene.hh"
    2  
    3 #include <algorithm>
    4 #include <cmath>
    5 #include <cstdio>
    6 #include <format>
    7  
    8 // 角度を −π〜π に / wraps an angle into −π..π
    9 static float wrapAngle(float a) {
    10 while (a > PI) a -= 2.0f * PI;
    11 while (a < -PI) a += 2.0f * PI;
    12 return a;
    13 }
    14 // 目標の角度へ短い方の向きで近づく / approaches a target angle the short way round
    15 static float approachAngle(float current, float target, float k) { return current + wrapAngle(target - current) * k; }
    16 static float approach(float rate, float dt) { return 1.0f - std::exp(-rate * dt); }
    17  
    18 constexpr float kWalkSpeed = 3.2f; // m/s
    19 constexpr float kRunSpeed = 6.0f; // m/s(Shift)
    20 constexpr float kAcceleration = 12.0f; // 速度が目標に近づく割合(毎秒) / how fast the velocity approaches its target
    21  
    22 PlayScene::PlayScene(Game &game) : g(game) {}
    23  
    24 Vec3 PlayScene::cameraPivot() const {
    25 // CameraPivotソケット(空のノード)のワールドの位置:モデル行列 × ノードの行列の原点
    26 // The world position of the CameraPivot socket (an empty node): model matrix × the node's matrix, origin
    27 Vec4 p = characterMatrix(position, heading) * g.player.nodeTransform(g.playerRig.cameraPivot) *
    28 Vec4{0.0f, 0.0f, 0.0f, 1.0f};
    29 return {p.x, p.y, p.z};
    30 }
    31  
    32 void PlayScene::enter() {
    33 position = prevPosition = g.level.spawn;
    34 heading = prevHeading = g.level.spawnYaw;
    35 camera.yaw = g.level.spawnYaw;
    36 camera.reset(cameraPivot(), g.level.solids);
    37 prevEye = camera.eye();
    38 prevForward = camera.forward();
    39 g.window.setCursorCaptured(true);
    40 }
    41  
    42 void PlayScene::pause() {
    43 // 止まっている間に補間で揺れないように / no interpolation wobble while paused (chapter 26)
    44 prevPosition = position;
    45 prevHeading = heading;
    46 prevEye = camera.eye();
    47 prevForward = camera.forward();
    48 }
    49  
    50 void PlayScene::update(float dt) {
    51 Input &in = g.input;
    52 prevPosition = position;
    53 prevHeading = heading;
    54 prevEye = camera.eye();
    55 prevForward = camera.forward();
    56 time += dt;
    57  
    58 if (in.pressed(GLFW_KEY_ESCAPE)) scenes().pop(); // 最後のシーン → 終了 / the last scene → quit
    59 if (in.pressed(GLFW_KEY_TAB)) g.window.setCursorCaptured(!g.window.cursorCaptured());
    60 if (in.pressed(GLFW_KEY_Q)) camera.shoulderSide = -camera.shoulderSide;
    61 if (in.pressed(GLFW_KEY_B)) g.showBoxes = !g.showBoxes;
    62 if (in.pressed(GLFW_KEY_F3)) g.showStats = !g.showStats;
    63 if (in.pressed(GLFW_KEY_C)) inspect = !inspect;
    64 if (in.pressed(GLFW_KEY_K)) cameraCollision = !cameraCollision;
    65 if (in.pressed(GLFW_KEY_P)) posing = !posing;
    66 if (in.pressed(GLFW_KEY_F4)) culling = !culling;
    67  
    68 // 1. 見回す(マウスの動きはフレームごと:最初のステップだけが使う) / 1. look around (mouse movement is per frame:
    69 // only the first step uses it)
    70 Vec2 mouse = g.takeMouseDelta();
    71 camera.look(mouse.x, mouse.y);
    72  
    73 // 2. カメラに対する移動:入力(右, 前)を、カメラの水平の右と前に掛ける(ワールドの軸ではない)
    74 // 2. movement relative to the camera: the input (right, forward) times the camera's horizontal right and forward
    75 // vectors (not the world axes)
    76 Vec2 stick = {in.axis("left", "right"), in.axis("back", "forward")};
    77 if (inspect) stick = {0.0f, 0.0f}; // C:キャラクターの周りを見るだけ / C: only look around the character
    78 Vec3 wish = stick.x * camera.right() + stick.y * camera.flatForward();
    79 float wishLength = length(wish);
    80 if (wishLength > 1.0f) wish = wish / wishLength; // 斜めでも同じ速さ / same speed diagonally
    81 bool running = in.actionHeld("run") && stick.y > 0.0f;
    82 Vec3 target = (running ? kRunSpeed : kWalkSpeed) * wish;
    83 velocity = velocity + approach(kAcceleration, dt) * (target - velocity);
    84 position = position + dt * velocity; // 第36章:まだ当たり判定なし / chapter 36: no collision yet
    85  
    86 // 3. キャラクターはカメラの向きを向く(肩越しの撃ち合いの決まり)。脚は移動の向きへ
    87 // 3. the character faces where the camera looks (the over-the-shoulder shooter convention); the legs turn towards
    88 // the movement
    89 if (!inspect) heading = approachAngle(heading, camera.yaw, approach(14.0f, dt));
    90 float speed = length(Vec3{velocity.x, 0.0f, velocity.z});
    91 float legTarget = 0.0f, direction = 1.0f;
    92 if (speed > 0.2f) {
    93 // 速度をキャラクターの座標へ:+Zが前、+Xが左(右手系で+Zを向くと+Xは左) / velocity in character space: +Z is
    94 // forward, +X is LEFT (facing +Z in a right-handed system, +X is on the left)
    95 Vec3 fwd = {std::sin(heading), 0.0f, -std::cos(heading)}, rgt = {std::cos(heading), 0.0f, std::sin(heading)};
    96 float mz = dot(velocity, fwd), mx = -dot(velocity, rgt);
    97 legTarget = std::atan2(mx, mz);
    98 if (std::fabs(legTarget) > radians(100.0f)) { // 後ろ歩き:脚は前を向いたまま逆に回す / walking backwards
    99 legTarget = wrapAngle(legTarget - PI);
    100 direction = -1.0f;
    101 }
    102 legTarget = std::clamp(legTarget, radians(-70.0f), radians(70.0f));
    103 }
    104 pose.legYaw = approachAngle(pose.legYaw, legTarget, approach(10.0f, dt));
    105 // 歩きの周期は進んだ距離に比例:足が地面を滑らない / the walk cycle advances with distance: feet do not skate
    106 float run = std::clamp((speed - kWalkSpeed) / (kRunSpeed - kWalkSpeed), 0.0f, 1.0f);
    107 float cycleLength = 1.5f + 0.9f * run; // 1周期(2歩)のm / meters per cycle (two steps)
    108 pose.walkPhase = std::fmod(pose.walkPhase + direction * 2.0f * PI * speed * dt / cycleLength, 2.0f * PI);
    109 pose.walkAmount = std::clamp(speed / kWalkSpeed, 0.0f, 1.0f);
    110 pose.stride = 1.0f + 0.5f * run;
    111 if (!inspect) pose.aimPitch = camera.pitch;
    112  
    113 // 4. カメラ:CameraPivotソケットを追う / 4. the camera follows the CameraPivot socket
    114 // (Kで当たり判定なしのカメラと比べられる) / (K compares with a camera that ignores the walls)
    115 camera.update(cameraPivot(), cameraCollision ? std::span<const Aabb>(g.level.solids) : std::span<const Aabb>(), dt);
    116 }
    117  
    118 void PlayScene::drawCharacters(const Shader &shader, bool depthOnly, Vec3 eye) {
    119 // 前のステップと今のステップの間をdrawAlphaで補間(第26章) / interpolate between the last and the current step
    120 // with drawAlpha (chapter 26)
    121 Mat4 m = characterMatrix(lerp(prevPosition, position, drawAlpha), approachAngle(prevHeading, heading, drawAlpha));
    122 if (posing) applyPose(g.player, g.rifle, g.playerRig, pose);
    123 else g.player.nodes = g.playerRig.rest; // P:読み込んだままの姿勢 / P: the pose as loaded
    124 Mat4 w = weaponMatrix(g.player, g.playerRig, m);
    125 if (depthOnly) {
    126 g.player.drawDepth(shader, m, g.renderer.white);
    127 g.rifle.drawDepth(shader, w, g.renderer.white);
    128 } else {
    129 g.player.draw(shader, m, g.renderer.white, ModelPass::Opaque, eye, Shading::Pbr);
    130 g.rifle.draw(shader, w, g.renderer.white, ModelPass::Opaque, eye, Shading::Pbr);
    131 }
    132 }
    133  
    134 void PlayScene::drawDebugBoxes() {
    135 // 当たり判定の箱を線で(unlit、HDRの色) / the collision boxes as lines (unlit, HDR color)
    136 const Shader &s = *g.renderer.unlit;
    137 s.use();
    138 s.set("uColor", Vec3{0.1f, 1.2f, 0.3f});
    139 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    140 glDisable(GL_CULL_FACE);
    141 for (const Aabb &b : g.level.solids) {
    142 s.set("uModel", translate(b.centre()) * scale(b.hi - b.lo));
    143 g.renderer.cube.draw();
    144 }
    145 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    146 // ソケット(空のノード)を小さな箱で、体に隠れないように深度テストなしで:CameraPivot 水色、Weapon 紫、
    147 // 両手 黄色、Muzzle 赤
    148 // The sockets (empty nodes) as small boxes, without the depth test so the body does not hide them: CameraPivot
    149 // cyan, Weapon magenta, the hands yellow, Muzzle red
    150 glDisable(GL_DEPTH_TEST);
    151 Mat4 m = characterMatrix(lerp(prevPosition, position, drawAlpha), approachAngle(prevHeading, heading, drawAlpha));
    152 auto marker = [&](const Mat4 &socket, Vec3 color) {
    153 s.set("uColor", color);
    154 s.set("uModel", socket * scale({0.07f, 0.07f, 0.07f}));
    155 g.renderer.cube.draw();
    156 };
    157 const CharacterRig &rig = g.playerRig;
    158 marker(m * g.player.nodeTransform(rig.cameraPivot), {0.0f, 2.0f, 2.0f});
    159 marker(m * g.player.nodeTransform(rig.weapon), {2.0f, 0.0f, 2.0f});
    160 marker(m * g.player.nodeTransform(rig.hand[0]), {2.0f, 2.0f, 0.0f});
    161 marker(m * g.player.nodeTransform(rig.hand[1]), {2.0f, 2.0f, 0.0f});
    162 int muzzle = g.rifle.findNode("Muzzle");
    163 if (muzzle >= 0) marker(weaponMatrix(g.player, rig, m) * g.rifle.nodeTransform(muzzle), {3.0f, 0.1f, 0.1f});
    164 glEnable(GL_DEPTH_TEST);
    165 glEnable(GL_CULL_FACE);
    166 }
    167  
    168 void PlayScene::draw(float alpha) {
    169 drawAlpha = alpha;
    170 Renderer &r = g.renderer;
    171 FrameView view;
    172 view.eye = lerp(prevEye, camera.eye(), alpha);
    173 view.forward = normalize(lerp(prevForward, camera.forward(), alpha));
    174 view.fovY = camera.fovY;
    175 view.aspect = static_cast<float>(g.window.width()) / static_cast<float>(g.window.height());
    176 view.time = time;
    177  
    178 // 昼の光(第21・24章の値):太陽と、Blinn-Phong用の環境光(PBRは空のIBL) / daylight (the chapter 21/24 values):
    179 // the sun and the Blinn-Phong ambient (PBR uses the sky's IBL)
    180 LightSet lights;
    181 lights.ambient = {0.20f, 0.24f, 0.33f};
    182 lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {2.6f, 2.45f, 2.2f}};
    183 r.beginFrame(view, lights);
    184  
    185 // カメラが体の中に入ったら(壁際で寄せられて)自分を描かない:頭や胴の内側が映る。肩へずらしているので、
    186 // 距離が短いだけでは入らない:体の軸からの水平距離で決める
    187 // When the camera ends up inside the body (pulled in at a wall) do not draw the player: we would see the inside of
    188 // the head or torso. Thanks to the shoulder offset a short distance alone does not mean that: decide by the
    189 // horizontal distance from the body's axis
    190 Vec3 feet = lerp(prevPosition, position, alpha);
    191 float axisDistance = length(Vec3{view.eye.x - feet.x, 0.0f, view.eye.z - feet.z});
    192 bool drawPlayer = axisDistance > 0.5f || view.eye.y > feet.y + 2.0f;
    193  
    194 // 1. 影 / 1. shadows
    195 if (r.beginShadows()) {
    196 shadowStats = g.level.drawShadows(*r.shadow, r.white, r.lightFrustum());
    197 drawCharacters(*r.shadow, true, view.eye);
    198 r.endShadows();
    199 }
    200 // 2. 場面 / 2. the scene
    201 r.beginScene();
    202 // 手前の物から:キャラクター → レベル(床は最後) / nearest first: the character → the level (floor last)
    203 r.pbr->use();
    204 if (drawPlayer) drawCharacters(*r.pbr, false, view.eye);
    205 r.pbrInstanced->use();
    206 // F4:カリングなし(全部の部品をインスタンスのバッファへ)と比べる。平面(0, 0, 0, 1)なら全部が内側
    207 // F4: compare with no culling (every piece goes into the instance buffers). Planes (0, 0, 0, 1) keep everything in
    208 Frustum everything;
    209 for (Vec4 &plane : everything.planes) plane = {0.0f, 0.0f, 0.0f, 1.0f};
    210 levelStats = g.level.draw(*r.pbrInstanced, r.white, culling ? r.viewFrustum() : everything);
    211 if (g.showBoxes) drawDebugBoxes();
    212 r.drawSky();
    213 r.endScene();
    214 // 3. 後処理 → 画面 / 3. post-processing → the screen
    215 r.present(g.window.width(), g.window.height());
    216 }
    217  
    218 void PlayScene::drawUi(float /*alpha*/) {
    219 SpriteBatch &batch = g.batch;
    220 batch.begin(g.screen.matrix());
    221 const TextStyle small{.color = {1.0f, 1.0f, 1.0f, 0.85f}, .shadow = {0.0f, 0.0f, 0.0f, 0.8f}};
    222 if (g.showStats) {
    223 const Renderer &r = g.renderer;
    224 std::string lines = std::format(
    225 "CPU frame {:.1f} ms (wall clock) llvmpipe raster: shadow {:.1f} ms, scene {:.1f} ms, post {:.1f} ms\n"
    226 "level pieces drawn {}/{} ({} draw calls) shadow casters {} ({} draw calls) shadow texel {:.1f} mm\n"
    227 "camera distance {:.2f} m{}{} collision boxes {} culling {} scene fragments {:.2f} M",
    228 g.frameMs, r.timings.shadowMs, r.timings.sceneMs, r.timings.postMs, levelStats.visible, levelStats.total,
    229 levelStats.drawCalls, shadowStats.visible, shadowStats.drawCalls, r.shadowTexelMm(),
    230 camera.currentDistance(), camera.blocked() ? " (pulled in by a wall)" : "",
    231 cameraCollision ? "" : " (camera collision OFF)", g.level.solids.size(), culling ? "on" : "OFF (F4)",
    232 static_cast<double>(r.timings.sceneFragments) / 1e6);
    233 batch.drawRect({0.0f, 0.0f, 1280.0f, 68.0f}, {0.0f, 0.0f, 0.0f, 0.45f});
    234 g.ui.draw(batch, lines, {10.0f, 6.0f}, small);
    235 }
    236 g.ui.draw(batch, "WASD 移動 / move マウス / mouse: look Shift 走る / run Q 肩 / shoulder B 箱 / boxes F3",
    237 {640.0f, 694.0f}, {.color = {1.0f, 1.0f, 1.0f, 0.7f}, .align = TextAlign::Centre,
    238 .shadow = {0.0f, 0.0f, 0.0f, 0.8f}});
    239 batch.end();
    240 }

ファイル: /dev/null | b/games/tps/src/play_scene.hh

前新
@@ -0,0 +1,44 @@
    1 // 遊ぶシーン(第36章):レベルの中をキャラクターで歩き回る。カメラの向きに対して動き、カメラは壁を避けて付いてくる
    2 // The play scene (chapter 36): walk a character around the level. It moves relative to the camera, and the camera
    3 // follows without entering walls
    4 #pragma once
    5  
    6 #include "game.hh"
    7 #include "third_person_camera.hh"
    8  
    9 #include "engine/scene.hh"
    10  
    11 class PlayScene : public Scene {
    12 public:
    13 explicit PlayScene(Game &game);
    14 void enter() override;
    15 void pause() override;
    16 void update(float dt) override;
    17 void draw(float alpha) override;
    18 void drawUi(float alpha) override;
    19  
    20 private:
    21 // 見えるもの全部(影のパスと場面のパスで同じ物を描く) / everything visible (the shadow and the scene pass draw
    22 // the same things)
    23 void drawCharacters(const Shader &shader, bool depthOnly, Vec3 eye);
    24 void drawDebugBoxes();
    25 Vec3 cameraPivot() const;
    26  
    27 Game &g;
    28 ThirdPersonCamera camera;
    29 Vec3 prevEye, prevForward; // 前のステップのカメラ(補間用) / last step's camera (for interpolation)
    30  
    31 // プレイヤー(第37章で当たり判定と重力が付く) / the player (chapter 37 adds collision and gravity)
    32 Vec3 position, prevPosition;
    33 Vec3 velocity;
    34 float heading = 0.0f, prevHeading = 0.0f; // カメラのyawと同じ決まり / same convention as the camera yaw
    35 CharacterPose pose;
    36 float time = 0.0f;
    37 bool inspect = false; // C:カメラだけ回す(キャラクターを前から見る) / C: turn only the camera (to see
    38 // the character from the front)
    39 bool cameraCollision = true; // K:カメラの当たり判定 / camera collision
    40 bool culling = true; // F4:視錐台カリング / frustum culling
    41 bool posing = true; // P:手続き的な姿勢 / procedural pose
    42 float drawAlpha = 1.0f; // drawの補間の割合 / draw's interpolation factor
    43 LevelDrawStats levelStats, shadowStats;
    44 };

ファイル: /dev/null | b/games/tps/src/renderer.cc

前新
@@ -0,0 +1,164 @@
    1 #include "renderer.hh"
    2  
    3 #include "engine/shapes.hh"
    4  
    5 #include <cmath>
    6 #include <cstdio>
    7  
    8 FragmentCounter::FragmentCounter() { glCreateQueries(GL_SAMPLES_PASSED, kQueries, queries); }
    9  
    10 FragmentCounter::~FragmentCounter() { glDeleteQueries(kQueries, queries); }
    11  
    12 void FragmentCounter::begin() {
    13 if (pending[next]) return; // 前の結果がまだ:今回は数えない / previous result not read yet: skip
    14 glBeginQuery(GL_SAMPLES_PASSED, queries[next]);
    15 running = true;
    16 }
    17  
    18 void FragmentCounter::end() {
    19 if (!running) return;
    20 glEndQuery(GL_SAMPLES_PASSED);
    21 pending[next] = true;
    22 next = (next + 1) % kQueries;
    23 running = false;
    24 }
    25  
    26 long long FragmentCounter::latest() {
    27 for (int i = 0; i < kQueries; ++i) {
    28 int k = (next + i) % kQueries; // 古い順 / oldest first
    29 if (!pending[k]) continue;
    30 GLint ready = 0;
    31 glGetQueryObjectiv(queries[k], GL_QUERY_RESULT_AVAILABLE, &ready);
    32 if (!ready) continue;
    33 GLuint64 v = 0;
    34 glGetQueryObjectui64v(queries[k], GL_QUERY_RESULT, &v);
    35 value = static_cast<long long>(v);
    36 pending[k] = false;
    37 }
    38 return value;
    39 }
    40  
    41 Mat4 FrameView::view() const { return lookAt(eye, eye + forward, {0.0f, 1.0f, 0.0f}); }
    42 Mat4 FrameView::projection() const { return perspectiveGl(fovY, aspect, nearPlane, farPlane); }
    43  
    44 std::unique_ptr<Renderer> Renderer::create(int width, int height, const RenderSettings &settings) {
    45 std::unique_ptr<Renderer> r(new Renderer());
    46 r->settings = settings;
    47 r->pbr = Shader::load("engine/shaders/phong.vert", "engine/shaders/pbr.frag");
    48 r->pbrInstanced = Shader::load("games/tps/shaders/instanced.vert", "engine/shaders/pbr.frag");
    49 r->shadow = Shader::load("engine/shaders/shadow.vert", "engine/shaders/shadow.frag");
    50 r->unlit = Shader::load("engine/shaders/unlit.vert", "engine/shaders/unlit.frag");
    51 r->skybox = Shader::load("engine/shaders/skybox.vert", "engine/shaders/skybox.frag");
    52 // 空は色の画像なのでsRGB(第21章) / the sky is a color image: sRGB (chapter 21)
    53 r->sky = Cubemap::loadDirectory("assets/textures/sky", ".png", true);
    54 if (!r->pbr || !r->pbrInstanced || !r->shadow || !r->unlit || !r->skybox || !r->sky) return nullptr;
    55 // 新しいプログラムも含めて、全部のブロックの大きさをC++の構造体と比べる(第19章からの決まり)
    56 // Check every block of every program (including the new one) against the C++ structs (the rule since chapter 19)
    57 for (const Shader *s : {&*r->pbr, &*r->pbrInstanced, &*r->shadow, &*r->unlit, &*r->skybox})
    58 if (!s->checkUniformBlock("Camera", sizeof(CameraBlock)) || !s->checkUniformBlock("Lights", sizeof(LightsBlock)) ||
    59 !s->checkUniformBlock("Post", sizeof(PostBlock)) || !s->checkUniformBlock("Shadow", sizeof(ShadowBlock)))
    60 return nullptr;
    61  
    62 // IBLを作る前にシームレスなフィルタリング(第18・24章) / seamless filtering before building the IBL (ch. 18, 24)
    63 glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
    64 r->ibl = Ibl::build(*r->sky);
    65 r->shadowMap.emplace(settings.shadowMapSize);
    66 r->post = PostChain::create(width, height, settings.post);
    67 if (!r->ibl || !r->shadowMap->complete() || !r->post) return nullptr;
    68  
    69 const unsigned char whitePixel[4] = {255, 255, 255, 255};
    70 r->white = Texture2D::fromPixels(whitePixel, 1, 1, {.flipY = false, .mipmaps = false});
    71 r->cube = makeCube();
    72 return r;
    73 }
    74  
    75 void Renderer::beginFrame(const FrameView &view, const LightSet &lights) {
    76 current = view;
    77 sunDirection = lights.directional.direction;
    78 CameraBlock camera;
    79 camera.view = view.view();
    80 camera.proj = view.projection();
    81 camera.viewPos = view.eye;
    82 camera.time = view.time;
    83 cameraUbo.update(camera);
    84 lightsUbo.update(lights.toBlock());
    85 cameraFrustum = Frustum::fromMatrix(camera.proj * camera.view);
    86 post->settings.exposure = std::exp2(exposureEv);
    87 post->settings.bloomStrength = 0.08f;
    88 }
    89  
    90 bool Renderer::beginShadows() {
    91 // 光の箱をカメラの視錐台の0.1〜shadowDistance mを囲む球に合わせる(第23章のJ、エンジンのfrustumSphere)。
    92 // 球なのでカメラが回っても箱の大きさは同じ、中心はテクセル単位で動く → 影の縁がちらつかない
    93 // Fit the light box to the sphere around 0.1..shadowDistance m of the camera frustum (chapter 23's J, the engine's
    94 // frustumSphere). A sphere keeps the box size constant while the camera turns, and its center moves in whole texels:
    95 // shadow edges do not shimmer
    96 BoundingSphere fit = frustumSphere(current.eye, current.forward, current.fovY, current.aspect, current.nearPlane,
    97 settings.shadowDistance);
    98 shadowTimer.begin();
    99 bool draw = shadowMap->begin(sunDirection, fit, ShadowBias{}, ShadowFilter::Pcf3x3, settings.shadows);
    100 lightBox = Frustum::fromMatrix(shadowMap->block().lightSpace);
    101 if (draw) {
    102 shadow->use();
    103 shadow->set("uAlphaMask", 0);
    104 } else {
    105 shadowTimer.end();
    106 }
    107 return draw;
    108 }
    109  
    110 void Renderer::endShadows() {
    111 shadowTimer.end();
    112 glEnable(GL_CULL_FACE);
    113 glCullFace(GL_BACK);
    114 }
    115  
    116 void Renderer::setFrameUniforms(const Shader &s) const {
    117 s.set("uViewMode", 0);
    118 s.set("uEnvironmentTint", Vec3{1.0f, 1.0f, 1.0f});
    119 s.set("uLighting", 0);
    120 }
    121  
    122 void Renderer::beginScene() {
    123 shadowMap->end(); // 深度テクスチャをユニット5へ(影を切っていてもUBOが「影なし」と言う) / depth → unit 5
    124 sceneTimer.begin();
    125 post->beginScene();
    126 sceneFragments.begin();
    127 glEnable(GL_DEPTH_TEST);
    128 glDepthFunc(GL_LESS);
    129 glDepthMask(GL_TRUE);
    130 glEnable(GL_CULL_FACE);
    131 glDisable(GL_BLEND);
    132 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    133 sky->bind(3);
    134 ibl->bind();
    135 setFrameUniforms(*pbr);
    136 setFrameUniforms(*pbrInstanced);
    137 }
    138  
    139 void Renderer::drawSky() {
    140 glDepthFunc(GL_LEQUAL);
    141 glDisable(GL_CULL_FACE);
    142 skybox->use();
    143 skybox->set("uEnvironmentTint", Vec3{1.0f, 1.0f, 1.0f});
    144 cube.draw();
    145 glEnable(GL_CULL_FACE);
    146 glDepthFunc(GL_LESS);
    147 }
    148  
    149 void Renderer::endScene() {
    150 sceneFragments.end();
    151 post->endScene();
    152 sceneTimer.end();
    153 }
    154  
    155 void Renderer::present(int windowWidth, int windowHeight) {
    156 postTimer.begin();
    157 post->present(windowWidth, windowHeight, 0);
    158 postTimer.end();
    159 if (std::optional<double> ms = shadowTimer.latestMs()) timings.shadowMs = *ms;
    160 if (std::optional<double> ms = sceneTimer.latestMs()) timings.sceneMs = *ms;
    161 if (std::optional<double> ms = postTimer.latestMs()) timings.postMs = *ms;
    162 if (!settings.shadows) timings.shadowMs = 0.0;
    163 timings.sceneFragments = sceneFragments.latest();
    164 }

ファイル: /dev/null | b/games/tps/src/renderer.hh

前新
@@ -0,0 +1,144 @@
    1 // TPSの3Dのフレーム(第36章):第23・24章の流れをエンジンの部品(ShadowMap・PostChain・Ibl)で組む。
    2 // 1. 影:太陽の箱をカメラの視錐台の手前20 mに合わせる(レベルは第23章の場面より大きい)
    3 // 2. 場面:HDRのFBOに、空・IBL・PBR(pbr.frag)・影で描く
    4 // 3. 後処理:ブルーム、露出、トーンマッピング、sRGB → 画面
    5 // The TPS's 3D frame (chapter 36): the chapter 23/24 pipeline built from the engine's pieces (ShadowMap, PostChain,
    6 // Ibl):
    7 // 1. shadows: the sun's box is fitted to the first 20 m of the camera frustum (the level is bigger than the
    8 // chapter 23 scene)
    9 // 2. scene: into the HDR FBO with the sky, IBL, PBR (pbr.frag) and shadows
    10 // 3. post: bloom, exposure, tone mapping, sRGB → the screen
    11 #pragma once
    12  
    13 #include "frustum.hh"
    14  
    15 #include "engine/cubemap.hh"
    16 #include "engine/gpu_timer.hh"
    17 #include "engine/ibl.hh"
    18 #include "engine/lights.hh"
    19 #include "engine/mesh.hh"
    20 #include "engine/renderer3d.hh"
    21 #include "engine/shader.hh"
    22 #include "engine/texture.hh"
    23 #include "engine/uniforms.hh"
    24  
    25 #include <memory>
    26 #include <optional>
    27  
    28 // このフレームのカメラ / this frame's camera
    29 struct FrameView {
    30 Vec3 eye;
    31 Vec3 forward; // 単位ベクトル / unit vector
    32 float fovY = radians(55.0f);
    33 float aspect = 16.0f / 9.0f;
    34 float nearPlane = 0.1f, farPlane = 120.0f;
    35 float time = 0.0f; // シェーダーのuTime / the shaders' uTime
    36  
    37 Mat4 view() const;
    38 Mat4 projection() const;
    39 };
    40  
    41 // 速さと見た目の兼ね合い(llvmpipeでも動くように既定は軽め) / speed vs. quality (light defaults so that llvmpipe
    42 // copes)
    43 struct RenderSettings {
    44 int shadowMapSize = 2048;
    45 float shadowDistance = 20.0f; // 影を付ける範囲(カメラからm) / shadows cover this far from the camera (m)
    46 bool shadows = true;
    47 // MSAAなし、R11F_G11F_B10F(RGBA16Fの半分の大きさ)、ブルーム3組 / no MSAA, R11F_G11F_B10F (half the size of
    48 // RGBA16F), 3 bloom pass pairs
    49 PostChainSettings post = {.samples = 0, .format = GL_R11F_G11F_B10F, .bloomPasses = 3};
    50 };
    51  
    52 // 深度テストを通ったフラグメントを数えるクエリ(GL_SAMPLES_PASSED、遮蔽クエリ)。GpuTimerと同じく4つを順に使い、
    53 // 結果を待たない。llvmpipeの時間は他の処理で大きく揺れるが、この数は毎回同じ:1フレームの重さの正直な目安
    54 // A query counting the fragments that pass the depth test (GL_SAMPLES_PASSED, an occlusion query). Like GpuTimer it
    55 // cycles through 4 queries and never waits. llvmpipe's times swing with other load, but this count is the same every
    56 // run: an honest measure of a frame's weight
    57 class FragmentCounter {
    58 public:
    59 FragmentCounter();
    60 ~FragmentCounter();
    61 FragmentCounter(const FragmentCounter &) = delete;
    62 FragmentCounter &operator=(const FragmentCounter &) = delete;
    63 void begin();
    64 void end();
    65 // 最新の結果(まだなければ前の値) / the latest result (the previous one while none is ready)
    66 long long latest();
    67  
    68 private:
    69 static constexpr int kQueries = 4;
    70 GLuint queries[kQueries] = {};
    71 bool pending[kQueries] = {};
    72 int next = 0;
    73 bool running = false;
    74 long long value = 0;
    75 };
    76  
    77 // パスごとの時間(ms)。llvmpipeではGPUの時間ではなく、CPUがラスタライズした時間 / per-pass times (ms). On llvmpipe
    78 // these are the CPU rasterizer's times, not GPU times
    79 struct RenderTimings {
    80 double shadowMs = 0.0, sceneMs = 0.0, postMs = 0.0;
    81 long long sceneFragments = 0; // 場面のパスで深度テストを通ったフラグメント / scene-pass fragments that passed depth
    82 };
    83  
    84 class Renderer {
    85 public:
    86 // シェーダー・空・IBL・影の地図・後処理を用意する。GpuTimerなどが動かせないので、ヒープに作って返す
    87 // Loads the shaders, the sky, the IBL, the shadow map and the post chain. Returned on the heap (GpuTimer and the
    88 // UBOs are not movable)
    89 static std::unique_ptr<Renderer> create(int width, int height, const RenderSettings &settings = {});
    90 Renderer(const Renderer &) = delete;
    91 Renderer &operator=(const Renderer &) = delete;
    92  
    93 // UBO(カメラ・光・後処理の設定)を書く / writes the UBOs (camera, lights, post settings)
    94 void beginFrame(const FrameView &view, const LightSet &lights);
    95 // 影のパスの始まり:trueなら影を落とす物をshadowシェーダー+Model::drawDepthで描き、endShadowsを呼ぶ
    96 // Starts the shadow pass: if it returns true, draw the casters with the shadow shader + Model::drawDepth, then call
    97 // endShadows
    98 bool beginShadows();
    99 void endShadows();
    100 // 光の箱(影の地図に入る範囲)の視錐台:影のパスのカリング用 / the light box as a frustum: culling for the shadow pass
    101 const Frustum &lightFrustum() const { return lightBox; }
    102 // カメラの視錐台 / the camera's frustum
    103 const Frustum &viewFrustum() const { return cameraFrustum; }
    104  
    105 // 場面のパス:HDRのFBOに切り替え、クリアし、空とIBLを繋ぐ / scene pass: binds the HDR FBO, clears, binds sky + IBL
    106 void beginScene();
    107 // 空(不透明な物の後、半透明の前) / the sky box (after the opaque objects, before the transparent ones)
    108 void drawSky();
    109 // 解決とブルーム / resolve and bloom
    110 void endScene();
    111 // 画面へ(後処理)。この後は既定のフレームバッファ / to the screen (post); afterwards the default framebuffer is bound
    112 void present(int windowWidth, int windowHeight);
    113 void resize(int width, int height) { post->resize(width, height); }
    114  
    115 // ゲームが描くのに使うもの / what the game draws with
    116 std::optional<Shader> pbr; // phong.vert + pbr.frag:一つずつ描く物 / single objects
    117 std::optional<Shader> pbrInstanced; // instanced.vert + pbr.frag:レベルの部品 / level pieces
    118 std::optional<Shader> shadow; // shadow.vert + shadow.frag
    119 std::optional<Shader> unlit; // 光らない一色(デバッグの箱) / unlit color (debug boxes)
    120 Texture2D white;
    121 Mesh cube; // 1 × 1 × 1、中心が原点 / centered unit cube
    122  
    123 RenderSettings settings;
    124 RenderTimings timings; // 数フレーム遅れの値 / values a few frames old
    125 float exposureEv = 0.0f;
    126 float shadowTexelMm() const { return 1000.0f * shadowMap->metresPerTexel(); }
    127  
    128 private:
    129 Renderer() = default;
    130 void setFrameUniforms(const Shader &s) const;
    131  
    132 std::optional<Shader> skybox;
    133 std::optional<Cubemap> sky;
    134 std::optional<Ibl> ibl;
    135 std::optional<ShadowMap> shadowMap;
    136 std::optional<PostChain> post;
    137 UniformBuffer<CameraBlock> cameraUbo{kCameraBinding};
    138 UniformBuffer<LightsBlock> lightsUbo{kLightsBinding};
    139 GpuTimer shadowTimer, sceneTimer, postTimer;
    140 FragmentCounter sceneFragments;
    141 FrameView current;
    142 Vec3 sunDirection = {-0.5f, -1.0f, -0.35f};
    143 Frustum lightBox, cameraFrustum;
    144 };

ファイル: /dev/null | b/games/tps/src/third_person_camera.cc

前新
@@ -0,0 +1,59 @@
    1 #include "third_person_camera.hh"
    2  
    3 #include <algorithm>
    4 #include <cmath>
    5  
    6 void ThirdPersonCamera::look(float dxPixels, float dyPixels) {
    7 yaw += dxPixels * sensitivity;
    8 pitch = std::clamp(pitch - dyPixels * sensitivity, radians(-60.0f), radians(50.0f));
    9 }
    10  
    11 Vec3 ThirdPersonCamera::forward() const {
    12 return {std::cos(pitch) * std::sin(yaw), std::sin(pitch), -std::cos(pitch) * std::cos(yaw)};
    13 }
    14 Vec3 ThirdPersonCamera::flatForward() const { return {std::sin(yaw), 0.0f, -std::cos(yaw)}; }
    15 Vec3 ThirdPersonCamera::right() const { return {std::cos(yaw), 0.0f, std::sin(yaw)}; }
    16  
    17 // 指数的な近づき方:毎秒rateの割合で目標へ(ステップの長さによらない) / exponential smoothing: approaches the target
    18 // at `rate` per second, independent of the step length
    19 static float approach(float rate, float dt) { return 1.0f - std::exp(-rate * dt); }
    20  
    21 void ThirdPersonCamera::update(Vec3 pivot, std::span<const Aabb> solids, float dt) {
    22 // 1. 注視点を追う:水平は速く、上下はゆっくり(ジャンプや段差でカメラが跳ねない)
    23 // 1. follow the pivot: quickly sideways, slowly up and down (jumps and steps do not jolt the camera)
    24 float kxz = approach(25.0f, dt), ky = approach(8.0f, dt);
    25 smoothPivot = {smoothPivot.x + (pivot.x - smoothPivot.x) * kxz, smoothPivot.y + (pivot.y - smoothPivot.y) * ky,
    26 smoothPivot.z + (pivot.z - smoothPivot.z) * kxz};
    27 side += (shoulderSide - side) * approach(10.0f, dt);
    28  
    29 // 2. 肩へずらす。横に壁があればそこまで / 2. offset to the shoulder, but not into a wall at the side
    30 Vec3 offset = (shoulderOffset * side) * right();
    31 float offsetLength = length(offset);
    32 shoulderPos = smoothPivot + offset;
    33 if (offsetLength > 1e-4f) {
    34 Ray sideways{smoothPivot, offset / offsetLength};
    35 if (std::optional<RayHit> hit = sphereCast(sideways, probeRadius, solids, offsetLength))
    36 shoulderPos = smoothPivot + std::fmax(hit->t - 0.02f, 0.0f) * sideways.direction;
    37 }
    38  
    39 // 3. 肩から後ろへ球を飛ばす。当たったら、その手前までしか下がれない
    40 // 3. cast the sphere backwards from the shoulder. If it hits, the camera may only go back as far as the hit
    41 Ray back{shoulderPos, -forward()};
    42 float allowed = distance;
    43 std::optional<RayHit> hit = sphereCast(back, probeRadius, solids, distance);
    44 hitWall = hit.has_value();
    45 if (hit) allowed = std::fmax(hit->t - 0.05f, 0.0f);
    46  
    47 // 4. 寄るときはすぐ(壁の中を映さない)、離れるときはゆっくり(壁を回り込んだ後にカメラが飛ばない)
    48 // 4. move in immediately (never show the inside of a wall), move out slowly (no jump after rounding a corner)
    49 if (allowed < dist) dist = allowed;
    50 else dist += (allowed - dist) * approach(4.0f, dt);
    51 eyePos = shoulderPos + dist * back.direction;
    52 }
    53  
    54 void ThirdPersonCamera::reset(Vec3 pivot, std::span<const Aabb> solids) {
    55 smoothPivot = pivot;
    56 side = shoulderSide;
    57 dist = distance;
    58 update(pivot, solids, 0.0f);
    59 }

ファイル: /dev/null | b/games/tps/src/third_person_camera.hh

前新
@@ -0,0 +1,44 @@
    1 // 三人称カメラ(第36章):キャラクターの肩越しに、注視点(CameraPivotソケット)の周りを回る。
    2 // 壁にめり込まないように、注視点から後ろへ球を飛ばし(スフィアキャスト)、当たったら手前に寄せる
    3 // The third-person camera (chapter 36): over the character's shoulder, orbiting the pivot (the CameraPivot socket).
    4 // To stay out of walls it casts a sphere backwards from the pivot (a sphere cast) and moves in where it hits
    5 #pragma once
    6  
    7 #include "collision3d.hh"
    8  
    9 #include <span>
    10  
    11 class ThirdPersonCamera {
    12 public:
    13 float yaw = 0.0f; // ラジアン:0で−Zを向き、正で右へ回る(エンジンのCameraと同じ) / radians: 0 looks
    14 // down −Z, positive turns right (like the engine's Camera)
    15 float pitch = radians(-8.0f); // 正で上を向く / positive looks up
    16 float sensitivity = 0.0025f; // ラジアン毎ピクセル / radians per pixel
    17 float distance = 3.6f; // 肩からの距離(何もなければ) / distance from the shoulder (when nothing is in the way)
    18 float shoulderOffset = 0.7f; // 右へのずらし(m) / sideways offset (m)
    19 float shoulderSide = 1.0f; // +1 = 右肩、−1 = 左肩(Q) / +1 = right shoulder, −1 = left (Q)
    20 float probeRadius = 0.2f; // 飛ばす球の半径(ニアクリップ面より大きく) / cast sphere radius (> the near plane)
    21 float fovY = radians(55.0f);
    22  
    23 // マウスで回す(1フレームに一度) / turn with the mouse (once per frame)
    24 void look(float dxPixels, float dyPixels);
    25 // 1ステップ:注視点を追い、肩へずらし、後ろへ球を飛ばして距離を決める / one step: follow the pivot, offset to the
    26 // shoulder, cast backwards and decide the distance
    27 void update(Vec3 pivot, std::span<const Aabb> solids, float dt);
    28 // 初期化:今すぐpivotの後ろへ(なめらかにしない) / snap behind pivot now (no smoothing)
    29 void reset(Vec3 pivot, std::span<const Aabb> solids);
    30  
    31 Vec3 forward() const; // 見ている向き / view direction
    32 Vec3 flatForward() const; // 水平の前 / horizontal forward
    33 Vec3 right() const; // 水平の右 / horizontal right
    34 Vec3 eye() const { return eyePos; }
    35 Vec3 shoulder() const { return shoulderPos; }
    36 float currentDistance() const { return dist; }
    37 bool blocked() const { return hitWall; } // 今のステップで壁に当たって寄せたか / pulled in by a wall this step
    38  
    39 private:
    40 Vec3 smoothPivot, shoulderPos, eyePos;
    41 float dist = 3.6f;
    42 float side = 1.0f;
    43 bool hitWall = false;
    44 };


コメント(0)

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