Complete Classic BMH and FLTD installation imports (by Codex)

This commit is contained in:
Codex committed 2026-10-18 10:07:38 +02:00
1 parent 65b087c1d0
commit 3a021fc160
32 files changed
+2297 -203

No files matched your search

+10 -3
View File
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: GPL-3.0-only
add_library(bmh_obw STATIC obw.cpp ../cli/json.cpp)
add_library(bmh_obw STATIC obw.cpp classic.cpp assets.cpp ../cli/json.cpp ../audio/container.cpp)
target_include_directories(bmh_obw PUBLIC ..)
target_link_libraries(bmh_obw PUBLIC bmhlaunch PRIVATE bmh_miniz)
add_executable(openbmh_import main.cpp)
@@ -11,7 +11,14 @@ if(MSVC)
target_compile_options(bmh_obw PRIVATE /W4 /utf-8)
target_compile_options(openbmh_import PRIVATE /W4 /utf-8)
target_compile_options(obw_import_tests PRIVATE /W4 /utf-8)
else()
target_compile_options(bmh_obw PRIVATE -Wall -Wextra)
endif()
add_test(NAME obw_import_tests COMMAND obw_import_tests)
# A separate component: existing 0.1 runtime packages retain their two products.
install(TARGETS openbmh_import RUNTIME DESTINATION . COMPONENT ImportTools)
add_executable(obw_classic_installation_tests ../../tests/obw_classic_installation_tests.cpp)
target_link_libraries(obw_classic_installation_tests PRIVATE bmh_obw)
if(MSVC)
target_compile_options(obw_classic_installation_tests PRIVATE /W4 /utf-8)
endif()
bmh_add_data_test(NAME obw_classic_installation_tests COMMAND obw_classic_installation_tests "${BMH_DATA}")
install(TARGETS openbmh_import RUNTIME DESTINATION . COMPONENT Runtime)
+279
View File
@@ -0,0 +1,279 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "import/assets.hpp"
#include "import/detail.hpp"
#include "formats/executable_layout.hpp"
#include "launch/game_data.hpp"
#include "launch/archive.hpp"
#include "audio/container.hpp"
#include <algorithm>
#include <cctype>
#include <limits>
namespace bmh::obw {
namespace {
using namespace detail;
namespace fs = std::filesystem;
void be32(std::string& out, uint32_t value) {
for (int shift = 24; shift >= 0; shift -= 8) out += char(value >> shift);
}
void chunk(std::string& out, const char* name, const std::string& payload) {
be32(out, uint32_t(payload.size()));
const auto start = out.size();
out.append(name, 4);
out += payload;
be32(out, crc(out.substr(start)));
}
std::string png(const Image& image, const Palette& palette, bool transparent) {
std::string out("\x89PNG\r\n\x1a\n", 8), header;
be32(header, uint32_t(image.width)); be32(header, uint32_t(image.height));
header.append("\x08\x03\x00\x00\x00", 5); // indexed PNG, exact palette indices
chunk(out, "IHDR", header);
std::string colors;
for (const uint32_t color : palette.argb)
for (int shift : {16, 8, 0}) colors += char(color >> shift);
chunk(out, "PLTE", colors);
if (transparent) chunk(out, "tRNS", std::string(1, '\0'));
std::string rows;
for (int y = 0; y < image.height; ++y) {
rows += '\0';
rows.append(reinterpret_cast<const char*>(image.pixels.data() + size_t(y) * image.width), size_t(image.width));
}
mz_ulong size = mz_compressBound(static_cast<mz_ulong>(rows.size()));
std::string compressed(size, '\0');
if (mz_compress2(reinterpret_cast<unsigned char*>(compressed.data()), &size,
reinterpret_cast<const unsigned char*>(rows.data()), static_cast<mz_ulong>(rows.size()), MZ_BEST_COMPRESSION) != MZ_OK)
fail("cannot compress PNG");
compressed.resize(size);
chunk(out, "IDAT", compressed); chunk(out, "IEND", "");
return out;
}
fs::path required(const fs::path& root, const std::string& name) {
const auto path = launch::find_file(root, name);
if (!path || !fs::is_regular_file(*path) || fs::is_symlink(fs::symlink_status(*path))) fail("missing regular resource: " + name);
return *path;
}
std::string lower(std::string value) {
for (char& c : value) c = char(std::tolower(static_cast<unsigned char>(c)));
return value;
}
bool numeric(const std::string& name) {
return !name.empty() && std::all_of(name.begin(), name.end(), [](unsigned char c) { return c >= '0' && c <= '9'; });
}
// Source sprites use a linear packed stride; a feature may cross a row edge.
Image extract(const Image& atlas, int sx, int sy, int width, int height) {
if (sx < 0 || sy < 0 || width <= 0 || height <= 0 || width > 1024 || height > 1024) fail("invalid sprite geometry");
Image out(width, height);
for (int y = 0; y < height; ++y) for (int x = 0; x < width; ++x) {
const auto at = size_t(sy + y) * size_t(atlas.width) + size_t(sx + x);
if (at >= atlas.pixels.size()) fail("sprite exceeds its packed atlas");
out.at(x, y) = atlas.pixels[at];
}
return out;
}
J asset(const std::string& key, const std::string& path, const std::string& source, const std::string& kind) {
return O{{"key", key}, {"files", O{{"native", path}}}, {"source", source},
{"author", "Original installation rights holders"}, {"license", "local-import-only"}, {"kind", kind}};
}
void image_entry(Documents& out, A& resources, A& index, const std::string& key,
const std::string& name, const Image& image, const Palette& palette, bool transparent = false) {
const auto base = "assets/classic/images/" + name;
out[base + ".png"] = png(image, palette, transparent);
out[base + ".pixels"] = binary(image.pixels);
resources.emplace_back(O{{"name", name}, {"width", image.width}, {"height", image.height},
{"pixels", base + ".pixels"}, {"png", base + ".png"}});
index.emplace_back(asset(key, base + ".png", name, "indexed-image"));
}
} // namespace
cli::Json portrait_recipe(const std::string& legacy_name, const LeImage& exe) {
using namespace detail;
// Unsigned overflow and signed source characters deliberately match the UI.
uint32_t seed = 0x14344;
for (size_t i = 0; i < legacy_name.size(); ++i) seed += int(int8_t(legacy_name[i])) * uint32_t(i) * 10;
const auto next = [&](uint32_t maximum) {
seed = (seed * 16 + 0xa7) % 4000000;
return int(seed * (maximum + 1) / 4000000);
};
next(100);
const int background = next(3);
A layers;
for (uint32_t layer = 0; layer < 5; ++layer) {
const auto count = exe.u8(layout::ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField2 + layer);
if (!count) fail("portrait layer has no parts");
layers.emplace_back(next(uint32_t(count - 1)));
}
return O{{"set", "bmh-classic@1"}, {"background", background}, {"layers", std::move(layers)}};
}
void import_assets(Documents& out, const std::filesystem::path& root, const Database& db, const LeImage& exe) {
using namespace detail;
const auto palette = load_palette(required(root, "M3PC.COL"));
A colors, index, images, fonts, audio, animations;
for (const auto color : palette.argb) colors.emplace_back(int64_t(color));
put(out, "assets/classic/palette.json", O{{"schema", "classic-palette@1.0"}, {"argb", std::move(colors)}});
std::map<std::string, Image> atlases;
for (const char* group : {"KB", "W"}) {
const auto folder = launch::find_file(root, group);
if (!folder || !fs::is_directory(*folder)) fail(std::string("missing directory: ") + group);
std::vector<fs::path> paths;
for (const auto& entry : fs::directory_iterator(*folder))
if (entry.is_regular_file() && lower(launch::path_to_utf8(entry.path().extension())) == ".vga" &&
numeric(launch::path_to_utf8(entry.path().stem()))) paths.push_back(entry.path());
std::sort(paths.begin(), paths.end());
for (const auto& path : paths) {
if (fs::is_symlink(fs::symlink_status(path)) || fs::file_size(path) > 16 * 1024 * 1024) fail("unsafe image input");
const auto bytes = read_file(path);
if (bytes.size() < 8 || le16(bytes, 0) == 0 || le16(bytes, 2) == 0 ||
uint64_t(le16(bytes, 0)) * le16(bytes, 2) > 16 * 1024 * 1024) fail("invalid image dimensions");
const auto name = lower(group) + '/' + launch::path_to_utf8(path.stem());
if (atlases.contains(name)) fail("duplicate image resource: " + name);
auto image = decode_vga(bytes);
image_entry(out, images, index, "asset:classic/" + name, name, image, palette);
atlases.emplace(name, std::move(image));
}
}
// Crests reference their original database identity, independently of runtime draws.
auto clubs = items(out, "clubs");
for (auto& club : clubs) {
const auto team = size_t(num(get(get(club, "x-legacy"), "team_index")));
const int selector = le16(db.raw_club_badge_selectors, team * 2) & 511;
const std::string sheet = "w/" + std::to_string(selector >> 3);
const bool neutral = (team >= 90 && team < 138) || (team >= 168 && team < 357);
const std::string atlas_name = neutral ? "kb/0" : sheet;
if (!atlases.contains(atlas_name)) fail("missing crest sheet " + atlas_name);
const auto name = "crests/" + std::to_string(team);
const auto key = "asset:club/" + str(get(club, "id")).substr(str(get(club, "id")).find(':') + 1) + "/crest";
image_entry(out, images, index, key, name, extract(atlases.at(atlas_name), neutral ? 8 : (selector & 7) * 38, 0, 38, 38), palette, true);
(*club.object())["crest"] = key;
}
table(out, "clubs", std::move(clubs));
const auto portrait = atlases.find("kb/29");
if (portrait == atlases.end()) fail("missing player portrait atlas KB/29.VGA");
A backgrounds, layers;
for (int i = 0; i < 4; ++i) {
const auto name = "portraits/background-" + std::to_string(i);
const auto key = "asset:portrait/bmh-classic/background/" + std::to_string(i);
image_entry(out, images, index, key, name, extract(portrait->second, 108 + i * 38, 168, 38, 38), palette);
backgrounds.emplace_back(O{{"asset", key}, {"x", 0}, {"y", 0}});
}
for (uint32_t layer = 0; layer < 5; ++layer) {
int sx = exe.u8(layout::ClubPlayerDetail_DrawPortrait_RuntimeField + layer);
int sy = exe.u8(layout::ClubPlayerDetail_DrawPortrait_RuntimeField2 + layer);
const int count = exe.u8(layout::ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField2 + layer);
const int width = exe.u8(layout::ClubPlayerDetail_DrawPortrait_RuntimeField3 + layer);
const int height = exe.u8(layout::ClubPlayerDetail_DrawPortrait_RuntimeField4 + layer);
if (!count) fail("empty portrait layer");
A parts;
for (int part = 0; part < count; ++part) {
const auto name = "portraits/layer-" + std::to_string(layer) + '-' + std::to_string(part);
const auto key = "asset:portrait/bmh-classic/layer/" + std::to_string(layer) + '/' + std::to_string(part);
image_entry(out, images, index, key, name, extract(portrait->second, sx, sy, width, height), palette, true);
parts.emplace_back(key);
sx += width;
if (sx > exe.u16(layout::ClubPlayerDetail_DrawPortrait_RuntimeField7 + layer * 2)) {
sx = exe.u8(layout::ClubPlayerDetail_DrawPortrait_RuntimeField + layer); sy += height;
}
}
// Destination relative to the 38x38 background at (181,109) in the legacy card.
layers.emplace_back(O{{"x", 1 + int(exe.u8(layout::ClubPlayerDetail_DrawPortrait_RuntimeField5 + layer))},
{"y", 5 + int(exe.u8(layout::ClubPlayerDetail_DrawPortrait_RuntimeField6 + layer))}, {"parts", std::move(parts)}});
}
put(out, "assets/portrait-sets/bmh-classic@1/set.json", O{{"schema", "portrait-set@1.0"},
{"id", "bmh-classic@1"}, {"width", 38}, {"height", 38}, {"transparent_index", 0},
{"backgrounds", std::move(backgrounds)}, {"layers", std::move(layers)}});
const auto font_dir = launch::find_file(root, "F");
if (!font_dir) fail("missing F directory");
for (const char* source : {"BMH2.FNT", "BMH3.FNT"}) {
const auto font = load_font(required(*font_dir, source));
const auto name = lower(source);
A glyphs;
for (const auto& glyph : font.glyphs) glyphs.emplace_back(O{{"bit_offset", int(glyph.bit_offset)},
{"bit_width", int(glyph.bit_width)}, {"advance", int(glyph.advance)}});
const auto bitmap = "assets/classic/fonts/" + name + ".bitmap";
out[bitmap] = binary(font.bitmap);
fonts.emplace_back(O{{"name", name}, {"height", font.height}, {"baseline", font.baseline},
{"nominal_width", font.nominal_width}, {"flags", int(font.flags)}, {"lo_char", int(font.lo_char)},
{"hi_char", int(font.hi_char)}, {"modulo", font.modulo}, {"glyphs", std::move(glyphs)}, {"bitmap", bitmap}});
index.emplace_back(asset("asset:font/classic/" + name, bitmap, std::string("F/") + source, "bitmap-font"));
}
const auto sound_dir = launch::find_file(root, "S");
if (!sound_dir) fail("missing S directory");
for (int i = 2000; i <= 2003; ++i) {
const auto name = std::to_string(i);
const auto bank = read_file(required(*sound_dir, name));
openbmh::audio::Container parsed;
std::string error;
if (!openbmh::audio::parse_container(bank, parsed, error)) fail("audio bank " + name + ": " + error);
const auto path = "assets/classic/audio/" + name + ".bank";
out[path] = binary(bank);
A chunks;
for (const auto& c : parsed.chunks) chunks.emplace_back(O{{"id", c.id}, {"offset", int64_t(c.payload_offset)}, {"size", int64_t(c.payload_size)}});
audio.emplace_back(O{{"name", name}, {"path", path}, {"codec", "original-alptraum@1"}, {"chunks", std::move(chunks)}});
index.emplace_back(asset("asset:audio/classic/" + name, path, "S/" + name, "audio-bank"));
}
// Preserve optional animation/editor artwork, but never personal options or saves.
for (const auto& entry : fs::directory_iterator(root)) {
const auto name = lower(launch::path_to_utf8(entry.path().filename()));
const auto ext = lower(launch::path_to_utf8(entry.path().extension()));
if (!entry.is_regular_file() || (ext != ".fli" && ext != ".flc" && name != "wappen.lbm")) continue;
if (entry.is_symlink() || entry.file_size() > 32 * 1024 * 1024) fail("unsafe optional artwork");
const auto path = "assets/classic/optional/" + name;
out[path] = binary(read_file(entry.path()));
animations.emplace_back(O{{"name", name}, {"path", path}});
index.emplace_back(asset("asset:classic/optional/" + name, path, name, "legacy-artwork"));
}
put(out, "assets/classic/resources.json", O{{"schema", "classic-resources@1.0"},
{"images", std::move(images)}, {"fonts", std::move(fonts)}, {"audio", std::move(audio)}, {"optional", std::move(animations)}});
put(out, "assets/index.json", O{{"schema", "asset-index@1.0"}, {"items", std::move(index)}});
}
void load_assets(const Documents& out, ClassicData& data) {
using namespace detail;
const auto palette = parse(out, "assets/classic/palette.json");
const auto& colors = arr(get(palette, "argb"));
if (colors.size() != 256) fail("palette must contain 256 colors");
for (size_t i = 0; i < 256; ++i) {
const auto color = num(colors[i]);
if (color < 0 || color > UINT32_MAX) fail("invalid palette color");
data.palette.argb[i] = uint32_t(color);
}
const auto resources = parse(out, "assets/classic/resources.json");
for (const auto& row : arr(get(resources, "images"))) {
const auto width = num(get(row, "width")), height = num(get(row, "height"));
const auto& pixels = out.at(str(get(row, "pixels")));
if (width <= 0 || height <= 0 || width > 65535 || height > 65535 || width * height != int64_t(pixels.size())) fail("image pixel count disagrees with dimensions");
Image image(int(width), int(height), 0);
image.pixels = bytes(pixels);
if (!data.images.emplace(str(get(row, "name")), std::move(image)).second) fail("duplicate indexed image");
}
for (const auto& row : arr(get(resources, "fonts"))) {
Font font;
font.height = int(num(get(row, "height"))); font.baseline = int(num(get(row, "baseline")));
font.nominal_width = int(num(get(row, "nominal_width"))); font.flags = uint8_t(num(get(row, "flags")));
font.lo_char = uint8_t(num(get(row, "lo_char"))); font.hi_char = uint8_t(num(get(row, "hi_char")));
font.modulo = int(num(get(row, "modulo"))); font.bitmap = bytes(out.at(str(get(row, "bitmap"))));
if (font.height <= 0 || font.modulo <= 0 || int64_t(font.height) * font.modulo != int64_t(font.bitmap.size())) fail("invalid font bitmap");
for (const auto& glyph : arr(get(row, "glyphs"))) {
const auto offset = num(get(glyph, "bit_offset")), width = num(get(glyph, "bit_width")), advance = num(get(glyph, "advance"));
// BMH2's zero-width replacement glyph points beyond the bitmap;
// it never dereferences that offset when drawing.
if (offset < 0 || offset > UINT16_MAX || width < 0 || width > UINT16_MAX ||
(width && offset + width > int64_t(font.modulo) * 8) || advance < INT16_MIN || advance > INT16_MAX) fail("invalid font glyph");
font.glyphs.push_back({uint16_t(offset), uint16_t(width), int16_t(advance)});
}
if (font.glyphs.size() != size_t(int(font.hi_char) - font.lo_char + 2)) fail("invalid font glyph count");
if (!data.fonts.emplace(str(get(row, "name")), std::move(font)).second) fail("duplicate font");
}
for (const auto& row : arr(get(resources, "audio"))) {
auto bank = bytes(out.at(str(get(row, "path"))));
openbmh::audio::Container parsed;
std::string error;
if (!openbmh::audio::parse_container(bank, parsed, error)) fail("invalid audio container: " + error);
if (!data.audio.emplace(str(get(row, "name")), std::move(bank)).second) fail("duplicate audio bank");
}
if (!data.images.contains("kb/29") || data.fonts.size() != 2 || data.audio.size() != 4) fail("incomplete classic media");
}
} // namespace bmh::obw
+11
View File
@@ -0,0 +1,11 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "import/classic.hpp"
namespace bmh::obw {
cli::Json portrait_recipe(const std::string& legacy_name, const LeImage& exe);
// PNGs retain original resolution. Portrait PARTS are exported, never composed faces.
void import_assets(Documents& out, const std::filesystem::path& root,
const Database& db, const LeImage& exe);
void load_assets(const Documents& out, ClassicData& data);
} // namespace bmh::obw
+446
View File
@@ -0,0 +1,446 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "import/classic.hpp"
#include "import/assets.hpp"
#include "import/detail.hpp"
#include "formats/executable_layout.hpp"
#include "launch/game_data.hpp"
#include "launch/archive.hpp"
#include <algorithm>
#include <cctype>
#include <iterator>
#include <set>
namespace bmh::obw {
namespace {
using namespace detail;
namespace fs = std::filesystem;
constexpr const char* profile = "classic-installation-v1";
constexpr const char* feature = "runtime:classic-v1";
constexpr const char* layout_id = "openbmh-classic-layout@1";
const A initializers{"classic-load-seeds@1", "classic-player-ratings@1", "classic-pending-offers@1",
"classic-markets-and-moods@1", "classic-free-agents@1", "classic-setup-options@1",
"classic-confirm-managers@1", "classic-season-setup@1"};
const A runtime_inputs{"game_rng_seed", "watcom_rng_seed", "managers", "game_level", "mode", "duration", "competition_options"};
struct Literal { const char* name; uint32_t address, size; };
// These four read-only labels share an LE code object. Extract the bounded
// strings individually, never the containing executable object/instructions.
constexpr Literal literals[] = {
{"free_kick_taker", layout::FreeKickTakerLabel, 9}, {"penalty_taker", layout::PenaltyTakerLabel, 9},
{"corner_taker", layout::CornerTakerLabel, 8}, {"automatic_takers", layout::AutomaticTakersLabel, 5}};
A literal_data(const LeImage& exe) {
constexpr char digits[] = "0123456789abcdef";
A values;
for (const auto& literal : literals) {
std::string hex;
bool terminated = false;
for (uint32_t i = 0; i < literal.size; ++i) {
const auto c = exe.u8(literal.address + i);
hex += digits[c >> 4]; hex += digits[c & 15];
if (c == 0) { terminated = true; break; }
if (c < 32 || c > 126) fail("invalid bounded embedded text literal");
}
if (!terminated) fail("unterminated bounded embedded text literal");
values.emplace_back(O{{"name", literal.name}, {"address", int(literal.address)}, {"bytes_hex", hex}});
}
return values;
}
Bytes required(const fs::path& root, const std::string& name, size_t size) {
const auto file = launch::find_file(root, name);
if (!file || !fs::is_regular_file(*file) || fs::is_symlink(fs::symlink_status(*file)) || fs::file_size(*file) != size)
fail(name + ": missing or incorrect size (expected " + std::to_string(size) + ')');
return read_file(*file);
}
A data_regions(Documents& out, const LeImage& exe, bool english, const std::string& variant) {
A regions;
const auto add = [&](const char* name, uint32_t begin, uint32_t end) {
if (!exe.contains(begin) || !exe.contains(end - 1)) fail("incomplete executable data region");
const std::string path = "x-classic/" + variant + '/' + name + ".bin";
out[path] = std::string(reinterpret_cast<const char*>(exe.data(begin)), end - begin);
regions.emplace_back(O{{"name", name}, {"base", int(begin)}, {"size", int(end - begin)}, {"path", path}});
};
add("common-data", layout::GermanDataSegmentBegin, layout::GermanImageEnd);
if (english) add("english-data", layout::EnDataStart, layout::Career_CompetitionPointersEnglish_RuntimeField);
return regions;
}
LeImage load_regions(const Documents& out, const J& value, const J& embedded, bool english) {
const auto& regions = arr(value);
if (regions.size() != size_t(english ? 2 : 1)) fail("incorrect data-region count");
Bytes image(layout::GermanImageEnd - 0x10000, 0);
std::set<uint32_t> seen;
for (const auto& region : regions) {
const auto base = num(get(region, "base")), size = num(get(region, "size"));
const bool german = base == layout::GermanDataSegmentBegin && size == layout::GermanImageEnd - layout::GermanDataSegmentBegin;
const bool en = english && base == layout::EnDataStart && size == layout::Career_CompetitionPointersEnglish_RuntimeField - layout::EnDataStart;
if ((!german && !en) || !seen.insert(uint32_t(base)).second) fail("unsupported/duplicate data region (code is forbidden)");
const auto& bytes = out.at(str(get(region, "path")));
if (int64_t(bytes.size()) != size) fail("truncated data region");
std::copy(bytes.begin(), bytes.end(), image.begin() + (base - 0x10000));
}
const auto& texts = arr(embedded);
if (texts.size() != std::size(literals)) fail("incomplete embedded text literals");
for (size_t i = 0; i < std::size(literals); ++i) {
const auto& literal = literals[i];
const auto data = unhex(str(get(texts[i], "bytes_hex")));
if (num(get(texts[i], "address")) != literal.address || str(get(texts[i], "name")) != literal.name ||
data.empty() || data.size() > literal.size || data.back() != 0) fail("invalid embedded text literal binding");
for (size_t ch = 0; ch + 1 < data.size(); ++ch)
if (data[ch] < 32 || data[ch] > 126) fail("invalid embedded text character");
std::copy(data.begin(), data.end(), image.begin() + (literal.address - 0x10000));
}
return LeImage::from_bytes(0x10000, std::move(image));
}
J localized(const std::string& value) { return O{{"default", legacy_text(value)}}; }
void competitions(Documents& out, const LeImage& exe) {
auto comps = items(out, "competitions");
const auto texts = parse(out, "x-legacy/texts.json");
const auto& strings = arr(get(texts, "items"));
std::map<int, A> cups;
for (uint32_t entry = 0; entry < 36; ++entry) {
const uint32_t at = layout::CupTable + entry * 0x28;
const int cup = int(int16_t(exe.u16(at + 0x18)));
if (cup < 0 || cup > 26) continue; // reserved sentinel entries stay in data regions
const int flags = exe.u8(at + 0x14), next = int(int8_t(exe.u8(at + 0x16)));
const int parallel = int(int8_t(exe.u8(at + 0x17)));
const int count = exe.u8(at + 0x1a);
O stage{{"id", "entry-" + std::to_string(entry)}, {"format", (flags & 4) ? "knockout" : "groups"},
{"teams", count}, {"legs", 1 + (flags & 1)}, {"matchdays", "calendar:classic-cup-" + std::to_string(cup)},
{"slots", A{O{{"resolver", "classic-entry@1"}, {"entry", int(entry)}, {"count", count}}}},
{"classic", O{{"entry", int(entry)}, {"flags", flags}, {"next_entry", next}, {"parallel_entry", parallel},
{"rounds", int(exe.u8(at + 0x1b))}, {"qualifying_rounds", int(exe.u8(at + 0x1c))},
{"groups", int(exe.u8(at + 0x1e) & 15)}, {"group_index", int(exe.u8(at + 0x1e) >> 4)},
{"qualification_quota", int(int8_t(exe.u8(at + 0x1f)))},
{"draw_each_round", bool(flags & 0x20)}, {"decide_on_day", bool(flags & 8)}}}};
cups[cup].emplace_back(std::move(stage));
}
const auto english = str(get(parse(out, "manifest.json"), "provenance")) == "import:fltd";
for (auto& [cup, stages] : cups) {
const auto text_index = (layout::DeskState_FormatError_ExecutableField3 - layout::TextPointerTable) / 4 + uint32_t(cup + 1);
const auto label = text_index < strings.size() ? get(strings[text_index], "text") : J("Classic competition " + std::to_string(cup));
std::string type = cup == 0 ? "cup" : cup >= 1 && cup <= 3 ? "club_international" :
cup >= 4 && cup <= 8 ? "national_team" : cup == 10 ? "friendly" : cup == 11 && !english ? "indoor" : "cup";
comps.emplace_back(O{{"id", "comp:classic-cup-" + std::to_string(cup)}, {"name", O{{"default", label}}},
{"type", type}, {"played", true}, {"stages", std::move(stages)},
{"classic", O{{"competition_id", cup}, {"calendar_bit", cup + 5},
{"qualification", "classic-season-entrants@1"}, {"runtime_participants", true}}}});
}
table(out, "competitions", std::move(comps));
auto calendars = items(out, "calendar");
auto& calendar = *calendars.at(0).object();
auto series = arr(calendar.at("series"));
for (const auto& [cup, unused] : cups) {
(void)unused;
series.emplace_back(O{{"id", "classic-cup-" + std::to_string(cup)}, {"legacy_calendar_bit", cup + 5}});
}
calendar["series"] = std::move(series);
calendar["initialization"] = O{{"policy", "classic-calendar@1"},
{"inputs", A{"start_date", "season_index", "competition_options"}},
{"source_anchor", "07-01"}, {"weekday_alignment", "classic-season-calendar@1"}};
table(out, "calendar", std::move(calendars));
}
} // namespace
void complete_classic(Documents& out, const fs::path& root, const Database& db,
const LeImage& exe, const LeImage& source_tables, bool english, const Options& options) {
using namespace detail;
const auto mod = english ? "FLTD-classic" : "BMH-classic";
if (!options.mod.empty() && options.mod != mod) fail("--mod does not match the source edition (expected " + std::string(mod) + ')');
const auto desktop = required(root, "M3.MEN", 864);
const auto formations = required(root, "M3.DAT", 1408);
out["x-classic/desktop-seed.bin"] = binary(desktop);
out["x-classic/formation-seed.bin"] = binary(formations);
const auto source_text = launch::find_file(root, english ? "TEXTE.BLK" : "TEXTD.BLK");
if (!source_text) fail("missing source text block");
const auto raw_texts = read_file(*source_text);
if (raw_texts.size() < 7) fail("truncated source text block");
out["x-classic/text-blob.bin"] = std::string(raw_texts.begin() + 7, raw_texts.end());
A text_header;
for (size_t i = 0; i < 7; ++i) text_header.emplace_back(int(raw_texts[i]));
const auto effective_regions = data_regions(out, exe, english, "effective");
const auto original_regions = data_regions(out, source_tables, english, "source");
put(out, "x-classic/startup.json", O{{"schema", "classic-startup@1.0"}, {"layout", layout_id},
{"mod", mod}, {"english", english}, {"rule_profile", "openbmh-supported@1"},
{"data_regions", effective_regions}, {"source_regions", original_regions},
{"embedded_literals", literal_data(exe)}, {"source_literals", literal_data(source_tables)},
{"desktop_seed", "x-classic/desktop-seed.bin"}, {"formation_seed", "x-classic/formation-seed.bin"},
{"text_blob", "x-classic/text-blob.bin"},
{"text_header", std::move(text_header)},
{"initializers", initializers}, {"runtime_inputs", runtime_inputs},
{"rng", O{{"import_consumes_draws", false}, {"game", "bmh-game@1"}, {"secondary", "watcom@1"}}}});
auto manifest = parse(out, "manifest.json");
auto& m = *manifest.object();
m["id"] = std::string("world:") + mod;
m["mod"] = mod;
m["requires"] = A{feature};
m["extensions"] = A{O{{"id", "x-legacy"}, {"version", "1.0"}}, O{{"id", "x-classic"}, {"version", "1.0"}}};
m["x-import"] = O{{"profile", profile}, {"content_complete", true}, {"runtime", feature},
{"rule_profile", "openbmh-supported@1"}, {"source_rules_preserved", true},
{"default_attribute_set", "bmh-classic@1"}, {"default_portrait_set", "bmh-classic@1"}};
put(out, "manifest.json", std::move(manifest));
auto players = items(out, "players");
A contracts;
for (size_t i = 0; i < players.size(); ++i) {
auto& player = *players[i].object();
player["appearance"] = portrait_recipe(db.players.at(i).name, exe);
player["photo"] = "asset:player/" + str(player.at("id")).substr(7) + "/photo";
if (player.contains("team")) contracts.emplace_back(O{{"id", id("contract", i)}, {"person", player.at("id")},
{"team", player.at("team")}, {"initialization", O{{"policy", "classic-player-contract@1"},
{"source_identity_word", int64_t(db.players.at(i).w364)}, {"source_skill_word", int64_t(db.players.at(i).w368)}}}});
}
table(out, "players", std::move(players));
table(out, "contracts", std::move(contracts));
auto nations = items(out, "nations");
auto clubs = items(out, "clubs");
A finance;
for (auto& club : clubs) {
auto& row = *club.object();
const auto team = size_t(num(get(row.at("x-legacy"), "team_index")));
if (team >= 168 && team < 357) row["nation"] = get(nations.at(5 + (team - 168) / 7), "id");
if (team >= 168) {
constexpr int levels[] = {55, 61, 65, 67, 70, 73, 76, 80};
const auto code = db.raw_foreign_club_strength.at(team - 168);
row["classic_strength"] = O{{"band", int(code >> 5)}, {"base", levels[code >> 5]},
{"style_flags", int(code & 31)}, {"policy", "classic-strength-only-team@1"}};
}
row["kit"] = O{{"set", "bmh-classic@1"}, {"selector", int(db.raw_club_kit_selectors.at(team))}};
if (team < 138) {
row["stadium_initialization"] = O{{"policy", "classic-stadium@1"}, {"name_pool", "stadiums"}};
finance.emplace_back(O{{"id", id("finance", team)}, {"team", row.at("id")},
{"initialization", O{{"policy", "classic-manager-finance@1"},
{"when", "human_manager_assigned"}, {"inputs", A{"game_level", "mode", "start_league"}}}}});
}
}
table(out, "clubs", std::move(clubs));
nations.erase(std::remove_if(nations.begin(), nations.end(), [](const J& nation) {
return str(get(nation, "id")) == "nation:x-legacy-unassigned";
}), nations.end());
table(out, "nations", std::move(nations));
table(out, "finance", std::move(finance));
A staff;
for (size_t i = 0; i < db.referees.size(); ++i) {
if (i >= db.raw_referee_properties.size()) fail("referee property count mismatch");
const auto property = db.raw_referee_properties[i];
staff.emplace_back(O{{"id", id("staff", i)}, {"name", localized(db.referees[i])}, {"role", "referee"},
{"attributes", O{{"strictness", int((property >> 3) & 3)}}},
{"x-legacy", O{{"referee_index", int(i)}, {"property", int(property)}}}});
}
table(out, "staff", std::move(staff));
auto rules = items(out, "rules");
rules.emplace_back(O{{"id", "rule:classic-runtime"}, {"type", "classic_runtime"}, {"version", 1},
{"startup", "x-classic/startup.json"}, {"layout", layout_id},
{"calendar", "classic-calendar@1"}, {"qualifications", "classic-season-entrants@1"},
{"financial_initialization", "classic-manager-finance@1"}, {"stadium_initialization", "classic-stadium@1"},
{"contract_initialization", "classic-player-contract@1"}, {"staff_initialization", "classic-confirm-managers@1"},
{"default_portrait_set", "bmh-classic@1"}});
rules.emplace_back(O{{"id", "rule:classic-data-tables"}, {"type", "classic_data_regions"},
{"layout", layout_id}, {"effective", effective_regions}, {"source", original_regions},
{"coverage", A{"competition_configuration", "qualification_and_movement", "calendar", "player_generation",
"contracts", "finance", "sponsors", "training", "stadiums", "transfer_market", "national_teams",
"match_parameters", "embedded_texts", "interface_tables", "audio_tables"}}});
table(out, "rules", std::move(rules));
competitions(out, exe);
import_assets(out, root, db, exe);
auto report = parse(out, "x-legacy/import-report.json");
auto& r = *report.object();
r["profile"] = profile;
r["unmapped"] = A{};
auto warnings = arr(r.at("warnings"));
warnings.erase(std::remove_if(warnings.begin(), warnings.end(), [](const J& warning) {
return warning.string() && warning.string()->starts_with("foreign club nation assignments");
}), warnings.end());
r["warnings"] = std::move(warnings);
r["coverage"] = O{{"core_entities", true}, {"all_classic_data_regions", true}, {"media", true},
{"new_career_initialization", "runtime:classic-v1"}, {"savegame_conversion", false}};
r["notes"] = A{"Complete installation content for the versioned Classic adapter, not a running career.",
"Runtime-generated values are initialization policies, not fabricated initial contracts or stadiums.",
"Generic competitions/rules are projections. Exact classic semantics use x-classic data and runtime:classic-v1.",
"Both the supported effective tables and unpatched source data tables are retained; no executable code is exported.",
"Player appearances are frozen from the original byte names; only portrait parts, never composed faces, are stored.",
"No FBM, personal EIN, SOUND.CFG, high scores, or executable is copied.",
"No 0.1 frontend reads OBW. The 0.2 runtime adapter is separate work."};
put(out, "x-legacy/import-report.json", std::move(report));
// All payload entries, including binary assets, are checked before publication/load.
refresh_classic_inventory(out);
}
void refresh_classic_inventory(Documents& out) {
using namespace detail;
A inventory;
for (const auto& [path, contents] : out)
if (path != "x-classic/inventory.json")
inventory.emplace_back(O{{"path", path}, {"bytes", int64_t(contents.size())}, {"crc32", int64_t(crc(contents))}});
put(out, "x-classic/inventory.json", O{{"schema", "classic-inventory@1.0"}, {"entries", std::move(inventory)}});
}
static ClassicData decode_classic(const Documents& out) {
using namespace detail;
const auto startup = parse(out, "x-classic/startup.json");
if (str(get(startup, "schema")) != "classic-startup@1.0" || str(get(startup, "layout")) != layout_id)
fail("unsupported classic startup/layout version");
ClassicData data;
const auto* en = get(startup, "english").boolean();
if (!en) fail("invalid edition flag");
data.english = *en;
data.executable = load_regions(out, get(startup, "data_regions"), get(startup, "embedded_literals"), data.english);
data.source_tables = load_regions(out, get(startup, "source_regions"), get(startup, "source_literals"), data.english);
const auto database = parse(out, "x-legacy/source-database.json");
data.database = decode_database(unhex(str(get(database, "bytes"))));
data.desktops = bytes(out.at(str(get(startup, "desktop_seed"))));
data.formations = bytes(out.at(str(get(startup, "formation_seed"))));
if (data.desktops.size() != 864 || data.formations.size() != 1408) fail("invalid startup seed sizes");
data.texts.blob = bytes(out.at(str(get(startup, "text_blob"))));
const auto& header = arr(get(startup, "text_header"));
if (header.size() != 7) fail("invalid source text header");
for (const auto& byte : header) {
if (num(byte) < 0 || num(byte) > 255) fail("invalid source text header byte");
data.text_header.push_back(uint8_t(num(byte)));
}
size_t position = 0;
while (data.texts.strings.size() < TEXT_COUNT && position < data.texts.blob.size()) {
const auto begin = position;
while (position < data.texts.blob.size() && data.texts.blob[position]) ++position;
if (position == data.texts.blob.size()) fail("unterminated classic text");
data.texts.offsets.push_back(begin);
data.texts.strings.emplace_back(data.texts.blob.begin() + begin, data.texts.blob.begin() + position);
++position;
}
if (data.texts.strings.size() != TEXT_COUNT) fail("incomplete classic texts");
load_assets(out, data);
return data;
}
void validate_classic(const Documents& out) {
using namespace detail;
const auto manifest = parse(out, "manifest.json");
const auto& imported = get(manifest, "x-import");
if (str(get(imported, "profile")) != profile || !get(imported, "content_complete").boolean() ||
!*get(imported, "content_complete").boolean()) fail("incomplete classic profile");
const auto& required_features = arr(get(manifest, "requires"));
if (required_features.size() != 1 || str(required_features[0]) != feature) fail("missing classic runtime requirement");
const auto startup = parse(out, "x-classic/startup.json");
const auto expected = str(get(manifest, "provenance")) == "import:fltd" ? "FLTD-classic" : "BMH-classic";
if (str(get(manifest, "mod")) != expected || str(get(startup, "mod")) != expected) fail("mod/edition mismatch");
if (str(get(imported, "rule_profile")) != "openbmh-supported@1" ||
str(get(startup, "rule_profile")) != "openbmh-supported@1" ||
cli::dump_json(get(startup, "initializers")) != cli::dump_json(initializers) ||
cli::dump_json(get(startup, "runtime_inputs")) != cli::dump_json(runtime_inputs)) fail("unsupported classic initialization contract");
std::set<std::string> seen;
const auto inventory = parse(out, "x-classic/inventory.json");
for (const auto& entry : arr(get(inventory, "entries"))) {
const auto path = str(get(entry, "path"));
if (!safe_path(path) || path == "x-classic/inventory.json" || !seen.insert(path).second || !out.contains(path)) fail("invalid inventory entry: " + path);
const auto& bytes = out.at(path);
if (int64_t(bytes.size()) != num(get(entry, "bytes")) || int64_t(crc(bytes)) != num(get(entry, "crc32"))) fail("damaged entry: " + path);
if (path.starts_with("state/")) fail("save state is forbidden in an installation mod");
auto suffix = fs::path(path).extension().string();
for (char& ch : suffix) ch = char(std::tolower(static_cast<unsigned char>(ch)));
if (suffix == ".exe" || suffix == ".fbm" || suffix == ".obs" || suffix == ".ein" || suffix == ".cfg") fail("non-content file in classic world");
}
if (seen.size() + 1 != out.size()) fail("unlisted archive entries");
auto data = decode_classic(out);
if (data.english != (std::string(expected) == "FLTD-classic")) fail("startup edition mismatch");
// Every fixture pointer must remain readable from the exported DATA view.
const auto fixture_rules = items(out, "rules");
const auto fixture = std::find_if(fixture_rules.begin(), fixture_rules.end(), [](const J& row) {
return str(get(row, "id")) == "rule:legacy-fixtures";
});
if (fixture == fixture_rules.end()) fail("missing fixture generators");
const std::map<int, uint32_t> bindings = data.english ?
std::map<int, uint32_t>{{4, layout::EnglishFourTeamFixtureTable}, {6, layout::EnglishSixTeamFixtureTable},
{12, layout::EnglishTwelveTeamFixtureTable}, {20, layout::EnglishTwentyTeamFixtureTable}} :
std::map<int, uint32_t>{{4, layout::CareerSession_RuntimeError_RuntimeField}, {6, layout::CareerSession_RuntimeError_RuntimeField2},
{12, layout::CareerSession_RuntimeError_RuntimeField3}, {16, layout::CareerSession_RuntimeError_ExecutableField3},
{18, layout::CareerSession_RuntimeError_ExecutableField}, {20, layout::CareerSession_RuntimeError_ExecutableField2}};
std::set<int> fixture_sizes;
for (const auto& entry : arr(get(*fixture, "tables"))) {
const int teams = int(num(get(entry, "teams")));
if (!bindings.contains(teams) || !fixture_sizes.insert(teams).second) fail("invalid fixture generator size");
if (str(get(entry, "id")) != "legacy:" + std::to_string(teams)) fail("invalid fixture generator identity");
const auto& rounds = arr(get(entry, "rounds"));
if (rounds.size() != size_t(teams - 1)) fail("invalid fixture round count");
for (size_t round = 0; round < rounds.size(); ++round) {
const auto row = data.executable.cstring(data.executable.u32(bindings.at(teams) + uint32_t(round + 1) * 4));
if (row.size() != size_t(teams) || arr(rounds[round]).size() != size_t(teams / 2)) fail("incomplete fixture round data");
std::set<char> seen;
for (const char team : row)
if (team < 'a' || team >= 'a' + teams || !seen.insert(team).second) fail("invalid fixture round participants");
for (size_t match = 0; match < size_t(teams / 2); ++match) {
const auto& pair = arr(arr(rounds[round])[match]);
if (pair.size() != 2 || num(pair[0]) != row[match * 2] - 'a' || num(pair[1]) != row[match * 2 + 1] - 'a') fail("fixture projection disagrees with classic data");
}
}
}
if (fixture_sizes.size() != bindings.size()) fail("incomplete fixture generators");
const auto portrait_set = parse(out, "assets/portrait-sets/bmh-classic@1/set.json");
const auto& layers = arr(get(portrait_set, "layers"));
if (layers.size() != 5 || arr(get(portrait_set, "backgrounds")).size() != 4) fail("invalid portrait set");
std::set<std::string> assets;
const auto index = parse(out, "assets/index.json");
for (const auto& row : arr(get(index, "items"))) {
const auto key = str(get(row, "key"));
if (!key.starts_with("asset:") || !assets.insert(key).second || str(get(row, "license")) != "local-import-only") fail("invalid asset metadata");
const auto* files = get(row, "files").object();
if (!files || files->empty()) fail("missing asset files");
for (const auto& [size, path] : *files) {
(void)size;
if (!out.contains(str(path))) fail("missing asset file: " + str(path));
}
}
for (const auto& row : arr(get(portrait_set, "backgrounds")))
if (!assets.contains(str(get(row, "asset")))) fail("missing portrait background asset");
for (const auto& layer : layers) for (const auto& part : arr(get(layer, "parts")))
if (!assets.contains(str(part))) fail("missing portrait part asset");
const auto players = items(out, "players");
if (players.size() != data.database.players.size()) fail("incomplete player projections");
for (const auto& player : players) {
const auto& appearance = get(player, "appearance");
const auto background = num(get(appearance, "background"));
const auto& parts = arr(get(appearance, "layers"));
if (str(get(appearance, "set")) != "bmh-classic@1" || background < 0 || background > 3 || parts.size() != 5) fail("invalid frozen player appearance");
for (size_t i = 0; i < 5; ++i)
if (num(parts[i]) < 0 || num(parts[i]) >= int64_t(arr(get(layers[i], "parts")).size())) fail("portrait part index out of range");
}
const auto clubs = items(out, "clubs");
for (const auto& club : clubs) if (!assets.contains(str(get(club, "crest")))) fail("missing club crest");
if (items(out, "finance").size() != 138 || items(out, "staff").size() != data.database.referees.size()) fail("incomplete finance/staff seeds");
std::map<std::string, std::string> owned;
for (const auto& player : players)
if (player.object()->contains("team")) owned.emplace(str(get(player, "id")), str(get(player, "team")));
const auto contracts = items(out, "contracts");
if (contracts.size() != owned.size()) fail("incomplete contract seeds");
for (const auto& contract : contracts) {
const auto who = str(get(contract, "person"));
if (!owned.contains(who) || owned.at(who) != str(get(contract, "team"))) fail("contract does not match its player/team");
owned.erase(who);
}
std::set<int> entries;
size_t leagues = 0;
for (const auto& competition : items(out, "competitions")) {
if (str(get(competition, "type")) == "league") { ++leagues; continue; }
const auto cup = num(get(get(competition, "classic"), "competition_id"));
for (const auto& stage : arr(get(competition, "stages"))) {
const auto entry = num(get(get(stage, "classic"), "entry"));
if (entry < 0 || entry >= 36 || !entries.insert(int(entry)).second ||
data.executable.u16(layout::CupTable + uint32_t(entry) * 0x28 + 0x18) != cup) fail("invalid classic cup stage binding");
}
}
if (leagues != 9) fail("classic world requires nine league definitions");
for (uint32_t entry = 0; entry < 36; ++entry) {
const int cup = int(int16_t(data.executable.u16(layout::CupTable + entry * 0x28 + 0x18)));
if (cup >= 0 && cup <= 26 && !entries.contains(int(entry))) fail("missing classic cup stage");
}
}
ClassicData load_classic(const Documents& out) {
validate(out);
return decode_classic(out);
}
} // namespace bmh::obw
+29
View File
@@ -0,0 +1,29 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "import/obw.hpp"
#include "formats/font.hpp"
#include "formats/palette.hpp"
namespace bmh::obw {
// Installation content only. No manager choices, career RNG or save state.
struct ClassicData {
bool english = false;
Database database;
TextDb texts;
LeImage executable; // DATA regions and four bounded literals; no instructions
LeImage source_tables;
Bytes desktops, formations, text_header;
Palette palette;
std::map<std::string, Image> images;
std::map<std::string, Font> fonts;
std::map<std::string, Bytes> audio;
};
void complete_classic(Documents& out, const std::filesystem::path& root,
const Database& database, const LeImage& executable,
const LeImage& source_tables, bool english, const Options& options);
void validate_classic(const Documents& out);
// For an editor after deliberate changes. CRC32 detects damage, not authenticity.
void refresh_classic_inventory(Documents& out);
ClassicData load_classic(const Documents& out);
} // namespace bmh::obw
+83
View File
@@ -0,0 +1,83 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "import/obw.hpp"
#include <iomanip>
#include <sstream>
#include <string_view>
#include "miniz.h"
namespace bmh::obw::detail {
using J = cli::Json;
using A = J::Array;
using O = J::Object;
[[noreturn]] inline void fail(const std::string& message) { throw FormatError("OBW: " + message); }
inline const J& get(const J& value, std::string_view key) {
if (!value.object()) fail("expected object for field: " + std::string(key));
const auto found = value.object()->find(key);
if (found == value.object()->end()) fail("missing field: " + std::string(key));
return found->second;
}
inline std::string str(const J& value) {
if (!value.string()) fail("expected string");
return *value.string();
}
inline int64_t num(const J& value) {
if (!value.integer()) fail("expected integer");
return *value.integer();
}
inline const A& arr(const J& value) {
if (!value.array()) fail("expected array");
return *value.array();
}
inline J parse(const Documents& out, const std::string& path) {
if (!out.contains(path)) fail("missing entry: " + path);
return cli::parse_json(out.at(path));
}
inline void put(Documents& out, const std::string& path, J value) {
out[path] = cli::dump_json(value) + '\n';
}
inline A items(const Documents& out, const std::string& table) {
return arr(get(parse(out, "world/" + table + ".json"), "items"));
}
inline void table(Documents& out, const std::string& name, A values) {
put(out, "world/" + name + ".json", O{{"schema", name + "@1.0"}, {"items", std::move(values)}});
}
inline std::string id(const std::string& prefix, size_t index) {
std::ostringstream out;
out << prefix << ':' << std::setfill('0') << std::setw(5) << index;
return out.str();
}
inline std::string binary(const Bytes& bytes) { return std::string(bytes.begin(), bytes.end()); }
inline Bytes bytes(const std::string& value) { return Bytes(value.begin(), value.end()); }
inline std::string legacy_text(const std::string& raw) {
std::string result;
for (const unsigned char byte : raw) {
if (byte >= 128) { result += char(0xc0 | (byte >> 6)); result += char(0x80 | (byte & 63)); }
else { const char one[] = {char(byte), 0}; result += iso646de_to_utf8(one, 1); }
}
return result;
}
inline Bytes unhex(const std::string& hex) {
if (hex.size() % 2) fail("odd hex length");
const auto digit = [](char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
fail("invalid hex digit");
};
Bytes result;
result.reserve(hex.size() / 2);
for (size_t i = 0; i < hex.size(); i += 2) result.push_back(uint8_t(digit(hex[i]) * 16 + digit(hex[i + 1])));
return result;
}
inline uint32_t crc(const std::string& data) {
return uint32_t(mz_crc32(MZ_CRC32_INIT, reinterpret_cast<const unsigned char*>(data.data()), data.size()));
}
inline bool safe_path(const std::string& path) {
if (path.empty() || path.front() == '/' || path.back() == '/' || path.find('\\') != std::string::npos ||
path.find(':') != std::string::npos || path.find('\0') != std::string::npos) return false;
std::istringstream parts(path);
std::string part;
while (std::getline(parts, part, '/')) if (part.empty() || part == "." || part == "..") return false;
return true;
}
} // namespace bmh::obw::detail
+27 -7
View File
@@ -9,7 +9,7 @@
int main(int argc, char** argv) {
try {
const auto args = bmh::launch::utf8_arguments(argc, argv);
std::filesystem::path source, destination;
std::filesystem::path source, destination, validate_path;
bmh::obw::Options options;
bool directory = false;
for (size_t i = 1; i < args.size(); ++i) {
@@ -17,11 +17,14 @@ int main(int argc, char** argv) {
if (arg == "--help" || arg == "-h") {
std::cout << "OpenBMH installation-to-OBW converter\n"
"Usage: openbmh_import --data DIR_OR_EXE --output WORLD.obw\n"
" --start-date YYYY-07-01 [--title TEXT] [--directory]\n\n"
"Reads BMH.EXE/M3D.MAN/TEXTD.BLK or FLTD.EXE/M3E.MAN/TEXTE.BLK.\n"
" --start-date YYYY-07-01 [--mod BMH-classic|FLTD-classic]\n"
" [--title TEXT] [--directory] [--database-only]\n"
" openbmh_import --validate WORLD.obw_OR_DIRECTORY\n\n"
"Imports a complete BMH or Football Limited installation, including media.\n"
"--directory writes an unpacked world instead of a ZIP archive.\n"
"Existing destinations are never overwritten. Imported content stays local.\n"
"Conversion profile only: no game loading, FBM saves or graphics yet.\n";
"--database-only explicitly selects the old partial development export.\n"
"Classic content targets the 0.2 adapter; 0.1 cannot load OBW. No FBM conversion.\n";
return 0;
}
if (arg == "--version") {
@@ -29,13 +32,29 @@ int main(int argc, char** argv) {
return 0;
}
if (arg == "--directory") { directory = true; continue; }
if (arg != "--data" && arg != "--output" && arg != "--start-date" && arg != "--title")
if (arg == "--database-only") { options.database_only = true; continue; }
if (arg != "--data" && arg != "--output" && arg != "--start-date" && arg != "--title" &&
arg != "--mod" && arg != "--validate")
throw std::runtime_error("unknown option: " + arg);
if (++i == args.size()) throw std::runtime_error("missing value for " + arg);
if (arg == "--data") source = bmh::launch::path_from_utf8(args[i]);
if (arg == "--output") destination = bmh::launch::path_from_utf8(args[i]);
if (arg == "--start-date") options.start_date = args[i];
if (arg == "--title") options.title = args[i];
if (arg == "--mod") {
options.mod = args[i];
if (options.mod == "FTDL-classic" || options.mod == "FTLD-classic") options.mod = "FLTD-classic";
if (options.mod != "BMH-classic" && options.mod != "FLTD-classic")
throw std::runtime_error("--mod must be BMH-classic or FLTD-classic");
}
if (arg == "--validate") validate_path = bmh::launch::path_from_utf8(args[i]);
}
if (!validate_path.empty()) {
if (!source.empty() || !destination.empty() || !options.start_date.empty() || !options.mod.empty() || directory || options.database_only)
throw std::runtime_error("--validate cannot be combined with conversion options");
const auto documents = bmh::obw::read(validate_path);
std::cout << "Valid OBW content: " << documents.size() << " entries; no engine runtime test implied.\n";
return 0;
}
if (source.empty() || destination.empty() || options.start_date.empty())
throw std::runtime_error("--data, --output and --start-date are required; see --help");
@@ -45,8 +64,9 @@ int main(int argc, char** argv) {
bmh::obw::write(documents, destination, directory);
std::cout << "Converted " << documents.size() << " documents to "
<< bmh::launch::path_to_utf8(destination) << "\n"
<< "Profile: legacy-database-v1; content_license: local-import-only.\n"
<< "See x-legacy/import-report.json for coverage and remaining mappings.\n";
<< "Profile: " << (options.database_only ? "legacy-database-v1 (partial)" : "classic-installation-v1 (complete Classic content)")
<< "; content_license: local-import-only.\n"
<< "See manifest.json and x-legacy/import-report.json. 0.2 runtime integration is separate.\n";
return 0;
} catch (const std::exception& error) {
std::cerr << "openbmh_import: " << error.what() << '\n';
+75 -8
View File
@@ -1,5 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "import/obw.hpp"
#include "import/classic.hpp"
#include "import/detail.hpp"
#include <algorithm>
#include <array>
@@ -165,10 +167,10 @@ std::string po_quote(const std::string& value) {
return result + '"';
}
const J& field(const J& value, const std::string& key, const std::string& path) {
const J& field(const J& value, std::string_view key, std::string_view path) {
const auto* object = value.object();
if (!object || !object->contains(key)) fail(path + ": missing " + key);
return object->at(key);
if (!object || !object->contains(key)) fail(std::string(path) + ": missing " + std::string(key));
return object->find(key)->second;
}
std::string string_field(const J& value, const std::string& key, const std::string& path) {
const auto* result = field(value, key, path).string();
@@ -466,6 +468,16 @@ Documents import_installation(const fs::path& source, const Options& options) {
return *file;
};
const auto exe = english ? launch::translate_fltd(*english_exe) : load_le(*german);
const std::string expected_mod = english ? "FLTD-classic" : "BMH-classic";
if (!options.mod.empty() && options.mod != expected_mod) fail("--mod must be " + expected_mod + " for this installation");
if (!options.database_only) {
const auto checked = launch::check_game_directory(english ? *english_exe : *german);
if (!checked.problems.empty()) {
std::string problem = "incomplete installation";
for (const auto& message : checked.problems) problem += "\n- " + message;
fail(problem + "\nUse --database-only only for an explicitly partial development export.");
}
}
const auto db_path = required(english ? "M3E.MAN" : "M3D.MAN");
const auto text_path = required(english ? "TEXTE.BLK" : "TEXTD.BLK");
const auto database = load_database(db_path);
@@ -474,6 +486,11 @@ Documents import_installation(const fs::path& source, const Options& options) {
// runnable legacy installation. No absolute developer paths enter the archive.
put(out, "x-legacy/source-database.json", O{{"schema", "legacy-source@1.0"},
{"name", english ? "M3E.MAN" : "M3D.MAN"}, {"encoding", "hex"}, {"bytes", hex(read_file(db_path))}});
if (!options.database_only) {
const auto source_tables = english ? launch::translate_fltd(*english_exe, false) : load_le(*german, false);
complete_classic(out, root, database, exe, source_tables, english, options);
}
validate(out);
return out;
}
@@ -488,13 +505,24 @@ void validate(const Documents& documents) {
{"format", "openbmh-world"}, {"format_version", "1.0"}, {"kind", "world"}, {"content_license", "local-import-only"}})
if (string_field(manifest, key, "manifest.json") != expected) fail("manifest.json: unsupported " + key);
start_year(string_field(manifest, "start_date", "manifest.json"));
uint64_t total = 0;
if (documents.size() > 8192) fail("world has too many entries");
for (const auto& [path, contents] : documents) {
total += contents.size();
if (contents.size() > 32 * 1024 * 1024 || total > 128ull * 1024 * 1024) fail("world exceeds import size limits");
if (!detail::safe_path(path)) fail("unsafe archive path: " + path);
}
const auto& features = field(manifest, "requires", "manifest.json");
if (!features.array() || features.array()->size() != 1 || !features.array()->front().string() ||
*features.array()->front().string() != "import:legacy-database-v1") fail("manifest.json: missing conversion-only feature guard");
const auto& profile = field(manifest, "x-import", "manifest.json");
const auto* playable = field(profile, "playable", "manifest.json:x-import").boolean();
if (!playable || *playable || string_field(profile, "profile", "manifest.json:x-import") != "legacy-database-v1")
fail("manifest.json: conversion profile must remain non-playable");
const bool classic = string_field(profile, "profile", "manifest.json:x-import") == "classic-installation-v1";
if (classic) validate_classic(documents);
else {
if (!features.array() || features.array()->size() != 1 || !features.array()->front().string() ||
*features.array()->front().string() != "import:legacy-database-v1") fail("manifest.json: missing conversion-only feature guard");
const auto* playable = field(profile, "playable", "manifest.json:x-import").boolean();
if (!playable || *playable || string_field(profile, "profile", "manifest.json:x-import") != "legacy-database-v1")
fail("manifest.json: conversion profile must remain non-playable");
}
std::map<std::string, std::string> ids;
struct Reference { std::string value, prefix, path; };
@@ -521,6 +549,7 @@ void validate(const Documents& documents) {
if (item.object()->contains(key)) references.push_back({string_field(item, key, at), prefix, at + '.' + key});
};
ref("nation", "nation:"); ref("team", "club:"); ref("stadium", "stadium:"); ref("national_team", "nt:");
if (std::string(name) == "contracts") ref("person", "player:");
if (std::string(name) == "players") {
const auto* nats = field(item, "nationalities", at).array();
if (!nats || nats->empty()) fail(at + ": nationalities must not be empty");
@@ -547,6 +576,13 @@ void validate(const Documents& documents) {
size_t participants = 0;
std::set<std::string> unique_teams;
for (const auto& slot : *slots) {
if (classic && slot.object() && slot.object()->contains("resolver")) {
if (string_field(slot, "resolver", at) != "classic-entry@1") fail(at + ": unknown slot resolver");
const auto* count = field(slot, "count", at).integer();
if (!count || *count < 0 || *count > 255) fail(at + ": invalid classic slot count");
participants += size_t(*count);
continue;
}
const auto* teams = field(slot, "teams", at).array();
if (!teams) fail(at + ": slot teams must be an array");
for (const auto& team : *teams) {
@@ -566,6 +602,37 @@ void validate(const Documents& documents) {
if (!ids.contains(ref.value) || !ref.value.starts_with(ref.prefix)) fail(ref.path + ": unknown or wrong-type id " + ref.value);
}
Documents read(const fs::path& source) {
Documents result;
uint64_t total = 0;
const auto add = [&](const std::string& name, const Bytes& bytes) {
if (!detail::safe_path(name)) fail("unsafe archive entry: " + name);
total += bytes.size();
if (total > 128ull * 1024 * 1024 || result.size() >= 8192) fail("world exceeds import size limits");
if (!result.emplace(name, detail::binary(bytes)).second) fail("duplicate archive entry: " + name);
};
if (fs::is_directory(source)) {
for (const auto& entry : fs::recursive_directory_iterator(source)) {
if (entry.is_symlink()) fail("symlinks are forbidden in an unpacked world");
if (!entry.is_regular_file()) continue;
if (entry.file_size() > 32 * 1024 * 1024 || total + entry.file_size() > 128ull * 1024 * 1024) fail("world exceeds import size limits");
const auto name = entry.path().lexically_relative(source).generic_u8string();
add(std::string(name.begin(), name.end()), read_file(entry.path()));
}
} else {
if (fs::file_size(source) > 128ull * 1024 * 1024) fail("world archive is too large");
auto archive = launch::Archive::open(source);
for (size_t i = 0; i < archive.entries().size(); ++i) {
const auto& entry = archive.entries()[i];
if (entry.directory) continue;
if (entry.size > 32 * 1024 * 1024 || total + entry.size > 128ull * 1024 * 1024) fail("world exceeds import size limits");
add(entry.name, archive.read(i));
}
}
validate(result);
return result;
}
void write(const Documents& documents, const fs::path& destination, bool directory) {
validate(documents);
if (fs::symlink_status(destination).type() != fs::file_type::not_found) fail("destination already exists");
+9 -4
View File
@@ -12,22 +12,27 @@
namespace bmh::obw {
// A conversion document, deliberately independent of GameState and CareerSession.
// Keys are relative, authored archive paths; values are UTF-8 text.
// An archive entry, deliberately independent of GameState and CareerSession.
// Keys are relative, authored paths; strings are binary-safe (including NUL).
using Documents = std::map<std::string, std::string>;
struct Options {
std::string start_date; // Required: legacy databases have ages, not birth dates.
std::string title = "Imported legacy world";
// Empty selects BMH-classic / FLTD-classic from the installation.
std::string mod;
// Explicit developer-only partial export; the default requires a complete installation.
bool database_only = false;
};
Documents convert_database(const Database& database, const TextDb& texts,
const LeImage& executable, bool english, const Options& options);
Documents import_installation(const std::filesystem::path& source, const Options& options);
// Checks the conversion profile and its cross-table references before any output.
// This is not the future engine's competition/playability validator.
// Checks the declared import profile, references and (for Classic) complete payload.
// This is not a generic competition engine or a JSON Schema implementation.
void validate(const Documents& documents);
Documents read(const std::filesystem::path& source);
// Refuses existing destinations. Publishes a complete sibling staging path by rename.
// No files in the installation are changed, copied back or executed.