diff --git a/games/rpg/CMakeLists.txt b/games/rpg/CMakeLists.txt index a52d0ed..9eb65a7 100644 --- a/games/rpg/CMakeLists.txt +++ b/games/rpg/CMakeLists.txt @@ -4,7 +4,8 @@ add_executable(rpg src/tilemap.cc src/tile_renderer.cc src/character.cc - src/map_scene.cc) + src/map_scene.cc + src/world.cc) target_include_directories(rpg PRIVATE src) target_link_libraries(rpg PRIVATE engine) enable_warnings(rpg) diff --git a/games/rpg/README.md b/games/rpg/README.md index 4499154..4af0743 100644 --- a/games/rpg/README.md +++ b/games/rpg/README.md @@ -10,6 +10,7 @@ |---|---| | 矢印 / WASD | 移動 / move | | Shift | 走る / run | +| Space / Enter | 調べる(宝箱) / check (chests) | | 1 2 3 | 層の表示(地面・飾り・上の層) / toggle the layers (ground, decor, overlay) | | B | 当たり判定の箱 / collision boxes | | Z | 引いて見る(行のカリングが見える) / zoom out (shows the row culling) | @@ -18,5 +19,7 @@ | Esc | 終了 / quit | マップは `assets/maps/*.map`(テキスト)。書式は `src/tilemap.hh`、タイルの文字は `assets/tiles.tileset`。 +扉は `object door <名前> <列> <行> map=<マップ> spawn=<出発点>`、マップの端の出口は `object warp … h=2 …`。 Maps are `assets/maps/*.map` (text). The format is described in `src/tilemap.hh`, the tile characters in -`assets/tiles.tileset`. +`assets/tiles.tileset`. Doors are `object door map= spawn=`, exits at the edge of +a map `object warp ... h=2 ...`. diff --git a/games/rpg/assets/LICENSE.txt b/games/rpg/assets/LICENSE.txt index 147e707..186a128 100644 --- a/games/rpg/assets/LICENSE.txt +++ b/games/rpg/assets/LICENSE.txt @@ -6,4 +6,6 @@ tiles.png/.atlas 16×16のタイル(草・道・水・木・家・家具 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) +maps/village.map 村のマップ / the village map (chapters 33-34; edit by hand freely) +maps/home.map 家の中 / the house interior (chapter 34) +maps/field.map 野原 / the field (chapter 34) diff --git a/games/rpg/assets/maps/field.map b/games/rpg/assets/maps/field.map new file mode 100644 index 0000000..1d35ef0 --- /dev/null +++ b/games/rpg/assets/maps/field.map @@ -0,0 +1,91 @@ +# のはら / Field +# 書式は games/rpg/src/tilemap.hh、文字の意味は ../tiles.tileset / format: games/rpg/src/tilemap.hh, +# characters: ../tiles.tileset ('.' = 空 / empty) +map field +title のはら / Field +tileset ../tiles.tileset +size 40 24 + +layer ground +,,,,,,,,,;,;,,,,;;,,,,,,,,,,,,,,,,,,,,,; +,,,,,,,;,,,,;,,,;,;,,,,,,,,,,,;,,,,,,,,, +,,,;,,,,,,,,,;,,,,,;,,,,,,,,,,,,,,,,;,,, +,,,,,,,,,,;,,,,,,,,,,,,,,,,,,,,;,;,;;;,, +,,,,,,;,;,,,,;,,,,,,;,;,;,,;;;;;;;;,,;,, +,,,,;,,,,,,,,,;,,,,;,,;,,;,;;;;;;;;,,,,; +,;,,,;;,,,;,,,,;,,;,;,,,;,,;;;;;;;;,,,,, +,,,,,,,,,,,;;,,,;,,,;,,,;;,;;;;;;;;,,,,; +;,,,,,,;,,,;,,,,,,,,,,,,,,,;;;;;;;;,,;;, +,,,,,;,,,;,,,,,;,,,,,,,,,,,,,,==;,,,,,;, +==:===========:==============::=,;,,,,,, +====================:===========,,,,,,,, +;,,;,,;,,,,,,,,,,,,,;;;,,,,,,,;,,,,,,,,; +,,;;,;;,,,,,,;,,,,,,,,,;,;,,,;,,,,,,,;,, +,,,,,,,,,,,,;,,,,,;,,,;,;,;,,,;,,,,,,,,, +,,,,,,,,,,;;,,,,,,,,,,,,;,,,,,,,;;,,,,,, +,,,;,,,;,,,,,,,;,^^^^^,,,,,,,;;,,;,,;,;, +,,,;,,;,,,;,,,,,,~~~~~;,,,,,,;,,,,,,,,;, +,,,,;,;,,;,,,,,;,~~~~~,,,,,;,,,,,,;,,,;, +,,;,,,,,;,,,,,,,,~~~~~,,,,,,;,,;,,;;,,,; +;,,,,,,,,;,;,;,,,,,,;,;;,,,,,,,,,,,,;,;, +;,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, +,,;,,;,,,,;;;,,,,,,,;,,,,;,,,,,,,,;;,,,; +;,,,,,,,;,,,,,,,,,,;,,,,,,,,,,,,,,,,,;,, + +layer decor +........................................ +TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT +b......................................b +T.............T...........----------...T +b.."""""..T.........T.....|.....s..|...b +T.."""""..........*.......|.*......|...T +b.."""""..................|........|...b +T.........................|.%....*.|...T +b....b..........b.........|........|...b +b.....T............R......----..----..bT +.......................................b +................"""""".........*.......T +b......*.R......"""""".....R...........b +T............S..""""""R.T........T..T..T +b..."""""""...*..........*...b.........b +T..."""""""............................T +b...""""""".............""""""""....*..b +T...""""""".R..........."""""""".......T +b......................."""""""".....T.b +T......................."""""""".......T +b.......T.........................R....b +T..T...........T.....b..T..............T +b......................................b +TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT + +layer overlay above +tttttttttttttttttttttttttttttttttttttttt +........................................ +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 1 10 face=right +object spawn west 1 10 face=right +object warp west 0 10 h=2 map=village spawn=east +object chest garden_chest 30 5 gold=100 diff --git a/games/rpg/assets/maps/home.map b/games/rpg/assets/maps/home.map new file mode 100644 index 0000000..61afb65 --- /dev/null +++ b/games/rpg/assets/maps/home.map @@ -0,0 +1,49 @@ +# 家 / Home +# 書式は games/rpg/src/tilemap.hh、文字の意味は ../tiles.tileset / format: games/rpg/src/tilemap.hh, +# characters: ../tiles.tileset ('.' = 空 / empty) +map home +title 家 / Home +tileset ../tiles.tileset +size 12 10 + +layer ground +xxxxxxxxxxxx +xwwwnwwnwwwx +x__________x +x__________x +x___rrrr___x +x___rrrr___x +x___rrrr___x +x__________x +x____m_____x +xxxxx_xxxxxx + +layer decor +............ +..KK.....F.. +.B........p. +.E........p. +............ +....cQQc.... +............ +.P........U. +..........X. +............ + +layer overlay above +............ +............ +............ +............ +............ +............ +............ +............ +............ +............ + +# 物:object <種類> <名前> <列> <行> [key=value …] / objects: kind name col row [key=value ...] +object spawn start 5 7 face=up +object spawn door 5 8 face=up +object door out 5 9 map=village spawn=home_door +object chest home_chest 8 2 gold=50 diff --git a/games/rpg/assets/maps/village.map b/games/rpg/assets/maps/village.map index 09d6c08..bc66d90 100644 --- a/games/rpg/assets/maps/village.map +++ b/games/rpg/assets/maps/village.map @@ -2,6 +2,7 @@ # 書式は games/rpg/src/tilemap.hh、文字の意味は ../tiles.tileset / format: games/rpg/src/tilemap.hh, # characters: ../tiles.tileset ('.' = 空 / empty) map village +title 村 / Village tileset ../tiles.tileset size 40 28 @@ -43,7 +44,7 @@ T...........s.........b............b...T b......................................b T.............AAAAAAA..................T b.b..LLLLL....LLLLLLL...s....LLLLLX....b -T...UMWdWMX..SMWMdMWM......bXMWdWMU..%.T +T...UMWDWMX..SMWMdMWM......bXMWdWMU..%.T b..........*...........*...............b T..%...................................b b....................................... @@ -97,3 +98,8 @@ tttttttttttttttttttttttttttttttttttttttt # 物:object <種類> <名前> <列> <行> [key=value …] / objects: kind name col row [key=value ...] object spawn start 7 9 face=down +object door home 7 7 map=home spawn=door +object warp east 39 10 h=2 map=field spawn=west +object spawn home_door 7 8 face=down +object spawn east 38 10 face=left +object chest village_chest 21 8 gold=30 diff --git a/games/rpg/src/game.hh b/games/rpg/src/game.hh index a29237e..44f8abb 100644 --- a/games/rpg/src/game.hh +++ b/games/rpg/src/game.hh @@ -5,6 +5,7 @@ #include "character.hh" #include "tile_renderer.hh" #include "tilemap.hh" +#include "world.hh" #include "engine/camera2d.hh" #include "engine/font.hh" @@ -15,11 +16,22 @@ #include #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}; +// マップを移るときのフェード(暗くなるのに半分、明るくなるのに半分) / the fade between maps (half to black, half back) +constexpr Transition kMapFade = {.duration = 0.6f, .color = {0.0f, 0.0f, 0.0f, 1.0f}}; + +// デバッグ表示の切り替え:シーンはマップごとに作り直されるので、ここ(Game)に置く(シーンに置くと扉で元に戻る) +// Debug view toggles: scenes are recreated for every map, so they live here in Game (in a scene they would reset at +// every door) +struct DebugView { + bool boxes = false, zoomOut = false, hud = true; + std::array layers = {true, true, true, true, true, true, true, true}; +}; // ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference struct Game { @@ -29,17 +41,22 @@ struct Game { SpriteBatch &batch; TileRenderer &tiles; // GPUの物は一つを使い回す(マップが変わったらbuildし直す) / one set of GPU objects, rebuilt // when the map changes + World &world; // マップの置き場と、残る状態 / the loaded maps and the persistent state const Font &ui; // mono16:画面の解像度 / screen resolution const Font &pixel; // pixel12:キャンバスの中 / inside the canvas const CharacterSheet &characters; Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI Viewport uiViewport; + DebugView debug; }; -// マップの上を歩くシーン / the scene where you walk around a map +// マップの上を歩くシーン。マップ1つにつき1つ作り、扉で次のマップのシーンに入れ替える +// The scene where you walk around a map. One per map; a door replaces it with the next map's scene class MapScene : public Scene { public: - MapScene(Game &game, Tilemap map); + // mapName = World::mapの名前、spawn = 出発点の物の名前(spawn <名前>) / mapName = the name for World::map, spawn = + // the name of a spawn object + MapScene(Game &game, std::string mapName, std::string spawn); void enter() override; void pause() override; void update(float dt) override; @@ -47,19 +64,35 @@ public: 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) + // 宝箱:開いたかどうかはWorldの印(マップ名/宝箱名)に残る / a chest: whether it is open is a World flag + // (map name/chest name) + struct Chest { + const MapObject *object; + Rect box; + std::string flag; + }; + struct Popup { + std::string text; + Vec2 position; + float life; + }; + void setUp(); // マップの物からシーンの物を作る / builds the scene's things from the map's objects + void interact(); + void checkWarps(); + Rect facingProbe() const; Camera2D followCamera(Vec2 target) const; Game &g; - Tilemap map; + std::string mapName, spawnName; + Tilemap *map = nullptr; // Worldの中(読み直しても同じ場所) / inside World (same address across reloads) Character hero; - std::vector scratch; // 当たり判定の箱の作業用(毎ステップ作り直さない) / scratch boxes for collision (kept - // between steps to avoid allocations) + std::vector chests; + std::vector blockers; // 固い物(宝箱)の箱 / boxes of solid objects (chests) + std::vector popups; + std::vector scratch; // 当たり判定の箱の作業用 / scratch boxes for collision float time = 0.0f; - bool showBoxes = false, zoomOut = false, showHud = true; - std::array layerOn; - // HUD用:前のフレームの描画の数 / for the HUD: last frame's drawing counts + bool warpArmed = false; // 出発点が扉の上でも、一度離れるまで扉は効かない / doors only work after the hero has + // stepped off all of them once (in case a spawn point is on a door) + bool leaving = false; // 扉に入った:フェードが終わるまで動かない / entered a door: frozen until the fade ends int rowFirst = 0, rowLast = 0, spriteCalls = 0; }; diff --git a/games/rpg/src/main.cc b/games/rpg/src/main.cc index ecf1fd3..d9dd05e 100644 --- a/games/rpg/src/main.cc +++ b/games/rpg/src/main.cc @@ -1,8 +1,8 @@ -// 第33章:見下ろし型RPG(1)タイルマップ、当たり判定のある移動、追いかけるカメラ -// Chapter 33: a top-down RPG (1) tile maps, movement with collision, a following camera +// 第34章:見下ろし型RPG(2)いくつものマップ、扉と出口、フェードでのシーンの切り替え、ファイルからのマップ +// Chapter 34: a top-down RPG (2) several maps, doors and exits, scene switching with fades, maps loaded from files // // 操作 / Controls: -// 矢印 / WASD 移動 / move Shift 走る / run +// 矢印 / WASD 移動 / move Shift 走る / run Space / Enter 調べる(宝箱) / check (chests) // 1 2 3 層の表示 / toggle layers (ground, decor, overlay) // B 当たり判定の箱 / collision boxes Z 引いて見る(カリングの確認) / zoom out (shows culling) // H HUDの表示 / toggle the HUD @@ -27,8 +27,10 @@ int main() { 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; + // マップは使うときにWorldが読む(最初の村だけ、ここで読めるか確かめる) / World loads maps when they are first + // needed (only the first one, the village, is checked here) + World world; + if (!batch || !tiles || !ui || !pixel || !characters || !world.map("village")) return 1; Input input; input.attach(window); @@ -37,15 +39,18 @@ int main() { 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)}); + input.bind("confirm", {InputBinding::key(GLFW_KEY_SPACE), InputBinding::key(GLFW_KEY_ENTER)}); 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, + Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .tiles = *tiles, .world = world, .ui = *ui, .pixel = *pixel, .characters = *characters, .screen = Camera2D::screen({1280.0f, 720.0f}), - .uiViewport = {}}; + .uiViewport = {}, .debug = {}}; SceneManager scenes; - scenes.push(std::make_unique(game, std::move(*village))); + // 黒から明るくなって始まる(空のスタックへのpushもフェードできる) / starts by fading in from black (a push onto the + // empty stack can fade too) + scenes.push(std::make_unique(game, "village", "start"), kMapFade); loop.run( window, input, diff --git a/games/rpg/src/map_scene.cc b/games/rpg/src/map_scene.cc index 888d87f..b813f45 100644 --- a/games/rpg/src/map_scene.cc +++ b/games/rpg/src/map_scene.cc @@ -1,5 +1,6 @@ -// マップのシーン:主人公を歩かせ、カメラで追い、層の順にタイルと人物を描く -// The map scene: walks the hero around, follows it with the camera, draws tiles and characters in layer order +// マップのシーン:主人公を歩かせ、カメラで追い、層の順にタイルと人物を描く。扉で別のマップへ(フェード付き) +// The map scene: walks the hero around, follows it with the camera, draws tiles and characters in layer order. Doors +// lead to other maps (with a fade) #include "game.hh" #include "engine/collision.hh" @@ -7,50 +8,132 @@ #include #include #include +#include constexpr float kWalkSpeed = 72.0f; // ピクセル毎秒(4.5マス/秒) / pixels per second (4.5 tiles/s) constexpr float kRunSpeed = 120.0f; +constexpr float kBannerTime = 2.5f; // マップの名前を出す秒数 / seconds the map's name is shown -MapScene::MapScene(Game &game, Tilemap tilemap) : g(game), map(std::move(tilemap)) { layerOn.fill(true); } +MapScene::MapScene(Game &game, std::string name, std::string spawn) + : g(game), mapName(std::move(name)), spawnName(std::move(spawn)) {} void MapScene::enter() { - g.tiles.build(map); // 静的な頂点バッファを作る(マップごとに一度) / build the static vertex buffer (once per map) - spawn(); + // マップはWorldから(初めてならファイルを読む)。扉は入る前に読めることを確かめてある + // The map comes from World (loaded from its file the first time). Doors check that it loads before switching + map = g.world.map(mapName); + setUp(); } -void MapScene::spawn() { +void MapScene::setUp() { + g.tiles.build(*map); // 静的な頂点バッファを作る(マップに入るたびに一度) / build the static vertex buffer (once per + // visit) + const MapObject *start = map->findObject("spawn", spawnName); + if (!start) { + fprintf(stderr, "%s: 出発点がない / no spawn point '%s' (startを使う / using start)\n", map->path().c_str(), + spawnName.c_str()); + start = map->findObject("spawn", "start"); + } hero.look = 0; - 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); + + // 宝箱:開いたかどうかはWorldに残っている(マップ名/宝箱名) / chests: whether they are open is kept in World + // (map name/chest name) + chests.clear(); + blockers.clear(); + for (const MapObject &o : map->objects()) + if (o.kind == "chest") { + Rect box = {o.rect.x + 1.0f, o.rect.y + 4.0f, 14.0f, 12.0f}; + chests.push_back({&o, box, mapName + "/" + o.name}); + blockers.push_back(box); + } + warpArmed = false; + leaving = false; } void MapScene::pause() { hero.previous = hero.box.position(); } +// 顔の前の小さな箱:これに触れる物を調べる / a small box in front of the face: things touching it can be checked +Rect MapScene::facingProbe() const { + const Rect &b = hero.box; + constexpr float r = 8.0f; + switch (hero.facing) { + case Facing::Down: return {b.x, b.bottom(), b.w, r}; + case Facing::Up: return {b.x, b.y - r, b.w, r}; + case Facing::Left: return {b.x - r, b.y - 2.0f, r, b.h + 4.0f}; + case Facing::Right: return {b.right(), b.y - 2.0f, r, b.h + 4.0f}; + } + return b; +} + +void MapScene::interact() { + Rect probe = facingProbe(); + for (const Chest &c : chests) { + if (!overlaps(probe, c.box) || g.world.flag(c.flag)) continue; + g.world.setFlag(c.flag); // マップを出ても開いたまま / stays open after leaving the map + int gold = c.object->getInt("gold", 0); + g.world.gold += gold; + popups.push_back({"+" + std::to_string(gold) + " G", {c.box.centre().x, c.box.y - 10.0f}, 1.2f}); + printf("%s: 開けた / opened (+%d G, %d G)\n", c.flag.c_str(), gold, g.world.gold); + return; + } +} + +void MapScene::checkWarps() { + bool onWarp = false; + for (const MapObject &o : map->objects()) { + if ((o.kind != "door" && o.kind != "warp") || !overlaps(hero.box, o.rect)) continue; + onWarp = true; + if (!warpArmed) continue; + std::string target(o.get("map")), spawn(o.get("spawn", "start")); + // 先のマップを今読む(初めてならファイルから)。読めなければ移らない / load the target map now (from its file the + // first time); if it cannot be loaded, stay + if (!g.world.map(target)) { + fprintf(stderr, "%s: %s %s の先のマップ「%s」を読めない / cannot load map '%s'\n", map->path().c_str(), + o.kind.c_str(), o.name.c_str(), target.c_str(), target.c_str()); + warpArmed = false; + return; + } + printf("%s → %s (%s)\n", mapName.c_str(), target.c_str(), spawn.c_str()); + // 入れ替えは頼むだけ:フェードアウトの後で、このシーンがexit、新しいシーンがenterする + // The replacement is only requested: after the fade out this scene exits and the new one enters + scenes().replace(std::make_unique(g, target, spawn), kMapFade); + leaving = true; + hero.moving = false; + hero.previous = hero.box.position(); // 止める:フェードの間は更新されない / freeze: no updates during the fade + return; + } + if (!onWarp) warpArmed = true; // 扉から離れた:次に触れた扉は効く / off every door: the next one works +} + void MapScene::update(float dt) { time += dt; + if (leaving) return; 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; + DebugView &dbg = g.debug; + if (in.pressed(GLFW_KEY_B)) dbg.boxes = !dbg.boxes; + if (in.pressed(GLFW_KEY_Z)) dbg.zoomOut = !dbg.zoomOut; + if (in.pressed(GLFW_KEY_H)) dbg.hud = !dbg.hud; 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()); - } + if (in.pressed(GLFW_KEY_1 + i)) dbg.layers[static_cast(i)] = !dbg.layers[static_cast(i)]; + if (in.pressed(GLFW_KEY_R) && g.world.reload(mapName)) { + // ファイルから読み直す。物のポインターが変わるので作り直し、主人公は今の場所に戻す + // Reload from the file. Object pointers change, so rebuild them; the hero goes back to where it was + Rect keep = hero.box; + Facing facing = hero.facing; + setUp(); + hero.box = keep; + hero.previous = keep.position(); + hero.facing = facing; + printf("%s: 読み直した / reloaded\n", map->path().c_str()); } // 主人公:自由に動く(マス目に縛られない)。斜めは正規化して同じ速さ / the hero moves freely (not locked to the @@ -61,14 +144,22 @@ void MapScene::update(float dt) { 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); + moveOnMap(hero.box, normalize(move) * (speed * dt), *map, blockers, scratch); } hero.anim.speed = in.actionHeld("run") ? 1.5f : 1.0f; hero.animate(g.characters, dt); + if (in.actionPressed("confirm")) interact(); + checkWarps(); + + for (Popup &p : popups) { + p.position.y -= 12.0f * dt; + p.life -= dt; + } + std::erase_if(popups, [](const Popup &p) { return p.life <= 0.0f; }); } Camera2D MapScene::followCamera(Vec2 target) const { - Vec2 size = map.pixelSize(), half = 0.5f * kView; + 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); @@ -78,41 +169,41 @@ Camera2D MapScene::followCamera(Vec2 target) const { } 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)}; - } + if (g.debug.zoomOut) view.zoom = 0.5f; 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; + 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; + const SpriteSheet &tileSheet = map->tileset().sheet(); auto drawCharacters = [&] { + // 人物と、背の低い物(宝箱)を足元のyの順に / characters and low objects (chests) sorted by the y of their feet b.begin(vp, SpriteSort::Layer); + for (const Chest &c : chests) { + Sprite s = tileSheet.sprite(tileSheet.find(g.world.flag(c.flag) ? "chest_open" : "chest_closed"), + c.object->rect.position()); + s.layer = c.box.bottom(); + b.draw(s); + } b.draw(hero.sprite(g.characters, alpha)); b.end(); spriteCalls += b.stats().drawCalls; }; - // 層はファイルの順に描く。「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(); + 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; + if (i < static_cast(g.debug.layers.size()) && !g.debug.layers[static_cast(i)]) continue; g.tiles.drawLayer(i, vp, visible); if (g.tiles.hasAnimated(i)) { b.begin(vp); @@ -123,44 +214,66 @@ void MapScene::draw(float alpha) { } 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; + // 世界の上の物:浮かぶ文字、デバッグの箱 / things over the world: floating text, debug boxes + b.begin(vp); + for (const Popup &p : popups) + g.pixel.draw(b, p.text, p.position, + {.color = {1.0f, 0.9f, 0.45f, std::min(1.0f, p.life * 3.0f)}, .align = TextAlign::Centre, + .shadow = hexColor(0x1b1726ff)}); + if (g.debug.boxes) { + scratch.clear(); + map->solidRects(visible, scratch); + for (const Rect &r : scratch) b.drawRectOutline(r, hexColor(0xff5050c0)); + for (const Rect &r : blockers) b.drawRectOutline(r, hexColor(0xff9040ff)); + for (const MapObject &o : map->objects()) + if (o.kind == "door" || o.kind == "warp") b.drawRectOutline(o.rect, hexColor(0x40c0ffff)); // 扉 / doors + Vec2 p = lerp(hero.previous, hero.box.position(), alpha); + b.drawRectOutline({p.x, p.y, hero.box.w, hero.box.h}, hexColor(0x50ff60ff)); + b.drawRectOutline(facingProbe(), hexColor(0xffff60c0)); + } + if (g.debug.zoomOut) b.drawRectOutline(visible, hexColor(0xffe040ff), 2.0f); + b.end(); + + // キャンバスの画面に固定の物:マップの名前、お金 / things fixed to the canvas screen: the map's name, the money + Camera2D canvas = Camera2D::screen(kView); + b.begin(canvas.matrix()); + float banner = std::clamp((kBannerTime - time) / 0.5f, 0.0f, 1.0f); + if (banner > 0.0f) { + Vec2 size = g.pixel.measure(map->title()); + Rect box = Rect::fromCentre({160.0f, 30.0f}, {size.x + 16.0f, size.y + 6.0f}); + b.drawRect(box, {0.106f, 0.09f, 0.15f, 0.85f * banner}); + b.drawRectOutline(box, {0.95f, 0.76f, 0.31f, banner}); + g.pixel.draw(b, map->title(), {160.0f, box.y + 3.0f}, {.color = {1.0f, 0.96f, 0.84f, banner}, .align = TextAlign::Centre}); } + char gold[32]; + snprintf(gold, sizeof gold, "%d G", g.world.gold); + g.pixel.draw(b, gold, {314.0f, 160.0f}, {.color = hexColor(0xf2c14eff), .align = TextAlign::Right, .shadow = hexColor(0x1b1726ff)}); + b.end(); } void MapScene::drawUi(float /*alpha*/) { - if (!showHud) return; + if (!g.debug.hud) 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); + snprintf(line, sizeof line, "%s %d×%d tile (%d, %d) rows %d-%d tile quads %d / %d draws: tiles %d + sprites %d maps %d", + map->name().c_str(), map->width(), map->height(), col, row, rowFirst, rowLast, ts.quads, ts.totalQuads, + ts.drawCalls, spriteCalls, g.world.loadedMaps()); 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" : "-"); + snprintf(layers, sizeof layers, "layers %s %s %s", g.debug.layers[0] ? "1" : "-", g.debug.layers[1] ? "2" : "-", + g.debug.layers[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", + g.ui.draw(b, "arrows / WASD: move Shift: run Space: 調べる / check 1 2 3: layers B: boxes Z: zoom out H: HUD R: reload Esc: 終了 / quit", {640.0f, 696.0f}, hud); b.end(); } diff --git a/games/rpg/src/tilemap.cc b/games/rpg/src/tilemap.cc index efc1c55..c54479f 100644 --- a/games/rpg/src/tilemap.cc +++ b/games/rpg/src/tilemap.cc @@ -126,7 +126,7 @@ int MapObject::getInt(std::string_view key, int fallback) const { // ---------------------------------------------------------------------------------------------------- Tilemap -std::optional Tilemap::load(const std::string &path) { +std::optional Tilemap::load(const std::string &path, TilesetCache *cache) { std::optional text = readTextFile(path); if (!text) { fprintf(stderr, "%s: 読めない / cannot read (プロジェクトのルートから実行した? / running from the project root?)\n", @@ -150,6 +150,8 @@ std::optional Tilemap::load(const std::string &path) { if (!(in >> command) || command[0] == '#') continue; if (command == "map") { in >> map.mapName; + } else if (command == "title") { + std::getline(in >> std::ws, map.mapTitle); } 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 @@ -158,9 +160,15 @@ std::optional Tilemap::load(const std::string &path) { } else if (command == "tileset") { std::string file; in >> file; - std::optional set = Tileset::load(folderOf(path) + file); + std::string tilesetPath = folderOf(path) + file; + if (cache && cache->contains(tilesetPath)) { + map.tiles = cache->at(tilesetPath); + continue; + } + std::optional set = Tileset::load(tilesetPath); if (!set) return fail("タイルセットを読めない / cannot load the tileset " + file); map.tiles = std::make_shared(std::move(*set)); + if (cache) (*cache)[tilesetPath] = map.tiles; } 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)"); diff --git a/games/rpg/src/tilemap.hh b/games/rpg/src/tilemap.hh index 2d43d51..9f95979 100644 --- a/games/rpg/src/tilemap.hh +++ b/games/rpg/src/tilemap.hh @@ -14,6 +14,7 @@ #include #include #include +#include #include constexpr int kTileSize = 16; @@ -52,6 +53,10 @@ private: std::array bySymbol{}; // ASCIIの文字 → kindsの番号(-1 = なし) / ASCII character → kinds index (-1 = none) }; +// 読んだタイルセットを覚えておく表(パス → タイルセット):同じタイルセットのマップは画像を共有する +// A table of loaded tilesets (path → tileset): maps with the same tileset share its image +using TilesetCache = std::unordered_map>; + // マップの物(扉・出発点・宝箱・人…)。位置と大きさはピクセル、性質は key=value の文字列 // An object on a map (door, spawn point, chest, person...). Position and size in pixels, properties as key=value struct MapObject { @@ -77,16 +82,20 @@ class Tilemap { public: // 書式 / format (see games/rpg/assets/maps/*.map): // map 名前 / the name + // title 画面に出す名前(行の残り全部) / the name shown on screen (the rest of the line) // 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); + // エラーは「ファイル:行: 説明」でstderrに出してnullopt / errors go to stderr as "file:line: message", then nullopt. + // cacheがあれば、タイルセットはそこから取る(なければ読んで入れる) / with a cache, the tileset comes from it (loaded + // and added if missing) + static std::optional load(const std::string &path, TilesetCache *cache = nullptr); const std::string &name() const { return mapName; } + const std::string &title() const { return mapTitle.empty() ? mapName : mapTitle; } const std::string &path() const { return filePath; } const Tileset &tileset() const { return *tiles; } int width() const { return cols; } @@ -105,7 +114,7 @@ public: private: Tilemap() = default; - std::string mapName, filePath; + std::string mapName, mapTitle, filePath; std::shared_ptr tiles; // 同じタイルセットを何枚ものマップで共有できる / several maps can share one int cols = 0, rows = 0; std::vector tileLayers; diff --git a/games/rpg/src/world.cc b/games/rpg/src/world.cc new file mode 100644 index 0000000..59007cf --- /dev/null +++ b/games/rpg/src/world.cc @@ -0,0 +1,38 @@ +#include "world.hh" + +#include +#include +#include + +Tilemap *World::map(const std::string &name) { + if (auto it = maps.find(name); it != maps.end()) return it->second.get(); + std::optional loaded = Tilemap::load(pathOf(name), &tilesets); + if (!loaded) return nullptr; + printf("%s: 読んだ / loaded (%d×%d)\n", pathOf(name).c_str(), loaded->width(), loaded->height()); + return (maps[name] = std::make_unique(std::move(*loaded))).get(); +} + +bool World::reload(const std::string &name) { + if (!maps.contains(name)) return map(name) != nullptr; + // タイルセットも読み直す。マップの格子はタイルセットの番号なので、読んである全部のマップを新しい表で読み直す + // (古いタイルセットを持ったままのマップが残らない)。全部読めたときだけ入れ替え、一つでも失敗したら何も変えない + // The tileset is read again too. Map grids hold the tileset's kind numbers, so every loaded map is read again with + // the new table (no map keeps the old tileset). They are swapped in only if all of them load; one failure changes + // nothing + std::vector names = {name}; // 今のマップから:エラーはまずそこに出る / the current map first: its + // errors come first + for (const auto &entry : maps) + if (entry.first != name) names.push_back(entry.first); + TilesetCache freshTilesets; + std::vector> fresh; + for (const std::string &n : names) { + std::optional loaded = Tilemap::load(pathOf(n), &freshTilesets); + if (!loaded) return false; + fresh.emplace_back(maps[n].get(), std::move(*loaded)); + } + // 同じ場所に入れる:シーンのポインターはそのまま / same addresses: scenes' pointers stay valid + for (auto &[target, loaded] : fresh) *target = std::move(loaded); + tilesets = std::move(freshTilesets); // 古いタイルセット(とテクスチャー)はここで消える / the old tileset (and its + // texture) is freed here + return true; +} diff --git a/games/rpg/src/world.hh b/games/rpg/src/world.hh new file mode 100644 index 0000000..837fb85 --- /dev/null +++ b/games/rpg/src/world.hh @@ -0,0 +1,43 @@ +// 世界の状態(第34章):読んだマップの置き場と、マップを出ても残るもの(開けた宝箱・お金) +// The world state (chapter 34): where loaded maps are kept, and what survives leaving a map (opened chests, money) +// +// シーンはマップに入るたびに作り直される(scenes().replace)。だから「残すもの」はシーンではなくここに置く: +// 残す:開けた宝箱などの印(flags)、お金 → 戻ってきても宝箱は開いたまま +// 残さない:シーンの中の物(主人公の位置、浮かぶ文字…)→ 入るたびにマップのファイルの通りから始まる +// A scene is created anew every time you enter a map (scenes().replace). So what must persist lives here, not in the +// scene: +// kept: flags such as opened chests, the money → a chest is still open when you come back +// not kept: everything inside the scene (the hero's position, floating text...) → each visit starts as the map +// file says +#pragma once + +#include "tilemap.hh" + +#include +#include +#include +#include + +class World { +public: + // マップを名前で:初めてなら games/rpg/assets/maps/<名前>.map を読む。読めなければnullptr。 + // ポインターは変わらない(読み直しても同じ場所) / a map by name: loaded from games/rpg/assets/maps/.map on + // first use; nullptr if it cannot be loaded. The pointer stays valid (also across reloads) + Tilemap *map(const std::string &name); + // ファイルから読み直す(タイルセットと、読んであるほかのマップも)。失敗したら全部前のまま / reloads from the file + // (the tileset and the other loaded maps too); on failure everything stays as it was + bool reload(const std::string &name); + int loadedMaps() const { return static_cast(maps.size()); } + + bool flag(const std::string &name) const { return flags.contains(name); } + void setFlag(const std::string &name) { flags.insert(name); } + + int gold = 0; + + static std::string pathOf(const std::string &name) { return "games/rpg/assets/maps/" + name + ".map"; } + +private: + std::unordered_map> maps; + TilesetCache tilesets; + std::unordered_set flags; +};