27. Space Invaders Part 1: Player, Aliens and Instancing

Part 6 starts here, and with it the games.
Chapters 25 and 26 built a small engine: sprites, a pixel canvas, text, a fixed-step loop, input, scenes, collision and random numbers.
Now we use it for something real, and the first game is the classic of 1978: Space Invaders.

The game takes three chapters.
This one sets up the game as its own program and builds the parts that move: the player's ship, the formation of 55 aliens, and their famous march, one alien at a time.
The formation is also drawn with instancing, the technique of chapter 19, and next to it the same formation through chapter 25's SpriteBatch, so we can compare the two honestly.
Nobody shoots yet; bullets, collisions and shields are chapter 28, score, scenes and polish chapter 29.

Games are mostly code, so this chapter has a lot of it.
I won't walk through every line; I'll explain the decisions behind it, and the files in the download are complete and commented.

27.1 What we're building

The program is called invaders, and it opens a 1280 × 720 window titled "OpenGL Tutorial - Invaders":

Invaders: a dark arena between two side panels. Five rows of eleven aliens, pink jellies on top, two rows of blue beetles and two rows of green blobs; the right part of the second row is still higher than the left part because the formation is in the middle of a step down. The teal ship stands at the left end of the green ground line. The left panel reads FORMATION instanced, draw calls 1, 880 B per frame, 16 B per alien, MARCH 60 aliens per second, alive 55, passes 11, landed 0; the right panel lists the controls

The clip moves the ship left and right, speeds the march up twice so you can see it reach the edges, step down and turn around, and switches the formation's renderer twice (only the numbers in the left panel change):

The controls:

  • ← → or A, D: move the ship
  • I: draw the formation with instancing or with the SpriteBatch
  • = and −: march faster or slower (doubles or halves the number of aliens moved per second, 15 to 960)
  • Esc: quit

Everything in this chapter is new, and all of it is inside one new folder, games/invaders/:

  • CMakeLists.txt: the invaders executable
  • src/main.cc: the window, loading, input actions, the game loop and the frame
  • src/game.hh: the screen layout constants, the shared Game data and the PlayScene class
  • src/play_scene.cc: the play scene (ship, march, drawing, the side-panel text)
  • src/formation.hh, src/formation.cc: the aliens and the march (no OpenGL)
  • src/formation_renderer.hh, src/formation_renderer.cc: the instanced formation renderer
  • shaders/formation.vert: its vertex shader
  • assets/sprites.png, assets/sprites.atlas: the art of all three parts; assets/LICENSE.txt (the finished files are in the chapter's ZIP and in ch27/ of the assets ZIP)
  • README.md: controls and how to run

Nothing outside games/invaders/ changes: not the engine, not the top-level CMakeLists.txt, not the shared assets/.
That's the rule for every game chapter, and the diff of this chapter contains only new files.

27.2 A game of its own

The folder

Chapter 25 decided that every game is its own executable in its own folder, and chapter 26 ended with the loop in the top-level CMakeLists.txt that finds them:

foreach(name invaders fighter rpg tps)
  if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/games/${name}/CMakeLists.txt")
    add_subdirectory(games/${name})
  endif()
endforeach()

So creating games/invaders/CMakeLists.txt is all it takes to add a program to the build.
Why a separate program and not a mode of game?
Because games grow: invaders will have its own scenes, shaders and art, and so will the fighter, the RPG and the shooter.
In separate folders, each game is small enough to read, the demo of chapters 25 and 26 stays as it was, and a mistake in one game can't break another.
What they share is the engine library and the shared assets/ (fonts, mostly), which a game only reads.

games/invaders/CMakeLists.txt

The whole file:

# Invaders(第27〜29章):エンジンだけを使う一つの実行ファイル。プロジェクトのルートから ./build/games/invaders/invaders
# Invaders (chapters 27-29): one executable that only uses the engine. Run ./build/games/invaders/invaders from the
# project root
add_executable(invaders
  src/main.cc
  src/play_scene.cc
  src/formation.cc
  src/formation_renderer.cc)
target_include_directories(invaders PRIVATE src)
target_link_libraries(invaders PRIVATE engine)
enable_warnings(invaders)
set_working_directory(invaders)

Five commands, each with one job:

  • add_executable(invaders …) creates the target and lists its sources. The paths are relative to this file's folder, so src/main.cc is games/invaders/src/main.cc. Headers don't have to be listed.
  • target_include_directories(invaders PRIVATE src) lets the sources include each other by plain name (#include "game.hh"). PRIVATE, because nothing links invaders.
  • target_link_libraries(invaders PRIVATE engine) is the one line that brings in everything else. As chapter 25 explained, the engine's PUBLIC requirements come with it: the include paths of engine/include, GLAD, GLFW and linalg.hh, and the libraries themselves. The game never names GLFW or GLAD.
  • enable_warnings(invaders) and set_working_directory(invaders) are the two helper functions from the top-level file (chapter 25): /W4 or -Wall -Wextra, and Visual Studio's debugger working directory set to the project root.

The two helpers can be called here because add_subdirectory reads this file after the top-level file defined them.
And set_working_directory uses ${PROJECT_SOURCE_DIR}, the folder of the nearest project() command, which is the project root even though we call it from games/invaders/.

Building

Configure and build as before, from the project root:

cmake -S . -B build
cmake --build build -j8

If you add the folder to a build folder configured in chapter 26, run the first command again: a build reruns CMake only when a CMakeLists.txt it has already read changes, and the if(EXISTS …) that finds the new folder is evaluated only when CMake runs.
To build only the game, name the target: cmake --build build --target invaders.
If you don't need the 3D check program of chapter 25 while working on 2D games, -DBUILD_SCENE3D=OFF on the first command saves its build time.

Where it lands and how to start it

The executable is created in the build folder that matches its CMakeLists.txt:

Platform Executable
Linux, FreeBSD build/games/invaders/invaders
Visual Studio solution build\games\invaders\Debug\invaders.exe (or Release\)
Visual Studio "Open Folder" out\build\x64-Debug\games\invaders\invaders.exe

It must run with the project root as its working directory, like every program since chapter 1, because it loads engine/shaders/…, assets/fonts/… and games/invaders/… by relative paths (chapter 25, section 25.6).
On Linux and FreeBSD:

./build/games/invaders/invaders

Not cd build/games/invaders && ./invaders: started from anywhere else, it can't find a single file and stops at once:

engine/shaders/sprite.vert: 開けない / cannot open (プロジェクトのルートから実行した? / running from the project root?)
engine/shaders/sprite.frag: 開けない / cannot open (プロジェクトのルートから実行した? / running from the project root?)
assets/fonts/mono16.fnt: 読めない / cannot read (プロジェクトのルートから実行した? / running from the project root?)
games/invaders/assets/sprites.atlas: 読めない / cannot read (プロジェクトのルートから実行した? / running from the project root?)

In the Visual Studio solution, invaders is a new project next to game, scene3d, gltf_dump and the libraries.
F5 still starts game, because the top-level file set VS_STARTUP_PROJECT to it; right-click invaders in the Solution Explorer and choose "Set as Startup Project", and F5 starts the game, already in the project root.
In "Open Folder" mode pick invaders.exe in the startup item list, open Debug → Debug and Launch Settings for invaders, and add "currentDir": "${workspaceRoot}" to the new configuration, as chapter 1 did for game.

The folder also has a short README.md with the controls and these commands, for anyone who finds the game without the tutorial.

27.3 The screen

320 × 180, and why the arena is 224 wide

All our pixel-art games use chapter 25's PixelCanvas: a small framebuffer that is drawn, then scaled to the window by a whole number.
For invaders it's 320 × 180, four times smaller than 1280 × 720 in both directions.

The original arcade cabinet had a monitor turned on its side: a portrait picture 224 pixels wide and 256 high.
Our canvas is landscape, so I keep the original's width for the playing field, the middle 224 pixels (x 48 to 272), and use the 48 pixels on each side as side panels.
The width is what matters for the feel of the game: it decides how far the formation can travel before it has to step down, and so how fast it comes down.
The original's pacing comes with its width; a 320 px arena would let the formation wander for three times as long (challenge 2).
The side panels show developer text in this chapter and the next, and the score and lives in chapter 29.

The 320 by 180 canvas at twice its size: two dark side panels 48 pixels wide on the left and right, the 224 pixel arena between them. Dashed orange lines at x 50 and 270 are the march limits. The formation of 5 by 11 aliens starts as a box 174 by 66 pixels from x 73 to 247, its top row at kFormationTop 28. The ship stands at kPlayerY 158 above the green ground line at kGroundY 170

The constants are at the top of game.hh:

// 仮想解像度320 × 180(ウィンドウ1280 × 720で4倍)。真ん中の224ピクセル幅が戦場、左右48ピクセルは脇の板
// Virtual resolution 320 × 180 (× 4 in the 1280 × 720 window). The middle 224 pixels are the arena, 48 pixels on
// each side are side panels
constexpr Vec2 kView = {320.0f, 180.0f};
constexpr float kArenaLeft = 48.0f, kArenaRight = 272.0f;
constexpr float kFormationTop = 28.0f;  // 最初の隊列の一番上 / the first formation's top row
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)

The aliens' own sizes are in formation.hh: each alien sprite is a 14 × 10 cell (12 × 8 of art plus a 1 px outline), columns are 16 px apart and rows 14 px.
That makes the formation 10⋅16+14=174 pixels wide and 4⋅14+10=66 high.
The vertical room is tight on a 180 px canvas: the formation's bottom starts at y 94, and the march ends when it gets below the ship's top at 158 (in chapter 28 that becomes the end of the game).
That's why a step down is 6 px and not 8: with 8 px the 9th step down would already reach the ship, with 6 px it's the 11th.

The colors

The colors follow chapter 25's rule for 2D: sprites and colors are sRGB values in GL_RGBA8, blending happens in sRGB space and GL_FRAMEBUFFER_SRGB stays off, so everything looks exactly as painted.
The canvas is cleared to 0x0c0a1a, the side panels are 0x16132a with a 1 px border of 0x3a3460, and the ground is a green line, 0x68c454.
Forty dim stars twinkle in the arena, each with its own phase.

27.4 The art

The sprites are original: not the arcade bitmaps, but three new aliens in the same spirit, drawn in code by a generator script of mine (built on the same pixel-art helpers as chapter 25's sprites, with the shared dark outline).
The script isn't part of the download; the generated sheet is:

The whole sprite sheet enlarged five times with the name under each sprite: jelly_0 and jelly_1, a pink jelly with eyes and tentacles; beetle_0 and beetle_1, a blue beetle with horns; blob_0 and blob_1, a green blob with big eyes and feet; alien_boom_0 and alien_boom_1; the teal ship and ship_boom_0 and ship_boom_1; a red ufo; shot; zig_0 to zig_3 and bolt_0 to bolt_3, the alien bullets; splat; a green shield; and the logo INVADERS in yellow to red letters

It holds the art of all three parts: explosions, bullets, the shield, the saucer and the logo are already there, so the PNG doesn't change in chapters 28 and 29.
It's 128 × 48 pixels with 24 sprites, with at least 1 px of transparent space around each (chapter 25's rule against bleeding), and it's loaded with chapter 25's SpriteSheet::loadAtlas.
The atlas file starts like this:

# Invaders sprites (chapters 27-29), generated by the author's own script
image sprites.png
sprite jelly_0 1 1 14 10
sprite jelly_1 17 1 14 10
sprite beetle_0 33 1 14 10
sprite beetle_1 49 1 14 10
sprite blob_0 65 1 14 10
sprite blob_1 81 1 14 10

Every alien has two poses, _0 and _1; switching between them is the "walk".
The jellies are the top row, the beetles rows 2 and 3, the blobs rows 4 and 5, as in the original's three kinds.
The ship is 15 × 9.
assets/LICENSE.txt lists the files with the same wording as the shared assets/LICENSE.txt.

27.5 main.cc and the game's shared data

The Game struct

Chapter 26's demo passed a context struct to every scene's constructor, so that the scenes can share the window, the input, the batch and the fonts without globals.
Invaders does the same with Game:

// ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference
struct Game {
  Window &window;
  Input &input;
  GameLoop &loop;
  SpriteBatch &batch;
  FormationRenderer &formationRenderer;
  const Font &ui;               // mono16:画面の解像度の文字 / text at screen resolution
  const SpriteSheet &sprites;   // games/invaders/assets/sprites.atlas
  Camera2D world;               // 320 × 180のキャンバス / the 320 × 180 canvas
  Camera2D screen;              // 1280 × 720のUI / the 1280 × 720 UI
  Viewport uiViewport;
  Rng rng{27};
  bool instanced = true;        // 隊列をインスタンシングで(I) / draw the formation instanced (I)
};

References for everything main owns, values for what belongs to the game (the two cameras, the UI viewport, the gameplay Rng and one setting).
rng is seeded with a constant as chapter 26 asked; this part's logic doesn't use it yet, it's there for the later parts.

main

main loads everything first and gives up with exit code 1 if anything is missing:

int main() {
  Window window;
  if (!window.create(1280, 720, "OpenGL Tutorial - Invaders")) return 1;

  std::optional<SpriteBatch> batch = SpriteBatch::create();
  std::optional<Font> ui = Font::load("assets/fonts/mono16.fnt");
  std::optional<SpriteSheet> sprites = SpriteSheet::loadAtlas("games/invaders/assets/sprites.atlas");
  if (!batch || !ui || !sprites) return 1;
  std::optional<FormationRenderer> formationRenderer = FormationRenderer::create(*sprites);
  if (!formationRenderer) return 1;

Window comes first, as always, so that every GL object dies before the context.
The mono16 font is the shared one from assets/fonts/; the sprite sheet and the formation renderer (section 27.9) are the game's own.

Then the input actions.
Only movement gets names; the demo keys (I, = and −) are read directly where they're used, because nobody will ever want to rebind them:

  // 行動に名前を付ける(キーを変えるならここだけ) / name the actions (to change keys, edit only this)
  Input input;
  input.attach(window);
  input.bind("left", {InputBinding::key(GLFW_KEY_LEFT), InputBinding::key(GLFW_KEY_A)});
  input.bind("right", {InputBinding::key(GLFW_KEY_RIGHT), InputBinding::key(GLFW_KEY_D)});

The loop, the canvas and the Game:

  // 固定ステップ:ゲームの動きは1/60秒ごとの更新の中だけ / fixed step: the game only changes in the 1/60 s updates
  GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5});
  PixelCanvas canvas(static_cast<int>(kView.x), static_cast<int>(kView.y));
  Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .formationRenderer = *formationRenderer,
            .ui = *ui, .sprites = *sprites, .world = Camera2D::screen(kView),
            .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}};

Camera2D::screen(kView) makes a camera whose world is the canvas's pixels (y down, origin top left), and Camera2D::screen({1280, 720}) the same for the UI.
The step is 1/60 s; the march's speed is defined per second (section 27.8), so the step only decides how often the game is updated, not how fast it plays.

Finally the scene manager with one scene, and chapter 26's frame:

  SceneManager scenes;
  scenes.push(std::make_unique<PlayScene>(game));

  loop.run(
      window, input,
      [&](float dt) {
        scenes.update(dt);
        if (scenes.empty()) window.close();
      },
      [&](float alpha) {
        // 1. 世界:320 × 180のキャンバスに描いて4倍で画面へ / 1. the world: into the 320 × 180 canvas, shown × 4
        canvas.begin(hexColor(0x0c0a1aff));
        scenes.draw(alpha);
        canvas.present(window.width(), window.height());
        // 2. UI:1280 × 720の文字 / 2. the UI: text at 1280 × 720
        game.uiViewport = letterbox(window.width(), window.height(), game.screen.viewSize, false);
        game.uiViewport.apply();
        scenes.drawUi(alpha);
        scenes.drawFade(*batch, game.screen.matrix(), game.screen.viewSize);
      });
  return 0;

The update lambda quits when the scene stack is empty, which is how Esc works: the play scene pops itself.
The draw lambda is chapter 26's frame structure unchanged: the world into the canvas, present at a whole-number scale (4 in a 1280 × 720 window), then the text at full resolution in the letterboxed UI viewport, then the scene manager's fade (unused in this chapter).

27.6 The ship

The ship's code is in PlayScene, whose constructor also places the formation and the stars:

PlayScene::PlayScene(Game &game) : g(game) {
  const char *names[3][2] = {{"jelly_0", "jelly_1"}, {"beetle_0", "beetle_1"}, {"blob_0", "blob_1"}};
  for (int k = 0; k < 3; ++k)
    for (int p = 0; p < 2; ++p) frames[k][p] = g.sprites.find(names[k][p]);
  shipFrame = g.sprites.find("ship");

  // 隊列:幅 = 10 × 16 + 14 = 174ピクセル、戦場の真ん中 / the formation: 10 × 16 + 14 = 174 px wide, centered in the arena
  formation.minX = kArenaLeft + 2.0f;
  formation.maxX = kArenaRight - 2.0f;
  formation.reset(std::round(0.5f * (kArenaLeft + kArenaRight - 174.0f)), kFormationTop);

  playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f);
  // 星:自分の種で作るので、場面を作り直しても同じ空 / stars: made with their own seed, so the sky stays the same when
  // the scene is created again
  Rng sky(1978);
  for (int i = 0; i < 40; ++i)
    stars.push_back({{std::round(sky.range(kArenaLeft + 2.0f, kArenaRight - 2.0f)), std::round(sky.range(4.0f, 150.0f))},
                     sky.unit()});
}

The ship starts in the middle, at x 153 (its left edge: the arena's center 160 minus 7, about half of its 15 px).
Every update moves it along the left/right action axis of chapter 26 at 60 px/s, which is exactly 1 px per step, and clamps it to the arena:

  // 自機:左右の行動の軸で動き、戦場からは出ない / the ship: moves along the left/right action axis, stays inside the
  // arena
  playerPrevX = playerX;
  playerX += in.axis("left", "right") * kPlayerSpeed * dt;
  playerX = std::clamp(playerX, kArenaLeft + 2.0f, kArenaRight - 2.0f - 15.0f);

With the 2 px margin on both sides the ship's left edge stays between x 50 and 255.
Holding a key moves it from one wall to the other, 205 px, in about 3.4 s.

The ship moves smoothly, so it's drawn interpolated, exactly as chapter 26 taught: keep the previous position, refresh it at the start of each step, and draw prev + (current − prev) · alpha.
The result is rounded to a whole canvas pixel, because pixel art is drawn at whole pixels (chapter 25), and pause() sets prev = current so that a paused scene doesn't wobble:

// 一時停止の間は補間しない(第26章) / no interpolation while paused (chapter 26)
void PlayScene::pause() { playerPrevX = playerX; }

The aliens, on the other hand, are not interpolated.
They move in jumps of 2 px by design, and a smooth glide between the jumps would be a different game.

27.7 The formation

Data without OpenGL

formation.hh and formation.cc hold the aliens and the march, and they don't include a single GL header.
The game logic never needs to know how the aliens are drawn; we're about to draw them in two different ways from the same data, and chapter 28's collisions will read the same boxes.

// 宇宙人の種類(上の行から):クラゲ、甲虫、丸い奴 / alien kinds (from the top row): jelly, beetle, blob
enum class AlienKind { Jelly = 0, Beetle = 1, Blob = 2 };

struct Alien {
  AlienKind kind = AlienKind::Blob;
  int column = 0, row = 0; // row 0 = 一番上 / the top row
  Vec2 position;           // 左上、整数のピクセル / top left, whole pixels
  int pose = 0;            // 0か1:動くたびに入れ替わる(足踏み) / 0 or 1: flips every time it moves (the walk)
  bool alive = true;
  Rect box() const;        // 当たり判定 = 絵の枠 / the collision box = the sprite cell
};

constexpr int kColumns = 11, kRows = 5;
constexpr Vec2 kAlienSize = {14.0f, 10.0f}; // スプライトの枠 / the sprite cell
constexpr float kColumnSpacing = 16.0f, kRowSpacing = 14.0f;

An Alien knows its kind, its place in the grid, its top-left position in whole pixels, its pose and whether it's alive.
Its collision box is simply its sprite cell; chapter 28 uses it.

class Formation {
public:
  // 全員を生き返らせ、左上の宇宙人の位置を(left, top)にして、右向きに歩き始める
  // Brings everyone back, puts the top-left alien at (left, top) and starts marching right
  void reset(float left, float top);
  // 行進:1秒にrate匹ずつ、次の一匹を動かす。全員が一回ずつ動いたら(一巡)、端に着いていれば次の一巡で下がり、
  // 向きを変える。生き残りが少ないほど一人あたりの順番が早く回ってくる = 自然に速くなる
  // The march: moves the next alien, `rate` aliens per second. When everyone has moved once (a pass) and the
  // formation touches an edge, the next pass moves everyone down, then the direction flips. The fewer aliens are left,
  // the sooner each one's turn comes around = the formation speeds up by itself
  void update(float dt);

  int alive() const;
  Rect bounds() const; // 生きている宇宙人を囲む箱(全滅なら大きさ0) / box around the living aliens (empty if none)

  std::vector<Alien> aliens; // 行進の順番:下の行の左から右へ、それから上の行 / march order: bottom row left to right,
                             // then the row above
  float rate = 60.0f;        // 1秒に動く宇宙人の数 / aliens moved per second
  float stepX = 2.0f, stepY = 6.0f;
  float minX = 0.0f, maxX = 320.0f; // 行進できる範囲 / where the formation may go
  int direction = 1;                // +1 = 右 / right, -1 = 左 / left
  bool dropping = false;            // この一巡は下へ / this pass moves down
  int passes = 0;                   // 終わった一巡の数 / completed passes

private:
  void moveOne();
  void advanceCursor();
  void endPass();
  size_t cursor = 0;   // 次に動く宇宙人 / the alien that moves next
  float budget = 0.0f; // 動かしてよい数(端数を持ち越す) / moves owed (fractions carry over)
};

The march order

reset builds the 55 aliens in march order: the bottom row from left to right, then the row above, up to the top row:

void Formation::reset(float left, float top) {
  aliens.clear();
  // 下の行から:行進は一番下の左端から始まる / bottom row first: the march starts at the bottom left
  for (int row = kRows - 1; row >= 0; --row)
    for (int col = 0; col < kColumns; ++col) {
      AlienKind kind = row == 0 ? AlienKind::Jelly : row <= 2 ? AlienKind::Beetle : AlienKind::Blob;
      aliens.push_back({.kind = kind, .column = col, .row = row,
                        .position = {left + kColumnSpacing * static_cast<float>(col),
                                     top + kRowSpacing * static_cast<float>(row)}});
    }
  direction = 1;
  dropping = false;
  passes = 0;
  cursor = 0;
  budget = 0.0f;
}

The order of the vector is the order in which the aliens take their turns, which is the subject of the next section.
The formation starts at round(12(48+272−174))=73, centered in the arena, with its top row at y 28.

27.8 The march

One alien per update

The aliens of the original don't move together.
The 1978 game moved one alien per video frame: the whole formation took one step only after every alien had taken its own.
That one rule gives the march its look and the game its tension, so we copy it.

A cursor walks through the aliens in march order.
Each move shifts only the alien under the cursor, 2 px sideways (or 6 px down, see below), and flips its pose; then the cursor goes to the next alien:

void Formation::moveOne() {
  // 死んだ宇宙人は飛ばす(順番を待たない) / skip dead aliens (they do not take a turn)
  while (!aliens[cursor].alive) advanceCursor();
  Alien &a = aliens[cursor];
  if (dropping) a.position.y += stepY;
  else a.position.x += stepX * static_cast<float>(direction);
  a.pose ^= 1;
  advanceCursor();
}

void Formation::advanceCursor() {
  if (++cursor < aliens.size()) return;
  cursor = 0;
  endPass();
}

When the cursor wraps around, every living alien has moved once: that's a pass.
Dead aliens are skipped without spending a turn (they can't die before chapter 28, but the code is ready).

The formation in the middle of a pass, enlarged four times. Each alien carries its number in march order: 0 to 10 in the bottom row, 11 to 21 above it, up to 44 to 54 in the top row. Aliens 0 to 26 are bright, in their second pose and 2 pixels further right; alien 27, in the middle row, is framed as the cursor that moves next; 27 to 54 are dim and still in the old place. Below, the sequence of passes: 11 passes right, drop, 22 passes left, drop, 22 passes right and so on, and after 241 passes the formation lands and is reset

Edges, drops and turning around

The formation only looks at the edges at the end of a pass, when all aliens are back in line:

// 一巡が終わった:下がり終えたなら向きを変え、端に届きそうなら次の一巡は下へ
// A pass is complete: after a drop, turn around; if the next step would cross an edge, the next pass drops
void Formation::endPass() {
  ++passes;
  if (dropping) {
    dropping = false;
    direction = -direction;
    return;
  }
  Rect b = bounds();
  if ((direction > 0 && b.right() + stepX > maxX) || (direction < 0 && b.left() - stepX < minX)) dropping = true;
}

If the next sideways step would take the formation past minX or maxX, the next pass is a drop pass: every alien moves 6 px down instead of sideways, one at a time like any other move.
After the drop pass the direction flips.
The edge test uses bounds(), the box around the living aliens, so that a formation whose outer columns have been shot keeps marching to the wall instead of turning around early (chapter 28):

Rect Formation::bounds() const {
  bool any = false;
  float l = 0, t = 0, r = 0, b = 0;
  for (const Alien &a : aliens) {
    if (!a.alive) continue;
    Rect box = a.box();
    if (!any) {
      l = box.left(), t = box.top(), r = box.right(), b = box.bottom();
      any = true;
    }
    l = std::min(l, box.left()), t = std::min(t, box.top());
    r = std::max(r, box.right()), b = std::max(b, box.bottom());
  }
  return {l, t, r - l, b - t};
}

The numbers, worked out from the code (and checked by running it):

  • The formation starts at x 73 to 247. Moving right, it stops when 247+2k+2>270, so after k=11 passes, at 95 to 269.
  • Then it drops and walks left until 95−2m−2<50: m=22 passes, to 51 to 225. Every later sweep is 22 passes (44 px) too. Because it started on an odd x, it never touches x 50 or 270 exactly; it turns 1 px before each limit.
  • The bottom starts at 94 and each drop adds 6. After 10 drops it's at 154; the first alien of the 11th drop pass takes it to 160, below the ship's top at 158. That's after 11+1+9⋅23+22=241 passes.

Since nobody can shoot yet, PlayScene restarts the formation at the top when that happens and prints a line:

  formation.update(dt);
  // 第27章では撃てないので、地面まで下りてきたら上からやり直す(第28章で「侵略された」になる)
  // There is no shooting in chapter 27 yet, so when the formation reaches the ship's row it starts again at the top
  // (chapter 28 turns this into "invaded")
  if (formation.bounds().bottom() > kPlayerY) {
    ++landings;
    printf("formation landed after %d passes: reset\n", formation.passes);
    formation.reset(std::round(0.5f * (kArenaLeft + kArenaRight - 174.0f)), kFormationTop);
  }

At the default 60 aliens per second a pass of 55 aliens takes 55/60≈0.92 s, a sweep of 22 passes about 20 s, and the landing comes after 13 256 updates, 220.9 s or about three minutes and 41 seconds.
At 960 aliens per second (press = four times) it takes 13.8 s.

The ripple

Because one alien moves at a time, the formation is never quite in line during a pass: the aliens that have already moved are 2 px ahead of those that haven't.
The front between them travels from the bottom left to the top right, again and again: the ripple.
During a drop pass the same front makes the formation look like it's folding down row by row.
Here are two real frames, enlarged four times (each canvas pixel is 4 × 4):

Two crops of the running game enlarged four times. Top, drop pass at frame 646: the three bottom rows and the left half of the second row are already lower, the right half of the second row and the top row are still in the old place. Bottom, marching left at frame 676: the bottom rows are a little further left than the rows above, the cursor is in row 4

Speed-up for free

The original's most famous feature, the formation getting faster as it gets smaller, falls out of the same rule.
A pass is "every living alien moves once", so it takes n/rate seconds for n living aliens.
Each pass moves the formation 2 px, so its sideways speed is 2⋅rate/n pixels per second:

Living aliens One pass at 60 aliens/s Formation speed
55 0.92 s 2.2 px/s
30 0.50 s 4 px/s
10 0.17 s 12 px/s
1 1/60 s 120 px/s

The last alien moves on every update and races across the arena at 120 px/s.
We don't write a single line for this; it starts to show in chapter 28, as soon as aliens can die, and chapter 29 adds a wave-by-wave speed-up on top.

A rate, not a frame count

The original's speed was tied to its video frames.
Ours is defined per second: rate is the number of aliens moved per second, 60 by default, and every update spends a budget:

void Formation::update(float dt) {
  if (alive() == 0) return;
  // 1ステップ(1/60秒)にrate/60匹。予算は浮動小数点数の和なので少し許す(60 × (1/60)は丁度1.0fだが、
  // 1/50秒のステップでは5回目の更新の予算が2ではなく1.99999964になる)
  // rate/60 aliens per 1/60 s step. The budget is a float sum, so allow a little (60 × (1/60) is exactly 1.0f,
  // but with a 1/50 s step the fifth update's budget is 1.99999964, not 2)
  budget += rate * dt;
  while (budget > 0.999f) {
    budget -= 1.0f;
    moveOne();
  }
}

At the default step of 1/60 s, rate * dt is exactly 1, and one alien moves per update.
At 120 two move per update, at 15 one moves every fourth update, and if someone changed the loop's step to 1/30 s, two would move per update at the same pace as before.
The game's speed doesn't depend on the step length, which the original's did.

Why 0.999f and not 1.0f?
Because the budget is a sum of floats, and sums of floats are rarely exact.
With the default numbers it happens to be exact: static_cast<float>(1.0 / 60.0) is 0.016666668, and 60 times that rounds to exactly 1.0f.
But take a step of 1/50 s: each update adds 1.2, so every fifth update should move two aliens, and on the fifth update the budget should be exactly 2.
It's 1.99999964.
With budget >= 1.0f the first alien moves, 0.99999964 is left, and the second alien waits for the next update.
The tolerance makes the comparison robust against those last bits; it's the same problem chapter 26's GameLoop solved with its snapTolerance.
The comment above the loop records both facts: exact at 1/60 s, 1.99999964 at 1/50 s.

27.9 Instancing the formation

Why instancing here

The outline of this course promised "an alien formation drawn with instancing", and there's a catch I want to be upfront about.
Chapter 19 introduced instancing to save draw calls: thousands of rocks in one call instead of thousands of calls.
But chapter 25's SpriteBatch already draws all 55 aliens, which use one texture, in one draw call.
Instancing can't save anything there.

So the formation gets a real instanced draw as a teaching contrast: the same aliens, the same image, drawn the other way, switchable at run time with I.
It shows instancing in 2D with an integer attribute and a uniform table, and it lets us measure what each approach costs instead of guessing.
Section 27.10 has the verdict.

The idea of instancing is in chapter 19 (sections 19.9 to 19.10): one mesh, an instance count, and attributes that advance once per instance thanks to a binding divisor.
Here the "mesh" is four corners of a unit square, and every instance is an alien.

The instance data: 16 bytes per alien

// 一匹分のインスタンスデータ(16バイト)。attribute location 9・10・8に繋ぐ
// One alien's instance data (16 bytes), connected to attribute locations 9, 10 and 8
struct AlienInstance {
  Vec2 position;       // 左上(ワールド座標) / top left (world space)     → location 9, vec2
  std::uint32_t frame; // スプライトシートのコマ番号 / sprite sheet frame → location 10, uint (整数のまま / stays an integer)
  std::uint32_t color; // RGBA8(Rが下位バイト) / RGBA8 (R lowest byte)  → location 8, vec4 (0..1に正規化 / normalized)
};
static_assert(sizeof(AlienInstance) == 16);

// 色(0〜1、sRGBの値)→ RGBA8。SpriteBatchと同じ丸め方(同じ絵になるように) / a 0..1 color → RGBA8, rounded like
// SpriteBatch does (so both paths give the same image)
std::uint32_t packRgba8(Vec4 color);

Where to draw (the top-left corner), which frame of the sheet, and a color: 16 bytes, checked by the static_assert.
The color is packed into one uint32_t with red in the lowest byte, read by the GPU as four normalized bytes, and packed with the same rounding as SpriteBatch packs its vertex colors, so both paths produce identical bytes:

std::uint32_t packRgba8(Vec4 c) {
  auto byte = [](float v) { return static_cast<std::uint32_t>(std::lround(std::clamp(v, 0.0f, 1.0f) * 255.0f)); };
  return byte(c.x) | (byte(c.y) << 8) | (byte(c.z) << 16) | (byte(c.w) << 24);
}

Compare that with the batch, whose SpriteVertex is a position, a UV and a color, 20 bytes, four of them per sprite: 80 bytes per alien.
The batch also computes all four corners on the CPU, with origin, rotation and flipping, and sorts the sprites before uploading.
The instanced path sends only what differs between aliens and lets the vertex shader build the corners.

The vertex shader

The whole of games/invaders/shaders/formation.vert:

#version 460 core
// 隊列のインスタンシング(第27章):頂点は四隅(0〜1)だけ。どこに・どのコマで・何色で描くかはインスタンスごとの属性
// Formation instancing (chapter 27): the vertices are only the corners (0..1). Where, which frame and which color
// come from per-instance attributes
// フラグメントシェーダーはSpriteBatchと同じ engine/shaders/sprite.frag(vUv・vColorを受け取る)
// The fragment shader is SpriteBatch's engine/shaders/sprite.frag (it takes vUv and vColor)

layout(location = 0) in vec2 aCorner;         // 頂点ごと:(0,0) (1,0) (0,1) (1,1) / per vertex
layout(location = 8) in vec4 aInstanceColor;  // インスタンスごと:RGBA8 → 0〜1(sRGB、乗算前) / per instance
layout(location = 9) in vec2 aInstanceOffset; // インスタンスごと:左上(ワールド座標) / per instance: top left
layout(location = 10) in uint aInstanceFrame; // インスタンスごと:コマ番号(整数の属性) / per instance: frame (integer)

uniform mat4 uViewProjection;
// スプライトシートの各コマ:UVの四角 (x, y, w, h) と大きさ(ピクセル) / every sheet frame: UV rect and size in pixels
uniform vec4 uFrameUv[32];
uniform vec2 uFrameSize[32];

out vec2 vUv;
out vec4 vColor;

void main() {
  vec4 uv = uFrameUv[aInstanceFrame];
  vUv = uv.xy + aCorner * uv.zw;
  vColor = vec4(aInstanceColor.rgb * aInstanceColor.a, aInstanceColor.a); // 乗算済みに / premultiplied
  vec2 world = aInstanceOffset + aCorner * uFrameSize[aInstanceFrame];
  gl_Position = uViewProjection * vec4(world, 0.0, 1.0);
}

aCorner is one of (0, 0), (1, 0), (0, 1), (1, 1) and is the same for every alien.
The frame number picks this frame's rectangle in the sheet (uFrameUv: x, y, width, height in UV units) and its size in pixels (uFrameSize).
The corner then interpolates across both: the world position is the offset plus the corner times the size, the UV is the rectangle's corner plus the corner times its size.
In y-down world space, (0, 0) is the top left of the sprite, and since our sprite textures are never flipped, image row 0 is v = 0: the top left of the image too.

Left: the unit square with v0 at 0,0 top left, v1 at 1,0 top right, v2 at 0,1 bottom left and v3 at 1,1 bottom right, x to the right and y down; triangle 0 is v0 v1 v2, triangle 1 is v2 v1 v3. Right: the same four corners on the jelly_0 frame, 14 by 10 pixels, with world = offset + corner × size and uv = uv.xy + corner × uv.zw

Four corners make a quad with GL_TRIANGLE_STRIP (chapter 4's primitive types): each new vertex forms a triangle with the two before it, so v0 v1 v2 and then v1 v2 v3, which OpenGL turns into v2 v1 v3 to keep the winding consistent.
No index buffer is needed.
Culling is off for 2D anyway, so the winding wouldn't matter here.

The last line of main and the premultiplication are copied from the engine's sprite.vert, and that's no accident: the fragment shader is the engine's engine/shaders/sprite.frag, unchanged.
A program links any vertex shader with any fragment shader whose inputs it provides, and sprite.frag only reads vUv and vColor.
Same texture lookup, same premultiplied tint, same blending: that's why the two paths can give the same pixels.

A frame table in uniform arrays

The shader needs the UV rectangle and size of every frame.
They don't change, so create writes them once, for all 24 frames of the sheet:

std::optional<FormationRenderer> FormationRenderer::create(const SpriteSheet &sheet, int capacity) {
  if (sheet.count() > kMaxFrames) {
    fprintf(stderr, "FormationRenderer: コマが多すぎる / too many frames (%d > %d)\n", sheet.count(), kMaxFrames);
    return std::nullopt;
  }
  FormationRenderer r;
  r.shader = Shader::load("games/invaders/shaders/formation.vert", "engine/shaders/sprite.frag");
  if (!r.shader) return std::nullopt;
  r.texture = &sheet.texture();
  r.capacity = capacity;

  // コマの表:配列のユニフォームは要素0の場所に、まとめて何個でも送れる(glProgramUniform4fvのcount)
  // The frame table: a uniform array is set in one call at the location of element 0 (the count of
  // glProgramUniform4fv)
  std::vector<Vec4> uvs;
  std::vector<Vec2> sizes;
  for (int i = 0; i < sheet.count(); ++i) {
    Rect uv = sheet.uv(i);
    uvs.push_back({uv.x, uv.y, uv.w, uv.h});
    sizes.push_back(sheet.size(i));
  }
  GLuint program = r.shader->id();
  glProgramUniform4fv(program, glGetUniformLocation(program, "uFrameUv"), sheet.count(), &uvs[0].x);
  glProgramUniform2fv(program, glGetUniformLocation(program, "uFrameSize"), sheet.count(), &sizes[0].x);

Shader::set from chapter 5 sets one value; for an array we call the DSA function directly.
glProgramUniform4fv(program, location, count, value) writes count vec4s starting at location:

  • program: the program object (Shader::id()).
  • location: the location of the array's first element. glGetUniformLocation(program, "uFrameUv") returns exactly that, the same as asking for "uFrameUv[0]"; the elements after it follow at consecutive locations.
  • count: how many elements to write, here 24. Writing past the array's end (more than 32) is not an error; the extra values are ignored.
  • value: a pointer to count × 4 floats. std::vector<Vec4> stores them back to back, so &uvs[0].x is the start.

glProgramUniform2fv is the same for the vec2 sizes.
The arrays have room for kMaxFrames = 32 frames, and create refuses a sheet with more.
They use 32 vec4 plus 32 vec2, a small part of the 1024 uniform components every OpenGL 4.6 driver must give a vertex shader.
The alternative would be to put UVs and size into every instance, 24 bytes more per alien; a frame number of 4 bytes and a table on the GPU is the cheaper deal.

The VAO: two bindings

Next the two buffers and the vertex array:

  // 頂点(バインディング0):四角形の四隅。GL_TRIANGLE_STRIPなので4つで三角形2枚
  // The vertices (binding 0): the quad's corners. With GL_TRIANGLE_STRIP four of them make two triangles
  const Vec2 corners[4] = {{0, 0}, {1, 0}, {0, 1}, {1, 1}};
  r.corners = Buffer(corners, sizeof corners);
  // インスタンス(バインディング1):毎フレーム書き換える / the instances (binding 1): rewritten every frame
  r.instances = Buffer(nullptr, static_cast<GLsizeiptr>(capacity) * static_cast<GLsizeiptr>(sizeof(AlienInstance)),
                       GL_DYNAMIC_STORAGE_BIT);

  glCreateVertexArrays(1, &r.vao);
  glVertexArrayVertexBuffer(r.vao, 0, r.corners.id(), 0, sizeof(Vec2));
  glEnableVertexArrayAttrib(r.vao, 0);
  glVertexArrayAttribFormat(r.vao, 0, 2, GL_FLOAT, GL_FALSE, 0);
  glVertexArrayAttribBinding(r.vao, 0, 0);

  glVertexArrayVertexBuffer(r.vao, 1, r.instances.id(), 0, sizeof(AlienInstance));
  // divisor 1:バインディング1は頂点ごとではなく、インスタンスごとに一つ進む(第19章と同じ)
  // divisor 1: binding 1 advances once per instance instead of once per vertex (as in chapter 19)
  glVertexArrayBindingDivisor(r.vao, 1, 1);
  glEnableVertexArrayAttrib(r.vao, 9);
  glVertexArrayAttribFormat(r.vao, 9, 2, GL_FLOAT, GL_FALSE, offsetof(AlienInstance, position));
  glVertexArrayAttribBinding(r.vao, 9, 1);
  // 整数の属性はglVertexArrayAttribIFormat(Iが付く)。Formatのほうだとfloatに変換されてしまい、`in uint`では読めない
  // Integer attributes need glVertexArrayAttribIFormat (with the I). The plain Format converts to float, which an
  // `in uint` cannot read
  glEnableVertexArrayAttrib(r.vao, 10);
  glVertexArrayAttribIFormat(r.vao, 10, 1, GL_UNSIGNED_INT, offsetof(AlienInstance, frame));
  glVertexArrayAttribBinding(r.vao, 10, 1);
  glEnableVertexArrayAttrib(r.vao, 8);
  glVertexArrayAttribFormat(r.vao, 8, 4, GL_UNSIGNED_BYTE, GL_TRUE, offsetof(AlienInstance, color));
  glVertexArrayAttribBinding(r.vao, 8, 1);
  return r;

Binding 0 holds the four corners with a stride of 8 bytes and the default divisor 0: it advances per vertex.
Binding 1 holds the instances with a stride of 16, and glVertexArrayBindingDivisor(r.vao, 1, 1) makes it advance once per instance, exactly as in chapter 19.
All three instance attributes are connected to binding 1, so they all advance together.

The two buffers of the instanced draw. Top, binding 0: four corners v0 to v3, stride 8, divisor 0, at location 0. Middle: the vertex shader runs four times per instance, v0 to v3 with gl_InstanceID 0, then 1, up to 54, each group reading the same four corners. Bottom, binding 1: instance 0 split into position at bytes 0 to 7, frame at 8 to 11 and color at 12 to 15, then instance 1, 2 up to 54, stride 16, divisor 1. Location 9 vec2 is set with glVertexArrayAttribFormat and GL_FLOAT, location 10 uint with glVertexArrayAttribIFormat and GL_UNSIGNED_INT, location 8 vec4 with GL_UNSIGNED_BYTE normalized. The call is glDrawArraysInstanced with GL_TRIANGLE_STRIP, 0, 4, 55: 880 bytes per frame against 4400 for the SpriteBatch

The locations follow the plan from chapter 19: 0 to 3 for vertex data, 4 to 7 for an instance matrix (unused here), 8 for the instance color, and 9 and up for anything else.
AlienInstance puts the position at 9 and the frame at 10.

The corner buffer is created with flags 0, immutable: it never changes.
The instance buffer has GL_DYNAMIC_STORAGE_BIT and room for capacity = 64 aliens, 1024 bytes, because it's rewritten every frame with glNamedBufferSubData (through Buffer::update, chapter 19).

Integer attributes need the I

The frame number is an integer, and the shader declares it in uint.
Vertex attributes come in three classes, and each has its own format function:

  • glVertexArrayAttribFormat(vaobj, attribindex, size, type, normalized, relativeoffset): the values arrive in the shader as floats (float, vec2 … vec4). Integer types are converted: either to their value (normalized = GL_FALSE, 7 becomes 7.0) or into 0 to 1 (GL_TRUE, 255 becomes 1.0). That's what the color uses: four GL_UNSIGNED_BYTE, normalized.
  • glVertexArrayAttribIFormat(vaobj, attribindex, size, type, relativeoffset): the values stay integers (int, uint, ivec, uvec). There's no normalized parameter, and type must be an integer type (GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_INT, GL_UNSIGNED_INT).
  • glVertexArrayAttribLFormat: 64-bit double attributes (double, dvec), with type GL_DOUBLE. Rare; just so you know it exists.

The parameters are the ones you know from chapter 3: the VAO, the attribute location, the number of components (1 to 4), the type of the data in the buffer, and the byte offset inside one element.

Pitfall: if you set up an integer attribute with the plain glVertexArrayAttribFormat, the buffer's 0, 1, 2 … are converted to 0.0, 1.0, 2.0 … and handed to a shader variable that expects an integer. The result is undefined, and in my test (Mesa) the shader indexed the frame table with garbage: the whole formation silently disappeared, with no GL error, no debug message and no shader error. The mismatch between the format class and the shader's input type isn't checked at draw time. If integers come out wrong, look for the missing I first.

Drawing

The draw function uploads the living aliens and draws them in one call:

void FormationRenderer::draw(const Mat4 &viewProjection, std::span<const AlienInstance> list) {
  const GLsizei count = static_cast<GLsizei>(std::min(list.size(), static_cast<size_t>(capacity)));
  bytes = count * static_cast<int>(sizeof(AlienInstance));
  drawCalls = count > 0 ? 1 : 0;
  if (count == 0) return;
  instances.update(list.data(), bytes);

  // SpriteBatchと同じ2Dの状態:深度なし、カリングなし、乗算済みアルファ / the same 2D state as SpriteBatch: no depth,
  // no culling, premultiplied alpha
  glDisable(GL_DEPTH_TEST);
  glDisable(GL_CULL_FACE);
  glEnable(GL_BLEND);
  glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
  shader->set("uViewProjection", viewProjection);
  shader->use();
  texture->bind(0);
  glBindVertexArray(vao);
  // 4頂点 × count個のインスタンス。gl_InstanceIDが0〜count-1、属性9・10・8はその番号の要素
  // 4 vertices × count instances. gl_InstanceID runs 0..count-1 and attributes 9, 10, 8 read that element
  glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, count);
  glBindVertexArray(0);
}

It sets the same state SpriteBatch::end() leaves behind (chapter 25): no depth test, no culling, premultiplied alpha blending.
The sprite sheet goes to unit 0, where sprite.frag expects uTexture.

glDrawArraysInstanced(mode, first, count, instancecount) is chapter 19's call without indices:

  • mode: GL_TRIANGLE_STRIP, two triangles from four vertices.
  • first: the first vertex to use, 0.
  • count: vertices per instance, 4.
  • instancecount: how many aliens, 55 here. The vertex shader runs for vertices 0 to 3 of instance 0, then of instance 1, and so on, 4⋅55=220 times in all.

The scene builds the list every frame from the formation:

void PlayScene::drawFormation() {
  if (g.instanced) {
    // インスタンシング:生きている宇宙人を16バイトずつ並べて、一回で描く / instancing: 16 bytes per living alien, one
    // draw call
    std::vector<AlienInstance> list;
    for (const Alien &a : formation.aliens)
      if (a.alive)
        list.push_back({a.position, static_cast<std::uint32_t>(alienFrame(a)), packRgba8(kWhite)});
    g.formationRenderer.draw(g.world.matrix(), list);
    formationDrawCalls = g.formationRenderer.lastDrawCalls();
    formationBytes = g.formationRenderer.lastBytes();
  } else {
    // 比べるため:同じ宇宙人をSpriteBatchで(一枚4頂点 × 20バイト) / for comparison: the same aliens through
    // SpriteBatch (4 vertices × 20 bytes per sprite)
    g.batch.begin(g.world.matrix());
    for (const Alien &a : formation.aliens)
      if (a.alive) g.batch.draw(g.sprites.sprite(alienFrame(a), a.position));
    g.batch.end();
    formationDrawCalls = g.batch.stats().drawCalls;
    formationBytes = g.batch.stats().sprites * 4 * static_cast<int>(sizeof(SpriteVertex));
  }
}

The else branch is the comparison: the same aliens through SpriteBatch, one Sprite each from SpriteSheet::sprite.
Both branches report their draw calls and bytes to the HUD.

27.10 Instancing or SpriteBatch?

Press I, and the left panel changes from one column to the other; the arena doesn't change at all:

The left panel and the upper part of the formation in both modes, at their real size. Left, instanced: glDrawArraysInstanced, 55 times 16 bytes; the panel reads instanced, draw calls 1, 880 B per frame, 16 B per alien. Right, SpriteBatch: 55 sprites times 4 vertices times 20 bytes; the panel reads SpriteBatch, draw calls 1, 4400 B per frame, 80 B per alien. The aliens look the same

Instanced SpriteBatch
Draw calls for the formation 1 1
Bytes uploaded per frame 55⋅16=880 55⋅4⋅20=4400
Corners computed by the vertex shader the CPU
Image identical identical

The images are pixel for pixel the same: the arena of the same frame in both modes, compared with a script, has no differing pixel at all.
And for 55 aliens neither cost is measurable; 4400 bytes per frame is nothing for any GPU or bus.

So when does instancing pay off?

  • When there are thousands. Chapter 19's asteroid ring had 4000 rocks of 162 vertices each; the batch approach would compute and upload every one of those vertices every frame. For 10 000 aliens the batch would compute 40 000 corners on the CPU and upload 800 000 bytes per frame (and, with its default capacity of 8192 sprites, need a second draw call), while instancing uploads 160 000 bytes in one call and lets the GPU do the rest.
  • When the data can stay on the GPU. Our instance buffer is rewritten every frame, but it doesn't have to be: only one alien moves per update, so updating its 16 bytes would be enough (challenge 5). A SpriteBatch can't do that, because it rebuilds every quad from scratch. Particles simulated by a compute shader are the extreme case: the CPU never touches the instances at all.

And what does it cost? Flexibility.
The instanced formation can only use one texture, has no rotation, origin or flipping, and can't be sorted into the batch's layers: whatever is drawn between the background and the ship has to be drawn in its own pass, at a fixed place in the frame.
The batch can mix any sprite with any other, which is why everything else in the game goes through it.
That's the usual trade in real engines too: generic batching for the many different things, instancing for the many identical things.

27.11 One frame of the play scene

The update

The whole update, in order: quit, the demo keys (I, = and −), the ship, the march and the landing check.

void PlayScene::update(float dt) {
  time += dt;
  Input &in = g.input;
  if (in.pressed(GLFW_KEY_ESCAPE)) {
    scenes().pop(); // スタックが空になる → main が終わらせる / the stack becomes empty → main quits
    return;
  }
  if (in.pressed(GLFW_KEY_I)) {
    g.instanced = !g.instanced;
    printf("formation: %s\n", g.instanced ? "instanced" : "SpriteBatch");
  }
  // 行進の速さを変える(説明用):1秒に動く宇宙人の数を2倍・半分 / change the march speed (for the demo): double or
  // halve the number of aliens moved per second
  if (in.pressed(GLFW_KEY_EQUAL)) formation.rate = std::min(formation.rate * 2.0f, 960.0f);
  if (in.pressed(GLFW_KEY_MINUS)) formation.rate = std::max(formation.rate * 0.5f, 15.0f);

The rate is clamped to 15 to 960 aliens per second: four presses of = take it from 60 to 960, two presses of − to 15.
The ship and the formation follow (shown above).
All of it runs only in update, with the fixed dt, so every run with the same input is identical, which chapter 26's scripted screenshots and clips rely on.

Three passes

Drawing goes back to front in three separate passes, because the instanced formation can't be sorted into the batch:

void PlayScene::draw(float alpha) {
  // 奥から:背景(バッチ)→ 隊列(インスタンシングかバッチ)→ 自機(バッチ) / back to front: background (batch) →
  // formation (instanced or batch) → ship (batch)
  g.batch.begin(g.world.matrix());
  drawBackground();
  g.batch.end();

  drawFormation();

  // 宇宙人は飛び飛びに動くので補間しない。自機は滑らかに動くので補間する(第26章)
  // Aliens move in jumps, so they are not interpolated. The ship moves smoothly, so it is (chapter 26)
  float x = std::round(playerPrevX + (playerX - playerPrevX) * alpha);
  g.batch.begin(g.world.matrix());
  g.batch.draw(g.sprites.sprite(shipFrame, {x, kPlayerY}));
  g.batch.end();
}

The background pass draws the side panels, their borders, the stars and the ground, all as drawRects with the batch's white texture:

void PlayScene::drawBackground() {
  SpriteBatch &b = g.batch;
  // 脇の板と枠 / the side panels and their borders
  b.drawRect({0.0f, 0.0f, kArenaLeft, kView.y}, hexColor(0x16132aff));
  b.drawRect({kArenaRight, 0.0f, kView.x - kArenaRight, kView.y}, hexColor(0x16132aff));
  b.drawRect({kArenaLeft - 1.0f, 0.0f, 1.0f, kView.y}, hexColor(0x3a3460ff));
  b.drawRect({kArenaRight, 0.0f, 1.0f, kView.y}, hexColor(0x3a3460ff));
  // 瞬く星 / twinkling stars
  for (const Star &s : stars) {
    float t = 0.5f + 0.5f * std::sin(2.0f * time + 6.283f * s.phase);
    b.drawRect({s.position.x, s.position.y, 1.0f, 1.0f}, {0.62f, 0.64f, 0.8f, 0.25f + 0.5f * t});
  }
  // 地面 / the ground
  b.drawRect({kArenaLeft, kGroundY, kArenaRight - kArenaLeft, 1.0f}, hexColor(0x68c454ff));
}

In the SpriteBatch mode the frame has the same three passes; only the middle one uses the batch instead of the formation renderer.
The ship is a single sprite in its own batch.

The side panels

drawUi writes the HUD of the left panel and the controls of the right panel with mono16 at screen resolution, in the UI pass, not in the canvas: at 320 × 180 there would be no room for readable text.
Each panel is 48 canvas pixels, 192 window pixels wide, enough for about 17 characters of mono16.
Chapter 29 replaces the developer text with the score and the lives.

27.12 Running it

Start the game from the project root:

./build/games/invaders/invaders

On a desktop GPU the first line names your driver; then nothing is printed until something happens.
Pressing I twice, = four times, and then waiting gives:

formation: SpriteBatch
formation: instanced
formation landed after 241 passes: reset

At 960 aliens per second the landing comes 13.8 s after the start; at the default 60 it takes three minutes and 41 seconds, a long time to watch a formation without shooting it.
Esc quits with exit code 0.
If you get the four "cannot open" lines of section 27.2, you started it from the wrong folder.

27.13 Platform notes

  • Windows (Visual Studio): invaders is a separate project, and F5 starts whatever is the startup project: right-click invaders → "Set as Startup Project". Starting invaders.exe by double-clicking it in Explorer doesn't work, because its working directory would be build\games\invaders\Debug. Our sources are UTF-8 without a byte order mark and contain Japanese comments; the project's CMake passes /utf-8 to MSVC (chapter 1), so MSVC reads them correctly (the game's on-screen text is ASCII anyway, so nothing on screen depends on it here).
  • Windows, "Open Folder": the binary is under out\build\x64-Debug\games\invaders\, and the working directory comes from launch.vs.json; every program needs its own currentDir entry (section 27.2).
  • Linux, FreeBSD: run from the project root, in a terminal or from a script that changes to it first. A desktop launcher (a .desktop file) can set the working directory with its Path= key; without it, the game starts in your home folder and finds nothing.
  • FreeBSD: nothing else differs from Linux. cmake --build calls whichever build tool CMake generated for, so the commands are the same, and cmake --build build --target invaders builds only the game.
  • All: GLFW names keys by their position on a US keyboard (chapter 26). GLFW_KEY_EQUAL is the key left of Backspace on a US keyboard; on a Japanese JIS keyboard the key in that position is labeled ^, and GLFW_KEY_MINUS is the key labeled −. The movement keys are named actions, so changing them is one line in main.cc.

27.14 How real games do it

  • The original: the 1978 arcade game ran on an Intel 8080 and drew into a 1-bit framebuffer of a monitor turned on its side. Moving one alien per frame was what the hardware could afford; the ripple and the speed-up are consequences of that, and both became part of the game's character. Our version keeps the rule but measures it in aliens per second.
  • Instancing in engines: Unity draws instanced meshes with Graphics.RenderMeshInstanced or materials with "Enable GPU Instancing", Godot has MultiMesh (and MultiMeshInstance2D for 2D), Unreal has the Instanced Static Mesh component and its hierarchical variant for foliage. They're used for grass, trees, crowds, debris and particles: many copies of one thing.
  • 2D in engines: sprites are batched automatically (Unity's 2D renderer and SRP Batcher, Godot's canvas renderer batch items that share a texture and material). Instancing is rarely needed for ordinary 2D games; it shows up in bullet-hell games with thousands of identical bullets, and in GPU particle systems where the instance data never leaves the GPU.
  • Separating logic and rendering: keeping Formation free of GL, with the renderer reading its data, is the usual structure: the simulation is testable without a window, and the renderer can change (as we did) without touching the rules. Engines with entity systems take it further, with rendering systems that read components the game logic writes.

27.15 Summary

  • A game is its own program: games/invaders/ with a five-command CMakeLists.txt (add_executable, its src include directory, target_link_libraries(invaders PRIVATE engine), enable_warnings, set_working_directory), picked up by the top-level foreach. It lands in build/games/invaders/invaders (VS: build\games\invaders\Debug\invaders.exe) and runs from the project root.
  • The screen: a 320 × 180 canvas at 4×, a 224 px arena (the original's width, which keeps its pacing) and two 48 px side panels for text drawn in the UI pass.
  • Logic without GL: Formation holds 55 Aliens in march order, bottom left to top right, with whole-pixel positions and collision boxes.
  • The march: one alien moves per turn, a pass is every living alien once, edges are checked at the end of a pass, a drop pass moves everyone 6 px down and then the direction flips. Sweeps are 22 passes; the formation lands after 241 passes. The ripple and the speed-up (2⋅rate/n px/s) come for free.
  • A rate budget: rate aliens per second, spent per update with a 0.999 tolerance against float sums, independent of the step length.
  • Instancing in 2D: a 4-corner GL_TRIANGLE_STRIP at binding 0, 16-byte AlienInstances at binding 1 with divisor 1, glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, 55), a frame table in uniform arrays set once with glProgramUniform4fv and a count, and the engine's sprite.frag reused unchanged.
  • Integer attributes need glVertexArrayAttribIFormat; the plain Format converts to float and an in uint reads garbage, silently.
  • Instancing vs SpriteBatch: both 1 draw call here, 880 vs 4400 B per frame, identical images. Instancing pays off with thousands of identical objects or data that stays on the GPU; its price is flexibility (one texture, no rotation, no layer mixing).

27.16 Challenges

  1. ★ Make the formation step down faster: in formation.hh set stepY to 8, and in game.hh set kFormationTop to 40. At 960 aliens per second (= four times) stdout should say formation landed after 149 passes: reset after about 8.6 s, instead of 241 passes and 13.8 s. With stepY = 4 and the original top of 28, it should take 379 passes, about 1.6 times as many as the default.
  2. ★ Use the whole canvas as the arena: set kArenaLeft to 0 and kArenaRight to 320. The first sweep should now take 35 passes and every later one 70 instead of 22, and the formation should land only after 745 passes: about 11 minutes and 23 seconds at 60 aliens per second, about 43 s at 960. The side-panel text now floats over the playing field. That's the pacing the 224 px arena protects.
  3. ★ Color the rows: instead of packRgba8(kWhite), pass a color per row (for example white for row 0, a pale yellow for the blobs), and give the SpriteBatch branch the same color through Sprite::color. Pressing I should still change nothing in the arena, and the bytes per frame should stay 880 and 4400.
  4. ★★ Halve the step and double the rate: in the PlayScene constructor set formation.stepX = 1 and formation.rate = 120. The formation should move at the same average speed with a finer, faster ripple, and the poses should flip twice as often. The first drop should start after about 10.5 s instead of 10.1 s (the sweeps are 23 and 46 passes now, and the formation gets 1 px closer to maxX), and stdout should report landed after 493 passes.
  5. ★★ Keep the instances on the GPU: give FormationRenderer a function that writes one alien's AlienInstance at its index (instances.update(&inst, 16, index * 16)), write all 55 once after reset, and after every move write only the alien that moved (the march order is the vector's order, so the index is known). The image should be identical in both modes, and the bytes uploaded should drop from 880 per frame to 16 per update at the default rate (one alien moves per update). The SpriteBatch can't follow you here, because it rebuilds every quad.
  6. ★★ Replace the instance attributes with vertex pulling: declare layout(std430, binding = 0) readonly buffer Aliens { AlienGpu aliens[]; }; with struct AlienGpu { vec2 position; uint frame; uint color; }; in formation.vert, read aliens[gl_InstanceID], unpack the color with unpackUnorm4x8, and bind the instance buffer with bindBase(GL_SHADER_STORAGE_BUFFER, 0) instead of attaching it to binding 1. The image should be identical, and the VAO needs no divisor and no attributes 8 to 10. Check that the std430 layout of AlienGpu is 16 bytes, like AlienInstance.
  7. ★★★ Make the aliens "breathe" in the vertex shader: add uniform float uTime; to formation.vert, set it every frame, and add sin(uTime * 3.0 + float(gl_InstanceID)) pixels to the y of the world position. The aliens should bob individually with no CPU cost, but only in the instanced mode, and Alien::box() no longer matches what you see: chapter 28's bullets would hit and miss the wrong pixels. Think about where such an effect belongs and how the game logic could know about it.

Download the diff

Download the project (ZIP)

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

前新
@@ -0,0 +1,12 @@
    1 # Invaders(第27〜29章):エンジンだけを使う一つの実行ファイル。プロジェクトのルートから ./build/games/invaders/invaders
    2 # Invaders (chapters 27-29): one executable that only uses the engine. Run ./build/games/invaders/invaders from the
    3 # project root
    4 add_executable(invaders
    5 src/main.cc
    6 src/play_scene.cc
    7 src/formation.cc
    8 src/formation_renderer.cc)
    9 target_include_directories(invaders PRIVATE src)
    10 target_link_libraries(invaders PRIVATE engine)
    11 enable_warnings(invaders)
    12 set_working_directory(invaders)

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

前新
@@ -0,0 +1,26 @@
    1 # Invaders(第27〜29章 / chapters 27-29)
    2  
    3 エンジン(`engine`)だけを使うスペースインベーダー風のゲーム。 / A Space Invaders style game that uses only the engine.
    4  
    5 ```sh
    6 cmake --build build -j8
    7 ./build/games/invaders/invaders # プロジェクトのルートから / from the project root
    8 ```
    9 Visual Studio: `build\games\invaders\Debug\invaders.exe`(作業ディレクトリはルートに設定済み / the working directory
    10 is already the project root)。
    11  
    12 ## 操作 / Controls
    13 | キー / Key | |
    14 |---|---|
    15 | ← → / A D | 移動 / move |
    16 | I | 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch |
    17 | = / - | 行進を速く・遅く / march faster / slower |
    18 | Esc | 終了 / quit |
    19  
    20 ## ファイル / Files
    21 * `src/main.cc` ウィンドウ、読み込み、行動、ゲームループ / window, loading, actions, game loop
    22 * `src/game.hh` 共有データ・画面の寸法・シーン / shared data, layout, scenes
    23 * `src/play_scene.cc` 遊ぶ場面 / the play scene
    24 * `src/formation.hh/.cc` 隊列と行進(GLなし) / the formation and its march (no GL)
    25 * `src/formation_renderer.hh/.cc`, `shaders/formation.vert` インスタンシングで隊列を描く / instanced formation drawing
    26 * `assets/` 絵(作者の自作スクリプトで生成。スクリプトはダウンロードに含まれない) / art (generated by the author's own script, not part of the download)

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

前新
@@ -0,0 +1,6 @@
    1 games/invaders/assets/ のファイルはこのチュートリアルのために作者が自作したもの(作者のPythonのスクリプトで生成。スクリプトはこのプロジェクトには含まれない)。自由に使ってよい。
    2 The files in games/invaders/assets/ were made for this tutorial by the author (generated with the author's own Python scripts, which are not part of this project). Free to use for any purpose.
    3  
    4 sprites.png/.atlas 宇宙人3種(各2コマ)・爆発・自機・円盤・弾・着弾・防壁・ロゴ / three aliens (2 poses each),
    5 explosions, the ship, the saucer, bullets, an impact, a shield, the logo
    6 (chapter 27)

ファイル: /dev/null | b/games/invaders/assets/sprites.atlas

前新
@@ -0,0 +1,30 @@
    1 # Invaders sprites (chapters 27-29), generated by the author's own script
    2 image sprites.png
    3 sprite jelly_0 1 1 14 10
    4 sprite jelly_1 17 1 14 10
    5 sprite beetle_0 33 1 14 10
    6 sprite beetle_1 49 1 14 10
    7 sprite blob_0 65 1 14 10
    8 sprite blob_1 81 1 14 10
    9 sprite alien_boom_0 97 1 14 10
    10 sprite alien_boom_1 113 1 14 10
    11 sprite ship 1 13 15 9
    12 sprite ship_boom_0 18 13 15 9
    13 sprite ship_boom_1 35 13 15 9
    14 sprite ufo 52 13 18 8
    15 sprite shot 72 13 1 5
    16 sprite zig_0 75 13 3 7
    17 sprite zig_1 80 13 3 7
    18 sprite zig_2 85 13 3 7
    19 sprite zig_3 90 13 3 7
    20 sprite bolt_0 95 13 3 7
    21 sprite bolt_1 100 13 3 7
    22 sprite bolt_2 105 13 3 7
    23 sprite bolt_3 110 13 3 7
    24 sprite splat 115 13 6 8
    25 sprite shield 1 24 22 16
    26 sprite logo 25 24 64 11
    27 clip alien_boom 8 once alien_boom_0 alien_boom_1
    28 clip ship_boom 8 loop ship_boom_0 ship_boom_1
    29 clip zig 12 loop zig_0 zig_1 zig_2 zig_3
    30 clip bolt 12 loop bolt_0 bolt_1 bolt_2 bolt_3

ファイル: /dev/null | b/games/invaders/assets/sprites.png

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

ファイル: /dev/null | b/games/invaders/shaders/formation.vert

前新
@@ -0,0 +1,27 @@
    1 #version 460 core
    2 // 隊列のインスタンシング(第27章):頂点は四隅(0〜1)だけ。どこに・どのコマで・何色で描くかはインスタンスごとの属性
    3 // Formation instancing (chapter 27): the vertices are only the corners (0..1). Where, which frame and which color
    4 // come from per-instance attributes
    5 // フラグメントシェーダーはSpriteBatchと同じ engine/shaders/sprite.frag(vUv・vColorを受け取る)
    6 // The fragment shader is SpriteBatch's engine/shaders/sprite.frag (it takes vUv and vColor)
    7  
    8 layout(location = 0) in vec2 aCorner; // 頂点ごと:(0,0) (1,0) (0,1) (1,1) / per vertex
    9 layout(location = 8) in vec4 aInstanceColor; // インスタンスごと:RGBA8 → 0〜1(sRGB、乗算前) / per instance
    10 layout(location = 9) in vec2 aInstanceOffset; // インスタンスごと:左上(ワールド座標) / per instance: top left
    11 layout(location = 10) in uint aInstanceFrame; // インスタンスごと:コマ番号(整数の属性) / per instance: frame (integer)
    12  
    13 uniform mat4 uViewProjection;
    14 // スプライトシートの各コマ:UVの四角 (x, y, w, h) と大きさ(ピクセル) / every sheet frame: UV rect and size in pixels
    15 uniform vec4 uFrameUv[32];
    16 uniform vec2 uFrameSize[32];
    17  
    18 out vec2 vUv;
    19 out vec4 vColor;
    20  
    21 void main() {
    22 vec4 uv = uFrameUv[aInstanceFrame];
    23 vUv = uv.xy + aCorner * uv.zw;
    24 vColor = vec4(aInstanceColor.rgb * aInstanceColor.a, aInstanceColor.a); // 乗算済みに / premultiplied
    25 vec2 world = aInstanceOffset + aCorner * uFrameSize[aInstanceFrame];
    26 gl_Position = uViewProjection * vec4(world, 0.0, 1.0);
    27 }

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

前新
@@ -0,0 +1,84 @@
    1 #include "formation.hh"
    2  
    3 #include <algorithm>
    4  
    5 Rect Alien::box() const { return {position.x, position.y, kAlienSize.x, kAlienSize.y}; }
    6  
    7 void Formation::reset(float left, float top) {
    8 aliens.clear();
    9 // 下の行から:行進は一番下の左端から始まる / bottom row first: the march starts at the bottom left
    10 for (int row = kRows - 1; row >= 0; --row)
    11 for (int col = 0; col < kColumns; ++col) {
    12 AlienKind kind = row == 0 ? AlienKind::Jelly : row <= 2 ? AlienKind::Beetle : AlienKind::Blob;
    13 aliens.push_back({.kind = kind, .column = col, .row = row,
    14 .position = {left + kColumnSpacing * static_cast<float>(col),
    15 top + kRowSpacing * static_cast<float>(row)}});
    16 }
    17 direction = 1;
    18 dropping = false;
    19 passes = 0;
    20 cursor = 0;
    21 budget = 0.0f;
    22 }
    23  
    24 int Formation::alive() const {
    25 return static_cast<int>(std::count_if(aliens.begin(), aliens.end(), [](const Alien &a) { return a.alive; }));
    26 }
    27  
    28 Rect Formation::bounds() const {
    29 bool any = false;
    30 float l = 0, t = 0, r = 0, b = 0;
    31 for (const Alien &a : aliens) {
    32 if (!a.alive) continue;
    33 Rect box = a.box();
    34 if (!any) {
    35 l = box.left(), t = box.top(), r = box.right(), b = box.bottom();
    36 any = true;
    37 }
    38 l = std::min(l, box.left()), t = std::min(t, box.top());
    39 r = std::max(r, box.right()), b = std::max(b, box.bottom());
    40 }
    41 return {l, t, r - l, b - t};
    42 }
    43  
    44 void Formation::update(float dt) {
    45 if (alive() == 0) return;
    46 // 1ステップ(1/60秒)にrate/60匹。予算は浮動小数点数の和なので少し許す(60 × (1/60)は丁度1.0fだが、
    47 // 1/50秒のステップでは5回目の更新の予算が2ではなく1.99999964になる)
    48 // rate/60 aliens per 1/60 s step. The budget is a float sum, so allow a little (60 × (1/60) is exactly 1.0f,
    49 // but with a 1/50 s step the fifth update's budget is 1.99999964, not 2)
    50 budget += rate * dt;
    51 while (budget > 0.999f) {
    52 budget -= 1.0f;
    53 moveOne();
    54 }
    55 }
    56  
    57 void Formation::moveOne() {
    58 // 死んだ宇宙人は飛ばす(順番を待たない) / skip dead aliens (they do not take a turn)
    59 while (!aliens[cursor].alive) advanceCursor();
    60 Alien &a = aliens[cursor];
    61 if (dropping) a.position.y += stepY;
    62 else a.position.x += stepX * static_cast<float>(direction);
    63 a.pose ^= 1;
    64 advanceCursor();
    65 }
    66  
    67 void Formation::advanceCursor() {
    68 if (++cursor < aliens.size()) return;
    69 cursor = 0;
    70 endPass();
    71 }
    72  
    73 // 一巡が終わった:下がり終えたなら向きを変え、端に届きそうなら次の一巡は下へ
    74 // A pass is complete: after a drop, turn around; if the next step would cross an edge, the next pass drops
    75 void Formation::endPass() {
    76 ++passes;
    77 if (dropping) {
    78 dropping = false;
    79 direction = -direction;
    80 return;
    81 }
    82 Rect b = bounds();
    83 if ((direction > 0 && b.right() + stepX > maxX) || (direction < 0 && b.left() - stepX < minX)) dropping = true;
    84 }

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

前新
@@ -0,0 +1,56 @@
    1 // 宇宙人の隊列(第27章):11列 × 5行。行進は「一度に一匹」:更新ごとに次の一匹だけが動く(GLは使わない)
    2 // The alien formation (chapter 27): 11 columns × 5 rows. The march moves "one alien at a time": each move shifts only
    3 // the next alien (no GL in here)
    4 #pragma once
    5  
    6 #include "engine/rect.hh"
    7  
    8 #include <vector>
    9  
    10 // 宇宙人の種類(上の行から):クラゲ、甲虫、丸い奴 / alien kinds (from the top row): jelly, beetle, blob
    11 enum class AlienKind { Jelly = 0, Beetle = 1, Blob = 2 };
    12  
    13 struct Alien {
    14 AlienKind kind = AlienKind::Blob;
    15 int column = 0, row = 0; // row 0 = 一番上 / the top row
    16 Vec2 position; // 左上、整数のピクセル / top left, whole pixels
    17 int pose = 0; // 0か1:動くたびに入れ替わる(足踏み) / 0 or 1: flips every time it moves (the walk)
    18 bool alive = true;
    19 Rect box() const; // 当たり判定 = 絵の枠 / the collision box = the sprite cell
    20 };
    21  
    22 constexpr int kColumns = 11, kRows = 5;
    23 constexpr Vec2 kAlienSize = {14.0f, 10.0f}; // スプライトの枠 / the sprite cell
    24 constexpr float kColumnSpacing = 16.0f, kRowSpacing = 14.0f;
    25  
    26 class Formation {
    27 public:
    28 // 全員を生き返らせ、左上の宇宙人の位置を(left, top)にして、右向きに歩き始める
    29 // Brings everyone back, puts the top-left alien at (left, top) and starts marching right
    30 void reset(float left, float top);
    31 // 行進:1秒にrate匹ずつ、次の一匹を動かす。全員が一回ずつ動いたら(一巡)、端に着いていれば次の一巡で下がり、
    32 // 向きを変える。生き残りが少ないほど一人あたりの順番が早く回ってくる = 自然に速くなる
    33 // The march: moves the next alien, `rate` aliens per second. When everyone has moved once (a pass) and the
    34 // formation touches an edge, the next pass moves everyone down, then the direction flips. The fewer aliens are left,
    35 // the sooner each one's turn comes around = the formation speeds up by itself
    36 void update(float dt);
    37  
    38 int alive() const;
    39 Rect bounds() const; // 生きている宇宙人を囲む箱(全滅なら大きさ0) / box around the living aliens (empty if none)
    40  
    41 std::vector<Alien> aliens; // 行進の順番:下の行の左から右へ、それから上の行 / march order: bottom row left to right,
    42 // then the row above
    43 float rate = 60.0f; // 1秒に動く宇宙人の数 / aliens moved per second
    44 float stepX = 2.0f, stepY = 6.0f;
    45 float minX = 0.0f, maxX = 320.0f; // 行進できる範囲 / where the formation may go
    46 int direction = 1; // +1 = 右 / right, -1 = 左 / left
    47 bool dropping = false; // この一巡は下へ / this pass moves down
    48 int passes = 0; // 終わった一巡の数 / completed passes
    49  
    50 private:
    51 void moveOne();
    52 void advanceCursor();
    53 void endPass();
    54 size_t cursor = 0; // 次に動く宇宙人 / the alien that moves next
    55 float budget = 0.0f; // 動かしてよい数(端数を持ち越す) / moves owed (fractions carry over)
    56 };

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

前新
@@ -0,0 +1,118 @@
    1 #include "formation_renderer.hh"
    2  
    3 #include <algorithm>
    4 #include <cmath>
    5 #include <cstddef>
    6 #include <cstdio>
    7 #include <utility>
    8 #include <vector>
    9  
    10 std::uint32_t packRgba8(Vec4 c) {
    11 auto byte = [](float v) { return static_cast<std::uint32_t>(std::lround(std::clamp(v, 0.0f, 1.0f) * 255.0f)); };
    12 return byte(c.x) | (byte(c.y) << 8) | (byte(c.z) << 16) | (byte(c.w) << 24);
    13 }
    14  
    15 std::optional<FormationRenderer> FormationRenderer::create(const SpriteSheet &sheet, int capacity) {
    16 if (sheet.count() > kMaxFrames) {
    17 fprintf(stderr, "FormationRenderer: コマが多すぎる / too many frames (%d > %d)\n", sheet.count(), kMaxFrames);
    18 return std::nullopt;
    19 }
    20 FormationRenderer r;
    21 r.shader = Shader::load("games/invaders/shaders/formation.vert", "engine/shaders/sprite.frag");
    22 if (!r.shader) return std::nullopt;
    23 r.texture = &sheet.texture();
    24 r.capacity = capacity;
    25  
    26 // コマの表:配列のユニフォームは要素0の場所に、まとめて何個でも送れる(glProgramUniform4fvのcount)
    27 // The frame table: a uniform array is set in one call at the location of element 0 (the count of
    28 // glProgramUniform4fv)
    29 std::vector<Vec4> uvs;
    30 std::vector<Vec2> sizes;
    31 for (int i = 0; i < sheet.count(); ++i) {
    32 Rect uv = sheet.uv(i);
    33 uvs.push_back({uv.x, uv.y, uv.w, uv.h});
    34 sizes.push_back(sheet.size(i));
    35 }
    36 GLuint program = r.shader->id();
    37 glProgramUniform4fv(program, glGetUniformLocation(program, "uFrameUv"), sheet.count(), &uvs[0].x);
    38 glProgramUniform2fv(program, glGetUniformLocation(program, "uFrameSize"), sheet.count(), &sizes[0].x);
    39  
    40 // 頂点(バインディング0):四角形の四隅。GL_TRIANGLE_STRIPなので4つで三角形2枚
    41 // The vertices (binding 0): the quad's corners. With GL_TRIANGLE_STRIP four of them make two triangles
    42 const Vec2 corners[4] = {{0, 0}, {1, 0}, {0, 1}, {1, 1}};
    43 r.corners = Buffer(corners, sizeof corners);
    44 // インスタンス(バインディング1):毎フレーム書き換える / the instances (binding 1): rewritten every frame
    45 r.instances = Buffer(nullptr, static_cast<GLsizeiptr>(capacity) * static_cast<GLsizeiptr>(sizeof(AlienInstance)),
    46 GL_DYNAMIC_STORAGE_BIT);
    47  
    48 glCreateVertexArrays(1, &r.vao);
    49 glVertexArrayVertexBuffer(r.vao, 0, r.corners.id(), 0, sizeof(Vec2));
    50 glEnableVertexArrayAttrib(r.vao, 0);
    51 glVertexArrayAttribFormat(r.vao, 0, 2, GL_FLOAT, GL_FALSE, 0);
    52 glVertexArrayAttribBinding(r.vao, 0, 0);
    53  
    54 glVertexArrayVertexBuffer(r.vao, 1, r.instances.id(), 0, sizeof(AlienInstance));
    55 // divisor 1:バインディング1は頂点ごとではなく、インスタンスごとに一つ進む(第19章と同じ)
    56 // divisor 1: binding 1 advances once per instance instead of once per vertex (as in chapter 19)
    57 glVertexArrayBindingDivisor(r.vao, 1, 1);
    58 glEnableVertexArrayAttrib(r.vao, 9);
    59 glVertexArrayAttribFormat(r.vao, 9, 2, GL_FLOAT, GL_FALSE, offsetof(AlienInstance, position));
    60 glVertexArrayAttribBinding(r.vao, 9, 1);
    61 // 整数の属性はglVertexArrayAttribIFormat(Iが付く)。Formatのほうだとfloatに変換されてしまい、`in uint`では読めない
    62 // Integer attributes need glVertexArrayAttribIFormat (with the I). The plain Format converts to float, which an
    63 // `in uint` cannot read
    64 glEnableVertexArrayAttrib(r.vao, 10);
    65 glVertexArrayAttribIFormat(r.vao, 10, 1, GL_UNSIGNED_INT, offsetof(AlienInstance, frame));
    66 glVertexArrayAttribBinding(r.vao, 10, 1);
    67 glEnableVertexArrayAttrib(r.vao, 8);
    68 glVertexArrayAttribFormat(r.vao, 8, 4, GL_UNSIGNED_BYTE, GL_TRUE, offsetof(AlienInstance, color));
    69 glVertexArrayAttribBinding(r.vao, 8, 1);
    70 return r;
    71 }
    72  
    73 void FormationRenderer::release() {
    74 if (vao) glDeleteVertexArrays(1, &vao);
    75 vao = 0;
    76 }
    77  
    78 FormationRenderer::~FormationRenderer() { release(); }
    79  
    80 FormationRenderer::FormationRenderer(FormationRenderer &&other) noexcept { *this = std::move(other); }
    81  
    82 FormationRenderer &FormationRenderer::operator=(FormationRenderer &&other) noexcept {
    83 if (this != &other) {
    84 release();
    85 shader = std::move(other.shader);
    86 corners = std::move(other.corners);
    87 instances = std::move(other.instances);
    88 vao = std::exchange(other.vao, 0);
    89 texture = other.texture;
    90 capacity = other.capacity;
    91 bytes = other.bytes;
    92 drawCalls = other.drawCalls;
    93 }
    94 return *this;
    95 }
    96  
    97 void FormationRenderer::draw(const Mat4 &viewProjection, std::span<const AlienInstance> list) {
    98 const GLsizei count = static_cast<GLsizei>(std::min(list.size(), static_cast<size_t>(capacity)));
    99 bytes = count * static_cast<int>(sizeof(AlienInstance));
    100 drawCalls = count > 0 ? 1 : 0;
    101 if (count == 0) return;
    102 instances.update(list.data(), bytes);
    103  
    104 // SpriteBatchと同じ2Dの状態:深度なし、カリングなし、乗算済みアルファ / the same 2D state as SpriteBatch: no depth,
    105 // no culling, premultiplied alpha
    106 glDisable(GL_DEPTH_TEST);
    107 glDisable(GL_CULL_FACE);
    108 glEnable(GL_BLEND);
    109 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
    110 shader->set("uViewProjection", viewProjection);
    111 shader->use();
    112 texture->bind(0);
    113 glBindVertexArray(vao);
    114 // 4頂点 × count個のインスタンス。gl_InstanceIDが0〜count-1、属性9・10・8はその番号の要素
    115 // 4 vertices × count instances. gl_InstanceID runs 0..count-1 and attributes 9, 10, 8 read that element
    116 glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, count);
    117 glBindVertexArray(0);
    118 }

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

前新
@@ -0,0 +1,65 @@
    1 // 隊列をインスタンシングで描く(第27章):四隅4つの頂点を全員で共有し、宇宙人ごとのデータ(位置・コマ・色)を
    2 // インスタンスのバッファから読む。一回のglDrawArraysInstancedで全員
    3 // Drawing the formation with instancing (chapter 27): every alien shares the same 4 corner vertices and reads its own
    4 // data (position, frame, color) from an instance buffer. One glDrawArraysInstanced for all of them
    5 //
    6 // SpriteBatchとの違い:バッチは一枚ごとに4頂点(80バイト)をCPUで計算して送る。ここでは一匹16バイトだけ送り、
    7 // 四隅はGPUが作る。代わりにできることは少ない(回転なし、一枚のテクスチャ、layerでバッチと混ぜられない)
    8 // Compared with SpriteBatch: the batch computes 4 vertices (80 bytes) per sprite on the CPU and uploads them. Here
    9 // only 16 bytes per alien are sent and the GPU builds the corners. In exchange it can do less (no rotation, one
    10 // texture, cannot be interleaved with batch sprites by layer)
    11 #pragma once
    12  
    13 #include "engine/buffer.hh"
    14 #include "engine/mathx.hh"
    15 #include "engine/shader.hh"
    16 #include "engine/sprite_sheet.hh"
    17  
    18 #include <cstdint>
    19 #include <optional>
    20 #include <span>
    21  
    22 // 一匹分のインスタンスデータ(16バイト)。attribute location 9・10・8に繋ぐ
    23 // One alien's instance data (16 bytes), connected to attribute locations 9, 10 and 8
    24 struct AlienInstance {
    25 Vec2 position; // 左上(ワールド座標) / top left (world space) → location 9, vec2
    26 std::uint32_t frame; // スプライトシートのコマ番号 / sprite sheet frame → location 10, uint (整数のまま / stays an integer)
    27 std::uint32_t color; // RGBA8(Rが下位バイト) / RGBA8 (R lowest byte) → location 8, vec4 (0..1に正規化 / normalized)
    28 };
    29 static_assert(sizeof(AlienInstance) == 16);
    30  
    31 // 色(0〜1、sRGBの値)→ RGBA8。SpriteBatchと同じ丸め方(同じ絵になるように) / a 0..1 color → RGBA8, rounded like
    32 // SpriteBatch does (so both paths give the same image)
    33 std::uint32_t packRgba8(Vec4 color);
    34  
    35 class FormationRenderer {
    36 public:
    37 // games/invaders/shaders/formation.vert + engine/shaders/sprite.frag(フラグメント側はバッチと同じ)。
    38 // シートの全コマのUVと大きさをユニフォームの配列に入れる(最大kMaxFrames)
    39 // games/invaders/shaders/formation.vert + engine/shaders/sprite.frag (the fragment stage is the batch's). The UV
    40 // rectangle and size of every sheet frame go into uniform arrays (at most kMaxFrames)
    41 static std::optional<FormationRenderer> create(const SpriteSheet &sheet, int capacity = 64);
    42 ~FormationRenderer();
    43 FormationRenderer(const FormationRenderer &) = delete;
    44 FormationRenderer &operator=(const FormationRenderer &) = delete;
    45 FormationRenderer(FormationRenderer &&other) noexcept;
    46 FormationRenderer &operator=(FormationRenderer &&other) noexcept;
    47  
    48 // インスタンスを送って(glNamedBufferSubData)一回で描く。状態はSpriteBatch::end()の後と同じにする
    49 // Uploads the instances (glNamedBufferSubData) and draws them in one call. Leaves the same state as SpriteBatch::end()
    50 void draw(const Mat4 &viewProjection, std::span<const AlienInstance> instances);
    51 int lastBytes() const { return bytes; } // 直前のdrawで送ったバイト数 / bytes uploaded by the last draw
    52 int lastDrawCalls() const { return drawCalls; }
    53  
    54 static constexpr int kMaxFrames = 32; // formation.vertの配列の大きさ / the array size in formation.vert
    55  
    56 private:
    57 FormationRenderer() = default;
    58 void release();
    59 std::optional<Shader> shader;
    60 Buffer corners; // バインディング0:四隅 (0,0) (1,0) (0,1) (1,1)、頂点ごと / binding 0: the corners, per vertex
    61 Buffer instances; // バインディング1:AlienInstance、インスタンスごと(divisor 1) / binding 1: per instance
    62 GLuint vao = 0;
    63 const Texture2D *texture = nullptr;
    64 int capacity = 0, bytes = 0, drawCalls = 0;
    65 };

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

前新
@@ -0,0 +1,73 @@
    1 // Invaders:どのシーンからも使う共有データ、画面の寸法、シーン
    2 // Invaders: the data every scene shares, the screen layout, the scenes
    3 #pragma once
    4  
    5 #include "formation.hh"
    6 #include "formation_renderer.hh"
    7  
    8 #include "engine/camera2d.hh"
    9 #include "engine/font.hh"
    10 #include "engine/game_loop.hh"
    11 #include "engine/input.hh"
    12 #include "engine/rng.hh"
    13 #include "engine/scene.hh"
    14 #include "engine/sprite_batch.hh"
    15 #include "engine/sprite_sheet.hh"
    16  
    17 #include <vector>
    18  
    19 // 仮想解像度320 × 180(ウィンドウ1280 × 720で4倍)。真ん中の224ピクセル幅が戦場、左右48ピクセルは脇の板
    20 // Virtual resolution 320 × 180 (× 4 in the 1280 × 720 window). The middle 224 pixels are the arena, 48 pixels on
    21 // each side are side panels
    22 constexpr Vec2 kView = {320.0f, 180.0f};
    23 constexpr float kArenaLeft = 48.0f, kArenaRight = 272.0f;
    24 constexpr float kFormationTop = 28.0f; // 最初の隊列の一番上 / the first formation's top row
    25 constexpr float kPlayerY = 158.0f; // 自機の上端 / the ship's top
    26 constexpr float kGroundY = 170.0f; // 地面の線 / the ground line
    27 constexpr float kPlayerSpeed = 60.0f; // ピクセル毎秒(1ステップ1ピクセル) / pixels per second (1 px per step)
    28  
    29 // ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference
    30 struct Game {
    31 Window &window;
    32 Input &input;
    33 GameLoop &loop;
    34 SpriteBatch &batch;
    35 FormationRenderer &formationRenderer;
    36 const Font &ui; // mono16:画面の解像度の文字 / text at screen resolution
    37 const SpriteSheet &sprites; // games/invaders/assets/sprites.atlas
    38 Camera2D world; // 320 × 180のキャンバス / the 320 × 180 canvas
    39 Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI
    40 Viewport uiViewport;
    41 Rng rng{27};
    42 bool instanced = true; // 隊列をインスタンシングで(I) / draw the formation instanced (I)
    43 };
    44  
    45 // 遊ぶ場面:自機と行進する隊列 / the play scene: the ship and the marching formation
    46 class PlayScene : public Scene {
    47 public:
    48 explicit PlayScene(Game &game);
    49 void pause() override;
    50 void update(float dt) override;
    51 void draw(float alpha) override;
    52 void drawUi(float alpha) override;
    53  
    54 private:
    55 struct Star {
    56 Vec2 position;
    57 float phase;
    58 };
    59 int alienFrame(const Alien &a) const;
    60 void drawBackground();
    61 void drawFormation();
    62  
    63 Game &g;
    64 Formation formation;
    65 float playerX = 0.0f, playerPrevX = 0.0f; // 自機の左端(補間用に前のステップも) / the ship's left edge (+ the
    66 // previous step's, for interpolation)
    67 std::vector<Star> stars;
    68 float time = 0.0f;
    69 int frames[3][2] = {}; // 種類 × 足踏み → シートのコマ / kind × pose → sheet frame
    70 int shipFrame = 0;
    71 int formationDrawCalls = 0, formationBytes = 0;
    72 int landings = 0;
    73 };

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

前新
@@ -0,0 +1,62 @@
    1 // Invaders 第1部(第27章):自機、インスタンシングで描く宇宙人の隊列、行進、操作
    2 // Invaders part 1 (chapter 27): the player's ship, the alien formation drawn with instancing, the march, the controls
    3 //
    4 // 操作 / Controls:
    5 // ← → / A D 移動 / move
    6 // I 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch
    7 // = / - 行進を速く・遅く / march faster / slower
    8 // Esc 終了 / quit
    9 #include "game.hh"
    10  
    11 #include "engine/pixel_canvas.hh"
    12 #include "engine/window.hh"
    13  
    14 #include <memory>
    15 #include <optional>
    16  
    17 int main() {
    18 Window window;
    19 if (!window.create(1280, 720, "OpenGL Tutorial - Invaders")) return 1;
    20  
    21 std::optional<SpriteBatch> batch = SpriteBatch::create();
    22 std::optional<Font> ui = Font::load("assets/fonts/mono16.fnt");
    23 std::optional<SpriteSheet> sprites = SpriteSheet::loadAtlas("games/invaders/assets/sprites.atlas");
    24 if (!batch || !ui || !sprites) return 1;
    25 std::optional<FormationRenderer> formationRenderer = FormationRenderer::create(*sprites);
    26 if (!formationRenderer) return 1;
    27  
    28 // 行動に名前を付ける(キーを変えるならここだけ) / name the actions (to change keys, edit only this)
    29 Input input;
    30 input.attach(window);
    31 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)});
    33  
    34 // 固定ステップ:ゲームの動きは1/60秒ごとの更新の中だけ / fixed step: the game only changes in the 1/60 s updates
    35 GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5});
    36 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,
    38 .ui = *ui, .sprites = *sprites, .world = Camera2D::screen(kView),
    39 .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}};
    40  
    41 SceneManager scenes;
    42 scenes.push(std::make_unique<PlayScene>(game));
    43  
    44 loop.run(
    45 window, input,
    46 [&](float dt) {
    47 scenes.update(dt);
    48 if (scenes.empty()) window.close();
    49 },
    50 [&](float alpha) {
    51 // 1. 世界:320 × 180のキャンバスに描いて4倍で画面へ / 1. the world: into the 320 × 180 canvas, shown × 4
    52 canvas.begin(hexColor(0x0c0a1aff));
    53 scenes.draw(alpha);
    54 canvas.present(window.width(), window.height());
    55 // 2. UI:1280 × 720の文字 / 2. the UI: text at 1280 × 720
    56 game.uiViewport = letterbox(window.width(), window.height(), game.screen.viewSize, false);
    57 game.uiViewport.apply();
    58 scenes.drawUi(alpha);
    59 scenes.drawFade(*batch, game.screen.matrix(), game.screen.viewSize);
    60 });
    61 return 0;
    62 }

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

前新
@@ -0,0 +1,167 @@
    1 // 遊ぶ場面(第27章):自機の操作、隊列の行進、隊列の描き方の比較(インスタンシング ⇔ SpriteBatch)
    2 // The play scene (chapter 27): steering the ship, the formation's march, two ways to draw the formation (instancing
    3 // ⇔ SpriteBatch)
    4 #include "game.hh"
    5  
    6 #include <algorithm>
    7 #include <cmath>
    8 #include <cstdio>
    9  
    10 PlayScene::PlayScene(Game &game) : g(game) {
    11 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)
    13 for (int p = 0; p < 2; ++p) frames[k][p] = g.sprites.find(names[k][p]);
    14 shipFrame = g.sprites.find("ship");
    15  
    16 // 隊列:幅 = 10 × 16 + 14 = 174ピクセル、戦場の真ん中 / the formation: 10 × 16 + 14 = 174 px wide, centered in the arena
    17 formation.minX = kArenaLeft + 2.0f;
    18 formation.maxX = kArenaRight - 2.0f;
    19 formation.reset(std::round(0.5f * (kArenaLeft + kArenaRight - 174.0f)), kFormationTop);
    20  
    21 playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f);
    22 // 星:自分の種で作るので、場面を作り直しても同じ空 / stars: made with their own seed, so the sky stays the same when
    23 // the scene is created again
    24 Rng sky(1978);
    25 for (int i = 0; i < 40; ++i)
    26 stars.push_back({{std::round(sky.range(kArenaLeft + 2.0f, kArenaRight - 2.0f)), std::round(sky.range(4.0f, 150.0f))},
    27 sky.unit()});
    28 }
    29  
    30 // 一時停止の間は補間しない(第26章) / no interpolation while paused (chapter 26)
    31 void PlayScene::pause() { playerPrevX = playerX; }
    32  
    33 int PlayScene::alienFrame(const Alien &a) const { return frames[static_cast<int>(a.kind)][a.pose]; }
    34  
    35 void PlayScene::update(float dt) {
    36 time += dt;
    37 Input &in = g.input;
    38 if (in.pressed(GLFW_KEY_ESCAPE)) {
    39 scenes().pop(); // スタックが空になる → main が終わらせる / the stack becomes empty → main quits
    40 return;
    41 }
    42 if (in.pressed(GLFW_KEY_I)) {
    43 g.instanced = !g.instanced;
    44 printf("formation: %s\n", g.instanced ? "instanced" : "SpriteBatch");
    45 }
    46 // 行進の速さを変える(説明用):1秒に動く宇宙人の数を2倍・半分 / change the march speed (for the demo): double or
    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);
    49 if (in.pressed(GLFW_KEY_MINUS)) formation.rate = std::max(formation.rate * 0.5f, 15.0f);
    50  
    51 // 自機:左右の行動の軸で動き、戦場からは出ない / the ship: moves along the left/right action axis, stays inside the
    52 // arena
    53 playerPrevX = playerX;
    54 playerX += in.axis("left", "right") * kPlayerSpeed * dt;
    55 playerX = std::clamp(playerX, kArenaLeft + 2.0f, kArenaRight - 2.0f - 15.0f);
    56  
    57 formation.update(dt);
    58 // 第27章では撃てないので、地面まで下りてきたら上からやり直す(第28章で「侵略された」になる)
    59 // There is no shooting in chapter 27 yet, so when the formation reaches the ship's row it starts again at the top
    60 // (chapter 28 turns this into "invaded")
    61 if (formation.bounds().bottom() > kPlayerY) {
    62 ++landings;
    63 printf("formation landed after %d passes: reset\n", formation.passes);
    64 formation.reset(std::round(0.5f * (kArenaLeft + kArenaRight - 174.0f)), kFormationTop);
    65 }
    66 }
    67  
    68 void PlayScene::drawBackground() {
    69 SpriteBatch &b = g.batch;
    70 // 脇の板と枠 / the side panels and their borders
    71 b.drawRect({0.0f, 0.0f, kArenaLeft, kView.y}, hexColor(0x16132aff));
    72 b.drawRect({kArenaRight, 0.0f, kView.x - kArenaRight, kView.y}, hexColor(0x16132aff));
    73 b.drawRect({kArenaLeft - 1.0f, 0.0f, 1.0f, kView.y}, hexColor(0x3a3460ff));
    74 b.drawRect({kArenaRight, 0.0f, 1.0f, kView.y}, hexColor(0x3a3460ff));
    75 // 瞬く星 / twinkling stars
    76 for (const Star &s : stars) {
    77 float t = 0.5f + 0.5f * std::sin(2.0f * time + 6.283f * s.phase);
    78 b.drawRect({s.position.x, s.position.y, 1.0f, 1.0f}, {0.62f, 0.64f, 0.8f, 0.25f + 0.5f * t});
    79 }
    80 // 地面 / the ground
    81 b.drawRect({kArenaLeft, kGroundY, kArenaRight - kArenaLeft, 1.0f}, hexColor(0x68c454ff));
    82 }
    83  
    84 void PlayScene::drawFormation() {
    85 if (g.instanced) {
    86 // インスタンシング:生きている宇宙人を16バイトずつ並べて、一回で描く / instancing: 16 bytes per living alien, one
    87 // draw call
    88 std::vector<AlienInstance> list;
    89 for (const Alien &a : formation.aliens)
    90 if (a.alive)
    91 list.push_back({a.position, static_cast<std::uint32_t>(alienFrame(a)), packRgba8(kWhite)});
    92 g.formationRenderer.draw(g.world.matrix(), list);
    93 formationDrawCalls = g.formationRenderer.lastDrawCalls();
    94 formationBytes = g.formationRenderer.lastBytes();
    95 } 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());
    99 for (const Alien &a : formation.aliens)
    100 if (a.alive) g.batch.draw(g.sprites.sprite(alienFrame(a), a.position));
    101 g.batch.end();
    102 formationDrawCalls = g.batch.stats().drawCalls;
    103 formationBytes = g.batch.stats().sprites * 4 * static_cast<int>(sizeof(SpriteVertex));
    104 }
    105 }
    106  
    107 void PlayScene::draw(float alpha) {
    108 // 奥から:背景(バッチ)→ 隊列(インスタンシングかバッチ)→ 自機(バッチ) / back to front: background (batch) →
    109 // formation (instanced or batch) → ship (batch)
    110 g.batch.begin(g.world.matrix());
    111 drawBackground();
    112 g.batch.end();
    113  
    114 drawFormation();
    115  
    116 // 宇宙人は飛び飛びに動くので補間しない。自機は滑らかに動くので補間する(第26章)
    117 // Aliens move in jumps, so they are not interpolated. The ship moves smoothly, so it is (chapter 26)
    118 float x = std::round(playerPrevX + (playerX - playerPrevX) * alpha);
    119 g.batch.begin(g.world.matrix());
    120 g.batch.draw(g.sprites.sprite(shipFrame, {x, kPlayerY}));
    121 g.batch.end();
    122 }
    123  
    124 void PlayScene::drawUi(float /*alpha*/) {
    125 SpriteBatch &b = g.batch;
    126 b.begin(g.screen.matrix());
    127 TextStyle head = {.color = hexColor(0xf2c14eff), .shadow = hexColor(0x000000ff)};
    128 TextStyle body = {.color = hexColor(0xd8dcefff), .shadow = hexColor(0x000000ff)};
    129 char line[64];
    130 // 左の板:隊列の描き方と、その値段 / the left panel: how the formation is drawn and what it costs
    131 float y = 24.0f;
    132 auto text = [&](const char *s, const TextStyle &st) {
    133 g.ui.draw(b, s, {14.0f, y}, st);
    134 y += 22.0f;
    135 };
    136 text("FORMATION (I)", head);
    137 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);
    141 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));
    146 text(line, body);
    147 snprintf(line, sizeof line, "alive %d", formation.alive());
    148 text(line, body);
    149 snprintf(line, sizeof line, "passes %d", formation.passes);
    150 text(line, body);
    151 snprintf(line, sizeof line, "landed %d", landings);
    152 text(line, body);
    153  
    154 // 右の板:操作 / the right panel: controls
    155 y = 24.0f;
    156 auto right = [&](const char *s, const TextStyle &st) {
    157 g.ui.draw(b, s, {1102.0f, y}, st);
    158 y += 22.0f;
    159 };
    160 right("CONTROLS", head);
    161 right("A D / arrows", body);
    162 right(" move", body);
    163 right("I formation", body);
    164 right("= - march", body);
    165 right("Esc quit", body);
    166 b.end();
    167 }


コメント(0)

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