Files
isaac-port/notes/systems/rooms_load.md
T

21 KiB
Raw Blame History

isaac-ng.exe (Rep+ 1.9.7.17) — RoomConfig stage table, .stb loading, mod room merging

Covers: RoomConfig construction, stages.xml parsing, when stages are loaded, mod room merging, variant-range bookkeeping, and the only XML room parser (--load-room). The per-room binary reader (ReadRoom 0x82aea0) is in CONTEXT_rooms.md and is not repeated here. Labels for everything below are in labels.json.

Conventions: Game* g = *(Game**)0xc71678; ModManager* mm = *(char**)0xc7169c + 0x2a6c0. difficulty = g+0x269c8 (0 normal, 1 hard, 2 greed, 3 greedier). ResolveContentPath 0x8f5ad0 = mm->ResolveContentPath(out, relPath). It checks each enabled mod's resources-dlc3/<rel>, then resources/<rel>, falls back to the vanilla rel path, and caches by path hash.

1. Layout

struct Game { ... RoomConfig roomConfig @ +0x18910 (size 0x1e28, ends at +0x1a738) ... }

struct RoomConfig {                              // ctor inlined in Game::ctor 0x6f1020 @0x6f1184..
  RoomConfigStage stages[37];  // +0x0000, stride 0xc4  (eh-vector ctor 0x828f00 / dtor 0x8295e0, count 0x25)
  /* +0x1c54 */ void* curses_begin, *curses_end, *curses_cap;   // std::vector (curses.xml, 0x82bf00) – not analysed
  /* +0x1c60 */ struct { int id; std::string name; } curseTable[16]; // 0x1c each, ctor 0x829650 – likely curses, unverified
  /* +0x1e20 */ std::list<RoomConfigRoom> generatedRooms;  // node 0x64 = next,prev + 0x5c Room; size @+0x1e24
                                                           // cleared by 0x82d320 "delete %d generated rooms." from Level::Init
};

struct RoomConfigStage {            // 0xc4, ctor 0x828f00
  /* +0x00 */ int         id;          // NOT initialised by the ctor; only set when stages.xml has the <stage>
  /* +0x04 */ std::string name;        // "name" attribute ("#BASEMENT_NAME"; '#' => localised, see 0x829500)
  /* +0x1c */ std::string playerSpot;  // bossgfxroot + "playerspot"
  /* +0x34 */ std::string bossSpot;    // bossgfxroot + "bossspot"
  /* +0x4c */ std::string suffix;      // "suffix"
  /* +0x64 */ RoomConfigMode modes[2]; // [0] normal/hard, [1] greed/greedier  (eh-vector ctor 0x828b60, dtor 0x829260)
  /* +0xbc */ int music;               // atoi("music")
  /* +0xc0 */ int backdrop;            // atoi("backdrop")
};

struct RoomConfigMode {             // 0x2c, ctor 0x828b60, Clear 0x828c00
  /* +0x00 */ std::string file;        // root/greedroot + "path" (still ".xml"; turned into ".stb" at load time)
  /* +0x18 */ RoomConfigRoom* rooms;   // new[] with count cookie at rooms[-1] (4 bytes), stride 0x5c
  /* +0x1c */ uint32_t count;
  /* +0x20 */ std::map<int /*room type*/, VariantRanges*> variantsByType; // MSVC map: head @+0x20, size @+0x24
  /* +0x28 */ bool loaded;
};

struct VariantRanges { Interval* head; };          // malloc'd 4 bytes (0x828e50)
struct Interval { uint32_t lo, hi; Interval* next; }; // 0xc bytes (tracked malloc 0x10 incl. size header);
                                                      // sorted ascending, disjoint, inclusive [lo,hi]

Room field corrections to CONTEXT_rooms.md, confirmed by the Lua binding table at 0x86bee8..0x86bfe9: +0x30 = InitialWeight and +0x34 = Weight (the current, mutable weight). CONTEXT_rooms.md had these two swapped. ReadRoom writes the same value to both. Every reset copies +0x30 into +0x34 (0x82aa27, 0x745195, 0x7516f7). Other Lua names: +0 StageID, +4 Mode, +8 Type, +0xc Variant, +0x58 OriginalVariant, +0x10 Subtype, +0x14 Name, +0x2c Difficulty, +0x44 SpawnCount, +0x46 Width, +0x47 Height, +0x48 Shape. Doors and Spawns are getters. +0x50 and +0x54 are still unknown: they are zeroed in the ctor 0x828b20, are not written by load or merge, have no Lua binding, and are not set by the XML parser.

2. stages.xml → stage table

Who calls it

  • Game::LoadConfigXmls 0x6f4740 runs once per Game object. It is called from app init 0x952410 (right after new Game 0x6f1020 at 0x952837) and from 0x959720 (also right after new Game). It does roomConfig.LoadStagesXml(ResolveContentPath("stages.xml")) at 0x6f4829, then curses.xml, and so on.
  • 0x6f3c00 (called at 0x9b24d8 from 0x9b23a0, the "Lua is resetting!" path, i.e. a mod enable/disable reload) re-parses stages.xml at 0x6f3ca0. After that, ModManager::LoadModCurses 0x8f86c0 runs at 0x9b2508.
  • The game resolves stages.xml through ResolveContentPath, so one mod can replace the whole stages.xml (<mod>/resources[-dlc3]/stages.xml). The game does not merge stages.xml files from several mods.

RoomConfig::LoadStagesXml 0x82b2f0 (thiscall, ret 4)

bool RoomConfig::LoadStagesXml(const char* path) {
  File* f = FileSystem::Open(0xc37a10, path, 0);  if (!f) return false;
  size_t n = f->Size();  char* buf = new_tracked(n+1);  f->Read(buf,1,n); buf[n]=0; f->Close(1);
  rapidxml::xml_document doc; doc.parse(buf);
  xml_node* root = doc.first_node("stages");
  std::string roomsRoot   = attr(root,"root")      ?: "rooms/";        // 0x82b3d9 / default 0x82b3f6
  std::string greedRoot   = attr(root,"greedroot") ?: "rooms/greed/";  // 0x82b43c / default 0x82b459
  std::string bossGfxRoot = attr(root,"bossgfxroot")->value();         // 0x82b49c: NO null check (crashes if missing)
  int id;                                    // [ebp-0x10188]; NOT reset per <stage>, so a missing id reuses the previous one
  for (xml_node* n = root->first_node("stage"); n; n = n->next_sibling /*[+0x2c], any sibling, no name filter*/) {
    RoomConfigStage tmp;                     // strings + modes re-constructed per node (0x82b503..0x82b5c9)
    tmp.music = 0; tmp.backdrop = 0;
    for (attr a : n->attributes) {            // strcmp chain, unknown attributes ignored
      if      (a=="id")         id = atoi(v);
      else if (a=="name")       tmp.name = v;
      else if (a=="path")     { tmp.modes[0].file = roomsRoot + v;     // 0x82b727
                                tmp.modes[1].file = greedRoot + v; }   // 0x82b79c  (ALWAYS both)
      else if (a=="playerspot") tmp.playerSpot = bossGfxRoot + v;
      else if (a=="bossspot")   tmp.bossSpot   = bossGfxRoot + v;
      else if (a=="music")      tmp.music      = atoi(v);
      else if (a=="backdrop")   tmp.backdrop   = atoi(v);
      else if (a=="suffix")     tmp.suffix     = v;
    }
    tmp.id = id;
    this->stages[id] = tmp;                  // 0x82bd60 operator=, NO bounds check on id (array has 37 entries)
  }
  return true;
}

RoomConfigStage::operator= 0x82bd60 copies everything. That includes modes[i].rooms, count, loaded and a deep copy of the variant map (0x82e720). The temporary has rooms=null, count=0, loaded=false, so re-parsing stages.xml "unloads" every stage that appears in the XML. The old room arrays are not freed and leak. Lazy loading then reloads them on next use. Stages missing from the XML keep their earlier state. On a fresh Game their file is empty and LoadStageBinary returns false at once (0x82aac2).

So a stage's file names are modes[0].file = "rooms/" + path and modes[1].file = "rooms/greed/" + path, for example "rooms/01.Basement.xml" and "rooms/greed/01.Basement.xml". The loader later turns these into ".stb".

Vanilla stage ids (taken from a mod's copy of vanilla stages.xml in mods/stageapi15_*/resources/stages.xml; the packed vanilla file was not extracted): 0 Special Rooms, 1-17 the normal chapters, 24 The Shop, 25 Ultra Greed, 26 The Void (path "01.Basement.xml" in that copy; a "26.The Void_ex.stb" exists in resources/rooms), 27-33 Downpour..Corpse, 35 Home, 36 Backwards. 18-23 are commented out in that copy. 34 is not present. Uncertain: whether the vanilla packed stages.xml differs.

3. LoadStageBinary 0x82aa40 (summary of what it does around the per-room reader)

bool RoomConfig::LoadStageBinary(int stageId, int mode /*-1 => difficulty>=2 ? 1 : 0*/) {
  Stage& s = stages[stageId]; Mode& m = s.modes[mode];
  if (m.file.empty()) return false;                                         // 0x82aac2
  Log("[RoomConfig] load stage %d: %s (mode %d)\n", s.id, s.GetDisplayName(), mode);
  std::string stb = m.file.substr(0, m.file.size()-3) + "stb";              // 0x82ab59..0x82ab8a
  File* f = FileSystem::Open(ResolveContentPath(stb), 0);                   // a mod's resources/ can REPLACE the vanilla .stb
  if (!f) return false;                                                     // no Clear and loaded stays false, so it retries next call
  m.Clear();                                                                // 0x828c00: frees entries, spawns, rooms[], interval lists, map; loaded=false
  if (read32(f) != 'STB1') return false;                                    // 0x82aca1 (file is not closed here: leak)
  m.count = read32(f);
  if (m.count) {
    Log("allocate %d rooms.\n", m.count);
    m.rooms = new RoomConfigRoom[m.count];                                  // ctor 0x828b20
    for (i = 0; i < m.count; i++) {
      ReadRoom(&m, i, stageId, f);                                          // 0x82aea0
      m.rooms[i].mode = mode;
      m.GetVariantRanges(m.rooms[i].type)->Insert(m.rooms[i].variant);      // return value ignored (duplicates allowed in vanilla)
      switch (stageId) {                                                    // table 0x82ae78
        case 1: case 2: case 3: if (variant==603 || variant==716) flags |= 4; break;
        case 29: case 30:       if (type==1 && subtype==31)          flags |= 2; break;
      }
    }
  }
  f->Close(1);
  mm->LoadModRooms(stageId, mode);                                          // 0x8f8040, see section 5
  m.loaded = true;  return true;
}

4. When stages get loaded (lazy, per floor, and never unloaded except by a stages.xml re-parse)

There is no load-all at startup. Every caller uses the same idiom: if (!m.loaded) LoadStageBinary(id, mode); else for each room: weight(+0x34) = initialWeight(+0x30);. That idiom is factored as RoomConfig::LoadOrResetStage 0x82a9c0 and inlined at other sites. So every level init resets all weights of the stages it uses.

Callers of LoadStageBinary:

site function stage / mode
0x745179 Level::Init 0x744940 LevelStage==12 (Void): stages 1..17 except 13, mode derived (-1 logic)
0x74523a Level::Init otherwise GetStageID(levelStage, stageType, -1) (0x82d030), mode derived
0x74532e Level::Init non-greed, StageType 4/5 (alt path), and (LevelStage==4, or LevelStage==3 with curse bit 2 = Labyrinth): stage 29 (Mines) is also loaded, mode derived. The LevelStage 1..6 && g+0x2654c&0x10000 case skips this (likely the Ascent flag, unverified).
0x7453e7 (via 0x82a9c0) Level::Init non-greed normal generation path: stage 0 (Special Rooms) with mode -1, then 0x740e10 (layout gen). Home (LS13), the 0x10000 path, g+0x26584==0x2c, and LS9 go to dedicated generators (0x74de30 / 0x742ef0 / 0x7508c0 / 0x74a500) and do NOT load stage 0 here.
0x745427 Level::Init greed/greedier: stage 0, mode 1 ("rooms/greed/00.Special Rooms.stb"), then 0x743550 (greed layout)
0x7516d8, 0x751ca6 0x751650 (reached from 0x7515c0 when Level+0x1830c != 2) stage 35 (Home), mode 0 always. Probably building dimension 2 (Death Certificate area); unverified.
0x82c76e RoomConfig::GetRoomByStageTypeAndVariant 0x82c720 lazy load of any (stageId, mode) on lookup
0x82cebe RoomConfig::GetRooms 0x82ce40 lazy load on filtered query

Mode is always derived the same way: mode==-1 ? (difficulty==2||difficulty==3) : mode.

RoomConfig::GetStageID 0x82d030 (ecx=LevelStage, edx=StageType, [esp+4]=mode/-1, cdecl):

greed = (mode==-1) ? (game && difficulty in {2,3}) : (mode==1);
if (greed) {
  if (ls==7) return 25; if (ls==6) return 24; if (ls==5) return 14;
  if (st==4) return ls*2+25;  if (st==5) return ls*2+26;
  return 3*ls - 2 + st;                    // ls1:1..3, ls2:4..6, ls3:7..9, ls4:10..12
}
if (ls==13) return 35;
if (ls < 9) { c = ls-1;
  if (st==4) return (c & ~1) + 27;         // 27,29,31,33
  if (st==5) return (c>>1)*2 + 28;         // 28,30,32,34
  return (c>>1)*3 + st + 1; }              // 1..12
if (ls==9)  return st==4 ? 36 : 13;
if (ls==12) return 26;
return (ls-3)*2 + st;                       // ls10: 14/15, ls11: 16/17

Lookups:

  • GetRoomByStageTypeAndVariant(stageId,type,variant,mode) 0x82c720 (ret 0x10) does a linear scan and returns the first room with type==t && variant(+0xc)==v. Vanilla rooms come first, then mods in merge order. If nothing matches it logs "[warn] StageID %d Room type %d, variant %d not found!" and returns null.
  • GetRooms(out vector<Room*>, stageId, type, shape(13=any), minVariant, maxVariant, minDifficulty, maxDifficulty, const uint32* requiredDoors, subtype(-1=any), mode) 0x82ce40 (ret 0x2c) filters with type== and shape==/13 and minV<=variant<=maxV (unsigned) and minD<=difficulty<=maxD (signed) and (doorMask & *req)==*req and subtype==/-1. It also drops rooms with flags&0x80 (the entity-4500 rooms) unless g+0x1bbd8 (a std::map<int,...>) contains key 79 (0x82cf69..0x82cfa4; what that map is was not determined).

5. Mod room merging — ModManager::LoadModRooms 0x8f8040 (thiscall this=mm, ret 8)

void ModManager::LoadModRooms(int stageId, int mode) {
  if (!g_Game) return;
  for (Mod* mod : this->mods /* vector<Mod*> at this+0 / +4, list order */) {
    if (!mod->enabled /* +0xfd */) continue;
    Mode& m = g->roomConfig.stages[stageId].modes[mode];
    Log("[ModManager] load stage %d: %s (mode %d)\n", stage.id, stage.GetDisplayName(), mode);
    std::string rel  = m.file.substr(0, size-3) + "stb";      // e.g. "rooms/01.Basement.stb", "rooms/greed/01.Basement.stb"
    std::string path = mod->GetContentPath(rel);               // 0x8f99c0, see below
    if (!FileSystem::ResolvePath(0xc379e0, path)) continue;    // silently skip when the mod has no such file
    File* f = FileSystem::Open(0xc37a10, path, 0);
    if (!f) { Log("[ModManager] Failed to open room config files %s!\n", path); continue; }
    if (read32(f) != 'STB1') { Log("[ModManager] bad room config header in %s!\n", path); return; }
         // NB: returns from the WHOLE function (0x8f8315 -> 0x8f864e -> exit). Later mods are not merged,
         // the file is not closed, and the caller still sets loaded=true.
    uint32 oldCount = m.count;  uint32 n = read32(f);
    if (n) {
      Log("reallocate %d rooms.\n", n);                        // logs the ADDED count, not the total
      RoomConfigRoom* nr = new RoomConfigRoom[oldCount + n];   // ctor 0x828b20, count cookie
      for (i < oldCount) memberwise copy rooms[i] -> nr[i];    // shallow: spawns ptr copied; name string deep-copied
      delete[] m.rooms;                                        // eh-vector dtor 0x6ef3e0 destroys only the name string
      m.rooms = nr;  m.count = oldCount + n;
    }
    for (i = oldCount; i < m.count; i++) {
      ReadRoom(&m, i, stageId, f);                             // 0x82aea0: sets variant(+0xc) = originalVariant(+0x58) = file value
      Room& r = m.rooms[i];
      r.mode = mode;
      VariantRanges* vr = m.GetVariantRanges(r.type);
      uint32 v = r.variant;
      if (!vr->Insert(v)) {                                    // variant already used for this type -> reassign
        Interval* first = vr->head;  Interval* nx = first->next;
        if (nx && nx->lo + 2 == first->hi) {                   // AS COMPILED (0x8f857d..0x8f8585): effectively never true
          v = nx->lo + 1;                                      //   because lists are sorted and disjoint. It looks like
          first->next = nx->next; first->hi = nx->hi; free(nx);//   the intended check was "first->hi + 2 == nx->lo" (fill a 1-wide gap).
        } else {
          first->hi++;  v = first->hi;                         // 0x8f85b4: extend the LOWEST interval by one
        }
        r.variant = v;                                         // +0x58 OriginalVariant keeps the file value
      }
    }
    // NB: the vanilla per-stage flag fixups (flags|=4 / |=2) are NOT applied to mod rooms.
    f->Close(1);
  }
}

Mod path builder Mod::GetContentPath(out, rel) 0x8f99c0. mod+0x48 is <moddir>/content/ (set at 0x8f6d6e) and mod+0x30 is <moddir>/resources/ (0x8f6cda).

  1. Try mod+0x48 minus its trailing '/', plus "-dlc3/" plus rel, i.e. <moddir>/content-dlc3/rooms/<file>.stb. If FileSystem::ResolvePath finds it, return it.
  2. Otherwise return <moddir>/content/rooms/<file>.stb without checking that it exists; the merge checks.

Only .stb files are tried. No mod .xml room file is ever read. Greed mode looks under content/rooms/greed/, because the mode file already contains the greedroot.

Consequences and semantics for a reimplementation:

  • Merge is append-only. Vanilla rooms are never replaced by mod content files. Full replacement only happens through resources/rooms/X.stb (ResolveContentPath in LoadStageBinary).
  • OriginalVariant (+0x58) is always the variant stored in the .stb. Variant (+0xc) equals it unless a mod room collided with an already-registered (type, variant), in which case it is remapped as above.
  • Collision detection uses the per-type interval set, which contains every vanilla variant (inserted unconditionally during the vanilla load) and every variant from earlier mod rooms and earlier mods.
  • Remap rule as compiled: new variant = ++head.hi, where head is the lowest interval of that type. Because the "merge with next interval" branch is dead, once the gap after the first interval is used up, the next collision produces head.hi == next.lo. That gives a duplicate variant (equal to an existing room's variant), and the intervals stay overlapping or adjacent from then on. A faithful port should keep this quirk. Example: vanilla type 1 has variants {0..5, 7..9}. Mod rooms colliding three times get 6, then 7 (duplicate of vanilla 7), then 8 (duplicate), and so on. A non-colliding mod variant is inserted normally and merges ranges.
  • GetRoomByStageTypeAndVariant returns the first match, so a duplicated variant resolves to the earlier (vanilla) room.
  • A room array reallocation moves all earlier Room objects. This is safe only because it happens inside the load, before anything holds Room pointers.

6. Variant ranges (0x828e50 / 0x829290)

VariantRanges* RoomConfigMode::GetVariantRanges(int type) {        // 0x828e50, thiscall ret 4
  auto it = variantsByType.lower_bound(type);                      // 0x416440
  if (it != end && !(type < it->key)) return it->value;
  VariantRanges* r = (VariantRanges*)tracked_malloc(4); r->head = nullptr;
  variantsByType.emplace_hint(it, type, r);                        // 0x5cca10
  return r;
}
bool VariantRanges::Insert(uint32 v) {                             // 0x829290, thiscall ret 4; unsigned compares
  if (!head) { head = new Interval{v,v,nullptr}; return true; }
  Interval* prev = nullptr;
  for (Interval* cur = head; cur; prev = cur, cur = cur->next) {
    if (v < cur->lo) {
      if (v == cur->lo - 1) {
        if (prev && prev->hi + 1 == v) { prev->hi = cur->hi; prev->next = cur->next; free(cur); } // bridge
        else cur->lo = v;
        return true;
      }
      if (prev && prev->hi + 1 == v) { prev->hi = v; return true; }
      Interval* n = new Interval{v,v,cur};  (prev ? prev->next : head) = n;  return true;
    }
    if (v <= cur->hi) return false;                                // already present
  }
  // ran past the last interval (prev = last)
  if (v == prev->hi + 1) { prev->hi = v; return true; }
  prev->next = new Interval{v,v,nullptr};  return true;
}

Queried only in LoadStageBinary (0x82ad79/0x82ad8a; result ignored) and LoadModRooms (0x8f854b/0x8f8565; used for collision handling). Mode::Clear 0x828c00 and the stage copy 0x82bd60 (deep copy via 0x82e720) also touch it. No other reader was found (not exhaustively searched; callers of 0x828e50/0x829290 are only those two).

7. XML room files

The game has exactly one XML room parser: RoomConfig::LoadRoomFromXmlFile 0x829710, which calls RoomConfigRoom::ParseXml 0x829af0. It parses a single <room> element from a file into a function-local static Room (0xc80e48). Its only caller is Game::Start 0x6f7750 @0x6f7a8f, used when the start parameter string is non-empty. That string comes from the --load-room= command-line option (string 0xb7e12c, used at 0x9aaf03), alongside --set-stage= / --set-stage-type=. The path is opened directly (FileSystem::Open, no ResolveContentPath). Attributes read: room type variant subtype name difficulty weight(->+0x30 and +0x34) width height shape flags(->+0x4c); <door x y exists="true|True">; <spawn x y> with <entity type variant subtype weight>. None of this is used for stage loading. Stage room data is .stb only, for both vanilla and mods.

Uncertainties

  • Stage +0 id for stages missing from stages.xml is never written by the ctor. It is probably zero (Game is likely zero-allocated), but this is not verified.
  • 0x751650: the "dimension 2 / Death Certificate" meaning is inferred. The stage 35 mode 0 load is certain.
  • The g+0x2654c & 0x10000 flag is assumed to be the Ascent/backwards state. The g+0x26584 == 0x2c branch was not identified.
  • Ordering of ModManager.mods (the vector at mm+0) was not analysed. Merge follows that order.
  • The vanilla packed stages.xml was not read. The attribute set and defaults above come from the code. The id list comes from a mod's copy of the vanilla file.
  • Room +0x50/+0x54 are still unknown.