28. Space Invaders Part 2: Shooting and Collisions
At the end of chapter 27 the ship could move and the formation marched, one alien at a time, but nobody could hurt anybody.
In this chapter the game becomes playable: the ship fires, the aliens fire back, bullets hit things, four shields wear away pixel by pixel, aliens and the ship explode, and there are lives and a game over.
Most of it is game logic built on chapter 26's toolkit: the AABB tests, Rng, Animator and the scene stack.
The OpenGL part is the shields.
They live in a small texture that changes while the game runs, and every hit re-uploads only the rectangle that changed, straight out of a bigger CPU array.
That needs glTextureSubImage2D with an offset, and the pixel-store parameter GL_UNPACK_ROW_LENGTH, which is the main new GL topic of this chapter.
Game chapters are code-heavy, so I'll show the important code and explain why it's written that way, rather than going through every line; the rest is in the download at the end.
28.1 What we're building
Here's the game after about four seconds of scripted play:
The clip shoots through the formation, shows both kinds of alien bullets, the shields wearing away from both sides, and one ship explosion, during which the march stops:
The controls:
- ← → or A D: move
- Space, ↑ or W: fire
- B: show the collision boxes
- I: draw the formation instanced or with the
SpriteBatch(chapter 27) - = and −: march faster or slower (a debugging aid)
- Space or Enter after a game over: play again
- Esc: quit
The program is still invaders, and nothing outside games/invaders/ changes.
Starting from chapter 27, the changes are:
src/shields.hh,src/shields.cc(new):Shields, the eroding shields, andloadSpriteImage, which cuts one sprite out of a CPU decode of the sprite sheetsrc/effects.hh,src/effects.cc(new):Particles(one-pixel debris) andFlare(a sprite shown for a moment)src/formation.hh,src/formation.cc: an alien can be dying;kill,updateExplosions,clearedandlowestInColumnsrc/game.hh: new constants, the shield art andshowBoxesinGame, bullets and the battle state inPlayScenesrc/play_scene.cc: the battlesrc/main.cc: the shield art and thefireandconfirmactionsCMakeLists.txt,README.md: the new files and controls
The sprite sheet doesn't change: chapter 27's generator already drew the bullets, the explosions, the impact splat and the shield.
The two new source files go into the game's CMakeLists.txt:
add_executable(invaders
src/main.cc
src/play_scene.cc
src/formation.cc
src/formation_renderer.cc
src/shields.cc
src/effects.cc)
28.2 Constants and state
The layout gets a row for the shields, and the battle gets its speeds and limits:
constexpr float kShieldY = 136.0f; // 防壁の上端 / the shields' top
constexpr float kPlayerY = 158.0f; // 自機の上端 / the ship's top
constexpr float kGroundY = 170.0f; // 地面の線 / the ground line
constexpr float kPlayerSpeed = 60.0f; // ピクセル毎秒(1ステップ1ピクセル) / pixels per second (1 px per step)
constexpr float kShotSpeed = 240.0f; // 自機の弾:1ステップ4ピクセル / the ship's bullet: 4 px per step
constexpr float kAlienShotSpeed = 75.0f; // 宇宙人の弾 / alien bullets
constexpr int kMaxAlienShots = 3;
constexpr int kStartLives = 3;
All speeds are in canvas pixels per second, and the game logic runs in chapter 26's fixed 1/60 s steps, so the ship's bullet moves exactly px per step and an alien bullet px.
Those two numbers come back in the collision section.
A bullet is a collision box, the previous step's y for interpolation, and an Animator for the alien bullets' four-frame clips:
struct Bullet {
Rect box;
float prevY;
Animator anim; // 宇宙人の弾は4コマのクリップ / alien bullets play a 4-frame clip
};
The scene keeps the new state next to chapter 27's:
std::optional<Bullet> shot; // 自機の弾は一度に一発(元のゲームと同じ) / one ship bullet at a time
// (as in the original)
std::vector<Bullet> alienShots;
float fireTimer = 1.0f; // 宇宙人が次に撃つまで / until the aliens fire next
float shipDying = 0.0f; // 自機の爆発の残り時間(> 0 の間は隊列も止まる) / ship explosion time
// left (the march stops meanwhile)
Animator shipBoom;
Particles particles;
std::vector<Flare> flares;
The ship's bullet is a std::optional, not a vector: there is either one or none, and the type says so.
28.3 The ship's bullet: one at a time
In the 1978 original you can't fire again while your shot is still on screen.
It sounds like a limitation, but it's most of the game: a missed shot costs you time, so you aim instead of mashing the button, and shooting the low alien right in front of you (a short flight) is faster than sniping at the top row.
We keep the rule:
void PlayScene::fire() {
// 画面に自機の弾がない時だけ撃てる:連打より狙いが大事(元のゲームの決まり)
// Only when no ship bullet is on screen: aiming beats mashing (the original's rule)
if (shot || shipDying > 0.0f || gameOver || !g.input.actionPressed("fire")) return;
float y = kPlayerY - 4.0f;
shot = Bullet{.box = {playerX + 7.0f, y, 1.0f, 5.0f}, .prevY = y, .anim = {}};
++shotsFired;
}
The fire action is bound to Space, ↑ and W in main.cc, and confirm (for the game-over screen) to Space and Enter:
input.bind("fire", {InputBinding::key(GLFW_KEY_SPACE), InputBinding::key(GLFW_KEY_UP), InputBinding::key(GLFW_KEY_W)});
input.bind("confirm", {InputBinding::key(GLFW_KEY_SPACE), InputBinding::key(GLFW_KEY_ENTER)});
actionPressed is true in exactly one update per key press (chapter 26), and the engine ignores GLFW's auto-repeat events, so holding Space fires once.
The bullet is 1 × 5 px and starts at x = ship + 7, the middle column of the 15 px ship.
It moves 4 px per step, so from y = 154 it reaches the top of the arena (y < 6) after 38 steps, about 0.63 s: that's the longest you can wait for your next shot.
28.4 Collision boxes
What collides with what
Every test in this chapter is chapter 26's overlaps: strict AABB overlap, so boxes that only touch don't collide.
B draws all the boxes:
| Thing | Box (canvas px) | Why |
|---|---|---|
| alien | its 14 × 10 sprite cell, Alien::box() from chapter 27 |
generous: a shot that touches the outline counts |
| ship | {x + 1, y + 1, 13, 7} |
the hull without the outline: a near miss is a miss |
| ship bullet | 1 × 5 | the sprite |
| alien bullet | 3 × 7 | the sprite |
| shield | its 22 × 16 rectangle | only the first test; then pixels decide |
The two choices in the middle of the table are on purpose.
The aliens get boxes slightly bigger than what you see and the ship gets a slightly smaller one, so every close call goes the player's way.
Players never complain that they hit something they barely touched, but they do complain when a bullet that clearly missed kills them.
The ship's box is one line:
Rect PlayScene::shipBox() const { return {playerX + 1.0f, kPlayerY + 1.0f, 13.0f, 7.0f}; }
Why nothing tunnels
Chapter 26 warned about tunneling: a box that moves farther in one step than the boxes are thick can jump over a target, and the cure was the swept test.
This game doesn't need sweep, and the reason is worth checking rather than hoping.
First, a target that stands still.
The ship bullet is 5 px long and moves 4 px per step, so its box in one step and its box in the next step share one row of pixels.
Together, the boxes of all steps cover the bullet's whole path without a gap, and anything standing in that path overlaps at least one of them.
The shields don't move, so the bullet tests every row of them on its way up.
Then two things that both move.
Two boxes of heights and overlap vertically while their relative offset is inside a window of pixels.
If the offset changes by less than that per step, no step can jump from one side of the window to the other: at least one step lands inside.
- Ship bullet against an alien: the window is px. The worst case is an alien stepping down 6 px while the bullet goes up 4: . Sideways, the window is px and an alien moves 2.
- Ship bullet against an alien bullet: px, and they close in at px per step.
- Alien bullet against the ship: px vertically against 1.25 px per step; sideways px against the ship's 1 px per step.
So every pair is safe at these speeds.
The argument has a fine print: an alien takes one move per step at the default march rate of 60 aliens per second.
The = key doubles the rate up to 960 aliens per second, 16 moves per step, and with only two aliens left each of them then moves 8 times in one step, 16 px sideways, more than the 15 px window: at that debugging speed a shot really can pass through the last aliens.
If you speed up the game later, redo this arithmetic, or move the bullet with sweep.
The ship bullet's tests, in order
updateShot moves the bullet and tests it against everything it can hit, and the first hit wins:
void PlayScene::updateShot(float dt) {
if (!shot) return;
shot->prevY = shot->box.y;
shot->box.y -= kShotSpeed * dt;
// 1ステップ4ピクセル、弾の長さ5ピクセル:続けて見れば隙間がないので、すり抜けない(第26章のトンネリング)。
// 宇宙人の弾とも:近づく速さは1ステップ5.25ピクセル < 5 + 7
// 4 px per step with a 5 px bullet: consecutive boxes leave no gap, so nothing is skipped (ch26's tunneling).
// Against alien bullets too: they close in at 5.25 px per step < 5 + 7
const Rect &box = shot->box;
for (size_t i = 0; i < alienShots.size(); ++i)
if (overlaps(box, alienShots[i].box)) {
flare(box.centre(), hexColor(0xfff4d6ff));
alienShots.erase(alienShots.begin() + static_cast<std::ptrdiff_t>(i));
shot.reset();
return;
}
for (Alien &a : formation.aliens)
if (a.alive && overlaps(box, a.box())) {
formation.kill(a);
particles.burst(a.box().centre(), 10, kAlienColors[static_cast<int>(a.kind)], 15.0f, 50.0f, g.rng);
++kills;
shot.reset();
return;
}
if (std::optional<Vec2> p = shields->hit(box, true)) {
shields->erode(*p, g.rng);
flare(*p, hexColor(0x68c454ff));
shot.reset();
return;
}
if (box.top() < 6.0f) { // 戦場の上の端 / the top of the arena
flare({box.x, 6.0f}, hexColor(0xfff4d6ff));
shot.reset();
}
}
The order is a design decision.
Alien bullets come first, so you can shoot a bullet out of the air right in front of you (both vanish with a flare).
Aliens come before shields, which only matters once the formation has come down to the shields: then an alien standing in a shield is hit rather than the shield.
The aliens are tested in march order, bottom row first, and since the rows are 4 px apart and a bullet's box starts on a whole pixel, the 5 px bullet can never overlap two rows at once: the alien it meets first is the one it kills.
Every branch returns at once, because shot.reset() destroys the box that box refers to.
Brute force is fine here: one bullet against at most 3 bullets, 55 aliens and 4 shields is about 60 tests per step.
A game with thousands of objects would first sort them into a grid (a broad phase, chapter 26), but this one never will.
28.5 Alien fire
Who shoots
In the original, only the lowest alien of a column can shoot: an alien can't fire through its neighbor below.
That rule is what makes clearing a column worthwhile, and it's a small function on the formation:
const Alien *Formation::lowestInColumn(int column) const {
const Alien *lowest = nullptr;
for (const Alien &a : aliens)
if (a.alive && a.column == column && (!lowest || a.position.y > lowest->position.y)) lowest = &a;
return lowest;
}
The scene decides when and from which column:
void PlayScene::alienFire(float dt) {
fireTimer -= dt;
if (fireTimer > 0.0f) return;
fireTimer = g.rng.range(0.5f, 1.1f);
if (static_cast<int>(alienShots.size()) >= kMaxAlienShots) return;
// 撃つ列:3回に1回は自機の真上の列、それ以外は生きている宇宙人をランダムに選んでその列。撃つのはその列の一番下
// The firing column: one time in three the column above the ship, otherwise the column of a random living alien.
// The lowest alien of that column shoots
std::vector<const Alien *> living;
for (const Alien &a : formation.aliens)
if (a.alive) living.push_back(&a);
if (living.empty()) return;
int column = living[static_cast<size_t>(g.rng.range(0, static_cast<int>(living.size()) - 1))]->column;
if (g.rng.chance(1.0f / 3.0f)) {
float shipX = shipBox().centre().x, best = 1e9f;
for (const Alien *a : living)
if (float d = std::fabs(a->box().centre().x - shipX); d < best) best = d, column = a->column;
}
const Alien *shooter = formation.lowestInColumn(column);
if (!shooter) return;
Bullet b{.box = {shooter->position.x + 5.0f, shooter->position.y + kAlienSize.y, 3.0f, 7.0f},
.prevY = shooter->position.y + kAlienSize.y, .anim = {}};
b.anim.play(g.rng.chance(0.5f) ? zigClip : boltClip);
alienShots.push_back(b);
}
Some details:
- A shot comes every 0.5 to 1.1 s, 0.8 s on average, but never more than 3 are on screen. When the limit is reached, the timer still restarts, so the aliens don't fire the instant one bullet disappears.
- Picking a random living alien and taking its column is not the same as picking a random column: a column with five aliens left fires five times as often as a column with one. As the formation thins out, the full columns keep the pressure up.
- One time in three the column whose alien is nearest above the ship fires. That's what keeps you moving: standing still under the formation gets you hit. (The original had a shot type that aimed at your column in the same way.)
- Each bullet is a zigzag or a bolt at random, with its own
Animatorplaying the 4-frame, 12 fps clip from the sprite sheet. - Every random number comes from
Game::rng, seeded with 27, and the game logic only runs in fixed steps, so the same input gives the same game every time. The screenshots and the clip rely on that.
Falling, and hitting the ship
void PlayScene::updateAlienShots(float dt) {
for (size_t i = 0; i < alienShots.size();) {
Bullet &b = alienShots[i];
b.prevY = b.box.y;
b.box.y += kAlienShotSpeed * dt;
b.anim.update(dt);
if (shipDying <= 0.0f && overlaps(b.box, shipBox())) {
killShip(); // 全部の弾を消す / clears every bullet
return;
}
bool gone = false;
if (std::optional<Vec2> p = shields->hit(b.box, false)) {
shields->erode(*p, g.rng);
flare(*p, hexColor(0x68c454ff));
gone = true;
} else if (b.box.bottom() >= kGroundY) {
flare({b.box.centre().x, kGroundY - 2.0f}, hexColor(0xffa040ff));
gone = true;
}
if (gone) alienShots.erase(alienShots.begin() + static_cast<std::ptrdiff_t>(i));
else ++i;
}
}
The loop erases from the vector it walks through, so it uses an index and only advances when nothing was erased; a range-based for would be undefined behavior here.
killShip clears the whole vector, so the function returns right after it instead of touching b again.
void PlayScene::killShip() {
--lives;
shipDying = kShipBoomTime;
shipBoom.play(shipBoomClip, true);
Vec2 c = shipBox().centre();
particles.burst(c, 24, hexColor(0x4fc0a5ff), 20.0f, 70.0f, g.rng);
particles.burst(c, 12, hexColor(0xffa040ff), 30.0f, 90.0f, g.rng);
alienShots.clear(); // 元のゲームと同じく、飛んでいる弾は消える / bullets in flight vanish, as in the original
printf("ship hit: lives %d\n", lives);
}
Clearing the bullets in flight is again the original's rule, and a kind one: when the ship comes back, there isn't a bullet already falling on its head.
28.6 Shields that erode
The shields are the most interesting part of the chapter.
A shield isn't a box that is either there or not: every hit bites a small piece out of it, and after a while bullets go through the holes.
That means the game needs the shields' pixels, both for drawing and for collisions.
One texture for four shields
All four shields live in one 88 × 16 GL_RGBA8 texture, shield at texel , and they're drawn as four ordinary batch sprites, each with its quarter of the texture as UV rectangle:
The class keeps the master copy of the pixels on the CPU, the texture, and a dirty rectangle:
class Shields {
public:
// 4つの防壁を一枚のテクスチャ(88 × 16)に並べる。topLeft[i] = 画面での防壁iの左上
// Puts the 4 shields side by side in one texture (88 × 16). topLeft[i] = where shield i goes on screen
static std::optional<Shields> create(const Image &art, const Vec2 (&topLeft)[kShieldCount]);
// boxの中に残っている防壁のピクセルがあるか。あれば、弾の進む向きで最初に当たるピクセル(の中心)
// (下から来る弾 = 一番下、上から来る弾 = 一番上)
// Is any shield pixel left inside box? If so, the pixel a bullet meets first (its center): the lowest for a
// bullet coming from below, the highest for one coming from above
std::optional<Vec2> hit(const Rect &box, bool fromBelow) const;
// 着弾の形(kSplat、6 × 8)でピクセルを消す。左右はランダムに反転 / clears pixels in the impact shape (kSplat,
// 6 × 8), mirrored at random
void erode(Vec2 point, Rng &rng);
// 四角の中を全部消す(防壁まで下りてきた宇宙人) / clears everything inside the box (aliens that reach the shields)
void eraseRect(const Rect &box);
// 変わった所だけをアップロードする(描く前に一度) / uploads only what changed (once, before drawing)
void upload();
void draw(SpriteBatch &batch, float layer = 0.0f) const;
Rect bounds(int i) const { return {topLeft[i].x, topLeft[i].y, kShieldW, kShieldH}; }
int lastUploadBytes() const { return uploadBytes; }
int pixelsLeft() const;
const Texture2D &texture() const { return tex; }
private:
static constexpr int kTexW = kShieldW * kShieldCount, kTexH = kShieldH;
Shields() = default;
void clearPixel(int x, int y); // テクスチャのピクセル座標 / texture pixel coordinates
bool solid(int x, int y) const { return pixels[static_cast<size_t>(4 * (y * kTexW + x) + 3)] != 0; }
std::vector<std::uint8_t> pixels; // kTexW × kTexH × RGBA8(CPUの正本) / the CPU master copy
Texture2D tex;
Vec2 topLeft[kShieldCount];
int dirtyX0 = kTexW, dirtyY0 = kTexH, dirtyX1 = 0, dirtyY1 = 0; // 変わった四角(x1・y1は含まない) / the changed
// rectangle (x1, y1 exclusive)
int uploadBytes = 0;
};
Why one texture and not four?
One texture means one sprite batch draw call for all four shields, one upload per frame at most, and one array to index.
The price is that a hit on the first shield and a hit on the fourth in the same frame grow one dirty rectangle that spans all four (challenge 4 fixes that).
A pixel is "solid" when its alpha isn't 0; the game never needs anything else, so collisions read only the alpha byte.
The scene puts the shields at even spacing over the 224 px arena, centers 76, 132, 188 and 244, so the top-left corners are at x = 65, 121, 177 and 233:
// 防壁4つを戦場に等間隔で(中心 76, 132, 188, 244) / four shields evenly across the arena (centers 76, 132, 188, 244)
Vec2 shieldPos[kShieldCount];
for (int i = 0; i < kShieldCount; ++i)
shieldPos[i] = {kArenaLeft + (kArenaRight - kArenaLeft) * (static_cast<float>(i) + 0.5f) / kShieldCount - kShieldW / 2,
kShieldY};
shields = Shields::create(g.shieldArt, shieldPos);
if (!shields) { // 防壁が無いと遊べない(理由はcreateが書いた) / no game without shields (create logged why)
fprintf(stderr, "防壁を作れないので終了 / cannot create the shields: quitting\n");
g.window.close(); // 防壁を使う関数は何もしない / the functions that use the shields do nothing
}
create copies the art four times into the array, makes the texture and uploads it once:
std::optional<Shields> Shields::create(const Image &art, const Vec2 (&positions)[kShieldCount]) {
if (art.width != kShieldW || art.height != kShieldH) {
fprintf(stderr, "防壁の絵が %d × %d でない / the shield art is not %d × %d\n", kShieldW, kShieldH, kShieldW, kShieldH);
return std::nullopt;
}
Shields s;
s.pixels.resize(static_cast<size_t>(kTexW * kTexH * 4));
for (int i = 0; i < kShieldCount; ++i) {
s.topLeft[i] = positions[i];
for (int y = 0; y < kShieldH; ++y)
std::copy_n(art.rgba.begin() + 4 * y * kShieldW, 4 * kShieldW,
s.pixels.begin() + 4 * (y * kTexW + i * kShieldW));
}
// 中身は後で書き換えるので、空のストレージを作ってから全体を一度送る / the contents change later, so allocate
// empty storage and send everything once
s.tex = Texture2D(kTexW, kTexH, GL_RGBA8, 1);
s.tex.setFilter(GL_NEAREST, GL_NEAREST);
s.tex.setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
s.tex.upload(s.pixels.data());
return s;
}
Texture2D(w, h, GL_RGBA8, 1) is chapter 6's constructor: glCreateTextures and glTextureStorage2D with one mipmap level.
That storage is immutable, which is easy to misread: its size, format and level count can never change, but its contents can be replaced as often as you like.
Immutable storage is exactly right for a texture whose pixels change all the time.
No mipmaps, GL_NEAREST and clamping are the pixel-art rules of chapter 25.
create fails only when the art has the wrong size.
But a constructor can't return that failure, and a scene without shields can't be played.
So the constructor logs an error and closes the window, the same idea as main giving up with return 1 when an asset is missing.
Every function that uses shields (update, draw and drawUi) then starts with one line:
if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor)
The guard in draw matters too: the first frame is drawn before the first update (chapter 26), and when Space restarts the game, the new scene is drawn in the same frame, before the loop notices the closed window.
The art, decoded twice
The shield's picture is the shield sprite of the sprite sheet, and I want it to stay there, drawn by the same generator as everything else.
But SpriteSheet only keeps the GPU texture, and the game needs the pixels in CPU memory.
So main decodes the same PNG a second time on the CPU and cuts out the sprite:
// 防壁の絵はCPUにも要る(削るため):同じPNGをもう一度デコードして切り出す / the shield art is needed on the CPU
// too (to erode it): decode the same PNG again and cut it out
std::optional<Image> shieldArt = loadSpriteImage("games/invaders/assets/sprites.png", *sprites, "shield");
if (!formationRenderer || !shieldArt) return 1;
std::optional<Image> loadSpriteImage(const std::string &pngPath, const SpriteSheet &sheet, const char *name) {
int index = sheet.find(name);
std::optional<std::vector<std::uint8_t>> bytes = readBinaryFile(pngPath);
if (index < 0 || !bytes) {
fprintf(stderr, "%s: スプライト %s がない / no sprite %s\n", pngPath.c_str(), name, name);
return std::nullopt;
}
std::optional<Image> sheetImage = decodeImage(bytes->data(), bytes->size(), false);
if (!sheetImage) return std::nullopt;
Rect r = sheet.pixels(index);
Image out;
out.width = static_cast<int>(r.w);
out.height = static_cast<int>(r.h);
out.rgba.resize(static_cast<size_t>(out.width * out.height * 4));
for (int y = 0; y < out.height; ++y)
for (int x = 0; x < out.width; ++x)
for (int c = 0; c < 4; ++c) {
size_t src = static_cast<size_t>(4 * ((static_cast<int>(r.y) + y) * sheetImage->width + static_cast<int>(r.x) + x) + c);
out.rgba[static_cast<size_t>(4 * (y * out.width + x) + c)] = sheetImage->rgba[src];
}
// 乗算済みアルファにする(loadSpriteTextureが自動でやっていること)。PNGの透明なピクセルには、にじみ止めの色
// (隣の不透明なピクセルの色)が入っているので、そのまま送ると (r, g, b, 0) が加算されて縁が光る
// Premultiply (what loadSpriteTexture does for you). The PNG's transparent pixels carry the nearest opaque color
// against fringes; sent as is, (r, g, b, 0) would be *added* by the premultiplied blend and the edges would glow
for (size_t i = 0; i < out.rgba.size(); i += 4)
for (size_t c = 0; c < 3; ++c) out.rgba[i + c] = static_cast<std::uint8_t>(out.rgba[i + c] * out.rgba[i + 3] / 255);
return out;
}
readBinaryFile and decodeImage (stb_image from memory, chapter 14) are engine functions; the sheet's atlas tells us where the sprite is (sheet.pixels(index), in texels with rows from the top).
Decoding a 128 × 48 PNG twice at start-up costs nothing worth measuring.
Premultiply by hand
The last loop of loadSpriteImage is the trap of this chapter.
Since chapter 25, every 2D texture is premultiplied (chapter 16) and the sprite batch blends with GL_ONE, GL_ONE_MINUS_SRC_ALPHA:
loadSpriteTexture multiplies RGB by alpha before uploading, so we never had to think about it.
A texture we fill ourselves gets no such help: what we upload is what the blend sees.
And the sheet's PNG is straight alpha with colored transparent texels on purpose: the script of mine that made the sheet fills every transparent texel with the color of its nearest opaque neighbor, so linear filtering never pulls black into an edge.
The shield sprite has 298 solid texels and 54 transparent ones, and all 54 carry a green like (104, 196, 84) with alpha 0.
Uploaded unchanged, each of them would add its full color to the background, , and the shield would turn into a solid 22 × 16 block.
Multiplying by alpha makes them (0, 0, 0, 0), which adds nothing.
The rule to remember: a texture you fill by hand must be premultiplied by hand, because every sprite is drawn with the premultiplied blend.
The pixels the game clears later are set to (0, 0, 0, 0), which is already correct.
The hit test: a box, then pixels
Collisions with a shield are two-phase.
First the bullet's box against the shield's 22 × 16 rectangle; most bullets fail that and cost nothing more.
Then, only for the pixels under the box, which of them are still solid:
std::optional<Vec2> Shields::hit(const Rect &box, bool fromBelow) const {
for (int i = 0; i < kShieldCount; ++i) {
Rect s = bounds(i);
// boxが重なるピクセルの範囲(防壁の中の座標) / the pixels the box covers (shield coordinates)
int x0 = std::max(0, static_cast<int>(std::floor(box.left() - s.x)));
int x1 = std::min(kShieldW, static_cast<int>(std::ceil(box.right() - s.x)));
int y0 = std::max(0, static_cast<int>(std::floor(box.top() - s.y)));
int y1 = std::min(kShieldH, static_cast<int>(std::ceil(box.bottom() - s.y)));
if (x0 >= x1 || y0 >= y1) continue;
for (int n = 0; n < y1 - y0; ++n) {
int y = fromBelow ? y1 - 1 - n : y0 + n;
for (int x = x0; x < x1; ++x)
if (solid(i * kShieldW + x, y))
return Vec2{s.x + static_cast<float>(x) + 0.5f, s.y + static_cast<float>(y) + 0.5f};
}
}
return std::nullopt;
}
The box is converted to a range of shield pixels, floor for the start and ceil for the end, clamped to the shield: an empty range means the box missed the rectangle (the AABB test, done on integers).
Then the rows are scanned in the bullet's direction: from the bottom for the ship's bullet, from the top for alien bullets.
The box covers 4 or 5 rows, and the bullet should explode at the first solid pixel it would have reached, not at a random one in the middle.
The result is the center of that pixel, in canvas coordinates.
Here's a real hit: a ship bullet at x = 131 under the second shield (column 10 of the shield):
At y = 150 the box covers shield rows 14 and 15, inside the arch, where column 10 is empty.
One step later, at y = 146, it covers rows 10 to 14; scanning from the bottom, rows 14, 13 and 12 are empty and row 11 is solid.
That's the hit, at (131.5, 147.5).
Erosion and the dirty rectangle
The hit point is handed to erode, which clears the pixels of a 6 × 8 pattern around it:
// 着弾の形(スプライトシートのsplatと同じ形):'W' = 消すピクセル / the impact shape (the same shape as the
// sheet's splat sprite): 'W' = a pixel to clear
static const char *const kSplat[] = {
"W..W.W",
"..WW..",
".WWWW.",
"WWWWW.",
".WWWWW",
"WWWWW.",
"..WW..",
"W..W.W",
};
constexpr int kSplatW = 6, kSplatH = 8;
It's the same shape as the splat sprite that flashes at the impact, so the hole looks like the explosion that made it.
A bullet that hits a shield shows a green splat for 0.12 s, and when it fades, a hole of exactly that shape is left.
void Shields::erode(Vec2 point, Rng &rng) {
bool mirror = rng.chance(0.5f);
for (int i = 0; i < kShieldCount; ++i) {
Rect s = bounds(i);
// 着弾の形の左上(防壁の中の座標) / the impact shape's top left (shield coordinates)
int ox = static_cast<int>(std::floor(point.x - s.x)) - kSplatW / 2;
int oy = static_cast<int>(std::floor(point.y - s.y)) - kSplatH / 2;
if (ox >= kShieldW || oy >= kShieldH || ox + kSplatW <= 0 || oy + kSplatH <= 0) continue;
for (int y = 0; y < kSplatH; ++y)
for (int x = 0; x < kSplatW; ++x) {
int sx = ox + x, sy = oy + y;
char c = kSplat[y][mirror ? kSplatW - 1 - x : x];
if (c == 'W' && sx >= 0 && sx < kShieldW && sy >= 0 && sy < kShieldH) clearPixel(i * kShieldW + sx, sy);
}
}
}
The pattern's top-left corner is 3 columns left of and 4 rows above the hit pixel, so the hit pixel is the pattern's cell (3, 4).
That cell is a W in both the pattern and its mirror image (column 3 or 2 of .WWWWW), which guarantees that the hit pixel itself is always cleared.
Without that, a pixel could survive its own hit, and every following bullet in that column would stop at the same pixel forever.
The random mirror (50 %, from the game's Rng) makes neighboring holes look less like stamps.
Clearing a pixel is where the dirty rectangle grows:
void Shields::clearPixel(int x, int y) {
if (x < 0 || y < 0 || x >= kTexW || y >= kTexH || !solid(x, y)) return;
std::fill_n(pixels.begin() + 4 * (y * kTexW + x), 4, std::uint8_t{0});
dirtyX0 = std::min(dirtyX0, x), dirtyY0 = std::min(dirtyY0, y);
dirtyX1 = std::max(dirtyX1, x + 1), dirtyY1 = std::max(dirtyY1, y + 1);
}
A pixel that is already empty returns early, so it doesn't grow the rectangle: only pixels that really change are counted.
In the example, 20 of the pattern's cells were solid (the rows below the arch's ceiling were already empty), and the dirty rectangle is 6 × 6 texels.
The "empty" rectangle is x0 = width, x1 = 0, so the first min/max always replaces it.
Uploading a rectangle: glTextureSubImage2D
The hits happen in update, possibly several per frame or none for a long time.
The upload happens in draw, once per frame, before the shields are drawn, and sends whatever the dirty rectangle has collected since the last frame:
void Shields::upload() {
uploadBytes = 0;
if (dirtyX0 >= dirtyX1 || dirtyY0 >= dirtyY1) return; // 変わっていない / nothing changed
int w = dirtyX1 - dirtyX0, h = dirtyY1 - dirtyY0;
// CPUの配列の一部(四角)を送る:行の長さ(GL_UNPACK_ROW_LENGTH)を配列全体の幅にすると、GLは一行ごとに
// kTexWピクセル先へ進む。ポインターは四角の左上。送ったら0(= 幅と同じ)に戻す
// Send a rectangle out of the CPU array: with GL_UNPACK_ROW_LENGTH = the whole array's width, the GL steps kTexW
// pixels for every row. The pointer is the rectangle's top left. Reset it to 0 (= the width) afterwards
glPixelStorei(GL_UNPACK_ROW_LENGTH, kTexW);
glTextureSubImage2D(tex.id(), 0, dirtyX0, dirtyY0, w, h, GL_RGBA, GL_UNSIGNED_BYTE,
pixels.data() + 4 * (dirtyY0 * kTexW + dirtyX0));
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
uploadBytes = w * h * 4;
dirtyX0 = kTexW, dirtyY0 = kTexH, dirtyX1 = 0, dirtyY1 = 0;
}
We met glTextureSubImage2D in chapter 6, where it always replaced the whole image.
Here the rectangle parameters finally do something:
texture:tex.id(), the texture object (DSA: no binding needed).level: 0, the only mipmap level. With mipmaps, a changed level 0 would leave the smaller levels stale until you regenerate them, which is one more reason pixel art has none.xoffset,yoffset: where the rectangle goes in the texture, here (dirtyX0,dirtyY0). Texture rows are numbered in upload order, so y = 0 is the first row we uploaded, which is the top of the shield (our sprites are never flipped).width,height: the size of the rectangle,w×htexels.format,type:GL_RGBA,GL_UNSIGNED_BYTE: how our memory is laid out, as in chapter 6.pixels: where the GL starts reading in our memory: the address of the rectangle's top-left texel inside the big array,pixels.data() + 4 · (dirtyY0 · 88 + dirtyX0).
The rectangle must lie inside the level, or the call fails with GL_INVALID_VALUE and changes nothing; dirtyX1/dirtyY1 are clamped by clearPixel, so ours always does.
When the call returns, the GL has read our memory (or copied it), so the game can change the array again right away.
For the example hit on the second shield, the rectangle is at x = 22 + 7 = 29, y = 7, 6 × 6 texels: 144 bytes instead of for the whole texture.
One impact clears at most a 6 × 8 area, so a single hit never sends more than bytes; the screenshot's HUD shows 96.
The unpack parameters
There's a catch in that call.
By default the GL assumes that the pixels we pass hold exactly the rectangle, row after row: width texels, then immediately the next row.
Our rectangle is a window into an 88-texel-wide array: after the 6 texels of one row come the other 82 texels of the array's row, and the rectangle's next row starts 88 texels (352 bytes) after the previous one.
That's what GL_UNPACK_ROW_LENGTH tells the GL: the length of a row in memory, in pixels, when it's not the width of what we upload.
glPixelStorei(pname, param) sets one of the pixel-store (unpack) parameters, which control how every following upload reads client memory: glTextureSubImage1D/2D/3D, the old glTexImage*, and their relatives.
The ones that matter for 2D uploads:
GL_UNPACK_ROW_LENGTH(default 0): pixels per row in memory; 0 means "the same aswidth".GL_UNPACK_SKIP_PIXELS,GL_UNPACK_SKIP_ROWS(default 0): how many pixels and rows to skip from the pointer before the rectangle starts.GL_UNPACK_ALIGNMENT(default 4; allowed 1, 2, 4, 8): every row starts at a multiple of this many bytes (chapter 6).GL_UNPACK_IMAGE_HEIGHT,GL_UNPACK_SKIP_IMAGES: the same idea one dimension up, for 3D textures and array layers.GL_UNPACK_SWAP_BYTES,GL_UNPACK_LSB_FIRST: old switches for byte order and 1-bit images; leave them alone.
Put together, with the row length (ROW_LENGTH, or width when it's 0) and the alignment, a row in memory is
and row of the rectangle starts at
where is the pixels pointer.
For RGBA8, is always a multiple of 4, so the default alignment changes nothing; with , bytes.
In the example, is 2580 bytes into the array (), the rows start at 2580, 2932, …, 4340, and the GL reads 24 bytes of each: 144 bytes out of a 1784-byte stretch of memory.
Instead of moving the pointer ourselves, we could pass pixels.data() and set GL_UNPACK_SKIP_PIXELS to 29 and GL_UNPACK_SKIP_ROWS to 7: it's the same formula with the offset moved from into the skip terms.
Both are fine; pointer arithmetic means one parameter to set and reset instead of three.
Three mistakes to avoid:
- Forgetting
ROW_LENGTH. The GL then reads contiguous bytes: the first row is right, and the other five rows come from further along the array's row 7. No error, just wrong pixels on screen, while the CPU copy (and so the collisions) is right. Challenge 3 shows what that looks like. - Not resetting it. Pixel-store state belongs to the context, not to a texture. Left at 88, it applies to the next upload of anything, for example a font atlas 512 texels wide, which would then be read with rows 88 pixels apart and come out sheared. Set it, upload, set it back to 0, like
Texture2D::uploaddoes with the alignment. - A bound pixel unpack buffer. If a buffer is bound to
GL_PIXEL_UNPACK_BUFFER, the last argument isn't a pointer but a byte offset into that buffer. We never bind one, but code that streams textures through a PBO does, and then a client pointer passed here is garbage.
The CPU copy is the master
The texture is only a mirror.
The truth is the std::vector<uint8_t> on the CPU: the game logic reads and writes only that, and upload brings the GPU copy up to date once per frame through the dirty rectangle.
Why not keep the shields only in the texture?
Because the collision test needs the pixels now, during the update, and reading a texture back (glGetTextureSubImage) makes the CPU wait until the GPU has finished every command that writes it: a pipeline stall in the middle of the game logic, every step.
The game logic also stays free of GL: Shields::hit and erode would work unchanged in a headless test or on a server.
And the logic runs in fixed steps while drawing happens per frame; the dirty rectangle is the hand-over between the two.
This pattern, CPU master plus GPU mirror updated by dirty regions, is everywhere: destructible terrain, minimaps, fog of war, text caches.
Aliens eat the shields
Once the formation has come down far enough, the aliens walk through the shields and destroy what they touch:
// 防壁まで下りてきた宇宙人は防壁を食べる / aliens that reach the shields eat them
for (const Alien &a : formation.aliens)
if (a.alive && a.box().bottom() > kShieldY) shields->eraseRect(a.box());
void Shields::eraseRect(const Rect &box) {
for (int i = 0; i < kShieldCount; ++i) {
Rect s = bounds(i);
int x0 = std::max(0, static_cast<int>(std::floor(box.left() - s.x)));
int x1 = std::min(kShieldW, static_cast<int>(std::ceil(box.right() - s.x)));
int y0 = std::max(0, static_cast<int>(std::floor(box.top() - s.y)));
int y1 = std::min(kShieldH, static_cast<int>(std::ceil(box.bottom() - s.y)));
for (int y = y0; y < y1; ++y)
for (int x = x0; x < x1; ++x) clearPixel(i * kShieldW + x, y);
}
}
The bottom row starts with its bottom edge at y = 94 and steps down 6 px at a time, so it reaches the shields' top (136) after 8 drops ().
This runs every step, but clearPixel skips pixels that are already empty, so after the first bite an alien standing still uploads nothing.
Drawing the shields is four sprites with sub-UVs, all from the same texture:
void Shields::draw(SpriteBatch &batch, float layer) const {
for (int i = 0; i < kShieldCount; ++i)
batch.draw({.texture = &tex,
.position = topLeft[i],
.size = {kShieldW, kShieldH},
.uv = {static_cast<float>(i) / kShieldCount, 0.0f, 1.0f / kShieldCount, 1.0f},
.layer = layer});
}
Here are the shields at the start of the scripted run and after 900 frames:
28.7 Explosions
An exploding alien is just another frame
In chapter 27 the formation got a real instanced draw: one instance per alien, 16 bytes each, with a per-instance frame index that the vertex shader looks up in a table of sprite-sheet rectangles.
That index pays off now: an explosion is just a different frame.
When an alien is shot it isn't removed; it stops being alive and starts a 0.25 s countdown:
void Formation::kill(Alien &alien) {
alien.alive = false;
alien.dying = kAlienBoomTime;
}
void Formation::updateExplosions(float dt) {
for (Alien &a : aliens) a.dying = std::max(0.0f, a.dying - dt);
}
bool Formation::cleared() const {
return std::none_of(aliens.begin(), aliens.end(), [](const Alien &a) { return a.alive || a.dying > 0.0f; });
}
alive is what the game logic looks at: the march skips the alien at once (so the formation speeds up immediately), it can't shoot, and it can't be hit again.
dying is only for the picture: the scene picks the explosion frame while it runs, alien_boom_0 for the first half and alien_boom_1 for the second (the clip's 2 frames at 8 fps take exactly 0.25 s):
int PlayScene::alienFrame(const Alien &a) const {
if (!a.alive) return boomFrames[a.dying > 0.5f * kAlienBoomTime ? 0 : 1];
return frames[static_cast<int>(a.kind)][a.pose];
}
and the instance list includes the dying aliens:
if (g.instanced) {
std::vector<AlienInstance> list;
for (const Alien &a : formation.aliens)
if (a.alive || a.dying > 0.0f)
list.push_back({a.position, static_cast<std::uint32_t>(alienFrame(a)), packRgba8(kWhite)});
g.formationRenderer.draw(g.world.matrix(), list);
Not one line of FormationRenderer or its shader changes.
That's why the screenshot's HUD says 768 B/frame with 47 aliens alive: 48 instances × 16 B, the 48th being the exploding beetle.
The SpriteBatch path draws the same frames, and the two renderers still give pixel-identical images (checked at that frame).
cleared() waits for the last explosion to finish, so the last alien's explosion isn't cut off by the next wave.
Debris
Ten one-pixel particles in the alien's color fly out of every explosion:
class Particles {
public:
// centreから全方向へcount個。速さはspeedLo〜speedHi(ピクセル毎秒)、寿命は0.3〜0.7秒
// count pieces from centre in all directions, speed speedLo..speedHi px/s, lifetime 0.3..0.7 s
void burst(Vec2 centre, int count, Vec4 color, float speedLo, float speedHi, Rng &rng);
void update(float dt);
void draw(SpriteBatch &batch, float layer = 0.0f) const;
void clear() { items.clear(); }
size_t size() const { return items.size(); }
private:
struct Particle {
Vec2 position, velocity;
float life, lifetime;
Vec4 color;
};
std::vector<Particle> items;
};
void Particles::update(float dt) {
for (Particle &p : items) {
p.position += p.velocity * dt;
p.velocity.y += 60.0f * dt; // 少し落ちる / falls a little
p.velocity = p.velocity * (1.0f - 1.5f * dt); // 空気抵抗のような減速 / slows down, like drag
p.life -= dt;
}
std::erase_if(items, [](const Particle &p) { return p.life <= 0.0f; });
}
void Particles::draw(SpriteBatch &batch, float layer) const {
for (const Particle &p : items) {
Vec4 c = p.color;
c.w *= std::min(1.0f, 2.0f * p.life / p.lifetime); // 後半で消えていく / fades during the second half
batch.drawRect({std::round(p.position.x), std::round(p.position.y), 1.0f, 1.0f}, c, layer);
}
}
It's the smallest particle system that still looks alive: a random direction (Rng::direction) and speed, a little gravity (60 px/s²) so the pieces arc down, drag so they slow down, and alpha that stays at 1 for the first half of the life and then falls linearly to 0.
Positions are rounded to whole pixels, the pixel-art rule.
The particles are part of the simulation (they move in update), but they don't take part in collisions and aren't interpolated: they live for half a second and are 1 px big, so nobody can see the difference.
They're drawn through the SpriteBatch as 1 × 1 white rectangles with a tint, so the whole effect costs no extra draw call.
Impact flares
Every impact that isn't an alien shows the splat sprite for 0.12 s, tinted: green on a shield, pale yellow at the top of the arena or where two bullets meet, orange where an alien bullet hits the ground.
struct Flare {
int frame; // スプライトシートのコマ / sprite sheet frame
Vec2 centre;
float life; // 残り秒 / seconds left
Vec4 color;
};
for (const Flare &f : flares) {
Sprite s = g.sprites.sprite(f.frame, {std::round(f.centre.x), std::round(f.centre.y)}, {0.5f, 0.5f});
s.color = f.color;
b.draw(s);
}
The sprite is drawn with origin (0.5, 0.5), centered on the impact point, and the update counts the life down and removes expired flares with std::erase_if.
These little flashes matter more for the feel of the game than their size suggests: they tell you where your shot ended, even when it hit nothing.
The ship's explosion freezes the march
When the ship is hit, killShip (above) starts a 1.4 s explosion: the 2-frame ship_boom clip looping at 8 fps plus 36 particles in teal and orange.
During that time the scene runs a reduced update:
playerPrevX = playerX;
if (shipDying > 0.0f) {
// 自機の爆発中:隊列も宇宙人の弾も止まる(元のゲームと同じ)。終わったら真ん中に戻るか、ゲームオーバー
// While the ship explodes the formation and the alien fire stop (as in the original). Afterwards the ship comes
// back in the middle, or the game is over
shipBoom.update(dt);
formation.updateExplosions(dt);
updateShot(dt);
shipDying -= dt;
if (shipDying <= 0.0f) {
shipDying = 0.0f;
if (lives > 0) {
playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f);
} else {
gameOver = true;
printf("game over: %d kills\n", kills);
}
}
return;
}
The march, the alien fire and the ship's controls stop, as in the original: the moment of losing a life is a pause, and the player gets a breath before the next round.
Alien explosions and the ship's last bullet still finish (a lucky last shot can still score).
After 1.4 s the ship comes back in the middle, with playerPrevX set too, so the interpolation doesn't slide it in from where it died.
28.8 Lives, invasion and starting over
The rest of update checks how the round ends:
// 自機の高さまで来たら侵略された:残りの自機に関係なくゲームオーバー / reaching the ship's row is an invasion:
// game over whatever lives are left
if (formation.alive() > 0 && formation.bounds().bottom() > kPlayerY) {
printf("invaded\n");
lives = 1;
killShip();
return;
}
// 全滅させたら次の隊列(第29章で場面ごと読み直す) / when the formation is wiped out, a new one comes (chapter 29
// reloads the whole scene)
if (formation.cleared()) {
++waves;
printf("wave cleared: %d kills\n", kills);
formation.reset(formationStartX(), kFormationTop);
fireTimer = 1.0f;
}
}
- The ship has 3 lives. Each hit costs one; after the third explosion the game is over.
- If the living aliens' box reaches the ship's row (its bottom below y = 158), it's an invasion: game over, however many lives are left. Setting
lives = 1beforekillShipreuses the explosion and its pause, and the explosion ends in the game-over state. For the bottom row (bottom edge at 94) that's after 11 drops: , while 10 drops reach exactly 154. - A cleared formation simply starts again at the top, with the damaged shields. Chapter 29 turns that into proper waves.
The game-over state keeps the scene alive (explosions and particles finish, the formation stays where it won) and the UI pass draws a banner over it.
Playing again is one line:
if (gameOver) {
formation.updateExplosions(dt);
// やり直し:この場面を新しい場面と入れ替える(全部が最初の状態に戻る) / play again: replace this scene with a
// new one (everything starts from scratch)
if (in.actionPressed("confirm")) scenes().replace(std::make_unique<PlayScene>(g));
return;
}
Restarting by replacing the scene is the simplest reset there is.
There's no reset() function that must remember to clear every member (and that someone forgets to update when a new member is added): the new PlayScene is constructed from scratch, with full lives, a new formation and new, untouched shields with their own texture.
The old scene, including its shield texture, is destroyed by the SceneManager after the update, when nothing uses it any more (chapter 26 queues scene changes for exactly this reason).
The stars are generated from their own Rng sky(1978), so the sky stays the same; Game::rng lives in Game and continues, so the second game plays differently from the first.
One rough edge is left on purpose: Space is both fire and confirm, so if you're still hammering Space when the game ends, it restarts at once.
Chapter 29 adds real title and game-over scenes with a short delay before input counts.
28.9 The update and the draw, in order
With this many interacting parts, the order of one update is part of the design:
- Demo keys (Esc, I, B, = and −).
- Particles and flares, which move in every state.
- Game over: only explosions and waiting for
confirm. - Ship exploding: the reduced update above.
- Move the ship and maybe fire.
formation.update: the march (one alien per step) and the explosion timers.updateShot: the ship's bullet against alien bullets, aliens, shields and the top.alienFire: maybe a new alien bullet.updateAlienShots: alien bullets against the ship, shields and the ground.- Aliens that reach the shields eat them.
- Invasion, then a cleared formation.
Moving the aliens before the ship's bullet means the bullet is tested against where the aliens are now, which is also what is drawn.
A new alien bullet is created after the ship's bullet was tested, so its first test against the ship's bullet happens one step later; that's harmless, since it then sits right below the alien that fired it.
The draw uploads first and then draws back to front in three passes, as in chapter 27:
void PlayScene::draw(float alpha) {
if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor)
// 防壁:変わった所だけGPUへ(描く前に) / shields: send only the changed part to the GPU (before drawing)
shields->upload();
if (shields->lastUploadBytes() > 0) shieldBytes = shields->lastUploadBytes();
// 奥から:背景と防壁(バッチ)→ 隊列(インスタンシングかバッチ)→ 自機・弾・爆発(バッチ)
// Back to front: background and shields (batch) → formation (instanced or batch) → ship, bullets, explosions (batch)
g.batch.begin(g.world.matrix());
drawBackground();
shields->draw(g.batch);
g.batch.end();
drawFormation();
The upload must come before the draw call that samples the shield texture; GL commands execute in order, so the draw sees the new pixels.
Bullets are drawn at prevY + (y − prevY) · alpha, rounded, the chapter 26 interpolation; pause() sets prevY = y for every bullet, like it already did for the ship.
28.10 Running it
Build as usual and run from the project root:
cmake --build build -j8
./build/games/invaders/invaders
The console logs what happens, which is handy when you tune the game:
ship hit: lives 2
ship hit: lives 1
ship hit: lives 0
game over: 22 kills
Platform notes:
- Windows (Visual Studio): choose
invadersas the startup item; the executable isbuild\games\invaders\Debug\invaders.exe, and the working directory is already the project root (chapter 25). The console window shows the log above. - Linux, FreeBSD: run the binary from the project root as shown, or the game can't find
games/invaders/assets/. - All: the keys are GLFW key codes, named by their place on a US keyboard, so on an AZERTY keyboard "W" (fire) is the key labeled Z; the arrow keys and Space work everywhere.
glPixelStorei(GL_UNPACK_ROW_LENGTH, …)is core desktop OpenGL on every driver; only OpenGL ES 2.0 and WebGL 1 lack it (ES 3.0 and WebGL 2 have it), which matters if you ever port this to a browser.
28.11 How real games do it
- The 1978 original had no separate shield data at all: the shields were pixels in the cabinet's 1-bit video memory, and a hit erased an explosion-shaped patch out of that memory, which is where the ragged look comes from. Our CPU array plays the role of that video memory, and the texture is only how we show it.
- Bullet limits are part of the classic design: one player shot, and only a few alien shots at a time, one of which aims at the player's column. Our 3 bullets and the 1-in-3 targeting are in that spirit.
- Object pools: shooters with hundreds of bullets keep them in fixed arrays that are never reallocated, often with a free list, so spawning costs nothing and memory never moves. Our vector of at most 3 never needs that.
- Particles: engines run particle systems with emitters, curves for color and size over the lifetime, and often simulate them on the GPU (compute shaders or transform feedback) when there are tens of thousands. Ours is the same idea, small enough to do on the CPU.
- Destructible pixels: games built around destructible terrain, such as Noita, simulate the world on the CPU in chunks and upload only the chunks that changed: our dirty rectangle, at scale. Large or frequent uploads go through a pixel unpack buffer (
GL_PIXEL_UNPACK_BUFFER), so the copy can happen without stalling the CPU. - Hitboxes: player-favorable boxes are everywhere; bullet-hell shooters make the player's box only a few pixels big, sometimes drawn as a dot, while the sprite is much larger.
- Collision filtering: engines let you say which layers collide with which (Godot's collision layers and masks, Unity's layer collision matrix). Our fixed order of tests per bullet is that matrix written out by hand.
28.12 Summary
- One ship bullet at a time (
std::optional<Bullet>): fire withactionPressed, only when the last shot is gone; aiming matters more than mashing. - Collisions are chapter 26's AABB
overlaps, with boxes chosen in the player's favor (aliens 14 × 10 with outline, ship 13 × 7 without). The ship bullet tests alien bullets, aliens, shields and the top, in that order; alien bullets test the ship, shields and the ground; the first hit wins. - No tunneling without sweeps, because every relative move per step is shorter than the sum of the two boxes' sizes (4 + 6 = 10 < 15, 5.25 < 12, 1.25 < 14); the debug march rate can break that.
- Alien fire: a timer of 0.5 to 1.1 s, at most 3 bullets, the column of a random living alien or (1 in 3) the column above the ship, and the lowest alien of that column fires. Everything random comes from the seeded
Game::rng. - Shields: one 88 × 16
GL_RGBA8texture drawn as four sprites with sub-UVs. The CPU array is the master; hits are tested per pixel in the bullet's direction and erode the 6 × 8 splat shape; a dirty rectangle collects the changes, anddrawuploads only that rectangle (at most 192 bytes per hit instead of 5632). glTextureSubImage2Dwithxoffset/yoffsetreplaces part of a level;GL_UNPACK_ROW_LENGTHsays how long a row is in our memory, so the rectangle can be read straight out of the big array (or useSKIP_PIXELS/SKIP_ROWS). Reset it to 0: pixel-store state is global.- Premultiply by hand whatever you upload yourself: the sheet's transparent texels carry bleed colors that the premultiplied blend would add.
- Explosions: a dead alien stays in the instance list for 0.25 s with an explosion frame (no renderer changes), plus 10 debris pixels; impact flares; the ship's 1.4 s explosion freezes the march and clears the alien bullets.
- Game over after 3 lives or an invasion; restarting replaces the scene with a fresh one.
28.13 Challenges
- ★ Tunneling arithmetic: if the alien bullets fell at 600 px/s instead of 75, could the ship's bullet (240 px/s, 5 px) pass through one without a hit? What's the fastest the alien bullets could fall before they might skip the ship's 7 px tall box? You should find 4 + 10 = 14 > 12, so yes, and that they must stay below 7 + 7 = 14 px per step, 840 px/s.
- ★ Allow two ship bullets at once: make
shotastd::vector<Bullet>, fire when it holds fewer than 2, and runupdateShot's tests for each bullet. Two quick taps should put two yellow boxes on screen (B), and the formation should empty noticeably faster with the same tapping; notice how the game turns from aiming into mashing. - ★★ Remove the two
GL_UNPACK_ROW_LENGTHlines fromShields::upload. On screen, only the top row of each new hole should appear; the rest of the hole is drawn filled with pixels copied from further along that top row, while bullets fly through it, because the collisions read the CPU copy. Then put the first line back but not the reset, and restart after a game over: nothing breaks, because the only later upload (create's full upload) happens to be 88 texels wide. Explain which upload would break. - ★★ Give
Shieldsone dirty rectangle per shield and upload up to four rectangles per frame. Hit the first and the fourth shield in the same frame at the same height (for example two 6 × 6 rectangles at rows 7 to 12 and columns 7 to 12 of each shield): one shared rectangle would be 72 × 6 texels, 1728 bytes, while two separate ones are 288 bytes. Make the HUD show the sum. - ★★ Ragged erosion: instead of
kSplat, clear each pixel of a disc of radius 3 around the hit with probability 0.6 (g.rng.chance(0.6f)). The holes should look organic and still be identical on every run with the same input. Then think about what happens if the hit pixel itself survives, and fix it so that it's always cleared. - ★★★ Pixel-perfect alien hits: cut every alien frame out of the sheet with
loadSpriteImageand, after the AABB test succeeds, test the bullet's box against the alpha of the alien's current frame (asShields::hitdoes). Shots through the gaps between a beetle's legs and horns should now miss, and the B boxes no longer tell the whole story. Which test is the broad phase and which the narrow phase now? - ★★★ Keep the shields only on the GPU: remove the CPU array, erode by uploading the splat cells with
glTextureSubImage2D, and do the hit test by reading the pixels under the bullet back withglGetTextureSubImage. It still works, but timeupdateShotwithstd::chrono: every read-back waits for the GPU to finish its queued work. Explain why the frame time gets worse the more the GPU has to do, and why the CPU master copy avoids that.
ファイル: a/games/invaders/CMakeLists.txt | b/games/invaders/CMakeLists.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -5,7 +5,9 @@ add_executable(invaders | |||
| 5 | src/main.cc | 5 | src/main.cc |
| 6 | src/play_scene.cc | 6 | src/play_scene.cc |
| 7 | src/formation.cc | 7 | src/formation.cc |
| 8 | src/formation_renderer.cc) | 8 | src/formation_renderer.cc |
| 9 | src/shields.cc | ||
| 10 | src/effects.cc) | ||
| 9 | target_include_directories(invaders PRIVATE src) | 11 | target_include_directories(invaders PRIVATE src) |
| 10 | target_link_libraries(invaders PRIVATE engine) | 12 | target_link_libraries(invaders PRIVATE engine) |
| 11 | enable_warnings(invaders) | 13 | enable_warnings(invaders) |
ファイル: a/games/invaders/README.md | b/games/invaders/README.md
| 前 | 新 | ||
|---|---|---|---|
| @@ -13,8 +13,11 @@ is already the project root)。 | |||
| 13 | | キー / Key | | | 13 | | キー / Key | | |
| 14 | |---|---| | 14 | |---|---| |
| 15 | | ← → / A D | 移動 / move | | 15 | | ← → / A D | 移動 / move | |
| 16 | | Space / ↑ / W | 撃つ / fire | | ||
| 16 | | I | 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch | | 17 | | I | 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch | |
| 18 | | B | 当たり判定の箱 / collision boxes | | ||
| 17 | | = / - | 行進を速く・遅く / march faster / slower | | 19 | | = / - | 行進を速く・遅く / march faster / slower | |
| 20 | | Space / Enter | ゲームオーバーの後:もう一度 / after game over: play again | | ||
| 18 | | Esc | 終了 / quit | | 21 | | Esc | 終了 / quit | |
| 19 | 22 | ||
| 20 | ## ファイル / Files | 23 | ## ファイル / Files |
| @@ -23,4 +26,6 @@ is already the project root)。 | |||
| 23 | * `src/play_scene.cc` 遊ぶ場面 / the play scene | 26 | * `src/play_scene.cc` 遊ぶ場面 / the play scene |
| 24 | * `src/formation.hh/.cc` 隊列と行進(GLなし) / the formation and its march (no GL) | 27 | * `src/formation.hh/.cc` 隊列と行進(GLなし) / the formation and its march (no GL) |
| 25 | * `src/formation_renderer.hh/.cc`, `shaders/formation.vert` インスタンシングで隊列を描く / instanced formation drawing | 28 | * `src/formation_renderer.hh/.cc`, `shaders/formation.vert` インスタンシングで隊列を描く / instanced formation drawing |
| 29 | * `src/shields.hh/.cc` 削れる防壁(CPUのピクセル+glTextureSubImage2D) / eroding shields (CPU pixels + glTextureSubImage2D) | ||
| 30 | * `src/effects.hh/.cc` 破片と着弾 / debris particles and impact flares | ||
| 26 | * `assets/` 絵(作者の自作スクリプトで生成。スクリプトはダウンロードに含まれない) / art (generated by the author's own script, not part of the download) | 31 | * `assets/` 絵(作者の自作スクリプトで生成。スクリプトはダウンロードに含まれない) / art (generated by the author's own script, not part of the download) |
ファイル: /dev/null | b/games/invaders/src/effects.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,29 @@ | |||
| 1 | #include "effects.hh" | ||
| 2 | |||
| 3 | #include <algorithm> | ||
| 4 | #include <cmath> | ||
| 5 | |||
| 6 | void Particles::burst(Vec2 centre, int count, Vec4 color, float speedLo, float speedHi, Rng &rng) { | ||
| 7 | for (int i = 0; i < count; ++i) { | ||
| 8 | float life = rng.range(0.3f, 0.7f); | ||
| 9 | items.push_back({centre, rng.direction() * rng.range(speedLo, speedHi), life, life, color}); | ||
| 10 | } | ||
| 11 | } | ||
| 12 | |||
| 13 | void Particles::update(float dt) { | ||
| 14 | for (Particle &p : items) { | ||
| 15 | p.position += p.velocity * dt; | ||
| 16 | p.velocity.y += 60.0f * dt; // 少し落ちる / falls a little | ||
| 17 | p.velocity = p.velocity * (1.0f - 1.5f * dt); // 空気抵抗のような減速 / slows down, like drag | ||
| 18 | p.life -= dt; | ||
| 19 | } | ||
| 20 | std::erase_if(items, [](const Particle &p) { return p.life <= 0.0f; }); | ||
| 21 | } | ||
| 22 | |||
| 23 | void Particles::draw(SpriteBatch &batch, float layer) const { | ||
| 24 | for (const Particle &p : items) { | ||
| 25 | Vec4 c = p.color; | ||
| 26 | c.w *= std::min(1.0f, 2.0f * p.life / p.lifetime); // 後半で消えていく / fades during the second half | ||
| 27 | batch.drawRect({std::round(p.position.x), std::round(p.position.y), 1.0f, 1.0f}, c, layer); | ||
| 28 | } | ||
| 29 | } | ||
ファイル: /dev/null | b/games/invaders/src/effects.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,36 @@ | |||
| 1 | // 爆発の飾り(第28章):飛び散るピクセル(パーティクル)と、短く見せるスプライト(着弾など) | ||
| 2 | // Explosion dressing (chapter 28): flying pixels (particles) and sprites shown for a moment (impacts and such) | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include "engine/rng.hh" | ||
| 6 | #include "engine/sprite_batch.hh" | ||
| 7 | |||
| 8 | #include <vector> | ||
| 9 | |||
| 10 | // 1ピクセルの破片。固定ステップで動き、だんだん消える / one-pixel debris: moves in the fixed step and fades out | ||
| 11 | class Particles { | ||
| 12 | public: | ||
| 13 | // centreから全方向へcount個。速さはspeedLo〜speedHi(ピクセル毎秒)、寿命は0.3〜0.7秒 | ||
| 14 | // count pieces from centre in all directions, speed speedLo..speedHi px/s, lifetime 0.3..0.7 s | ||
| 15 | void burst(Vec2 centre, int count, Vec4 color, float speedLo, float speedHi, Rng &rng); | ||
| 16 | void update(float dt); | ||
| 17 | void draw(SpriteBatch &batch, float layer = 0.0f) const; | ||
| 18 | void clear() { items.clear(); } | ||
| 19 | size_t size() const { return items.size(); } | ||
| 20 | |||
| 21 | private: | ||
| 22 | struct Particle { | ||
| 23 | Vec2 position, velocity; | ||
| 24 | float life, lifetime; | ||
| 25 | Vec4 color; | ||
| 26 | }; | ||
| 27 | std::vector<Particle> items; | ||
| 28 | }; | ||
| 29 | |||
| 30 | // 一コマのスプライトを少しの間だけ見せる(着弾の「パッ」) / shows one sprite frame for a moment (the impact "pop") | ||
| 31 | struct Flare { | ||
| 32 | int frame; // スプライトシートのコマ / sprite sheet frame | ||
| 33 | Vec2 centre; | ||
| 34 | float life; // 残り秒 / seconds left | ||
| 35 | Vec4 color; | ||
| 36 | }; | ||
ファイル: a/games/invaders/src/formation.cc | b/games/invaders/src/formation.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -21,6 +21,26 @@ void Formation::reset(float left, float top) { | |||
| 21 | budget = 0.0f; | 21 | budget = 0.0f; |
| 22 | } | 22 | } |
| 23 | 23 | ||
| 24 | void Formation::kill(Alien &alien) { | ||
| 25 | alien.alive = false; | ||
| 26 | alien.dying = kAlienBoomTime; | ||
| 27 | } | ||
| 28 | |||
| 29 | void Formation::updateExplosions(float dt) { | ||
| 30 | for (Alien &a : aliens) a.dying = std::max(0.0f, a.dying - dt); | ||
| 31 | } | ||
| 32 | |||
| 33 | bool Formation::cleared() const { | ||
| 34 | return std::none_of(aliens.begin(), aliens.end(), [](const Alien &a) { return a.alive || a.dying > 0.0f; }); | ||
| 35 | } | ||
| 36 | |||
| 37 | const Alien *Formation::lowestInColumn(int column) const { | ||
| 38 | const Alien *lowest = nullptr; | ||
| 39 | for (const Alien &a : aliens) | ||
| 40 | if (a.alive && a.column == column && (!lowest || a.position.y > lowest->position.y)) lowest = &a; | ||
| 41 | return lowest; | ||
| 42 | } | ||
| 43 | |||
| 24 | int Formation::alive() const { | 44 | int Formation::alive() const { |
| 25 | return static_cast<int>(std::count_if(aliens.begin(), aliens.end(), [](const Alien &a) { return a.alive; })); | 45 | return static_cast<int>(std::count_if(aliens.begin(), aliens.end(), [](const Alien &a) { return a.alive; })); |
| 26 | } | 46 | } |
| @@ -42,6 +62,7 @@ Rect Formation::bounds() const { | |||
| 42 | } | 62 | } |
| 43 | 63 | ||
| 44 | void Formation::update(float dt) { | 64 | void Formation::update(float dt) { |
| 65 | updateExplosions(dt); | ||
| 45 | if (alive() == 0) return; | 66 | if (alive() == 0) return; |
| 46 | // 1ステップ(1/60秒)にrate/60匹。予算は浮動小数点数の和なので少し許す(60 × (1/60)は丁度1.0fだが、 | 67 | // 1ステップ(1/60秒)にrate/60匹。予算は浮動小数点数の和なので少し許す(60 × (1/60)は丁度1.0fだが、 |
| 47 | // 1/50秒のステップでは5回目の更新の予算が2ではなく1.99999964になる) | 68 | // 1/50秒のステップでは5回目の更新の予算が2ではなく1.99999964になる) |
ファイル: a/games/invaders/src/formation.hh | b/games/invaders/src/formation.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -16,12 +16,16 @@ struct Alien { | |||
| 16 | Vec2 position; // 左上、整数のピクセル / top left, whole pixels | 16 | Vec2 position; // 左上、整数のピクセル / top left, whole pixels |
| 17 | int pose = 0; // 0か1:動くたびに入れ替わる(足踏み) / 0 or 1: flips every time it moves (the walk) | 17 | int pose = 0; // 0か1:動くたびに入れ替わる(足踏み) / 0 or 1: flips every time it moves (the walk) |
| 18 | bool alive = true; | 18 | bool alive = true; |
| 19 | float dying = 0.0f; // 爆発の残り時間(第28章):死んだ後もしばらく爆発のコマで残る / explosion time left | ||
| 20 | // (chapter 28): a dead alien stays on screen as an explosion for a moment | ||
| 19 | Rect box() const; // 当たり判定 = 絵の枠 / the collision box = the sprite cell | 21 | Rect box() const; // 当たり判定 = 絵の枠 / the collision box = the sprite cell |
| 20 | }; | 22 | }; |
| 21 | 23 | ||
| 22 | constexpr int kColumns = 11, kRows = 5; | 24 | constexpr int kColumns = 11, kRows = 5; |
| 23 | constexpr Vec2 kAlienSize = {14.0f, 10.0f}; // スプライトの枠 / the sprite cell | 25 | constexpr Vec2 kAlienSize = {14.0f, 10.0f}; // スプライトの枠 / the sprite cell |
| 24 | constexpr float kColumnSpacing = 16.0f, kRowSpacing = 14.0f; | 26 | constexpr float kColumnSpacing = 16.0f, kRowSpacing = 14.0f; |
| 27 | constexpr float kAlienBoomTime = 0.25f; // 爆発のコマを見せる時間(alien_boomのクリップ:2コマ、8 fps) / how long the | ||
| 28 | // explosion shows (the alien_boom clip: 2 frames at 8 fps) | ||
| 25 | 29 | ||
| 26 | class Formation { | 30 | class Formation { |
| 27 | public: | 31 | public: |
| @@ -35,8 +39,17 @@ public: | |||
| 35 | // the sooner each one's turn comes around = the formation speeds up by itself | 39 | // the sooner each one's turn comes around = the formation speeds up by itself |
| 36 | void update(float dt); | 40 | void update(float dt); |
| 37 | 41 | ||
| 42 | // 撃たれた:行進から外れ、爆発のコマになる / shot: leaves the march and turns into an explosion | ||
| 43 | void kill(Alien &alien); | ||
| 44 | // 爆発の時計だけ進める(自機の爆発中は行進が止まるが、宇宙人の爆発は進む) / advances only the explosion timers (the | ||
| 45 | // march stops while the ship explodes, alien explosions go on) | ||
| 46 | void updateExplosions(float dt); | ||
| 47 | |||
| 38 | int alive() const; | 48 | int alive() const; |
| 49 | bool cleared() const; // 全滅して、爆発も終わった / everyone is dead and the explosions are over | ||
| 39 | Rect bounds() const; // 生きている宇宙人を囲む箱(全滅なら大きさ0) / box around the living aliens (empty if none) | 50 | Rect bounds() const; // 生きている宇宙人を囲む箱(全滅なら大きさ0) / box around the living aliens (empty if none) |
| 51 | // その列で一番下の生きている宇宙人(撃つのはこの宇宙人) / the lowest living alien of a column (it does the shooting) | ||
| 52 | const Alien *lowestInColumn(int column) const; | ||
| 40 | 53 | ||
| 41 | std::vector<Alien> aliens; // 行進の順番:下の行の左から右へ、それから上の行 / march order: bottom row left to right, | 54 | std::vector<Alien> aliens; // 行進の順番:下の行の左から右へ、それから上の行 / march order: bottom row left to right, |
| 42 | // then the row above | 55 | // then the row above |
ファイル: a/games/invaders/src/game.hh | b/games/invaders/src/game.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -2,9 +2,12 @@ | |||
| 2 | // Invaders: the data every scene shares, the screen layout, the scenes | 2 | // Invaders: the data every scene shares, the screen layout, the scenes |
| 3 | #pragma once | 3 | #pragma once |
| 4 | 4 | ||
| 5 | #include "effects.hh" | ||
| 5 | #include "formation.hh" | 6 | #include "formation.hh" |
| 6 | #include "formation_renderer.hh" | 7 | #include "formation_renderer.hh" |
| 8 | #include "shields.hh" | ||
| 7 | 9 | ||
| 10 | #include "engine/animation.hh" | ||
| 8 | #include "engine/camera2d.hh" | 11 | #include "engine/camera2d.hh" |
| 9 | #include "engine/font.hh" | 12 | #include "engine/font.hh" |
| 10 | #include "engine/game_loop.hh" | 13 | #include "engine/game_loop.hh" |
| @@ -14,6 +17,7 @@ | |||
| 14 | #include "engine/sprite_batch.hh" | 17 | #include "engine/sprite_batch.hh" |
| 15 | #include "engine/sprite_sheet.hh" | 18 | #include "engine/sprite_sheet.hh" |
| 16 | 19 | ||
| 20 | #include <optional> | ||
| 17 | #include <vector> | 21 | #include <vector> |
| 18 | 22 | ||
| 19 | // 仮想解像度320 × 180(ウィンドウ1280 × 720で4倍)。真ん中の224ピクセル幅が戦場、左右48ピクセルは脇の板 | 23 | // 仮想解像度320 × 180(ウィンドウ1280 × 720で4倍)。真ん中の224ピクセル幅が戦場、左右48ピクセルは脇の板 |
| @@ -22,9 +26,14 @@ | |||
| 22 | constexpr Vec2 kView = {320.0f, 180.0f}; | 26 | constexpr Vec2 kView = {320.0f, 180.0f}; |
| 23 | constexpr float kArenaLeft = 48.0f, kArenaRight = 272.0f; | 27 | constexpr float kArenaLeft = 48.0f, kArenaRight = 272.0f; |
| 24 | constexpr float kFormationTop = 28.0f; // 最初の隊列の一番上 / the first formation's top row | 28 | constexpr float kFormationTop = 28.0f; // 最初の隊列の一番上 / the first formation's top row |
| 29 | constexpr float kShieldY = 136.0f; // 防壁の上端 / the shields' top | ||
| 25 | constexpr float kPlayerY = 158.0f; // 自機の上端 / the ship's top | 30 | constexpr float kPlayerY = 158.0f; // 自機の上端 / the ship's top |
| 26 | constexpr float kGroundY = 170.0f; // 地面の線 / the ground line | 31 | constexpr float kGroundY = 170.0f; // 地面の線 / the ground line |
| 27 | constexpr float kPlayerSpeed = 60.0f; // ピクセル毎秒(1ステップ1ピクセル) / pixels per second (1 px per step) | 32 | constexpr float kPlayerSpeed = 60.0f; // ピクセル毎秒(1ステップ1ピクセル) / pixels per second (1 px per step) |
| 33 | constexpr float kShotSpeed = 240.0f; // 自機の弾:1ステップ4ピクセル / the ship's bullet: 4 px per step | ||
| 34 | constexpr float kAlienShotSpeed = 75.0f; // 宇宙人の弾 / alien bullets | ||
| 35 | constexpr int kMaxAlienShots = 3; | ||
| 36 | constexpr int kStartLives = 3; | ||
| 28 | 37 | ||
| 29 | // ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference | 38 | // ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference |
| 30 | struct Game { | 39 | struct Game { |
| @@ -35,14 +44,17 @@ struct Game { | |||
| 35 | FormationRenderer &formationRenderer; | 44 | FormationRenderer &formationRenderer; |
| 36 | const Font &ui; // mono16:画面の解像度の文字 / text at screen resolution | 45 | const Font &ui; // mono16:画面の解像度の文字 / text at screen resolution |
| 37 | const SpriteSheet &sprites; // games/invaders/assets/sprites.atlas | 46 | const SpriteSheet &sprites; // games/invaders/assets/sprites.atlas |
| 47 | const Image &shieldArt; // 防壁の絵(CPU側、削る元) / the shield art (CPU side, what gets eroded) | ||
| 38 | Camera2D world; // 320 × 180のキャンバス / the 320 × 180 canvas | 48 | Camera2D world; // 320 × 180のキャンバス / the 320 × 180 canvas |
| 39 | Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI | 49 | Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI |
| 40 | Viewport uiViewport; | 50 | Viewport uiViewport; |
| 41 | Rng rng{27}; | 51 | Rng rng{27}; |
| 42 | bool instanced = true; // 隊列をインスタンシングで(I) / draw the formation instanced (I) | 52 | bool instanced = true; // 隊列をインスタンシングで(I) / draw the formation instanced (I) |
| 53 | bool showBoxes = false; // 当たり判定の箱(B) / collision boxes (B) | ||
| 43 | }; | 54 | }; |
| 44 | 55 | ||
| 45 | // 遊ぶ場面:自機と行進する隊列 / the play scene: the ship and the marching formation | 56 | // 遊ぶ場面:自機、行進する隊列、弾、防壁、爆発 / the play scene: the ship, the marching formation, bullets, |
| 57 | // shields, explosions | ||
| 46 | class PlayScene : public Scene { | 58 | class PlayScene : public Scene { |
| 47 | public: | 59 | public: |
| 48 | explicit PlayScene(Game &game); | 60 | explicit PlayScene(Game &game); |
| @@ -56,18 +68,44 @@ private: | |||
| 56 | Vec2 position; | 68 | Vec2 position; |
| 57 | float phase; | 69 | float phase; |
| 58 | }; | 70 | }; |
| 71 | // 弾:当たり判定の箱と、補間用の前のステップのy / a bullet: its collision box and last step's y (interpolation) | ||
| 72 | struct Bullet { | ||
| 73 | Rect box; | ||
| 74 | float prevY; | ||
| 75 | Animator anim; // 宇宙人の弾は4コマのクリップ / alien bullets play a 4-frame clip | ||
| 76 | }; | ||
| 59 | int alienFrame(const Alien &a) const; | 77 | int alienFrame(const Alien &a) const; |
| 78 | Rect shipBox() const; | ||
| 79 | void fire(); | ||
| 80 | void alienFire(float dt); | ||
| 81 | void updateShot(float dt); | ||
| 82 | void updateAlienShots(float dt); | ||
| 83 | void killShip(); | ||
| 84 | void flare(Vec2 centre, Vec4 color, float life = 0.12f); | ||
| 60 | void drawBackground(); | 85 | void drawBackground(); |
| 61 | void drawFormation(); | 86 | void drawFormation(); |
| 87 | void drawBoxes(); | ||
| 62 | 88 | ||
| 63 | Game &g; | 89 | Game &g; |
| 64 | Formation formation; | 90 | Formation formation; |
| 91 | std::optional<Shields> shields; | ||
| 65 | float playerX = 0.0f, playerPrevX = 0.0f; // 自機の左端(補間用に前のステップも) / the ship's left edge (+ the | 92 | float playerX = 0.0f, playerPrevX = 0.0f; // 自機の左端(補間用に前のステップも) / the ship's left edge (+ the |
| 66 | // previous step's, for interpolation) | 93 | // previous step's, for interpolation) |
| 94 | std::optional<Bullet> shot; // 自機の弾は一度に一発(元のゲームと同じ) / one ship bullet at a time | ||
| 95 | // (as in the original) | ||
| 96 | std::vector<Bullet> alienShots; | ||
| 97 | float fireTimer = 1.0f; // 宇宙人が次に撃つまで / until the aliens fire next | ||
| 98 | float shipDying = 0.0f; // 自機の爆発の残り時間(> 0 の間は隊列も止まる) / ship explosion time | ||
| 99 | // left (the march stops meanwhile) | ||
| 100 | Animator shipBoom; | ||
| 101 | Particles particles; | ||
| 102 | std::vector<Flare> flares; | ||
| 67 | std::vector<Star> stars; | 103 | std::vector<Star> stars; |
| 68 | float time = 0.0f; | 104 | float time = 0.0f; |
| 69 | int frames[3][2] = {}; // 種類 × 足踏み → シートのコマ / kind × pose → sheet frame | 105 | int frames[3][2] = {}; // 種類 × 足踏み → シートのコマ / kind × pose → sheet frame |
| 70 | int shipFrame = 0; | 106 | int shipFrame = 0, shotFrame = 0, splatFrame = 0, boomFrames[2] = {}; |
| 71 | int formationDrawCalls = 0, formationBytes = 0; | 107 | const AnimationClip *zigClip = nullptr, *boltClip = nullptr, *shipBoomClip = nullptr; |
| 72 | int landings = 0; | 108 | int formationDrawCalls = 0, formationBytes = 0, shieldBytes = 0; |
| 109 | int lives = kStartLives, kills = 0, shotsFired = 0, waves = 1; | ||
| 110 | bool gameOver = false; | ||
| 73 | }; | 111 | }; |
ファイル: a/games/invaders/src/main.cc | b/games/invaders/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,9 +1,11 @@ | |||
| 1 | // Invaders 第1部(第27章):自機、インスタンシングで描く宇宙人の隊列、行進、操作 | 1 | // Invaders 第2部(第28章):弾、AABBの当たり判定、宇宙人の弾、削れる防壁、爆発 |
| 2 | // Invaders part 1 (chapter 27): the player's ship, the alien formation drawn with instancing, the march, the controls | 2 | // Invaders part 2 (chapter 28): bullets, AABB collisions, alien bullets, shields that erode, explosions |
| 3 | // | 3 | // |
| 4 | // 操作 / Controls: | 4 | // 操作 / Controls: |
| 5 | // ← → / A D 移動 / move | 5 | // ← → / A D 移動 / move |
| 6 | // Space / ↑ 撃つ / fire | ||
| 6 | // I 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch | 7 | // I 隊列の描き方:インスタンシング ⇔ SpriteBatch / formation: instancing ⇔ SpriteBatch |
| 8 | // B 当たり判定の箱 / collision boxes | ||
| 7 | // = / - 行進を速く・遅く / march faster / slower | 9 | // = / - 行進を速く・遅く / march faster / slower |
| 8 | // Esc 終了 / quit | 10 | // Esc 終了 / quit |
| 9 | #include "game.hh" | 11 | #include "game.hh" |
| @@ -23,19 +25,24 @@ int main() { | |||
| 23 | std::optional<SpriteSheet> sprites = SpriteSheet::loadAtlas("games/invaders/assets/sprites.atlas"); | 25 | std::optional<SpriteSheet> sprites = SpriteSheet::loadAtlas("games/invaders/assets/sprites.atlas"); |
| 24 | if (!batch || !ui || !sprites) return 1; | 26 | if (!batch || !ui || !sprites) return 1; |
| 25 | std::optional<FormationRenderer> formationRenderer = FormationRenderer::create(*sprites); | 27 | std::optional<FormationRenderer> formationRenderer = FormationRenderer::create(*sprites); |
| 26 | if (!formationRenderer) return 1; | 28 | // 防壁の絵はCPUにも要る(削るため):同じPNGをもう一度デコードして切り出す / the shield art is needed on the CPU |
| 29 | // too (to erode it): decode the same PNG again and cut it out | ||
| 30 | std::optional<Image> shieldArt = loadSpriteImage("games/invaders/assets/sprites.png", *sprites, "shield"); | ||
| 31 | if (!formationRenderer || !shieldArt) return 1; | ||
| 27 | 32 | ||
| 28 | // 行動に名前を付ける(キーを変えるならここだけ) / name the actions (to change keys, edit only this) | 33 | // 行動に名前を付ける(キーを変えるならここだけ) / name the actions (to change keys, edit only this) |
| 29 | Input input; | 34 | Input input; |
| 30 | input.attach(window); | 35 | input.attach(window); |
| 31 | input.bind("left", {InputBinding::key(GLFW_KEY_LEFT), InputBinding::key(GLFW_KEY_A)}); | 36 | input.bind("left", {InputBinding::key(GLFW_KEY_LEFT), InputBinding::key(GLFW_KEY_A)}); |
| 32 | input.bind("right", {InputBinding::key(GLFW_KEY_RIGHT), InputBinding::key(GLFW_KEY_D)}); | 37 | input.bind("right", {InputBinding::key(GLFW_KEY_RIGHT), InputBinding::key(GLFW_KEY_D)}); |
| 38 | input.bind("fire", {InputBinding::key(GLFW_KEY_SPACE), InputBinding::key(GLFW_KEY_UP), InputBinding::key(GLFW_KEY_W)}); | ||
| 39 | input.bind("confirm", {InputBinding::key(GLFW_KEY_SPACE), InputBinding::key(GLFW_KEY_ENTER)}); | ||
| 33 | 40 | ||
| 34 | // 固定ステップ:ゲームの動きは1/60秒ごとの更新の中だけ / fixed step: the game only changes in the 1/60 s updates | 41 | // 固定ステップ:ゲームの動きは1/60秒ごとの更新の中だけ / fixed step: the game only changes in the 1/60 s updates |
| 35 | GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); | 42 | GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); |
| 36 | PixelCanvas canvas(static_cast<int>(kView.x), static_cast<int>(kView.y)); | 43 | PixelCanvas canvas(static_cast<int>(kView.x), static_cast<int>(kView.y)); |
| 37 | Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .formationRenderer = *formationRenderer, | 44 | Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .formationRenderer = *formationRenderer, |
| 38 | .ui = *ui, .sprites = *sprites, .world = Camera2D::screen(kView), | 45 | .ui = *ui, .sprites = *sprites, .shieldArt = *shieldArt, .world = Camera2D::screen(kView), |
| 39 | .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}}; | 46 | .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}}; |
| 40 | 47 | ||
| 41 | SceneManager scenes; | 48 | SceneManager scenes; |
ファイル: a/games/invaders/src/play_scene.cc | b/games/invaders/src/play_scene.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,22 +1,49 @@ | |||
| 1 | // 遊ぶ場面(第27章):自機の操作、隊列の行進、隊列の描き方の比較(インスタンシング ⇔ SpriteBatch) | 1 | // 遊ぶ場面(第28章):自機の弾と宇宙人の弾、AABBの当たり判定、削れる防壁、爆発 |
| 2 | // The play scene (chapter 27): steering the ship, the formation's march, two ways to draw the formation (instancing | 2 | // The play scene (chapter 28): the ship's and the aliens' bullets, AABB collisions, eroding shields, explosions |
| 3 | // ⇔ SpriteBatch) | ||
| 4 | #include "game.hh" | 3 | #include "game.hh" |
| 5 | 4 | ||
| 5 | #include "engine/collision.hh" | ||
| 6 | |||
| 6 | #include <algorithm> | 7 | #include <algorithm> |
| 7 | #include <cmath> | 8 | #include <cmath> |
| 8 | #include <cstdio> | 9 | #include <cstdio> |
| 10 | #include <memory> | ||
| 11 | |||
| 12 | // 宇宙人の色(破片の色) / alien colors (for the debris) | ||
| 13 | static const Vec4 kAlienColors[3] = {hexColor(0xf06292ff), hexColor(0x5dbce6ff), hexColor(0x9adc48ff)}; | ||
| 14 | constexpr float kFormationWidth = (kColumns - 1) * kColumnSpacing + kAlienSize.x; // 174 | ||
| 15 | constexpr float kShipBoomTime = 1.4f; | ||
| 16 | |||
| 17 | static float formationStartX() { return std::round(0.5f * (kArenaLeft + kArenaRight - kFormationWidth)); } | ||
| 9 | 18 | ||
| 10 | PlayScene::PlayScene(Game &game) : g(game) { | 19 | PlayScene::PlayScene(Game &game) : g(game) { |
| 11 | const char *names[3][2] = {{"jelly_0", "jelly_1"}, {"beetle_0", "beetle_1"}, {"blob_0", "blob_1"}}; | 20 | const char *names[3][2] = {{"jelly_0", "jelly_1"}, {"beetle_0", "beetle_1"}, {"blob_0", "blob_1"}}; |
| 12 | for (int k = 0; k < 3; ++k) | 21 | for (int k = 0; k < 3; ++k) |
| 13 | for (int p = 0; p < 2; ++p) frames[k][p] = g.sprites.find(names[k][p]); | 22 | for (int p = 0; p < 2; ++p) frames[k][p] = g.sprites.find(names[k][p]); |
| 14 | shipFrame = g.sprites.find("ship"); | 23 | shipFrame = g.sprites.find("ship"); |
| 24 | shotFrame = g.sprites.find("shot"); | ||
| 25 | splatFrame = g.sprites.find("splat"); | ||
| 26 | boomFrames[0] = g.sprites.find("alien_boom_0"); | ||
| 27 | boomFrames[1] = g.sprites.find("alien_boom_1"); | ||
| 28 | zigClip = g.sprites.clip("zig"); | ||
| 29 | boltClip = g.sprites.clip("bolt"); | ||
| 30 | shipBoomClip = g.sprites.clip("ship_boom"); | ||
| 15 | 31 | ||
| 16 | // 隊列:幅 = 10 × 16 + 14 = 174ピクセル、戦場の真ん中 / the formation: 10 × 16 + 14 = 174 px wide, centered in the arena | 32 | // 隊列:幅174ピクセル、戦場の真ん中 / the formation: 174 px wide, centered in the arena |
| 17 | formation.minX = kArenaLeft + 2.0f; | 33 | formation.minX = kArenaLeft + 2.0f; |
| 18 | formation.maxX = kArenaRight - 2.0f; | 34 | formation.maxX = kArenaRight - 2.0f; |
| 19 | formation.reset(std::round(0.5f * (kArenaLeft + kArenaRight - 174.0f)), kFormationTop); | 35 | formation.reset(formationStartX(), kFormationTop); |
| 36 | |||
| 37 | // 防壁4つを戦場に等間隔で(中心 76, 132, 188, 244) / four shields evenly across the arena (centers 76, 132, 188, 244) | ||
| 38 | Vec2 shieldPos[kShieldCount]; | ||
| 39 | for (int i = 0; i < kShieldCount; ++i) | ||
| 40 | shieldPos[i] = {kArenaLeft + (kArenaRight - kArenaLeft) * (static_cast<float>(i) + 0.5f) / kShieldCount - kShieldW / 2, | ||
| 41 | kShieldY}; | ||
| 42 | shields = Shields::create(g.shieldArt, shieldPos); | ||
| 43 | if (!shields) { // 防壁が無いと遊べない(理由はcreateが書いた) / no game without shields (create logged why) | ||
| 44 | fprintf(stderr, "防壁を作れないので終了 / cannot create the shields: quitting\n"); | ||
| 45 | g.window.close(); // 防壁を使う関数は何もしない / the functions that use the shields do nothing | ||
| 46 | } | ||
| 20 | 47 | ||
| 21 | playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f); | 48 | playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f); |
| 22 | // 星:自分の種で作るので、場面を作り直しても同じ空 / stars: made with their own seed, so the sky stays the same when | 49 | // 星:自分の種で作るので、場面を作り直しても同じ空 / stars: made with their own seed, so the sky stays the same when |
| @@ -28,11 +55,130 @@ PlayScene::PlayScene(Game &game) : g(game) { | |||
| 28 | } | 55 | } |
| 29 | 56 | ||
| 30 | // 一時停止の間は補間しない(第26章) / no interpolation while paused (chapter 26) | 57 | // 一時停止の間は補間しない(第26章) / no interpolation while paused (chapter 26) |
| 31 | void PlayScene::pause() { playerPrevX = playerX; } | 58 | void PlayScene::pause() { |
| 59 | playerPrevX = playerX; | ||
| 60 | if (shot) shot->prevY = shot->box.y; | ||
| 61 | for (Bullet &b : alienShots) b.prevY = b.box.y; | ||
| 62 | } | ||
| 32 | 63 | ||
| 33 | int PlayScene::alienFrame(const Alien &a) const { return frames[static_cast<int>(a.kind)][a.pose]; } | 64 | int PlayScene::alienFrame(const Alien &a) const { |
| 65 | if (!a.alive) return boomFrames[a.dying > 0.5f * kAlienBoomTime ? 0 : 1]; | ||
| 66 | return frames[static_cast<int>(a.kind)][a.pose]; | ||
| 67 | } | ||
| 68 | |||
| 69 | // 自機の当たり判定:輪郭を除いた船体(13 × 7) / the ship's collision box: the hull without the outline (13 × 7) | ||
| 70 | Rect PlayScene::shipBox() const { return {playerX + 1.0f, kPlayerY + 1.0f, 13.0f, 7.0f}; } | ||
| 71 | |||
| 72 | void PlayScene::flare(Vec2 centre, Vec4 color, float life) { flares.push_back({splatFrame, centre, life, color}); } | ||
| 73 | |||
| 74 | void PlayScene::fire() { | ||
| 75 | // 画面に自機の弾がない時だけ撃てる:連打より狙いが大事(元のゲームの決まり) | ||
| 76 | // Only when no ship bullet is on screen: aiming beats mashing (the original's rule) | ||
| 77 | if (shot || shipDying > 0.0f || gameOver || !g.input.actionPressed("fire")) return; | ||
| 78 | float y = kPlayerY - 4.0f; | ||
| 79 | shot = Bullet{.box = {playerX + 7.0f, y, 1.0f, 5.0f}, .prevY = y, .anim = {}}; | ||
| 80 | ++shotsFired; | ||
| 81 | } | ||
| 82 | |||
| 83 | void PlayScene::killShip() { | ||
| 84 | --lives; | ||
| 85 | shipDying = kShipBoomTime; | ||
| 86 | shipBoom.play(shipBoomClip, true); | ||
| 87 | Vec2 c = shipBox().centre(); | ||
| 88 | particles.burst(c, 24, hexColor(0x4fc0a5ff), 20.0f, 70.0f, g.rng); | ||
| 89 | particles.burst(c, 12, hexColor(0xffa040ff), 30.0f, 90.0f, g.rng); | ||
| 90 | alienShots.clear(); // 元のゲームと同じく、飛んでいる弾は消える / bullets in flight vanish, as in the original | ||
| 91 | printf("ship hit: lives %d\n", lives); | ||
| 92 | } | ||
| 93 | |||
| 94 | void PlayScene::updateShot(float dt) { | ||
| 95 | if (!shot) return; | ||
| 96 | shot->prevY = shot->box.y; | ||
| 97 | shot->box.y -= kShotSpeed * dt; | ||
| 98 | // 1ステップ4ピクセル、弾の長さ5ピクセル:続けて見れば隙間がないので、すり抜けない(第26章のトンネリング)。 | ||
| 99 | // 宇宙人の弾とも:近づく速さは1ステップ5.25ピクセル < 5 + 7 | ||
| 100 | // 4 px per step with a 5 px bullet: consecutive boxes leave no gap, so nothing is skipped (ch26's tunneling). | ||
| 101 | // Against alien bullets too: they close in at 5.25 px per step < 5 + 7 | ||
| 102 | const Rect &box = shot->box; | ||
| 103 | for (size_t i = 0; i < alienShots.size(); ++i) | ||
| 104 | if (overlaps(box, alienShots[i].box)) { | ||
| 105 | flare(box.centre(), hexColor(0xfff4d6ff)); | ||
| 106 | alienShots.erase(alienShots.begin() + static_cast<std::ptrdiff_t>(i)); | ||
| 107 | shot.reset(); | ||
| 108 | return; | ||
| 109 | } | ||
| 110 | for (Alien &a : formation.aliens) | ||
| 111 | if (a.alive && overlaps(box, a.box())) { | ||
| 112 | formation.kill(a); | ||
| 113 | particles.burst(a.box().centre(), 10, kAlienColors[static_cast<int>(a.kind)], 15.0f, 50.0f, g.rng); | ||
| 114 | ++kills; | ||
| 115 | shot.reset(); | ||
| 116 | return; | ||
| 117 | } | ||
| 118 | if (std::optional<Vec2> p = shields->hit(box, true)) { | ||
| 119 | shields->erode(*p, g.rng); | ||
| 120 | flare(*p, hexColor(0x68c454ff)); | ||
| 121 | shot.reset(); | ||
| 122 | return; | ||
| 123 | } | ||
| 124 | if (box.top() < 6.0f) { // 戦場の上の端 / the top of the arena | ||
| 125 | flare({box.x, 6.0f}, hexColor(0xfff4d6ff)); | ||
| 126 | shot.reset(); | ||
| 127 | } | ||
| 128 | } | ||
| 129 | |||
| 130 | void PlayScene::alienFire(float dt) { | ||
| 131 | fireTimer -= dt; | ||
| 132 | if (fireTimer > 0.0f) return; | ||
| 133 | fireTimer = g.rng.range(0.5f, 1.1f); | ||
| 134 | if (static_cast<int>(alienShots.size()) >= kMaxAlienShots) return; | ||
| 135 | // 撃つ列:3回に1回は自機の真上の列、それ以外は生きている宇宙人をランダムに選んでその列。撃つのはその列の一番下 | ||
| 136 | // The firing column: one time in three the column above the ship, otherwise the column of a random living alien. | ||
| 137 | // The lowest alien of that column shoots | ||
| 138 | std::vector<const Alien *> living; | ||
| 139 | for (const Alien &a : formation.aliens) | ||
| 140 | if (a.alive) living.push_back(&a); | ||
| 141 | if (living.empty()) return; | ||
| 142 | int column = living[static_cast<size_t>(g.rng.range(0, static_cast<int>(living.size()) - 1))]->column; | ||
| 143 | if (g.rng.chance(1.0f / 3.0f)) { | ||
| 144 | float shipX = shipBox().centre().x, best = 1e9f; | ||
| 145 | for (const Alien *a : living) | ||
| 146 | if (float d = std::fabs(a->box().centre().x - shipX); d < best) best = d, column = a->column; | ||
| 147 | } | ||
| 148 | const Alien *shooter = formation.lowestInColumn(column); | ||
| 149 | if (!shooter) return; | ||
| 150 | Bullet b{.box = {shooter->position.x + 5.0f, shooter->position.y + kAlienSize.y, 3.0f, 7.0f}, | ||
| 151 | .prevY = shooter->position.y + kAlienSize.y, .anim = {}}; | ||
| 152 | b.anim.play(g.rng.chance(0.5f) ? zigClip : boltClip); | ||
| 153 | alienShots.push_back(b); | ||
| 154 | } | ||
| 155 | |||
| 156 | void PlayScene::updateAlienShots(float dt) { | ||
| 157 | for (size_t i = 0; i < alienShots.size();) { | ||
| 158 | Bullet &b = alienShots[i]; | ||
| 159 | b.prevY = b.box.y; | ||
| 160 | b.box.y += kAlienShotSpeed * dt; | ||
| 161 | b.anim.update(dt); | ||
| 162 | if (shipDying <= 0.0f && overlaps(b.box, shipBox())) { | ||
| 163 | killShip(); // 全部の弾を消す / clears every bullet | ||
| 164 | return; | ||
| 165 | } | ||
| 166 | bool gone = false; | ||
| 167 | if (std::optional<Vec2> p = shields->hit(b.box, false)) { | ||
| 168 | shields->erode(*p, g.rng); | ||
| 169 | flare(*p, hexColor(0x68c454ff)); | ||
| 170 | gone = true; | ||
| 171 | } else if (b.box.bottom() >= kGroundY) { | ||
| 172 | flare({b.box.centre().x, kGroundY - 2.0f}, hexColor(0xffa040ff)); | ||
| 173 | gone = true; | ||
| 174 | } | ||
| 175 | if (gone) alienShots.erase(alienShots.begin() + static_cast<std::ptrdiff_t>(i)); | ||
| 176 | else ++i; | ||
| 177 | } | ||
| 178 | } | ||
| 34 | 179 | ||
| 35 | void PlayScene::update(float dt) { | 180 | void PlayScene::update(float dt) { |
| 181 | if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor) | ||
| 36 | time += dt; | 182 | time += dt; |
| 37 | Input &in = g.input; | 183 | Input &in = g.input; |
| 38 | if (in.pressed(GLFW_KEY_ESCAPE)) { | 184 | if (in.pressed(GLFW_KEY_ESCAPE)) { |
| @@ -43,25 +189,73 @@ void PlayScene::update(float dt) { | |||
| 43 | g.instanced = !g.instanced; | 189 | g.instanced = !g.instanced; |
| 44 | printf("formation: %s\n", g.instanced ? "instanced" : "SpriteBatch"); | 190 | printf("formation: %s\n", g.instanced ? "instanced" : "SpriteBatch"); |
| 45 | } | 191 | } |
| 46 | // 行進の速さを変える(説明用):1秒に動く宇宙人の数を2倍・半分 / change the march speed (for the demo): double or | 192 | if (in.pressed(GLFW_KEY_B)) g.showBoxes = !g.showBoxes; |
| 47 | // halve the number of aliens moved per second | ||
| 48 | if (in.pressed(GLFW_KEY_EQUAL)) formation.rate = std::min(formation.rate * 2.0f, 960.0f); | 193 | if (in.pressed(GLFW_KEY_EQUAL)) formation.rate = std::min(formation.rate * 2.0f, 960.0f); |
| 49 | if (in.pressed(GLFW_KEY_MINUS)) formation.rate = std::max(formation.rate * 0.5f, 15.0f); | 194 | if (in.pressed(GLFW_KEY_MINUS)) formation.rate = std::max(formation.rate * 0.5f, 15.0f); |
| 50 | 195 | ||
| 51 | // 自機:左右の行動の軸で動き、戦場からは出ない / the ship: moves along the left/right action axis, stays inside the | 196 | // 飾りはいつでも動く / the dressing always moves |
| 52 | // arena | 197 | particles.update(dt); |
| 198 | for (Flare &f : flares) f.life -= dt; | ||
| 199 | std::erase_if(flares, [](const Flare &f) { return f.life <= 0.0f; }); | ||
| 200 | |||
| 201 | if (gameOver) { | ||
| 202 | formation.updateExplosions(dt); | ||
| 203 | // やり直し:この場面を新しい場面と入れ替える(全部が最初の状態に戻る) / play again: replace this scene with a | ||
| 204 | // new one (everything starts from scratch) | ||
| 205 | if (in.actionPressed("confirm")) scenes().replace(std::make_unique<PlayScene>(g)); | ||
| 206 | return; | ||
| 207 | } | ||
| 208 | |||
| 53 | playerPrevX = playerX; | 209 | playerPrevX = playerX; |
| 210 | if (shipDying > 0.0f) { | ||
| 211 | // 自機の爆発中:隊列も宇宙人の弾も止まる(元のゲームと同じ)。終わったら真ん中に戻るか、ゲームオーバー | ||
| 212 | // While the ship explodes the formation and the alien fire stop (as in the original). Afterwards the ship comes | ||
| 213 | // back in the middle, or the game is over | ||
| 214 | shipBoom.update(dt); | ||
| 215 | formation.updateExplosions(dt); | ||
| 216 | updateShot(dt); | ||
| 217 | shipDying -= dt; | ||
| 218 | if (shipDying <= 0.0f) { | ||
| 219 | shipDying = 0.0f; | ||
| 220 | if (lives > 0) { | ||
| 221 | playerX = playerPrevX = std::round(0.5f * (kArenaLeft + kArenaRight) - 7.0f); | ||
| 222 | } else { | ||
| 223 | gameOver = true; | ||
| 224 | printf("game over: %d kills\n", kills); | ||
| 225 | } | ||
| 226 | } | ||
| 227 | return; | ||
| 228 | } | ||
| 229 | |||
| 230 | // 自機 / the ship | ||
| 54 | playerX += in.axis("left", "right") * kPlayerSpeed * dt; | 231 | playerX += in.axis("left", "right") * kPlayerSpeed * dt; |
| 55 | playerX = std::clamp(playerX, kArenaLeft + 2.0f, kArenaRight - 2.0f - 15.0f); | 232 | playerX = std::clamp(playerX, kArenaLeft + 2.0f, kArenaRight - 2.0f - 15.0f); |
| 233 | fire(); | ||
| 56 | 234 | ||
| 57 | formation.update(dt); | 235 | formation.update(dt); |
| 58 | // 第27章では撃てないので、地面まで下りてきたら上からやり直す(第28章で「侵略された」になる) | 236 | updateShot(dt); |
| 59 | // There is no shooting in chapter 27 yet, so when the formation reaches the ship's row it starts again at the top | 237 | alienFire(dt); |
| 60 | // (chapter 28 turns this into "invaded") | 238 | updateAlienShots(dt); |
| 61 | if (formation.bounds().bottom() > kPlayerY) { | 239 | if (shipDying > 0.0f) return; |
| 62 | ++landings; | 240 | |
| 63 | printf("formation landed after %d passes: reset\n", formation.passes); | 241 | // 防壁まで下りてきた宇宙人は防壁を食べる / aliens that reach the shields eat them |
| 64 | formation.reset(std::round(0.5f * (kArenaLeft + kArenaRight - 174.0f)), kFormationTop); | 242 | for (const Alien &a : formation.aliens) |
| 243 | if (a.alive && a.box().bottom() > kShieldY) shields->eraseRect(a.box()); | ||
| 244 | // 自機の高さまで来たら侵略された:残りの自機に関係なくゲームオーバー / reaching the ship's row is an invasion: | ||
| 245 | // game over whatever lives are left | ||
| 246 | if (formation.alive() > 0 && formation.bounds().bottom() > kPlayerY) { | ||
| 247 | printf("invaded\n"); | ||
| 248 | lives = 1; | ||
| 249 | killShip(); | ||
| 250 | return; | ||
| 251 | } | ||
| 252 | // 全滅させたら次の隊列(第29章で場面ごと読み直す) / when the formation is wiped out, a new one comes (chapter 29 | ||
| 253 | // reloads the whole scene) | ||
| 254 | if (formation.cleared()) { | ||
| 255 | ++waves; | ||
| 256 | printf("wave cleared: %d kills\n", kills); | ||
| 257 | formation.reset(formationStartX(), kFormationTop); | ||
| 258 | fireTimer = 1.0f; | ||
| 65 | } | 259 | } |
| 66 | } | 260 | } |
| 67 | 261 | ||
| @@ -82,52 +276,79 @@ void PlayScene::drawBackground() { | |||
| 82 | } | 276 | } |
| 83 | 277 | ||
| 84 | void PlayScene::drawFormation() { | 278 | void PlayScene::drawFormation() { |
| 279 | // 生きている宇宙人と、爆発中の宇宙人(爆発のコマ) / living aliens and exploding ones (explosion frames) | ||
| 85 | if (g.instanced) { | 280 | if (g.instanced) { |
| 86 | // インスタンシング:生きている宇宙人を16バイトずつ並べて、一回で描く / instancing: 16 bytes per living alien, one | ||
| 87 | // draw call | ||
| 88 | std::vector<AlienInstance> list; | 281 | std::vector<AlienInstance> list; |
| 89 | for (const Alien &a : formation.aliens) | 282 | for (const Alien &a : formation.aliens) |
| 90 | if (a.alive) | 283 | if (a.alive || a.dying > 0.0f) |
| 91 | list.push_back({a.position, static_cast<std::uint32_t>(alienFrame(a)), packRgba8(kWhite)}); | 284 | list.push_back({a.position, static_cast<std::uint32_t>(alienFrame(a)), packRgba8(kWhite)}); |
| 92 | g.formationRenderer.draw(g.world.matrix(), list); | 285 | g.formationRenderer.draw(g.world.matrix(), list); |
| 93 | formationDrawCalls = g.formationRenderer.lastDrawCalls(); | 286 | formationDrawCalls = g.formationRenderer.lastDrawCalls(); |
| 94 | formationBytes = g.formationRenderer.lastBytes(); | 287 | formationBytes = g.formationRenderer.lastBytes(); |
| 95 | } else { | 288 | } else { |
| 96 | // 比べるため:同じ宇宙人をSpriteBatchで(一枚4頂点 × 20バイト) / for comparison: the same aliens through | ||
| 97 | // SpriteBatch (4 vertices × 20 bytes per sprite) | ||
| 98 | g.batch.begin(g.world.matrix()); | 289 | g.batch.begin(g.world.matrix()); |
| 99 | for (const Alien &a : formation.aliens) | 290 | for (const Alien &a : formation.aliens) |
| 100 | if (a.alive) g.batch.draw(g.sprites.sprite(alienFrame(a), a.position)); | 291 | if (a.alive || a.dying > 0.0f) g.batch.draw(g.sprites.sprite(alienFrame(a), a.position)); |
| 101 | g.batch.end(); | 292 | g.batch.end(); |
| 102 | formationDrawCalls = g.batch.stats().drawCalls; | 293 | formationDrawCalls = g.batch.stats().drawCalls; |
| 103 | formationBytes = g.batch.stats().sprites * 4 * static_cast<int>(sizeof(SpriteVertex)); | 294 | formationBytes = g.batch.stats().sprites * 4 * static_cast<int>(sizeof(SpriteVertex)); |
| 104 | } | 295 | } |
| 105 | } | 296 | } |
| 106 | 297 | ||
| 298 | void PlayScene::drawBoxes() { | ||
| 299 | // 当たり判定の箱(B):宇宙人 = 赤、自機 = 緑、弾 = 黄、防壁 = 青(防壁はさらにピクセル単位で調べる) | ||
| 300 | // The collision boxes (B): aliens red, ship green, bullets yellow, shields blue (shields are then tested per pixel) | ||
| 301 | SpriteBatch &b = g.batch; | ||
| 302 | for (const Alien &a : formation.aliens) | ||
| 303 | if (a.alive) b.drawRectOutline(a.box(), hexColor(0xff4040c0)); | ||
| 304 | for (int i = 0; i < kShieldCount; ++i) b.drawRectOutline(shields->bounds(i), hexColor(0x40a0ffc0)); | ||
| 305 | if (shipDying <= 0.0f && !gameOver) b.drawRectOutline(shipBox(), hexColor(0x40ff60ff)); | ||
| 306 | if (shot) b.drawRectOutline(shot->box, hexColor(0xffe040ff)); | ||
| 307 | for (const Bullet &s : alienShots) b.drawRectOutline(s.box, hexColor(0xffe040ff)); | ||
| 308 | } | ||
| 309 | |||
| 107 | void PlayScene::draw(float alpha) { | 310 | void PlayScene::draw(float alpha) { |
| 108 | // 奥から:背景(バッチ)→ 隊列(インスタンシングかバッチ)→ 自機(バッチ) / back to front: background (batch) → | 311 | if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor) |
| 109 | // formation (instanced or batch) → ship (batch) | 312 | // 防壁:変わった所だけGPUへ(描く前に) / shields: send only the changed part to the GPU (before drawing) |
| 313 | shields->upload(); | ||
| 314 | if (shields->lastUploadBytes() > 0) shieldBytes = shields->lastUploadBytes(); | ||
| 315 | |||
| 316 | // 奥から:背景と防壁(バッチ)→ 隊列(インスタンシングかバッチ)→ 自機・弾・爆発(バッチ) | ||
| 317 | // Back to front: background and shields (batch) → formation (instanced or batch) → ship, bullets, explosions (batch) | ||
| 110 | g.batch.begin(g.world.matrix()); | 318 | g.batch.begin(g.world.matrix()); |
| 111 | drawBackground(); | 319 | drawBackground(); |
| 320 | shields->draw(g.batch); | ||
| 112 | g.batch.end(); | 321 | g.batch.end(); |
| 113 | 322 | ||
| 114 | drawFormation(); | 323 | drawFormation(); |
| 115 | 324 | ||
| 116 | // 宇宙人は飛び飛びに動くので補間しない。自機は滑らかに動くので補間する(第26章) | 325 | SpriteBatch &b = g.batch; |
| 117 | // Aliens move in jumps, so they are not interpolated. The ship moves smoothly, so it is (chapter 26) | 326 | b.begin(g.world.matrix()); |
| 118 | float x = std::round(playerPrevX + (playerX - playerPrevX) * alpha); | 327 | float x = std::round(playerPrevX + (playerX - playerPrevX) * alpha); |
| 119 | g.batch.begin(g.world.matrix()); | 328 | if (shipDying > 0.0f) b.draw(g.sprites.sprite(shipBoom.frame(), {x, kPlayerY})); |
| 120 | g.batch.draw(g.sprites.sprite(shipFrame, {x, kPlayerY})); | 329 | else if (!gameOver) b.draw(g.sprites.sprite(shipFrame, {x, kPlayerY})); |
| 121 | g.batch.end(); | 330 | // 弾は滑らかに動くので補間する / bullets move smoothly, so they are interpolated |
| 331 | if (shot) b.draw(g.sprites.sprite(shotFrame, {shot->box.x, std::round(shot->prevY + (shot->box.y - shot->prevY) * alpha)})); | ||
| 332 | for (const Bullet &s : alienShots) | ||
| 333 | b.draw(g.sprites.sprite(s.anim.frame(), {s.box.x, std::round(s.prevY + (s.box.y - s.prevY) * alpha)})); | ||
| 334 | for (const Flare &f : flares) { | ||
| 335 | Sprite s = g.sprites.sprite(f.frame, {std::round(f.centre.x), std::round(f.centre.y)}, {0.5f, 0.5f}); | ||
| 336 | s.color = f.color; | ||
| 337 | b.draw(s); | ||
| 338 | } | ||
| 339 | particles.draw(b); | ||
| 340 | if (g.showBoxes) drawBoxes(); | ||
| 341 | b.end(); | ||
| 122 | } | 342 | } |
| 123 | 343 | ||
| 124 | void PlayScene::drawUi(float /*alpha*/) { | 344 | void PlayScene::drawUi(float /*alpha*/) { |
| 345 | if (!shields) return; // 終了する所(コンストラクタ) / quitting (see the constructor) | ||
| 125 | SpriteBatch &b = g.batch; | 346 | SpriteBatch &b = g.batch; |
| 126 | b.begin(g.screen.matrix()); | 347 | b.begin(g.screen.matrix()); |
| 127 | TextStyle head = {.color = hexColor(0xf2c14eff), .shadow = hexColor(0x000000ff)}; | 348 | TextStyle head = {.color = hexColor(0xf2c14eff), .shadow = hexColor(0x000000ff)}; |
| 128 | TextStyle body = {.color = hexColor(0xd8dcefff), .shadow = hexColor(0x000000ff)}; | 349 | TextStyle body = {.color = hexColor(0xd8dcefff), .shadow = hexColor(0x000000ff)}; |
| 129 | char line[64]; | 350 | char line[64]; |
| 130 | // 左の板:隊列の描き方と、その値段 / the left panel: how the formation is drawn and what it costs | 351 | // 左の板:隊列の描き方と、戦いの数字 / the left panel: how the formation is drawn, and the battle numbers |
| 131 | float y = 24.0f; | 352 | float y = 24.0f; |
| 132 | auto text = [&](const char *s, const TextStyle &st) { | 353 | auto text = [&](const char *s, const TextStyle &st) { |
| 133 | g.ui.draw(b, s, {14.0f, y}, st); | 354 | g.ui.draw(b, s, {14.0f, y}, st); |
| @@ -135,20 +356,27 @@ void PlayScene::drawUi(float /*alpha*/) { | |||
| 135 | }; | 356 | }; |
| 136 | text("FORMATION (I)", head); | 357 | text("FORMATION (I)", head); |
| 137 | text(g.instanced ? "instanced" : "SpriteBatch", body); | 358 | text(g.instanced ? "instanced" : "SpriteBatch", body); |
| 138 | snprintf(line, sizeof line, "draw calls %d", formationDrawCalls); | ||
| 139 | text(line, body); | ||
| 140 | snprintf(line, sizeof line, "%d B/frame", formationBytes); | 359 | snprintf(line, sizeof line, "%d B/frame", formationBytes); |
| 141 | text(line, body); | 360 | text(line, body); |
| 142 | text(g.instanced ? "(16 B/alien)" : "(80 B/alien)", body); | ||
| 143 | y += 16.0f; | ||
| 144 | text("MARCH (= -)", head); | ||
| 145 | snprintf(line, sizeof line, "%.0f aliens/s", static_cast<double>(formation.rate)); | 361 | snprintf(line, sizeof line, "%.0f aliens/s", static_cast<double>(formation.rate)); |
| 146 | text(line, body); | 362 | text(line, body); |
| 147 | snprintf(line, sizeof line, "alive %d", formation.alive()); | 363 | snprintf(line, sizeof line, "alive %d", formation.alive()); |
| 148 | text(line, body); | 364 | text(line, body); |
| 149 | snprintf(line, sizeof line, "passes %d", formation.passes); | 365 | y += 16.0f; |
| 366 | text("BATTLE", head); | ||
| 367 | snprintf(line, sizeof line, "lives %d", lives); | ||
| 368 | text(line, body); | ||
| 369 | snprintf(line, sizeof line, "kills %d", kills); | ||
| 150 | text(line, body); | 370 | text(line, body); |
| 151 | snprintf(line, sizeof line, "landed %d", landings); | 371 | snprintf(line, sizeof line, "shots %d", shotsFired); |
| 372 | text(line, body); | ||
| 373 | snprintf(line, sizeof line, "wave %d", waves); | ||
| 374 | text(line, body); | ||
| 375 | y += 16.0f; | ||
| 376 | text("SHIELDS", head); | ||
| 377 | snprintf(line, sizeof line, "%d px left", shields->pixelsLeft()); | ||
| 378 | text(line, body); | ||
| 379 | snprintf(line, sizeof line, "upload %d B", shieldBytes); | ||
| 152 | text(line, body); | 380 | text(line, body); |
| 153 | 381 | ||
| 154 | // 右の板:操作 / the right panel: controls | 382 | // 右の板:操作 / the right panel: controls |
| @@ -160,8 +388,18 @@ void PlayScene::drawUi(float /*alpha*/) { | |||
| 160 | right("CONTROLS", head); | 388 | right("CONTROLS", head); |
| 161 | right("A D / arrows", body); | 389 | right("A D / arrows", body); |
| 162 | right(" move", body); | 390 | right(" move", body); |
| 391 | right("Space fire", body); | ||
| 163 | right("I formation", body); | 392 | right("I formation", body); |
| 393 | right("B boxes", body); | ||
| 164 | right("= - march", body); | 394 | right("= - march", body); |
| 165 | right("Esc quit", body); | 395 | right("Esc quit", body); |
| 396 | |||
| 397 | if (gameOver) { | ||
| 398 | b.drawRect({192.0f, 300.0f, 896.0f, 110.0f}, hexColor(0x0c0a1ad0)); | ||
| 399 | g.ui.draw(b, "GAME OVER", {640.0f, 316.0f}, | ||
| 400 | {.color = hexColor(0xd9474bff), .scale = 3.0f, .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); | ||
| 401 | g.ui.draw(b, "Space / Enter: play again", {640.0f, 378.0f}, | ||
| 402 | {.color = hexColor(0xd8dcefff), .align = TextAlign::Centre, .shadow = hexColor(0x000000ff)}); | ||
| 403 | } | ||
| 166 | b.end(); | 404 | b.end(); |
| 167 | } | 405 | } |
ファイル: /dev/null | b/games/invaders/src/shields.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,158 @@ | |||
| 1 | #include "shields.hh" | ||
| 2 | |||
| 3 | #include "engine/file_util.hh" | ||
| 4 | |||
| 5 | #include <algorithm> | ||
| 6 | #include <cmath> | ||
| 7 | #include <cstdio> | ||
| 8 | |||
| 9 | // 着弾の形(スプライトシートのsplatと同じ形):'W' = 消すピクセル / the impact shape (the same shape as the | ||
| 10 | // sheet's splat sprite): 'W' = a pixel to clear | ||
| 11 | static const char *const kSplat[] = { | ||
| 12 | "W..W.W", | ||
| 13 | "..WW..", | ||
| 14 | ".WWWW.", | ||
| 15 | "WWWWW.", | ||
| 16 | ".WWWWW", | ||
| 17 | "WWWWW.", | ||
| 18 | "..WW..", | ||
| 19 | "W..W.W", | ||
| 20 | }; | ||
| 21 | constexpr int kSplatW = 6, kSplatH = 8; | ||
| 22 | |||
| 23 | std::optional<Image> loadSpriteImage(const std::string &pngPath, const SpriteSheet &sheet, const char *name) { | ||
| 24 | int index = sheet.find(name); | ||
| 25 | std::optional<std::vector<std::uint8_t>> bytes = readBinaryFile(pngPath); | ||
| 26 | if (index < 0 || !bytes) { | ||
| 27 | fprintf(stderr, "%s: スプライト %s がない / no sprite %s\n", pngPath.c_str(), name, name); | ||
| 28 | return std::nullopt; | ||
| 29 | } | ||
| 30 | std::optional<Image> sheetImage = decodeImage(bytes->data(), bytes->size(), false); | ||
| 31 | if (!sheetImage) return std::nullopt; | ||
| 32 | Rect r = sheet.pixels(index); | ||
| 33 | Image out; | ||
| 34 | out.width = static_cast<int>(r.w); | ||
| 35 | out.height = static_cast<int>(r.h); | ||
| 36 | out.rgba.resize(static_cast<size_t>(out.width * out.height * 4)); | ||
| 37 | for (int y = 0; y < out.height; ++y) | ||
| 38 | for (int x = 0; x < out.width; ++x) | ||
| 39 | for (int c = 0; c < 4; ++c) { | ||
| 40 | size_t src = static_cast<size_t>(4 * ((static_cast<int>(r.y) + y) * sheetImage->width + static_cast<int>(r.x) + x) + c); | ||
| 41 | out.rgba[static_cast<size_t>(4 * (y * out.width + x) + c)] = sheetImage->rgba[src]; | ||
| 42 | } | ||
| 43 | // 乗算済みアルファにする(loadSpriteTextureが自動でやっていること)。PNGの透明なピクセルには、にじみ止めの色 | ||
| 44 | // (隣の不透明なピクセルの色)が入っているので、そのまま送ると (r, g, b, 0) が加算されて縁が光る | ||
| 45 | // Premultiply (what loadSpriteTexture does for you). The PNG's transparent pixels carry the nearest opaque color | ||
| 46 | // against fringes; sent as is, (r, g, b, 0) would be *added* by the premultiplied blend and the edges would glow | ||
| 47 | for (size_t i = 0; i < out.rgba.size(); i += 4) | ||
| 48 | for (size_t c = 0; c < 3; ++c) out.rgba[i + c] = static_cast<std::uint8_t>(out.rgba[i + c] * out.rgba[i + 3] / 255); | ||
| 49 | return out; | ||
| 50 | } | ||
| 51 | |||
| 52 | std::optional<Shields> Shields::create(const Image &art, const Vec2 (&positions)[kShieldCount]) { | ||
| 53 | if (art.width != kShieldW || art.height != kShieldH) { | ||
| 54 | fprintf(stderr, "防壁の絵が %d × %d でない / the shield art is not %d × %d\n", kShieldW, kShieldH, kShieldW, kShieldH); | ||
| 55 | return std::nullopt; | ||
| 56 | } | ||
| 57 | Shields s; | ||
| 58 | s.pixels.resize(static_cast<size_t>(kTexW * kTexH * 4)); | ||
| 59 | for (int i = 0; i < kShieldCount; ++i) { | ||
| 60 | s.topLeft[i] = positions[i]; | ||
| 61 | for (int y = 0; y < kShieldH; ++y) | ||
| 62 | std::copy_n(art.rgba.begin() + 4 * y * kShieldW, 4 * kShieldW, | ||
| 63 | s.pixels.begin() + 4 * (y * kTexW + i * kShieldW)); | ||
| 64 | } | ||
| 65 | // 中身は後で書き換えるので、空のストレージを作ってから全体を一度送る / the contents change later, so allocate | ||
| 66 | // empty storage and send everything once | ||
| 67 | s.tex = Texture2D(kTexW, kTexH, GL_RGBA8, 1); | ||
| 68 | s.tex.setFilter(GL_NEAREST, GL_NEAREST); | ||
| 69 | s.tex.setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); | ||
| 70 | s.tex.upload(s.pixels.data()); | ||
| 71 | return s; | ||
| 72 | } | ||
| 73 | |||
| 74 | void Shields::clearPixel(int x, int y) { | ||
| 75 | if (x < 0 || y < 0 || x >= kTexW || y >= kTexH || !solid(x, y)) return; | ||
| 76 | std::fill_n(pixels.begin() + 4 * (y * kTexW + x), 4, std::uint8_t{0}); | ||
| 77 | dirtyX0 = std::min(dirtyX0, x), dirtyY0 = std::min(dirtyY0, y); | ||
| 78 | dirtyX1 = std::max(dirtyX1, x + 1), dirtyY1 = std::max(dirtyY1, y + 1); | ||
| 79 | } | ||
| 80 | |||
| 81 | std::optional<Vec2> Shields::hit(const Rect &box, bool fromBelow) const { | ||
| 82 | for (int i = 0; i < kShieldCount; ++i) { | ||
| 83 | Rect s = bounds(i); | ||
| 84 | // boxが重なるピクセルの範囲(防壁の中の座標) / the pixels the box covers (shield coordinates) | ||
| 85 | int x0 = std::max(0, static_cast<int>(std::floor(box.left() - s.x))); | ||
| 86 | int x1 = std::min(kShieldW, static_cast<int>(std::ceil(box.right() - s.x))); | ||
| 87 | int y0 = std::max(0, static_cast<int>(std::floor(box.top() - s.y))); | ||
| 88 | int y1 = std::min(kShieldH, static_cast<int>(std::ceil(box.bottom() - s.y))); | ||
| 89 | if (x0 >= x1 || y0 >= y1) continue; | ||
| 90 | for (int n = 0; n < y1 - y0; ++n) { | ||
| 91 | int y = fromBelow ? y1 - 1 - n : y0 + n; | ||
| 92 | for (int x = x0; x < x1; ++x) | ||
| 93 | if (solid(i * kShieldW + x, y)) | ||
| 94 | return Vec2{s.x + static_cast<float>(x) + 0.5f, s.y + static_cast<float>(y) + 0.5f}; | ||
| 95 | } | ||
| 96 | } | ||
| 97 | return std::nullopt; | ||
| 98 | } | ||
| 99 | |||
| 100 | void Shields::erode(Vec2 point, Rng &rng) { | ||
| 101 | bool mirror = rng.chance(0.5f); | ||
| 102 | for (int i = 0; i < kShieldCount; ++i) { | ||
| 103 | Rect s = bounds(i); | ||
| 104 | // 着弾の形の左上(防壁の中の座標) / the impact shape's top left (shield coordinates) | ||
| 105 | int ox = static_cast<int>(std::floor(point.x - s.x)) - kSplatW / 2; | ||
| 106 | int oy = static_cast<int>(std::floor(point.y - s.y)) - kSplatH / 2; | ||
| 107 | if (ox >= kShieldW || oy >= kShieldH || ox + kSplatW <= 0 || oy + kSplatH <= 0) continue; | ||
| 108 | for (int y = 0; y < kSplatH; ++y) | ||
| 109 | for (int x = 0; x < kSplatW; ++x) { | ||
| 110 | int sx = ox + x, sy = oy + y; | ||
| 111 | char c = kSplat[y][mirror ? kSplatW - 1 - x : x]; | ||
| 112 | if (c == 'W' && sx >= 0 && sx < kShieldW && sy >= 0 && sy < kShieldH) clearPixel(i * kShieldW + sx, sy); | ||
| 113 | } | ||
| 114 | } | ||
| 115 | } | ||
| 116 | |||
| 117 | void Shields::eraseRect(const Rect &box) { | ||
| 118 | for (int i = 0; i < kShieldCount; ++i) { | ||
| 119 | Rect s = bounds(i); | ||
| 120 | int x0 = std::max(0, static_cast<int>(std::floor(box.left() - s.x))); | ||
| 121 | int x1 = std::min(kShieldW, static_cast<int>(std::ceil(box.right() - s.x))); | ||
| 122 | int y0 = std::max(0, static_cast<int>(std::floor(box.top() - s.y))); | ||
| 123 | int y1 = std::min(kShieldH, static_cast<int>(std::ceil(box.bottom() - s.y))); | ||
| 124 | for (int y = y0; y < y1; ++y) | ||
| 125 | for (int x = x0; x < x1; ++x) clearPixel(i * kShieldW + x, y); | ||
| 126 | } | ||
| 127 | } | ||
| 128 | |||
| 129 | void Shields::upload() { | ||
| 130 | uploadBytes = 0; | ||
| 131 | if (dirtyX0 >= dirtyX1 || dirtyY0 >= dirtyY1) return; // 変わっていない / nothing changed | ||
| 132 | int w = dirtyX1 - dirtyX0, h = dirtyY1 - dirtyY0; | ||
| 133 | // CPUの配列の一部(四角)を送る:行の長さ(GL_UNPACK_ROW_LENGTH)を配列全体の幅にすると、GLは一行ごとに | ||
| 134 | // kTexWピクセル先へ進む。ポインターは四角の左上。送ったら0(= 幅と同じ)に戻す | ||
| 135 | // Send a rectangle out of the CPU array: with GL_UNPACK_ROW_LENGTH = the whole array's width, the GL steps kTexW | ||
| 136 | // pixels for every row. The pointer is the rectangle's top left. Reset it to 0 (= the width) afterwards | ||
| 137 | glPixelStorei(GL_UNPACK_ROW_LENGTH, kTexW); | ||
| 138 | glTextureSubImage2D(tex.id(), 0, dirtyX0, dirtyY0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, | ||
| 139 | pixels.data() + 4 * (dirtyY0 * kTexW + dirtyX0)); | ||
| 140 | glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); | ||
| 141 | uploadBytes = w * h * 4; | ||
| 142 | dirtyX0 = kTexW, dirtyY0 = kTexH, dirtyX1 = 0, dirtyY1 = 0; | ||
| 143 | } | ||
| 144 | |||
| 145 | void Shields::draw(SpriteBatch &batch, float layer) const { | ||
| 146 | for (int i = 0; i < kShieldCount; ++i) | ||
| 147 | batch.draw({.texture = &tex, | ||
| 148 | .position = topLeft[i], | ||
| 149 | .size = {kShieldW, kShieldH}, | ||
| 150 | .uv = {static_cast<float>(i) / kShieldCount, 0.0f, 1.0f / kShieldCount, 1.0f}, | ||
| 151 | .layer = layer}); | ||
| 152 | } | ||
| 153 | |||
| 154 | int Shields::pixelsLeft() const { | ||
| 155 | int n = 0; | ||
| 156 | for (size_t i = 3; i < pixels.size(); i += 4) n += pixels[i] != 0; | ||
| 157 | return n; | ||
| 158 | } | ||
ファイル: /dev/null | b/games/invaders/src/shields.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,64 @@ | |||
| 1 | // 削れる防壁(第28章):ピクセルの絵をCPUに持ち、弾が当たった所を消して、変わった四角だけを | ||
| 2 | // glTextureSubImage2Dでテクスチャに送り直す | ||
| 3 | // Shields that erode (chapter 28): the pixels live on the CPU; an impact clears pixels there, and only the changed | ||
| 4 | // rectangle is sent to the texture again with glTextureSubImage2D | ||
| 5 | #pragma once | ||
| 6 | |||
| 7 | #include "engine/rect.hh" | ||
| 8 | #include "engine/rng.hh" | ||
| 9 | #include "engine/sprite_batch.hh" | ||
| 10 | #include "engine/sprite_sheet.hh" | ||
| 11 | #include "engine/texture.hh" | ||
| 12 | |||
| 13 | #include <cstdint> | ||
| 14 | #include <optional> | ||
| 15 | #include <string> | ||
| 16 | #include <vector> | ||
| 17 | |||
| 18 | constexpr int kShieldCount = 4; | ||
| 19 | constexpr int kShieldW = 22, kShieldH = 16; | ||
| 20 | |||
| 21 | // スプライトシートのPNGをCPUでもう一度デコードして、名前の絵だけを切り出す(RGBA8、上の行から)。 | ||
| 22 | // 透明なピクセルのRGBは0にする(乗算済みアルファ:GPUに送るときに要る) | ||
| 23 | // Decodes the sprite sheet's PNG again on the CPU and cuts out one named sprite (RGBA8, rows from the top). | ||
| 24 | // Transparent pixels get RGB 0 (premultiplied alpha: needed when they are sent to the GPU) | ||
| 25 | std::optional<Image> loadSpriteImage(const std::string &pngPath, const SpriteSheet &sheet, const char *name); | ||
| 26 | |||
| 27 | class Shields { | ||
| 28 | public: | ||
| 29 | // 4つの防壁を一枚のテクスチャ(88 × 16)に並べる。topLeft[i] = 画面での防壁iの左上 | ||
| 30 | // Puts the 4 shields side by side in one texture (88 × 16). topLeft[i] = where shield i goes on screen | ||
| 31 | static std::optional<Shields> create(const Image &art, const Vec2 (&topLeft)[kShieldCount]); | ||
| 32 | |||
| 33 | // boxの中に残っている防壁のピクセルがあるか。あれば、弾の進む向きで最初に当たるピクセル(の中心) | ||
| 34 | // (下から来る弾 = 一番下、上から来る弾 = 一番上) | ||
| 35 | // Is any shield pixel left inside box? If so, the pixel a bullet meets first (its center): the lowest for a | ||
| 36 | // bullet coming from below, the highest for one coming from above | ||
| 37 | std::optional<Vec2> hit(const Rect &box, bool fromBelow) const; | ||
| 38 | // 着弾の形(kSplat、6 × 8)でピクセルを消す。左右はランダムに反転 / clears pixels in the impact shape (kSplat, | ||
| 39 | // 6 × 8), mirrored at random | ||
| 40 | void erode(Vec2 point, Rng &rng); | ||
| 41 | // 四角の中を全部消す(防壁まで下りてきた宇宙人) / clears everything inside the box (aliens that reach the shields) | ||
| 42 | void eraseRect(const Rect &box); | ||
| 43 | |||
| 44 | // 変わった所だけをアップロードする(描く前に一度) / uploads only what changed (once, before drawing) | ||
| 45 | void upload(); | ||
| 46 | void draw(SpriteBatch &batch, float layer = 0.0f) const; | ||
| 47 | Rect bounds(int i) const { return {topLeft[i].x, topLeft[i].y, kShieldW, kShieldH}; } | ||
| 48 | int lastUploadBytes() const { return uploadBytes; } | ||
| 49 | int pixelsLeft() const; | ||
| 50 | const Texture2D &texture() const { return tex; } | ||
| 51 | |||
| 52 | private: | ||
| 53 | static constexpr int kTexW = kShieldW * kShieldCount, kTexH = kShieldH; | ||
| 54 | Shields() = default; | ||
| 55 | void clearPixel(int x, int y); // テクスチャのピクセル座標 / texture pixel coordinates | ||
| 56 | bool solid(int x, int y) const { return pixels[static_cast<size_t>(4 * (y * kTexW + x) + 3)] != 0; } | ||
| 57 | |||
| 58 | std::vector<std::uint8_t> pixels; // kTexW × kTexH × RGBA8(CPUの正本) / the CPU master copy | ||
| 59 | Texture2D tex; | ||
| 60 | Vec2 topLeft[kShieldCount]; | ||
| 61 | int dirtyX0 = kTexW, dirtyY0 = kTexH, dirtyX1 = 0, dirtyY1 = 0; // 変わった四角(x1・y1は含まない) / the changed | ||
| 62 | // rectangle (x1, y1 exclusive) | ||
| 63 | int uploadBytes = 0; | ||
| 64 | }; | ||
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。