Initial public OpenBMH 0.1 source (by Codex)

This commit is contained in:
Codex committed 2026-10-16 19:36:32 +02:00
commit 558fbf166b
613 files changed
+168029

No files matched your search

+301
View File
@@ -0,0 +1,301 @@
#include "runtime_fixture_tables.hpp"
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "test_inputs.hpp"
#include <sstream>
// Tests of the file formats and game rules against an original BMH installation.
//
// Usage: format_tests [<BMH data directory> [<reference savegame directory>]]
//
// The data directory is an original installation (supported game edition 2026/27 in development).
// The optional reference directory holds savegames recorded in the running original
// (see docs/REFERENCE.md): SP1VOR.FBM right before and SP2VOR.FBM right after
// matchday 1. Expected values in these tests were read off the original's screens.
#include <cstdio>
#include <filesystem>
#include <string>
#include "formats/fbm.hpp"
#include "formats/font.hpp"
#include "formats/le.hpp"
#include "formats/m3d.hpp"
#include "formats/palette.hpp"
#include "formats/savestate.hpp"
#include "formats/textd.hpp"
#include "formats/vga.hpp"
#include "game/random.hpp"
#include "game/schedule.hpp"
#include "game/state.hpp"
namespace fs = std::filesystem;
using namespace bmh;
static int failures = 0;
#define CHECK(cond) \
do { \
if (!(cond)) { \
std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
failures++; \
} \
} while (0)
static void test_random() {
// reference values computed by hand from the formulas verified in the machine code
GameRandom g(0);
CHECK(g.range(0, 99) == 0); // seed 167 -> 167*100/4e6 = 0
CHECK(g.seed() == 167);
// seed 2839, 2839 * 4000000 overflows int32 to -1528901888 -> /4e6 = -382 (like imul/idiv)
CHECK(g.range(0, 3999999) == -382);
GameRandom neg(-1000); // negative seeds stay negative
int32_t v = neg.range(0, 10);
CHECK(neg.seed() == (-16000 + 167) % 4000000);
CHECK(v == 0); // -15833*11/4e6 truncates to 0
WatcomRandom w(1);
CHECK(w.rand() == 16838); // Watcom/MSVC-compatible LCG, first value for seed 1
CHECK(w.range(5, 5) == 5);
}
// Every byte in these fixtures is generated by this test, not extracted from a game.
static void test_generated_formats() {
const auto directory = fs::temp_directory_path() / "openbmh-generated-formats";
fs::create_directories(directory);
const auto write_file = [](const fs::path& path, const Bytes& bytes) {
std::ofstream out(path, std::ios::binary);
out.write(reinterpret_cast<const char*>(bytes.data()), std::streamsize(bytes.size()));
if (!out) throw std::runtime_error("Cannot write generated format fixture");
};
Bytes palette(768);
for (size_t i = 0; i < palette.size(); ++i) palette[i] = uint8_t((i * 11 + 7) % 64);
write_file(directory / "generated.col", palette);
const auto loaded = load_palette(directory / "generated.col");
for (size_t i = 0; i < 256; ++i) {
const auto expand = [](uint8_t value) { return (unsigned(value) * 255 + 31) / 63; };
CHECK(loaded.argb[i] == (0xff000000u | expand(palette[i * 3]) << 16 |
expand(palette[i * 3 + 1]) << 8 | expand(palette[i * 3 + 2])));
}
Bytes text(7, 0);
for (int i = 0; i < TEXT_COUNT; ++i) {
const std::string value = "Synthetic entry " + std::to_string(i);
text.insert(text.end(), value.begin(), value.end()); text.push_back(0);
}
write_file(directory / "generated.blk", text);
const auto db = load_textd(directory / "generated.blk");
CHECK(db[0] == "Synthetic entry 0" && db[TEXT_COUNT - 1] == "Synthetic entry " + std::to_string(TEXT_COUNT - 1));
CHECK(iso646de_to_utf8("[\\]{|}~") == "ÄÖÜäöüß");
Bytes font(28 + 2 + 8, 0);
font[0] = 2; font[3] = 2; font[4] = 2; font[6] = 1;
font[8] = 'A'; font[9] = 'A'; font[16] = 1;
font[28] = 0x80; font[29] = 0x40;
font[32] = 2; font[36] = 2;
write_file(directory / "generated.fnt", font);
const auto glyphs = load_font(directory / "generated.fnt");
Image canvas(5, 3, 0);
CHECK(glyphs.text_width("AA") == 4 && glyphs.draw(canvas, 0, 0, "A", 9) == 2);
CHECK(canvas.at(0, 0) == 9 && canvas.at(1, 1) == 9 && canvas.at(1, 0) == 0);
CHECK(glyphs.glyph('Z').advance == 2);
fs::remove_all(directory);
}
static void test_images(const fs::path& data) {
Palette pal = load_palette(data / "M3PC.COL");
CHECK((pal.argb[0] >> 24) == 0xFF);
CHECK(vga_dac_rgb8(11) == 45 && vga_dac_rgb8(32) == 130);
CHECK(vga_dac_rgb8(0x8b) == 45); // preserve the format's low-six-bit mask
CHECK(vga_dac_rgb8(0) == 0 && vga_dac_rgb8(63) == 255);
int count = 0;
for (const char* dir : {"KB", "W"}) {
for (const auto& e : fs::directory_iterator(data / dir)) {
std::string ext = e.path().extension().string();
for (auto& ch : ext) ch = char(toupper(ch));
std::string stem = e.path().stem().string();
if (ext != ".VGA" || stem.find_first_not_of("0123456789") != std::string::npos) continue;
try {
Image img = load_vga(e.path());
CHECK(img.width > 0 && img.height > 0 && img.width <= 320 && img.height <= 250);
count++;
} catch (const FormatError& ex) {
std::printf("FAIL %s: %s\n", e.path().string().c_str(), ex.what());
failures++;
}
}
}
std::printf(" decoded %d VGA images\n", count);
CHECK(count == 107);
}
static void test_fonts_and_text(const fs::path& data) {
Font f2 = load_font(data / "F" / "BMH2.FNT");
Font f3 = load_font(data / "F" / "BMH3.FNT");
CHECK(f2.height == 8 && f3.height == 6);
CHECK(f2.text_width("A") > 0);
TextDb t = load_textd(data / "TEXTD.BLK");
CHECK(t[0] == bmh::test::expected_text("format.text.0"));
CHECK(iso646de_to_utf8(t[1].c_str()) == bmh::test::expected_text("format.text.1"));
}
static void test_executable(const fs::path& data) {
LeImage exe = bmh::test::load_executable(data / "BMH.exe");
CHECK(exe.base() == 0x10000);
CHECK(exe.u32(::bmh::layout::MatchdaySetup_Attendance_ExecutableField) == 35000); // first entry of the stadium capacity table
CHECK(exe.cstring(::bmh::layout::FixtureTextDatabaseFilename) == "textd.blk"); // file name used by legacy routine
}
static void test_database(const fs::path& data) {
Database db = load_database(data / "M3D.MAN");
CHECK(db.club_names.size() == 419);
CHECK(iso646de_to_utf8(db.club_names[0].c_str()) == bmh::test::expected_text("format.text.2"));
CHECK(db.players.size() == 2574);
CHECK(db.players[0].position() == 0);
CHECK(db.referees.at(0) == bmh::test::expected_text("format.text.3"));
CHECK(db.stadiums.at(0) == bmh::test::expected_text("format.text.4"));
std::printf(" %zu clubs, %zu players, %zu referees, %zu stadiums\n", db.club_names.size(), db.players.size(),
db.referees.size(), db.stadiums.size());
}
static void test_savegame(const fs::path& data) {
Savegame s = load_savegame(bmh::test::external_input("format-start.fbm"));
CHECK(s.version == "V2.24");
CHECK(s.checksum_ok);
CHECK(s.stream.size() == 165311);
// The block table must reproduce the stream length exactly (125 state blocks + 4 pools).
SaveState st(s.stream);
CHECK(st.blocks().size() == 125);
// Compare decoded records with an explicitly supplied external expectation table.
std::ifstream player_input(bmh::test::external_input("format-players.tsv"));
CHECK(bool(player_input));
size_t id; int condition, technique, form, age, position, strength;
size_t checked = 0;
while (player_input >> id >> condition >> technique >> form >> age >> position >> strength) {
const Player p{"", le32(s.stream, st.block(::bmh::layout::PlayerConditionTechniqueForm).offset + id * 4),
le32(s.stream, st.block(::bmh::layout::PlayerSkillWords).offset + id * 4),
le32(s.stream, st.block(::bmh::layout::PlayerIdentityWords).offset + id * 4)};
CHECK(p.condition() == condition && p.technique() == technique && p.form() == form &&
p.age() == age && p.position() == position && p.strength() == strength);
++checked;
}
CHECK(player_input.eof() && checked > 0);
// encrypt/decrypt roundtrip
Bytes copy = s.stream;
fbm_encrypt(copy.data(), copy.size(), s.key);
fbm_decrypt(copy.data(), copy.size(), s.key);
CHECK(copy == s.stream);
}
// Club name of a team id in a running game: offset table *ClubIdentities into the club name pool.
static std::string team_name(const SaveState& st, int team) {
const Bytes& pool = st.pool(0);
size_t ofs = le16(Bytes(st.data(::bmh::layout::ClubIdentities) + team * 2, st.data(::bmh::layout::ClubIdentities) + team * 2 + 2), 0);
return iso646de_to_utf8(reinterpret_cast<const char*>(pool.data() + ofs));
}
static void test_schedule(const fs::path& data) {
// Round strings: every round is a perfect matching of the league's teams.
for (int teams : {18, 20, 16, 12, 6, 4}) {
for (int md = 1; md <= 2 * (teams - 1); md++) {
std::vector<int> seen(teams, 0);
for (const Fixture& f : generate_fixtures(teams, md, teams - 1, 0)) {
seen.at(f.home)++;
seen.at(f.away)++;
}
for (int n : seen) CHECK(n == 1);
}
}
// Second half repeats the first with home and away swapped.
auto first = league_fixtures(0, 1), second = league_fixtures(0, 18);
CHECK(first[0].home == second[0].away && first[0].away == second[0].home);
// Team order of the recorded career (clubs are shuffled when a new game starts).
Savegame s = load_savegame(bmh::test::external_input("format-start.fbm"));
SaveState st(s.stream);
CHECK(team_name(st, 0) == bmh::test::expected_text("format.text.5"));
CHECK(team_name(st, 14) == bmh::test::expected_text("format.text.2"));
CHECK(team_league(14) == 0 && team_league(90) == 5 && team_league(138) == kLeagueCount);
// Before the season every result is "not played".
const uint8_t* results = st.data(::bmh::layout::LeagueResults);
for (size_t i = 0; i < kResultsSize; i++) CHECK(!decode_result(results[i]).played);
}
// Matchday 1 of the Bundesliga as shown by the original (docs/REFERENCE.md).
static void test_matchday1(const fs::path& refs) {
Savegame s = load_savegame(refs / "SP2VOR.FBM");
CHECK(s.checksum_ok);
SaveState st(s.stream);
struct Expected { std::string home, away; int hg, ag; };
std::ifstream expected_input(bmh::test::external_input("format-matches.tsv"));
std::vector<Expected> expected;
for (std::string line; std::getline(expected_input, line);) {
std::istringstream row(line); Expected value;
std::getline(row, value.home, '\t'); std::getline(row, value.away, '\t');
if (!(row >> value.hg >> value.ag)) throw std::runtime_error("Invalid match expectation");
expected.push_back(std::move(value));
}
CHECK(expected.size() == 9);
auto fixtures = league_fixtures(0, 1);
CHECK(fixtures.size() == 9);
for (size_t m = 0; m < fixtures.size() && m < 9; m++) {
Result r = decode_result(st.data(::bmh::layout::LeagueResults)[result_index(0, 1, m)]);
bool ok = team_name(st, fixtures[m].home) == expected[m].home && team_name(st, fixtures[m].away) == expected[m].away &&
r.played && r.home_goals == expected[m].hg && r.away_goals == expected[m].ag;
if (!ok) std::printf(" match %zu: %s - %s %d:%d\n", m, team_name(st, fixtures[m].home).c_str(),
team_name(st, fixtures[m].away).c_str(), r.home_goals, r.away_goals);
CHECK(ok);
}
// Matchday 2 has not been played yet.
CHECK(!decode_result(st.data(::bmh::layout::LeagueResults)[result_index(0, 2, 0)]).played);
}
// Team values K/T/F/M/Ø right before matchday 1. The original showed them on the results
// screen at 90'; for these nine teams nothing changed during their match, so the values
// equal the pre-match ones. Ø is also the "Stärke" shown on the desktop (Bayern 84,
// Frankfurt 91 before the match).
static void test_team_values(const fs::path& refs) {
Savegame s = load_savegame(refs / "SP1VOR.FBM");
SaveState st(s.stream);
GameState g = GameState::from_save(st);
using namespace avg;
const uint16_t lineup = LINEUP_ONLY | ALL_POSITIONS;
struct Expected { int team, k, t, f, m, strength; };
std::ifstream expected_input(bmh::test::external_input("format-team-values.tsv"));
std::vector<Expected> expected;
for (Expected value; expected_input >> value.team >> value.k >> value.t >> value.f >> value.m >> value.strength;)
expected.push_back(value);
CHECK(expected_input.eof() && !expected.empty());
for (const Expected& e : expected) {
CHECK(team_average(g, e.team, lineup | CONDITION).value == e.k);
CHECK(team_average(g, e.team, lineup | TECHNIQUE).value == e.t);
CHECK(team_average(g, e.team, lineup | FORM).value == e.f);
CHECK(team_average(g, e.team, lineup | MORALE).value == e.m);
CHECK(team_average(g, e.team, lineup | CONDITION | TECHNIQUE | FORM | MORALE).value == e.strength);
}
}
int main(int argc, char** argv) {
test_random();
test_generated_formats();
if (argc < 2) {
std::printf("no data directory given, skipping data tests\n");
} else {
fs::path data = argv[1];
try {
test_images(data);
test_fonts_and_text(data);
test_database(data);
test_executable(data);
test_savegame(data);
test_schedule(data);
if (argc >= 3 && *argv[2]) test_matchday1(argv[2]), test_team_values(argv[2]);
else std::printf("no reference directory given, skipping matchday tests\n");
} catch (const std::exception& ex) {
std::printf("FAIL exception: %s\n", ex.what());
failures++;
}
}
std::printf(failures ? "%d FAILURE(S)\n" : "all tests passed\n", failures);
return failures ? 1 : 0;
}