Salvage Repentance+ 1.9.7.17 decompilation toolkit, notes and name database

Ghidra 12.2 project and full dump of isaac-ng.exe v1.9.7.17, query scripts, notes
indexed by entity, anm2/rooms reimplementations, and db/ (names + fields) that
build.sh re-applies. Fixes awk numeric address comparison in find.sh/decompile.sh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shweetandClaude Opus 5.5 committed 2026-10-24 13:08:19 -04:00
commit ad8f933086
124 files changed
+1366681

No files matched your search

+92
View File
@@ -0,0 +1,92 @@
# Room config (.stb) handling in isaac-ng.exe (Repentance+ v1.9.7.17)
| File | Contents |
|---|---|
| `stb.hpp` / `stb.cpp` | Binary format, room reader, door-slot mapping, variant ranges, mod merge |
| `rooms.hpp` / `rooms.cpp` | RNG, stages.xml, lazy stage loading, room selection, spawn picking, GetStageID |
| `test.cpp` | Checks; pass a resources dir to load real data |
| `docs/rooms_load_decomp.md` | Stage table, stages.xml, load timing, mod merge (with addresses) |
| `docs/rooms_use_decomp.md` | RNG, GetRandomRoom, PickEntry, weights, Room::Init spawning (with addresses) |
| `docs/stbdump.py` | Standalone Python .stb parser |
| `docs/rex.py`, `docs/labels_*.json` | The disassembly helper and function names used for this work |
```
g++ -std=c++17 -O2 -ffp-contract=off stb.cpp rooms.cpp test.cpp -o rooms_test
./rooms_test ".../dump/rep+full/resources"
```
## File format
Little-endian and packed, with no padding:
```
"STB1" u32 roomCount
room: u32 type u32 variant u32 subtype u8 difficulty u16 nameLen char name[nameLen]
f32 weight u8 width u8 height u8 shape u8 doorCount u16 spawnCount
door[doorCount]: i16 x i16 y u8 exists
spawn[spawnCount]: i16 x i16 y u8 entryCount
entry[entryCount]: u16 type u16 variant u16 subtype f32 weight
```
- **Magic:** only `STB1` is accepted.
- **Error handling:** read results are never checked.
- **Coordinates:** they are relative to the interior, so the left wall is x=-1 and a 1x1 room's right wall is x=13.
- **Doors:** each door becomes a bit (DoorSlot 0–7) through a fixed position table, 0x829a10. That table also covers the inner walls of L-shaped rooms (x=12, y=6, and so on).
- A door with `exists=0` is dropped.
- All 30,845 vanilla rooms parse with no leftover bytes, and every door maps to a valid slot.
- **Entry types:** type is u16 on disk.
- Types below 1000 are entities.
- 1000 and up are grid entities: 1000 = rock, 4500 = pressure plate, 9000 = trapdoor, and so on.
- 970 is a metadata marker that spawns nothing.
- **Flags computed at load:**
- A room containing a 4500.0 entry gets flag 0x80.
- An entry 970.2 standing on a door tile sets that door's bit in a second mask (+0x3c).
- Two hard-coded vanilla fixups:
- stages 1–3, variants 603 and 716 get flag 4;
- stages 29–30, type 1 with subtype 31 get flag 2.
## Where files come from
- **`stages.xml`** (parsed at 0x82b2f0) defines 37 stage slots.
- Each `path` sets both `rooms/<path>` (normal) and `rooms/greed/<path>` (greed).
- `.xml` is replaced by `.stb` at load time. No `.xml` room file is read for stages; only the `--load-room=` debug option reads one.
- **Loading is lazy.** It happens per (stage, mode) the first time a stage is needed. Level::Init resets weights for the stages it uses: the current stage, stage 0 (special rooms), Mines in some cases, and 1–17 except 13 on The Void.
- **Vanilla files can be replaced** through `<mod>/resources[-dlc3]/rooms/X.stb`.
- **Mod content files are appended:**
- `<mod>/content[-dlc3]/rooms/X.stb` is appended after the vanilla rooms, in mod order.
- A (type, variant) that is already taken is remapped by extending the *lowest* variant interval for that type. A bug makes this hand out variants that already exist once the first gap is used up, and lookups then return the vanilla room.
- A bad header in one mod's file stops the merge for every mod after it.
## Picking a room (GetRandomRoom 0x82c7d0)
1. **Filter:**
- type must match;
- shape must match, or the query shape is 13 (any);
- variant must be in range (unsigned compare);
- difficulty must be in range (signed compare);
- the room must have all the required doors;
- subtype must match, or the query subtype is -1 (any);
- with seed effect 79, rooms with flag 0x80 are dropped.
On The Void, candidates come from stages 1–17 except 13, with max difficulty forced to 20.
2. **Sum weights:** add up `Weight` over all candidates. Separately, sum over the "exact" candidates whose door mask equals the requested doors exactly.
3. **Draw:** use `RNG(seed, shift 7)`. When there are exact candidates, a second draw `f2` decides the list: if `9.99 * exactSum/total > f2`, the room comes from the exact list. In practice, rooms whose doors match exactly almost always win.
4. **Pick:** return the first room whose cumulative weight is strictly greater than `f1 * sum`.
5. **Reduce:** with `reduceWeight`, the picked room's weight becomes `max(1e-7, w*0.1)`. The weight is reset from InitialWeight on the next Level::Init for that stage.
6. **No match:** log a warning and return NULL. Wrapper 0x82cdd0 then retries with a fallback stage.
**Not reimplemented:** the Curse of the Giant path. 50% of type-1 picks split a big shape into two smaller rooms (0x82d880) and merge them into a generated room (0x82d4a0); the merge wasn't decoded.
## Spawning (Room::Init 0x7f2800)
- **Pick:** `RNG(desc.spawnSeed, shift 11)` advances once per spawn, even when the spawn has no entries. `PickEntry` returns the first entry whose cumulative weight is greater than `f * sumWeights`, and falls back to entry 0.
- **Placement:** `gridIdx = (x+1) + (y+1)*gridWidth`, with world position `(col*40+40, row*40+120)`.
- **Spawn:** type < 1000 goes to `Game::Spawn`; type ≥ 1000 becomes a grid entity, mapped through jump tables listed in the docs.
- **Two passes:** an earlier pass with the same seed handles meta types 825–970 (room and descriptor flags). Its details are in the docs.
**Not covered:**
- the entry transform at 0x7ec100, which handles stage replacements and probably the Lua spawn callback;
- the full grid-type jump tables;
- the RoomDescriptor+0x80 skip set;
- Room +0x50/+0x54;
- the name of seed effect 79.
@@ -0,0 +1,163 @@
{
"0x407170": "Color::Color()",
"0x4071f0": "Color::operator=(const&)",
"0x4074c0": "ANM2::ANM2",
"0x407690": "ANM2::ANM2(copy)",
"0x407a60": "LayerState::~LayerState",
"0x407ae0": "swap(ANM2&,ANM2&)",
"0x407e90": "ANM2::operator=(ANM2)",
"0x407f10": "ANM2::Reset",
"0x408170": "ANM2::~ANM2",
"0x4081d0": "LayerState::LayerState",
"0x408310": "LayerState::Init(LayerInfo*)",
"0x408590": "LayerState::GetTexture",
"0x408640": "LayerState::SetTexture",
"0x4086e0": "AnimationState::AnimationState(owner,copy)",
"0x4087a0": "AnimationState::~AnimationState",
"0x408830": "AnimationState::SetAnimationData",
"0x408970": "AnimationState::ChangeAnimationKeepFrame",
"0x408b90": "AnimationState::AdvanceLayerPosition(idx,xmm2 frame)",
"0x408c10": "AnimationState::AdvanceNullLayerPosition(idx,xmm2 frame)",
"0x408c90": "AnimationState::FireTriggersAtCurrentFrame",
"0x408d00": "AnimationState::AdvancePosition(int)",
"0x408e00": "AnimationState::SetFrameFloat(xmm1)",
"0x408ef0": "AnimationState::SetLayerFrame(layer,frame)",
"0x408f70": "AnimationState::GetLayerFrameIdx(layer)",
"0x408fc0": "AnimationState::SetNullLayerFrame(null,frame)",
"0x409030": "AnimationState::Update",
"0x409100": "lua_Update",
"0x40a0d0": "lua_Render",
"0x40a140": "lua_RenderLayer",
"0x40a1b0": "AnimationState::Rewind",
"0x40a220": "AnimationState::GetLayerFrame(layer)->AnimationFrame*",
"0x40a2b0": "lua_PlayRandom",
"0x40a360": "lua_Play",
"0x40a380": "ANM2::Play(cstr,force)",
"0x40a4b0": "lua_IsPlaying",
"0x40a530": "lua_IsFinished",
"0x40a5b0": "lua_SetAnimation",
"0x40a5d0": "ANM2::SetAnimation(cstr,reset)",
"0x40a690": "lua_SetFrame",
"0x40a720": "lua_SetFrame_1",
"0x40a760": "lua_SetLastFrame",
"0x40a780": "lua_GetFrame",
"0x40a7e0": "lua_SetLayerFrame",
"0x40a910": "lua_Stop",
"0x40a920": "lua_PlayOverlay",
"0x40a9d0": "lua_IsOverlayPlaying",
"0x40aa50": "lua_IsOverlayFinished",
"0x40aad0": "lua_SetOverlayAnimation",
"0x40abb0": "lua_SetOverlayFrame",
"0x40ac50": "lua_GetOverlayFrame",
"0x40ac60": "lua_RemoveOverlay",
"0x40add0": "AnimationState::IsEventTriggered(name)",
"0x40ae70": "AnimationState::WasEventTriggered(name)",
"0x40af10": "AnimationState::NextEventTrigger(name)",
"0x40b000": "lua_IsEventTriggered",
"0x40b060": "lua_WasEventTriggered",
"0x40bd50": "ANM2::Load(path,loadGraphics)",
"0x40bea0": "ANM2::Reload",
"0x40bec0": "AnimationData::AnimationData()",
"0x40bf30": "ANM2::ReplaceSpritesheet",
"0x40bff0": "lua_LoadGraphics",
"0x40c000": "ANM2::LoadGraphics",
"0x40c1e0": "LayerAnimation::LayerAnimation()",
"0x40c210": "NullAnimation::NullAnimation()",
"0x40ca70": "memcmp_eq(ecx,edx,n)",
"0x40cae0": "str_eq(ecx,edx=len,s2,len2)",
"0x40d140": "LayerInfo::LayerInfo()",
"0x40d240": "AnmCache::~AnmCache",
"0x40d4c0": "AnmCache::LogMemoryUsage",
"0x40d850": "AnmFileData::Clear",
"0x40db90": "AnmCache::Load(path,ANM2*)",
"0x40e110": "AnmCache::AddRef",
"0x40e2b0": "AnmCache::RemoveRef",
"0x40e470": "AnmCache::Clear",
"0x40e520": "TextureCache::Add",
"0x40e5d0": "TextureCache::Has",
"0x40e740": "TextureCache::Release",
"0x40e910": "TextureCache::Purge",
"0x40ea10": "TextureCache::Preload",
"0x40ea50": "AnmCache::Preload",
"0x40ed50": "AnmCache::ParseFile(path,key)",
"0x413bf0": "xml_node::first_attribute(name)",
"0x413c70": "xml_node::first_node(name)",
"0x414e00": "InterpolateNullFrames(ecx=buf,edx=&count,scratch)",
"0x415170": "InterpolateLayerFrames(ecx=buf,edx=&count,scratch)",
"0x4288a0": "std::set<int>::find_node",
"0x428b20": "Game::Spawn(type,variant,pos*,vel*,spawner,subtype,seed)",
"0x440e40": "lua_GetLayerCount",
"0x440e50": "set_PlaybackSpeed",
"0x456360": "get_PlaybackSpeed",
"0x499d20": "fmodf",
"0x4a5cf0": "lua_GetDefaultAnimationName",
"0x67f670": "ResolveRelativePath(out,anmPath,edx=rel)",
"0x6828b0": "LerpAngleDeg(xmm0 a,xmm1 b,xmm2 t)",
"0x6831c0": "Color::operator*=(other)",
"0x6832e0": "Color::Lerp(out,a,b,t)",
"0x6da750": "std::bitset<8>::any",
"0x6ef3e0": "RoomConfigRoom::dtor (name only)",
"0x6f1020": "Game::ctor",
"0x6f3c00": "Game::ReloadStagesXmlOnLuaReset",
"0x6f4740": "Game::LoadConfigXmls(stages,curses,...)",
"0x6f7750": "Game::Start",
"0x6f9400": "Seeds::GetForcedCurses?",
"0x6f95a0": "Seeds::GetPreventedCurses?",
"0x6fa0c0": "Game::Exit?(bool) (resets all room weights)",
"0x70b2e0": "CreateGridEntity(ecx=gridType,edx=gridIdx)",
"0x744940": "Level::Init",
"0x751650": "Level::GenerateHome?",
"0x752c30": "std::bitset<8>::to_string(out)",
"0x7e8fe0": "RNG::SetSeed(seed,shiftIdx)",
"0x7e9020": "RNG::RandomInt(n)",
"0x7e9080": "RNG::RandomFloat",
"0x7e90f0": "RNG::Next",
"0x7ec100": "Room::TransformEntry?(out,gridIdx,seed)",
"0x7ed310": "Room::SpawnEntry(gridIdx,Entry*,seed,b,b) ret14",
"0x7f2800": "Room::Init(cfgRoom,desc)",
"0x815ae0": "Room::RespawnShopItems?",
"0x828b20": "RoomConfigRoom::ctor",
"0x828b60": "RoomConfigMode::ctor",
"0x828c00": "RoomConfigMode::Clear",
"0x828e50": "RoomConfigMode::GetVariantRanges(type) (map<int,VariantRanges*> find-or-create)",
"0x828f00": "RoomConfigStage::ctor",
"0x829260": "RoomConfigMode::dtor?",
"0x829290": "VariantRanges::Insert(variant)->bool newlyInserted",
"0x829500": "RoomConfigStage::GetDisplayName",
"0x8295e0": "RoomConfigStage::dtor?",
"0x829650": "RoomConfigCurse::ctor?",
"0x829710": "RoomConfig::LoadRoomFromXmlFile(ecx=Room*,edx=path) (--load-room)",
"0x829a10": "GetDoorSlotFromGridPos(ecx=x,edx=y,stack shape)",
"0x829af0": "RoomConfigRoom::ParseXml(node)",
"0x82a9c0": "RoomConfig::ResetStageWeights(stageId,mode) ret8",
"0x82aa40": "RoomConfig::LoadStageBinary(stageId,mode) thiscall ret8",
"0x82aea0": "RoomConfig::ReadRoom(ecx=mode,edx=idx,stack:stageId,File*)",
"0x82b2f0": "RoomConfig::LoadStagesXml(path) thiscall ret4",
"0x82bd60": "RoomConfigStage::operator=(const&)",
"0x82bf00": "RoomConfig::LoadCursesXml(path,flag)?",
"0x82c720": "RoomConfig::GetRoomByStageTypeAndVariant(stageId,type,variant,mode) ret10",
"0x82c7d0": "RoomConfig::GetRandomRoom(seed,reduceWeight,stageId,type,shape,minVar,maxVar,minDiff,maxDiff,const bitset8* doors,subtype,mode) ret30",
"0x82cdd0": "RoomConfig::GetRandomRoomWithFallbackStage? ret34",
"0x82ce40": "RoomConfig::CollectRooms(out vector<Room*>,stageId,type,shape,minVar,maxVar,minDiff,maxDiff,doors*,subtype,mode) ret2c",
"0x82d000": "RoomConfig::GetStageDisplayName(out,stageId,?)",
"0x82d030": "RoomConfig::GetStageID(ecx=levelStage,edx=stageType,mode)",
"0x82d100": "RoomConfig::GetStageIdByName?(std::string*)",
"0x82d290": "RoomConfig::Spawn::PickEntry(float r) ret4",
"0x82d320": "RoomConfig::ClearGeneratedRooms",
"0x82d4a0": "RoomConfig::MergeRoomsIntoGenerated?(roomA,roomB,shape)",
"0x82d880": "RoomConfig::GetRandomSplitRoom (Curse of Giant) ret30",
"0x85db20": "lua_GetAnimation",
"0x85db70": "lua_GetOverlayAnimation",
"0x8f5ad0": "ResolveContentPath",
"0x8f8040": "ModManager::LoadModRooms(stageId,mode) ret8",
"0x8f86c0": "ModManager::LoadModCurses",
"0x8f99c0": "Mod::GetContentPath(out,name) (content-dlc3/ then content/)",
"0xa0f4e0": "operator_new_tracked",
"0xa112c0": "KAGE_LogMessage(level,fmt,...)",
"0xa159d0": "HashPath(djb2 lower,/)",
"0xa16060": "FileSystem::GetMountPrefixes",
"0xa17180": "FileSystem::ResolvePath",
"0xa178d0": "FileSystem::Open",
"0xa68490": "GetTimeNs",
"0xaf0917": "floor"
}
+77
View File
@@ -0,0 +1,77 @@
import pefile, capstone, re, struct, json, os
EXE=os.environ.get("EXE","/home/anon/.local/share/Steam/steamapps/common/The Binding of Isaac Rebirth/isaac-ng.exe")
_d=os.path.dirname(os.path.abspath(__file__))
pe=pefile.PE(EXE); IB=pe.OPTIONAL_HEADER.ImageBase
img=pe.get_memory_mapped_image()
text=[s for s in pe.sections if s.Name.startswith(b'.text')][0]
TS=IB+text.VirtualAddress; TE=TS+text.Misc_VirtualSize
md=capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_32); md.skipdata=True
def rd(va,n): return img[va-IB:va-IB+n]
def u32(va): return struct.unpack('<I',rd(va,4))[0]
def cstr(va):
b=img[va-IB:va-IB+4096]; i=b.find(b'\0'); return b[:i if i>=0 else 4096].decode('latin1')
def findstr(s):
return [IB+m.start()+1 for m in re.finditer(re.escape(b'\0'+s.encode()+b'\0'), img)]
_t=None
def xrefs(va):
global _t
if _t is None: _t=img[TS-IB:TE-IB]
return [TS+m.start() for m in re.finditer(re.escape(struct.pack('<I',va)), _t)]
IMP={}
for e in pe.DIRECTORY_ENTRY_IMPORT:
for i in e.imports: IMP[i.address]=e.dll.decode().split('.')[0]+'!'+(i.name.decode() if i.name else str(i.ordinal))
THK={}
for m in re.finditer(rb'\xff\x25(....)', img[TS-IB:TE-IB]):
a=struct.unpack('<I',m.group(1))[0]
if a in IMP: THK[TS+m.start()]=IMP[a]
LF=_d+'/labels.json'
def labels():
L={int(k,16):v for k,v in json.load(open(LF)).items()} if os.path.exists(LF) else {}
for k,v in THK.items(): L.setdefault(k,'thunk_'+v)
for k,v in IMP.items(): L.setdefault(k,'imp_'+v)
return L
def addlabel(a,n):
L={int(k,16):v for k,v in json.load(open(LF)).items()} if os.path.exists(LF) else {}
L[a]=n; json.dump({hex(k):v for k,v in sorted(L.items())},open(LF,'w'),indent=0)
def _ann(i,L):
s=f"{i.address:08x}: {i.mnemonic} {i.op_str}"
for m in re.finditer(r'0x([0-9a-f]{5,8})', i.op_str):
a=int(m.group(1),16)
if a in L: s+=f" ; <{L[a]}>"
elif IB<=a<IB+len(img) and not (TS<=a<TE):
try:
c=cstr(a)
if 2<=len(c)<160 and all(32<=ord(ch)<127 or ch in '\n\t' for ch in c): s+=(' ; "'+c+'"').replace('\n','\\n')
else: s+=f' ; [{u32(a):#x}]'
except: pass
return s
def dump(start,end,path=None):
L=labels(); out=[]
for i in md.disasm(rd(start,end-start),start):
if i.address in L and i.address!=start: out.append(f";;;; {L[i.address]}")
out.append(_ann(i,L))
t="\n".join(out)
if path: open(path,'w').write(t)
return t
def fnend(a, maxlen=0x20000):
# end = first run of >=2 int3 after a ret
b=rd(a,maxlen)
for m in re.finditer(rb'[\xc3\xc2..]\xcc\xcc|\xc3\xcc', b):
pass
i=0
while i<len(b)-1:
if b[i]==0xcc and b[i+1]==0xcc: return a+i
i+=1
return a+maxlen
def fn(a, path=None): return dump(a, fnend(a), path)
def callers(t):
out=[]
for m in re.finditer(rb'\xe8(....)', img[TS-IB:TE-IB]):
src=TS+m.start()
if src+5+struct.unpack('<i',m.group(1))[0]==t: out.append(src)
return out
def funcstart(va):
a=va
while a>TS:
if rd(a-1,1)==b'\xcc' and rd(a,1)!=b'\xcc': return a
a-=1
+326
View File
@@ -0,0 +1,326 @@
# 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)
```cpp
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)
```cpp
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):
```cpp
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)
```cpp
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)
```cpp
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.
+254
View File
@@ -0,0 +1,254 @@
# isaac-ng.exe (Rep+ 1.9.7.17) — how room-config (.stb) data is consumed
All addresses are VAs (ImageBase 0x400000). Struct layouts are from CONTEXT_rooms.md. One correction comes first.
## 0. Correction: weight fields
`ReadRoom` (0x82afe1..0x82aff0) writes the same float to both +0x30 and +0x34. The rest of the code shows which is which:
* **+0x30 = InitialWeight** (never written at runtime; it is the source for every reset)
* **+0x34 = Weight** (the runtime value; GetRandomRoom reads it for sums and multiplies it by 0.1 after a pick)
So CONTEXT_rooms.md has the two names swapped.
Global layout used below: `Game* g = [0xc71678]`. `g+0` is the Level (`+0 stage`, `+4 stageType`, `+0xc curses`), `g+0x18300` is `Room*`, `g+0x18910` is `RoomConfig` (embedded), and `g+0x1bbd8` is the seed-effects `std::set<int>`. `g+0x269c8` is difficulty (2/3 = greed/greedier, which gives mode 1).
`RoomConfig`: `+stageId*0xc4` is the stage (37 stages, 0..36). `+0x1e20` is `std::list<Room>*` of generated rooms (node 0x64 = next, prev, Room@+8), and `+0x1e24` is its count.
Mode resolution, used everywhere (for example 0x82c738 and 0x82ce84): `if (mode == -1) mode = (g && (g->difficulty==2 || g->difficulty==3)) ? 1 : 0;`. If `!stageMode.loaded` (+0x28), it calls LoadStageBinary first.
## 1. RNG class (0x7e8fe0 / 0x7e9020 / 0x7e9080 / 0x7e90f0)
```cpp
struct RNG { u32 seed; u32 s1, s2, s3; }; // 0x10 bytes
static const u32 kShifts[81][3] @0xb1f4c8; // listed below
void RNG::SetSeed(u32 seed, u32 idx) { // 0x7e8fe0
this->seed = seed; idx = min(idx, 80u); // (idx==0 -> 0)
s1,s2,s3 = kShifts[idx];
}
u32 RNG::Next() { // 0x7e90f0 ("RNG Seed is zero!" + int3 if seed==0)
u32 x = seed; x ^= x >> s1; x ^= x << s2; x ^= x >> s3; return seed = x;
}
u32 RNG::RandomInt(u32 n) { u32 x = Next(); return n ? x % n : 0; } // 0x7e9020
float RNG::RandomFloat() { return (float)(double)Next() * 2.3283062e-10f; } // 0x7e9080
// float conversion: cvtdq2pd + (x>>31 ? 4294967296.0 : 0) [table 0xbacb00] -> cvtpd2ps -> mulss 0x2f7ffffe
```
`kShifts` (index: s1,s2,s3):
```
0:(1,3,10) 1:(1,5,16) 2:(1,5,19) 3:(1,9,29) 4:(1,11,6) 5:(1,11,16) 6:(1,19,3) 7:(1,21,20) 8:(1,27,27)
9:(2,5,15) 10:(2,5,21) 11:(2,7,7) 12:(2,7,9) 13:(2,7,25) 14:(2,9,15) 15:(2,15,17) 16:(2,15,25) 17:(2,21,9)
18:(3,1,14) 19:(3,3,26) 20:(3,3,28) 21:(3,3,29) 22:(3,5,20) 23:(3,5,22) 24:(3,5,25) 25:(3,7,29) 26:(3,13,7)
27:(3,23,25) 28:(3,25,24) 29:(3,27,11) 30:(4,3,17) 31:(4,3,27) 32:(4,5,15) 33:(5,3,21) 34:(5,7,22) 35:(5,9,7)
36:(5,9,28) 37:(5,9,31) 38:(5,13,6) 39:(5,15,17) 40:(5,17,13) 41:(5,21,12) 42:(5,27,8) 43:(5,27,21) 44:(5,27,25)
45:(5,27,28) 46:(6,1,11) 47:(6,3,17) 48:(6,17,9) 49:(6,21,7) 50:(6,21,13) 51:(7,1,9) 52:(7,1,18) 53:(7,1,25)
54:(7,13,25) 55:(7,17,21) 56:(7,25,12) 57:(7,25,20) 58:(8,7,23) 59:(8,9,23) 60:(9,5,14) 61:(9,5,25) 62:(9,11,19)
63:(9,21,16) 64:(10,9,21) 65:(10,9,25) 66:(11,7,12) 67:(11,7,16) 68:(11,17,13) 69:(11,21,13) 70:(12,9,23)
71:(13,3,17) 72:(13,3,27) 73:(13,5,19) 74:(13,17,15) 75:(14,1,15) 76:(14,13,15) 77:(15,1,29) 78:(17,15,20)
79:(17,15,23) 80:(17,15,26)
```
Inlined RNGs often load a triplet straight from the table (`movq xmm0,[0xb1f4c8+idx*12]`). This gives `idx = (addr-0xb1f4c8)/12`.
## 2. RoomConfig::GetRandomRoom — 0x82c7d0 (thiscall, ret 0x30)
```cpp
Room* RoomConfig::GetRandomRoom(u32 seed, bool reduceWeight, int stageId, int type, int shape /*13 = any*/,
u32 minVariant, u32 maxVariant, int minDifficulty, int maxDifficulty,
const std::bitset<8>* requiredDoors, int subtype /*-1 = any*/, int mode /*-1 = auto*/)
{
// (a) Curse of the Giant (LevelCurse bit 0x80). 0x82c846..0x82c8e4
u32 curses = (g->level.curses /*g+0xc*/ | g+0x26550 | Seeds_ForcedCurses() /*0x6f9400*/) & ~Seeds_PreventedCurses() /*0x6f95a0*/;
if (curses & 0x80) {
RNG r{seed, kShifts[17]}; // (2,21,9)
if ((r.Next() & 1) == 0) {
Room* g2 = GetRandomSplitRoom(seed, reduceWeight, stageId, type, shape, minV, maxV, minD, maxD, requiredDoors, subtype, mode); // 0x82d880
if (g2) return g2;
}
}
// (b) Candidate collection. 0x82c8ec..0x82ca03
std::vector<Room*> all;
if (g->level.stage == 12 /*Void*/ && stageId != 0 && stageId != 35 /*Home*/) {
for (int s = 1; s <= 17; ++s) { if (s == 13) continue; // skip Blue Womb
auto v = CollectRooms(s, type, shape, minV, maxV, minD, /*maxD*/ 20, requiredDoors, subtype, mode);
all.insert(all.end(), v.begin(), v.end()); } // NOTE: the requested stageId is ignored; maxDifficulty is forced to 20
} else
all = CollectRooms(stageId, type, shape, minV, maxV, minD, maxD, requiredDoors, subtype, mode); // 0x82ce40
// (c) Sums. 0x82ca21..0x82caa5 (float, accumulated in vector order)
float total = 0, exactSum = 0; std::vector<Room*> exact;
for (Room* r : all) {
total += r->Weight /*+0x34*/;
if (requiredDoors->any() /*0x6da750*/ && r->doorMask /*+0x38*/ == requiredDoors->to_ulong()) {
exact.push_back(r); exactSum += r->Weight; }
}
if (!(total > 0.0f)) { // comiss 0,total ; jb => fail when 0 >= total (also when empty)
KAGE_LogMessage(1, "[warn] GetRandomRoom: unable to find matching room ... RequiredDoors %s, Subtype %d, returning NULL",
seed, stageId, type, shape, minV, maxV, minD, maxD, requiredDoors->to_string() /*0x752c30*/, subtype);
return nullptr;
}
// (d) Weighted pick. 0x82cba4..0x82cd9a
RNG rng{seed, kShifts[7]}; // (1,21,20)
u32 r1 = rng.Next(); float f1 = toFloat(r1); // RandomFloat math
float exactChance = (exactSum / total) * 9.99f; // 0x411fd70a
Room* pick = nullptr;
if (!exact.empty()) {
u32 r2 = rng.Next(); float f2 = toFloat(r2); // 2nd draw is only consumed when exact is non-empty
if (exactChance > f2) { // comiss xmm4,xmm0 ; jbe
float target = f1 * exactSum, acc = 0;
for (Room* r : exact) { acc += r->Weight; if (acc > target) { pick = r; break; } }
goto done; // NOTE: if not found -> NULL, with no fallback to `all`
}
}
{ float target = f1 * total, acc = 0;
for (Room* r : all) { acc += r->Weight; if (acc > target) { pick = r; break; } } }
done:
if (pick && reduceWeight)
pick->Weight = maxss(1e-7f /*0x33d6bf95*/, pick->Weight * 0.1f /*0x3dcccccd*/); // 0x82cd7c
return pick; // may be NULL when float rounding means acc never exceeds target
}
```
Notes:
* Every comparison is strict `acc > target` (`comiss acc,target; ja`).
* A room's weight goes into the sums as it currently is, so weights already reduced earlier in the run take part.
* "exact" means the room's door mask is exactly the requested set. CollectRooms only requires the requested doors to be a subset. This makes rooms that fit the doors exactly much more likely: they are chosen with probability `min(1, 9.99*exactSum/total)`.
* Fallback when nothing matches: it logs the warning and returns NULL. There is no retry inside the function. Callers retry, for example the wrapper below.
### CollectRooms — 0x82ce40 (thiscall, ret 0x2c, returns vector by out-ptr)
```cpp
for (u32 i = 0; i < m.count; ++i) { Room* r = &m.rooms[i]; // m = stage(stageId).modes[mode]
if (r->type != type) continue;
if (shape != 13 && r->shape /*+0x48*/ != shape) continue; // 13 = ROOMSHAPE_NUM acts as a wildcard
if (r->variant < minVariant || r->variant > maxVariant) continue; // unsigned compare (jb/ja)
if (r->difficulty < minDifficulty || r->difficulty > maxDifficulty) continue; // signed (jl/jg)
if ((r->doorMask & *requiredDoors) != *requiredDoors) continue; // must have all the required doors (superset allowed)
if (subtype != -1 && r->subtype != subtype) continue;
if (Seeds.contains(79 /*0x4f*/) && (r->flags /*+0x4c*/ & 0x80)) continue; // flag 0x80 = room contains a 4500.0 entity (pressure plate)
out.push_back(r);
}
```
The weight is not filtered here, so rooms with weight 0 are collected but can never be picked (they add 0 to the sums). The value 79 is a SeedEffect id. Its name was not checked; it is probably the "no pressure plates"-style seed.
### Wrapper 0x82cdd0 (ret 0x34, 13 stack args)
`r = GetRandomRoom(a1 seed, a2 reduce, a3 stageId, a5 type, a6 shape, 0, 0xFFFFFFFF, a9 minD, a10 maxD, a11 doors, a12 subtype, -1)`. If that returns NULL, it repeats the call with `stageId = a4` (fallback stage).
Args a7, a8 and a13 appear unused (uncertain). Called from 16 sites in Level generation (0x7392c7, 0x73a3df, ...).
### Curse of the Giant split rooms — 0x82d880 (same signature as GetRandomRoom)
This path is only taken if `type == 1` and `shape != 13`, and the split table `0xb1f494[shape]` must be non-empty. Each table entry is 32 bytes: `{shapeA, offXA, offYA, doorsA, shapeB, offXB, offYB, doorsB}`:
```
4(IH): {1,0,0,8, 1,0,1,2} 5(IIV):{3,0,0,8, 3,0,1,2} 6(1x2? per enum 6): {1,0,0,4, 1,1,0,1} 7: {2,0,0,4, 2,1,0,1}
8(2x2): {4,0,0,0x44,4,1,0,0x11} {6,0,0,0x88,6,0,1,0x22} {9,0,0,3,1,0,0,0xc} {10,0,0,0x24,1,1,0,9} {11,0,0,0x18,1,0,1,6} {12,0,0,0xc0,1,0,1,3}
9: {1,0,1,4,4,1,0,0x10} {1,1,0,8,6,0,1,0x20} 10: {4,0,0,0x40,1,1,1,1} {1,0,0,8,6,0,1,2}
11: {1,0,0,4,4,1,0,1} {6,0,0,0x80,1,1,1,2} 12: {4,0,0,4,1,1,0,1} {6,0,0,8,1,0,1,2}
```
The function works like this:
1. `RNG rng{seed, kShifts[55]}` and `e = table[rng.RandomInt(count)]`.
2. Each required door d (0..7) is remapped into each half. If `offY>0 && d∈{4,6}` or `offX>0 && d∈{5,7}`, then `d -= 4`. The door is kept only if it is valid for the half's shape (valid-door mask per shape is at 0xb1f894: `[0,0xf,5,0xa,0x5f,0xa,0xaf,5,0xff,0xff,0xff,0xff,0xff]`). The result is OR-ed into `doorsA` / `doorsB`.
3. `sA = next(rng.seed)` with (7,17,21), and `A = GetRandomRoom(sA, reduce, stageId, 1, shapeA, minV, maxV, minD, maxD, &doorsA, subtype, mode)`.
4. `sB = next(sA)`, and B is picked the same way with `shapeB`.
5. If both are found, it returns `0x82d4a0(A, B, shape)`. That function builds a merged Room and appends it to the `RoomConfig+0x1e20` generated list (count at +0x1e24). Otherwise it returns NULL.
### GetRoomByStageTypeAndVariant — 0x82c720 (thiscall, ret 0x10)
```cpp
Room* RoomConfig::GetRoomByStageTypeAndVariant(int stageId, int type, int variant, int mode /*-1 auto*/) {
// mode resolve + lazy load
for (u32 i = 0; i < m.count; ++i) if (m.rooms[i].type == type && m.rooms[i].variant == variant) return &m.rooms[i];
KAGE_LogMessage(1, "[warn] StageID %d Room type %d, variant %d not found!\n", stageId, type, variant);
return nullptr;
}
```
It does a linear scan, returns the first match and ignores subtype.
### GetStageID — 0x82d030 (ecx=levelStage, edx=stageType, [esp+4]=mode; caller cleans)
This maps LevelStage and StageType to the stb id.
* **Greed** (`mode==1`, or `mode==-1` with greed difficulty):
* stage 7 → 25 and stage 6 → 24 (`stage+18`); stage 5 → 14 (`stage+9`).
* Otherwise: type 4 → `2*stage+25`, type 5 → `2*stage+26`, else `3*stage-2+type`.
* **Normal**:
* stage 13 → 35 (Home).
* stage < 9: with `n = stage-1`, type 4 → `(n&~1)+27`, type 5 → `(n>>1)*2+28`, else `(n>>1)*3+type+1`.
* stage 9 → 13, or 36 when type 4.
* stage 12 → 26.
* Otherwise → `(stage-3)*2+type` (10 → 14/15, 11 → 16/17).
## 3. RoomConfig::Spawn::PickEntry — 0x82d290 (thiscall on Spawn, 1 float arg, ret 4)
```cpp
const Entry* Spawn::PickEntry(float r /*[0,1)*/) const {
float target = r * sumWeights; // +0xc
float acc = 0;
for (u8 i = 0; i < entryCount /*+8*/; ++i) { // u8 counter
acc += entries[i].weight; // +8 of 0xc-byte Entry
if (acc > target) return &entries[i]; // comiss; ja (strict)
}
KAGE_LogMessage(1, "[warn] RoomConfig::Spawn::PickEntry did not terminate properly. Picking first entry: (%d, %d, %d, %f)\n",
entries[0].type, entries[0].variant, entries[0].subtype, (double)entries[0].weight);
return &entries[0];
}
```
Callers always check `entryCount > 0` before calling it.
## 4. Runtime Weight (+0x34) modification and reset
* **Reduced**: only in GetRandomRoom when `reduceWeight` is true (0x82cd72..0x82cd95): `w = max(1e-7, w*0.1)`. No other writer was found in native code. Lua exposes the `Weight` / `InitialWeight` properties (strings 0xb6a14c / 0xb735c4, used by bindings near 0x86be2d / 0x86bf71); I did not check whether they are writable.
* **Reset (`Weight = InitialWeight` for every room of a stage/mode)**:
* `RoomConfig::ResetStageWeights(stageId, mode)` at **0x82a9c0**. If the stage is not loaded it calls LoadStageBinary instead, which also gives fresh weights. Otherwise it loops over the rooms.
* **Level::Init 0x744940** (log "Level::Init m_Stage %d, m_StageType %d Seed %u"), right after `ClearGeneratedRooms()` (call at 0x74510c):
* Level stage 12 (Void) resets stb 1..17 except 13, both loaded and mode-resolved (0x74511c..0x7451cb).
* Any other stage resets `GetStageID(stage, stageType, -1)` (0x7451dc..0x74526c).
* Additionally, if stageType is 4/5 and (stage==4, or stage==3 with Labyrinth curse bit 2 set), it resets stb 29 (Mines; 0x7452af..0x745362).
* Not greed: unless stage==13/the specific level-gen cases (stage 13, stage≤6 with g+0x2654c&0x10000, challenge g+0x26584==0x2c, stage 9), it calls `ResetStageWeights(0 /*special rooms*/, -1)` at 0x7453e7 and then generates (0x740e10).
* Greed: it resets stb 0 inline (0x7453f9..0x74545a) and then calls 0x743550.
* So the **special-room (stb 0) weights are reset on each normal level init**, except on Home (stage 13), Blue Womb (stage 9), challenge 0x2c, and stage≤6 with the g+0x2654c&0x10000 flag. Those go to the dedicated generators 0x74de30, 0x74a500, 0x7508c0 and 0x742ef0, and whether those reset stb 0 was not checked.
* **Home generation 0x751650**: resets or loads stb 35 (mode 0).
* **0x6fa0c0** (called from the shutdown path 0x9ab84a; probably Game::Exit/end-of-run): resets every loaded stage, 37 stages × 2 modes (0x6fa3c5..0x6fa41a).
* **Generated rooms**: `RoomConfig::ClearGeneratedRooms` at **0x82d320** logs `"delete %d generated rooms.\n"` with count `+0x1e24`. For each list node it frees every Spawn's entries (`Room+0x40`/`+0x44`) and the spawn array, destroys the name string, frees the 0x64-byte node, and resets the list and count. It is called from Level::Init (0x74510c) and from 0x7477e5. Generated rooms are created by the Giant-curse merge (0x82d4a0 → 0x82de80 list insert).
## 5. From Room spawns to entities (high level)
`Room::Init(RoomConfig::Room* cfg, RoomDescriptor* desc)` at **0x7f2800** (thiscall on `g+0x18300`, called from 0x73e8a2). Grid width is `Room+0xc` and height is `Room+0x10`. The grid-entity pointer array is `Room+0x24 + idx*4`, with indices up to 0x1bf (448 cells).
**Pass 1, pre-scan (0x7f319a..0x7f3339).**
* It logs `"SpawnRNG seed: %u"` with `desc+0x5c` (SpawnSeed), then builds an RNG from that seed with kShifts[11] (2,7,7).
* For each spawn i: `rng.Next()`, `f = toFloat`; if entryCount > 0 it calls `e = PickEntry(f)`.
* It switches on `e->type` in 825..970 (table 0x7f7928/0x7f7908) and sets room or descriptor flags.
* Type **970** (room-config meta entity) is handled by variant:
* variant 0 → `desc+0x44 |= 0x200`
* variant 1 → by subtype: 20 / 11 → local flags; 10 → `desc+0x44 |= 0x1000`; 0..3 → `Room+0x7460/0x7464 = table 0xc5d0e8[subtype]` (a direction vector)
* variant 3 → `desc+0x44 |= 0x2000`
* variant 4 → uses the grid position (0x7f342d)
* Types 825/907, 829, 876/918, 882, 905 and 919 have their own cases.
**Pass 2, real spawn (0x7f39b3..0x7f3aff).** It restarts from the same `desc+0x5c` seed, so pass 1 and pass 2 make identical picks.
```cpp
RNG rng{desc->spawnSeed, kShifts[11]};
for (u16 i = 0; i < cfg->spawnCount; ++i) {
Spawn& s = cfg->spawns[i];
u32 seed = rng.Next(); float f = toFloat(seed); // advanced even if entryCount==0
int gridIdx = (s.x + 1) + (s.y + 1) * room->width; // stb x,y are relative to the inner area (no walls)
if (s.entryCount == 0) continue;
const Entry* e = s.PickEntry(f);
if (!desc->set80.contains(gridIdx)) // std::set<int> at RoomDescriptor+0x80 (probably removed/restricted grid indices; meaning unverified)
room->SpawnEntry(gridIdx, e, seed, false, false); // 0x7ed310
}
```
**`Room::SpawnEntry(gridIdx, Entry*, seed, bool, bool)`** at **0x7ed310** (ret 0x14).
* It copies the entry, then calls 0x7ec100 (entry transform/replacement; likely where MC_PRE_ROOM_ENTITY_SPAWN and stage replacements happen; unverified).
* The per-entity seed RNG uses kShifts[35] (5,9,7).
* Position of a grid index: `x = (idx % w)*40 + 40`, `y = (idx / w)*40 + 120` (0x7ee4dc, 0x815cef).
* **type < 1000** spawns an entity via `Game::Spawn(type, variant, pos, Vector0, nullptr, subtype, seed)` (0x428b20). Special cases:
* 970 (0x3ca) spawns nothing (returns true; 0x7ed936)
* 969 (0x3c9) is special-cased (0x7ed93c)
* 999 (0x3e7), 965 (0x3c5) and 911 (0x38f) are also special-cased
* **type ≥ 1000** creates a grid entity: `CreateGridEntity(gridType, gridIdx)` (0x70b2e0), then `grid->variant = v`, then `Init(seed)` (0x709db0). The stb-to-GridEntityType mapping (0x7ede09..0x7ee64d):
* 1000..1011: jump table at 0x7ee6a0 (1000 → ROCK 2, etc.)
* 1300 → special case
* 1400..1501: table at 0x7ee700 (fire places/poops → 14 POOP with variants, `desc+0x50++`)
* 1900 → 3 (BLOCK)
* 1901..1940: table at 0x7ee790 (10, 8, 9, 24 …)
* 1999 → 15
* 3000..3009: table at 0x7ee7c8; 3000 → PIT 7, `desc+0x54++`
* 4000 → 11 (LOCK)
* 4500 → 20 (PRESSURE_PLATE)
* 5000 → 21 (STATUE) var 0; 5001 → 21 var 1
* 6000/6001 → 7 (also 0x7ed9a4)
* 6100 → 23 (TELEPORTER)
* 9000 → 17 (TRAPDOOR) var 0; 9100 → 18 (CRAWLSPACE); 10000 → 19 (GRAVITY)
* anything else → 1 (DECORATION)
* 0x815ae0 is a separate re-spawn routine (shop restock for room types 2/22). It uses the same grid-index and position math and spawns only 5.150 entries, plus a 1000.15 poof.
## Uncertainties
* The 0x82cdd0 argument meanings (a7, a8, a13 unused) were not checked against callers.
* SeedEffect 79 has not been named. `g+0x26550` is assumed to be extra curses.
* The meaning of `RoomDescriptor+0x80` and of the 0x7ec100 transform.
* 0x6fa0c0 being "end of run". Its only direct caller is in the shutdown path, so a reset between runs in the same session may happen only through Level::Init. That means non-current stages and stb 0 in some flows keep their reduced weights.
* The 0x82d4a0 merge internals (how the spawn offsets and doors are combined) were not decoded.
+29
View File
@@ -0,0 +1,29 @@
import struct, sys, os, collections
def parse(b):
p=0
def r(fmt):
nonlocal p; v=struct.unpack_from('<'+fmt,b,p); p+=struct.calcsize('<'+fmt); return v if len(v)>1 else v[0]
assert b[:4]==b'STB1', b[:4]; p=4
n=r('I'); rooms=[]
for _ in range(n):
t,v,st=r('I'),r('I'),r('I'); diff=r('B'); nl=r('H'); name=b[p:p+nl].decode('utf-8','replace'); p+=nl
w=r('f'); W,H,shape=r('B'),r('B'),r('B'); nd=r('B'); ns=r('H')
doors=[r('hhB') for _ in range(nd)]
spawns=[]
for _ in range(ns):
x,y,ne=r('hhB'); ents=[r('HHHf') for _ in range(ne)]; spawns.append((x,y,ents))
rooms.append(dict(type=t,variant=v,subtype=st,diff=diff,name=name,weight=w,w=W,h=H,shape=shape,doors=doors,spawns=spawns))
return rooms,p
tot=collections.Counter(); bad=0
for f in sys.argv[1:]:
b=open(f,'rb').read(); rooms,p=parse(b)
if p!=len(b): print('TRAILING',f,len(b)-p); bad+=1
for r in rooms:
tot['rooms']+=1; tot['shape%d'%r['shape']]+=1
for x,y,e in r['doors']:
if not e: tot['door_disabled']+=1
for x,y,ents in r['spawns']:
for t,v,s,w in ents:
if t==970: tot['ent970v%d'%v]+=1
if t==4500: tot['ent4500v%d'%v]+=1
print(bad, dict(sorted(tot.items())))
+38
View File
@@ -0,0 +1,38 @@
"""Recover named function addresses in isaac-ng.exe from Repentogon's libzhl.dll signature table.
Usage: python zhl_sigs.py <libzhl.dll> <isaac-ng.exe> <out.json>"""
import sys, re, struct, json, pefile, capstone
dll, exe, out = sys.argv[1:4]
pe = pefile.PE(dll); IB = pe.OPTIONAL_HEADER.ImageBase; img = pe.get_memory_mapped_image()
def cstr(va):
o = va - IB
if not (0 <= o < len(img)): return None
e = img.find(b'\0', o, o + 4096)
try: return img[o:e].decode('ascii')
except: return None
text = [s for s in pe.sections if s.Name.startswith(b'.text')][0]
TS = IB + text.VirtualAddress; code = img[text.VirtualAddress:text.VirtualAddress + text.Misc_VirtualSize]
# find the most common call target preceded by 'push name' patterns: use known registrar from a name xref
md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_32)
pairs = {}
# scan for "push imm32" runs ending in "mov ecx, imm32; call rel32"
for m in re.finditer(rb'(?:\x68....){4}\xb9....\xe8....', code, re.S):
start = m.start(); seg = code[start:m.end()]
pushes = [struct.unpack('<I', seg[1 + 5 * i:5 + 5 * i])[0] for i in range(4)]
sig, _ti, fun, name = pushes
n, f, s = cstr(name), cstr(fun), cstr(sig)
if not n or not f or not s or not f.startswith('_fun'): continue
if not re.fullmatch(r'[0-9a-fA-F?]+', s) or len(s) % 2: continue
pairs[n] = s
print(len(pairs), 'signatures in', dll, file=sys.stderr)
pe2 = pefile.PE(exe); IB2 = pe2.OPTIONAL_HEADER.ImageBase; img2 = pe2.get_memory_mapped_image()
t2 = [s for s in pe2.sections if s.Name.startswith(b'.text')][0]
T2 = IB2 + t2.VirtualAddress; code2 = img2[t2.VirtualAddress:t2.VirtualAddress + t2.Misc_VirtualSize]
res, miss, multi = {}, [], []
for name, sig in pairs.items():
rx = b''.join(b'.' if sig[i:i+2] == '??' else re.escape(bytes([int(sig[i:i+2], 16)])) for i in range(0, len(sig), 2))
hits = [T2 + m.start() for m in re.finditer(rx, code2, re.S)]
if len(hits) == 1: res[hex(hits[0])] = name
elif not hits: miss.append(name)
else: multi.append((name, len(hits)))
json.dump(res, open(out, 'w'), indent=0, sort_keys=True)
print(f'{len(res)} unique, {len(miss)} missing, {len(multi)} ambiguous', file=sys.stderr)
+333
View File
@@ -0,0 +1,333 @@
#include "rooms.hpp"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <sstream>
namespace rooms {
// =============================================================================================
// RNG
// =============================================================================================
const uint8_t kRngShifts[81][3] = { // @0xb1f4c8
{1,3,10},{1,5,16},{1,5,19},{1,9,29},{1,11,6},{1,11,16},{1,19,3},{1,21,20},{1,27,27},
{2,5,15},{2,5,21},{2,7,7},{2,7,9},{2,7,25},{2,9,15},{2,15,17},{2,15,25},{2,21,9},
{3,1,14},{3,3,26},{3,3,28},{3,3,29},{3,5,20},{3,5,22},{3,5,25},{3,7,29},{3,13,7},
{3,23,25},{3,25,24},{3,27,11},{4,3,17},{4,3,27},{4,5,15},{5,3,21},{5,7,22},{5,9,7},
{5,9,28},{5,9,31},{5,13,6},{5,15,17},{5,17,13},{5,21,12},{5,27,8},{5,27,21},{5,27,25},
{5,27,28},{6,1,11},{6,3,17},{6,17,9},{6,21,7},{6,21,13},{7,1,9},{7,1,18},{7,1,25},
{7,13,25},{7,17,21},{7,25,12},{7,25,20},{8,7,23},{8,9,23},{9,5,14},{9,5,25},{9,11,19},
{9,21,16},{10,9,21},{10,9,25},{11,7,12},{11,7,16},{11,17,13},{11,21,13},{12,9,23},
{13,3,17},{13,3,27},{13,5,19},{13,17,15},{14,1,15},{14,13,15},{15,1,29},{17,15,20},
{17,15,23},{17,15,26},
};
void RNG::SetSeed(uint32_t s, unsigned idx) {
seed = s;
if (idx > 80) idx = 80;
s1 = kRngShifts[idx][0]; s2 = kRngShifts[idx][1]; s3 = kRngShifts[idx][2];
}
uint32_t RNG::Next() {
if (seed == 0) std::fprintf(stderr, "RNG Seed is zero!\n"); // ORIGINAL: then int3 (debug break)
uint32_t x = seed;
x ^= x >> s1;
x ^= x << s2;
x ^= x >> s3;
return seed = x;
}
float RNG::ToFloat(uint32_t x) {
// cvtdq2pd (signed) + {0, 2^32}[x>>31] -> cvtpd2ps -> mulss 0x2f7ffffe
double d = (double)(int32_t)x + ((x >> 31) ? 4294967296.0 : 0.0);
float f = (float)d;
uint32_t kbits = 0x2f7ffffe; float k; std::memcpy(&k, &kbits, 4);
return f * k;
}
// =============================================================================================
// stages.xml (RoomConfig::LoadStagesXml 0x82b2f0). Minimal attribute scanner: the file is flat.
// =============================================================================================
namespace {
using Attrs = std::vector<std::pair<std::string, std::string>>;
std::string StripComments(std::string s) {
for (size_t a; (a = s.find("<!--")) != std::string::npos;) {
size_t b = s.find("-->", a);
s.erase(a, b == std::string::npos ? std::string::npos : b + 3 - a);
}
return s;
}
// Parses the attributes of the tag starting at s[pos] == '<'. Returns position after the tag.
size_t ParseTag(const std::string& s, size_t pos, std::string& name, Attrs& attrs) {
size_t p = pos + 1, n = s.size();
name.clear(); attrs.clear();
while (p < n && !isspace((unsigned char)s[p]) && s[p] != '>' && s[p] != '/') name += s[p++];
for (;;) {
while (p < n && isspace((unsigned char)s[p])) ++p;
if (p >= n) return n;
if (s[p] == '>') return p + 1;
if (s[p] == '/') { ++p; continue; }
std::string k, v;
while (p < n && s[p] != '=' && !isspace((unsigned char)s[p]) && s[p] != '>') k += s[p++];
while (p < n && isspace((unsigned char)s[p])) ++p;
if (p < n && s[p] == '=') {
++p; while (p < n && isspace((unsigned char)s[p])) ++p;
char q = s[p++];
size_t e = s.find(q, p);
v = s.substr(p, e - p); p = e + 1;
}
attrs.emplace_back(k, v);
}
}
const std::string* Find(const Attrs& a, const char* k) {
for (auto& kv : a) if (kv.first == k) return &kv.second;
return nullptr;
}
} // namespace
bool RoomConfig::LoadStagesXml(const std::string& path) {
std::ifstream f(path, std::ios::binary);
if (!f) return false;
std::stringstream ss; ss << f.rdbuf();
std::string s = StripComments(ss.str());
size_t p = s.find("<stages");
if (p == std::string::npos) return false; // ORIGINAL: NULL deref
std::string tag; Attrs at;
size_t q = ParseTag(s, p, tag, at);
const std::string* r = Find(at, "root");
const std::string* g = Find(at, "greedroot");
const std::string* b = Find(at, "bossgfxroot"); // ORIGINAL: no null check -> crash if missing
std::string roomsRoot = r ? *r : "rooms/", greedRoot = g ? *g : "rooms/greed/", bossRoot = b ? *b : "";
int id = 0; // ORIGINAL: uninitialised and NOT reset per <stage>: a <stage> without id reuses the previous id
// Iterates first_node("stage") then every next sibling element, without a name check.
bool first = true;
while ((p = s.find('<', q)) != std::string::npos) {
if (s.compare(p, 2, "</") == 0) break; // </stages>
q = ParseTag(s, p, tag, at);
if (first && tag != "stage") continue;
first = false;
RoomConfigStage tmp;
for (auto& kv : at) {
const std::string& k = kv.first; const std::string& v = kv.second;
if (k == "id") id = std::atoi(v.c_str());
else if (k == "name") tmp.name = v;
else if (k == "path") { tmp.modes[0].file = roomsRoot + v; tmp.modes[1].file = greedRoot + v; }
else if (k == "playerspot") tmp.playerSpot = bossRoot + v;
else if (k == "bossspot") tmp.bossSpot = bossRoot + v;
else if (k == "music") tmp.music = std::atoi(v.c_str());
else if (k == "backdrop") tmp.backdrop = std::atoi(v.c_str());
else if (k == "suffix") tmp.suffix = v;
}
tmp.id = id;
if (id < 0 || id >= kNumStages) { std::fprintf(stderr, "stage id %d out of range (ORIGINAL: writes out of bounds)\n", id); continue; }
stages[id] = std::move(tmp); // also "unloads" that stage (rooms/loaded come from the fresh temp)
}
return true;
}
// =============================================================================================
// Loading
// =============================================================================================
int RoomConfig::ResolveMode(int mode) const {
if (mode == -1) mode = (game && (game->difficulty == 2 || game->difficulty == 3)) ? 1 : 0;
return mode;
}
static bool ReadFile(const std::string& path, std::vector<uint8_t>& out) {
std::ifstream f(path, std::ios::binary);
if (!f) return false;
out.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
return true;
}
bool RoomConfig::LoadStageBinary(int stageId, int mode) {
mode = ResolveMode(mode);
RoomConfigMode& m = stages[stageId].modes[mode];
if (m.file.empty()) return false;
std::fprintf(stderr, "[RoomConfig] load stage %d: %s (mode %d)\n", stages[stageId].id, stages[stageId].name.c_str(), mode);
std::string rel = m.file.substr(0, m.file.size() >= 3 ? m.file.size() - 3 : 0) + "stb"; // ".xml" -> ".stb"
std::string path = resolve ? resolve(rel) : rel;
std::vector<uint8_t> buf;
if (path.empty() || !ReadFile(path, buf)) return false; // not marked loaded
if (!ParseStb(buf.data(), buf.size(), stageId, mode, m)) return false; // bad header: cleared, not loaded
// ModManager::LoadModRooms 0x8f8040
if (modRoomFiles) {
for (const std::string& mf : modRoomFiles(rel)) {
std::vector<uint8_t> mb;
if (!ReadFile(mf, mb)) continue; // silently skipped
if (!MergeModStb(mb.data(), mb.size(), stageId, mode, m)) {
std::fprintf(stderr, "[ModManager] bad room config header in %s!\n", mf.c_str());
break; // ORIGINAL: returns from the whole merge (later mods skipped)
}
}
}
m.loaded = true;
return true;
}
void RoomConfig::ResetStageWeights(int stageId, int mode) { // 0x82a9c0
mode = ResolveMode(mode);
RoomConfigMode& m = stages[stageId].modes[mode];
if (!m.loaded) { LoadStageBinary(stageId, mode); return; }
for (Room& r : m.rooms) r.weight = r.initialWeight;
}
RoomConfigMode* RoomConfig::Mode(int stageId, int mode) {
mode = ResolveMode(mode);
RoomConfigMode& m = stages[stageId].modes[mode];
if (!m.loaded) LoadStageBinary(stageId, mode);
return &m;
}
// =============================================================================================
// Lookup / selection
// =============================================================================================
Room* RoomConfig::GetRoomByStageTypeAndVariant(int stageId, int type, int variant, int mode) {
RoomConfigMode* m = Mode(stageId, mode);
for (Room& r : m->rooms)
if (r.type == type && r.variant == variant) return &r; // first match; subtype ignored
std::fprintf(stderr, "[warn] StageID %d Room type %d, variant %d not found!\n", stageId, type, variant);
return nullptr;
}
std::vector<Room*> RoomConfig::CollectRooms(int stageId, const RoomQuery& q) {
std::vector<Room*> out;
RoomConfigMode* m = Mode(stageId, q.mode);
for (Room& r : m->rooms) {
if (r.type != q.type) continue;
if (q.shape != 13 && r.shape != q.shape) continue;
if ((uint32_t)r.variant < q.minVariant || (uint32_t)r.variant > q.maxVariant) continue;
if (r.difficulty < q.minDifficulty || r.difficulty > q.maxDifficulty) continue;
if ((r.doors & q.requiredDoors) != q.requiredDoors) continue;
if (q.subtype != -1 && r.subtype != q.subtype) continue;
if (game && game->seedEffect79 && (r.flags & FLAG_HAS_4500_0)) continue;
out.push_back(&r); // weight is NOT filtered: weight-0 rooms are collected but never picked
}
return out;
}
Room* RoomConfig::GetRandomRoom(uint32_t seed, bool reduceWeight, int stageId, const RoomQuery& q) {
// ORIGINAL: with Curse of the Giant, 50% (RNG{seed,17}.Next() & 1 == 0) of type-1 picks go through
// GetRandomSplitRoom 0x82d880 (two smaller rooms merged into a generated room). Not reimplemented.
std::vector<Room*> all;
if (game && game->levelStage == 12 && stageId != 0 && stageId != 35) { // The Void
RoomQuery vq = q; vq.maxDifficulty = 20; // requested stageId ignored
for (int s = 1; s <= 17; ++s) {
if (s == 13) continue;
auto v = CollectRooms(s, vq);
all.insert(all.end(), v.begin(), v.end());
}
} else {
all = CollectRooms(stageId, q);
}
float total = 0, exactSum = 0;
std::vector<Room*> exact;
for (Room* r : all) {
total += r->weight;
if (q.requiredDoors != 0 && r->doors == q.requiredDoors) { exact.push_back(r); exactSum += r->weight; }
}
if (!(total > 0.0f)) {
std::fprintf(stderr, "[warn] GetRandomRoom: unable to find matching room (seed %x, StageID %d, Type %d, Shape %d, ...), returning NULL\n",
seed, stageId, q.type, q.shape);
return nullptr;
}
RNG rng(seed, 7);
float f1 = RNG::ToFloat(rng.Next());
float exactChance = (exactSum / total) * 9.99f;
Room* pick = nullptr;
bool fromExact = false;
if (!exact.empty()) {
float f2 = RNG::ToFloat(rng.Next()); // only drawn when there are exact matches
fromExact = exactChance > f2; // rooms whose doors match EXACTLY are strongly preferred
}
const std::vector<Room*>& list = fromExact ? exact : all;
float target = f1 * (fromExact ? exactSum : total), acc = 0;
for (Room* r : list) {
acc += r->weight;
if (acc > target) { pick = r; break; }
}
// pick can be NULL if float rounding keeps acc <= target; no fallback inside.
if (pick && reduceWeight) pick->weight = std::max(1e-7f, pick->weight * 0.1f); // maxss(1e-7, w*0.1)
return pick;
}
Room* RoomConfig::GetRandomRoomWithFallback(uint32_t seed, bool reduceWeight, int stageId, int fallbackStageId, RoomQuery q) {
q.minVariant = 0; q.maxVariant = 0xFFFFFFFFu; q.mode = -1; // what wrapper 0x82cdd0 passes
Room* r = GetRandomRoom(seed, reduceWeight, stageId, q);
if (!r) r = GetRandomRoom(seed, reduceWeight, fallbackStageId, q);
return r;
}
int GetStageID(int stage, int type, int mode, int difficulty) { // 0x82d030
bool greed = mode == 1 || (mode == -1 && (difficulty == 2 || difficulty == 3));
if (greed) {
if (stage == 7 || stage == 6) return stage + 18; // 25 Ultra Greed, 24 The Shop
if (stage == 5) return stage + 9; // 14 Sheol
if (type == 4) return 2 * stage + 25;
if (type == 5) return 2 * stage + 26;
return 3 * stage - 2 + type;
}
if (stage == 13) return 35; // Home
if (stage < 9) {
int n = stage - 1;
if (type == 4) return (n & ~1) + 27; // Downpour/Mines/Mausoleum/Corpse
if (type == 5) return (n >> 1) * 2 + 28; // Dross/Ashpit/Gehenna
return (n >> 1) * 3 + type + 1;
}
if (stage == 9) return type == 4 ? 36 : 13; // Backwards / Blue Womb
if (stage == 12) return 26; // The Void
return (stage - 3) * 2 + type; // 10 -> 14/15, 11 -> 16/17
}
// =============================================================================================
// Spawns
// =============================================================================================
const Entry* PickEntry(const Spawn& s, float r) { // 0x82d290
float target = r * s.sumWeights, acc = 0;
for (uint8_t i = 0; i < (uint8_t)s.entries.size(); ++i) {
acc += s.entries[i].weight;
if (acc > target) return &s.entries[i];
}
const Entry& e = s.entries[0];
std::fprintf(stderr, "[warn] RoomConfig::Spawn::PickEntry did not terminate properly. Picking first entry: (%d, %d, %d, %f)\n",
(int)e.type, e.variant, e.subtype, (double)e.weight);
return &s.entries[0];
}
std::vector<PlannedSpawn> PlanSpawns(const Room& cfg, uint32_t spawnSeed, int w, const std::set<int>& skip) {
std::vector<PlannedSpawn> out;
RNG rng(spawnSeed, 11); // (2,7,7); both passes of Room::Init restart from the same seed
for (const Spawn& s : cfg.spawns) {
uint32_t seed = rng.Next(); // advanced even for spawns with no entries
float f = RNG::ToFloat(seed);
int idx = (s.x + 1) + (s.y + 1) * w;
if (s.entries.empty()) continue;
const Entry* e = PickEntry(s, f);
if (skip.count(idx)) continue;
PlannedSpawn p;
p.gridIndex = idx;
p.worldX = (float)((idx % w) * 40 + 40);
p.worldY = (float)((idx / w) * 40 + 120);
p.entry = e;
p.seed = seed;
p.isGrid = e->type >= 1000;
out.push_back(p);
}
return out;
}
} // namespace rooms
+109
View File
@@ -0,0 +1,109 @@
// RoomConfig: stage table (stages.xml), lazy .stb loading + mod merge, room selection, spawn picking.
// Reverse-engineered from isaac-ng.exe v1.9.7.17; addresses refer to that build.
#pragma once
#include "stb.hpp"
#include <array>
#include <functional>
#include <set>
namespace rooms {
// ---------------------------------------------------------------------------------------------
// RNG (0x7e8fe0 SetSeed, 0x7e90f0 Next, 0x7e9020 RandomInt, 0x7e9080 RandomFloat)
// xorshift32 with one of 81 shift triplets (table @0xb1f4c8).
// ---------------------------------------------------------------------------------------------
struct RNG {
uint32_t seed = 0, s1 = 0, s2 = 0, s3 = 0;
RNG() = default;
RNG(uint32_t seed, unsigned shiftIdx) { SetSeed(seed, shiftIdx); }
void SetSeed(uint32_t seed, unsigned shiftIdx);
uint32_t Next(); // ORIGINAL: seed == 0 logs "RNG Seed is zero!" and hits int3
uint32_t RandomInt(uint32_t n) { uint32_t x = Next(); return n ? x % n : 0; }
float RandomFloat() { return ToFloat(Next()); }
static float ToFloat(uint32_t x); // (float)(double)x * 2.3283062e-10f
};
extern const uint8_t kRngShifts[81][3];
// ---------------------------------------------------------------------------------------------
// Stage table
// ---------------------------------------------------------------------------------------------
constexpr int kNumStages = 37;
struct RoomConfigStage { // 0xc4, ctor 0x828f00
int id = 0; // +0x00
std::string name; // +0x04 "#BASEMENT_NAME" ('#' -> localised via "Stages")
std::string playerSpot; // +0x1c bossgfxroot + playerspot
std::string bossSpot; // +0x34 bossgfxroot + bossspot
std::string suffix; // +0x4c
RoomConfigMode modes[2]; // +0x64 [0] normal/hard, [1] greed/greedier
int music = 0; // +0xbc
int backdrop = 0; // +0xc0
};
// Resolves a game-relative path ("rooms/01.Basement.stb") to a readable file, or "" if absent.
// The game uses ModManager::ResolveContentPath (0x8f5ad0): enabled mods' resources-dlc3/<rel>,
// resources/<rel>, then the vanilla packed files.
using PathResolver = std::function<std::string(const std::string& rel)>;
// Returns the candidate mod room files for a rel path, in mod-list order (for each enabled mod:
// <mod>/content-dlc3/<rel> if it exists, else <mod>/content/<rel>) - see Mod::GetContentPath 0x8f99c0.
using ModRoomFiles = std::function<std::vector<std::string>(const std::string& rel)>;
struct RoomQuery { // GetRandomRoom / CollectRooms parameters
int type = 1;
int shape = 13; // 13 (ROOMSHAPE_NUM) = any
uint32_t minVariant = 0, maxVariant = 0xFFFFFFFFu; // unsigned compare
int minDifficulty = 0, maxDifficulty = 0; // signed compare
uint32_t requiredDoors = 0; // room must have ALL of these (superset ok)
int subtype = -1; // -1 = any
int mode = -1; // -1 = greed difficulty ? 1 : 0
};
struct GameState { // the bits of global Game state room selection reads
int levelStage = 1; // g+0 (12 = The Void)
int difficulty = 0; // g+0x269c8 (2/3 = greed/greedier)
bool seedEffect79 = false; // seed effect 79 active -> rooms flagged 0x80 (have 4500.0) excluded
bool curseOfTheGiant = false; // curse bit 0x80 -> 50% split-room path (NOT reimplemented)
};
class RoomConfig {
public:
std::array<RoomConfigStage, kNumStages> stages;
GameState* game = nullptr;
PathResolver resolve;
ModRoomFiles modRoomFiles;
bool LoadStagesXml(const std::string& path); // 0x82b2f0
bool LoadStageBinary(int stageId, int mode); // 0x82aa40 (+ ModManager::LoadModRooms 0x8f8040)
void ResetStageWeights(int stageId, int mode); // 0x82a9c0
Room* GetRoomByStageTypeAndVariant(int stageId, int type, int variant, int mode = -1); // 0x82c720
std::vector<Room*> CollectRooms(int stageId, const RoomQuery& q); // 0x82ce40
Room* GetRandomRoom(uint32_t seed, bool reduceWeight, int stageId, const RoomQuery& q); // 0x82c7d0
// 0x82cdd0: GetRandomRoom on stageId, retried on fallbackStageId if it returned NULL.
Room* GetRandomRoomWithFallback(uint32_t seed, bool reduceWeight, int stageId, int fallbackStageId, RoomQuery q);
int ResolveMode(int mode) const;
RoomConfigMode* Mode(int stageId, int mode); // resolves mode and lazily loads
};
// GetStageID 0x82d030: (LevelStage, StageType, mode) -> stb stage id.
int GetStageID(int levelStage, int stageType, int mode, int difficulty);
// ---------------------------------------------------------------------------------------------
// Spawns (Room::Init 0x7f2800, Spawn::PickEntry 0x82d290)
// ---------------------------------------------------------------------------------------------
const Entry* PickEntry(const Spawn& s, float r);
struct PlannedSpawn {
int gridIndex; // (x+1) + (y+1)*gridWidth
float worldX, worldY; // (idx % w)*40 + 40, (idx / w)*40 + 120
const Entry* entry;
uint32_t seed; // the RNG output used for the pick; passed on as the spawn seed
bool isGrid; // type >= 1000 -> grid entity, else Game::Spawn (970 spawns nothing)
};
// The real pass of Room::Init. gridWidth is the runtime room width INCLUDING walls (cfg width + 2).
// `skip` = RoomDescriptor+0x80 set of grid indices that must not be spawned (meaning unconfirmed).
std::vector<PlannedSpawn> PlanSpawns(const Room& cfg, uint32_t spawnSeed, int gridWidth,
const std::set<int>& skip = {});
} // namespace rooms
+223
View File
@@ -0,0 +1,223 @@
#include "stb.hpp"
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iterator>
namespace rooms {
// ---------------------------------------------------------------------------------------------
// 0x829a10. x/y are the door's stored coordinates. The 12 / 6 / 19 cases are the inner-corner walls
// of L-shaped rooms (9 LTL, 10 LTR, 11 LBL, 12 LBR).
// ---------------------------------------------------------------------------------------------
int GetDoorSlot(int x, int y, int shape) {
if ((x == -1 || x == 12) && y == 3) return LEFT0;
if ((x == -1 || x == 12) && y == 10) return LEFT1;
if (x == 6) {
if (y == -1) return UP0;
if (y == 14) return shape == 11 ? UP0 : DOWN0; // ORIGINAL: shape 11 returns UP0 here (unreachable with vanilla data)
if (y == 6) return shape == 9 ? UP0 : -1;
if (y == 7) return DOWN0;
return -1;
}
if (x == 19) {
if (y == -1) return UP1;
if (y == 14) return shape == 12 ? UP1 : DOWN1; // ORIGINAL: same oddity for shape 12
if (y == 6) return shape == 10 ? UP1 : -1;
if (y == 7) return DOWN1;
return -1;
}
if (x == 13 || x == 26) {
if (y == 3) return RIGHT0;
if (y == 10) return RIGHT1;
}
return -1;
}
// ---------------------------------------------------------------------------------------------
// 0x829290: sorted list of disjoint, non-adjacent [lo, hi] intervals.
// ---------------------------------------------------------------------------------------------
bool VariantRanges::Insert(uint32_t v) {
if (ranges.empty()) { ranges.push_back({v, v}); return true; }
size_t i = 0;
for (; i < ranges.size(); ++i) {
Range& n = ranges[i];
if (v < n.lo) break;
if (v <= n.hi) return false; // already covered
}
if (i == ranges.size()) { // past the last interval
Range& last = ranges.back();
if (v == last.hi + 1) last.hi = v;
else ranges.push_back({v, v});
return true;
}
Range& n = ranges[i];
Range* prev = i ? &ranges[i - 1] : nullptr;
if (v == n.lo - 1) {
if (prev && prev->hi + 1 == v) { prev->hi = n.hi; ranges.erase(ranges.begin() + i); } // bridge two ranges
else n.lo = v;
return true;
}
if (prev && prev->hi + 1 == v) { prev->hi = v; return true; }
ranges.insert(ranges.begin() + i, Range{v, v});
return true;
}
bool VariantRanges::Contains(uint32_t v) const {
for (const Range& r : ranges) { if (v < r.lo) return false; if (v <= r.hi) return true; }
return false;
}
// ---------------------------------------------------------------------------------------------
// Reader
// ---------------------------------------------------------------------------------------------
namespace {
struct Reader {
const uint8_t* p; const uint8_t* end;
// File::Read(buf, size, count). Short reads leave the destination untouched; the game never checks.
void read(void* dst, size_t n) {
size_t avail = (size_t)(end - p);
size_t take = n < avail ? n : avail;
std::memcpy(dst, p, take); p += take;
}
template <class T> T get(T init = T()) { T v = init; read(&v, sizeof v); return v; }
};
} // namespace
// RoomConfig::ReadRoom 0x82aea0
static void ReadRoom(Reader& r, int stageId, Room& room) {
room.stageId = stageId;
uint32_t type = r.get<uint32_t>();
uint32_t variant = r.get<uint32_t>();
uint32_t subtype = r.get<uint32_t>();
uint8_t difficulty = r.get<uint8_t>();
uint16_t nameLen = r.get<uint16_t>();
room.name.assign(nameLen, '\0');
if (nameLen) r.read(&room.name[0], nameLen);
float weight = r.get<float>();
uint8_t width = r.get<uint8_t>();
uint8_t height = r.get<uint8_t>();
uint8_t shape = r.get<uint8_t>();
room.type = (int)type;
room.originalVariant = (int)variant;
room.variant = (int)variant;
room.subtype = (int)subtype;
room.difficulty = difficulty;
room.initialWeight = weight;
room.weight = weight;
room.width = width;
room.height = height;
room.shape = shape;
room.flags = 0;
uint8_t doorCount = r.get<uint8_t>();
uint16_t spawnCount = r.get<uint16_t>();
for (unsigned i = 0; i < doorCount; ++i) {
int16_t x = r.get<int16_t>();
int16_t y = r.get<int16_t>();
uint8_t exists = r.get<uint8_t>();
if (!exists) continue; // disabled doors are simply not recorded
int slot = GetDoorSlot(x, y, room.shape);
if (slot >= 0) room.doors |= 1u << slot; // ORIGINAL: std::bitset<8>::set, slot >= 8 would throw
}
room.spawns.resize(spawnCount);
for (unsigned i = 0; i < spawnCount; ++i) {
Spawn& s = room.spawns[i];
s.x = (int16_t)r.get<uint16_t>();
s.y = (int16_t)r.get<uint16_t>();
uint8_t n = r.get<uint8_t>();
s.entries.resize(n);
for (unsigned k = 0; k < n; ++k) {
Entry& e = s.entries[k];
e.type = r.get<uint16_t>();
e.variant = r.get<uint16_t>();
e.subtype = r.get<uint16_t>();
e.weight = r.get<float>();
s.sumWeights += e.weight; // addss, file order
if (e.type == 970) {
if (e.variant == 2) { // 970.2 standing on a door tile marks that door
int slot = GetDoorSlot(s.x, s.y, room.shape);
if (slot >= 0) room.doorMask970 |= 1u << slot;
}
} else if (e.type == 4500 && e.variant == 0) {
room.flags |= FLAG_HAS_4500_0;
}
}
}
}
// The per-file part of RoomConfig::LoadStageBinary 0x82aa40 (path resolution and mod merging excluded).
bool ParseStb(const uint8_t* data, size_t size, int stageId, int mode, RoomConfigMode& m) {
Reader r{data, data + size};
m.rooms.clear(); m.variantsByType.clear(); m.loaded = false; // RoomConfigMode::Clear 0x828c00
char magic[4] = {0, 0, 0, 0};
r.read(magic, 4);
if (std::memcmp(magic, "STB1", 4) != 0) return false; // ORIGINAL: also leaks the open file handle
uint32_t count = r.get<uint32_t>();
if (count) std::fprintf(stderr, "allocate %u rooms.\n", count);
m.rooms.resize(count);
for (uint32_t i = 0; i < count; ++i) {
Room& room = m.rooms[i];
ReadRoom(r, stageId, room);
room.mode = mode;
m.variantsByType[room.type].Insert((uint32_t)room.variant);
// switch (stageId - 1) via byte table 0x82ae78
if (stageId >= 1 && stageId <= 3) {
if (room.variant == 603 || room.variant == 716) room.flags |= FLAG_STAGE1_3_VARIANT603_716;
} else if (stageId == 29 || stageId == 30) {
if (room.type == 1 && room.subtype == 31) room.flags |= FLAG_STAGE29_30_TYPE1_SUB31;
}
}
// ...then ModManager merges mod rooms for (stageId, mode) - see README.
m.loaded = true;
return true;
}
bool MergeModStb(const uint8_t* data, size_t size, int stageId, int mode, RoomConfigMode& m) {
Reader r{data, data + size};
char magic[4] = {0, 0, 0, 0};
r.read(magic, 4);
if (std::memcmp(magic, "STB1", 4) != 0) return false;
uint32_t n = r.get<uint32_t>();
if (n) std::fprintf(stderr, "reallocate %u rooms.\n", n); // logs the ADDED count
size_t old = m.rooms.size();
m.rooms.resize(old + n);
for (size_t i = old; i < m.rooms.size(); ++i) {
Room& room = m.rooms[i];
ReadRoom(r, stageId, room);
room.mode = mode;
// NB: the stage 1-3 / 29-30 flag fixups are NOT applied to mod rooms.
VariantRanges& vr = m.variantsByType[room.type];
uint32_t v = (uint32_t)room.variant;
if (!vr.Insert(v)) { // (type, variant) already taken -> remap; originalVariant keeps the file value
auto& rg = vr.ranges;
if (rg.size() > 1 && rg[1].lo + 2 == rg[0].hi) { // AS COMPILED @0x8f857d: never true for a sorted list
v = rg[1].lo + 1;
rg[0].hi = rg[1].hi;
rg.erase(rg.begin() + 1);
} else {
v = ++rg[0].hi; // extend the LOWEST interval; once it reaches the next interval this
// hands out variants that already exist (lookups then find the earlier room)
}
room.variant = (int)v;
}
}
return true;
}
bool LoadStb(const std::string& path, int stageId, int mode, RoomConfigMode& out) {
std::ifstream f(path, std::ios::binary);
if (!f) return false;
std::vector<uint8_t> buf((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
return ParseStb(buf.data(), buf.size(), stageId, mode, out);
}
} // namespace rooms
+113
View File
@@ -0,0 +1,113 @@
// Reimplementation of The Binding of Isaac: Repentance+ (isaac-ng.exe v1.9.7.17) room-config (.stb)
// loading. Addresses refer to that build (ImageBase 0x400000).
//
// Covered: the binary format and reader (RoomConfig::LoadStageBinary 0x82aa40, ReadRoom 0x82aea0),
// door-slot mapping (0x829a10), per-type variant index (0x828e50 / 0x829290), the stage-specific flag
// post-pass. See rooms.hpp for selection / spawn picking.
#pragma once
#include <cstdint>
#include <map>
#include <string>
#include <vector>
namespace rooms {
// ---------------------------------------------------------------------------------------------
// File format (little endian, no padding, no alignment):
//
// char magic[4] = "STB1" ("STB0" / anything else is rejected)
// u32 roomCount
// Room rooms[roomCount]:
// u32 type RoomType
// u32 variant
// u32 subtype
// u8 difficulty
// u16 nameLength; char name[nameLength] (no terminator)
// f32 weight
// u8 width interior tiles (13 for 1x1)
// u8 height (7 for 1x1)
// u8 shape RoomShape 1..12
// u8 doorCount
// u16 spawnCount
// Door doors[doorCount]: i16 x, i16 y, u8 exists
// Spawn spawns[spawnCount]:
// i16 x, i16 y grid coords inside the room (0,0 = top-left interior tile)
// u8 entryCount
// Entry entries[entryCount]: u16 type, u16 variant, u16 subtype, f32 weight
//
// The reader never checks Read() return values; a truncated file yields whatever the buffers held.
// ---------------------------------------------------------------------------------------------
enum DoorSlot : int { LEFT0 = 0, UP0 = 1, RIGHT0 = 2, DOWN0 = 3, LEFT1 = 4, UP1 = 5, RIGHT1 = 6, DOWN1 = 7 };
struct Entry { // 0xc
uint32_t type = 0; // +0x0 (read as u16, widened)
uint16_t variant = 0; // +0x4
uint16_t subtype = 0; // +0x6
float weight = 0; // +0x8
};
struct Spawn { // 0x10
int16_t x = 0, y = 0; // +0x0 +0x2
std::vector<Entry> entries; // +0x4 ptr, +0x8 u8 count
float sumWeights = 0; // +0xc float sum of entry weights, accumulated in file order
};
// Room flags at +0x4c, set at load time.
enum RoomFlags : uint32_t {
FLAG_STAGE29_30_TYPE1_SUB31 = 0x02, // stages 29/30: type 1 && subtype 31
FLAG_STAGE1_3_VARIANT603_716 = 0x04, // stages 1-3: variant 603 or 716
FLAG_HAS_4500_0 = 0x80, // a spawn contains entity 4500 variant 0 (as any entry)
};
struct Room { // RoomConfig_Room, 0x5c
int stageId = 0; // +0x00
int mode = 0; // +0x04 0 = normal, 1 = greed
int type = 0; // +0x08
int variant = 0; // +0x0c
int subtype = 0; // +0x10
std::string name; // +0x14
int difficulty = 0; // +0x2c
float initialWeight = 0; // +0x30 (Lua RoomConfigRoom.InitialWeight)
float weight = 0; // +0x34 current (Lua .Weight); reset from +0x30 on every stage (re)load
uint32_t doors = 0; // +0x38 bit per DoorSlot that "exists"
uint32_t doorMask970 = 0; // +0x3c bit per DoorSlot holding an entity 970 variant 2
std::vector<Spawn> spawns; // +0x40 / +0x44 (u16 count)
uint8_t width = 0; // +0x46
uint8_t height = 0; // +0x47
int shape = 0; // +0x48
uint32_t flags = 0; // +0x4c
int unk50 = 0, unk54 = 0; // +0x50 +0x54 zeroed by ctor 0x828b20
int originalVariant = 0; // +0x58
};
// Per-type list of variant intervals [lo, hi] (0x829290 merges adjacent / contained variants).
struct VariantRanges {
struct Range { uint32_t lo, hi; };
std::vector<Range> ranges; // original: singly linked list of {lo, hi, next}, sorted ascending
bool Insert(uint32_t v); // returns false if v was already covered
bool Contains(uint32_t v) const;
};
struct RoomConfigMode { // stage + 0x64 + mode*0x2c
std::string file; // +0x00 "rooms/01.basement.xml" (".xml" -> ".stb" at load)
std::vector<Room> rooms; // +0x18 / +0x1c
std::map<int, VariantRanges> variantsByType; // +0x20
bool loaded = false; // +0x28
};
// ModManager::LoadModRooms 0x8f8040, for ONE mod file: appends the file's rooms to `m`, remapping
// (type, variant) collisions exactly like the game (including its dead gap-filling branch).
// Returns false on a bad header (the game then stops merging ALL remaining mods for this stage).
bool MergeModStb(const uint8_t* data, size_t size, int stageId, int mode, RoomConfigMode& m);
// Door slot from a door's grid position, 0x829a10. -1 if not a door position.
// Coordinates are interior-relative: the left wall is x = -1, a 1x1 room's right wall is x = 13.
int GetDoorSlot(int x, int y, int shape);
// RoomConfig::ReadRoom 0x82aea0 + the per-room part of LoadStageBinary 0x82aa40.
// Returns false on a bad header. `log` receives KAGE-style messages.
bool LoadStb(const std::string& path, int stageId, int mode, RoomConfigMode& out);
bool ParseStb(const uint8_t* data, size_t size, int stageId, int mode, RoomConfigMode& out);
} // namespace rooms
+98
View File
@@ -0,0 +1,98 @@
// Build: g++ -std=c++17 -O2 -ffp-contract=off stb.cpp rooms.cpp test.cpp -o rooms_test
// Usage: ./rooms_test <resources dir containing stages.xml and rooms/>
#include "rooms.hpp"
#include <cstdio>
#include <cstring>
#include <dirent.h>
#include <strings.h>
using namespace rooms;
static int failures = 0;
#define CHECK(c) do { if (!(c)) { std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); ++failures; } } while (0)
// Case-insensitive path lookup (vanilla paths are "01.Basement", extracted dumps are lowercase).
static std::string FindCI(const std::string& root, const std::string& rel) {
std::string cur = root; size_t p = 0;
while (p <= rel.size()) {
size_t s = rel.find('/', p); if (s == std::string::npos) s = rel.size();
std::string part = rel.substr(p, s - p); p = s + 1;
if (part.empty()) continue;
DIR* d = opendir(cur.c_str()); if (!d) return "";
std::string hit;
while (dirent* e = readdir(d)) if (strcasecmp(e->d_name, part.c_str()) == 0) { hit = e->d_name; break; }
closedir(d);
if (hit.empty()) return "";
cur += "/" + hit;
}
return cur;
}
static void Put32(std::vector<uint8_t>& b, uint32_t v) { for (int i = 0; i < 4; ++i) b.push_back(uint8_t(v >> (8 * i))); }
static std::vector<uint8_t> MiniStb(std::vector<uint32_t> variants) {
std::vector<uint8_t> b = {'S', 'T', 'B', '1'}; Put32(b, (uint32_t)variants.size());
for (uint32_t v : variants) {
Put32(b, 1); Put32(b, v); Put32(b, 0); b.push_back(1);
b.push_back(0); b.push_back(0); // empty name
float w = 1.0f; uint32_t wb; std::memcpy(&wb, &w, 4); Put32(b, wb);
b.push_back(13); b.push_back(7); b.push_back(1); // 13x7, shape 1
b.push_back(0); b.push_back(0); b.push_back(0); // 0 doors, 0 spawns
}
return b;
}
int main(int argc, char** argv) {
// Door slots
CHECK(GetDoorSlot(-1, 3, 1) == LEFT0 && GetDoorSlot(13, 3, 1) == RIGHT0 && GetDoorSlot(6, -1, 1) == UP0 && GetDoorSlot(6, 7, 1) == DOWN0);
CHECK(GetDoorSlot(12, 3, 9) == LEFT0 && GetDoorSlot(6, 6, 9) == UP0 && GetDoorSlot(6, 6, 1) == -1);
// RNG
RNG r(1, 0); uint32_t x = 1; x ^= x >> 1; x ^= x << 3; x ^= x >> 10; CHECK(r.Next() == x);
CHECK(RNG::ToFloat(0xFFFFFFFFu) < 1.0f);
// Stage IDs
CHECK(GetStageID(1, 0, -1, 0) == 1 && GetStageID(2, 1, -1, 0) == 2 && GetStageID(3, 2, -1, 0) == 6);
CHECK(GetStageID(1, 4, -1, 0) == 27 && GetStageID(3, 4, -1, 0) == 29 && GetStageID(5, 5, -1, 0) == 32);
CHECK(GetStageID(9, 0, -1, 0) == 13 && GetStageID(12, 0, -1, 0) == 26 && GetStageID(11, 1, -1, 0) == 17);
// Mod merge collision remapping: vanilla type-1 variants {0..5, 7..9}
{
RoomConfigMode m;
auto v = MiniStb({0, 1, 2, 3, 4, 5, 7, 8, 9});
CHECK(ParseStb(v.data(), v.size(), 1, 0, m));
auto mod = MiniStb({3, 3, 3, 100});
CHECK(MergeModStb(mod.data(), mod.size(), 1, 0, m));
CHECK(m.rooms.size() == 13);
CHECK(m.rooms[9].variant == 6 && m.rooms[10].variant == 7 && m.rooms[11].variant == 8); // 7, 8 duplicate vanilla
CHECK(m.rooms[9].originalVariant == 3 && m.rooms[12].variant == 100);
}
if (argc > 1) {
std::string res = argv[1];
RoomConfig rc;
GameState gs; rc.game = &gs;
rc.resolve = [&](const std::string& rel) { return FindCI(res, rel); };
CHECK(rc.LoadStagesXml(FindCI(res, "stages.xml")));
CHECK(rc.stages[1].modes[0].file == "rooms/01.Basement.xml");
size_t total = 0;
for (int s = 0; s < kNumStages; ++s)
for (int m = 0; m < 2; ++m)
if (rc.LoadStageBinary(s, m)) total += rc.stages[s].modes[m].rooms.size();
std::printf("loaded %zu rooms\n", total);
RoomQuery q; q.type = 1; q.shape = 1; q.minDifficulty = 0; q.maxDifficulty = 15;
q.requiredDoors = (1u << LEFT0) | (1u << RIGHT0);
Room* room = rc.GetRandomRoom(0x12345678u, true, 1, q);
CHECK(room != nullptr);
if (room) {
std::printf("picked basement room %d.%d '%s' diff=%d doors=0x%x weight now %g (initial %g)\n",
room->type, room->variant, room->name.c_str(), room->difficulty, room->doors, room->weight, room->initialWeight);
for (auto& p : PlanSpawns(*room, 0xCAFEBABEu, room->width + 2))
std::printf(" grid %3d (%4.0f,%4.0f) %s %u.%u.%u\n", p.gridIndex, p.worldX, p.worldY,
p.isGrid ? "grid " : "entity", p.entry->type, p.entry->variant, p.entry->subtype);
}
Room* boss = rc.GetRoomByStageTypeAndVariant(0, 5, 1010);
if (boss) std::printf("special rooms type 5 (boss) variant 1010: '%s'\n", boss->name.c_str());
}
std::printf("%s (%d failures)\n", failures ? "FAILED" : "all checks passed", failures);
return failures != 0;
}