34. トップダウンRPG パート2:マップ・扉・シーン切り替え

第33章の最後では、主人公は1つの村を歩き回れる様になりました。
テキストファイルのタイルマップ、静的な頂点バッファ、固いマスとの当たり判定、追いかけるカメラです。
でも、マップ1枚は1つの面であって、世界ではありません。
此の章では村に入れる家と野原への出口を付け、ゲームがマップの間を移動出来る様にします。

使う技は第26章のシーンのスタックです。
マップに1回入るごとに其れが1つのシーンになり、扉はフェードの陰で其れを次のシーンと入れ替えます。
面白いのは切り替え其の物(其れはエンジンがもう出来ます)ではなく、其処から出て来る問いの方です。
主人公がマップを出て戻って来た時、何が前と同じなのでしょうか?
開けた宝箱は開いた儘であるべきですが、主人公が1分前に家を出た場所に立っているべきではありません。
此の章は其の問いに、1つの決まりと1つのクラスWorldで答えます。

今回、新しいOpenGLの関数はありません。
GLに関係するのは、静的なタイルのバッファをマップごとに作り直し、VAO・プログラム・アトラスのテクスチャは使い続ける事だけです。

34.1 此の章で作る物

プログラムrpgのマップは3枚になります。
村(40 × 28マス)、主人公の家(12 × 10)、そして野原(40 × 24)です。
家の扉は中へ、道の東の端は野原へ続き、お金の入った宝箱が3枚のマップに1つずつあります。
動画は一周の見本です。
家に入って宝箱を開け、外に出て村の宝箱を開け、野原まで走り、柵に囲まれた庭の宝箱を開けて村に戻ると、最初の宝箱はまだ開いています:

2 × 2に並べたゲームの4つの画面。左上は村で、開けた宝箱の隣の主人公と浮かぶ+30 G。右上は家の中で、画面より小さく暗い背景の真ん中にあり、開けた宝箱の所の主人公と+50 G。左下は野原で、柵に囲まれた庭と3つ目の宝箱、+100 Gと隅の180 G。右下はデバッグの箱付きの村で、扉の上の主人公、青い扉の長方形、黄色い前の箱、赤い固いマス、上にマップの名前の帯

どのマップも、入った時に名前を帯で出し、お金の合計はキャンバスの右下の隅にあります。
家のマップは320 × 180のキャンバスより小さい(192 × 160ピクセル)ので、カメラは其れを真ん中に置き、キャンバスの残りは暗い儘です。
此の場合は第33章のカメラがもう扱っていました。

操作は第33章の物にキーが1つ増えるだけです:

  • 矢印キー又はW、A、S、Dで移動、Shiftで走る
  • スペース又はEnterで目の前の物を調べる:此処では宝箱を開けます
  • 1、2、3で層の表示、Bで当たり判定の箱(扉、宝箱、前の箱も出る様になりました)、Zで引いて見る、HでHUD、Rでマップとタイルセットをファイルから読み直す、Escで終了

第33章からの変更は全てgames/rpg/の中です:

  • src/world.hh、src/world.cc(新規):World。マップの置き場と、マップを出ても残る状態
  • src/tilemap.hh、src/tilemap.cc:titleの命令と、Tilemap::loadのタイルセットの表の引数
  • src/game.hh:kMapFade、DebugView、Gameの中のWorld &、そしてマップの名前と出発点の名前から作るMapScene
  • src/map_scene.cc:扉と出口、宝箱、前を調べる箱、名前の帯、お金の表示
  • src/main.cc:Worldを作り、「confirm」の行動を割り当て、フェードで始める
  • assets/maps/:village.mapに扉、出口、出発点、宝箱が付き、home.mapとfield.mapは新規(完成したファイルは章のZIPとアセットのZIPのch34/に入っています)
  • CMakeLists.txt、README.md、assets/LICENSE.txt:新しいソースファイル、新しいキー、新しいマップ

ゲームのCMakeLists.txtに増えるのはsrc/world.ccだけです:

# 見下ろし型RPG(第33〜35章) / the top-down RPG (chapters 33-35)
add_executable(rpg
  src/main.cc
  src/tilemap.cc
  src/tile_renderer.cc
  src/character.cc
  src/map_scene.cc
  src/world.cc)
target_include_directories(rpg PRIVATE src)
target_link_libraries(rpg PRIVATE engine)
enable_warnings(rpg)
set_working_directory(rpg)

34.2 扉はマップファイルの物

第33章のマップの書式には、正に此の時の為の物の一覧が既にありました。
object <種類> <名前> <列> <行> [key=value …]です。
其の時の物は出発点のstartだけでした。
扉は物の種類が1つ増えるだけなので、扉を足しても書式は全く変わりません。
今の村の物は此れです:

# 物:object <種類> <名前> <列> <行> [key=value …] / objects: kind name col row [key=value ...]
object spawn start 7 9 face=down
object door home 7 7 map=home spawn=door
object warp east 39 10 h=2 map=field spawn=west
object spawn home_door 7 8 face=down
object spawn east 38 10 face=left
object chest village_chest 21 8 gold=30

  • door home 7 7 map=home spawn=door:7列目・7行目にある主人公の家の扉。入るとhome.mapを読み、其のマップのdoorという名前の出発点に主人公を置きます。
  • warp east 39 10 h=2 map=field spawn=west:マップの東の端にある見えない出口。幅1マス、高さ2マス(h=2)で、丁度道がマップから出る所にあります。
  • spawn home_doorとspawn east:家から、そして野原から戻って来た時に主人公が現れる場所。
  • chest village_chest 21 8 gold=30:30ゴールドの入った宝箱。

コードの中ではdoorとwarpは全く同じ動きをします。
2つの名前はマップを作る人の意図を示すだけで、doorは見える扉のタイル、warpはマップの端の見えない帯です。
組は此の様に繋がります。
どの扉もマップと其の中の出発点を名指し、どの出発点も戻る為の扉の隣にあります:

3枚のマップを同じ縮尺で描いた図。固いマスは灰色、水は青。home.map(12 × 10マス)は村の上にあり、扉は下の端。2本の矢印が村の7列目・7行目の扉と家を繋ぐ。door homeはhome.mapのspawn doorへ、5列目・9行目のdoor outはvillage.mapのspawn home_doorへ。村の右にfield.map(40 × 24マス)。村の東の端と野原の西の端の10行目と11行目の間に2本の矢印。warp eastはfield.mapのspawn westへ、warp westはvillage.mapのspawn eastへ。宝箱は村に30 G、家に50 G、野原の庭に100 G

マップは此の繋がりのグラフで、コードは其のグラフを何も知りません。
4枚目のマップのファイルと其れを名指す扉を足せば、ゲームのマップは4枚になります(課題1)。

新しい家の中、home.mapの最初と地面の層です:

map home
title 家 / Home
tileset ../tiles.tileset
size 12 10

layer ground
xxxxxxxxxxxx
xwwwnwwnwwwx
x__________x
x__________x
x___rrrr___x
x___rrrr___x
x___rrrr___x
x__________x
x____m_____x
xxxxx_xxxxxx

xは長方形の残りを埋める固い「何も無い」タイル、wとnは家の中の壁(普通の物と窓付き)、_は木の床、rは敷物、mは玄関マットです。
どれも第33章のtiles.tilesetに既にあり、此の章でタイルセットは変わりません。
一番下の行の5列目の隙間が出入口で、家の物はファイルの最後にあります:

# 物: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

扉outは一番下の行の隙間で、出発点doorは其のすぐ上のマスです。
野原も同じ作りです。
西の出口からの道、背の高い草の草むら2つ、池、そして3つ目の宝箱のある柵で囲まれた庭があり、左の端にwarp west 0 10 h=2があります。

村のタイルが1つ変わる

第33章では、村の家の扉はdで、tiles.tilesetでsolidの付いた扉のタイルでした。
固い扉には入れません。
足元の箱は其の下の辺で止まり、扉の物に重なる事が無いからです。
其の為、主人公の家の扉はsolidの無い同じスプライトDになりました:

T...UMWDWMX..SMWMdMWM......bXMWdWMU..%.T

他の2軒の家はdの儘です。
第35章で言う事が出来るまでは閉まっています。
扉のタイルが歩ける様になると、主人公を止めるのは其の上の固い軒で、切り替えを起こすのは扉の物です:

村の扉の拡大図。マップの1ピクセルを画面の4ピクセルにして、5〜9列目、5〜9行目を描き、端にピクセルの座標。6行目は屋根の軒Lで固い。7行目は家の正面で、壁MとWは固く、真ん中の扉のタイルDは歩ける。Dは青で囲まれ、x 112〜128、y 112〜128の扉の物。其の下の7列目・8行目が出発点home_doorのマスで、緑の10 × 6の足元の箱はy 138〜144にあり、どの扉にも重ならない。9ステップ上の黄色い点線の箱はy 127.2で、もう扉の長方形に重なっている

出発点のマスは8行目なので、第33章のplaceAtは10 × 6の足元の箱をy = 128 + 16 − 6 = 138に置きます。
扉の長方形の下の辺(y = 128)から10 px下で、何にも重なっていません。
毎秒72 pxで上に歩くと箱は更新1回で1.2 px動き、9回の更新の後に上の辺は138 − 10.8 = 127.2、扉の中です。
↑を押してから0.15秒で切り替えが始まります。

マップの名前

どのマップにも画面に出す名前が付き、行の残り全部を取る新しい命令titleで書きます:

    if (command == "map") {
      in >> map.mapName;
    } else if (command == "title") {
      std::getline(in >> std::ws, map.mapTitle);

in >> std::wsが命令の後の空白を飛ばすので、title 村 / Villageは村 / Villageを覚えます。
titleの行が無いファイルでは、Tilemap::title()はマップの名前を返します。
野原の名前はのはら / Fieldと仮名です。
第26章の共有のpixel12フォントにはUIの漢字が252字ありますが、野原は其の中に無いので、漢字だと?になってしまいます。
第35章ではRPGに、文章に要る全ての文字を持つ自分のフォントアトラスを作ります。

34.3 マップに1回入るごとに1つのシーン

第26章のSceneManagerには、どこかへ行く方法が2つあります。
pushは今のシーンの上に新しいシーンを載せ、今のシーンは下に(一時停止して)残します。
replaceは今のシーンを消し、其の場所に新しいシーンを置きます。
マップには、どちらも有り得ます:

村、家、村、野原、村と回る時のシーンのスタックを3行で描いた図。replaceでは、スタックはいつも1つ。扉ごとにpushすると、スタックは5個まで増え、其の内4個は一時停止:村、家、村、野原、村。家だけpushとpopにすると、スタックは村、村の上に家、popの後また村、其の後はreplaceで野原、村

pushなら、家の中に居る間、村は主人公の位置も含めて出た時の儘で残り、popで其の儘戻って来ます。
メニューや「洞窟に入って、同じ場所に出て来る」には良いのですが、あたし達の扉はどちら向きにも通れます。
家の扉がまた村をpushし、何回か行き来するとスタックには一時停止した村が山積みになります。
なので此の章は1回入るごとに1つのシーンにします。
扉はいつも今のMapSceneを、行き先のマップの新しいシーンでreplaceします。
インベーダーも第29章で同じ事をしていました。
新しい波はどれも、古い物をreplaceする新しいPlaySceneです。
新しいシーンは、一番簡単な「全部やり直し」です。
課題5ではpushとpopを家で試し、其の代償を見ます。

フェードはgame.hhの定数です:

// マップを移るときのフェード(暗くなるのに半分、明るくなるのに半分) / the fade between maps (half to black, half back)
constexpr Transition kMapFade = {.duration = 0.6f, .color = {0.0f, 0.0f, 0.0f, 1.0f}};

そして扉の確認は、毎回の更新の最後に行います:

void MapScene::checkWarps() {
  bool onWarp = false;
  for (const MapObject &o : map->objects()) {
    if ((o.kind != "door" && o.kind != "warp") || !overlaps(hero.box, o.rect)) continue;
    onWarp = true;
    if (!warpArmed) continue;
    std::string target(o.get("map")), spawn(o.get("spawn", "start"));
    // 先のマップを今読む(初めてならファイルから)。読めなければ移らない / load the target map now (from its file the
    // first time); if it cannot be loaded, stay
    if (!g.world.map(target)) {
      fprintf(stderr, "%s: %s %s の先のマップ「%s」を読めない / cannot load map '%s'\n", map->path().c_str(),
              o.kind.c_str(), o.name.c_str(), target.c_str(), target.c_str());
      warpArmed = false;
      return;
    }
    printf("%s → %s (%s)\n", mapName.c_str(), target.c_str(), spawn.c_str());
    // 入れ替えは頼むだけ:フェードアウトの後で、このシーンがexit、新しいシーンがenterする
    // The replacement is only requested: after the fade out this scene exits and the new one enters
    scenes().replace(std::make_unique<MapScene>(g, target, spawn), kMapFade);
    leaving = true;
    hero.moving = false;
    hero.previous = hero.box.position(); // 止める:フェードの間は更新されない / freeze: no updates during the fade
    return;
  }
  if (!onWarp) warpArmed = true; // 扉から離れた:次に触れた扉は効く / off every door: the next one works
}

順に見ていきます:

  • 主人公の足元の箱が物の長方形に重なった時、扉が働きます。overlapsは第26章の厳密なAABBのテストなので、辺が触れるだけでは数えません。
  • 切り替えを頼む前に、扉はWorldを通して行き先のマップを読みます(次の節)。ファイルが無いか壊れていれば、マップの無いシーンに切り替える代わりに主人公は其の場に留まり、stderrに理由が出ます。
  • scenes().replace(…, kMapFade)は、第26章で説明した様に切り替えを予約するだけです。此のシーンは先ず自分の更新を終え、後で消されます。
  • printfは、スクリプトで動かした時の確認に使うvillage → home (door)という記録の行を出します。

0.6秒の間に起きる事

0.6秒のTransitionは、半分の時間で画面を暗くし、切り替え、残りの半分で明るくします。
曲線は第26章で見ました。
毎秒60回の更新なら、フェードアウトに18回、フェードインに18回です。
村から家への切り替えの4つのフレームを、扉が働いた更新から数えて並べました:

村から家へのフェードの4つのフレーム。どれも320 × 180のキャンバス全体。0.07秒では村が少し暗く、フェードアウト中。0.23秒ではほぼ真っ黒。0.37秒では家の中が暗く現れ、フェードイン中で、帯に家 / Home。0.63秒では家がすっかり見える

  • フェードアウト(0.3秒): どのシーンも更新されませんが、古い村のシーンは毎フレーム描かれ続けます。
  • 切り替え: マネージャーは村のシーンのexit()を呼んで其れを消し、新しい家のシーンのenter()を呼びます。其処で家のタイルを作り、主人公を置きます。
  • フェードイン(0.3秒): 家のシーンはもう動いているので、画面が明るくなる間に歩けます。

checkWarpsの2行が此れらの段階を扱います。
hero.previous = hero.box.position()は補間を止めます。
フェードアウトの間は何も更新されませんが、draw(alpha)は毎フレーム変わるアルファでpreviousと今の位置を混ぜ続けます。
なので扉が働いた時に動いていた主人公は、0.3秒の間前後に揺れてしまいます。
第26章の課題5が、本物になって出て来ました。
leaving = trueはupdateをすぐに返させます。
此れが効くのは、フェードインの間に頼んだ場合です。
マネージャーは今の切り替えが終わってから次の切り替えを始めるので、着いて0.1秒で扉に触れたシーンは其れまで更新され続けます。
其れは簡単に起きます。
東の出発点は村の出口から3 px、歩いて更新3回です。
leavingが無いと主人公は歩き続け、更新の度にreplaceがもう1つ予約されます。

出発点と、扉を「効かせる」決まり

扉の確認にはもう1つの見張り、warpArmedがあります。
setUpが其れをfalseにし、主人公がどの扉にもどの出口にも重なっていない最初の更新でtrueになります。
あたし達のマップでは出発点が全部扉の隣なので、其れは最初の更新です。
でも、もしマップを作る人が出発点を扉の上に置くと、主人公は扉の上に着き、扉がすぐに働き、向こうのマップの扉が送り返し……と永遠に続きます。
此の決まりがあれば、扉は一度全部の扉から降りた後でしか働きません。
行き先のマップが読めない時にも同じ印を戻すので、壊れた扉のメッセージは毎秒60回ではなく1回だけ出ます。

最初のシーンもフェードで始まる

mainは最初のシーンを同じ切り替えでpushします:

  SceneManager scenes;
  // 黒から明るくなって始まる(空のスタックへのpushもフェードできる) / starts by fading in from black (a push onto the
  // empty stack can fade too)
  scenes.push(std::make_unique<MapScene>(game, "village", "start"), kMapFade);

空のスタックへのpushも、他の変更と同じ様にフェードします。
キャンバスの暗いクリアの色が0.3秒で黒になり、其れから村が明るくなります。
小さな事ですが、此れでゲームは、どのマップとも同じ始まり方をします。

34.4 マップのシーンをenter()で作る

シーンのコンストラクターは、マップの名前と出発点の名前を覚えるだけです。
本当の仕事は全部enter()の中で、切り替えの瞬間、フェードアウトの後に行います:

void MapScene::enter() {
  // マップはWorldから(初めてならファイルを読む)。扉は入る前に読めることを確かめてある
  // The map comes from World (loaded from its file the first time). Doors check that it loads before switching
  map = g.world.map(mapName);
  setUp();
}

void MapScene::setUp() {
  g.tiles.build(*map); // 静的な頂点バッファを作る(マップに入るたびに一度) / build the static vertex buffer (once per
                       // visit)
  const MapObject *start = map->findObject("spawn", spawnName);
  if (!start) {
    fprintf(stderr, "%s: 出発点がない / no spawn point '%s' (startを使う / using start)\n", map->path().c_str(),
            spawnName.c_str());
    start = map->findObject("spawn", "start");
  }
  hero.look = 0;
  hero.placeAt(start ? start->rect.position() : Vec2{kTile, kTile});
  std::string_view face = start ? start->get("face", "down") : "down";
  hero.facing = face == "up" ? Facing::Up : face == "left" ? Facing::Left : face == "right" ? Facing::Right : Facing::Down;
  // 最初のフレームは更新なしで描かれる:今のうちに立ちのクリップを選んでおく / the first frame is drawn before any
  // update: pick the standing clip now
  hero.animate(g.characters, 0.0f);

  // 宝箱:開いたかどうかはWorldに残っている(マップ名/宝箱名) / chests: whether they are open is kept in World
  // (map name/chest name)
  chests.clear();
  blockers.clear();
  for (const MapObject &o : map->objects())
    if (o.kind == "chest") {
      Rect box = {o.rect.x + 1.0f, o.rect.y + 4.0f, 14.0f, 12.0f};
      chests.push_back({&o, box, mapName + "/" + o.name});
      blockers.push_back(box);
    }
  warpArmed = false;
  leaving = false;
}

此の分け方が大事なのは、古いシーンと新しいシーンが共有する物がある為です。
GameはTileRendererを1つだけ持っています。
VAOが1つ、プログラム(エンジンのスプライトのシェーダー)が1つ、頂点バッファと添字のバッファが1つずつです。
フェードアウトの間、古いシーンはまだ其のバッファで描いているので、新しいシーンは其れをコンストラクターで触ってはいけません。
コンストラクターは扉が働いた時、0.3秒早く呼ばれるからです。
enter()の時には古いシーンはもう無いので、g.tiles.build(*map)は安全にバッファを入れ替えられます。

buildは第33章の関数の儘で、最後は此うなっています:

  // 不変のストレージ(フラグ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());

不変のストレージ(Bufferの中の、フラグ0のglNamedBufferStorage)は大きさを変えられず、書き直しも出来ません。
3枚のマップは大きさが違うので、入る度にバッファのオブジェクトを2つ新しく作ります。
verticesとindicesに代入すると、古い物は消されます。
VAOは其の儘で、glVertexArrayVertexBufferとglVertexArrayElementBufferが其れを新しいバッファに向けます。
スプライトのプログラムとアトラスのテクスチャは全く変わりません。

どれ位の仕事でしょうか?
SpriteVertexは20バイト(位置、UV、詰めた色)なので、四角形1つは80バイトです:

マップ 大きさ 静的な四角形 頂点バッファ 添字のバッファ
village 40 × 28 1449 115 920バイト 25 104バイト
home 12 × 10 134 10 720バイト 2 880バイト
field 40 × 24 1325 106 000バイト 22 560バイト

(添字のバッファは一番大きい層の分だけで、四角形1つに添字6個 × 4バイトです。村は地面の1046個、家は120個、野原は940個。)
1120マスのループと約116 KBの送信1回が真っ黒な画面の陰で起きるだけなので、目には見えません。
大きなマップのゲームは、全部を作り直さずに塊ごとに読み込みます(課題6はマップごとにバッファを1つ持ちます)。
でもenter()で作り直すのが、正しい物の中で一番簡単な方法です。

setUpの残りは、マップの物をシーン自身のデータにします。
主人公を出発点に置き(扉が存在しない出発点を名指していたら、警告を出してstartを使います)、出発点の向きを向かせ、宝箱の物ごとにChestを1つ作ります。
hero.animate(g.characters, 0.0f)は第33章の最初のフレームの為の直しです。
新しいシーンは切り替えのすぐ後、最初の更新の前に一度描かれ、クリップが無ければ主人公には見せるコマがありません。
宝箱の当たり判定の箱は、マスの下の方の14 × 12ピクセルです。
其の為、主人公は下から近付けて、宝箱の手前に描かれます。

34.5 World:ファイルから、初めて使う時に読むマップ

第33章のmainは村を読み込んで、シーンの中に移していました。
マップが3枚になり、シーンが現れては消える様になると、マップにはシーンより長生きする置き場が要ります。
其れがWorldです:

class World {
public:
  // マップを名前で:初めてなら games/rpg/assets/maps/<名前>.map を読む。読めなければnullptr。
  // ポインターは変わらない(読み直しても同じ場所) / a map by name: loaded from games/rpg/assets/maps/<name>.map on
  // first use; nullptr if it cannot be loaded. The pointer stays valid (also across reloads)
  Tilemap *map(const std::string &name);
  // ファイルから読み直す(タイルセットと、読んであるほかのマップも)。失敗したら全部前のまま / reloads from the file
  // (the tileset and the other loaded maps too); on failure everything stays as it was
  bool reload(const std::string &name);
  int loadedMaps() const { return static_cast<int>(maps.size()); }

  bool flag(const std::string &name) const { return flags.contains(name); }
  void setFlag(const std::string &name) { flags.insert(name); }

  int gold = 0;

  static std::string pathOf(const std::string &name) { return "games/rpg/assets/maps/" + name + ".map"; }

private:
  std::unordered_map<std::string, std::unique_ptr<Tilemap>> maps;
  TilesetCache tilesets;
  std::unordered_set<std::string> flags;
};

そして実装の全部です:

#include "world.hh"

#include <cstdio>
#include <utility>
#include <vector>

Tilemap *World::map(const std::string &name) {
  if (auto it = maps.find(name); it != maps.end()) return it->second.get();
  std::optional<Tilemap> loaded = Tilemap::load(pathOf(name), &tilesets);
  if (!loaded) return nullptr;
  printf("%s: 読んだ / loaded (%d×%d)\n", pathOf(name).c_str(), loaded->width(), loaded->height());
  return (maps[name] = std::make_unique<Tilemap>(std::move(*loaded))).get();
}

bool World::reload(const std::string &name) {
  if (!maps.contains(name)) return map(name) != nullptr;
  // タイルセットも読み直す。マップの格子はタイルセットの番号なので、読んである全部のマップを新しい表で読み直す
  // (古いタイルセットを持ったままのマップが残らない)。全部読めたときだけ入れ替え、一つでも失敗したら何も変えない
  // The tileset is read again too. Map grids hold the tileset's kind numbers, so every loaded map is read again with
  // the new table (no map keeps the old tileset). They are swapped in only if all of them load; one failure changes
  // nothing
  std::vector<std::string> names = {name}; // 今のマップから:エラーはまずそこに出る / the current map first: its
                                            // errors come first
  for (const auto &entry : maps)
    if (entry.first != name) names.push_back(entry.first);
  TilesetCache freshTilesets;
  std::vector<std::pair<Tilemap *, Tilemap>> fresh;
  for (const std::string &n : names) {
    std::optional<Tilemap> loaded = Tilemap::load(pathOf(n), &freshTilesets);
    if (!loaded) return false;
    fresh.emplace_back(maps[n].get(), std::move(*loaded));
  }
  // 同じ場所に入れる:シーンのポインターはそのまま / same addresses: scenes' pointers stay valid
  for (auto &[target, loaded] : fresh) *target = std::move(loaded);
  tilesets = std::move(freshTilesets); // 古いタイルセット(とテクスチャー)はここで消える / the old tileset (and its
                                       // texture) is freed here
  return true;
}

初めて使う時に読む。 World::map("field")は名前を探し、初めてならgames/rpg/assets/maps/field.mapというパスを作り、読み込み、1行出して取って置きます。
野原は主人公が東の出口まで歩くまで読まれず、2回目からは読み直されません。
下の実行の記録で、各マップの「loaded」の行は丁度1回ずつ出ています。
マップの名前はファイルの名前なので、扉のmap=だけで繋がります。
何十枚ものマップがある本物のゲームも此の様に読み、暫く使っていないマップを忘れる事もあります。
小さなテキストファイル3つなら、其の儘置いておけば良いです。

変わらないアドレス。 置き場が持つのはTilemapの値ではなくstd::unique_ptr<Tilemap>です。
unique_ptrの指す先は、入れ物が何をしても動きません。
なので、シーンが持つTilemap *は、他のマップを読んでも有効な儘です。
(std::unordered_mapは大きくなっても要素を動かさず、無効になるのはイテレーターだけです。
でもstd::vectorや、多くのエンジンが代わりに使うオープンアドレス法のハッシュ表は値を動かすので、ポインターにすれば其の選択に左右されません。
又、値で持つとmaps[name] = …はTilemapに無いデフォルトコンストラクターが要るので、コンパイル出来ません。)
同じ仕掛けでRも動きます。
reloadは新しく読んだ物を其々同じオブジェクトにムーブ代入する(*target = std::move(loaded))ので、シーンのポインターは其の儘新しいマップを見ます。
其の後シーンはsetUp()をもう一度呼びます。
宝箱が古い物の一覧の中のMapObjectを指しているからです。
そして主人公を元の場所に戻します。
どれかのファイルに間違いがあれば、reloadは何も入れ替える前にfalseを返し、全てのマップが元の儘残ります。

タイルセットの共有。 3枚のマップはどれもtileset ../tiles.tilesetと書いてあり、何もしなければ其々がタイルセット、アトラスのPNG、其のGLのテクスチャを自分で1つずつ読みます。
Tilemap::loadは表を省略可能な引数で受け取る様になりました:

// 読んだタイルセットを覚えておく表(パス → タイルセット):同じタイルセットのマップは画像を共有する
// A table of loaded tilesets (path → tileset): maps with the same tileset share its image
using TilesetCache = std::unordered_map<std::string, std::shared_ptr<const Tileset>>;

    } else if (command == "tileset") {
      std::string file;
      in >> file;
      std::string tilesetPath = folderOf(path) + file;
      if (cache && cache->contains(tilesetPath)) {
        map.tiles = cache->at(tilesetPath);
        continue;
      }
      std::optional<Tileset> set = Tileset::load(tilesetPath);
      if (!set) return fail("タイルセットを読めない / cannot load the tileset " + file);
      map.tiles = std::make_shared<const Tileset>(std::move(*set));
      if (cache) (*cache)[tilesetPath] = map.tiles;

キーはマップのファイルが作るパス(games/rpg/assets/maps/../tiles.tileset、3枚とも同じ文字列)で、値は第33章が既にTilemap::tilesに使っていたshared_ptrです。
なので3枚のマップはTilesetのオブジェクトとテクスチャを1つずつ共有し、其のテクスチャはどれかのマップが使っている限り生きています。
Rはタイルセットとアトラスも読み直します。
其の為、reloadは今のマップだけでなく、読んである全てのマップを読み直します。
マップの格子はタイルセットの種類の番号なので、マップと其のタイルセットは一緒に変わらなければなりません。
直した後も古いタイルセットを持ち続けるマップは、自分が読み直されるまで古いタイルを見せ、其のマップがある限り古いアトラスが新しい物の隣でメモリに残ります。
なのでreloadは新しい表を作り、先ず今のマップ(探しているエラーは其処にあります)、次に他のマップを其の表で読み、全部読めた時だけ其々のオブジェクトに移して表を入れ替えます。
此処で古いタイルセットと其のテクスチャが消えます。
どこかのファイルが1つでも壊れていれば、何も変わりません。
小さなテキストファイル3つを読み直すのは一瞬です。
マップが沢山あるゲームなら、直したタイルセットを使うマップだけを読み直すでしょう。

寿命とGLのコンテキスト。 タイルセットはテクスチャを持つので、WorldはGLのオブジェクトを持ちます。
全てのGLのオブジェクトは、コンテキストがまだある内に消さなければなりません。
mainはWorldをWindowの後に宣言するので、Worldの方が先に消えます:

  // マップは使うときにWorldが読む(最初の村だけ、ここで読めるか確かめる) / World loads maps when they are first
  // needed (only the first one, the village, is checked here)
  World world;
  if (!batch || !tiles || !ui || !pixel || !characters || !world.map("village")) return 1;

world.map("village")は最初のマップを起動時に確かめます。
此処での間違いはプログラムを止めるべきです。
他のマップは全部、其の扉が確かめます。

34.6 残す物と、やり直す物

さて、最初の問いです。
新しいMapSceneは入る度に作られ、出る時に消されるので、其の中の物は全部毎回やり直しになります。
其処から簡単な決まりが出来ます:

  • マップを出ても残らなければならない物は全部Worldに置く(デバッグの切り替えはGame::debugに)。
  • シーンの中の物は一時的:毎回、マップのファイルに書いてある通りから始まる。

1回の遊びに沿った4本の帯。mainはWindow、SpriteBatch、TileRenderer、フォント、CharacterSheetをプログラム全体の間持つ。Worldもプログラム全体の間生きていて、マップの置き場(village.mapは最初に、home.mapは2回目の訪問で、field.mapは4回目で読まれる)、足されていく印home/home_chest、village/village_chest、field/garden_chest、そして各訪問の終わりのお金0、50、80、180、180 Gを持つ。Game::debugはB、Z、H、1 2 3の切り替えを扉を通っても保つ。MapSceneの帯はフェードで区切られた別々の5つの箱、村、家、村、野原、村で、どれも主人公は出発点、宝箱は物から、浮かぶ文字と名前の時間から始まり、どれもenterでtiles.buildを呼ぶ

今の所Worldが持つのは3つ、マップの置き場、印(flags)、そしてお金です。
印は集合の中の文字列に過ぎません。
flag(name)は其れがあるかを聞き、setFlag(name)は足します。
宝箱の印はsetUpで作る"<マップ>/<宝箱の名前>"(village/village_chest)なので、2枚のマップが両方ともchestという宝箱を持っていても、状態は混ざりません。
宝箱を開けると、其の状態はWorldに入ります。
シーンに入るのは浮かぶ「+N G」の文字だけです:

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;
  }
}

そして宝箱を描く時は、どのスプライトを使うかをWorldに聞きます:

  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;
  };

Chestの一覧其の物は毎回マップの物から作り直されるので、自分の状態は何も持ちません。
宝箱が開いているかどうかは、シーンには決して覚えません。
村の宝箱の、出掛ける前と、野原に行って戻って来た後です:

村の道の2つの画面。左はbefore: chest closedと書かれ、主人公は閉じた宝箱に向かって歩き、お金は50 G。右はafter the field and back: still openと書かれ、宝箱は開いていて、お金は180 G

そして此れがやり直される物です。
主人公は、前に出た時に立っていた場所ではなく、通って来た扉の出発点に居ます。
「+30 G」の文字は消え、名前の帯がまた出て、水のアニメーションも最初からです。
第35章では村人も此の一覧に加わり、戻って来ると自分の場所に戻っています。
其の為のコードは何も要りません。
新しいオブジェクトには、只其の通りの事が起きるだけです。
課題3では宝箱の印をシーンに移して逆を見ます。
戻って来る度に、全部の宝箱が中身ごと元に戻ります。
第35章では、どのマップの物も印次第で在ったり無かったりさせられる様にするので、同じ仕組みで、一度開けた門を二度と現れない様に出来ます。

落とし穴:デバッグの切り替え

此の章を作っている時、最初の版はデバッグの切り替え(B、Z、Hと層のキー)を第33章と同じくMapSceneに置いていました。
HでHUDを消すと村では消えたのに、主人公が家に入った途端に戻って来ました。
家は新しいシーンだからです。
宝箱と同じ問いを実際に踏んで見つけた訳で、答えも同じです。
切り替えはプログラムと同じだけ生きるGameに移りました:

// デバッグ表示の切り替え:シーンはマップごとに作り直されるので、ここ(Game)に置く(シーンに置くと扉で元に戻る)
// Debug view toggles: scenes are recreated for every map, so they live here in Game (in a scene they would reset at
// every door)
struct DebugView {
  bool boxes = false, zoomOut = false, hud = true;
  std::array<bool, 8> layers = {true, true, true, true, true, true, true, true};
};

// ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference
struct Game {
  Window &window;
  Input &input;
  GameLoop &loop;
  SpriteBatch &batch;
  TileRenderer &tiles;      // GPUの物は一つを使い回す(マップが変わったらbuildし直す) / one set of GPU objects, rebuilt
                            // when the map changes
  World &world;             // マップの置き場と、残る状態 / the loaded maps and the persistent state
  const Font &ui;           // mono16:画面の解像度 / screen resolution
  const Font &pixel;        // pixel12:キャンバスの中 / inside the canvas
  const CharacterSheet &characters;
  Camera2D screen;          // 1280 × 720のUI / the 1280 × 720 UI
  Viewport uiViewport;
  DebugView debug;
};

Gameは、全てのシーンが参照で受け取る共有の物の袋です(第26章のやり方)。
エンジンのオブジェクト、1つだけのTileRenderer、World、そしてDebugViewが入っています。
GameとWorldの違いは意味の違いです。
Worldはゲームの状態、セーブファイルが書く様な物です。
Game::debugは開発者の為の便利な物で、扉で元に戻って欲しくないだけです。

34.7 目の前の物を調べる

宝箱を開けるには、主人公が其れを向いていなければなりません。
移動には足元の箱を使い、調べるには其の前にある2つ目の小さな箱、前の箱(probe)を使います:

// 顔の前の小さな箱:これに触れる物を調べる / a small box in front of the face: things touching it can be checked
Rect MapScene::facingProbe() const {
  const Rect &b = hero.box;
  constexpr float r = 8.0f;
  switch (hero.facing) {
  case Facing::Down: return {b.x, b.bottom(), b.w, r};
  case Facing::Up: return {b.x, b.y - r, b.w, r};
  case Facing::Left: return {b.x - r, b.y - 2.0f, r, b.h + 4.0f};
  case Facing::Right: return {b.right(), b.y - 2.0f, r, b.h + 4.0f};
  }
  return b;
}

前の箱は、向いている方向に足元の箱の辺から8 px伸びます。
横向きの前の箱は6 pxの足元の箱より4 px高く(上下に2 pxずつ)、主人公が宝箱より数ピクセル上や下に立っていても見つけられます。
Bは前の箱を黄色で描きます。
章の最初のデバッグの画面の通りです。
「confirm」の行動を押すとinteract()が呼ばれ、前の箱に重なる最初の閉じた宝箱を開けます。
行動はmainで、第33章の移動の行動の隣に割り当てます:

  input.bind("confirm", {InputBinding::key(GLFW_KEY_SPACE), InputBinding::key(GLFW_KEY_ENTER)});

宝箱は固い物でもあります。
其の箱はextraの一覧(blockers)としてmoveOnMapに渡されるので、主人公は樽と同じ様に其の周りを滑ります。
そして主人公と同じyで並べるバッチでlayer = 箱の下の辺として描くので、主人公は宝箱より上に立つと其の後ろに、下に立つと手前に描かれます。

34.8 名前の帯とお金の表示

どちらもpixel12でキャンバスに描きます。
Camera2D::screen(kView)を使う専用のバッチなので、世界のカメラがスクロールしても動きません:

  // キャンバスの画面に固定の物:マップの名前、お金 / things fixed to the canvas screen: the map's name, the money
  Camera2D canvas = Camera2D::screen(kView);
  b.begin(canvas.matrix());
  float banner = std::clamp((kBannerTime - time) / 0.5f, 0.0f, 1.0f);
  if (banner > 0.0f) {
    Vec2 size = g.pixel.measure(map->title());
    Rect box = Rect::fromCentre({160.0f, 30.0f}, {size.x + 16.0f, size.y + 6.0f});
    b.drawRect(box, {0.106f, 0.09f, 0.15f, 0.85f * banner});
    b.drawRectOutline(box, {0.95f, 0.76f, 0.31f, banner});
    g.pixel.draw(b, map->title(), {160.0f, box.y + 3.0f}, {.color = {1.0f, 0.96f, 0.84f, banner}, .align = TextAlign::Centre});
  }
  char gold[32];
  snprintf(gold, sizeof gold, "%d G", g.world.gold);
  g.pixel.draw(b, gold, {314.0f, 160.0f}, {.color = hexColor(0xf2c14eff), .align = TextAlign::Right, .shadow = hexColor(0x1b1726ff)});
  b.end();

timeはシーン自身の時計で、新しいシーンではいつも0から始まります。
なので帯は、何のコードも足さずに毎回の訪問で出ます。
2.0秒の間はすっかり見え、其の後(kBannerTime − time) / 0.5が最後の0.5秒で消していきます。
シーンはフェードインの間にもう動いているので、帯は新しいマップが見えた時にはもう其処にあります。
此れもやり直しの決まりの良い例です。
「帯を出した」という印をWorldに置けば、各名前はゲームの中で1回しか出ません。
地方に初めて入った時だけ名前を出すゲームは、そうしています。

34.9 動かす

今まで通りビルドし、プロジェクトのルートから動かします:

./build/games/rpg/rpg

Windowsでは、Visual Studioがプロジェクトのルートを作業フォルダにしてbuild\games\rpg\Debug\rpg.exeを動かします。
stdoutには、読み込み、切り替え、宝箱の全部が記録されます。
動画の一周をスクリプトで、毎秒60回の更新で動かすと此うなります:

OpenGL 4.5 (Core Profile) Mesa 25.2.8-0ubuntu0.24.04.4 / llvmpipe (LLVM 20.1.2, 256 bits)
games/rpg/assets/maps/village.map: 読んだ / loaded (40×28)
games/rpg/assets/maps/home.map: 読んだ / loaded (12×10)
village → home (door)
home/home_chest: 開けた / opened (+50 G, 50 G)
home → village (home_door)
village/village_chest: 開けた / opened (+30 G, 80 G)
games/rpg/assets/maps/field.map: 読んだ / loaded (40×24)
village → field (west)
field/garden_chest: 開けた / opened (+100 G, 180 G)
field → village (east)

(最初の行はテスト環境のドライバーの物です。皆さんの物には自分のGPUの名前が出ます。)
どのマップも、初めて其処へ切り替える直前に1回だけ読まれ、2回目に村に入る時は何も読みません。
HUDの最後の数「maps」は置き場のマップの数で、最初は1、家で2、野原で3になります。

間違いの時の動きを見るには、村の扉のmap=homeをmap=nowhereに変え、村でRを押して下さい。
扉に入ると、先ずTilemap::loadがgames/rpg/assets/maps/nowhere.mapの「cannot read」の行を出し、続いてgames/rpg/assets/maps/village.map: door home の先のマップ「nowhere」を読めない / cannot load map 'nowhere'が出て、主人公は村に留まります。
元に戻してもう一度Rを押し、扉から一度降りてまた乗ると、ゲームを再起動しなくても扉が働きます。

34.10 プラットフォームごとの注意

  • Linux、FreeBSD: マップの名前はファイルの名前になり、此れらのファイルシステムは大文字と小文字を区別します。map=HomeはHome.mapを探して失敗しますが、大文字と小文字を区別しないWindowsでは同じファイルが動きます。マップの名前は小文字にし、Windowsで作ったマップは出す前にLinuxでも試して下さい。
  • 全て: パスは/を使い、Windowsも其れを受け付けます。第33章のローダーはWindowsの改行の\rを既に取り除くので、マップのファイルはどのエディターで直してもどこでも動きます。
  • Windows(Visual Studio): 記録には日本語と→が入っています。コンソールで正しく出るのは、UTF-8のコードページ(chcp 65001)かWindows Terminalの時だけです。ゲーム自体には影響しません。

34.11 本物のエンジンではどうしているか

  • Unity: SceneManager.LoadSceneは今のシーンを入れ替え(あたし達のreplace)、LoadSceneMode.Additiveは開いているシーンの隣にシーンを読み込みます。大きなゲームは此れで消えない「核」のシーンを持ち、面を読み込んだり外したりします。DontDestroyOnLoadを付けたオブジェクトや、ScriptableObject又は普通のstaticなクラスに置いたデータが、あたし達のWorldの役をします。LoadSceneAsyncはフェードの間に読み込むので、大きな面でもゲームが止まりません。
  • Godot: get_tree().change_scene_to_file()が今のシーンを入れ替えます。全体の状態はオートロード(決して消されないシングルトンのノード)に置き、WorldとMapSceneと同じ分け方です。
  • RPGツクール: 扉は、行き先のマップ、位置、フェード(黒、白、なし)を指定する「場所移動」のコマンドを持つイベントです。全体のスイッチと変数が其のWorldで、各イベントには「セルフスイッチ」があります。宝箱が開けられた事を覚えるのは、正に其れです。
  • 昔の家庭用ゲーム機のRPG: マップは行き先のマップと行き先の出入口又は位置を持つワープの表を持ち、宝箱を開けるとセーブデータのビットが1つ立ちます。あたし達のdoor … map= spawn=の行と印の文字列は、其れを読める形にした物です。
  • エディター: Tiledのオブジェクトレイヤーとカスタムプロパティは、あたし達のobjectの行と同じ情報を持ち、多くのエンジンが其れを直接読みます。
  • オープンワールド: 切り替える代わりに、隣の塊を裏で読み込み続け、フェードは一度もしません(課題7は其の小さな版です)。

34.12 まとめ

  • 扉とマップの端の出口はマップの物(map=とspawn=の付いたdoor、warp)なので、新しいマップと繋がりにコードは要りません。扉のタイルは歩ける(D)。其の上の固い軒が主人公を止め、扉の物との重なりが切り替えを起こします。
  • マップに1回入るごとに1つのシーン: 扉は0.6秒(暗くなるのに0.3秒、明るくなるのに0.3秒)のフェードでscenes().replace(std::make_unique<MapScene>(…), kMapFade)を呼びます。あたし達の扉はどちら向きにも通れるので、pushでは一時停止したマップが積み上がります。
  • 切り替えの間: フェードアウトの間は誰も更新されないので、出て行くシーンはprevious = 今にして止めます。フェードインの間の頼みは待たされるので、leavingでシーンが歩き続けたり頼み直したりするのを止めます。扉は、主人公が一度どの扉にも乗っていない状態になってから効きます。
  • 仕事はenter()で: コンストラクターは名前を覚えるだけです。enter()がWorldからマップを貰い、1つだけの静的なタイルのバッファを作り直し(不変のストレージは大きさを変えられないので新しいバッファ。VAO、プログラム、テクスチャは同じ)、主人公を置き、宝箱を作ります。
  • Worldはマップを初めて使う時に読み、取って置きます。 unique_ptrの後ろに置くのでアドレスは変わらず(Rは読んである全部のマップとタイルセットを其の場で読み直し、1つでも失敗すれば何も変えない)、タイルセットはshared_ptrのTilesetCacheで共有します。Windowの後に宣言するので、其のテクスチャはコンテキストより先に消えます。
  • 決まり: マップを出ても残らなければならない物は全部World(印、お金、マップの置き場)とGame::debugに置き、シーンの中の物は一時的(主人公の位置、浮かぶ文字、帯の時間、第35章では村人)。宝箱が開いているかどうかは印"<マップ>/<名前>"です。
  • 調べるには足元の箱の前の8 pxの箱を使います。宝箱は、yで並べるバッチで描く固い箱です。マップの名前は2.5秒出し、最後の0.5秒で消します。

34.13 課題

  1. ★ 村長の家に中を付けて下さい。home.mapをelder.mapに写し(mapとtitleの行を変えます。宝箱の印はひとりでにelder/home_chestになります)、village.mapの17列目・7行目の扉をdからDにし、object door elder 17 7 map=elder spawn=doorとobject spawn elder_door 17 8 face=downを足します。elder.mapでは扉の行き先をspawn=elder_doorにします。村でRを押して入ると、再コンパイル無しで新しい家が動き、初めて入った時にHUDのマップの数が1つ増えるはずです。
  2. ★ kMapFadeを{.duration = 1.5f, .color = hexColor(0xffffffff)}にして下さい。扉はゆっくり白へフェードする様になり、0.75秒のフェードアウトの間はキーが効かず、0.75秒のフェードインの間はもう歩けるはずです。
  3. ★ 宝箱が元に戻る様にして下さい。開けた宝箱をWorldではなく、MapSceneのstd::unordered_set<std::string>のメンバーに覚えます。宝箱は1回の訪問で1回開いてお金をくれ、戻って来る度に閉じてお金も元通りになるはずです。World::goldは増え続けます。
  4. ★★ セーブとロード:F5でWorldの印とお金をテキストファイルに書き(印ごとにflag <名前>の行、そしてgold <n>の行)、F9で其れらを空にしてファイルを読み戻し、scenes().replaceAll(std::make_unique<MapScene>(g, "village", "start"), kMapFade)を呼んで下さい。家の宝箱を開けてF5、村の宝箱を開けてF9を押すと、村の出発点に50 Gで立ち、家の宝箱は開いていて、村の宝箱はまた閉じているはずです。MapSceneの中に保存の要る物は何も無く、其れが決まりの狙いです。
  5. ★★ 家にpushとpopを使って下さい。村の扉はkMapFadeで家の中をpushし、家の扉はscenes().pop(kMapFade)を呼びます。村に戻ると主人公は入る前に立っていた場所に居て、扉の方を向いているはずです。但し、resume()でタイルを作り直す(g.tiles.build(*map))までは、村は家のタイルで描かれます。resume()ではleaving = falseとwarpArmed = falseにもしなければなりません。村のシーンは扉が働いた時に止まった儘で、主人公はまだ其の扉の上に立っているからです。シーンのpause()はもうpreviousを止めているので、フェードの間に村が揺れる事はありません。
  6. ★★ 先に読む:置き場のマップごとにTileRendererを1つ持ち(例えばマップの置き場の隣に、名前からTileRendererへの表を置きます)、毎回のenter()ではなく、マップを初めて読んだ時に1回だけ作って下さい。切り替えではバッファの仕事が全く無くなるはずです。代わりに全部のマップのメモリを同時に使います。あたし達の3枚では頂点が115 920 + 10 720 + 106 000 = 232 640バイトです(添字のバッファは別)。
  7. ★★★ 継ぎ目の無いマップの端:主人公が村の東の出口に着いたら、村の右に(村の幅640 pxだけずらして)野原を描き、フェード無しでカメラを横にスクロールさせ、カメラが移り切った所でシーンを切り替えて下さい。昔のゼルダのフィールドの画面の様に、世界が続いて感じられるはずです。タイルのバッファが同時に2つ、1枚のマップに縛られないカメラ、そして主人公がまだ村のシーンに居る間の野原との当たり判定が要ります。

DIFFをダウンロード

プロジェクトをダウンロード(ZIP)

ファイル: a/games/rpg/CMakeLists.txt | b/games/rpg/CMakeLists.txt

前新
@@ -4,7 +4,8 @@ add_executable(rpg
4 src/tilemap.cc 4 src/tilemap.cc
5 src/tile_renderer.cc 5 src/tile_renderer.cc
6 src/character.cc 6 src/character.cc
7 src/map_scene.cc) 7 src/map_scene.cc
    8 src/world.cc)
8 target_include_directories(rpg PRIVATE src) 9 target_include_directories(rpg PRIVATE src)
9 target_link_libraries(rpg PRIVATE engine) 10 target_link_libraries(rpg PRIVATE engine)
10 enable_warnings(rpg) 11 enable_warnings(rpg)

ファイル: a/games/rpg/README.md | b/games/rpg/README.md

前新
@@ -10,6 +10,7 @@
10 |---|---| 10 |---|---|
11 | 矢印 / WASD | 移動 / move | 11 | 矢印 / WASD | 移動 / move |
12 | Shift | 走る / run | 12 | Shift | 走る / run |
    13 | Space / Enter | 調べる(宝箱) / check (chests) |
13 | 1 2 3 | 層の表示(地面・飾り・上の層) / toggle the layers (ground, decor, overlay) | 14 | 1 2 3 | 層の表示(地面・飾り・上の層) / toggle the layers (ground, decor, overlay) |
14 | B | 当たり判定の箱 / collision boxes | 15 | B | 当たり判定の箱 / collision boxes |
15 | Z | 引いて見る(行のカリングが見える) / zoom out (shows the row culling) | 16 | Z | 引いて見る(行のカリングが見える) / zoom out (shows the row culling) |
@@ -18,5 +19,7 @@
18 | Esc | 終了 / quit | 19 | Esc | 終了 / quit |
19   20  
20 マップは `assets/maps/*.map`(テキスト)。書式は `src/tilemap.hh`、タイルの文字は `assets/tiles.tileset`。 21 マップは `assets/maps/*.map`(テキスト)。書式は `src/tilemap.hh`、タイルの文字は `assets/tiles.tileset`。
    22 扉は `object door <名前> <列> <行> map=<マップ> spawn=<出発点>`、マップの端の出口は `object warp … h=2 …`。
21 Maps are `assets/maps/*.map` (text). The format is described in `src/tilemap.hh`, the tile characters in 23 Maps are `assets/maps/*.map` (text). The format is described in `src/tilemap.hh`, the tile characters in
22 `assets/tiles.tileset`. 24 `assets/tiles.tileset`. Doors are `object door <name> <col> <row> map=<map> spawn=<spawn point>`, exits at the edge of
    25 a map `object warp ... h=2 ...`.

ファイル: a/games/rpg/assets/LICENSE.txt | b/games/rpg/assets/LICENSE.txt

前新
@@ -6,4 +6,6 @@ tiles.png/.atlas 16×16のタイル(草・道・水・木・家・家具
6 characters.png 人物5人 × 4方向の歩き(16×16、9コマずつ) / five characters × 4-direction walk (16×16, 9 frames 6 characters.png 人物5人 × 4方向の歩き(16×16、9コマずつ) / five characters × 4-direction walk (16×16, 9 frames
7 each) (chapter 33) 7 each) (chapter 33)
8 tiles.tileset タイルの文字・固さ・動き(手書き) / tile characters, solidity, animation (hand-written, chapter 33) 8 tiles.tileset タイルの文字・固さ・動き(手書き) / tile characters, solidity, animation (hand-written, chapter 33)
9 maps/village.map 村のマップ / the village map (chapter 33; edit by hand freely) 9 maps/village.map 村のマップ / the village map (chapters 33-34; edit by hand freely)
    10 maps/home.map 家の中 / the house interior (chapter 34)
    11 maps/field.map 野原 / the field (chapter 34)

ファイル: /dev/null | b/games/rpg/assets/maps/field.map

前新
@@ -0,0 +1,91 @@
    1 # のはら / Field
    2 # 書式は games/rpg/src/tilemap.hh、文字の意味は ../tiles.tileset / format: games/rpg/src/tilemap.hh,
    3 # characters: ../tiles.tileset ('.' = 空 / empty)
    4 map field
    5 title のはら / Field
    6 tileset ../tiles.tileset
    7 size 40 24
    8  
    9 layer ground
    10 ,,,,,,,,,;,;,,,,;;,,,,,,,,,,,,,,,,,,,,,;
    11 ,,,,,,,;,,,,;,,,;,;,,,,,,,,,,,;,,,,,,,,,
    12 ,,,;,,,,,,,,,;,,,,,;,,,,,,,,,,,,,,,,;,,,
    13 ,,,,,,,,,,;,,,,,,,,,,,,,,,,,,,,;,;,;;;,,
    14 ,,,,,,;,;,,,,;,,,,,,;,;,;,,;;;;;;;;,,;,,
    15 ,,,,;,,,,,,,,,;,,,,;,,;,,;,;;;;;;;;,,,,;
    16 ,;,,,;;,,,;,,,,;,,;,;,,,;,,;;;;;;;;,,,,,
    17 ,,,,,,,,,,,;;,,,;,,,;,,,;;,;;;;;;;;,,,,;
    18 ;,,,,,,;,,,;,,,,,,,,,,,,,,,;;;;;;;;,,;;,
    19 ,,,,,;,,,;,,,,,;,,,,,,,,,,,,,,==;,,,,,;,
    20 ==:===========:==============::=,;,,,,,,
    21 ====================:===========,,,,,,,,
    22 ;,,;,,;,,,,,,,,,,,,,;;;,,,,,,,;,,,,,,,,;
    23 ,,;;,;;,,,,,,;,,,,,,,,,;,;,,,;,,,,,,,;,,
    24 ,,,,,,,,,,,,;,,,,,;,,,;,;,;,,,;,,,,,,,,,
    25 ,,,,,,,,,,;;,,,,,,,,,,,,;,,,,,,,;;,,,,,,
    26 ,,,;,,,;,,,,,,,;,^^^^^,,,,,,,;;,,;,,;,;,
    27 ,,,;,,;,,,;,,,,,,~~~~~;,,,,,,;,,,,,,,,;,
    28 ,,,,;,;,,;,,,,,;,~~~~~,,,,,;,,,,,,;,,,;,
    29 ,,;,,,,,;,,,,,,,,~~~~~,,,,,,;,,;,,;;,,,;
    30 ;,,,,,,,,;,;,;,,,,,,;,;;,,,,,,,,,,,,;,;,
    31 ;,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
    32 ,,;,,;,,,,;;;,,,,,,,;,,,,;,,,,,,,,;;,,,;
    33 ;,,,,,,,;,,,,,,,,,,;,,,,,,,,,,,,,,,,,;,,
    34  
    35 layer decor
    36 ........................................
    37 TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
    38 b......................................b
    39 T.............T...........----------...T
    40 b.."""""..T.........T.....|.....s..|...b
    41 T.."""""..........*.......|.*......|...T
    42 b.."""""..................|........|...b
    43 T.........................|.%....*.|...T
    44 b....b..........b.........|........|...b
    45 b.....T............R......----..----..bT
    46 .......................................b
    47 ................"""""".........*.......T
    48 b......*.R......"""""".....R...........b
    49 T............S..""""""R.T........T..T..T
    50 b..."""""""...*..........*...b.........b
    51 T..."""""""............................T
    52 b...""""""".............""""""""....*..b
    53 T...""""""".R..........."""""""".......T
    54 b......................."""""""".....T.b
    55 T......................."""""""".......T
    56 b.......T.........................R....b
    57 T..T...........T.....b..T..............T
    58 b......................................b
    59 TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
    60  
    61 layer overlay above
    62 tttttttttttttttttttttttttttttttttttttttt
    63 ........................................
    64 t.............t........................t
    65 ..........t.........t...................
    66 t......................................t
    67 ........................................
    68 t......................................t
    69 ........................................
    70 ......t................................t
    71 ........................................
    72 .......................................t
    73 ........................................
    74 t.......................t........t..t..t
    75 ........................................
    76 t......................................t
    77 ........................................
    78 t......................................t
    79 .....................................t..
    80 t......................................t
    81 ........t...............................
    82 t..t...........t........t..............t
    83 ........................................
    84 tttttttttttttttttttttttttttttttttttttttt
    85 ........................................
    86  
    87 # 物:object <種類> <名前> <列> <行> [key=value …] / objects: kind name col row [key=value ...]
    88 object spawn start 1 10 face=right
    89 object spawn west 1 10 face=right
    90 object warp west 0 10 h=2 map=village spawn=east
    91 object chest garden_chest 30 5 gold=100

ファイル: /dev/null | b/games/rpg/assets/maps/home.map

前新
@@ -0,0 +1,49 @@
    1 # 家 / Home
    2 # 書式は games/rpg/src/tilemap.hh、文字の意味は ../tiles.tileset / format: games/rpg/src/tilemap.hh,
    3 # characters: ../tiles.tileset ('.' = 空 / empty)
    4 map home
    5 title 家 / Home
    6 tileset ../tiles.tileset
    7 size 12 10
    8  
    9 layer ground
    10 xxxxxxxxxxxx
    11 xwwwnwwnwwwx
    12 x__________x
    13 x__________x
    14 x___rrrr___x
    15 x___rrrr___x
    16 x___rrrr___x
    17 x__________x
    18 x____m_____x
    19 xxxxx_xxxxxx
    20  
    21 layer decor
    22 ............
    23 ..KK.....F..
    24 .B........p.
    25 .E........p.
    26 ............
    27 ....cQQc....
    28 ............
    29 .P........U.
    30 ..........X.
    31 ............
    32  
    33 layer overlay above
    34 ............
    35 ............
    36 ............
    37 ............
    38 ............
    39 ............
    40 ............
    41 ............
    42 ............
    43 ............
    44  
    45 # 物:object <種類> <名前> <列> <行> [key=value …] / objects: kind name col row [key=value ...]
    46 object spawn start 5 7 face=up
    47 object spawn door 5 8 face=up
    48 object door out 5 9 map=village spawn=home_door
    49 object chest home_chest 8 2 gold=50

ファイル: a/games/rpg/assets/maps/village.map | b/games/rpg/assets/maps/village.map

前新
@@ -2,6 +2,7 @@
2 # 書式は games/rpg/src/tilemap.hh、文字の意味は ../tiles.tileset / format: games/rpg/src/tilemap.hh, 2 # 書式は games/rpg/src/tilemap.hh、文字の意味は ../tiles.tileset / format: games/rpg/src/tilemap.hh,
3 # characters: ../tiles.tileset ('.' = 空 / empty) 3 # characters: ../tiles.tileset ('.' = 空 / empty)
4 map village 4 map village
    5 title 村 / Village
5 tileset ../tiles.tileset 6 tileset ../tiles.tileset
6 size 40 28 7 size 40 28
7   8  
@@ -43,7 +44,7 @@ T...........s.........b............b...T
43 b......................................b 44 b......................................b
44 T.............AAAAAAA..................T 45 T.............AAAAAAA..................T
45 b.b..LLLLL....LLLLLLL...s....LLLLLX....b 46 b.b..LLLLL....LLLLLLL...s....LLLLLX....b
46 T...UMWdWMX..SMWMdMWM......bXMWdWMU..%.T 47 T...UMWDWMX..SMWMdMWM......bXMWdWMU..%.T
47 b..........*...........*...............b 48 b..........*...........*...............b
48 T..%...................................b 49 T..%...................................b
49 b....................................... 50 b.......................................
@@ -97,3 +98,8 @@ tttttttttttttttttttttttttttttttttttttttt
97   98  
98 # 物:object <種類> <名前> <列> <行> [key=value …] / objects: kind name col row [key=value ...] 99 # 物:object <種類> <名前> <列> <行> [key=value …] / objects: kind name col row [key=value ...]
99 object spawn start 7 9 face=down 100 object spawn start 7 9 face=down
    101 object door home 7 7 map=home spawn=door
    102 object warp east 39 10 h=2 map=field spawn=west
    103 object spawn home_door 7 8 face=down
    104 object spawn east 38 10 face=left
    105 object chest village_chest 21 8 gold=30

ファイル: a/games/rpg/src/game.hh | b/games/rpg/src/game.hh

前新
@@ -5,6 +5,7 @@
5 #include "character.hh" 5 #include "character.hh"
6 #include "tile_renderer.hh" 6 #include "tile_renderer.hh"
7 #include "tilemap.hh" 7 #include "tilemap.hh"
    8 #include "world.hh"
8   9  
9 #include "engine/camera2d.hh" 10 #include "engine/camera2d.hh"
10 #include "engine/font.hh" 11 #include "engine/font.hh"
@@ -15,11 +16,22 @@
15   16  
16 #include <array> 17 #include <array>
17 #include <optional> 18 #include <optional>
    19 #include <string>
18 #include <vector> 20 #include <vector>
19   21  
20 // 仮想解像度:320 × 180(1280 × 720の4倍)、タイル16 × 16で20 × 11.25マスが見える 22 // 仮想解像度:320 × 180(1280 × 720の4倍)、タイル16 × 16で20 × 11.25マスが見える
21 // The virtual resolution: 320 × 180 (× 4 = 1280 × 720); with 16 × 16 tiles, 20 × 11.25 tiles are visible 23 // The virtual resolution: 320 × 180 (× 4 = 1280 × 720); with 16 × 16 tiles, 20 × 11.25 tiles are visible
22 constexpr Vec2 kView = {320.0f, 180.0f}; 24 constexpr Vec2 kView = {320.0f, 180.0f};
    25 // マップを移るときのフェード(暗くなるのに半分、明るくなるのに半分) / the fade between maps (half to black, half back)
    26 constexpr Transition kMapFade = {.duration = 0.6f, .color = {0.0f, 0.0f, 0.0f, 1.0f}};
    27  
    28 // デバッグ表示の切り替え:シーンはマップごとに作り直されるので、ここ(Game)に置く(シーンに置くと扉で元に戻る)
    29 // Debug view toggles: scenes are recreated for every map, so they live here in Game (in a scene they would reset at
    30 // every door)
    31 struct DebugView {
    32 bool boxes = false, zoomOut = false, hud = true;
    33 std::array<bool, 8> layers = {true, true, true, true, true, true, true, true};
    34 };
23   35  
24 // ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference 36 // ゲーム全体で一つ。mainが作り、シーンは参照で持つ / one per game: main creates it, the scenes keep a reference
25 struct Game { 37 struct Game {
@@ -29,17 +41,22 @@ struct Game {
29 SpriteBatch &batch; 41 SpriteBatch &batch;
30 TileRenderer &tiles; // GPUの物は一つを使い回す(マップが変わったらbuildし直す) / one set of GPU objects, rebuilt 42 TileRenderer &tiles; // GPUの物は一つを使い回す(マップが変わったらbuildし直す) / one set of GPU objects, rebuilt
31 // when the map changes 43 // when the map changes
    44 World &world; // マップの置き場と、残る状態 / the loaded maps and the persistent state
32 const Font &ui; // mono16:画面の解像度 / screen resolution 45 const Font &ui; // mono16:画面の解像度 / screen resolution
33 const Font &pixel; // pixel12:キャンバスの中 / inside the canvas 46 const Font &pixel; // pixel12:キャンバスの中 / inside the canvas
34 const CharacterSheet &characters; 47 const CharacterSheet &characters;
35 Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI 48 Camera2D screen; // 1280 × 720のUI / the 1280 × 720 UI
36 Viewport uiViewport; 49 Viewport uiViewport;
    50 DebugView debug;
37 }; 51 };
38   52  
39 // マップの上を歩くシーン / the scene where you walk around a map 53 // マップの上を歩くシーン。マップ1つにつき1つ作り、扉で次のマップのシーンに入れ替える
    54 // The scene where you walk around a map. One per map; a door replaces it with the next map's scene
40 class MapScene : public Scene { 55 class MapScene : public Scene {
41 public: 56 public:
42 MapScene(Game &game, Tilemap map); 57 // mapName = World::mapの名前、spawn = 出発点の物の名前(spawn <名前>) / mapName = the name for World::map, spawn =
    58 // the name of a spawn object
    59 MapScene(Game &game, std::string mapName, std::string spawn);
43 void enter() override; 60 void enter() override;
44 void pause() override; 61 void pause() override;
45 void update(float dt) override; 62 void update(float dt) override;
@@ -47,19 +64,35 @@ public:
47 void drawUi(float alpha) override; 64 void drawUi(float alpha) override;
48   65  
49 private: 66 private:
50 void spawn(); 67 // 宝箱:開いたかどうかはWorldの印(マップ名/宝箱名)に残る / a chest: whether it is open is a World flag
51 // カメラ:主人公の足元を追い、マップの端で止める(マップが画面より小さければ真ん中に) 68 // (map name/chest name)
52 // The camera: follows the hero's feet and stops at the map's edges (centered when the map is smaller than the view) 69 struct Chest {
    70 const MapObject *object;
    71 Rect box;
    72 std::string flag;
    73 };
    74 struct Popup {
    75 std::string text;
    76 Vec2 position;
    77 float life;
    78 };
    79 void setUp(); // マップの物からシーンの物を作る / builds the scene's things from the map's objects
    80 void interact();
    81 void checkWarps();
    82 Rect facingProbe() const;
53 Camera2D followCamera(Vec2 target) const; 83 Camera2D followCamera(Vec2 target) const;
54   84  
55 Game &g; 85 Game &g;
56 Tilemap map; 86 std::string mapName, spawnName;
    87 Tilemap *map = nullptr; // Worldの中(読み直しても同じ場所) / inside World (same address across reloads)
57 Character hero; 88 Character hero;
58 std::vector<Rect> scratch; // 当たり判定の箱の作業用(毎ステップ作り直さない) / scratch boxes for collision (kept 89 std::vector<Chest> chests;
59 // between steps to avoid allocations) 90 std::vector<Rect> blockers; // 固い物(宝箱)の箱 / boxes of solid objects (chests)
    91 std::vector<Popup> popups;
    92 std::vector<Rect> scratch; // 当たり判定の箱の作業用 / scratch boxes for collision
60 float time = 0.0f; 93 float time = 0.0f;
61 bool showBoxes = false, zoomOut = false, showHud = true; 94 bool warpArmed = false; // 出発点が扉の上でも、一度離れるまで扉は効かない / doors only work after the hero has
62 std::array<bool, 8> layerOn; 95 // stepped off all of them once (in case a spawn point is on a door)
63 // HUD用:前のフレームの描画の数 / for the HUD: last frame's drawing counts 96 bool leaving = false; // 扉に入った:フェードが終わるまで動かない / entered a door: frozen until the fade ends
64 int rowFirst = 0, rowLast = 0, spriteCalls = 0; 97 int rowFirst = 0, rowLast = 0, spriteCalls = 0;
65 }; 98 };

ファイル: a/games/rpg/src/main.cc | b/games/rpg/src/main.cc

前新
@@ -1,8 +1,8 @@
1 // 第33章:見下ろし型RPG(1)タイルマップ、当たり判定のある移動、追いかけるカメラ 1 // 第34章:見下ろし型RPG(2)いくつものマップ、扉と出口、フェードでのシーンの切り替え、ファイルからのマップ
2 // Chapter 33: a top-down RPG (1) tile maps, movement with collision, a following camera 2 // Chapter 34: a top-down RPG (2) several maps, doors and exits, scene switching with fades, maps loaded from files
3 // 3 //
4 // 操作 / Controls: 4 // 操作 / Controls:
5 // 矢印 / WASD 移動 / move Shift 走る / run 5 // 矢印 / WASD 移動 / move Shift 走る / run Space / Enter 調べる(宝箱) / check (chests)
6 // 1 2 3 層の表示 / toggle layers (ground, decor, overlay) 6 // 1 2 3 層の表示 / toggle layers (ground, decor, overlay)
7 // B 当たり判定の箱 / collision boxes Z 引いて見る(カリングの確認) / zoom out (shows culling) 7 // B 当たり判定の箱 / collision boxes Z 引いて見る(カリングの確認) / zoom out (shows culling)
8 // H HUDの表示 / toggle the HUD 8 // H HUDの表示 / toggle the HUD
@@ -27,8 +27,10 @@ int main() {
27 std::optional<Font> ui = Font::load("assets/fonts/mono16.fnt"); 27 std::optional<Font> ui = Font::load("assets/fonts/mono16.fnt");
28 std::optional<Font> pixel = Font::load("assets/fonts/pixel12.fnt", TextureFilter::Nearest); 28 std::optional<Font> pixel = Font::load("assets/fonts/pixel12.fnt", TextureFilter::Nearest);
29 std::optional<CharacterSheet> characters = CharacterSheet::load("games/rpg/assets/characters.png"); 29 std::optional<CharacterSheet> characters = CharacterSheet::load("games/rpg/assets/characters.png");
30 std::optional<Tilemap> village = Tilemap::load("games/rpg/assets/maps/village.map"); 30 // マップは使うときにWorldが読む(最初の村だけ、ここで読めるか確かめる) / World loads maps when they are first
31 if (!batch || !tiles || !ui || !pixel || !characters || !village) return 1; 31 // needed (only the first one, the village, is checked here)
    32 World world;
    33 if (!batch || !tiles || !ui || !pixel || !characters || !world.map("village")) return 1;
32   34  
33 Input input; 35 Input input;
34 input.attach(window); 36 input.attach(window);
@@ -37,15 +39,18 @@ int main() {
37 input.bind("up", {InputBinding::key(GLFW_KEY_UP), InputBinding::key(GLFW_KEY_W)}); 39 input.bind("up", {InputBinding::key(GLFW_KEY_UP), InputBinding::key(GLFW_KEY_W)});
38 input.bind("down", {InputBinding::key(GLFW_KEY_DOWN), InputBinding::key(GLFW_KEY_S)}); 40 input.bind("down", {InputBinding::key(GLFW_KEY_DOWN), InputBinding::key(GLFW_KEY_S)});
39 input.bind("run", {InputBinding::key(GLFW_KEY_LEFT_SHIFT), InputBinding::key(GLFW_KEY_RIGHT_SHIFT)}); 41 input.bind("run", {InputBinding::key(GLFW_KEY_LEFT_SHIFT), InputBinding::key(GLFW_KEY_RIGHT_SHIFT)});
    42 input.bind("confirm", {InputBinding::key(GLFW_KEY_SPACE), InputBinding::key(GLFW_KEY_ENTER)});
40   43  
41 GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5}); 44 GameLoop loop({.step = 1.0 / 60.0, .maxSteps = 5});
42 PixelCanvas canvas(static_cast<int>(kView.x), static_cast<int>(kView.y)); 45 PixelCanvas canvas(static_cast<int>(kView.x), static_cast<int>(kView.y));
43 Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .tiles = *tiles, .ui = *ui, 46 Game game{.window = window, .input = input, .loop = loop, .batch = *batch, .tiles = *tiles, .world = world, .ui = *ui,
44 .pixel = *pixel, .characters = *characters, .screen = Camera2D::screen({1280.0f, 720.0f}), 47 .pixel = *pixel, .characters = *characters, .screen = Camera2D::screen({1280.0f, 720.0f}),
45 .uiViewport = {}}; 48 .uiViewport = {}, .debug = {}};
46   49  
47 SceneManager scenes; 50 SceneManager scenes;
48 scenes.push(std::make_unique<MapScene>(game, std::move(*village))); 51 // 黒から明るくなって始まる(空のスタックへのpushもフェードできる) / starts by fading in from black (a push onto the
    52 // empty stack can fade too)
    53 scenes.push(std::make_unique<MapScene>(game, "village", "start"), kMapFade);
49   54  
50 loop.run( 55 loop.run(
51 window, input, 56 window, input,

ファイル: a/games/rpg/src/map_scene.cc | b/games/rpg/src/map_scene.cc

前新
@@ -1,5 +1,6 @@
1 // マップのシーン:主人公を歩かせ、カメラで追い、層の順にタイルと人物を描く 1 // マップのシーン:主人公を歩かせ、カメラで追い、層の順にタイルと人物を描く。扉で別のマップへ(フェード付き)
2 // The map scene: walks the hero around, follows it with the camera, draws tiles and characters in layer order 2 // The map scene: walks the hero around, follows it with the camera, draws tiles and characters in layer order. Doors
    3 // lead to other maps (with a fade)
3 #include "game.hh" 4 #include "game.hh"
4   5  
5 #include "engine/collision.hh" 6 #include "engine/collision.hh"
@@ -7,50 +8,132 @@
7 #include <algorithm> 8 #include <algorithm>
8 #include <cmath> 9 #include <cmath>
9 #include <cstdio> 10 #include <cstdio>
    11 #include <memory>
10   12  
11 constexpr float kWalkSpeed = 72.0f; // ピクセル毎秒(4.5マス/秒) / pixels per second (4.5 tiles/s) 13 constexpr float kWalkSpeed = 72.0f; // ピクセル毎秒(4.5マス/秒) / pixels per second (4.5 tiles/s)
12 constexpr float kRunSpeed = 120.0f; 14 constexpr float kRunSpeed = 120.0f;
    15 constexpr float kBannerTime = 2.5f; // マップの名前を出す秒数 / seconds the map's name is shown
13   16  
14 MapScene::MapScene(Game &game, Tilemap tilemap) : g(game), map(std::move(tilemap)) { layerOn.fill(true); } 17 MapScene::MapScene(Game &game, std::string name, std::string spawn)
    18 : g(game), mapName(std::move(name)), spawnName(std::move(spawn)) {}
15   19  
16 void MapScene::enter() { 20 void MapScene::enter() {
17 g.tiles.build(map); // 静的な頂点バッファを作る(マップごとに一度) / build the static vertex buffer (once per map) 21 // マップはWorldから(初めてならファイルを読む)。扉は入る前に読めることを確かめてある
18 spawn(); 22 // The map comes from World (loaded from its file the first time). Doors check that it loads before switching
    23 map = g.world.map(mapName);
    24 setUp();
19 } 25 }
20   26  
21 void MapScene::spawn() { 27 void MapScene::setUp() {
    28 g.tiles.build(*map); // 静的な頂点バッファを作る(マップに入るたびに一度) / build the static vertex buffer (once per
    29 // visit)
    30 const MapObject *start = map->findObject("spawn", spawnName);
    31 if (!start) {
    32 fprintf(stderr, "%s: 出発点がない / no spawn point '%s' (startを使う / using start)\n", map->path().c_str(),
    33 spawnName.c_str());
    34 start = map->findObject("spawn", "start");
    35 }
22 hero.look = 0; 36 hero.look = 0;
23 const MapObject *start = map.findObject("spawn", "start");    
24 hero.placeAt(start ? start->rect.position() : Vec2{kTile, kTile}); 37 hero.placeAt(start ? start->rect.position() : Vec2{kTile, kTile});
25 std::string_view face = start ? start->get("face", "down") : "down"; 38 std::string_view face = start ? start->get("face", "down") : "down";
26 hero.facing = face == "up" ? Facing::Up : face == "left" ? Facing::Left : face == "right" ? Facing::Right : Facing::Down; 39 hero.facing = face == "up" ? Facing::Up : face == "left" ? Facing::Left : face == "right" ? Facing::Right : Facing::Down;
27 // 最初のフレームは更新なしで描かれる:今のうちに立ちのクリップを選んでおく / the first frame is drawn before any 40 // 最初のフレームは更新なしで描かれる:今のうちに立ちのクリップを選んでおく / the first frame is drawn before any
28 // update: pick the standing clip now 41 // update: pick the standing clip now
29 hero.animate(g.characters, 0.0f); 42 hero.animate(g.characters, 0.0f);
    43  
    44 // 宝箱:開いたかどうかはWorldに残っている(マップ名/宝箱名) / chests: whether they are open is kept in World
    45 // (map name/chest name)
    46 chests.clear();
    47 blockers.clear();
    48 for (const MapObject &o : map->objects())
    49 if (o.kind == "chest") {
    50 Rect box = {o.rect.x + 1.0f, o.rect.y + 4.0f, 14.0f, 12.0f};
    51 chests.push_back({&o, box, mapName + "/" + o.name});
    52 blockers.push_back(box);
    53 }
    54 warpArmed = false;
    55 leaving = false;
30 } 56 }
31   57  
32 void MapScene::pause() { hero.previous = hero.box.position(); } 58 void MapScene::pause() { hero.previous = hero.box.position(); }
33   59  
    60 // 顔の前の小さな箱:これに触れる物を調べる / a small box in front of the face: things touching it can be checked
    61 Rect MapScene::facingProbe() const {
    62 const Rect &b = hero.box;
    63 constexpr float r = 8.0f;
    64 switch (hero.facing) {
    65 case Facing::Down: return {b.x, b.bottom(), b.w, r};
    66 case Facing::Up: return {b.x, b.y - r, b.w, r};
    67 case Facing::Left: return {b.x - r, b.y - 2.0f, r, b.h + 4.0f};
    68 case Facing::Right: return {b.right(), b.y - 2.0f, r, b.h + 4.0f};
    69 }
    70 return b;
    71 }
    72  
    73 void MapScene::interact() {
    74 Rect probe = facingProbe();
    75 for (const Chest &c : chests) {
    76 if (!overlaps(probe, c.box) || g.world.flag(c.flag)) continue;
    77 g.world.setFlag(c.flag); // マップを出ても開いたまま / stays open after leaving the map
    78 int gold = c.object->getInt("gold", 0);
    79 g.world.gold += gold;
    80 popups.push_back({"+" + std::to_string(gold) + " G", {c.box.centre().x, c.box.y - 10.0f}, 1.2f});
    81 printf("%s: 開けた / opened (+%d G, %d G)\n", c.flag.c_str(), gold, g.world.gold);
    82 return;
    83 }
    84 }
    85  
    86 void MapScene::checkWarps() {
    87 bool onWarp = false;
    88 for (const MapObject &o : map->objects()) {
    89 if ((o.kind != "door" && o.kind != "warp") || !overlaps(hero.box, o.rect)) continue;
    90 onWarp = true;
    91 if (!warpArmed) continue;
    92 std::string target(o.get("map")), spawn(o.get("spawn", "start"));
    93 // 先のマップを今読む(初めてならファイルから)。読めなければ移らない / load the target map now (from its file the
    94 // first time); if it cannot be loaded, stay
    95 if (!g.world.map(target)) {
    96 fprintf(stderr, "%s: %s %s の先のマップ「%s」を読めない / cannot load map '%s'\n", map->path().c_str(),
    97 o.kind.c_str(), o.name.c_str(), target.c_str(), target.c_str());
    98 warpArmed = false;
    99 return;
    100 }
    101 printf("%s → %s (%s)\n", mapName.c_str(), target.c_str(), spawn.c_str());
    102 // 入れ替えは頼むだけ:フェードアウトの後で、このシーンがexit、新しいシーンがenterする
    103 // The replacement is only requested: after the fade out this scene exits and the new one enters
    104 scenes().replace(std::make_unique<MapScene>(g, target, spawn), kMapFade);
    105 leaving = true;
    106 hero.moving = false;
    107 hero.previous = hero.box.position(); // 止める:フェードの間は更新されない / freeze: no updates during the fade
    108 return;
    109 }
    110 if (!onWarp) warpArmed = true; // 扉から離れた:次に触れた扉は効く / off every door: the next one works
    111 }
    112  
34 void MapScene::update(float dt) { 113 void MapScene::update(float dt) {
35 time += dt; 114 time += dt;
    115 if (leaving) return;
36 Input &in = g.input; 116 Input &in = g.input;
37 if (in.pressed(GLFW_KEY_ESCAPE)) { 117 if (in.pressed(GLFW_KEY_ESCAPE)) {
38 scenes().pop(); // 最後のシーン:mainが終わる / the last scene: main quits 118 scenes().pop(); // 最後のシーン:mainが終わる / the last scene: main quits
39 return; 119 return;
40 } 120 }
41 if (in.pressed(GLFW_KEY_B)) showBoxes = !showBoxes; 121 DebugView &dbg = g.debug;
42 if (in.pressed(GLFW_KEY_Z)) zoomOut = !zoomOut; 122 if (in.pressed(GLFW_KEY_B)) dbg.boxes = !dbg.boxes;
43 if (in.pressed(GLFW_KEY_H)) showHud = !showHud; 123 if (in.pressed(GLFW_KEY_Z)) dbg.zoomOut = !dbg.zoomOut;
    124 if (in.pressed(GLFW_KEY_H)) dbg.hud = !dbg.hud;
44 for (int i = 0; i < 3; ++i) 125 for (int i = 0; i < 3; ++i)
45 if (in.pressed(GLFW_KEY_1 + i)) layerOn[static_cast<size_t>(i)] = !layerOn[static_cast<size_t>(i)]; 126 if (in.pressed(GLFW_KEY_1 + i)) dbg.layers[static_cast<size_t>(i)] = !dbg.layers[static_cast<size_t>(i)];
46 if (in.pressed(GLFW_KEY_R)) { 127 if (in.pressed(GLFW_KEY_R) && g.world.reload(mapName)) {
47 // ファイルから読み直す(テキストエディターで直してすぐ確かめる)。失敗したら今のマップのまま 128 // ファイルから読み直す。物のポインターが変わるので作り直し、主人公は今の場所に戻す
48 // Reload from the file (edit in a text editor, check at once). On failure the current map stays 129 // Reload from the file. Object pointers change, so rebuild them; the hero goes back to where it was
49 if (std::optional<Tilemap> fresh = Tilemap::load(map.path())) { 130 Rect keep = hero.box;
50 map = std::move(*fresh); 131 Facing facing = hero.facing;
51 g.tiles.build(map); 132 setUp();
52 printf("%s: 読み直した / reloaded\n", map.path().c_str()); 133 hero.box = keep;
53 } 134 hero.previous = keep.position();
    135 hero.facing = facing;
    136 printf("%s: 読み直した / reloaded\n", map->path().c_str());
54 } 137 }
55   138  
56 // 主人公:自由に動く(マス目に縛られない)。斜めは正規化して同じ速さ / the hero moves freely (not locked to the 139 // 主人公:自由に動く(マス目に縛られない)。斜めは正規化して同じ速さ / the hero moves freely (not locked to the
@@ -61,14 +144,22 @@ void MapScene::update(float dt) {
61 if (hero.moving) { 144 if (hero.moving) {
62 hero.facing = facingFor(move, hero.facing); 145 hero.facing = facingFor(move, hero.facing);
63 float speed = in.actionHeld("run") ? kRunSpeed : kWalkSpeed; 146 float speed = in.actionHeld("run") ? kRunSpeed : kWalkSpeed;
64 moveOnMap(hero.box, normalize(move) * (speed * dt), map, {}, scratch); 147 moveOnMap(hero.box, normalize(move) * (speed * dt), *map, blockers, scratch);
65 } 148 }
66 hero.anim.speed = in.actionHeld("run") ? 1.5f : 1.0f; 149 hero.anim.speed = in.actionHeld("run") ? 1.5f : 1.0f;
67 hero.animate(g.characters, dt); 150 hero.animate(g.characters, dt);
    151 if (in.actionPressed("confirm")) interact();
    152 checkWarps();
    153  
    154 for (Popup &p : popups) {
    155 p.position.y -= 12.0f * dt;
    156 p.life -= dt;
    157 }
    158 std::erase_if(popups, [](const Popup &p) { return p.life <= 0.0f; });
68 } 159 }
69   160  
70 Camera2D MapScene::followCamera(Vec2 target) const { 161 Camera2D MapScene::followCamera(Vec2 target) const {
71 Vec2 size = map.pixelSize(), half = 0.5f * kView; 162 Vec2 size = map->pixelSize(), half = 0.5f * kView;
72 Vec2 c; 163 Vec2 c;
73 c.x = size.x <= kView.x ? 0.5f * size.x : std::clamp(target.x, half.x, size.x - half.x); 164 c.x = size.x <= kView.x ? 0.5f * size.x : std::clamp(target.x, half.x, size.x - half.x);
74 c.y = size.y <= kView.y ? 0.5f * size.y : std::clamp(target.y, half.y, size.y - half.y); 165 c.y = size.y <= kView.y ? 0.5f * size.y : std::clamp(target.y, half.y, size.y - half.y);
@@ -78,41 +169,41 @@ Camera2D MapScene::followCamera(Vec2 target) const {
78 } 169 }
79   170  
80 void MapScene::draw(float alpha) { 171 void MapScene::draw(float alpha) {
81 // 足元の少し上(体の真ん中)を追う / follow a point a little above the feet (the middle of the body)    
82 Vec2 feet = hero.feet(alpha); 172 Vec2 feet = hero.feet(alpha);
83 Camera2D camera = followCamera({feet.x, feet.y - 6.0f}); 173 Camera2D camera = followCamera({feet.x, feet.y - 6.0f});
84 Rect visible = camera.visibleRect(); 174 Rect visible = camera.visibleRect();
85 // Z:引いて見る。カリングは本物のカメラのままなので、見えない行が描かれていないのが分かる    
86 // Z: zoom out. Culling still uses the real camera, so you can see that rows outside it are not drawn    
87 Camera2D view = camera; 175 Camera2D view = camera;
88 if (zoomOut) { 176 if (g.debug.zoomOut) view.zoom = 0.5f;
89 view.zoom = 0.5f;    
90 view.centre = {std::round(camera.centre.x), std::round(camera.centre.y)};    
91 }    
92 Mat4 vp = view.matrix(); 177 Mat4 vp = view.matrix();
93 SpriteBatch &b = g.batch; 178 SpriteBatch &b = g.batch;
94 g.tiles.resetStats(); 179 g.tiles.resetStats();
95 spriteCalls = 0; 180 spriteCalls = 0;
96 rowFirst = std::clamp(static_cast<int>(std::floor(visible.top() / kTile)), 0, map.height()); 181 rowFirst = std::clamp(static_cast<int>(std::floor(visible.top() / kTile)), 0, map->height());
97 rowLast = std::clamp(static_cast<int>(std::ceil(visible.bottom() / kTile)), 0, map.height()) - 1; 182 rowLast = std::clamp(static_cast<int>(std::ceil(visible.bottom() / kTile)), 0, map->height()) - 1;
    183 const SpriteSheet &tileSheet = map->tileset().sheet();
98   184  
99 auto drawCharacters = [&] { 185 auto drawCharacters = [&] {
    186 // 人物と、背の低い物(宝箱)を足元のyの順に / characters and low objects (chests) sorted by the y of their feet
100 b.begin(vp, SpriteSort::Layer); 187 b.begin(vp, SpriteSort::Layer);
    188 for (const Chest &c : chests) {
    189 Sprite s = tileSheet.sprite(tileSheet.find(g.world.flag(c.flag) ? "chest_open" : "chest_closed"),
    190 c.object->rect.position());
    191 s.layer = c.box.bottom();
    192 b.draw(s);
    193 }
101 b.draw(hero.sprite(g.characters, alpha)); 194 b.draw(hero.sprite(g.characters, alpha));
102 b.end(); 195 b.end();
103 spriteCalls += b.stats().drawCalls; 196 spriteCalls += b.stats().drawCalls;
104 }; 197 };
105   198  
106 // 層はファイルの順に描く。「above」の層(木の上・屋根の棟)は人物の後 / layers are drawn in file order; "above"    
107 // layers (tree tops, roof ridges) come after the characters    
108 bool charactersDrawn = false; 199 bool charactersDrawn = false;
109 const std::vector<TileLayer> &layers = map.layers(); 200 const std::vector<TileLayer> &layers = map->layers();
110 for (int i = 0; i < static_cast<int>(layers.size()); ++i) { 201 for (int i = 0; i < static_cast<int>(layers.size()); ++i) {
111 if (layers[static_cast<size_t>(i)].above && !charactersDrawn) { 202 if (layers[static_cast<size_t>(i)].above && !charactersDrawn) {
112 drawCharacters(); 203 drawCharacters();
113 charactersDrawn = true; 204 charactersDrawn = true;
114 } 205 }
115 if (i < static_cast<int>(layerOn.size()) && !layerOn[static_cast<size_t>(i)]) continue; 206 if (i < static_cast<int>(g.debug.layers.size()) && !g.debug.layers[static_cast<size_t>(i)]) continue;
116 g.tiles.drawLayer(i, vp, visible); 207 g.tiles.drawLayer(i, vp, visible);
117 if (g.tiles.hasAnimated(i)) { 208 if (g.tiles.hasAnimated(i)) {
118 b.begin(vp); 209 b.begin(vp);
@@ -123,44 +214,66 @@ void MapScene::draw(float alpha) {
123 } 214 }
124 if (!charactersDrawn) drawCharacters(); 215 if (!charactersDrawn) drawCharacters();
125   216  
126 if (showBoxes || zoomOut) { 217 // 世界の上の物:浮かぶ文字、デバッグの箱 / things over the world: floating text, debug boxes
127 b.begin(vp); 218 b.begin(vp);
128 if (showBoxes) { 219 for (const Popup &p : popups)
129 // 固いマス(赤)と主人公の足元の箱(緑) / solid cells (red) and the hero's foot box (green) 220 g.pixel.draw(b, p.text, p.position,
130 scratch.clear(); 221 {.color = {1.0f, 0.9f, 0.45f, std::min(1.0f, p.life * 3.0f)}, .align = TextAlign::Centre,
131 map.solidRects(visible, scratch); 222 .shadow = hexColor(0x1b1726ff)});
132 for (const Rect &r : scratch) b.drawRectOutline(r, hexColor(0xff5050c0)); 223 if (g.debug.boxes) {
133 Vec2 p = lerp(hero.previous, hero.box.position(), alpha); 224 scratch.clear();
134 b.drawRectOutline({p.x, p.y, hero.box.w, hero.box.h}, hexColor(0x50ff60ff)); 225 map->solidRects(visible, scratch);
135 } 226 for (const Rect &r : scratch) b.drawRectOutline(r, hexColor(0xff5050c0));
136 if (zoomOut) b.drawRectOutline(visible, hexColor(0xffe040ff), 2.0f); // 本物のカメラ / the real camera 227 for (const Rect &r : blockers) b.drawRectOutline(r, hexColor(0xff9040ff));
137 b.end(); 228 for (const MapObject &o : map->objects())
138 spriteCalls += b.stats().drawCalls; 229 if (o.kind == "door" || o.kind == "warp") b.drawRectOutline(o.rect, hexColor(0x40c0ffff)); // 扉 / doors
    230 Vec2 p = lerp(hero.previous, hero.box.position(), alpha);
    231 b.drawRectOutline({p.x, p.y, hero.box.w, hero.box.h}, hexColor(0x50ff60ff));
    232 b.drawRectOutline(facingProbe(), hexColor(0xffff60c0));
    233 }
    234 if (g.debug.zoomOut) b.drawRectOutline(visible, hexColor(0xffe040ff), 2.0f);
    235 b.end();
    236  
    237 // キャンバスの画面に固定の物:マップの名前、お金 / things fixed to the canvas screen: the map's name, the money
    238 Camera2D canvas = Camera2D::screen(kView);
    239 b.begin(canvas.matrix());
    240 float banner = std::clamp((kBannerTime - time) / 0.5f, 0.0f, 1.0f);
    241 if (banner > 0.0f) {
    242 Vec2 size = g.pixel.measure(map->title());
    243 Rect box = Rect::fromCentre({160.0f, 30.0f}, {size.x + 16.0f, size.y + 6.0f});
    244 b.drawRect(box, {0.106f, 0.09f, 0.15f, 0.85f * banner});
    245 b.drawRectOutline(box, {0.95f, 0.76f, 0.31f, banner});
    246 g.pixel.draw(b, map->title(), {160.0f, box.y + 3.0f}, {.color = {1.0f, 0.96f, 0.84f, banner}, .align = TextAlign::Centre});
139 } 247 }
    248 char gold[32];
    249 snprintf(gold, sizeof gold, "%d G", g.world.gold);
    250 g.pixel.draw(b, gold, {314.0f, 160.0f}, {.color = hexColor(0xf2c14eff), .align = TextAlign::Right, .shadow = hexColor(0x1b1726ff)});
    251 b.end();
140 } 252 }
141   253  
142 void MapScene::drawUi(float /*alpha*/) { 254 void MapScene::drawUi(float /*alpha*/) {
143 if (!showHud) return; 255 if (!g.debug.hud) return;
144 SpriteBatch &b = g.batch; 256 SpriteBatch &b = g.batch;
145 const TileRenderer::Stats &ts = g.tiles.stats(); 257 const TileRenderer::Stats &ts = g.tiles.stats();
146 char line[256]; 258 char line[256];
147 int col = static_cast<int>(std::floor(hero.box.centre().x / kTile)), row = static_cast<int>(std::floor(hero.box.centre().y / kTile)); 259 int col = static_cast<int>(std::floor(hero.box.centre().x / kTile)), row = static_cast<int>(std::floor(hero.box.centre().y / kTile));
148 snprintf(line, sizeof line, "%s %d×%d tile (%d, %d) rows %d-%d tile quads %d / %d draw calls: tiles %d + sprites %d", 260 snprintf(line, sizeof line, "%s %d×%d tile (%d, %d) rows %d-%d tile quads %d / %d draws: tiles %d + sprites %d maps %d",
149 map.name().c_str(), map.width(), map.height(), col, row, rowFirst, rowLast, ts.quads, ts.totalQuads, 261 map->name().c_str(), map->width(), map->height(), col, row, rowFirst, rowLast, ts.quads, ts.totalQuads,
150 ts.drawCalls, spriteCalls); 262 ts.drawCalls, spriteCalls, g.world.loadedMaps());
151 b.begin(g.screen.matrix()); 263 b.begin(g.screen.matrix());
152 TextStyle hud = {.color = hexColor(0xfff4d6ff), .shadow = hexColor(0x000000ff)}; 264 TextStyle hud = {.color = hexColor(0xfff4d6ff), .shadow = hexColor(0x000000ff)};
153 b.drawRect({0.0f, 0.0f, 1280.0f, 30.0f}, hexColor(0x1b1726c0)); 265 b.drawRect({0.0f, 0.0f, 1280.0f, 30.0f}, hexColor(0x1b1726c0));
154 g.ui.draw(b, line, {12.0f, 6.0f}, hud); 266 g.ui.draw(b, line, {12.0f, 6.0f}, hud);
155 char layers[64]; 267 char layers[64];
156 snprintf(layers, sizeof layers, "layers %s %s %s", layerOn[0] ? "1" : "-", layerOn[1] ? "2" : "-", layerOn[2] ? "3" : "-"); 268 snprintf(layers, sizeof layers, "layers %s %s %s", g.debug.layers[0] ? "1" : "-", g.debug.layers[1] ? "2" : "-",
    269 g.debug.layers[2] ? "3" : "-");
157 hud.align = TextAlign::Right; 270 hud.align = TextAlign::Right;
158 hud.color = hexColor(0xf2c14eff); 271 hud.color = hexColor(0xf2c14eff);
159 g.ui.draw(b, layers, {1268.0f, 6.0f}, hud); 272 g.ui.draw(b, layers, {1268.0f, 6.0f}, hud);
160 b.drawRect({0.0f, 690.0f, 1280.0f, 30.0f}, hexColor(0x1b1726c0)); 273 b.drawRect({0.0f, 690.0f, 1280.0f, 30.0f}, hexColor(0x1b1726c0));
161 hud.align = TextAlign::Centre; 274 hud.align = TextAlign::Centre;
162 hud.color = hexColor(0xc8cce0ff); 275 hud.color = hexColor(0xc8cce0ff);
163 g.ui.draw(b, "arrows / WASD: move Shift: run 1 2 3: layers B: boxes Z: zoom out H: HUD R: reload the map Esc: 終了 / quit", 276 g.ui.draw(b, "arrows / WASD: move Shift: run Space: 調べる / check 1 2 3: layers B: boxes Z: zoom out H: HUD R: reload Esc: 終了 / quit",
164 {640.0f, 696.0f}, hud); 277 {640.0f, 696.0f}, hud);
165 b.end(); 278 b.end();
166 } 279 }

ファイル: a/games/rpg/src/tilemap.cc | b/games/rpg/src/tilemap.cc

前新
@@ -126,7 +126,7 @@ int MapObject::getInt(std::string_view key, int fallback) const {
126   126  
127 // ---------------------------------------------------------------------------------------------------- Tilemap 127 // ---------------------------------------------------------------------------------------------------- Tilemap
128   128  
129 std::optional<Tilemap> Tilemap::load(const std::string &path) { 129 std::optional<Tilemap> Tilemap::load(const std::string &path, TilesetCache *cache) {
130 std::optional<std::string> text = readTextFile(path); 130 std::optional<std::string> text = readTextFile(path);
131 if (!text) { 131 if (!text) {
132 fprintf(stderr, "%s: 読めない / cannot read (プロジェクトのルートから実行した? / running from the project root?)\n", 132 fprintf(stderr, "%s: 読めない / cannot read (プロジェクトのルートから実行した? / running from the project root?)\n",
@@ -150,6 +150,8 @@ std::optional<Tilemap> Tilemap::load(const std::string &path) {
150 if (!(in >> command) || command[0] == '#') continue; 150 if (!(in >> command) || command[0] == '#') continue;
151 if (command == "map") { 151 if (command == "map") {
152 in >> map.mapName; 152 in >> map.mapName;
    153 } else if (command == "title") {
    154 std::getline(in >> std::ws, map.mapTitle);
153 } else if ((command == "tileset" || command == "size") && !map.tileLayers.empty()) { 155 } else if ((command == "tileset" || command == "size") && !map.tileLayers.empty()) {
154 // 読んだ層は今の大きさとタイルセットの番号で出来ている:後から変えると層が合わなくなる 156 // 読んだ層は今の大きさとタイルセットの番号で出来ている:後から変えると層が合わなくなる
155 // The layers already read use the current size and the tileset's kind numbers: changing them later would not 157 // The layers already read use the current size and the tileset's kind numbers: changing them later would not
@@ -158,9 +160,15 @@ std::optional<Tilemap> Tilemap::load(const std::string &path) {
158 } else if (command == "tileset") { 160 } else if (command == "tileset") {
159 std::string file; 161 std::string file;
160 in >> file; 162 in >> file;
161 std::optional<Tileset> set = Tileset::load(folderOf(path) + file); 163 std::string tilesetPath = folderOf(path) + file;
    164 if (cache && cache->contains(tilesetPath)) {
    165 map.tiles = cache->at(tilesetPath);
    166 continue;
    167 }
    168 std::optional<Tileset> set = Tileset::load(tilesetPath);
162 if (!set) return fail("タイルセットを読めない / cannot load the tileset " + file); 169 if (!set) return fail("タイルセットを読めない / cannot load the tileset " + file);
163 map.tiles = std::make_shared<const Tileset>(std::move(*set)); 170 map.tiles = std::make_shared<const Tileset>(std::move(*set));
    171 if (cache) (*cache)[tilesetPath] = map.tiles;
164 } else if (command == "size") { 172 } else if (command == "size") {
165 if (!(in >> map.cols >> map.rows) || map.cols <= 0 || map.rows <= 0 || map.cols > 1024 || map.rows > 1024) 173 if (!(in >> map.cols >> map.rows) || map.cols <= 0 || map.rows <= 0 || map.cols > 1024 || map.rows > 1024)
166 return fail("size <幅> <高さ>(1〜1024) / size <width> <height> (1..1024)"); 174 return fail("size <幅> <高さ>(1〜1024) / size <width> <height> (1..1024)");

ファイル: a/games/rpg/src/tilemap.hh | b/games/rpg/src/tilemap.hh

前新
@@ -14,6 +14,7 @@
14 #include <optional> 14 #include <optional>
15 #include <string> 15 #include <string>
16 #include <string_view> 16 #include <string_view>
    17 #include <unordered_map>
17 #include <vector> 18 #include <vector>
18   19  
19 constexpr int kTileSize = 16; 20 constexpr int kTileSize = 16;
@@ -52,6 +53,10 @@ private:
52 std::array<int, 128> bySymbol{}; // ASCIIの文字 → kindsの番号(-1 = なし) / ASCII character → kinds index (-1 = none) 53 std::array<int, 128> bySymbol{}; // ASCIIの文字 → kindsの番号(-1 = なし) / ASCII character → kinds index (-1 = none)
53 }; 54 };
54   55  
    56 // 読んだタイルセットを覚えておく表(パス → タイルセット):同じタイルセットのマップは画像を共有する
    57 // A table of loaded tilesets (path → tileset): maps with the same tileset share its image
    58 using TilesetCache = std::unordered_map<std::string, std::shared_ptr<const Tileset>>;
    59  
55 // マップの物(扉・出発点・宝箱・人…)。位置と大きさはピクセル、性質は key=value の文字列 60 // マップの物(扉・出発点・宝箱・人…)。位置と大きさはピクセル、性質は key=value の文字列
56 // An object on a map (door, spawn point, chest, person...). Position and size in pixels, properties as key=value 61 // An object on a map (door, spawn point, chest, person...). Position and size in pixels, properties as key=value
57 struct MapObject { 62 struct MapObject {
@@ -77,16 +82,20 @@ class Tilemap {
77 public: 82 public:
78 // 書式 / format (see games/rpg/assets/maps/*.map): 83 // 書式 / format (see games/rpg/assets/maps/*.map):
79 // map <name> 名前 / the name 84 // map <name> 名前 / the name
    85 // title <text…> 画面に出す名前(行の残り全部) / the name shown on screen (the rest of the line)
80 // tileset <file.tileset> .mapからの相対パス / relative to the .map 86 // tileset <file.tileset> .mapからの相対パス / relative to the .map
81 // size <width> <height> マスの数 / in tiles 87 // size <width> <height> マスの数 / in tiles
82 // layer <name> [above] 続くheight行が格子(1文字 = 1マス、'.' = 空) / the next `height` lines are the grid 88 // layer <name> [above] 続くheight行が格子(1文字 = 1マス、'.' = 空) / the next `height` lines are the grid
83 // (1 character = 1 tile, '.' = empty) 89 // (1 character = 1 tile, '.' = empty)
84 // object <kind> <name> <col> <row> [key=value …] w= h= でマスの大きさ(既定1×1) / w= h= set the size in tiles 90 // object <kind> <name> <col> <row> [key=value …] w= h= でマスの大きさ(既定1×1) / w= h= set the size in tiles
85 // (default 1 × 1) 91 // (default 1 × 1)
86 // エラーは「ファイル:行: 説明」でstderrに出してnullopt / errors go to stderr as "file:line: message", then nullopt 92 // エラーは「ファイル:行: 説明」でstderrに出してnullopt / errors go to stderr as "file:line: message", then nullopt.
87 static std::optional<Tilemap> load(const std::string &path); 93 // cacheがあれば、タイルセットはそこから取る(なければ読んで入れる) / with a cache, the tileset comes from it (loaded
    94 // and added if missing)
    95 static std::optional<Tilemap> load(const std::string &path, TilesetCache *cache = nullptr);
88   96  
89 const std::string &name() const { return mapName; } 97 const std::string &name() const { return mapName; }
    98 const std::string &title() const { return mapTitle.empty() ? mapName : mapTitle; }
90 const std::string &path() const { return filePath; } 99 const std::string &path() const { return filePath; }
91 const Tileset &tileset() const { return *tiles; } 100 const Tileset &tileset() const { return *tiles; }
92 int width() const { return cols; } 101 int width() const { return cols; }
@@ -105,7 +114,7 @@ public:
105   114  
106 private: 115 private:
107 Tilemap() = default; 116 Tilemap() = default;
108 std::string mapName, filePath; 117 std::string mapName, mapTitle, filePath;
109 std::shared_ptr<const Tileset> tiles; // 同じタイルセットを何枚ものマップで共有できる / several maps can share one 118 std::shared_ptr<const Tileset> tiles; // 同じタイルセットを何枚ものマップで共有できる / several maps can share one
110 int cols = 0, rows = 0; 119 int cols = 0, rows = 0;
111 std::vector<TileLayer> tileLayers; 120 std::vector<TileLayer> tileLayers;

ファイル: /dev/null | b/games/rpg/src/world.cc

前新
@@ -0,0 +1,38 @@
    1 #include "world.hh"
    2  
    3 #include <cstdio>
    4 #include <utility>
    5 #include <vector>
    6  
    7 Tilemap *World::map(const std::string &name) {
    8 if (auto it = maps.find(name); it != maps.end()) return it->second.get();
    9 std::optional<Tilemap> loaded = Tilemap::load(pathOf(name), &tilesets);
    10 if (!loaded) return nullptr;
    11 printf("%s: 読んだ / loaded (%d×%d)\n", pathOf(name).c_str(), loaded->width(), loaded->height());
    12 return (maps[name] = std::make_unique<Tilemap>(std::move(*loaded))).get();
    13 }
    14  
    15 bool World::reload(const std::string &name) {
    16 if (!maps.contains(name)) return map(name) != nullptr;
    17 // タイルセットも読み直す。マップの格子はタイルセットの番号なので、読んである全部のマップを新しい表で読み直す
    18 // (古いタイルセットを持ったままのマップが残らない)。全部読めたときだけ入れ替え、一つでも失敗したら何も変えない
    19 // The tileset is read again too. Map grids hold the tileset's kind numbers, so every loaded map is read again with
    20 // the new table (no map keeps the old tileset). They are swapped in only if all of them load; one failure changes
    21 // nothing
    22 std::vector<std::string> names = {name}; // 今のマップから:エラーはまずそこに出る / the current map first: its
    23 // errors come first
    24 for (const auto &entry : maps)
    25 if (entry.first != name) names.push_back(entry.first);
    26 TilesetCache freshTilesets;
    27 std::vector<std::pair<Tilemap *, Tilemap>> fresh;
    28 for (const std::string &n : names) {
    29 std::optional<Tilemap> loaded = Tilemap::load(pathOf(n), &freshTilesets);
    30 if (!loaded) return false;
    31 fresh.emplace_back(maps[n].get(), std::move(*loaded));
    32 }
    33 // 同じ場所に入れる:シーンのポインターはそのまま / same addresses: scenes' pointers stay valid
    34 for (auto &[target, loaded] : fresh) *target = std::move(loaded);
    35 tilesets = std::move(freshTilesets); // 古いタイルセット(とテクスチャー)はここで消える / the old tileset (and its
    36 // texture) is freed here
    37 return true;
    38 }

ファイル: /dev/null | b/games/rpg/src/world.hh

前新
@@ -0,0 +1,43 @@
    1 // 世界の状態(第34章):読んだマップの置き場と、マップを出ても残るもの(開けた宝箱・お金)
    2 // The world state (chapter 34): where loaded maps are kept, and what survives leaving a map (opened chests, money)
    3 //
    4 // シーンはマップに入るたびに作り直される(scenes().replace)。だから「残すもの」はシーンではなくここに置く:
    5 // 残す:開けた宝箱などの印(flags)、お金 → 戻ってきても宝箱は開いたまま
    6 // 残さない:シーンの中の物(主人公の位置、浮かぶ文字…)→ 入るたびにマップのファイルの通りから始まる
    7 // A scene is created anew every time you enter a map (scenes().replace). So what must persist lives here, not in the
    8 // scene:
    9 // kept: flags such as opened chests, the money → a chest is still open when you come back
    10 // not kept: everything inside the scene (the hero's position, floating text...) → each visit starts as the map
    11 // file says
    12 #pragma once
    13  
    14 #include "tilemap.hh"
    15  
    16 #include <memory>
    17 #include <string>
    18 #include <unordered_map>
    19 #include <unordered_set>
    20  
    21 class World {
    22 public:
    23 // マップを名前で:初めてなら games/rpg/assets/maps/<名前>.map を読む。読めなければnullptr。
    24 // ポインターは変わらない(読み直しても同じ場所) / a map by name: loaded from games/rpg/assets/maps/<name>.map on
    25 // first use; nullptr if it cannot be loaded. The pointer stays valid (also across reloads)
    26 Tilemap *map(const std::string &name);
    27 // ファイルから読み直す(タイルセットと、読んであるほかのマップも)。失敗したら全部前のまま / reloads from the file
    28 // (the tileset and the other loaded maps too); on failure everything stays as it was
    29 bool reload(const std::string &name);
    30 int loadedMaps() const { return static_cast<int>(maps.size()); }
    31  
    32 bool flag(const std::string &name) const { return flags.contains(name); }
    33 void setFlag(const std::string &name) { flags.insert(name); }
    34  
    35 int gold = 0;
    36  
    37 static std::string pathOf(const std::string &name) { return "games/rpg/assets/maps/" + name + ".map"; }
    38  
    39 private:
    40 std::unordered_map<std::string, std::unique_ptr<Tilemap>> maps;
    41 TilesetCache tilesets;
    42 std::unordered_set<std::string> flags;
    43 };


コメント(0)

まだコメントはありません。