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 @@
# ANM2 handling in isaac-ng.exe (Repentance+ v1.9.7.17)
These notes reconstruct how the game parses `.anm2` files and how sprites play them, from the 32-bit `isaac-ng.exe` in the game root.
Addresses assume ImageBase `0x400000`. The `zhl.log` addresses on disk come from an older build and don't match this one.
| File | Contents |
|---|---|
| `anm2.hpp` / `anm2.cpp` | Reimplementation: parser, load-time frame baking, AnimationState, Sprite API |
| `test.cpp` | Behaviour checks, plus an optional run against a real file |
| `docs/parser_decomp.md` | Field-by-field parser decompilation, with an address for every claim |
| `docs/cache_load_decomp.md` | AnmCache, the ANM2 object layout (0x114), and ctor/copy/Load/Reload |
| `docs/labels_*.json` | Function names for this build, for a disassembler |
Build and test:
```
g++ -std=c++17 -O2 -msse2 -mfpmath=sse -ffp-contract=off anm2.cpp test.cpp -o anm2_test
./anm2_test path/to/file.anm2 AnimName EventName
```
`-ffp-contract=off` matters: the game never fuses multiply-adds, and the interpolated values must match bit for bit.
## Pipeline
1. **Load.** `ANM2::Load` (0x40bd50) calls `AnmCache::Load` (0x40db90).
- The cache key is djb2 of `mountPrefix + path`, lowercased with `\` turned into `/`.
- On a cache miss, `AnmCache::LoadFile` (0x40ed50) parses the file with rapidxml.
- The sprite borrows pointers into the cache entry, and entries are refcounted.
2. **Bake.** Everything is precomputed at load time:
- Interpolated keyframes become one-tick frames (0x415170 for layers, 0x414e00 for nulls and root).
- The RootAnimation is multiplied into every layer and null track, splitting frames at root-frame boundaries.
- Nothing is interpolated at runtime, and root frames are not kept.
3. **Play.** Each sprite holds two `AnimationState`s: main at +0x30 and overlay at +0x50.
- Each one keeps a float `frame` and a current keyframe index per track.
- It also keeps two event bitmasks:
- `eventsThisUpdate` (+0x18) answers `IsEventTriggered`.
- `eventsSinceStart` (+0x1c) answers `WasEventTriggered`.
## Events and triggers
- **Event table:** `<Events>` holds at most **16** names, and each id must equal its position.
The sprite looks an event name up linearly and tests bit `i` of the mask.
- **Triggers:** `<Trigger EventId AtFrame>` holds raw ints, at most 128 per animation, with no validation.
- **Firing (0x408c90):** for each trigger, if `(float)AtFrame == frame` exactly, the game sets bit `EventId & 31` in **both** masks.
- **`Update` (0x409030):** this is the only place frames are stepped.
- It computes `nf = floor(frame + PlaybackSpeed)`.
- If `nf < FrameNum`, it calls `AdvancePosition(nf)` and then stores `frame + speed`, so fractional frames are kept.
- `AdvancePosition` first clears `eventsThisUpdate`, then runs `frame = floor(frame)+1` and fires triggers on every whole frame up to `nf`.
So with speed > 1, no event is skipped mid-animation.
- If `nf >= FrameNum` and the animation loops, it calls `Rewind()` instead.
- Rewind sets the frame to 0, clears both masks and fires the frame-0 triggers.
- The frames between the old position and the end are **not** stepped, so with speed > 1 an event near the end of a loop can be skipped.
- If `nf >= FrameNum` and the animation doesn't loop, it calls `AdvancePosition(FrameNum-1)`, but only when that isn't behind the current frame, and then sets `playing = false`.
- **Masks while stopped:** `Update` returns immediately when stopped, so the masks are left as they were.
- If the update that finished the animation crossed an event frame, `IsEventTriggered` stays true from then on.
- The same happens after `Stop()`.
- In the normal speed-1 case the final update clears the mask, because it re-advances to the frame it is already on.
- **`Play(name)` (0x40a380):** it does `SetAnimationData` (frame=-1, masks cleared, indices -1), then `Rewind`, then `playing = true`.
- **Frame-0 events are already set when `Play` returns.**
- With the same name and no `force`:
- a non-looping animation is never restarted, even after it has finished;
- a looping animation restarts only if it was stopped.
- **`SetFrame(f)` (0x408e00):** clamps to `nextafterf(FrameNum, 0)` and clears only `eventsThisUpdate`.
- Triggers fire only when the clamped frame exactly equals AtFrame.
- Track indices are reset to 0 and moved forward to the **unclamped** f.
- `Sprite:SetFrame(name, f)` also stops playback; `SetOverlayFrame(name, f)` does not.
- **`NextEventTrigger` (0x40af10):** returns the nearest AtFrame strictly greater than `(int)frame` (truncated, not floored), or -1.
- **Lua `Sprite:IsEventTriggered` / `WasEventTriggered`:** these only look at the main state.
- **Playback speed:** `PlaybackSpeed` (+0x104) is shared by both states. A negative speed logs "cannot go backward" and fires nothing.
## Bugs in the original
These are not reproduced; each one is marked `ORIGINAL:` in the code.
- **`AnimationState::ChangeAnimationKeepFrame` (0x408970)** is reached through `SetAnimation(name, false)`. It has two bugs:
- When the new animation has a different, non-zero null-animation count, the new null index array is stored into the *layer* slot (`mov [esi+8], ebx` at 0x408b6a). The null slot is left NULL, so the next `Update` dereferences NULL.
- It also copies the *old* layer count into the new array, which overflows the heap when the new animation has fewer layers.
- **Parser:**
- Every limit (16/64/128/5000/256) only logs and keeps writing.
- A missing required element (`Content`, `RootAnimation`, `Triggers`, …) is a NULL dereference.
- `LayerId="-1"` overwrites the animation's `Loop` flag.
- Frame attributes that are missing keep stale values from a reused scratch buffer, so a missing XScale can mean scale 0.
- An animation with no root frames applies an uninitialised root transform.
- **`GetLayerFrame` (0x40a220)** has an off-by-one bounds check (`jg`).
- **`ANM2::Load`** sets `loaded` even when loading failed.
- **`Sprite:Reload`** leaks one cache reference per call.
## Not covered
- **Rendering:** `AnimationLayer::RenderFrame` (0x409120) only reads the current baked frame, through `layerFrameIdx`.
- **Texture loading.**
- **The spritesheet path resolver** (0x67f670): it was only skimmed, and `ResolveRelativePath` here approximates it.
+944
View File
@@ -0,0 +1,944 @@
// See anm2.hpp. Build with SSE floats and no FMA contraction to keep float results identical to the
// game: e.g. `g++ -O2 -msse2 -mfpmath=sse -ffp-contract=off`.
#include "anm2.hpp"
#include <cmath>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
namespace anm2 {
// =============================================================================================
// Logging
// =============================================================================================
static LogFn g_log = [](int level, const std::string& msg) { std::fprintf(stderr, "[%x] %s", level, msg.c_str()); };
void SetLogger(LogFn fn) { g_log = std::move(fn); }
static void Log(int level, const char* fmt, ...) {
char buf[1024];
va_list ap; va_start(ap, fmt); std::vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap);
if (g_log) g_log(level, buf);
}
// =============================================================================================
// Minimal XML DOM (the game uses rapidxml in-situ with default flags; .anm2 only needs elements
// and attributes). Lookups by name are exact and case-sensitive like rapidxml's.
// =============================================================================================
namespace xml {
struct Attr { std::string name, value; };
struct Node {
std::string name;
std::vector<Attr> attrs;
std::vector<Node> children;
const Node* child(const char* n) const { // rapidxml first_node(name) 0x413c70
for (auto& c : children) if (c.name == n) return &c;
return nullptr;
}
};
class Parser {
public:
explicit Parser(const std::string& s) : s_(s) {}
bool parse(Node& doc) {
doc.name.clear();
return parseChildren(doc, /*top=*/true);
}
private:
const std::string& s_;
size_t p_ = 0;
bool eof() const { return p_ >= s_.size(); }
void ws() { while (!eof() && (unsigned char)s_[p_] <= ' ') ++p_; }
bool starts(const char* t) const { return s_.compare(p_, std::strlen(t), t) == 0; }
bool skipPast(const char* t) {
size_t q = s_.find(t, p_);
if (q == std::string::npos) { p_ = s_.size(); return false; }
p_ = q + std::strlen(t); return true;
}
static bool nameChar(char c) {
return !((unsigned char)c <= ' ' || c == '/' || c == '>' || c == '=' || c == '<' || c == '?' || c == '!');
}
static void appendUtf8(std::string& o, unsigned long cp) {
if (cp < 0x80) o += char(cp);
else if (cp < 0x800) { o += char(0xC0 | (cp >> 6)); o += char(0x80 | (cp & 0x3F)); }
else if (cp < 0x10000) { o += char(0xE0 | (cp >> 12)); o += char(0x80 | ((cp >> 6) & 0x3F)); o += char(0x80 | (cp & 0x3F)); }
else { o += char(0xF0 | (cp >> 18)); o += char(0x80 | ((cp >> 12) & 0x3F)); o += char(0x80 | ((cp >> 6) & 0x3F)); o += char(0x80 | (cp & 0x3F)); }
}
static std::string decode(const std::string& v) { // rapidxml default: decode entities in attr values
std::string o;
for (size_t i = 0; i < v.size(); ++i) {
if (v[i] != '&') { o += v[i]; continue; }
size_t semi = v.find(';', i);
if (semi == std::string::npos) { o += v[i]; continue; }
std::string e = v.substr(i + 1, semi - i - 1);
if (e == "amp") o += '&'; else if (e == "lt") o += '<'; else if (e == "gt") o += '>';
else if (e == "quot") o += '"'; else if (e == "apos") o += '\'';
else if (!e.empty() && e[0] == '#') {
unsigned long cp = (e.size() > 1 && e[1] == 'x') ? std::strtoul(e.c_str() + 2, nullptr, 16)
: std::strtoul(e.c_str() + 1, nullptr, 10);
appendUtf8(o, cp);
} else { o += v[i]; continue; }
i = semi;
}
return o;
}
bool parseChildren(Node& parent, bool top) {
for (;;) {
size_t lt = s_.find('<', p_);
if (lt == std::string::npos) { p_ = s_.size(); return top; }
p_ = lt;
if (starts("<?")) { skipPast("?>"); continue; }
if (starts("<!--")) { skipPast("-->"); continue; }
if (starts("<![CDATA[")) { skipPast("]]>"); continue; }
if (starts("<!")) { skipPast(">"); continue; }
if (starts("</")) { skipPast(">"); return !top; }
++p_;
Node n;
while (!eof() && nameChar(s_[p_])) n.name += s_[p_++];
if (n.name.empty()) return false; // "expected element name"
for (;;) {
ws();
if (eof()) return false;
if (s_[p_] == '/') { p_ += 2; parent.children.push_back(std::move(n)); break; }
if (s_[p_] == '>') { ++p_; if (!parseChildren(n, false)) return false; parent.children.push_back(std::move(n)); break; }
Attr a;
while (!eof() && nameChar(s_[p_])) a.name += s_[p_++];
if (a.name.empty()) return false; // "expected attribute name"
ws(); if (eof() || s_[p_] != '=') return false; ++p_; ws();
if (eof() || (s_[p_] != '"' && s_[p_] != '\'')) return false;
char q = s_[p_++];
size_t e = s_.find(q, p_);
if (e == std::string::npos) return false;
a.value = decode(s_.substr(p_, e - p_));
p_ = e + 1;
n.attrs.push_back(std::move(a));
}
}
}
};
} // namespace xml
// =============================================================================================
// Value converters (inlined everywhere in 0x40ed50)
// =============================================================================================
static int ToInt(const std::string& v) { return std::atoi(v.c_str()); }
static float ToFloat(const std::string& v) { return (float)std::atof(v.c_str()); }
static float ToScale(const std::string& v) { float f = ToFloat(v); return f / 100.0f; }
static float ToColor(const std::string& v) { float f = ToFloat(v); return f / 255.0f; }
static bool ToBool(const std::string& v) { // 0x4100b6
if (v.empty()) return false;
if (v == "true" || v == "True") return true;
return std::atoi(v.c_str()) != 0;
}
// fmodf as the game does it: 0x499d20 = (float)fmod((double)x, (double)y)
static float FmodF(float x, float y) { return (float)std::fmod((double)x, (double)y); }
// Spritesheet path resolver 0x67f670 (approximation; only skimmed): '\' -> '/', path is relative
// to the .anm2's directory, ".." pops a directory, result truncated to 0x104 chars.
static std::string ResolveRelativePath(const std::string& anmPath, const std::string& rel) {
auto split = [](std::string s) {
for (char& c : s) if (c == '\\') c = '/';
std::vector<std::string> parts; std::string cur;
for (char c : s) { if (c == '/') { if (!cur.empty()) parts.push_back(cur); cur.clear(); } else cur += c; }
if (!cur.empty()) parts.push_back(cur);
return parts;
};
std::vector<std::string> dir = split(anmPath);
if (!dir.empty()) dir.pop_back(); // drop file name
for (auto& part : split(rel)) {
if (part == "..") { if (!dir.empty()) dir.pop_back(); }
else if (part != ".") dir.push_back(part);
}
std::string out = (!anmPath.empty() && (anmPath[0] == '/' || anmPath[0] == '\\')) ? "/" : "";
for (size_t i = 0; i < dir.size(); ++i) { if (i) out += '/'; out += dir[i]; }
if (out.size() > 0x104) out.resize(0x104);
return out;
}
// =============================================================================================
// Color helpers
// =============================================================================================
Color LerpColor(const Color& a, const Color& b, float t) { // 0x6832e0: a*(1-t) + b*t, all 11 floats
float it = 1.0f - t;
Color o;
for (int i = 0; i < 4; ++i) o.tint[i] = a.tint[i] * it + b.tint[i] * t;
for (int i = 0; i < 4; ++i) o.colorize[i] = a.colorize[i] * it + b.colorize[i] * t;
for (int i = 0; i < 3; ++i) o.offset[i] = a.offset[i] * it + b.offset[i] * t;
return o;
}
void MulColor(Color& self, const Color& other) { // 0x6831c0
for (int i = 0; i < 4; ++i) self.tint[i] = other.tint[i] * self.tint[i];
if (other.colorize[0] + other.colorize[1] + other.colorize[2] != 0.0f) {
if (self.colorize[0] + self.colorize[1] + self.colorize[2] == 0.0f)
for (int i = 0; i < 4; ++i) self.colorize[i] = other.colorize[i];
else
for (int i = 0; i < 4; ++i) self.colorize[i] = (self.colorize[i] + other.colorize[i]) * 0.5f;
}
for (int i = 0; i < 3; ++i) self.offset[i] = other.offset[i] + self.offset[i];
}
static float WrapAngle(float x) {
if (std::fabs(x) > 360.0f) x = FmodF(x, 360.0f);
if (x > 180.0f) x -= 360.0f;
else if (x < -180.0f) x += 360.0f;
return x;
}
float LerpAngleDeg(float a, float b, float t) { // 0x6828b0
a = WrapAngle(a);
b = WrapAngle(b);
if (std::fabs(b - a) > 180.0f) { if (b > a) a += 360.0f; else b += 360.0f; }
return WrapAngle((b - a) * t + a);
}
// =============================================================================================
// Load-time interpolation: every interpolated keyframe (except the last) is expanded into `delay`
// one-tick frames. Nothing is interpolated at runtime.
// =============================================================================================
void InterpolateLayerFrames(std::vector<AnimationFrame>& src) { // 0x415170
std::vector<AnimationFrame> dst;
dst.reserve(src.size());
int tick = 0;
const unsigned count = (unsigned)src.size();
for (unsigned i = 0; i < count; ++i) {
const AnimationFrame& a = src[i];
if (i != count - 1 && a.interpolated) {
if (i + 1 >= (unsigned)kMaxFrames) Log(0x10, "too many frames after interpolation\n");
const AnimationFrame& b = src[i + 1];
float t = 0.0f;
const float step = 1.0f / (float)a.delay;
for (int k = 0; k < a.delay; ++k) { // delay <= 0 emits nothing
AnimationFrame o;
o.xCrop = a.xCrop; o.yCrop = a.yCrop; o.width = a.width; o.height = a.height;
o.x = (b.x - a.x) * t + a.x;
o.y = (b.y - a.y) * t + a.y;
o.xScale = (b.xScale - a.xScale) * t + a.xScale;
o.yScale = (b.yScale - a.yScale) * t + a.yScale;
o.xPivot = a.xPivot; o.yPivot = a.yPivot;
o.delay = 1;
o.visible = a.visible;
o.color = LerpColor(a.color, b.color, t);
o.rotation = LerpAngleDeg(a.rotation, b.rotation, t);
o.interpolated = a.interpolated;
o.start = tick; o.end = tick + 1; ++tick;
dst.push_back(o);
t = step + t; // accumulated, not k/delay
}
} else {
AnimationFrame o = a;
o.start = tick; o.end = tick + a.delay; tick += a.delay;
dst.push_back(o);
}
}
src.swap(dst);
}
void InterpolateNullFrames(std::vector<NullFrame>& src) { // 0x414e00
std::vector<NullFrame> dst;
dst.reserve(src.size());
int tick = 0;
const unsigned count = (unsigned)src.size();
for (unsigned i = 0; i < count; ++i) {
const NullFrame& a = src[i];
if (i != count - 1 && a.interpolated) {
if (i + 1 >= (unsigned)kMaxFrames) Log(0x10, "too many frames after interpolation\n");
const NullFrame& b = src[i + 1];
float t = 0.0f;
const float step = 1.0f / (float)a.delay;
for (int k = 0; k < a.delay; ++k) {
NullFrame o;
o.x = (b.x - a.x) * t + a.x;
o.y = (b.y - a.y) * t + a.y;
o.xScale = (b.xScale - a.xScale) * t + a.xScale;
o.yScale = (b.yScale - a.yScale) * t + a.yScale;
o.delay = 1;
o.visible = a.visible;
o.color = LerpColor(a.color, b.color, t);
o.rotation = LerpAngleDeg(a.rotation, b.rotation, t);
o.interpolated = a.interpolated;
o.start = tick; o.end = tick + 1; ++tick;
dst.push_back(o);
t = step + t;
}
} else {
NullFrame o = a;
o.start = tick; o.end = tick + a.delay; tick += a.delay;
dst.push_back(o);
}
}
src.swap(dst);
}
// =============================================================================================
// RootAnimation baking (inlined twice in the parser: layers 0x411df1, nulls 0x413017).
// Each track frame is cut wherever a root-frame boundary falls inside it; each piece gets the
// transform of the root frame active during it. Pieces keep the source `delay` (only start/end are
// updated) - the runtime only uses start/end.
// =============================================================================================
template <class Fr>
static std::vector<Fr> ApplyRoot(std::vector<Fr>& src, const std::vector<NullFrame>& root, const std::string& path) {
std::vector<Fr> dst;
const int rootCount = (int)root.size();
NullFrame identity; // ORIGINAL: with 0 root frames it applies stale scratch slot root[0] (undefined)
int g = 0, r = 0;
for (Fr& s : src) {
s.start = g;
for (int k = 0; k < s.delay; ++k) {
++g;
const 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; // a root frame ended on this tick
}
if (!emit && k == s.delay - 1) emit = true; // last tick of the source frame
if (!emit) continue;
if ((int)dst.size() >= kMaxFrames)
Log(0x10, "%s: too many frames after interpolation/root frame adjustment\n", path.c_str());
const NullFrame& R = rootCount ? root[prev] : identity;
Fr o = s;
o.x = o.x * R.xScale + R.x;
o.y = R.yScale * o.y + R.y;
o.visible = o.visible && R.visible;
o.xScale = o.xScale * R.xScale;
o.yScale = R.yScale * o.yScale;
MulColor(o.color, R.color);
o.rotation = R.rotation + o.rotation;
o.end = g;
dst.push_back(o);
s.start = g;
}
}
return dst;
}
// =============================================================================================
// Frame attribute readers. Only tint (1) and offset (0) are reset per frame in the original; any
// other missing attribute keeps whatever was left in a reused 5000-entry scratch buffer.
// Here missing attributes take the struct defaults instead (pos 0, scale 1, delay 1, visible, rot 0).
// =============================================================================================
static void ReadNullFrame(const xml::Node& fr, NullFrame& f) {
float tint[4] = {1, 1, 1, 1}, off[3] = {0, 0, 0};
for (auto& a : fr.attrs) {
const std::string& n = a.name; const std::string& v = a.value;
if (n == "XPosition") f.x = ToFloat(v);
else if (n == "YPosition") f.y = ToFloat(v);
else if (n == "Delay") f.delay = ToInt(v);
else if (n == "Visible") f.visible = ToBool(v);
else if (n == "XScale") f.xScale = ToScale(v);
else if (n == "YScale") f.yScale = ToScale(v);
else if (n == "RedTint") tint[0] = ToColor(v);
else if (n == "GreenTint") tint[1] = ToColor(v);
else if (n == "BlueTint") tint[2] = ToColor(v);
else if (n == "AlphaTint") tint[3] = ToColor(v);
else if (n == "RedOffset") off[0] = ToColor(v);
else if (n == "GreenOffset") off[1] = ToColor(v);
else if (n == "BlueOffset") off[2] = ToColor(v);
else if (n == "Rotation") f.rotation = ToFloat(v);
else if (n == "Interpolated") f.interpolated = ToBool(v);
}
for (int i = 0; i < 4; ++i) f.color.tint[i] = tint[i];
for (int i = 0; i < 3; ++i) f.color.offset[i] = off[i];
}
static void ReadLayerFrame(const xml::Node& fr, AnimationFrame& f) {
float tint[4] = {1, 1, 1, 1}, off[3] = {0, 0, 0};
for (auto& a : fr.attrs) {
const std::string& n = a.name; const std::string& v = a.value;
if (n == "XPosition") f.x = ToFloat(v);
else if (n == "YPosition") f.y = ToFloat(v);
else if (n == "XPivot") f.xPivot = ToFloat(v);
else if (n == "YPivot") f.yPivot = ToFloat(v);
else if (n == "Width") f.width = ToFloat(v);
else if (n == "Height") f.height = ToFloat(v);
else if (n == "XScale") f.xScale = ToScale(v);
else if (n == "YScale") f.yScale = ToScale(v);
else if (n == "Delay") f.delay = ToInt(v);
else if (n == "Visible") f.visible = ToBool(v);
else if (n == "XCrop") f.xCrop = ToFloat(v);
else if (n == "YCrop") f.yCrop = ToFloat(v);
else if (n == "RedTint") tint[0] = ToColor(v);
else if (n == "GreenTint") tint[1] = ToColor(v);
else if (n == "BlueTint") tint[2] = ToColor(v);
else if (n == "AlphaTint") tint[3] = ToColor(v);
else if (n == "RedOffset") off[0] = ToColor(v);
else if (n == "GreenOffset") off[1] = ToColor(v);
else if (n == "BlueOffset") off[2] = ToColor(v);
else if (n == "Rotation") f.rotation = ToFloat(v);
else if (n == "Interpolated") f.interpolated = ToBool(v);
}
for (int i = 0; i < 4; ++i) f.color.tint[i] = tint[i];
for (int i = 0; i < 3; ++i) f.color.offset[i] = off[i];
}
// Required child lookup. ORIGINAL: never NULL-checked; a missing element crashes the game.
static const xml::Node* Need(const xml::Node* parent, const char* name, const std::string& path) {
const xml::Node* n = parent ? parent->child(name) : nullptr;
if (!n) Log(0x10, "%s: missing <%s> (the original crashes here)\n", path.c_str(), name);
return n;
}
// =============================================================================================
// AnmCache::LoadFile 0x40ed50
// =============================================================================================
bool ParseAnm2(const std::string& path, const std::string& text, AnmData& d) {
d = AnmData{}; // entry->Clear() (ORIGINAL: defaultAnimation survives Clear(); see notes)
xml::Node doc;
if (!xml::Parser(text).parse(doc)) { Log(0x10, "%s: XML parse error\n", path.c_str()); return false; }
const xml::Node* actor = Need(&doc, "AnimatedActor", path);
const xml::Node* content = Need(actor, "Content", path);
if (!content) return false;
// ---- Spritesheets (not stored; each layer receives a copy of its sheet's path) ----
// Children are never filtered by tag name.
const xml::Node* sheets = Need(content, "Spritesheets", path);
if (!sheets) return false;
std::string sheetPath[kMaxLayers];
std::string pathBuf; // ORIGINAL: char[260] not cleared between elements -> a Path-less sheet reuses the previous one
int sheetCount = 0;
for (auto& e : sheets->children) {
int id = kMaxLayers;
for (auto& a : e.attrs) {
if (a.name == "Path") pathBuf = ResolveRelativePath(path, a.value);
else if (a.name == "Id") id = ToInt(a.value);
}
if (id >= kMaxLayers || id != sheetCount)
Log(0x10, "%s: invalid spritesheet id %d\n", path.c_str(), id);
if (id >= 0 && id < kMaxLayers) sheetPath[id] = pathBuf; // ORIGINAL: stored at [id] unchecked
++sheetCount;
}
// ---- Layers ----
const xml::Node* layers = Need(content, "Layers", path);
if (!layers) return false;
LayerInfo layer[kMaxLayers];
int layerCount = 0;
for (auto& e : layers->children) {
std::string name; int id = kMaxLayers; int sheet = -1;
for (auto& a : e.attrs) {
if (a.name == "Name") name = a.value;
else if (a.name == "Id") id = ToInt(a.value);
else if (a.name == "SpritesheetId") sheet = ToInt(a.value);
}
if (id >= kMaxLayers || id != layerCount) Log(0x10, "%s: invalid layer id %d\n", path.c_str(), id);
if (sheet < 0 || sheet >= sheetCount) Log(0x10, "%s: invalid spritesheet id %d\n", path.c_str(), sheet);
if (id >= 0 && id < kMaxLayers) {
LayerInfo& L = layer[id];
L.spritesheetPath = (sheet >= 0 && sheet < kMaxLayers) ? sheetPath[sheet] : std::string();
L.id = id; L.spritesheetId = sheet; L.name = name;
}
++layerCount;
}
if (layerCount == 0) Log(0x10, "%s: no layers\n", path.c_str()); // only logged
for (int i = 0; i < layerCount && i < kMaxLayers; ++i) d.layers.push_back(layer[i]);
// ---- Nulls ----
const xml::Node* nulls = Need(content, "Nulls", path);
if (!nulls) return false;
std::string nullName[kMaxLayers];
int nullCount = 0;
for (auto& e : nulls->children) {
int id = kMaxLayers; std::string name;
for (auto& a : e.attrs) {
if (a.name == "Id") id = ToInt(a.value);
else if (a.name == "Name") name = a.value;
}
if (id >= kMaxLayers || id != nullCount) Log(0x10, "%s: invalid Null ID %d\n", path.c_str(), id);
if (id >= 0 && id < kMaxLayers) nullName[id] = name;
++nullCount;
}
for (int i = 0; i < nullCount && i < kMaxLayers; ++i) d.nullNames.push_back(nullName[i]);
// ---- Events (max 16) ----
const xml::Node* events = Need(content, "Events", path);
if (!events) return false;
std::string eventName[kMaxEvents];
int eventCount = 0;
for (auto& e : events->children) {
int id = kMaxEvents; std::string name;
for (auto& a : e.attrs) {
if (a.name == "Id") id = ToInt(a.value);
else if (a.name == "Name") name = a.value;
}
if (id >= kMaxEvents || id != eventCount) Log(0x10, "%s: invalid Event ID %d\n", path.c_str(), id);
if (id >= 0 && id < kMaxEvents) eventName[id] = name;
++eventCount;
}
for (int i = 0; i < eventCount && i < kMaxEvents; ++i) d.eventNames.push_back(eventName[i]);
// ---- Animations ----
const xml::Node* anims = Need(actor, "Animations", path);
if (!anims) return false;
for (auto& a : anims->attrs) if (a.name == "DefaultAnimation") d.defaultAnimation = a.value;
// Iteration starts at first_node("Animation") and then follows next_sibling WITHOUT a name check.
size_t firstAnim = anims->children.size();
for (size_t i = 0; i < anims->children.size(); ++i)
if (anims->children[i].name == "Animation") { firstAnim = i; break; }
for (size_t ai = firstAnim; ai < anims->children.size(); ++ai) {
const xml::Node& an = anims->children[ai];
if ((int)d.animations.size() >= kMaxAnimations)
Log(0x10, "%s: more than %d animations (the original overflows its stack here)\n", path.c_str(), kMaxAnimations);
AnimationData A;
for (auto& a : an.attrs) {
if (a.name == "Name") A.name = a.value;
else if (a.name == "FrameNum") A.frameNum = ToInt(a.value);
else if (a.name == "Loop") A.loop = ToBool(a.value);
}
A.index = (int)d.animations.size();
// RootAnimation
const xml::Node* rootNode = Need(&an, "RootAnimation", path);
std::vector<NullFrame> root;
if (rootNode) {
int t = 0;
for (auto& fr : rootNode->children) {
if ((int)root.size() >= kMaxFrames) Log(0x10, "%s: too many root frames\n", path.c_str());
NullFrame f; ReadNullFrame(fr, f);
f.start = t; f.end = t + f.delay; t = f.end;
root.push_back(f);
}
}
InterpolateNullFrames(root);
// LayerAnimations
if (const xml::Node* las = Need(&an, "LayerAnimations", path)) {
for (auto& ln : las->children) {
if ((int)A.layerAnims.size() >= kMaxLayers) Log(0x10, "%s: too many animation layers\n", path.c_str());
LayerAnimation L;
for (auto& a : ln.attrs) {
if (a.name == "LayerId") L.layerId = ToInt(a.value);
else if (a.name == "Visible") L.visible = ToBool(a.value);
}
std::vector<AnimationFrame> frames;
int t = 0;
for (auto& fr : ln.children) {
if ((int)frames.size() >= kMaxFrames) Log(0x10, "%s: too many animation frames\n", path.c_str());
AnimationFrame f; ReadLayerFrame(fr, f);
f.start = t; f.end = t + f.delay; t = f.end;
frames.push_back(f);
}
InterpolateLayerFrames(frames);
L.frames = ApplyRoot(frames, root, path);
A.layerAnims.push_back(std::move(L));
}
// map[LayerId] = index; last duplicate wins.
// ORIGINAL: unchecked; LayerId -1 overwrites Loop (+0x34), >=64 writes past the array.
for (int i = 0; i < (int)A.layerAnims.size(); ++i) {
int id = A.layerAnims[i].layerId;
if (id >= 0 && id < kMaxLayers) A.layerMap[id] = i;
}
}
// NullAnimations (no id validation, no map)
if (const xml::Node* nas = Need(&an, "NullAnimations", path)) {
for (auto& nn : nas->children) {
if ((int)A.nullAnims.size() >= kMaxLayers) Log(0x10, "%s: too many null layers\n", path.c_str());
NullAnimation N;
for (auto& a : nn.attrs) {
if (a.name == "NullId") N.nullId = ToInt(a.value);
else if (a.name == "Visible") N.visible = ToBool(a.value);
}
std::vector<NullFrame> frames;
int t = 0;
for (auto& fr : nn.children) {
if ((int)frames.size() >= kMaxFrames) Log(0x10, "%s: too many null frames\n", path.c_str());
NullFrame f; ReadNullFrame(fr, f);
f.start = t; f.end = t + f.delay; t = f.end;
frames.push_back(f);
}
InterpolateNullFrames(frames);
N.frames = ApplyRoot(frames, root, path);
A.nullAnims.push_back(std::move(N));
}
}
// Triggers (max 128; EventId and AtFrame are raw ints, never validated)
if (const xml::Node* trs = Need(&an, "Triggers", path)) {
for (auto& te : trs->children) {
if ((int)A.triggers.size() >= kMaxTriggers) Log(0x10, "%s: too many triggers\n", path.c_str());
Trigger T; // ORIGINAL: local array not reset -> missing attrs keep a previous trigger's values
for (auto& a : te.attrs) {
if (a.name == "EventId") T.eventId = ToInt(a.value);
else if (a.name == "AtFrame") T.atFrame = ToInt(a.value);
}
A.triggers.push_back(T);
}
}
d.animations.push_back(std::move(A));
}
return true;
}
bool LoadAnm2File(const std::string& path, AnmData& out) {
std::ifstream f(path, std::ios::binary);
if (!f) { Log(1, "ERROR Could not open %s\n", path.c_str()); return false; }
std::stringstream ss; ss << f.rdbuf();
return ParseAnm2(path, ss.str(), out);
}
// =============================================================================================
// AnimationState
// =============================================================================================
static int FloorToInt(float f) {
// floor() on the double, stored back to float, then cvttss2si
float fl = (float)std::floor((double)f);
return (int)fl;
}
int AnimationState::FindEvent(const char* name) const {
if (!anim_) Log(0x10, "AnimationData is NULL\n"); // logged, not returned
const AnmData* d = owner_->data_;
if (!d) return -1;
for (size_t i = 0; i < d->eventNames.size(); ++i)
if (std::strcmp(d->eventNames[i].c_str(), name) == 0) return (int)i;
return -1;
}
// 0x408830: hard reset. Index arrays are reallocated to the new animation's sizes and filled
// with -1, frame = -1.0f, not playing, both event masks cleared.
void AnimationState::SetAnimationData(const AnimationData* a) {
anim_ = a;
layerFrameIdx_.assign(a ? a->layerAnims.size() : 0, -1);
nullFrameIdx_.assign(a ? a->nullAnims.size() : 0, -1);
frame_ = -1.0f;
playing_ = false;
eventsThisUpdate_ = 0;
eventsSinceStart_ = 0;
}
// 0x408970: switch animation, keep frame / playing / masks / existing per-track indices.
// ORIGINAL BUGS (not reproduced):
// * it memcpy's the OLD layer count into the NEW index array -> heap overflow when the new animation
// has fewer layer-anims;
// * when the null-anim count changes to a non-zero value, the new null array is stored into the
// LAYER slot (`mov [esi+8], ebx` @0x408b6a) and the null slot is left NULL -> the next Update
// dereferences NULL. I.e. Sprite:SetAnimation(name, false) between animations with different
// non-zero null counts crashes the game.
void AnimationState::ChangeAnimationKeepFrame(const AnimationData* a) {
size_t nl = a ? a->layerAnims.size() : 0, nn = a ? a->nullAnims.size() : 0;
if (layerFrameIdx_.size() != nl) layerFrameIdx_.resize(nl, -1);
if (nullFrameIdx_.size() != nn) nullFrameIdx_.resize(nn, -1);
anim_ = a;
}
// 0x408c90. Exact float equality between the current frame and AtFrame. Both masks get the bit;
// `bts reg, id` means bit (eventId & 31).
void AnimationState::FireTriggersAtCurrentFrame() {
if (!anim_) { Log(0x10, "AnimationData is NULL\n"); return; } // ORIGINAL: continues and crashes
for (const Trigger& t : anim_->triggers) {
if ((float)t.atFrame == frame_) {
eventsThisUpdate_ |= 1u << (t.eventId & 31);
eventsSinceStart_ |= 1u << (t.eventId & 31);
}
}
}
// 0x40a1b0
void AnimationState::Rewind() {
frame_ = 0.0f;
eventsThisUpdate_ = 0;
eventsSinceStart_ = 0;
FireTriggersAtCurrentFrame(); // events on frame 0 fire immediately on Play
for (int& i : layerFrameIdx_) i = 0;
for (int& i : nullFrameIdx_) i = 0;
}
// 0x408b90: move forward while the current keyframe has ended. Never moves backward.
void AnimationState::AdvanceLayerPosition(int i, float t) {
if (!anim_ || i < 0 || i >= (int)anim_->layerAnims.size()) { Log(0x10, "id out of bounds\n"); return; }
const auto& frames = anim_->layerAnims[i].frames;
int& idx = layerFrameIdx_[i];
while (idx >= 0 && idx + 1 < (int)frames.size() && t >= (float)frames[idx].end) ++idx;
}
// 0x408c10
void AnimationState::AdvanceNullLayerPosition(int i, float t) {
if (!anim_ || i < 0 || i >= (int)anim_->nullAnims.size()) { Log(0x10, "id out of bounds\n"); return; }
const auto& frames = anim_->nullAnims[i].frames;
int& idx = nullFrameIdx_[i];
while (idx >= 0 && idx + 1 < (int)frames.size() && t >= (float)frames[idx].end) ++idx;
}
// 0x408d00: step one whole frame at a time up to `target`, firing triggers on every integer frame
// passed. eventsThisUpdate is cleared first, so it reflects only frames crossed by this call.
void AnimationState::AdvancePosition(int target) {
int cur = FloorToInt(frame_);
if (target < cur)
Log(0x10, "Animation::AdvancePosition cannot go backward (new: %d, cur: %d)\n", target, cur);
const float t = (float)target;
eventsThisUpdate_ = 0;
while (t > frame_) {
frame_ = (float)std::floor((double)frame_) + 1.0f;
FireTriggersAtCurrentFrame();
}
for (int i = 0; i < (int)anim_->layerAnims.size(); ++i) AdvanceLayerPosition(i, t);
for (int i = 0; i < (int)anim_->nullAnims.size(); ++i) AdvanceNullLayerPosition(i, t);
}
// 0x409030
void AnimationState::Update() {
if (!anim_ || !playing_) return; // NB: event masks are NOT cleared while stopped
const float oldFrame = frame_;
const float newFrame = frame_ + owner_->playbackSpeed;
const int nf = FloorToInt(newFrame);
if (nf >= anim_->frameNum) {
if (anim_->loop) {
// Frames between the old position and FrameNum-1 are NOT stepped through (only matters
// for speed > 1), and the fractional overshoot is dropped.
Rewind();
return;
}
int last = anim_->frameNum - 1;
if (last >= FloorToInt(oldFrame)) AdvancePosition(last);
playing_ = false; // frame_ stays at FrameNum-1 (an integer)
return;
}
AdvancePosition(nf); // with speed < 0 this logs "cannot go backward" and fires nothing
frame_ = newFrame; // keep the fractional part
}
// 0x408e00: jump directly to a frame. Clamped to just below FrameNum; triggers fire only if the
// clamped frame equals AtFrame exactly. eventsSinceStart is NOT cleared. Track indices are reset to 0
// and advanced to the UNCLAMPED value.
void AnimationState::SetFrame(float f) {
float maxF = std::nextafterf((float)anim_->frameNum, 0.0f);
frame_ = (maxF < f) ? maxF : f; // minss
eventsThisUpdate_ = 0;
FireTriggersAtCurrentFrame();
for (int i = 0; i < (int)anim_->layerAnims.size(); ++i) { layerFrameIdx_[i] = 0; AdvanceLayerPosition(i, f); }
for (int i = 0; i < (int)anim_->nullAnims.size(); ++i) { nullFrameIdx_[i] = 0; AdvanceNullLayerPosition(i, f); }
}
// 0x408ef0 / 0x40a7e0: layerId goes through layerMap.
void AnimationState::SetLayerFrame(int layerId, int frame) {
const AnmData* d = owner_->data_;
if (!anim_) return;
if (layerId < 0 || !d || layerId >= (int)d->layers.size()) { Log(0x10, "LayerId out of bounds\n"); return; }
int la = (layerId < kMaxLayers) ? anim_->layerMap[layerId] : -1;
if (la < 0 || la >= (int)anim_->layerAnims.size()) {
Log(0x10, "id out of bounds\n");
return; // ORIGINAL: logs, then writes layerFrameIdx[-1] = 0 anyway
}
layerFrameIdx_[la] = 0;
AdvanceLayerPosition(la, (float)frame);
}
// 0x408fc0: index is the null-ANIMATION index (no map), bounds-checked against the sprite's null count.
void AnimationState::SetNullLayerFrame(int i, int frame) {
const AnmData* d = owner_->data_;
if (i < 0 || !d || i >= (int)d->nullNames.size()) Log(0x10, "layerId out of bounds\n");
if (!anim_ || i < 0 || i >= (int)anim_->nullAnims.size()) { Log(0x10, "id out of bounds\n"); return; }
nullFrameIdx_[i] = 0;
AdvanceNullLayerPosition(i, (float)frame);
}
bool AnimationState::IsEventTriggered(const char* name) const { // 0x40add0
int i = FindEvent(name);
return i >= 0 && (eventsThisUpdate_ & (1u << i)) != 0;
}
bool AnimationState::WasEventTriggered(const char* name) const { // 0x40ae70
int i = FindEvent(name);
return i >= 0 && (eventsSinceStart_ & (1u << i)) != 0;
}
// 0x40af10: nearest trigger frame strictly after the current frame (truncated, not floored), or -1.
int AnimationState::NextEventTrigger(const char* name) const {
int ev = FindEvent(name);
if (ev < 0) return -1;
int best = -1, bestDist = -1;
const int cur = (int)frame_; // cvttss2si
for (const Trigger& t : anim_->triggers) {
if (t.eventId != ev) continue;
int dist = t.atFrame - cur;
if (dist > 0 && (bestDist < 0 || dist < bestDist)) { best = t.atFrame; bestDist = dist; }
}
return best;
}
const AnimationFrame* AnimationState::GetLayerFrame(int layerId) const { // 0x40a220
if (!anim_) { Log(0x10, "AnimationData is NULL\n"); return nullptr; }
const AnmData* d = owner_->data_;
if (layerId < 0 || !d || layerId >= (int)d->layers.size()) Log(0x10, "LayerId out of bounds\n");
// ORIGINAL quirk: the second bounds test is `layerId > layerCount` (jg), i.e. off by one.
if (layerId < 0 || layerId >= kMaxLayers || !d || layerId > (int)d->layers.size()) return nullptr;
int la = anim_->layerMap[layerId];
if (la < 0 || la >= (int)anim_->layerAnims.size()) return nullptr;
int fi = layerFrameIdx_[la];
const auto& fr = anim_->layerAnims[la].frames;
if (fi < 0 || fi >= (int)fr.size()) return nullptr;
return &fr[fi];
}
const NullFrame* AnimationState::GetNullFrameByID(int nullId) const { // 0x40ac70: first match with a valid index
if (!anim_) { Log(0x10, "AnimationData is NULL\n"); return nullptr; }
for (size_t i = 0; i < anim_->nullAnims.size(); ++i) {
const NullAnimation& n = anim_->nullAnims[i];
int fi = nullFrameIdx_[i];
if (n.nullId == nullId && fi >= 0 && fi < (int)n.frames.size()) return &n.frames[fi];
}
return nullptr;
}
const NullFrame* AnimationState::GetNullFrame(const char* name) const { // 0x40ace0
const AnmData* d = owner_->data_;
if (!d) return nullptr;
for (size_t i = 0; i < d->nullNames.size(); ++i)
if (std::strcmp(d->nullNames[i].c_str(), name) == 0) return GetNullFrameByID((int)i);
return nullptr;
}
// =============================================================================================
// Sprite (ANM2)
// =============================================================================================
void Sprite::Load(const AnmData* data) {
data_ = data; // ORIGINAL: borrowed pointers into the AnmCache entry
main_.SetAnimationData(nullptr);
overlay_.SetAnimationData(nullptr);
loaded_ = true; // ORIGINAL: set even if the cache load failed
}
void Sprite::Reset() {
main_.SetAnimationData(nullptr);
overlay_.SetAnimationData(nullptr);
data_ = nullptr;
playbackSpeed = 1.0f;
overlayRenderFirst = false;
loaded_ = false;
}
// 0x409100: both states advance with the same PlaybackSpeed.
void Sprite::Update() {
if (!loaded_) return;
main_.Update();
overlay_.Update();
}
const AnimationData* Sprite::FindAnimation(const char* name) const {
if (data_)
for (const AnimationData& a : data_->animations)
if (std::strcmp(a.name.c_str(), name) == 0) return &a;
return nullptr;
}
// 0x40a5d0 / 0x40aaf0
bool Sprite::SetAnimation(const char* name, bool reset) {
const AnimationData* a = FindAnimation(name);
if (!a) { Log(1, "[warn] no animation named %s\n", name); return false; }
if (reset) main_.SetAnimationData(a); else main_.ChangeAnimationKeepFrame(a);
return true;
}
bool Sprite::SetOverlayAnimation(const char* name, bool reset) {
const AnimationData* a = FindAnimation(name);
if (!a) { Log(1, "[warn] no animation named %s\n", name); return false; }
if (reset) overlay_.SetAnimationData(a); else overlay_.ChangeAnimationKeepFrame(a);
return true;
}
// Shared logic of Play / PlayOverlay / PlayRandom / PlayIndex. Without `force`, playing the
// animation that is already current does nothing if it is non-looping (even when it has finished),
// or if it is looping and still playing. A stopped looping animation restarts.
static bool ShouldRestart(const AnimationState& s, const char* name, bool force) {
if (force || !s.anim()) return true;
if (std::strcmp(s.anim()->name.c_str(), name) != 0) return true;
if (!s.anim()->loop) return false;
return !s.playing();
}
void Sprite::Play(const char* name, bool force) { // 0x40a380
if (!ShouldRestart(main_, name, force)) return;
if (SetAnimation(name, true)) { main_.Rewind(); main_.setPlaying(true); }
}
void Sprite::PlayOverlay(const char* name, bool force) { // 0x40a940
if (!ShouldRestart(overlay_, name, force)) return;
if (SetOverlayAnimation(name, true)) { overlay_.Rewind(); overlay_.setPlaying(true); }
}
void Sprite::PlayRandom(uint32_t seed) { // 0x40a2b0: animation index = seed % count (unsigned)
if (!data_ || data_->animations.empty()) { Log(1, "[warn] PlayRandom: no animations\n"); return; }
const char* name = data_->animations[seed % (uint32_t)data_->animations.size()].name.c_str();
if (!ShouldRestart(main_, name, false)) return;
if (SetAnimation(name, true)) { main_.Rewind(); main_.setPlaying(true); }
}
void Sprite::PlayIndex(int index) { // 0x40a400
if (!data_ || index < 0 || index >= (int)data_->animations.size()) {
Log(1, "[warn] Animation index out of range!\n"); return;
}
const char* name = data_->animations[index].name.c_str();
if (!ShouldRestart(main_, name, false)) return;
if (SetAnimation(name, true)) { main_.Rewind(); main_.setPlaying(true); }
}
// 0x40a6e0: selects (hard reset), jumps, and STOPS the main animation.
void Sprite::SetFrame(const char* name, int frame) {
if (!SetAnimation(name, true) || !main_.anim()) return;
main_.SetFrame((float)frame);
main_.setPlaying(false);
}
void Sprite::SetFrame(float frame) { if (main_.anim()) main_.SetFrame(frame); } // 0x40a740 (keeps playing)
void Sprite::SetLastFrame() { // 0x40a760: does not stop playback
if (main_.anim()) main_.AdvancePosition(main_.anim()->frameNum - 1);
}
int Sprite::GetFrame() const { return main_.anim() ? FloorToInt(main_.frame()) : -1; } // 0x40a780
void Sprite::Stop() { if (main_.anim()) main_.setPlaying(false); } // 0x40a910
bool Sprite::IsPlaying(const char* name) const { // 0x40a4d0
if (!main_.anim() || !main_.playing()) return false;
return name[0] == 0 || std::strcmp(main_.anim()->name.c_str(), name) == 0;
}
bool Sprite::IsFinished(const char* name) const { // 0x40a550
if (!main_.anim()) return name[0] == 0;
if (main_.playing()) return false;
return name[0] == 0 || std::strcmp(main_.anim()->name.c_str(), name) == 0;
}
// 0x40b030 / 0x40b090: main state only (Repentogon adds overlay variants).
bool Sprite::IsEventTriggered(const char* name) const { return main_.anim() && main_.IsEventTriggered(name); }
bool Sprite::WasEventTriggered(const char* name) const { return main_.anim() && main_.WasEventTriggered(name); }
void Sprite::SetLayerFrame(int layerId, int frame) { if (main_.anim()) main_.SetLayerFrame(layerId, frame); }
// 0x40abf0: unlike SetFrame(name, frame), does NOT stop the overlay.
void Sprite::SetOverlayFrame(const char* name, int frame) {
if (!SetOverlayAnimation(name, true) || !overlay_.anim()) return;
overlay_.SetFrame((float)frame);
}
void Sprite::SetOverlayFrame(int frame) { if (overlay_.anim()) overlay_.SetFrame((float)frame); } // 0x40ac30
int Sprite::GetOverlayFrame() const { return overlay_.anim() ? (int)overlay_.frame() : -1; } // 0x40ac50: truncates
void Sprite::StopOverlay() { if (overlay_.anim()) overlay_.setPlaying(false); } // 0x40a9c0
void Sprite::RemoveOverlay() { overlay_.SetAnimationData(nullptr); } // 0x40ac60
bool Sprite::IsOverlayPlaying(const char* name) const { // 0x40a9f0
if (!overlay_.anim() || !overlay_.playing()) return false;
return name[0] == 0 || std::strcmp(overlay_.anim()->name.c_str(), name) == 0;
}
bool Sprite::IsOverlayFinished(const char* name) const { // 0x40aa70
if (!overlay_.anim()) return name[0] == 0;
if (overlay_.playing()) return false;
return name[0] == 0 || std::strcmp(overlay_.anim()->name.c_str(), name) == 0;
}
} // namespace anm2
+225
View File
@@ -0,0 +1,225 @@
// Reimplementation of The Binding of Isaac: Repentance+ (isaac-ng.exe v1.9.7.17) .anm2 handling.
// Reverse-engineered from the shipped binary; addresses in comments refer to that build (ImageBase 0x400000).
//
// Scope: XML parsing + load-time frame baking (AnmCache::LoadFile 0x40ed50), and the runtime
// AnimationState / Sprite (ANM2) playback and event-trigger logic. Rendering and texture loading are
// out of scope (only the data the renderer consumes is produced).
//
// Behaviour is matched 1:1 for well-formed files. Where the original reads uninitialised memory,
// overflows fixed arrays, or crashes, this code picks a safe behaviour instead; every such spot is
// marked "ORIGINAL:" so you can see what the game actually does.
#pragma once
#include <cstdint>
#include <functional>
#include <string>
#include <vector>
namespace anm2 {
// KAGE_LogMessage(level, fmt, ...) @0xa112c0. Levels seen: 1 = warn, 4 = info, 0x10 = error/assert.
using LogFn = std::function<void(int level, const std::string& msg)>;
void SetLogger(LogFn fn);
// ---------------------------------------------------------------------------------------------
// Data (what the parser produces). Original layouts given as offsets for cross-reference.
// ---------------------------------------------------------------------------------------------
// ColorMod, 0x2c bytes. ctor 0x407170, Lerp 0x6832e0, operator*= 0x6831c0.
struct Color {
float tint[4] = {1, 1, 1, 1}; // +0x00 Red/Green/Blue/AlphaTint / 255
float colorize[4] = {0, 0, 0, 0}; // +0x10 never written by the parser
float offset[3] = {0, 0, 0}; // +0x20 Red/Green/BlueOffset / 255
};
// AnimationFrame, 0x6c bytes (layer keyframe after baking).
struct AnimationFrame {
float xCrop = 0, yCrop = 0; // +0x00 +0x04
float width = 0, height = 0; // +0x08 +0x0c
float x = 0, y = 0; // +0x10 +0x14 XPosition/YPosition
float xScale = 1, yScale = 1; // +0x18 +0x1c XScale/100, YScale/100
float xPivot = 0, yPivot = 0; // +0x20 +0x24
int delay = 1; // +0x28
bool visible = true; // +0x2c
Color color; // +0x30
float rotation = 0; // +0x5c degrees
bool interpolated = false; // +0x60
int start = 0; // +0x64 first tick (inclusive)
int end = 0; // +0x68 last tick (exclusive)
};
// NullFrame, 0x54 bytes. Used for null-layer frames AND root frames.
struct NullFrame {
float x = 0, y = 0; // +0x00 +0x04
int delay = 1; // +0x08
bool visible = true; // +0x0c
float xScale = 1, yScale = 1; // +0x10 +0x14
Color color; // +0x18
float rotation = 0; // +0x44
bool interpolated = false; // +0x48
int start = 0; // +0x4c
int end = 0; // +0x50
};
struct LayerAnimation { // 0x10, ctor 0x40c1e0
int layerId = -1; // +0x0
std::vector<AnimationFrame> frames;// +0x4 / +0x8
bool visible = true; // +0xc
};
struct NullAnimation { // 0x10, ctor 0x40c210
int nullId = 0; // +0x0 ORIGINAL: no default (stale stack value)
bool visible = true; // +0x4 ORIGINAL: no default
std::vector<NullFrame> frames; // +0x8 / +0xc
};
struct Trigger { int eventId = 0; int atFrame = 0; }; // 8 bytes
constexpr int kMaxLayers = 64; // spritesheets / layers / nulls / layer- and null-anims per animation
constexpr int kMaxEvents = 16; // "invalid Event ID" if id >= 16
constexpr int kMaxTriggers = 128;
constexpr int kMaxFrames = 5000; // per track, before and after baking
constexpr int kMaxAnimations = 256; // ORIGINAL: stack array, no check at all
struct AnimationData { // 0x13c, ctor 0x40bec0
std::string name; // +0x000
std::vector<LayerAnimation> layerAnims; // +0x018 / +0x01c
std::vector<NullAnimation> nullAnims; // +0x020 / +0x024
std::vector<Trigger> triggers; // +0x028 / +0x02c
int frameNum = 0; // +0x030
bool loop = false; // +0x034
int layerMap[kMaxLayers]; // +0x038 LayerId -> index into layerAnims, -1 = none
int index = 0; // +0x138 position in file
AnimationData() { for (int& v : layerMap) v = -1; }
};
struct LayerInfo { // 0x38, ctor 0x40d140
int id = 0; // +0x00
int spritesheetId = -1; // +0x04
std::string name; // +0x08
std::string spritesheetPath; // +0x20 resolved, relative to the .anm2's directory
};
// AnmCache entry (map node + 0x14). Sprites borrow pointers into this.
struct AnmData {
std::vector<LayerInfo> layers; // +0x04 / +0x08
std::vector<AnimationData> animations; // +0x0c / +0x10
std::vector<std::string> nullNames; // +0x14 / +0x18
std::vector<std::string> eventNames; // +0x1c / +0x20
std::string defaultAnimation; // +0x24
};
// AnmCache::LoadFile @0x40ed50 minus the file I/O. `path` is only used for messages and for
// resolving spritesheet paths. Returns false only if the XML is unusable (the original crashes on
// a missing required element; see anm2.cpp).
bool ParseAnm2(const std::string& path, const std::string& xmlText, AnmData& out);
bool LoadAnm2File(const std::string& path, AnmData& out);
// Load-time baking helpers (exposed for testing).
void InterpolateLayerFrames(std::vector<AnimationFrame>& frames); // 0x415170
void InterpolateNullFrames(std::vector<NullFrame>& frames); // 0x414e00
float LerpAngleDeg(float a, float b, float t); // 0x6828b0
Color LerpColor(const Color& a, const Color& b, float t); // 0x6832e0
void MulColor(Color& self, const Color& other); // 0x6831c0
// ---------------------------------------------------------------------------------------------
// Runtime
// ---------------------------------------------------------------------------------------------
class Sprite;
// AnimationState, 0x20 bytes. Sprite has two: main @+0x30 and overlay @+0x50.
class AnimationState {
public:
explicit AnimationState(Sprite* owner) : owner_(owner) {}
void SetAnimationData(const AnimationData* a); // 0x408830 (hard reset)
void ChangeAnimationKeepFrame(const AnimationData* a); // 0x408970
void Rewind(); // 0x40a1b0
void Update(); // 0x409030
void AdvancePosition(int targetFrame); // 0x408d00
void SetFrame(float frame); // 0x408e00
void SetLayerFrame(int layerId, int frame); // 0x408ef0
void SetNullLayerFrame(int nullAnimIdx, int frame); // 0x408fc0
bool IsEventTriggered(const char* name) const; // 0x40add0
bool WasEventTriggered(const char* name) const; // 0x40ae70
int NextEventTrigger(const char* name) const; // 0x40af10
const AnimationFrame* GetLayerFrame(int layerId) const; // 0x40a220
const NullFrame* GetNullFrameByID(int nullId) const; // 0x40ac70
const NullFrame* GetNullFrame(const char* name) const; // 0x40ace0
const AnimationData* anim() const { return anim_; }
float frame() const { return frame_; }
bool playing() const { return playing_; }
void setPlaying(bool p) { playing_ = p; }
uint32_t eventsThisUpdate() const { return eventsThisUpdate_; }
uint32_t eventsSinceStart() const { return eventsSinceStart_; }
int layerFrameIndex(int layerAnimIdx) const { return layerFrameIdx_[layerAnimIdx]; }
private:
void FireTriggersAtCurrentFrame(); // 0x408c90
void AdvanceLayerPosition(int layerAnimIdx, float t); // 0x408b90
void AdvanceNullLayerPosition(int nullAnimIdx, float t);// 0x408c10
int FindEvent(const char* name) const;
Sprite* owner_; // +0x00
const AnimationData* anim_ = nullptr; // +0x04
std::vector<int> layerFrameIdx_; // +0x08
std::vector<int> nullFrameIdx_; // +0x0c
float frame_ = -1.0f; // +0x10
bool playing_ = false; // +0x14
uint32_t eventsThisUpdate_ = 0; // +0x18 IsEventTriggered
uint32_t eventsSinceStart_ = 0; // +0x1c WasEventTriggered
};
// ANM2 ("Sprite" in Lua), 0x114 bytes. Only the animation-relevant fields are reproduced.
class Sprite {
public:
Sprite() : main_(this), overlay_(this) {}
void Load(const AnmData* data); // ANM2::Load 0x40bd50 + AnmCache::Load 0x40db90 (data part)
void Reset(); // 0x407f10 (animation part)
void Update(); // 0x409100
void Play(const char* name, bool force = false); // 0x40a380
void PlayRandom(uint32_t seed); // 0x40a2b0
void PlayIndex(int index); // 0x40a400
bool SetAnimation(const char* name, bool reset = true); // 0x40a5d0
void SetFrame(const char* name, int frame); // 0x40a6e0
void SetFrame(float frame); // 0x40a740 (Lua SetFrame_1 converts int->float)
void SetLastFrame(); // 0x40a760
int GetFrame() const; // 0x40a780
void Stop(); // 0x40a910
bool IsPlaying(const char* name = "") const; // 0x40a4d0
bool IsFinished(const char* name = "") const; // 0x40a550
bool IsEventTriggered(const char* name) const; // 0x40b030
bool WasEventTriggered(const char* name) const; // 0x40b090
void SetLayerFrame(int layerId, int frame); // 0x40a7e0
void PlayOverlay(const char* name, bool force = false); // 0x40a940
bool SetOverlayAnimation(const char* name, bool reset = true);// 0x40aaf0
void SetOverlayFrame(const char* name, int frame); // 0x40abf0
void SetOverlayFrame(int frame); // 0x40ac30
int GetOverlayFrame() const; // 0x40ac50
void StopOverlay(); // 0x40a9c0
void RemoveOverlay(); // 0x40ac60
bool IsOverlayPlaying(const char* name = "") const; // 0x40a9f0
bool IsOverlayFinished(const char* name = "") const; // 0x40aa70
float playbackSpeed = 1.0f; // +0x104
bool overlayRenderFirst = false; // +0x70
AnimationState& main() { return main_; }
AnimationState& overlay() { return overlay_; }
const AnmData* data() const { return data_; }
private:
friend class AnimationState;
const AnimationData* FindAnimation(const char* name) const;
AnimationState main_, overlay_; // +0x30, +0x50
const AnmData* data_ = nullptr; // stands in for the borrowed +0x74..+0x90 pointers
bool loaded_ = false; // +0x109
};
} // namespace anm2
+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.
+129
View File
@@ -0,0 +1,129 @@
// Behaviour checks for the reimplementation. Build:
// g++ -std=c++17 -O2 -msse2 -mfpmath=sse -ffp-contract=off anm2.cpp test.cpp -o anm2_test
// Usage: ./anm2_test [file.anm2 animName eventName]
#include "anm2.hpp"
#include <cassert>
#include <cstdio>
using namespace anm2;
static const char* kSynthetic = R"(<AnimatedActor>
<Info CreatedBy="test" Version="1" Fps="30"/>
<Content>
<Spritesheets><Spritesheet Path="sheets\body.png" Id="0"/></Spritesheets>
<Layers><Layer Name="body" Id="0" SpritesheetId="0"/></Layers>
<Nulls><Null Name="Hand" Id="0"/></Nulls>
<Events><Event Name="Start" Id="0"/><Event Name="Shoot" Id="1"/><Event Name="End" Id="2"/></Events>
</Content>
<Animations DefaultAnimation="Attack">
<Animation Name="Attack" FrameNum="6" Loop="false">
<RootAnimation>
<Frame XPosition="10" YPosition="0" XScale="200" YScale="100" Delay="3" Visible="true" Rotation="0" Interpolated="false"/>
<Frame XPosition="0" YPosition="0" XScale="100" YScale="100" Delay="3" Visible="true" Rotation="0" Interpolated="false"/>
</RootAnimation>
<LayerAnimations>
<LayerAnimation LayerId="0" Visible="true">
<Frame XPosition="0" YPosition="0" XScale="100" YScale="100" Delay="4" Visible="true" Rotation="170" Interpolated="true"/>
<Frame XPosition="8" YPosition="0" XScale="100" YScale="100" Delay="2" Visible="true" Rotation="-170" Interpolated="false"/>
</LayerAnimation>
</LayerAnimations>
<NullAnimations>
<NullAnimation NullId="0" Visible="true">
<Frame XPosition="1" YPosition="2" XScale="100" YScale="100" Delay="6" Visible="true" Rotation="0" Interpolated="false"/>
</NullAnimation>
</NullAnimations>
<Triggers>
<Trigger EventId="0" AtFrame="0"/>
<Trigger EventId="1" AtFrame="3"/>
<Trigger EventId="2" AtFrame="5"/>
</Triggers>
</Animation>
<Animation Name="Idle" FrameNum="4" Loop="true">
<RootAnimation><Frame XPosition="0" YPosition="0" XScale="100" YScale="100" Delay="4" Visible="true" Rotation="0" Interpolated="false"/></RootAnimation>
<LayerAnimations/><NullAnimations/>
<Triggers><Trigger EventId="1" AtFrame="2"/></Triggers>
</Animation>
</Animations>
</AnimatedActor>)";
static int failures = 0;
#define CHECK(c) do { if (!(c)) { std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); ++failures; } } while (0)
int main(int argc, char** argv) {
AnmData d;
CHECK(ParseAnm2("gfx/test/actor.anm2", kSynthetic, d));
CHECK(d.layers.size() == 1 && d.layers[0].spritesheetPath == "gfx/test/sheets/body.png");
CHECK(d.eventNames.size() == 3 && d.defaultAnimation == "Attack");
const AnimationData& atk = d.animations[0];
// Layer: interpolated 4-frame key expanded to 4 one-tick frames, then cut at the root boundary (tick 3).
const auto& lf = atk.layerAnims[0].frames;
std::printf("Attack/body baked frames:\n");
for (auto& f : lf) std::printf(" [%d,%d) x=%g sx=%g rot=%g delay=%d\n", f.start, f.end, f.x, f.xScale, f.rotation, f.delay);
CHECK(lf.size() == 5);
CHECK(lf[0].x == 10.0f && lf[0].xScale == 2.0f); // root pos 10, root scale 2
CHECK(lf[1].x == 2.0f * 2.0f + 10.0f); // lerp 0->8 at t=.25 = 2
CHECK(lf[3].x == 6.0f && lf[3].xScale == 1.0f); // second root frame (identity)
CHECK(lf[1].rotation == 175.0f && lf[2].rotation == 180.0f && lf[3].rotation == -175.0f); // shortest-path angle lerp
CHECK(lf[4].start == 4 && lf[4].end == 6 && lf[4].delay == 2);
// Null: one 6-tick frame split by the root boundary into [0,3) and [3,6).
CHECK(atk.nullAnims[0].frames.size() == 2 && atk.nullAnims[0].frames[0].x == 1.0f * 2.0f + 10.0f);
Sprite s;
s.Load(&d);
s.Play("Attack");
CHECK(s.IsEventTriggered("Start")); // frame-0 triggers fire inside Play (Rewind)
std::printf("\nAttack playback:\n");
for (int u = 0; u < 8; ++u) {
s.Update();
std::printf(" update %d: frame=%d playing=%d Shoot=%d End=%d wasStart=%d\n", u, s.GetFrame(),
s.main().playing(), s.IsEventTriggered("Shoot"), s.IsEventTriggered("End"), s.WasEventTriggered("Start"));
}
CHECK(s.IsFinished("Attack") && s.GetFrame() == 5);
CHECK(!s.IsEventTriggered("End")); // the finishing Update re-runs AdvancePosition(5), clearing the mask
// ...but if the finishing Update itself crosses the event frame, the mask survives while stopped.
s.Play("Attack", true);
s.playbackSpeed = 2.0f;
s.Update(); s.Update(); // frames 2, 4
s.Update(); // 6 >= FrameNum: AdvancePosition(5) fires End, stops
CHECK(!s.IsPlaying() && s.IsEventTriggered("End"));
s.Update(); s.Update(); // no-ops while stopped
CHECK(s.IsEventTriggered("End"));
s.playbackSpeed = 1.0f;
s.Play("Attack"); // non-looping, same name, not forced: no-op
CHECK(!s.IsPlaying());
s.Play("Attack", true);
CHECK(s.IsPlaying() && s.GetFrame() == 0);
// Speed 2 on a loop: the loop wraps via Rewind, skipping frames >= old+1 that were never stepped.
s.Play("Idle");
s.playbackSpeed = 2.0f;
s.Update(); CHECK(s.GetFrame() == 2 && s.IsEventTriggered("Shoot"));
s.Update(); CHECK(s.GetFrame() == 0 && !s.IsEventTriggered("Shoot"));
s.playbackSpeed = 1.0f;
// SetFrame clamps to nextafter(FrameNum, 0) and fires only on exact equality.
s.SetFrame("Attack", 3);
CHECK(s.IsEventTriggered("Shoot") && !s.IsPlaying());
s.SetFrame(100.0f);
CHECK(s.main().frame() < 6.0f && s.GetFrame() == 5 && !s.IsEventTriggered("End"));
CHECK(s.main().NextEventTrigger("Shoot") == -1);
s.SetFrame(1.0f);
CHECK(s.main().NextEventTrigger("Shoot") == 3);
if (argc >= 4) {
AnmData real;
if (!LoadAnm2File(argv[1], real)) return 1;
Sprite r; r.Load(&real); r.Play(argv[2]);
std::printf("\n%s / %s (FrameNum=%d): '%s' fires at:", argv[1], argv[2],
r.main().anim() ? r.main().anim()->frameNum : -1, argv[3]);
if (r.IsEventTriggered(argv[3])) std::printf(" 0");
for (int u = 0; u < 1000 && r.IsPlaying(); ++u) { r.Update(); if (r.IsEventTriggered(argv[3])) std::printf(" %d", r.GetFrame()); }
std::printf("\n");
}
std::printf("\n%s (%d failures)\n", failures ? "FAILED" : "all checks passed", failures);
return failures != 0;
}