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

+635
View File
@@ -0,0 +1,635 @@
# AnmCache + ANM2 (Sprite) lifecycle — isaac-ng.exe (Repentance+ 1.9.7.17)
All addresses are VA (ImageBase 0x400000). "Confirmed" means read directly from asm; "guess" marks naming/semantics
I inferred but did not prove. The XML parser itself (0x40ed50) is out of scope; only its interface is given.
Note: several labels in labels.json are misleading. `lua_Load`, `lua_Reload`, `lua_Reset`, `lua_ReplaceSpritesheet`,
`lua_LoadGraphics` are **native ANM2 member functions**. The Sprite Lua table (0x867200..) points straight at them, and they
have hundreds of native callers (Load 0x40bd50 has 369 call sites).
---------------------------------------------------------------------------------------------------------------------
## 0. Helpers referenced
| addr | meaning |
|---|---|
| 0xa159d0 | `uint32 HashPath(const char* s /*ecx*/)`: djb2, case-folded and slash-normalised (below) |
| 0xa68490 | `uint64 GetTimeNs()` = QPC / QPF * 1e9 (constant at 0xbaa8b0 = 1e9) |
| 0xa16060 | `std::vector<const char*> FileSystem::GetMountPrefixes()` (below) |
| 0xa17180 | `char* FileSystem::ResolvePath(const char*)` (this = 0xc379e0). Returns a heap string or NULL |
| 0x40ccd0 | `std::string::assign(const char*, size_t)` |
| 0x40cf50 | `std::string` copy-ctor |
| 0x40d040 | `std::string` dtor (0x40bf20 is a jmp thunk to it) |
| 0x40cae0 | `bool StrEqual(const char* a/*ecx*/, size_t la/*edx*/, const char* b, size_t lb)` |
| 0xa0f4e0 | tracked `operator new(size /*ecx*/)` |
| 0xa648b0 | tracked alloc/free: `fastcall(bool isFree /*cl*/, void* p /*edx*/, size_t sz, int 0)` |
| 0xaef5c4 / 0xaef638 | MSVC `eh vector constructor iterator` / `eh vector destructor iterator` |
| 0xaef15c | sized `operator delete(p, size)` |
| 0x416490 | `std::map<uint32,..>::_Find_lower_bound` for g_AnmCache.files |
| 0x416440 | same, for g_AnmCache.textures |
| 0x414500 | `files.operator[](key)`: returns `&node->value` (node+0x14). Calls try_emplace 0x4158b0 |
| 0x414440 | `textures.operator[](key)` |
| 0x415d20 / 0x414d60 | `files.erase(node)` / `textures.erase(it)` |
| 0x414a80 | map iterator `operator++` |
**Tracked free.** Every block has its size at `p-4`. Freeing does
`MemStats* s = g_memStats(0xc7de78) ? g_memStats+0x30 : &g_fallbackStat(0xc7f618); s->bytes(u64) -= *(u32*)(p-4); free(p-4);`.
```cpp
uint32 HashPath(const char* s) { // 0xa159d0
if (!s) return 0;
uint32 h = 5381;
for (; *s; ++s) {
uint8 c = *s;
if ((uint8)(c - 'A') <= 25) c += 0x20; // tolower (ASCII only)
if (c == '\\') c = '/';
h = h * 33 + c;
}
return h;
}
std::vector<const char*> FileSystem::GetMountPrefixes() { // 0xa16060 (static, sret)
std::vector<const char*> v;
// g_FileSystem(0xc379e0)+8 : std::vector<Mount*> mounts (begin 0xc379e8, end 0xc379ec)
for (int i = mounts.size() - 1; i >= 0; --i) { // NOTE: reverse order (last-mounted first)
strncmp(mounts[i]->name, "", 0); // dead call, result ignored (literal in binary)
v.push_back(mounts[i]->name /* Mount+0xc, const char* */);
}
return v;
}
```
---------------------------------------------------------------------------------------------------------------------
## 1. AnmCache
### 1.1 Globals (one static "AnmCache" object, dtor at 0x40d240, static init 0x401140)
| addr | type | name |
|---|---|---|
| 0xc78ee0 | `std::map<uint32, AnmCacheEntry>` (`_Myhead` @0xc78ee0, `_Mysize` @0xc78ee4) | `g_AnmCache.files` |
| 0xc78ee8 | `std::map<uint32, TexturePtr>` (head/size; node size 0x1c) | `g_AnmCache.textures` |
| 0xc798b8 | `std::vector<const char*>` (begin/end/cap @ b8/bc/c0) | `s_mountPrefixes` (filled lazily) |
| 0xc79c40 | `uint64` | `s_totalAnm2LoadMs` |
| 0xc78da4 | `std::vector<ANM2*>` (begin/end/cap @ a4/a8/ac) | heap-sprite pool, deleted in ~AnmCache. One push site at 0x960c97, which also stores to 0xc72214 |
The map comparator is plain `uint32 <`. MSVC tree node: left@0, parent@4, right@8, color@0xc, isnil@0xd, value@0x10.
### 1.2 `files` node layout (node size 0x54, confirmed by try_emplace 0x4158b0 init and erase `delete(node,0x54)`)
```
node+0x10 uint32 key // HashPath(prefix + path)
node+0x14 AnmFileData data (0x3c bytes) ─┐
node+0x50 int refCount ─┘ value = {data, refCount} (0x40 bytes)
```
`AnmFileData` (offsets relative to data = node+0x14; ANM2 copy targets in the right column):
| off | type | meaning | copied to ANM2 |
|---|---|---|---|
| +0x00 | bool | `needsReload`(?) flag. try_emplace and ParseAnm2 only ever write 0. Load re-parses if it is set and the file resolves. I never saw it set to 1 (**uncertain**) | – |
| +0x04 | LayerInfo* (count-prefixed new[], stride 0x38) | layers | ANM2 builds LayerState[] from it |
| +0x08 | uint | layerCount | +0x80 |
| +0x0c | AnimationData* (new[], stride 0x13c) | animations | +0x74 |
| +0x10 | uint | animationCount | +0x78 |
| +0x14 | std::string* (new[], stride 0x18) | null names | +0x84 |
| +0x18 | uint | nullCount | +0x88 |
| +0x1c | std::string* (new[], stride 0x18) | event names | +0x8c |
| +0x20 | uint | eventCount | +0x90 |
| +0x24 | std::string | default animation name | +0x18 (assign) |
`LayerInfo` (0x38). Its dtor 0x40db70 destroys strings at +8 and +0x20.
`+0x00 int`, `+0x04 int` (probably layerId and spritesheetId; the parser agent should confirm), `+0x08 std::string name`,
`+0x20 std::string spritesheetPath` (fully resolved image path that LayerState copies).
`AnimationData` (0x13c) begins with `+0x00 std::string name`. Its new[] dtor is just the string dtor. Other fields are as
in CONTEXT.md (+0x18 layerAnims, +0x1c count, +0x20 nullAnims, +0x24 count, +0x28 triggers, +0x2c count, +0x30
FrameNum, +0x34 Loop, +0x38 int layerIdToLayerAnimIdx[]).
### 1.3 Cache key: how a path is looked up (identical loop in Load / AddRef / RemoveRef / Preload / texture Has / Release)
```cpp
static bool FindEntry(const char* path, Node*& out, uint32& keyOut) {
if (s_mountPrefixes.size() < 1) // lazy init
s_mountPrefixes = FileSystem::GetMountPrefixes(); // move-assign (0x4149d0 = vector dtor)
out = files.head; keyOut = 0;
for (const char* prefix : s_mountPrefixes) {
char buf[256];
strncpy_s(buf, 256, prefix, 256);
strcat_s (buf, 256, path);
keyOut = HashPath(buf);
Node* n = files.lower_bound(keyOut);
out = (n != head && !(keyOut < n->key)) ? n : head;
if (out != head) break; // first prefix that hits wins
}
return out != head;
}
```
- The key is **djb2(lowercase, '\\'→'/', mountPrefix + path)**. Nothing is appended.
- If nothing matches, `keyOut` is the hash for the **last** prefix tried. That is mount[0], the first-mounted one,
because GetMountPrefixes reverses the list. That is the key a newly parsed file is stored under.
- If there are no mounts at all, keyOut stays 0. ParseAnm2 then substitutes HashPath(path), but Load re-looks up key 0,
so Load reports "failed to load" (edge case, faithful).
### 1.4 `void AnmCache::Load(const std::string& path, ANM2* spr)` — 0x40db90
Static. Args are on the stack (`ret 8`) and ecx is unused. Callers: ANM2::Load 0x40bd83, ANM2::Reload 0x40beab.
```cpp
void AnmCache::Load(const std::string& path, ANM2* spr) {
if (path.size() == 0) return; // no timing either
uint64 t0ms = GetTimeNs() / 1000000;
Node* n; uint32 key;
FindEntry(path.c_str(), n, key);
char* resolved = FileSystem::ResolvePath(&g_FileSystem /*0xc379e0*/, path.c_str());
if (n == files.head || (n->data.needsReload && resolved != nullptr)) {
ParseAnm2(&files, path, key); // 0x40ed50, see 1.10
n = files.lower_bound(key); if (n == head || key < n->key) n = head;
}
if (resolved) TrackedFree(resolved);
if (n == files.head) {
KAGE_LogMessage(1, "AnmCache failed to load %s\n", path.c_str());
} else {
AnmFileData& d = n->data;
// --- rebuild per-layer runtime state ---
if (spr->layerStates) delete[] spr->layerStates; // eh-vector-dtor, LayerState::~LayerState 0x407a60
uint cnt = d.layerCount;
if (cnt) {
spr->layerStates = new LayerState[cnt]; // operator new(cnt*0xa0+4) 0xa0f4e0, count prefix,
// ctor 0x4081d0 per element
for (uint i = 0; i < d.layerCount; ++i) {
spr->layerStates[i].Init(&d.layers[i]); // 0x408310
spr->layerStates[i].owner = spr; // +4
}
cnt = d.layerCount;
}
// QUIRK: if cnt==0, layerStates was deleted but NOT nulled (dangling, would double-free on Reset).
spr->layerCount = cnt; // +0x80
spr->animations = d.animations; // +0x74 (shared, not copied!)
spr->animCount = d.animationCount; // +0x78
spr->nullNames = d.nullNames; // +0x84
spr->nullCount = d.nullCount; // +0x88
spr->eventNames = d.eventNames; // +0x8c
spr->eventCount = d.eventCount; // +0x90
if (&spr->defaultAnimation != &d.defaultAnimation)
spr->defaultAnimation.assign(d.defaultAnimation); // +0x18
}
uint64 t1ms = GetTimeNs() / 1000000;
s_totalAnm2LoadMs += t1ms - t0ms; // 0xc79c40 (timing covers cache hits too)
}
```
The sprite only borrows pointers into the cache entry. The refCount (AddRef/RemoveRef) is what keeps an entry alive
through `Clear()`.
### 1.5 `void AnmCache::AddRef(const std::string& path)` — 0x40e110 (static, `ret 4`)
```cpp
if (FindEntry(path.c_str(), n, key)) ++n->refCount; // node+0x50
else KAGE_LogMessage(1, "[warn] AnmCache: cannot add reference to %s\n", path.c_str());
```
Callers: ANM2 copy-ctor (0x407866), ANM2::Load, ANM2::Reload.
### 1.6 `void AnmCache::RemoveRef(const std::string& path)` — 0x40e2b0 (static, `ret 4`)
```cpp
if (FindEntry(path.c_str(), n, key)) {
if (n->refCount == 0) KAGE_LogMessage(0x10, "cannot remove reference at RefCount 0\n"); // level 0x10 = error/assert
if (n->refCount != 0) --n->refCount;
} else KAGE_LogMessage(1, "[warn] AnmCache: cannot remove reference to %s\n", path.c_str());
```
Callers: ANM2::Reset 0x407f3d, ANM2::Load 0x40bd60, plus 5 others elsewhere.
### 1.7 `void AnmCache::Clear()` — 0x40e470 (static)
Removes only unreferenced entries:
```cpp
for (it = files.begin(); it != files.end(); ) {
if (it->refCount == 0) {
KAGE_LogMessage(1, "AnmCache: Clear %u.\n", it->key);
it->data.Clear(); // 0x40d850
Node* victim = it; ++it;
files.erase(victim); // 0x415d20, then ~string(node+0x38), delete(node,0x54)
} else ++it;
}
```
Callers: 0x68fd57, 0x8f8c6f, 0x9b248f (level/stage transitions; not identified further).
### 1.8 `void AnmFileData::Clear()` — 0x40d850 (thiscall, this = node+0x14)
```cpp
delete[] layers; layers = nullptr; layerCount = 0; // eh-vec-dtor 0x40db70, size cnt*0x38+4
for (uint a = 0; a < animationCount; ++a) {
AnimationData& A = animations[a];
for (uint i = 0; i < A.layerAnimCount; ++i) TrackedFree(A.layerAnims[i].frames); // +4
delete[] A.layerAnims; // stride 0x10, trivial dtor 0x40c200
for (uint i = 0; i < A.nullAnimCount; ++i) TrackedFree(A.nullAnims[i].frames); // +8
delete[] A.nullAnims;
TrackedFree(A.triggers); // +0x28
}
delete[] animations; animations = nullptr; animationCount = 0; // dtor = ~string(name)
delete[] nullNames; nullNames = nullptr; nullCount = 0;
delete[] eventNames; eventNames = nullptr; eventCount = 0;
// needsReload (+0) and defaultAnimation (+0x24) are NOT touched here
```
### 1.9 `void AnmCache::LogMemoryUsage()` — 0x40d4c0 (static)
Called once, from the stats dump 0x6f4170. That routine is called from 0x9b7680. Just before the call it logs
`"Total entity spawn time: %llu ms"` and `"Total ANM2 loading time: " << s_totalAnm2LoadMs << " ms"` (0x6f4257) through an
ostringstream.
```cpp
uint32 bytes = 0, entries = 0;
for (auto& [key, v] : files) {
const AnmFileData& d = v.data;
bytes += d.animationCount * 0x13c;
for (uint a = 0; a < d.animationCount; ++a) {
const AnimationData& A = d.animations[a];
bytes += A.layerAnimCount * 0x10;
for (i) bytes += A.layerAnims[i].frameCount * 0x6c; // LayerAnimation+8
bytes += A.nullAnimCount * 0x10;
for (i) bytes += A.nullAnims[i].frameCount * 0x54; // NullAnimation+0xc
bytes += A.triggerCount * 8;
}
bytes += (d.nullCount + d.eventCount) * 0x18 + d.layerCount * 0x38 + 0x40; // 0x40 = sizeof(value)
++entries;
}
KAGE_LogMessage(1, "AnmCache memory usage: %u bytes in %u entries.\n", bytes, entries);
```
(The asm is an SSE4.1 `pmulld` vectorisation of these loops. Sums are 32-bit.)
### 1.10 `ParseAnm2` interface — 0x40ed50 (decompiled by the other agent)
`void __thiscall AnmCache::ParseFile(std::map<uint32,AnmCacheEntry>* files /*=0xc78ee0*/, const std::string& path, uint32 key)`, `ret 8`.
- It first resolves `path` through `(*(Game**)0xc7169c)+0x2a6c0 -> 0x8f5ad0(&tmpStr, path)` (probably mod-override path
resolution) and opens it with `FileSystem(0xc37a10)::Open(0xa178d0)(resolved, 0)`. On failure it logs
`"ERROR Could not open %s\n"` and returns **without creating an entry**.
- `if (key == 0) key = HashPath(path.c_str());`
- `AnmFileData* d = &files[key]` (operator[] 0x414500, which creates the node with refCount 0). Then `d->Clear(); d->needsReload = 0;`
- It reads the whole file through the file vtable (+4 size, +0x14 read, +0 close/delete) into a NUL-terminated buffer
and runs rapidxml. Then it fills d->layers/+0x8 (0x40f4eb), nulls +0x14/+0x18 (0x40f7fe), events +0x1c/+0x20
(0x40fb2e), defaultAnimation +0x24 (0x40fbf4), animations +0xc/+0x10 (0x4139de).
- On a re-parse (reload) the refCount is kept, because operator[] returns the existing node.
### 1.11 Preload — `void AnmCache::Preload(const char* path)` — 0x40ea50 (static, `ret 4`)
Called from the entity-config preloader 0x69ba90 (with the entity's anm2 path at config+0x74). The same routine logs
"Preload sound %d." for sounds.
```cpp
if (!*path) return;
uint32 key; Node* n;
if (!FindEntry(path, n, key)) {
ParseFile(&files, std::string(path), key);
if (!FindEntry-by-key(key, n)) return; // plain lower_bound with the same key
}
for (uint i = 0; i < n->data.layerCount; ++i) {
const char* img = n->data.layers[i].spritesheetPath.c_str(); // LayerInfo+0x20
if (!TextureCache::Has(img)) {
Graphics_Prepare(*(void**)0xc71678); // 0x6fd350, unidentified (context/manager getter)
TexturePtr t = LoadImage(img); // 0x9588a0(&out, path)
TextureCache::Add(t); // 0x40e520
}
}
// refCount is NOT incremented by preload
```
### 1.12 Texture side of the cache (`textures` map @0xc78ee8; node: key@0x10, TexturePtr@0x14 {obj,ctrl})
- `bool TextureCache::Has(const char* name)`, 0x40e5d0: FindEntry-style prefix loop, but on `textures`.
- `void TextureCache::Add(TexturePtr t /*by value, 8 bytes*/)`, 0x40e520, `ret 8`:
`if (t) { const char* nm = t->name44 ? t->name44 : (t->name40 ? t->name40 : "unknown"); textures[HashPath(nm)] = t; }`, then releases the by-value arg.
The key here has **no prefix**, so the texture's own name (+0x44) must already contain the mount prefix for Has/Release to match. (Guess.)
- `void TextureCache::Release(const char* name)`, 0x40e740: finds the entry with the prefix loop. If found and
`ctrl==NULL || useCount(u16 @ctrl+4) <= 2` (read under the ctrl+8 lock, vfuncs +0xc lock(-1) / +0x10 unlock), it resets the
pointer (0x40c7f0(0)) and erases the entry.
- `void TextureCache::Purge()`, 0x40e910: the same `<= 2` rule applied to every texture entry. 14 callers.
- `void TextureCache::Preload(const char* name)`, 0x40ea10: `if (!Has(name)) Add(LoadImage(name));`
`TexturePtr` is a KAGE intrusive/shared smart pointer `{T* obj; RefCtrl* ctrl}`. The ctrl vtable has +4 = TryAddRef,
returning bool, and +0xc = Release, returning true when the object dies. When Release returns true, the global deleter
hook `(*(void(**)(TexturePtr*))0xc7163c)(&sp)` is called. Helpers: copy-ctor 0x40c550, assign 0x40c3b0, dtor 0x40c440,
`reset(raw)` 0x40c7f0 / ctor-from-raw 0x40c4a0 (both allocate a new 0x18-byte ctrl block with vtable 0xb1a6e0).
### 1.13 `AnmCache::~AnmCache()` — 0x40d240 (this = 0xc78ee0; called from 0x9ab8db and the atexit thunk 0xb1522e)
1. For each `ANM2*` in the pool vector 0xc78da4: inlined `~ANM2` (Reset, free the 4 AnimationState arrays, 2 strings), then `delete(p, 0x114)`. Then the pool is cleared.
2. `data.Clear()` for **every** file entry, with no refcount check. Then the tree is destroyed (0x415ae0) and the head is reset.
3. Every texture pointer is released, the tree is destroyed (0x415800) and the head is reset.
---------------------------------------------------------------------------------------------------------------------
## 2. ANM2 (Sprite) — object layout, sizeof = 0x114
The size is confirmed by `operator=(ANM2)` using `ret 0x114` (by-value param) and by `delete(p, 0x114)` in 0x40d240.
| off | type | field | init (ctor+Reset) | source / evidence |
|---|---|---|---|---|
| 0x000 | std::string | filename | "" | Load assigns it. AddRef/RemoveRef receive `this` as `const std::string&`. GetFilename 0x4312e0 copies it |
| 0x018 | std::string | defaultAnimation | "" | GetDefaultAnimationName/GetDefaultAnimation 0x4a5cf0 returns &+0x18 |
| 0x030 | AnimationState (0x20) | main | owner=this | |
| 0x050 | AnimationState (0x20) | overlay | owner=this | RemoveOverlay 0x40ac60 = `overlay.SetAnimationData(nullptr)` |
| 0x070 | bool | overlayRenderFirst | 0 | SetOverlayRenderPriority 0x431300. Render 0x40a0d0 draws the overlay before main if set |
| 0x074 | AnimationData* | animations (borrowed from cache) | 0 | |
| 0x078 | uint | animationCount | 0 | PlayRandom uses `rand % +0x78` |
| 0x07c | LayerState* | layerStates (count-prefixed new[], stride 0xa0) | 0 | |
| 0x080 | uint | layerCount | 0 | GetLayerCount 0x440e40 |
| 0x084 | std::string* | nullNames (borrowed) | 0 | |
| 0x088 | uint | nullCount | 0 | |
| 0x08c | std::string* | eventNames (borrowed) | 0 | |
| 0x090 | uint | eventCount | 0 | |
| 0x094 | Vector (2 floats) | Offset | Vector::Zero (0xc7b640) | Lua Offset: get 0x49cb40 (`&+0x94`), set 0x456340 |
| 0x09c | Vector | Scale | Vector::One (0xc3793c) | Lua Scale: get 0x417200, set 0x420170 |
| 0x0a4 | float | Rotation | 0 | Lua Rotation: get 0x417210, set 0x43ee80 |
| 0x0a8 | ColorMod (0x2c: Tint RGBA, Colorize RGBA, Offset RGB) | Color | {1,1,1,1, 0,0,0,0, 0,0,0} | Lua Color: get 0x407410, set 0x4073d0 |
| 0x0d4 | ColorMod-shaped (0x2c) | **unknown** (second colour) | Reset: {1,1,1,**0**, 0,0,0,0, 0,0,0} (ctor writes alpha 1.0, then Reset overwrites it with 0) | copied/swapped like Color. Not exposed to Lua and not read in 0x409120..0x40a0d0 (**uncertain**) |
| 0x100 | bool | FlipX | 0 | get 0x407420 / set 0x435c60 |
| 0x101 | bool | FlipY | 0 | get 0x407430 / set 0x505b50 |
| 0x104 | float | PlaybackSpeed | 1.0 | get 0x456360 / set 0x440e50 |
| 0x108 | bool | **unknown** | 0 | only copied/swapped/reset in this module |
| 0x109 | bool | loaded | 0 | IsLoaded 0x420160. Render returns early if 0 |
| 0x10c | int | shadowLayerIndex | -1 | set by Load to the layer named exactly "shadow" (last match wins) |
| 0x110 | uint32 | renderFlags | 0 | OR-ed with LayerState+0x8c at render time (0x4091eb, 0x409a63, 0x409cc0). Load sets 0x400 if any layer name starts with '*' and 0x800 if any null name starts with '*'. At render, bit 4 means "draw only if debug global 0xc7977e", bit 2 is some crop/clip path |
### 2.1 AnimationState (0x20) — confirmed
```
+0x00 ANM2* owner
+0x04 AnimationData* anim
+0x08 int* layerFrameIdx (anim->layerAnimCount entries)
+0x0c int* nullFrameIdx (anim->nullAnimCount entries)
+0x10 float frame (-1.0f after SetAnimationData)
+0x14 bool playing
+0x18 u32 eventsThisUpdate
+0x1c u32 eventsSinceStart
```
### 2.2 LayerState (0xa0) — per layer, in ANM2+0x7c
| off | type | field (name = guess unless noted) | Init(LayerInfo*) 0x408310 value |
|---|---|---|---|
| 0x00 | const LayerInfo* | info (cache-owned; name = info+8) | arg |
| 0x04 | ANM2* | owner (set by the creator) | – |
| 0x08 | std::string | spritesheetPath (confirmed; ReplaceSpritesheet edits it) | info ? info->spritesheetPath(+0x20) : "" |
| 0x20 | u32 x4 | texture sampler/wrap params (two pairs pushed to the texture through vfunc +0x44 and +0x48 in GetTexture) | copy of globals 0xc3799c..0xc379a8 |
| 0x30 | bool | graphicsLoaded (confirmed: LoadGraphics skips if set, ReplaceSpritesheet clears it) | 0 (the dword write clears 0x30..0x33) |
| 0x31 | bool | cleared by LoadGraphics (dirty flag?) | 0 |
| 0x32,0x33 | bool | copied only (flipX/flipY?) | 0 |
| 0x34 | Vector | size/scale | Vector::One |
| 0x3c | float | rotation | 0 |
| 0x40 | Vector | position/offset | Vector::Zero |
| 0x48 | ColorMod (0x2c) | color | default ColorMod |
| 0x74 | bool | visible | 1 |
| 0x78 | int | blend: mode/flags | 0 |
| 0x7c | int | blend: RGB src factor | `(g_0xc798e4 & 4) ? 1 : 6` (ONE if premultiplied, else SRC_ALPHA) |
| 0x80 | int | blend: RGB dst factor | 7 (ONE_MINUS_SRC_ALPHA) |
| 0x84 | int | blend: alpha src | 1 |
| 0x88 | int | blend: alpha dst | 7 |
| 0x8c | u32 | renderFlags (OR-ed with ANM2+0x110). '*'-prefixed layers get `|= 5` | 0 |
| 0x90 | Vector | crop offset? | Vector::Zero |
| 0x98 | TexturePtr {obj @0x98, ctrl @0x9c} | spritesheet texture (confirmed) | reset(nullptr) |
LayerState functions:
- ctor 0x4081d0: zeroes the string and the fields listed, uses the same defaults, then `Init(nullptr)`.
- dtor 0x407a60: releases the TexturePtr at +0x98 and destroys the string at +8. It does **not** call TextureCache::Release.
- `TexturePtr GetTexture() const`, 0x408590 (sret): if a texture is present, it pushes +0x20/+0x24 to `tex->vfunc[0x44]`
when they differ from tex+0x30/+0x34, and +0x28/+0x2c to `tex->vfunc[0x48]` when they differ from tex+0x38/+0x3c. Then it
returns a copy.
- `void SetTexture(TexturePtr t /*by value*/)`, 0x408640: `if (t) memcpy(&+0x20, t.obj+0x30, 16); texture = t;`
---------------------------------------------------------------------------------------------------------------------
## 3. ANM2 lifecycle — pseudocode
### 3.1 ctor `ANM2::ANM2()` — 0x4074c0 (170 callers)
```cpp
ANM2::ANM2() {
filename = ""; defaultAnimation = "";
main.owner = this; main.layerFrameIdx = main.nullFrameIdx = nullptr; main.SetAnimationData(nullptr);
overlay.owner = this; overlay.layerFrameIdx = overlay.nullFrameIdx = nullptr; overlay.SetAnimationData(nullptr);
offset = {0,0}; /* +0x94/+0x98 */ scale(+0x9c/+0xa0) = {0,0}; // overwritten by Reset
color(+0xa8) = ColorMod{1,1,1,1, 0,0,0,0, 0,0,0};
color2(+0xd4) = ColorMod{1,1,1,1, 0,0,0,0, 0,0,0};
layerStates = nullptr; // +0x7c
Reset(); // 0x407f10 sets the real defaults
}
```
### 3.2 `void ANM2::Reset()` — 0x407f10 (Lua `Sprite:Reset`, also used by the dtor and operator=)
```cpp
void ANM2::Reset() {
if (filename.size()) AnmCache::RemoveRef(filename);
filename.clear();
main.SetAnimationData(nullptr);
overlay.SetAnimationData(nullptr);
defaultAnimation.clear();
animations = nullptr; animationCount = 0;
delete[] layerStates; layerStates = nullptr; layerCount = 0; // ~LayerState each
nullNames = nullptr; nullCount = 0; eventNames = nullptr; eventCount = 0;
offset = Vector::Zero; // 0xc7b640
scale = Vector::One; // 0xc3793c
rotation = 0.0f;
color = ColorMod{1,1,1,1, 0,0,0,0, 0,0,0};
color2 = ColorMod{1,1,1,0, 0,0,0,0, 0,0,0}; // note alpha 0 (literal)
flipX = flipY = false; // word write at +0x100
playbackSpeed = 1.0f;
unk108 = false; loaded = false; // word write at +0x108
overlayRenderFirst = false; // +0x70
shadowLayerIndex = -1;
renderFlags = 0;
}
```
### 3.3 dtor `ANM2::~ANM2()` — 0x408170 (also used by many EH unwind funclets)
```cpp
ANM2::~ANM2() { Reset(); overlay.~AnimationState(); main.~AnimationState(); defaultAnimation.~string(); filename.~string(); }
```
### 3.4 copy-ctor `ANM2::ANM2(const ANM2& o)` — 0x407690 (`ret 4`, 40 callers)
```cpp
ANM2::ANM2(const ANM2& o)
: filename(o.filename), defaultAnimation(o.defaultAnimation),
main(this, o.main), overlay(this, o.overlay) // AnimationState copy 0x4086e0
{
overlayRenderFirst = o.overlayRenderFirst;
animations = o.animations; animationCount = o.animationCount;
layerStates = nullptr;
layerCount = o.layerCount; nullNames = o.nullNames; nullCount = o.nullCount;
eventNames = o.eventNames; eventCount = o.eventCount;
offset = {0,0}; // QUIRK: Offset is NOT copied (literal zero stores at 0x407767/0x407771)
scale = o.scale; rotation = o.rotation;
color = o.color; color2 = o.color2;
flipX = o.flipX; flipY = o.flipY; playbackSpeed = o.playbackSpeed;
unk108 = o.unk108; loaded = o.loaded; shadowLayerIndex = o.shadowLayerIndex;
renderFlags = 0; // QUIRK: not copied
if (loaded) AnmCache::AddRef(filename);
layerStates = new LayerState[o.layerCount]; // ctor 0x4081d0 each
for (uint i = 0; i < o.layerCount; ++i) {
LayerState& d = layerStates[i]; const LayerState& s = o.layerStates[i];
d.info = s.info;
d.spritesheetPath = s.spritesheetPath;
d.texture = s.GetTexture(); // 0x408590 + assign 0x40c3b0
d.b30 = s.b30; d.b31 = s.b31; d.b32 = s.b32; d.b33 = s.b33;
d.size = s.size; d.rotation = s.rotation; d.pos = s.pos; // +0x34..+0x44
d.color = s.color; // +0x48 (0x2c)
d.visible = s.visible; // +0x74
memcpy(&d.blendMode, &s.blendMode, 0x1c); // +0x78..+0x94 (blend x5, flags, crop vector)
d.owner = this;
// +0x20..+0x2c sampler params keep the Init(nullptr) defaults
}
}
```
`AnimationState::AnimationState(ANM2* owner, const AnimationState& s)`, 0x4086e0, `ret 8`: copies anim and makes a deep copy
of both index arrays (`operator new(count*4)`, memcpy) using `anim->layerAnimCount/nullAnimCount`. Then it copies frame,
playing and both masks.
### 3.5 `ANM2& ANM2::operator=(ANM2 tmp /*by value*/)` — 0x407e90 (`ret 0x114`, copy-and-swap)
```cpp
ANM2& ANM2::operator=(ANM2 tmp) { swap(*this, tmp); /* inline ~ANM2(tmp) */ tmp.Reset(); ...; return *this; }
```
`void swap(ANM2& a /*ecx*/, ANM2& b /*edx*/)`, 0x407ae0, fastcall. It swaps:
filename, defaultAnimation (raw 0x18-byte swap), main and overlay **except owner** (+4..+0x1c), +0x74..+0x90,
scale, rotation, color, color2, flipX, flipY, playbackSpeed, +0x108, loaded, shadowLayerIndex, renderFlags.
It does **not** swap +0x70 (overlayRenderFirst) or +0x94 (Offset). Afterwards it re-points `layerStates[i].owner`
in both objects. Net effect of `a = b`: `a` keeps its own Offset and overlayRenderFirst, and its renderFlags become 0
(from the copy-ctor).
### 3.6 `void ANM2::Load(const std::string& path, bool loadGraphics)` — 0x40bd50 (`ret 8`)
```cpp
void ANM2::Load(const std::string& path, bool loadGraphics) {
if (filename.size()) AnmCache::RemoveRef(filename);
if (this != (ANM2*)&path) filename.assign(path);
AnmCache::Load(path, this); // fills animations/layerStates/... (see 1.4)
AnmCache::AddRef(path);
if (loadGraphics) LoadGraphics();
main.SetAnimationData(nullptr);
overlay.SetAnimationData(nullptr);
loaded = true; // QUIRK: set even when the cache load failed
shadowLayerIndex = -1;
for (uint i = 0; i < layerCount; ++i) {
const char* nm = layerStates[i].info ? layerStates[i].info->name.c_str() : "";
if (strcmp(nm, "shadow") == 0) shadowLayerIndex = i;
else if (nm[0] == '*') { layerStates[i].renderFlags |= 5; renderFlags |= 0x400; }
}
for (uint i = 0; i < nullCount; ++i)
if (nullNames[i].c_str()[0] == '*') renderFlags |= 0x800;
}
```
(The AnimationStates are reset only **after** AnmCache::Load has replaced `animations`. Before that they briefly hold
pointers into the old data.)
### 3.7 `void ANM2::Reload()` — 0x40bea0 (Lua only; no native callers)
```cpp
void ANM2::Reload() {
if (filename.size()) {
AnmCache::Load(filename, this);
AnmCache::AddRef(filename); // QUIRK: no matching RemoveRef, so each Reload leaks one ref
LoadGraphics();
}
// anim states, loaded flag and shadow index are NOT touched
}
```
### 3.8 `bool ANM2::ReplaceSpritesheet(int layer, const std::string& path)` — 0x40bf30 (`ret 8`)
```cpp
bool ANM2::ReplaceSpritesheet(int layer, const std::string& path) {
if (layer < 0 || layer >= (int)layerCount) return false;
LayerState& ls = layerStates[layer];
if (StrEqual(ls.spritesheetPath, path)) return false; // unchanged
ls.spritesheetPath = path;
ls.graphicsLoaded = false; // +0x30
return true; // texture loads on the next LoadGraphics()
}
```
### 3.9 `void ANM2::LoadGraphics(/*unused 4-byte arg*/)` — 0x40c000 (`ret 4`; 0x40bff0 is the Lua/zero-arg thunk that pushes garbage)
```cpp
void ANM2::LoadGraphics() {
for (uint i = 0; i < layerCount; ++i) {
LayerState& ls = layerStates[i];
if (ls.graphicsLoaded) continue;
TexturePtr tex = LoadImage(ls.spritesheetPath.c_str()); // 0x9588a0(&tex, path)
bool ok = tex.obj && tex.obj->vfunc0(); // IsValid/IsLoaded
if (ok) TextureCache::Add(tex); // 0x40e520 (by-value copy)
TexturePtr old = ls.GetTexture(); // 0x408590
if (old.obj) {
const char* oldName = old.obj->name44; // tex+0x44
ls.SetTexture(TexturePtr(nullptr)); // 0x40c4a0 + 0x408640
TextureCache::Release(oldName); // 0x40e740 (evicts if useCount <= 2)
}
ls.SetTexture(tex); // set even if !ok
ls.graphicsLoaded = ok; // +0x30
ls.b31 = false; // +0x31
}
}
```
---------------------------------------------------------------------------------------------------------------------
## 4. AnimationState: what happens when an animation is set
### 4.1 `void AnimationState::SetAnimationData(AnimationData* a)` — 0x408830 (`ret 4`; ~60 callers)
Used by Reset, Load, RemoveOverlay, and SetAnimation(name, reset=true).
```cpp
void AnimationState::SetAnimationData(AnimationData* a) {
anim = a;
if (layerFrameIdx) { KageFree(layerFrameIdx); layerFrameIdx = nullptr; } // 0xa648b0(cl=1)
if (nullFrameIdx) { KageFree(nullFrameIdx); nullFrameIdx = nullptr; }
if (anim) {
if (anim->layerAnimCount) { // +0x1c
layerFrameIdx = (int*)KageAlloc(anim->layerAnimCount * 4); // 0xa648b0(cl=0)
memset(layerFrameIdx, 0xFF, anim->layerAnimCount * 4); // all -1
}
if (anim->nullAnimCount) { // +0x24 (only checked if anim != null)
nullFrameIdx = (int*)KageAlloc(anim->nullAnimCount * 4);
memset(nullFrameIdx, 0xFF, anim->nullAnimCount * 4);
}
}
frame = -1.0f; playing = false; eventsThisUpdate = 0; eventsSinceStart = 0;
}
```
The arrays are sized by the **animation's** layer-animation and null-animation counts, not by the sprite's
layer/null counts. Rendering maps sprite layer id → layer-anim index through `anim->layerIdToLayerAnimIdx[id]` (+0x38).
### 4.2 `void AnimationState::ChangeAnimationKeepFrame(AnimationData* a)` — 0x408970 (`ret 4`)
Used by SetAnimation(name, reset=false) 0x40a678 and by SetOverlayAnimation 0x40ab98.
```cpp
void AnimationState::ChangeAnimationKeepFrame(AnimationData* a) {
int oldL = anim ? anim->layerAnimCount : 0, newL = a ? a->layerAnimCount : 0;
int oldN = anim ? anim->nullAnimCount : 0, newN = a ? a->nullAnimCount : 0;
if (oldL != newL) {
if (newL <= 0) { if (layerFrameIdx) { KageFree(layerFrameIdx); layerFrameIdx = nullptr; } }
else {
int* p = (int*)KageAlloc(newL * 4); memset(p, 0xFF, newL * 4);
if (oldL > 0) memcpy(p, layerFrameIdx, oldL * 4); // QUIRK: copies OLD count, overflows if oldL > newL
if (layerFrameIdx) TrackedFree(layerFrameIdx);
layerFrameIdx = p;
}
}
if (oldN != newN) {
if (newN <= 0) { if (nullFrameIdx) { KageFree(nullFrameIdx); nullFrameIdx = nullptr; } }
else {
int* p = (int*)KageAlloc(newN * 4); memset(p, 0xFF, newN * 4);
if (oldN > 0) memcpy(p, nullFrameIdx, oldN * 4);
if (nullFrameIdx) { TrackedFree(nullFrameIdx); nullFrameIdx = nullptr; }
layerFrameIdx = p; // !!! BUG IN BINARY (0x408b6a): the new NULL array is stored into
// layerFrameIdx (leaking the layer array). nullFrameIdx ends NULL.
}
}
anim = a; // frame / playing / event masks are preserved
}
```
(Re-check 0x408b63..0x408b6d if you doubt this. The store really is `mov [esi+8], ebx`.)
### 4.3 Callers that select an animation
- `bool ANM2::SetAnimation(const char* name, bool reset)`, 0x40a5d0 (`ret 8`). The Lua wrapper 0x40a5b0 takes a std::string.
It does a linear `strcmp` over `animations[0..animationCount)` on `AnimationData::name` (+0). If nothing matches it logs
`"[warn] no animation named %s\n"` and returns false. Otherwise it calls
`reset ? main.SetAnimationData(&animations[i]) : main.ChangeAnimationKeepFrame(&animations[i])` and returns true.
SetOverlayAnimation 0x40aaf0 does the same on `overlay`.
- `void ANM2::Play(const char* name, bool force)`, 0x40a380 (Lua 0x40a360):
`if (force || !main.anim || strcmp(main.anim->name, name) || (!main.anim->loop && !main.playing)) { if (SetAnimation(name, true)) { main.Rewind(); main.playing = true; } }`
PlayRandom 0x40a2b0 (`animations[seed % animationCount]`) and the index variant 0x40a400 (`"[warn] Animation index out of range!"`) follow the same pattern.
- `void AnimationState::Rewind()`, 0x40a1b0:
`frame = 0; eventsThisUpdate = eventsSinceStart = 0; FireTriggersAtCurrentFrame(); fill layerFrameIdx[0..layerAnimCount) and nullFrameIdx[0..nullAnimCount) with 0;`
- `Stop` 0x40a910: `if (main.anim) main.playing = false;`
---------------------------------------------------------------------------------------------------------------------
## 5. Open questions / uncertainty
1. `AnmFileData+0 needsReload`: the only writes I found set it to 0 (node creation, ParseAnm2). It may be set elsewhere,
for example when a mod is toggled. I did not scan the whole binary for byte writes to node+0x14.
2. ANM2 +0xd4 (0x2c-byte colour struct whose Reset alpha is 0) and +0x108 (bool): purpose unknown. Neither is read in the
0x401000..0x41d000 module. Look at entity render code outside it.
3. LayerState +0x20..+0x2c (texture param pairs), +0x31..+0x33, +0x78..+0x94: names are guesses from defaults and the
Repentance+ LayerState API (blend factors 1/6/7 match GL enum ordinals ONE/SRC_ALPHA/ONE_MINUS_SRC_ALPHA).
4. LayerInfo +0/+4 ints: likely layerId and spritesheetId. The parser decomp should confirm.
5. TextureCache key mismatch: Add uses the unprefixed `tex->name`, while Has/Release use `prefix+name`. This only works if
the texture name already includes the mount prefix (not verified).
6. Mount prefix strings come from `Mount+0xc` in FileSystem 0xc379e0+8. Their actual values (e.g. "resources/") were not
observed at runtime.
@@ -0,0 +1,104 @@
{
"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)",
"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)",
"0x85db20": "lua_GetAnimation",
"0x85db70": "lua_GetOverlayAnimation",
"0xa112c0": "KAGE_LogMessage(level,fmt,...)",
"0xa159d0": "HashPath(djb2 lower,/)",
"0xa16060": "FileSystem::GetMountPrefixes",
"0xa17180": "FileSystem::ResolvePath",
"0xa68490": "GetTimeNs",
"0xaf0917": "floor"
}
+537
View File
@@ -0,0 +1,537 @@
# isaac-ng.exe (Repentance+ 1.9.7.17) — ANM2 parser decompilation
Target: `0x40ed50` (`AnmCache::LoadFile`), the frame-expansion helpers `0x414e00` / `0x415170`, and what they call.
Annotated dumps: `parse.asm` (0x40ed50-0x413b40) and `interp.asm` (0x414e00-0x4155c2). Labels were added to `labels.json`.
Addresses in [brackets] are the evidence for each claim.
---------------------------------------------------------------------------------------------------
## 0. Who calls it (load path)
* `0x40ed50` is `__thiscall` on the global AnmCache map `0xc78ee0`. It takes 2 stack args, `(const std::string& path, uint32 hash)`, and ends with `ret 8`.
If `hash==0`, it is computed as `0xa159d0(path.c_str())` [0x40ee02].
Callers:
* `0x40ddf9`, inside `AnmCache::Get` `0x40db90`. That function is called from `lua_Load` (0x40bd83) and `lua_Reload` (0x40beab).
It builds the candidate path for each content/mod directory (vector `0xc798b8..0xc798bc`, `strncpy_s`/`strcat_s`), hashes it, and looks it up in the cache map (`0x416490`).
It calls the parser when there is no entry. It also calls it when there is an entry whose byte flag `+0` is set and `0xa17180(path)` returns non-zero (reload).
After that it copies the cache data into the Sprite (0x40de78...).
* `0x40ec3f`, inside `AnmCache::Preload(const char*)` `0x40ea50`. This is the same lookup, done by C-string.
* Flow inside the parser:
1. `0x8f5ad0` resolves the path. `0xa178d0` opens the file.
On failure it logs `"ERROR Could not open %s\n"` at level 1 and returns [0x40edee]. The cache entry is not touched.
2. `entry = cacheMap[hash]` (`0x414500` → `0x4158b0`, value at node+0x14).
3. `entry->Clear()` (`0x40d850`, which frees every array), then `entry->byte0 = 0` [0x40ee25-0x40ee32].
4. It reads the whole file into `buf = alloc(size+1)` and adds a NUL. It then runs rapidxml in-situ (doc at ebp-0x26638, `0x413b90` ctor, `0x4155d0` parse).
XML access is rapidxml: node `+0x18 first_node`, `+0x20 first_attribute`, `+0x2c next_sibling`.
Attributes are `+0 name`, `+4 value`, `+0x10 parent`, `+0x18 next_attribute` (the next attribute is used only when parent != 0). A NULL name or value is read as `""` (0xc71640).
* `0x413c70 = first_node(name)`. It compares sizes, then bytes, and returns 0 if the node is missing.
* `0x413bf0 = first_attribute(name)`. With `name==0` it returns the first attribute.
**No element is optional.** The code never checks a `first_node` result for NULL. It always reads `[node+0x18]` immediately.
So a missing `AnimatedActor`, `Content`, `Spritesheets`, `Layers`, `Nulls`, `Events`, `Animations`, `RootAnimation`, `LayerAnimations`, `NullAnimations` or `Triggers` crashes with a NULL deref.
The child-name lookups inside `<Animation>` are inlined loops [0x410261, 0x410e02, 0x4122e3, 0x413472]. Each ends in `xor edi,edi; mov edi,[edi+0x18]`.
Child elements are **never checked by tag name**. Every child of `<Spritesheets>`, `<Layers>`, `<Nulls>`, `<Events>`, `<RootAnimation>`, `<LayerAnimation>`, `<Triggers>` and so on is processed whatever its tag is.
Animations are iterated from `first_node("Animation")` along `next_sibling` [0x40fc0f, 0x4136ab]. Siblings after the first `<Animation>` are not filtered by name either.
Attribute matching is an exact, case-sensitive `strcmp`. Unknown attributes are ignored.
### Value converters (inlined everywhere)
* `int`: `atoi(value)`. Unparsable text gives 0.
* `float`: `(float)atof(value)` (`fstp dword`).
* `scale`: `f = (float)atof(v); f = f / 100.0f`.
This is done on x87 as `fld f; fdiv dword 100.0; fstp`. It is bit-identical to a single-precision `f/100.0f`.
* `color`: the same, but `/ 255.0f` (constant 0xbaaae4 = 255.0). This applies to **both tints and offsets**.
* `bool` (Loop, Visible, Interpolated) [0x4100b6-0x410186, 0x411586-0x411602]:
```
bool ParseBool(std::string s) { if (s.empty()) return false;
if (s == "true") return true; if (s == "True") return true; return atoi(s.c_str()) != 0; }
```
So "1" and "TRUE"-like numbers work, and "false", "FALSE" and "" give false.
---------------------------------------------------------------------------------------------------
## 1. Data structures
### 1.1 Cache entry (`AnmData`, value of the AnmCache map, at map node + 0x14)
| off | type | meaning |
|---|---|---|
| +0x00 | u8 | flag. The parser clears it to 0 [0x40ee32]. The caller reloads when it is set. |
| +0x04 | LayerInfo* | `new[]` with a count cookie at ptr-4 [0x40f3e3-0x40f4eb] |
| +0x08 | int | layerCount [0x40f4f7] |
| +0x0c | AnimationData* | `new[]` with a cookie [0x4136fe-0x4139de] |
| +0x10 | int | animationCount [0x4139e1] |
| +0x14 | std::string* | null names, `new[]` with a cookie. **Only set if nullCount>0** [0x40f7fe] |
| +0x18 | int | nullCount [0x40f813] |
| +0x1c | std::string* | event names, `new[]` with a cookie. **Only set if eventCount>0** [0x40fb2e] |
| +0x20 | int | eventCount [0x40fb46] |
| +0x24 | std::string | DefaultAnimation [0x40fbf4]. Not reset by Clear(), so on a reload without the attribute the old value stays. |
**The spritesheet table is not stored.** Spritesheet paths live only in a 64-entry local array (ebp-0x16a0) and are copied into each layer (`LayerInfo.+0x20`).
The Sprite object (`+0x80 layerCount`, `+0x8c eventNames`, ... in CONTEXT.md) is a separate object filled from this entry by `0x40db90`.
### 1.2 LayerInfo (0x38) — ctor `0x40d140`
| off | type | field |
|---|---|---|
| +0x00 | int | Id |
| +0x04 | int | SpritesheetId |
| +0x08 | std::string | Name |
| +0x20 | std::string | resolved spritesheet path (copy of `spritesheetPath[SpritesheetId]`) |
### 1.3 AnimationData (0x13c) — ctor `0x40bec0`
| off | type | field / ctor default |
|---|---|---|
| +0x000 | std::string | Name |
| +0x018 | LayerAnimation* | `new[]` with a cookie (NULL if 0) |
| +0x01c | int | layerAnimCount |
| +0x020 | NullAnimation* | `new[]` with a cookie (NULL if 0) |
| +0x024 | int | nullAnimCount |
| +0x028 | Trigger* | plain `new` with no cookie (NULL if 0) |
| +0x02c | int | triggerCount |
| +0x030 | int | FrameNum (ctor -1; the parser always writes it, default 0) |
| +0x034 | bool | Loop (default false) |
| +0x038 | int[64] | layerId → layer-animation index (ctor fills with -1, see §2.9) |
| +0x138 | int | index of this animation in file order [0x41022e] |
There are **no root frames** in AnimationData. RootAnimation is baked into the layer and null frames at load time (§3.3).
### 1.4 LayerAnimation (0x10) — ctor `0x40c1e0`
| off | type | field / default |
|---|---|---|
| +0x0 | int | LayerId (default -1) |
| +0x4 | AnimationFrame* | frames (plain `new`, NULL if 0 frames) |
| +0x8 | int | frameCount (count *after* expansion and root splitting) |
| +0xc | bool | Visible (default **true**) |
### 1.5 NullAnimation (0x10) — ctor `0x40c210` (zeroes only +8/+0xc)
| off | type | field / default |
|---|---|---|
| +0x0 | int | NullId (**no default**: stale or uninitialized, see §2.10) |
| +0x4 | bool | Visible (**no default**) |
| +0x8 | NullFrame* | frames (plain `new`, NULL if 0) |
| +0xc | int | frameCount |
### 1.6 AnimationFrame (0x6c) — ctor inlined [0x40fdfe]
| off | type | XML attr | conversion |
|---|---|---|---|
| +0x00 | float | XCrop | atof |
| +0x04 | float | YCrop | atof |
| +0x08 | float | Width | atof |
| +0x0c | float | Height | atof |
| +0x10 | float | XPosition | atof |
| +0x14 | float | YPosition | atof |
| +0x18 | float | XScale | atof/100 |
| +0x1c | float | YScale | atof/100 |
| +0x20 | float | XPivot | atof |
| +0x24 | float | YPivot | atof |
| +0x28 | int | Delay | atoi (after expansion: 1 for interpolated sub-frames, see §3) |
| +0x2c | bool | Visible | ParseBool |
| +0x30 | Color (0x2c) | | see 1.8 |
| +0x5c | float | Rotation | atof, degrees, no conversion |
| +0x60 | bool | Interpolated | ParseBool |
| +0x64 | int | **startFrame** (inclusive) | computed |
| +0x68 | int | **endFrame** (exclusive; = start of the next frame) | computed |
**Correction to CONTEXT.md:** `+0x68` is the *end* frame (start + length).
The runtime `AdvanceLayerPosition` 0x408b90 advances while `frame >= (float)frames[idx].end(+0x68)`, so CONTEXT's "cumulative startFrame" is really the end tick. `+0x64` holds the start.
ctor zeroes +0x00..+0x24 and sets the Color to tint (1,1,1,1) with the rest 0 (`0x407170`), and `+0x60 = 0`.
**+0x28 Delay, +0x2c Visible, +0x5c Rotation, +0x64 and +0x68 are not initialized.**
### 1.7 NullFrame (0x54) — used for null frames AND root frames; ctor inlined [0x40fc50]
| off | type | XML attr | conversion |
|---|---|---|---|
| +0x00 | float | XPosition | atof |
| +0x04 | float | YPosition | atof |
| +0x08 | int | Delay | atoi |
| +0x0c | bool | Visible | ParseBool |
| +0x10 | float | XScale | atof/100 |
| +0x14 | float | YScale | atof/100 |
| +0x18 | Color (0x2c) | | |
| +0x44 | float | Rotation | atof |
| +0x48 | bool | Interpolated | ParseBool |
| +0x4c | int | startFrame (inclusive) | computed |
| +0x50 | int | endFrame (exclusive) | computed |
ctor zeroes +0, +4, +0x10, +0x14, runs Color(), and sets +0x48=0. **+0x08, +0x0c, +0x44, +0x4c and +0x50 are uninitialized.**
**Correction to CONTEXT.md:** `+0x50` is the end frame, not the start. `+0x4c` is the start.
### 1.8 Color (0x2c) — `0x407170` ctor, `0x4071f0` copy
`float tint[4] (RGBA, default 1)`, `float colorize[4] (default 0)`, `float offset[3] (RGB, default 0)`.
* `+0x00..+0x0c` RedTint/GreenTint/BlueTint/AlphaTint, each `/255`.
* `+0x10..+0x1c` colorize. The parser never writes it, so it is always 0.
* `+0x20..+0x28` RedOffset/GreenOffset/BlueOffset, each `/255`.
So in an AnimationFrame the offsets are at +0x50/+0x54/+0x58. In a NullFrame they are at +0x38/+0x3c/+0x40.
### 1.9 Trigger (8)
`int EventId (+0)`, `int AtFrame (+4)`. Both use atoi. There are no defaults (see §2.11).
---------------------------------------------------------------------------------------------------
## 2. Parser pseudocode (`0x40ed50`)
```cpp
void AnmCache::LoadFile(const std::string& path, uint32 hash)
{
std::string resolved = ResolvePath(path); // 0x8f5ad0
File* f = FileSystem::Open(resolved.c_str(), 0); // 0xa178d0
if (!f) { KAGE_LogMessage(1, "ERROR Could not open %s\n", path.c_str()); return; }
if (!hash) hash = HashString(path.c_str()); // 0xa159d0
AnmData& d = s_cache[hash]; d.Clear(); d.flag = 0;
size_t n = f->Size(); char* text = Alloc(n+1); f->Read(text,1,n); text[n]=0; f->Close(1);
rapidxml::xml_document doc; doc.parse(text);
xml_node* actor = doc.first_node("AnimatedActor");
xml_node* content = actor->first_node("Content");
```
### 2.1 Spritesheets [0x40eec2-0x40f01d]
```cpp
std::string sheetPath[64]; // local only
char pathBuf[260]; // ebp-0x120, NOT cleared between elements
int sheetCount = 0;
for (xml_node* e = content->first_node("Spritesheets")->first_node(); e; e = e->next_sibling()) {
int id = 64; // default = invalid
for (attr a : e->attributes()) {
if (a.name == "Path") ResolveRelativePath(pathBuf, path.c_str(), a.value); // 0x67f670
else if (a.name == "Id") id = atoi(a.value);
}
if (id >= 64 || id != sheetCount) // signed compare: jge 0x40 / jne
Log(0x10, "%s: invalid spritesheet id %d\n", path.c_str(), id);
sheetPath[id] = pathBuf; // written even when invalid (out-of-bounds if id>=64 or <0)
++sheetCount;
}
```
`0x67f670` is not fully reversed. It turns `\` into `/`, splits on `/`, takes the directory of the .anm2 path, appends the relative path and handles `".."` (string 0xb1ceb8), then `strncpy`s up to 0x104 chars into `pathBuf`.
The resulting path is relative to the .anm2 file's directory.
If an element has no Path attribute, the previous element's path is reused because the buffer is stale. An element with no attributes at all also logs "invalid spritesheet id 64".
### 2.2 Layers [0x40f052-0x40f4f7]
```cpp
LayerInfo layer[64]; int layerCount = 0;
for (e : content->first_node("Layers")->children) {
std::string name; int id = 64; int sheet = -1;
for (a : e->attributes()) {
if (a.name=="Name") name = a.value;
else if (a.name=="Id") id = atoi(a.value);
else if (a.name=="SpritesheetId") sheet = atoi(a.value);
}
if (id >= 64 || id != layerCount) Log(0x10, "%s: invalid layer id %d\n", path, id);
if (sheet < 0 || sheet >= sheetCount) Log(0x10, "%s: invalid spritesheet id %d\n", path, sheet);
layer[id].spritesheetPath = sheetPath[sheet]; // unchecked index (sheet=-1 reads OOB)
layer[id].id = id; layer[id].spritesheetId = sheet; layer[id].name = name;
++layerCount;
}
if (layerCount == 0) Log(0x10, "%s: no layers\n", path); // only a log, parsing continues
d.layers = new LayerInfo[layerCount]; copy layer[0..layerCount-1]; d.layerCount = layerCount;
```
An element with no attributes skips straight to the error with id=64 and sheet=-1 [0x40f0b2→0x40f26a].
### 2.3 Nulls [0x40f514-0x40f813]
```cpp
std::string nullName[64]; int nullCount = 0;
for (e : content->first_node("Nulls")->children) {
int id = 64; std::string name;
for (a) { if (a.name=="Id") id = atoi(v); else if (a.name=="Name") name = v; }
if (id >= 64 || id != nullCount) Log(0x10, "%s: invalid Null ID %d\n", path, id);
nullName[id] = name; ++nullCount;
}
if (nullCount) d.nullNames = new std::string[nullCount] (copy); d.nullCount = nullCount;
```
### 2.4 Events [0x40f839-0x40fb46] — **maximum 16 events**
```cpp
std::string eventName[16]; int eventCount = 0;
for (e : content->first_node("Events")->children) {
int id = 16; std::string name;
for (a) { if (a.name=="Id") id = atoi(v); else if (a.name=="Name") name = v; }
if (id >= 16 || id != eventCount) Log(0x10, "%s: invalid Event ID %d\n", path, id);
eventName[id] = name; ++eventCount;
}
if (eventCount) d.eventNames = new std::string[eventCount]; d.eventCount = eventCount;
```
Event IDs are 0..15. The runtime 32-bit `bts` masks therefore only ever use bits 0..15. Trigger EventIds are **not** validated against eventCount.
### 2.5 Animations header [0x40fb5a-0x40fc14]
```cpp
AnimationData anim[256]; // local, ctor 0x40bec0. There is NO "too many animations" check (>256 overflows the stack)
int animCount = 0;
xml_node* anims = actor->first_node("Animations");
for (a : anims->attributes()) if (a.name=="DefaultAnimation") d.defaultAnimation = a.value;
xml_node* animNode = anims->first_node("Animation");
// 6 scratch buffers of 5000 frames, allocated ONCE and reused for every animation:
NullFrame* A = new NullFrame[5000]; // ebp-0x26698 root frames
NullFrame* B = new NullFrame[5000]; // ebp-0x26668 scratch for root interpolation
NullFrame* C = new NullFrame[5000]; // ebp-0x2669c null frames
NullFrame* D = new NullFrame[5000]; // ebp-0x26694 scratch / output for nulls
AnimationFrame* E = new AnimationFrame[5000]; // ebp-0x26670 layer frames
AnimationFrame* F = new AnimationFrame[5000]; // ebp-0x2668c scratch / output for layers
```
### 2.6 Per animation [0x40ff10-0x410269]
```cpp
for (; animNode; animNode = animNode->next_sibling()) {
std::string name; int frameNum = 0; bool loop = false;
for (a : animNode->attributes()) {
if (a.name=="Name") name = v;
else if (a.name=="FrameNum") frameNum = atoi(v);
else if (a.name=="Loop") loop = ParseBool(v);
}
AnimationData& an = anim[animCount]; an.index(+0x138) = animCount; ++animCount;
an.name = name; an.frameNum = frameNum; an.loop = loop;
```
FrameNum is only stored. The parser does not use it to clamp or pad frames.
### 2.7 RootAnimation [0x410261-0x410ddc]
```cpp
xml_node* root = FindChild(animNode, "RootAnimation"); // crash if missing
int rootCount = 0, t = 0;
for (xml_node* fr = root->first_node(); fr; fr = fr->next_sibling()) {
if (rootCount >= 5000) Log(0x10, "%s: too many root frames\n", path); // continues anyway (overflow)
NullFrame& f = A[rootCount++];
float tint[4] = {1,1,1,1}, off[3] = {0,0,0}; // reset for every frame
for (a : fr->attributes()) switch(name):
XPosition: f.x = atof; YPosition: f.y = atof; Delay: f.delay = atoi;
Visible: f.visible = ParseBool; XScale: f.sx = atof/100; YScale: f.sy = atof/100;
RedTint/GreenTint/BlueTint/AlphaTint: tint[i] = atof/255;
RedOffset/GreenOffset/BlueOffset: off[i] = atof/255;
Rotation: f.rot = atof; Interpolated: f.interp = ParseBool;
f.color.tint = tint; f.color.offset = off; // colorize untouched
f.start = t; f.end = t + f.delay; t = f.end; // [0x410daa]
}
InterpolateNullFrames(A, &rootCount, B); // 0x414e00, result in place in A
```
**Missing-attribute defaults:** only tint (1) and offset (0) are reset for each frame. Every other field keeps whatever the reused buffer slot held.
For a never-used slot that is: x, y, sx, sy = **0** (so a missing XScale means scale 0), interp=false, and delay, visible and rot uninitialized heap memory.
Otherwise it is the value from a previous animation, or the expanded output that `0x414e00` memcpy'd into that slot.
Real .anm2 files always write every attribute. For a reimplementation: use defaults of pos 0, scale 1, delay 1, visible true, rot 0, interp false, and note the difference.
The same is true for layer and null frames (buffers E and C).
### 2.8 LayerAnimations [0x410de4-0x4122c2]
```cpp
LayerAnimation la[64]; // ctor per animation: id=-1, frames=0, count=0, visible=true
int laCount = 0;
for (xml_node* ln = FindChild(animNode,"LayerAnimations")->first_node(); ln; ln = ln->next_sibling()) {
if (laCount >= 64) Log(0x10, "%s: too many animation layers\n", path); // continues (overflow)
LayerAnimation& L = la[laCount++];
for (a) { if (a.name=="LayerId") L.layerId = atoi(v); else if (a.name=="Visible") L.visible = ParseBool(v); }
int n = 0, t = 0;
for (xml_node* fr = ln->first_node(); fr; fr = fr->next_sibling()) {
if (n >= 5000) Log(0x10, "%s: too many animation frames\n", path);
AnimationFrame& f = E[n++];
float tint[4]={1,1,1,1}, off[3]={0,0,0};
attrs: XPosition(+0x10) YPosition(+0x14) XPivot(+0x20) YPivot(+0x24) Width(+8) Height(+0xc)
XScale(+0x18,/100) YScale(+0x1c,/100) Delay(+0x28,atoi) Visible(+0x2c)
XCrop(+0) YCrop(+4) Red/Green/Blue/AlphaTint(/255) Red/Green/BlueOffset(/255)
Rotation(+0x5c) Interpolated(+0x60)
f.color.tint = tint; f.color.offset = off;
f.start = t; f.end = t + f.delay; t = f.end; // [0x411db2]
}
InterpolateLayerFrames(E, &n, F); // 0x415170, result in place in E
// ---- root-frame adjustment (bakes RootAnimation into the layer), §3.3 ----
int out = ApplyRoot<AnimationFrame>(E, n, A, rootCount, F); // [0x411df1-0x4121a1]
if (out) { L.frames = new AnimationFrame[out]; copy F[0..out-1]; }
L.frameCount = out;
}
if (laCount) {
an.layerAnims = new LayerAnimation[laCount] (copy id, visible, frames, count);
an.layerAnimCount = laCount;
for (i = 0; i < laCount; ++i) an.layerMap[an.layerAnims[i].layerId] = i; // [0x4122a0] unchecked index
} else an.layerAnimCount = 0;
```
LayerId is **not validated** against layerCount or against 0..63.
`layerMap[id]` with id=-1 writes into `+0x34` (Loop). id ≥ 64 writes past the array into +0x138 and beyond.
Two LayerAnimations with the same LayerId: the last one wins in the map.
### 2.9 Note on `layerMap` (+0x38)
The map is rebuilt at the end (§2.12) in a temporary and *swapped* into the final array. So it is the final map that counts:
* For animation index ≥1, the slots that are not referenced are -1, because they come from the swapped-out ctor-initialized element.
* For **animation 0**, the slots that are not referenced are uninitialized stack memory [0x41384f-0x413957; nothing initializes ebp-0x267c0].
Reimplement as "-1 everywhere, then map[layerId]=index".
### 2.10 NullAnimations [0x4122c5-0x413477]
```cpp
NullAnimation na[64]; // ctor per animation only zeroes frames/count; NullId and Visible keep stale stack values
int naCount = 0;
for (nn : FindChild(animNode,"NullAnimations")->children) {
if (naCount >= 64) Log(0x10, "%s: too many null layers\n", path);
NullAnimation& N = na[naCount++];
for (a) { if (a.name=="NullId") N.nullId = atoi(v); else if (a.name=="Visible") N.visible = ParseBool(v); }
int n = 0, t = 0;
for (fr : nn->children) {
if (n >= 5000) Log(0x10, "%s: too many null frames\n", path);
NullFrame& f = C[n++];
// same attribute set and conversions as root frames (§2.7)
f.start = t; f.end = t + f.delay; t = f.end; // [0x412fd8]
}
InterpolateNullFrames(C, &n, D); // 0x414e00
int out = ApplyRoot<NullFrame>(C, n, A, rootCount, D); // [0x413017-0x41334a]
if (out) { N.frames = new NullFrame[out]; copy D[0..out-1]; }
N.frameCount = out;
}
if (naCount) an.nullAnims = new NullAnimation[naCount] (copy nullId, visible, frames, count);
an.nullAnimCount = naCount;
```
NullId is not validated, and there is no null map.
### 2.11 Triggers [0x413472-0x4136a2] — **maximum 128 (0x80)**
```cpp
Trigger tr[128]; int tc = 0; // local array NOT reset per animation or per trigger
for (te : FindChild(animNode,"Triggers")->children) {
if (tc >= 128) Log(0x10, "%s: too many triggers\n", path); // continues (overflow)
Trigger& T = tr[tc++];
for (a) { if (a.name=="EventId") T.eventId = atoi(v); else if (a.name=="AtFrame") T.atFrame = atoi(v); }
}
if (tc) { an.triggers = new Trigger[tc]; copy; }
an.triggerCount = tc;
} // next animation
```
AtFrame is the raw tick number. There is no conversion and it is not checked against FrameNum.
### 2.12 Finish [0x4136f0-0x413b37]
```cpp
d.anims = new AnimationData[animCount]; // ctor 0x40bec0
for (i...) { tmp = copy of anim[i] with map rebuilt (§2.9); swap(d.anims[i], tmp); }
d.animCount = animCount;
free A..F; destroy local arrays; destroy the xml document; free the text buffer.
}
```
### Limits summary
| limit | value | behaviour when exceeded |
|---|---|---|
| spritesheets | id < 64 and id == index | "%s: invalid spritesheet id %d" (level 0x10), still stored at [id] |
| layers | id < 64 and id == index | "%s: invalid layer id %d" |
| layer→spritesheet | 0 ≤ id < sheetCount | "%s: invalid spritesheet id %d" |
| no layers | count == 0 | "%s: no layers" |
| nulls | id < 64 and id == index | "%s: invalid Null ID %d" |
| events | **id < 16** and id == index | "%s: invalid Event ID %d" |
| animations | 256 (stack array) | no check |
| root frames / anim | 5000 | "%s: too many root frames" (when count ≥5000 before adding) |
| layer anims / anim | 64 | "%s: too many animation layers" |
| frames / layer anim | 5000 | "%s: too many animation frames" |
| null anims / anim | 64 | "%s: too many null layers" |
| frames / null anim | 5000 | "%s: too many null frames" |
| expanded frames | 5000 | "too many frames after interpolation\n" (checked as **i+1 ≥ 5000**, where i is the *source* index, not the output count; see §3) |
| root-adjusted frames | 5000 | "%s: too many frames after interpolation/root frame adjustment" |
| triggers / anim | 128 | "%s: too many triggers" |
Every check only logs and keeps going. None of them stops parsing or clamps a value (in the original that means memory corruption).
---------------------------------------------------------------------------------------------------
## 3. Frame expansion
Both helpers use a custom calling convention: `ecx = frames (in/out)`, `edx = int* count (in/out)`, one stack arg `scratch` (caller cleans).
They write the output to `scratch`, then `memcpy(frames, scratch, out*size)` and set `*count = out` [0x415131, 0x41559b].
**Interpolation is pre-baked at load time.** Each interpolated keyframe becomes `delay` one-tick frames.
### 3.1 `0x415170` InterpolateLayerFrames (AnimationFrame)
```cpp
void InterpolateLayerFrames(AnimationFrame* src, int* count, AnimationFrame* dst) {
int out = 0, tick = 0;
for (unsigned i = 0; i < (unsigned)*count; ++i) {
AnimationFrame& a = src[i];
if (i != *count - 1 && a.interpolated) { // last frame is never interpolated
if (i + 1 >= 5000) Log(0x10, "too many frames after interpolation\n");
AnimationFrame& b = src[i+1];
float t = 0.0f;
float step = 1.0f / (float)a.delay; // cvtdq2ps + divss
for (int k = 0; k < a.delay; ++k) { // delay <= 0: emits nothing, tick not advanced
AnimationFrame& o = dst[out++];
o.xcrop=a.xcrop; o.ycrop=a.ycrop; o.width=a.width; o.height=a.height; // NOT interpolated
o.x = (b.x - a.x ) * t + a.x; // subss, mulss, addss (no FMA)
o.y = (b.y - a.y ) * t + a.y;
o.sx = (b.sx - a.sx) * t + a.sx;
o.sy = (b.sy - a.sy) * t + a.sy;
o.pivotX = a.pivotX; o.pivotY = a.pivotY; // NOT interpolated
o.delay = 1;
o.visible = a.visible;
o.color = Color::Lerp(a.color, b.color, t); // 0x6832e0
o.rotation = LerpAngleDeg(a.rotation, b.rotation, t); // 0x6828b0
o.interpolated = a.interpolated; // true
o.start = tick; o.end = tick + 1; ++tick;
t = step + t; // accumulated in float, NOT k/delay
}
} else {
AnimationFrame& o = dst[out++];
o = a; // full copy
o.start = tick; o.end = tick + a.delay; tick += a.delay;
}
}
memcpy(src, dst, out * 0x6c); *count = out;
}
```
### 3.2 `0x414e00` InterpolateNullFrames (NullFrame, used for root and null frames)
This is the same algorithm on the NullFrame fields.
* Interpolated: x, y, sx, sy (lerp), color (Color::Lerp), rotation (LerpAngleDeg).
* Copied from `a`: visible, interpolated. delay=1, start=tick, end=tick+1.
* A non-interpolated frame is a full copy with start=tick, end=tick+delay.
* The overflow check is the same `i+1 >= 5000` [0x414e63].
**Color::Lerp `0x6832e0(out, a, b, t)`:** for all 11 floats (tint RGBA, colorize RGBA, offset RGB), `out = a*(1-t) + b*t`. `(1-t)` is computed once as a float.
**LerpAngleDeg `0x6828b0(a, b, t)`** (all single precision. `fmodf` = `0x499d20` = `(float)fmod((double)x,(double)y)`):
```cpp
static float Wrap(float x) { if (fabsf(x) > 360.f) x = fmodf(x, 360.f);
if (x > 180.f) x -= 360.f; else if (x < -180.f) x += 360.f; return x; }
float LerpAngleDeg(float a, float b, float t) {
a = Wrap(a); b = Wrap(b);
if (fabsf(b - a) > 180.f) { if (b > a) a += 360.f; else b += 360.f; }
return Wrap((b - a) * t + a);
}
```
All comparisons are strict. Because `Wrap` is applied, interpolated sub-frames carry rotation normalized to [-180,180] (for example a keyframe at 270° comes out as -90° at t=0). Non-interpolated frames keep their raw rotation.
### 3.3 Root-frame adjustment (inlined twice: layers [0x411df1-0x41219a], nulls [0x413017-0x413343])
After interpolation, each layer or null track is re-timed against the (interpolated) root track `A[0..rootCount)`.
Every frame is split wherever a root frame boundary falls inside it, and each piece is multiplied by the root frame that is active during that piece:
```cpp
template<class Fr> // Fr = AnimationFrame or NullFrame
int ApplyRoot(Fr* src, int n, const NullFrame* root, int rootCount, Fr* dst) {
int out = 0, g = 0, r = 0; // g = global tick, r = current root index
for (int i = 0; i < n; ++i) {
Fr& s = src[i];
s.start = g; // overwrites start
for (int k = 0; k < s.delay; ++k) { // delay <= 0: no output
++g; // g = tick index + 1
int prev = r; bool emit = false;
if (r + 1 < rootCount) {
while (g >= root[r].end) { ++r; if (r + 1 >= rootCount) break; }
if (r > prev) emit = true; // the root frame ends on this tick
}
if (!emit && k == s.delay - 1) emit = true; // last tick of the source frame
if (!emit) continue;
if (out >= 5000) Log(0x10, "%s: too many frames after interpolation/root frame adjustment\n", path);
const NullFrame& R = root[prev]; // root frame active during this piece (index BEFORE advancing)
Fr& o = dst[out++];
o = s; // includes s.start (start of this piece) and s.delay (NOT updated)
o.x = o.x * R.sx + R.x; // mulss then addss
o.y = R.sy * o.y + R.y;
o.visible = o.visible && R.visible;
o.sx = o.sx * R.sx; o.sy = R.sy * o.sy;
o.color *= R.color; // 0x6831c0
o.rotation = R.rotation + o.rotation;
o.end = g; // piece ends here
s.start = g; // next piece of this source frame starts here
}
}
return out;
}
```
* The root transform does not rotate the position around the root. Pivot, crop and size are unchanged. The pieces' `delay` field keeps the source delay, so only start/end are correct afterwards. The runtime uses `end`.
* When a track outlasts the root animation, the last root frame stays in effect (r is capped at rootCount-1).
* **rootCount == 0**: the inner test is skipped and `root[0]` is still applied. That is a stale or uninitialized slot of buffer A, so the original's behaviour is undefined. A reimplementation should use the identity transform.
**Color::operator*= `0x6831c0` (this = frame color, other = root color):**
```cpp
tint[i] = other.tint[i] * tint[i]; // i = 0..3
if (other.colorize.r + other.colorize.g + other.colorize.b != 0) {
if (colorize.r + colorize.g + colorize.b == 0) colorize = other.colorize; // copy all 4
else for (i<4) colorize[i] = (colorize[i] + other.colorize[i]) * 0.5f;
}
offset[i] = other.offset[i] + offset[i]; // i = 0..2
```
(The parser always leaves colorize at 0, so only the tint multiply and offset add matter for .anm2 data.)
---------------------------------------------------------------------------------------------------
## 4. Uncertainties
* `0x67f670` (spritesheet path resolution) was skimmed, not fully decompiled. It joins the directory of the .anm2 path with the relative path, handles `\`→`/` and `..`, and truncates to 0x104.
* `0x8f5ad0` (initial path resolution / mod redirect) and `0xa178d0` (file open) were not examined beyond their role.
* What the cache-entry byte `+0` means (it is cleared here, and the caller's reload test reads it) was not traced fully.
* The rapidxml parse flags were not examined. Entity decoding and whitespace handling follow rapidxml's defaults for whatever flags 0x4155d0 was instantiated with.