39. Third-Person Shooter Part 4: HUD, Game Flow and Next Steps
After chapter 38 the shooter plays: enemies patrol, notice you, shoot back, and fall over when you hit them often enough.
But it's still a prototype.
It starts in the middle of the level, quits on Esc, respawns you forever, and tells you how you're doing with one line of debug text at the bottom.
This last chapter turns it into a small finished game.
We give it a real HUD (a crosshair that opens with the spread, hit and kill markers, a health bar that shows what you just lost, ammo pips, the enemies left and red arcs that point at whoever shot you), a game flow (a title screen over the level, the round, a result screen, a pause screen), a set of performance options with honest measurements, and a package that runs from any folder.
Then we look back at the whole series, at what you can build with it now, and at what comes next on this site.
There is almost no new OpenGL in this chapter.
The HUD is the 2D toolkit from Part 5 drawn over the 3D image, the game flow is chapter 26's scene stack, and the performance section uses the queries from chapters 19 and 36.
That's the point: by now the hard parts are design decisions, not API calls.
39.1 What we're building
The game now starts on a title screen, with the level slowly turning behind it:
The first clip is chapter 38's fight replayed with the new HUD, all the way to the result screen:
The second one shows the flow: the title, the fade into the round, a short walk, Esc for the pause screen, and T back to the title:
The controls (the ones from chapters 36 to 38 still work):
- Title: Space or Enter starts a round, Esc quits
- Play: Esc pauses; F5 cycles the render scale 100 → 75 → 50 %, F6 turns shadows on and off, F7 switches the shadow map between 2048² and 1024²
- Result: Space plays again, Esc goes back to the title
- Pause: Esc or Space resumes, T goes back to the title
- Command line:
--playskips the title,--msaauses the engine's default post-processing chain for comparison, and any other argument is a level file as before
Starting from chapter 38, the changes are all inside games/tps/:
src/hud.hh,src/hud.cc(new):HudStateanddrawHudsrc/menu_scenes.hh,src/menu_scenes.cc(new):TitleScene,ResultSceneandPauseScenesrc/play_scene.hh,src/play_scene.cc: Esc pauses, the round ends with a result instead of a respawn, the HUD replaces chapter 38's crosshair and status line, F5 to F7src/renderer.hh,src/renderer.cc: render scale and shadow-map sizesrc/main.cc: starts at the title, theconfirmaction, the arguments, andfindDataDirectoryfor installed copiesCMakeLists.txt: the two new sources and the install rulesREADME.md: the new controls, the Release and install commands
The two new sources go at the end of the list:
# 第36〜39章:三人称シューティング(TPS) / Chapters 36-39: the third-person shooter (TPS)
add_executable(tps
src/main.cc
src/collision3d.cc
src/character_body.cc
src/frustum.cc
src/level.cc
src/renderer.cc
src/character.cc
src/third_person_camera.cc
src/enemy.cc
src/effects.cc
src/play_scene.cc
src/hud.cc
src/menu_scenes.cc)
target_include_directories(tps PRIVATE src)
target_link_libraries(tps PRIVATE engine)
enable_warnings(tps)
set_working_directory(tps)
39.2 The HUD is a picture of the game state
Here is the HUD in the middle of a fight, on the platform, just after the enemy in the east lane hit us:
The first design decision is where the HUD's data comes from.
In chapter 38 the drawing code reached into PlayScene's members directly: health, ammo, hitMarker, aimBlend and so on.
That works for one status line, but it ties every pixel of the HUD to the scene's internals.
Instead, PlayScene now fills a plain struct every frame, and a free function draws it:
// 撃たれた向きの印 / a damage-direction marker
struct DamageMarker {
float angle; // 画面の上 = 0、時計回り(ラジアン):カメラの向きから見た撃った敵の向き / screen up = 0, clockwise
// (radians): the shooter's direction relative to where the camera looks
float life; // 残り時間(秒) / seconds left
};
// HUDが描くもの全部(PlaySceneが毎フレーム詰める) / everything the HUD shows (PlayScene fills it every frame)
struct HudState {
float health = 100.0f;
float healthShown = 100.0f; // 遅れて減る薄い棒(どれだけ減ったか見える) / a lagging pale bar (shows the loss)
int ammo = 0, magazine = 0;
float reload = -1.0f; // 0〜1:込め直しの進み、−1 = していない / 0..1 reload progress, −1 = not reloading
int enemiesLeft = 0, enemiesTotal = 0;
float spread = 10.0f; // 照準の線の真ん中からの距離(px) / the crosshair lines' distance from the center (px)
float hitMarker = 0.0f; // 当てた印の残り(0〜1) / hit marker left (0..1)
bool killMarker = false; // 今の印は倒した一発 / the current marker is a kill
float hurt = 0.0f; // 画面の縁の赤(0〜1) / red screen edge (0..1)
bool alive = true;
std::vector<DamageMarker> damage;
};
// batch.begin(…)とend()の間で呼ぶ / call between batch.begin(...) and end()
void drawHud(SpriteBatch &batch, const Font &font, const HudState &hud);
HudState holds only what the player sees, already in HUD terms: the spread is in pixels, the hit marker is a fraction from 1 down to 0, the reload is progress from 0 to 1 (or −1 for "not reloading").
drawHud knows nothing about enemies, cameras or rays.
That has three practical benefits:
- You can test and tune the HUD without playing: fill a
HudStateby hand (health 12, reloading at 0.5, three damage markers) and look at it. - The game logic can change without touching the drawing, and the other way round. The spread formula, for example, lives in
PlayScene, which knows about aiming and moving;drawHudjust draws lines at that distance. - The same struct could feed a different HUD (a minimal one, a big-text accessibility one) or be saved for a replay.
The fill is a short block at the end of PlayScene::drawUi:
// HUD(第39章):毎フレーム状態を詰めて描く / the HUD (chapter 39): fill in the state and draw it every frame
int left = 0;
for (const Enemy &e : enemies) left += e.alive() ? 1 : 0;
float moving = length(Vec3{body.velocity.x, 0.0f, body.velocity.z}) > 0.5f ? 1.0f : 0.0f;
hud.health = health;
hud.ammo = ammo;
hud.magazine = kMagazine;
hud.reload = reloadTime > 0.0f ? 1.0f - reloadTime / kReloadTime : -1.0f;
hud.enemiesLeft = left;
hud.enemiesTotal = static_cast<int>(enemies.size());
hud.spread = 5.0f + 9.0f * (1.0f - aimBlend) + 8.0f * moving + (fireTimer > 0.0f ? 4.0f : 0.0f);
hud.hitMarker = std::fmax(hitMarker, 0.0f) / (killed ? 0.35f : 0.15f);
hud.killMarker = killed;
hud.hurt = hurt / 0.35f;
hud.alive = alive;
drawHud(batch, g.ui, hud);
Two of the values are updated in the fixed-step update instead, because they change over time on their own: healthShown (the lagging bar) and the list of damage markers.
Everything else is a direct translation of the scene's state at the moment of drawing.
The layout uses chapter 25's 1280 × 720 virtual screen (Camera2D::screen), letterboxed into the window, so every position below is a fixed pixel position:
The important things sit where the eyes already are.
The crosshair, the hit marker, the reload bar and the damage arcs are all within about 120 px of the center, because that's where you look while you fight.
Health and ammo go into the bottom corners, where a glance finds them, and the enemy count at the top.
Nothing covers the middle third of the screen except thin lines.
39.3 Drawn after post-processing
Where in the frame does the HUD go?
The answer comes straight from the color rules of chapter 21 and chapter 25:
The 3D part of the frame works in linear HDR values: the scene pass writes light, bloom blurs light, and the post pass applies exposure and tone mapping and then encodes to sRGB as its last step.
After present, the default framebuffer holds finished display values.
The 2D toolkit expects exactly that: its textures, fonts and hexColor values are sRGB-encoded, blending happens on those encoded values, and GL_FRAMEBUFFER_SRGB stays off, so a color comes out on the screen exactly as it was painted (the 2D rule from chapter 25).
So the HUD is drawn after present, on top of the finished image, with the same SpriteBatch and Font as the 2D games.
Drawing it any earlier would go wrong in several ways at once:
- inside the scene pass, the HUD's white (1, 1, 1) would be treated as light, tone mapping would turn it gray, and bright pixels would bloom
- its sRGB colors would be read as linear values, so every color would come out lighter and paler than painted
- with a render scale below 100 %, the HUD would be drawn small and stretched up with everything else, and the thin lines of the crosshair would blur
Drawn after post, the HUD is independent of all of it: exposure, bloom, render scale and the 3D anti-aliasing never touch it.
main already had this order since chapter 36 (3D first, then scenes.drawUi, then the fade), and the TPS now fills that UI pass with something worth looking at.
39.4 The crosshair and the hit markers
The crosshair has to be visible on everything: the white floor, the dark walls, the bright sky, and red enemies.
A pure white line disappears on the floor and a black one on the walls, so every piece is drawn twice, a dark rectangle one pixel larger on each side and the colored one on top:
// 黒い縁つきの線(明るい床でも暗い壁でも見える) / a line with a dark outline (readable on bright floors and dark walls)
static void outlined(SpriteBatch &batch, Rect r, Vec4 color) {
batch.drawRect({r.x - 1.0f, r.y - 1.0f, r.w + 2.0f, r.h + 2.0f}, {0.0f, 0.0f, 0.0f, 0.6f * color.w});
batch.drawRect(r, color);
}
// 中心のまわりに回した細い四角形(当てた印、撃たれた向き) / a thin rectangle turned about the center (hit marker,
// damage direction)
static void spoke(SpriteBatch &batch, float angle, float radius, Vec2 size, Vec4 color) {
Vec2 dir = {std::sin(angle), -std::cos(angle)}; // 画面の上 = 0、時計回り / screen up = 0, clockwise
batch.draw({.position = kCentre + radius * dir, .size = size, .origin = {0.5f, 0.5f}, .rotation = angle,
.color = color});
}
outlined is the outline trick that every game HUD uses in some form.
spoke places a thin rectangle at a distance from the center in a direction, turned to point outward.
The angle is measured like a clock hand: 0 is screen up, and positive angles turn clockwise.
In chapter 25's y-down screen coordinates that direction is , and Sprite::rotation turns clockwise too, so the same angle positions the sprite and turns it.
With origin = {0.5, 0.5} the sprite turns about its own center.
The crosshair itself:
static void crosshair(SpriteBatch &batch, const HudState &hud) {
if (!hud.alive) return;
// 4本の線:拡散が大きいほど開く(撃つ・動く・狙っていない) / four lines that open with the spread (firing, moving,
// not aiming)
float g = hud.spread;
Vec4 c = {1.0f, 1.0f, 1.0f, 0.95f};
outlined(batch, {639.0f, 360.0f - g - 9.0f, 2.0f, 9.0f}, c);
outlined(batch, {639.0f, 360.0f + g, 2.0f, 9.0f}, c);
outlined(batch, {640.0f - g - 9.0f, 359.0f, 9.0f, 2.0f}, c);
outlined(batch, {640.0f + g, 359.0f, 9.0f, 2.0f}, c);
outlined(batch, {639.0f, 359.0f, 2.0f, 2.0f}, c);
// 当てた印:斜めの4本(倒したら赤く大きく) / hit marker: four diagonal strokes (red and bigger on a kill)
if (hud.hitMarker > 0.0f) {
float k = hud.hitMarker;
Vec4 m = hud.killMarker ? Vec4{1.0f, 0.25f, 0.2f, k} : Vec4{1.0f, 1.0f, 1.0f, k};
float r = hud.killMarker ? 16.0f : 12.0f;
for (int i = 0; i < 4; ++i) spoke(batch, 0.25f * PI + 0.5f * PI * static_cast<float>(i), r, {2.0f, 8.0f}, m);
}
}
The gap is the HUD's honest picture of the spread.
PlayScene computes it from the same things the shot uses:
with the aim blend (0 hip fire, 1 aiming with the right button) and 1 while moving.
So the lines sit 14 px from the center when you stand and fire from the hip, 5 px while aiming, 22 px while running around, and 4 px more for the 0.11 s after each shot.
The extra 4 px is pure feedback, a little kick, because the shot's spread in chapter 38 doesn't grow while you fire.
The other terms follow the real spread cone (1.4° from the hip, 0.4° aiming, +1.2° while moving), though not exactly; challenge 2 makes them match.
The hit marker is four short diagonal strokes around the center, shown for 0.15 s after a hit.
A kill shows them red, 4 px farther out, and for 0.35 s:
The marker is what tells you that a shot landed.
In a third-person game the tracer may be hidden behind the character, the enemy is often small, and the hit flash from chapter 38 lasts 0.12 s; the marker in the middle of the screen, exactly where you're looking, is the one signal that's always seen.
Making kills different (color, size, duration) lets you stop shooting at an enemy that's already falling.
PlayScene::shoot sets the timer, and remembers whether it was a kill:
Enemy &e = enemies[static_cast<size_t>(index)];
bool wasAlive = e.alive();
e.alert(position, kDamage * multiplier);
killed = wasAlive && !e.alive();
if (killed) ++kills;
++shotsHit;
hitMarker = killed ? 0.35f : 0.15f;
39.5 Health, ammo and enemies
The health bar and the lagging bar
The health panel is a dark bar, a pale bar and the real bar on top of each other:
static void healthPanel(SpriteBatch &batch, const Font &font, const HudState &hud) {
batch.drawRect({20.0f, 640.0f, 300.0f, 62.0f}, kPanel);
font.draw(batch, "体力 / HEALTH", {32.0f, 646.0f}, {.color = {0.8f, 0.85f, 0.9f, 1.0f}, .shadow = kShadow});
Rect bar = {32.0f, 672.0f, 220.0f, 16.0f};
batch.drawRect(bar, {0.0f, 0.0f, 0.0f, 0.6f});
float shown = std::clamp(hud.healthShown / 100.0f, 0.0f, 1.0f), now = std::clamp(hud.health / 100.0f, 0.0f, 1.0f);
batch.drawRect({bar.x, bar.y, bar.w * shown, bar.h}, {1.0f, 0.85f, 0.8f, 0.8f}); // 減った分 / what was lost
// 緑 → 黄 → 赤 / green → yellow → red
Vec4 color = now > 0.5f ? lerp(Vec4{0.95f, 0.8f, 0.2f, 1.0f}, Vec4{0.3f, 0.9f, 0.45f, 1.0f}, (now - 0.5f) * 2.0f)
: lerp(Vec4{0.95f, 0.2f, 0.15f, 1.0f}, Vec4{0.95f, 0.8f, 0.2f, 1.0f}, now * 2.0f);
batch.drawRect({bar.x, bar.y, bar.w * now, bar.h}, color);
font.draw(batch, std::format("{:.0f}", std::ceil(hud.health)), {302.0f, 668.0f},
{.scale = 1.5f, .align = TextAlign::Right, .shadow = kShadow});
}
The pale bar is the one detail that makes a health bar readable in a fight.
When a bullet takes 8 points, the green bar drops at once, but the pale bar stays where it was for a moment, so for a short time you can see the piece you lost (17.6 px of the 220 px bar), as in the bottom-left crop above.
It's updated in the fixed step:
// 遅れて減る棒:0.4秒待ってから毎秒40ずつ追いつく / the lagging bar waits 0.4 s, then catches up at 40 per second
if (sinceHurt > 0.4f) hud.healthShown = std::fmax(hud.healthShown - 40.0f * dt, health);
hud.healthShown = std::fmax(hud.healthShown, health);
It waits until 0.4 s after the last hit, then slides down at 40 points per second; one 8-point hit stays visible for 0.4 + 8 / 40 = 0.6 s.
The second fmax keeps it from ever being below the real health, so when health regenerates (12 per second, from 4 s after the last hit, as in chapter 38), both bars rise together.
The bar's color goes from green over yellow to red with two lerps on the sRGB values.
Interpolating encoded values isn't physically meaningful, but here it doesn't need to be: it's a UI color ramp, and in the 2D rule colors are chosen as they look.
The number is ceil(health), so 0.3 health shows as 1, not 0: the bar must never say "0" while you're still alive.
Ammo
The ammo panel shows the count large, the magazine size small, and one pip per round:
static void ammoPanel(SpriteBatch &batch, const Font &font, const HudState &hud) {
batch.drawRect({1000.0f, 640.0f, 260.0f, 62.0f}, kPanel);
font.draw(batch, "弾 / AMMO", {1012.0f, 646.0f}, {.color = {0.8f, 0.85f, 0.9f, 1.0f}, .shadow = kShadow});
Vec4 c = hud.ammo == 0 ? Vec4{1.0f, 0.3f, 0.25f, 1.0f} : hud.ammo <= hud.magazine / 4 ? Vec4{1.0f, 0.8f, 0.3f, 1.0f}
: kWhite;
font.draw(batch, std::format("{}", hud.ammo), {1190.0f, 644.0f},
{.color = c, .scale = 2.5f, .align = TextAlign::Right, .shadow = kShadow});
font.draw(batch, std::format("/ {}", hud.magazine), {1196.0f, 666.0f}, {.color = {0.8f, 0.8f, 0.8f, 1.0f},
.shadow = kShadow});
// 弾の数だけの小さな印(1発 = 1本) / one small pip per round
for (int i = 0; i < hud.magazine; ++i)
batch.drawRect({1012.0f + 6.0f * static_cast<float>(i), 674.0f, 4.0f, 14.0f},
i < hud.ammo ? Vec4{0.95f, 0.85f, 0.5f, 1.0f} : Vec4{1.0f, 1.0f, 1.0f, 0.15f});
if (hud.reload >= 0.0f) {
font.draw(batch, "装填中 / RELOADING", {640.0f, 410.0f},
{.color = {1.0f, 0.85f, 0.4f, 1.0f}, .align = TextAlign::Centre, .shadow = kShadow});
batch.drawRect({580.0f, 434.0f, 120.0f, 4.0f}, {0.0f, 0.0f, 0.0f, 0.6f});
batch.drawRect({580.0f, 434.0f, 120.0f * hud.reload, 4.0f}, {1.0f, 0.85f, 0.4f, 1.0f});
}
}
The count turns yellow at a quarter of the magazine (6 rounds or fewer) and red at 0.
The pips are 4 × 14 px, 6 px apart: 24 of them fit into 142 px, and the empty ones stay faintly visible, so you see the magazine draining as a shape, without reading numbers.
While reloading, "RELOADING" and a progress bar appear right under the crosshair, where you're looking anyway; PlayScene gives the progress as 1 - reloadTime / kReloadTime, so the bar fills in the 1.6 s of chapter 38's reload.
Enemies left
static void enemiesPanel(SpriteBatch &batch, const Font &font, const HudState &hud) {
float w = 30.0f + 22.0f * static_cast<float>(hud.enemiesTotal);
float x = 640.0f - 0.5f * std::fmax(w, 200.0f);
batch.drawRect({x, 16.0f, std::fmax(w, 200.0f), 52.0f}, kPanel);
font.draw(batch, std::format("敵 / ENEMIES {} / {}", hud.enemiesLeft, hud.enemiesTotal), {640.0f, 20.0f},
{.color = {0.9f, 0.9f, 0.95f, 1.0f}, .align = TextAlign::Centre, .shadow = kShadow});
float x0 = 640.0f - 11.0f * static_cast<float>(hud.enemiesTotal) + 3.0f;
for (int i = 0; i < hud.enemiesTotal; ++i) {
bool alive = i < hud.enemiesLeft;
batch.drawRect({x0 + 22.0f * static_cast<float>(i), 44.0f, 16.0f, 16.0f},
alive ? Vec4{0.85f, 0.2f, 0.15f, 1.0f} : Vec4{1.0f, 1.0f, 1.0f, 0.18f});
}
}
One red square per living enemy and a gray one per dead enemy.
It's the round's goal made visible: when the last square turns gray, you've won.
The panel is at least 200 px wide and centered, so it also works for a level with 3 or 12 enemies.
39.6 Where did that come from? Damage arcs
In a third-person shooter you're often shot from behind or from the side, and the red screen edge from chapter 38 says only that you were hit.
The damage arcs say from where.
When an enemy bullet hits us, enemyFire records the direction to the shooter:
if (hit) {
hurtPlayer(kEnemyDamage);
// HUDの撃たれた向き:撃った敵の水平の向きを、カメラの向きから測る / the HUD's damage direction: the shooter's
// horizontal direction measured from where the camera looks
Vec3 d = e.body.position - position;
hud.damage.push_back({wrapAngle(std::atan2(d.x, -d.z) - camera.yaw), 1.0f});
effects.sparks(end, -1.0f * dir, {6.0f, 0.9f, 0.4f}, 8, rng);
The angle uses the same convention as the camera's yaw from chapter 36: headingForward(yaw) is , so yaw 0 looks along −z and positive yaw turns right.
For a horizontal direction , is the yaw that would look straight at it.
Subtracting the camera's yaw gives the shooter's angle relative to where we look, and wrapAngle brings it into −π..π:
In the example, the camera's yaw is 30° (looking a little to the right) and the shooter is at from us: 4 m to the left and 5 m ahead in world terms.
, so : on the screen the arc sits 68.7° counter-clockwise from the top, up and to the left, which is exactly where we'd have to turn.
The clock-hand convention of spoke makes this a direct mapping: screen up means straight ahead, clockwise means to the right.
(For the horizontal angle we use the player's position, not the camera's; the difference is a meter or two and invisible on a 120 px circle.)
The marker lives for one second and is drawn as five short strokes along the 120 px circle, fading with its life:
void drawHud(SpriteBatch &batch, const Font &font, const HudState &hud) {
// 撃たれたとき:画面の縁を赤く / when hit: a red screen edge
if (hud.hurt > 0.0f) {
Vec4 red = {0.75f, 0.0f, 0.0f, 0.45f * hud.hurt};
batch.drawRect({0.0f, 0.0f, 1280.0f, 36.0f}, red);
batch.drawRect({0.0f, 684.0f, 1280.0f, 36.0f}, red);
batch.drawRect({0.0f, 36.0f, 36.0f, 648.0f}, red);
batch.drawRect({1244.0f, 36.0f, 36.0f, 648.0f}, red);
}
// 撃たれた向き:照準のまわりの赤い弧(敵の方を指す) / where the hits came from: red arcs around the crosshair
// pointing at the shooters
for (const DamageMarker &d : hud.damage) {
Vec4 c = {1.0f, 0.15f, 0.1f, 0.9f * std::clamp(d.life, 0.0f, 1.0f)};
for (int i = -2; i <= 2; ++i) spoke(batch, d.angle + 0.06f * static_cast<float>(i), 120.0f, {14.0f, 5.0f}, c);
}
crosshair(batch, hud);
healthPanel(batch, font, hud);
ammoPanel(batch, font, hud);
enemiesPanel(batch, font, hud);
}
Each stroke is 14 × 5 px with its long side along the circle, and the five are 0.06 rad apart, so together they cover about 0.24 rad, a 29 px piece of the circle plus the strokes' own length.
The red edge is drawn first, then the arcs, then everything else, so the arcs stay readable on top of the red.
The angle is fixed when the hit happens.
If you turn toward the shooter during that second, the arc doesn't move; challenge 4 stores the shooter's world direction instead and recomputes every frame, which is what most shooters do.
39.7 Game flow with the scene stack
The flow is built entirely from chapter 26's SceneManager: push puts a scene on top, pop removes it, replace swaps the top one, replaceAll empties the stack and starts over, and a Transition adds a fade.
An overlay scene (isOverlay() true) lets the scenes below it draw, but only the top scene is updated, so whatever is below stays frozen.
All three new scenes live in menu_scenes.hh and .cc.
They get the game's shared Game struct by reference, like PlayScene, so they can use the renderer, the level, the batch and the font.
The title screen
The title isn't a picture: it renders the real level with the real renderer, seen by a camera that circles it.
void TitleScene::enter() { g.window.setCursorCaptured(false); }
void TitleScene::update(float dt) {
prevTime = time;
time += dt;
if (g.input.actionPressed("confirm")) scenes().replace(std::make_unique<PlayScene>(g), kFade);
if (g.input.pressed(GLFW_KEY_ESCAPE)) scenes().pop(); // 最後のシーン → 終了 / the last scene → quit
}
void TitleScene::draw(float alpha) {
// 背景:レベルの上をゆっくり回るカメラ(遊ぶときと同じ3Dのフレーム:影 → 場面 → 後処理)
// Background: a camera slowly circling over the level (the same 3D frame as in play: shadows → scene → post)
Renderer &r = g.renderer;
float t = prevTime + (time - prevTime) * alpha;
float a = 0.12f * t + 0.6f;
FrameView view;
view.eye = {15.0f * std::sin(a), 5.5f, 15.0f * std::cos(a)};
view.forward = normalize(Vec3{0.0f, 2.0f, 0.0f} - view.eye);
view.aspect = static_cast<float>(g.window.width()) / static_cast<float>(g.window.height());
view.time = t;
LightSet lights;
lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {2.6f, 2.45f, 2.2f}};
r.beginFrame(view, lights);
if (r.beginShadows()) {
g.level.drawShadows(*r.shadow, r.white, r.lightFrustum());
r.endShadows();
}
r.beginScene();
r.pbrInstanced->use();
g.level.draw(*r.pbrInstanced, r.white, r.viewFrustum());
r.drawSky();
r.endScene();
r.present(g.window.width(), g.window.height());
}
The frame is the same as in PlayScene (shadows → scene → sky → post), just without the characters, the effects and the HUD.
The camera circles at 15 m from the center and 5.5 m high, looking at a point 2 m above the floor, and turns at 0.12 rad/s, so one lap takes s, slow enough to read as calm.
The angle is interpolated with alpha between the last two fixed steps, as chapter 26 taught for anything that moves, so the background is smooth at any frame rate.
Using the real level has a cost: the title is as expensive to draw as the game itself.
On a GPU that's nothing; on llvmpipe the title runs at the game's frame rate.
The benefit is that the first thing a player sees is the actual place they're about to fight in, and that there's no separate art to make or keep up to date.
drawUi puts a dark band across the middle and the text on it, with the shared mono16 font at ×2 and ×4.
The "PRESS SPACE" line blinks with , so its alpha swings between 0.1 and 1.0 every s; it never disappears completely.
confirm is a new action bound to Space and Enter in main.
replace with a 0.8 s fade means: 0.4 s fading to black with nothing updated, then the switch (TitleScene::exit, PlayScene::enter), then 0.4 s fading in while the new scene already runs.
TitleScene::enter releases the mouse cursor, PlayScene::enter captures it again.
Winning and losing
In chapter 38, at 0 health you fell over and respawned after 3 s, forever.
Now a round ends.
PlayScene::update gets two new steps at its end (step 9 also holds the lagging health bar from 39.5):
// 9. HUDの値(第39章) / 9. the HUD's values (chapter 39)
int left = 0;
for (const Enemy &e : enemies) left += e.alive() ? 1 : 0;
if (alive && left > 0) roundTime += dt;
// 遅れて減る棒:0.4秒待ってから毎秒40ずつ追いつく / the lagging bar waits 0.4 s, then catches up at 40 per second
if (sinceHurt > 0.4f) hud.healthShown = std::fmax(hud.healthShown - 40.0f * dt, health);
hud.healthShown = std::fmax(hud.healthShown, health);
for (DamageMarker &d : hud.damage) d.life -= dt;
std::erase_if(hud.damage, [](const DamageMarker &d) { return d.life <= 0.0f; });
// 10. 勝ち・負け:少し見せてから結果の画面を重ねる。敵のいないレベル(pieces.level)は勝ちにならない
// 10. win / loss: show it for a moment, then push the result screen. A level without enemies (pieces.level) is
// never won
bool cleared = left == 0 && !enemies.empty();
if (!finished && (!alive || cleared)) {
endTimer += dt;
if (endTimer > (alive ? 2.0f : 2.5f)) {
finished = true;
RoundResult result{.won = alive, .seconds = roundTime, .kills = kills,
.enemies = static_cast<int>(enemies.size()), .shotsFired = shotsFired, .shotsHit = shotsHit};
scenes().push(std::make_unique<ResultScene>(g, result));
}
}
The round ends either way, but not instantly.
When the last enemy falls, the "ALL ENEMIES DOWN" text and the falling animation get 2 s; when you fall, the "DOWN" text and your own fall get 2.5 s.
Only then is ResultScene pushed, once, which finished guarantees.
A level without enemies, such as pieces.level, is never won (cleared needs at least one enemy), so you can still walk around it to look at the pieces.
roundTime counts only while you're alive and enemies remain, so the time on the result screen is the time the fight took, without the pause before the result.
The result screen
RoundResult is the hand-over from the round to the result screen: a small value type, copied into the new scene.
// 一回の結果(PlaySceneが渡す) / the outcome of one round (PlayScene hands it over)
struct RoundResult {
bool won = false;
float seconds = 0.0f;
int kills = 0, enemies = 0, shotsFired = 0, shotsHit = 0;
};
// 勝ち・負け:PlaySceneの上に重ねる(下の絵は止まったまま見える)。Space もう一度、Esc タイトルへ
// Win / lose: an overlay on PlayScene (the frozen picture stays visible below). Space retry, Esc back to the title
class ResultScene : public Scene {
public:
ResultScene(Game &game, RoundResult result) : g(game), r(result) {}
bool isOverlay() const override { return true; }
void enter() override;
void update(float dt) override;
void draw(float /*alpha*/) override {}
void drawUi(float alpha) override;
private:
Game &g;
RoundResult r;
float time = 0.0f;
};
The result is an overlay, so the frozen round stays visible behind a dark panel:
In the winning run, the last enemy fell at 9.8 s, and 14 of 30 shots hit: , printed as 47 %.
The stats are one string with three lines, formatted with std::format; {:04.1f} pads the seconds to "09.8" so the time reads like a clock.
// 結果の画面ではマウスを使えるように(もう一度:PlayScene::enterがまた捕まえる) / free the cursor on the result
// screen (retry: PlayScene::enter captures it again)
void ResultScene::enter() { g.window.setCursorCaptured(false); }
void ResultScene::update(float dt) {
time += dt;
if (time < 0.5f) return; // 撃ち続けていたボタンで飛ばさない / do not skip it with a button still held from play
if (g.input.actionPressed("confirm")) scenes().replaceAll(std::make_unique<PlayScene>(g), kFade);
if (g.input.pressed(GLFW_KEY_ESCAPE)) scenes().replaceAll(std::make_unique<TitleScene>(g), kFade);
}
Three decisions are hidden in these lines.
The first is the 0.5 s of ignored input.
At the moment the round ends you're usually still pressing something: the fire button, or Space for a jump.
Without the guard, a Space held from the fight would retry before you'd even seen the result.
The panel also fades in over 0.4 s, so by the time it's readable it accepts input.
The second is what "retry" means.
replaceAll with a new PlayScene throws away the whole round (enemies, their AI states, health, ammo, the effects, the round time) and builds a fresh one from the level data.
Nothing has to be reset by hand, because everything that belongs to a round lives in the scene object, and everything that outlives a round (the window, the renderer, the models, the level) lives in Game.
That split, decided in chapter 36, is what makes "play again" a single line here, and it's the same idea as the RPG's World in chapter 34: deciding which state belongs to which lifetime is most of the work of a game flow.
The third is the mouse cursor.
During the round it's captured, and an overlay doesn't change that by itself, so ResultScene::enter releases it: on the result screen you can move the mouse to another window.
Retrying builds a new PlayScene, whose enter captures it again, and the title releases it anyway.
Pausing
Esc in the play scene now pushes PauseScene instead of quitting:
// Esc:一時停止(第39章。上に重ねるので、この場面は止まったまま描かれる) / Esc: pause (chapter 39; an overlay, so
// this scene stays visible, frozen)
if (in.pressed(GLFW_KEY_ESCAPE)) scenes().push(std::make_unique<PauseScene>(g));
void PauseScene::enter() { g.window.setCursorCaptured(false); }
void PauseScene::exit() { g.window.setCursorCaptured(true); }
void PauseScene::update(float dt) {
time += dt;
if (g.input.pressed(GLFW_KEY_ESCAPE) || g.input.actionPressed("confirm")) scenes().pop();
if (g.input.pressed(GLFW_KEY_T)) scenes().replaceAll(std::make_unique<TitleScene>(g), kFade);
}
Pausing is where the scene stack pays off.
Because only the top scene is updated, the round stops completely: no enemy moves, no timer runs, the AI's reaction times and the reload don't advance, and the fixed-step loop keeps running for the pause scene alone.
Because the pause scene is an overlay, the frozen round is still drawn behind it.
And because SceneManager::push calls PlayScene::pause(), which sets every prev copy to the current value (chapter 26), the interpolated picture doesn't wobble between two steps while paused.
The cursor follows the scenes: PauseScene::enter releases it so you can move the mouse to another window, and exit captures it again when you resume.
If T leaves the pause for the title, exit captures it and TitleScene::enter releases it right after, so the net effect is correct without special cases.
Arguments: --play and --msaa
main now starts at the title and reads two flags, before anything else:
// 引数を先に読む:レベルのパスは起動したディレクトリから見たものなので、データの場所へ移る前に絶対パスにする
// Read the arguments first: a level path is relative to the directory we were started in, so make it absolute
// before moving to the data
std::string levelPath = "games/tps/assets/levels/arena.level";
// --playでタイトルを飛ばしてすぐ遊ぶ(試すとき、台本で動かすとき) / --play skips the title (for testing and
// scripted runs)
bool skipTitle = false;
RenderSettings settings;
for (int i = 1; i < argc; ++i) {
if (std::string_view(argv[i]) == "--play") skipTitle = true;
// --msaa:エンジンの既定の後処理(4× MSAA、RGBA16F、ブルーム4組)と比べる / --msaa: compare with the engine's
// default post chain (4× MSAA, RGBA16F, 4 bloom pairs)
else if (std::string_view(argv[i]) == "--msaa") settings.post = PostChainSettings{};
else {
std::error_code ec;
std::filesystem::path p = std::filesystem::absolute(argv[i], ec);
levelPath = ec ? std::string(argv[i]) : p.string();
}
}
findDataDirectory(argv[0]);
Window window;
if (!window.create(1280, 720, "OpenGL Tutorial - TPS")) return 1;
std::unique_ptr<Renderer> renderer = Renderer::create(window.width(), window.height(), settings);
if (!renderer) return 1;
window.onResize = [&](int width, int height) { renderer->resize(width, height); };
SceneManager scenes;
// 第39章:タイトルから / chapter 39: start at the title
if (skipTitle) scenes.push(std::make_unique<PlayScene>(game));
else scenes.push(std::make_unique<TitleScene>(game));
// pushは予約だけ:更新0回の最初のフレームも描けるように、ここで適用する(シーンの更新は呼ばれない)
// push only queues the request: apply it now so that the first frame (which runs no update) has a scene to draw
// (no scene's update is called)
scenes.update(0.0f);
--play skips the title and starts exactly as chapter 38 did.
That matters for scripted runs: going through the title adds the fade's fixed steps before the round starts, and a recorded mouse script would then land half a frame late.
The clips and screenshots of this chapter use --play wherever they aim.
--msaa replaces the TPS's light post-processing settings with the engine's defaults, for the comparison in the next section.
Any other argument is a level file, turned into an absolute path right away; 39.10 explains why that has to happen before findDataDirectory.
39.8 Performance: measure first
How the game measures itself
Every 60 frames, the TPS prints the averages to the terminal.
Here is the second line (frames 61 to 120) of two runs of tps --play, one right after the other, on the same quiet machine:
frames 61-120: CPU 121.2 ms/frame, llvmpipe raster shadow 5.2 / scene 104.7 / post 10.7 ms, scene fragments 1.07 M
frames 61-120: CPU 117.7 ms/frame, llvmpipe raster shadow 4.9 / scene 101.7 / post 10.4 ms, scene fragments 1.07 M
The same frames, the same input, the same picture, and still 3.5 ms apart.
The lines have three kinds of numbers, and they deserve different amounts of trust.
- CPU ms per frame is the wall-clock time between two frames, measured with
std::chrono::steady_clockinmain. It's what the player feels. - shadow / scene / post come from three
GpuTimers (chapter 19),GL_TIME_ELAPSEDqueries around each pass. On a real GPU they measure how long the GPU spent on that pass. - scene fragments comes from the
FragmentCounteradded in chapter 36, aGL_SAMPLES_PASSEDquery around the scene pass.
Chapter 36 (36.6) explained that counter: four query objects in a ring, read like GpuTimer's only once GL_QUERY_RESULT_AVAILABLE says so, so measuring never makes the CPU wait for the GPU.
It counts the samples that pass the depth and stencil tests, which without MSAA are the fragments that get written, and it runs at the same time as the scene pass's GL_TIME_ELAPSED query, because queries of different targets may overlap.
The fragment count isn't exactly the shading work: a fragment that's shaded and then fails the depth test isn't counted, and one that's overwritten later is counted twice.
But it has one property the times don't have: it's the same in every run.
The game logic is deterministic, the camera is in the same place, and the rasterizer produces the same fragments, no matter what else the machine is doing.
The numbers
All numbers in this chapter were measured on the same machine as every screenshot: Mesa's llvmpipe, a software rasterizer, on two CPU cores.
On llvmpipe "the GPU" is the CPU, so every millisecond below, including the "GPU" timer queries, is CPU time spent rasterizing and shading.
They are not GPU numbers, and they don't predict what your GPU will do; they show how the costs relate to each other on this one rasterizer.
The method: tps --play, standing at the spawn while the guard on the platform shoots (the same in every run), the average of frames 61 to 120, each configuration twice, on a quiet machine, at 1280 × 720:
| Configuration | CPU frame | Shadow pass | Scene pass | Post | Scene fragments |
|---|---|---|---|---|---|
| Default: shadow map 2048², no MSAA | 118–121 ms | 4.9–5.2 ms | 102–105 ms | 10.4–10.7 ms | 1.07 M |
| F5: render scale 75 % | 78–79 ms | 5.0–5.3 ms | 62–63 ms | 9.9–10.1 ms | 0.60 M |
| F5 twice: render scale 50 % | 48–51 ms | 5.1–5.5 ms | 33–35 ms | 9.7–10.1 ms | 0.27 M |
| F6: shadows off | 94–97 ms | 0 | 82–86 ms | 10.8–11.1 ms | 1.07 M |
The default "scene pass" includes everything between beginScene and endScene: the level, the characters, the sky, the particles, and the bloom blur at half size.
"Post" is the last fullscreen pass to the window.
The three passes add up to the frame time within a millisecond or two; the rest is our own CPU code (the update, the AI, culling, the sprite batch).
Reading them honestly
The fragments follow the render scale squared.
At 1280 × 720 the window has 921 600 pixels, and the scene pass writes 1.07 M fragments, about 1.16 per pixel: the floor, the walls and the characters overlap a little.
At 75 % the scene is 960 × 540 = 518 400 pixels and the count is 0.60 M; at 50 % it's 640 × 360 = 230 400 pixels and 0.27 M.
and , the same overdraw of 1.16–1.17 at every size.
These counts are what I'd trust first in any A/B comparison on this machine.
The scene pass follows the fragments.
The three scene-pass times lie almost exactly on a line: about 10 ms plus 87 ms per million fragments (that line predicts 103.5, 62.6 and 33.9 ms for the three counts; measured were 102–105, 62–63 and 33–35).
So on llvmpipe, one fragment of pbr.frag (Cook–Torrance, IBL, nine PCF shadow taps) costs about 87 ns of CPU time.
The post pass shades 921 600 pixels in about 10.5 ms, about 11 ns each, so a scene fragment costs roughly eight post fragments.
The post pass doesn't shrink with the render scale, because it always covers the whole window.
Fragment cost dominates.
Half the render scale in each direction gives a quarter of the fragments and takes the frame from about 120 ms to about 50 ms.
The shadow pass (5 ms) and the post pass (10.5 ms) are fixed costs that the render scale doesn't touch, which is why 50 % isn't four times faster.
Shadows cost more in the scene pass than in the shadow pass.
Turning shadows off saves about 24 ms per frame, but the shadow pass itself was only about 5 ms.
The other 19–20 ms come out of the scene pass: without shadows, pbr.frag skips the 3 × 3 PCF lookups, about 18 ns per fragment over 1.07 M fragments.
The fragment count is identical (shadows don't change what's visible), so this is a pure per-fragment saving.
The other variants were measured while other jobs shared the two cores, so only paired runs (default and variant back to back) can be compared, and only roughly:
| Variant | Default → variant (CPU frame, two pairs) | What changed |
|---|---|---|
| F7: shadow map 1024² | 420 → 341 ms, 280 → 332 ms | the shadow pass went from 9–11 ms to 3.6–4.2 ms, under half; the frame difference is inside the noise |
| F4: no frustum culling | 504 → 386 ms, 359 → 376 ms | inside the noise |
--msaa: 4× MSAA, RGBA16F, 4 bloom pairs |
360 → 548 ms, 359 → 389 ms | the scene pass took 15–60 % longer; 4.29 M samples instead of 1.07 M |
| Release build | 475 → 464 ms, 343 → 401 ms | inside the noise |
Look at the first two pairs of the culling row: one says culling off is 118 ms faster, the other 17 ms slower.
That's what noise looks like on a loaded machine, and it's why I never trust one frame or one run: only averages, only pairs, and preferably a measure like the fragment count that doesn't depend on the load at all.
Render scale
The strongest knob on this machine is rendering the 3D scene at fewer pixels.
Renderer keeps the window size and a scale, and sizes the post chain's framebuffers from both:
// ウィンドウの大きさが変わった / the window size changed
void resize(int width, int height);
// 描く解像度(第39章の速さの工夫):場面のFBOをウィンドウのscale倍にして、後処理で画面いっぱいに引き伸ばす。
// フラグメントの数がscale²倍になる
// Render scale (chapter 39's performance tip): the scene FBOs are scale × the window size and the post pass
// stretches them over the screen. The fragment count goes with scale²
void setRenderScale(float scale);
float renderScale() const { return scale; }
void setShadowMapSize(int size) { shadowMap->resize(size); }
int shadowMapSize() const { return shadowMap->size(); }
void Renderer::resize(int width, int height) {
windowW = width;
windowH = height;
setRenderScale(scale);
}
void Renderer::setRenderScale(float s) {
scale = s;
post->resize(std::max(1, static_cast<int>(std::lround(s * static_cast<float>(windowW)))),
std::max(1, static_cast<int>(std::lround(s * static_cast<float>(windowH)))));
}
PostChain::resize resizes the scene framebuffers (and the half-size bloom buffers with them), and Framebuffer::bind sets glViewport to the framebuffer's own size, so the scene pass automatically renders into the smaller image.
present still binds the default framebuffer at the full window size, and the post pass's fullscreen triangle samples the smaller scene texture with GL_LINEAR: the upscale costs nothing extra, it's the same pass as before.
Then the HUD is drawn at full resolution on top:
The 3D image gets softer, the crosshair doesn't.
This is the reason the HUD is drawn after post: lowering the render scale is the most common way games keep their frame rate, and the UI must stay crisp while it happens.
resize keeps the scale when the window changes size, and the F5 key handler just cycles through three values:
// 速さの工夫(第39章):F5 描く解像度 100 → 75 → 50 %、F6 影のオン・オフ、F7 影の地図 2048 ⇔ 1024
// Performance options (chapter 39): F5 render scale 100 → 75 → 50 %, F6 shadows on / off, F7 shadow map 2048 ⇔ 1024
if (in.pressed(GLFW_KEY_F5)) {
float s = g.renderer.renderScale();
g.renderer.setRenderScale(s > 0.9f ? 0.75f : s > 0.6f ? 0.5f : 1.0f);
}
if (in.pressed(GLFW_KEY_F6)) g.renderer.settings.shadows = !g.renderer.settings.shadows;
if (in.pressed(GLFW_KEY_F7)) g.renderer.setShadowMapSize(g.renderer.shadowMapSize() == 2048 ? 1024 : 2048);
Shadows and the shadow map
F6 sets RenderSettings::shadows, which the renderer already passed to ShadowMap::begin since chapter 36: the shadow pass is skipped, and the Shadow block tells pbr.frag there's no shadow to look up.
F7 calls ShadowMap::resize, which rebuilds the depth texture at 1024².
That's a quarter of the texels, so the shadow pass got much cheaper, but each texel now covers 45.8 mm instead of 22.9 mm on the ground (the F3 band shows it), and shadow edges get blockier.
On this machine the frame barely noticed; the shadow pass was never the expensive part.
MSAA, culling and Release builds
--msaa switches to the engine's default PostChainSettings{}: 4× MSAA, RGBA16F and four bloom pairs.
GL_SAMPLES_PASSED counts samples, so it reports 4.29 M, four times 1.07 M.
llvmpipe still runs the fragment shader once per pixel, but it stores four samples per pixel and resolves them, and the format is twice as large, so the scene pass took 15–60 % longer in the pairs.
That's why the TPS uses {samples 0, GL_R11F_G11F_B10F, 3 bloom pairs} by default (chapter 36).
Turning off frustum culling (F4) made no measurable difference here.
Off-screen pieces are clipped before rasterization anyway, so culling saves only vertex work and driver overhead, and on llvmpipe both are small next to a million shaded fragments.
A Release build didn't change the frame time either, and that's expected too.
Our own C++ code (the update, the AI, culling, the sprite batch) takes a few milliseconds; the rest of the frame is inside Mesa, which is an optimized library whether our program is or not.
39.9 What matters on a real GPU
Everything in 39.8 is true for llvmpipe, and much of it turns around on a real GPU.
A desktop GPU shades a million PBR fragments in a small fraction of a millisecond, so the whole TPS frame is very light there, and the bottleneck moves to places that llvmpipe hides:
- The CPU side. Draw calls, state changes, uniform and buffer updates, and our own game code. Here a Release build matters a lot, and instancing and culling (chapter 19, chapter 36) save real time, because each draw call costs driver work on the CPU.
- Memory bandwidth. Every framebuffer write and every texture read moves memory. MSAA multiplies the samples written and resolved, RGBA16F is twice the size of
GL_R11F_G11F_B10F, and every bloom pass reads and writes a whole image. These costs are real on GPUs too, especially on integrated and mobile ones. - Overdraw and early depth. Fragments that fail the depth test before shading are almost free on a GPU. Drawing the things that hide the most first (the level has drawn its floor last since chapter 36) and the sky last lets the hardware reject hidden fragments early. A shader that uses
discardor writes depth can turn this off. - Resolution. Fragment cost still grows with the pixel count, and at 4K a GPU shades 8.3 million pixels per frame. That's why render scale exists in real games too, usually as dynamic resolution: the engine lowers the scale when the GPU time goes over budget and raises it again when there's room, with the HUD drawn at full resolution on top, exactly like ours.
- Shadows. The shadow-map size, the distance the shadows cover (our 20 m frustum fit from chapter 36) and the filter (our 3 × 3 PCF) are the usual quality settings.
The rules that don't change:
- Measure before optimizing. Guessing where the time goes is wrong surprisingly often; the 24 ms of shadows in 39.8 were mostly not in the shadow pass.
- Measure the CPU and the GPU separately. If the CPU frame is 16 ms and the GPU passes add up to 4 ms, the GPU is waiting, and no shader optimization will help. The F3 band and the per-pass
GpuTimers show both. - Average, and compare in pairs. One frame means nothing; 60 frames are a number; the same 60 frames with and without a change are a comparison.
- Count work, not just time. Fragment counts, draw calls, triangles and texture sizes don't fluctuate with load, so they're the best way to check that a change did what you think.
- Use a frame debugger. RenderDoc (Windows and Linux) captures one frame and shows every draw call with its state, its inputs and outputs, and timings per event, which answers "what is this pass actually drawing?" faster than any printf. The GPU vendors' profilers (NVIDIA Nsight Graphics, AMD Radeon GPU Profiler, Intel GPA) go further on their own hardware.
39.10 Packaging
So far every program in this series ran from the project root: the working directory had to be the root (chapter 1), because the code loads engine/shaders/…, assets/… and games/tps/… relative to it.
That's convenient during development and useless for giving the game to someone.
A package is a folder with the executable and exactly the data it needs, that runs from wherever it is.
Release builds
Until now we built without a build type on Linux and FreeBSD, and the Debug configuration in Visual Studio.
Neither optimizes.
A Release build compiles with optimization (-O3 with GCC and Clang, /O2 with MSVC) and defines NDEBUG, which turns assert off:
cmake -S . -B build-release -DCMAKE_BUILD_TYPE=Release
cmake --build build-release --target tps -j8
Single-configuration generators (Makefiles, Ninja) choose the build type when configuring, so a Release build gets its own build directory.
Visual Studio is a multi-configuration generator: one build tree, and the configuration is chosen when building, cmake --build build --config Release --target tps.
The Release executable here is noticeably smaller than the unoptimized one: the installed folder is 3.2 MB with it and 4.4 MB without.
Install rules
CMake's install commands describe what a package contains and where each piece goes.
They do nothing during a normal build; they run when you call cmake --install.
The TPS's rules are at the end of its CMakeLists.txt:
# 配布(第39章):cmake --install <build> --prefix <dir> --component tps で <dir>/tps/ に実行ファイルと使うデータを
# プロジェクトと同じ並びで置く(tpsは見つからなければ実行ファイルの隣のデータを使う)。
# Release: cmake -S . -B build-release -DCMAKE_BUILD_TYPE=Release(Visual Studio: --config Release)
# Packaging (chapter 39): cmake --install <build> --prefix <dir> --component tps puts the executable and the data it
# uses into <dir>/tps/, laid out like the project (tps falls back to the data next to its executable).
# Release: cmake -S . -B build-release -DCMAKE_BUILD_TYPE=Release (Visual Studio: --config Release)
install(TARGETS tps RUNTIME DESTINATION tps COMPONENT tps)
install(DIRECTORY ${PROJECT_SOURCE_DIR}/engine/shaders DESTINATION tps/engine COMPONENT tps)
install(DIRECTORY ${PROJECT_SOURCE_DIR}/assets/textures/sky DESTINATION tps/assets/textures COMPONENT tps)
install(FILES ${PROJECT_SOURCE_DIR}/assets/models/crate.glb ${PROJECT_SOURCE_DIR}/assets/models/barrel.glb
DESTINATION tps/assets/models COMPONENT tps)
install(FILES ${PROJECT_SOURCE_DIR}/assets/LICENSE.txt DESTINATION tps/assets COMPONENT tps)
install(DIRECTORY assets shaders DESTINATION tps/games/tps COMPONENT tps)
install(FILES README.md DESTINATION tps/games/tps COMPONENT tps)
install(TARGETS tps RUNTIME DESTINATION tps …)copies the built executable (RUNTIMEmeans the program itself, not libraries) intotps/under the install prefix. CMake knows where the binary ended up for the chosen configuration, so the same line works for every generator.install(DIRECTORY dir DESTINATION d …)copies a whole directory. Without a trailing slash the directory itself is copied, soengine/shadersends up astps/engine/shaders; withengine/shaders/only its contents would be copied intod.install(FILES … DESTINATION d …)copies single files. The level usescrate.glbandbarrel.glbfrom the sharedassets/models/, so exactly those two are copied, not every model of chapters 1 to 24.- Relative paths are relative to the current
CMakeLists.txt(games/tps/), soassets shadersare the game's own folders; the shared data needs${PROJECT_SOURCE_DIR}, the project root. COMPONENT tpslabels every rule. The project has four games, and--component tpsinstalls only this one.
The destinations recreate the project's layout inside tps/: engine/shaders/, assets/… and games/tps/… sit next to the executable exactly as they sit in the project root.
That's the whole trick: the game's paths don't change at all, only the folder they're relative to.
The license files travel with the data (assets/LICENSE.txt for the shared assets, games/tps/assets/LICENSE.txt for the game's own, including the font notices), as they should in anything you hand out.
Finding the data
The paths are relative to the working directory, and an installed game can be started from anywhere: a terminal in another folder, a desktop shortcut, a file manager.
So main, right after reading its arguments, makes sure the working directory is where the data is:
// 実行ファイルのある所。argv[0]は起動のしかたで変わり、PATHから起動すると名前(tps)だけなので、OSに聞く
// Where the executable is. argv[0] depends on how the program was started (only the name, "tps", when it was found
// through PATH), so ask the OS
static std::filesystem::path executableDirectory(const char *argv0) {
namespace fs = std::filesystem;
std::error_code ec;
#if defined(_WIN32)
char *path = nullptr; // CRTが用意するフルパス / the full path the C runtime provides
if (_get_pgmptr(&path) == 0 && path && *path) return fs::path(path).parent_path();
#elif defined(__linux__)
fs::path self = fs::read_symlink("/proc/self/exe", ec); // 実行中のファイルへのリンク / a link to the running file
if (!ec) return self.parent_path();
#elif defined(__FreeBSD__)
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1}; // -1 = このプロセス / this process
char path[1024];
size_t size = sizeof(path);
if (sysctl(mib, 4, path, &size, nullptr, 0) == 0) return fs::path(path).parent_path();
#endif
// 他のOS、または聞けなかったとき:argv[0](ディレクトリが付いていれば使える) / other systems, or if asking failed:
// argv[0] (usable when it contains a directory)
fs::path p = fs::absolute(fs::path(argv0), ec);
return ec ? fs::path() : p.parent_path();
}
// データのある場所へ移る(第39章、配布)。開発中はプロジェクトのルートから実行するので、そこにデータがある。
// インストールした物は実行ファイルの隣にengine/・assets/・games/tps/を置くので、見つからなければそこへ移る
// Move to where the data is (chapter 39, packaging). During development we run from the project root, which has the
// data. An installed copy keeps engine/, assets/ and games/tps/ next to the executable, so if the data is not found
// here, go there
static void findDataDirectory(const char *argv0) {
namespace fs = std::filesystem;
const fs::path marker = "games/tps/assets/levels/arena.level";
std::error_code ec;
if (fs::exists(marker, ec)) return;
fs::path exeDir = executableDirectory(argv0);
if (!exeDir.empty() && fs::exists(exeDir / marker, ec)) {
fs::current_path(exeDir, ec);
printf("data: %s\n", exeDir.string().c_str());
} else {
fprintf(stderr, "データが見つからない(プロジェクトのルートから実行する) / data not found (run from the project root)\n");
}
}
If the level file can be found from the current directory, nothing changes: that's the project root during development, and Visual Studio's debugger working directory (set_working_directory) keeps working as before.
Otherwise it asks executableDirectory where the program is and, if the data is there, makes that the working directory with std::filesystem::current_path.
All std::filesystem calls take a std::error_code, so nothing throws (the series doesn't use exceptions); if the data is nowhere, the game says so, and the next load fails with a clear file name.
Why not simply argv[0]?
It's whatever the program was started with: an absolute or relative path in a terminal (fine), usually the full path from a file manager (fine), but just tps when the program was found through PATH, and then absolute makes it relative to the current directory, which is wrong.
So executableDirectory asks the operating system, which always knows:
- Linux:
/proc/self/exeis a symbolic link to the running executable, andstd::filesystem::read_symlinkreads it. - FreeBSD:
/procis usually not mounted, so the path comes fromsysctlwithCTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1, where −1 means "this process". - Windows: the C runtime's
_get_pgmptrgives the full path of the program, somain.ccdoesn't need<windows.h>(whosenear,far,minandmaxmacros clash with ordinary code) forGetModuleFileNameW. - Anything else, or if asking fails:
argv[0], which is right whenever it contains a directory.
The order in main matters too.
A level path given on the command line is relative to the folder you typed it in, so it's made absolute (std::filesystem::absolute) while that's still the working directory, before findDataDirectory moves away.
tps --play mylevel.level started from another folder then loads mylevel.level from that folder, and the game's own files from the package.
Building the package
cmake -S . -B build-release -DCMAKE_BUILD_TYPE=Release
cmake --build build-release --target tps -j8
cmake --install build-release --prefix dist --component tps
./dist/tps/tps
--prefix dist puts everything under dist/, so the game ends up in dist/tps/.
Here it is, started from / to prove that the working directory doesn't matter:
(The screenshot used a build directory called build; the name doesn't matter.)
To hand it out, zip dist/tps/ (or make a .tar.gz on Linux and FreeBSD, which keeps the executable bit).
An alternative to install rules is a POST_BUILD step that copies the data next to the executable in the build tree (add_custom_command(TARGET tps POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory …)).
That's simpler for one directory but copies on every build and mixes data into the build tree; install rules keep the package description in one place and work with every generator.
Windows, Linux and FreeBSD
- Windows (Visual Studio): build and install with the configuration,
cmake --build build --config Release --target tpsand thencmake --install build --config Release --prefix dist --component tps; the executable isdist\tps\tps.exe. GLFW is linked statically (glfw3.lib), so no GLFW DLL is needed. The program does need the Microsoft C++ runtime: either the player installs the Visual C++ Redistributable (most Windows PCs already have it), or you link the runtime statically with/MT(CMake:CMAKE_MSVC_RUNTIME_LIBRARYset toMultiThreaded), which also needs the GLFW library built for/MT(glfw3_mt.libin the prebuilt package). Ship the folder as a zip. - Linux: the executable links the system's GLFW, so the player needs the package that provides
libglfw.so.3(ldd dist/tps/tpslists what's needed), and a driver with OpenGL 4.6. For wider distribution, link GLFW statically or bundle it next to the executable. - FreeBSD: the same as Linux: GLFW comes from
pkg install glfw,lddworks the same way, and the graphics driver comes from Mesa (withdrm-kmodfor the kernel side). - All: the package doesn't contain the source, the build tree or
external/; GLAD andstb_imageare compiled into the executable, andlinalg.hhis a header.
39.11 How real engines do it
- HUDs: engines have UI systems with layout, anchors and styling, such as Unreal's UMG, Unity's UI Toolkit and uGUI, and middleware like Noesis GUI or RmlUi; tools and debug overlays very often use Dear ImGui, an immediate-mode library that is close in spirit to our "fill a struct, draw it every frame". They lay out against a reference resolution and scale to the screen (like our 1280 × 720 virtual screen with letterboxing), keep important elements inside a safe area for TVs, and offer accessibility options (HUD scale, color-blind-friendly colors, subtitles).
- Hit feedback: hit markers, kill markers, damage-direction indicators and lagging health bars are standard in shooters, usually combined with sound, controller vibration and a small camera shake; the audio is often the strongest cue.
- Game flow: a state machine or a stack of screens like ours, plus loading screens and level streaming once the data takes longer than a moment to load, and a save system for anything that outlives a session.
- Performance: dynamic resolution combined with temporal upscalers (AMD FSR, NVIDIA DLSS, Intel XeSS) that reconstruct a sharp full-resolution image from a lower internal resolution, much better than our bilinear stretch; GPU-driven rendering (culling in compute shaders and indirect draws) to cut CPU work; and constant profiling in development builds with per-pass GPU timers like ours.
- Packaging: CMake's own CPack turns the same install rules into zips, installers and Linux packages; stores (Steam, itch.io) take a folder per platform; Linux games are also shipped as AppImage or Flatpak. Big games pack their loose files into archives (pak or zip files), which load faster and are harder to break by accident.
39.12 The shooter in review
Four chapters took us from a level of GLB pieces to a finished little game:
- Chapter 36: the level from GLB pieces with instancing and frustum culling, the PBR renderer with shadows fitted to the camera, the character built from rigid parts with a procedural pose, and the over-the-shoulder camera that never goes through walls, with movement relative to where it looks.
- Chapter 37: the player as a capsule pushed out of the level's boxes, gravity and jumping with coyote time and a jump buffer, sliding along walls by removing the velocity along the wall's normal with the dot product, and climbing and snapping down steps.
- Chapter 38: shooting with two rays (from the camera to find the aim point, from the muzzle to fire), ray–box, ray–sphere and ray–capsule tests, enemies with a state machine and line of sight, and the effects: muzzle flashes as lights, tracers, sparks.
- This chapter: a HUD drawn from a plain state struct after post-processing, the title, result and pause scenes on the scene stack, render scale and shadow options with honest llvmpipe measurements, and an installable package.
39.13 Looking back over the series
That was the last chapter of the OpenGL series.
Here is the whole road, from an empty window to four games:
- Part 1, getting started (chapters 1 to 9): the project on Windows, Linux and FreeBSD, a window with a debug context and a render loop, buffers and vertex arrays with Direct State Access, index buffers, a shader class with uniforms and hot reload, textures, transformations with
linalg.hh, depth, and a camera. - Part 2, lighting (chapters 10 to 12): Phong lighting with the normal matrix, materials and lighting maps, directional, point and spot lights.
- Part 3, models (chapters 13 and 14): our own glTF/GLB reader with a small JSON parser, and loading textured models with their node hierarchy.
- Part 4, advanced OpenGL (chapters 15 to 24): depth and stencil tests, blending and culling, framebuffers and post-processing, cubemaps, uniform buffers and instancing, anti-aliasing, gamma correction and HDR, normal mapping, shadow mapping, and physically based rendering with image-based lighting.
- Part 5, 2D and game foundations (chapters 25 and 26): the engine library, sprites and a sprite batcher, bitmap-font text, a fixed-timestep game loop, input actions and a scene stack.
- Part 6, four games (chapters 27 to 39): Space Invaders with instancing and collisions, a 2D fighter with hitboxes, a scene graph, scrolling stages and an AI opponent, a top-down RPG with tilemaps, maps, doors, dialogue and a quest, and this third-person shooter.
Notice how the weight shifted.
Part 1 was nearly all OpenGL calls.
By Part 4 the calls were familiar and the chapters were about techniques: what a shadow map is, why HDR needs tone mapping, how a BRDF conserves energy.
In Part 6 there was hardly any new OpenGL at all, and the chapters were about game design: state machines, collision response, data files, game flow.
That's how it is in real projects too: the API is the floor you stand on, and once it holds, the interesting problems are above it.
39.14 What you can build now
You now know every piece of a small real-time renderer and game, and you've built each piece yourself:
- a modern OpenGL 4.6 renderer with PBR materials from glTF files, image-based lighting, shadow maps fitted to the camera, HDR with bloom and tone mapping, and instancing for repeated geometry
- a 2D layer for sprites, text and UI on top of it, with correct color handling
- a fixed-step game loop with interpolation, input actions, a scene stack with transitions, deterministic randomness
- collision and physics in 2D and 3D, raycasts, and simple state-machine AI
- data-driven content: levels, maps, dialogue and items in text files, checked at start-up
- measurement and packaging: timer queries, fragment counts, Release builds and install rules
The four games are deliberately small, which makes them good starting points.
Some directions to take them:
- Invaders: waves with new formations and alien types, power-ups, a two-player mode, sound effects with a small audio library (miniaudio, for example), a high-score table saved to a file.
- The fighter: more characters loaded from data files instead of code, special moves with input buffers (quarter circles), a training mode that shows hitboxes and frame data, and online play with rollback netcode, which the deterministic fixed-step loop makes possible.
- The RPG: a battle system, a save system for the
Worldstate, a map editor (or loading maps from the Tiled editor), more quests in the dialogue script, and character portraits in the dialogue box. - The shooter: skinned animation (the rigid-part character of chapter 36 is the motivation), cascaded shadow maps for a bigger level, a navigation mesh and A* for the enemies instead of chapter 38's straight lines, waves of enemies, sound with 3D positioning, and a minimap.
Making a fifth game from scratch, using the engine library, is the best exercise of all.
39.15 What comes next: Slang and Vulkan
After OpenGL, the next series on this site are Slang and then Vulkan.
They aren't published yet; when they are, you'll find them in the tutorial index.
Slang is a shading language that compiles one source to several targets, including SPIR-V for Vulkan.
If you know GLSL from the GLSL series and this one, it will feel familiar: it has the same vectors, matrices and built-in functions under slightly different names (float3, mul, lerp), and it adds modules, generics and interfaces, so a large shader code base can be organized like ordinary code instead of being glued together with #include and #define.
Vulkan is the explicit API that this series has been preparing you for since chapter 1.
Where OpenGL's driver keeps a global state and decides on its own when to allocate memory, compile pipelines and synchronize, Vulkan makes you do it: command buffers that you record and submit, pipeline objects that contain the whole state of a draw, descriptor sets that bind buffers and textures, explicit memory allocation and explicit synchronization with barriers, semaphores and fences.
The Vulkan series will use Slang for its shaders, so it builds on the Slang series.
OpenGL is recommended before it, but not required.
What you built here maps onto Vulkan almost piece by piece.
A Shader plus its blend, depth and cull state becomes a pipeline; a uniform buffer bound with layout(binding = N) becomes a descriptor; a framebuffer with its attachments becomes the attachments of a render pass; glMemoryBarrier and the implicit ordering of OpenGL become explicit barriers.
The ideas (vertex layouts, std140-like layouts, render-to-texture, shadow maps, HDR, PBR, instancing) are exactly the same, and everything you learned about the math in the Linear Algebra series stays true, apart from the different clip-space conventions (Vulkan's y points down and its depth goes from 0 to 1).
Thank you for following this series all the way to the end.
I hope you had as much fun building these games as I had writing about them, and I'll see you in the next series.
39.16 Summary
- HUD as data:
PlayScenefills a plainHudState(health, lagging health, ammo, reload progress, enemies, spread in pixels, hit and kill markers, hurt, damage markers) and the free functiondrawHuddraws it; drawing and game logic stay independent. - Where it goes: after
present, on the finished sRGB image, with the 2D toolkit and the 2D color rule (sRGB values,GL_FRAMEBUFFER_SRGBoff), so tone mapping, bloom and the render scale never touch it. - Crosshair and markers: outlined lines whose gap follows the spread (5 to 26 px), a dot, four diagonal hit strokes for 0.15 s, red and wider for 0.35 s on a kill;
spokeplaces rotated sprites by a clock-hand angle. - Health and ammo: a green-to-red bar with a pale lagging bar (waits 0.4 s, then 40 per second),
ceilfor the number; a large ammo count, one pip per round, and a reload bar under the crosshair; one square per enemy. - Damage arcs: , wrapped to −π..π; five strokes on a 120 px circle, screen up = ahead, clockwise = right, fading over 1 s.
- Game flow:
TitleScenerenders the real level with an orbiting camera;replacewith a 0.8 s fade starts a round; winning or losing pushesResultSceneafter 2 or 2.5 s; Space retries with a brand-newPlayScenethroughreplaceAll, Esc goes to the title; Esc in play pushesPauseScene, an overlay that freezes the round;--playskips the title. - Measuring: a 60-frame average of the CPU frame time,
GL_TIME_ELAPSEDper pass andGL_SAMPLES_PASSEDfor the scene; on llvmpipe all of it is CPU time, and the fragment count is the reliable A/B measure because it's the same in every run. - Results on llvmpipe: fragments follow the render scale squared, the scene pass follows the fragments (about 87 ns each), so render scale is the strongest knob (120 → 78 → 50 ms); shadows cost about 24 ms, mostly in the scene pass's PCF lookups; MSAA counted 4.29 M samples; culling and a Release build stayed within the noise.
- On a real GPU: the CPU side, bandwidth, overdraw and resolution matter instead; measure CPU and GPU separately, average, compare in pairs, count work, and use RenderDoc.
- Packaging: a Release build,
installrules withCOMPONENT tpsthat recreate the project layout indist/tps/,cmake --install … --component tps, andfindDataDirectory, which switches to the executable's folder (asked from the OS, not taken fromargv[0]) when the data isn't in the working directory; arguments are read first, so a level path stays relative to where you started the game.
39.17 Challenges
- ★ The window is 1280 × 720 and the scene pass writes 1.16 fragments per pixel. How many scene fragments do you expect at a render scale of 60 %, and at 1920 × 1080 with 100 %? Check with F3 (about 0.38 M; about 2.4 M if the overdraw stays the same; resize the window for the second one).
- ★ Make the crosshair gap match the real spread cone: the gap in pixels is for a spread and a vertical field of view on the 720 px virtual screen. With chapter 38's numbers you should get about 17 px when standing and firing from the hip (1.4° at 55°), 6.5 px when aiming (0.4° at 42°) and 31 px when moving from the hip (2.6° at 55°).
- ★ Add a "BEST" line to the result screen with the best winning time so far, kept in a
static floatinmenu_scenes.cc. After a win in 9.8 s it shows "BEST 0:09.8"; a slower win keeps it, a faster one replaces it, losing doesn't change it, and it's forgotten when the program ends. - ★★ Make the damage arcs follow the camera: store the shooter's world position in
DamageMarkerinstead of the angle, and compute indrawUifrom the current yaw. Turning toward an arc should move it to the top of the circle while it fades; with the example in 39.6, turning 68.7° to the left should put it straight up. - ★★ Dynamic resolution: every 30 frames, lower the render scale by 0.1 (down to 0.5) when the average CPU frame time is above 33 ms, and raise it by 0.1 (up to 1.0) when it's below 25 ms; print the scale when it changes. On the llvmpipe machine of 39.8 it should go down to 0.5 and stay there (even 50 % takes about 50 ms); on a GPU it should stay at 1.0. The HUD must stay sharp the whole time.
- ★★ Save the settings: write the render scale, the shadow switch and the shadow-map size to
settings.txtinexecutableDirectory(argv[0])whenever F5, F6 or F7 changes them, and read the file inmainbefore the renderer is created (a missing or broken file keeps the defaults). Choose 50 % and shadows off, quit, and start again: the game should come up at 50 % without shadows; in an installed copy the file appears indist/tps/, next to the executable. - ★★★ Add a minimap: render the level once from straight above with an orthographic projection into a 256 × 256
Framebuffer, then draw that texture as a sprite in the top-right corner of the HUD, with a dot for the player, an arrow for the camera's direction and red dots for living enemies, all updated every frame. Remember that a framebuffer's color texture drawn as a sprite needsflipY(chapter 25) and that the level image is linear HDR unless you run it through a simple tone map first.
ファイル: a/games/tps/CMakeLists.txt | b/games/tps/CMakeLists.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -10,8 +10,25 @@ add_executable(tps | |||
| 10 | src/third_person_camera.cc | 10 | src/third_person_camera.cc |
| 11 | src/enemy.cc | 11 | src/enemy.cc |
| 12 | src/effects.cc | 12 | src/effects.cc |
| 13 | src/play_scene.cc) | 13 | src/play_scene.cc |
| 14 | src/hud.cc | ||
| 15 | src/menu_scenes.cc) | ||
| 14 | target_include_directories(tps PRIVATE src) | 16 | target_include_directories(tps PRIVATE src) |
| 15 | target_link_libraries(tps PRIVATE engine) | 17 | target_link_libraries(tps PRIVATE engine) |
| 16 | enable_warnings(tps) | 18 | enable_warnings(tps) |
| 17 | set_working_directory(tps) | 19 | set_working_directory(tps) |
| 20 | |||
| 21 | # 配布(第39章):cmake --install <build> --prefix <dir> --component tps で <dir>/tps/ に実行ファイルと使うデータを | ||
| 22 | # プロジェクトと同じ並びで置く(tpsは見つからなければ実行ファイルの隣のデータを使う)。 | ||
| 23 | # Release: cmake -S . -B build-release -DCMAKE_BUILD_TYPE=Release(Visual Studio: --config Release) | ||
| 24 | # Packaging (chapter 39): cmake --install <build> --prefix <dir> --component tps puts the executable and the data it | ||
| 25 | # uses into <dir>/tps/, laid out like the project (tps falls back to the data next to its executable). | ||
| 26 | # Release: cmake -S . -B build-release -DCMAKE_BUILD_TYPE=Release (Visual Studio: --config Release) | ||
| 27 | install(TARGETS tps RUNTIME DESTINATION tps COMPONENT tps) | ||
| 28 | install(DIRECTORY ${PROJECT_SOURCE_DIR}/engine/shaders DESTINATION tps/engine COMPONENT tps) | ||
| 29 | install(DIRECTORY ${PROJECT_SOURCE_DIR}/assets/textures/sky DESTINATION tps/assets/textures COMPONENT tps) | ||
| 30 | install(FILES ${PROJECT_SOURCE_DIR}/assets/models/crate.glb ${PROJECT_SOURCE_DIR}/assets/models/barrel.glb | ||
| 31 | DESTINATION tps/assets/models COMPONENT tps) | ||
| 32 | install(FILES ${PROJECT_SOURCE_DIR}/assets/LICENSE.txt DESTINATION tps/assets COMPONENT tps) | ||
| 33 | install(DIRECTORY assets shaders DESTINATION tps/games/tps COMPONENT tps) | ||
| 34 | install(FILES README.md DESTINATION tps/games/tps COMPONENT tps) | ||
ファイル: a/games/tps/README.md | b/games/tps/README.md
| 前 | 新 | ||
|---|---|---|---|
| @@ -4,10 +4,32 @@ | |||
| 4 | 4 | ||
| 5 | ```sh | 5 | ```sh |
| 6 | ./build/games/tps/tps # Windows: build\games\tps\Debug\tps.exe | 6 | ./build/games/tps/tps # Windows: build\games\tps\Debug\tps.exe |
| 7 | ./build/games/tps/tps --play # タイトルを飛ばす / skip the title | ||
| 8 | ./build/games/tps/tps --msaa # エンジンの既定の後処理(4× MSAA)で比べる / compare with 4× MSAA | ||
| 7 | ./build/games/tps/tps games/tps/assets/levels/pieces.level # 部品を並べたレベル / every piece in a row | 9 | ./build/games/tps/tps games/tps/assets/levels/pieces.level # 部品を並べたレベル / every piece in a row |
| 8 | ``` | 10 | ``` |
| 9 | 11 | ||
| 10 | ## 操作 / Controls(第36〜38章 / chapters 36-38) | 12 | ## Release と配布 / Release build and packaging(第39章 / chapter 39) |
| 13 | |||
| 14 | ```sh | ||
| 15 | cmake -S . -B build-release -DCMAKE_BUILD_TYPE=Release # Visual Studio: cmake --build build --config Release | ||
| 16 | cmake --build build-release --target tps -j8 | ||
| 17 | cmake --install build-release --prefix dist --component tps | ||
| 18 | ./dist/tps/tps # どこから実行しても良い / runs from any directory | ||
| 19 | ``` | ||
| 20 | |||
| 21 | `dist/tps/` にはプロジェクトと同じ並びで、実行ファイルと使うデータだけが入る(`engine/shaders/`、`assets/textures/sky/`、 | ||
| 22 | `assets/models/crate.glb`・`barrel.glb`、`games/tps/assets/`・`shaders/`)。データが今のディレクトリになければ、 | ||
| 23 | 実行ファイルの隣を使う。 | ||
| 24 | `dist/tps/` holds the executable and only the data it uses, laid out like the project. If the data is not in the | ||
| 25 | current directory, the game uses the directory of its executable. | ||
| 26 | |||
| 27 | ## 次へ / Next steps | ||
| 28 | |||
| 29 | このシリーズの次は **Slang + Vulkan**:同じレンダラー(PBR、影、IBL、後処理)をVulkanで、シェーダーはSlangで書き直す。 | ||
| 30 | The next series is **Slang + Vulkan**: the same renderer (PBR, shadows, IBL, post) rebuilt on Vulkan with shaders in Slang. | ||
| 31 | |||
| 32 | ## 操作 / Controls(第36〜39章 / chapters 36-39) | ||
| 11 | 33 | ||
| 12 | | キー / key | | | 34 | | キー / key | | |
| 13 | |---|---| | 35 | |---|---| |
| @@ -28,8 +50,12 @@ | |||
| 28 | | F3 | 時間と描いた数 / timings and draw counts | | 50 | | F3 | 時間と描いた数 / timings and draw counts | |
| 29 | | F8 | 毎フレームの状態を標準出力へ(台本作り用) / log the state every frame to stdout (for scripting) | | 51 | | F8 | 毎フレームの状態を標準出力へ(台本作り用) / log the state every frame to stdout (for scripting) | |
| 30 | | F4 | 視錐台カリングのオン・オフ / frustum culling on / off | | 52 | | F4 | 視錐台カリングのオン・オフ / frustum culling on / off | |
| 53 | | F5 | 描く解像度 100 → 75 → 50 % / render scale | | ||
| 54 | | F6 | 影のオン・オフ / shadows on / off | | ||
| 55 | | F7 | 影の地図 2048² ⇔ 1024² / shadow map size | | ||
| 31 | | Tab | カーソルのキャプチャ / cursor capture | | 56 | | Tab | カーソルのキャプチャ / cursor capture | |
| 32 | | Esc | 終了 / quit | | 57 | | Esc | 一時停止(タイトルでは終了) / pause (quit on the title) | |
| 58 | | Space / Enter | タイトル・結果の画面で決定 / confirm on the title and result screens | | ||
| 33 | 59 | ||
| 34 | ## ファイル / Files | 60 | ## ファイル / Files |
| 35 | 61 | ||
| @@ -43,6 +69,8 @@ src/character_body.* 当たり判定・重力・壁ずり・段差 / coll | |||
| 43 | src/enemy.* 敵の状態機械のAI / the enemies' state-machine AI | 69 | src/enemy.* 敵の状態機械のAI / the enemies' state-machine AI |
| 44 | src/effects.* 銃口の光・トレーサー・火花 / muzzle flash, tracers, sparks | 70 | src/effects.* 銃口の光・トレーサー・火花 / muzzle flash, tracers, sparks |
| 45 | src/angles.hh 角度の小道具 / angle helpers | 71 | src/angles.hh 角度の小道具 / angle helpers |
| 72 | src/hud.* HUD(照準・体力・弾・敵・撃たれた向き) / the HUD | ||
| 73 | src/menu_scenes.* タイトル・結果・一時停止 / title, result and pause scenes | ||
| 46 | shaders/particle.vert/.frag 火花のビルボード / spark billboards | 74 | shaders/particle.vert/.frag 火花のビルボード / spark billboards |
| 47 | src/frustum.* 視錐台の平面 / frustum planes | 75 | src/frustum.* 視錐台の平面 / frustum planes |
| 48 | src/renderer.* 影 → 場面(PBR + IBL) → 後処理 / shadows → scene (PBR + IBL) → post | 76 | src/renderer.* 影 → 場面(PBR + IBL) → 後処理 / shadows → scene (PBR + IBL) → post |
ファイル: /dev/null | b/games/tps/src/hud.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,114 @@ | |||
| 1 | #include "hud.hh" | ||
| 2 | |||
| 3 | #include <algorithm> | ||
| 4 | #include <cmath> | ||
| 5 | #include <format> | ||
| 6 | |||
| 7 | constexpr Vec2 kCentre = {640.0f, 360.0f}; | ||
| 8 | constexpr Vec4 kShadow = {0.0f, 0.0f, 0.0f, 0.85f}; | ||
| 9 | constexpr Vec4 kPanel = {0.03f, 0.04f, 0.06f, 0.55f}; | ||
| 10 | |||
| 11 | // 黒い縁つきの線(明るい床でも暗い壁でも見える) / a line with a dark outline (readable on bright floors and dark walls) | ||
| 12 | static void outlined(SpriteBatch &batch, Rect r, Vec4 color) { | ||
| 13 | batch.drawRect({r.x - 1.0f, r.y - 1.0f, r.w + 2.0f, r.h + 2.0f}, {0.0f, 0.0f, 0.0f, 0.6f * color.w}); | ||
| 14 | batch.drawRect(r, color); | ||
| 15 | } | ||
| 16 | |||
| 17 | // 中心のまわりに回した細い四角形(当てた印、撃たれた向き) / a thin rectangle turned about the center (hit marker, | ||
| 18 | // damage direction) | ||
| 19 | static void spoke(SpriteBatch &batch, float angle, float radius, Vec2 size, Vec4 color) { | ||
| 20 | Vec2 dir = {std::sin(angle), -std::cos(angle)}; // 画面の上 = 0、時計回り / screen up = 0, clockwise | ||
| 21 | batch.draw({.position = kCentre + radius * dir, .size = size, .origin = {0.5f, 0.5f}, .rotation = angle, | ||
| 22 | .color = color}); | ||
| 23 | } | ||
| 24 | |||
| 25 | static void crosshair(SpriteBatch &batch, const HudState &hud) { | ||
| 26 | if (!hud.alive) return; | ||
| 27 | // 4本の線:拡散が大きいほど開く(撃つ・動く・狙っていない) / four lines that open with the spread (firing, moving, | ||
| 28 | // not aiming) | ||
| 29 | float g = hud.spread; | ||
| 30 | Vec4 c = {1.0f, 1.0f, 1.0f, 0.95f}; | ||
| 31 | outlined(batch, {639.0f, 360.0f - g - 9.0f, 2.0f, 9.0f}, c); | ||
| 32 | outlined(batch, {639.0f, 360.0f + g, 2.0f, 9.0f}, c); | ||
| 33 | outlined(batch, {640.0f - g - 9.0f, 359.0f, 9.0f, 2.0f}, c); | ||
| 34 | outlined(batch, {640.0f + g, 359.0f, 9.0f, 2.0f}, c); | ||
| 35 | outlined(batch, {639.0f, 359.0f, 2.0f, 2.0f}, c); | ||
| 36 | // 当てた印:斜めの4本(倒したら赤く大きく) / hit marker: four diagonal strokes (red and bigger on a kill) | ||
| 37 | if (hud.hitMarker > 0.0f) { | ||
| 38 | float k = hud.hitMarker; | ||
| 39 | Vec4 m = hud.killMarker ? Vec4{1.0f, 0.25f, 0.2f, k} : Vec4{1.0f, 1.0f, 1.0f, k}; | ||
| 40 | float r = hud.killMarker ? 16.0f : 12.0f; | ||
| 41 | for (int i = 0; i < 4; ++i) spoke(batch, 0.25f * PI + 0.5f * PI * static_cast<float>(i), r, {2.0f, 8.0f}, m); | ||
| 42 | } | ||
| 43 | } | ||
| 44 | |||
| 45 | static void healthPanel(SpriteBatch &batch, const Font &font, const HudState &hud) { | ||
| 46 | batch.drawRect({20.0f, 640.0f, 300.0f, 62.0f}, kPanel); | ||
| 47 | font.draw(batch, "体力 / HEALTH", {32.0f, 646.0f}, {.color = {0.8f, 0.85f, 0.9f, 1.0f}, .shadow = kShadow}); | ||
| 48 | Rect bar = {32.0f, 672.0f, 220.0f, 16.0f}; | ||
| 49 | batch.drawRect(bar, {0.0f, 0.0f, 0.0f, 0.6f}); | ||
| 50 | float shown = std::clamp(hud.healthShown / 100.0f, 0.0f, 1.0f), now = std::clamp(hud.health / 100.0f, 0.0f, 1.0f); | ||
| 51 | batch.drawRect({bar.x, bar.y, bar.w * shown, bar.h}, {1.0f, 0.85f, 0.8f, 0.8f}); // 減った分 / what was lost | ||
| 52 | // 緑 → 黄 → 赤 / green → yellow → red | ||
| 53 | Vec4 color = now > 0.5f ? lerp(Vec4{0.95f, 0.8f, 0.2f, 1.0f}, Vec4{0.3f, 0.9f, 0.45f, 1.0f}, (now - 0.5f) * 2.0f) | ||
| 54 | : lerp(Vec4{0.95f, 0.2f, 0.15f, 1.0f}, Vec4{0.95f, 0.8f, 0.2f, 1.0f}, now * 2.0f); | ||
| 55 | batch.drawRect({bar.x, bar.y, bar.w * now, bar.h}, color); | ||
| 56 | font.draw(batch, std::format("{:.0f}", std::ceil(hud.health)), {302.0f, 668.0f}, | ||
| 57 | {.scale = 1.5f, .align = TextAlign::Right, .shadow = kShadow}); | ||
| 58 | } | ||
| 59 | |||
| 60 | static void ammoPanel(SpriteBatch &batch, const Font &font, const HudState &hud) { | ||
| 61 | batch.drawRect({1000.0f, 640.0f, 260.0f, 62.0f}, kPanel); | ||
| 62 | font.draw(batch, "弾 / AMMO", {1012.0f, 646.0f}, {.color = {0.8f, 0.85f, 0.9f, 1.0f}, .shadow = kShadow}); | ||
| 63 | Vec4 c = hud.ammo == 0 ? Vec4{1.0f, 0.3f, 0.25f, 1.0f} : hud.ammo <= hud.magazine / 4 ? Vec4{1.0f, 0.8f, 0.3f, 1.0f} | ||
| 64 | : kWhite; | ||
| 65 | font.draw(batch, std::format("{}", hud.ammo), {1190.0f, 644.0f}, | ||
| 66 | {.color = c, .scale = 2.5f, .align = TextAlign::Right, .shadow = kShadow}); | ||
| 67 | font.draw(batch, std::format("/ {}", hud.magazine), {1196.0f, 666.0f}, {.color = {0.8f, 0.8f, 0.8f, 1.0f}, | ||
| 68 | .shadow = kShadow}); | ||
| 69 | // 弾の数だけの小さな印(1発 = 1本) / one small pip per round | ||
| 70 | for (int i = 0; i < hud.magazine; ++i) | ||
| 71 | batch.drawRect({1012.0f + 6.0f * static_cast<float>(i), 674.0f, 4.0f, 14.0f}, | ||
| 72 | i < hud.ammo ? Vec4{0.95f, 0.85f, 0.5f, 1.0f} : Vec4{1.0f, 1.0f, 1.0f, 0.15f}); | ||
| 73 | if (hud.reload >= 0.0f) { | ||
| 74 | font.draw(batch, "装填中 / RELOADING", {640.0f, 410.0f}, | ||
| 75 | {.color = {1.0f, 0.85f, 0.4f, 1.0f}, .align = TextAlign::Centre, .shadow = kShadow}); | ||
| 76 | batch.drawRect({580.0f, 434.0f, 120.0f, 4.0f}, {0.0f, 0.0f, 0.0f, 0.6f}); | ||
| 77 | batch.drawRect({580.0f, 434.0f, 120.0f * hud.reload, 4.0f}, {1.0f, 0.85f, 0.4f, 1.0f}); | ||
| 78 | } | ||
| 79 | } | ||
| 80 | |||
| 81 | static void enemiesPanel(SpriteBatch &batch, const Font &font, const HudState &hud) { | ||
| 82 | float w = 30.0f + 22.0f * static_cast<float>(hud.enemiesTotal); | ||
| 83 | float x = 640.0f - 0.5f * std::fmax(w, 200.0f); | ||
| 84 | batch.drawRect({x, 16.0f, std::fmax(w, 200.0f), 52.0f}, kPanel); | ||
| 85 | font.draw(batch, std::format("敵 / ENEMIES {} / {}", hud.enemiesLeft, hud.enemiesTotal), {640.0f, 20.0f}, | ||
| 86 | {.color = {0.9f, 0.9f, 0.95f, 1.0f}, .align = TextAlign::Centre, .shadow = kShadow}); | ||
| 87 | float x0 = 640.0f - 11.0f * static_cast<float>(hud.enemiesTotal) + 3.0f; | ||
| 88 | for (int i = 0; i < hud.enemiesTotal; ++i) { | ||
| 89 | bool alive = i < hud.enemiesLeft; | ||
| 90 | batch.drawRect({x0 + 22.0f * static_cast<float>(i), 44.0f, 16.0f, 16.0f}, | ||
| 91 | alive ? Vec4{0.85f, 0.2f, 0.15f, 1.0f} : Vec4{1.0f, 1.0f, 1.0f, 0.18f}); | ||
| 92 | } | ||
| 93 | } | ||
| 94 | |||
| 95 | void drawHud(SpriteBatch &batch, const Font &font, const HudState &hud) { | ||
| 96 | // 撃たれたとき:画面の縁を赤く / when hit: a red screen edge | ||
| 97 | if (hud.hurt > 0.0f) { | ||
| 98 | Vec4 red = {0.75f, 0.0f, 0.0f, 0.45f * hud.hurt}; | ||
| 99 | batch.drawRect({0.0f, 0.0f, 1280.0f, 36.0f}, red); | ||
| 100 | batch.drawRect({0.0f, 684.0f, 1280.0f, 36.0f}, red); | ||
| 101 | batch.drawRect({0.0f, 36.0f, 36.0f, 648.0f}, red); | ||
| 102 | batch.drawRect({1244.0f, 36.0f, 36.0f, 648.0f}, red); | ||
| 103 | } | ||
| 104 | // 撃たれた向き:照準のまわりの赤い弧(敵の方を指す) / where the hits came from: red arcs around the crosshair | ||
| 105 | // pointing at the shooters | ||
| 106 | for (const DamageMarker &d : hud.damage) { | ||
| 107 | Vec4 c = {1.0f, 0.15f, 0.1f, 0.9f * std::clamp(d.life, 0.0f, 1.0f)}; | ||
| 108 | for (int i = -2; i <= 2; ++i) spoke(batch, d.angle + 0.06f * static_cast<float>(i), 120.0f, {14.0f, 5.0f}, c); | ||
| 109 | } | ||
| 110 | crosshair(batch, hud); | ||
| 111 | healthPanel(batch, font, hud); | ||
| 112 | ammoPanel(batch, font, hud); | ||
| 113 | enemiesPanel(batch, font, hud); | ||
| 114 | } | ||
ファイル: /dev/null | b/games/tps/src/hud.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,36 @@ | |||
| 1 | // HUD(第39章):照準・体力・弾・残りの敵・撃たれた向き。第25・26章の2Dの道具(SpriteBatch・Font)で、 | ||
| 2 | // 後処理が終わった3Dの絵の上に描く(色はsRGBのまま、第25章の決まり)。1280 × 720の仮想画面 | ||
| 3 | // The HUD (chapter 39): crosshair, health, ammo, enemies left, where the hits came from. Drawn with the 2D toolkit of | ||
| 4 | // chapters 25-26 (SpriteBatch, Font) over the finished, post-processed 3D image (colors stay sRGB, the chapter 25 | ||
| 5 | // rule). A 1280 × 720 virtual screen | ||
| 6 | #pragma once | ||
| 7 | |||
| 8 | #include "engine/font.hh" | ||
| 9 | #include "engine/sprite_batch.hh" | ||
| 10 | |||
| 11 | #include <vector> | ||
| 12 | |||
| 13 | // 撃たれた向きの印 / a damage-direction marker | ||
| 14 | struct DamageMarker { | ||
| 15 | float angle; // 画面の上 = 0、時計回り(ラジアン):カメラの向きから見た撃った敵の向き / screen up = 0, clockwise | ||
| 16 | // (radians): the shooter's direction relative to where the camera looks | ||
| 17 | float life; // 残り時間(秒) / seconds left | ||
| 18 | }; | ||
| 19 | |||
| 20 | // HUDが描くもの全部(PlaySceneが毎フレーム詰める) / everything the HUD shows (PlayScene fills it every frame) | ||
| 21 | struct HudState { | ||
| 22 | float health = 100.0f; | ||
| 23 | float healthShown = 100.0f; // 遅れて減る薄い棒(どれだけ減ったか見える) / a lagging pale bar (shows the loss) | ||
| 24 | int ammo = 0, magazine = 0; | ||
| 25 | float reload = -1.0f; // 0〜1:込め直しの進み、−1 = していない / 0..1 reload progress, −1 = not reloading | ||
| 26 | int enemiesLeft = 0, enemiesTotal = 0; | ||
| 27 | float spread = 10.0f; // 照準の線の真ん中からの距離(px) / the crosshair lines' distance from the center (px) | ||
| 28 | float hitMarker = 0.0f; // 当てた印の残り(0〜1) / hit marker left (0..1) | ||
| 29 | bool killMarker = false; // 今の印は倒した一発 / the current marker is a kill | ||
| 30 | float hurt = 0.0f; // 画面の縁の赤(0〜1) / red screen edge (0..1) | ||
| 31 | bool alive = true; | ||
| 32 | std::vector<DamageMarker> damage; | ||
| 33 | }; | ||
| 34 | |||
| 35 | // batch.begin(…)とend()の間で呼ぶ / call between batch.begin(...) and end() | ||
| 36 | void drawHud(SpriteBatch &batch, const Font &font, const HudState &hud); | ||
ファイル: a/games/tps/src/main.cc | b/games/tps/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,7 +1,9 @@ | |||
| 1 | // 第36〜39章:三人称シューティング(TPS)。第36章:レベル、キャラクター、三人称カメラ。第37章:当たり判定、重力、 | 1 | // 第36〜39章:三人称シューティング(TPS)。第36章:レベル、キャラクター、三人称カメラ。第37章:当たり判定、重力、 |
| 2 | // ジャンプ、壁ずり。第38章:射撃、敵、体力、当たったときの効果 | 2 | // ジャンプ、壁ずり。第38章:射撃、敵、体力、当たったときの効果。第39章:HUD、タイトル → 遊ぶ → 勝ち・負け、 |
| 3 | // 速さの工夫、配布(インストール) | ||
| 3 | // Chapters 36-39: the third-person shooter (TPS). Chapter 36: the level, the character and the third-person camera. | 4 | // Chapters 36-39: the third-person shooter (TPS). Chapter 36: the level, the character and the third-person camera. |
| 4 | // Chapter 37: collision, gravity, jumping, wall sliding. Chapter 38: shooting, enemies, health, hit effects | 5 | // Chapter 37: collision, gravity, jumping, wall sliding. Chapter 38: shooting, enemies, health, hit effects. |
| 6 | // Chapter 39: HUD, title → play → win / lose, performance options, packaging (install) | ||
| 5 | // | 7 | // |
| 6 | // 操作 / Controls: | 8 | // 操作 / Controls: |
| 7 | // WASD カメラの向きに対して移動 / move relative to the camera | 9 | // WASD カメラの向きに対して移動 / move relative to the camera |
| @@ -12,9 +14,12 @@ | |||
| 12 | // 右ボタン / RMB 狙う(肩に寄って視野が狭まる) / aim (closer over the shoulder, narrower view) | 14 | // 右ボタン / RMB 狙う(肩に寄って視野が狭まる) / aim (closer over the shoulder, narrower view) |
| 13 | // R 弾を込め直す / reload | 15 | // R 弾を込め直す / reload |
| 14 | // Q 右肩 ⇔ 左肩 / right ⇔ left shoulder | 16 | // Q 右肩 ⇔ 左肩 / right ⇔ left shoulder |
| 15 | // B 当たり判定の箱・カプセル・ソケット・軌跡 / collision boxes, capsule, sockets, trail | 17 | // B 当たり判定の箱・カプセル・ソケット・軌跡・敵のAI / collision boxes, capsule, sockets, trail, enemy AI |
| 16 | // F3 時間と描いた数 / timings and draw counts | 18 | // F3 時間と描いた数 / timings and draw counts |
| 17 | // F4 視錐台カリングのオン・オフ / frustum culling on / off | 19 | // F4 視錐台カリングのオン・オフ / frustum culling on / off |
| 20 | // F5 描く解像度 100 → 75 → 50 % / render scale 100 → 75 → 50 % | ||
| 21 | // F6 影のオン・オフ / shadows on / off | ||
| 22 | // F7 影の地図 2048² ⇔ 1024² / shadow map 2048² ⇔ 1024² | ||
| 18 | // C カメラだけ回す(キャラクターを前から見る) / turn only the camera (look at the character) | 23 | // C カメラだけ回す(キャラクターを前から見る) / turn only the camera (look at the character) |
| 19 | // K カメラの当たり判定のオン・オフ / camera collision on / off | 24 | // K カメラの当たり判定のオン・オフ / camera collision on / off |
| 20 | // O 上から見下ろす(デバッグ) / view from above (debugging) | 25 | // O 上から見下ろす(デバッグ) / view from above (debugging) |
| @@ -22,29 +27,109 @@ | |||
| 22 | // L 壁ずり ⇔ 壁で止まる(比べる) / wall sliding ⇔ stopping at walls (to compare) | 27 | // L 壁ずり ⇔ 壁で止まる(比べる) / wall sliding ⇔ stopping at walls (to compare) |
| 23 | // P 手続き的な姿勢のオン・オフ(読み込んだままの姿勢) / procedural pose on / off (the pose as loaded) | 28 | // P 手続き的な姿勢のオン・オフ(読み込んだままの姿勢) / procedural pose on / off (the pose as loaded) |
| 24 | // Tab カーソルのキャプチャ / cursor capture | 29 | // Tab カーソルのキャプチャ / cursor capture |
| 25 | // Esc 終了 / quit | 30 | // Esc 一時停止(タイトルでは終了) / pause (quit on the title) |
| 26 | // 実行はプロジェクトのルートから:./build/games/tps/tps / run from the project root: ./build/games/tps/tps | 31 | // 引数:レベルのファイル(既定 games/tps/assets/levels/arena.level)、--play(タイトルを飛ばす)、--msaa(エンジンの |
| 32 | // 既定の後処理で比べる) | ||
| 33 | // Arguments: a level file (default games/tps/assets/levels/arena.level), --play (skip the title), --msaa (compare | ||
| 34 | // with the engine's default post chain) | ||
| 35 | // 実行はプロジェクトのルートから:./build/games/tps/tps。インストールした物(cmake --install)は実行ファイルの隣の | ||
| 36 | // データを自分で見つける | ||
| 37 | // Run from the project root: ./build/games/tps/tps. An installed copy (cmake --install) finds the data next to its | ||
| 38 | // executable by itself | ||
| 27 | #include "game.hh" | 39 | #include "game.hh" |
| 40 | #include "menu_scenes.hh" | ||
| 28 | #include "play_scene.hh" | 41 | #include "play_scene.hh" |
| 29 | 42 | ||
| 30 | #include "engine/scene.hh" | 43 | #include "engine/scene.hh" |
| 31 | 44 | ||
| 32 | #include <chrono> | 45 | #include <chrono> |
| 33 | #include <cstdio> | 46 | #include <cstdio> |
| 47 | #include <cstdlib> | ||
| 48 | #include <filesystem> | ||
| 34 | #include <memory> | 49 | #include <memory> |
| 35 | #include <optional> | 50 | #include <optional> |
| 51 | #include <string> | ||
| 52 | #include <string_view> | ||
| 53 | #include <system_error> | ||
| 54 | |||
| 55 | #if defined(__FreeBSD__) | ||
| 56 | #include <sys/types.h> | ||
| 57 | #include <sys/sysctl.h> | ||
| 58 | #endif | ||
| 59 | |||
| 60 | // 実行ファイルのある所。argv[0]は起動のしかたで変わり、PATHから起動すると名前(tps)だけなので、OSに聞く | ||
| 61 | // Where the executable is. argv[0] depends on how the program was started (only the name, "tps", when it was found | ||
| 62 | // through PATH), so ask the OS | ||
| 63 | static std::filesystem::path executableDirectory(const char *argv0) { | ||
| 64 | namespace fs = std::filesystem; | ||
| 65 | std::error_code ec; | ||
| 66 | #if defined(_WIN32) | ||
| 67 | char *path = nullptr; // CRTが用意するフルパス / the full path the C runtime provides | ||
| 68 | if (_get_pgmptr(&path) == 0 && path && *path) return fs::path(path).parent_path(); | ||
| 69 | #elif defined(__linux__) | ||
| 70 | fs::path self = fs::read_symlink("/proc/self/exe", ec); // 実行中のファイルへのリンク / a link to the running file | ||
| 71 | if (!ec) return self.parent_path(); | ||
| 72 | #elif defined(__FreeBSD__) | ||
| 73 | int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1}; // -1 = このプロセス / this process | ||
| 74 | char path[1024]; | ||
| 75 | size_t size = sizeof(path); | ||
| 76 | if (sysctl(mib, 4, path, &size, nullptr, 0) == 0) return fs::path(path).parent_path(); | ||
| 77 | #endif | ||
| 78 | // 他のOS、または聞けなかったとき:argv[0](ディレクトリが付いていれば使える) / other systems, or if asking failed: | ||
| 79 | // argv[0] (usable when it contains a directory) | ||
| 80 | fs::path p = fs::absolute(fs::path(argv0), ec); | ||
| 81 | return ec ? fs::path() : p.parent_path(); | ||
| 82 | } | ||
| 83 | |||
| 84 | // データのある場所へ移る(第39章、配布)。開発中はプロジェクトのルートから実行するので、そこにデータがある。 | ||
| 85 | // インストールした物は実行ファイルの隣にengine/・assets/・games/tps/を置くので、見つからなければそこへ移る | ||
| 86 | // Move to where the data is (chapter 39, packaging). During development we run from the project root, which has the | ||
| 87 | // data. An installed copy keeps engine/, assets/ and games/tps/ next to the executable, so if the data is not found | ||
| 88 | // here, go there | ||
| 89 | static void findDataDirectory(const char *argv0) { | ||
| 90 | namespace fs = std::filesystem; | ||
| 91 | const fs::path marker = "games/tps/assets/levels/arena.level"; | ||
| 92 | std::error_code ec; | ||
| 93 | if (fs::exists(marker, ec)) return; | ||
| 94 | fs::path exeDir = executableDirectory(argv0); | ||
| 95 | if (!exeDir.empty() && fs::exists(exeDir / marker, ec)) { | ||
| 96 | fs::current_path(exeDir, ec); | ||
| 97 | printf("data: %s\n", exeDir.string().c_str()); | ||
| 98 | } else { | ||
| 99 | fprintf(stderr, "データが見つからない(プロジェクトのルートから実行する) / data not found (run from the project root)\n"); | ||
| 100 | } | ||
| 101 | } | ||
| 36 | 102 | ||
| 37 | int main(int argc, char **argv) { | 103 | int main(int argc, char **argv) { |
| 104 | // 引数を先に読む:レベルのパスは起動したディレクトリから見たものなので、データの場所へ移る前に絶対パスにする | ||
| 105 | // Read the arguments first: a level path is relative to the directory we were started in, so make it absolute | ||
| 106 | // before moving to the data | ||
| 107 | std::string levelPath = "games/tps/assets/levels/arena.level"; | ||
| 108 | // --playでタイトルを飛ばしてすぐ遊ぶ(試すとき、台本で動かすとき) / --play skips the title (for testing and | ||
| 109 | // scripted runs) | ||
| 110 | bool skipTitle = false; | ||
| 111 | RenderSettings settings; | ||
| 112 | for (int i = 1; i < argc; ++i) { | ||
| 113 | if (std::string_view(argv[i]) == "--play") skipTitle = true; | ||
| 114 | // --msaa:エンジンの既定の後処理(4× MSAA、RGBA16F、ブルーム4組)と比べる / --msaa: compare with the engine's | ||
| 115 | // default post chain (4× MSAA, RGBA16F, 4 bloom pairs) | ||
| 116 | else if (std::string_view(argv[i]) == "--msaa") settings.post = PostChainSettings{}; | ||
| 117 | else { | ||
| 118 | std::error_code ec; | ||
| 119 | std::filesystem::path p = std::filesystem::absolute(argv[i], ec); | ||
| 120 | levelPath = ec ? std::string(argv[i]) : p.string(); | ||
| 121 | } | ||
| 122 | } | ||
| 123 | findDataDirectory(argv[0]); | ||
| 38 | Window window; | 124 | Window window; |
| 39 | if (!window.create(1280, 720, "OpenGL Tutorial - TPS")) return 1; | 125 | if (!window.create(1280, 720, "OpenGL Tutorial - TPS")) return 1; |
| 40 | 126 | std::unique_ptr<Renderer> renderer = Renderer::create(window.width(), window.height(), settings); | |
| 41 | std::unique_ptr<Renderer> renderer = Renderer::create(window.width(), window.height()); | ||
| 42 | if (!renderer) return 1; | 127 | if (!renderer) return 1; |
| 43 | window.onResize = [&](int width, int height) { renderer->resize(width, height); }; | 128 | window.onResize = [&](int width, int height) { renderer->resize(width, height); }; |
| 44 | 129 | ||
| 45 | // 引数でほかのレベルも読める(例:部品を並べたpieces.level) / another level can be given as an argument (e.g. | 130 | // 引数でほかのレベルも読める(例:部品を並べたpieces.level) / another level can be given as an argument (e.g. |
| 46 | // pieces.level, which lines up every piece) | 131 | // pieces.level, which lines up every piece) |
| 47 | std::optional<Level> level = Level::load(argc > 1 ? argv[1] : "games/tps/assets/levels/arena.level"); | 132 | std::optional<Level> level = Level::load(levelPath); |
| 48 | std::optional<Model> player = Model::load("games/tps/assets/models/player.glb"); | 133 | std::optional<Model> player = Model::load("games/tps/assets/models/player.glb"); |
| 49 | std::optional<Model> rifle = Model::load("games/tps/assets/models/rifle.glb"); | 134 | std::optional<Model> rifle = Model::load("games/tps/assets/models/rifle.glb"); |
| 50 | std::optional<Model> enemy = Model::load("games/tps/assets/models/enemy.glb"); | 135 | std::optional<Model> enemy = Model::load("games/tps/assets/models/enemy.glb"); |
| @@ -71,6 +156,7 @@ int main(int argc, char **argv) { | |||
| 71 | input.bind("fire", {InputBinding::mouse(GLFW_MOUSE_BUTTON_LEFT)}); | 156 | input.bind("fire", {InputBinding::mouse(GLFW_MOUSE_BUTTON_LEFT)}); |
| 72 | input.bind("aim", {InputBinding::mouse(GLFW_MOUSE_BUTTON_RIGHT)}); | 157 | input.bind("aim", {InputBinding::mouse(GLFW_MOUSE_BUTTON_RIGHT)}); |
| 73 | input.bind("reload", {InputBinding::key(GLFW_KEY_R)}); | 158 | input.bind("reload", {InputBinding::key(GLFW_KEY_R)}); |
| 159 | input.bind("confirm", {InputBinding::key(GLFW_KEY_SPACE), InputBinding::key(GLFW_KEY_ENTER)}); | ||
| 74 | 160 | ||
| 75 | GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); | 161 | GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); |
| 76 | Game game{.window = window, .input = input, .loop = loop, .renderer = *renderer, .batch = *batch, .ui = *ui, | 162 | Game game{.window = window, .input = input, .loop = loop, .renderer = *renderer, .batch = *batch, .ui = *ui, |
| @@ -79,7 +165,9 @@ int main(int argc, char **argv) { | |||
| 79 | .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}}; | 165 | .screen = Camera2D::screen({1280.0f, 720.0f}), .uiViewport = {}}; |
| 80 | 166 | ||
| 81 | SceneManager scenes; | 167 | SceneManager scenes; |
| 82 | scenes.push(std::make_unique<PlayScene>(game)); | 168 | // 第39章:タイトルから / chapter 39: start at the title |
| 169 | if (skipTitle) scenes.push(std::make_unique<PlayScene>(game)); | ||
| 170 | else scenes.push(std::make_unique<TitleScene>(game)); | ||
| 83 | // pushは予約だけ:更新0回の最初のフレームも描けるように、ここで適用する(シーンの更新は呼ばれない) | 171 | // pushは予約だけ:更新0回の最初のフレームも描けるように、ここで適用する(シーンの更新は呼ばれない) |
| 84 | // push only queues the request: apply it now so that the first frame (which runs no update) has a scene to draw | 172 | // push only queues the request: apply it now so that the first frame (which runs no update) has a scene to draw |
| 85 | // (no scene's update is called) | 173 | // (no scene's update is called) |
ファイル: /dev/null | b/games/tps/src/menu_scenes.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,134 @@ | |||
| 1 | #include "menu_scenes.hh" | ||
| 2 | |||
| 3 | #include "play_scene.hh" | ||
| 4 | |||
| 5 | #include <cmath> | ||
| 6 | #include <format> | ||
| 7 | #include <memory> | ||
| 8 | |||
| 9 | constexpr Vec4 kShadow = {0.0f, 0.0f, 0.0f, 0.9f}; | ||
| 10 | constexpr Vec4 kGold = {1.0f, 0.82f, 0.35f, 1.0f}; | ||
| 11 | constexpr Transition kFade = {.duration = 0.8f}; | ||
| 12 | |||
| 13 | //------------------------------------------ | ||
| 14 | // TitleScene | ||
| 15 | //------------------------------------------ | ||
| 16 | |||
| 17 | void TitleScene::enter() { g.window.setCursorCaptured(false); } | ||
| 18 | |||
| 19 | void TitleScene::update(float dt) { | ||
| 20 | prevTime = time; | ||
| 21 | time += dt; | ||
| 22 | if (g.input.actionPressed("confirm")) scenes().replace(std::make_unique<PlayScene>(g), kFade); | ||
| 23 | if (g.input.pressed(GLFW_KEY_ESCAPE)) scenes().pop(); // 最後のシーン → 終了 / the last scene → quit | ||
| 24 | } | ||
| 25 | |||
| 26 | void TitleScene::draw(float alpha) { | ||
| 27 | // 背景:レベルの上をゆっくり回るカメラ(遊ぶときと同じ3Dのフレーム:影 → 場面 → 後処理) | ||
| 28 | // Background: a camera slowly circling over the level (the same 3D frame as in play: shadows → scene → post) | ||
| 29 | Renderer &r = g.renderer; | ||
| 30 | float t = prevTime + (time - prevTime) * alpha; | ||
| 31 | float a = 0.12f * t + 0.6f; | ||
| 32 | FrameView view; | ||
| 33 | view.eye = {15.0f * std::sin(a), 5.5f, 15.0f * std::cos(a)}; | ||
| 34 | view.forward = normalize(Vec3{0.0f, 2.0f, 0.0f} - view.eye); | ||
| 35 | view.aspect = static_cast<float>(g.window.width()) / static_cast<float>(g.window.height()); | ||
| 36 | view.time = t; | ||
| 37 | LightSet lights; | ||
| 38 | lights.directional = {.direction = {-0.5f, -1.0f, -0.35f}, .color = {2.6f, 2.45f, 2.2f}}; | ||
| 39 | r.beginFrame(view, lights); | ||
| 40 | if (r.beginShadows()) { | ||
| 41 | g.level.drawShadows(*r.shadow, r.white, r.lightFrustum()); | ||
| 42 | r.endShadows(); | ||
| 43 | } | ||
| 44 | r.beginScene(); | ||
| 45 | r.pbrInstanced->use(); | ||
| 46 | g.level.draw(*r.pbrInstanced, r.white, r.viewFrustum()); | ||
| 47 | r.drawSky(); | ||
| 48 | r.endScene(); | ||
| 49 | r.present(g.window.width(), g.window.height()); | ||
| 50 | } | ||
| 51 | |||
| 52 | void TitleScene::drawUi(float /*alpha*/) { | ||
| 53 | SpriteBatch &batch = g.batch; | ||
| 54 | batch.begin(g.screen.matrix()); | ||
| 55 | batch.drawRect({0.0f, 190.0f, 1280.0f, 260.0f}, {0.02f, 0.03f, 0.06f, 0.6f}); | ||
| 56 | g.ui.draw(batch, "三人称シューティング", {640.0f, 214.0f}, | ||
| 57 | {.color = {0.85f, 0.9f, 1.0f, 1.0f}, .scale = 2.0f, .align = TextAlign::Centre, .shadow = kShadow}); | ||
| 58 | g.ui.draw(batch, "THIRD-PERSON SHOOTER", {640.0f, 262.0f}, | ||
| 59 | {.color = kGold, .scale = 4.0f, .align = TextAlign::Centre, .shadow = kShadow, .shadowOffset = {1.0f, 1.0f}}); | ||
| 60 | g.ui.draw(batch, "OpenGL Tutorial 第36〜39章 / chapters 36-39", {640.0f, 350.0f}, | ||
| 61 | {.color = {0.8f, 0.8f, 0.85f, 1.0f}, .align = TextAlign::Centre, .shadow = kShadow}); | ||
| 62 | float blink = 0.55f + 0.45f * std::cos(4.0f * time); | ||
| 63 | g.ui.draw(batch, "スペースキーで開始 / PRESS SPACE", {640.0f, 392.0f}, | ||
| 64 | {.color = {1.0f, 1.0f, 1.0f, blink}, .scale = 1.5f, .align = TextAlign::Centre, .shadow = kShadow}); | ||
| 65 | g.ui.draw(batch, | ||
| 66 | "WASD 移動 / move マウス / mouse 見回す / look LMB 撃つ / fire RMB 狙う / aim R 装填 / reload\n" | ||
| 67 | "Space 跳ぶ / jump Shift 走る / run Q 肩 / shoulder Esc 一時停止 / pause F3 時間 / timings", | ||
| 68 | {640.0f, 650.0f}, {.color = {1.0f, 1.0f, 1.0f, 0.8f}, .align = TextAlign::Centre, .shadow = kShadow}); | ||
| 69 | batch.end(); | ||
| 70 | } | ||
| 71 | |||
| 72 | //------------------------------------------ | ||
| 73 | // ResultScene | ||
| 74 | //------------------------------------------ | ||
| 75 | |||
| 76 | // 結果の画面ではマウスを使えるように(もう一度:PlayScene::enterがまた捕まえる) / free the cursor on the result | ||
| 77 | // screen (retry: PlayScene::enter captures it again) | ||
| 78 | void ResultScene::enter() { g.window.setCursorCaptured(false); } | ||
| 79 | |||
| 80 | void ResultScene::update(float dt) { | ||
| 81 | time += dt; | ||
| 82 | if (time < 0.5f) return; // 撃ち続けていたボタンで飛ばさない / do not skip it with a button still held from play | ||
| 83 | if (g.input.actionPressed("confirm")) scenes().replaceAll(std::make_unique<PlayScene>(g), kFade); | ||
| 84 | if (g.input.pressed(GLFW_KEY_ESCAPE)) scenes().replaceAll(std::make_unique<TitleScene>(g), kFade); | ||
| 85 | } | ||
| 86 | |||
| 87 | void ResultScene::drawUi(float /*alpha*/) { | ||
| 88 | SpriteBatch &batch = g.batch; | ||
| 89 | batch.begin(g.screen.matrix()); | ||
| 90 | float k = std::fmin(time / 0.4f, 1.0f); // 0.4秒で暗くなる / darkens over 0.4 s | ||
| 91 | batch.drawRect({0.0f, 0.0f, 1280.0f, 720.0f}, {0.0f, 0.0f, 0.0f, 0.45f * k}); | ||
| 92 | batch.drawRect({340.0f, 180.0f, 600.0f, 340.0f}, {0.03f, 0.04f, 0.07f, 0.85f * k}); | ||
| 93 | Vec4 title = r.won ? kGold : Vec4{1.0f, 0.3f, 0.25f, 1.0f}; | ||
| 94 | title.w = k; | ||
| 95 | g.ui.draw(batch, r.won ? "任務完了" : "任務失敗", {640.0f, 200.0f}, | ||
| 96 | {.color = title, .scale = 2.0f, .align = TextAlign::Centre, .shadow = kShadow}); | ||
| 97 | g.ui.draw(batch, r.won ? "MISSION COMPLETE" : "MISSION FAILED", {640.0f, 244.0f}, | ||
| 98 | {.color = title, .scale = 3.0f, .align = TextAlign::Centre, .shadow = kShadow}); | ||
| 99 | int minutes = static_cast<int>(r.seconds) / 60; | ||
| 100 | float seconds = r.seconds - 60.0f * static_cast<float>(minutes); | ||
| 101 | float accuracy = r.shotsFired > 0 ? 100.0f * static_cast<float>(r.shotsHit) / static_cast<float>(r.shotsFired) : 0.0f; | ||
| 102 | std::string stats = std::format("時間 / TIME {}:{:04.1f}\n撃破 / KILLS {} / {}\n命中率 / ACCURACY {:.0f}% ({}/{})", | ||
| 103 | minutes, seconds, r.kills, r.enemies, accuracy, r.shotsHit, r.shotsFired); | ||
| 104 | g.ui.draw(batch, stats, {440.0f, 320.0f}, {.color = {0.9f, 0.9f, 0.95f, k}, .scale = 1.5f, .shadow = kShadow}); | ||
| 105 | float blink = 0.6f + 0.4f * std::cos(4.0f * time); | ||
| 106 | g.ui.draw(batch, "Space もう一度 / retry Esc タイトルへ / title", {640.0f, 470.0f}, | ||
| 107 | {.color = {1.0f, 1.0f, 1.0f, k * blink}, .align = TextAlign::Centre, .shadow = kShadow}); | ||
| 108 | batch.end(); | ||
| 109 | } | ||
| 110 | |||
| 111 | //------------------------------------------ | ||
| 112 | // PauseScene | ||
| 113 | //------------------------------------------ | ||
| 114 | |||
| 115 | void PauseScene::enter() { g.window.setCursorCaptured(false); } | ||
| 116 | void PauseScene::exit() { g.window.setCursorCaptured(true); } | ||
| 117 | |||
| 118 | void PauseScene::update(float dt) { | ||
| 119 | time += dt; | ||
| 120 | if (g.input.pressed(GLFW_KEY_ESCAPE) || g.input.actionPressed("confirm")) scenes().pop(); | ||
| 121 | if (g.input.pressed(GLFW_KEY_T)) scenes().replaceAll(std::make_unique<TitleScene>(g), kFade); | ||
| 122 | } | ||
| 123 | |||
| 124 | void PauseScene::drawUi(float /*alpha*/) { | ||
| 125 | SpriteBatch &batch = g.batch; | ||
| 126 | batch.begin(g.screen.matrix()); | ||
| 127 | float k = std::fmin(time / 0.25f, 1.0f); | ||
| 128 | batch.drawRect({0.0f, 0.0f, 1280.0f, 720.0f}, {0.0f, 0.0f, 0.0f, 0.5f * k}); | ||
| 129 | g.ui.draw(batch, "一時停止 / PAUSED", {640.0f, 280.0f}, | ||
| 130 | {.color = {1.0f, 1.0f, 1.0f, k}, .scale = 3.0f, .align = TextAlign::Centre, .shadow = kShadow}); | ||
| 131 | g.ui.draw(batch, "Esc / Space 再開 / resume T タイトルへ / title", {640.0f, 360.0f}, | ||
| 132 | {.color = {0.9f, 0.9f, 0.95f, k}, .scale = 1.5f, .align = TextAlign::Centre, .shadow = kShadow}); | ||
| 133 | batch.end(); | ||
| 134 | } | ||
ファイル: /dev/null | b/games/tps/src/menu_scenes.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,62 @@ | |||
| 1 | // ゲームの流れ(第39章):タイトル → 遊ぶ → 勝ち・負けの画面、一時停止。第26章のSceneManagerで切り替える | ||
| 2 | // Game flow (chapter 39): title → play → win / lose screen, plus pause. Switched with chapter 26's SceneManager | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include "game.hh" | ||
| 6 | |||
| 7 | #include "engine/scene.hh" | ||
| 8 | |||
| 9 | // タイトル:レベルの上をゆっくり回るカメラ+題名。Space / Enterで始める、Escで終了 | ||
| 10 | // The title: a camera slowly circling over the level + the title. Space / Enter starts, Esc quits | ||
| 11 | class TitleScene : public Scene { | ||
| 12 | public: | ||
| 13 | explicit TitleScene(Game &game) : g(game) {} | ||
| 14 | void enter() override; | ||
| 15 | void update(float dt) override; | ||
| 16 | void draw(float alpha) override; | ||
| 17 | void drawUi(float alpha) override; | ||
| 18 | |||
| 19 | private: | ||
| 20 | Game &g; | ||
| 21 | float time = 0.0f, prevTime = 0.0f; | ||
| 22 | }; | ||
| 23 | |||
| 24 | // 一回の結果(PlaySceneが渡す) / the outcome of one round (PlayScene hands it over) | ||
| 25 | struct RoundResult { | ||
| 26 | bool won = false; | ||
| 27 | float seconds = 0.0f; | ||
| 28 | int kills = 0, enemies = 0, shotsFired = 0, shotsHit = 0; | ||
| 29 | }; | ||
| 30 | |||
| 31 | // 勝ち・負け:PlaySceneの上に重ねる(下の絵は止まったまま見える)。Space もう一度、Esc タイトルへ | ||
| 32 | // Win / lose: an overlay on PlayScene (the frozen picture stays visible below). Space retry, Esc back to the title | ||
| 33 | class ResultScene : public Scene { | ||
| 34 | public: | ||
| 35 | ResultScene(Game &game, RoundResult result) : g(game), r(result) {} | ||
| 36 | bool isOverlay() const override { return true; } | ||
| 37 | void enter() override; | ||
| 38 | void update(float dt) override; | ||
| 39 | void draw(float /*alpha*/) override {} | ||
| 40 | void drawUi(float alpha) override; | ||
| 41 | |||
| 42 | private: | ||
| 43 | Game &g; | ||
| 44 | RoundResult r; | ||
| 45 | float time = 0.0f; | ||
| 46 | }; | ||
| 47 | |||
| 48 | // 一時停止:Esc / Space 再開、T タイトルへ / pause: Esc / Space resume, T back to the title | ||
| 49 | class PauseScene : public Scene { | ||
| 50 | public: | ||
| 51 | explicit PauseScene(Game &game) : g(game) {} | ||
| 52 | bool isOverlay() const override { return true; } | ||
| 53 | void enter() override; | ||
| 54 | void exit() override; | ||
| 55 | void update(float dt) override; | ||
| 56 | void draw(float /*alpha*/) override {} | ||
| 57 | void drawUi(float alpha) override; | ||
| 58 | |||
| 59 | private: | ||
| 60 | Game &g; | ||
| 61 | float time = 0.0f; | ||
| 62 | }; | ||
ファイル: a/games/tps/src/play_scene.cc | b/games/tps/src/play_scene.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,6 +1,7 @@ | |||
| 1 | #include "play_scene.hh" | 1 | #include "play_scene.hh" |
| 2 | 2 | ||
| 3 | #include "angles.hh" | 3 | #include "angles.hh" |
| 4 | #include "menu_scenes.hh" | ||
| 4 | 5 | ||
| 5 | #include <algorithm> | 6 | #include <algorithm> |
| 6 | #include <cmath> | 7 | #include <cmath> |
| @@ -25,7 +26,6 @@ constexpr float kReloadTime = 1.6f; | |||
| 25 | constexpr float kDamage = 34.0f; // 胸に3発、頭に2発 / three to the chest, two to the head | 26 | constexpr float kDamage = 34.0f; // 胸に3発、頭に2発 / three to the chest, two to the head |
| 26 | constexpr float kEnemyDamage = 8.0f; | 27 | constexpr float kEnemyDamage = 8.0f; |
| 27 | constexpr float kHearing = 18.0f; // 銃声が聞こえる距離 / how far a shot is heard | 28 | constexpr float kHearing = 18.0f; // 銃声が聞こえる距離 / how far a shot is heard |
| 28 | constexpr float kRespawnTime = 3.0f; | ||
| 29 | 29 | ||
| 30 | // 円錐の中のでたらめな向き(拡散):axisから最大angleラジアン / a random direction inside a cone (spread): at most angle | 30 | // 円錐の中のでたらめな向き(拡散):axisから最大angleラジアン / a random direction inside a cone (spread): at most angle |
| 31 | // radians from axis | 31 | // radians from axis |
| @@ -77,7 +77,9 @@ void PlayScene::update(float dt) { | |||
| 77 | prevForward = camera.forward(); | 77 | prevForward = camera.forward(); |
| 78 | time += dt; | 78 | time += dt; |
| 79 | 79 | ||
| 80 | if (in.pressed(GLFW_KEY_ESCAPE)) scenes().pop(); // 最後のシーン → 終了 / the last scene → quit | 80 | // Esc:一時停止(第39章。上に重ねるので、この場面は止まったまま描かれる) / Esc: pause (chapter 39; an overlay, so |
| 81 | // this scene stays visible, frozen) | ||
| 82 | if (in.pressed(GLFW_KEY_ESCAPE)) scenes().push(std::make_unique<PauseScene>(g)); | ||
| 81 | if (in.pressed(GLFW_KEY_TAB)) g.window.setCursorCaptured(!g.window.cursorCaptured()); | 83 | if (in.pressed(GLFW_KEY_TAB)) g.window.setCursorCaptured(!g.window.cursorCaptured()); |
| 82 | if (in.pressed(GLFW_KEY_Q)) camera.shoulderSide = -camera.shoulderSide; | 84 | if (in.pressed(GLFW_KEY_Q)) camera.shoulderSide = -camera.shoulderSide; |
| 83 | if (in.pressed(GLFW_KEY_B)) g.showBoxes = !g.showBoxes; | 85 | if (in.pressed(GLFW_KEY_B)) g.showBoxes = !g.showBoxes; |
| @@ -89,6 +91,14 @@ void PlayScene::update(float dt) { | |||
| 89 | if (in.pressed(GLFW_KEY_L)) body.slide = !body.slide; | 91 | if (in.pressed(GLFW_KEY_L)) body.slide = !body.slide; |
| 90 | if (in.pressed(GLFW_KEY_O)) overhead = !overhead; | 92 | if (in.pressed(GLFW_KEY_O)) overhead = !overhead; |
| 91 | if (in.pressed(GLFW_KEY_F8)) logging = !logging; | 93 | if (in.pressed(GLFW_KEY_F8)) logging = !logging; |
| 94 | // 速さの工夫(第39章):F5 描く解像度 100 → 75 → 50 %、F6 影のオン・オフ、F7 影の地図 2048 ⇔ 1024 | ||
| 95 | // Performance options (chapter 39): F5 render scale 100 → 75 → 50 %, F6 shadows on / off, F7 shadow map 2048 ⇔ 1024 | ||
| 96 | if (in.pressed(GLFW_KEY_F5)) { | ||
| 97 | float s = g.renderer.renderScale(); | ||
| 98 | g.renderer.setRenderScale(s > 0.9f ? 0.75f : s > 0.6f ? 0.5f : 1.0f); | ||
| 99 | } | ||
| 100 | if (in.pressed(GLFW_KEY_F6)) g.renderer.settings.shadows = !g.renderer.settings.shadows; | ||
| 101 | if (in.pressed(GLFW_KEY_F7)) g.renderer.setShadowMapSize(g.renderer.shadowMapSize() == 2048 ? 1024 : 2048); | ||
| 92 | 102 | ||
| 93 | // 1. 見回す(マウスの動きはフレームごと:最初のステップだけが使う) / 1. look around (mouse movement is per frame: | 103 | // 1. 見回す(マウスの動きはフレームごと:最初のステップだけが使う) / 1. look around (mouse movement is per frame: |
| 94 | // only the first step uses it) | 104 | // only the first step uses it) |
| @@ -184,21 +194,35 @@ void PlayScene::update(float dt) { | |||
| 184 | separateCharacters(); | 194 | separateCharacters(); |
| 185 | effects.update(dt); | 195 | effects.update(dt); |
| 186 | 196 | ||
| 187 | // 8. 体力:撃たれなければ4秒後から回復。倒れたら3秒後に出発点から(第39章で負けの画面になる) | 197 | // 8. 体力:撃たれなければ4秒後から回復。0で負け(第39章:結果の画面へ) / 8. health: regenerates from 4 s after |
| 188 | // 8. health: regenerates from 4 s after the last hit. When down, back at the start after 3 s (chapter 39 turns this | 198 | // the last hit; 0 = defeat (chapter 39: to the result screen) |
| 189 | // into the defeat screen) | ||
| 190 | hurt = std::fmax(hurt - dt, 0.0f); | 199 | hurt = std::fmax(hurt - dt, 0.0f); |
| 191 | sinceHurt += dt; | 200 | sinceHurt += dt; |
| 192 | if (alive && sinceHurt > 4.0f) health = std::fmin(health + 12.0f * dt, 100.0f); | 201 | if (alive && sinceHurt > 4.0f) health = std::fmin(health + 12.0f * dt, 100.0f); |
| 193 | if (!alive && (deadTime += dt) > kRespawnTime) { | 202 | if (!alive) deadTime += dt; |
| 194 | alive = true; | 203 | |
| 195 | health = 100.0f; | 204 | // 9. HUDの値(第39章) / 9. the HUD's values (chapter 39) |
| 196 | ammo = kMagazine; | 205 | int left = 0; |
| 197 | body.position = position = prevPosition = g.level.spawn; | 206 | for (const Enemy &e : enemies) left += e.alive() ? 1 : 0; |
| 198 | body.velocity = {0.0f, 0.0f, 0.0f}; | 207 | if (alive && left > 0) roundTime += dt; |
| 199 | camera.reset(cameraPivot(), g.level.solids); // カメラもすぐ出発点へ / the camera cuts to the spawn too | 208 | // 遅れて減る棒:0.4秒待ってから毎秒40ずつ追いつく / the lagging bar waits 0.4 s, then catches up at 40 per second |
| 200 | prevEye = camera.eye(); | 209 | if (sinceHurt > 0.4f) hud.healthShown = std::fmax(hud.healthShown - 40.0f * dt, health); |
| 201 | prevForward = camera.forward(); | 210 | hud.healthShown = std::fmax(hud.healthShown, health); |
| 211 | for (DamageMarker &d : hud.damage) d.life -= dt; | ||
| 212 | std::erase_if(hud.damage, [](const DamageMarker &d) { return d.life <= 0.0f; }); | ||
| 213 | |||
| 214 | // 10. 勝ち・負け:少し見せてから結果の画面を重ねる。敵のいないレベル(pieces.level)は勝ちにならない | ||
| 215 | // 10. win / loss: show it for a moment, then push the result screen. A level without enemies (pieces.level) is | ||
| 216 | // never won | ||
| 217 | bool cleared = left == 0 && !enemies.empty(); | ||
| 218 | if (!finished && (!alive || cleared)) { | ||
| 219 | endTimer += dt; | ||
| 220 | if (endTimer > (alive ? 2.0f : 2.5f)) { | ||
| 221 | finished = true; | ||
| 222 | RoundResult result{.won = alive, .seconds = roundTime, .kills = kills, | ||
| 223 | .enemies = static_cast<int>(enemies.size()), .shotsFired = shotsFired, .shotsHit = shotsHit}; | ||
| 224 | scenes().push(std::make_unique<ResultScene>(g, result)); | ||
| 225 | } | ||
| 202 | } | 226 | } |
| 203 | } | 227 | } |
| 204 | 228 | ||
| @@ -275,9 +299,10 @@ void PlayScene::shoot() { | |||
| 275 | Enemy &e = enemies[static_cast<size_t>(index)]; | 299 | Enemy &e = enemies[static_cast<size_t>(index)]; |
| 276 | bool wasAlive = e.alive(); | 300 | bool wasAlive = e.alive(); |
| 277 | e.alert(position, kDamage * multiplier); | 301 | e.alert(position, kDamage * multiplier); |
| 278 | if (wasAlive && !e.alive()) ++kills; | 302 | killed = wasAlive && !e.alive(); |
| 303 | if (killed) ++kills; | ||
| 279 | ++shotsHit; | 304 | ++shotsHit; |
| 280 | hitMarker = 0.15f; | 305 | hitMarker = killed ? 0.35f : 0.15f; |
| 281 | effects.sparks(end, -1.0f * dir, {6.0f, 0.9f, 0.4f}, 14, rng); // 赤い火花 / red sparks | 306 | effects.sparks(end, -1.0f * dir, {6.0f, 0.9f, 0.4f}, 14, rng); // 赤い火花 / red sparks |
| 282 | } else if (wall) { | 307 | } else if (wall) { |
| 283 | end = blocked ? start : muzzle + wall->t * dir; | 308 | end = blocked ? start : muzzle + wall->t * dir; |
| @@ -305,6 +330,10 @@ void PlayScene::enemyFire(Enemy &e, Vec3 aim) { | |||
| 305 | effects.tracer(muzzle, end, {6.0f, 1.4f, 0.5f}); | 330 | effects.tracer(muzzle, end, {6.0f, 1.4f, 0.5f}); |
| 306 | if (hit) { | 331 | if (hit) { |
| 307 | hurtPlayer(kEnemyDamage); | 332 | hurtPlayer(kEnemyDamage); |
| 333 | // HUDの撃たれた向き:撃った敵の水平の向きを、カメラの向きから測る / the HUD's damage direction: the shooter's | ||
| 334 | // horizontal direction measured from where the camera looks | ||
| 335 | Vec3 d = e.body.position - position; | ||
| 336 | hud.damage.push_back({wrapAngle(std::atan2(d.x, -d.z) - camera.yaw), 1.0f}); | ||
| 308 | effects.sparks(end, -1.0f * dir, {6.0f, 0.9f, 0.4f}, 8, rng); | 337 | effects.sparks(end, -1.0f * dir, {6.0f, 0.9f, 0.4f}, 8, rng); |
| 309 | } else if (wall) { | 338 | } else if (wall) { |
| 310 | effects.sparks(end, wall->normal, {5.0f, 3.2f, 1.2f}, 8, rng); | 339 | effects.sparks(end, wall->normal, {5.0f, 3.2f, 1.2f}, 8, rng); |
| @@ -347,7 +376,7 @@ void PlayScene::separateCharacters() { | |||
| 347 | 376 | ||
| 348 | void PlayScene::logState() const { | 377 | void PlayScene::logState() const { |
| 349 | Vec3 eye = camera.eye(); | 378 | Vec3 eye = camera.eye(); |
| 350 | printf("log frame %d pos (%.2f %.2f %.2f) eye (%.3f %.3f %.3f) yaw %.4f pitch %.4f hp %.0f ammo %d |", g.frame, | 379 | printf("log frame %d t %.4f pos (%.2f %.2f %.2f) eye (%.3f %.3f %.3f) yaw %.4f pitch %.4f hp %.0f ammo %d |", g.frame, static_cast<double>(time), |
| 351 | position.x, position.y, position.z, eye.x, eye.y, eye.z, camera.yaw, camera.pitch, health, ammo); | 380 | position.x, position.y, position.z, eye.x, eye.y, eye.z, camera.yaw, camera.pitch, health, ammo); |
| 352 | for (const Enemy &e : enemies) | 381 | for (const Enemy &e : enemies) |
| 353 | printf(" %s (%.2f %.2f %.2f) %.0f%s |", enemyStateName(e.state), e.body.position.x, e.body.position.y, | 382 | printf(" %s (%.2f %.2f %.2f) %.0f%s |", enemyStateName(e.state), e.body.position.x, e.body.position.y, |
| @@ -558,7 +587,7 @@ void PlayScene::drawUi(float /*alpha*/) { | |||
| 558 | "level pieces drawn {}/{} ({} draw calls) shadow casters {} ({} draw calls) shadow texel {:.1f} mm\n" | 587 | "level pieces drawn {}/{} ({} draw calls) shadow casters {} ({} draw calls) shadow texel {:.1f} mm\n" |
| 559 | "camera distance {:.2f} m{}{} collision boxes {} culling {} scene fragments {:.2f} M\n" | 588 | "camera distance {:.2f} m{}{} collision boxes {} culling {} scene fragments {:.2f} M\n" |
| 560 | "body: {} {}{}{} contacts {} y {:.2f} m velocity ({:.1f}, {:.1f}, {:.1f}) jumps {} wall slide {}\n" | 589 | "body: {} {}{}{} contacts {} y {:.2f} m velocity ({:.1f}, {:.1f}, {:.1f}) jumps {} wall slide {}\n" |
| 561 | "particles {} kills {} deaths {}", | 590 | "particles {} kills {} deaths {} render scale {:.0f} % (F5) shadows {} {} px (F6/F7)", |
| 562 | g.frameMs, r.timings.shadowMs, r.timings.sceneMs, r.timings.postMs, levelStats.visible, levelStats.total, | 591 | g.frameMs, r.timings.shadowMs, r.timings.sceneMs, r.timings.postMs, levelStats.visible, levelStats.total, |
| 563 | levelStats.drawCalls, shadowStats.visible, shadowStats.drawCalls, r.shadowTexelMm(), | 592 | levelStats.drawCalls, shadowStats.visible, shadowStats.drawCalls, r.shadowTexelMm(), |
| 564 | camera.currentDistance(), camera.blocked() ? " (pulled in by a wall)" : "", | 593 | camera.currentDistance(), camera.blocked() ? " (pulled in by a wall)" : "", |
| @@ -566,47 +595,34 @@ void PlayScene::drawUi(float /*alpha*/) { | |||
| 566 | static_cast<double>(r.timings.sceneFragments) / 1e6, body.grounded ? "grounded" : "airborne", | 595 | static_cast<double>(r.timings.sceneFragments) / 1e6, body.grounded ? "grounded" : "airborne", |
| 567 | body.hitWall ? "wall " : "", body.steppedUp ? "stepped-up " : "", body.snappedDown ? "snapped-down " : "", | 596 | body.hitWall ? "wall " : "", body.steppedUp ? "stepped-up " : "", body.snappedDown ? "snapped-down " : "", |
| 568 | body.contacts, body.position.y, body.velocity.x, body.velocity.y, body.velocity.z, jumps, | 597 | body.contacts, body.position.y, body.velocity.x, body.velocity.y, body.velocity.z, jumps, |
| 569 | body.slide ? "on" : "OFF (L)", effects.particleCount(), kills, deaths); | 598 | body.slide ? "on" : "OFF (L)", effects.particleCount(), kills, deaths, 100.0f * r.renderScale(), |
| 570 | batch.drawRect({0.0f, 0.0f, 1280.0f, 108.0f}, {0.0f, 0.0f, 0.0f, 0.45f}); | 599 | r.settings.shadows ? "on" : "OFF", r.shadowMapSize()); |
| 571 | g.ui.draw(batch, lines, {10.0f, 6.0f}, small); | 600 | // HUDの敵の枠(y 16〜68)の下に / below the HUD's enemies panel (y 16-68) |
| 572 | } | 601 | batch.drawRect({0.0f, 76.0f, 1280.0f, 108.0f}, {0.0f, 0.0f, 0.0f, 0.55f}); |
| 573 | // 照準(第38章の簡単なもの。第39章でHUDになる):真ん中の点と4本の線。拡散が大きいほど開く。当てると赤く | 602 | g.ui.draw(batch, lines, {10.0f, 82.0f}, small); |
| 574 | // The crosshair (chapter 38's simple one; chapter 39 makes it a HUD): a center dot and four lines that open with the | ||
| 575 | // spread; red on a hit | ||
| 576 | if (alive) { | ||
| 577 | float moving = length(Vec3{body.velocity.x, 0.0f, body.velocity.z}) > 0.5f ? 1.0f : 0.0f; | ||
| 578 | float gap = 5.0f + 9.0f * (1.0f - aimBlend) + 8.0f * moving; | ||
| 579 | Vec4 c = hitMarker > 0.0f ? Vec4{1.0f, 0.25f, 0.2f, 1.0f} : Vec4{1.0f, 1.0f, 1.0f, 0.9f}; | ||
| 580 | batch.drawRect({639.0f, 359.0f, 2.0f, 2.0f}, c); | ||
| 581 | batch.drawRect({639.0f, 360.0f - gap - 8.0f, 2.0f, 8.0f}, c); | ||
| 582 | batch.drawRect({639.0f, 360.0f + gap, 2.0f, 8.0f}, c); | ||
| 583 | batch.drawRect({640.0f - gap - 8.0f, 359.0f, 8.0f, 2.0f}, c); | ||
| 584 | batch.drawRect({640.0f + gap, 359.0f, 8.0f, 2.0f}, c); | ||
| 585 | } | ||
| 586 | // 撃たれたら画面の縁を赤く / a red screen edge when hit | ||
| 587 | if (hurt > 0.0f) { | ||
| 588 | Vec4 red = {0.8f, 0.0f, 0.0f, 0.5f * hurt / 0.35f}; | ||
| 589 | batch.drawRect({0.0f, 0.0f, 1280.0f, 40.0f}, red); | ||
| 590 | batch.drawRect({0.0f, 680.0f, 1280.0f, 40.0f}, red); | ||
| 591 | batch.drawRect({0.0f, 40.0f, 40.0f, 640.0f}, red); | ||
| 592 | batch.drawRect({1240.0f, 40.0f, 40.0f, 640.0f}, red); | ||
| 593 | } | 603 | } |
| 604 | // HUD(第39章):毎フレーム状態を詰めて描く / the HUD (chapter 39): fill in the state and draw it every frame | ||
| 594 | int left = 0; | 605 | int left = 0; |
| 595 | for (const Enemy &e : enemies) left += e.alive() ? 1 : 0; | 606 | for (const Enemy &e : enemies) left += e.alive() ? 1 : 0; |
| 596 | std::string status = std::format("体力 / HP {:3.0f} 弾 / AMMO {:2d}/{}{} 敵 / ENEMIES {}/{} hits {}/{}", health, | 607 | float moving = length(Vec3{body.velocity.x, 0.0f, body.velocity.z}) > 0.5f ? 1.0f : 0.0f; |
| 597 | ammo, kMagazine, reloadTime > 0.0f ? " (装填 / reloading)" : "", left, | 608 | hud.health = health; |
| 598 | enemies.size(), shotsHit, shotsFired); | 609 | hud.ammo = ammo; |
| 599 | g.ui.draw(batch, status, {20.0f, 660.0f}, {.color = {1.0f, 1.0f, 1.0f, 0.95f}, .scale = 1.0f, | 610 | hud.magazine = kMagazine; |
| 600 | .shadow = {0.0f, 0.0f, 0.0f, 0.9f}}); | 611 | hud.reload = reloadTime > 0.0f ? 1.0f - reloadTime / kReloadTime : -1.0f; |
| 601 | if (!alive) | 612 | hud.enemiesLeft = left; |
| 613 | hud.enemiesTotal = static_cast<int>(enemies.size()); | ||
| 614 | hud.spread = 5.0f + 9.0f * (1.0f - aimBlend) + 8.0f * moving + (fireTimer > 0.0f ? 4.0f : 0.0f); | ||
| 615 | hud.hitMarker = std::fmax(hitMarker, 0.0f) / (killed ? 0.35f : 0.15f); | ||
| 616 | hud.killMarker = killed; | ||
| 617 | hud.hurt = hurt / 0.35f; | ||
| 618 | hud.alive = alive; | ||
| 619 | drawHud(batch, g.ui, hud); | ||
| 620 | // 結果の画面が出たら消す(重なって読めない) / hidden once the result screen is up (they would overlap) | ||
| 621 | if (!alive && !finished) | ||
| 602 | g.ui.draw(batch, "倒れた / DOWN", {640.0f, 300.0f}, {.color = {1.0f, 0.3f, 0.25f, 1.0f}, .scale = 3.0f, | 622 | g.ui.draw(batch, "倒れた / DOWN", {640.0f, 300.0f}, {.color = {1.0f, 0.3f, 0.25f, 1.0f}, .scale = 3.0f, |
| 603 | .align = TextAlign::Centre, .shadow = {0, 0, 0, 0.9f}}); | 623 | .align = TextAlign::Centre, .shadow = {0, 0, 0, 0.9f}}); |
| 604 | else if (left == 0) | 624 | else if (left == 0 && !enemies.empty() && !finished) |
| 605 | g.ui.draw(batch, "敵を全部倒した / ALL ENEMIES DOWN", {640.0f, 300.0f}, | 625 | g.ui.draw(batch, "敵を全部倒した / ALL ENEMIES DOWN", {640.0f, 300.0f}, |
| 606 | {.color = {1.0f, 0.85f, 0.3f, 1.0f}, .scale = 2.0f, .align = TextAlign::Centre, .shadow = {0, 0, 0, 0.9f}}); | 626 | {.color = {1.0f, 0.85f, 0.3f, 1.0f}, .scale = 2.0f, .align = TextAlign::Centre, .shadow = {0, 0, 0, 0.9f}}); |
| 607 | g.ui.draw(batch, "LMB 撃つ / fire RMB 狙う / aim R 装填 / reload Space 跳ぶ / jump Shift 走る / run " | ||
| 608 | "Q 肩 / shoulder", | ||
| 609 | {640.0f, 694.0f}, {.color = {1.0f, 1.0f, 1.0f, 0.7f}, .align = TextAlign::Centre, | ||
| 610 | .shadow = {0.0f, 0.0f, 0.0f, 0.8f}}); | ||
| 611 | batch.end(); | 627 | batch.end(); |
| 612 | } | 628 | } |
ファイル: a/games/tps/src/play_scene.hh | b/games/tps/src/play_scene.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -8,6 +8,7 @@ | |||
| 8 | #include "effects.hh" | 8 | #include "effects.hh" |
| 9 | #include "enemy.hh" | 9 | #include "enemy.hh" |
| 10 | #include "game.hh" | 10 | #include "game.hh" |
| 11 | #include "hud.hh" | ||
| 11 | #include "third_person_camera.hh" | 12 | #include "third_person_camera.hh" |
| 12 | 13 | ||
| 13 | #include "engine/rng.hh" | 14 | #include "engine/rng.hh" |
| @@ -82,5 +83,12 @@ private: | |||
| 82 | float aimBlend = 0.0f; // 0 = 腰だめ、1 = 狙う(右ボタン) / 0 = hip fire, 1 = aiming (right button) | 83 | float aimBlend = 0.0f; // 0 = 腰だめ、1 = 狙う(右ボタン) / 0 = hip fire, 1 = aiming (right button) |
| 83 | float hitMarker = 0.0f; // 当てたときの印の残り / remaining hit-marker time | 84 | float hitMarker = 0.0f; // 当てたときの印の残り / remaining hit-marker time |
| 84 | int shotsFired = 0, shotsHit = 0, kills = 0, deaths = 0; | 85 | int shotsFired = 0, shotsHit = 0, kills = 0, deaths = 0; |
| 86 | |||
| 87 | // 第39章:HUD、ゲームの流れ / chapter 39: HUD, game flow | ||
| 88 | HudState hud; | ||
| 89 | bool killed = false; // 今の当てた印は倒した一発 / the current hit marker is a kill | ||
| 90 | float roundTime = 0.0f; // 遊んだ時間 / time played | ||
| 91 | float endTimer = 0.0f; // 勝ち・負けから結果の画面まで / from win / loss to the result screen | ||
| 92 | bool finished = false; // 結果の画面を出した / the result screen was shown | ||
| 85 | LevelDrawStats levelStats, shadowStats; | 93 | LevelDrawStats levelStats, shadowStats; |
| 86 | }; | 94 | }; |
ファイル: a/games/tps/src/renderer.cc | b/games/tps/src/renderer.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -2,6 +2,7 @@ | |||
| 2 | 2 | ||
| 3 | #include "engine/shapes.hh" | 3 | #include "engine/shapes.hh" |
| 4 | 4 | ||
| 5 | #include <algorithm> | ||
| 5 | #include <cmath> | 6 | #include <cmath> |
| 6 | #include <cstdio> | 7 | #include <cstdio> |
| 7 | 8 | ||
| @@ -64,6 +65,8 @@ std::unique_ptr<Renderer> Renderer::create(int width, int height, const RenderSe | |||
| 64 | r->ibl = Ibl::build(*r->sky); | 65 | r->ibl = Ibl::build(*r->sky); |
| 65 | r->shadowMap.emplace(settings.shadowMapSize); | 66 | r->shadowMap.emplace(settings.shadowMapSize); |
| 66 | r->post = PostChain::create(width, height, settings.post); | 67 | r->post = PostChain::create(width, height, settings.post); |
| 68 | r->windowW = width; | ||
| 69 | r->windowH = height; | ||
| 67 | if (!r->ibl || !r->shadowMap->complete() || !r->post) return nullptr; | 70 | if (!r->ibl || !r->shadowMap->complete() || !r->post) return nullptr; |
| 68 | 71 | ||
| 69 | const unsigned char whitePixel[4] = {255, 255, 255, 255}; | 72 | const unsigned char whitePixel[4] = {255, 255, 255, 255}; |
| @@ -73,6 +76,18 @@ std::unique_ptr<Renderer> Renderer::create(int width, int height, const RenderSe | |||
| 73 | return r; | 76 | return r; |
| 74 | } | 77 | } |
| 75 | 78 | ||
| 79 | void Renderer::resize(int width, int height) { | ||
| 80 | windowW = width; | ||
| 81 | windowH = height; | ||
| 82 | setRenderScale(scale); | ||
| 83 | } | ||
| 84 | |||
| 85 | void Renderer::setRenderScale(float s) { | ||
| 86 | scale = s; | ||
| 87 | post->resize(std::max(1, static_cast<int>(std::lround(s * static_cast<float>(windowW)))), | ||
| 88 | std::max(1, static_cast<int>(std::lround(s * static_cast<float>(windowH))))); | ||
| 89 | } | ||
| 90 | |||
| 76 | void Renderer::beginFrame(const FrameView &view, const LightSet &lights) { | 91 | void Renderer::beginFrame(const FrameView &view, const LightSet &lights) { |
| 77 | current = view; | 92 | current = view; |
| 78 | sunDirection = lights.directional.direction; | 93 | sunDirection = lights.directional.direction; |
ファイル: a/games/tps/src/renderer.hh | b/games/tps/src/renderer.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -110,7 +110,16 @@ public: | |||
| 110 | void endScene(); | 110 | void endScene(); |
| 111 | // 画面へ(後処理)。この後は既定のフレームバッファ / to the screen (post); afterwards the default framebuffer is bound | 111 | // 画面へ(後処理)。この後は既定のフレームバッファ / to the screen (post); afterwards the default framebuffer is bound |
| 112 | void present(int windowWidth, int windowHeight); | 112 | void present(int windowWidth, int windowHeight); |
| 113 | void resize(int width, int height) { post->resize(width, height); } | 113 | // ウィンドウの大きさが変わった / the window size changed |
| 114 | void resize(int width, int height); | ||
| 115 | // 描く解像度(第39章の速さの工夫):場面のFBOをウィンドウのscale倍にして、後処理で画面いっぱいに引き伸ばす。 | ||
| 116 | // フラグメントの数がscale²倍になる | ||
| 117 | // Render scale (chapter 39's performance tip): the scene FBOs are scale × the window size and the post pass | ||
| 118 | // stretches them over the screen. The fragment count goes with scale² | ||
| 119 | void setRenderScale(float scale); | ||
| 120 | float renderScale() const { return scale; } | ||
| 121 | void setShadowMapSize(int size) { shadowMap->resize(size); } | ||
| 122 | int shadowMapSize() const { return shadowMap->size(); } | ||
| 114 | 123 | ||
| 115 | // ゲームが描くのに使うもの / what the game draws with | 124 | // ゲームが描くのに使うもの / what the game draws with |
| 116 | std::optional<Shader> pbr; // phong.vert + pbr.frag:一つずつ描く物 / single objects | 125 | std::optional<Shader> pbr; // phong.vert + pbr.frag:一つずつ描く物 / single objects |
| @@ -141,5 +150,7 @@ private: | |||
| 141 | FragmentCounter sceneFragments; | 150 | FragmentCounter sceneFragments; |
| 142 | FrameView current; | 151 | FrameView current; |
| 143 | Vec3 sunDirection = {-0.5f, -1.0f, -0.35f}; | 152 | Vec3 sunDirection = {-0.5f, -1.0f, -0.35f}; |
| 153 | int windowW = 1280, windowH = 720; // ウィンドウの大きさ / the window size | ||
| 154 | float scale = 1.0f; | ||
| 144 | Frustum lightBox, cameraFrustum; | 155 | Frustum lightBox, cameraFrustum; |
| 145 | }; | 156 | }; |
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。