Files
2026-10-21 17:34:54 -05:00

363 lines
16 KiB
C++

// Runs the game's scene code in tbg_screens and compares rendered frames with a Mesen capture's screenshots
// (C++ counterpart of re/tools/scr_compare.py; capture from re/lua/scr_trace.lua, e.g. re/runs/scr/main).
//
// usage: scr_validate ROM CAPDIR --frames 200,400,1000 [--plan "300:start,2000:a/4,..."] [--out DIR]
// Our frames run ahead of Mesen's (the stubbed sound driver answers instantly), so frames are aligned as
// scr_run.py does: our DECOMP / VRAM-DMA events are matched in order with the capture's and
// offset = mesen_frame - our_frame of the last match. Plan presses are in Mesen frames. A pixel differs if any
// channel is off by more than 8; the best of our frames within +-1 of the aligned one is reported.
//
// With CAPDIR "-" it drives the scene flow instead (SceneRunner, no capture; frames and plan in our frame
// numbers): battles end at once with the result of --result P1:P2 (default 2:0), options return at once, and
// --frames are written to DIR as fNNNNN.png.
#include <zlib.h>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iterator>
#include <map>
#include <memory>
#include <optional>
#include <regex>
#include <sstream>
#include <string>
#include <vector>
#include "screens/flow.hpp"
#include "screens/ppu.hpp"
#include "screens/snes.hpp"
using namespace tbg::screens;
namespace {
std::vector<std::uint8_t> read_file(const std::string& p) {
std::ifstream f(p, std::ios::binary);
return {std::istreambuf_iterator<char>(f), {}};
}
std::uint32_t be32(const std::uint8_t* p) {
return static_cast<std::uint32_t>(p[0]) << 24 | static_cast<std::uint32_t>(p[1]) << 16 |
static_cast<std::uint32_t>(p[2]) << 8 | p[3];
}
// Minimal PNG reader: 8-bit RGB/RGBA, non-interlaced. Returns RGB bytes (w*h*3) or nothing.
std::optional<std::vector<std::uint8_t>> read_png_rgb(const std::string& path, std::uint32_t& w, std::uint32_t& h) {
const auto d = read_file(path);
if (d.size() < 33) return std::nullopt;
std::vector<std::uint8_t> idat;
int ctype = 0;
for (std::size_t p = 8; p + 8 <= d.size();) {
const std::uint32_t len = be32(&d[p]);
const std::string type(reinterpret_cast<const char*>(&d[p + 4]), 4);
const std::uint8_t* body = &d[p + 8];
if (type == "IHDR") {
w = be32(body), h = be32(body + 4);
if (body[8] != 8 || body[12] != 0) return std::nullopt;
ctype = body[9];
} else if (type == "IDAT") {
idat.insert(idat.end(), body, body + len);
}
p += 12 + len;
}
const std::size_t bpp = ctype == 6 ? 4 : ctype == 2 ? 3 : 0;
if (!bpp) return std::nullopt;
const std::size_t stride = w * bpp;
std::vector<std::uint8_t> raw((stride + 1) * h);
uLongf n = static_cast<uLongf>(raw.size());
if (uncompress(raw.data(), &n, idat.data(), static_cast<uLong>(idat.size())) != Z_OK) return std::nullopt;
std::vector<std::uint8_t> img(stride * h), out(static_cast<std::size_t>(w) * h * 3);
for (std::size_t y = 0; y < h; ++y) {
const std::uint8_t f = raw[y * (stride + 1)];
const std::uint8_t* src = &raw[y * (stride + 1) + 1];
std::uint8_t* row = &img[y * stride];
const std::uint8_t* up = y ? &img[(y - 1) * stride] : nullptr;
for (std::size_t i = 0; i < stride; ++i) {
const int a = i >= bpp ? row[i - bpp] : 0, b = up ? up[i] : 0, c = (up && i >= bpp) ? up[i - bpp] : 0;
int pr = 0;
switch (f) {
case 1: pr = a; break;
case 2: pr = b; break;
case 3: pr = (a + b) / 2; break;
case 4: {
const int pp = a + b - c, pa = std::abs(pp - a), pb = std::abs(pp - b), pc = std::abs(pp - c);
pr = (pa <= pb && pa <= pc) ? a : (pb <= pc ? b : c);
break;
}
default: break;
}
row[i] = static_cast<std::uint8_t>(src[i] + pr);
}
for (std::size_t x = 0; x < w; ++x)
for (std::size_t k = 0; k < 3; ++k) out[(y * w + x) * 3 + k] = row[x * bpp + k];
}
return out;
}
void write_png(const std::string& path, const std::vector<std::uint32_t>& px, std::uint32_t w, std::uint32_t h) {
std::vector<std::uint8_t> raw;
for (std::uint32_t y = 0; y < h; ++y) {
raw.push_back(0);
for (std::uint32_t x = 0; x < w; ++x) {
const std::uint32_t c = px[y * w + x];
raw.push_back(static_cast<std::uint8_t>(c >> 16)), raw.push_back(static_cast<std::uint8_t>(c >> 8));
raw.push_back(static_cast<std::uint8_t>(c));
}
}
uLongf n = compressBound(static_cast<uLong>(raw.size()));
std::vector<std::uint8_t> z(n);
compress2(z.data(), &n, raw.data(), static_cast<uLong>(raw.size()), 6);
z.resize(n);
std::ofstream f(path, std::ios::binary);
auto chunk = [&f](const char* t, const std::vector<std::uint8_t>& body) {
std::vector<std::uint8_t> buf(t, t + 4);
buf.insert(buf.end(), body.begin(), body.end());
const auto len = static_cast<std::uint32_t>(body.size());
const auto crc = static_cast<std::uint32_t>(crc32(0, buf.data(), static_cast<uInt>(buf.size())));
const std::uint8_t l[4] = {static_cast<std::uint8_t>(len >> 24), static_cast<std::uint8_t>(len >> 16),
static_cast<std::uint8_t>(len >> 8), static_cast<std::uint8_t>(len)};
const std::uint8_t c[4] = {static_cast<std::uint8_t>(crc >> 24), static_cast<std::uint8_t>(crc >> 16),
static_cast<std::uint8_t>(crc >> 8), static_cast<std::uint8_t>(crc)};
f.write(reinterpret_cast<const char*>(l), 4);
f.write(reinterpret_cast<const char*>(buf.data()), static_cast<std::streamsize>(buf.size()));
f.write(reinterpret_cast<const char*>(c), 4);
};
f.write("\x89PNG\r\n\x1a\n", 8);
std::vector<std::uint8_t> ihdr = {static_cast<std::uint8_t>(w >> 24), static_cast<std::uint8_t>(w >> 16),
static_cast<std::uint8_t>(w >> 8), static_cast<std::uint8_t>(w),
static_cast<std::uint8_t>(h >> 24), static_cast<std::uint8_t>(h >> 16),
static_cast<std::uint8_t>(h >> 8), static_cast<std::uint8_t>(h), 8, 2, 0, 0, 0};
chunk("IHDR", ihdr);
chunk("IDAT", z);
chunk("IEND", {});
}
struct Event {
int frame;
char kind; // 'D' decompress, 'V' VRAM DMA
std::string a, b;
};
std::string hex6(std::uint32_t v) {
char b[16];
std::snprintf(b, sizeof b, "%06X", v);
return b;
}
std::uint16_t pad_word(const std::string& buttons) {
static const std::map<std::string, std::uint16_t> bits = {
{"b", kPadB}, {"y", kPadY}, {"select", kPadSelect}, {"start", kPadStart}, {"up", kPadUp}, {"down", kPadDown},
{"left", kPadLeft}, {"right", kPadRight}, {"a", kPadA}, {"x", kPadX}, {"l", kPadL}, {"r", kPadR}};
std::uint16_t w = 0;
std::stringstream ss(buttons);
for (std::string b; std::getline(ss, b, '+');)
if (auto it = bits.find(b); it != bits.end()) w = static_cast<std::uint16_t>(w | it->second);
return w;
}
struct Press {
int f, hold;
std::uint16_t w;
};
int run_flow(const std::vector<std::uint8_t>& rom, const std::vector<int>& want, const std::vector<Press>& plan,
const std::string& out_dir, int p1_rounds, int p2_rounds) {
SceneRunner run(rom);
run.on_sound = [&run](int cmd, int y) {
if (cmd == 0x13 || cmd == 0x14 || cmd == 0x15) std::printf("f%d sound cmd %02X y %02X\n", run.snes().frame, cmd, y);
};
const int last = want.empty() ? 0 : *std::max_element(want.begin(), want.end());
auto frame_buf = std::make_unique<Frame>();
std::vector<std::uint32_t> px(frame_buf->size());
for (int f = 1; f <= last; ++f) {
std::uint16_t pad = 0;
for (const auto& p : plan)
if (p.f <= f && f < p.f + p.hold) pad = static_cast<std::uint16_t>(pad | p.w);
const auto stop = run.step(pad, 0);
if (stop == SceneRunner::Stop::Halted) {
std::printf("f%d halted: %s\n", f, run.error().c_str());
return 1;
}
if (stop == SceneRunner::Stop::Battle) {
std::printf("f%d battle: mode %d, P1 %d vs %d, difficulty %d, beaten %02X -> result %d:%d\n", f, run.mode(),
run.player_character(), run.opponent(), run.difficulty(), run.wram(0xE2), p1_rounds, p2_rounds);
run.finish_battle(p1_rounds, p2_rounds);
}
if (stop == SceneRunner::Stop::Options) {
std::printf("f%d options\n", f);
run.finish_options();
}
if (std::find(want.begin(), want.end(), f) != want.end() && !out_dir.empty()) {
run.render(*frame_buf);
std::copy(frame_buf->begin(), frame_buf->end(), px.begin());
char name[32];
std::snprintf(name, sizeof name, "/f%05d.png", f);
write_png(out_dir + name, px, 256, 224);
}
}
std::printf("ran %d frames; pc %02X:%04X\n", last, run.snes().cpu.pbr, run.snes().cpu.pc);
return 0;
}
} // namespace
int main(int argc, char** argv) {
if (argc < 3) {
std::fprintf(stderr, "usage: %s ROM CAPDIR --frames N,... [--plan SPEC] [--out DIR]\n", argv[0]);
return 2;
}
const std::string capdir = argv[2];
std::string frames_s, plan_s, out_dir, result_s = "2:0";
for (int i = 3; i + 1 < argc; i += 2) {
const std::string k = argv[i];
if (k == "--frames") frames_s = argv[i + 1];
if (k == "--plan") plan_s = argv[i + 1];
if (k == "--out") out_dir = argv[i + 1];
if (k == "--result") result_s = argv[i + 1];
}
const auto rom = read_file(argv[1]);
std::vector<int> want;
{
std::stringstream ss(frames_s);
for (std::string t; std::getline(ss, t, ',');) want.push_back(std::stoi(t));
}
std::vector<Press> plan;
{
const std::regex re(R"((\d+):([\w+]+)(?:/(\d+))?)");
std::stringstream ss(plan_s);
for (std::string t; std::getline(ss, t, ',');) {
std::smatch m;
if (std::regex_match(t, m, re))
plan.push_back({std::stoi(m[1]), m[3].matched ? std::stoi(m[3]) : 4, pad_word(m[2])});
}
}
if (capdir == "-") {
int r1 = 2, r2 = 0;
std::sscanf(result_s.c_str(), "%d:%d", &r1, &r2);
return run_flow(rom, want, plan, out_dir, r1, r2);
}
std::vector<Event> cap;
{
std::ifstream f(capdir + "/events.txt");
const std::regex dre(R"(f(\d+) DECOMP caller=\w+ src=(\w+) dst=(\w+).*)");
const std::regex vre(R"(f(\d+) DMA .*bb=21(18|19) src=(\w+) n=(\w+) vaddr=(\w+).*)");
for (std::string line; std::getline(f, line);) {
std::smatch m;
if (std::regex_match(line, m, dre))
cap.push_back({std::stoi(m[1]), 'D', m[2], m[3]});
else if (std::regex_match(line, m, vre))
cap.push_back({std::stoi(m[1]), 'V', m[3], m[5]});
}
}
std::map<int, std::vector<std::uint8_t>> refs;
for (int f : want) {
char name[32];
std::snprintf(name, sizeof name, "/f%05d.png", f);
std::uint32_t w = 0, h = 0;
if (auto img = read_png_rgb(capdir + name, w, h); img && w == 256 && h == 224) refs[f] = std::move(*img);
}
auto snes = std::make_unique<Snes>(rom);
std::size_t ci = 0;
int offset = 0, unmatched = 0;
auto event = [&](char kind, const std::string& a, const std::string& b) {
const int f = snes->frame + 1;
for (std::size_t j = ci; j < std::min(ci + 40, cap.size()); ++j) {
if (cap[j].kind == kind && cap[j].a == a && (cap[j].b == b || kind == 'V')) {
offset = cap[j].frame - f;
ci = j + 1;
return;
}
}
++unmatched;
};
snes->on_dma = [&](std::uint32_t mask) {
for (int ch = 0; ch < 8; ++ch) {
if (!((mask >> ch) & 1)) continue;
const int b = ch * 16;
if ((snes->dma_reg(b + 1) == 0x18 || snes->dma_reg(b + 1) == 0x19) && !(snes->dma_reg(b) & 0x80))
event('V', hex6(snes->dma_reg(b + 4) << 16 | snes->dma_reg(b + 3) << 8 | snes->dma_reg(b + 2)),
hex6(snes->ppu.vaddr).substr(2));
}
};
std::vector<std::pair<std::string, std::string>> pending; // the capture logs the decompressor at its exit
snes->cpu.hooks[0x80B7DA] = [&](tbg::audio::Cpu65816& c) { // A = src bank, B = dst bank, X = src, Y = dst
pending.emplace_back(hex6((c.a & 0xFF) << 16 | c.x), hex6(((c.a >> 8) & 0xFF) << 16 | c.y));
c.exec();
};
snes->cpu.hooks[0x80B868] = [&](tbg::audio::Cpu65816& c) {
if (!pending.empty()) {
event('D', pending.back().first, pending.back().second);
pending.pop_back();
}
c.exec();
};
struct Best {
double d;
int mf;
Frame img;
};
std::map<int, std::unique_ptr<Best>> best;
const int last = want.empty() ? 0 : *std::max_element(want.begin(), want.end());
auto frame_buf = std::make_unique<Frame>();
try {
while (snes->frame + 1 + offset <= last + 2) {
const int mf0 = snes->frame + 1 + offset;
std::uint16_t pad = 0;
for (const auto& p : plan)
if (p.f <= mf0 && mf0 < p.f + p.hold) pad = static_cast<std::uint16_t>(pad | p.w);
snes->pad = {pad, 0};
snes->frame_step();
const int mf = snes->frame + offset;
for (int f : want) {
if (!refs.count(f) || std::abs(mf - f) > 1) continue;
render_frame(*snes, *frame_buf);
const auto& ref = refs[f];
int bad = 0;
for (std::size_t i = 0; i < frame_buf->size(); ++i) {
const std::uint32_t c = (*frame_buf)[i];
const int r = static_cast<int>((c >> 16) & 255), g = static_cast<int>((c >> 8) & 255),
b = static_cast<int>(c & 255);
if (std::max({std::abs(r - ref[i * 3]), std::abs(g - ref[i * 3 + 1]), std::abs(b - ref[i * 3 + 2])}) > 8)
++bad;
}
const double d = bad / double(kScreenW * kScreenH);
if (!best[f] || d < best[f]->d) best[f] = std::make_unique<Best>(Best{d, mf, *frame_buf});
}
}
} catch (const Halt& h) {
std::printf("halted at frame %d: %s\n", snes->frame, h.what());
}
std::printf("ran %d frames; matched %zu/%zu capture events, unmatched own %d; offset %d\n", snes->frame, ci,
cap.size(), unmatched, offset);
int failures = 0;
for (int f : want) {
if (!best[f]) {
std::printf("f%d: not reached or no screenshot\n", f);
++failures;
continue;
}
std::printf("f%d: %.2f%% pixels differ (our frame aligned to mesen f%d)\n", f, 100 * best[f]->d, best[f]->mf);
if (!out_dir.empty()) {
std::vector<std::uint32_t> side(static_cast<std::size_t>(516) * 224);
const auto& ref = refs[f];
for (std::size_t y = 0; y < 224; ++y)
for (std::size_t x = 0; x < 516; ++x) {
std::uint32_t c = 0xFF00FF;
if (x < 256)
c = static_cast<std::uint32_t>(ref[(y * 256 + x) * 3]) << 16 |
static_cast<std::uint32_t>(ref[(y * 256 + x) * 3 + 1]) << 8 | ref[(y * 256 + x) * 3 + 2];
else if (x >= 260)
c = best[f]->img[y * 256 + x - 260];
side[y * 516 + x] = c;
}
char name[32];
std::snprintf(name, sizeof name, "/cmp_f%05d.png", f);
write_png(out_dir + name, side, 516, 224);
}
}
return failures;
}