33. Top-Down RPG Part 1: Tilemaps and Movement
With the fighting game done, Part 6 moves on to its third game: a small top-down RPG in the style of the 16-bit era, built over three chapters.
This first part is about the world itself.
We read a village from a text file, draw it from a vertex buffer that is filled once and never touched again, let the hero walk around it with collision against solid tiles, and follow him with a camera that stops at the edges of the map.
The OpenGL topic of the chapter is static geometry.
The SpriteBatch from chapter 25 builds every vertex on the CPU and sends it to the GPU every frame, which is right for things that move and wasteful for a map that never changes.
The tiles go into one immutable buffer instead, and each frame draws only the rows the camera can see, with one glDrawElementsBaseVertex per layer.
33.1 What we're building
The program rpg opens a 40 × 28-tile village: two small houses and the elder's house along a road, a river with a bridge, a square with a well, a fenced garden and a forest along the edges.
The clip walks down to the road, walks and then runs east over the bridge until the camera stops at the right edge of the map, goes south to the forest, where the tree crowns cover the hero, and then west and north around a tree:
The controls:
- Arrow keys or W, A, S, D: walk (diagonals too); hold Shift to run
- 1, 2, 3: show or hide the ground, decor and overlay layers
- B: show the collision boxes (solid cells in red, the hero's foot box in green)
- Z: zoom out to see the culling; H: hide the HUD
- R: reload the map from its file; Esc: quit
Everything is new and lives in games/rpg/; nothing outside that folder changes:
CMakeLists.txt: therpgexecutablesrc/main.cc,src/game.hh: the window, the sharedGamedata, the framesrc/tilemap.hh,src/tilemap.cc:TilesetandTilemap, the readers for the two text formatssrc/tile_renderer.hh,src/tile_renderer.cc:TileRenderer, the static buffer with row cullingsrc/character.hh,src/character.cc: the character sheet,CharacterandmoveOnMapsrc/map_scene.cc:MapScene, the scene that updates and draws a mapassets/:tiles.pngandtiles.atlas,characters.png, the hand-writtentiles.tileset,maps/village.map,LICENSE.txt(the finished files are in the chapter's ZIP and inch33/of the assets ZIP)README.md: the controls
33.2 The game folder
Chapter 27 showed how a game joins the build, so here is the short version.
The top-level CMakeLists.txt adds games/rpg as soon as games/rpg/CMakeLists.txt exists, and the game's own file is the same template every game uses:
# 見下ろし型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)
target_include_directories(rpg PRIVATE src)
target_link_libraries(rpg PRIVATE engine)
enable_warnings(rpg)
set_working_directory(rpg)
Linking engine brings in GLAD, GLFW and the include paths of the engine and linalg.hh.
set_working_directory makes Visual Studio start the game in the project root, which is where every path points from: the engine's shaders are engine/shaders/…, the shared fonts are assets/fonts/…, and the game's own data is games/rpg/assets/….
The resolution follows the rule for the pixel-art games: a PixelCanvas of 320 × 180, presented at 4 times in the 1280 × 720 window.
With 16 × 16 tiles that's 320 / 16 = 20 tiles across and 180 / 16 = 11.25 tiles down.
The frame is the one from the chapter 26 demo: the world into the canvas, the canvas onto the screen, then the UI at full resolution:
[&](float alpha) {
// 1. 世界:320 × 180のキャンバスに描き、整数倍で画面へ / 1. the world: into the 320 × 180 canvas, then scaled
// by a whole number onto the screen
canvas.begin(hexColor(0x1b1726ff));
scenes.draw(alpha);
canvas.present(window.width(), window.height());
// 2. UI:1280 × 720の文字 / 2. the UI: text at 1280 × 720
game.uiViewport = letterbox(window.width(), window.height(), game.screen.viewSize, false);
game.uiViewport.apply();
scenes.drawUi(alpha);
scenes.drawFade(*batch, game.screen.matrix(), game.screen.viewSize);
});
There is only one scene in this chapter, MapScene.
main creates the SpriteBatch, a TileRenderer, the fonts, the character sheet and the village, puts references to the long-lived ones into a Game struct, and pushes a MapScene that owns its Tilemap.
Chapter 34 adds more maps and switches between them with the scene manager, which is why the map lives in the scene and the GPU objects in Game.
33.3 The tileset
All tiles come from one atlas, generated like the other games' art by a Python script of mine (not part of the download):
The positions are in tiles.atlas, the engine's atlas format from chapter 25, read by SpriteSheet::loadAtlas unchanged: lines like sprite grass 1 1 16 16, and two clips for the animated water, clip water 2 loop water0 water1 and the same for the shore.
Every tile has a 1-pixel border copied from its own edge (extruded), as chapter 25 recommended for tiles.
What the atlas can't say is what a tile is: whether you can walk through it, and whether it moves.
That goes into a second, hand-written file, tiles.tileset, which also gives every tile the one character that stands for it in a map:
# タイルの種類:マップの格子の1文字 → アトラスのスプライト、固いか、動くか
# Tile kinds: one character of a map grid → a sprite in the atlas, solid or not, animated or not
# tile <文字 / char> <スプライト / sprite> [solid] [anim <clip>]
# '.' はどの層でも「空」 / '.' means "empty" in every layer
atlas tiles.atlas
# 地面 / ground
tile , grass
tile ; grass2
tile = path
tile : path2
tile o cobble
tile ~ water0 solid anim water
tile ^ shore0 solid anim shore
tile H bridge
The file goes on the same way for the floors and walls of interiors, the decoration (T tree trunk, b bush, - and | fences, M W d house walls, windows and doors, A and L roof and eaves, furniture, crates and barrels) and the two tiles that are drawn above the characters, t (tree crown) and a (roof ridge).
Solidity and animation are properties of the tile kind, not of a place on the map: a T is a solid tree trunk in every map that uses this tileset, and making all bushes walkable is one word in one file (challenge 2).
Each tile line becomes a TileKind:
// タイルの種類(.tilesetの「tile」の1行) / a tile kind (one "tile" line of the .tileset)
struct TileKind {
char symbol = '.'; // マップの格子で使う文字 / the character used in map grids
std::string name; // アトラスのスプライト名 / the sprite's name in the atlas
int sprite = -1; // SpriteSheetの番号 / SpriteSheet index
bool solid = false; // 通れない / blocks movement
const AnimationClip *anim = nullptr; // 動くタイル(水)。nullptr = 動かない / animated tile (water); nullptr = still
};
Tileset keeps the kinds in a vector and a 128-entry table from ASCII character to kind index (−1 for none), so looking up a map character is one array access.
The sprite name and the clip name are resolved once, while loading: an unknown sprite is an error with the file and line, not a missing tile later.
The anim pointer points into the atlas's own clip list, which is safe because SpriteSheet keeps its clips in a std::deque whose elements stay where they are when the sheet is moved.
33.4 The map file
A format you can see
Here is the start of village.map:
map village
tileset ../tiles.tileset
size 40 28
layer ground
,,,,,,,,,,,,,,,,,,,;,,,,,,,;;,,,,,,,,,;,
,,,;;,,,,,;,;,,,,,,,,,,;,,,;,;,,,,,,,,;;
,,,,,,,,,;,,,;,,,,,,,,,,,^^,,,,,,,,;,,,,
A map is a few commands, one per line, and every layer is a grid of characters: size rows of width characters, one character per tile, with . meaning "empty" in every layer.
tileset is relative to the map file, so maps in assets/maps/ share assets/tiles.tileset.
Open the file in any text editor and you see the village: here the top of the ground layer, mostly grass (, and the darker ;), and the top of the river (^, the shore) on the right.
The decor layer shows it better:
layer decor
........................................
TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
b......................................b
T...........s.........b............b...T
b......................................b
T.............AAAAAAA..................T
b.b..LLLLL....LLLLLLL...s....LLLLLX....b
T...UMWdWMX..SMWMdMWM......bXMWdWMU..%.T
The row of T is the forest's tree trunks along the top; the three houses are the L eaves and the walls below them, M for wall, W for window and d for a door you can't enter (the enterable D is already in the tileset; chapter 34 puts it to use).
The wider house in the middle has one more roof row, A.
Objects come last, as flat key=value pairs: object spawn start 7 9 face=down puts the spawn point named start at column 7, row 9, facing down.
Chapter 34 uses the same kind of line for doors, with key=value pairs that name the map and the spawn point on the other side.
Why not JSON
We wrote a JSON parser for glTF in chapter 13 (and the author has a blog post about writing one), so why another format?
Because a map is meant to be edited by hand, and JSON is bad at grids.
The JSON maps of Tiled, the most common map editor (its .tmj files), store each layer as a flat array of numbers, [17, 17, 17, 23, …]: fine for a tool to write, impossible to read as a picture, and painful to change by hand.
Our objects are flat lists of key=value pairs with no nesting, so JSON's one strength, structure, buys nothing.
A line-based format parses with std::getline and std::istringstream in about 150 lines, without a library.
Real projects usually draw their maps in Tiled and export TMX or TMJ; Tiled can also store layers as CSV, which our grid loop could read with small changes.
Reading it
Tilemap::load reads the file line by line and looks at the first word.
Comments (#) and blank lines are skipped, and a trailing \r is removed, so a map saved with Windows line endings reads the same.
A layer line is followed by exactly height grid lines, read right there:
} else if (command == "layer") {
if (!map.tiles || map.cols == 0) return fail("layerの前にtilesetとsizeが要る / tileset and size must come first");
TileLayer layer;
in >> layer.name;
std::string flag;
while (in >> flag) {
if (flag == "above") layer.above = true;
else return fail("知らない印 / unknown flag: " + flag);
}
layer.cells.assign(static_cast<size_t>(map.cols * map.rows), -1);
// 続くrows行が格子。1文字が1マス / the next `rows` lines are the grid, one character per cell
for (int row = 0; row < map.rows; ++row) {
if (!std::getline(lines, line)) return fail("格子の行が足りない / the grid has too few rows");
++number;
if (!line.empty() && line.back() == '\r') line.pop_back();
if (static_cast<int>(line.size()) != map.cols)
return fail("格子の行の長さが" + std::to_string(line.size()) + "(" + std::to_string(map.cols) +
"のはず) / grid row has " + std::to_string(line.size()) + " characters (expected " +
std::to_string(map.cols) + ")");
for (int col = 0; col < map.cols; ++col) {
char c = line[static_cast<size_t>(col)];
if (c == '.') continue;
int kind = map.tiles->kindIndex(c);
if (kind < 0) return fail(std::string("タイルセットにない文字 / character not in the tileset: '") + c + "'");
layer.cells[static_cast<size_t>(row * map.cols + col)] = kind;
}
}
map.tileLayers.push_back(std::move(layer));
A layer stores kind indices, row by row (row * width + col), with −1 for empty cells; the characters are gone after loading.
Every error goes through fail, which prints file:line: message and makes the load return std::nullopt.
That form is what compilers print, so most editors and IDEs let you click it and jump to the line.
A row that is one character short, or a character the tileset doesn't know, is reported with its line number instead of producing a strange map.
The order of the lines matters in one place.
A layer is read with the size and the tileset that are current at its layer line: its cell array has width × height entries, and its numbers are indices into that tileset's kinds.
A size or tileset line after the first layer would leave the layers already read with the wrong size, or with indices into a different tileset, and the code that merges the solidity grid (next) and builds the vertex buffer would then read and write outside its arrays.
So the loader refuses both once a layer exists, with a check in front of the tileset and size branches:
} else if ((command == "tileset" || command == "size") && !map.tileLayers.empty()) {
// 読んだ層は今の大きさとタイルセットの番号で出来ている:後から変えると層が合わなくなる
// The layers already read use the current size and the tileset's kind numbers: changing them later would not
// match those layers
return fail(command + "はlayerより前に書く / " + command + " must come before the first layer");
A size 20 14 put in front of layer decor gives:
games/rpg/assets/maps/village.map:38: sizeはlayerより前に書く / size must come before the first layer
One solidity grid
After the last line, the solid tiles of all layers are merged into one grid:
// 固さを一枚にまとめる:どれかの層の固いタイルがあれば通れない / combine solidity into one grid: a solid tile in any
// layer blocks the cell
map.solid.assign(static_cast<size_t>(map.cols * map.rows), false);
for (const TileLayer &layer : map.tileLayers)
for (size_t i = 0; i < layer.cells.size(); ++i)
if (layer.cells[i] >= 0 && map.tiles->kind(layer.cells[i]).solid) map.solid[i] = true;
return map;
A cell is solid if the tile in any layer is solid: water in the ground layer, a trunk in decor.
Movement never asks about layers again, only about cells:
bool Tilemap::solidAt(int col, int row) const {
if (col < 0 || row < 0 || col >= cols || row >= rows) return true;
return solid[static_cast<size_t>(row * cols + col)];
}
Outside the map counts as solid, so there is no separate code that keeps the hero on the map: the edge is just another wall.
In the village 308 of the 1120 cells are solid.
33.5 Three layers
The format allows any number of layers; the village uses three, by convention:
- ground: grass, path, cobbles, water, the bridge; every cell is filled
- decor: things that stand on the ground and are drawn below the characters: trunks, bushes, rocks, fences, house walls, furniture, barrels
- overlay, marked
above: things drawn after the characters: tree crowns and roof ridges
A tree is two tiles: the trunk T in decor, solid, and the crown t in overlay, directly above it and not solid.
Here are the first rows of the overlay layer; the crowns sit on top of the trunk row of the decor excerpt above, and the a ridges on top of the roofs:
layer overlay above
tttttttttttttttttttttttttttttttttttttttt
........................................
t......................................t
........................................
t.............aaaaaaa..................t
.....aaaaa...................aaaaa......
So the hero can walk into the crown's cell and disappears behind the tree, while the trunk stops him:
(The image shows the hero 6 pixels to the side of the crown; a 16-pixel crown hides a 16-pixel hero completely, which is correct but makes a poor screenshot.)
Houses work the same way: the ridge row is overlay, the eaves and walls are solid decor.
Why is "decor, then characters, then overlay" always the right order?
Every decor object is at most one tile tall, and a character can't stand inside a solid tile.
A hero standing below a barrel overlaps the barrel's cell with his head and should be in front of it, and he is, because he's drawn after decor.
A hero standing above a barrel has his feet above the barrel's cell, and his picture extends upward, so the two never overlap.
Taller things are split into a solid bottom in decor and a walkable top in overlay, and the overlay covers exactly the characters standing behind.
Among the characters themselves the order is the classic Y-sort: the one whose feet are lower on the screen is nearer, which the batch does with SpriteSort::Layer and layer = feet y (only the hero today; the villagers of chapter 35 need it).
33.6 Drawing the tiles from a static buffer
Why not the sprite batch
The simplest way to draw the map is to hand every tile to the SpriteBatch as a sprite.
It works, and it's what the batch is for, but look at what happens each frame: the CPU computes four corners for each of the 1449 tiles, writes 1449 × 4 = 5796 vertices of 20 bytes, 115 920 bytes, into the batch's dynamic buffer, and the driver copies them to the GPU.
At 60 frames per second that's about 7 MB per second of data that is the same every frame.
The tiles never move; only the camera does, and the camera is one matrix uniform.
So the map's vertices are built once, when the map is loaded, into a buffer that is never written again.
The camera matrix moves them on the GPU, exactly as the 3D models since chapter 14 sat in static buffers while the camera flew around them.
Building the buffer
TileRenderer::build walks the layers in file order and, inside each layer, the rows from top to bottom and the columns from left to right:
void TileRenderer::build(const Tilemap &m) {
map = &m;
const SpriteSheet &sheet = m.tileset().sheet();
std::vector<SpriteVertex> data;
layers.clear();
int maxLayerQuads = 0;
for (const TileLayer &tl : m.layers()) {
Layer layer;
layer.firstQuad = static_cast<int>(data.size() / 4);
layer.rowStart.reserve(static_cast<size_t>(m.height() + 1));
for (int row = 0; row < m.height(); ++row) {
layer.rowStart.push_back(static_cast<int>(data.size() / 4) - layer.firstQuad);
for (int col = 0; col < m.width(); ++col) {
int k = tl.cells[static_cast<size_t>(row * m.width() + col)];
if (k < 0) continue; // 空のマスは四角形を作らない / empty cells make no quad
const TileKind &kind = m.tileset().kind(k);
Vec2 p = {kTile * static_cast<float>(col), kTile * static_cast<float>(row)};
if (kind.anim) {
// 動くタイルはバッファに入れず、毎フレームバッチで描く / animated tiles stay out of the buffer and are drawn
// through the batch every frame
layer.animated.push_back({p, &kind, row});
continue;
}
Rect uv = sheet.uv(kind.sprite);
// 左上・右上・右下・左下(SpriteBatchと同じ順:添字 0-1-2 2-3-0) / top left, top right, bottom right,
// bottom left (the SpriteBatch's order: indices 0-1-2 2-3-0)
data.push_back({p, {uv.left(), uv.top()}, 0xFFFFFFFFu});
data.push_back({{p.x + kTile, p.y}, {uv.right(), uv.top()}, 0xFFFFFFFFu});
data.push_back({{p.x + kTile, p.y + kTile}, {uv.right(), uv.bottom()}, 0xFFFFFFFFu});
data.push_back({{p.x, p.y + kTile}, {uv.left(), uv.bottom()}, 0xFFFFFFFFu});
}
}
layer.rowStart.push_back(static_cast<int>(data.size() / 4) - layer.firstQuad);
maxLayerQuads = std::max(maxLayerQuads, layer.rowStart.back());
layers.push_back(std::move(layer));
}
// 添字は一番大きい層の分だけ:どの範囲もbaseVertexで頂点をずらして同じ添字0, 1, 2, 2, 3, 0, 4…を使う
// Indices only for the largest layer: every range reuses the same indices 0, 1, 2, 2, 3, 0, 4... with baseVertex
// shifting the vertices
std::vector<std::uint32_t> quadIndices;
quadIndices.reserve(static_cast<size_t>(std::max(1, maxLayerQuads)) * 6);
for (std::uint32_t q = 0; q < static_cast<std::uint32_t>(std::max(1, maxLayerQuads)); ++q)
for (std::uint32_t i : {0u, 1u, 2u, 2u, 3u, 0u}) quadIndices.push_back(4 * q + i);
if (data.empty()) data.resize(4); // 空のバッファは作れない / zero-size storage is not allowed
// 不変のストレージ(フラグ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());
frameStats.totalQuads = static_cast<int>(data.size() / 4);
}
Three details matter here.
- Empty cells make no quad. The decor layer has 848 empty cells of 1120 and the overlay 989, so the three layers hold 1046 + 272 + 131 = 1449 quads instead of 3 × 1120 = 3360.
- Animated tiles are left out and listed separately (section 33.7). The ground layer has 1120 cells, 74 of them water or shore, so it holds 1046 quads.
rowStart[r]records, for each layer, the first quad of row r, counted inside the layer, plus one entry past the last row. Row r of a layer is the quadsrowStart[r]up torowStart[r + 1].
The vertices use the SpriteVertex layout of the batch (position, UV, an RGBA8 color, 20 bytes), and TileRenderer::create loads the engine's own sprite.vert and sprite.frag and sets up a VAO with the same attribute format, so a tile drawn from the static buffer gives exactly the pixels it would give through the batch.
One program serves two VAOs.
Immutable storage, once more
Buffer is the class from chapter 4, and its third argument goes straight to glNamedBufferStorage(buffer, size, data, flags) from chapter 3.
With flags = 0 the storage is created with its contents and can never change: no glNamedBufferSubData (that needs GL_DYNAMIC_STORAGE_BIT, which the batch uses), no mapping (the batch's persistent mode needs GL_MAP_WRITE_BIT and friends).
In return the driver knows the data will never be written by the CPU and can put it wherever the GPU reads fastest.
The old way to say the same thing is glBufferData(…, GL_STATIC_DRAW), which is only a hint; immutable storage with no flags is a promise.
Two consequences show up in the code.
Storage can't be zero bytes (glNamedBufferStorage with size 0 is GL_INVALID_VALUE), so a map with no still tiles gets one dummy quad that is never drawn.
And storage can't be resized or given again (a second glNamedBufferStorage on the same buffer is GL_INVALID_OPERATION), so when the map changes, R reloads it or chapter 34 walks through a door, build creates new Buffer objects; the move assignment deletes the old ones.
The VAO stays, but it still points at the old buffer names, so glVertexArrayVertexBuffer and glVertexArrayElementBuffer attach the new ones.
Forgetting those two lines is the classic mistake: the VAO would draw from a deleted buffer.
The vertex buffer is 115 920 bytes.
The index buffer holds the usual 0 1 2 2 3 0 pattern, but only for the largest layer, 1046 quads, which is 6276 indices or 25 104 bytes.
Why that is enough is the next part.
Row culling and glDrawElementsBaseVertex
The camera sees a horizontal band of the map, 180 pixels high, which touches 12 rows, or 13 when the top of the view is 13 to 15 pixels into a row (for a top at 13, ).
Because every layer is stored row by row, the visible rows of a layer are one contiguous range of quads: from rowStart[r0] to rowStart[r1].
For the frame of the culling screenshot below, rows 5 to 16 are visible, and the three ranges are:
Each range is one draw call:
// visibleが触れる行の範囲 [r0, r1) / the range of rows [r0, r1) that `visible` touches
static std::pair<int, int> visibleRows(const Rect &visible, int rows) {
int r0 = static_cast<int>(std::floor(visible.top() / kTile));
int r1 = static_cast<int>(std::ceil(visible.bottom() / kTile));
return {std::clamp(r0, 0, rows), std::clamp(r1, 0, rows)};
}
void TileRenderer::drawLayer(int index, const Mat4 &viewProjection, const Rect &visible) {
if (!map || index < 0 || index >= static_cast<int>(layers.size())) return;
const Layer &layer = layers[static_cast<size_t>(index)];
auto [r0, r1] = visibleRows(visible, map->height());
int first = layer.rowStart[static_cast<size_t>(r0)], count = layer.rowStart[static_cast<size_t>(r1)] - first;
if (count <= 0) return;
shader->use();
shader->set("uViewProjection", viewProjection);
map->tileset().sheet().texture().bind(0);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // 乗算済みアルファ(loadSpriteTexture) / premultiplied alpha
glBindVertexArray(vao);
// 行は続けて並んでいるので、見える行は一続きの範囲:添字は0から、頂点はbaseVertexだけずらす
// Rows are stored one after another, so the visible rows are one contiguous range: indices start at 0, vertices are
// shifted by baseVertex
glDrawElementsBaseVertex(GL_TRIANGLES, count * 6, GL_UNSIGNED_INT, nullptr, (layer.firstQuad + first) * 4);
glBindVertexArray(0);
frameStats.quads += count;
++frameStats.drawCalls;
}
glDrawElementsBaseVertex(mode, count, type, indices, basevertex) came up in chapter 25, where the batch used it to draw from the middle of its ring buffer; here it does the same job for a static buffer:
mode:GL_TRIANGLES, two triangles per quad.count: the number of indices, so quads × 6. For the ground in the frame above, 460 quads give 2760.type:GL_UNSIGNED_INT, matching thestd::uint32_tindices.indices: a byte offset into the element buffer, herenullptr= 0: every draw starts at the first index.basevertex: a number added to every index before the vertex is fetched. The range starts at quadfirstQuad + first, which is vertex(firstQuad + first) × 4: 776 for the ground, (1046 + 49) × 4 = 4380 for decor, (1318 + 51) × 4 = 5476 for the overlay.
So index 0 of every draw lands on the first vertex of its range, index 6 on the fifth vertex, and so on: the same small index buffer serves every range of every layer.
It has to be as long as the longest range ever drawn, and no range is longer than its whole layer, hence "the largest layer".
The usual mistakes are units: count in quads instead of indices draws a sixth of the tiles, basevertex in quads instead of vertices draws the wrong tiles, and a byte offset in indices where you meant an index count reads garbage.
An index plus basevertex past the end of the buffer reads outside it, which is undefined behavior, so the rowStart arithmetic has to be right.
Three layers, three draw calls, for all still tiles of the screen.
Here is the culling made visible: Z zooms the view out to half size but keeps the culling of the real camera, the yellow rectangle:
Only rows 5 to 16 exist, but they exist across the whole width of the map: columns outside the view are still sent to the GPU, which clips them.
That's the compromise of row culling: a column range inside a band of rows is not contiguous in the buffer (each row contributes its own slice), so culling columns too would take one draw per row, or a different layout (chunks, challenge 4).
For a map 40 tiles wide and a view 20 tiles wide, half the quads drawn are off-screen, which costs a little vertex work and no fragment work.
In the screenshot 460 + 122 + 24 = 606 of the 1449 quads are drawn; over every camera position in the village the number goes from 544 to 691 (691 only at the very top, where 13 rows include the full forest row), about 590 on average.
The animated tiles, the water, are culled per tile against the rectangle, in columns as well as rows; that's the other half of the renderer (here the river happens to run inside the rectangle's columns, so it ends at the same rows as everything else).
(The zoomed view draws one art pixel as half a canvas pixel, so every other pixel row and column of the art disappears; it's a debug view, not a zoom for players.)
33.7 Animated tiles through the batch
Water and shore tiles have anim water or anim shore in the tileset, two frames at 2 frames per second.
A static buffer can't change its UVs, so build leaves those cells out and records their position, kind and row in layer.animated.
Each frame, right after drawing a layer's still tiles, the scene draws that layer's animated tiles through the SpriteBatch:
void TileRenderer::drawAnimated(SpriteBatch &batch, int index, const Rect &visible, float time, float spriteLayer) const {
if (!map || index < 0 || index >= static_cast<int>(layers.size())) return;
const SpriteSheet &sheet = map->tileset().sheet();
for (const Animated &a : layers[static_cast<size_t>(index)].animated) {
if (a.position.y + kTile <= visible.top() || a.position.y >= visible.bottom() || a.position.x + kTile <= visible.left() ||
a.position.x >= visible.right())
continue;
const AnimationClip &clip = *a.kind->anim;
size_t frame = static_cast<size_t>(time * clip.fps) % clip.frames.size();
Sprite s = sheet.sprite(clip.frames[frame], a.position);
s.layer = spriteLayer;
batch.draw(s);
}
}
The frame comes straight from the scene's time, so all water tiles change together, and no per-tile state is needed.
Why does this split work?
- The two parts never overlap. A cell is either in the static buffer or in the animated list, never both, and tiles of one layer never overlap each other (each fills its own 16 × 16 square). So drawing a layer as "still tiles, then animated tiles" gives the same picture as drawing all its tiles in any order.
- The order between layers is kept. The scene calls
batch.end()for the animated tiles of layer before it draws the still tiles of layer , so water is always under the decor and the characters. - The pixels are identical. Both paths use the same program, the same vertex layout, the same atlas texture and the same premultiplied blending, so a water tile looks exactly as if it were in the buffer.
- The cost is small. The village has 74 animated tiles in all, and only the visible ones are sent: at most a few dozen sprites per frame, one batch draw call, instead of 1449.
The general rule: put what never changes into static buffers and stream only what does.
Two other ways to animate tiles, both reasonable for bigger maps: give the animated quads their own small buffer with GL_DYNAMIC_STORAGE_BIT and rewrite only their UVs with glNamedBufferSubData when the frame changes (twice a second here), or animate in the vertex shader, with a frame count per vertex and a time uniform that offsets the UV.
33.8 Moving around
Free movement, a foot box
There are two classic ways to move in a top-down RPG.
Grid movement (Pokémon, Dragon Quest) moves the hero one whole tile per step and only asks solidAt about the target cell.
Free movement (Zelda: A Link to the Past, Stardew Valley) moves him by a few pixels every update in any direction, with box collision.
We use free movement: the engine's moveAndSlide from chapter 26 already slides along walls, the same boxes will collide with villagers and doors in the next two chapters, and it feels more modern.
Grid movement is challenge 5.
The collision box is not the picture.
It's a 10 × 6 box at the feet, and the 16 × 16 picture is drawn with its origin at (0.5, 1), the middle of its bottom edge, on the bottom center of the box:
Only the feet collide, so the head may overlap the tile above: the hero can stand right below a wall or a barrel and look like he is in front of it, the classic top-down look.
The box is narrower than a tile, 10 of 16 pixels, which leaves 6 pixels of slack in a one-tile gap.
placeAt puts a character into a cell with the box centered and the feet on the cell's bottom edge: for the spawn cell (7, 9) the box is (115, 154, 10, 6) and the feet are at (120, 160).
moveOnMap
Every update the scene reads the two axes, normalizes the direction so diagonals aren't faster (a unit vector, linear algebra chapter 3), and moves the box:
// 主人公:自由に動く(マス目に縛られない)。斜めは正規化して同じ速さ / the hero moves freely (not locked to the
// grid); diagonals are normalized to the same speed
hero.beginStep();
Vec2 move = {in.axis("left", "right"), in.axis("up", "down")};
hero.moving = move.x != 0.0f || move.y != 0.0f;
if (hero.moving) {
hero.facing = facingFor(move, hero.facing);
float speed = in.actionHeld("run") ? kRunSpeed : kWalkSpeed;
moveOnMap(hero.box, normalize(move) * (speed * dt), map, {}, scratch);
}
hero.anim.speed = in.actionHeld("run") ? 1.5f : 1.0f;
hero.animate(g.characters, dt);
Walking is 72 px/s, 4.5 tiles per second or 1.2 pixels per 1/60 s update; running with Shift is 120 px/s, 2 pixels per update.
Diagonally each axis gets px/s.
Both are far below the 6-pixel box height per update, so the box can't tunnel through a tile (chapter 26's challenge 6 showed what happens otherwise).
facingFor keeps the current facing as long as its key is still held, so walking diagonally doesn't make the picture flicker between two directions, and the walk animation plays 1.5 times faster while running.
beginStep saves the box position for interpolation, as in chapter 26.
moveOnMap is where the map meets the engine's collision:
MoveResult moveOnMap(Rect &box, Vec2 delta, const Tilemap &map, std::span<const Rect> extra, std::vector<Rect> &scratch) {
constexpr float kAssist = 6.0f; // 何ピクセルまでの引っかかりを回り込むか / how many pixels of overlap to slide round
// 動く範囲(+回り込みの分)に触れる固いマスだけを集める / collect only the solid cells near the move (+ the assist)
Rect area = {std::min(box.x, box.x + delta.x) - kAssist, std::min(box.y, box.y + delta.y) - kAssist,
box.w + std::abs(delta.x) + 2.0f * kAssist, box.h + std::abs(delta.y) + 2.0f * kAssist};
scratch.clear();
map.solidRects(area, scratch);
scratch.insert(scratch.end(), extra.begin(), extra.end());
MoveResult result = moveAndSlide(box, delta, scratch);
// 角の回り込み:一方向だけに歩いて止まったとき、横にdずらせば進めるなら、少しずつずらす(Zelda風)
// Corner assist: when walking in one direction only and stopped, if shifting sideways by d would free the way, shift
// a little each step (Zelda-style)
bool alongX = delta.x != 0.0f && delta.y == 0.0f && result.hitX;
bool alongY = delta.y != 0.0f && delta.x == 0.0f && result.hitY;
if (!alongX && !alongY) return result;
float speed = std::abs(alongX ? delta.x : delta.y);
Vec2 forward = alongX ? Vec2{delta.x > 0.0f ? 1.0f : -1.0f, 0.0f} : Vec2{0.0f, delta.y > 0.0f ? 1.0f : -1.0f};
Vec2 side = alongX ? Vec2{0.0f, 1.0f} : Vec2{1.0f, 0.0f};
for (float d = 1.0f; d <= kAssist; d += 1.0f)
for (float sign : {-1.0f, 1.0f}) {
Rect shifted = box.translated(side * (sign * d));
if (blocked(shifted, scratch) || blocked(shifted.translated(forward), scratch)) continue;
moveAndSlide(box, side * (sign * std::min(d, speed)), scratch);
return result;
}
return result;
}
moveAndSlide wants a list of solid boxes, and the map has 308 solid cells.
Building a Rect for each of them every update would work and would be silly: only the cells near the move can be hit.
solidRects(area, out) turns just the solid cells that touch area into boxes; area is the box, stretched by the move and grown by 6 pixels on every side for the corner assist.
For a box at (21, 26) moving 1.2 pixels to the right that's x from 15 to 38.2 and y from 20 to 38, columns 0 to 2 and rows 1 to 2: 6 cells checked, as in the right half of the picture.
scratch is a vector kept in the scene so the update doesn't allocate, and extra takes other boxes (the villagers of chapter 35); today it's empty.
The corner assist
Free movement has one annoying property in a tile world: openings are exactly one tile wide, and the box has to be lined up within 6 pixels to get through.
Walk up toward the gap in a fence while 4 pixels too far left, and the corner of the fence stops you dead.
The corner assist helps exactly there.
When the move was along one axis only and that axis was blocked, it tries shifting the box sideways by 1, 2, … 6 pixels, in both directions, and checks whether the shifted box is free and free one pixel further forward.
The first shift that works is taken, but only by min(d, speed), the walking distance of one update, so the hero glides around the corner instead of jumping:
In the left case the shift of 4 is found and the box moves 1.2 pixels; in the next updates the overlap is 2.8 and then 1.6 pixels, the smallest freeing shifts are 3 and 2, and it moves 1.2 again each time; at an overlap of 0.4 the shift of 1 is enough and it moves by 1.
That's x = 13.2, 14.4, 15.6 and 16.6 in four updates, 67 ms, and then the box walks up into the gap without the player doing anything but holding Up.
7 pixels off is more than the assist's 6, so nothing happens: you really are walking into the fence.
The assist only runs for straight moves; a diagonal already slides along the wall by itself.
Zelda: A Link to the Past does the same, and players don't notice it, they only notice when a game doesn't.
Drawing the character
CharacterSheet loads characters.png as a 16 × 16 grid (1-pixel margin and spacing) with nine columns per character: standing, step A and step B, facing down, up and to the side.
It adds an idle clip and a walk clip per character and direction with addClip; the walk is step A, stand, step B, stand at 8 frames per second, two steps in 0.5 seconds.
The side frames face right, and flipX turns them left.
The sprite itself:
Sprite Character::sprite(const CharacterSheet &sheet, float alpha) const {
Vec2 f = feet(alpha);
// まだクリップがない(最初のanimateの前)とframe()は-1:そのままではシートの外を読むので、立ちのコマを使う
// Without a clip yet (before the first animate) frame() is -1, which would read outside the sheet: use the standing
// frame instead
int frame = anim.frame();
if (frame < 0) frame = sheet.idle(look, facing)->frames.front();
// 整数のピクセルに丸める(カメラも同じ丸め方:人物とタイルの相対位置が揺れない) / round to whole pixels (the camera
// rounds the same way: characters and tiles never wobble against each other)
Sprite s = sheet.sheet().sprite(frame, {std::round(f.x), std::round(f.y)}, {0.5f, 1.0f});
s.flipX = facing == Facing::Left;
s.layer = f.y; // 下にいる人ほど手前(Y順) / the lower on screen, the nearer (Y-sorting)
return s;
}
feet(alpha) interpolates between the box position of the previous update and the current one, as chapter 26 taught, and adds (5, 6) to get the bottom center of the box.
Why the rounding, and why it must match the camera, is the next section.
The two lines with frame guard a moment that really happens.
A scene is drawn once before its first update: the scene manager calls enter() when it applies the push at the end of an update step, and the frame is drawn right after that.
At that point the Animator has never been given a clip, and frame() returns −1, "no frame".
The engine's SpriteSheet::sprite doesn't check its index, so −1 reads the rectangle in front of the start of the sheet's array: memory that isn't ours (AddressSanitizer reports it as a heap-buffer-overflow in SpriteSheet::pixels).
So spawn() ends with hero.animate(g.characters, 0.0f), which picks the standing clip for the spawn's facing without advancing time, and the guard falls back to the standing frame for any character that is drawn before its first animate.
33.9 The camera
The camera follows a point 6 pixels above the feet, the middle of the body, and stops at the map's edges:
Camera2D MapScene::followCamera(Vec2 target) const {
Vec2 size = map.pixelSize(), half = 0.5f * kView;
Vec2 c;
c.x = size.x <= kView.x ? 0.5f * size.x : std::clamp(target.x, half.x, size.x - half.x);
c.y = size.y <= kView.y ? 0.5f * size.y : std::clamp(target.y, half.y, size.y - half.y);
// 中心を整数に丸める:タイルがいつもピクセルの格子に乗る(主人公の絵も同じ丸め方) / round the center to whole pixels:
// tiles always sit on the pixel grid (the hero's picture is rounded the same way)
return {.viewSize = kView, .centre = {std::round(c.x), std::round(c.y)}};
}
void MapScene::draw(float alpha) {
// 足元の少し上(体の真ん中)を追う / follow a point a little above the feet (the middle of the body)
Vec2 feet = hero.feet(alpha);
Camera2D camera = followCamera({feet.x, feet.y - 6.0f});
Rect visible = camera.visibleRect();
A center closer than half a view to an edge would show the void outside the map, so each axis is clamped to .
For the 640 × 448 village and the 320 × 180 view that's x in [160, 480] and y in [90, 358].
A map smaller than the view on an axis (the house interiors of chapter 34) is centered on that axis instead.
While the camera is clamped the hero walks off-center, toward the edge, which is what every 2D game does.
camera.visibleRect() of this camera is the rectangle the culling uses; it's computed from the same camera that draws, so culling and drawing can never disagree (the Z view deliberately breaks that).
The center is rounded to whole pixels, and the hero's sprite is rounded the same way.
At the integer scale of our canvas, a fractional camera position wouldn't blur or shimmer anything: nearest sampling only shifts the picture, and something has to decide by which whole pixel.
The point is to make that decision once, the same way, for everything.
If the camera kept its fraction while the sprite was rounded in our code, the hero would be rounded twice, once by us and once by the rasterizer against the camera's fraction, and from frame to frame he could land one pixel off against the ground: a hero who twitches while the world scrolls.
Here both start from numbers with the same fractional part: the camera center is x = box.x + 5, y = feet − 6 = box.y, and the sprite is at box.x + 5, box.y + 6.
Rounded the same way, the hero and the ground move by the same whole pixels, and every tile edge sits exactly on a pixel edge, with no vertex at a half pixel where a tie rule would decide.
Chapter 25's pixelSnap does the rounding inside Camera2D::matrix; here we need the rounded center ourselves, for the culling rectangle and the HUD, so we round before building the camera.
33.10 The frame
The scene's draw puts the pieces together: still tiles and animated tiles per layer, in file order, and the characters just before the first above layer:
// 層はファイルの順に描く。「above」の層(木の上・屋根の棟)は人物の後 / layers are drawn in file order; "above"
// layers (tree tops, roof ridges) come after the characters
bool charactersDrawn = false;
const std::vector<TileLayer> &layers = map.layers();
for (int i = 0; i < static_cast<int>(layers.size()); ++i) {
if (layers[static_cast<size_t>(i)].above && !charactersDrawn) {
drawCharacters();
charactersDrawn = true;
}
if (i < static_cast<int>(layerOn.size()) && !layerOn[static_cast<size_t>(i)]) continue;
g.tiles.drawLayer(i, vp, visible);
if (g.tiles.hasAnimated(i)) {
b.begin(vp);
g.tiles.drawAnimated(b, i, visible, time);
b.end();
spriteCalls += b.stats().drawCalls;
}
}
if (!charactersDrawn) drawCharacters();
drawCharacters is a batch with SpriteSort::Layer holding the hero.
The characters are drawn before the above test skips a hidden layer, so hiding the overlay with 3 still draws the hero.
In a normal frame that's 3 tile draw calls plus 2 batch draw calls, one for the visible water and one for the hero, which the HUD shows as draw calls: tiles 3 + sprites 2 (sprites 1 when no water is in view).
With B a third batch draws the outlines: the solid cells near the view in red, from the same solidRects, and the interpolated foot box in green.
33.11 Debug keys and reloading
The keys 1, 2, 3, B, Z and H are all one-line toggles in update, and you've seen what they show.
R is the one that changes how you work:
if (in.pressed(GLFW_KEY_R)) {
// ファイルから読み直す(テキストエディターで直してすぐ確かめる)。失敗したら今のマップのまま
// Reload from the file (edit in a text editor, check at once). On failure the current map stays
if (std::optional<Tilemap> fresh = Tilemap::load(map.path())) {
map = std::move(*fresh);
g.tiles.build(map);
printf("%s: 読み直した / reloaded\n", map.path().c_str());
}
}
Keep the game running, edit village.map in your editor, save, press R, and the village changes, no rebuild.
The tileset is reloaded with the map, so the same works for tiles.tileset.
Because load returns std::nullopt on any error, a broken file leaves the current map in place and prints where the problem is.
Putting an & into row 9 of the decor layer, a character the tileset doesn't know, gives:
games/rpg/assets/maps/village.map:48: タイルセットにない文字 / character not in the tileset: '&'
Line 48 is that grid row; fix it, press R again, and the reload goes through with games/rpg/assets/maps/village.map: 読み直した / reloaded.
Two things to keep in mind when editing by hand: a grid row must be exactly width characters, so a tab or a trailing space is reported as a row that's too long, and the layers of a map should be aligned with each other (a crown in overlay right above its trunk in decor).
The village itself was written by a script of mine only to keep trees and roofs aligned across the layers; from here on, the file is the source.
33.12 Running it
From the project root:
cmake -S . -B build
cmake --build build -j8
./build/games/rpg/rpg
In Visual Studio, choose rpg as the startup project (it's build\games\rpg\Debug\rpg.exe) and press F5; the working directory is already the project root.
The top bar of the HUD shows the map and its size, the hero's tile, the visible rows, the still tile quads drawn and the total, and the draw calls.
Walking from the top of the village to the bottom, the visible rows go from 0–11 to 16–27 and the quad count moves between 544 and 691, while the tile draw calls stay at 3.
No stderr line may say "character not in the font" or show a GL debug message.
33.13 Platform notes
- Windows (Visual Studio): the sources contain Japanese strings (the error messages, the HUD's 終了). MSVC needs
/utf-8to keep them as UTF-8; the project's CMake sets it for MSVC, so there's nothing to do. - Windows: maps edited with Notepad or Visual Studio end their lines with
\r\n. The loader strips the\r, otherwise every grid row would be one character too long. Git'score.autocrlfmay also convert the files on checkout; both endings work. - All: some editors add or remove a final newline, or trim trailing spaces; both are harmless here. Editors that turn spaces into tabs don't matter either, since a grid uses no spaces, but an editor that wraps long lines would break the grid, so turn soft wrapping off or make the window wider than 40 columns.
- Linux, FreeBSD: run from the project root (
./build/games/rpg/rpg); started from anywhere else, every load fails, and the map's message asks "running from the project root?".
33.14 How real engines do it
- Map editors: Tiled (TMX as XML, TMJ as JSON, layers optionally as CSV) and LDtk are the common free editors; engines import their files or have their own editor (Godot's TileMap layers, Unity's Tilemap with its Tile Palette). Tile properties such as "solid" live in the tileset there too, as custom properties or physics shapes per tile.
- Chunks: instead of whole rows, big maps are split into chunks (for example 16 × 16 tiles), each with its own static mesh or its own range in one buffer, and only the chunks that touch the view are drawn. That culls in both directions at the cost of a few more draw calls (challenge 4). Unity's Tilemap Renderer has a chunk mode, and Godot groups the cells of a TileMapLayer into rendering quadrants for the same reason.
- Tilemap shaders: a whole layer can be drawn with one screen-sized quad. The layer's tile indices go into a small integer texture (one texel per cell,
R16UI), and the fragment shader finds the cell under each pixel, reads its index withtexelFetchand samples the atlas (or aGL_TEXTURE_2D_ARRAYof tiles) at that tile's UV. Changing a tile is then one texel upload (challenge 7). GLSL chapter 11 covers the sampling. - Instancing: one quad drawn once per tile with a per-instance tile index, the technique of chapter 19. It saves memory (a few bytes per tile instead of 80), and the instance range can be culled by rows just like ours.
- Movement: almost every free-moving top-down game has some form of corner assist and a collision box smaller than the sprite; grid games keep a "moving to cell" state and lerp between cells.
33.15 Summary
- Map format: our own line-based text,
map,tileset,size,layer <name> [above]followed by a grid with one character per tile (.= empty), andobject <kind> <name> <col> <row> [key=value …]. It's readable and editable as a picture, parses withgetlineandistringstream, and reports errors asfile:line: message. JSON gives nothing for grids and flat key=value objects. - Tileset:
tiles.atlas(the engine's format) says where the pictures are;tiles.tilesetmaps characters to sprites and addssolidandanim <clip>. Solidity is a property of the tile kind; one combined grid answers "is this cell solid in any layer", and outside the map is solid. - Layers: ground, decor below the characters, overlay
abovethem. Tall things are a solid bottom in decor and a walkable top in overlay, so the hero walks behind trees and roofs; characters are Y-sorted among themselves. - Static buffer: all still tiles of all layers, row by row, in one
glNamedBufferStoragebuffer with flags 0 (immutable, never written again, rebuilt as a new buffer when the map changes, with the VAO re-pointed). Village: 1449 quads, 115 920 bytes, plus 6276 indices for the largest layer. - Row culling: the visible rows of a layer are one contiguous range, drawn with one
glDrawElementsBaseVertex(count = quads × 6, basevertex = first quad × 4, indices from 0). 3 draw calls for all still tiles, 544–691 of 1449 quads per frame; off-screen columns are clipped by the GPU. - Animated tiles: left out of the buffer and drawn per visible tile through the
SpriteBatchafter their layer's still tiles; it works because the two sets never overlap, the layer order is kept, and both paths produce the same pixels. - Movement: free, with a 10 × 6 foot box,
moveAndSlideagainst only the solid cells near the move, normalized diagonals, 72 px/s walking and 120 px/s running, and a corner assist of up to 6 pixels for one-tile gaps. - Camera: follows the middle of the body, clamped to [half view, map − half view], rounded to whole pixels in the same way as the hero's sprite so they never move against each other.
- Tools: 1 2 3 layers, B boxes, Z the culling, H the HUD, R reloads the map while the game runs and keeps the old one on errors.
33.16 Challenges
- ★ Add a line
tile & stumptotiles.tileset(a second, non-solid kind using the existingstumpsprite), put a few&into the decor layer ofvillage.map, and press R in the running game. The stumps should appear without recompiling and the hero should walk through them. Doing it in the other order, the map before the tileset, should printvillage.map:N: … character not in the tileset: '&'and keep the old map. - ★ Remove
solidfrom thebushline of the tileset and reload. The hero should walk through bushes and be drawn over them (decor is below the characters), and B should no longer outline them. - ★ Print
g.tiles.stats().quadsonce a second while walking from the top of the village to the bottom and back. It should stay between 544 and 691 (the highest values only at the very top, where 13 rows are visible), and the tile draw calls should stay at 3. - ★★ Cull columns too: split every layer into 8 × 8-tile chunks, store each chunk row by row with its own
rowStarttable, and draw the visible rows of every chunk that touches the view. Over all camera positions in the village the still quads drawn should drop from 544–691 to 301–546, while the tile draw calls rise from 3 to between 14 and 34 (one per non-empty chunk range). On llvmpipe you won't see a difference; on a map of 1000 × 1000 tiles you would. - ★★ Grid movement: on a key press, move the hero exactly one tile in 0.2 s (lerp between the two cells, 80 px/s), only if
solidAtis false for the target cell, and ignore new input until the step ends. You should get Pokémon-style stepping: no corner assist needed, no diagonals, every collision a single lookup, and the hero always standing on whole tiles. - ★★ Smooth camera: instead of locking to the hero, move a camera center in
updatewithc += (target − c) · (1 − exp(−8 dt)), keep a previous value for interpolation, and still clamp and round it when drawing. The camera should lag a little behind when the hero starts and catch up when he stops (after half a second it has covered of the distance), without any jitter, because the result is still rounded the same way as the sprite. - ★★★ Draw a whole layer with one quad: upload the layer's cells as an
R16UItexture of 40 × 28 texels (kind index + 1, 0 = empty), draw one quad covering the map, and in a new fragment shader compute the cell under each fragment,texelFetchits kind, discard empty cells, and sample the atlas at that tile's UV rectangle (pass the rectangles as a uniform array). The image should be identical to the static buffer's, with 1 quad per layer, and changing a single tile should take oneglTextureSubImage2Dof one texel.
ファイル: /dev/null | b/games/rpg/CMakeLists.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,11 @@ | |||
| 1 | # 見下ろし型RPG(第33〜35章) / the top-down RPG (chapters 33-35) | ||
| 2 | add_executable(rpg | ||
| 3 | src/main.cc | ||
| 4 | src/tilemap.cc | ||
| 5 | src/tile_renderer.cc | ||
| 6 | src/character.cc | ||
| 7 | src/map_scene.cc) | ||
| 8 | target_include_directories(rpg PRIVATE src) | ||
| 9 | target_link_libraries(rpg PRIVATE engine) | ||
| 10 | enable_warnings(rpg) | ||
| 11 | set_working_directory(rpg) | ||
ファイル: /dev/null | b/games/rpg/README.md
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,22 @@ | |||
| 1 | # RPG(第33〜35章) / RPG (chapters 33-35) | ||
| 2 | |||
| 3 | 見下ろし型のRPG。プロジェクトのルートから実行する / A top-down RPG. Run it from the project root: | ||
| 4 | |||
| 5 | ```sh | ||
| 6 | ./build/games/rpg/rpg # Visual Studio: build\games\rpg\Debug\rpg.exe (working directory = the root) | ||
| 7 | ``` | ||
| 8 | |||
| 9 | | キー / Key | | | ||
| 10 | |---|---| | ||
| 11 | | 矢印 / WASD | 移動 / move | | ||
| 12 | | Shift | 走る / run | | ||
| 13 | | 1 2 3 | 層の表示(地面・飾り・上の層) / toggle the layers (ground, decor, overlay) | | ||
| 14 | | B | 当たり判定の箱 / collision boxes | | ||
| 15 | | Z | 引いて見る(行のカリングが見える) / zoom out (shows the row culling) | | ||
| 16 | | H | HUD | | ||
| 17 | | R | マップをファイルから読み直す / reload the map from its file | | ||
| 18 | | Esc | 終了 / quit | | ||
| 19 | |||
| 20 | マップは `assets/maps/*.map`(テキスト)。書式は `src/tilemap.hh`、タイルの文字は `assets/tiles.tileset`。 | ||
| 21 | Maps are `assets/maps/*.map` (text). The format is described in `src/tilemap.hh`, the tile characters in | ||
| 22 | `assets/tiles.tileset`. | ||
ファイル: /dev/null | b/games/rpg/assets/LICENSE.txt
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,9 @@ | |||
| 1 | games/rpg/assets/ のファイルはこのチュートリアルのために作者が自作したもの(作者のPythonのスクリプトで生成。スクリプトはこのプロジェクトには含まれない)。自由に使ってよい。 | ||
| 2 | The files in games/rpg/assets/ were made for this tutorial by the author (generated with the author's own Python scripts, which are not part of this project). Free to use for any purpose. | ||
| 3 | |||
| 4 | tiles.png/.atlas 16×16のタイル(草・道・水・木・家・家具…、1ピクセルの押し出し付き) / 16×16 tiles (grass, path, | ||
| 5 | water, trees, houses, furniture..., 1 px extruded) (chapter 33) | ||
| 6 | characters.png 人物5人 × 4方向の歩き(16×16、9コマずつ) / five characters × 4-direction walk (16×16, 9 frames | ||
| 7 | each) (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) | ||
ファイル: /dev/null | b/games/rpg/assets/characters.png
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/games/rpg/assets/maps/village.map
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,99 @@ | |||
| 1 | # 村 / Village | ||
| 2 | # 書式は games/rpg/src/tilemap.hh、文字の意味は ../tiles.tileset / format: games/rpg/src/tilemap.hh, | ||
| 3 | # characters: ../tiles.tileset ('.' = 空 / empty) | ||
| 4 | map village | ||
| 5 | tileset ../tiles.tileset | ||
| 6 | size 40 28 | ||
| 7 | |||
| 8 | layer ground | ||
| 9 | ,,,,,,,,,,,,,,,,,,,;,,,,,,,;;,,,,,,,,,;, | ||
| 10 | ,,,;;,,,,,;,;,,,,,,,,,,;,,,;,;,,,,,,,,;; | ||
| 11 | ,,,,,,,,,;,,,;,,,,,,,,,,,^^,,,,,,,,;,,,, | ||
| 12 | ,,;,,,,,;,,,,,;;,,,;,,,,,~~,,;;,,,,,,,,, | ||
| 13 | ;,,;,,,,,,,;;,,,,,;,,,,,;~~,,,;,,,,,;,,, | ||
| 14 | ,,,;,,,,,,,,,,,,,,,,;,,,;~~,,,,,,;,,,,,; | ||
| 15 | ,,,,,,,,,,,,,,,,,,,,,,,,,~~,,,,,,,,;;,,, | ||
| 16 | ,,,,,,,,;,,;,;,,,,,,,,;;,~~,,,,;,,,,,,,, | ||
| 17 | ,,,,,,,:,,,,,,,,,=,,,,,;,~~,,,,=,,,,,;,, | ||
| 18 | ,,,,,,,=,,,,,,,,,=,,,,,,,~~,,,,=,;,,,,;, | ||
| 19 | ,======:=============:===HH===:==:==:=== | ||
| 20 | ,====:==============:====HH==:====:===== | ||
| 21 | ,,,,,,,,,,,,,,,,;;,=,,;,,^^,,,;,,,,,,,,, | ||
| 22 | ,,,,,,,,,,,;,,,ooooooooo;~~,,,,,,,,,;,,, | ||
| 23 | ,,,==:=====,,,,ooooooooo,~~;,,,,,,,,,,,; | ||
| 24 | ,,;:=======,,,;ooooooooo;~~,,;;,,,,,,,,, | ||
| 25 | ,,,==:=====;,,,ooooooooo,~~,,,,,,,,,,,,, | ||
| 26 | ,,,,,,,,,,,,,,,ooooooooo,~~,,,,,,,,,,,,, | ||
| 27 | ,,;;;,,,,,,,;,,ooooooooo;~~,,,;,,,,,,,,, | ||
| 28 | ,,,,;,;,,,,,,,,,,,,,,,,;,~~,,,,,,,,,,,,; | ||
| 29 | ,,,^^^^^^^;,,,,,;,,,,,,,,~~;,,,,,;,,,,,; | ||
| 30 | ,,,~~~~~~~,,,,,,,,;,,,,,,~~,,;,,,,,,,,,; | ||
| 31 | ,,,~~~~~~~,,,,,,,,,;,,,,,~~,,,,,,,,;;,,, | ||
| 32 | ,,,~~~~~~~,,,,,,,,,,,,,,,~~,,;,,,,,;,,,, | ||
| 33 | ,,,,,,,,,,,;,,;,,,,,,,,,,~~;,,,,,,,,,,,, | ||
| 34 | ,,,,,,,,,,,,,,,,,,,,,,,,,~~,,;,,,,;,,,,, | ||
| 35 | ,,,;;,,,;,,,;,,,,,,,,,,,;~~,,,,,,,,,,,,, | ||
| 36 | ,;,,,,,,,,,,,;,,,,,,;,;,,,,,,,;,,,,,,,,; | ||
| 37 | |||
| 38 | layer decor | ||
| 39 | ........................................ | ||
| 40 | TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT | ||
| 41 | b......................................b | ||
| 42 | T...........s.........b............b...T | ||
| 43 | b......................................b | ||
| 44 | T.............AAAAAAA..................T | ||
| 45 | b.b..LLLLL....LLLLLLL...s....LLLLLX....b | ||
| 46 | T...UMWdWMX..SMWMdMWM......bXMWdWMU..%.T | ||
| 47 | b..........*...........*...............b | ||
| 48 | T..%...................................b | ||
| 49 | b....................................... | ||
| 50 | T....................................... | ||
| 51 | b..*........*..................*....*..b | ||
| 52 | T.----------...U*......U....b........T.T | ||
| 53 | b.|."""""".|...........................b | ||
| 54 | T.|."""""".|.......O..........T...T....T | ||
| 55 | b.|."""""".|...........................b | ||
| 56 | T.-----.----....................T...b..T | ||
| 57 | b..............U......*U.....*.........b | ||
| 58 | T.*........S...........................T | ||
| 59 | b............T....*............b....T..b | ||
| 60 | T.........*.....R....*..b........R.....T | ||
| 61 | b.*...........T....b.........T.....*...b | ||
| 62 | T..........*...........T...............T | ||
| 63 | b.R.*...*.R.T....b.........R.....T.....b | ||
| 64 | T....................T.................T | ||
| 65 | .......................................b | ||
| 66 | TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT | ||
| 67 | |||
| 68 | layer overlay above | ||
| 69 | tttttttttttttttttttttttttttttttttttttttt | ||
| 70 | ........................................ | ||
| 71 | t......................................t | ||
| 72 | ........................................ | ||
| 73 | t.............aaaaaaa..................t | ||
| 74 | .....aaaaa...................aaaaa...... | ||
| 75 | t......................................t | ||
| 76 | ........................................ | ||
| 77 | t....................................... | ||
| 78 | ........................................ | ||
| 79 | t....................................... | ||
| 80 | ........................................ | ||
| 81 | t....................................t.t | ||
| 82 | ........................................ | ||
| 83 | t.............................t...t....t | ||
| 84 | ........................................ | ||
| 85 | t...............................t......t | ||
| 86 | ........................................ | ||
| 87 | t......................................t | ||
| 88 | .............t......................t... | ||
| 89 | t......................................t | ||
| 90 | ..............t..............t.......... | ||
| 91 | t......................t...............t | ||
| 92 | ............t....................t...... | ||
| 93 | t....................t.................t | ||
| 94 | ........................................ | ||
| 95 | tttttttttttttttttttttttttttttttttttttttt | ||
| 96 | ........................................ | ||
| 97 | |||
| 98 | # 物:object <種類> <名前> <列> <行> [key=value …] / objects: kind name col row [key=value ...] | ||
| 99 | object spawn start 7 9 face=down | ||
ファイル: /dev/null | b/games/rpg/assets/tiles.atlas
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,51 @@ | |||
| 1 | # rpg tiles (generated by the author's own script): 16x16, extruded 1 px | ||
| 2 | image tiles.png | ||
| 3 | sprite grass 1 1 16 16 | ||
| 4 | sprite grass2 19 1 16 16 | ||
| 5 | sprite path 37 1 16 16 | ||
| 6 | sprite path2 55 1 16 16 | ||
| 7 | sprite cobble 73 1 16 16 | ||
| 8 | sprite water0 91 1 16 16 | ||
| 9 | sprite water1 109 1 16 16 | ||
| 10 | sprite shore0 127 1 16 16 | ||
| 11 | sprite shore1 145 1 16 16 | ||
| 12 | sprite bridge 163 1 16 16 | ||
| 13 | sprite floor 181 1 16 16 | ||
| 14 | sprite rug 199 1 16 16 | ||
| 15 | sprite doormat 217 1 16 16 | ||
| 16 | sprite wall_in 235 1 16 16 | ||
| 17 | sprite wall_in_window 1 19 16 16 | ||
| 18 | sprite void 19 19 16 16 | ||
| 19 | sprite tree_top 37 19 16 16 | ||
| 20 | sprite tree_bottom 55 19 16 16 | ||
| 21 | sprite bush 73 19 16 16 | ||
| 22 | sprite rock 91 19 16 16 | ||
| 23 | sprite flowers 109 19 16 16 | ||
| 24 | sprite tall_grass 127 19 16 16 | ||
| 25 | sprite fence 145 19 16 16 | ||
| 26 | sprite fence_v 163 19 16 16 | ||
| 27 | sprite sign 181 19 16 16 | ||
| 28 | sprite well 199 19 16 16 | ||
| 29 | sprite stump 217 19 16 16 | ||
| 30 | sprite mushrooms 235 19 16 16 | ||
| 31 | sprite house_wall 1 37 16 16 | ||
| 32 | sprite house_window 19 37 16 16 | ||
| 33 | sprite house_door 37 37 16 16 | ||
| 34 | sprite roof_ridge 55 37 16 16 | ||
| 35 | sprite roof 73 37 16 16 | ||
| 36 | sprite roof_eave 91 37 16 16 | ||
| 37 | sprite bed_top 109 37 16 16 | ||
| 38 | sprite bed_bottom 127 37 16 16 | ||
| 39 | sprite bookshelf 145 37 16 16 | ||
| 40 | sprite table 163 37 16 16 | ||
| 41 | sprite stool 181 37 16 16 | ||
| 42 | sprite pot 199 37 16 16 | ||
| 43 | sprite plant 217 37 16 16 | ||
| 44 | sprite hearth 235 37 16 16 | ||
| 45 | sprite crate 1 55 16 16 | ||
| 46 | sprite barrel 19 55 16 16 | ||
| 47 | sprite chest_closed 37 55 16 16 | ||
| 48 | sprite chest_open 55 55 16 16 | ||
| 49 | sprite gate 73 55 16 16 | ||
| 50 | clip water 2 loop water0 water1 | ||
| 51 | clip shore 2 loop shore0 shore1 | ||
ファイル: /dev/null | b/games/rpg/assets/tiles.png
新しいファイル:100644 / バイナリファイル
ファイル: /dev/null | b/games/rpg/assets/tiles.tileset
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,54 @@ | |||
| 1 | # タイルの種類:マップの格子の1文字 → アトラスのスプライト、固いか、動くか | ||
| 2 | # Tile kinds: one character of a map grid → a sprite in the atlas, solid or not, animated or not | ||
| 3 | # tile <文字 / char> <スプライト / sprite> [solid] [anim <clip>] | ||
| 4 | # '.' はどの層でも「空」 / '.' means "empty" in every layer | ||
| 5 | atlas tiles.atlas | ||
| 6 | |||
| 7 | # 地面 / ground | ||
| 8 | tile , grass | ||
| 9 | tile ; grass2 | ||
| 10 | tile = path | ||
| 11 | tile : path2 | ||
| 12 | tile o cobble | ||
| 13 | tile ~ water0 solid anim water | ||
| 14 | tile ^ shore0 solid anim shore | ||
| 15 | tile H bridge | ||
| 16 | tile _ floor | ||
| 17 | tile r rug | ||
| 18 | tile m doormat | ||
| 19 | tile w wall_in solid | ||
| 20 | tile n wall_in_window solid | ||
| 21 | tile x void solid | ||
| 22 | |||
| 23 | # 飾り(人物の下に描く) / decoration (drawn below the characters) | ||
| 24 | tile T tree_bottom solid | ||
| 25 | tile b bush solid | ||
| 26 | tile R rock solid | ||
| 27 | tile * flowers | ||
| 28 | tile " tall_grass | ||
| 29 | tile - fence solid | ||
| 30 | tile | fence_v solid | ||
| 31 | tile S sign solid | ||
| 32 | tile O well solid | ||
| 33 | tile s stump solid | ||
| 34 | tile % mushrooms | ||
| 35 | tile M house_wall solid | ||
| 36 | tile W house_window solid | ||
| 37 | tile d house_door solid | ||
| 38 | tile D house_door | ||
| 39 | tile A roof solid | ||
| 40 | tile L roof_eave solid | ||
| 41 | tile B bed_top solid | ||
| 42 | tile E bed_bottom solid | ||
| 43 | tile K bookshelf solid | ||
| 44 | tile Q table solid | ||
| 45 | tile c stool | ||
| 46 | tile p pot solid | ||
| 47 | tile P plant solid | ||
| 48 | tile F hearth solid | ||
| 49 | tile X crate solid | ||
| 50 | tile U barrel solid | ||
| 51 | |||
| 52 | # 人物の上に重ねる(layer … above) / drawn above the characters (layer ... above) | ||
| 53 | tile t tree_top | ||
| 54 | tile a roof_ridge | ||
ファイル: /dev/null | b/games/rpg/src/character.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,115 @@ | |||
| 1 | #include "character.hh" | ||
| 2 | |||
| 3 | #include <algorithm> | ||
| 4 | #include <cmath> | ||
| 5 | #include <cstdio> | ||
| 6 | |||
| 7 | std::optional<CharacterSheet> CharacterSheet::load(const std::string &path) { | ||
| 8 | std::optional<SpriteSheet> grid = SpriteSheet::loadGrid(path, 16, 16, 1, 1); | ||
| 9 | if (!grid) return std::nullopt; | ||
| 10 | if (grid->count() % kColumns != 0) { | ||
| 11 | fprintf(stderr, "%s: 列が%dでない / not %d columns\n", path.c_str(), kColumns, kColumns); | ||
| 12 | return std::nullopt; | ||
| 13 | } | ||
| 14 | CharacterSheet cs; | ||
| 15 | cs.grid = std::move(grid); | ||
| 16 | // クリップは人ごと・方向ごとに作る(SpriteSheetのdequeに入るのでポインターは変わらない) | ||
| 17 | // Clips per character and direction (they live in the SpriteSheet's deque, so the pointers stay valid) | ||
| 18 | static const char *const kDir[] = {"down", "up", "side"}; | ||
| 19 | for (int look = 0; look < cs.looks(); ++look) | ||
| 20 | for (int d = 0; d < 3; ++d) { | ||
| 21 | int first = look * kColumns + d * 3; | ||
| 22 | std::string base = std::to_string(look) + "." + kDir[d]; | ||
| 23 | cs.grid->addClip({.name = base + ".idle", .frames = {first}, .fps = 1.0f}); | ||
| 24 | // 歩き:A・立ち・B・立ち(8コマ/秒 = 0.5秒で一歩ずつ二歩) / walking: A, stand, B, stand (8 frames/s = two steps | ||
| 25 | // in 0.5 s) | ||
| 26 | cs.grid->addClip({.name = base + ".walk", .frames = {first + 1, first, first + 2, first}, .fps = 8.0f}); | ||
| 27 | cs.clips.push_back(cs.grid->clip(base + ".idle")); | ||
| 28 | cs.clips.push_back(cs.grid->clip(base + ".walk")); | ||
| 29 | } | ||
| 30 | return cs; | ||
| 31 | } | ||
| 32 | |||
| 33 | const AnimationClip *CharacterSheet::clip(int look, Facing facing, bool walking) const { | ||
| 34 | int d = facing == Facing::Down ? 0 : facing == Facing::Up ? 1 : 2; // 左右は同じ絵(左はflipX) / left and right | ||
| 35 | // share pictures (left = flipX) | ||
| 36 | look = std::clamp(look, 0, looks() - 1); | ||
| 37 | return clips[static_cast<size_t>(look * 6 + d * 2 + (walking ? 1 : 0))]; | ||
| 38 | } | ||
| 39 | |||
| 40 | void Character::placeAt(Vec2 tileTopLeft) { | ||
| 41 | box = {tileTopLeft.x + 0.5f * (kTile - kFootBox.x), tileTopLeft.y + kTile - kFootBox.y, kFootBox.x, kFootBox.y}; | ||
| 42 | previous = box.position(); | ||
| 43 | } | ||
| 44 | |||
| 45 | void Character::animate(const CharacterSheet &sheet, float dt) { | ||
| 46 | anim.play(moving ? sheet.walk(look, facing) : sheet.idle(look, facing)); | ||
| 47 | anim.update(dt); | ||
| 48 | } | ||
| 49 | |||
| 50 | Vec2 Character::feet(float alpha) const { | ||
| 51 | Vec2 p = lerp(previous, box.position(), alpha); | ||
| 52 | return {p.x + 0.5f * box.w, p.y + box.h}; | ||
| 53 | } | ||
| 54 | |||
| 55 | Sprite Character::sprite(const CharacterSheet &sheet, float alpha) const { | ||
| 56 | Vec2 f = feet(alpha); | ||
| 57 | // まだクリップがない(最初のanimateの前)とframe()は-1:そのままではシートの外を読むので、立ちのコマを使う | ||
| 58 | // Without a clip yet (before the first animate) frame() is -1, which would read outside the sheet: use the standing | ||
| 59 | // frame instead | ||
| 60 | int frame = anim.frame(); | ||
| 61 | if (frame < 0) frame = sheet.idle(look, facing)->frames.front(); | ||
| 62 | // 整数のピクセルに丸める(カメラも同じ丸め方:人物とタイルの相対位置が揺れない) / round to whole pixels (the camera | ||
| 63 | // rounds the same way: characters and tiles never wobble against each other) | ||
| 64 | Sprite s = sheet.sheet().sprite(frame, {std::round(f.x), std::round(f.y)}, {0.5f, 1.0f}); | ||
| 65 | s.flipX = facing == Facing::Left; | ||
| 66 | s.layer = f.y; // 下にいる人ほど手前(Y順) / the lower on screen, the nearer (Y-sorting) | ||
| 67 | return s; | ||
| 68 | } | ||
| 69 | |||
| 70 | Facing facingFor(Vec2 move, Facing current) { | ||
| 71 | bool left = move.x < 0.0f, right = move.x > 0.0f, up = move.y < 0.0f, down = move.y > 0.0f; | ||
| 72 | if ((current == Facing::Left && left) || (current == Facing::Right && right) || (current == Facing::Up && up) || | ||
| 73 | (current == Facing::Down && down)) | ||
| 74 | return current; | ||
| 75 | if (left) return Facing::Left; | ||
| 76 | if (right) return Facing::Right; | ||
| 77 | if (up) return Facing::Up; | ||
| 78 | if (down) return Facing::Down; | ||
| 79 | return current; | ||
| 80 | } | ||
| 81 | |||
| 82 | static bool blocked(const Rect &r, std::span<const Rect> solids) { | ||
| 83 | for (const Rect &s : solids) | ||
| 84 | if (overlaps(r, s)) return true; | ||
| 85 | return false; | ||
| 86 | } | ||
| 87 | |||
| 88 | MoveResult moveOnMap(Rect &box, Vec2 delta, const Tilemap &map, std::span<const Rect> extra, std::vector<Rect> &scratch) { | ||
| 89 | constexpr float kAssist = 6.0f; // 何ピクセルまでの引っかかりを回り込むか / how many pixels of overlap to slide round | ||
| 90 | // 動く範囲(+回り込みの分)に触れる固いマスだけを集める / collect only the solid cells near the move (+ the assist) | ||
| 91 | Rect area = {std::min(box.x, box.x + delta.x) - kAssist, std::min(box.y, box.y + delta.y) - kAssist, | ||
| 92 | box.w + std::abs(delta.x) + 2.0f * kAssist, box.h + std::abs(delta.y) + 2.0f * kAssist}; | ||
| 93 | scratch.clear(); | ||
| 94 | map.solidRects(area, scratch); | ||
| 95 | scratch.insert(scratch.end(), extra.begin(), extra.end()); | ||
| 96 | MoveResult result = moveAndSlide(box, delta, scratch); | ||
| 97 | |||
| 98 | // 角の回り込み:一方向だけに歩いて止まったとき、横にdずらせば進めるなら、少しずつずらす(Zelda風) | ||
| 99 | // Corner assist: when walking in one direction only and stopped, if shifting sideways by d would free the way, shift | ||
| 100 | // a little each step (Zelda-style) | ||
| 101 | bool alongX = delta.x != 0.0f && delta.y == 0.0f && result.hitX; | ||
| 102 | bool alongY = delta.y != 0.0f && delta.x == 0.0f && result.hitY; | ||
| 103 | if (!alongX && !alongY) return result; | ||
| 104 | float speed = std::abs(alongX ? delta.x : delta.y); | ||
| 105 | Vec2 forward = alongX ? Vec2{delta.x > 0.0f ? 1.0f : -1.0f, 0.0f} : Vec2{0.0f, delta.y > 0.0f ? 1.0f : -1.0f}; | ||
| 106 | Vec2 side = alongX ? Vec2{0.0f, 1.0f} : Vec2{1.0f, 0.0f}; | ||
| 107 | for (float d = 1.0f; d <= kAssist; d += 1.0f) | ||
| 108 | for (float sign : {-1.0f, 1.0f}) { | ||
| 109 | Rect shifted = box.translated(side * (sign * d)); | ||
| 110 | if (blocked(shifted, scratch) || blocked(shifted.translated(forward), scratch)) continue; | ||
| 111 | moveAndSlide(box, side * (sign * std::min(d, speed)), scratch); | ||
| 112 | return result; | ||
| 113 | } | ||
| 114 | return result; | ||
| 115 | } | ||
ファイル: /dev/null | b/games/rpg/src/character.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,72 @@ | |||
| 1 | // 人物(第33章):4方向の歩きの絵と、タイルにぶつかりながら動く足元の箱 | ||
| 2 | // Characters (chapter 33): 4-direction walk pictures, and a foot box that moves while colliding with tiles | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include "tilemap.hh" | ||
| 6 | |||
| 7 | #include "engine/animation.hh" | ||
| 8 | #include "engine/collision.hh" | ||
| 9 | #include "engine/sprite_sheet.hh" | ||
| 10 | |||
| 11 | #include <optional> | ||
| 12 | #include <span> | ||
| 13 | #include <string> | ||
| 14 | #include <vector> | ||
| 15 | |||
| 16 | enum class Facing { Down, Up, Left, Right }; | ||
| 17 | |||
| 18 | // characters.png:1行が1人、9列 = 下向き(立ち・歩きA・歩きB)、上向き(同じ)、横向き(同じ、右向き) | ||
| 19 | // characters.png: one row per character, 9 columns = facing down (stand, step A, step B), up (the same), side (the | ||
| 20 | // same, facing right) | ||
| 21 | class CharacterSheet { | ||
| 22 | public: | ||
| 23 | static std::optional<CharacterSheet> load(const std::string &path); | ||
| 24 | const SpriteSheet &sheet() const { return *grid; } | ||
| 25 | int looks() const { return grid->count() / kColumns; } // 何人分あるか / how many characters there are | ||
| 26 | const AnimationClip *idle(int look, Facing facing) const { return clip(look, facing, false); } | ||
| 27 | const AnimationClip *walk(int look, Facing facing) const { return clip(look, facing, true); } | ||
| 28 | |||
| 29 | static constexpr int kColumns = 9; | ||
| 30 | |||
| 31 | private: | ||
| 32 | CharacterSheet() = default; | ||
| 33 | const AnimationClip *clip(int look, Facing facing, bool walking) const; | ||
| 34 | std::optional<SpriteSheet> grid; | ||
| 35 | std::vector<const AnimationClip *> clips; // look * 6 + 方向 * 2 + 歩き / look * 6 + direction * 2 + walking | ||
| 36 | }; | ||
| 37 | |||
| 38 | // 当たり判定は足元の小さな箱。絵(16 × 16)はその下の真ん中に合わせて描く:頭は上のマスに重なってよい | ||
| 39 | // The collision box is a small box at the feet. The 16 × 16 picture is drawn aligned to its bottom center: the head | ||
| 40 | // may overlap the tile above | ||
| 41 | constexpr Vec2 kFootBox = {10.0f, 6.0f}; | ||
| 42 | |||
| 43 | struct Character { | ||
| 44 | int look = 0; // characters.pngの行 / the row in characters.png | ||
| 45 | Rect box; // 足元の箱(ピクセル) / the foot box (pixels) | ||
| 46 | Vec2 previous; // 前のステップのbox.position()(描くときの補間) / box.position() of the last step (for | ||
| 47 | // interpolation when drawing) | ||
| 48 | Facing facing = Facing::Down; | ||
| 49 | bool moving = false; | ||
| 50 | Animator anim; | ||
| 51 | |||
| 52 | // マス(col, row)の真ん中、足がマスの下の辺に来るように置く / puts the character in cell (col, row), feet on the | ||
| 53 | // cell's bottom edge | ||
| 54 | void placeAt(Vec2 tileTopLeft); | ||
| 55 | void beginStep() { previous = box.position(); } | ||
| 56 | void animate(const CharacterSheet &sheet, float dt); | ||
| 57 | Vec2 feet(float alpha) const; // 補間した足元(箱の下の真ん中) / the interpolated feet (bottom center of the box) | ||
| 58 | Sprite sprite(const CharacterSheet &sheet, float alpha) const; | ||
| 59 | }; | ||
| 60 | |||
| 61 | // 動きの向きから顔の向き:今の向きが押されている方向の一つなら変えない(斜めに歩いても向きが震えない) | ||
| 62 | // Facing from a movement: keep the current facing if it is one of the pressed directions (walking diagonally does not | ||
| 63 | // make the facing flicker) | ||
| 64 | Facing facingFor(Vec2 move, Facing current); | ||
| 65 | |||
| 66 | // 箱をdeltaだけ動かす:マップの固いマス+extra(人物などの箱)に当たれば止まり、壁に沿って滑る。 | ||
| 67 | // 真横・真上下に歩いていて角に数ピクセルだけ引っかかったら、その分だけ横にずらして角を回り込む(corner assist) | ||
| 68 | // Moves the box by delta: it stops at the map's solid cells + `extra` (other characters' boxes...) and slides along | ||
| 69 | // walls. When walking straight and only a few pixels catch on a corner, it is nudged sideways around the corner | ||
| 70 | // (corner assist) | ||
| 71 | MoveResult moveOnMap(Rect &box, Vec2 delta, const Tilemap &map, std::span<const Rect> extra, | ||
| 72 | std::vector<Rect> &scratch); | ||
ファイル: /dev/null | b/games/rpg/src/game.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,65 @@ | |||
| 1 | // RPG:どのシーンからも使う共有データと、シーンのクラス | ||
| 2 | // The RPG: the shared data every scene uses, and the scene classes | ||
| 3 | #pragma once | ||
| 4 | |||
| 5 | #include "character.hh" | ||
| 6 | #include "tile_renderer.hh" | ||
| 7 | #include "tilemap.hh" | ||
| 8 | |||
| 9 | #include "engine/camera2d.hh" | ||
| 10 | #include "engine/font.hh" | ||
| 11 | #include "engine/game_loop.hh" | ||
| 12 | #include "engine/input.hh" | ||
| 13 | #include "engine/scene.hh" | ||
| 14 | #include "engine/sprite_batch.hh" | ||
| 15 | |||
| 16 | #include <array> | ||
| 17 | #include <optional> | ||
| 18 | #include <vector> | ||
| 19 | |||
| 20 | // 仮想解像度: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 | ||
| 22 | constexpr Vec2 kView = {320.0f, 180.0f}; | ||
| 23 | |||
| 24 | // ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference | ||
| 25 | struct Game { | ||
| 26 | Window &window; | ||
| 27 | Input &input; | ||
| 28 | GameLoop &loop; | ||
| 29 | SpriteBatch &batch; | ||
| 30 | TileRenderer &tiles; // GPUの物は一つを使い回す(マップが変わったらbuildし直す) / one set of GPU objects, rebuilt | ||
| 31 | // when the map changes | ||
| 32 | const Font &ui; // mono16:画面の解像度 / screen resolution | ||
| 33 | const Font &pixel; // pixel12:キャンバスの中 / inside the canvas | ||
| 34 | const CharacterSheet &characters; | ||
| 35 | Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI | ||
| 36 | Viewport uiViewport; | ||
| 37 | }; | ||
| 38 | |||
| 39 | // マップの上を歩くシーン / the scene where you walk around a map | ||
| 40 | class MapScene : public Scene { | ||
| 41 | public: | ||
| 42 | MapScene(Game &game, Tilemap map); | ||
| 43 | void enter() override; | ||
| 44 | void pause() override; | ||
| 45 | void update(float dt) override; | ||
| 46 | void draw(float alpha) override; | ||
| 47 | void drawUi(float alpha) override; | ||
| 48 | |||
| 49 | private: | ||
| 50 | void spawn(); | ||
| 51 | // カメラ:主人公の足元を追い、マップの端で止める(マップが画面より小さければ真ん中に) | ||
| 52 | // The camera: follows the hero's feet and stops at the map's edges (centered when the map is smaller than the view) | ||
| 53 | Camera2D followCamera(Vec2 target) const; | ||
| 54 | |||
| 55 | Game &g; | ||
| 56 | Tilemap map; | ||
| 57 | Character hero; | ||
| 58 | std::vector<Rect> scratch; // 当たり判定の箱の作業用(毎ステップ作り直さない) / scratch boxes for collision (kept | ||
| 59 | // between steps to avoid allocations) | ||
| 60 | float time = 0.0f; | ||
| 61 | bool showBoxes = false, zoomOut = false, showHud = true; | ||
| 62 | std::array<bool, 8> layerOn; | ||
| 63 | // HUD用:前のフレームの描画の数 / for the HUD: last frame's drawing counts | ||
| 64 | int rowFirst = 0, rowLast = 0, spriteCalls = 0; | ||
| 65 | }; | ||
ファイル: /dev/null | b/games/rpg/src/main.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,69 @@ | |||
| 1 | // 第33章:見下ろし型RPG(1)タイルマップ、当たり判定のある移動、追いかけるカメラ | ||
| 2 | // Chapter 33: a top-down RPG (1) tile maps, movement with collision, a following camera | ||
| 3 | // | ||
| 4 | // 操作 / Controls: | ||
| 5 | // 矢印 / WASD 移動 / move Shift 走る / run | ||
| 6 | // 1 2 3 層の表示 / toggle layers (ground, decor, overlay) | ||
| 7 | // B 当たり判定の箱 / collision boxes Z 引いて見る(カリングの確認) / zoom out (shows culling) | ||
| 8 | // H HUDの表示 / toggle the HUD | ||
| 9 | // R マップをファイルから読み直す / reload the map from its file Esc 終了 / quit | ||
| 10 | // | ||
| 11 | // 実行はプロジェクトのルートから / run from the project root: ./build/games/rpg/rpg | ||
| 12 | #include "game.hh" | ||
| 13 | |||
| 14 | #include "engine/pixel_canvas.hh" | ||
| 15 | #include "engine/window.hh" | ||
| 16 | |||
| 17 | #include <cstdio> | ||
| 18 | #include <memory> | ||
| 19 | #include <optional> | ||
| 20 | |||
| 21 | int main() { | ||
| 22 | Window window; | ||
| 23 | if (!window.create(1280, 720, "OpenGL Tutorial - RPG")) return 1; | ||
| 24 | |||
| 25 | std::optional<SpriteBatch> batch = SpriteBatch::create(); | ||
| 26 | std::optional<TileRenderer> tiles = TileRenderer::create(); | ||
| 27 | std::optional<Font> ui = Font::load("assets/fonts/mono16.fnt"); | ||
| 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"); | ||
| 30 | std::optional<Tilemap> village = Tilemap::load("games/rpg/assets/maps/village.map"); | ||
| 31 | if (!batch || !tiles || !ui || !pixel || !characters || !village) return 1; | ||
| 32 | |||
| 33 | Input input; | ||
| 34 | input.attach(window); | ||
| 35 | input.bind("left", {InputBinding::key(GLFW_KEY_LEFT), InputBinding::key(GLFW_KEY_A)}); | ||
| 36 | input.bind("right", {InputBinding::key(GLFW_KEY_RIGHT), InputBinding::key(GLFW_KEY_D)}); | ||
| 37 | 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)}); | ||
| 39 | input.bind("run", {InputBinding::key(GLFW_KEY_LEFT_SHIFT), InputBinding::key(GLFW_KEY_RIGHT_SHIFT)}); | ||
| 40 | |||
| 41 | GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); | ||
| 42 | 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, | ||
| 44 | .pixel = *pixel, .characters = *characters, .screen = Camera2D::screen({1280.0f, 720.0f}), | ||
| 45 | .uiViewport = {}}; | ||
| 46 | |||
| 47 | SceneManager scenes; | ||
| 48 | scenes.push(std::make_unique<MapScene>(game, std::move(*village))); | ||
| 49 | |||
| 50 | loop.run( | ||
| 51 | window, input, | ||
| 52 | [&](float dt) { | ||
| 53 | scenes.update(dt); | ||
| 54 | if (scenes.empty()) window.close(); | ||
| 55 | }, | ||
| 56 | [&](float alpha) { | ||
| 57 | // 1. 世界:320 × 180のキャンバスに描き、整数倍で画面へ / 1. the world: into the 320 × 180 canvas, then scaled | ||
| 58 | // by a whole number onto the screen | ||
| 59 | canvas.begin(hexColor(0x1b1726ff)); | ||
| 60 | scenes.draw(alpha); | ||
| 61 | canvas.present(window.width(), window.height()); | ||
| 62 | // 2. UI:1280 × 720の文字 / 2. the UI: text at 1280 × 720 | ||
| 63 | game.uiViewport = letterbox(window.width(), window.height(), game.screen.viewSize, false); | ||
| 64 | game.uiViewport.apply(); | ||
| 65 | scenes.drawUi(alpha); | ||
| 66 | scenes.drawFade(*batch, game.screen.matrix(), game.screen.viewSize); | ||
| 67 | }); | ||
| 68 | return 0; | ||
| 69 | } | ||
ファイル: /dev/null | b/games/rpg/src/map_scene.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,166 @@ | |||
| 1 | // マップのシーン:主人公を歩かせ、カメラで追い、層の順にタイルと人物を描く | ||
| 2 | // The map scene: walks the hero around, follows it with the camera, draws tiles and characters in layer order | ||
| 3 | #include "game.hh" | ||
| 4 | |||
| 5 | #include "engine/collision.hh" | ||
| 6 | |||
| 7 | #include <algorithm> | ||
| 8 | #include <cmath> | ||
| 9 | #include <cstdio> | ||
| 10 | |||
| 11 | constexpr float kWalkSpeed = 72.0f; // ピクセル毎秒(4.5マス/秒) / pixels per second (4.5 tiles/s) | ||
| 12 | constexpr float kRunSpeed = 120.0f; | ||
| 13 | |||
| 14 | MapScene::MapScene(Game &game, Tilemap tilemap) : g(game), map(std::move(tilemap)) { layerOn.fill(true); } | ||
| 15 | |||
| 16 | void MapScene::enter() { | ||
| 17 | g.tiles.build(map); // 静的な頂点バッファを作る(マップごとに一度) / build the static vertex buffer (once per map) | ||
| 18 | spawn(); | ||
| 19 | } | ||
| 20 | |||
| 21 | void MapScene::spawn() { | ||
| 22 | hero.look = 0; | ||
| 23 | const MapObject *start = map.findObject("spawn", "start"); | ||
| 24 | hero.placeAt(start ? start->rect.position() : Vec2{kTile, kTile}); | ||
| 25 | 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; | ||
| 27 | // 最初のフレームは更新なしで描かれる:今のうちに立ちのクリップを選んでおく / the first frame is drawn before any | ||
| 28 | // update: pick the standing clip now | ||
| 29 | hero.animate(g.characters, 0.0f); | ||
| 30 | } | ||
| 31 | |||
| 32 | void MapScene::pause() { hero.previous = hero.box.position(); } | ||
| 33 | |||
| 34 | void MapScene::update(float dt) { | ||
| 35 | time += dt; | ||
| 36 | Input &in = g.input; | ||
| 37 | if (in.pressed(GLFW_KEY_ESCAPE)) { | ||
| 38 | scenes().pop(); // 最後のシーン:mainが終わる / the last scene: main quits | ||
| 39 | return; | ||
| 40 | } | ||
| 41 | if (in.pressed(GLFW_KEY_B)) showBoxes = !showBoxes; | ||
| 42 | if (in.pressed(GLFW_KEY_Z)) zoomOut = !zoomOut; | ||
| 43 | if (in.pressed(GLFW_KEY_H)) showHud = !showHud; | ||
| 44 | 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)]; | ||
| 46 | if (in.pressed(GLFW_KEY_R)) { | ||
| 47 | // ファイルから読み直す(テキストエディターで直してすぐ確かめる)。失敗したら今のマップのまま | ||
| 48 | // Reload from the file (edit in a text editor, check at once). On failure the current map stays | ||
| 49 | if (std::optional<Tilemap> fresh = Tilemap::load(map.path())) { | ||
| 50 | map = std::move(*fresh); | ||
| 51 | g.tiles.build(map); | ||
| 52 | printf("%s: 読み直した / reloaded\n", map.path().c_str()); | ||
| 53 | } | ||
| 54 | } | ||
| 55 | |||
| 56 | // 主人公:自由に動く(マス目に縛られない)。斜めは正規化して同じ速さ / the hero moves freely (not locked to the | ||
| 57 | // grid); diagonals are normalized to the same speed | ||
| 58 | hero.beginStep(); | ||
| 59 | Vec2 move = {in.axis("left", "right"), in.axis("up", "down")}; | ||
| 60 | hero.moving = move.x != 0.0f || move.y != 0.0f; | ||
| 61 | if (hero.moving) { | ||
| 62 | hero.facing = facingFor(move, hero.facing); | ||
| 63 | float speed = in.actionHeld("run") ? kRunSpeed : kWalkSpeed; | ||
| 64 | moveOnMap(hero.box, normalize(move) * (speed * dt), map, {}, scratch); | ||
| 65 | } | ||
| 66 | hero.anim.speed = in.actionHeld("run") ? 1.5f : 1.0f; | ||
| 67 | hero.animate(g.characters, dt); | ||
| 68 | } | ||
| 69 | |||
| 70 | Camera2D MapScene::followCamera(Vec2 target) const { | ||
| 71 | Vec2 size = map.pixelSize(), half = 0.5f * kView; | ||
| 72 | Vec2 c; | ||
| 73 | 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); | ||
| 75 | // 中心を整数に丸める:タイルがいつもピクセルの格子に乗る(主人公の絵も同じ丸め方) / round the center to whole pixels: | ||
| 76 | // tiles always sit on the pixel grid (the hero's picture is rounded the same way) | ||
| 77 | return {.viewSize = kView, .centre = {std::round(c.x), std::round(c.y)}}; | ||
| 78 | } | ||
| 79 | |||
| 80 | 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); | ||
| 83 | Camera2D camera = followCamera({feet.x, feet.y - 6.0f}); | ||
| 84 | 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; | ||
| 88 | if (zoomOut) { | ||
| 89 | view.zoom = 0.5f; | ||
| 90 | view.centre = {std::round(camera.centre.x), std::round(camera.centre.y)}; | ||
| 91 | } | ||
| 92 | Mat4 vp = view.matrix(); | ||
| 93 | SpriteBatch &b = g.batch; | ||
| 94 | g.tiles.resetStats(); | ||
| 95 | spriteCalls = 0; | ||
| 96 | 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; | ||
| 98 | |||
| 99 | auto drawCharacters = [&] { | ||
| 100 | b.begin(vp, SpriteSort::Layer); | ||
| 101 | b.draw(hero.sprite(g.characters, alpha)); | ||
| 102 | b.end(); | ||
| 103 | spriteCalls += b.stats().drawCalls; | ||
| 104 | }; | ||
| 105 | |||
| 106 | // 層はファイルの順に描く。「above」の層(木の上・屋根の棟)は人物の後 / layers are drawn in file order; "above" | ||
| 107 | // layers (tree tops, roof ridges) come after the characters | ||
| 108 | bool charactersDrawn = false; | ||
| 109 | const std::vector<TileLayer> &layers = map.layers(); | ||
| 110 | for (int i = 0; i < static_cast<int>(layers.size()); ++i) { | ||
| 111 | if (layers[static_cast<size_t>(i)].above && !charactersDrawn) { | ||
| 112 | drawCharacters(); | ||
| 113 | charactersDrawn = true; | ||
| 114 | } | ||
| 115 | if (i < static_cast<int>(layerOn.size()) && !layerOn[static_cast<size_t>(i)]) continue; | ||
| 116 | g.tiles.drawLayer(i, vp, visible); | ||
| 117 | if (g.tiles.hasAnimated(i)) { | ||
| 118 | b.begin(vp); | ||
| 119 | g.tiles.drawAnimated(b, i, visible, time); | ||
| 120 | b.end(); | ||
| 121 | spriteCalls += b.stats().drawCalls; | ||
| 122 | } | ||
| 123 | } | ||
| 124 | if (!charactersDrawn) drawCharacters(); | ||
| 125 | |||
| 126 | if (showBoxes || zoomOut) { | ||
| 127 | b.begin(vp); | ||
| 128 | if (showBoxes) { | ||
| 129 | // 固いマス(赤)と主人公の足元の箱(緑) / solid cells (red) and the hero's foot box (green) | ||
| 130 | scratch.clear(); | ||
| 131 | map.solidRects(visible, scratch); | ||
| 132 | for (const Rect &r : scratch) b.drawRectOutline(r, hexColor(0xff5050c0)); | ||
| 133 | Vec2 p = lerp(hero.previous, hero.box.position(), alpha); | ||
| 134 | b.drawRectOutline({p.x, p.y, hero.box.w, hero.box.h}, hexColor(0x50ff60ff)); | ||
| 135 | } | ||
| 136 | if (zoomOut) b.drawRectOutline(visible, hexColor(0xffe040ff), 2.0f); // 本物のカメラ / the real camera | ||
| 137 | b.end(); | ||
| 138 | spriteCalls += b.stats().drawCalls; | ||
| 139 | } | ||
| 140 | } | ||
| 141 | |||
| 142 | void MapScene::drawUi(float /*alpha*/) { | ||
| 143 | if (!showHud) return; | ||
| 144 | SpriteBatch &b = g.batch; | ||
| 145 | const TileRenderer::Stats &ts = g.tiles.stats(); | ||
| 146 | 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)); | ||
| 148 | snprintf(line, sizeof line, "%s %d×%d tile (%d, %d) rows %d-%d tile quads %d / %d draw calls: tiles %d + sprites %d", | ||
| 149 | map.name().c_str(), map.width(), map.height(), col, row, rowFirst, rowLast, ts.quads, ts.totalQuads, | ||
| 150 | ts.drawCalls, spriteCalls); | ||
| 151 | b.begin(g.screen.matrix()); | ||
| 152 | TextStyle hud = {.color = hexColor(0xfff4d6ff), .shadow = hexColor(0x000000ff)}; | ||
| 153 | b.drawRect({0.0f, 0.0f, 1280.0f, 30.0f}, hexColor(0x1b1726c0)); | ||
| 154 | g.ui.draw(b, line, {12.0f, 6.0f}, hud); | ||
| 155 | char layers[64]; | ||
| 156 | snprintf(layers, sizeof layers, "layers %s %s %s", layerOn[0] ? "1" : "-", layerOn[1] ? "2" : "-", layerOn[2] ? "3" : "-"); | ||
| 157 | hud.align = TextAlign::Right; | ||
| 158 | hud.color = hexColor(0xf2c14eff); | ||
| 159 | g.ui.draw(b, layers, {1268.0f, 6.0f}, hud); | ||
| 160 | b.drawRect({0.0f, 690.0f, 1280.0f, 30.0f}, hexColor(0x1b1726c0)); | ||
| 161 | hud.align = TextAlign::Centre; | ||
| 162 | 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", | ||
| 164 | {640.0f, 696.0f}, hud); | ||
| 165 | b.end(); | ||
| 166 | } | ||
ファイル: /dev/null | b/games/rpg/src/tile_renderer.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,150 @@ | |||
| 1 | #include "tile_renderer.hh" | ||
| 2 | |||
| 3 | #include <algorithm> | ||
| 4 | #include <cmath> | ||
| 5 | #include <cstdint> | ||
| 6 | #include <utility> | ||
| 7 | |||
| 8 | std::optional<TileRenderer> TileRenderer::create() { | ||
| 9 | TileRenderer r; | ||
| 10 | r.shader = Shader::load("engine/shaders/sprite.vert", "engine/shaders/sprite.frag"); | ||
| 11 | if (!r.shader) return std::nullopt; | ||
| 12 | // VAOの形はSpriteBatchと同じ:位置(0)、UV(1)、色(2、RGBA8を0〜1に) / the same VAO format as the SpriteBatch: | ||
| 13 | // position (0), UV (1), color (2, RGBA8 normalized to 0..1) | ||
| 14 | glCreateVertexArrays(1, &r.vao); | ||
| 15 | glEnableVertexArrayAttrib(r.vao, 0); | ||
| 16 | glVertexArrayAttribFormat(r.vao, 0, 2, GL_FLOAT, GL_FALSE, offsetof(SpriteVertex, position)); | ||
| 17 | glVertexArrayAttribBinding(r.vao, 0, 0); | ||
| 18 | glEnableVertexArrayAttrib(r.vao, 1); | ||
| 19 | glVertexArrayAttribFormat(r.vao, 1, 2, GL_FLOAT, GL_FALSE, offsetof(SpriteVertex, uv)); | ||
| 20 | glVertexArrayAttribBinding(r.vao, 1, 0); | ||
| 21 | glEnableVertexArrayAttrib(r.vao, 2); | ||
| 22 | glVertexArrayAttribFormat(r.vao, 2, 4, GL_UNSIGNED_BYTE, GL_TRUE, offsetof(SpriteVertex, color)); | ||
| 23 | glVertexArrayAttribBinding(r.vao, 2, 0); | ||
| 24 | return r; | ||
| 25 | } | ||
| 26 | |||
| 27 | TileRenderer::~TileRenderer() { release(); } | ||
| 28 | |||
| 29 | void TileRenderer::release() { | ||
| 30 | if (vao) glDeleteVertexArrays(1, &vao); | ||
| 31 | vao = 0; | ||
| 32 | } | ||
| 33 | |||
| 34 | TileRenderer::TileRenderer(TileRenderer &&o) noexcept | ||
| 35 | : shader(std::move(o.shader)), vertices(std::move(o.vertices)), indices(std::move(o.indices)), | ||
| 36 | vao(std::exchange(o.vao, 0)), map(o.map), layers(std::move(o.layers)), frameStats(o.frameStats) {} | ||
| 37 | |||
| 38 | TileRenderer &TileRenderer::operator=(TileRenderer &&o) noexcept { | ||
| 39 | if (this != &o) { | ||
| 40 | release(); | ||
| 41 | shader = std::move(o.shader); | ||
| 42 | vertices = std::move(o.vertices); | ||
| 43 | indices = std::move(o.indices); | ||
| 44 | vao = std::exchange(o.vao, 0); | ||
| 45 | map = o.map; | ||
| 46 | layers = std::move(o.layers); | ||
| 47 | frameStats = o.frameStats; | ||
| 48 | } | ||
| 49 | return *this; | ||
| 50 | } | ||
| 51 | |||
| 52 | void TileRenderer::build(const Tilemap &m) { | ||
| 53 | map = &m; | ||
| 54 | const SpriteSheet &sheet = m.tileset().sheet(); | ||
| 55 | std::vector<SpriteVertex> data; | ||
| 56 | layers.clear(); | ||
| 57 | int maxLayerQuads = 0; | ||
| 58 | for (const TileLayer &tl : m.layers()) { | ||
| 59 | Layer layer; | ||
| 60 | layer.firstQuad = static_cast<int>(data.size() / 4); | ||
| 61 | layer.rowStart.reserve(static_cast<size_t>(m.height() + 1)); | ||
| 62 | for (int row = 0; row < m.height(); ++row) { | ||
| 63 | layer.rowStart.push_back(static_cast<int>(data.size() / 4) - layer.firstQuad); | ||
| 64 | for (int col = 0; col < m.width(); ++col) { | ||
| 65 | int k = tl.cells[static_cast<size_t>(row * m.width() + col)]; | ||
| 66 | if (k < 0) continue; // 空のマスは四角形を作らない / empty cells make no quad | ||
| 67 | const TileKind &kind = m.tileset().kind(k); | ||
| 68 | Vec2 p = {kTile * static_cast<float>(col), kTile * static_cast<float>(row)}; | ||
| 69 | if (kind.anim) { | ||
| 70 | // 動くタイルはバッファに入れず、毎フレームバッチで描く / animated tiles stay out of the buffer and are drawn | ||
| 71 | // through the batch every frame | ||
| 72 | layer.animated.push_back({p, &kind, row}); | ||
| 73 | continue; | ||
| 74 | } | ||
| 75 | Rect uv = sheet.uv(kind.sprite); | ||
| 76 | // 左上・右上・右下・左下(SpriteBatchと同じ順:添字 0-1-2 2-3-0) / top left, top right, bottom right, | ||
| 77 | // bottom left (the SpriteBatch's order: indices 0-1-2 2-3-0) | ||
| 78 | data.push_back({p, {uv.left(), uv.top()}, 0xFFFFFFFFu}); | ||
| 79 | data.push_back({{p.x + kTile, p.y}, {uv.right(), uv.top()}, 0xFFFFFFFFu}); | ||
| 80 | data.push_back({{p.x + kTile, p.y + kTile}, {uv.right(), uv.bottom()}, 0xFFFFFFFFu}); | ||
| 81 | data.push_back({{p.x, p.y + kTile}, {uv.left(), uv.bottom()}, 0xFFFFFFFFu}); | ||
| 82 | } | ||
| 83 | } | ||
| 84 | layer.rowStart.push_back(static_cast<int>(data.size() / 4) - layer.firstQuad); | ||
| 85 | maxLayerQuads = std::max(maxLayerQuads, layer.rowStart.back()); | ||
| 86 | layers.push_back(std::move(layer)); | ||
| 87 | } | ||
| 88 | // 添字は一番大きい層の分だけ:どの範囲もbaseVertexで頂点をずらして同じ添字0, 1, 2, 2, 3, 0, 4…を使う | ||
| 89 | // Indices only for the largest layer: every range reuses the same indices 0, 1, 2, 2, 3, 0, 4... with baseVertex | ||
| 90 | // shifting the vertices | ||
| 91 | std::vector<std::uint32_t> quadIndices; | ||
| 92 | quadIndices.reserve(static_cast<size_t>(std::max(1, maxLayerQuads)) * 6); | ||
| 93 | for (std::uint32_t q = 0; q < static_cast<std::uint32_t>(std::max(1, maxLayerQuads)); ++q) | ||
| 94 | for (std::uint32_t i : {0u, 1u, 2u, 2u, 3u, 0u}) quadIndices.push_back(4 * q + i); | ||
| 95 | if (data.empty()) data.resize(4); // 空のバッファは作れない / zero-size storage is not allowed | ||
| 96 | |||
| 97 | // 不変のストレージ(フラグ0):作るときに中身を渡し、あとは書き換えない。ドライバーはGPUの速いメモリに置ける | ||
| 98 | // Immutable storage (flags 0): the contents are given at creation and never change. The driver may keep it in fast | ||
| 99 | // GPU memory | ||
| 100 | vertices = Buffer(data.data(), static_cast<GLsizeiptr>(data.size() * sizeof(SpriteVertex)), 0); | ||
| 101 | indices = Buffer(quadIndices.data(), static_cast<GLsizeiptr>(quadIndices.size() * sizeof(std::uint32_t)), 0); | ||
| 102 | glVertexArrayVertexBuffer(vao, 0, vertices.id(), 0, sizeof(SpriteVertex)); | ||
| 103 | glVertexArrayElementBuffer(vao, indices.id()); | ||
| 104 | frameStats.totalQuads = static_cast<int>(data.size() / 4); | ||
| 105 | } | ||
| 106 | |||
| 107 | // visibleが触れる行の範囲 [r0, r1) / the range of rows [r0, r1) that `visible` touches | ||
| 108 | static std::pair<int, int> visibleRows(const Rect &visible, int rows) { | ||
| 109 | int r0 = static_cast<int>(std::floor(visible.top() / kTile)); | ||
| 110 | int r1 = static_cast<int>(std::ceil(visible.bottom() / kTile)); | ||
| 111 | return {std::clamp(r0, 0, rows), std::clamp(r1, 0, rows)}; | ||
| 112 | } | ||
| 113 | |||
| 114 | void TileRenderer::drawLayer(int index, const Mat4 &viewProjection, const Rect &visible) { | ||
| 115 | if (!map || index < 0 || index >= static_cast<int>(layers.size())) return; | ||
| 116 | const Layer &layer = layers[static_cast<size_t>(index)]; | ||
| 117 | auto [r0, r1] = visibleRows(visible, map->height()); | ||
| 118 | int first = layer.rowStart[static_cast<size_t>(r0)], count = layer.rowStart[static_cast<size_t>(r1)] - first; | ||
| 119 | if (count <= 0) return; | ||
| 120 | shader->use(); | ||
| 121 | shader->set("uViewProjection", viewProjection); | ||
| 122 | map->tileset().sheet().texture().bind(0); | ||
| 123 | glDisable(GL_DEPTH_TEST); | ||
| 124 | glDisable(GL_CULL_FACE); | ||
| 125 | glEnable(GL_BLEND); | ||
| 126 | glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // 乗算済みアルファ(loadSpriteTexture) / premultiplied alpha | ||
| 127 | glBindVertexArray(vao); | ||
| 128 | // 行は続けて並んでいるので、見える行は一続きの範囲:添字は0から、頂点はbaseVertexだけずらす | ||
| 129 | // Rows are stored one after another, so the visible rows are one contiguous range: indices start at 0, vertices are | ||
| 130 | // shifted by baseVertex | ||
| 131 | glDrawElementsBaseVertex(GL_TRIANGLES, count * 6, GL_UNSIGNED_INT, nullptr, (layer.firstQuad + first) * 4); | ||
| 132 | glBindVertexArray(0); | ||
| 133 | frameStats.quads += count; | ||
| 134 | ++frameStats.drawCalls; | ||
| 135 | } | ||
| 136 | |||
| 137 | void TileRenderer::drawAnimated(SpriteBatch &batch, int index, const Rect &visible, float time, float spriteLayer) const { | ||
| 138 | if (!map || index < 0 || index >= static_cast<int>(layers.size())) return; | ||
| 139 | const SpriteSheet &sheet = map->tileset().sheet(); | ||
| 140 | for (const Animated &a : layers[static_cast<size_t>(index)].animated) { | ||
| 141 | if (a.position.y + kTile <= visible.top() || a.position.y >= visible.bottom() || a.position.x + kTile <= visible.left() || | ||
| 142 | a.position.x >= visible.right()) | ||
| 143 | continue; | ||
| 144 | const AnimationClip &clip = *a.kind->anim; | ||
| 145 | size_t frame = static_cast<size_t>(time * clip.fps) % clip.frames.size(); | ||
| 146 | Sprite s = sheet.sprite(clip.frames[frame], a.position); | ||
| 147 | s.layer = spriteLayer; | ||
| 148 | batch.draw(s); | ||
| 149 | } | ||
| 150 | } | ||
ファイル: /dev/null | b/games/rpg/src/tile_renderer.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,75 @@ | |||
| 1 | // タイルマップの描画(第33章):動かないタイルは読み込み時に一度だけ作る静的な頂点バッファに入れる | ||
| 2 | // Drawing tile maps (chapter 33): tiles that never change go into a static vertex buffer built once at load time | ||
| 3 | // | ||
| 4 | // SpriteBatchは毎フレーム頂点を作ってGPUへ送る(動的なバッファ)。タイルは変わらないので、送るのは一度だけでいい: | ||
| 5 | // 不変のストレージ(glNamedBufferStorage、フラグ0)に全部の層の四角形を行の順に並べ、見えている行の範囲だけを | ||
| 6 | // glDrawElementsBaseVertexの1回で描く。動くタイル(水)は数が少ないので、毎フレームSpriteBatchで描く | ||
| 7 | // The SpriteBatch builds vertices every frame and sends them to the GPU (a dynamic buffer). Tiles never change, so | ||
| 8 | // they only need to be sent once: the quads of all layers go row by row into immutable storage (glNamedBufferStorage, | ||
| 9 | // flags 0), and only the range of visible rows is drawn, with one glDrawElementsBaseVertex per layer. Animated tiles | ||
| 10 | // (water) are few, so they go through the SpriteBatch every frame | ||
| 11 | #pragma once | ||
| 12 | |||
| 13 | #include "tilemap.hh" | ||
| 14 | |||
| 15 | #include "engine/buffer.hh" | ||
| 16 | #include "engine/shader.hh" | ||
| 17 | #include "engine/sprite_batch.hh" | ||
| 18 | |||
| 19 | #include <optional> | ||
| 20 | #include <vector> | ||
| 21 | |||
| 22 | class TileRenderer { | ||
| 23 | public: | ||
| 24 | // シェーダーはエンジンのsprite.vert/.frag(頂点の形もSpriteBatchと同じ) / the shader is the engine's | ||
| 25 | // sprite.vert/.frag (the vertex format is the same as the SpriteBatch's) | ||
| 26 | static std::optional<TileRenderer> create(); | ||
| 27 | ~TileRenderer(); | ||
| 28 | TileRenderer(const TileRenderer &) = delete; | ||
| 29 | TileRenderer &operator=(const TileRenderer &) = delete; | ||
| 30 | TileRenderer(TileRenderer &&other) noexcept; | ||
| 31 | TileRenderer &operator=(TileRenderer &&other) noexcept; | ||
| 32 | |||
| 33 | // マップの全部の層の頂点を作り、新しいバッファに入れる(不変のストレージは大きさを変えられない:作り直す) | ||
| 34 | // Builds the vertices of every layer of the map into new buffers (immutable storage cannot change size: rebuild) | ||
| 35 | void build(const Tilemap &map); | ||
| 36 | // 層の動かないタイルのうち、visibleに入る行だけを描く(描画コール1回) / draws the still tiles of a layer, only the | ||
| 37 | // rows inside `visible` (one draw call) | ||
| 38 | void drawLayer(int layer, const Mat4 &viewProjection, const Rect &visible); | ||
| 39 | // 層の動くタイルをバッチに足す(呼ぶ側がbegin/endする) / adds the layer's animated tiles to the batch (the caller | ||
| 40 | // does begin/end) | ||
| 41 | void drawAnimated(SpriteBatch &batch, int layer, const Rect &visible, float time, float spriteLayer = 0.0f) const; | ||
| 42 | bool hasAnimated(int layer) const { return !layers[static_cast<size_t>(layer)].animated.empty(); } | ||
| 43 | |||
| 44 | // 前のフレームの数(HUD用) / counts of the last frame (for the HUD) | ||
| 45 | struct Stats { | ||
| 46 | int quads = 0; // 描いた四角形 / quads drawn | ||
| 47 | int drawCalls = 0; | ||
| 48 | int totalQuads = 0; // バッファの中の全部 / everything in the buffer | ||
| 49 | }; | ||
| 50 | const Stats &stats() const { return frameStats; } | ||
| 51 | void resetStats() { frameStats = {0, 0, frameStats.totalQuads}; } | ||
| 52 | |||
| 53 | private: | ||
| 54 | TileRenderer() = default; | ||
| 55 | void release(); | ||
| 56 | |||
| 57 | struct Animated { | ||
| 58 | Vec2 position; | ||
| 59 | const TileKind *kind; | ||
| 60 | int row; | ||
| 61 | }; | ||
| 62 | struct Layer { | ||
| 63 | int firstQuad = 0; // バッファの中の最初の四角形 / the layer's first quad in the buffer | ||
| 64 | std::vector<int> rowStart; // rows + 1個:行rの最初の四角形(層の中の番号) / rows + 1 entries: the first quad | ||
| 65 | // of row r (counted inside the layer) | ||
| 66 | std::vector<Animated> animated; | ||
| 67 | }; | ||
| 68 | |||
| 69 | std::optional<Shader> shader; | ||
| 70 | Buffer vertices, indices; | ||
| 71 | GLuint vao = 0; | ||
| 72 | const Tilemap *map = nullptr; | ||
| 73 | std::vector<Layer> layers; | ||
| 74 | Stats frameStats; | ||
| 75 | }; | ||
ファイル: /dev/null | b/games/rpg/src/tilemap.cc
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,246 @@ | |||
| 1 | // タイルセットとマップの読み込み:1行ずつ、最初の単語で命令を見分ける | ||
| 2 | // Loading tilesets and maps: line by line, the first word says what the line is | ||
| 3 | #include "tilemap.hh" | ||
| 4 | |||
| 5 | #include "engine/file_util.hh" | ||
| 6 | |||
| 7 | #include <charconv> | ||
| 8 | #include <cmath> | ||
| 9 | #include <cstdio> | ||
| 10 | #include <sstream> | ||
| 11 | |||
| 12 | std::string folderOf(const std::string &path) { | ||
| 13 | size_t slash = path.find_last_of("/\\"); | ||
| 14 | return slash == std::string::npos ? std::string() : path.substr(0, slash + 1); | ||
| 15 | } | ||
| 16 | |||
| 17 | // 「ファイル:行: 説明」の形で出す(エディターやIDEがそこへ飛べる) / prints "file:line: message" (editors and IDEs can | ||
| 18 | // jump there) | ||
| 19 | static void parseError(const std::string &path, int line, const std::string &what) { | ||
| 20 | fprintf(stderr, "%s:%d: %s\n", path.c_str(), line, what.c_str()); | ||
| 21 | } | ||
| 22 | |||
| 23 | static bool toInt(std::string_view s, int &out) { | ||
| 24 | auto [end, ec] = std::from_chars(s.data(), s.data() + s.size(), out); | ||
| 25 | return ec == std::errc() && end == s.data() + s.size(); | ||
| 26 | } | ||
| 27 | |||
| 28 | // ---------------------------------------------------------------------------------------------------- Tileset | ||
| 29 | |||
| 30 | std::optional<Tileset> Tileset::load(const std::string &path) { | ||
| 31 | std::optional<std::string> text = readTextFile(path); | ||
| 32 | if (!text) { | ||
| 33 | fprintf(stderr, "%s: 読めない / cannot read\n", path.c_str()); | ||
| 34 | return std::nullopt; | ||
| 35 | } | ||
| 36 | Tileset set; | ||
| 37 | set.bySymbol.fill(-1); | ||
| 38 | bool haveAtlas = false; | ||
| 39 | std::istringstream lines(*text); | ||
| 40 | std::string line; | ||
| 41 | int number = 0; | ||
| 42 | while (std::getline(lines, line)) { | ||
| 43 | ++number; | ||
| 44 | std::istringstream in(line); | ||
| 45 | std::string command; | ||
| 46 | if (!(in >> command) || command[0] == '#') continue; | ||
| 47 | if (command == "atlas") { | ||
| 48 | std::string file; | ||
| 49 | in >> file; | ||
| 50 | std::optional<SpriteSheet> sheet = SpriteSheet::loadAtlas(folderOf(path) + file); | ||
| 51 | if (!sheet) return std::nullopt; // loadAtlasが理由を出した / loadAtlas printed why | ||
| 52 | set.atlas = std::move(sheet); | ||
| 53 | haveAtlas = true; | ||
| 54 | } else if (command == "tile") { | ||
| 55 | std::string symbol, sprite; | ||
| 56 | if (!(in >> symbol >> sprite) || symbol.size() != 1 || static_cast<unsigned char>(symbol[0]) >= 128 || | ||
| 57 | symbol[0] == '.') { | ||
| 58 | parseError(path, number, "tile <1文字(.以外のASCII) / one ASCII character other than .> <sprite> ..."); | ||
| 59 | return std::nullopt; | ||
| 60 | } | ||
| 61 | if (!haveAtlas) { | ||
| 62 | parseError(path, number, "atlasの行が先に要る / the atlas line must come first"); | ||
| 63 | return std::nullopt; | ||
| 64 | } | ||
| 65 | TileKind kind{.symbol = symbol[0], .name = sprite, .sprite = set.atlas->find(sprite)}; | ||
| 66 | if (kind.sprite < 0) { | ||
| 67 | parseError(path, number, "アトラスにないスプライト / sprite not in the atlas: " + sprite); | ||
| 68 | return std::nullopt; | ||
| 69 | } | ||
| 70 | std::string flag; | ||
| 71 | while (in >> flag) { | ||
| 72 | if (flag == "solid") kind.solid = true; | ||
| 73 | else if (flag == "anim") { | ||
| 74 | std::string clip; | ||
| 75 | in >> clip; | ||
| 76 | kind.anim = set.atlas->clip(clip); | ||
| 77 | if (!kind.anim) { | ||
| 78 | parseError(path, number, "アトラスにないクリップ / clip not in the atlas: " + clip); | ||
| 79 | return std::nullopt; | ||
| 80 | } | ||
| 81 | } else { | ||
| 82 | parseError(path, number, "知らない印 / unknown flag: " + flag); | ||
| 83 | return std::nullopt; | ||
| 84 | } | ||
| 85 | } | ||
| 86 | if (set.bySymbol[static_cast<size_t>(kind.symbol)] >= 0) { | ||
| 87 | parseError(path, number, std::string("同じ文字が二度 / the same character twice: ") + kind.symbol); | ||
| 88 | return std::nullopt; | ||
| 89 | } | ||
| 90 | set.bySymbol[static_cast<size_t>(kind.symbol)] = static_cast<int>(set.kinds.size()); | ||
| 91 | set.kinds.push_back(std::move(kind)); | ||
| 92 | } else { | ||
| 93 | parseError(path, number, "知らない命令 / unknown command: " + command); | ||
| 94 | return std::nullopt; | ||
| 95 | } | ||
| 96 | } | ||
| 97 | if (!haveAtlas) { | ||
| 98 | parseError(path, number, "atlasの行がない / no atlas line"); | ||
| 99 | return std::nullopt; | ||
| 100 | } | ||
| 101 | return set; | ||
| 102 | } | ||
| 103 | |||
| 104 | int Tileset::kindIndex(char symbol) const { | ||
| 105 | unsigned char c = static_cast<unsigned char>(symbol); | ||
| 106 | return c < 128 ? bySymbol[c] : -1; | ||
| 107 | } | ||
| 108 | |||
| 109 | const TileKind *Tileset::find(char symbol) const { | ||
| 110 | int i = kindIndex(symbol); | ||
| 111 | return i < 0 ? nullptr : &kinds[static_cast<size_t>(i)]; | ||
| 112 | } | ||
| 113 | |||
| 114 | // ---------------------------------------------------------------------------------------------------- MapObject | ||
| 115 | |||
| 116 | std::string_view MapObject::get(std::string_view key, std::string_view fallback) const { | ||
| 117 | for (const auto &[k, v] : properties) | ||
| 118 | if (k == key) return v; | ||
| 119 | return fallback; | ||
| 120 | } | ||
| 121 | |||
| 122 | int MapObject::getInt(std::string_view key, int fallback) const { | ||
| 123 | int value = 0; | ||
| 124 | return toInt(get(key), value) ? value : fallback; | ||
| 125 | } | ||
| 126 | |||
| 127 | // ---------------------------------------------------------------------------------------------------- Tilemap | ||
| 128 | |||
| 129 | std::optional<Tilemap> Tilemap::load(const std::string &path) { | ||
| 130 | std::optional<std::string> text = readTextFile(path); | ||
| 131 | if (!text) { | ||
| 132 | fprintf(stderr, "%s: 読めない / cannot read (プロジェクトのルートから実行した? / running from the project root?)\n", | ||
| 133 | path.c_str()); | ||
| 134 | return std::nullopt; | ||
| 135 | } | ||
| 136 | Tilemap map; | ||
| 137 | map.filePath = path; | ||
| 138 | std::istringstream lines(*text); | ||
| 139 | std::string line; | ||
| 140 | int number = 0; | ||
| 141 | auto fail = [&](const std::string &what) { | ||
| 142 | parseError(path, number, what); | ||
| 143 | return std::nullopt; | ||
| 144 | }; | ||
| 145 | while (std::getline(lines, line)) { | ||
| 146 | ++number; | ||
| 147 | if (!line.empty() && line.back() == '\r') line.pop_back(); // Windowsの改行 / Windows line endings | ||
| 148 | std::istringstream in(line); | ||
| 149 | std::string command; | ||
| 150 | if (!(in >> command) || command[0] == '#') continue; | ||
| 151 | if (command == "map") { | ||
| 152 | in >> map.mapName; | ||
| 153 | } else if ((command == "tileset" || command == "size") && !map.tileLayers.empty()) { | ||
| 154 | // 読んだ層は今の大きさとタイルセットの番号で出来ている:後から変えると層が合わなくなる | ||
| 155 | // The layers already read use the current size and the tileset's kind numbers: changing them later would not | ||
| 156 | // match those layers | ||
| 157 | return fail(command + "はlayerより前に書く / " + command + " must come before the first layer"); | ||
| 158 | } else if (command == "tileset") { | ||
| 159 | std::string file; | ||
| 160 | in >> file; | ||
| 161 | std::optional<Tileset> set = Tileset::load(folderOf(path) + file); | ||
| 162 | if (!set) return fail("タイルセットを読めない / cannot load the tileset " + file); | ||
| 163 | map.tiles = std::make_shared<const Tileset>(std::move(*set)); | ||
| 164 | } else if (command == "size") { | ||
| 165 | 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)"); | ||
| 167 | } else if (command == "layer") { | ||
| 168 | if (!map.tiles || map.cols == 0) return fail("layerの前にtilesetとsizeが要る / tileset and size must come first"); | ||
| 169 | TileLayer layer; | ||
| 170 | in >> layer.name; | ||
| 171 | std::string flag; | ||
| 172 | while (in >> flag) { | ||
| 173 | if (flag == "above") layer.above = true; | ||
| 174 | else return fail("知らない印 / unknown flag: " + flag); | ||
| 175 | } | ||
| 176 | layer.cells.assign(static_cast<size_t>(map.cols * map.rows), -1); | ||
| 177 | // 続くrows行が格子。1文字が1マス / the next `rows` lines are the grid, one character per cell | ||
| 178 | for (int row = 0; row < map.rows; ++row) { | ||
| 179 | if (!std::getline(lines, line)) return fail("格子の行が足りない / the grid has too few rows"); | ||
| 180 | ++number; | ||
| 181 | if (!line.empty() && line.back() == '\r') line.pop_back(); | ||
| 182 | if (static_cast<int>(line.size()) != map.cols) | ||
| 183 | return fail("格子の行の長さが" + std::to_string(line.size()) + "(" + std::to_string(map.cols) + | ||
| 184 | "のはず) / grid row has " + std::to_string(line.size()) + " characters (expected " + | ||
| 185 | std::to_string(map.cols) + ")"); | ||
| 186 | for (int col = 0; col < map.cols; ++col) { | ||
| 187 | char c = line[static_cast<size_t>(col)]; | ||
| 188 | if (c == '.') continue; | ||
| 189 | int kind = map.tiles->kindIndex(c); | ||
| 190 | if (kind < 0) return fail(std::string("タイルセットにない文字 / character not in the tileset: '") + c + "'"); | ||
| 191 | layer.cells[static_cast<size_t>(row * map.cols + col)] = kind; | ||
| 192 | } | ||
| 193 | } | ||
| 194 | map.tileLayers.push_back(std::move(layer)); | ||
| 195 | } else if (command == "object") { | ||
| 196 | MapObject object; | ||
| 197 | int col = 0, row = 0; | ||
| 198 | std::string x, y; | ||
| 199 | if (!(in >> object.kind >> object.name >> x >> y) || !toInt(x, col) || !toInt(y, row)) | ||
| 200 | return fail("object <種類> <名前> <列> <行> [key=value …] / object <kind> <name> <col> <row> [key=value ...]"); | ||
| 201 | std::string pair; | ||
| 202 | while (in >> pair) { | ||
| 203 | size_t eq = pair.find('='); | ||
| 204 | if (eq == std::string::npos || eq == 0) return fail("key=valueのはず / expected key=value: " + pair); | ||
| 205 | object.properties.emplace_back(pair.substr(0, eq), pair.substr(eq + 1)); | ||
| 206 | } | ||
| 207 | int w = object.getInt("w", 1), h = object.getInt("h", 1); | ||
| 208 | object.rect = {kTile * static_cast<float>(col), kTile * static_cast<float>(row), kTile * static_cast<float>(w), | ||
| 209 | kTile * static_cast<float>(h)}; | ||
| 210 | map.mapObjects.push_back(std::move(object)); | ||
| 211 | } else { | ||
| 212 | return fail("知らない命令 / unknown command: " + command); | ||
| 213 | } | ||
| 214 | } | ||
| 215 | if (!map.tiles || map.tileLayers.empty()) return fail("tilesetとlayerが要る / a tileset and layers are required"); | ||
| 216 | |||
| 217 | // 固さを一枚にまとめる:どれかの層の固いタイルがあれば通れない / combine solidity into one grid: a solid tile in any | ||
| 218 | // layer blocks the cell | ||
| 219 | map.solid.assign(static_cast<size_t>(map.cols * map.rows), false); | ||
| 220 | for (const TileLayer &layer : map.tileLayers) | ||
| 221 | for (size_t i = 0; i < layer.cells.size(); ++i) | ||
| 222 | if (layer.cells[i] >= 0 && map.tiles->kind(layer.cells[i]).solid) map.solid[i] = true; | ||
| 223 | return map; | ||
| 224 | } | ||
| 225 | |||
| 226 | const MapObject *Tilemap::findObject(std::string_view kind, std::string_view name) const { | ||
| 227 | for (const MapObject &o : mapObjects) | ||
| 228 | if (o.kind == kind && o.name == name) return &o; | ||
| 229 | return nullptr; | ||
| 230 | } | ||
| 231 | |||
| 232 | bool Tilemap::solidAt(int col, int row) const { | ||
| 233 | if (col < 0 || row < 0 || col >= cols || row >= rows) return true; | ||
| 234 | return solid[static_cast<size_t>(row * cols + col)]; | ||
| 235 | } | ||
| 236 | |||
| 237 | void Tilemap::solidRects(const Rect &area, std::vector<Rect> &out) const { | ||
| 238 | // areaに触れるマスだけを調べる(マップ全部の箱を作らない) / only the cells touching `area` are checked (no boxes | ||
| 239 | // for the whole map) | ||
| 240 | int c0 = static_cast<int>(std::floor(area.left() / kTile)), c1 = static_cast<int>(std::floor(area.right() / kTile)); | ||
| 241 | int r0 = static_cast<int>(std::floor(area.top() / kTile)), r1 = static_cast<int>(std::floor(area.bottom() / kTile)); | ||
| 242 | for (int row = r0; row <= r1; ++row) | ||
| 243 | for (int col = c0; col <= c1; ++col) | ||
| 244 | if (solidAt(col, row)) | ||
| 245 | out.push_back({kTile * static_cast<float>(col), kTile * static_cast<float>(row), kTile, kTile}); | ||
| 246 | } | ||
ファイル: /dev/null | b/games/rpg/src/tilemap.hh
| 前 | 新 | ||
|---|---|---|---|
| @@ -0,0 +1,117 @@ | |||
| 1 | // タイルマップ(第33章):タイルの種類の一覧(.tileset)と、文字の格子で書いたマップ(.map)を読む | ||
| 2 | // Tile maps (chapter 33): reads the list of tile kinds (.tileset) and maps written as character grids (.map) | ||
| 3 | // | ||
| 4 | // どちらも1行に1つの命令のテキスト。ライブラリなしで読めて、テキストエディターで地図が「見える」 | ||
| 5 | // Both are text files with one command per line: they parse without a library, and in a text editor you *see* the map | ||
| 6 | #pragma once | ||
| 7 | |||
| 8 | #include "engine/animation.hh" | ||
| 9 | #include "engine/rect.hh" | ||
| 10 | #include "engine/sprite_sheet.hh" | ||
| 11 | |||
| 12 | #include <array> | ||
| 13 | #include <memory> | ||
| 14 | #include <optional> | ||
| 15 | #include <string> | ||
| 16 | #include <string_view> | ||
| 17 | #include <vector> | ||
| 18 | |||
| 19 | constexpr int kTileSize = 16; | ||
| 20 | constexpr float kTile = 16.0f; | ||
| 21 | |||
| 22 | // タイルの種類(.tilesetの「tile」の1行) / a tile kind (one "tile" line of the .tileset) | ||
| 23 | struct TileKind { | ||
| 24 | char symbol = '.'; // マップの格子で使う文字 / the character used in map grids | ||
| 25 | std::string name; // アトラスのスプライト名 / the sprite's name in the atlas | ||
| 26 | int sprite = -1; // SpriteSheetの番号 / SpriteSheet index | ||
| 27 | bool solid = false; // 通れない / blocks movement | ||
| 28 | const AnimationClip *anim = nullptr; // 動くタイル(水)。nullptr = 動かない / animated tile (water); nullptr = still | ||
| 29 | }; | ||
| 30 | |||
| 31 | // タイルセット:アトラス(画像)+文字 → 種類の表。全部のマップで同じ文字は同じタイル | ||
| 32 | // A tileset: the atlas (image) + the character → kind table. A character means the same tile in every map | ||
| 33 | class Tileset { | ||
| 34 | public: | ||
| 35 | // 書式 / format: | ||
| 36 | // atlas <file.atlas> (.tilesetからの相対パス / relative to the .tileset) | ||
| 37 | // tile <char> <sprite> [solid] [anim <clip>] | ||
| 38 | // # コメント / comment | ||
| 39 | static std::optional<Tileset> load(const std::string &path); | ||
| 40 | |||
| 41 | const SpriteSheet &sheet() const { return *atlas; } | ||
| 42 | // 文字の種類。'.'や知らない文字はnullptr / the kind of a character; nullptr for '.' and unknown characters | ||
| 43 | const TileKind *find(char symbol) const; | ||
| 44 | int kindIndex(char symbol) const; | ||
| 45 | const TileKind &kind(int index) const { return kinds[static_cast<size_t>(index)]; } | ||
| 46 | int kindCount() const { return static_cast<int>(kinds.size()); } | ||
| 47 | |||
| 48 | private: | ||
| 49 | Tileset() = default; | ||
| 50 | std::optional<SpriteSheet> atlas; // SpriteSheetは読み込みでしか作れない / a SpriteSheet only comes from loading | ||
| 51 | std::vector<TileKind> kinds; | ||
| 52 | std::array<int, 128> bySymbol{}; // ASCIIの文字 → kindsの番号(-1 = なし) / ASCII character → kinds index (-1 = none) | ||
| 53 | }; | ||
| 54 | |||
| 55 | // マップの物(扉・出発点・宝箱・人…)。位置と大きさはピクセル、性質は key=value の文字列 | ||
| 56 | // An object on a map (door, spawn point, chest, person...). Position and size in pixels, properties as key=value | ||
| 57 | struct MapObject { | ||
| 58 | std::string kind; // spawn, door, … | ||
| 59 | std::string name; | ||
| 60 | Rect rect; // ピクセル / pixels | ||
| 61 | std::vector<std::pair<std::string, std::string>> properties; | ||
| 62 | |||
| 63 | std::string_view get(std::string_view key, std::string_view fallback = "") const; | ||
| 64 | int getInt(std::string_view key, int fallback) const; | ||
| 65 | }; | ||
| 66 | |||
| 67 | // 1枚の層:width × heightのマス、各マスはタイルの種類の番号(-1 = 空) / one layer: width × height cells, each the | ||
| 68 | // index of a tile kind (-1 = empty) | ||
| 69 | struct TileLayer { | ||
| 70 | std::string name; | ||
| 71 | bool above = false; // trueなら人物の上に描く(木の上半分・屋根の棟) / drawn above the characters (tree tops, | ||
| 72 | // roof ridges) | ||
| 73 | std::vector<int> cells; // 行ごと(row * width + col) / row by row (row * width + col) | ||
| 74 | }; | ||
| 75 | |||
| 76 | class Tilemap { | ||
| 77 | public: | ||
| 78 | // 書式 / format (see games/rpg/assets/maps/*.map): | ||
| 79 | // map <name> 名前 / the name | ||
| 80 | // tileset <file.tileset> .mapからの相対パス / relative to the .map | ||
| 81 | // size <width> <height> マスの数 / in tiles | ||
| 82 | // layer <name> [above] 続くheight行が格子(1文字 = 1マス、'.' = 空) / the next `height` lines are the grid | ||
| 83 | // (1 character = 1 tile, '.' = empty) | ||
| 84 | // object <kind> <name> <col> <row> [key=value …] w= h= でマスの大きさ(既定1×1) / w= h= set the size in tiles | ||
| 85 | // (default 1 × 1) | ||
| 86 | // エラーは「ファイル:行: 説明」でstderrに出してnullopt / errors go to stderr as "file:line: message", then nullopt | ||
| 87 | static std::optional<Tilemap> load(const std::string &path); | ||
| 88 | |||
| 89 | const std::string &name() const { return mapName; } | ||
| 90 | const std::string &path() const { return filePath; } | ||
| 91 | const Tileset &tileset() const { return *tiles; } | ||
| 92 | int width() const { return cols; } | ||
| 93 | int height() const { return rows; } | ||
| 94 | Vec2 pixelSize() const { return {kTile * static_cast<float>(cols), kTile * static_cast<float>(rows)}; } | ||
| 95 | const std::vector<TileLayer> &layers() const { return tileLayers; } | ||
| 96 | const std::vector<MapObject> &objects() const { return mapObjects; } | ||
| 97 | const MapObject *findObject(std::string_view kind, std::string_view name) const; | ||
| 98 | |||
| 99 | // そのマスに固いタイルがあるか(どれかの層で)。マップの外も固い(端から出られない) | ||
| 100 | // Is there a solid tile in the cell (in any layer)? Outside the map counts as solid (you cannot walk off the edge) | ||
| 101 | bool solidAt(int col, int row) const; | ||
| 102 | // areaに触れる固いマスの箱をoutに足す(moveAndSlideに渡す) / appends the boxes of the solid cells touching `area` | ||
| 103 | // to out (to pass to moveAndSlide) | ||
| 104 | void solidRects(const Rect &area, std::vector<Rect> &out) const; | ||
| 105 | |||
| 106 | private: | ||
| 107 | Tilemap() = default; | ||
| 108 | std::string mapName, filePath; | ||
| 109 | std::shared_ptr<const Tileset> tiles; // 同じタイルセットを何枚ものマップで共有できる / several maps can share one | ||
| 110 | int cols = 0, rows = 0; | ||
| 111 | std::vector<TileLayer> tileLayers; | ||
| 112 | std::vector<MapObject> mapObjects; | ||
| 113 | std::vector<bool> solid; // 全部の層をまとめた固さ / the solidity of all layers combined | ||
| 114 | }; | ||
| 115 | |||
| 116 | // パスのフォルダ部分("a/b/c.map" → "a/b/") / the folder part of a path ("a/b/c.map" → "a/b/") | ||
| 117 | std::string folderOf(const std::string &path); | ||
コメント(0)
まだコメントはありません。
ログインするとコメント出来ます。