34. Top-Down RPG Part 2: Maps, Doors and Scene Switching
At the end of chapter 33 the hero could walk around one village: a tile map from a text file, a static vertex buffer, collision against solid cells and a camera that follows.
One map is a level, not a world.
In this chapter the village gets a house you can enter and an exit to a field, and the game learns to move between maps.
The technique is the scene stack from chapter 26: every map visit is its own scene, and a door replaces it with the next one behind a fade.
The interesting part isn't the switch itself, which the engine already does, but the question it raises: when the hero leaves a map and comes back, what is still the same?
An opened chest should stay open; the hero shouldn't be standing where they left the house a minute ago.
The chapter answers that with one rule and one class, World.
There are no new OpenGL functions this time.
The only GL point is that the static tile buffer is rebuilt for each map, while the VAO, the program and the atlas texture are kept.
34.1 What we're building
The program rpg now has three maps: the village (40 × 28 tiles), the hero's home (12 × 10) and a field (40 × 24).
The house door leads inside, the road's east end leads to the field, and three chests with gold are spread over the three maps.
The clip is a full tour: into the house, open the chest, back out, open the village chest, run to the field, open the chest in the fenced garden, and back to the village, where the first chest is still open:
Each map shows its title in a banner when you enter it, and the gold total sits in the bottom-right corner of the canvas.
The home map is smaller than the 320 × 180 canvas (192 × 160 pixels), so the camera centers it and the rest of the canvas stays dark; chapter 33's camera already handled that case.
The controls are chapter 33's plus one key:
- Arrow keys or W, A, S, D move, Shift runs
- Space or Enter checks what's in front of you: here, it opens a chest
- 1, 2, 3 toggle the layers, B shows the collision boxes (now also doors, chests and the probe), Z zooms out, H toggles the HUD, R reloads the maps and the tileset from their files, Esc quits
Starting from chapter 33, the changes are all inside games/rpg/:
src/world.hh,src/world.cc(new):World, the map cache and the state that survives leaving a mapsrc/tilemap.hh,src/tilemap.cc: thetitlecommand and a tileset cache argument forTilemap::loadsrc/game.hh:kMapFade,DebugView,World &inGame, and aMapScenethat is built from a map name and a spawn namesrc/map_scene.cc: doors and exits, chests, the facing probe, the title banner and the gold countersrc/main.cc: creates theWorld, binds the "confirm" action and starts with a fadeassets/maps/:village.mapgets a door, an exit, spawn points and a chest;home.mapandfield.mapare new (the finished files are in the chapter's ZIP and inch34/of the assets ZIP)CMakeLists.txt,README.md,assets/LICENSE.txt: the new source file, the new key, the new maps
The game's CMakeLists.txt only gains src/world.cc:
# 見下ろし型RPG(第33〜35章) / the top-down RPG (chapters 33-35)
add_executable(rpg
src/main.cc
src/tilemap.cc
src/tile_renderer.cc
src/character.cc
src/map_scene.cc
src/world.cc)
target_include_directories(rpg PRIVATE src)
target_link_libraries(rpg PRIVATE engine)
enable_warnings(rpg)
set_working_directory(rpg)
34.2 Doors are objects in the map file
Chapter 33's map format already had an object list for exactly this moment: object <kind> <name> <col> <row> [key=value …].
The only object then was the spawn point start.
A door is just another kind of object, so adding doors doesn't change the format at all.
These are the village's objects now:
# 物:object <種類> <名前> <列> <行> [key=value …] / objects: kind name col row [key=value ...]
object spawn start 7 9 face=down
object door home 7 7 map=home spawn=door
object warp east 39 10 h=2 map=field spawn=west
object spawn home_door 7 8 face=down
object spawn east 38 10 face=left
object chest village_chest 21 8 gold=30
door home 7 7 map=home spawn=door: the door of the hero's house at column 7, row 7. Walking into it loadshome.mapand puts the hero at the spawn point calleddoorin that map.warp east 39 10 h=2 map=field spawn=west: an invisible exit at the east edge of the map, one tile wide and two tiles high (h=2), exactly where the road leaves the map.spawn home_doorandspawn east: where the hero appears when coming back from the house and from the field.chest village_chest 21 8 gold=30: a chest with 30 gold.
door and warp behave exactly the same in the code; the two names only say what the map's author meant: door marks a visible door tile, warp an invisible strip at the map edge.
The pairs fit together like this; every door names a map and a spawn point in that map, and every spawn point sits next to the door that leads back:
A map is a graph of these links, and nothing in the code knows the graph: add a fourth map file and a door that names it, and the game has four maps (challenge 1).
Here is the new interior, the top of home.map with its ground layer:
map home
title 家 / Home
tileset ../tiles.tileset
size 12 10
layer ground
xxxxxxxxxxxx
xwwwnwwnwwwx
x__________x
x__________x
x___rrrr___x
x___rrrr___x
x___rrrr___x
x__________x
x____m_____x
xxxxx_xxxxxx
x is the solid "void" tile that fills the rest of the rectangle, w and n are inside walls (plain and with a window), _ is wooden floor, r the rug and m the doormat.
All of them were already in chapter 33's tiles.tileset, which doesn't change in this chapter.
The gap in the bottom row at column 5 is the doorway; the house's objects are at the end of the file:
# 物:object <種類> <名前> <列> <行> [key=value …] / objects: kind name col row [key=value ...]
object spawn start 5 7 face=up
object spawn door 5 8 face=up
object door out 5 9 map=village spawn=home_door
object chest home_chest 8 2 gold=50
The door out is the bottom row's gap, and the spawn point door is the tile just above it.
The field is built the same way: a path from the west exit, two meadows of tall grass, a pond, and a fenced garden with the third chest, with warp west 0 10 h=2 at its left edge.
One tile changes in the village
In chapter 33 the house door in the village was d, a door tile marked solid in tiles.tileset.
A solid door can't be entered: the foot box would stop at its bottom edge and never overlap the door object.
So the hero's door is now D, the same sprite without solid:
T...UMWDWMX..SMWMdMWM......bXMWdWMU..%.T
The other two houses still have d: they stay closed until chapter 35 gives them something to say.
With a walkable door tile, the solid eave above it is what stops the hero, and the door object is what fires:
The spawn tile is row 8, so chapter 33's placeAt puts the 10 × 6 foot box at y = 128 + 16 − 6 = 138, 10 px below the door rectangle's bottom edge (y = 128), so it overlaps nothing.
Walking up at 72 px/s moves the box 1.2 px per update, and after 9 updates its top is at 138 − 10.8 = 127.2, inside the door: the switch starts 0.15 s after you press ↑.
Titles
Every map now has a name to show on screen, with a new title command that takes the rest of the line:
if (command == "map") {
in >> map.mapName;
} else if (command == "title") {
std::getline(in >> std::ws, map.mapTitle);
in >> std::ws skips the spaces after the command, so title 村 / Village stores 村 / Village.
Tilemap::title() falls back to the map's name when a file has no title line.
The field is titled のはら / Field, in kana: the shared pixel12 font from chapter 26 has 252 UI kanji, and 野原 isn't among them, so the kanji would be drawn as ?.
Chapter 35 gives the RPG its own font atlas with every character its text needs.
34.3 One scene per map visit
Chapter 26's SceneManager offers two ways to go somewhere: push puts a scene on top of the current one and keeps it (paused) below; replace destroys the current scene and puts the new one in its place.
For maps, both are plausible:
A push would keep the village exactly as you left it, hero position and all, while you're in the house, and a pop would bring it back.
That's good for a menu or for "enter a cave, come out at the same spot", but our doors go both ways: the house's door pushes the village again, and after a few trips the stack holds a pile of paused villages.
So this chapter uses one scene per visit: a door always replaces the current MapScene with a new one for the target map.
Invaders already did the same in chapter 29, where each new wave is a fresh PlayScene that replaces the old one: a new scene is the simplest possible "reset everything".
Challenge 5 tries push and pop for the house, and shows what that costs.
The fade is a constant in game.hh:
// マップを移るときのフェード(暗くなるのに半分、明るくなるのに半分) / the fade between maps (half to black, half back)
constexpr Transition kMapFade = {.duration = 0.6f, .color = {0.0f, 0.0f, 0.0f, 1.0f}};
and the door check runs at the end of every update:
void MapScene::checkWarps() {
bool onWarp = false;
for (const MapObject &o : map->objects()) {
if ((o.kind != "door" && o.kind != "warp") || !overlaps(hero.box, o.rect)) continue;
onWarp = true;
if (!warpArmed) continue;
std::string target(o.get("map")), spawn(o.get("spawn", "start"));
// 先のマップを今読む(初めてならファイルから)。読めなければ移らない / load the target map now (from its file the
// first time); if it cannot be loaded, stay
if (!g.world.map(target)) {
fprintf(stderr, "%s: %s %s の先のマップ「%s」を読めない / cannot load map '%s'\n", map->path().c_str(),
o.kind.c_str(), o.name.c_str(), target.c_str(), target.c_str());
warpArmed = false;
return;
}
printf("%s → %s (%s)\n", mapName.c_str(), target.c_str(), spawn.c_str());
// 入れ替えは頼むだけ:フェードアウトの後で、このシーンがexit、新しいシーンがenterする
// The replacement is only requested: after the fade out this scene exits and the new one enters
scenes().replace(std::make_unique<MapScene>(g, target, spawn), kMapFade);
leaving = true;
hero.moving = false;
hero.previous = hero.box.position(); // 止める:フェードの間は更新されない / freeze: no updates during the fade
return;
}
if (!onWarp) warpArmed = true; // 扉から離れた:次に触れた扉は効く / off every door: the next one works
}
Walking through it:
- A door fires when the hero's foot box overlaps the object's rectangle;
overlapsis chapter 26's strict AABB test, so touching edges don't count. - Before asking for the switch, the door loads the target map through
World(next section). If the file is missing or broken, the hero stays where they are and stderr says why, instead of switching to a scene that has no map. scenes().replace(…, kMapFade)only queues the switch, as chapter 26 explained; this scene finishes its update first and is destroyed later.printfwrites the trace linevillage → home (door)that the scripted runs are checked against.
What happens during the 0.6 s
A Transition of 0.6 s darkens the screen for half the time, switches, and brightens it for the other half; chapter 26 showed the curve.
At 60 updates per second that is 18 updates of fade-out and 18 of fade-in.
These are four frames of the village → home switch, counted from the update in which the door fired:
- Fade-out (0.3 s): no scene is updated, but the old village scene is still drawn every frame.
- The switch: the manager calls
exit()on the village scene, destroys it, and callsenter()on the new house scene, which builds the house's tiles and places the hero. - Fade-in (0.3 s): the house scene already runs, so you can walk while the screen brightens.
Two lines in checkWarps deal with these phases.
hero.previous = hero.box.position() freezes the interpolation: during the fade-out nothing is updated, but draw(alpha) still blends previous and the current position with an alpha that changes every frame, so a hero who was moving when the door fired would shuffle back and forth for 0.3 s.
That's chapter 26's challenge 5, met for real.
leaving = true makes update return early, which matters for a request made during a fade-in: the manager only starts a new transition once the current one has finished, so a scene that touches a door 0.1 s after arriving keeps being updated until then.
That's easy to do: the east spawn point is 3 px from the village's exit, three updates of walking.
Without leaving the hero would keep walking, and every update would queue one more replace.
Spawn points, and the arming rule
The door check has a second guard, warpArmed.
setUp sets it to false, and it becomes true in the first update in which the hero overlaps no door or warp at all.
With our maps that's the very first update, since every spawn point is next to its door; but if a map author puts a spawn point on a door, the hero would arrive on a door, the door would fire immediately, the other map's door would send them back, and so on forever.
With the arming rule a door only works after you've stepped off all of them once.
The same flag is reset when a target map can't be loaded, so a broken door prints its message once, not 60 times a second.
The first scene fades in too
main pushes the first scene with the same transition:
SceneManager scenes;
// 黒から明るくなって始まる(空のスタックへのpushもフェードできる) / starts by fading in from black (a push onto the
// empty stack can fade too)
scenes.push(std::make_unique<MapScene>(game, "village", "start"), kMapFade);
A push onto an empty stack fades like any other change: the canvas's dark clear color goes to black in 0.3 s, then the village fades in.
It's a small thing, but the game now starts the same way every map starts.
34.4 Building a map's scene in enter()
The scene's constructor only stores the map name and the spawn name.
All the real work happens in enter(), which runs at the moment of the switch, after the fade-out:
void MapScene::enter() {
// マップはWorldから(初めてならファイルを読む)。扉は入る前に読めることを確かめてある
// The map comes from World (loaded from its file the first time). Doors check that it loads before switching
map = g.world.map(mapName);
setUp();
}
void MapScene::setUp() {
g.tiles.build(*map); // 静的な頂点バッファを作る(マップに入るたびに一度) / build the static vertex buffer (once per
// visit)
const MapObject *start = map->findObject("spawn", spawnName);
if (!start) {
fprintf(stderr, "%s: 出発点がない / no spawn point '%s' (startを使う / using start)\n", map->path().c_str(),
spawnName.c_str());
start = map->findObject("spawn", "start");
}
hero.look = 0;
hero.placeAt(start ? start->rect.position() : Vec2{kTile, kTile});
std::string_view face = start ? start->get("face", "down") : "down";
hero.facing = face == "up" ? Facing::Up : face == "left" ? Facing::Left : face == "right" ? Facing::Right : Facing::Down;
// 最初のフレームは更新なしで描かれる:今のうちに立ちのクリップを選んでおく / the first frame is drawn before any
// update: pick the standing clip now
hero.animate(g.characters, 0.0f);
// 宝箱:開いたかどうかはWorldに残っている(マップ名/宝箱名) / chests: whether they are open is kept in World
// (map name/chest name)
chests.clear();
blockers.clear();
for (const MapObject &o : map->objects())
if (o.kind == "chest") {
Rect box = {o.rect.x + 1.0f, o.rect.y + 4.0f, 14.0f, 12.0f};
chests.push_back({&o, box, mapName + "/" + o.name});
blockers.push_back(box);
}
warpArmed = false;
leaving = false;
}
That split matters because of what the old and new scenes share.
Game holds one TileRenderer: one VAO, one program (the engine's sprite shader), one vertex buffer and one index buffer.
During the fade-out the old scene is still drawing with that buffer, so the new scene must not touch it in its constructor, which runs when the door fires, 0.3 s too early.
In enter() the old scene is already gone, so g.tiles.build(*map) can replace the buffers safely.
build is chapter 33's function, unchanged.
It ends like this:
// 不変のストレージ(フラグ0):作るときに中身を渡し、あとは書き換えない。ドライバーはGPUの速いメモリに置ける
// Immutable storage (flags 0): the contents are given at creation and never change. The driver may keep it in fast
// GPU memory
vertices = Buffer(data.data(), static_cast<GLsizeiptr>(data.size() * sizeof(SpriteVertex)), 0);
indices = Buffer(quadIndices.data(), static_cast<GLsizeiptr>(quadIndices.size() * sizeof(std::uint32_t)), 0);
glVertexArrayVertexBuffer(vao, 0, vertices.id(), 0, sizeof(SpriteVertex));
glVertexArrayElementBuffer(vao, indices.id());
Immutable storage (glNamedBufferStorage with flags 0, inside Buffer) can't be resized or rewritten, and the three maps have different sizes, so each visit creates two new buffer objects; assigning to vertices and indices deletes the old ones.
The VAO stays, and glVertexArrayVertexBuffer and glVertexArrayElementBuffer point it at the new buffers.
The sprite program and the atlas texture don't change at all.
How much work is that?
A SpriteVertex is 20 bytes (position, UV and a packed color), so a quad is 80 bytes:
| Map | Size | Static quads | Vertex buffer | Index buffer |
|---|---|---|---|---|
| village | 40 × 28 | 1449 | 115 920 bytes | 25 104 bytes |
| home | 12 × 10 | 134 | 10 720 bytes | 2 880 bytes |
| field | 40 × 24 | 1325 | 106 000 bytes | 22 560 bytes |
(The index buffer covers only the largest layer, 6 indices × 4 bytes per quad: 1046 ground quads in the village, 120 in the house, 940 in the field.)
A loop over 1120 cells and one upload of about 116 KB happen behind a black screen; you won't see them.
A game with large maps streams chunks instead of rebuilding everything (and challenge 6 keeps one buffer per map), but rebuilding in enter() is the simplest thing that is correct.
The rest of setUp turns the map's objects into the scene's own data: the hero at the spawn point (with a warning and a fallback to start if the door named a spawn that doesn't exist), facing the way the spawn says, and one Chest per chest object.
hero.animate(g.characters, 0.0f) is chapter 33's fix for the first frame: the new scene is drawn once right after the switch, before its first update, and without a clip the hero would have no frame to show.
A chest's collision box is 14 × 12 pixels at the bottom of its tile, so the hero can walk up to it from below and is drawn in front of it.
34.5 World: maps from files, loaded on first use
Chapter 33's main loaded the village and moved it into the scene.
With three maps and scenes that come and go, the maps need a home that outlives the scenes.
That's World:
class World {
public:
// マップを名前で:初めてなら games/rpg/assets/maps/<名前>.map を読む。読めなければnullptr。
// ポインターは変わらない(読み直しても同じ場所) / a map by name: loaded from games/rpg/assets/maps/<name>.map on
// first use; nullptr if it cannot be loaded. The pointer stays valid (also across reloads)
Tilemap *map(const std::string &name);
// ファイルから読み直す(タイルセットと、読んであるほかのマップも)。失敗したら全部前のまま / reloads from the file
// (the tileset and the other loaded maps too); on failure everything stays as it was
bool reload(const std::string &name);
int loadedMaps() const { return static_cast<int>(maps.size()); }
bool flag(const std::string &name) const { return flags.contains(name); }
void setFlag(const std::string &name) { flags.insert(name); }
int gold = 0;
static std::string pathOf(const std::string &name) { return "games/rpg/assets/maps/" + name + ".map"; }
private:
std::unordered_map<std::string, std::unique_ptr<Tilemap>> maps;
TilesetCache tilesets;
std::unordered_set<std::string> flags;
};
and its whole implementation:
#include "world.hh"
#include <cstdio>
#include <utility>
#include <vector>
Tilemap *World::map(const std::string &name) {
if (auto it = maps.find(name); it != maps.end()) return it->second.get();
std::optional<Tilemap> loaded = Tilemap::load(pathOf(name), &tilesets);
if (!loaded) return nullptr;
printf("%s: 読んだ / loaded (%d×%d)\n", pathOf(name).c_str(), loaded->width(), loaded->height());
return (maps[name] = std::make_unique<Tilemap>(std::move(*loaded))).get();
}
bool World::reload(const std::string &name) {
if (!maps.contains(name)) return map(name) != nullptr;
// タイルセットも読み直す。マップの格子はタイルセットの番号なので、読んである全部のマップを新しい表で読み直す
// (古いタイルセットを持ったままのマップが残らない)。全部読めたときだけ入れ替え、一つでも失敗したら何も変えない
// The tileset is read again too. Map grids hold the tileset's kind numbers, so every loaded map is read again with
// the new table (no map keeps the old tileset). They are swapped in only if all of them load; one failure changes
// nothing
std::vector<std::string> names = {name}; // 今のマップから:エラーはまずそこに出る / the current map first: its
// errors come first
for (const auto &entry : maps)
if (entry.first != name) names.push_back(entry.first);
TilesetCache freshTilesets;
std::vector<std::pair<Tilemap *, Tilemap>> fresh;
for (const std::string &n : names) {
std::optional<Tilemap> loaded = Tilemap::load(pathOf(n), &freshTilesets);
if (!loaded) return false;
fresh.emplace_back(maps[n].get(), std::move(*loaded));
}
// 同じ場所に入れる:シーンのポインターはそのまま / same addresses: scenes' pointers stay valid
for (auto &[target, loaded] : fresh) *target = std::move(loaded);
tilesets = std::move(freshTilesets); // 古いタイルセット(とテクスチャー)はここで消える / the old tileset (and its
// texture) is freed here
return true;
}
Loaded on first use. World::map("field") looks the name up; the first time it builds the path games/rpg/assets/maps/field.map, loads it, prints a line and keeps it.
The field isn't read until the hero walks to the east exit, and it isn't read again on later visits: in the run's trace below, each map's "loaded" line appears exactly once.
Map names are file names, so a door's map= is all the wiring there is.
A real game with dozens of maps would load them like this, and might also forget maps it hasn't used for a while; three small text files can simply stay.
Stable addresses. The cache holds std::unique_ptr<Tilemap>, not Tilemap values.
A unique_ptr's target never moves, whatever the container does, so the Tilemap * that a scene keeps stays valid while other maps are loaded.
(std::unordered_map happens to keep its elements in place when it grows, too, and only invalidates its iterators; but a std::vector, or the open-addressing hash maps many engines use instead, do move their values, and the pointer makes the guarantee independent of that choice. Holding values would also break maps[name] = …, which needs a default constructor that Tilemap doesn't have.)
The same trick makes R work: reload loads fresh copies and move-assigns each into the same object (*target = std::move(loaded)), so the scene's pointer now sees the new map.
The scene then calls setUp() again, because the chests point at MapObjects inside the old object list, and puts the hero back where they were.
If any of the files has an error, reload returns false before anything has been replaced, and every map stays as it was.
Shared tilesets. All three maps say tileset ../tiles.tileset, and without help each would load its own copy of the tileset, the atlas PNG and its GL texture.
Tilemap::load now takes an optional cache:
// 読んだタイルセットを覚えておく表(パス → タイルセット):同じタイルセットのマップは画像を共有する
// A table of loaded tilesets (path → tileset): maps with the same tileset share its image
using TilesetCache = std::unordered_map<std::string, std::shared_ptr<const Tileset>>;
} else if (command == "tileset") {
std::string file;
in >> file;
std::string tilesetPath = folderOf(path) + file;
if (cache && cache->contains(tilesetPath)) {
map.tiles = cache->at(tilesetPath);
continue;
}
std::optional<Tileset> set = Tileset::load(tilesetPath);
if (!set) return fail("タイルセットを読めない / cannot load the tileset " + file);
map.tiles = std::make_shared<const Tileset>(std::move(*set));
if (cache) (*cache)[tilesetPath] = map.tiles;
The key is the path as the map file builds it (games/rpg/assets/maps/../tiles.tileset, the same string for all three maps), and the value is the shared_ptr that chapter 33 already used for Tilemap::tiles.
So the three maps share one Tileset object and one texture, and that texture lives as long as any map uses it.
R re-reads the tileset and the atlas too, and that is why reload re-reads every loaded map, not only the current one.
A map's grid holds indices into its tileset's kinds, so the maps and their tileset have to change together: a map that kept the old tileset after an edit would show the old tiles until it is reloaded itself, and the old atlas would stay in memory next to the new one for as long as that map exists.
So reload builds a new cache, loads the current map first (its errors are the ones you are looking for) and then the others with it, and only when all of them have loaded moves them into their objects and replaces the cache, which frees the old tileset and its texture.
One bad file anywhere and nothing changes.
Re-reading three small text files costs nothing; a game with many maps would reload only the maps that use the edited tileset.
Lifetimes and the GL context. The tilesets own textures, so World owns GL objects, and every GL object must be deleted while the context still exists.
main declares World after the Window, so it is destroyed before it:
// マップは使うときにWorldが読む(最初の村だけ、ここで読めるか確かめる) / World loads maps when they are first
// needed (only the first one, the village, is checked here)
World world;
if (!batch || !tiles || !ui || !pixel || !characters || !world.map("village")) return 1;
world.map("village") checks the first map at start-up, where an error should stop the program; every other map is checked by its door.
34.6 What is kept, and what is reset
Now the question from the introduction.
A new MapScene is created for every visit and destroyed when you leave, so everything inside it starts over each time.
That gives a simple rule:
- Anything that must survive leaving a map lives in
World(and the debug toggles inGame::debug). - Anything in the scene is transient: each visit starts exactly as the map file says.
So far World keeps three things: the map cache, the flags and the gold.
A flag is just a string in a set; flag(name) asks whether it's there, setFlag(name) adds it.
A chest's flag is "<map>/<chest name>", built in setUp (village/village_chest), so two maps can both have a chest called chest without sharing its state.
Opening a chest stores its state in World; only the floating "+N G" text goes into the scene:
void MapScene::interact() {
Rect probe = facingProbe();
for (const Chest &c : chests) {
if (!overlaps(probe, c.box) || g.world.flag(c.flag)) continue;
g.world.setFlag(c.flag); // マップを出ても開いたまま / stays open after leaving the map
int gold = c.object->getInt("gold", 0);
g.world.gold += gold;
popups.push_back({"+" + std::to_string(gold) + " G", {c.box.centre().x, c.box.y - 10.0f}, 1.2f});
printf("%s: 開けた / opened (+%d G, %d G)\n", c.flag.c_str(), gold, g.world.gold);
return;
}
}
and drawing a chest asks World which sprite to use:
auto drawCharacters = [&] {
// 人物と、背の低い物(宝箱)を足元のyの順に / characters and low objects (chests) sorted by the y of their feet
b.begin(vp, SpriteSort::Layer);
for (const Chest &c : chests) {
Sprite s = tileSheet.sprite(tileSheet.find(g.world.flag(c.flag) ? "chest_open" : "chest_closed"),
c.object->rect.position());
s.layer = c.box.bottom();
b.draw(s);
}
b.draw(hero.sprite(g.characters, alpha));
b.end();
spriteCalls += b.stats().drawCalls;
};
The Chest list itself is rebuilt from the map's objects on every visit, so it carries no state of its own; whether a chest is open is never stored in the scene.
Here is the village chest before the trip and after the field and back:
And this is what resets: the hero is at the spawn point of the door you came through, not where they were standing when they last left; the "+30 G" popup is gone; the title banner shows again; the water animation starts over.
In chapter 35 the villagers will join that list and be back at their places when you return.
None of that needed code: it's simply what happens to a fresh object.
Challenge 3 moves the chest flags into the scene to see the opposite: every chest refills whenever you come back.
Chapter 35 also lets any map object depend on a flag, so the same mechanism can make a gate disappear for good once it's been opened.
The pitfall: debug toggles
While this chapter was being built, the first version kept the debug toggles (B, Z, H and the layer keys) in MapScene, as chapter 33 did.
Turning the HUD off with H worked in the village and the HUD came back as soon as the hero entered the house, because the house is a new scene.
It's the same question as the chests, found the practical way, and it has the same answer: the toggles moved to Game, which lives as long as the program:
// デバッグ表示の切り替え:シーンはマップごとに作り直されるので、ここ(Game)に置く(シーンに置くと扉で元に戻る)
// Debug view toggles: scenes are recreated for every map, so they live here in Game (in a scene they would reset at
// every door)
struct DebugView {
bool boxes = false, zoomOut = false, hud = true;
std::array<bool, 8> layers = {true, true, true, true, true, true, true, true};
};
// ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference
struct Game {
Window &window;
Input &input;
GameLoop &loop;
SpriteBatch &batch;
TileRenderer &tiles; // GPUの物は一つを使い回す(マップが変わったらbuildし直す) / one set of GPU objects, rebuilt
// when the map changes
World &world; // マップの置き場と、残る状態 / the loaded maps and the persistent state
const Font &ui; // mono16:画面の解像度 / screen resolution
const Font &pixel; // pixel12:キャンバスの中 / inside the canvas
const CharacterSheet &characters;
Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI
Viewport uiViewport;
DebugView debug;
};
Game is the bag of shared things every scene gets by reference (chapter 26's pattern): engine objects, the one TileRenderer, the World and DebugView.
The difference between Game and World is one of meaning: World is the game's state, the kind of thing a save file would write; Game::debug is a developer convenience that just shouldn't reset at a door.
34.7 Checking what's in front of you
To open a chest, the hero must face it.
Movement uses the foot box; interaction uses a second, small box in front of it, the probe:
// 顔の前の小さな箱:これに触れる物を調べる / a small box in front of the face: things touching it can be checked
Rect MapScene::facingProbe() const {
const Rect &b = hero.box;
constexpr float r = 8.0f;
switch (hero.facing) {
case Facing::Down: return {b.x, b.bottom(), b.w, r};
case Facing::Up: return {b.x, b.y - r, b.w, r};
case Facing::Left: return {b.x - r, b.y - 2.0f, r, b.h + 4.0f};
case Facing::Right: return {b.right(), b.y - 2.0f, r, b.h + 4.0f};
}
return b;
}
The probe reaches 8 px from the foot box's edge in the facing direction.
Sideways probes are 4 px taller than the 6 px foot box (2 px above and below it), so a chest is still found when the hero stands a few pixels higher or lower than it.
B draws the probe in yellow, as in the debug view at the start of the chapter.
Pressing the "confirm" action calls interact(), which opens the first closed chest that overlaps the probe; the action is bound in main next to chapter 33's movement actions:
input.bind("confirm", {InputBinding::key(GLFW_KEY_SPACE), InputBinding::key(GLFW_KEY_ENTER)});
Chests are also solid: their boxes are passed to moveOnMap as the extra list (blockers), so the hero slides around them like around a barrel.
And they are drawn in the same y-sorted batch as the hero with layer = box bottom, so the hero is drawn behind a chest when standing above it and in front of it when standing below it.
34.8 The banner and the gold counter
Both are drawn into the canvas with pixel12, in a batch of their own that uses Camera2D::screen(kView), so they stay put while the world camera scrolls:
// キャンバスの画面に固定の物:マップの名前、お金 / things fixed to the canvas screen: the map's name, the money
Camera2D canvas = Camera2D::screen(kView);
b.begin(canvas.matrix());
float banner = std::clamp((kBannerTime - time) / 0.5f, 0.0f, 1.0f);
if (banner > 0.0f) {
Vec2 size = g.pixel.measure(map->title());
Rect box = Rect::fromCentre({160.0f, 30.0f}, {size.x + 16.0f, size.y + 6.0f});
b.drawRect(box, {0.106f, 0.09f, 0.15f, 0.85f * banner});
b.drawRectOutline(box, {0.95f, 0.76f, 0.31f, banner});
g.pixel.draw(b, map->title(), {160.0f, box.y + 3.0f}, {.color = {1.0f, 0.96f, 0.84f, banner}, .align = TextAlign::Centre});
}
char gold[32];
snprintf(gold, sizeof gold, "%d G", g.world.gold);
g.pixel.draw(b, gold, {314.0f, 160.0f}, {.color = hexColor(0xf2c14eff), .align = TextAlign::Right, .shadow = hexColor(0x1b1726ff)});
b.end();
time is the scene's own clock, starting at 0 in every new scene, so the banner shows on every visit without any extra code: fully visible for 2.0 s, then (kBannerTime − time) / 0.5 fades it out over the last 0.5 s.
Because the scene already runs during the fade-in, the banner is there as soon as the new map appears.
It's also a good example of the reset rule: a "banner shown" flag in World would show each title only once per game, which is what some games do for a region's first visit.
34.9 Running it
Build as before and run from the project root:
./build/games/rpg/rpg
On Windows, Visual Studio runs build\games\rpg\Debug\rpg.exe with the project root as the working directory.
stdout traces every load, switch and chest.
This is the scripted tour of the clip, at 60 updates per second:
OpenGL 4.5 (Core Profile) Mesa 25.2.8-0ubuntu0.24.04.4 / llvmpipe (LLVM 20.1.2, 256 bits)
games/rpg/assets/maps/village.map: 読んだ / loaded (40×28)
games/rpg/assets/maps/home.map: 読んだ / loaded (12×10)
village → home (door)
home/home_chest: 開けた / opened (+50 G, 50 G)
home → village (home_door)
village/village_chest: 開けた / opened (+30 G, 80 G)
games/rpg/assets/maps/field.map: 読んだ / loaded (40×24)
village → field (west)
field/garden_chest: 開けた / opened (+100 G, 180 G)
field → village (east)
(The first line comes from the test harness's driver; yours names your GPU.)
Each map is loaded once, just before the first switch to it, and the second trip into the village loads nothing.
The HUD's last number, "maps", counts the cached maps: 1, then 2 in the house, then 3 in the field.
To see the error path, change the village door's map=home to map=nowhere and press R in the village.
Walking into the door now prints Tilemap::load's "cannot read" line for games/rpg/assets/maps/nowhere.map, followed by games/rpg/assets/maps/village.map: door home の先のマップ「nowhere」を読めない / cannot load map 'nowhere', and the hero stays in the village.
Change it back, press R again, and step off the door and back on: it works without restarting the game.
34.10 Platform notes
- Linux, FreeBSD: map names become file names, and these file systems are case-sensitive:
map=Homelooks forHome.mapand fails, while the same file works on Windows, whose file system ignores case. Keep map names lowercase, and test a map you made on Windows on Linux too before you ship it. - All: the paths use
/, which Windows accepts as well, and chapter 33's loader already strips the\rof Windows line endings, so map files edited in any editor work everywhere. - Windows (Visual Studio): the trace contains Japanese and
→; the console shows them correctly only in a UTF-8 code page (chcp 65001) or in Windows Terminal. The game itself is unaffected.
34.11 How real engines do it
- Unity:
SceneManager.LoadScenereplaces the current scene (ourreplace), whileLoadSceneMode.Additiveloads a scene next to the open ones, which is how large games keep a persistent "core" scene and stream levels in and out. Objects marked withDontDestroyOnLoad, or data kept in ScriptableObjects or plain static classes, play the part of ourWorld.LoadSceneAsyncloads during the fade so a big level doesn't stall the game. - Godot:
get_tree().change_scene_to_file()replaces the current scene; global state lives in autoloads (singleton nodes that are never freed), which is the same split asWorldandMapScene. - RPG Maker: a door is an event with a "Transfer Player" command that names the target map, position and fade (black, white or none). Global switches and variables are its
World, and each event has "self switches", which is exactly how a chest remembers it was opened. - Classic console RPGs: maps carry a table of warps with a target map and a target warp or position, and opening a chest sets a bit in the save data; our
door … map= spawn=lines and flag strings are a readable version of that. - Editors: Tiled's object layers with custom properties hold the same information as our
objectlines, and many engines read them directly. - Open worlds: instead of switching, they stream the neighboring chunks in the background and never fade (challenge 7 is a small version).
34.12 Summary
- Doors and edge exits are map objects (
door,warpwithmap=andspawn=), so new maps and connections need no code. A door tile is walkable (D); the solid eave above it stops the hero, and the overlap with the door object fires the switch. - One scene per map visit: a door calls
scenes().replace(std::make_unique<MapScene>(…), kMapFade)with a 0.6 s fade, 0.3 s out and 0.3 s in.pushwould pile up paused maps because our doors go both ways. - During the switch: nobody is updated during the fade-out, so the leaving scene freezes
previous = current; a request made during a fade-in waits, soleavingstops the scene from walking on and asking again. Doors arm only after the hero has stood on none of them once. enter()does the work: the constructor only stores names;enter()gets the map fromWorld, rebuilds the one static tile buffer (immutable storage can't be resized, so new buffers; same VAO, program and texture), places the hero and builds the chests.Worldloads maps on first use and caches them behindunique_ptrso their addresses never change (R reloads every loaded map and the tileset in place, all or nothing), and shares tilesets through aTilesetCacheofshared_ptrs. It is declared after theWindow, so its textures die before the context.- The rule: anything that must survive leaving a map lives in
World(flags, gold, the map cache) andGame::debug; anything in the scene is transient (hero position, popups, banner time, and the villagers in chapter 35). A chest's open state is the flag"<map>/<name>". - Interaction uses an 8 px probe in front of the foot box; chests are solid boxes drawn in the y-sorted batch. Map titles are shown for 2.5 s with a 0.5 s fade.
34.13 Challenges
- ★ Give the elder's house an interior: copy
home.maptoelder.map(change itsmapandtitlelines; the chest's flag becomeselder/home_chestby itself), turn the door at column 17, row 7 ofvillage.mapfromdintoD, and addobject door elder 17 7 map=elder spawn=doorandobject spawn elder_door 17 8 face=down; inelder.map, make the door lead tospawn=elder_door. Press R in the village and walk in: the new house should work without recompiling, and the HUD's map count should go up by one on the first visit. - ★ Change
kMapFadeto{.duration = 1.5f, .color = hexColor(0xffffffff)}. Doors should now fade slowly to white; for the 0.75 s of the fade-out the keys do nothing, and during the 0.75 s fade-in you can already walk. - ★ Make the chests refill: keep the opened chests in a
std::unordered_set<std::string>member ofMapSceneinstead ofWorld. A chest should open and pay out once per visit, and be closed again, with its gold, every time you come back;World::goldkeeps growing. - ★★ Save and load: on F5, write
World's flags and gold to a text file (oneflag <name>line per flag and agold <n>line); on F9, clear them, read the file back and callscenes().replaceAll(std::make_unique<MapScene>(g, "village", "start"), kMapFade). Open the house chest, press F5, open the village chest, press F9: you should be at the village's start point with 50 G, the house chest open and the village chest closed again. Nothing inMapSceneneeds saving, which is the point of the rule. - ★★ Use
pushandpopfor the house: the village's door pushes the interior withkMapFade, and the house's door callsscenes().pop(kMapFade). Back in the village the hero should be exactly where they stood before entering, still facing the door, but the village will be drawn with the house's tiles until you rebuild them inresume()(g.tiles.build(*map)).resume()must also setleaving = falseandwarpArmed = false: the village scene was frozen when its door fired, and the hero is still standing on that door. The scene'spause()already freezesprevious, so the village doesn't wobble during the fade. - ★★ Preload: keep one
TileRendererper cached map (for example in a map from name toTileRenderernext to the map cache) and build it once, when the map is first loaded, instead of in everyenter(). Switching should then do no buffer work at all; the price is memory for every map at once: 115 920 + 10 720 + 106 000 = 232 640 bytes of vertices for our three maps (plus their index buffers). - ★★★ Seamless edge exits: when the hero reaches the village's east exit, draw the field to the right of the village (offset by the village's width, 640 px) and scroll the camera across without a fade, switching scenes only when the camera has fully moved. The world should feel continuous, like the overworld screens of a classic Zelda. You'll need two tile buffers at once, a camera that isn't clamped to one map, and collision against the field while the hero is still in the village's scene.
ファイル: a/games/rpg/CMakeLists.txt | b/games/rpg/CMakeLists.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -4,7 +4,8 @@ add_executable(rpg | |||
| 4 | src/tilemap.cc | 4 | src/tilemap.cc |
| 5 | src/tile_renderer.cc | 5 | src/tile_renderer.cc |
| 6 | src/character.cc | 6 | src/character.cc |
| 7 | src/map_scene.cc) | 7 | src/map_scene.cc |
| 8 | src/world.cc) | ||
| 8 | target_include_directories(rpg PRIVATE src) | 9 | target_include_directories(rpg PRIVATE src) |
| 9 | target_link_libraries(rpg PRIVATE engine) | 10 | target_link_libraries(rpg PRIVATE engine) |
| 10 | enable_warnings(rpg) | 11 | enable_warnings(rpg) |
ファイル: a/games/rpg/README.md | b/games/rpg/README.md
| 前 | 新 | ||
|---|---|---|---|
| @@ -10,6 +10,7 @@ | |||
| 10 | |---|---| | 10 | |---|---| |
| 11 | | 矢印 / WASD | 移動 / move | | 11 | | 矢印 / WASD | 移動 / move | |
| 12 | | Shift | 走る / run | | 12 | | Shift | 走る / run | |
| 13 | | Space / Enter | 調べる(宝箱) / check (chests) | | ||
| 13 | | 1 2 3 | 層の表示(地面・飾り・上の層) / toggle the layers (ground, decor, overlay) | | 14 | | 1 2 3 | 層の表示(地面・飾り・上の層) / toggle the layers (ground, decor, overlay) | |
| 14 | | B | 当たり判定の箱 / collision boxes | | 15 | | B | 当たり判定の箱 / collision boxes | |
| 15 | | Z | 引いて見る(行のカリングが見える) / zoom out (shows the row culling) | | 16 | | Z | 引いて見る(行のカリングが見える) / zoom out (shows the row culling) | |
| @@ -18,5 +19,7 @@ | |||
| 18 | | Esc | 終了 / quit | | 19 | | Esc | 終了 / quit | |
| 19 | 20 | ||
| 20 | マップは `assets/maps/*.map`(テキスト)。書式は `src/tilemap.hh`、タイルの文字は `assets/tiles.tileset`。 | 21 | マップは `assets/maps/*.map`(テキスト)。書式は `src/tilemap.hh`、タイルの文字は `assets/tiles.tileset`。 |
| 22 | 扉は `object door <名前> <列> <行> map=<マップ> spawn=<出発点>`、マップの端の出口は `object warp … h=2 …`。 | ||
| 21 | Maps are `assets/maps/*.map` (text). The format is described in `src/tilemap.hh`, the tile characters in | 23 | Maps are `assets/maps/*.map` (text). The format is described in `src/tilemap.hh`, the tile characters in |
| 22 | `assets/tiles.tileset`. | 24 | `assets/tiles.tileset`. Doors are `object door <name> <col> <row> map=<map> spawn=<spawn point>`, exits at the edge of |
| 25 | a map `object warp ... h=2 ...`. | ||
ファイル: a/games/rpg/assets/LICENSE.txt | b/games/rpg/assets/LICENSE.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -6,4 +6,6 @@ tiles.png/.atlas 16×16のタイル(草・道・水・木・家・家具 | |||
| 6 | characters.png 人物5人 × 4方向の歩き(16×16、9コマずつ) / five characters × 4-direction walk (16×16, 9 frames | 6 | characters.png 人物5人 × 4方向の歩き(16×16、9コマずつ) / five characters × 4-direction walk (16×16, 9 frames |
| 7 | each) (chapter 33) | 7 | each) (chapter 33) |
| 8 | tiles.tileset タイルの文字・固さ・動き(手書き) / tile characters, solidity, animation (hand-written, chapter 33) | 8 | tiles.tileset タイルの文字・固さ・動き(手書き) / tile characters, solidity, animation (hand-written, chapter 33) |
| 9 | maps/village.map 村のマップ / the village map (chapter 33; edit by hand freely) | 9 | maps/village.map 村のマップ / the village map (chapters 33-34; edit by hand freely) |
| 10 | maps/home.map 家の中 / the house interior (chapter 34) | ||
| 11 | maps/field.map 野原 / the field (chapter 34) | ||
ファイル: /dev/null | b/games/rpg/assets/maps/field.map
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,91 @@ | |||
| 1 | # のはら / Field | ||
| 2 | # 書式は games/rpg/src/tilemap.hh、文字の意味は ../tiles.tileset / format: games/rpg/src/tilemap.hh, | ||
| 3 | # characters: ../tiles.tileset ('.' = 空 / empty) | ||
| 4 | map field | ||
| 5 | title のはら / Field | ||
| 6 | tileset ../tiles.tileset | ||
| 7 | size 40 24 | ||
| 8 | |||
| 9 | layer ground | ||
| 10 | ,,,,,,,,,;,;,,,,;;,,,,,,,,,,,,,,,,,,,,,; | ||
| 11 | ,,,,,,,;,,,,;,,,;,;,,,,,,,,,,,;,,,,,,,,, | ||
| 12 | ,,,;,,,,,,,,,;,,,,,;,,,,,,,,,,,,,,,,;,,, | ||
| 13 | ,,,,,,,,,,;,,,,,,,,,,,,,,,,,,,,;,;,;;;,, | ||
| 14 | ,,,,,,;,;,,,,;,,,,,,;,;,;,,;;;;;;;;,,;,, | ||
| 15 | ,,,,;,,,,,,,,,;,,,,;,,;,,;,;;;;;;;;,,,,; | ||
| 16 | ,;,,,;;,,,;,,,,;,,;,;,,,;,,;;;;;;;;,,,,, | ||
| 17 | ,,,,,,,,,,,;;,,,;,,,;,,,;;,;;;;;;;;,,,,; | ||
| 18 | ;,,,,,,;,,,;,,,,,,,,,,,,,,,;;;;;;;;,,;;, | ||
| 19 | ,,,,,;,,,;,,,,,;,,,,,,,,,,,,,,==;,,,,,;, | ||
| 20 | ==:===========:==============::=,;,,,,,, | ||
| 21 | ====================:===========,,,,,,,, | ||
| 22 | ;,,;,,;,,,,,,,,,,,,,;;;,,,,,,,;,,,,,,,,; | ||
| 23 | ,,;;,;;,,,,,,;,,,,,,,,,;,;,,,;,,,,,,,;,, | ||
| 24 | ,,,,,,,,,,,,;,,,,,;,,,;,;,;,,,;,,,,,,,,, | ||
| 25 | ,,,,,,,,,,;;,,,,,,,,,,,,;,,,,,,,;;,,,,,, | ||
| 26 | ,,,;,,,;,,,,,,,;,^^^^^,,,,,,,;;,,;,,;,;, | ||
| 27 | ,,,;,,;,,,;,,,,,,~~~~~;,,,,,,;,,,,,,,,;, | ||
| 28 | ,,,,;,;,,;,,,,,;,~~~~~,,,,,;,,,,,,;,,,;, | ||
| 29 | ,,;,,,,,;,,,,,,,,~~~~~,,,,,,;,,;,,;;,,,; | ||
| 30 | ;,,,,,,,,;,;,;,,,,,,;,;;,,,,,,,,,,,,;,;, | ||
| 31 | ;,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, | ||
| 32 | ,,;,,;,,,,;;;,,,,,,,;,,,,;,,,,,,,,;;,,,; | ||
| 33 | ;,,,,,,,;,,,,,,,,,,;,,,,,,,,,,,,,,,,,;,, | ||
| 34 | |||
| 35 | layer decor | ||
| 36 | ........................................ | ||
| 37 | TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT | ||
| 38 | b......................................b | ||
| 39 | T.............T...........----------...T | ||
| 40 | b.."""""..T.........T.....|.....s..|...b | ||
| 41 | T.."""""..........*.......|.*......|...T | ||
| 42 | b.."""""..................|........|...b | ||
| 43 | T.........................|.%....*.|...T | ||
| 44 | b....b..........b.........|........|...b | ||
| 45 | b.....T............R......----..----..bT | ||
| 46 | .......................................b | ||
| 47 | ................"""""".........*.......T | ||
| 48 | b......*.R......"""""".....R...........b | ||
| 49 | T............S..""""""R.T........T..T..T | ||
| 50 | b..."""""""...*..........*...b.........b | ||
| 51 | T..."""""""............................T | ||
| 52 | b...""""""".............""""""""....*..b | ||
| 53 | T...""""""".R..........."""""""".......T | ||
| 54 | b......................."""""""".....T.b | ||
| 55 | T......................."""""""".......T | ||
| 56 | b.......T.........................R....b | ||
| 57 | T..T...........T.....b..T..............T | ||
| 58 | b......................................b | ||
| 59 | TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT | ||
| 60 | |||
| 61 | layer overlay above | ||
| 62 | tttttttttttttttttttttttttttttttttttttttt | ||
| 63 | ........................................ | ||
| 64 | t.............t........................t | ||
| 65 | ..........t.........t................... | ||
| 66 | t......................................t | ||
| 67 | ........................................ | ||
| 68 | t......................................t | ||
| 69 | ........................................ | ||
| 70 | ......t................................t | ||
| 71 | ........................................ | ||
| 72 | .......................................t | ||
| 73 | ........................................ | ||
| 74 | t.......................t........t..t..t | ||
| 75 | ........................................ | ||
| 76 | t......................................t | ||
| 77 | ........................................ | ||
| 78 | t......................................t | ||
| 79 | .....................................t.. | ||
| 80 | t......................................t | ||
| 81 | ........t............................... | ||
| 82 | t..t...........t........t..............t | ||
| 83 | ........................................ | ||
| 84 | tttttttttttttttttttttttttttttttttttttttt | ||
| 85 | ........................................ | ||
| 86 | |||
| 87 | # 物:object <種類> <名前> <列> <行> [key=value …] / objects: kind name col row [key=value ...] | ||
| 88 | object spawn start 1 10 face=right | ||
| 89 | object spawn west 1 10 face=right | ||
| 90 | object warp west 0 10 h=2 map=village spawn=east | ||
| 91 | object chest garden_chest 30 5 gold=100 | ||
ファイル: /dev/null | b/games/rpg/assets/maps/home.map
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,49 @@ | |||
| 1 | # 家 / Home | ||
| 2 | # 書式は games/rpg/src/tilemap.hh、文字の意味は ../tiles.tileset / format: games/rpg/src/tilemap.hh, | ||
| 3 | # characters: ../tiles.tileset ('.' = 空 / empty) | ||
| 4 | map home | ||
| 5 | title 家 / Home | ||
| 6 | tileset ../tiles.tileset | ||
| 7 | size 12 10 | ||
| 8 | |||
| 9 | layer ground | ||
| 10 | xxxxxxxxxxxx | ||
| 11 | xwwwnwwnwwwx | ||
| 12 | x__________x | ||
| 13 | x__________x | ||
| 14 | x___rrrr___x | ||
| 15 | x___rrrr___x | ||
| 16 | x___rrrr___x | ||
| 17 | x__________x | ||
| 18 | x____m_____x | ||
| 19 | xxxxx_xxxxxx | ||
| 20 | |||
| 21 | layer decor | ||
| 22 | ............ | ||
| 23 | ..KK.....F.. | ||
| 24 | .B........p. | ||
| 25 | .E........p. | ||
| 26 | ............ | ||
| 27 | ....cQQc.... | ||
| 28 | ............ | ||
| 29 | .P........U. | ||
| 30 | ..........X. | ||
| 31 | ............ | ||
| 32 | |||
| 33 | layer overlay above | ||
| 34 | ............ | ||
| 35 | ............ | ||
| 36 | ............ | ||
| 37 | ............ | ||
| 38 | ............ | ||
| 39 | ............ | ||
| 40 | ............ | ||
| 41 | ............ | ||
| 42 | ............ | ||
| 43 | ............ | ||
| 44 | |||
| 45 | # 物:object <種類> <名前> <列> <行> [key=value …] / objects: kind name col row [key=value ...] | ||
| 46 | object spawn start 5 7 face=up | ||
| 47 | object spawn door 5 8 face=up | ||
| 48 | object door out 5 9 map=village spawn=home_door | ||
| 49 | object chest home_chest 8 2 gold=50 | ||
ファイル: a/games/rpg/assets/maps/village.map | b/games/rpg/assets/maps/village.map
| 前 | 新 | ||
|---|---|---|---|
| @@ -2,6 +2,7 @@ | |||
| 2 | # 書式は games/rpg/src/tilemap.hh、文字の意味は ../tiles.tileset / format: games/rpg/src/tilemap.hh, | 2 | # 書式は games/rpg/src/tilemap.hh、文字の意味は ../tiles.tileset / format: games/rpg/src/tilemap.hh, |
| 3 | # characters: ../tiles.tileset ('.' = 空 / empty) | 3 | # characters: ../tiles.tileset ('.' = 空 / empty) |
| 4 | map village | 4 | map village |
| 5 | title 村 / Village | ||
| 5 | tileset ../tiles.tileset | 6 | tileset ../tiles.tileset |
| 6 | size 40 28 | 7 | size 40 28 |
| 7 | 8 | ||
| @@ -43,7 +44,7 @@ T...........s.........b............b...T | |||
| 43 | b......................................b | 44 | b......................................b |
| 44 | T.............AAAAAAA..................T | 45 | T.............AAAAAAA..................T |
| 45 | b.b..LLLLL....LLLLLLL...s....LLLLLX....b | 46 | b.b..LLLLL....LLLLLLL...s....LLLLLX....b |
| 46 | T...UMWdWMX..SMWMdMWM......bXMWdWMU..%.T | 47 | T...UMWDWMX..SMWMdMWM......bXMWdWMU..%.T |
| 47 | b..........*...........*...............b | 48 | b..........*...........*...............b |
| 48 | T..%...................................b | 49 | T..%...................................b |
| 49 | b....................................... | 50 | b....................................... |
| @@ -97,3 +98,8 @@ tttttttttttttttttttttttttttttttttttttttt | |||
| 97 | 98 | ||
| 98 | # 物:object <種類> <名前> <列> <行> [key=value …] / objects: kind name col row [key=value ...] | 99 | # 物:object <種類> <名前> <列> <行> [key=value …] / objects: kind name col row [key=value ...] |
| 99 | object spawn start 7 9 face=down | 100 | object spawn start 7 9 face=down |
| 101 | object door home 7 7 map=home spawn=door | ||
| 102 | object warp east 39 10 h=2 map=field spawn=west | ||
| 103 | object spawn home_door 7 8 face=down | ||
| 104 | object spawn east 38 10 face=left | ||
| 105 | object chest village_chest 21 8 gold=30 | ||
ファイル: a/games/rpg/src/game.hh | b/games/rpg/src/game.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -5,6 +5,7 @@ | |||
| 5 | #include "character.hh" | 5 | #include "character.hh" |
| 6 | #include "tile_renderer.hh" | 6 | #include "tile_renderer.hh" |
| 7 | #include "tilemap.hh" | 7 | #include "tilemap.hh" |
| 8 | #include "world.hh" | ||
| 8 | 9 | ||
| 9 | #include "engine/camera2d.hh" | 10 | #include "engine/camera2d.hh" |
| 10 | #include "engine/font.hh" | 11 | #include "engine/font.hh" |
| @@ -15,11 +16,22 @@ | |||
| 15 | 16 | ||
| 16 | #include <array> | 17 | #include <array> |
| 17 | #include <optional> | 18 | #include <optional> |
| 19 | #include <string> | ||
| 18 | #include <vector> | 20 | #include <vector> |
| 19 | 21 | ||
| 20 | // 仮想解像度:320 × 180(1280 × 720の4倍)、タイル16 × 16で20 × 11.25マスが見える | 22 | // 仮想解像度:320 × 180(1280 × 720の4倍)、タイル16 × 16で20 × 11.25マスが見える |
| 21 | // The virtual resolution: 320 × 180 (× 4 = 1280 × 720); with 16 × 16 tiles, 20 × 11.25 tiles are visible | 23 | // The virtual resolution: 320 × 180 (× 4 = 1280 × 720); with 16 × 16 tiles, 20 × 11.25 tiles are visible |
| 22 | constexpr Vec2 kView = {320.0f, 180.0f}; | 24 | constexpr Vec2 kView = {320.0f, 180.0f}; |
| 25 | // マップを移るときのフェード(暗くなるのに半分、明るくなるのに半分) / the fade between maps (half to black, half back) | ||
| 26 | constexpr Transition kMapFade = {.duration = 0.6f, .color = {0.0f, 0.0f, 0.0f, 1.0f}}; | ||
| 27 | |||
| 28 | // デバッグ表示の切り替え:シーンはマップごとに作り直されるので、ここ(Game)に置く(シーンに置くと扉で元に戻る) | ||
| 29 | // Debug view toggles: scenes are recreated for every map, so they live here in Game (in a scene they would reset at | ||
| 30 | // every door) | ||
| 31 | struct DebugView { | ||
| 32 | bool boxes = false, zoomOut = false, hud = true; | ||
| 33 | std::array<bool, 8> layers = {true, true, true, true, true, true, true, true}; | ||
| 34 | }; | ||
| 23 | 35 | ||
| 24 | // ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference | 36 | // ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference |
| 25 | struct Game { | 37 | struct Game { |
| @@ -29,17 +41,22 @@ struct Game { | |||
| 29 | SpriteBatch &batch; | 41 | SpriteBatch &batch; |
| 30 | TileRenderer &tiles; // GPUの物は一つを使い回す(マップが変わったらbuildし直す) / one set of GPU objects, rebuilt | 42 | TileRenderer &tiles; // GPUの物は一つを使い回す(マップが変わったらbuildし直す) / one set of GPU objects, rebuilt |
| 31 | // when the map changes | 43 | // when the map changes |
| 44 | World &world; // マップの置き場と、残る状態 / the loaded maps and the persistent state | ||
| 32 | const Font &ui; // mono16:画面の解像度 / screen resolution | 45 | const Font &ui; // mono16:画面の解像度 / screen resolution |
| 33 | const Font &pixel; // pixel12:キャンバスの中 / inside the canvas | 46 | const Font &pixel; // pixel12:キャンバスの中 / inside the canvas |
| 34 | const CharacterSheet &characters; | 47 | const CharacterSheet &characters; |
| 35 | Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI | 48 | Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI |
| 36 | Viewport uiViewport; | 49 | Viewport uiViewport; |
| 50 | DebugView debug; | ||
| 37 | }; | 51 | }; |
| 38 | 52 | ||
| 39 | // マップの上を歩くシーン / the scene where you walk around a map | 53 | // マップの上を歩くシーン。マップ1つにつき1つ作り、扉で次のマップのシーンに入れ替える |
| 54 | // The scene where you walk around a map. One per map; a door replaces it with the next map's scene | ||
| 40 | class MapScene : public Scene { | 55 | class MapScene : public Scene { |
| 41 | public: | 56 | public: |
| 42 | MapScene(Game &game, Tilemap map); | 57 | // mapName = World::mapの名前、spawn = 出発点の物の名前(spawn <名前>) / mapName = the name for World::map, spawn = |
| 58 | // the name of a spawn object | ||
| 59 | MapScene(Game &game, std::string mapName, std::string spawn); | ||
| 43 | void enter() override; | 60 | void enter() override; |
| 44 | void pause() override; | 61 | void pause() override; |
| 45 | void update(float dt) override; | 62 | void update(float dt) override; |
| @@ -47,19 +64,35 @@ public: | |||
| 47 | void drawUi(float alpha) override; | 64 | void drawUi(float alpha) override; |
| 48 | 65 | ||
| 49 | private: | 66 | private: |
| 50 | void spawn(); | 67 | // 宝箱:開いたかどうかはWorldの印(マップ名/宝箱名)に残る / a chest: whether it is open is a World flag |
| 51 | // カメラ:主人公の足元を追い、マップの端で止める(マップが画面より小さければ真ん中に) | 68 | // (map name/chest name) |
| 52 | // The camera: follows the hero's feet and stops at the map's edges (centered when the map is smaller than the view) | 69 | struct Chest { |
| 70 | const MapObject *object; | ||
| 71 | Rect box; | ||
| 72 | std::string flag; | ||
| 73 | }; | ||
| 74 | struct Popup { | ||
| 75 | std::string text; | ||
| 76 | Vec2 position; | ||
| 77 | float life; | ||
| 78 | }; | ||
| 79 | void setUp(); // マップの物からシーンの物を作る / builds the scene's things from the map's objects | ||
| 80 | void interact(); | ||
| 81 | void checkWarps(); | ||
| 82 | Rect facingProbe() const; | ||
| 53 | Camera2D followCamera(Vec2 target) const; | 83 | Camera2D followCamera(Vec2 target) const; |
| 54 | 84 | ||
| 55 | Game &g; | 85 | Game &g; |
| 56 | Tilemap map; | 86 | std::string mapName, spawnName; |
| 87 | Tilemap *map = nullptr; // Worldの中(読み直しても同じ場所) / inside World (same address across reloads) | ||
| 57 | Character hero; | 88 | Character hero; |
| 58 | std::vector<Rect> scratch; // 当たり判定の箱の作業用(毎ステップ作り直さない) / scratch boxes for collision (kept | 89 | std::vector<Chest> chests; |
| 59 | // between steps to avoid allocations) | 90 | std::vector<Rect> blockers; // 固い物(宝箱)の箱 / boxes of solid objects (chests) |
| 91 | std::vector<Popup> popups; | ||
| 92 | std::vector<Rect> scratch; // 当たり判定の箱の作業用 / scratch boxes for collision | ||
| 60 | float time = 0.0f; | 93 | float time = 0.0f; |
| 61 | bool showBoxes = false, zoomOut = false, showHud = true; | 94 | bool warpArmed = false; // 出発点が扉の上でも、一度離れるまで扉は効かない / doors only work after the hero has |
| 62 | std::array<bool, 8> layerOn; | 95 | // stepped off all of them once (in case a spawn point is on a door) |
| 63 | // HUD用:前のフレームの描画の数 / for the HUD: last frame's drawing counts | 96 | bool leaving = false; // 扉に入った:フェードが終わるまで動かない / entered a door: frozen until the fade ends |
| 64 | int rowFirst = 0, rowLast = 0, spriteCalls = 0; | 97 | int rowFirst = 0, rowLast = 0, spriteCalls = 0; |
| 65 | }; | 98 | }; |
ファイル: a/games/rpg/src/main.cc | b/games/rpg/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,8 +1,8 @@ | |||
| 1 | // 第33章:見下ろし型RPG(1)タイルマップ、当たり判定のある移動、追いかけるカメラ | 1 | // 第34章:見下ろし型RPG(2)いくつものマップ、扉と出口、フェードでのシーンの切り替え、ファイルからのマップ |
| 2 | // Chapter 33: a top-down RPG (1) tile maps, movement with collision, a following camera | 2 | // Chapter 34: a top-down RPG (2) several maps, doors and exits, scene switching with fades, maps loaded from files |
| 3 | // | 3 | // |
| 4 | // 操作 / Controls: | 4 | // 操作 / Controls: |
| 5 | // 矢印 / WASD 移動 / move Shift 走る / run | 5 | // 矢印 / WASD 移動 / move Shift 走る / run Space / Enter 調べる(宝箱) / check (chests) |
| 6 | // 1 2 3 層の表示 / toggle layers (ground, decor, overlay) | 6 | // 1 2 3 層の表示 / toggle layers (ground, decor, overlay) |
| 7 | // B 当たり判定の箱 / collision boxes Z 引いて見る(カリングの確認) / zoom out (shows culling) | 7 | // B 当たり判定の箱 / collision boxes Z 引いて見る(カリングの確認) / zoom out (shows culling) |
| 8 | // H HUDの表示 / toggle the HUD | 8 | // H HUDの表示 / toggle the HUD |
| @@ -27,8 +27,10 @@ int main() { | |||
| 27 | std::optional<Font> ui = Font::load("assets/fonts/mono16.fnt"); | 27 | std::optional<Font> ui = Font::load("assets/fonts/mono16.fnt"); |
| 28 | std::optional<Font> pixel = Font::load("assets/fonts/pixel12.fnt", TextureFilter::Nearest); | 28 | std::optional<Font> pixel = Font::load("assets/fonts/pixel12.fnt", TextureFilter::Nearest); |
| 29 | std::optional<CharacterSheet> characters = CharacterSheet::load("games/rpg/assets/characters.png"); | 29 | std::optional<CharacterSheet> characters = CharacterSheet::load("games/rpg/assets/characters.png"); |
| 30 | std::optional<Tilemap> village = Tilemap::load("games/rpg/assets/maps/village.map"); | 30 | // マップは使うときにWorldが読む(最初の村だけ、ここで読めるか確かめる) / World loads maps when they are first |
| 31 | if (!batch || !tiles || !ui || !pixel || !characters || !village) return 1; | 31 | // needed (only the first one, the village, is checked here) |
| 32 | World world; | ||
| 33 | if (!batch || !tiles || !ui || !pixel || !characters || !world.map("village")) return 1; | ||
| 32 | 34 | ||
| 33 | Input input; | 35 | Input input; |
| 34 | input.attach(window); | 36 | input.attach(window); |
| @@ -37,15 +39,18 @@ int main() { | |||
| 37 | input.bind("up", {InputBinding::key(GLFW_KEY_UP), InputBinding::key(GLFW_KEY_W)}); | 39 | input.bind("up", {InputBinding::key(GLFW_KEY_UP), InputBinding::key(GLFW_KEY_W)}); |
| 38 | input.bind("down", {InputBinding::key(GLFW_KEY_DOWN), InputBinding::key(GLFW_KEY_S)}); | 40 | input.bind("down", {InputBinding::key(GLFW_KEY_DOWN), InputBinding::key(GLFW_KEY_S)}); |
| 39 | input.bind("run", {InputBinding::key(GLFW_KEY_LEFT_SHIFT), InputBinding::key(GLFW_KEY_RIGHT_SHIFT)}); | 41 | input.bind("run", {InputBinding::key(GLFW_KEY_LEFT_SHIFT), InputBinding::key(GLFW_KEY_RIGHT_SHIFT)}); |
| 42 | input.bind("confirm", {InputBinding::key(GLFW_KEY_SPACE), InputBinding::key(GLFW_KEY_ENTER)}); | ||
| 40 | 43 | ||
| 41 | GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); | 44 | GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); |
| 42 | PixelCanvas canvas(static_cast<int>(kView.x), static_cast<int>(kView.y)); | 45 | PixelCanvas canvas(static_cast<int>(kView.x), static_cast<int>(kView.y)); |
| 43 | Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .tiles = *tiles, .ui = *ui, | 46 | Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .tiles = *tiles, .world = world, .ui = *ui, |
| 44 | .pixel = *pixel, .characters = *characters, .screen = Camera2D::screen({1280.0f, 720.0f}), | 47 | .pixel = *pixel, .characters = *characters, .screen = Camera2D::screen({1280.0f, 720.0f}), |
| 45 | .uiViewport = {}}; | 48 | .uiViewport = {}, .debug = {}}; |
| 46 | 49 | ||
| 47 | SceneManager scenes; | 50 | SceneManager scenes; |
| 48 | scenes.push(std::make_unique<MapScene>(game, std::move(*village))); | 51 | // 黒から明るくなって始まる(空のスタックへのpushもフェードできる) / starts by fading in from black (a push onto the |
| 52 | // empty stack can fade too) | ||
| 53 | scenes.push(std::make_unique<MapScene>(game, "village", "start"), kMapFade); | ||
| 49 | 54 | ||
| 50 | loop.run( | 55 | loop.run( |
| 51 | window, input, | 56 | window, input, |
ファイル: a/games/rpg/src/map_scene.cc | b/games/rpg/src/map_scene.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -1,5 +1,6 @@ | |||
| 1 | // マップのシーン:主人公を歩かせ、カメラで追い、層の順にタイルと人物を描く | 1 | // マップのシーン:主人公を歩かせ、カメラで追い、層の順にタイルと人物を描く。扉で別のマップへ(フェード付き) |
| 2 | // The map scene: walks the hero around, follows it with the camera, draws tiles and characters in layer order | 2 | // The map scene: walks the hero around, follows it with the camera, draws tiles and characters in layer order. Doors |
| 3 | // lead to other maps (with a fade) | ||
| 3 | #include "game.hh" | 4 | #include "game.hh" |
| 4 | 5 | ||
| 5 | #include "engine/collision.hh" | 6 | #include "engine/collision.hh" |
| @@ -7,50 +8,132 @@ | |||
| 7 | #include <algorithm> | 8 | #include <algorithm> |
| 8 | #include <cmath> | 9 | #include <cmath> |
| 9 | #include <cstdio> | 10 | #include <cstdio> |
| 11 | #include <memory> | ||
| 10 | 12 | ||
| 11 | constexpr float kWalkSpeed = 72.0f; // ピクセル毎秒(4.5マス/秒) / pixels per second (4.5 tiles/s) | 13 | constexpr float kWalkSpeed = 72.0f; // ピクセル毎秒(4.5マス/秒) / pixels per second (4.5 tiles/s) |
| 12 | constexpr float kRunSpeed = 120.0f; | 14 | constexpr float kRunSpeed = 120.0f; |
| 15 | constexpr float kBannerTime = 2.5f; // マップの名前を出す秒数 / seconds the map's name is shown | ||
| 13 | 16 | ||
| 14 | MapScene::MapScene(Game &game, Tilemap tilemap) : g(game), map(std::move(tilemap)) { layerOn.fill(true); } | 17 | MapScene::MapScene(Game &game, std::string name, std::string spawn) |
| 18 | : g(game), mapName(std::move(name)), spawnName(std::move(spawn)) {} | ||
| 15 | 19 | ||
| 16 | void MapScene::enter() { | 20 | void MapScene::enter() { |
| 17 | g.tiles.build(map); // 静的な頂点バッファを作る(マップごとに一度) / build the static vertex buffer (once per map) | 21 | // マップはWorldから(初めてならファイルを読む)。扉は入る前に読めることを確かめてある |
| 18 | spawn(); | 22 | // The map comes from World (loaded from its file the first time). Doors check that it loads before switching |
| 23 | map = g.world.map(mapName); | ||
| 24 | setUp(); | ||
| 19 | } | 25 | } |
| 20 | 26 | ||
| 21 | void MapScene::spawn() { | 27 | void MapScene::setUp() { |
| 28 | g.tiles.build(*map); // 静的な頂点バッファを作る(マップに入るたびに一度) / build the static vertex buffer (once per | ||
| 29 | // visit) | ||
| 30 | const MapObject *start = map->findObject("spawn", spawnName); | ||
| 31 | if (!start) { | ||
| 32 | fprintf(stderr, "%s: 出発点がない / no spawn point '%s' (startを使う / using start)\n", map->path().c_str(), | ||
| 33 | spawnName.c_str()); | ||
| 34 | start = map->findObject("spawn", "start"); | ||
| 35 | } | ||
| 22 | hero.look = 0; | 36 | hero.look = 0; |
| 23 | const MapObject *start = map.findObject("spawn", "start"); | ||
| 24 | hero.placeAt(start ? start->rect.position() : Vec2{kTile, kTile}); | 37 | hero.placeAt(start ? start->rect.position() : Vec2{kTile, kTile}); |
| 25 | std::string_view face = start ? start->get("face", "down") : "down"; | 38 | std::string_view face = start ? start->get("face", "down") : "down"; |
| 26 | hero.facing = face == "up" ? Facing::Up : face == "left" ? Facing::Left : face == "right" ? Facing::Right : Facing::Down; | 39 | hero.facing = face == "up" ? Facing::Up : face == "left" ? Facing::Left : face == "right" ? Facing::Right : Facing::Down; |
| 27 | // 最初のフレームは更新なしで描かれる:今のうちに立ちのクリップを選んでおく / the first frame is drawn before any | 40 | // 最初のフレームは更新なしで描かれる:今のうちに立ちのクリップを選んでおく / the first frame is drawn before any |
| 28 | // update: pick the standing clip now | 41 | // update: pick the standing clip now |
| 29 | hero.animate(g.characters, 0.0f); | 42 | hero.animate(g.characters, 0.0f); |
| 43 | |||
| 44 | // 宝箱:開いたかどうかはWorldに残っている(マップ名/宝箱名) / chests: whether they are open is kept in World | ||
| 45 | // (map name/chest name) | ||
| 46 | chests.clear(); | ||
| 47 | blockers.clear(); | ||
| 48 | for (const MapObject &o : map->objects()) | ||
| 49 | if (o.kind == "chest") { | ||
| 50 | Rect box = {o.rect.x + 1.0f, o.rect.y + 4.0f, 14.0f, 12.0f}; | ||
| 51 | chests.push_back({&o, box, mapName + "/" + o.name}); | ||
| 52 | blockers.push_back(box); | ||
| 53 | } | ||
| 54 | warpArmed = false; | ||
| 55 | leaving = false; | ||
| 30 | } | 56 | } |
| 31 | 57 | ||
| 32 | void MapScene::pause() { hero.previous = hero.box.position(); } | 58 | void MapScene::pause() { hero.previous = hero.box.position(); } |
| 33 | 59 | ||
| 60 | // 顔の前の小さな箱:これに触れる物を調べる / a small box in front of the face: things touching it can be checked | ||
| 61 | Rect MapScene::facingProbe() const { | ||
| 62 | const Rect &b = hero.box; | ||
| 63 | constexpr float r = 8.0f; | ||
| 64 | switch (hero.facing) { | ||
| 65 | case Facing::Down: return {b.x, b.bottom(), b.w, r}; | ||
| 66 | case Facing::Up: return {b.x, b.y - r, b.w, r}; | ||
| 67 | case Facing::Left: return {b.x - r, b.y - 2.0f, r, b.h + 4.0f}; | ||
| 68 | case Facing::Right: return {b.right(), b.y - 2.0f, r, b.h + 4.0f}; | ||
| 69 | } | ||
| 70 | return b; | ||
| 71 | } | ||
| 72 | |||
| 73 | void MapScene::interact() { | ||
| 74 | Rect probe = facingProbe(); | ||
| 75 | for (const Chest &c : chests) { | ||
| 76 | if (!overlaps(probe, c.box) || g.world.flag(c.flag)) continue; | ||
| 77 | g.world.setFlag(c.flag); // マップを出ても開いたまま / stays open after leaving the map | ||
| 78 | int gold = c.object->getInt("gold", 0); | ||
| 79 | g.world.gold += gold; | ||
| 80 | popups.push_back({"+" + std::to_string(gold) + " G", {c.box.centre().x, c.box.y - 10.0f}, 1.2f}); | ||
| 81 | printf("%s: 開けた / opened (+%d G, %d G)\n", c.flag.c_str(), gold, g.world.gold); | ||
| 82 | return; | ||
| 83 | } | ||
| 84 | } | ||
| 85 | |||
| 86 | void MapScene::checkWarps() { | ||
| 87 | bool onWarp = false; | ||
| 88 | for (const MapObject &o : map->objects()) { | ||
| 89 | if ((o.kind != "door" && o.kind != "warp") || !overlaps(hero.box, o.rect)) continue; | ||
| 90 | onWarp = true; | ||
| 91 | if (!warpArmed) continue; | ||
| 92 | std::string target(o.get("map")), spawn(o.get("spawn", "start")); | ||
| 93 | // 先のマップを今読む(初めてならファイルから)。読めなければ移らない / load the target map now (from its file the | ||
| 94 | // first time); if it cannot be loaded, stay | ||
| 95 | if (!g.world.map(target)) { | ||
| 96 | fprintf(stderr, "%s: %s %s の先のマップ「%s」を読めない / cannot load map '%s'\n", map->path().c_str(), | ||
| 97 | o.kind.c_str(), o.name.c_str(), target.c_str(), target.c_str()); | ||
| 98 | warpArmed = false; | ||
| 99 | return; | ||
| 100 | } | ||
| 101 | printf("%s → %s (%s)\n", mapName.c_str(), target.c_str(), spawn.c_str()); | ||
| 102 | // 入れ替えは頼むだけ:フェードアウトの後で、このシーンがexit、新しいシーンがenterする | ||
| 103 | // The replacement is only requested: after the fade out this scene exits and the new one enters | ||
| 104 | scenes().replace(std::make_unique<MapScene>(g, target, spawn), kMapFade); | ||
| 105 | leaving = true; | ||
| 106 | hero.moving = false; | ||
| 107 | hero.previous = hero.box.position(); // 止める:フェードの間は更新されない / freeze: no updates during the fade | ||
| 108 | return; | ||
| 109 | } | ||
| 110 | if (!onWarp) warpArmed = true; // 扉から離れた:次に触れた扉は効く / off every door: the next one works | ||
| 111 | } | ||
| 112 | |||
| 34 | void MapScene::update(float dt) { | 113 | void MapScene::update(float dt) { |
| 35 | time += dt; | 114 | time += dt; |
| 115 | if (leaving) return; | ||
| 36 | Input &in = g.input; | 116 | Input &in = g.input; |
| 37 | if (in.pressed(GLFW_KEY_ESCAPE)) { | 117 | if (in.pressed(GLFW_KEY_ESCAPE)) { |
| 38 | scenes().pop(); // 最後のシーン:mainが終わる / the last scene: main quits | 118 | scenes().pop(); // 最後のシーン:mainが終わる / the last scene: main quits |
| 39 | return; | 119 | return; |
| 40 | } | 120 | } |
| 41 | if (in.pressed(GLFW_KEY_B)) showBoxes = !showBoxes; | 121 | DebugView &dbg = g.debug; |
| 42 | if (in.pressed(GLFW_KEY_Z)) zoomOut = !zoomOut; | 122 | if (in.pressed(GLFW_KEY_B)) dbg.boxes = !dbg.boxes; |
| 43 | if (in.pressed(GLFW_KEY_H)) showHud = !showHud; | 123 | if (in.pressed(GLFW_KEY_Z)) dbg.zoomOut = !dbg.zoomOut; |
| 124 | if (in.pressed(GLFW_KEY_H)) dbg.hud = !dbg.hud; | ||
| 44 | for (int i = 0; i < 3; ++i) | 125 | for (int i = 0; i < 3; ++i) |
| 45 | if (in.pressed(GLFW_KEY_1 + i)) layerOn[static_cast<size_t>(i)] = !layerOn[static_cast<size_t>(i)]; | 126 | if (in.pressed(GLFW_KEY_1 + i)) dbg.layers[static_cast<size_t>(i)] = !dbg.layers[static_cast<size_t>(i)]; |
| 46 | if (in.pressed(GLFW_KEY_R)) { | 127 | if (in.pressed(GLFW_KEY_R) && g.world.reload(mapName)) { |
| 47 | // ファイルから読み直す(テキストエディターで直してすぐ確かめる)。失敗したら今のマップのまま | 128 | // ファイルから読み直す。物のポインターが変わるので作り直し、主人公は今の場所に戻す |
| 48 | // Reload from the file (edit in a text editor, check at once). On failure the current map stays | 129 | // Reload from the file. Object pointers change, so rebuild them; the hero goes back to where it was |
| 49 | if (std::optional<Tilemap> fresh = Tilemap::load(map.path())) { | 130 | Rect keep = hero.box; |
| 50 | map = std::move(*fresh); | 131 | Facing facing = hero.facing; |
| 51 | g.tiles.build(map); | 132 | setUp(); |
| 52 | printf("%s: 読み直した / reloaded\n", map.path().c_str()); | 133 | hero.box = keep; |
| 53 | } | 134 | hero.previous = keep.position(); |
| 135 | hero.facing = facing; | ||
| 136 | printf("%s: 読み直した / reloaded\n", map->path().c_str()); | ||
| 54 | } | 137 | } |
| 55 | 138 | ||
| 56 | // 主人公:自由に動く(マス目に縛られない)。斜めは正規化して同じ速さ / the hero moves freely (not locked to the | 139 | // 主人公:自由に動く(マス目に縛られない)。斜めは正規化して同じ速さ / the hero moves freely (not locked to the |
| @@ -61,14 +144,22 @@ void MapScene::update(float dt) { | |||
| 61 | if (hero.moving) { | 144 | if (hero.moving) { |
| 62 | hero.facing = facingFor(move, hero.facing); | 145 | hero.facing = facingFor(move, hero.facing); |
| 63 | float speed = in.actionHeld("run") ? kRunSpeed : kWalkSpeed; | 146 | float speed = in.actionHeld("run") ? kRunSpeed : kWalkSpeed; |
| 64 | moveOnMap(hero.box, normalize(move) * (speed * dt), map, {}, scratch); | 147 | moveOnMap(hero.box, normalize(move) * (speed * dt), *map, blockers, scratch); |
| 65 | } | 148 | } |
| 66 | hero.anim.speed = in.actionHeld("run") ? 1.5f : 1.0f; | 149 | hero.anim.speed = in.actionHeld("run") ? 1.5f : 1.0f; |
| 67 | hero.animate(g.characters, dt); | 150 | hero.animate(g.characters, dt); |
| 151 | if (in.actionPressed("confirm")) interact(); | ||
| 152 | checkWarps(); | ||
| 153 | |||
| 154 | for (Popup &p : popups) { | ||
| 155 | p.position.y -= 12.0f * dt; | ||
| 156 | p.life -= dt; | ||
| 157 | } | ||
| 158 | std::erase_if(popups, [](const Popup &p) { return p.life <= 0.0f; }); | ||
| 68 | } | 159 | } |
| 69 | 160 | ||
| 70 | Camera2D MapScene::followCamera(Vec2 target) const { | 161 | Camera2D MapScene::followCamera(Vec2 target) const { |
| 71 | Vec2 size = map.pixelSize(), half = 0.5f * kView; | 162 | Vec2 size = map->pixelSize(), half = 0.5f * kView; |
| 72 | Vec2 c; | 163 | Vec2 c; |
| 73 | c.x = size.x <= kView.x ? 0.5f * size.x : std::clamp(target.x, half.x, size.x - half.x); | 164 | c.x = size.x <= kView.x ? 0.5f * size.x : std::clamp(target.x, half.x, size.x - half.x); |
| 74 | c.y = size.y <= kView.y ? 0.5f * size.y : std::clamp(target.y, half.y, size.y - half.y); | 165 | c.y = size.y <= kView.y ? 0.5f * size.y : std::clamp(target.y, half.y, size.y - half.y); |
| @@ -78,41 +169,41 @@ Camera2D MapScene::followCamera(Vec2 target) const { | |||
| 78 | } | 169 | } |
| 79 | 170 | ||
| 80 | void MapScene::draw(float alpha) { | 171 | void MapScene::draw(float alpha) { |
| 81 | // 足元の少し上(体の真ん中)を追う / follow a point a little above the feet (the middle of the body) | ||
| 82 | Vec2 feet = hero.feet(alpha); | 172 | Vec2 feet = hero.feet(alpha); |
| 83 | Camera2D camera = followCamera({feet.x, feet.y - 6.0f}); | 173 | Camera2D camera = followCamera({feet.x, feet.y - 6.0f}); |
| 84 | Rect visible = camera.visibleRect(); | 174 | Rect visible = camera.visibleRect(); |
| 85 | // Z:引いて見る。カリングは本物のカメラのままなので、見えない行が描かれていないのが分かる | ||
| 86 | // Z: zoom out. Culling still uses the real camera, so you can see that rows outside it are not drawn | ||
| 87 | Camera2D view = camera; | 175 | Camera2D view = camera; |
| 88 | if (zoomOut) { | 176 | if (g.debug.zoomOut) view.zoom = 0.5f; |
| 89 | view.zoom = 0.5f; | ||
| 90 | view.centre = {std::round(camera.centre.x), std::round(camera.centre.y)}; | ||
| 91 | } | ||
| 92 | Mat4 vp = view.matrix(); | 177 | Mat4 vp = view.matrix(); |
| 93 | SpriteBatch &b = g.batch; | 178 | SpriteBatch &b = g.batch; |
| 94 | g.tiles.resetStats(); | 179 | g.tiles.resetStats(); |
| 95 | spriteCalls = 0; | 180 | spriteCalls = 0; |
| 96 | rowFirst = std::clamp(static_cast<int>(std::floor(visible.top() / kTile)), 0, map.height()); | 181 | rowFirst = std::clamp(static_cast<int>(std::floor(visible.top() / kTile)), 0, map->height()); |
| 97 | rowLast = std::clamp(static_cast<int>(std::ceil(visible.bottom() / kTile)), 0, map.height()) - 1; | 182 | rowLast = std::clamp(static_cast<int>(std::ceil(visible.bottom() / kTile)), 0, map->height()) - 1; |
| 183 | const SpriteSheet &tileSheet = map->tileset().sheet(); | ||
| 98 | 184 | ||
| 99 | auto drawCharacters = [&] { | 185 | auto drawCharacters = [&] { |
| 186 | // 人物と、背の低い物(宝箱)を足元のyの順に / characters and low objects (chests) sorted by the y of their feet | ||
| 100 | b.begin(vp, SpriteSort::Layer); | 187 | b.begin(vp, SpriteSort::Layer); |
| 188 | for (const Chest &c : chests) { | ||
| 189 | Sprite s = tileSheet.sprite(tileSheet.find(g.world.flag(c.flag) ? "chest_open" : "chest_closed"), | ||
| 190 | c.object->rect.position()); | ||
| 191 | s.layer = c.box.bottom(); | ||
| 192 | b.draw(s); | ||
| 193 | } | ||
| 101 | b.draw(hero.sprite(g.characters, alpha)); | 194 | b.draw(hero.sprite(g.characters, alpha)); |
| 102 | b.end(); | 195 | b.end(); |
| 103 | spriteCalls += b.stats().drawCalls; | 196 | spriteCalls += b.stats().drawCalls; |
| 104 | }; | 197 | }; |
| 105 | 198 | ||
| 106 | // 層はファイルの順に描く。「above」の層(木の上・屋根の棟)は人物の後 / layers are drawn in file order; "above" | ||
| 107 | // layers (tree tops, roof ridges) come after the characters | ||
| 108 | bool charactersDrawn = false; | 199 | bool charactersDrawn = false; |
| 109 | const std::vector<TileLayer> &layers = map.layers(); | 200 | const std::vector<TileLayer> &layers = map->layers(); |
| 110 | for (int i = 0; i < static_cast<int>(layers.size()); ++i) { | 201 | for (int i = 0; i < static_cast<int>(layers.size()); ++i) { |
| 111 | if (layers[static_cast<size_t>(i)].above && !charactersDrawn) { | 202 | if (layers[static_cast<size_t>(i)].above && !charactersDrawn) { |
| 112 | drawCharacters(); | 203 | drawCharacters(); |
| 113 | charactersDrawn = true; | 204 | charactersDrawn = true; |
| 114 | } | 205 | } |
| 115 | if (i < static_cast<int>(layerOn.size()) && !layerOn[static_cast<size_t>(i)]) continue; | 206 | if (i < static_cast<int>(g.debug.layers.size()) && !g.debug.layers[static_cast<size_t>(i)]) continue; |
| 116 | g.tiles.drawLayer(i, vp, visible); | 207 | g.tiles.drawLayer(i, vp, visible); |
| 117 | if (g.tiles.hasAnimated(i)) { | 208 | if (g.tiles.hasAnimated(i)) { |
| 118 | b.begin(vp); | 209 | b.begin(vp); |
| @@ -123,44 +214,66 @@ void MapScene::draw(float alpha) { | |||
| 123 | } | 214 | } |
| 124 | if (!charactersDrawn) drawCharacters(); | 215 | if (!charactersDrawn) drawCharacters(); |
| 125 | 216 | ||
| 126 | if (showBoxes || zoomOut) { | 217 | // 世界の上の物:浮かぶ文字、デバッグの箱 / things over the world: floating text, debug boxes |
| 127 | b.begin(vp); | 218 | b.begin(vp); |
| 128 | if (showBoxes) { | 219 | for (const Popup &p : popups) |
| 129 | // 固いマス(赤)と主人公の足元の箱(緑) / solid cells (red) and the hero's foot box (green) | 220 | g.pixel.draw(b, p.text, p.position, |
| 130 | scratch.clear(); | 221 | {.color = {1.0f, 0.9f, 0.45f, std::min(1.0f, p.life * 3.0f)}, .align = TextAlign::Centre, |
| 131 | map.solidRects(visible, scratch); | 222 | .shadow = hexColor(0x1b1726ff)}); |
| 132 | for (const Rect &r : scratch) b.drawRectOutline(r, hexColor(0xff5050c0)); | 223 | if (g.debug.boxes) { |
| 133 | Vec2 p = lerp(hero.previous, hero.box.position(), alpha); | 224 | scratch.clear(); |
| 134 | b.drawRectOutline({p.x, p.y, hero.box.w, hero.box.h}, hexColor(0x50ff60ff)); | 225 | map->solidRects(visible, scratch); |
| 135 | } | 226 | for (const Rect &r : scratch) b.drawRectOutline(r, hexColor(0xff5050c0)); |
| 136 | if (zoomOut) b.drawRectOutline(visible, hexColor(0xffe040ff), 2.0f); // 本物のカメラ / the real camera | 227 | for (const Rect &r : blockers) b.drawRectOutline(r, hexColor(0xff9040ff)); |
| 137 | b.end(); | 228 | for (const MapObject &o : map->objects()) |
| 138 | spriteCalls += b.stats().drawCalls; | 229 | if (o.kind == "door" || o.kind == "warp") b.drawRectOutline(o.rect, hexColor(0x40c0ffff)); // 扉 / doors |
| 230 | Vec2 p = lerp(hero.previous, hero.box.position(), alpha); | ||
| 231 | b.drawRectOutline({p.x, p.y, hero.box.w, hero.box.h}, hexColor(0x50ff60ff)); | ||
| 232 | b.drawRectOutline(facingProbe(), hexColor(0xffff60c0)); | ||
| 233 | } | ||
| 234 | if (g.debug.zoomOut) b.drawRectOutline(visible, hexColor(0xffe040ff), 2.0f); | ||
| 235 | b.end(); | ||
| 236 | |||
| 237 | // キャンバスの画面に固定の物:マップの名前、お金 / things fixed to the canvas screen: the map's name, the money | ||
| 238 | Camera2D canvas = Camera2D::screen(kView); | ||
| 239 | b.begin(canvas.matrix()); | ||
| 240 | float banner = std::clamp((kBannerTime - time) / 0.5f, 0.0f, 1.0f); | ||
| 241 | if (banner > 0.0f) { | ||
| 242 | Vec2 size = g.pixel.measure(map->title()); | ||
| 243 | Rect box = Rect::fromCentre({160.0f, 30.0f}, {size.x + 16.0f, size.y + 6.0f}); | ||
| 244 | b.drawRect(box, {0.106f, 0.09f, 0.15f, 0.85f * banner}); | ||
| 245 | b.drawRectOutline(box, {0.95f, 0.76f, 0.31f, banner}); | ||
| 246 | g.pixel.draw(b, map->title(), {160.0f, box.y + 3.0f}, {.color = {1.0f, 0.96f, 0.84f, banner}, .align = TextAlign::Centre}); | ||
| 139 | } | 247 | } |
| 248 | char gold[32]; | ||
| 249 | snprintf(gold, sizeof gold, "%d G", g.world.gold); | ||
| 250 | g.pixel.draw(b, gold, {314.0f, 160.0f}, {.color = hexColor(0xf2c14eff), .align = TextAlign::Right, .shadow = hexColor(0x1b1726ff)}); | ||
| 251 | b.end(); | ||
| 140 | } | 252 | } |
| 141 | 253 | ||
| 142 | void MapScene::drawUi(float /*alpha*/) { | 254 | void MapScene::drawUi(float /*alpha*/) { |
| 143 | if (!showHud) return; | 255 | if (!g.debug.hud) return; |
| 144 | SpriteBatch &b = g.batch; | 256 | SpriteBatch &b = g.batch; |
| 145 | const TileRenderer::Stats &ts = g.tiles.stats(); | 257 | const TileRenderer::Stats &ts = g.tiles.stats(); |
| 146 | char line[256]; | 258 | char line[256]; |
| 147 | int col = static_cast<int>(std::floor(hero.box.centre().x / kTile)), row = static_cast<int>(std::floor(hero.box.centre().y / kTile)); | 259 | int col = static_cast<int>(std::floor(hero.box.centre().x / kTile)), row = static_cast<int>(std::floor(hero.box.centre().y / kTile)); |
| 148 | snprintf(line, sizeof line, "%s %d×%d tile (%d, %d) rows %d-%d tile quads %d / %d draw calls: tiles %d + sprites %d", | 260 | snprintf(line, sizeof line, "%s %d×%d tile (%d, %d) rows %d-%d tile quads %d / %d draws: tiles %d + sprites %d maps %d", |
| 149 | map.name().c_str(), map.width(), map.height(), col, row, rowFirst, rowLast, ts.quads, ts.totalQuads, | 261 | map->name().c_str(), map->width(), map->height(), col, row, rowFirst, rowLast, ts.quads, ts.totalQuads, |
| 150 | ts.drawCalls, spriteCalls); | 262 | ts.drawCalls, spriteCalls, g.world.loadedMaps()); |
| 151 | b.begin(g.screen.matrix()); | 263 | b.begin(g.screen.matrix()); |
| 152 | TextStyle hud = {.color = hexColor(0xfff4d6ff), .shadow = hexColor(0x000000ff)}; | 264 | TextStyle hud = {.color = hexColor(0xfff4d6ff), .shadow = hexColor(0x000000ff)}; |
| 153 | b.drawRect({0.0f, 0.0f, 1280.0f, 30.0f}, hexColor(0x1b1726c0)); | 265 | b.drawRect({0.0f, 0.0f, 1280.0f, 30.0f}, hexColor(0x1b1726c0)); |
| 154 | g.ui.draw(b, line, {12.0f, 6.0f}, hud); | 266 | g.ui.draw(b, line, {12.0f, 6.0f}, hud); |
| 155 | char layers[64]; | 267 | char layers[64]; |
| 156 | snprintf(layers, sizeof layers, "layers %s %s %s", layerOn[0] ? "1" : "-", layerOn[1] ? "2" : "-", layerOn[2] ? "3" : "-"); | 268 | snprintf(layers, sizeof layers, "layers %s %s %s", g.debug.layers[0] ? "1" : "-", g.debug.layers[1] ? "2" : "-", |
| 269 | g.debug.layers[2] ? "3" : "-"); | ||
| 157 | hud.align = TextAlign::Right; | 270 | hud.align = TextAlign::Right; |
| 158 | hud.color = hexColor(0xf2c14eff); | 271 | hud.color = hexColor(0xf2c14eff); |
| 159 | g.ui.draw(b, layers, {1268.0f, 6.0f}, hud); | 272 | g.ui.draw(b, layers, {1268.0f, 6.0f}, hud); |
| 160 | b.drawRect({0.0f, 690.0f, 1280.0f, 30.0f}, hexColor(0x1b1726c0)); | 273 | b.drawRect({0.0f, 690.0f, 1280.0f, 30.0f}, hexColor(0x1b1726c0)); |
| 161 | hud.align = TextAlign::Centre; | 274 | hud.align = TextAlign::Centre; |
| 162 | hud.color = hexColor(0xc8cce0ff); | 275 | hud.color = hexColor(0xc8cce0ff); |
| 163 | g.ui.draw(b, "arrows / WASD: move Shift: run 1 2 3: layers B: boxes Z: zoom out H: HUD R: reload the map Esc: 終了 / quit", | 276 | g.ui.draw(b, "arrows / WASD: move Shift: run Space: 調べる / check 1 2 3: layers B: boxes Z: zoom out H: HUD R: reload Esc: 終了 / quit", |
| 164 | {640.0f, 696.0f}, hud); | 277 | {640.0f, 696.0f}, hud); |
| 165 | b.end(); | 278 | b.end(); |
| 166 | } | 279 | } |
ファイル: a/games/rpg/src/tilemap.cc | b/games/rpg/src/tilemap.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -126,7 +126,7 @@ int MapObject::getInt(std::string_view key, int fallback) const { | |||
| 126 | 126 | ||
| 127 | // ---------------------------------------------------------------------------------------------------- Tilemap | 127 | // ---------------------------------------------------------------------------------------------------- Tilemap |
| 128 | 128 | ||
| 129 | std::optional<Tilemap> Tilemap::load(const std::string &path) { | 129 | std::optional<Tilemap> Tilemap::load(const std::string &path, TilesetCache *cache) { |
| 130 | std::optional<std::string> text = readTextFile(path); | 130 | std::optional<std::string> text = readTextFile(path); |
| 131 | if (!text) { | 131 | if (!text) { |
| 132 | fprintf(stderr, "%s: 読めない / cannot read (プロジェクトのルートから実行した? / running from the project root?)\n", | 132 | fprintf(stderr, "%s: 読めない / cannot read (プロジェクトのルートから実行した? / running from the project root?)\n", |
| @@ -150,6 +150,8 @@ std::optional<Tilemap> Tilemap::load(const std::string &path) { | |||
| 150 | if (!(in >> command) || command[0] == '#') continue; | 150 | if (!(in >> command) || command[0] == '#') continue; |
| 151 | if (command == "map") { | 151 | if (command == "map") { |
| 152 | in >> map.mapName; | 152 | in >> map.mapName; |
| 153 | } else if (command == "title") { | ||
| 154 | std::getline(in >> std::ws, map.mapTitle); | ||
| 153 | } else if ((command == "tileset" || command == "size") && !map.tileLayers.empty()) { | 155 | } else if ((command == "tileset" || command == "size") && !map.tileLayers.empty()) { |
| 154 | // 読んだ層は今の大きさとタイルセットの番号で出来ている:後から変えると層が合わなくなる | 156 | // 読んだ層は今の大きさとタイルセットの番号で出来ている:後から変えると層が合わなくなる |
| 155 | // The layers already read use the current size and the tileset's kind numbers: changing them later would not | 157 | // The layers already read use the current size and the tileset's kind numbers: changing them later would not |
| @@ -158,9 +160,15 @@ std::optional<Tilemap> Tilemap::load(const std::string &path) { | |||
| 158 | } else if (command == "tileset") { | 160 | } else if (command == "tileset") { |
| 159 | std::string file; | 161 | std::string file; |
| 160 | in >> file; | 162 | in >> file; |
| 161 | std::optional<Tileset> set = Tileset::load(folderOf(path) + file); | 163 | std::string tilesetPath = folderOf(path) + file; |
| 164 | if (cache && cache->contains(tilesetPath)) { | ||
| 165 | map.tiles = cache->at(tilesetPath); | ||
| 166 | continue; | ||
| 167 | } | ||
| 168 | std::optional<Tileset> set = Tileset::load(tilesetPath); | ||
| 162 | if (!set) return fail("タイルセットを読めない / cannot load the tileset " + file); | 169 | if (!set) return fail("タイルセットを読めない / cannot load the tileset " + file); |
| 163 | map.tiles = std::make_shared<const Tileset>(std::move(*set)); | 170 | map.tiles = std::make_shared<const Tileset>(std::move(*set)); |
| 171 | if (cache) (*cache)[tilesetPath] = map.tiles; | ||
| 164 | } else if (command == "size") { | 172 | } else if (command == "size") { |
| 165 | if (!(in >> map.cols >> map.rows) || map.cols <= 0 || map.rows <= 0 || map.cols > 1024 || map.rows > 1024) | 173 | if (!(in >> map.cols >> map.rows) || map.cols <= 0 || map.rows <= 0 || map.cols > 1024 || map.rows > 1024) |
| 166 | return fail("size <幅> <高さ>(1〜1024) / size <width> <height> (1..1024)"); | 174 | return fail("size <幅> <高さ>(1〜1024) / size <width> <height> (1..1024)"); |
ファイル: a/games/rpg/src/tilemap.hh | b/games/rpg/src/tilemap.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -14,6 +14,7 @@ | |||
| 14 | #include <optional> | 14 | #include <optional> |
| 15 | #include <string> | 15 | #include <string> |
| 16 | #include <string_view> | 16 | #include <string_view> |
| 17 | #include <unordered_map> | ||
| 17 | #include <vector> | 18 | #include <vector> |
| 18 | 19 | ||
| 19 | constexpr int kTileSize = 16; | 20 | constexpr int kTileSize = 16; |
| @@ -52,6 +53,10 @@ private: | |||
| 52 | std::array<int, 128> bySymbol{}; // ASCIIの文字 → kindsの番号(-1 = なし) / ASCII character → kinds index (-1 = none) | 53 | std::array<int, 128> bySymbol{}; // ASCIIの文字 → kindsの番号(-1 = なし) / ASCII character → kinds index (-1 = none) |
| 53 | }; | 54 | }; |
| 54 | 55 | ||
| 56 | // 読んだタイルセットを覚えておく表(パス → タイルセット):同じタイルセットのマップは画像を共有する | ||
| 57 | // A table of loaded tilesets (path → tileset): maps with the same tileset share its image | ||
| 58 | using TilesetCache = std::unordered_map<std::string, std::shared_ptr<const Tileset>>; | ||
| 59 | |||
| 55 | // マップの物(扉・出発点・宝箱・人…)。位置と大きさはピクセル、性質は key=value の文字列 | 60 | // マップの物(扉・出発点・宝箱・人…)。位置と大きさはピクセル、性質は key=value の文字列 |
| 56 | // An object on a map (door, spawn point, chest, person...). Position and size in pixels, properties as key=value | 61 | // An object on a map (door, spawn point, chest, person...). Position and size in pixels, properties as key=value |
| 57 | struct MapObject { | 62 | struct MapObject { |
| @@ -77,16 +82,20 @@ class Tilemap { | |||
| 77 | public: | 82 | public: |
| 78 | // 書式 / format (see games/rpg/assets/maps/*.map): | 83 | // 書式 / format (see games/rpg/assets/maps/*.map): |
| 79 | // map <name> 名前 / the name | 84 | // map <name> 名前 / the name |
| 85 | // title <text…> 画面に出す名前(行の残り全部) / the name shown on screen (the rest of the line) | ||
| 80 | // tileset <file.tileset> .mapからの相対パス / relative to the .map | 86 | // tileset <file.tileset> .mapからの相対パス / relative to the .map |
| 81 | // size <width> <height> マスの数 / in tiles | 87 | // size <width> <height> マスの数 / in tiles |
| 82 | // layer <name> [above] 続くheight行が格子(1文字 = 1マス、'.' = 空) / the next `height` lines are the grid | 88 | // layer <name> [above] 続くheight行が格子(1文字 = 1マス、'.' = 空) / the next `height` lines are the grid |
| 83 | // (1 character = 1 tile, '.' = empty) | 89 | // (1 character = 1 tile, '.' = empty) |
| 84 | // object <kind> <name> <col> <row> [key=value …] w= h= でマスの大きさ(既定1×1) / w= h= set the size in tiles | 90 | // object <kind> <name> <col> <row> [key=value …] w= h= でマスの大きさ(既定1×1) / w= h= set the size in tiles |
| 85 | // (default 1 × 1) | 91 | // (default 1 × 1) |
| 86 | // エラーは「ファイル:行: 説明」でstderrに出してnullopt / errors go to stderr as "file:line: message", then nullopt | 92 | // エラーは「ファイル:行: 説明」でstderrに出してnullopt / errors go to stderr as "file:line: message", then nullopt. |
| 87 | static std::optional<Tilemap> load(const std::string &path); | 93 | // cacheがあれば、タイルセットはそこから取る(なければ読んで入れる) / with a cache, the tileset comes from it (loaded |
| 94 | // and added if missing) | ||
| 95 | static std::optional<Tilemap> load(const std::string &path, TilesetCache *cache = nullptr); | ||
| 88 | 96 | ||
| 89 | const std::string &name() const { return mapName; } | 97 | const std::string &name() const { return mapName; } |
| 98 | const std::string &title() const { return mapTitle.empty() ? mapName : mapTitle; } | ||
| 90 | const std::string &path() const { return filePath; } | 99 | const std::string &path() const { return filePath; } |
| 91 | const Tileset &tileset() const { return *tiles; } | 100 | const Tileset &tileset() const { return *tiles; } |
| 92 | int width() const { return cols; } | 101 | int width() const { return cols; } |
| @@ -105,7 +114,7 @@ public: | |||
| 105 | 114 | ||
| 106 | private: | 115 | private: |
| 107 | Tilemap() = default; | 116 | Tilemap() = default; |
| 108 | std::string mapName, filePath; | 117 | std::string mapName, mapTitle, filePath; |
| 109 | std::shared_ptr<const Tileset> tiles; // 同じタイルセットを何枚ものマップで共有できる / several maps can share one | 118 | std::shared_ptr<const Tileset> tiles; // 同じタイルセットを何枚ものマップで共有できる / several maps can share one |
| 110 | int cols = 0, rows = 0; | 119 | int cols = 0, rows = 0; |
| 111 | std::vector<TileLayer> tileLayers; | 120 | std::vector<TileLayer> tileLayers; |
ファイル: /dev/null | b/games/rpg/src/world.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,38 @@ | |||
| 1 | #include "world.hh" | ||
| 2 | |||
| 3 | #include <cstdio> | ||
| 4 | #include <utility> | ||
| 5 | #include <vector> | ||
| 6 | |||
| 7 | Tilemap *World::map(const std::string &name) { | ||
| 8 | if (auto it = maps.find(name); it != maps.end()) return it->second.get(); | ||
| 9 | std::optional<Tilemap> loaded = Tilemap::load(pathOf(name), &tilesets); | ||
| 10 | if (!loaded) return nullptr; | ||
| 11 | printf("%s: 読んだ / loaded (%d×%d)\n", pathOf(name).c_str(), loaded->width(), loaded->height()); | ||
| 12 | return (maps[name] = std::make_unique<Tilemap>(std::move(*loaded))).get(); | ||
| 13 | } | ||
| 14 | |||
| 15 | bool World::reload(const std::string &name) { | ||
| 16 | if (!maps.contains(name)) return map(name) != nullptr; | ||
| 17 | // タイルセットも読み直す。マップの格子はタイルセットの番号なので、読んである全部のマップを新しい表で読み直す | ||
| 18 | // (古いタイルセットを持ったままのマップが残らない)。全部読めたときだけ入れ替え、一つでも失敗したら何も変えない | ||
| 19 | // The tileset is read again too. Map grids hold the tileset's kind numbers, so every loaded map is read again with | ||
| 20 | // the new table (no map keeps the old tileset). They are swapped in only if all of them load; one failure changes | ||
| 21 | // nothing | ||
| 22 | std::vector<std::string> names = {name}; // 今のマップから:エラーはまずそこに出る / the current map first: its | ||
| 23 | // errors come first | ||
| 24 | for (const auto &entry : maps) | ||
| 25 | if (entry.first != name) names.push_back(entry.first); | ||
| 26 | TilesetCache freshTilesets; | ||
| 27 | std::vector<std::pair<Tilemap *, Tilemap>> fresh; | ||
| 28 | for (const std::string &n : names) { | ||
| 29 | std::optional<Tilemap> loaded = Tilemap::load(pathOf(n), &freshTilesets); | ||
| 30 | if (!loaded) return false; | ||
| 31 | fresh.emplace_back(maps[n].get(), std::move(*loaded)); | ||
| 32 | } | ||
| 33 | // 同じ場所に入れる:シーンのポインターはそのまま / same addresses: scenes' pointers stay valid | ||
| 34 | for (auto &[target, loaded] : fresh) *target = std::move(loaded); | ||
| 35 | tilesets = std::move(freshTilesets); // 古いタイルセット(とテクスチャー)はここで消える / the old tileset (and its | ||
| 36 | // texture) is freed here | ||
| 37 | return true; | ||
| 38 | } | ||
ファイル: /dev/null | b/games/rpg/src/world.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,43 @@ | |||
| 1 | // 世界の状態(第34章):読んだマップの置き場と、マップを出ても残るもの(開けた宝箱・お金) | ||
| 2 | // The world state (chapter 34): where loaded maps are kept, and what survives leaving a map (opened chests, money) | ||
| 3 | // | ||
| 4 | // シーンはマップに入るたびに作り直される(scenes().replace)。だから「残すもの」はシーンではなくここに置く: | ||
| 5 | // 残す:開けた宝箱などの印(flags)、お金 → 戻ってきても宝箱は開いたまま | ||
| 6 | // 残さない:シーンの中の物(主人公の位置、浮かぶ文字…)→ 入るたびにマップのファイルの通りから始まる | ||
| 7 | // A scene is created anew every time you enter a map (scenes().replace). So what must persist lives here, not in the | ||
| 8 | // scene: | ||
| 9 | // kept: flags such as opened chests, the money → a chest is still open when you come back | ||
| 10 | // not kept: everything inside the scene (the hero's position, floating text...) → each visit starts as the map | ||
| 11 | // file says | ||
| 12 | #pragma once | ||
| 13 | |||
| 14 | #include "tilemap.hh" | ||
| 15 | |||
| 16 | #include <memory> | ||
| 17 | #include <string> | ||
| 18 | #include <unordered_map> | ||
| 19 | #include <unordered_set> | ||
| 20 | |||
| 21 | class World { | ||
| 22 | public: | ||
| 23 | // マップを名前で:初めてなら games/rpg/assets/maps/<名前>.map を読む。読めなければnullptr。 | ||
| 24 | // ポインターは変わらない(読み直しても同じ場所) / a map by name: loaded from games/rpg/assets/maps/<name>.map on | ||
| 25 | // first use; nullptr if it cannot be loaded. The pointer stays valid (also across reloads) | ||
| 26 | Tilemap *map(const std::string &name); | ||
| 27 | // ファイルから読み直す(タイルセットと、読んであるほかのマップも)。失敗したら全部前のまま / reloads from the file | ||
| 28 | // (the tileset and the other loaded maps too); on failure everything stays as it was | ||
| 29 | bool reload(const std::string &name); | ||
| 30 | int loadedMaps() const { return static_cast<int>(maps.size()); } | ||
| 31 | |||
| 32 | bool flag(const std::string &name) const { return flags.contains(name); } | ||
| 33 | void setFlag(const std::string &name) { flags.insert(name); } | ||
| 34 | |||
| 35 | int gold = 0; | ||
| 36 | |||
| 37 | static std::string pathOf(const std::string &name) { return "games/rpg/assets/maps/" + name + ".map"; } | ||
| 38 | |||
| 39 | private: | ||
| 40 | std::unordered_map<std::string, std::unique_ptr<Tilemap>> maps; | ||
| 41 | TilesetCache tilesets; | ||
| 42 | std::unordered_set<std::string> flags; | ||
| 43 | }; | ||
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。