diff --git a/games/rpg/CMakeLists.txt b/games/rpg/CMakeLists.txt new file mode 100644 index 0000000..a52d0ed --- /dev/null +++ b/games/rpg/CMakeLists.txt @@ -0,0 +1,11 @@ +# 見下ろし型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) diff --git a/games/rpg/README.md b/games/rpg/README.md new file mode 100644 index 0000000..4499154 --- /dev/null +++ b/games/rpg/README.md @@ -0,0 +1,22 @@ +# RPG(第33〜35章) / RPG (chapters 33-35) + +見下ろし型のRPG。プロジェクトのルートから実行する / A top-down RPG. Run it from the project root: + +```sh +./build/games/rpg/rpg # Visual Studio: build\games\rpg\Debug\rpg.exe (working directory = the root) +``` + +| キー / Key | | +|---|---| +| 矢印 / WASD | 移動 / move | +| Shift | 走る / run | +| 1 2 3 | 層の表示(地面・飾り・上の層) / toggle the layers (ground, decor, overlay) | +| B | 当たり判定の箱 / collision boxes | +| Z | 引いて見る(行のカリングが見える) / zoom out (shows the row culling) | +| H | HUD | +| R | マップをファイルから読み直す / reload the map from its file | +| Esc | 終了 / quit | + +マップは `assets/maps/*.map`(テキスト)。書式は `src/tilemap.hh`、タイルの文字は `assets/tiles.tileset`。 +Maps are `assets/maps/*.map` (text). The format is described in `src/tilemap.hh`, the tile characters in +`assets/tiles.tileset`. diff --git a/games/rpg/assets/LICENSE.txt b/games/rpg/assets/LICENSE.txt new file mode 100644 index 0000000..147e707 --- /dev/null +++ b/games/rpg/assets/LICENSE.txt @@ -0,0 +1,9 @@ +games/rpg/assets/ のファイルはこのチュートリアルのために作者が自作したもの(作者のPythonのスクリプトで生成。スクリプトはこのプロジェクトには含まれない)。自由に使ってよい。 +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. + +tiles.png/.atlas 16×16のタイル(草・道・水・木・家・家具…、1ピクセルの押し出し付き) / 16×16 tiles (grass, path, + water, trees, houses, furniture..., 1 px extruded) (chapter 33) +characters.png 人物5人 × 4方向の歩き(16×16、9コマずつ) / five characters × 4-direction walk (16×16, 9 frames + each) (chapter 33) +tiles.tileset タイルの文字・固さ・動き(手書き) / tile characters, solidity, animation (hand-written, chapter 33) +maps/village.map 村のマップ / the village map (chapter 33; edit by hand freely) diff --git a/games/rpg/assets/characters.png b/games/rpg/assets/characters.png new file mode 100644 index 0000000..28d8e72 Binary files /dev/null and b/games/rpg/assets/characters.png differ diff --git a/games/rpg/assets/maps/village.map b/games/rpg/assets/maps/village.map new file mode 100644 index 0000000..09d6c08 --- /dev/null +++ b/games/rpg/assets/maps/village.map @@ -0,0 +1,99 @@ +# 村 / Village +# 書式は games/rpg/src/tilemap.hh、文字の意味は ../tiles.tileset / format: games/rpg/src/tilemap.hh, +# characters: ../tiles.tileset ('.' = 空 / empty) +map village +tileset ../tiles.tileset +size 40 28 + +layer ground +,,,,,,,,,,,,,,,,,,,;,,,,,,,;;,,,,,,,,,;, +,,,;;,,,,,;,;,,,,,,,,,,;,,,;,;,,,,,,,,;; +,,,,,,,,,;,,,;,,,,,,,,,,,^^,,,,,,,,;,,,, +,,;,,,,,;,,,,,;;,,,;,,,,,~~,,;;,,,,,,,,, +;,,;,,,,,,,;;,,,,,;,,,,,;~~,,,;,,,,,;,,, +,,,;,,,,,,,,,,,,,,,,;,,,;~~,,,,,,;,,,,,; +,,,,,,,,,,,,,,,,,,,,,,,,,~~,,,,,,,,;;,,, +,,,,,,,,;,,;,;,,,,,,,,;;,~~,,,,;,,,,,,,, +,,,,,,,:,,,,,,,,,=,,,,,;,~~,,,,=,,,,,;,, +,,,,,,,=,,,,,,,,,=,,,,,,,~~,,,,=,;,,,,;, +,======:=============:===HH===:==:==:=== +,====:==============:====HH==:====:===== +,,,,,,,,,,,,,,,,;;,=,,;,,^^,,,;,,,,,,,,, +,,,,,,,,,,,;,,,ooooooooo;~~,,,,,,,,,;,,, +,,,==:=====,,,,ooooooooo,~~;,,,,,,,,,,,; +,,;:=======,,,;ooooooooo;~~,,;;,,,,,,,,, +,,,==:=====;,,,ooooooooo,~~,,,,,,,,,,,,, +,,,,,,,,,,,,,,,ooooooooo,~~,,,,,,,,,,,,, +,,;;;,,,,,,,;,,ooooooooo;~~,,,;,,,,,,,,, +,,,,;,;,,,,,,,,,,,,,,,,;,~~,,,,,,,,,,,,; +,,,^^^^^^^;,,,,,;,,,,,,,,~~;,,,,,;,,,,,; +,,,~~~~~~~,,,,,,,,;,,,,,,~~,,;,,,,,,,,,; +,,,~~~~~~~,,,,,,,,,;,,,,,~~,,,,,,,,;;,,, +,,,~~~~~~~,,,,,,,,,,,,,,,~~,,;,,,,,;,,,, +,,,,,,,,,,,;,,;,,,,,,,,,,~~;,,,,,,,,,,,, +,,,,,,,,,,,,,,,,,,,,,,,,,~~,,;,,,,;,,,,, +,,,;;,,,;,,,;,,,,,,,,,,,;~~,,,,,,,,,,,,, +,;,,,,,,,,,,,;,,,,,,;,;,,,,,,,;,,,,,,,,; + +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 +b..........*...........*...............b +T..%...................................b +b....................................... +T....................................... +b..*........*..................*....*..b +T.----------...U*......U....b........T.T +b.|."""""".|...........................b +T.|."""""".|.......O..........T...T....T +b.|."""""".|...........................b +T.-----.----....................T...b..T +b..............U......*U.....*.........b +T.*........S...........................T +b............T....*............b....T..b +T.........*.....R....*..b........R.....T +b.*...........T....b.........T.....*...b +T..........*...........T...............T +b.R.*...*.R.T....b.........R.....T.....b +T....................T.................T +.......................................b +TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT + +layer overlay above +tttttttttttttttttttttttttttttttttttttttt +........................................ +t......................................t +........................................ +t.............aaaaaaa..................t +.....aaaaa...................aaaaa...... +t......................................t +........................................ +t....................................... +........................................ +t....................................... +........................................ +t....................................t.t +........................................ +t.............................t...t....t +........................................ +t...............................t......t +........................................ +t......................................t +.............t......................t... +t......................................t +..............t..............t.......... +t......................t...............t +............t....................t...... +t....................t.................t +........................................ +tttttttttttttttttttttttttttttttttttttttt +........................................ + +# 物:object <種類> <名前> <列> <行> [key=value …] / objects: kind name col row [key=value ...] +object spawn start 7 9 face=down diff --git a/games/rpg/assets/tiles.atlas b/games/rpg/assets/tiles.atlas new file mode 100644 index 0000000..b0593c7 --- /dev/null +++ b/games/rpg/assets/tiles.atlas @@ -0,0 +1,51 @@ +# rpg tiles (generated by the author's own script): 16x16, extruded 1 px +image tiles.png +sprite grass 1 1 16 16 +sprite grass2 19 1 16 16 +sprite path 37 1 16 16 +sprite path2 55 1 16 16 +sprite cobble 73 1 16 16 +sprite water0 91 1 16 16 +sprite water1 109 1 16 16 +sprite shore0 127 1 16 16 +sprite shore1 145 1 16 16 +sprite bridge 163 1 16 16 +sprite floor 181 1 16 16 +sprite rug 199 1 16 16 +sprite doormat 217 1 16 16 +sprite wall_in 235 1 16 16 +sprite wall_in_window 1 19 16 16 +sprite void 19 19 16 16 +sprite tree_top 37 19 16 16 +sprite tree_bottom 55 19 16 16 +sprite bush 73 19 16 16 +sprite rock 91 19 16 16 +sprite flowers 109 19 16 16 +sprite tall_grass 127 19 16 16 +sprite fence 145 19 16 16 +sprite fence_v 163 19 16 16 +sprite sign 181 19 16 16 +sprite well 199 19 16 16 +sprite stump 217 19 16 16 +sprite mushrooms 235 19 16 16 +sprite house_wall 1 37 16 16 +sprite house_window 19 37 16 16 +sprite house_door 37 37 16 16 +sprite roof_ridge 55 37 16 16 +sprite roof 73 37 16 16 +sprite roof_eave 91 37 16 16 +sprite bed_top 109 37 16 16 +sprite bed_bottom 127 37 16 16 +sprite bookshelf 145 37 16 16 +sprite table 163 37 16 16 +sprite stool 181 37 16 16 +sprite pot 199 37 16 16 +sprite plant 217 37 16 16 +sprite hearth 235 37 16 16 +sprite crate 1 55 16 16 +sprite barrel 19 55 16 16 +sprite chest_closed 37 55 16 16 +sprite chest_open 55 55 16 16 +sprite gate 73 55 16 16 +clip water 2 loop water0 water1 +clip shore 2 loop shore0 shore1 diff --git a/games/rpg/assets/tiles.png b/games/rpg/assets/tiles.png new file mode 100644 index 0000000..25eca2d Binary files /dev/null and b/games/rpg/assets/tiles.png differ diff --git a/games/rpg/assets/tiles.tileset b/games/rpg/assets/tiles.tileset new file mode 100644 index 0000000..700d6f9 --- /dev/null +++ b/games/rpg/assets/tiles.tileset @@ -0,0 +1,54 @@ +# タイルの種類:マップの格子の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 ] +# '.' はどの層でも「空」 / '.' 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 +tile _ floor +tile r rug +tile m doormat +tile w wall_in solid +tile n wall_in_window solid +tile x void solid + +# 飾り(人物の下に描く) / decoration (drawn below the characters) +tile T tree_bottom solid +tile b bush solid +tile R rock solid +tile * flowers +tile " tall_grass +tile - fence solid +tile | fence_v solid +tile S sign solid +tile O well solid +tile s stump solid +tile % mushrooms +tile M house_wall solid +tile W house_window solid +tile d house_door solid +tile D house_door +tile A roof solid +tile L roof_eave solid +tile B bed_top solid +tile E bed_bottom solid +tile K bookshelf solid +tile Q table solid +tile c stool +tile p pot solid +tile P plant solid +tile F hearth solid +tile X crate solid +tile U barrel solid + +# 人物の上に重ねる(layer … above) / drawn above the characters (layer ... above) +tile t tree_top +tile a roof_ridge diff --git a/games/rpg/src/character.cc b/games/rpg/src/character.cc new file mode 100644 index 0000000..9856f71 --- /dev/null +++ b/games/rpg/src/character.cc @@ -0,0 +1,115 @@ +#include "character.hh" + +#include +#include +#include + +std::optional CharacterSheet::load(const std::string &path) { + std::optional grid = SpriteSheet::loadGrid(path, 16, 16, 1, 1); + if (!grid) return std::nullopt; + if (grid->count() % kColumns != 0) { + fprintf(stderr, "%s: 列が%dでない / not %d columns\n", path.c_str(), kColumns, kColumns); + return std::nullopt; + } + CharacterSheet cs; + cs.grid = std::move(grid); + // クリップは人ごと・方向ごとに作る(SpriteSheetのdequeに入るのでポインターは変わらない) + // Clips per character and direction (they live in the SpriteSheet's deque, so the pointers stay valid) + static const char *const kDir[] = {"down", "up", "side"}; + for (int look = 0; look < cs.looks(); ++look) + for (int d = 0; d < 3; ++d) { + int first = look * kColumns + d * 3; + std::string base = std::to_string(look) + "." + kDir[d]; + cs.grid->addClip({.name = base + ".idle", .frames = {first}, .fps = 1.0f}); + // 歩き:A・立ち・B・立ち(8コマ/秒 = 0.5秒で一歩ずつ二歩) / walking: A, stand, B, stand (8 frames/s = two steps + // in 0.5 s) + cs.grid->addClip({.name = base + ".walk", .frames = {first + 1, first, first + 2, first}, .fps = 8.0f}); + cs.clips.push_back(cs.grid->clip(base + ".idle")); + cs.clips.push_back(cs.grid->clip(base + ".walk")); + } + return cs; +} + +const AnimationClip *CharacterSheet::clip(int look, Facing facing, bool walking) const { + int d = facing == Facing::Down ? 0 : facing == Facing::Up ? 1 : 2; // 左右は同じ絵(左はflipX) / left and right + // share pictures (left = flipX) + look = std::clamp(look, 0, looks() - 1); + return clips[static_cast(look * 6 + d * 2 + (walking ? 1 : 0))]; +} + +void Character::placeAt(Vec2 tileTopLeft) { + box = {tileTopLeft.x + 0.5f * (kTile - kFootBox.x), tileTopLeft.y + kTile - kFootBox.y, kFootBox.x, kFootBox.y}; + previous = box.position(); +} + +void Character::animate(const CharacterSheet &sheet, float dt) { + anim.play(moving ? sheet.walk(look, facing) : sheet.idle(look, facing)); + anim.update(dt); +} + +Vec2 Character::feet(float alpha) const { + Vec2 p = lerp(previous, box.position(), alpha); + return {p.x + 0.5f * box.w, p.y + box.h}; +} + +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; +} + +Facing facingFor(Vec2 move, Facing current) { + bool left = move.x < 0.0f, right = move.x > 0.0f, up = move.y < 0.0f, down = move.y > 0.0f; + if ((current == Facing::Left && left) || (current == Facing::Right && right) || (current == Facing::Up && up) || + (current == Facing::Down && down)) + return current; + if (left) return Facing::Left; + if (right) return Facing::Right; + if (up) return Facing::Up; + if (down) return Facing::Down; + return current; +} + +static bool blocked(const Rect &r, std::span solids) { + for (const Rect &s : solids) + if (overlaps(r, s)) return true; + return false; +} + +MoveResult moveOnMap(Rect &box, Vec2 delta, const Tilemap &map, std::span extra, std::vector &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; +} diff --git a/games/rpg/src/character.hh b/games/rpg/src/character.hh new file mode 100644 index 0000000..ef3af65 --- /dev/null +++ b/games/rpg/src/character.hh @@ -0,0 +1,72 @@ +// 人物(第33章):4方向の歩きの絵と、タイルにぶつかりながら動く足元の箱 +// Characters (chapter 33): 4-direction walk pictures, and a foot box that moves while colliding with tiles +#pragma once + +#include "tilemap.hh" + +#include "engine/animation.hh" +#include "engine/collision.hh" +#include "engine/sprite_sheet.hh" + +#include +#include +#include +#include + +enum class Facing { Down, Up, Left, Right }; + +// characters.png:1行が1人、9列 = 下向き(立ち・歩きA・歩きB)、上向き(同じ)、横向き(同じ、右向き) +// characters.png: one row per character, 9 columns = facing down (stand, step A, step B), up (the same), side (the +// same, facing right) +class CharacterSheet { +public: + static std::optional load(const std::string &path); + const SpriteSheet &sheet() const { return *grid; } + int looks() const { return grid->count() / kColumns; } // 何人分あるか / how many characters there are + const AnimationClip *idle(int look, Facing facing) const { return clip(look, facing, false); } + const AnimationClip *walk(int look, Facing facing) const { return clip(look, facing, true); } + + static constexpr int kColumns = 9; + +private: + CharacterSheet() = default; + const AnimationClip *clip(int look, Facing facing, bool walking) const; + std::optional grid; + std::vector clips; // look * 6 + 方向 * 2 + 歩き / look * 6 + direction * 2 + walking +}; + +// 当たり判定は足元の小さな箱。絵(16 × 16)はその下の真ん中に合わせて描く:頭は上のマスに重なってよい +// The collision box is a small box at the feet. The 16 × 16 picture is drawn aligned to its bottom center: the head +// may overlap the tile above +constexpr Vec2 kFootBox = {10.0f, 6.0f}; + +struct Character { + int look = 0; // characters.pngの行 / the row in characters.png + Rect box; // 足元の箱(ピクセル) / the foot box (pixels) + Vec2 previous; // 前のステップのbox.position()(描くときの補間) / box.position() of the last step (for + // interpolation when drawing) + Facing facing = Facing::Down; + bool moving = false; + Animator anim; + + // マス(col, row)の真ん中、足がマスの下の辺に来るように置く / puts the character in cell (col, row), feet on the + // cell's bottom edge + void placeAt(Vec2 tileTopLeft); + void beginStep() { previous = box.position(); } + void animate(const CharacterSheet &sheet, float dt); + Vec2 feet(float alpha) const; // 補間した足元(箱の下の真ん中) / the interpolated feet (bottom center of the box) + Sprite sprite(const CharacterSheet &sheet, float alpha) const; +}; + +// 動きの向きから顔の向き:今の向きが押されている方向の一つなら変えない(斜めに歩いても向きが震えない) +// Facing from a movement: keep the current facing if it is one of the pressed directions (walking diagonally does not +// make the facing flicker) +Facing facingFor(Vec2 move, Facing current); + +// 箱をdeltaだけ動かす:マップの固いマス+extra(人物などの箱)に当たれば止まり、壁に沿って滑る。 +// 真横・真上下に歩いていて角に数ピクセルだけ引っかかったら、その分だけ横にずらして角を回り込む(corner assist) +// Moves the box by delta: it stops at the map's solid cells + `extra` (other characters' boxes...) and slides along +// walls. When walking straight and only a few pixels catch on a corner, it is nudged sideways around the corner +// (corner assist) +MoveResult moveOnMap(Rect &box, Vec2 delta, const Tilemap &map, std::span extra, + std::vector &scratch); diff --git a/games/rpg/src/game.hh b/games/rpg/src/game.hh new file mode 100644 index 0000000..a29237e --- /dev/null +++ b/games/rpg/src/game.hh @@ -0,0 +1,65 @@ +// RPG:どのシーンからも使う共有データと、シーンのクラス +// The RPG: the shared data every scene uses, and the scene classes +#pragma once + +#include "character.hh" +#include "tile_renderer.hh" +#include "tilemap.hh" + +#include "engine/camera2d.hh" +#include "engine/font.hh" +#include "engine/game_loop.hh" +#include "engine/input.hh" +#include "engine/scene.hh" +#include "engine/sprite_batch.hh" + +#include +#include +#include + +// 仮想解像度:320 × 180(1280 × 720の4倍)、タイル16 × 16で20 × 11.25マスが見える +// The virtual resolution: 320 × 180 (× 4 = 1280 × 720); with 16 × 16 tiles, 20 × 11.25 tiles are visible +constexpr Vec2 kView = {320.0f, 180.0f}; + +// ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference +struct Game { + Window &window; + Input &input; + GameLoop &loop; + SpriteBatch &batch; + TileRenderer &tiles; // GPUの物は一つを使い回す(マップが変わったらbuildし直す) / one set of GPU objects, rebuilt + // when the map changes + const Font &ui; // mono16:画面の解像度 / screen resolution + const Font &pixel; // pixel12:キャンバスの中 / inside the canvas + const CharacterSheet &characters; + Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI + Viewport uiViewport; +}; + +// マップの上を歩くシーン / the scene where you walk around a map +class MapScene : public Scene { +public: + MapScene(Game &game, Tilemap map); + void enter() override; + void pause() override; + void update(float dt) override; + void draw(float alpha) override; + void drawUi(float alpha) override; + +private: + void spawn(); + // カメラ:主人公の足元を追い、マップの端で止める(マップが画面より小さければ真ん中に) + // The camera: follows the hero's feet and stops at the map's edges (centered when the map is smaller than the view) + Camera2D followCamera(Vec2 target) const; + + Game &g; + Tilemap map; + Character hero; + std::vector scratch; // 当たり判定の箱の作業用(毎ステップ作り直さない) / scratch boxes for collision (kept + // between steps to avoid allocations) + float time = 0.0f; + bool showBoxes = false, zoomOut = false, showHud = true; + std::array layerOn; + // HUD用:前のフレームの描画の数 / for the HUD: last frame's drawing counts + int rowFirst = 0, rowLast = 0, spriteCalls = 0; +}; diff --git a/games/rpg/src/main.cc b/games/rpg/src/main.cc new file mode 100644 index 0000000..ecf1fd3 --- /dev/null +++ b/games/rpg/src/main.cc @@ -0,0 +1,69 @@ +// 第33章:見下ろし型RPG(1)タイルマップ、当たり判定のある移動、追いかけるカメラ +// Chapter 33: a top-down RPG (1) tile maps, movement with collision, a following camera +// +// 操作 / Controls: +// 矢印 / WASD 移動 / move Shift 走る / run +// 1 2 3 層の表示 / toggle layers (ground, decor, overlay) +// B 当たり判定の箱 / collision boxes Z 引いて見る(カリングの確認) / zoom out (shows culling) +// H HUDの表示 / toggle the HUD +// R マップをファイルから読み直す / reload the map from its file Esc 終了 / quit +// +// 実行はプロジェクトのルートから / run from the project root: ./build/games/rpg/rpg +#include "game.hh" + +#include "engine/pixel_canvas.hh" +#include "engine/window.hh" + +#include +#include +#include + +int main() { + Window window; + if (!window.create(1280, 720, "OpenGL Tutorial - RPG")) return 1; + + std::optional batch = SpriteBatch::create(); + std::optional tiles = TileRenderer::create(); + std::optional ui = Font::load("assets/fonts/mono16.fnt"); + std::optional pixel = Font::load("assets/fonts/pixel12.fnt", TextureFilter::Nearest); + std::optional characters = CharacterSheet::load("games/rpg/assets/characters.png"); + std::optional village = Tilemap::load("games/rpg/assets/maps/village.map"); + if (!batch || !tiles || !ui || !pixel || !characters || !village) return 1; + + Input input; + input.attach(window); + input.bind("left", {InputBinding::key(GLFW_KEY_LEFT), InputBinding::key(GLFW_KEY_A)}); + input.bind("right", {InputBinding::key(GLFW_KEY_RIGHT), InputBinding::key(GLFW_KEY_D)}); + input.bind("up", {InputBinding::key(GLFW_KEY_UP), InputBinding::key(GLFW_KEY_W)}); + input.bind("down", {InputBinding::key(GLFW_KEY_DOWN), InputBinding::key(GLFW_KEY_S)}); + input.bind("run", {InputBinding::key(GLFW_KEY_LEFT_SHIFT), InputBinding::key(GLFW_KEY_RIGHT_SHIFT)}); + + GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); + PixelCanvas canvas(static_cast(kView.x), static_cast(kView.y)); + Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .tiles = *tiles, .ui = *ui, + .pixel = *pixel, .characters = *characters, .screen = Camera2D::screen({1280.0f, 720.0f}), + .uiViewport = {}}; + + SceneManager scenes; + scenes.push(std::make_unique(game, std::move(*village))); + + loop.run( + window, input, + [&](float dt) { + scenes.update(dt); + if (scenes.empty()) window.close(); + }, + [&](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); + }); + return 0; +} diff --git a/games/rpg/src/map_scene.cc b/games/rpg/src/map_scene.cc new file mode 100644 index 0000000..888d87f --- /dev/null +++ b/games/rpg/src/map_scene.cc @@ -0,0 +1,166 @@ +// マップのシーン:主人公を歩かせ、カメラで追い、層の順にタイルと人物を描く +// The map scene: walks the hero around, follows it with the camera, draws tiles and characters in layer order +#include "game.hh" + +#include "engine/collision.hh" + +#include +#include +#include + +constexpr float kWalkSpeed = 72.0f; // ピクセル毎秒(4.5マス/秒) / pixels per second (4.5 tiles/s) +constexpr float kRunSpeed = 120.0f; + +MapScene::MapScene(Game &game, Tilemap tilemap) : g(game), map(std::move(tilemap)) { layerOn.fill(true); } + +void MapScene::enter() { + g.tiles.build(map); // 静的な頂点バッファを作る(マップごとに一度) / build the static vertex buffer (once per map) + spawn(); +} + +void MapScene::spawn() { + hero.look = 0; + const MapObject *start = map.findObject("spawn", "start"); + hero.placeAt(start ? start->rect.position() : Vec2{kTile, kTile}); + std::string_view face = start ? start->get("face", "down") : "down"; + hero.facing = face == "up" ? Facing::Up : face == "left" ? Facing::Left : face == "right" ? Facing::Right : Facing::Down; + // 最初のフレームは更新なしで描かれる:今のうちに立ちのクリップを選んでおく / the first frame is drawn before any + // update: pick the standing clip now + hero.animate(g.characters, 0.0f); +} + +void MapScene::pause() { hero.previous = hero.box.position(); } + +void MapScene::update(float dt) { + time += dt; + Input &in = g.input; + if (in.pressed(GLFW_KEY_ESCAPE)) { + scenes().pop(); // 最後のシーン:mainが終わる / the last scene: main quits + return; + } + if (in.pressed(GLFW_KEY_B)) showBoxes = !showBoxes; + if (in.pressed(GLFW_KEY_Z)) zoomOut = !zoomOut; + if (in.pressed(GLFW_KEY_H)) showHud = !showHud; + for (int i = 0; i < 3; ++i) + if (in.pressed(GLFW_KEY_1 + i)) layerOn[static_cast(i)] = !layerOn[static_cast(i)]; + 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 fresh = Tilemap::load(map.path())) { + map = std::move(*fresh); + g.tiles.build(map); + printf("%s: 読み直した / reloaded\n", map.path().c_str()); + } + } + + // 主人公:自由に動く(マス目に縛られない)。斜めは正規化して同じ速さ / 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); +} + +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(); + // Z:引いて見る。カリングは本物のカメラのままなので、見えない行が描かれていないのが分かる + // Z: zoom out. Culling still uses the real camera, so you can see that rows outside it are not drawn + Camera2D view = camera; + if (zoomOut) { + view.zoom = 0.5f; + view.centre = {std::round(camera.centre.x), std::round(camera.centre.y)}; + } + Mat4 vp = view.matrix(); + SpriteBatch &b = g.batch; + g.tiles.resetStats(); + spriteCalls = 0; + rowFirst = std::clamp(static_cast(std::floor(visible.top() / kTile)), 0, map.height()); + rowLast = std::clamp(static_cast(std::ceil(visible.bottom() / kTile)), 0, map.height()) - 1; + + auto drawCharacters = [&] { + b.begin(vp, SpriteSort::Layer); + b.draw(hero.sprite(g.characters, alpha)); + b.end(); + spriteCalls += b.stats().drawCalls; + }; + + // 層はファイルの順に描く。「above」の層(木の上・屋根の棟)は人物の後 / layers are drawn in file order; "above" + // layers (tree tops, roof ridges) come after the characters + bool charactersDrawn = false; + const std::vector &layers = map.layers(); + for (int i = 0; i < static_cast(layers.size()); ++i) { + if (layers[static_cast(i)].above && !charactersDrawn) { + drawCharacters(); + charactersDrawn = true; + } + if (i < static_cast(layerOn.size()) && !layerOn[static_cast(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(); + + if (showBoxes || zoomOut) { + b.begin(vp); + if (showBoxes) { + // 固いマス(赤)と主人公の足元の箱(緑) / solid cells (red) and the hero's foot box (green) + scratch.clear(); + map.solidRects(visible, scratch); + for (const Rect &r : scratch) b.drawRectOutline(r, hexColor(0xff5050c0)); + Vec2 p = lerp(hero.previous, hero.box.position(), alpha); + b.drawRectOutline({p.x, p.y, hero.box.w, hero.box.h}, hexColor(0x50ff60ff)); + } + if (zoomOut) b.drawRectOutline(visible, hexColor(0xffe040ff), 2.0f); // 本物のカメラ / the real camera + b.end(); + spriteCalls += b.stats().drawCalls; + } +} + +void MapScene::drawUi(float /*alpha*/) { + if (!showHud) return; + SpriteBatch &b = g.batch; + const TileRenderer::Stats &ts = g.tiles.stats(); + char line[256]; + int col = static_cast(std::floor(hero.box.centre().x / kTile)), row = static_cast(std::floor(hero.box.centre().y / kTile)); + snprintf(line, sizeof line, "%s %d×%d tile (%d, %d) rows %d-%d tile quads %d / %d draw calls: tiles %d + sprites %d", + map.name().c_str(), map.width(), map.height(), col, row, rowFirst, rowLast, ts.quads, ts.totalQuads, + ts.drawCalls, spriteCalls); + b.begin(g.screen.matrix()); + TextStyle hud = {.color = hexColor(0xfff4d6ff), .shadow = hexColor(0x000000ff)}; + b.drawRect({0.0f, 0.0f, 1280.0f, 30.0f}, hexColor(0x1b1726c0)); + g.ui.draw(b, line, {12.0f, 6.0f}, hud); + char layers[64]; + snprintf(layers, sizeof layers, "layers %s %s %s", layerOn[0] ? "1" : "-", layerOn[1] ? "2" : "-", layerOn[2] ? "3" : "-"); + hud.align = TextAlign::Right; + hud.color = hexColor(0xf2c14eff); + g.ui.draw(b, layers, {1268.0f, 6.0f}, hud); + b.drawRect({0.0f, 690.0f, 1280.0f, 30.0f}, hexColor(0x1b1726c0)); + hud.align = TextAlign::Centre; + hud.color = hexColor(0xc8cce0ff); + 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", + {640.0f, 696.0f}, hud); + b.end(); +} diff --git a/games/rpg/src/tile_renderer.cc b/games/rpg/src/tile_renderer.cc new file mode 100644 index 0000000..2cc936b --- /dev/null +++ b/games/rpg/src/tile_renderer.cc @@ -0,0 +1,150 @@ +#include "tile_renderer.hh" + +#include +#include +#include +#include + +std::optional TileRenderer::create() { + TileRenderer r; + r.shader = Shader::load("engine/shaders/sprite.vert", "engine/shaders/sprite.frag"); + if (!r.shader) return std::nullopt; + // VAOの形はSpriteBatchと同じ:位置(0)、UV(1)、色(2、RGBA8を0〜1に) / the same VAO format as the SpriteBatch: + // position (0), UV (1), color (2, RGBA8 normalized to 0..1) + glCreateVertexArrays(1, &r.vao); + glEnableVertexArrayAttrib(r.vao, 0); + glVertexArrayAttribFormat(r.vao, 0, 2, GL_FLOAT, GL_FALSE, offsetof(SpriteVertex, position)); + glVertexArrayAttribBinding(r.vao, 0, 0); + glEnableVertexArrayAttrib(r.vao, 1); + glVertexArrayAttribFormat(r.vao, 1, 2, GL_FLOAT, GL_FALSE, offsetof(SpriteVertex, uv)); + glVertexArrayAttribBinding(r.vao, 1, 0); + glEnableVertexArrayAttrib(r.vao, 2); + glVertexArrayAttribFormat(r.vao, 2, 4, GL_UNSIGNED_BYTE, GL_TRUE, offsetof(SpriteVertex, color)); + glVertexArrayAttribBinding(r.vao, 2, 0); + return r; +} + +TileRenderer::~TileRenderer() { release(); } + +void TileRenderer::release() { + if (vao) glDeleteVertexArrays(1, &vao); + vao = 0; +} + +TileRenderer::TileRenderer(TileRenderer &&o) noexcept + : shader(std::move(o.shader)), vertices(std::move(o.vertices)), indices(std::move(o.indices)), + vao(std::exchange(o.vao, 0)), map(o.map), layers(std::move(o.layers)), frameStats(o.frameStats) {} + +TileRenderer &TileRenderer::operator=(TileRenderer &&o) noexcept { + if (this != &o) { + release(); + shader = std::move(o.shader); + vertices = std::move(o.vertices); + indices = std::move(o.indices); + vao = std::exchange(o.vao, 0); + map = o.map; + layers = std::move(o.layers); + frameStats = o.frameStats; + } + return *this; +} + +void TileRenderer::build(const Tilemap &m) { + map = &m; + const SpriteSheet &sheet = m.tileset().sheet(); + std::vector data; + layers.clear(); + int maxLayerQuads = 0; + for (const TileLayer &tl : m.layers()) { + Layer layer; + layer.firstQuad = static_cast(data.size() / 4); + layer.rowStart.reserve(static_cast(m.height() + 1)); + for (int row = 0; row < m.height(); ++row) { + layer.rowStart.push_back(static_cast(data.size() / 4) - layer.firstQuad); + for (int col = 0; col < m.width(); ++col) { + int k = tl.cells[static_cast(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(col), kTile * static_cast(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(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 quadIndices; + quadIndices.reserve(static_cast(std::max(1, maxLayerQuads)) * 6); + for (std::uint32_t q = 0; q < static_cast(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(data.size() * sizeof(SpriteVertex)), 0); + indices = Buffer(quadIndices.data(), static_cast(quadIndices.size() * sizeof(std::uint32_t)), 0); + glVertexArrayVertexBuffer(vao, 0, vertices.id(), 0, sizeof(SpriteVertex)); + glVertexArrayElementBuffer(vao, indices.id()); + frameStats.totalQuads = static_cast(data.size() / 4); +} + +// visibleが触れる行の範囲 [r0, r1) / the range of rows [r0, r1) that `visible` touches +static std::pair visibleRows(const Rect &visible, int rows) { + int r0 = static_cast(std::floor(visible.top() / kTile)); + int r1 = static_cast(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(layers.size())) return; + const Layer &layer = layers[static_cast(index)]; + auto [r0, r1] = visibleRows(visible, map->height()); + int first = layer.rowStart[static_cast(r0)], count = layer.rowStart[static_cast(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; +} + +void TileRenderer::drawAnimated(SpriteBatch &batch, int index, const Rect &visible, float time, float spriteLayer) const { + if (!map || index < 0 || index >= static_cast(layers.size())) return; + const SpriteSheet &sheet = map->tileset().sheet(); + for (const Animated &a : layers[static_cast(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(time * clip.fps) % clip.frames.size(); + Sprite s = sheet.sprite(clip.frames[frame], a.position); + s.layer = spriteLayer; + batch.draw(s); + } +} diff --git a/games/rpg/src/tile_renderer.hh b/games/rpg/src/tile_renderer.hh new file mode 100644 index 0000000..7c26256 --- /dev/null +++ b/games/rpg/src/tile_renderer.hh @@ -0,0 +1,75 @@ +// タイルマップの描画(第33章):動かないタイルは読み込み時に一度だけ作る静的な頂点バッファに入れる +// Drawing tile maps (chapter 33): tiles that never change go into a static vertex buffer built once at load time +// +// SpriteBatchは毎フレーム頂点を作ってGPUへ送る(動的なバッファ)。タイルは変わらないので、送るのは一度だけでいい: +// 不変のストレージ(glNamedBufferStorage、フラグ0)に全部の層の四角形を行の順に並べ、見えている行の範囲だけを +// glDrawElementsBaseVertexの1回で描く。動くタイル(水)は数が少ないので、毎フレームSpriteBatchで描く +// The SpriteBatch builds vertices every frame and sends them to the GPU (a dynamic buffer). Tiles never change, so +// they only need to be sent once: the quads of all layers go row by row into immutable storage (glNamedBufferStorage, +// flags 0), and only the range of visible rows is drawn, with one glDrawElementsBaseVertex per layer. Animated tiles +// (water) are few, so they go through the SpriteBatch every frame +#pragma once + +#include "tilemap.hh" + +#include "engine/buffer.hh" +#include "engine/shader.hh" +#include "engine/sprite_batch.hh" + +#include +#include + +class TileRenderer { +public: + // シェーダーはエンジンのsprite.vert/.frag(頂点の形もSpriteBatchと同じ) / the shader is the engine's + // sprite.vert/.frag (the vertex format is the same as the SpriteBatch's) + static std::optional create(); + ~TileRenderer(); + TileRenderer(const TileRenderer &) = delete; + TileRenderer &operator=(const TileRenderer &) = delete; + TileRenderer(TileRenderer &&other) noexcept; + TileRenderer &operator=(TileRenderer &&other) noexcept; + + // マップの全部の層の頂点を作り、新しいバッファに入れる(不変のストレージは大きさを変えられない:作り直す) + // Builds the vertices of every layer of the map into new buffers (immutable storage cannot change size: rebuild) + void build(const Tilemap &map); + // 層の動かないタイルのうち、visibleに入る行だけを描く(描画コール1回) / draws the still tiles of a layer, only the + // rows inside `visible` (one draw call) + void drawLayer(int layer, const Mat4 &viewProjection, const Rect &visible); + // 層の動くタイルをバッチに足す(呼ぶ側がbegin/endする) / adds the layer's animated tiles to the batch (the caller + // does begin/end) + void drawAnimated(SpriteBatch &batch, int layer, const Rect &visible, float time, float spriteLayer = 0.0f) const; + bool hasAnimated(int layer) const { return !layers[static_cast(layer)].animated.empty(); } + + // 前のフレームの数(HUD用) / counts of the last frame (for the HUD) + struct Stats { + int quads = 0; // 描いた四角形 / quads drawn + int drawCalls = 0; + int totalQuads = 0; // バッファの中の全部 / everything in the buffer + }; + const Stats &stats() const { return frameStats; } + void resetStats() { frameStats = {0, 0, frameStats.totalQuads}; } + +private: + TileRenderer() = default; + void release(); + + struct Animated { + Vec2 position; + const TileKind *kind; + int row; + }; + struct Layer { + int firstQuad = 0; // バッファの中の最初の四角形 / the layer's first quad in the buffer + std::vector rowStart; // rows + 1個:行rの最初の四角形(層の中の番号) / rows + 1 entries: the first quad + // of row r (counted inside the layer) + std::vector animated; + }; + + std::optional shader; + Buffer vertices, indices; + GLuint vao = 0; + const Tilemap *map = nullptr; + std::vector layers; + Stats frameStats; +}; diff --git a/games/rpg/src/tilemap.cc b/games/rpg/src/tilemap.cc new file mode 100644 index 0000000..efc1c55 --- /dev/null +++ b/games/rpg/src/tilemap.cc @@ -0,0 +1,246 @@ +// タイルセットとマップの読み込み:1行ずつ、最初の単語で命令を見分ける +// Loading tilesets and maps: line by line, the first word says what the line is +#include "tilemap.hh" + +#include "engine/file_util.hh" + +#include +#include +#include +#include + +std::string folderOf(const std::string &path) { + size_t slash = path.find_last_of("/\\"); + return slash == std::string::npos ? std::string() : path.substr(0, slash + 1); +} + +// 「ファイル:行: 説明」の形で出す(エディターやIDEがそこへ飛べる) / prints "file:line: message" (editors and IDEs can +// jump there) +static void parseError(const std::string &path, int line, const std::string &what) { + fprintf(stderr, "%s:%d: %s\n", path.c_str(), line, what.c_str()); +} + +static bool toInt(std::string_view s, int &out) { + auto [end, ec] = std::from_chars(s.data(), s.data() + s.size(), out); + return ec == std::errc() && end == s.data() + s.size(); +} + +// ---------------------------------------------------------------------------------------------------- Tileset + +std::optional Tileset::load(const std::string &path) { + std::optional text = readTextFile(path); + if (!text) { + fprintf(stderr, "%s: 読めない / cannot read\n", path.c_str()); + return std::nullopt; + } + Tileset set; + set.bySymbol.fill(-1); + bool haveAtlas = false; + std::istringstream lines(*text); + std::string line; + int number = 0; + while (std::getline(lines, line)) { + ++number; + std::istringstream in(line); + std::string command; + if (!(in >> command) || command[0] == '#') continue; + if (command == "atlas") { + std::string file; + in >> file; + std::optional sheet = SpriteSheet::loadAtlas(folderOf(path) + file); + if (!sheet) return std::nullopt; // loadAtlasが理由を出した / loadAtlas printed why + set.atlas = std::move(sheet); + haveAtlas = true; + } else if (command == "tile") { + std::string symbol, sprite; + if (!(in >> symbol >> sprite) || symbol.size() != 1 || static_cast(symbol[0]) >= 128 || + symbol[0] == '.') { + parseError(path, number, "tile <1文字(.以外のASCII) / one ASCII character other than .> ..."); + return std::nullopt; + } + if (!haveAtlas) { + parseError(path, number, "atlasの行が先に要る / the atlas line must come first"); + return std::nullopt; + } + TileKind kind{.symbol = symbol[0], .name = sprite, .sprite = set.atlas->find(sprite)}; + if (kind.sprite < 0) { + parseError(path, number, "アトラスにないスプライト / sprite not in the atlas: " + sprite); + return std::nullopt; + } + std::string flag; + while (in >> flag) { + if (flag == "solid") kind.solid = true; + else if (flag == "anim") { + std::string clip; + in >> clip; + kind.anim = set.atlas->clip(clip); + if (!kind.anim) { + parseError(path, number, "アトラスにないクリップ / clip not in the atlas: " + clip); + return std::nullopt; + } + } else { + parseError(path, number, "知らない印 / unknown flag: " + flag); + return std::nullopt; + } + } + if (set.bySymbol[static_cast(kind.symbol)] >= 0) { + parseError(path, number, std::string("同じ文字が二度 / the same character twice: ") + kind.symbol); + return std::nullopt; + } + set.bySymbol[static_cast(kind.symbol)] = static_cast(set.kinds.size()); + set.kinds.push_back(std::move(kind)); + } else { + parseError(path, number, "知らない命令 / unknown command: " + command); + return std::nullopt; + } + } + if (!haveAtlas) { + parseError(path, number, "atlasの行がない / no atlas line"); + return std::nullopt; + } + return set; +} + +int Tileset::kindIndex(char symbol) const { + unsigned char c = static_cast(symbol); + return c < 128 ? bySymbol[c] : -1; +} + +const TileKind *Tileset::find(char symbol) const { + int i = kindIndex(symbol); + return i < 0 ? nullptr : &kinds[static_cast(i)]; +} + +// ---------------------------------------------------------------------------------------------------- MapObject + +std::string_view MapObject::get(std::string_view key, std::string_view fallback) const { + for (const auto &[k, v] : properties) + if (k == key) return v; + return fallback; +} + +int MapObject::getInt(std::string_view key, int fallback) const { + int value = 0; + return toInt(get(key), value) ? value : fallback; +} + +// ---------------------------------------------------------------------------------------------------- Tilemap + +std::optional Tilemap::load(const std::string &path) { + std::optional text = readTextFile(path); + if (!text) { + fprintf(stderr, "%s: 読めない / cannot read (プロジェクトのルートから実行した? / running from the project root?)\n", + path.c_str()); + return std::nullopt; + } + Tilemap map; + map.filePath = path; + std::istringstream lines(*text); + std::string line; + int number = 0; + auto fail = [&](const std::string &what) { + parseError(path, number, what); + return std::nullopt; + }; + while (std::getline(lines, line)) { + ++number; + if (!line.empty() && line.back() == '\r') line.pop_back(); // Windowsの改行 / Windows line endings + std::istringstream in(line); + std::string command; + if (!(in >> command) || command[0] == '#') continue; + if (command == "map") { + in >> map.mapName; + } 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"); + } else if (command == "tileset") { + std::string file; + in >> file; + std::optional set = Tileset::load(folderOf(path) + file); + if (!set) return fail("タイルセットを読めない / cannot load the tileset " + file); + map.tiles = std::make_shared(std::move(*set)); + } else if (command == "size") { + if (!(in >> map.cols >> map.rows) || map.cols <= 0 || map.rows <= 0 || map.cols > 1024 || map.rows > 1024) + return fail("size <幅> <高さ>(1〜1024) / size (1..1024)"); + } 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(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(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(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(row * map.cols + col)] = kind; + } + } + map.tileLayers.push_back(std::move(layer)); + } else if (command == "object") { + MapObject object; + int col = 0, row = 0; + std::string x, y; + if (!(in >> object.kind >> object.name >> x >> y) || !toInt(x, col) || !toInt(y, row)) + return fail("object <種類> <名前> <列> <行> [key=value …] / object [key=value ...]"); + std::string pair; + while (in >> pair) { + size_t eq = pair.find('='); + if (eq == std::string::npos || eq == 0) return fail("key=valueのはず / expected key=value: " + pair); + object.properties.emplace_back(pair.substr(0, eq), pair.substr(eq + 1)); + } + int w = object.getInt("w", 1), h = object.getInt("h", 1); + object.rect = {kTile * static_cast(col), kTile * static_cast(row), kTile * static_cast(w), + kTile * static_cast(h)}; + map.mapObjects.push_back(std::move(object)); + } else { + return fail("知らない命令 / unknown command: " + command); + } + } + if (!map.tiles || map.tileLayers.empty()) return fail("tilesetとlayerが要る / a tileset and layers are required"); + + // 固さを一枚にまとめる:どれかの層の固いタイルがあれば通れない / combine solidity into one grid: a solid tile in any + // layer blocks the cell + map.solid.assign(static_cast(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; +} + +const MapObject *Tilemap::findObject(std::string_view kind, std::string_view name) const { + for (const MapObject &o : mapObjects) + if (o.kind == kind && o.name == name) return &o; + return nullptr; +} + +bool Tilemap::solidAt(int col, int row) const { + if (col < 0 || row < 0 || col >= cols || row >= rows) return true; + return solid[static_cast(row * cols + col)]; +} + +void Tilemap::solidRects(const Rect &area, std::vector &out) const { + // areaに触れるマスだけを調べる(マップ全部の箱を作らない) / only the cells touching `area` are checked (no boxes + // for the whole map) + int c0 = static_cast(std::floor(area.left() / kTile)), c1 = static_cast(std::floor(area.right() / kTile)); + int r0 = static_cast(std::floor(area.top() / kTile)), r1 = static_cast(std::floor(area.bottom() / kTile)); + for (int row = r0; row <= r1; ++row) + for (int col = c0; col <= c1; ++col) + if (solidAt(col, row)) + out.push_back({kTile * static_cast(col), kTile * static_cast(row), kTile, kTile}); +} diff --git a/games/rpg/src/tilemap.hh b/games/rpg/src/tilemap.hh new file mode 100644 index 0000000..2d43d51 --- /dev/null +++ b/games/rpg/src/tilemap.hh @@ -0,0 +1,117 @@ +// タイルマップ(第33章):タイルの種類の一覧(.tileset)と、文字の格子で書いたマップ(.map)を読む +// Tile maps (chapter 33): reads the list of tile kinds (.tileset) and maps written as character grids (.map) +// +// どちらも1行に1つの命令のテキスト。ライブラリなしで読めて、テキストエディターで地図が「見える」 +// Both are text files with one command per line: they parse without a library, and in a text editor you *see* the map +#pragma once + +#include "engine/animation.hh" +#include "engine/rect.hh" +#include "engine/sprite_sheet.hh" + +#include +#include +#include +#include +#include +#include + +constexpr int kTileSize = 16; +constexpr float kTile = 16.0f; + +// タイルの種類(.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 +}; + +// タイルセット:アトラス(画像)+文字 → 種類の表。全部のマップで同じ文字は同じタイル +// A tileset: the atlas (image) + the character → kind table. A character means the same tile in every map +class Tileset { +public: + // 書式 / format: + // atlas (.tilesetからの相対パス / relative to the .tileset) + // tile [solid] [anim ] + // # コメント / comment + static std::optional load(const std::string &path); + + const SpriteSheet &sheet() const { return *atlas; } + // 文字の種類。'.'や知らない文字はnullptr / the kind of a character; nullptr for '.' and unknown characters + const TileKind *find(char symbol) const; + int kindIndex(char symbol) const; + const TileKind &kind(int index) const { return kinds[static_cast(index)]; } + int kindCount() const { return static_cast(kinds.size()); } + +private: + Tileset() = default; + std::optional atlas; // SpriteSheetは読み込みでしか作れない / a SpriteSheet only comes from loading + std::vector kinds; + std::array bySymbol{}; // ASCIIの文字 → kindsの番号(-1 = なし) / ASCII character → kinds index (-1 = none) +}; + +// マップの物(扉・出発点・宝箱・人…)。位置と大きさはピクセル、性質は key=value の文字列 +// An object on a map (door, spawn point, chest, person...). Position and size in pixels, properties as key=value +struct MapObject { + std::string kind; // spawn, door, … + std::string name; + Rect rect; // ピクセル / pixels + std::vector> properties; + + std::string_view get(std::string_view key, std::string_view fallback = "") const; + int getInt(std::string_view key, int fallback) const; +}; + +// 1枚の層:width × heightのマス、各マスはタイルの種類の番号(-1 = 空) / one layer: width × height cells, each the +// index of a tile kind (-1 = empty) +struct TileLayer { + std::string name; + bool above = false; // trueなら人物の上に描く(木の上半分・屋根の棟) / drawn above the characters (tree tops, + // roof ridges) + std::vector cells; // 行ごと(row * width + col) / row by row (row * width + col) +}; + +class Tilemap { +public: + // 書式 / format (see games/rpg/assets/maps/*.map): + // map 名前 / the name + // tileset .mapからの相対パス / relative to the .map + // size マスの数 / in tiles + // layer [above] 続くheight行が格子(1文字 = 1マス、'.' = 空) / the next `height` lines are the grid + // (1 character = 1 tile, '.' = empty) + // object [key=value …] w= h= でマスの大きさ(既定1×1) / w= h= set the size in tiles + // (default 1 × 1) + // エラーは「ファイル:行: 説明」でstderrに出してnullopt / errors go to stderr as "file:line: message", then nullopt + static std::optional load(const std::string &path); + + const std::string &name() const { return mapName; } + const std::string &path() const { return filePath; } + const Tileset &tileset() const { return *tiles; } + int width() const { return cols; } + int height() const { return rows; } + Vec2 pixelSize() const { return {kTile * static_cast(cols), kTile * static_cast(rows)}; } + const std::vector &layers() const { return tileLayers; } + const std::vector &objects() const { return mapObjects; } + const MapObject *findObject(std::string_view kind, std::string_view name) const; + + // そのマスに固いタイルがあるか(どれかの層で)。マップの外も固い(端から出られない) + // Is there a solid tile in the cell (in any layer)? Outside the map counts as solid (you cannot walk off the edge) + bool solidAt(int col, int row) const; + // areaに触れる固いマスの箱をoutに足す(moveAndSlideに渡す) / appends the boxes of the solid cells touching `area` + // to out (to pass to moveAndSlide) + void solidRects(const Rect &area, std::vector &out) const; + +private: + Tilemap() = default; + std::string mapName, filePath; + std::shared_ptr tiles; // 同じタイルセットを何枚ものマップで共有できる / several maps can share one + int cols = 0, rows = 0; + std::vector tileLayers; + std::vector mapObjects; + std::vector solid; // 全部の層をまとめた固さ / the solidity of all layers combined +}; + +// パスのフォルダ部分("a/b/c.map" → "a/b/") / the folder part of a path ("a/b/c.map" → "a/b/") +std::string folderOf(const std::string &path);