28. スペースインベーダー パート2:射撃と衝突判定

第27章の終わりで、自機は動き、隊列は1匹ずつ行進する様になりましたが、まだ誰も誰かを傷付ける事は出来ませんでした。
此の章でゲームは遊べる物になります。
自機が撃ち、エイリアンが撃ち返し、弾が物に当たり、4つの防壁がピクセル単位で削れ、エイリアンと自機が爆発し、残機とゲームオーバーがあります。

殆どは第26章の道具箱(AABBのテスト、Rng、Animator、シーンのスタック)の上に作るゲームの処理です。
OpenGLの部分は防壁です。
防壁はゲームの途中で変わる小さなテクスチャに住んでいて、当たる度に、変わった四角だけを、もっと大きなCPUの配列から直接送り直します。
其の為には、オフセット付きのglTextureSubImage2Dと、ピクセルストアのパラメーターGL_UNPACK_ROW_LENGTHが要ります。
此れが此の章の新しいGLの主な話題です。

ゲームの章はコードが多いので、全ての行を説明するのではなく、大事なコードを見せて、何故そう書くのかを説明します。
残りは最後のダウンロードにあります。

28.1 此の章で作る物

スクリプトで4秒程遊んだ後のゲームです:

246フレーム目。8匹撃たれて隙間の空いた隊列、3行目で白とオレンジの爆発になる甲虫、落ちて来る2発のエイリアンの弾、自機の上の4つの緑の防壁、其の2つ目は下から欠けている。左の板にはinstanced、768 B per frame、alive 47、lives 3、kills 8、upload 96 B

動画では隊列を撃ち抜き、2種類のエイリアンの弾、両側から削れて行く防壁、そして自機の爆発を1回見せます。
爆発の間、行進は止まります:

操作:

  • ← →又はA D:移動
  • スペース、↑又はW:撃つ
  • B:当たり判定の箱を表示
  • I:隊列をインスタンシングで描くかSpriteBatchで描くか(第27章)
  • =と−:行進を速く・遅く(デバッグ用)
  • ゲームオーバーの後にスペース又はEnter:もう一度
  • Esc:終了

プログラムは引き続きinvadersで、games/invaders/の外は何も変わりません。
第27章からの変更:

  • src/shields.hh、src/shields.cc(新規):Shields(削れる防壁)と、スプライトシートをCPUでデコードして1枚のスプライトを切り出すloadSpriteImage
  • src/effects.hh、src/effects.cc(新規):Particles(1ピクセルの破片)とFlare(少しの間だけ見せるスプライト)
  • src/formation.hh、src/formation.cc:エイリアンが「爆発中」になれる様に。kill、updateExplosions、cleared、lowestInColumn
  • src/game.hh:新しい定数、Gameに防壁の絵とshowBoxes、PlaySceneに弾と戦いの状態
  • src/play_scene.cc:戦い
  • src/main.cc:防壁の絵と、fire及びconfirmの行動
  • CMakeLists.txt、README.md:新しいファイルと操作

スプライトシートは変わりません。
第27章の生成スクリプトが、弾、爆発、着弾の形、防壁を既に描いてあるからです。
新しい2つのソースファイルはゲームのCMakeLists.txtに入ります:

add_executable(invaders
  src/main.cc
  src/play_scene.cc
  src/formation.cc
  src/formation_renderer.cc
  src/shields.cc
  src/effects.cc)

28.2 定数と状態

画面の配置に防壁の行が増え、戦いには速さと上限が要ります:

constexpr float kShieldY = 136.0f;      // 防壁の上端 / the shields' top
constexpr float kPlayerY = 158.0f;      // 自機の上端 / the ship's top
constexpr float kGroundY = 170.0f;      // 地面の線 / the ground line
constexpr float kPlayerSpeed = 60.0f;   // ピクセル毎秒(1ステップ1ピクセル) / pixels per second (1 px per step)
constexpr float kShotSpeed = 240.0f;    // 自機の弾:1ステップ4ピクセル / the ship's bullet: 4 px per step
constexpr float kAlienShotSpeed = 75.0f; // 宇宙人の弾 / alien bullets
constexpr int kMaxAlienShots = 3;
constexpr int kStartLives = 3;

速さは全てキャンバスのピクセル毎秒で、ゲームの処理は第26章の1/60秒の固定ステップで動きます。
従って自機の弾は1ステップに丁度240/60=4 px、エイリアンの弾は75/60=1.25 px動きます。
此の2つの数は当たり判定の節で又出て来ます。

弾は当たり判定の箱、補間用の前のステップのy、そしてエイリアンの弾の4コマのクリップの為のAnimatorです:

  struct Bullet {
    Rect box;
    float prevY;
    Animator anim; // 宇宙人の弾は4コマのクリップ / alien bullets play a 4-frame clip
  };

シーンは第27章の状態の隣に新しい状態を持ちます:

  std::optional<Bullet> shot;               // 自機の弾は一度に一発(元のゲームと同じ) / one ship bullet at a time
                                            // (as in the original)
  std::vector<Bullet> alienShots;
  float fireTimer = 1.0f;                   // 宇宙人が次に撃つまで / until the aliens fire next
  float shipDying = 0.0f;                   // 自機の爆発の残り時間(> 0 の間は隊列も止まる) / ship explosion time
                                            // left (the march stops meanwhile)
  Animator shipBoom;
  Particles particles;
  std::vector<Flare> flares;

自機の弾はvectorではなくstd::optionalです。
1発あるか無いかのどちらかで、型が其れを表しています。

28.3 自機の弾:一度に1発

1978年の元のゲームでは、自分の弾がまだ画面にある間は次を撃てません。
制限に聞こえますが、此れがゲームの殆どです。
外した弾は時間を失うので、ボタンを連打するのではなく狙う様になります。
又、目の前の低いエイリアンを撃つ(飛ぶ距離が短い)方が、一番上の行を狙うより速いのです。
此の決まりを守ります:

void PlayScene::fire() {
  // 画面に自機の弾がない時だけ撃てる:連打より狙いが大事(元のゲームの決まり)
  // Only when no ship bullet is on screen: aiming beats mashing (the original's rule)
  if (shot || shipDying > 0.0f || gameOver || !g.input.actionPressed("fire")) return;
  float y = kPlayerY - 4.0f;
  shot = Bullet{.box = {playerX + 7.0f, y, 1.0f, 5.0f}, .prevY = y, .anim = {}};
  ++shotsFired;
}

main.ccで、fireの行動はスペース、↑、Wに、confirm(ゲームオーバーの画面用)はスペースとEnterに割り当てます:

  input.bind("fire", {InputBinding::key(GLFW_KEY_SPACE), InputBinding::key(GLFW_KEY_UP), InputBinding::key(GLFW_KEY_W)});
  input.bind("confirm", {InputBinding::key(GLFW_KEY_SPACE), InputBinding::key(GLFW_KEY_ENTER)});

actionPressedはキーを1回押すごとに丁度1回の更新でtrueになり(第26章)、エンジンはGLFWの自動連打のイベントを無視するので、スペースを押しっぱなしにしても1発しか出ません。
弾は1 × 5 pxで、x = 自機 + 7、つまり15 pxの自機の真ん中の列から出ます。
1ステップに4 px動くので、y = 154から戦場の上端(y < 6)まで38ステップ、約0.63秒かかります。
此れが、次の弾を撃てるまでに待つ一番長い時間です。

28.4 当たり判定の箱

何と何が当たるか

此の章のテストは全て第26章のoverlapsです。
厳密なAABBの重なりなので、触れているだけの箱は当たりません。
Bで全ての箱が見えます:

同じフレームで全ての当たり判定の箱の輪郭を描いた物。エイリアンの周りに赤い14 × 10の箱、自機の中に小さな緑の箱、弾に黄色の箱、4つの防壁の周りに青い箱

物 箱(キャンバスのpx) 理由
エイリアン 14 × 10のスプライトの枠、第27章のAlien::box() 甘め:輪郭に触れた弾も当たり
自機 {x + 1, y + 1, 13, 7} 輪郭を除いた船体:ぎりぎりは外れ
自機の弾 1 × 5 スプライトと同じ
エイリアンの弾 3 × 7 スプライトと同じ
防壁 22 × 16の長方形 最初のテストだけ。其の後はピクセルが決める

表の真ん中の2つはわざとです。
エイリアンの箱は見た目より少し大きく、自機の箱は少し小さいので、際どい場面は全てプレイヤーに有利になります。
プレイヤーは「ほんの少し触れただけの物に当たった」とは文句を言いませんが、「明らかに外れた弾でやられた」とは文句を言います。
自機の箱は1行です:

Rect PlayScene::shipBox() const { return {playerX + 1.0f, kPlayerY + 1.0f, 13.0f, 7.0f}; }

何故すり抜けないのか

第26章ではすり抜け(トンネリング)に注意しました。
1ステップで箱の厚さより遠くへ動く箱は、目標を飛び越える事があり、其の対策が掃引テストでした。
此のゲームにはsweepは要りませんが、其の理由は願うのではなく確かめる価値があります。

左:自機の弾の3ステップ分の箱、y = 150、146、142。どれも長さ5 pxで4 pxずつ離れているので、次の箱と1行を共有する。右:2つの箱の相対的なずれの数直線が3本。弾とエイリアンでは重なる範囲が15 px、最悪の移動が10 pxなので、調べる点は必ず範囲に入る。弾とエイリアンの弾では範囲12 px、移動5.25 px。速すぎる例では範囲12 pxに対して16 px動き、飛び越え得る

まず、止まっている目標です。
自機の弾は長さ5 pxで1ステップに4 px動くので、或るステップの箱と次のステップの箱は1行のピクセルを共有します。
全てのステップの箱を合わせると、弾の通り道を隙間無く覆うので、通り道に立っている物は必ず其のどれかと重なります。
防壁は動かないので、弾は上へ進む途中で防壁の全ての行を調べます。

次に、両方が動く場合です。
高さh1とh2の2つの箱は、相対的なずれがh1+h2ピクセルの範囲の中にある間、縦に重なります。
ずれが1ステップに其れより少ししか変わらなければ、どのステップも範囲の片側から反対側へ飛び越えられません。
少なくとも1つのステップは範囲の中に入ります。

  • 自機の弾とエイリアン:範囲は5+10=15 px。最悪なのは、弾が4 px上がる間にエイリアンが6 px下がる時で、4+6=10<15。横の範囲は1+14=15 pxで、エイリアンは2 px動きます。
  • 自機の弾とエイリアンの弾:5+7=12 pxで、1ステップに4+1.25=5.25<12 px近づきます。
  • エイリアンの弾と自機:縦は7+7=14 pxに対して1ステップ1.25 px、横は3+13=16 pxに対して自機の1ステップ1 px。

従って、此の速さならどの組も安全です。
但し、此の議論には但し書きがあります。
既定の行進の速さ(毎秒60匹)では、エイリアンは1ステップに1回しか動きません。
=キーは速さを倍々にして毎秒960匹、1ステップに16回まで上げます。
エイリアンが2匹しか残っていなければ、其々が1ステップに8回、横に16 px動き、15 pxの範囲を超えます。
此のデバッグ用の速さでは、弾が最後のエイリアンを本当にすり抜ける事があります。
後でゲームを速くするなら、此の計算をやり直すか、弾をsweepで動かして下さい。

自機の弾のテストの順番

updateShotは弾を動かし、当たり得る物全てに対してテストし、最初に当たった物が勝ちます:

void PlayScene::updateShot(float dt) {
  if (!shot) return;
  shot->prevY = shot->box.y;
  shot->box.y -= kShotSpeed * dt;
  // 1ステップ4ピクセル、弾の長さ5ピクセル:続けて見れば隙間がないので、すり抜けない(第26章のトンネリング)。
  // 宇宙人の弾とも:近づく速さは1ステップ5.25ピクセル < 5 + 7
  // 4 px per step with a 5 px bullet: consecutive boxes leave no gap, so nothing is skipped (ch26's tunneling).
  // Against alien bullets too: they close in at 5.25 px per step < 5 + 7
  const Rect &box = shot->box;
  for (size_t i = 0; i < alienShots.size(); ++i)
    if (overlaps(box, alienShots[i].box)) {
      flare(box.centre(), hexColor(0xfff4d6ff));
      alienShots.erase(alienShots.begin() + static_cast<std::ptrdiff_t>(i));
      shot.reset();
      return;
    }
  for (Alien &a : formation.aliens)
    if (a.alive && overlaps(box, a.box())) {
      formation.kill(a);
      particles.burst(a.box().centre(), 10, kAlienColors[static_cast<int>(a.kind)], 15.0f, 50.0f, g.rng);
      ++kills;
      shot.reset();
      return;
    }
  if (std::optional<Vec2> p = shields->hit(box, true)) {
    shields->erode(*p, g.rng);
    flare(*p, hexColor(0x68c454ff));
    shot.reset();
    return;
  }
  if (box.top() < 6.0f) { // 戦場の上の端 / the top of the arena
    flare({box.x, 6.0f}, hexColor(0xfff4d6ff));
    shot.reset();
  }
}

順番は設計の判断です。
エイリアンの弾が最初なので、目の前の弾を撃ち落とせます(両方がフレアと共に消えます)。
エイリアンは防壁より先です。
此れは隊列が防壁まで下りて来てからだけ意味があり、其の時は防壁の中に立っているエイリアンの方が当たります。
エイリアンは行進の順番、つまり下の行から調べます。
行の間は4 pxで、弾の箱は整数のピクセルから始まるので、5 pxの弾が2つの行に同時に重なる事はありません。
最初に出会ったエイリアンが倒れるエイリアンです。
shot.reset()はboxが指している箱を消すので、どの分岐もすぐにreturnします。

此処では総当たりで十分です。
弾1発に対して、最大3発の弾、55匹のエイリアン、4つの防壁で、1ステップに約60回のテストです。
何千もの物があるゲームなら、まずグリッドに分けます(ブロードフェーズ、第26章)が、此のゲームには必要ありません。

28.5 エイリアンの射撃

誰が撃つか

元のゲームでは、列の一番下のエイリアンだけが撃てます。
エイリアンは下の仲間を撃ち抜いて撃つ事は出来ません。
此の決まりがあるから、列を片付ける事に意味があります。
隊列の小さな関数です:

const Alien *Formation::lowestInColumn(int column) const {
  const Alien *lowest = nullptr;
  for (const Alien &a : aliens)
    if (a.alive && a.column == column && (!lowest || a.position.y > lowest->position.y)) lowest = &a;
  return lowest;
}

いつ、どの列から撃つかはシーンが決めます:

void PlayScene::alienFire(float dt) {
  fireTimer -= dt;
  if (fireTimer > 0.0f) return;
  fireTimer = g.rng.range(0.5f, 1.1f);
  if (static_cast<int>(alienShots.size()) >= kMaxAlienShots) return;
  // 撃つ列:3回に1回は自機の真上の列、それ以外は生きている宇宙人をランダムに選んでその列。撃つのはその列の一番下
  // The firing column: one time in three the column above the ship, otherwise the column of a random living alien.
  // The lowest alien of that column shoots
  std::vector<const Alien *> living;
  for (const Alien &a : formation.aliens)
    if (a.alive) living.push_back(&a);
  if (living.empty()) return;
  int column = living[static_cast<size_t>(g.rng.range(0, static_cast<int>(living.size()) - 1))]->column;
  if (g.rng.chance(1.0f / 3.0f)) {
    float shipX = shipBox().centre().x, best = 1e9f;
    for (const Alien *a : living)
      if (float d = std::fabs(a->box().centre().x - shipX); d < best) best = d, column = a->column;
  }
  const Alien *shooter = formation.lowestInColumn(column);
  if (!shooter) return;
  Bullet b{.box = {shooter->position.x + 5.0f, shooter->position.y + kAlienSize.y, 3.0f, 7.0f},
           .prevY = shooter->position.y + kAlienSize.y, .anim = {}};
  b.anim.play(g.rng.chance(0.5f) ? zigClip : boltClip);
  alienShots.push_back(b);
}

細かい所:

  • 弾は0.5〜1.1秒ごと、平均0.8秒ごとに出ますが、画面には3発までです。上限に達している時もタイマーは又始まるので、弾が1発消えた瞬間に撃つ事はありません。
  • 生きているエイリアンをランダムに選んで其の列を取るのは、列をランダムに選ぶのと同じではありません。エイリアンが5匹残っている列は、1匹の列の5倍撃ちます。隊列が薄くなっても、満員の列が圧力を保ちます。
  • 3回に1回は、自機の真上に一番近いエイリアンの列が撃ちます。此れでプレイヤーは動き続けます。隊列の下でじっとしていると当たります。(元のゲームにも、同じ様にプレイヤーの列を狙う種類の弾がありました。)
  • 弾は其々ランダムにジグザグか稲妻で、スプライトシートの4コマ、12 fpsのクリップを自分のAnimatorで再生します。
  • 乱数は全て、種27のGame::rngから来ます。ゲームの処理は固定ステップでしか動かないので、同じ入力なら毎回同じゲームになります。スクリーンショットと動画は其れに頼っています。

落ちる弾と、自機への当たり

void PlayScene::updateAlienShots(float dt) {
  for (size_t i = 0; i < alienShots.size();) {
    Bullet &b = alienShots[i];
    b.prevY = b.box.y;
    b.box.y += kAlienShotSpeed * dt;
    b.anim.update(dt);
    if (shipDying <= 0.0f && overlaps(b.box, shipBox())) {
      killShip(); // 全部の弾を消す / clears every bullet
      return;
    }
    bool gone = false;
    if (std::optional<Vec2> p = shields->hit(b.box, false)) {
      shields->erode(*p, g.rng);
      flare(*p, hexColor(0x68c454ff));
      gone = true;
    } else if (b.box.bottom() >= kGroundY) {
      flare({b.box.centre().x, kGroundY - 2.0f}, hexColor(0xffa040ff));
      gone = true;
    }
    if (gone) alienShots.erase(alienShots.begin() + static_cast<std::ptrdiff_t>(i));
    else ++i;
  }
}

此のループは、歩いている途中のvectorから要素を消すので、インデックスを使い、何も消さなかった時だけ進みます。
範囲forでは未定義動作になります。
killShipはvector全体を空にするので、其の後でbに触れずにすぐreturnします。

void PlayScene::killShip() {
  --lives;
  shipDying = kShipBoomTime;
  shipBoom.play(shipBoomClip, true);
  Vec2 c = shipBox().centre();
  particles.burst(c, 24, hexColor(0x4fc0a5ff), 20.0f, 70.0f, g.rng);
  particles.burst(c, 12, hexColor(0xffa040ff), 30.0f, 90.0f, g.rng);
  alienShots.clear(); // 元のゲームと同じく、飛んでいる弾は消える / bullets in flight vanish, as in the original
  printf("ship hit: lives %d\n", lives);
}

飛んでいる弾を消すのも元のゲームの決まりで、優しい決まりです。
自機が戻って来た時に、既に頭の上に弾が落ちて来ている事がありません。

28.6 削れる防壁

防壁は此の章で一番面白い所です。
防壁は「ある」か「無い」かの箱ではありません。
当たる度に小さく欠け、暫くすると弾が穴を抜ける様になります。
つまり、ゲームには防壁のピクセルが、描く為にも当たり判定の為にも要ります。

4つの防壁に1枚のテクスチャ

4つの防壁は全て、88 × 16のGL_RGBA8のテクスチャ1枚に住んでいます。
防壁iはテクセルx=22iにあり、テクスチャの4分の1をUVの範囲にした普通のバッチのスプライト4枚として描かれます:

上:緑の防壁4つを並べた88 × 16のテクスチャ。テクセルのx 0、22、44、66、u 0、0.25、0.5、0.75。下:キャンバスのx 48〜272の戦場と、x 65、121、177、233の4つの防壁のスプライト。其々テクスチャの4分の1から描かれる

クラスはピクセルの正本をCPUに持ち、其の隣にテクスチャと、変わった四角(ダーティ矩形)を持ちます:

class Shields {
public:
  // 4つの防壁を一枚のテクスチャ(88 × 16)に並べる。topLeft[i] = 画面での防壁iの左上
  // Puts the 4 shields side by side in one texture (88 × 16). topLeft[i] = where shield i goes on screen
  static std::optional<Shields> create(const Image &art, const Vec2 (&topLeft)[kShieldCount]);

  // boxの中に残っている防壁のピクセルがあるか。あれば、弾の進む向きで最初に当たるピクセル(の中心)
  // (下から来る弾 = 一番下、上から来る弾 = 一番上)
  // Is any shield pixel left inside box? If so, the pixel a bullet meets first (its center): the lowest for a
  // bullet coming from below, the highest for one coming from above
  std::optional<Vec2> hit(const Rect &box, bool fromBelow) const;
  // 着弾の形(kSplat、6 × 8)でピクセルを消す。左右はランダムに反転 / clears pixels in the impact shape (kSplat,
  // 6 × 8), mirrored at random
  void erode(Vec2 point, Rng &rng);
  // 四角の中を全部消す(防壁まで下りてきた宇宙人) / clears everything inside the box (aliens that reach the shields)
  void eraseRect(const Rect &box);

  // 変わった所だけをアップロードする(描く前に一度) / uploads only what changed (once, before drawing)
  void upload();
  void draw(SpriteBatch &batch, float layer = 0.0f) const;
  Rect bounds(int i) const { return {topLeft[i].x, topLeft[i].y, kShieldW, kShieldH}; }
  int lastUploadBytes() const { return uploadBytes; }
  int pixelsLeft() const;
  const Texture2D &texture() const { return tex; }

private:
  static constexpr int kTexW = kShieldW * kShieldCount, kTexH = kShieldH;
  Shields() = default;
  void clearPixel(int x, int y); // テクスチャのピクセル座標 / texture pixel coordinates
  bool solid(int x, int y) const { return pixels[static_cast<size_t>(4 * (y * kTexW + x) + 3)] != 0; }

  std::vector<std::uint8_t> pixels; // kTexW × kTexH × RGBA8(CPUの正本) / the CPU master copy
  Texture2D tex;
  Vec2 topLeft[kShieldCount];
  int dirtyX0 = kTexW, dirtyY0 = kTexH, dirtyX1 = 0, dirtyY1 = 0; // 変わった四角(x1・y1は含まない) / the changed
                                                                   // rectangle (x1, y1 exclusive)
  int uploadBytes = 0;
};

何故4枚ではなく1枚なのでしょうか?
1枚なら、4つの防壁全てでスプライトバッチの描画呼び出しが1回、アップロードはフレームに多くて1回、添字を付ける配列も1つです。
其の代わり、同じフレームで1つ目の防壁と4つ目の防壁に当たると、1つの変わった四角が4つ全てに跨る大きさになります(課題4で直します)。

アルファが0でないピクセルが「中身がある」ピクセルです。
ゲームには其れ以外は要らないので、当たり判定はアルファのバイトだけを読みます。
シーンは224 pxの戦場に防壁を等間隔に置きます。
中心は76、132、188、244なので、左上はx = 65、121、177、233です:

  // 防壁4つを戦場に等間隔で(中心 76, 132, 188, 244) / four shields evenly across the arena (centers 76, 132, 188, 244)
  Vec2 shieldPos[kShieldCount];
  for (int i = 0; i < kShieldCount; ++i)
    shieldPos[i] = {kArenaLeft + (kArenaRight - kArenaLeft) * (static_cast<float>(i) + 0.5f) / kShieldCount - kShieldW / 2,
                    kShieldY};
  shields = Shields::create(g.shieldArt, shieldPos);
  if (!shields) { // 防壁が無いと遊べない(理由はcreateが書いた) / no game without shields (create logged why)
    fprintf(stderr, "防壁を作れないので終了 / cannot create the shields: quitting\n");
    g.window.close(); // 防壁を使う関数は何もしない / the functions that use the shields do nothing
  }

createは絵を配列に4回コピーし、テクスチャを作って1度だけ送ります:

std::optional<Shields> Shields::create(const Image &art, const Vec2 (&positions)[kShieldCount]) {
  if (art.width != kShieldW || art.height != kShieldH) {
    fprintf(stderr, "防壁の絵が %d × %d でない / the shield art is not %d × %d\n", kShieldW, kShieldH, kShieldW, kShieldH);
    return std::nullopt;
  }
  Shields s;
  s.pixels.resize(static_cast<size_t>(kTexW * kTexH * 4));
  for (int i = 0; i < kShieldCount; ++i) {
    s.topLeft[i] = positions[i];
    for (int y = 0; y < kShieldH; ++y)
      std::copy_n(art.rgba.begin() + 4 * y * kShieldW, 4 * kShieldW,
                  s.pixels.begin() + 4 * (y * kTexW + i * kShieldW));
  }
  // 中身は後で書き換えるので、空のストレージを作ってから全体を一度送る / the contents change later, so allocate
  // empty storage and send everything once
  s.tex = Texture2D(kTexW, kTexH, GL_RGBA8, 1);
  s.tex.setFilter(GL_NEAREST, GL_NEAREST);
  s.tex.setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
  s.tex.upload(s.pixels.data());
  return s;
}

Texture2D(w, h, GL_RGBA8, 1)は第6章のコンストラクタで、glCreateTexturesとミップマップ1段のglTextureStorage2Dです。
此のストレージはイミュータブル(不変)ですが、此れは誤解し易い言葉です。
大きさ、形式、段数は決して変えられませんが、中身は何度でも書き換えられます。
ピクセルが絶えず変わるテクスチャには、正にイミュータブルなストレージが合っています。
ミップマップ無し、GL_NEAREST、クランプは第25章のピクセルアートの決まりです。

createが失敗するのは絵の大きさが違う時だけです。
でもコンストラクタは其の失敗を返せませんし、防壁の無いシーンでは遊べません。
其の為コンストラクタはエラーを書いてウィンドウを閉じます。
アセットが無い時にmainがreturn 1で諦めるのと同じ考えです。
そしてshieldsを使う関数(update、draw、drawUi)は全て、最初に此の1行を持ちます:

  if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor)

drawの確認も省けません。
最初のフレームは最初の更新より前に描かれますし(第26章)、スペースでやり直す時は、ループが閉じたウィンドウに気付く前に、新しいシーンが同じフレームの中で描かれるからです。

絵を2回デコードする

防壁の絵はスプライトシートのshieldスプライトで、他の全てと同じ生成スクリプトで描いた物として其処に置いておきたいのです。
でもSpriteSheetはGPUのテクスチャしか持たず、ゲームにはCPUのメモリのピクセルが要ります。
其の為mainは同じPNGをCPUでもう一度デコードし、スプライトを切り出します:

  // 防壁の絵はCPUにも要る(削るため):同じPNGをもう一度デコードして切り出す / the shield art is needed on the CPU
  // too (to erode it): decode the same PNG again and cut it out
  std::optional<Image> shieldArt = loadSpriteImage("games/invaders/assets/sprites.png", *sprites, "shield");
  if (!formationRenderer || !shieldArt) return 1;

std::optional<Image> loadSpriteImage(const std::string &pngPath, const SpriteSheet &sheet, const char *name) {
  int index = sheet.find(name);
  std::optional<std::vector<std::uint8_t>> bytes = readBinaryFile(pngPath);
  if (index < 0 || !bytes) {
    fprintf(stderr, "%s: スプライト %s がない / no sprite %s\n", pngPath.c_str(), name, name);
    return std::nullopt;
  }
  std::optional<Image> sheetImage = decodeImage(bytes->data(), bytes->size(), false);
  if (!sheetImage) return std::nullopt;
  Rect r = sheet.pixels(index);
  Image out;
  out.width = static_cast<int>(r.w);
  out.height = static_cast<int>(r.h);
  out.rgba.resize(static_cast<size_t>(out.width * out.height * 4));
  for (int y = 0; y < out.height; ++y)
    for (int x = 0; x < out.width; ++x)
      for (int c = 0; c < 4; ++c) {
        size_t src = static_cast<size_t>(4 * ((static_cast<int>(r.y) + y) * sheetImage->width + static_cast<int>(r.x) + x) + c);
        out.rgba[static_cast<size_t>(4 * (y * out.width + x) + c)] = sheetImage->rgba[src];
      }
  // 乗算済みアルファにする(loadSpriteTextureが自動でやっていること)。PNGの透明なピクセルには、にじみ止めの色
  // (隣の不透明なピクセルの色)が入っているので、そのまま送ると (r, g, b, 0) が加算されて縁が光る
  // Premultiply (what loadSpriteTexture does for you). The PNG's transparent pixels carry the nearest opaque color
  // against fringes; sent as is, (r, g, b, 0) would be *added* by the premultiplied blend and the edges would glow
  for (size_t i = 0; i < out.rgba.size(); i += 4)
    for (size_t c = 0; c < 3; ++c) out.rgba[i + c] = static_cast<std::uint8_t>(out.rgba[i + c] * out.rgba[i + 3] / 255);
  return out;
}

readBinaryFileとdecodeImage(メモリからのstb_image、第14章)はエンジンの関数で、スプライトの場所はシートのアトラスが教えてくれます(sheet.pixels(index)、テクセル単位で上の行から)。
128 × 48のPNGを起動時に2回デコードしても、測る価値のある時間はかかりません。

乗算済みアルファは自分で

loadSpriteImageの最後のループが、此の章の落とし穴です。
第25章から、2Dのテクスチャは全て乗算済みアルファ(第16章)で、スプライトバッチはGL_ONE, GL_ONE_MINUS_SRC_ALPHAで混ぜます:

result=srcrgb+(1−srca)⋅dstrgb

loadSpriteTextureはアップロードの前にRGBにアルファを掛けるので、今まで考える必要はありませんでした。
自分で中身を入れるテクスチャには、そんな助けはありません。
送った物が其のままブレンドに使われます。
そしてシートのPNGはストレートアルファで、透明なテクセルにはわざと色が入っています。
シートを作ったあたしのスクリプトは、線型フィルタリングが縁に黒を引き込まない様に、透明なテクセル全てを一番近い不透明な隣の色で埋めるからです。
防壁のスプライトには中身のあるテクセルが298個、透明なテクセルが54個あり、54個全てに(104, 196, 84)の様な緑がアルファ0で入っています。
其のまま送ると、其々が背景に色を丸ごと足し((104,196,84)+1⋅dst)、防壁は22 × 16の塗り潰しの四角になってしまいます。
アルファを掛けると(0, 0, 0, 0)になり、何も足しません。

覚えておく決まり:自分で中身を入れたテクスチャは、自分で乗算済みにする。
スプライトは全て乗算済みのブレンドで描かれるからです。
後でゲームが消すピクセルは(0, 0, 0, 0)にするので、既に正しい値です。

当たり判定:箱、其れからピクセル

防壁との当たり判定は2段階です。
まず弾の箱と防壁の22 × 16の長方形です。
殆どの弾は此処で外れ、其れ以上の手間はかかりません。
次に、箱の下のピクセルだけについて、まだ中身があるかを調べます:

std::optional<Vec2> Shields::hit(const Rect &box, bool fromBelow) const {
  for (int i = 0; i < kShieldCount; ++i) {
    Rect s = bounds(i);
    // boxが重なるピクセルの範囲(防壁の中の座標) / the pixels the box covers (shield coordinates)
    int x0 = std::max(0, static_cast<int>(std::floor(box.left() - s.x)));
    int x1 = std::min(kShieldW, static_cast<int>(std::ceil(box.right() - s.x)));
    int y0 = std::max(0, static_cast<int>(std::floor(box.top() - s.y)));
    int y1 = std::min(kShieldH, static_cast<int>(std::ceil(box.bottom() - s.y)));
    if (x0 >= x1 || y0 >= y1) continue;
    for (int n = 0; n < y1 - y0; ++n) {
      int y = fromBelow ? y1 - 1 - n : y0 + n;
      for (int x = x0; x < x1; ++x)
        if (solid(i * kShieldW + x, y))
          return Vec2{s.x + static_cast<float>(x) + 0.5f, s.y + static_cast<float>(y) + 0.5f};
    }
  }
  return std::nullopt;
}

箱を防壁のピクセルの範囲に直します。
始まりはfloor、終わりはceilで、防壁の中に収めます。
範囲が空なら、箱は長方形に当たっていません(整数で行うAABBのテストです)。
其れから行を弾の進む向きに調べます。
自機の弾なら下から、エイリアンの弾なら上からです。
箱は4〜5行を覆いますが、弾は其の真ん中の適当なピクセルではなく、最初に届いたはずの中身のあるピクセルで爆発すべきです。
結果は其のピクセルの中心で、キャンバスの座標です。

実際の当たりを見てみます。
2つ目の防壁の下、x = 131(防壁の10列目)の自機の弾です:

左:22 × 16のマス目にした2つ目の防壁。前のステップ(y = 150)の弾の箱はアーチの中の14行目と15行目を覆い、何も見付けない。此のステップ(y = 146)の箱は10〜14行目を覆い、10列目で一番下の中身のあるピクセルは11行目で、此れが当たり。右:削った後。当たりの周りの6 × 8の着弾の形の20ピクセルが消え、其れを囲む変わった四角は6 × 6テクセル、144バイト

y = 150では、箱は防壁の14行目と15行目、つまりアーチの中を覆い、10列目は空です。
1ステップ後のy = 146では10〜14行目を覆います。
下から見ると14、13、12行目は空で、11行目に中身があります。
此れが当たりで、位置は(131.5, 147.5)です。

削る事と、変わった四角

当たった点はerodeに渡され、其の周りの6 × 8の形のピクセルを消します:

// 着弾の形(スプライトシートのsplatと同じ形):'W' = 消すピクセル / the impact shape (the same shape as the
// sheet's splat sprite): 'W' = a pixel to clear
static const char *const kSplat[] = {
  "W..W.W",
  "..WW..",
  ".WWWW.",
  "WWWWW.",
  ".WWWWW",
  "WWWWW.",
  "..WW..",
  "W..W.W",
};
constexpr int kSplatW = 6, kSplatH = 8;

着弾の時に光るsplatスプライトと同じ形なので、穴は其れを作った爆発の様に見えます。
防壁に当たった弾は緑の着弾を0.12秒見せ、其れが消えると丁度其の形の穴が残ります。

void Shields::erode(Vec2 point, Rng &rng) {
  bool mirror = rng.chance(0.5f);
  for (int i = 0; i < kShieldCount; ++i) {
    Rect s = bounds(i);
    // 着弾の形の左上(防壁の中の座標) / the impact shape's top left (shield coordinates)
    int ox = static_cast<int>(std::floor(point.x - s.x)) - kSplatW / 2;
    int oy = static_cast<int>(std::floor(point.y - s.y)) - kSplatH / 2;
    if (ox >= kShieldW || oy >= kShieldH || ox + kSplatW <= 0 || oy + kSplatH <= 0) continue;
    for (int y = 0; y < kSplatH; ++y)
      for (int x = 0; x < kSplatW; ++x) {
        int sx = ox + x, sy = oy + y;
        char c = kSplat[y][mirror ? kSplatW - 1 - x : x];
        if (c == 'W' && sx >= 0 && sx < kShieldW && sy >= 0 && sy < kShieldH) clearPixel(i * kShieldW + sx, sy);
      }
  }
}

形の左上は当たったピクセルの3列左、4行上なので、当たったピクセルは形の(3, 4)のマスです。
其のマスは、形でも其の鏡像でもWです(.WWWWWの3列目又は2列目)。
其の為、当たったピクセル自身は必ず消えます。
そうでないと、或るピクセルが自分への当たりを生き延び、其の列の其の後の弾が全部永遠に同じピクセルで止まってしまいます。
ランダムな左右反転(ゲームのRngで50 %)は、隣り合う穴がスタンプの様に見えない様にする為です。

ピクセルを消す所で、変わった四角が広がります:

void Shields::clearPixel(int x, int y) {
  if (x < 0 || y < 0 || x >= kTexW || y >= kTexH || !solid(x, y)) return;
  std::fill_n(pixels.begin() + 4 * (y * kTexW + x), 4, std::uint8_t{0});
  dirtyX0 = std::min(dirtyX0, x), dirtyY0 = std::min(dirtyY0, y);
  dirtyX1 = std::max(dirtyX1, x + 1), dirtyY1 = std::max(dirtyY1, y + 1);
}

既に空のピクセルはすぐreturnするので、四角を広げません。
本当に変わったピクセルだけが数えられます。
例では、形のマスのうち20個に中身があり(アーチの天井より下の行は既に空でした)、変わった四角は6 × 6テクセルです。
「空」の四角はx0 = 幅、x1 = 0なので、最初のminとmaxで必ず置き換わります。

四角をアップロードする:glTextureSubImage2D

当たりはupdateの中で起こり、1フレームに何回もあるかも知れませんし、長い間無いかも知れません。
アップロードはdrawの中で、防壁を描く前にフレームに1回行い、前のフレームから変わった四角に溜まった物を送ります:

void Shields::upload() {
  uploadBytes = 0;
  if (dirtyX0 >= dirtyX1 || dirtyY0 >= dirtyY1) return; // 変わっていない / nothing changed
  int w = dirtyX1 - dirtyX0, h = dirtyY1 - dirtyY0;
  // CPUの配列の一部(四角)を送る:行の長さ(GL_UNPACK_ROW_LENGTH)を配列全体の幅にすると、GLは一行ごとに
  // kTexWピクセル先へ進む。ポインターは四角の左上。送ったら0(= 幅と同じ)に戻す
  // Send a rectangle out of the CPU array: with GL_UNPACK_ROW_LENGTH = the whole array's width, the GL steps kTexW
  // pixels for every row. The pointer is the rectangle's top left. Reset it to 0 (= the width) afterwards
  glPixelStorei(GL_UNPACK_ROW_LENGTH, kTexW);
  glTextureSubImage2D(tex.id(), 0, dirtyX0, dirtyY0, w, h, GL_RGBA, GL_UNSIGNED_BYTE,
                      pixels.data() + 4 * (dirtyY0 * kTexW + dirtyX0));
  glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
  uploadBytes = w * h * 4;
  dirtyX0 = kTexW, dirtyY0 = kTexH, dirtyX1 = 0, dirtyY1 = 0;
}

glTextureSubImage2Dには第6章で会いましたが、其の時はいつも画像全体を置き換えていました。
此処でやっと四角のパラメーターが意味を持ちます:

  • texture:tex.id()、テクスチャオブジェクト(DSAなのでバインドは要りません)。
  • level:0、唯一のミップマップの段。ミップマップがあれば、0段目を変えると小さい段は作り直すまで古いままです。ピクセルアートにミップマップが無い理由がもう1つ増えました。
  • xoffset、yoffset:四角がテクスチャの何処に入るか。此処では(dirtyX0, dirtyY0)。テクスチャの行は送った順に番号が付くので、y = 0は最初に送った行、つまり防壁の上端です(あたし達のスプライトは決して反転しません)。
  • width、height:四角の大きさ、w × hテクセル。
  • format、type:GL_RGBA、GL_UNSIGNED_BYTE。第6章と同じく、あたし達のメモリの並び方です。
  • pixels:GLがあたし達のメモリの何処から読み始めるか。大きな配列の中の四角の左上のテクセルのアドレス、pixels.data() + 4 · (dirtyY0 · 88 + dirtyX0)です。

四角は其の段の中に収まっていなければならず、はみ出すとGL_INVALID_VALUEで失敗し、何も変わりません。
dirtyX1とdirtyY1はclearPixelの中で範囲に収まっているので、あたし達の四角は必ず収まります。
呼び出しから戻った時には、GLはあたし達のメモリを読んで(又はコピーして)いるので、ゲームはすぐに配列を又変えて構いません。

2つ目の防壁への例の当たりでは、四角はx = 22 + 7 = 29、y = 7、6 × 6テクセルです。
テクスチャ全体の88⋅16⋅4=5632バイトの代わりに144バイトです。
1回の着弾で消えるのは多くて6 × 8の範囲なので、1回の当たりで送るのは6⋅8⋅4=192バイトを超えません。
スクリーンショットのHUDでは96です。

アンパックのパラメーター

此の呼び出しには落とし穴があります。
既定では、GLは渡したpixelsに丁度其の四角だけが行ごとに入っていると考えます。
widthテクセル、其の直後に次の行です。
でもあたし達の四角は、88テクセル幅の配列の中の窓です。
1行の6テクセルの後には配列の其の行の残り82テクセルが続き、四角の次の行は前の行の88テクセル(352バイト)後から始まります。

其れをGLに伝えるのがGL_UNPACK_ROW_LENGTHです。
アップロードする物の幅と違う時の、メモリの中の1行の長さ(ピクセル数)です。

上:88 × 16のCPUの配列と、x 29、y 7、6 × 6の変わった四角。ポインターは其の左上で、配列の先頭から2580バイト。下:同じバイトをメモリの並びで。GL UNPACK ROW LENGTHが88ならGLは24バイト読み、328バイト飛ばし、352バイト後から次の行を読む事を、1784バイトの間に6回繰り返す。既定の0なら144バイトを一続きに読み、其れは違うピクセル

glPixelStorei(pname, param)はピクセルストア(アンパック)のパラメーターを1つ設定します。
此れは其の後の全てのアップロードがクライアントのメモリをどう読むかを決めます。
glTextureSubImage1D/2D/3D、古いglTexImage*、其の仲間です。
2Dのアップロードで大事な物:

  • GL_UNPACK_ROW_LENGTH(既定0):メモリの中の1行のピクセル数。0は「widthと同じ」の意味。
  • GL_UNPACK_SKIP_PIXELS、GL_UNPACK_SKIP_ROWS(既定0):四角が始まる前に、ポインターから飛ばすピクセル数と行数。
  • GL_UNPACK_ALIGNMENT(既定4、1、2、4、8のどれか):各行が此のバイト数の倍数から始まる(第6章)。
  • GL_UNPACK_IMAGE_HEIGHT、GL_UNPACK_SKIP_IMAGES:同じ考えを1次元上で。3Dテクスチャと配列のレイヤー用。
  • GL_UNPACK_SWAP_BYTES、GL_UNPACK_LSB_FIRST:バイト順と1ビット画像の古いスイッチ。触らないで下さい。

まとめると、lを行の長さ(ROW_LENGTH、0ならwidth)、aをアラインメントとして、メモリの中の1行は

s=a⌈4l/a⌉バイト(RGBA8:1ピクセル4バイト)

で、四角のj行目は

p+(skipRows+j)⋅s+4⋅skipPixels

から始まります。
pはpixelsのポインターです。
RGBA8では4lは必ず4の倍数なので、既定のアラインメントは何も変えません。
l=88ならs=352バイトです。
例では、pは配列の先頭から2580バイト(4⋅(7⋅88+29))、各行は2580、2932、…、4340から始まり、GLは其々から24バイトを読みます。
1784バイトのメモリの中から144バイトです。

ポインターを自分でずらす代わりに、pixels.data()を渡し、GL_UNPACK_SKIP_PIXELSを29、GL_UNPACK_SKIP_ROWSを7にしても構いません。
同じ式で、オフセットをpからskipの項へ移しただけです。
どちらでも良いのですが、ポインターの計算なら設定して戻すパラメーターが3つではなく1つで済みます。

避けるべき3つの間違い:

  • ROW_LENGTHを忘れる。 するとGLは6⋅6⋅4=144バイトを一続きに読みます。最初の行は正しく、残りの5行は配列の7行目の先の方から来ます。エラーは出ず、画面のピクセルが違うだけで、CPUの正本(従って当たり判定)は正しいままです。課題3で其れがどう見えるかが分かります。
  • 戻さない。 ピクセルストアの状態はテクスチャではなくコンテキストの物です。88のままだと、次に何かをアップロードする時、例えば幅512テクセルのフォントアトラスにも効き、其れは88ピクセルおきの行として読まれ、斜めにずれて出て来ます。設定して、送って、0に戻す。Texture2D::uploadがアラインメントでしているのと同じです。
  • ピクセルアンパックバッファがバインドされている。 GL_PIXEL_UNPACK_BUFFERにバッファがバインドされていると、最後の引数はポインターではなく、其のバッファの中のバイトオフセットになります。あたし達はバインドしませんが、PBOでテクスチャを流し込むコードはバインドするので、其の時に此処へクライアントのポインターを渡すと滅茶苦茶になります。

CPUの写しが正本

テクスチャは鏡に過ぎません。
本当の値はCPUのstd::vector<uint8_t>です。
ゲームの処理は其れだけを読み書きし、uploadがフレームに1回、変わった四角でGPUの写しを最新にします。

何故防壁をテクスチャだけに持たないのでしょうか?
当たり判定には更新の途中で今すぐピクセルが要り、テクスチャを読み戻す(glGetTextureSubImage)と、其れに書き込む全ての命令をGPUが終えるまでCPUが待つからです。
ゲームの処理の真ん中で、毎ステップ、パイプラインが止まります。
又、ゲームの処理はGLを知らずに済みます。
Shields::hitとerodeは、画面の無いテストでもサーバーでも其のまま動きます。
そして処理は固定ステップで動き、描画はフレームごとです。
変わった四角は其の2つの間の受け渡しです。
「CPUの正本 + 変わった所だけ更新するGPUの写し」という形は何処にでもあります。
壊せる地形、ミニマップ、戦場の霧、文字のキャッシュ等です。

エイリアンが防壁を食べる

隊列が十分下りて来ると、エイリアンは防壁の中を歩き、触れた所を壊します:

  // 防壁まで下りてきた宇宙人は防壁を食べる / aliens that reach the shields eat them
  for (const Alien &a : formation.aliens)
    if (a.alive && a.box().bottom() > kShieldY) shields->eraseRect(a.box());

void Shields::eraseRect(const Rect &box) {
  for (int i = 0; i < kShieldCount; ++i) {
    Rect s = bounds(i);
    int x0 = std::max(0, static_cast<int>(std::floor(box.left() - s.x)));
    int x1 = std::min(kShieldW, static_cast<int>(std::ceil(box.right() - s.x)));
    int y0 = std::max(0, static_cast<int>(std::floor(box.top() - s.y)));
    int y1 = std::min(kShieldH, static_cast<int>(std::ceil(box.bottom() - s.y)));
    for (int y = y0; y < y1; ++y)
      for (int x = x0; x < x1; ++x) clearPixel(i * kShieldW + x, y);
  }
}

一番下の行の下端はy = 94から始まり、6 pxずつ下がるので、8回下がった所で防壁の上端(136)に届きます(94+8⋅6=142)。
此れは毎ステップ実行されますが、clearPixelは既に空のピクセルを飛ばすので、最初に齧った後、止まっているエイリアンは何もアップロードしません。

防壁を描くのは、同じテクスチャから部分UVで4枚のスプライトです:

void Shields::draw(SpriteBatch &batch, float layer) const {
  for (int i = 0; i < kShieldCount; ++i)
    batch.draw({.texture = &tex,
                .position = topLeft[i],
                .size = {kShieldW, kShieldH},
                .uv = {static_cast<float>(i) / kShieldCount, 0.0f, 1.0f / kShieldCount, 1.0f},
                .layer = layer});
}

スクリプトで遊んだ最初と、900フレーム後の防壁です:

防壁の行を等倍で切り出した物が2つ。2フレーム目:無傷の防壁4つ。900フレーム目:2つ目は自機の弾で下から切り開かれ、3つ目は上下から食われてピクセルがぶら下がって残り、4つ目は少し欠けている

28.7 爆発

爆発するエイリアンは別のコマに過ぎない

第27章で隊列には本物のインスタンシングの描画が付きました。
エイリアン1匹にインスタンス1つ、其々16バイトで、インスタンスごとのコマ番号を頂点シェーダーがスプライトシートの長方形の表から引きます。
其のコマ番号が今役に立ちます。
爆発は別のコマに過ぎないのです。
撃たれたエイリアンは取り除かれません。
aliveでなくなり、0.25秒の秒読みを始めます:

void Formation::kill(Alien &alien) {
  alien.alive = false;
  alien.dying = kAlienBoomTime;
}

void Formation::updateExplosions(float dt) {
  for (Alien &a : aliens) a.dying = std::max(0.0f, a.dying - dt);
}

bool Formation::cleared() const {
  return std::none_of(aliens.begin(), aliens.end(), [](const Alien &a) { return a.alive || a.dying > 0.0f; });
}

ゲームの処理が見るのはaliveです。
行進はすぐに其のエイリアンを飛ばし(隊列はすぐに速くなります)、撃つ事も、もう一度当たる事もありません。
dyingは絵の為だけです。
其の間シーンは爆発のコマを選びます。
前半はalien_boom_0、後半はalien_boom_1です(2コマ、8 fpsのクリップで丁度0.25秒):

int PlayScene::alienFrame(const Alien &a) const {
  if (!a.alive) return boomFrames[a.dying > 0.5f * kAlienBoomTime ? 0 : 1];
  return frames[static_cast<int>(a.kind)][a.pose];
}

インスタンスのリストには爆発中のエイリアンも入ります:

  if (g.instanced) {
    std::vector<AlienInstance> list;
    for (const Alien &a : formation.aliens)
      if (a.alive || a.dying > 0.0f)
        list.push_back({a.position, static_cast<std::uint32_t>(alienFrame(a)), packRgba8(kWhite)});
    g.formationRenderer.draw(g.world.matrix(), list);

FormationRendererにも其のシェーダーにも、1行の変更もありません。
スクリーンショットのHUDが、生きているエイリアンが47匹で768 B/frameと言っているのは其の為です。
48インスタンス × 16 Bで、48番目は爆発中の甲虫です。
SpriteBatchの方も同じコマを描き、2つの描き方は今でもピクセル単位で同じ画像になります(其のフレームで確かめました)。
cleared()は最後の爆発が終わるのを待つので、最後のエイリアンの爆発が次の隊列に切られる事はありません。

破片

爆発ごとに、エイリアンの色の1ピクセルのパーティクルが10個飛び出します:

class Particles {
public:
  // centreから全方向へcount個。速さはspeedLo〜speedHi(ピクセル毎秒)、寿命は0.3〜0.7秒
  // count pieces from centre in all directions, speed speedLo..speedHi px/s, lifetime 0.3..0.7 s
  void burst(Vec2 centre, int count, Vec4 color, float speedLo, float speedHi, Rng &rng);
  void update(float dt);
  void draw(SpriteBatch &batch, float layer = 0.0f) const;
  void clear() { items.clear(); }
  size_t size() const { return items.size(); }

private:
  struct Particle {
    Vec2 position, velocity;
    float life, lifetime;
    Vec4 color;
  };
  std::vector<Particle> items;
};

void Particles::update(float dt) {
  for (Particle &p : items) {
    p.position += p.velocity * dt;
    p.velocity.y += 60.0f * dt;   // 少し落ちる / falls a little
    p.velocity = p.velocity * (1.0f - 1.5f * dt); // 空気抵抗のような減速 / slows down, like drag
    p.life -= dt;
  }
  std::erase_if(items, [](const Particle &p) { return p.life <= 0.0f; });
}

void Particles::draw(SpriteBatch &batch, float layer) const {
  for (const Particle &p : items) {
    Vec4 c = p.color;
    c.w *= std::min(1.0f, 2.0f * p.life / p.lifetime); // 後半で消えていく / fades during the second half
    batch.drawRect({std::round(p.position.x), std::round(p.position.y), 1.0f, 1.0f}, c, layer);
  }
}

まだ生きて見える一番小さなパーティクルシステムです。
ランダムな向き(Rng::direction)と速さ、破片が弧を描いて落ちる少しの重力(60 px/s²)、遅くなる為の抵抗、そして寿命の前半は1のままで其の後0まで直線的に下がるアルファです。
位置はピクセルアートの決まりに従い、整数のピクセルに丸めます。
パーティクルはシミュレーションの一部(updateで動きます)ですが、当たり判定には加わらず、補間もしません。
寿命は半秒、大きさは1 pxなので、違いは誰にも見えません。
SpriteBatchを通して、色を付けた1 × 1の白い四角として描くので、効果全体で描画呼び出しは増えません。

着弾のフレア

エイリアン以外への着弾では、splatスプライトを0.12秒、色を付けて見せます。
防壁なら緑、戦場の上端や弾同士がぶつかった所なら薄い黄色、エイリアンの弾が地面に落ちた所ならオレンジです。

struct Flare {
  int frame;     // スプライトシートのコマ / sprite sheet frame
  Vec2 centre;
  float life;    // 残り秒 / seconds left
  Vec4 color;
};

  for (const Flare &f : flares) {
    Sprite s = g.sprites.sprite(f.frame, {std::round(f.centre.x), std::round(f.centre.y)}, {0.5f, 0.5f});
    s.color = f.color;
    b.draw(s);
  }

スプライトは原点(0.5, 0.5)、つまり着弾の点を中心に描き、更新で寿命を減らして、切れたフレアをstd::erase_ifで取り除きます。
此の小さな光は、大きさの割にゲームの手触りに効きます。
何にも当たらなかった時でも、自分の弾が何処で終わったかを教えてくれます。

自機の爆発で行進が止まる

自機に当たると、killShip(上)が1.4秒の爆発を始めます。
2コマのship_boomのクリップを8 fpsで繰り返し、青緑とオレンジのパーティクルが36個です。
其の間、シーンは減らした更新を行います:

  playerPrevX = playerX;
  if (shipDying > 0.0f) {
    // 自機の爆発中:隊列も宇宙人の弾も止まる(元のゲームと同じ)。終わったら真ん中に戻るか、ゲームオーバー
    // While the ship explodes the formation and the alien fire stop (as in the original). Afterwards the ship comes
    // back in the middle, or the game is over
    shipBoom.update(dt);
    formation.updateExplosions(dt);
    updateShot(dt);
    shipDying -= dt;
    if (shipDying <= 0.0f) {
      shipDying = 0.0f;
      if (lives > 0) {
        playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f);
      } else {
        gameOver = true;
        printf("game over: %d kills\n", kills);
      }
    }
    return;
  }

元のゲームと同じく、行進、エイリアンの射撃、自機の操作が止まります。
残機を失う瞬間は一息で、プレイヤーは次の勝負の前に息をつけます。
エイリアンの爆発と自機の最後の弾は最後まで進みます(運の良い最後の一発は得点になり得ます)。
1.4秒後に自機は真ん中に戻ります。
playerPrevXも設定するので、補間で死んだ場所から滑って来る事はありません。

28.8 残機・侵略・やり直し

updateの残りは、勝負がどう終わるかを調べます:

  // 自機の高さまで来たら侵略された:残りの自機に関係なくゲームオーバー / reaching the ship's row is an invasion:
  // game over whatever lives are left
  if (formation.alive() > 0 && formation.bounds().bottom() > kPlayerY) {
    printf("invaded\n");
    lives = 1;
    killShip();
    return;
  }
  // 全滅させたら次の隊列(第29章で場面ごと読み直す) / when the formation is wiped out, a new one comes (chapter 29
  // reloads the whole scene)
  if (formation.cleared()) {
    ++waves;
    printf("wave cleared: %d kills\n", kills);
    formation.reset(formationStartX(), kFormationTop);
    fireTimer = 1.0f;
  }
}

  • 自機の残機は3。当たる度に1つ減り、3回目の爆発の後でゲームオーバーです。
  • 生きているエイリアンの箱が自機の行に届く(下端がy = 158より下)と、侵略です。残機が幾つあってもゲームオーバーです。killShipの前にlives = 1にするのは、爆発と其の一時停止を使い回す為で、爆発はゲームオーバーの状態で終わります。一番下の行(下端94)なら、11回下がった後です:94+11⋅6=160>158。10回では丁度154です。
  • 全滅させた隊列は、壊れた防壁のまま、単に一番上から又始まります。第29章で此れを本当の面(ウェーブ)にします。

ゲームオーバーの状態でもシーンは生きています(爆発とパーティクルは最後まで進み、隊列は勝った場所に留まります)。
UIのパスが其の上に帯を描きます。
もう一度遊ぶのは1行です:

  if (gameOver) {
    formation.updateExplosions(dt);
    // やり直し:この場面を新しい場面と入れ替える(全部が最初の状態に戻る) / play again: replace this scene with a
    // new one (everything starts from scratch)
    if (in.actionPressed("confirm")) scenes().replace(std::make_unique<PlayScene>(g));
    return;
  }

シーンを入れ替えてやり直すのが、一番簡単なリセットです。
全てのメンバーを忘れずに戻さなければならないreset()関数(そして新しいメンバーを足した時に誰かが更新し忘れる関数)はありません。
新しいPlaySceneは一から作られ、残機は満タン、隊列は新しく、防壁も自分のテクスチャを持つ新品です。
古いシーンは防壁のテクスチャも含めて、更新の後、もう誰も使わなくなってからSceneManagerが壊します(第26章がシーンの変更を予約するのは正に此の為です)。
星は自分のRng sky(1978)から作るので空は同じままです。
Game::rngはGameの中で続くので、2回目のゲームは1回目と違う展開になります。

1つ、わざと荒い所を残してあります。
スペースはfireでもありconfirmでもあるので、ゲームが終わった時にまだスペースを連打していると、すぐにやり直しになります。
第29章で、入力が効くまでに少し間を置く本物のタイトルとゲームオーバーのシーンを足します。

28.9 更新と描画の順番

此れだけ部品が絡み合うと、1回の更新の順番も設計の一部です:

  1. デモのキー(Esc、I、B、=と−)。
  2. パーティクルとフレア。どの状態でも動きます。
  3. ゲームオーバー:爆発と、confirmを待つ事だけ。
  4. 自機の爆発中:上の減らした更新。
  5. 自機を動かし、撃つかも知れない。
  6. formation.update:行進(1ステップに1匹)と爆発のタイマー。
  7. updateShot:自機の弾をエイリアンの弾、エイリアン、防壁、上端とテスト。
  8. alienFire:エイリアンの弾が増えるかも知れない。
  9. updateAlienShots:エイリアンの弾を自機、防壁、地面とテスト。
  10. 防壁まで来たエイリアンが防壁を食べる。
  11. 侵略、其れから全滅。

エイリアンを自機の弾より先に動かすので、弾は今のエイリアンの位置、つまり描かれる位置とテストされます。
新しいエイリアンの弾は自機の弾のテストの後で作られるので、自機の弾との最初のテストは1ステップ後になります。
其の時は撃ったエイリアンのすぐ下にいるので、害はありません。

描画は先にアップロードし、其れから第27章と同じく3つのパスで奥から手前へ描きます:

void PlayScene::draw(float alpha) {
  if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor)
  // 防壁:変わった所だけGPUへ(描く前に) / shields: send only the changed part to the GPU (before drawing)
  shields->upload();
  if (shields->lastUploadBytes() > 0) shieldBytes = shields->lastUploadBytes();

  // 奥から:背景と防壁(バッチ)→ 隊列(インスタンシングかバッチ)→ 自機・弾・爆発(バッチ)
  // Back to front: background and shields (batch) → formation (instanced or batch) → ship, bullets, explosions (batch)
  g.batch.begin(g.world.matrix());
  drawBackground();
  shields->draw(g.batch);
  g.batch.end();

  drawFormation();

アップロードは、防壁のテクスチャを読む描画呼び出しより前でなければなりません。
GLの命令は順番に実行されるので、描画は新しいピクセルを見ます。
弾は第26章の補間でprevY + (y − prevY) · alphaを丸めた位置に描きます。
pause()は、自機と同じ様に全ての弾のprevY = yにします。

28.10 動かす

何時も通りビルドし、プロジェクトのルートから実行します:

cmake --build build -j8
./build/games/invaders/invaders

コンソールには何が起きたかが出るので、ゲームを調整する時に便利です:

ship hit: lives 2
ship hit: lives 1
ship hit: lives 0
game over: 22 kills

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

  • Windows(Visual Studio): スタートアップ項目にinvadersを選びます。実行ファイルはbuild\games\invaders\Debug\invaders.exeで、作業ディレクトリは既にプロジェクトのルートです(第25章)。上のログはコンソールのウィンドウに出ます。
  • Linux、FreeBSD: 上の通りプロジェクトのルートから実行して下さい。そうしないとgames/invaders/assets/が見付かりません。
  • 全て: キーはGLFWのキーコードで、USキーボードでの位置で名前が付いています。従ってAZERTYのキーボードでは「W」(撃つ)はZと書かれたキーです。矢印キーとスペースはどこでも同じです。glPixelStorei(GL_UNPACK_ROW_LENGTH, …)はどのドライバーでもデスクトップのOpenGLのコアにあります。無いのはOpenGL ES 2.0とWebGL 1だけで(ES 3.0とWebGL 2にはあります)、いつかブラウザに移すなら気にして下さい。

28.11 本物のゲームではどうしているか

  • 1978年の元のゲームには、防壁の為の別のデータが全くありませんでした。防壁は筐体の1ビットのビデオメモリのピクセルで、当たると其のメモリから爆発の形の部分を消しました。あのギザギザの見た目は其処から来ています。あたし達のCPUの配列が其のビデオメモリの役で、テクスチャは其れを見せる手段に過ぎません。
  • 弾の数の上限は古典的な設計の一部です。プレイヤーの弾は1発、エイリアンの弾も一度に数発だけで、其の1つはプレイヤーの列を狙います。あたし達の3発と3回に1回の狙いも、其の考えに沿っています。
  • オブジェクトプール: 何百発もの弾があるシューティングは、弾を決して確保し直さない固定の配列に持ち、よく空きリストを使います。出すのに手間がかからず、メモリも動きません。最大3要素のあたし達のvectorには要りません。
  • パーティクル: エンジンはエミッターと、寿命に沿った色や大きさのカーブを持つパーティクルシステムを使い、何万個にもなる時はGPUで(コンピュートシェーダー又はトランスフォームフィードバックで)シミュレーションする事が多いです。あたし達のも同じ考えで、CPUで十分な小ささです。
  • 壊せるピクセル: Noitaの様に壊せる地形を中心にしたゲームは、世界をCPUでチャンクに分けてシミュレーションし、変わったチャンクだけをアップロードします。あたし達の変わった四角を大きくした物です。大きな、又は頻繁なアップロードはピクセルアンパックバッファ(GL_PIXEL_UNPACK_BUFFER)を通し、CPUを止めずにコピー出来る様にします。
  • 当たり判定の箱: プレイヤーに有利な箱は何処にでもあります。弾幕シューティングでは、スプライトはずっと大きいのに、自機の箱は数ピクセルしか無く、点として描かれる事もあります。
  • 衝突のフィルター: エンジンでは、どのレイヤーがどのレイヤーと当たるかを指定出来ます(Godotのコリジョンレイヤーとマスク、Unityのレイヤーの衝突マトリクス)。弾ごとのあたし達の決まったテストの順番は、其のマトリクスを手で書いた物です。

28.12 まとめ

  • 自機の弾は一度に1発(std::optional<Bullet>):actionPressedで、前の弾が消えた時だけ撃てます。連打より狙いが大事です。
  • 当たり判定は第26章のAABBのoverlapsで、箱はプレイヤーに有利に選びます(エイリアンは輪郭込みの14 × 10、自機は輪郭抜きの13 × 7)。自機の弾はエイリアンの弾、エイリアン、防壁、上端の順に、エイリアンの弾は自機、防壁、地面の順にテストし、最初の当たりが勝ちます。
  • すり抜け無し: 掃引テスト無しで大丈夫なのは、1ステップの相対的な移動が、どれも2つの箱の大きさの和より短いからです(4 + 6 = 10 < 15、5.25 < 12、1.25 < 14)。デバッグ用の行進の速さでは崩れます。
  • エイリアンの射撃: 0.5〜1.1秒のタイマー、最大3発、生きているエイリアンをランダムに選んだ列か(3回に1回)自機の上の列で、其の列の一番下のエイリアンが撃ちます。乱数は全て種付きのGame::rngから。
  • 防壁: 88 × 16のGL_RGBA8のテクスチャ1枚を、部分UVのスプライト4枚で描きます。CPUの配列が正本で、当たりは弾の向きにピクセル単位で調べ、6 × 8の着弾の形で削ります。変わった四角が変更を集め、drawは其の四角だけを送ります(1回の当たりで5632バイトではなく最大192バイト)。
  • glTextureSubImage2Dはxoffsetとyoffsetで段の一部を置き換えます。GL_UNPACK_ROW_LENGTHはあたし達のメモリでの1行の長さを伝えるので、四角を大きな配列から直接読めます(又はSKIP_PIXELSとSKIP_ROWS)。ピクセルストアの状態はグローバルなので0に戻します。
  • 自分で送る物は自分で乗算済みに: シートの透明なテクセルには、乗算済みのブレンドが足してしまうにじみ止めの色が入っています。
  • 爆発: 死んだエイリアンは0.25秒、爆発のコマでインスタンスのリストに残り(描画側の変更無し)、破片が10ピクセル。着弾のフレア。自機の1.4秒の爆発は行進を止め、エイリアンの弾を消します。
  • ゲームオーバーは残機3を失うか侵略で。やり直しはシーンを新しい物と入れ替えます。

28.13 課題

  1. ★ すり抜けの計算:エイリアンの弾が毎秒75ではなく600 pxで落ちたら、自機の弾(毎秒240 px、5 px)は当たらずに其れをすり抜け得るでしょうか?又、エイリアンの弾が自機の高さ7 pxの箱を飛ばさない為には、どこまで速く落ちて良いでしょうか?4 + 10 = 14 > 12なので「すり抜け得る」、そして1ステップ7 + 7 = 14 px未満、つまり毎秒840 px未満になるはずです。
  2. ★ 自機の弾を同時に2発まで撃てる様にして下さい。shotをstd::vector<Bullet>にし、2発未満の時に撃ち、updateShotのテストを弾ごとに行います。素早く2回押すと黄色の箱が2つ見え(B)、同じ押し方で隊列が目に見えて早く空になるはずです。ゲームが狙う物から連打する物に変わる事に注目して下さい。
  3. ★★ Shields::uploadからGL_UNPACK_ROW_LENGTHの2行を消して下さい。画面では新しい穴の一番上の行だけが現れ、残りは、其の一番上の行の先の方(配列の同じ行の右側)からコピーされたピクセルで埋まったまま描かれるはずです。一方、当たり判定はCPUの正本を読むので、弾は其処を抜けて行きます。次に最初の行だけ戻し、0に戻す行は戻さずに、ゲームオーバーの後でやり直して下さい。何も壊れないはずです。後で行われる唯一のアップロード(createの全体のアップロード)が偶々88テクセル幅だからです。どんなアップロードなら壊れるかを説明して下さい。
  4. ★★ Shieldsに防壁ごとの変わった四角を持たせ、フレームに最大4つの四角を送る様にして下さい。同じフレームで1つ目と4つ目の防壁の同じ高さに当てると(例えば、各防壁の7〜12行目・7〜12列目の6 × 6の四角2つ)、共有の四角なら72 × 6テクセルで1728バイト、別々なら288バイトです。HUDに合計を出して下さい。
  5. ★★ ギザギザの削り方:kSplatの代わりに、当たりの周りの半径3の円の各ピクセルを確率0.6で消して下さい(g.rng.chance(0.6f))。穴は自然な形に見え、同じ入力なら毎回同じになるはずです。其れから、当たったピクセル自身が残ると何が起きるかを考え、必ず消える様に直して下さい。
  6. ★★★ ピクセル単位のエイリアンの当たり:エイリアンの全てのコマをloadSpriteImageでシートから切り出し、AABBのテストが当たった後で、弾の箱をエイリアンの今のコマのアルファとテストして下さい(Shields::hitと同じ様に)。甲虫の足と角の間の隙間を通る弾は外れる様になり、Bの箱だけでは全てが分からなくなるはずです。今、どちらのテストがブロードフェーズで、どちらがナローフェーズでしょうか?
  7. ★★★ 防壁をGPUだけに持たせて下さい。CPUの配列を消し、着弾の形のマスをglTextureSubImage2Dで送って削り、当たり判定は弾の下のピクセルをglGetTextureSubImageで読み戻して行います。其れでも動きますが、updateShotをstd::chronoで計ってみて下さい。読み戻す度に、GPUが溜まった仕事を終えるのを待ちます。GPUの仕事が多い程フレームの時間が悪くなる理由と、CPUの正本が其れを避ける理由を説明して下さい。

DIFFをダウンロード

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

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

前新
@@ -5,7 +5,9 @@ add_executable(invaders
5 src/main.cc 5 src/main.cc
6 src/play_scene.cc 6 src/play_scene.cc
7 src/formation.cc 7 src/formation.cc
8 src/formation_renderer.cc) 8 src/formation_renderer.cc
    9 src/shields.cc
    10 src/effects.cc)
9 target_include_directories(invaders PRIVATE src) 11 target_include_directories(invaders PRIVATE src)
10 target_link_libraries(invaders PRIVATE engine) 12 target_link_libraries(invaders PRIVATE engine)
11 enable_warnings(invaders) 13 enable_warnings(invaders)

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

前新
@@ -13,8 +13,11 @@ is already the project root)。
13 | キー / Key | | 13 | キー / Key | |
14 |---|---| 14 |---|---|
15 | ← → / A D | 移動 / move | 15 | ← → / A D | 移動 / move |
    16 | Space / ↑ / W | 撃つ / fire |
16 | I | 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch | 17 | I | 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch |
    18 | B | 当たり判定の箱 / collision boxes |
17 | = / - | 行進を速く・遅く / march faster / slower | 19 | = / - | 行進を速く・遅く / march faster / slower |
    20 | Space / Enter | ゲームオーバーの後:もう一度 / after game over: play again |
18 | Esc | 終了 / quit | 21 | Esc | 終了 / quit |
19   22  
20 ## ファイル / Files 23 ## ファイル / Files
@@ -23,4 +26,6 @@ is already the project root)。
23 * `src/play_scene.cc` 遊ぶ場面 / the play scene 26 * `src/play_scene.cc` 遊ぶ場面 / the play scene
24 * `src/formation.hh/.cc` 隊列と行進(GLなし) / the formation and its march (no GL) 27 * `src/formation.hh/.cc` 隊列と行進(GLなし) / the formation and its march (no GL)
25 * `src/formation_renderer.hh/.cc`, `shaders/formation.vert` インスタンシングで隊列を描く / instanced formation drawing 28 * `src/formation_renderer.hh/.cc`, `shaders/formation.vert` インスタンシングで隊列を描く / instanced formation drawing
    29 * `src/shields.hh/.cc` 削れる防壁(CPUのピクセル+glTextureSubImage2D) / eroding shields (CPU pixels + glTextureSubImage2D)
    30 * `src/effects.hh/.cc` 破片と着弾 / debris particles and impact flares
26 * `assets/` 絵(作者の自作スクリプトで生成。スクリプトはダウンロードに含まれない) / art (generated by the author's own script, not part of the download) 31 * `assets/` 絵(作者の自作スクリプトで生成。スクリプトはダウンロードに含まれない) / art (generated by the author's own script, not part of the download)

ファイル: /dev/null | b/games/invaders/src/effects.cc

前新
@@ -0,0 +1,29 @@
    1 #include "effects.hh"
    2  
    3 #include <algorithm>
    4 #include <cmath>
    5  
    6 void Particles::burst(Vec2 centre, int count, Vec4 color, float speedLo, float speedHi, Rng &rng) {
    7 for (int i = 0; i < count; ++i) {
    8 float life = rng.range(0.3f, 0.7f);
    9 items.push_back({centre, rng.direction() * rng.range(speedLo, speedHi), life, life, color});
    10 }
    11 }
    12  
    13 void Particles::update(float dt) {
    14 for (Particle &p : items) {
    15 p.position += p.velocity * dt;
    16 p.velocity.y += 60.0f * dt; // 少し落ちる / falls a little
    17 p.velocity = p.velocity * (1.0f - 1.5f * dt); // 空気抵抗のような減速 / slows down, like drag
    18 p.life -= dt;
    19 }
    20 std::erase_if(items, [](const Particle &p) { return p.life <= 0.0f; });
    21 }
    22  
    23 void Particles::draw(SpriteBatch &batch, float layer) const {
    24 for (const Particle &p : items) {
    25 Vec4 c = p.color;
    26 c.w *= std::min(1.0f, 2.0f * p.life / p.lifetime); // 後半で消えていく / fades during the second half
    27 batch.drawRect({std::round(p.position.x), std::round(p.position.y), 1.0f, 1.0f}, c, layer);
    28 }
    29 }

ファイル: /dev/null | b/games/invaders/src/effects.hh

前新
@@ -0,0 +1,36 @@
    1 // 爆発の飾り(第28章):飛び散るピクセル(パーティクル)と、短く見せるスプライト(着弾など)
    2 // Explosion dressing (chapter 28): flying pixels (particles) and sprites shown for a moment (impacts and such)
    3 #pragma once
    4  
    5 #include "engine/rng.hh"
    6 #include "engine/sprite_batch.hh"
    7  
    8 #include <vector>
    9  
    10 // 1ピクセルの破片。固定ステップで動き、だんだん消える / one-pixel debris: moves in the fixed step and fades out
    11 class Particles {
    12 public:
    13 // centreから全方向へcount個。速さはspeedLo〜speedHi(ピクセル毎秒)、寿命は0.3〜0.7秒
    14 // count pieces from centre in all directions, speed speedLo..speedHi px/s, lifetime 0.3..0.7 s
    15 void burst(Vec2 centre, int count, Vec4 color, float speedLo, float speedHi, Rng &rng);
    16 void update(float dt);
    17 void draw(SpriteBatch &batch, float layer = 0.0f) const;
    18 void clear() { items.clear(); }
    19 size_t size() const { return items.size(); }
    20  
    21 private:
    22 struct Particle {
    23 Vec2 position, velocity;
    24 float life, lifetime;
    25 Vec4 color;
    26 };
    27 std::vector<Particle> items;
    28 };
    29  
    30 // 一コマのスプライトを少しの間だけ見せる(着弾の「パッ」) / shows one sprite frame for a moment (the impact "pop")
    31 struct Flare {
    32 int frame; // スプライトシートのコマ / sprite sheet frame
    33 Vec2 centre;
    34 float life; // 残り秒 / seconds left
    35 Vec4 color;
    36 };

ファイル: a/games/invaders/src/formation.cc | b/games/invaders/src/formation.cc

前新
@@ -21,6 +21,26 @@ void Formation::reset(float left, float top) {
21 budget = 0.0f; 21 budget = 0.0f;
22 } 22 }
23   23  
    24 void Formation::kill(Alien &alien) {
    25 alien.alive = false;
    26 alien.dying = kAlienBoomTime;
    27 }
    28  
    29 void Formation::updateExplosions(float dt) {
    30 for (Alien &a : aliens) a.dying = std::max(0.0f, a.dying - dt);
    31 }
    32  
    33 bool Formation::cleared() const {
    34 return std::none_of(aliens.begin(), aliens.end(), [](const Alien &a) { return a.alive || a.dying > 0.0f; });
    35 }
    36  
    37 const Alien *Formation::lowestInColumn(int column) const {
    38 const Alien *lowest = nullptr;
    39 for (const Alien &a : aliens)
    40 if (a.alive && a.column == column && (!lowest || a.position.y > lowest->position.y)) lowest = &a;
    41 return lowest;
    42 }
    43  
24 int Formation::alive() const { 44 int Formation::alive() const {
25 return static_cast<int>(std::count_if(aliens.begin(), aliens.end(), [](const Alien &a) { return a.alive; })); 45 return static_cast<int>(std::count_if(aliens.begin(), aliens.end(), [](const Alien &a) { return a.alive; }));
26 } 46 }
@@ -42,6 +62,7 @@ Rect Formation::bounds() const {
42 } 62 }
43   63  
44 void Formation::update(float dt) { 64 void Formation::update(float dt) {
    65 updateExplosions(dt);
45 if (alive() == 0) return; 66 if (alive() == 0) return;
46 // 1ステップ(1/60秒)にrate/60匹。予算は浮動小数点数の和なので少し許す(60 × (1/60)は丁度1.0fだが、 67 // 1ステップ(1/60秒)にrate/60匹。予算は浮動小数点数の和なので少し許す(60 × (1/60)は丁度1.0fだが、
47 // 1/50秒のステップでは5回目の更新の予算が2ではなく1.99999964になる) 68 // 1/50秒のステップでは5回目の更新の予算が2ではなく1.99999964になる)

ファイル: a/games/invaders/src/formation.hh | b/games/invaders/src/formation.hh

前新
@@ -16,12 +16,16 @@ struct Alien {
16 Vec2 position; // 左上、整数のピクセル / top left, whole pixels 16 Vec2 position; // 左上、整数のピクセル / top left, whole pixels
17 int pose = 0; // 0か1:動くたびに入れ替わる(足踏み) / 0 or 1: flips every time it moves (the walk) 17 int pose = 0; // 0か1:動くたびに入れ替わる(足踏み) / 0 or 1: flips every time it moves (the walk)
18 bool alive = true; 18 bool alive = true;
    19 float dying = 0.0f; // 爆発の残り時間(第28章):死んだ後もしばらく爆発のコマで残る / explosion time left
    20 // (chapter 28): a dead alien stays on screen as an explosion for a moment
19 Rect box() const; // 当たり判定 = 絵の枠 / the collision box = the sprite cell 21 Rect box() const; // 当たり判定 = 絵の枠 / the collision box = the sprite cell
20 }; 22 };
21   23  
22 constexpr int kColumns = 11, kRows = 5; 24 constexpr int kColumns = 11, kRows = 5;
23 constexpr Vec2 kAlienSize = {14.0f, 10.0f}; // スプライトの枠 / the sprite cell 25 constexpr Vec2 kAlienSize = {14.0f, 10.0f}; // スプライトの枠 / the sprite cell
24 constexpr float kColumnSpacing = 16.0f, kRowSpacing = 14.0f; 26 constexpr float kColumnSpacing = 16.0f, kRowSpacing = 14.0f;
    27 constexpr float kAlienBoomTime = 0.25f; // 爆発のコマを見せる時間(alien_boomのクリップ:2コマ、8 fps) / how long the
    28 // explosion shows (the alien_boom clip: 2 frames at 8 fps)
25   29  
26 class Formation { 30 class Formation {
27 public: 31 public:
@@ -35,8 +39,17 @@ public:
35 // the sooner each one's turn comes around = the formation speeds up by itself 39 // the sooner each one's turn comes around = the formation speeds up by itself
36 void update(float dt); 40 void update(float dt);
37   41  
    42 // 撃たれた:行進から外れ、爆発のコマになる / shot: leaves the march and turns into an explosion
    43 void kill(Alien &alien);
    44 // 爆発の時計だけ進める(自機の爆発中は行進が止まるが、宇宙人の爆発は進む) / advances only the explosion timers (the
    45 // march stops while the ship explodes, alien explosions go on)
    46 void updateExplosions(float dt);
    47  
38 int alive() const; 48 int alive() const;
    49 bool cleared() const; // 全滅して、爆発も終わった / everyone is dead and the explosions are over
39 Rect bounds() const; // 生きている宇宙人を囲む箱(全滅なら大きさ0) / box around the living aliens (empty if none) 50 Rect bounds() const; // 生きている宇宙人を囲む箱(全滅なら大きさ0) / box around the living aliens (empty if none)
    51 // その列で一番下の生きている宇宙人(撃つのはこの宇宙人) / the lowest living alien of a column (it does the shooting)
    52 const Alien *lowestInColumn(int column) const;
40   53  
41 std::vector<Alien> aliens; // 行進の順番:下の行の左から右へ、それから上の行 / march order: bottom row left to right, 54 std::vector<Alien> aliens; // 行進の順番:下の行の左から右へ、それから上の行 / march order: bottom row left to right,
42 // then the row above 55 // then the row above

ファイル: a/games/invaders/src/game.hh | b/games/invaders/src/game.hh

前新
@@ -2,9 +2,12 @@
2 // Invaders: the data every scene shares, the screen layout, the scenes 2 // Invaders: the data every scene shares, the screen layout, the scenes
3 #pragma once 3 #pragma once
4   4  
    5 #include "effects.hh"
5 #include "formation.hh" 6 #include "formation.hh"
6 #include "formation_renderer.hh" 7 #include "formation_renderer.hh"
    8 #include "shields.hh"
7   9  
    10 #include "engine/animation.hh"
8 #include "engine/camera2d.hh" 11 #include "engine/camera2d.hh"
9 #include "engine/font.hh" 12 #include "engine/font.hh"
10 #include "engine/game_loop.hh" 13 #include "engine/game_loop.hh"
@@ -14,6 +17,7 @@
14 #include "engine/sprite_batch.hh" 17 #include "engine/sprite_batch.hh"
15 #include "engine/sprite_sheet.hh" 18 #include "engine/sprite_sheet.hh"
16   19  
    20 #include <optional>
17 #include <vector> 21 #include <vector>
18   22  
19 // 仮想解像度320 × 180(ウィンドウ1280 × 720で4倍)。真ん中の224ピクセル幅が戦場、左右48ピクセルは脇の板 23 // 仮想解像度320 × 180(ウィンドウ1280 × 720で4倍)。真ん中の224ピクセル幅が戦場、左右48ピクセルは脇の板
@@ -22,9 +26,14 @@
22 constexpr Vec2 kView = {320.0f, 180.0f}; 26 constexpr Vec2 kView = {320.0f, 180.0f};
23 constexpr float kArenaLeft = 48.0f, kArenaRight = 272.0f; 27 constexpr float kArenaLeft = 48.0f, kArenaRight = 272.0f;
24 constexpr float kFormationTop = 28.0f; // 最初の隊列の一番上 / the first formation's top row 28 constexpr float kFormationTop = 28.0f; // 最初の隊列の一番上 / the first formation's top row
    29 constexpr float kShieldY = 136.0f; // 防壁の上端 / the shields' top
25 constexpr float kPlayerY = 158.0f; // 自機の上端 / the ship's top 30 constexpr float kPlayerY = 158.0f; // 自機の上端 / the ship's top
26 constexpr float kGroundY = 170.0f; // 地面の線 / the ground line 31 constexpr float kGroundY = 170.0f; // 地面の線 / the ground line
27 constexpr float kPlayerSpeed = 60.0f; // ピクセル毎秒(1ステップ1ピクセル) / pixels per second (1 px per step) 32 constexpr float kPlayerSpeed = 60.0f; // ピクセル毎秒(1ステップ1ピクセル) / pixels per second (1 px per step)
    33 constexpr float kShotSpeed = 240.0f; // 自機の弾:1ステップ4ピクセル / the ship's bullet: 4 px per step
    34 constexpr float kAlienShotSpeed = 75.0f; // 宇宙人の弾 / alien bullets
    35 constexpr int kMaxAlienShots = 3;
    36 constexpr int kStartLives = 3;
28   37  
29 // ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference 38 // ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference
30 struct Game { 39 struct Game {
@@ -35,14 +44,17 @@ struct Game {
35 FormationRenderer &formationRenderer; 44 FormationRenderer &formationRenderer;
36 const Font &ui; // mono16:画面の解像度の文字 / text at screen resolution 45 const Font &ui; // mono16:画面の解像度の文字 / text at screen resolution
37 const SpriteSheet &sprites; // games/invaders/assets/sprites.atlas 46 const SpriteSheet &sprites; // games/invaders/assets/sprites.atlas
    47 const Image &shieldArt; // 防壁の絵(CPU側、削る元) / the shield art (CPU side, what gets eroded)
38 Camera2D world; // 320 × 180のキャンバス / the 320 × 180 canvas 48 Camera2D world; // 320 × 180のキャンバス / the 320 × 180 canvas
39 Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI 49 Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI
40 Viewport uiViewport; 50 Viewport uiViewport;
41 Rng rng{27}; 51 Rng rng{27};
42 bool instanced = true; // 隊列をインスタンシングで(I) / draw the formation instanced (I) 52 bool instanced = true; // 隊列をインスタンシングで(I) / draw the formation instanced (I)
    53 bool showBoxes = false; // 当たり判定の箱(B) / collision boxes (B)
43 }; 54 };
44   55  
45 // 遊ぶ場面:自機と行進する隊列 / the play scene: the ship and the marching formation 56 // 遊ぶ場面:自機、行進する隊列、弾、防壁、爆発 / the play scene: the ship, the marching formation, bullets,
    57 // shields, explosions
46 class PlayScene : public Scene { 58 class PlayScene : public Scene {
47 public: 59 public:
48 explicit PlayScene(Game &game); 60 explicit PlayScene(Game &game);
@@ -56,18 +68,44 @@ private:
56 Vec2 position; 68 Vec2 position;
57 float phase; 69 float phase;
58 }; 70 };
    71 // 弾:当たり判定の箱と、補間用の前のステップのy / a bullet: its collision box and last step's y (interpolation)
    72 struct Bullet {
    73 Rect box;
    74 float prevY;
    75 Animator anim; // 宇宙人の弾は4コマのクリップ / alien bullets play a 4-frame clip
    76 };
59 int alienFrame(const Alien &a) const; 77 int alienFrame(const Alien &a) const;
    78 Rect shipBox() const;
    79 void fire();
    80 void alienFire(float dt);
    81 void updateShot(float dt);
    82 void updateAlienShots(float dt);
    83 void killShip();
    84 void flare(Vec2 centre, Vec4 color, float life = 0.12f);
60 void drawBackground(); 85 void drawBackground();
61 void drawFormation(); 86 void drawFormation();
    87 void drawBoxes();
62   88  
63 Game &g; 89 Game &g;
64 Formation formation; 90 Formation formation;
    91 std::optional<Shields> shields;
65 float playerX = 0.0f, playerPrevX = 0.0f; // 自機の左端(補間用に前のステップも) / the ship's left edge (+ the 92 float playerX = 0.0f, playerPrevX = 0.0f; // 自機の左端(補間用に前のステップも) / the ship's left edge (+ the
66 // previous step's, for interpolation) 93 // previous step's, for interpolation)
    94 std::optional<Bullet> shot; // 自機の弾は一度に一発(元のゲームと同じ) / one ship bullet at a time
    95 // (as in the original)
    96 std::vector<Bullet> alienShots;
    97 float fireTimer = 1.0f; // 宇宙人が次に撃つまで / until the aliens fire next
    98 float shipDying = 0.0f; // 自機の爆発の残り時間(> 0 の間は隊列も止まる) / ship explosion time
    99 // left (the march stops meanwhile)
    100 Animator shipBoom;
    101 Particles particles;
    102 std::vector<Flare> flares;
67 std::vector<Star> stars; 103 std::vector<Star> stars;
68 float time = 0.0f; 104 float time = 0.0f;
69 int frames[3][2] = {}; // 種類 × 足踏み → シートのコマ / kind × pose → sheet frame 105 int frames[3][2] = {}; // 種類 × 足踏み → シートのコマ / kind × pose → sheet frame
70 int shipFrame = 0; 106 int shipFrame = 0, shotFrame = 0, splatFrame = 0, boomFrames[2] = {};
71 int formationDrawCalls = 0, formationBytes = 0; 107 const AnimationClip *zigClip = nullptr, *boltClip = nullptr, *shipBoomClip = nullptr;
72 int landings = 0; 108 int formationDrawCalls = 0, formationBytes = 0, shieldBytes = 0;
    109 int lives = kStartLives, kills = 0, shotsFired = 0, waves = 1;
    110 bool gameOver = false;
73 }; 111 };

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

前新
@@ -1,9 +1,11 @@
1 // Invaders 第1部(第27章):自機、インスタンシングで描く宇宙人の隊列、行進、操作 1 // Invaders 第2部(第28章):弾、AABBの当たり判定、宇宙人の弾、削れる防壁、爆発
2 // Invaders part 1 (chapter 27): the player's ship, the alien formation drawn with instancing, the march, the controls 2 // Invaders part 2 (chapter 28): bullets, AABB collisions, alien bullets, shields that erode, explosions
3 // 3 //
4 // 操作 / Controls: 4 // 操作 / Controls:
5 // ← → / A D 移動 / move 5 // ← → / A D 移動 / move
    6 // Space / ↑ 撃つ / fire
6 // I 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch 7 // I 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch
    8 // B 当たり判定の箱 / collision boxes
7 // = / - 行進を速く・遅く / march faster / slower 9 // = / - 行進を速く・遅く / march faster / slower
8 // Esc 終了 / quit 10 // Esc 終了 / quit
9 #include "game.hh" 11 #include "game.hh"
@@ -23,19 +25,24 @@ int main() {
23 std::optional<SpriteSheet> sprites = SpriteSheet::loadAtlas("games/invaders/assets/sprites.atlas"); 25 std::optional<SpriteSheet> sprites = SpriteSheet::loadAtlas("games/invaders/assets/sprites.atlas");
24 if (!batch || !ui || !sprites) return 1; 26 if (!batch || !ui || !sprites) return 1;
25 std::optional<FormationRenderer> formationRenderer = FormationRenderer::create(*sprites); 27 std::optional<FormationRenderer> formationRenderer = FormationRenderer::create(*sprites);
26 if (!formationRenderer) return 1; 28 // 防壁の絵はCPUにも要る(削るため):同じPNGをもう一度デコードして切り出す / the shield art is needed on the CPU
    29 // too (to erode it): decode the same PNG again and cut it out
    30 std::optional<Image> shieldArt = loadSpriteImage("games/invaders/assets/sprites.png", *sprites, "shield");
    31 if (!formationRenderer || !shieldArt) return 1;
27   32  
28 // 行動に名前を付ける(キーを変えるならここだけ) / name the actions (to change keys, edit only this) 33 // 行動に名前を付ける(キーを変えるならここだけ) / name the actions (to change keys, edit only this)
29 Input input; 34 Input input;
30 input.attach(window); 35 input.attach(window);
31 input.bind("left", {InputBinding::key(GLFW_KEY_LEFT), InputBinding::key(GLFW_KEY_A)}); 36 input.bind("left", {InputBinding::key(GLFW_KEY_LEFT), InputBinding::key(GLFW_KEY_A)});
32 input.bind("right", {InputBinding::key(GLFW_KEY_RIGHT), InputBinding::key(GLFW_KEY_D)}); 37 input.bind("right", {InputBinding::key(GLFW_KEY_RIGHT), InputBinding::key(GLFW_KEY_D)});
    38 input.bind("fire", {InputBinding::key(GLFW_KEY_SPACE), InputBinding::key(GLFW_KEY_UP), InputBinding::key(GLFW_KEY_W)});
    39 input.bind("confirm", {InputBinding::key(GLFW_KEY_SPACE), InputBinding::key(GLFW_KEY_ENTER)});
33   40  
34 // 固定ステップ:ゲームの動きは1/60秒ごとの更新の中だけ / fixed step: the game only changes in the 1/60 s updates 41 // 固定ステップ:ゲームの動きは1/60秒ごとの更新の中だけ / fixed step: the game only changes in the 1/60 s updates
35 GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); 42 GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5});
36 PixelCanvas canvas(static_cast<int>(kView.x), static_cast<int>(kView.y)); 43 PixelCanvas canvas(static_cast<int>(kView.x), static_cast<int>(kView.y));
37 Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .formationRenderer = *formationRenderer, 44 Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .formationRenderer = *formationRenderer,
38 .ui = *ui, .sprites = *sprites, .world = Camera2D::screen(kView), 45 .ui = *ui, .sprites = *sprites, .shieldArt = *shieldArt, .world = Camera2D::screen(kView),
39 .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}}; 46 .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}};
40   47  
41 SceneManager scenes; 48 SceneManager scenes;

ファイル: a/games/invaders/src/play_scene.cc | b/games/invaders/src/play_scene.cc

前新
@@ -1,22 +1,49 @@
1 // 遊ぶ場面(第27章):自機の操作、隊列の行進、隊列の描き方の比較(インスタンシング ⇔ SpriteBatch) 1 // 遊ぶ場面(第28章):自機の弾と宇宙人の弾、AABBの当たり判定、削れる防壁、爆発
2 // The play scene (chapter 27): steering the ship, the formation's march, two ways to draw the formation (instancing 2 // The play scene (chapter 28): the ship's and the aliens' bullets, AABB collisions, eroding shields, explosions
3 // ⇔ SpriteBatch)    
4 #include "game.hh" 3 #include "game.hh"
5   4  
    5 #include "engine/collision.hh"
    6  
6 #include <algorithm> 7 #include <algorithm>
7 #include <cmath> 8 #include <cmath>
8 #include <cstdio> 9 #include <cstdio>
    10 #include <memory>
    11  
    12 // 宇宙人の色(破片の色) / alien colors (for the debris)
    13 static const Vec4 kAlienColors[3] = {hexColor(0xf06292ff), hexColor(0x5dbce6ff), hexColor(0x9adc48ff)};
    14 constexpr float kFormationWidth = (kColumns - 1) * kColumnSpacing + kAlienSize.x; // 174
    15 constexpr float kShipBoomTime = 1.4f;
    16  
    17 static float formationStartX() { return std::round(0.5f * (kArenaLeft + kArenaRight - kFormationWidth)); }
9   18  
10 PlayScene::PlayScene(Game &game) : g(game) { 19 PlayScene::PlayScene(Game &game) : g(game) {
11 const char *names[3][2] = {{"jelly_0", "jelly_1"}, {"beetle_0", "beetle_1"}, {"blob_0", "blob_1"}}; 20 const char *names[3][2] = {{"jelly_0", "jelly_1"}, {"beetle_0", "beetle_1"}, {"blob_0", "blob_1"}};
12 for (int k = 0; k < 3; ++k) 21 for (int k = 0; k < 3; ++k)
13 for (int p = 0; p < 2; ++p) frames[k][p] = g.sprites.find(names[k][p]); 22 for (int p = 0; p < 2; ++p) frames[k][p] = g.sprites.find(names[k][p]);
14 shipFrame = g.sprites.find("ship"); 23 shipFrame = g.sprites.find("ship");
    24 shotFrame = g.sprites.find("shot");
    25 splatFrame = g.sprites.find("splat");
    26 boomFrames[0] = g.sprites.find("alien_boom_0");
    27 boomFrames[1] = g.sprites.find("alien_boom_1");
    28 zigClip = g.sprites.clip("zig");
    29 boltClip = g.sprites.clip("bolt");
    30 shipBoomClip = g.sprites.clip("ship_boom");
15   31  
16 // 隊列:幅 = 10 × 16 + 14 = 174ピクセル、戦場の真ん中 / the formation: 10 × 16 + 14 = 174 px wide, centered in the arena 32 // 隊列:幅174ピクセル、戦場の真ん中 / the formation: 174 px wide, centered in the arena
17 formation.minX = kArenaLeft + 2.0f; 33 formation.minX = kArenaLeft + 2.0f;
18 formation.maxX = kArenaRight - 2.0f; 34 formation.maxX = kArenaRight - 2.0f;
19 formation.reset(std::round(0.5f * (kArenaLeft + kArenaRight - 174.0f)), kFormationTop); 35 formation.reset(formationStartX(), kFormationTop);
    36  
    37 // 防壁4つを戦場に等間隔で(中心 76, 132, 188, 244) / four shields evenly across the arena (centers 76, 132, 188, 244)
    38 Vec2 shieldPos[kShieldCount];
    39 for (int i = 0; i < kShieldCount; ++i)
    40 shieldPos[i] = {kArenaLeft + (kArenaRight - kArenaLeft) * (static_cast<float>(i) + 0.5f) / kShieldCount - kShieldW / 2,
    41 kShieldY};
    42 shields = Shields::create(g.shieldArt, shieldPos);
    43 if (!shields) { // 防壁が無いと遊べない(理由はcreateが書いた) / no game without shields (create logged why)
    44 fprintf(stderr, "防壁を作れないので終了 / cannot create the shields: quitting\n");
    45 g.window.close(); // 防壁を使う関数は何もしない / the functions that use the shields do nothing
    46 }
20   47  
21 playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f); 48 playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f);
22 // 星:自分の種で作るので、場面を作り直しても同じ空 / stars: made with their own seed, so the sky stays the same when 49 // 星:自分の種で作るので、場面を作り直しても同じ空 / stars: made with their own seed, so the sky stays the same when
@@ -28,11 +55,130 @@ PlayScene::PlayScene(Game &game) : g(game) {
28 } 55 }
29   56  
30 // 一時停止の間は補間しない(第26章) / no interpolation while paused (chapter 26) 57 // 一時停止の間は補間しない(第26章) / no interpolation while paused (chapter 26)
31 void PlayScene::pause() { playerPrevX = playerX; } 58 void PlayScene::pause() {
    59 playerPrevX = playerX;
    60 if (shot) shot->prevY = shot->box.y;
    61 for (Bullet &b : alienShots) b.prevY = b.box.y;
    62 }
32   63  
33 int PlayScene::alienFrame(const Alien &a) const { return frames[static_cast<int>(a.kind)][a.pose]; } 64 int PlayScene::alienFrame(const Alien &a) const {
    65 if (!a.alive) return boomFrames[a.dying > 0.5f * kAlienBoomTime ? 0 : 1];
    66 return frames[static_cast<int>(a.kind)][a.pose];
    67 }
    68  
    69 // 自機の当たり判定:輪郭を除いた船体(13 × 7) / the ship's collision box: the hull without the outline (13 × 7)
    70 Rect PlayScene::shipBox() const { return {playerX + 1.0f, kPlayerY + 1.0f, 13.0f, 7.0f}; }
    71  
    72 void PlayScene::flare(Vec2 centre, Vec4 color, float life) { flares.push_back({splatFrame, centre, life, color}); }
    73  
    74 void PlayScene::fire() {
    75 // 画面に自機の弾がない時だけ撃てる:連打より狙いが大事(元のゲームの決まり)
    76 // Only when no ship bullet is on screen: aiming beats mashing (the original's rule)
    77 if (shot || shipDying > 0.0f || gameOver || !g.input.actionPressed("fire")) return;
    78 float y = kPlayerY - 4.0f;
    79 shot = Bullet{.box = {playerX + 7.0f, y, 1.0f, 5.0f}, .prevY = y, .anim = {}};
    80 ++shotsFired;
    81 }
    82  
    83 void PlayScene::killShip() {
    84 --lives;
    85 shipDying = kShipBoomTime;
    86 shipBoom.play(shipBoomClip, true);
    87 Vec2 c = shipBox().centre();
    88 particles.burst(c, 24, hexColor(0x4fc0a5ff), 20.0f, 70.0f, g.rng);
    89 particles.burst(c, 12, hexColor(0xffa040ff), 30.0f, 90.0f, g.rng);
    90 alienShots.clear(); // 元のゲームと同じく、飛んでいる弾は消える / bullets in flight vanish, as in the original
    91 printf("ship hit: lives %d\n", lives);
    92 }
    93  
    94 void PlayScene::updateShot(float dt) {
    95 if (!shot) return;
    96 shot->prevY = shot->box.y;
    97 shot->box.y -= kShotSpeed * dt;
    98 // 1ステップ4ピクセル、弾の長さ5ピクセル:続けて見れば隙間がないので、すり抜けない(第26章のトンネリング)。
    99 // 宇宙人の弾とも:近づく速さは1ステップ5.25ピクセル < 5 + 7
    100 // 4 px per step with a 5 px bullet: consecutive boxes leave no gap, so nothing is skipped (ch26's tunneling).
    101 // Against alien bullets too: they close in at 5.25 px per step < 5 + 7
    102 const Rect &box = shot->box;
    103 for (size_t i = 0; i < alienShots.size(); ++i)
    104 if (overlaps(box, alienShots[i].box)) {
    105 flare(box.centre(), hexColor(0xfff4d6ff));
    106 alienShots.erase(alienShots.begin() + static_cast<std::ptrdiff_t>(i));
    107 shot.reset();
    108 return;
    109 }
    110 for (Alien &a : formation.aliens)
    111 if (a.alive && overlaps(box, a.box())) {
    112 formation.kill(a);
    113 particles.burst(a.box().centre(), 10, kAlienColors[static_cast<int>(a.kind)], 15.0f, 50.0f, g.rng);
    114 ++kills;
    115 shot.reset();
    116 return;
    117 }
    118 if (std::optional<Vec2> p = shields->hit(box, true)) {
    119 shields->erode(*p, g.rng);
    120 flare(*p, hexColor(0x68c454ff));
    121 shot.reset();
    122 return;
    123 }
    124 if (box.top() < 6.0f) { // 戦場の上の端 / the top of the arena
    125 flare({box.x, 6.0f}, hexColor(0xfff4d6ff));
    126 shot.reset();
    127 }
    128 }
    129  
    130 void PlayScene::alienFire(float dt) {
    131 fireTimer -= dt;
    132 if (fireTimer > 0.0f) return;
    133 fireTimer = g.rng.range(0.5f, 1.1f);
    134 if (static_cast<int>(alienShots.size()) >= kMaxAlienShots) return;
    135 // 撃つ列:3回に1回は自機の真上の列、それ以外は生きている宇宙人をランダムに選んでその列。撃つのはその列の一番下
    136 // The firing column: one time in three the column above the ship, otherwise the column of a random living alien.
    137 // The lowest alien of that column shoots
    138 std::vector<const Alien *> living;
    139 for (const Alien &a : formation.aliens)
    140 if (a.alive) living.push_back(&a);
    141 if (living.empty()) return;
    142 int column = living[static_cast<size_t>(g.rng.range(0, static_cast<int>(living.size()) - 1))]->column;
    143 if (g.rng.chance(1.0f / 3.0f)) {
    144 float shipX = shipBox().centre().x, best = 1e9f;
    145 for (const Alien *a : living)
    146 if (float d = std::fabs(a->box().centre().x - shipX); d < best) best = d, column = a->column;
    147 }
    148 const Alien *shooter = formation.lowestInColumn(column);
    149 if (!shooter) return;
    150 Bullet b{.box = {shooter->position.x + 5.0f, shooter->position.y + kAlienSize.y, 3.0f, 7.0f},
    151 .prevY = shooter->position.y + kAlienSize.y, .anim = {}};
    152 b.anim.play(g.rng.chance(0.5f) ? zigClip : boltClip);
    153 alienShots.push_back(b);
    154 }
    155  
    156 void PlayScene::updateAlienShots(float dt) {
    157 for (size_t i = 0; i < alienShots.size();) {
    158 Bullet &b = alienShots[i];
    159 b.prevY = b.box.y;
    160 b.box.y += kAlienShotSpeed * dt;
    161 b.anim.update(dt);
    162 if (shipDying <= 0.0f && overlaps(b.box, shipBox())) {
    163 killShip(); // 全部の弾を消す / clears every bullet
    164 return;
    165 }
    166 bool gone = false;
    167 if (std::optional<Vec2> p = shields->hit(b.box, false)) {
    168 shields->erode(*p, g.rng);
    169 flare(*p, hexColor(0x68c454ff));
    170 gone = true;
    171 } else if (b.box.bottom() >= kGroundY) {
    172 flare({b.box.centre().x, kGroundY - 2.0f}, hexColor(0xffa040ff));
    173 gone = true;
    174 }
    175 if (gone) alienShots.erase(alienShots.begin() + static_cast<std::ptrdiff_t>(i));
    176 else ++i;
    177 }
    178 }
34   179  
35 void PlayScene::update(float dt) { 180 void PlayScene::update(float dt) {
    181 if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor)
36 time += dt; 182 time += dt;
37 Input &in = g.input; 183 Input &in = g.input;
38 if (in.pressed(GLFW_KEY_ESCAPE)) { 184 if (in.pressed(GLFW_KEY_ESCAPE)) {
@@ -43,25 +189,73 @@ void PlayScene::update(float dt) {
43 g.instanced = !g.instanced; 189 g.instanced = !g.instanced;
44 printf("formation: %s\n", g.instanced ? "instanced" : "SpriteBatch"); 190 printf("formation: %s\n", g.instanced ? "instanced" : "SpriteBatch");
45 } 191 }
46 // 行進の速さを変える(説明用):1秒に動く宇宙人の数を2倍・半分 / change the march speed (for the demo): double or 192 if (in.pressed(GLFW_KEY_B)) g.showBoxes = !g.showBoxes;
47 // halve the number of aliens moved per second    
48 if (in.pressed(GLFW_KEY_EQUAL)) formation.rate = std::min(formation.rate * 2.0f, 960.0f); 193 if (in.pressed(GLFW_KEY_EQUAL)) formation.rate = std::min(formation.rate * 2.0f, 960.0f);
49 if (in.pressed(GLFW_KEY_MINUS)) formation.rate = std::max(formation.rate * 0.5f, 15.0f); 194 if (in.pressed(GLFW_KEY_MINUS)) formation.rate = std::max(formation.rate * 0.5f, 15.0f);
50   195  
51 // 自機:左右の行動の軸で動き、戦場からは出ない / the ship: moves along the left/right action axis, stays inside the 196 // 飾りはいつでも動く / the dressing always moves
52 // arena 197 particles.update(dt);
    198 for (Flare &f : flares) f.life -= dt;
    199 std::erase_if(flares, [](const Flare &f) { return f.life <= 0.0f; });
    200  
    201 if (gameOver) {
    202 formation.updateExplosions(dt);
    203 // やり直し:この場面を新しい場面と入れ替える(全部が最初の状態に戻る) / play again: replace this scene with a
    204 // new one (everything starts from scratch)
    205 if (in.actionPressed("confirm")) scenes().replace(std::make_unique<PlayScene>(g));
    206 return;
    207 }
    208  
53 playerPrevX = playerX; 209 playerPrevX = playerX;
    210 if (shipDying > 0.0f) {
    211 // 自機の爆発中:隊列も宇宙人の弾も止まる(元のゲームと同じ)。終わったら真ん中に戻るか、ゲームオーバー
    212 // While the ship explodes the formation and the alien fire stop (as in the original). Afterwards the ship comes
    213 // back in the middle, or the game is over
    214 shipBoom.update(dt);
    215 formation.updateExplosions(dt);
    216 updateShot(dt);
    217 shipDying -= dt;
    218 if (shipDying <= 0.0f) {
    219 shipDying = 0.0f;
    220 if (lives > 0) {
    221 playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f);
    222 } else {
    223 gameOver = true;
    224 printf("game over: %d kills\n", kills);
    225 }
    226 }
    227 return;
    228 }
    229  
    230 // 自機 / the ship
54 playerX += in.axis("left", "right") * kPlayerSpeed * dt; 231 playerX += in.axis("left", "right") * kPlayerSpeed * dt;
55 playerX = std::clamp(playerX, kArenaLeft + 2.0f, kArenaRight - 2.0f - 15.0f); 232 playerX = std::clamp(playerX, kArenaLeft + 2.0f, kArenaRight - 2.0f - 15.0f);
    233 fire();
56   234  
57 formation.update(dt); 235 formation.update(dt);
58 // 第27章では撃てないので、地面まで下りてきたら上からやり直す(第28章で「侵略された」になる) 236 updateShot(dt);
59 // There is no shooting in chapter 27 yet, so when the formation reaches the ship's row it starts again at the top 237 alienFire(dt);
60 // (chapter 28 turns this into "invaded") 238 updateAlienShots(dt);
61 if (formation.bounds().bottom() > kPlayerY) { 239 if (shipDying > 0.0f) return;
62 ++landings; 240  
63 printf("formation landed after %d passes: reset\n", formation.passes); 241 // 防壁まで下りてきた宇宙人は防壁を食べる / aliens that reach the shields eat them
64 formation.reset(std::round(0.5f * (kArenaLeft + kArenaRight - 174.0f)), kFormationTop); 242 for (const Alien &a : formation.aliens)
    243 if (a.alive && a.box().bottom() > kShieldY) shields->eraseRect(a.box());
    244 // 自機の高さまで来たら侵略された:残りの自機に関係なくゲームオーバー / reaching the ship's row is an invasion:
    245 // game over whatever lives are left
    246 if (formation.alive() > 0 && formation.bounds().bottom() > kPlayerY) {
    247 printf("invaded\n");
    248 lives = 1;
    249 killShip();
    250 return;
    251 }
    252 // 全滅させたら次の隊列(第29章で場面ごと読み直す) / when the formation is wiped out, a new one comes (chapter 29
    253 // reloads the whole scene)
    254 if (formation.cleared()) {
    255 ++waves;
    256 printf("wave cleared: %d kills\n", kills);
    257 formation.reset(formationStartX(), kFormationTop);
    258 fireTimer = 1.0f;
65 } 259 }
66 } 260 }
67   261  
@@ -82,52 +276,79 @@ void PlayScene::drawBackground() {
82 } 276 }
83   277  
84 void PlayScene::drawFormation() { 278 void PlayScene::drawFormation() {
    279 // 生きている宇宙人と、爆発中の宇宙人(爆発のコマ) / living aliens and exploding ones (explosion frames)
85 if (g.instanced) { 280 if (g.instanced) {
86 // インスタンシング:生きている宇宙人を16バイトずつ並べて、一回で描く / instancing: 16 bytes per living alien, one    
87 // draw call    
88 std::vector<AlienInstance> list; 281 std::vector<AlienInstance> list;
89 for (const Alien &a : formation.aliens) 282 for (const Alien &a : formation.aliens)
90 if (a.alive) 283 if (a.alive || a.dying > 0.0f)
91 list.push_back({a.position, static_cast<std::uint32_t>(alienFrame(a)), packRgba8(kWhite)}); 284 list.push_back({a.position, static_cast<std::uint32_t>(alienFrame(a)), packRgba8(kWhite)});
92 g.formationRenderer.draw(g.world.matrix(), list); 285 g.formationRenderer.draw(g.world.matrix(), list);
93 formationDrawCalls = g.formationRenderer.lastDrawCalls(); 286 formationDrawCalls = g.formationRenderer.lastDrawCalls();
94 formationBytes = g.formationRenderer.lastBytes(); 287 formationBytes = g.formationRenderer.lastBytes();
95 } else { 288 } else {
96 // 比べるため:同じ宇宙人をSpriteBatchで(一枚4頂点 × 20バイト) / for comparison: the same aliens through    
97 // SpriteBatch (4 vertices × 20 bytes per sprite)    
98 g.batch.begin(g.world.matrix()); 289 g.batch.begin(g.world.matrix());
99 for (const Alien &a : formation.aliens) 290 for (const Alien &a : formation.aliens)
100 if (a.alive) g.batch.draw(g.sprites.sprite(alienFrame(a), a.position)); 291 if (a.alive || a.dying > 0.0f) g.batch.draw(g.sprites.sprite(alienFrame(a), a.position));
101 g.batch.end(); 292 g.batch.end();
102 formationDrawCalls = g.batch.stats().drawCalls; 293 formationDrawCalls = g.batch.stats().drawCalls;
103 formationBytes = g.batch.stats().sprites * 4 * static_cast<int>(sizeof(SpriteVertex)); 294 formationBytes = g.batch.stats().sprites * 4 * static_cast<int>(sizeof(SpriteVertex));
104 } 295 }
105 } 296 }
106   297  
    298 void PlayScene::drawBoxes() {
    299 // 当たり判定の箱(B):宇宙人 = 赤、自機 = 緑、弾 = 黄、防壁 = 青(防壁はさらにピクセル単位で調べる)
    300 // The collision boxes (B): aliens red, ship green, bullets yellow, shields blue (shields are then tested per pixel)
    301 SpriteBatch &b = g.batch;
    302 for (const Alien &a : formation.aliens)
    303 if (a.alive) b.drawRectOutline(a.box(), hexColor(0xff4040c0));
    304 for (int i = 0; i < kShieldCount; ++i) b.drawRectOutline(shields->bounds(i), hexColor(0x40a0ffc0));
    305 if (shipDying <= 0.0f && !gameOver) b.drawRectOutline(shipBox(), hexColor(0x40ff60ff));
    306 if (shot) b.drawRectOutline(shot->box, hexColor(0xffe040ff));
    307 for (const Bullet &s : alienShots) b.drawRectOutline(s.box, hexColor(0xffe040ff));
    308 }
    309  
107 void PlayScene::draw(float alpha) { 310 void PlayScene::draw(float alpha) {
108 // 奥から:背景(バッチ)→ 隊列(インスタンシングかバッチ)→ 自機(バッチ) / back to front: background (batch) → 311 if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor)
109 // formation (instanced or batch) → ship (batch) 312 // 防壁:変わった所だけGPUへ(描く前に) / shields: send only the changed part to the GPU (before drawing)
    313 shields->upload();
    314 if (shields->lastUploadBytes() > 0) shieldBytes = shields->lastUploadBytes();
    315  
    316 // 奥から:背景と防壁(バッチ)→ 隊列(インスタンシングかバッチ)→ 自機・弾・爆発(バッチ)
    317 // Back to front: background and shields (batch) → formation (instanced or batch) → ship, bullets, explosions (batch)
110 g.batch.begin(g.world.matrix()); 318 g.batch.begin(g.world.matrix());
111 drawBackground(); 319 drawBackground();
    320 shields->draw(g.batch);
112 g.batch.end(); 321 g.batch.end();
113   322  
114 drawFormation(); 323 drawFormation();
115   324  
116 // 宇宙人は飛び飛びに動くので補間しない。自機は滑らかに動くので補間する(第26章) 325 SpriteBatch &b = g.batch;
117 // Aliens move in jumps, so they are not interpolated. The ship moves smoothly, so it is (chapter 26) 326 b.begin(g.world.matrix());
118 float x = std::round(playerPrevX + (playerX - playerPrevX) * alpha); 327 float x = std::round(playerPrevX + (playerX - playerPrevX) * alpha);
119 g.batch.begin(g.world.matrix()); 328 if (shipDying > 0.0f) b.draw(g.sprites.sprite(shipBoom.frame(), {x, kPlayerY}));
120 g.batch.draw(g.sprites.sprite(shipFrame, {x, kPlayerY})); 329 else if (!gameOver) b.draw(g.sprites.sprite(shipFrame, {x, kPlayerY}));
121 g.batch.end(); 330 // 弾は滑らかに動くので補間する / bullets move smoothly, so they are interpolated
    331 if (shot) b.draw(g.sprites.sprite(shotFrame, {shot->box.x, std::round(shot->prevY + (shot->box.y - shot->prevY) * alpha)}));
    332 for (const Bullet &s : alienShots)
    333 b.draw(g.sprites.sprite(s.anim.frame(), {s.box.x, std::round(s.prevY + (s.box.y - s.prevY) * alpha)}));
    334 for (const Flare &f : flares) {
    335 Sprite s = g.sprites.sprite(f.frame, {std::round(f.centre.x), std::round(f.centre.y)}, {0.5f, 0.5f});
    336 s.color = f.color;
    337 b.draw(s);
    338 }
    339 particles.draw(b);
    340 if (g.showBoxes) drawBoxes();
    341 b.end();
122 } 342 }
123   343  
124 void PlayScene::drawUi(float /*alpha*/) { 344 void PlayScene::drawUi(float /*alpha*/) {
    345 if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor)
125 SpriteBatch &b = g.batch; 346 SpriteBatch &b = g.batch;
126 b.begin(g.screen.matrix()); 347 b.begin(g.screen.matrix());
127 TextStyle head = {.color = hexColor(0xf2c14eff), .shadow = hexColor(0x000000ff)}; 348 TextStyle head = {.color = hexColor(0xf2c14eff), .shadow = hexColor(0x000000ff)};
128 TextStyle body = {.color = hexColor(0xd8dcefff), .shadow = hexColor(0x000000ff)}; 349 TextStyle body = {.color = hexColor(0xd8dcefff), .shadow = hexColor(0x000000ff)};
129 char line[64]; 350 char line[64];
130 // 左の板:隊列の描き方と、その値段 / the left panel: how the formation is drawn and what it costs 351 // 左の板:隊列の描き方と、戦いの数字 / the left panel: how the formation is drawn, and the battle numbers
131 float y = 24.0f; 352 float y = 24.0f;
132 auto text = [&](const char *s, const TextStyle &st) { 353 auto text = [&](const char *s, const TextStyle &st) {
133 g.ui.draw(b, s, {14.0f, y}, st); 354 g.ui.draw(b, s, {14.0f, y}, st);
@@ -135,20 +356,27 @@ void PlayScene::drawUi(float /*alpha*/) {
135 }; 356 };
136 text("FORMATION (I)", head); 357 text("FORMATION (I)", head);
137 text(g.instanced ? "instanced" : "SpriteBatch", body); 358 text(g.instanced ? "instanced" : "SpriteBatch", body);
138 snprintf(line, sizeof line, "draw calls %d", formationDrawCalls);    
139 text(line, body);    
140 snprintf(line, sizeof line, "%d B/frame", formationBytes); 359 snprintf(line, sizeof line, "%d B/frame", formationBytes);
141 text(line, body); 360 text(line, body);
142 text(g.instanced ? "(16 B/alien)" : "(80 B/alien)", body);    
143 y += 16.0f;    
144 text("MARCH (= -)", head);    
145 snprintf(line, sizeof line, "%.0f aliens/s", static_cast<double>(formation.rate)); 361 snprintf(line, sizeof line, "%.0f aliens/s", static_cast<double>(formation.rate));
146 text(line, body); 362 text(line, body);
147 snprintf(line, sizeof line, "alive %d", formation.alive()); 363 snprintf(line, sizeof line, "alive %d", formation.alive());
148 text(line, body); 364 text(line, body);
149 snprintf(line, sizeof line, "passes %d", formation.passes); 365 y += 16.0f;
    366 text("BATTLE", head);
    367 snprintf(line, sizeof line, "lives %d", lives);
    368 text(line, body);
    369 snprintf(line, sizeof line, "kills %d", kills);
150 text(line, body); 370 text(line, body);
151 snprintf(line, sizeof line, "landed %d", landings); 371 snprintf(line, sizeof line, "shots %d", shotsFired);
    372 text(line, body);
    373 snprintf(line, sizeof line, "wave %d", waves);
    374 text(line, body);
    375 y += 16.0f;
    376 text("SHIELDS", head);
    377 snprintf(line, sizeof line, "%d px left", shields->pixelsLeft());
    378 text(line, body);
    379 snprintf(line, sizeof line, "upload %d B", shieldBytes);
152 text(line, body); 380 text(line, body);
153   381  
154 // 右の板:操作 / the right panel: controls 382 // 右の板:操作 / the right panel: controls
@@ -160,8 +388,18 @@ void PlayScene::drawUi(float /*alpha*/) {
160 right("CONTROLS", head); 388 right("CONTROLS", head);
161 right("A D / arrows", body); 389 right("A D / arrows", body);
162 right(" move", body); 390 right(" move", body);
    391 right("Space fire", body);
163 right("I formation", body); 392 right("I formation", body);
    393 right("B boxes", body);
164 right("= - march", body); 394 right("= - march", body);
165 right("Esc quit", body); 395 right("Esc quit", body);
    396  
    397 if (gameOver) {
    398 b.drawRect({192.0f, 300.0f, 896.0f, 110.0f}, hexColor(0x0c0a1ad0));
    399 g.ui.draw(b, "GAME OVER", {640.0f, 316.0f},
    400 {.color = hexColor(0xd9474bff), .scale = 3.0f, .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)});
    401 g.ui.draw(b, "Space / Enter: play again", {640.0f, 378.0f},
    402 {.color = hexColor(0xd8dcefff), .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)});
    403 }
166 b.end(); 404 b.end();
167 } 405 }

ファイル: /dev/null | b/games/invaders/src/shields.cc

前新
@@ -0,0 +1,158 @@
    1 #include "shields.hh"
    2  
    3 #include "engine/file_util.hh"
    4  
    5 #include <algorithm>
    6 #include <cmath>
    7 #include <cstdio>
    8  
    9 // 着弾の形(スプライトシートのsplatと同じ形):'W' = 消すピクセル / the impact shape (the same shape as the
    10 // sheet's splat sprite): 'W' = a pixel to clear
    11 static const char *const kSplat[] = {
    12 "W..W.W",
    13 "..WW..",
    14 ".WWWW.",
    15 "WWWWW.",
    16 ".WWWWW",
    17 "WWWWW.",
    18 "..WW..",
    19 "W..W.W",
    20 };
    21 constexpr int kSplatW = 6, kSplatH = 8;
    22  
    23 std::optional<Image> loadSpriteImage(const std::string &pngPath, const SpriteSheet &sheet, const char *name) {
    24 int index = sheet.find(name);
    25 std::optional<std::vector<std::uint8_t>> bytes = readBinaryFile(pngPath);
    26 if (index < 0 || !bytes) {
    27 fprintf(stderr, "%s: スプライト %s がない / no sprite %s\n", pngPath.c_str(), name, name);
    28 return std::nullopt;
    29 }
    30 std::optional<Image> sheetImage = decodeImage(bytes->data(), bytes->size(), false);
    31 if (!sheetImage) return std::nullopt;
    32 Rect r = sheet.pixels(index);
    33 Image out;
    34 out.width = static_cast<int>(r.w);
    35 out.height = static_cast<int>(r.h);
    36 out.rgba.resize(static_cast<size_t>(out.width * out.height * 4));
    37 for (int y = 0; y < out.height; ++y)
    38 for (int x = 0; x < out.width; ++x)
    39 for (int c = 0; c < 4; ++c) {
    40 size_t src = static_cast<size_t>(4 * ((static_cast<int>(r.y) + y) * sheetImage->width + static_cast<int>(r.x) + x) + c);
    41 out.rgba[static_cast<size_t>(4 * (y * out.width + x) + c)] = sheetImage->rgba[src];
    42 }
    43 // 乗算済みアルファにする(loadSpriteTextureが自動でやっていること)。PNGの透明なピクセルには、にじみ止めの色
    44 // (隣の不透明なピクセルの色)が入っているので、そのまま送ると (r, g, b, 0) が加算されて縁が光る
    45 // Premultiply (what loadSpriteTexture does for you). The PNG's transparent pixels carry the nearest opaque color
    46 // against fringes; sent as is, (r, g, b, 0) would be *added* by the premultiplied blend and the edges would glow
    47 for (size_t i = 0; i < out.rgba.size(); i += 4)
    48 for (size_t c = 0; c < 3; ++c) out.rgba[i + c] = static_cast<std::uint8_t>(out.rgba[i + c] * out.rgba[i + 3] / 255);
    49 return out;
    50 }
    51  
    52 std::optional<Shields> Shields::create(const Image &art, const Vec2 (&positions)[kShieldCount]) {
    53 if (art.width != kShieldW || art.height != kShieldH) {
    54 fprintf(stderr, "防壁の絵が %d × %d でない / the shield art is not %d × %d\n", kShieldW, kShieldH, kShieldW, kShieldH);
    55 return std::nullopt;
    56 }
    57 Shields s;
    58 s.pixels.resize(static_cast<size_t>(kTexW * kTexH * 4));
    59 for (int i = 0; i < kShieldCount; ++i) {
    60 s.topLeft[i] = positions[i];
    61 for (int y = 0; y < kShieldH; ++y)
    62 std::copy_n(art.rgba.begin() + 4 * y * kShieldW, 4 * kShieldW,
    63 s.pixels.begin() + 4 * (y * kTexW + i * kShieldW));
    64 }
    65 // 中身は後で書き換えるので、空のストレージを作ってから全体を一度送る / the contents change later, so allocate
    66 // empty storage and send everything once
    67 s.tex = Texture2D(kTexW, kTexH, GL_RGBA8, 1);
    68 s.tex.setFilter(GL_NEAREST, GL_NEAREST);
    69 s.tex.setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
    70 s.tex.upload(s.pixels.data());
    71 return s;
    72 }
    73  
    74 void Shields::clearPixel(int x, int y) {
    75 if (x < 0 || y < 0 || x >= kTexW || y >= kTexH || !solid(x, y)) return;
    76 std::fill_n(pixels.begin() + 4 * (y * kTexW + x), 4, std::uint8_t{0});
    77 dirtyX0 = std::min(dirtyX0, x), dirtyY0 = std::min(dirtyY0, y);
    78 dirtyX1 = std::max(dirtyX1, x + 1), dirtyY1 = std::max(dirtyY1, y + 1);
    79 }
    80  
    81 std::optional<Vec2> Shields::hit(const Rect &box, bool fromBelow) const {
    82 for (int i = 0; i < kShieldCount; ++i) {
    83 Rect s = bounds(i);
    84 // boxが重なるピクセルの範囲(防壁の中の座標) / the pixels the box covers (shield coordinates)
    85 int x0 = std::max(0, static_cast<int>(std::floor(box.left() - s.x)));
    86 int x1 = std::min(kShieldW, static_cast<int>(std::ceil(box.right() - s.x)));
    87 int y0 = std::max(0, static_cast<int>(std::floor(box.top() - s.y)));
    88 int y1 = std::min(kShieldH, static_cast<int>(std::ceil(box.bottom() - s.y)));
    89 if (x0 >= x1 || y0 >= y1) continue;
    90 for (int n = 0; n < y1 - y0; ++n) {
    91 int y = fromBelow ? y1 - 1 - n : y0 + n;
    92 for (int x = x0; x < x1; ++x)
    93 if (solid(i * kShieldW + x, y))
    94 return Vec2{s.x + static_cast<float>(x) + 0.5f, s.y + static_cast<float>(y) + 0.5f};
    95 }
    96 }
    97 return std::nullopt;
    98 }
    99  
    100 void Shields::erode(Vec2 point, Rng &rng) {
    101 bool mirror = rng.chance(0.5f);
    102 for (int i = 0; i < kShieldCount; ++i) {
    103 Rect s = bounds(i);
    104 // 着弾の形の左上(防壁の中の座標) / the impact shape's top left (shield coordinates)
    105 int ox = static_cast<int>(std::floor(point.x - s.x)) - kSplatW / 2;
    106 int oy = static_cast<int>(std::floor(point.y - s.y)) - kSplatH / 2;
    107 if (ox >= kShieldW || oy >= kShieldH || ox + kSplatW <= 0 || oy + kSplatH <= 0) continue;
    108 for (int y = 0; y < kSplatH; ++y)
    109 for (int x = 0; x < kSplatW; ++x) {
    110 int sx = ox + x, sy = oy + y;
    111 char c = kSplat[y][mirror ? kSplatW - 1 - x : x];
    112 if (c == 'W' && sx >= 0 && sx < kShieldW && sy >= 0 && sy < kShieldH) clearPixel(i * kShieldW + sx, sy);
    113 }
    114 }
    115 }
    116  
    117 void Shields::eraseRect(const Rect &box) {
    118 for (int i = 0; i < kShieldCount; ++i) {
    119 Rect s = bounds(i);
    120 int x0 = std::max(0, static_cast<int>(std::floor(box.left() - s.x)));
    121 int x1 = std::min(kShieldW, static_cast<int>(std::ceil(box.right() - s.x)));
    122 int y0 = std::max(0, static_cast<int>(std::floor(box.top() - s.y)));
    123 int y1 = std::min(kShieldH, static_cast<int>(std::ceil(box.bottom() - s.y)));
    124 for (int y = y0; y < y1; ++y)
    125 for (int x = x0; x < x1; ++x) clearPixel(i * kShieldW + x, y);
    126 }
    127 }
    128  
    129 void Shields::upload() {
    130 uploadBytes = 0;
    131 if (dirtyX0 >= dirtyX1 || dirtyY0 >= dirtyY1) return; // 変わっていない / nothing changed
    132 int w = dirtyX1 - dirtyX0, h = dirtyY1 - dirtyY0;
    133 // CPUの配列の一部(四角)を送る:行の長さ(GL_UNPACK_ROW_LENGTH)を配列全体の幅にすると、GLは一行ごとに
    134 // kTexWピクセル先へ進む。ポインターは四角の左上。送ったら0(= 幅と同じ)に戻す
    135 // Send a rectangle out of the CPU array: with GL_UNPACK_ROW_LENGTH = the whole array's width, the GL steps kTexW
    136 // pixels for every row. The pointer is the rectangle's top left. Reset it to 0 (= the width) afterwards
    137 glPixelStorei(GL_UNPACK_ROW_LENGTH, kTexW);
    138 glTextureSubImage2D(tex.id(), 0, dirtyX0, dirtyY0, w, h, GL_RGBA, GL_UNSIGNED_BYTE,
    139 pixels.data() + 4 * (dirtyY0 * kTexW + dirtyX0));
    140 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    141 uploadBytes = w * h * 4;
    142 dirtyX0 = kTexW, dirtyY0 = kTexH, dirtyX1 = 0, dirtyY1 = 0;
    143 }
    144  
    145 void Shields::draw(SpriteBatch &batch, float layer) const {
    146 for (int i = 0; i < kShieldCount; ++i)
    147 batch.draw({.texture = &tex,
    148 .position = topLeft[i],
    149 .size = {kShieldW, kShieldH},
    150 .uv = {static_cast<float>(i) / kShieldCount, 0.0f, 1.0f / kShieldCount, 1.0f},
    151 .layer = layer});
    152 }
    153  
    154 int Shields::pixelsLeft() const {
    155 int n = 0;
    156 for (size_t i = 3; i < pixels.size(); i += 4) n += pixels[i] != 0;
    157 return n;
    158 }

ファイル: /dev/null | b/games/invaders/src/shields.hh

前新
@@ -0,0 +1,64 @@
    1 // 削れる防壁(第28章):ピクセルの絵をCPUに持ち、弾が当たった所を消して、変わった四角だけを
    2 // glTextureSubImage2Dでテクスチャに送り直す
    3 // Shields that erode (chapter 28): the pixels live on the CPU; an impact clears pixels there, and only the changed
    4 // rectangle is sent to the texture again with glTextureSubImage2D
    5 #pragma once
    6  
    7 #include "engine/rect.hh"
    8 #include "engine/rng.hh"
    9 #include "engine/sprite_batch.hh"
    10 #include "engine/sprite_sheet.hh"
    11 #include "engine/texture.hh"
    12  
    13 #include <cstdint>
    14 #include <optional>
    15 #include <string>
    16 #include <vector>
    17  
    18 constexpr int kShieldCount = 4;
    19 constexpr int kShieldW = 22, kShieldH = 16;
    20  
    21 // スプライトシートのPNGをCPUでもう一度デコードして、名前の絵だけを切り出す(RGBA8、上の行から)。
    22 // 透明なピクセルのRGBは0にする(乗算済みアルファ:GPUに送るときに要る)
    23 // Decodes the sprite sheet's PNG again on the CPU and cuts out one named sprite (RGBA8, rows from the top).
    24 // Transparent pixels get RGB 0 (premultiplied alpha: needed when they are sent to the GPU)
    25 std::optional<Image> loadSpriteImage(const std::string &pngPath, const SpriteSheet &sheet, const char *name);
    26  
    27 class Shields {
    28 public:
    29 // 4つの防壁を一枚のテクスチャ(88 × 16)に並べる。topLeft[i] = 画面での防壁iの左上
    30 // Puts the 4 shields side by side in one texture (88 × 16). topLeft[i] = where shield i goes on screen
    31 static std::optional<Shields> create(const Image &art, const Vec2 (&topLeft)[kShieldCount]);
    32  
    33 // boxの中に残っている防壁のピクセルがあるか。あれば、弾の進む向きで最初に当たるピクセル(の中心)
    34 // (下から来る弾 = 一番下、上から来る弾 = 一番上)
    35 // Is any shield pixel left inside box? If so, the pixel a bullet meets first (its center): the lowest for a
    36 // bullet coming from below, the highest for one coming from above
    37 std::optional<Vec2> hit(const Rect &box, bool fromBelow) const;
    38 // 着弾の形(kSplat、6 × 8)でピクセルを消す。左右はランダムに反転 / clears pixels in the impact shape (kSplat,
    39 // 6 × 8), mirrored at random
    40 void erode(Vec2 point, Rng &rng);
    41 // 四角の中を全部消す(防壁まで下りてきた宇宙人) / clears everything inside the box (aliens that reach the shields)
    42 void eraseRect(const Rect &box);
    43  
    44 // 変わった所だけをアップロードする(描く前に一度) / uploads only what changed (once, before drawing)
    45 void upload();
    46 void draw(SpriteBatch &batch, float layer = 0.0f) const;
    47 Rect bounds(int i) const { return {topLeft[i].x, topLeft[i].y, kShieldW, kShieldH}; }
    48 int lastUploadBytes() const { return uploadBytes; }
    49 int pixelsLeft() const;
    50 const Texture2D &texture() const { return tex; }
    51  
    52 private:
    53 static constexpr int kTexW = kShieldW * kShieldCount, kTexH = kShieldH;
    54 Shields() = default;
    55 void clearPixel(int x, int y); // テクスチャのピクセル座標 / texture pixel coordinates
    56 bool solid(int x, int y) const { return pixels[static_cast<size_t>(4 * (y * kTexW + x) + 3)] != 0; }
    57  
    58 std::vector<std::uint8_t> pixels; // kTexW × kTexH × RGBA8(CPUの正本) / the CPU master copy
    59 Texture2D tex;
    60 Vec2 topLeft[kShieldCount];
    61 int dirtyX0 = kTexW, dirtyY0 = kTexH, dirtyX1 = 0, dirtyY1 = 0; // 変わった四角(x1・y1は含まない) / the changed
    62 // rectangle (x1, y1 exclusive)
    63 int uploadBytes = 0;
    64 };


コメント(0)

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