Integrate Classic 0.2 launcher and native runtime (by Codex)

# Conflicts:
#	tools/public_release/check_public_tree.py
#	tools/public_release/test_public_tree.py
This commit is contained in:
Codex committed 2026-10-22 23:05:57 +02:00
commit b8183e4165
108 files changed
+6344 -257

No files matched your search

+245 -25
View File
@@ -1,6 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "app/career_session.hpp"
#include "content/save.hpp"
#include "import/save.hpp"
#include <stdexcept>
#include <system_error>
@@ -420,16 +422,14 @@ void restore_saved_turn_cursor(TurnDriver& driver, GameState& state, const Datab
if (!unsupported_continuation.empty()) return;
std::vector<int> active_leagues;
// DayCompetitions2's competition bits expand to group leagues in this original order;
// bit 2 owns both league 2 and 3. The stale descriptors after the active group count
// are intentionally ignored.
static constexpr int first_league[8] = {0, 1, 2, 4, 5, 6, 7, 8};
static constexpr int league_count[8] = {1, 1, 2, 1, 1, 1, 1, 1};
// Expand the selected edition's groups. Only the German third divisions
// share bit 2; the English divisions each have their own calendar group.
// Stale descriptors beyond the active group count are ignored.
for (int bit = 0; bit < 5; ++bit) {
if (!((competitions >> bit) & 1u)) continue;
const int first = bit, last = bit < 4 ? bit + 1 : 8;
for (int k = first; k < last; ++k)
for (int league = first_league[k]; league < first_league[k] + league_count[k]; ++league)
for (int league = kGroupLeague[k]; league < kGroupLeague[k] + kGroupLeagues[k]; ++league)
active_leagues.push_back(league);
}
if (active_leagues.size() > 6)
@@ -560,6 +560,11 @@ CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_
session_id_ = next_session_id.fetch_add(1, std::memory_order_relaxed);
initialize_club_modal_runtime();
g_ = startup_state(exe_, db_, read_file(data / "M3.MEN"), read_file(data / "M3.DAT"));
if (const auto resource = content::find(data)) {
g_.display_start_year = resource->content->start_year;
content::set_display_start_year(data, g_.display_start_year);
exe_.set_display_start_year(g_.display_start_year);
}
g_.texts = &texts_;
g_.currency_suffix = exe_.cstring(::bmh::layout::CurrencySuffixText); // CurrencySuffixText
configure_training_camp_data(g_, exe_);
@@ -567,14 +572,18 @@ CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_
g_.credit_divisor = std::bit_cast<double>(uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField)) | uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField2)) << 32);
g_.credit_rate_table_available = true;
install_default_hooks();
if (content::find(data))
turn_driver_.desk_autosave = [this](const GameState &state, WatcomRandom &random) {
write_desk_autosave(state, random);
};
startup_players(g_, game_, rand_); // CareerFirstSteps2
MinuteReport report;
if (!new_career_before_dialog(g_, game_, rand_, report)) // InitializeCareer up to the dialog
throw std::runtime_error("career start: " + report.reason);
}
CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_seed,
const std::filesystem::path& save_path)
CareerSession::CareerSession(const std::filesystem::path &data, uint32_t watcom_seed,
const std::filesystem::path &save_path, bool importing_legacy)
: data_directory_(data), exe_(load_le(data / "BMH.exe")), db_(load_database(data / "M3D.MAN")),
texts_(load_textd(data / "TEXTD.BLK")), rand_(watcom_seed) {
install_league_sizes(exe_);
@@ -584,15 +593,62 @@ CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_
? TransferAllocatorContext::zero : TransferAllocatorContext::blocked;
session_id_ = next_session_id.fetch_add(1, std::memory_order_relaxed);
initialize_club_modal_runtime();
const Savegame file = load_savegame(save_path);
if (!file.checksum_ok || file.version != "V2.24") throw std::runtime_error("savegame: unsupported or damaged FBM");
const DbCounts counts{exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField), exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField3), exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField2), exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField4)};
const SaveState save(file.stream, counts);
g_ = GameState::from_save(save, counts);
bool original_english_save = false;
std::optional<content::SavedCareer> native;
if (const auto resource = content::find(data); resource && !importing_legacy) {
if (content::key(save_path.extension()) != ".obs")
throw FormatError("0.2 loads native OBS saves; use Add to migrate legacy games");
native = content::load_career(save_path, *resource->content);
g_ = std::move(native->state);
rand_ = native->random;
game_ = native->game;
} else {
const Savegame file = load_savegame(save_path);
original_english_save = file.version == "V2.20";
if (!file.checksum_ok ||
(file.version != "V2.24" && !(importing_legacy && kEnglishCompetitions && original_english_save)))
throw FormatError("savegame: unsupported or damaged FBM");
const DbCounts counts{exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField),
exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField3),
exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField2),
exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField4)};
const auto stream = original_english_save ? obw::normalize_english_save(file, counts) : file.stream;
const SaveState save(stream, counts);
const auto manager_count = save.data(::bmh::layout::ManagerCount)[0];
if (manager_count < 1 || manager_count > 4)
throw FormatError("Invalid legacy manager count");
if (importing_legacy) {
size_t english_blocks = 0;
for (const auto &[address, size] : kEnglishCompetitionBlocks)
for (const auto &block : save.extension())
if (block.address == address && block.bytes.size() == size)
++english_blocks;
if ((kEnglishCompetitions && english_blocks != std::size(kEnglishCompetitionBlocks)) ||
(!kEnglishCompetitions && english_blocks != 0))
throw FormatError(
"Spielstand und Mod-Ausgabe passen nicht zusammen oder englische Pokaldaten fehlen.");
}
g_ = GameState::from_save(save, counts);
if (importing_legacy && file.plain_header.size() >= 11) {
const std::string year(file.plain_header.begin() + 7, file.plain_header.begin() + 11);
if (std::all_of(year.begin(), year.end(), [](unsigned char c) { return std::isdigit(c); })) {
const int elapsed = ui::desk_date(g_.date, exe_).year - exe_.display_start_year();
const int origin = std::stoi(year) - elapsed;
if (origin >= 1900 && origin <= 9998)
g_.display_start_year = origin;
}
}
}
if (content::find(data)) {
content::set_display_start_year(data, g_.display_start_year);
exe_.set_display_start_year(g_.display_start_year);
}
// CompetitionPointers2, after DeskDate2: these are process statics, not FBM fields.
// Resuming within this month must not count it as a newly elapsed month.
g_.autosave_months = 0;
g_.autosave_month = month_code(g_.date);
if (!native) {
g_.autosave_months = 0;
g_.autosave_month = month_code(g_.date);
}
// Original CompetitionPointers2 calls CompetitionPointers after loading the stream. This
// rebinds pointer fields in the saved competition table before any resume
// path dereferences them (the serialized values may point into the old process).
@@ -604,10 +660,55 @@ CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_
g_.credit_divisor = std::bit_cast<double>(uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField)) | uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField2)) << 32);
g_.credit_rate_table_available = true;
install_default_hooks();
national_coach_after_load(g_); // (NationalCoachAfterLoad: a Bundestrainer takes the national team over again)
if (g_.memory.has(::bmh::layout::CareerSession_Save_RuntimeField)) game_.set_seed(int32_t(g_.memory.u32(::bmh::layout::CareerSession_Save_RuntimeField)));
restore_saved_turn_cursor(turn_driver_, g_, db_, session_id_, 1, saved_turn_error_);
capture_source_desk_callargs();
if (content::find(data))
turn_driver_.desk_autosave = [this](const GameState &state, WatcomRandom &random) {
write_desk_autosave(state, random);
};
if (!native)
national_coach_after_load(
g_); // (NationalCoachAfterLoad: a Bundestrainer takes the national team over again)
if (!native && g_.memory.has(::bmh::layout::CareerSession_Save_RuntimeField))
game_.set_seed(int32_t(g_.memory.u32(::bmh::layout::CareerSession_Save_RuntimeField)));
if (native) {
content::restore_driver(turn_driver_, native->driver);
restore_native_session_context(native->session);
turn_driver_.session_id = session_id_;
turn_driver_.revision = 1;
exe_.set_display_start_year(g_.display_start_year);
} else if (original_english_save &&
!g_.memory.u8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4)) {
// V2.20 never stored transient match descriptors. Like its original loader,
// rebuild the current groups without replaying daily/financial progression
// or shuffling the saved manager order.
const int day = g_.season_day();
if (day < 0 || day >= 365)
throw FormatError("V2.20 calendar day is invalid");
const auto entry = g_.memory.u16(::bmh::layout::CompetitionCalendar + uint32_t(day) * 2);
const auto competitions = g_.memory.u32(::bmh::layout::SavedCompetition);
std::vector<uint8_t> referees = db_.raw_referee_properties;
for (auto &referee : referees)
referee &= 0x7f;
MatchdayContext context;
context.month = month_code(g_.date);
context.season_day = day;
context.weekday = ui::desk_date(g_.date, exe_).weekday;
context.referees = &referees;
MinuteReport report;
auto groups = setup_matchday(g_, competitions, context, game_, rand_, report);
if (report.unsupported)
throw FormatError("V2.20 continuation: " + report.reason);
std::string error;
if (!begin_turn_driver(turn_driver_, g_, std::move(groups), entry, db_.raw_referee_properties,
session_id_, 1, error))
throw FormatError(error);
turn_driver_.referees = std::move(referees);
turn_driver_.loaded_matchday_resume = true;
} else
restore_saved_turn_cursor(turn_driver_, g_, db_, session_id_, 1, saved_turn_error_);
if (importing_legacy && !saved_turn_error_.empty())
throw FormatError(saved_turn_error_);
if (!native)
capture_source_desk_callargs();
}
int CareerSession::runtime_club(int master) const { return runtime_club(g_, master); }
@@ -4129,6 +4230,7 @@ bool CareerSession::finish(ui::CareerInitializationResult& result, std::string&
for (size_t m = 0; m < managers_.size(); ++m)
managers_[m].runtime_club = g_.manager_teams.at(m);
result.managers = managers_;
flush_native_autosave();
return true;
}
@@ -4335,6 +4437,7 @@ TurnAdvanceResult CareerSession::dispatch_kickoff(const ui::DeskRequest& request
return id < names.size() ? names[id] : std::string();
}, exe_, g_);
}
flush_native_autosave();
return result;
}
@@ -4800,7 +4903,10 @@ bool CareerSession::apply_settings_file(const ui::SaveLoadRequest& request,int m
std::string extension=request.path.extension().string();
std::transform(extension.begin(),extension.end(),extension.begin(),
[](unsigned char c){return char(std::tolower(c));});
if(extension!=".ein") {error="invalid_settings_file_extension";return false;}
if (extension != (content::find(data_directory_) ? ".obsettings" : ".ein")) {
error = "invalid_settings_file_extension";
return false;
}
const uint32_t base=::bmh::layout::LeaguePresentationOptions;
if(!staged.memory.has(base+uint32_t(kBytes-1))) {error="settings_file_memory_unavailable";return false;}
std::error_code ec;
@@ -4808,7 +4914,14 @@ bool CareerSession::apply_settings_file(const ui::SaveLoadRequest& request,int m
if(!ec&&std::filesystem::is_symlink(status)) {error="settings_file_target_is_symlink";return false;}
if(request.action==ui::SaveLoadAction::load) {
Bytes bytes;
try {bytes=read_file(request.path);}catch(const std::exception&) {error="settings_file_read_failed";return false;}
try {
bytes = content::find(data_directory_)
? content::load_preferences(request.path, "settings", kBytes)
: read_file(request.path);
} catch (const std::exception &) {
error = "settings_file_read_failed";
return false;
}
if(bytes.size()!=kBytes) {error="settings_file_wrong_size";return false;}
for(size_t i=0;i<kBytes;++i)staged.memory.set8(base+uint32_t(i),bytes[i]);
std::array<uint8_t,kBytes> raw{};
@@ -4831,6 +4944,11 @@ bool CareerSession::apply_settings_file(const ui::SaveLoadRequest& request,int m
Bytes bytes(kBytes);
for(size_t i=0;i<kBytes;++i)bytes[i]=staged.memory.u8(base+uint32_t(i));
try {
if (content::find(data_directory_)) {
content::save_preferences(request.path, "settings", bytes, request.overwrite);
error.clear();
return true;
}
std::ofstream file(request.path,std::ios::binary|std::ios::trunc);
if(!file) {error="settings_file_write_failed";return false;}
file.write(reinterpret_cast<const char*>(bytes.data()),std::streamsize(bytes.size()));file.flush();
@@ -7522,6 +7640,11 @@ std::string CareerSession::take_autosave_error() {
}
void CareerSession::write_desk_autosave(const GameState& state, WatcomRandom& random) {
// OpenBMH deviates from the original: native saves do not consume gameplay randomness for encryption.
if (content::find(data_directory_)) {
native_autosave_pending_ = bool(autosave_directory_);
return;
}
std::filesystem::path temporary;
try {
if (!autosave_directory_ || !std::filesystem::is_directory(*autosave_directory_))
@@ -7556,6 +7679,83 @@ void CareerSession::write_desk_autosave(const GameState& state, WatcomRandom& ra
}
}
cli::Json CareerSession::native_session_context() const {
cli::Json::Array runtime, callargs, managers;
for (const auto &[address, value] : club_modal_runtime_)
runtime.emplace_back(cli::Json::Object{{"address", int64_t(address)}, {"value", int(value)}});
for (const auto &args : source_desk_callargs_)
callargs.emplace_back(cli::Json::Array{args.competition, args.opponent});
for (const auto &manager : managers_)
managers.emplace_back(cli::Json::Array{manager.slot, manager.master_club, manager.runtime_club});
return cli::Json::Object{{"schema", "classic-session@1.0"},
{"runtime", std::move(runtime)},
{"desk_callargs", std::move(callargs)},
{"managers", std::move(managers)}};
}
void CareerSession::restore_native_session_context(const cli::Json &root) {
const auto field = [&](const char *name) -> const cli::Json & {
if (!root.object() || !root.object()->contains(name))
throw FormatError("Native session field missing");
return root.object()->at(name);
};
if (!field("schema").string() || *field("schema").string() != "classic-session@1.0")
throw FormatError("Unsupported native session");
const auto array = [](const cli::Json &j, size_t maximum) -> const cli::Json::Array & {
if (!j.array() || j.array()->size() > maximum)
throw FormatError("Invalid native session array");
return *j.array();
};
const auto integer = [](const cli::Json &j, int64_t low, int64_t high) -> int64_t {
if (!j.integer() || *j.integer() < low || *j.integer() > high)
throw FormatError("Invalid native session integer");
return *j.integer();
};
std::map<uint32_t, uint8_t> runtime;
for (const auto &row : array(field("runtime"), 8192)) {
if (!row.object() || !row.object()->contains("address") || !row.object()->contains("value"))
throw FormatError("Invalid runtime byte");
const auto at = uint32_t(integer(row.object()->at("address"), 0, UINT32_MAX));
if (!club_modal_runtime_.contains(at) ||
!runtime.emplace(at, uint8_t(integer(row.object()->at("value"), 0, 255))).second)
throw FormatError("Unknown or duplicated runtime byte");
}
if (runtime.size() != club_modal_runtime_.size())
throw FormatError("Incomplete native runtime bytes");
std::vector<ui::DeskMatchCallargs> callargs;
for (const auto &row : array(field("desk_callargs"), 4)) {
const auto &fields = array(row, 2);
if (fields.size() != 2)
throw FormatError("Invalid desk arguments");
callargs.push_back({int(integer(fields[0], -1, 255)), int(integer(fields[1], -1, 4095))});
}
std::vector<ui::InitializedManager> managers;
for (const auto &row : array(field("managers"), 4)) {
const auto &fields = array(row, 3);
if (fields.size() != 3)
throw FormatError("Invalid manager mapping");
managers.push_back({int(integer(fields[0], 0, 3)), int(integer(fields[1], 0, 4095)),
int(integer(fields[2], 0, 4095))});
}
club_modal_runtime_ = std::move(runtime);
source_desk_callargs_ = std::move(callargs);
managers_ = std::move(managers);
}
void CareerSession::flush_native_autosave() {
if (!std::exchange(native_autosave_pending_, false))
return;
try {
if (!autosave_directory_ || !std::filesystem::is_directory(*autosave_directory_))
throw FormatError("Autosave directory unavailable");
const auto resource = content::find(data_directory_);
if (!resource)
throw FormatError("Native content unavailable");
content::save_career(*autosave_directory_ / "AUTOSAVE.obs", *resource->content, g_, rand_, game_,
turn_driver_, true, native_session_context());
} catch (const std::exception &e) {
autosave_error_ = e.what();
}
}
bool CareerSession::save_game(const std::filesystem::path& path, int manager_slot, bool overwrite, std::string& error) {
if (advertising_renewal_dispatch_active_) { error="save_blocked_during_advertising_renewal"; return false; }
if(balance_draft_||balance_dispatch_active_||strengths_owner_||strengths_dispatch_active_||
@@ -7569,7 +7769,7 @@ bool CareerSession::save_game(const std::filesystem::path& path, int manager_slo
std::string extension = path.extension().string();
std::transform(extension.begin(), extension.end(), extension.begin(), [](unsigned char c) { return char(std::tolower(c)); });
if (manager_slot != active || manager_slot < 0 || size_t(manager_slot) >= g_.manager_teams.size() ||
extension != ".fbm" || path.filename().empty()) {
extension != (content::find(data_directory_) ? ".obs" : ".fbm") || path.filename().empty()) {
error = "invalid_save_request"; return false;
}
std::error_code ec;
@@ -7582,6 +7782,11 @@ bool CareerSession::save_game(const std::filesystem::path& path, int manager_slo
const bool exists = std::filesystem::exists(path, ec);
if (ec || (exists && !overwrite)) { error = exists ? "overwrite_confirmation_required" : "save_target_unavailable"; return false; }
try {
if (const auto resource = content::find(data_directory_)) {
content::save_career(path, *resource->content, g_, rand_, game_, turn_driver_, overwrite,
native_session_context());
return true;
}
WatcomRandom staged_rand = rand_;
const Savegame save = make_savegame(g_, staged_rand);
write_savegame(path, save);
@@ -7623,7 +7828,10 @@ bool CareerSession::dispatch_menu_layout(const ui::SaveLoadRequest& request, uin
std::string extension = request.path.extension().string();
std::transform(extension.begin(), extension.end(), extension.begin(),
[](unsigned char c) { return char(std::tolower(c)); });
if (extension != ".men") { error = "invalid_menu_layout_extension"; return false; }
if (extension != (content::find(data_directory_) ? ".oblayout" : ".men")) {
error = "invalid_menu_layout_extension";
return false;
}
const size_t active_base = size_t(request.manager_slot) * 0xb0c;
if (active_base + 0xb0c > g_.manager_records.size() ||
size_t(request.manager_slot) >= g_.manager_teams.size() ||
@@ -7668,8 +7876,14 @@ bool CareerSession::dispatch_menu_layout(const ui::SaveLoadRequest& request, uin
if (request.action == ui::SaveLoadAction::load) {
Bytes payload;
try { payload = read_file(request.path); }
catch (const std::exception&) { error = "menu_layout_read_failed"; return false; }
try {
payload = content::find(data_directory_)
? content::load_preferences(request.path, "layout", kLayoutBytes)
: read_file(request.path);
} catch (const std::exception &) {
error = "menu_layout_read_failed";
return false;
}
if (!validate_payload(payload)) return false;
GameState staged = g_;
for (size_t i = 0; i < kLayoutBytes; ++i)
@@ -7704,6 +7918,12 @@ bool CareerSession::dispatch_menu_layout(const ui::SaveLoadRequest& request, uin
for (size_t i = 0; i < kLayoutBytes; ++i) payload[i] = g_.memory.u8(base + uint32_t(i));
if (!validate_payload(payload)) return false;
try {
if (content::find(data_directory_)) {
content::save_preferences(request.path, "layout", payload, request.overwrite);
++revision;
error.clear();
return true;
}
std::ofstream file(request.path, std::ios::binary | std::ios::trunc);
if (!file) { error = "menu_layout_write_failed"; return false; }
file.write(reinterpret_cast<const char*>(payload.data()), std::streamsize(payload.size()));
+6 -1
View File
@@ -808,7 +808,8 @@ public:
bool dispatch_menu_layout(const ui::SaveLoadRequest&, uint64_t& revision, std::string& error);
// Load an existing V2.24 save without applying new-career options or startup RNG.
CareerSession(const std::filesystem::path& data, uint32_t watcom_seed, const std::filesystem::path& save_path);
CareerSession(const std::filesystem::path &data, uint32_t watcom_seed,
const std::filesystem::path &save_path, bool importing_legacy = false);
const GameState& state() const { return g_; }
GameState& state() { return g_; }
@@ -883,6 +884,10 @@ private:
std::optional<std::filesystem::path> autosave_directory_;
std::string autosave_error_;
void write_desk_autosave(const GameState&, WatcomRandom&);
bool native_autosave_pending_ = false;
void flush_native_autosave();
cli::Json native_session_context() const;
void restore_native_session_context(const cli::Json &);
bool live_source_identity(const ui::StrengthsIdentity&) const;
bool validate_desk_setting_owner(const DeskSettingIdentity&, uint64_t revision, std::string& error,
bool require_desk_phase = true) const;
+11 -6
View File
@@ -1,4 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/executable_layout.hpp"
#include "app/controller.hpp"
#include "app/window_actions.hpp"
@@ -351,8 +352,8 @@ void start_original_desk_audio(openbmh::audio::Playback& playback, const GameSta
original_audio_command(playback, 1); // SavePathInDirectory / CareerFirstSteps2, resume the same song.
}
bool save_path_in_directory(const fs::path& path, const fs::path& directory,
std::string_view expected_extension = ".fbm") {
bool save_path_in_directory(const fs::path &path, const fs::path &directory,
std::string_view expected_extension) {
if (path.filename().empty()) return false;
std::string ext = path.extension().string();
std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return char(std::tolower(c)); });
@@ -979,7 +980,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu
page.highscore.rows={};
if(page.highscore.ranked) {
auto texts=load_textd(ui::asset_path(data,"TEXTD.BLK"));
const auto file=highscore_file(save_directory,page.highscore.signature,texts.strings.at(889));
const auto file = highscore_file(save_directory, page.highscore.signature,
texts.strings.at(889), bool(content::find(data)));
HighscoreTable rows{};
if(fs::exists(file))rows=load_highscore_table(file);
page.highscore=make_highscore_projection(game,std::move(rows),HighscoreContext::ActiveManager);
@@ -1876,7 +1878,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu
result.settings_owner_sequence == flow.settings_owner_sequence() &&
request.origin_item_id == desk_owner.item_id && request.manager_slot == desk_owner.manager_slot;
if (!session || !same_pending || request.revision != revision ||
!save_path_in_directory(request.path, save_directory, ".ein")) {
!save_path_in_directory(request.path, save_directory,
content::find(data) ? ".obsettings" : ".ein")) {
flow.reject_settings_file("stale_request_or_invalid_settings_path");
return {};
}
@@ -1907,7 +1910,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu
return {};
}
if (request.revision != revision ||
!save_path_in_directory(request.path, save_directory, ".men")) {
!save_path_in_directory(request.path, save_directory,
content::find(data) ? ".oblayout" : ".men")) {
flow.reject_file_action("stale_request_or_invalid_menu_layout_path");
return {};
}
@@ -1925,7 +1929,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu
}
} else if (result.request == ui::FlowRequest::file_action) {
const auto& request = result.file_action;
if (request.revision != revision || !save_path_in_directory(request.path, save_directory)) {
if (request.revision != revision ||
!save_path_in_directory(request.path, save_directory, content::find(data) ? ".obs" : ".fbm")) {
flow.reject_file_action("stale_request_or_invalid_save_path");
return {};
}
+57 -35
View File
@@ -1,4 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/executable_layout.hpp"
#include "ui/live_timing.hpp"
// openbmh_play - the UI of src/ui connected to the engine: options, manager dialogs, a new
@@ -29,6 +30,8 @@
#include "launch/archive.hpp"
#include "launch/file_dialog.hpp"
#include "launch/game_data.hpp"
#include "launch/launcher.hpp"
#include "content/package.hpp"
#include "version.hpp"
#include "app/live_matchday_events.hpp"
#include "audio/playback.hpp"
@@ -131,7 +134,7 @@ int main(int argc, char** argv) {
} else if (is("--live-frame-ms") && value) {
live_frame_ms = std::clamp(std::atoi(args[++i].c_str()), 0, 1000);
live_frame_ms_explicit = true;
} else if (is("--data") && value) {
} else if ((is("--run-mod") || is("--mod") || is("--data")) && value) {
data = launch::path_from_utf8(args[++i]);
} else if (is("--seed") && value) {
seed = uint32_t(std::strtoul(args[++i].c_str(), nullptr, 0));
@@ -143,51 +146,69 @@ int main(int argc, char** argv) {
std::printf("OpenBMH %s\n", bmh::kOpenBmhVersion);
return 0;
} else if (is("--help") || is("-h")) {
std::printf("usage: openbmh_play [<game directory | BMH.EXE | game.zip | game.7z>] [--seed <Watcom seed>] "
"[--save-directory <directory>] [--mute] [--volume <0..1>] [--no-music] [--live-frame-ms <0..1000>]\n");
std::printf("usage: OpenBMH [--mod <mods/name/content.obw>] [--seed <Watcom seed>] "
"[--save-directory <directory>] [--mute] [--volume <0..1>] [--no-music] "
"[--live-frame-ms <0..1000>]\n");
return 0;
} else if (args[i].rfind("--", 0) != 0 && data.empty()) {
data = launch::path_from_utf8(args[i]);
} else {
show_start_error("Unknown option or missing argument: " + args[i]);
return 1;
}
}
// the game: as given (directory, EXE or archive); else the directory OpenBMH itself lies in,
// when it holds a playable game (the simplest install: openbmh next to BMH.EXE); else
// chosen in the file dialog
if (data.empty()) {
if (char* base = SDL_GetBasePath()) {
const fs::path here = launch::path_from_utf8(base);
SDL_free(base);
try {
const launch::ResolvedGame game = launch::resolve_game(here, launch::default_cache_directory());
if (game.error.empty() && game.check.playable) data = here;
} catch (const std::exception&) {
// (not a game directory: fall through to the file dialog)
}
}
}
std::filesystem::path executable;
if (char *base = SDL_GetBasePath()) {
executable = launch::path_from_utf8(base);
SDL_free(base);
#ifdef _WIN32
executable /= "OpenBMH.exe";
#else
executable /= "OpenBMH";
#endif
} else
executable = fs::absolute(launch::path_from_utf8(args.front()));
if (data.empty()) {
try {
const auto chosen = launch::choose_game_file("OpenBMH");
if (!chosen) return 0; // cancelled
data = *chosen;
} catch (const std::exception& e) {
show_start_error(std::string(e.what()) +
"\nStart OpenBMH with the game as argument: openbmh_play <game directory | BMH.EXE | game.zip>");
return launch::run_launcher(executable, [](const fs::path &package, const fs::path &source,
const fs::path &destination) {
const auto content = content::open(package);
content::Mount mount(package, content);
const auto source_bytes = read_file(source);
const auto digest = content::sha256(std::string(source_bytes.begin(), source_bytes.end()));
const auto seed = uint32_t(std::stoul(digest.substr(0, 8), nullptr, 16));
app::CareerSession migrated(mount.root(), seed, source, true);
std::string error;
if (!migrated.save_game(destination, migrated.state().memory.u8(::bmh::layout::ActiveManager),
false, error))
throw FormatError("Spielstand konnte nicht übernommen werden: " + error);
});
} catch (const std::exception &e) {
show_start_error(e.what());
return 1;
}
}
bool english_game = false; // (the window title marks the English version as experimental)
{
const launch::ResolvedGame game = launch::resolve_game(data, launch::default_cache_directory());
if (!game.error.empty() || !game.check.playable) {
show_start_error("The game cannot be started:\n" + launch::describe(game));
return 1;
std::shared_ptr<const content::Classic> contents;
std::unique_ptr<content::Mount> mount;
bool english_game = false;
try {
if (fs::is_directory(data))
data /= "content.obw";
contents = content::open(data);
mount = std::make_unique<content::Mount>(data, contents);
data = mount->root();
english_game = contents->english;
if (save_directory.empty()) {
const auto root = executable.parent_path();
launch::ModLibrary library(root);
launch::ModEntry mod;
mod.content_id = contents->content_id;
save_directory = library.user_directory(mod);
}
english_game = game.check.family == launch::GameFamily::english;
// (from an archive: its unpacked copy in the cache, which then also keeps the saves)
data = game.check.directory;
} catch (const std::exception &e) {
show_start_error(e.what());
return 1;
}
if (save_directory.empty()) save_directory = data;
try {
const Palette palette = load_palette(ui::asset_path(data, "M3PC.COL"));
ui::StartupFlow flow(data, save_directory);
@@ -1676,7 +1697,8 @@ int main(int argc, char** argv) {
wait_season_ack();
}
} else {
const auto file = highscore_file(save_directory, signature, season_texts[889]);
const auto file =
highscore_file(save_directory, signature, season_texts[889], bool(content::find(data)));
auto scores = make_highscore_projection(state, load_highscore_table(file), HighscoreContext::SeasonBoundary);
// The Original stores this table outside the native FBM. Use the
// configured writable save base rather than a working-directory path.
+3 -1
View File
@@ -1,4 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/executable_layout.hpp"
// Information windows of docs/CLI_CONCEPT/05-information.md that the engine can already
// project: TeamInfo (club information, from LeagueTable / Fixtures), HighScore (menu 26) and
@@ -186,7 +187,8 @@ void Console::register_info_commands() {
const uint16_t signature = g.memory.has(::bmh::layout::CareerSession_FormatError_RuntimeField7) ? g.memory.u16(::bmh::layout::CareerSession_FormatError_RuntimeField7) : 0;
if (signature != 0) {
// the ranked list of this game's level, stored next to the saved games
const auto file = highscore_file(save_directory(), signature, texts_.strings.at(kHighscorePrefix));
const auto file = highscore_file(save_directory(), signature, texts_.strings.at(kHighscorePrefix),
bool(content::find(options_.data)));
HighscoreTable rows{};
std::error_code ec;
if (std::filesystem::exists(file, ec)) rows = load_highscore_table(file);
+7 -3
View File
@@ -5,6 +5,7 @@
#include <algorithm>
#include "formats/content.hpp"
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
#include "ui/cup_draw.hpp"
@@ -396,7 +397,8 @@ std::filesystem::path Console::browser_file(const std::string& name) const {
if (name == "." || name == ".." || name.find_first_of("/\\:") != std::string::npos)
fail("E_BAD_ARGUMENT", "not a file name: " + name + " (no directories; use ChangeDirectory)");
std::filesystem::path path = browse_directory_ / name;
if (!path.has_extension()) path += ".FBM";
if (!path.has_extension())
path += content::find(options_.data) ? ".obs" : ".FBM";
return path;
}
@@ -410,7 +412,8 @@ void Console::register_file_commands() {
std::error_code ec;
for (const auto& entry : std::filesystem::directory_iterator(browse_directory_, ec)) {
if (entry.is_directory(ec)) dirs.push_back({entry.path().filename().string(), "dir"});
else if (entry.is_regular_file(ec) && lower(entry.path().extension().string()) == ".fbm")
else if (entry.is_regular_file(ec) && lower(entry.path().extension().string()) ==
(content::find(options_.data) ? ".obs" : ".fbm"))
files.push_back({entry.path().stem().string(), "file"});
}
if (ec) fail("E_IO", "cannot read the directory " + shown_directory());
@@ -463,7 +466,8 @@ void Console::register_file_commands() {
void Console::load_game(const std::filesystem::path& requested) {
std::filesystem::path path = requested;
if (!path.has_extension()) path += ".FBM";
if (!path.has_extension())
path += content::find(options_.data) ? ".obs" : ".FBM";
std::error_code ec;
if (!std::filesystem::is_regular_file(path, ec)) fail("E_IO", "file not found: " + path.filename().string());
std::unique_ptr<app::CareerSession> loaded;
+64 -23
View File
@@ -32,6 +32,9 @@
#include "launch/archive.hpp"
#include "launch/game_data.hpp"
#include "content/package.hpp"
#include "launch/process.hpp"
#include "launch/mods.hpp"
#include "version.hpp"
namespace {
@@ -83,7 +86,8 @@ Arguments parse_args(int argc, char** argv) {
std::exit(0);
}
if (arg == "--help" || arg == "-h") args.help = true;
else if (arg == "--data") args.data = bmh::launch::path_from_utf8(next(arg));
else if (arg == "--data" || arg == "--mod")
args.data = bmh::launch::path_from_utf8(next(arg));
else if (arg == "--seed") { args.seed = parse_seed(next(arg)); args.seed_set = true; }
else if (arg == "--text") args.json = false;
else if (arg == "--json") args.json = true;
@@ -116,21 +120,26 @@ Arguments parse_args(int argc, char** argv) {
}
void print_usage() {
std::cout << "openbmh_cli --data <BMH directory> [--seed <n>] [--text|--json] [--log <jsonl>]\n"
"openbmh_cli --replay <jsonl> [--data <BMH directory>] [--text|--json]\n"
"openbmh_cli --console --data <BMH directory> [--saves <dir>] [--seed <n>] [--text|--json] [--echo]\n"
" [--log|--replay <jsonl> [--keep-going]] [--serve <dir> | --listen <port>] [--seats N]\n"
" --listen: the console on 127.0.0.1:<port>, line protocol (SEAT k with --seats; a block ends\n"
" with go., the answer with a line \".\"); --json gives structured lines, State(view) projections.\n"
" --seats N: one mailbox <dir>/seat<k> per manager; a request \"WaitTurn\" waits for k's turn.\n"
" --resume <jsonl>: with --seats, first play an earlier session log again, then go on.\n"
"openbmh_cli --send <dir> [--timeout <seconds>] (the block on stdin)\n"
" --serve: the session answers blocks dropped into <dir> (request-N.txt -> response-N.txt);\n"
" --send hands one block to it and prints the answer - for agents that work in steps.\n"
" console language (docs/CLI_CONCEPT): command lines, executed by a line \"go.\";\n"
" ListOptions shows what is possible, Help the reference, Quit ends.\n"
"Commands: help, new, load, save, status, desk, kickoff, camp.*, bank.*, stadium.*, toto.submit, quit\n"
"Text: new <master_club> <manager_name> [strength], load/save <path>, kickoff, status, desk, quit\n";
std::cout
<< "openbmh_cli --mod <content.obw> [--seed <n>] [--text|--json] [--log <jsonl>]\n"
"openbmh_cli --replay <jsonl> [--mod <content.obw>] [--text|--json]\n"
"openbmh_cli --console --mod <content.obw> [--saves <dir>] [--seed <n>] [--text|--json] [--echo]\n"
" [--log|--replay <jsonl> [--keep-going]] [--serve <dir> | --listen <port>] [--seats "
"N]\n"
" --listen: the console on 127.0.0.1:<port>, line protocol (SEAT k with --seats; a block ends\n"
" with go., the answer with a line \".\"); --json gives structured lines, State(view) "
"projections.\n"
" --seats N: one mailbox <dir>/seat<k> per manager; a request \"WaitTurn\" waits for k's turn.\n"
" --resume <jsonl>: with --seats, first play an earlier session log again, then go on.\n"
"openbmh_cli --send <dir> [--timeout <seconds>] (the block on stdin)\n"
" --serve: the session answers blocks dropped into <dir> (request-N.txt -> response-N.txt);\n"
" --send hands one block to it and prints the answer - for agents that work in steps.\n"
" console language (docs/CLI_CONCEPT): command lines, executed by a line \"go.\";\n"
" ListOptions shows what is possible, Help the reference, Quit ends.\n"
"Commands: help, new, load, save, status, desk, kickoff, camp.*, bank.*, stadium.*, toto.submit, "
"quit\n"
"Text: new <master_club> <manager_name> [strength], load/save <path>, kickoff, status, desk, "
"quit\n";
}
std::string command_line_response(const Json& response) {
@@ -710,14 +719,46 @@ int main(int argc, char** argv) {
Arguments args = parse_args(argc, argv);
if (args.help) { print_usage(); return 0; }
if (!args.send.empty()) return run_send(args);
// --data may also name BMH.EXE or a ZIP/7z archive with one game (src/launch); an
// archive is unpacked into the per-user cache and its copy is used
if (!args.data.empty()) {
const auto game = bmh::launch::resolve_game(args.data, bmh::launch::default_cache_directory());
if (!game.error.empty() || !game.check.playable)
throw std::runtime_error("the game cannot be used:\n" + bmh::launch::describe(game));
args.data = game.check.directory;
// Replay and resumed sessions can supply their content/save paths in
// the log header. Resolve them before mounting or selecting defaults.
const auto &source_log = !args.replay.empty() ? args.replay : args.resume;
if (!source_log.empty()) {
std::ifstream input(source_log, std::ios::binary);
std::string line;
if (!input || !std::getline(input, line))
throw std::runtime_error("cannot_read_session_log_header");
const auto header = parse_json(line);
const auto *fields = header.object();
if (!fields || !fields->contains("type") || !fields->at("type").string() ||
*fields->at("type").string() != (args.console ? "openbmh_console_log" : "openbmh_cli_log"))
throw std::runtime_error("invalid_session_log_header");
if (args.data.empty()) {
if (!fields->contains("data") || !fields->at("data").string())
throw std::runtime_error("missing_session_content_path");
args.data = bmh::launch::path_from_utf8(*fields->at("data").string());
}
if (args.console && args.saves.empty() && fields->contains("saves") &&
fields->at("saves").string())
args.saves = bmh::launch::path_from_utf8(*fields->at("saves").string());
}
std::shared_ptr<const bmh::content::Classic> contents;
std::unique_ptr<bmh::content::Mount> mount;
if (!args.data.empty()) {
if (std::filesystem::is_directory(args.data))
args.data /= "content.obw";
contents = bmh::content::open(args.data);
mount = std::make_unique<bmh::content::Mount>(args.data, contents);
args.data = mount->root();
if (args.saves.empty()) {
bmh::launch::ModLibrary library(
bmh::launch::executable_path(bmh::launch::path_from_utf8(argv[0])).parent_path());
bmh::launch::ModEntry mod;
mod.content_id = contents->content_id;
args.saves = library.user_directory(mod);
}
} else
throw std::runtime_error(
"0.2 requires --mod <content.obw>; import installations in OpenBMH first");
if (args.console) {
if (!args.log.empty() && !args.replay.empty()) throw std::runtime_error("--log and --replay cannot be combined");
if (args.listen_port) return run_console_listen(args);
+63
View File
@@ -0,0 +1,63 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "content/digest.hpp"
#include <array>
#include <bit>
#include <cstdint>
#include <vector>
namespace bmh::content {
std::string sha256(std::string_view input) {
constexpr std::array<uint32_t, 64> k{
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
std::array<uint32_t, 8> h{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
std::vector<uint8_t> data(input.begin(), input.end());
const uint64_t bits = uint64_t(data.size()) * 8;
data.push_back(0x80);
while (data.size() % 64 != 56)
data.push_back(0);
for (int i = 7; i >= 0; --i)
data.push_back(uint8_t(bits >> (8 * i)));
for (size_t offset = 0; offset < data.size(); offset += 64) {
std::array<uint32_t, 64> w{};
for (size_t i = 0; i < 16; ++i)
for (size_t j = 0; j < 4; ++j)
w[i] = (w[i] << 8) | data[offset + 4 * i + j];
for (size_t i = 16; i < 64; ++i) {
const auto a = w[i - 15], b = w[i - 2];
w[i] = w[i - 16] + (std::rotr(a, 7) ^ std::rotr(a, 18) ^ (a >> 3)) + w[i - 7] +
(std::rotr(b, 17) ^ std::rotr(b, 19) ^ (b >> 10));
}
auto [a, b, c, d, e, f, g, v] = h;
for (size_t i = 0; i < 64; ++i) {
const auto t = v + (std::rotr(e, 6) ^ std::rotr(e, 11) ^ std::rotr(e, 25)) +
((e & f) ^ (~e & g)) + k[i] + w[i];
const auto u =
(std::rotr(a, 2) ^ std::rotr(a, 13) ^ std::rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c));
v = g;
g = f;
f = e;
e = d + t;
d = c;
c = b;
b = a;
a = t + u;
}
const std::array<uint32_t, 8> work{a, b, c, d, e, f, g, v};
for (size_t i = 0; i < 8; ++i)
h[i] += work[i];
}
constexpr char digits[] = "0123456789abcdef";
std::string result;
for (auto word : h)
for (int i = 7; i >= 0; --i)
result += digits[(word >> (4 * i)) & 15];
return result;
}
} // namespace bmh::content
+7
View File
@@ -0,0 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <string>
#include <string_view>
namespace bmh::content {
std::string sha256(std::string_view data);
}
+134
View File
@@ -0,0 +1,134 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "content/package.hpp"
#include "import/detail.hpp"
#include "formats/executable_layout.hpp"
#include <chrono>
#include <fstream>
namespace bmh::content {
namespace fs = std::filesystem;
using namespace obw::detail;
namespace {
constexpr const char *inventory = "x-classic/seal.json";
O hashes(const Documents &docs) {
O result;
for (const auto &[name, value] : docs)
if (name != inventory) {
if (!safe_path(name))
fail("invalid content entry");
result[name] = sha256(value);
}
return result;
}
std::string identity(const Documents &docs) {
auto entries = hashes(docs);
entries.erase("x-classic/inventory.json");
auto manifest = parse(docs, "manifest.json");
manifest.object()->erase("generator");
manifest.object()->erase("title");
entries["manifest.json"] = sha256(cli::dump_json(manifest));
return sha256(cli::dump_json(entries));
}
} // namespace
Documents read_archive(const fs::path &file) {
if (fs::is_symlink(fs::symlink_status(file)) || !fs::is_regular_file(file) ||
fs::file_size(file) > 128ull * 1024 * 1024)
fail("invalid native archive");
// The archive itself remains a real file when its path is a mounted asset root.
std::ifstream stream(file, std::ios::binary);
std::string input(size_t(fs::file_size(file)), '\0');
if (!stream.read(input.data(), std::streamsize(input.size())))
fail("cannot read native archive");
mz_zip_archive zip{};
if (!mz_zip_reader_init_mem(&zip, input.data(), input.size(), 0))
fail("invalid ZIP archive");
struct End {
mz_zip_archive *zip;
~End() { mz_zip_reader_end(zip); }
} end{&zip};
Documents out;
uint64_t total = 0;
const auto count = mz_zip_reader_get_num_files(&zip);
if (count > 8192)
fail("too many archive entries");
for (mz_uint i = 0; i < count; ++i) {
mz_zip_archive_file_stat stat{};
if (!mz_zip_reader_file_stat(&zip, i, &stat))
fail("cannot read entry metadata");
if (stat.m_is_directory)
continue;
const std::string name = stat.m_filename;
if (!safe_path(name) || stat.m_uncomp_size > 32ull * 1024 * 1024 ||
(total += stat.m_uncomp_size) > 128ull * 1024 * 1024)
fail("unsafe or oversized archive entry");
std::string value(size_t(stat.m_uncomp_size), '\0');
if (!mz_zip_reader_extract_to_mem(&zip, i, value.data(), value.size(), 0))
fail("damaged ZIP entry");
if (!out.emplace(name, std::move(value)).second)
fail("duplicate archive entry");
}
return out;
}
void write_archive(const Documents &out, const fs::path &file, bool overwrite) {
mz_zip_archive zip{};
if (!mz_zip_writer_init_heap(&zip, 0, 0))
fail("cannot initialize ZIP writer");
struct End {
mz_zip_archive *zip;
~End() { mz_zip_writer_end(zip); }
} end{&zip};
uint64_t total = 0;
if (out.size() > 8192)
fail("too many archive entries");
for (const auto &[name, data] : out) {
if (!safe_path(name) || data.size() > 32ull * 1024 * 1024 ||
(total += data.size()) > 128ull * 1024 * 1024)
fail("invalid archive size or path");
if (!mz_zip_writer_add_mem(&zip, name.c_str(), data.data(), data.size(), MZ_BEST_SPEED))
fail("cannot add ZIP entry");
}
void *buffer = nullptr;
size_t size = 0;
if (!mz_zip_writer_finalize_heap_archive(&zip, &buffer, &size))
fail("cannot finalize ZIP archive");
struct Free {
void *data;
~Free() { mz_free(data); }
} free{buffer};
write_atomic(file, std::string_view(static_cast<const char *>(buffer), size), overwrite);
}
std::string seal(Documents &docs) {
obw::validate(docs);
auto entries = hashes(docs);
const auto id = identity(docs);
put(docs, inventory,
O{{"schema", "classic-seal@1.0"}, {"content_id", id}, {"entries", std::move(entries)}});
return id;
}
std::string verify(const Documents &docs) {
const auto stored = parse(docs, inventory);
if (str(get(stored, "schema")) != "classic-seal@1.0")
fail("unsupported Classic seal");
const auto actual = hashes(docs);
const auto encoded = cli::dump_json(actual);
if (cli::dump_json(get(stored, "entries")) != encoded || str(get(stored, "content_id")) != identity(docs))
fail("Classic contents were changed; import the installation again");
return identity(docs);
}
std::shared_ptr<const Classic> open(const fs::path &path) {
auto docs = read_archive(path);
const auto id = verify(docs);
auto value = std::make_shared<Classic>(obw::load_classic(docs));
constexpr std::array<uint8_t, 9> german{18, 18, 18, 18, 18, 12, 12, 12, 12};
constexpr std::array<uint8_t, 9> english{20, 20, 20, 20, 10, 12, 12, 12, 12};
const auto &leagues = value->english ? english : german;
for (size_t i = 0; i < leagues.size(); ++i)
if (value->executable.u8(layout::LeagueSizes + uint32_t(i)) != leagues[i])
fail("Classic supports only the original BMH and Football Limited league structures");
value->content_id = id;
const auto manifest = parse(docs, "manifest.json");
value->start_year = std::stoi(str(get(manifest, "start_date")).substr(0, 4));
value->executable.set_display_start_year(value->start_year);
value->documents = std::move(docs);
return value;
}
} // namespace bmh::content
+15
View File
@@ -0,0 +1,15 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "import/classic.hpp"
#include "content/digest.hpp"
#include "formats/native_file.hpp"
namespace bmh::content {
using Documents = obw::Documents;
// Generic bounded ZIP documents; format-specific validation belongs to its reader.
Documents read_archive(const std::filesystem::path &file);
void write_archive(const Documents &, const std::filesystem::path &, bool overwrite = false);
// Sealed Classic contents: hashes cover every entry, including the original importer inventory.
std::string seal(Documents &);
std::string verify(const Documents &);
std::shared_ptr<const Classic> open(const std::filesystem::path &);
} // namespace bmh::content
+263
View File
@@ -0,0 +1,263 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "content/save.hpp"
#include "import/detail.hpp"
#include "game/save.hpp"
#include <limits>
#include <algorithm>
#include <bit>
namespace bmh::content {
using namespace obw::detail;
namespace {
J rng(uint32_t seed, uint64_t calls) { return O{{"seed", int64_t(seed)}, {"calls", std::to_string(calls)}}; }
uint64_t calls(const J &value) {
const auto s = str(get(value, "calls"));
size_t end = 0;
uint64_t n;
try {
n = std::stoull(s, &end);
} catch (...) {
fail("invalid random draw counter");
}
if (end != s.size() || s.empty() ||
!std::all_of(s.begin(), s.end(), [](unsigned char c) { return c >= '0' && c <= '9'; }))
fail("invalid random draw counter");
return n;
}
uint32_t seed(const J &value) {
const auto n = num(get(value, "seed"));
if (n < 0 || n > UINT32_MAX)
fail("invalid random seed");
return uint32_t(n);
}
Documents world_of(const Documents &docs) {
Documents world;
for (const auto &[name, value] : docs)
if (!name.starts_with("state/"))
world[name] = value;
world["manifest.json"] = docs.at("state/world-manifest.json");
return world;
}
} // namespace
namespace {
template <class T> J vector_json(const std::vector<T> &values) {
A rows;
for (auto value : values)
rows.emplace_back(int64_t(value));
return rows;
}
template <class T> void vector_json(const J &j, std::vector<T> &out) {
if (!j.array() || j.array()->size() > 1000000)
fail("invalid checkpoint array");
for (const auto &row : *j.array()) {
const auto n = num(row);
if (n < int64_t(std::numeric_limits<T>::min()) || n > int64_t(std::numeric_limits<T>::max()))
fail("checkpoint array value out of range");
out.push_back(T(n));
}
}
J group_json(const MatchGroup &g) {
O out;
#define FIELD(name) out[#name] = vector_json(g.name);
FIELD(desc)
FIELD(fixtures) FIELD(results) FIELD(cup_results) FIELD(cup_other_leg) FIELD(records) FIELD(end_minute)
FIELD(spectators) FIELD(log)
#undef FIELD
out["cup_addresses"] = A{int64_t(g.cup_result_address[0]), int64_t(g.cup_result_address[1])};
out["phase"] = g.phase;
out["ended"] = int64_t(g.ended);
out["kickoff_void_mask"] = int64_t(g.kickoff_void_mask);
return out;
}
MatchGroup group_json(const J &in) {
MatchGroup g;
#define FIELD(name) vector_json(get(in, #name), g.name);
FIELD(desc)
FIELD(fixtures) FIELD(results) FIELD(cup_results) FIELD(cup_other_leg) FIELD(records) FIELD(end_minute)
FIELD(spectators) FIELD(log)
#undef FIELD
const auto &at = arr(get(in, "cup_addresses"));
if (at.size() != 2)
fail("invalid cup addresses");
for (size_t i = 0; i < 2; ++i) {
const auto n = num(at[i]);
if (n < 0 || n > UINT32_MAX)
fail("invalid cup address");
g.cup_result_address[i] = uint32_t(n);
}
const auto phase = num(get(in, "phase")), ended = num(get(in, "ended")),
mask = num(get(in, "kickoff_void_mask"));
if (phase < 0 || phase > 1 || ended < 0 || ended > UINT32_MAX || mask < 0 || mask > UINT32_MAX)
fail("invalid match checkpoint");
g.phase = int(phase);
g.ended = uint32_t(ended);
g.kickoff_void_mask = uint32_t(mask);
if ((g.desc.size() != 0xc0 && g.desc.size() != 0xd0) || g.fixtures.size() % 2 || g.matches() > 32 ||
(!g.records.empty() && g.records.size() != size_t(g.matches()) * 18) ||
(!g.end_minute.empty() && g.end_minute.size() != size_t(g.matches())) ||
(!g.spectators.empty() && g.spectators.size() != size_t(g.matches())))
fail("invalid match dimensions");
return g;
}
J groups_json(const std::vector<MatchGroup> &groups) {
A rows;
for (const auto &group : groups)
rows.push_back(group_json(group));
return rows;
}
std::vector<MatchGroup> groups_json(const J &j) {
std::vector<MatchGroup> groups;
const auto &rows = arr(j);
if (rows.size() > 6)
fail("too many match groups");
for (const auto &row : rows)
groups.push_back(group_json(row));
return groups;
}
} // namespace
J driver_checkpoint(const TurnDriver &d) {
return O{{"schema", "classic-driver@1.0"},
{"stage", int(d.stage)},
{"calendar_entry", d.calendar_entry},
{"manager_position", d.manager_position},
{"next_event_id", std::to_string(d.next_event_id)},
{"loaded_matchday_resume", d.loaded_matchday_resume},
{"suppress_remaining_pre_match_offers", d.suppress_remaining_pre_match_offers},
{"national_nomination_desk", d.national_nomination_desk},
{"enable_national_nomination_desks", d.enable_national_nomination_desks},
{"groups", groups_json(d.groups)},
{"referee_source", vector_json(d.referee_source)},
{"referees", vector_json(d.referees)},
{"last_results", O{{"valid", d.last_results.valid},
{"date", int64_t(d.last_results.date)},
{"calendar_entry", d.last_results.calendar_entry},
{"matchday", d.last_results.matchday},
{"groups", groups_json(d.last_results.groups)},
{"tournament_name", vector_json(d.last_results.tournament_name)}}}};
}
void restore_driver(TurnDriver &d, const J &j) {
if (str(get(j, "schema")) != "classic-driver@1.0")
fail("unsupported driver checkpoint");
const auto stage = num(get(j, "stage"));
const auto position = num(get(j, "manager_position"));
const auto entry = num(get(j, "calendar_entry"));
if (stage < 0 || stage > 2 || position < 0 || position > 4 || entry < 0 || entry > UINT16_MAX)
fail("invalid saved desk cursor");
d.stage = TurnDriver::Stage(stage);
d.manager_position = int(position);
d.calendar_entry = uint16_t(entry);
const auto flag = [](const J &value, const char *name) {
const auto &b = get(value, name);
if (!b.boolean())
fail("invalid driver flag");
return *b.boolean();
};
d.loaded_matchday_resume = flag(j, "loaded_matchday_resume");
d.suppress_remaining_pre_match_offers = flag(j, "suppress_remaining_pre_match_offers");
d.national_nomination_desk = flag(j, "national_nomination_desk");
d.enable_national_nomination_desks = flag(j, "enable_national_nomination_desks");
J counter = O{{"calls", get(j, "next_event_id")}};
d.next_event_id = calls(counter);
d.groups = groups_json(get(j, "groups"));
d.referee_source.clear();
d.referees.clear();
vector_json(get(j, "referee_source"), d.referee_source);
vector_json(get(j, "referees"), d.referees);
const auto &last = get(j, "last_results");
d.last_results.valid = flag(last, "valid");
const auto date = num(get(last, "date")), calendar = num(get(last, "calendar_entry")),
matchday = num(get(last, "matchday"));
if (date < 0 || date > UINT32_MAX || calendar < 0 || calendar > UINT16_MAX || matchday < 0 ||
matchday > UINT16_MAX)
fail("invalid result snapshot");
d.last_results.date = uint32_t(date);
d.last_results.calendar_entry = uint16_t(calendar);
d.last_results.matchday = uint16_t(matchday);
d.last_results.groups = groups_json(get(last, "groups"));
d.last_results.tournament_name.clear();
vector_json(get(last, "tournament_name"), d.last_results.tournament_name);
}
void save_career(const std::filesystem::path &path, const Classic &content, const GameState &state,
const WatcomRandom &random, const GameRandom &game, const TurnDriver &driver, bool overwrite,
const J &session) {
if (driver.stage != TurnDriver::Stage::Empty && driver.stage != TurnDriver::Stage::MatchdayDesks &&
driver.stage != TurnDriver::Stage::SeasonEndDesk)
fail("save unavailable outside a manager desk");
Documents docs = content.documents;
if (verify(docs) != content.content_id)
fail("invalid content identity");
docs["state/world-manifest.json"] = docs.at("manifest.json");
auto manifest = parse(docs, "manifest.json");
(*manifest.object())["kind"] = "save";
(*manifest.object())["save_profile"] = "classic-career-v1";
(*manifest.object())["content_id"] = content.content_id;
put(docs, "manifest.json", std::move(manifest));
put(docs, "state/career.json", encode_native_state(state));
put(docs, "state/rng.json",
O{{"schema", "classic-rng@1.0"},
{"watcom", rng(random.seed(), random.calls())},
{"game", rng(uint32_t(game.seed()), game.calls())}});
put(docs, "state/session.json", session);
put(docs, "state/driver.json", driver_checkpoint(driver));
put(docs, "state/information.json", encode_native_bytes(save_header(state)));
O checks;
for (const auto &[name, value] : docs)
if (name.starts_with("state/"))
checks[name] = sha256(value);
put(docs, "state/integrity.json", O{{"schema", "save-integrity@1.0"}, {"entries", std::move(checks)}});
write_archive(docs, path, overwrite);
}
SavedCareer load_career(const std::filesystem::path &path, const Classic &content) {
const auto docs = read_archive(path);
const auto manifest = parse(docs, "manifest.json");
if (str(get(manifest, "kind")) != "save" || str(get(manifest, "save_profile")) != "classic-career-v1" ||
str(get(manifest, "content_id")) != content.content_id)
fail("save belongs to another mod or format");
const auto integrity = parse(docs, "state/integrity.json");
if (str(get(integrity, "schema")) != "save-integrity@1.0")
fail("unsupported save integrity");
O checks;
for (const auto &[name, value] : docs)
if (name.starts_with("state/") && name != "state/integrity.json")
checks[name] = sha256(value);
if (cli::dump_json(get(integrity, "entries")) != cli::dump_json(checks))
fail("damaged native save");
const auto world = world_of(docs);
if (verify(world) != content.content_id)
fail("save world contents changed");
SavedCareer out;
out.state = decode_native_state(parse(docs, "state/career.json"));
if (out.state.players.size() != content.database.players.size() ||
out.state.club_ids.size() != content.database.club_names.size() ||
out.state.manager_records.size() != 5 * 0xb0c)
fail("native state does not match Classic dimensions");
const auto generators = parse(docs, "state/rng.json");
if (str(get(generators, "schema")) != "classic-rng@1.0")
fail("unsupported RNG checkpoint");
const auto &w = get(generators, "watcom");
const auto &g = get(generators, "game");
out.random.restore(seed(w), calls(w));
out.game.restore(std::bit_cast<int32_t>(seed(g)), calls(g));
out.session = parse(docs, "state/session.json");
out.driver = parse(docs, "state/driver.json");
out.header = decode_native_bytes(parse(docs, "state/information.json"), 172);
return out;
}
Bytes save_information(const std::filesystem::path &path) {
const auto docs = read_archive(path);
return decode_native_bytes(parse(docs, "state/information.json"), 172);
}
Bytes load_preferences(const std::filesystem::path &path, const char *kind, size_t size) {
const auto b = read_file(path);
const auto root = cli::parse_json(std::string(b.begin(), b.end()));
if (str(get(root, "schema")) != std::string("classic-") + kind + "@1.0")
fail("unsupported preferences");
return decode_native_bytes(get(root, "payload"), size);
}
void save_preferences(const std::filesystem::path &path, const char *kind, const Bytes &b, bool overwrite) {
write_atomic(path,
cli::dump_json(O{{"schema", std::string("classic-") + kind + "@1.0"},
{"payload", encode_native_bytes(b)}}) +
"\n",
overwrite);
}
} // namespace bmh::content
+23
View File
@@ -0,0 +1,23 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "content/package.hpp"
#include "formats/native_state.hpp"
#include "game/turn_driver.hpp"
namespace bmh::content {
struct SavedCareer {
GameState state;
WatcomRandom random;
GameRandom game;
cli::Json driver, session;
Bytes header;
};
void save_career(const std::filesystem::path &, const Classic &, const GameState &, const WatcomRandom &,
const GameRandom &, const TurnDriver &, bool overwrite, const cli::Json &session = {});
SavedCareer load_career(const std::filesystem::path &, const Classic &);
Bytes save_information(const std::filesystem::path &);
cli::Json driver_checkpoint(const TurnDriver &);
void restore_driver(TurnDriver &, const cli::Json &);
// Native settings/layout files retain the validated Classic bytes with a typed envelope.
Bytes load_preferences(const std::filesystem::path &, const char *kind, size_t size);
void save_preferences(const std::filesystem::path &, const char *kind, const Bytes &, bool overwrite);
} // namespace bmh::content
+10
View File
@@ -0,0 +1,10 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "formats/executable_layout.hpp"
namespace bmh::layout {
// Football Limited V2.20 data-segment locations of the OPL voice slots and
// the 96-word key-on frequency table. Kept separate from simulation tables.
inline constexpr auto EnglishAudioOperatorSlots = EnDataStart + 0x6a63;
inline constexpr auto EnglishAudioNoteFrequencies = EnDataStart + 0xb310;
} // namespace bmh::layout
+3
View File
@@ -1,4 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/binary.hpp"
#include <fstream>
@@ -7,6 +8,8 @@
namespace bmh {
Bytes read_file(const std::filesystem::path& path) {
if (const auto r = content::find(path))
return content::bytes(*r);
std::ifstream in(path, std::ios::binary);
if (!in) throw FormatError("cannot open " + path.string());
return Bytes(std::istreambuf_iterator<char>(in), {});
+69
View File
@@ -0,0 +1,69 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include <algorithm>
#include <cctype>
namespace bmh::content {
namespace {
std::mutex mutex;
struct Binding {
std::shared_ptr<const Classic> content;
int year;
};
std::map<std::filesystem::path, Binding> mounts;
auto normalized(const std::filesystem::path &p) { return std::filesystem::absolute(p).lexically_normal(); }
} // namespace
std::string key(const std::filesystem::path &p) {
auto result = p.generic_string();
std::transform(result.begin(), result.end(), result.begin(),
[](unsigned char c) { return char(std::tolower(c)); });
return result;
}
Mount::Mount(std::filesystem::path root, std::shared_ptr<const Classic> value) : root_(normalized(root)) {
if (!value)
throw FormatError("content: empty mount");
std::lock_guard lock(mutex);
const auto year = value->start_year;
if (!mounts.emplace(root_, Binding{std::move(value), year}).second)
throw FormatError("content: already mounted");
}
Mount::~Mount() {
std::lock_guard lock(mutex);
mounts.erase(root_);
}
std::optional<Resource> find(const std::filesystem::path &p) {
const auto full = normalized(p);
std::lock_guard lock(mutex);
for (const auto &[root, data] : mounts) {
const auto relative = full.lexically_relative(root);
if (relative.empty() || *relative.begin() == "..")
continue;
return Resource{data.content, key(relative), data.year};
}
return std::nullopt;
}
void set_display_start_year(const std::filesystem::path &root, int year) {
if (year < 1900 || year > 9998)
throw FormatError("Invalid Classic display origin");
std::lock_guard lock(mutex);
const auto it = mounts.find(normalized(root));
if (it == mounts.end())
throw FormatError("Content is not mounted");
it->second.year = year;
}
Bytes bytes(const Resource &r) {
if (r.key == "m3.men")
return r.content->desktops;
if (r.key == "m3.dat")
return r.content->formations;
if (r.key == "textd.blk.header")
return r.content->text_header;
if (r.key.starts_with("s/")) {
const auto it = r.content->audio.find(r.key.substr(2));
if (it != r.content->audio.end())
return it->second;
}
if (const auto it = r.content->supplemental.find(r.key); it != r.content->supplemental.end())
return it->second;
throw FormatError("content: no byte resource: " + r.key);
}
} // namespace bmh::content
+54
View File
@@ -0,0 +1,54 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include "formats/font.hpp"
#include "formats/palette.hpp"
#include "formats/le.hpp"
#include "formats/m3d.hpp"
#include "formats/textd.hpp"
namespace bmh::content {
// Immutable decoded Classic content. Logical aliases keep the existing UI geometry
// independent of both storage layout and the legacy binary codecs.
struct Classic {
bool english = false;
Database database;
TextDb texts;
LeImage executable, 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, Palette> image_palettes;
std::map<std::string, Bytes> audio;
std::map<std::string, Bytes> supplemental;
std::map<std::string, std::string> documents;
std::string content_id;
int start_year = 2026;
};
struct Resource {
std::shared_ptr<const Classic> content;
std::string key;
int display_start_year = 2026;
};
// The mount owns a shared content reference; callers never reconstruct legacy files.
// One game runs per process. Multiple mounts are supported by tools and tests.
class Mount {
public:
Mount(std::filesystem::path root, std::shared_ptr<const Classic> content);
~Mount();
Mount(const Mount &) = delete;
Mount &operator=(const Mount &) = delete;
const std::filesystem::path &root() const { return root_; }
private:
std::filesystem::path root_;
};
std::optional<Resource> find(const std::filesystem::path &locator);
void set_display_start_year(const std::filesystem::path &root, int year);
Bytes bytes(const Resource &resource);
std::string key(const std::filesystem::path &relative);
} // namespace bmh::content
+7
View File
@@ -1,9 +1,16 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/font.hpp"
namespace bmh {
Font load_font(const std::filesystem::path& path) {
if (const auto r = content::find(path)) {
const auto found = r->content->fonts.find(std::filesystem::path(r->key).filename().string());
if (found == r->content->fonts.end())
throw FormatError("content: missing font: " + r->key);
return found->second;
}
Bytes d = read_file(path);
if (d.size() < 28) throw FormatError("FNT: file too short");
Font f;
+8
View File
@@ -1,4 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/le.hpp"
#include "formats/rule_base.hpp"
@@ -37,6 +38,13 @@ void save_image(const LeImage& image, const std::filesystem::path& path) {
}
LeImage load_le(const std::filesystem::path& path, bool apply_supported_rules) {
if (const auto r = content::find(path)) {
if (r->key != "bmh.exe")
throw FormatError("content: unknown Classic table set");
auto tables = apply_supported_rules ? r->content->executable : r->content->source_tables;
tables.set_display_start_year(r->display_start_year);
return tables;
}
const Bytes raw = read_file(path);
if (raw.size() >= sizeof kImageMagic + 8 && std::equal(kImageMagic, kImageMagic + sizeof kImageMagic, raw.begin())) {
const auto word = [&](size_t at) { return uint32_t(raw[at] | raw[at + 1] << 8 | raw[at + 2] << 16) | uint32_t(raw[at + 3]) << 24; };
+20 -16
View File
@@ -18,20 +18,23 @@ namespace bmh {
class LeImage {
public:
uint32_t base() const { return base_; }
uint32_t size() const { return uint32_t(bytes_.size()); }
bool contains(uint32_t address) const { return address >= base_ && address - base_ < bytes_.size(); }
uint8_t u8(uint32_t address) const { return bytes_.at(address - base_); }
uint16_t u16(uint32_t address) const { return uint16_t(u8(address) | u8(address + 1) << 8); }
uint32_t u32(uint32_t address) const { return uint32_t(u16(address)) | uint32_t(u16(address + 2)) << 16; }
// A NUL terminated string at `address` (ISO 646-DE bytes, see textd.hpp).
std::string cstring(uint32_t address) const;
// The string a pointer variable at `address` points to (e.g. Weekly_AdvertisingOffers_TextPointer).
std::string string_at_pointer(uint32_t address) const { return cstring(u32(address)); }
const uint8_t* data(uint32_t address) const { return bytes_.data() + (address - base_); }
// Overwrites bytes inside the image (the rule base, formats/rule_base.hpp).
void patch(uint32_t address, const uint8_t* bytes, size_t count) {
for (size_t i = 0; i < count; ++i) bytes_.at(address - base_ + i) = bytes[i];
int display_start_year() const { return display_start_year_; }
void set_display_start_year(int year) { display_start_year_ = year; }
uint32_t base() const { return base_; }
uint32_t size() const { return uint32_t(bytes_.size()); }
bool contains(uint32_t address) const { return address >= base_ && address - base_ < bytes_.size(); }
uint8_t u8(uint32_t address) const { return bytes_.at(address - base_); }
uint16_t u16(uint32_t address) const { return uint16_t(u8(address) | u8(address + 1) << 8); }
uint32_t u32(uint32_t address) const { return uint32_t(u16(address)) | uint32_t(u16(address + 2)) << 16; }
// A NUL terminated string at `address` (ISO 646-DE bytes, see textd.hpp).
std::string cstring(uint32_t address) const;
// The string a pointer variable at `address` points to (e.g. Weekly_AdvertisingOffers_TextPointer).
std::string string_at_pointer(uint32_t address) const { return cstring(u32(address)); }
const uint8_t *data(uint32_t address) const { return bytes_.data() + (address - base_); }
// Overwrites bytes inside the image (the rule base, formats/rule_base.hpp).
void patch(uint32_t address, const uint8_t *bytes, size_t count) {
for (size_t i = 0; i < count; ++i)
bytes_.at(address - base_ + i) = bytes[i];
}
// An image built by OpenBMH itself (the English FLTD.EXE translated into the German
@@ -47,8 +50,9 @@ public:
friend LeImage load_le(const std::filesystem::path& path, bool apply_supported_rules);
private:
uint32_t base_ = 0;
Bytes bytes_;
int display_start_year_ = 2026;
uint32_t base_ = 0;
Bytes bytes_;
};
// OpenBMH deviates from the original: applies a shared supported rule profile when loading editions with different rule-table values.
+6
View File
@@ -1,4 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/m3d.hpp"
#include <cstring>
@@ -35,6 +36,11 @@ std::string pool_string(const Bytes& pool, size_t offset) {
} // namespace
Database load_database(const std::filesystem::path& path, const DbCounts& c) {
if (const auto r = content::find(path)) {
if (r->key != "m3d.man")
throw FormatError("content: unknown database");
return r->content->database;
}
return decode_database(read_file(path), c);
}
+64
View File
@@ -0,0 +1,64 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/native_file.hpp"
#include "formats/binary.hpp"
#include <chrono>
#include <fstream>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
namespace bmh::content {
namespace fs = std::filesystem;
namespace {
[[noreturn]] void fail(const std::string &error) { throw FormatError(error); }
} // namespace
void write_atomic(const fs::path &file, std::string_view data, bool overwrite) {
const auto parent = file.has_parent_path() ? file.parent_path() : fs::path(".");
if (!fs::is_directory(parent))
fail("destination directory unavailable");
const auto status = fs::symlink_status(file);
if (fs::is_symlink(status) || fs::is_directory(status) || (!overwrite && fs::exists(status)))
fail("destination already exists or is unsafe");
fs::path staging;
for (int i = 0; i < 100; ++i) {
auto candidate =
parent /
(".openbmh-write-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) +
"-" + std::to_string(i));
if (fs::create_directory(candidate)) {
staging = std::move(candidate);
break;
}
}
if (staging.empty())
fail("cannot reserve staging directory");
struct Cleanup {
fs::path path;
~Cleanup() {
std::error_code ec;
fs::remove_all(path, ec);
}
} cleanup{staging};
const auto temp = staging / "payload";
std::ofstream stream(temp, std::ios::binary);
stream.write(data.data(), std::streamsize(data.size()));
stream.close();
if (!stream)
fail("cannot write temporary file");
const auto current = fs::symlink_status(file);
if (fs::is_symlink(current) || fs::is_directory(current) || (!overwrite && fs::exists(current)))
fail("destination changed while writing");
#ifdef _WIN32
if (!MoveFileExW(temp.c_str(), file.c_str(),
MOVEFILE_WRITE_THROUGH | (overwrite ? MOVEFILE_REPLACE_EXISTING : 0)))
fail("cannot publish file");
#else
if (overwrite)
fs::rename(temp, file);
else {
fs::create_hard_link(temp, file);
fs::remove(temp);
}
#endif
}
} // namespace bmh::content
+7
View File
@@ -0,0 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <filesystem>
#include <string_view>
namespace bmh::content {
void write_atomic(const std::filesystem::path &, std::string_view, bool overwrite = false);
}
+195
View File
@@ -0,0 +1,195 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/native_state.hpp"
#include <limits>
#include <type_traits>
namespace bmh {
namespace {
using J = cli::Json;
using O = J::Object;
using A = J::Array;
[[noreturn]] void invalid() { throw FormatError("native state: invalid or missing field"); }
const J &field(const J &obj, const char *name) {
if (!obj.object())
invalid();
const auto it = obj.object()->find(name);
if (it == obj.object()->end())
invalid();
return it->second;
}
template <class T> J number(T v) { return J(int64_t(v)); }
template <class T> void number(const J &j, T &v) {
if (!j.integer())
invalid();
const auto n = *j.integer();
if constexpr (std::is_unsigned_v<T>) {
if (n < 0 || uint64_t(n) > uint64_t(std::numeric_limits<T>::max()))
invalid();
} else if (n < std::numeric_limits<T>::min() || n > std::numeric_limits<T>::max())
invalid();
v = T(n);
}
J scalar(bool b) { return b; }
void scalar(const J &j, bool &b) {
if (!j.boolean())
invalid();
b = *j.boolean();
}
template <class T> J scalar(T n) { return number(n); }
template <class T> void scalar(const J &j, T &n) { number(j, n); }
template <class Range> J sequence(const Range &values) {
A out;
for (const auto v : values)
out.push_back(number(v));
return out;
}
template <class T> void sequence(const J &j, std::vector<T> &values) {
if (!j.array() || j.array()->size() > 1000000)
invalid();
values.resize(j.array()->size());
for (size_t i = 0; i < values.size(); ++i)
number((*j.array())[i], values[i]);
}
template <class T, size_t N> void sequence(const J &j, std::array<T, N> &values) {
if (!j.array() || j.array()->size() != N)
invalid();
for (size_t i = 0; i < N; ++i)
number((*j.array())[i], values[i]);
}
std::string hex(const Bytes &data) {
constexpr char d[] = "0123456789abcdef";
std::string out;
out.reserve(data.size() * 2);
for (auto c : data) {
out += d[c >> 4];
out += d[c & 15];
}
return out;
}
Bytes unhex(const J &value) {
if (!value.string() || value.string()->size() % 2 || value.string()->size() > 32 * 1024 * 1024)
invalid();
const auto &s = *value.string();
Bytes b;
b.reserve(s.size() / 2);
const auto digit = [](char c) -> int {
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
invalid();
};
for (size_t i = 0; i < s.size(); i += 2)
b.push_back(uint8_t(digit(s[i]) * 16 + digit(s[i + 1])));
return b;
}
} // namespace
cli::Json encode_native_bytes(const Bytes &bytes) {
return O{{"schema", "classic-bytes@1.0"}, {"hex", hex(bytes)}};
}
Bytes decode_native_bytes(const J &value, size_t expected) {
if (!field(value, "schema").string() || *field(value, "schema").string() != "classic-bytes@1.0")
invalid();
auto b = unhex(field(value, "hex"));
if (b.size() != expected)
invalid();
return b;
}
#define STATE_SCALARS(X) \
X(indoor) \
X(level) X(chance_rain) X(chance_temperature) X(last_shooter) X(last_pick_quality) X(live_scene) \
X(sportschau_selection_available) X(sportschau_club_threshold) X(list_toggle) X(lineups_frozen) \
X(offer_answer) X(transfer_notice_suppressed) X(pools_open) X(autosave_months) X(autosave_month) \
X(display_start_year) X(date) X(season_start) X(development_balance) X(trend_rotation) \
X(season)
#define STATE_BYTES(X) \
X(team_morale) \
X(player_bonus) X(formations) X(manager_records) X(tactics) X(manager_options) X(club_table) \
X(club_heap_bc) X(club_heap_78) X(club_heap_b8) X(master_database_metadata) X(referee_names) \
X(stadium_names) X(tournament_name) X(manager_results) X(manager_ratings) X(position_history) \
X(league_rounds) X(results) X(stocks) X(foreign_strength) X(mailbox) X(club_names) \
X(player_names)
#define STATE_NUMBERS(X) \
X(squad_slots) \
X(team_flags) X(manager_teams) X(live_matches) X(sportschau_homes) X(sportschau_priorities) X(club_ids) \
X(player_cards) X(player_name_offsets)
J encode_native_state(const GameState &g) {
O out{{"schema", "classic-state@1.0"}};
#define PUT_SCALAR(name) out[#name] = scalar(g.name);
STATE_SCALARS(PUT_SCALAR)
#undef PUT_SCALAR
#define PUT_BYTES(name) out[#name] = hex(g.name);
STATE_BYTES(PUT_BYTES)
#undef PUT_BYTES
#define PUT_NUMBERS(name) out[#name] = sequence(g.name);
STATE_NUMBERS(PUT_NUMBERS)
#undef PUT_NUMBERS
A players;
for (const auto &p : g.players)
players.push_back(O{{"name_hex", hex(Bytes(p.name.begin(), p.name.end()))},
{"form", number(p.w35c)},
{"skills", number(p.w368)},
{"identity", number(p.w364)}});
out["players"] = std::move(players);
A blocks;
for (const auto &[at, bytes] : g.memory.blocks())
blocks.push_back(O{{"address", number(at)}, {"hex", hex(bytes)}});
out["memory"] = std::move(blocks);
// Reality scene residues influence later matches and must survive a checkpoint.
out["reality"] = O{{"initialized", g.reality.initialized}, {"deflected", g.reality.deflected},
{"card_kind", number(g.reality.card_kind)}, {"distance", g.reality.distance},
{"actors", sequence(g.reality.cue_actors)}, {"grid", g.reality.grid.checkpoint()}};
return out;
}
GameState decode_native_state(const J &in) {
if (!field(in, "schema").string() || *field(in, "schema").string() != "classic-state@1.0")
invalid();
GameState g;
#define GET_SCALAR(name) scalar(field(in, #name), g.name);
STATE_SCALARS(GET_SCALAR)
#undef GET_SCALAR
#define GET_BYTES(name) g.name = unhex(field(in, #name));
STATE_BYTES(GET_BYTES)
#undef GET_BYTES
#define GET_NUMBERS(name) sequence(field(in, #name), g.name);
STATE_NUMBERS(GET_NUMBERS)
#undef GET_NUMBERS
const auto &players = field(in, "players");
if (!players.array() || players.array()->size() > 4095)
invalid();
for (const auto &row : *players.array()) {
Player p;
auto bytes = unhex(field(row, "name_hex"));
p.name.assign(bytes.begin(), bytes.end());
number(field(row, "form"), p.w35c);
number(field(row, "skills"), p.w368);
number(field(row, "identity"), p.w364);
g.players.push_back(std::move(p));
}
const auto &memory = field(in, "memory");
if (!memory.array() || memory.array()->size() > 8192)
invalid();
std::map<uint32_t, Bytes> blocks;
for (const auto &row : *memory.array()) {
uint32_t at;
number(field(row, "address"), at);
auto b = unhex(field(row, "hex"));
if (uint64_t(at) + b.size() > UINT32_MAX || !blocks.emplace(at, std::move(b)).second)
invalid();
}
g.memory = StaticMemory::from_blocks(std::move(blocks));
const auto &reality = field(in, "reality");
scalar(field(reality, "initialized"), g.reality.initialized);
scalar(field(reality, "deflected"), g.reality.deflected);
number(field(reality, "card_kind"), g.reality.card_kind);
number(field(reality, "distance"), g.reality.distance);
sequence(field(reality, "actors"), g.reality.cue_actors);
g.reality.grid.restore_checkpoint(field(reality, "grid"));
if (g.display_start_year < 1900 || g.display_start_year > 9998 || g.manager_teams.size() > 4 ||
g.level < 0 || g.level > 9 || g.date < g.season_start || g.date > 3000000)
invalid();
return g;
}
#undef STATE_SCALARS
#undef STATE_BYTES
#undef STATE_NUMBERS
} // namespace bmh
+11
View File
@@ -0,0 +1,11 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "cli/json.hpp"
#include "game/state.hpp"
namespace bmh {
// Explicit, platform-independent checkpoint. No object dumps, pointers or callbacks.
cli::Json encode_native_state(const GameState &);
GameState decode_native_state(const cli::Json &);
cli::Json encode_native_bytes(const Bytes &);
Bytes decode_native_bytes(const cli::Json &, size_t expected);
} // namespace bmh
+6
View File
@@ -1,4 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/palette.hpp"
#include "formats/binary.hpp"
@@ -6,6 +7,11 @@
namespace bmh {
Palette load_palette(const std::filesystem::path& path) {
if (const auto r = content::find(path)) {
if (r->key != "m3pc.col")
throw FormatError("content: unknown palette");
return r->content->palette;
}
Bytes b = read_file(path);
if (b.size() < 768) throw FormatError("palette too short: " + path.string());
Palette p;
+6
View File
@@ -1,4 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/content.hpp"
#include "formats/textd.hpp"
#include "formats/binary.hpp"
@@ -6,6 +7,11 @@
namespace bmh {
TextDb load_textd(const std::filesystem::path& path) {
if (const auto r = content::find(path)) {
if (r->key != "textd.blk")
throw FormatError("content: unknown text set");
return r->content->texts;
}
Bytes d = read_file(path);
if (d.size() < 7) throw FormatError("TEXTD: file too short");
// header: u8 id, u16 buffer size, u32 unknown; the buffer may be larger than the file rest
+12 -1
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/vga.hpp"
#include "formats/content.hpp"
namespace bmh {
@@ -40,6 +41,16 @@ Image decode_vga(const Bytes& d) {
return img;
}
Image load_vga(const std::filesystem::path& path) { return decode_vga(read_file(path)); }
Image load_vga(const std::filesystem::path &path) {
if (const auto r = content::find(path)) {
auto name = std::filesystem::path(r->key);
name.replace_extension();
const auto found = r->content->images.find(name.generic_string());
if (found == r->content->images.end())
throw FormatError("content: missing image: " + r->key);
return found->second;
}
return decode_vga(read_file(path));
}
} // namespace bmh
+29 -1
View File
@@ -1,6 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/highscore.hpp"
#include "formats/native_state.hpp"
#include "formats/native_file.hpp"
#include <algorithm>
#include <bit>
@@ -186,11 +188,25 @@ HighscoreTable decode_highscore_table(const HighscoreBytes& bytes) {
}
return rows;
}
std::filesystem::path highscore_file(const std::filesystem::path& base, uint16_t signature, const std::string& prefix) {
std::filesystem::path highscore_file(const std::filesystem::path &base, uint16_t signature,
const std::string &prefix, bool native) {
if (!signature) throw std::invalid_argument("highscore: signature0 has no ranked file");
if (native)
return base / ("highscore-" + std::to_string(signature) + ".obscore");
return base / (prefix + std::to_string(signature));
}
HighscoreTable load_highscore_table(const std::filesystem::path& file) {
if (file.extension() == ".obscore") {
const auto data = read_file(file);
const auto j = cli::parse_json(std::string(data.begin(), data.end()));
if (!j.object() || !j.object()->contains("schema") || !j.object()->at("schema").string() ||
*j.object()->at("schema").string() != "classic-highscore@1.0" || !j.object()->contains("payload"))
throw FormatError("Invalid native highscore");
const auto raw = decode_native_bytes(j.object()->at("payload"), 360);
HighscoreBytes bytes;
std::copy(raw.begin(), raw.end(), bytes.begin());
return decode_highscore_table(bytes);
}
std::ifstream in(file, std::ios::binary);
if (!in) {
HighscoreTable empty{};
@@ -203,6 +219,18 @@ HighscoreTable load_highscore_table(const std::filesystem::path& file) {
}
bool save_highscore_table(const std::filesystem::path& file, const HighscoreTable& rows) {
const auto bytes = encode_highscore_table(rows);
if (file.extension() == ".obscore") {
try {
content::write_atomic(file,
cli::dump_json(cli::Json::Object{
{"schema", "classic-highscore@1.0"},
{"payload", encode_native_bytes(Bytes(bytes.begin(), bytes.end()))}}),
true);
return true;
} catch (const std::exception &) {
return false;
}
}
std::ofstream out(file, std::ios::binary | std::ios::trunc);
if (!out) return false;
out.write(reinterpret_cast<const char*>(bytes.data()), bytes.size());
+2 -2
View File
@@ -53,8 +53,8 @@ HighscoreProjection make_highscore_projection(const GameState& g, HighscoreTable
HighscoreBytes encode_highscore_table(const HighscoreTable& rows);
HighscoreTable decode_highscore_table(const HighscoreBytes& bytes);
// The caller supplies the configured installation base and Original TEXTD889 prefix.
std::filesystem::path highscore_file(const std::filesystem::path& base,
uint16_t signature, const std::string& prefix = "high/h.");
std::filesystem::path highscore_file(const std::filesystem::path &base, uint16_t signature,
const std::string &prefix = "high/h.", bool native = false);
HighscoreTable load_highscore_table(const std::filesystem::path& file);
bool save_highscore_table(const std::filesystem::path& file, const HighscoreTable& rows);
+7
View File
@@ -70,6 +70,13 @@ public:
}
void set_pointer(uint32_t a, uint32_t address) { set32(a, address == 0 ? 0 : address + kGuestDataBase); }
const std::map<uint32_t, Bytes> &blocks() const { return blocks_; }
static StaticMemory from_blocks(std::map<uint32_t, Bytes> blocks) {
StaticMemory memory;
memory.blocks_ = std::move(blocks);
return memory;
}
private:
static std::string hex(uint32_t v) {
char b[16];
+8
View File
@@ -20,6 +20,10 @@ public:
void srand(uint32_t seed) { seed_ = seed; }
uint32_t seed() const { return seed_; }
uint64_t calls() const { return calls_; }
void restore(uint32_t seed, uint64_t calls) {
seed_ = seed;
calls_ = calls;
}
int rand() {
calls_++;
if (draw_hook) draw_hook(1);
@@ -47,6 +51,10 @@ public:
int32_t seed() const { return seed_; }
void set_seed(int32_t seed) { seed_ = seed; }
uint64_t calls() const { return calls_; }
void restore(int32_t seed, uint64_t calls) {
seed_ = seed;
calls_ = calls;
}
int32_t range(int32_t lo, int32_t hi) {
calls_++;
if (draw_hook) draw_hook(0);
+57
View File
@@ -166,3 +166,60 @@ std::pair<int,int> RealityGrid::position(int figure) const {
}
} // namespace bmh
namespace bmh {
cli::Json RealityGrid::checkpoint() const {
cli::Json::Array planes, positions;
for (const auto &plane : occupied_) {
cli::Json::Array cells;
for (auto b : plane)
cells.emplace_back(int(b));
planes.emplace_back(std::move(cells));
}
for (const auto &[x, y] : positions_)
positions.emplace_back(cli::Json::Array{x, y});
return cli::Json::Object{
{"planes", std::move(planes)},
{"positions", std::move(positions)},
{"ball", cli::Json::Array{ball_.first, ball_.second}},
{"previous_ball", cli::Json::Array{previous_ball_.first, previous_ball_.second}}};
}
void RealityGrid::restore_checkpoint(const cli::Json &value) {
const auto field = [&](const char *name) -> const cli::Json & {
if (!value.object() || !value.object()->contains(name))
throw FormatError("native Reality grid field missing");
return value.object()->at(name);
};
const auto array = [](const cli::Json &j, size_t size) -> const cli::Json::Array & {
if (!j.array() || j.array()->size() != size)
throw FormatError("invalid native Reality grid dimensions");
return *j.array();
};
const auto integer = [](const cli::Json &j) -> int {
if (!j.integer() || *j.integer() < INT32_MIN || *j.integer() > INT32_MAX)
throw FormatError("invalid native Reality coordinate");
return int(*j.integer());
};
RealityGrid restored;
const auto &planes = array(field("planes"), 2);
for (size_t p = 0; p < 2; ++p) {
const auto &cells = array(planes[p], 0x478);
for (size_t i = 0; i < cells.size(); ++i) {
const int n = integer(cells[i]);
if (n < 0 || n > 255)
throw FormatError("invalid native Reality cell");
restored.occupied_[p][i] = uint8_t(n);
}
}
const auto pair = [&](const cli::Json &j) {
const auto &xy = array(j, 2);
return std::pair<int, int>{integer(xy[0]), integer(xy[1])};
};
const auto &positions = array(field("positions"), 24);
for (size_t i = 0; i < 24; ++i)
restored.positions_[i] = pair(positions[i]);
restored.ball_ = pair(field("ball"));
restored.previous_ball_ = pair(field("previous_ball"));
*this = std::move(restored);
}
} // namespace bmh
+12 -9
View File
@@ -6,6 +6,7 @@
#include <utility>
#include "formats/le.hpp"
#include "cli/json.hpp"
namespace bmh {
@@ -59,15 +60,17 @@ RealityPath reality_goal_path(int x, int y, int goal_x);
// either player plane. This is runtime scene state, not a Native save extension.
class RealityGrid {
public:
bool place(int figure, int x, int y, int side);
void clear(int x, int y, int side); // caller clears old occupancy before a move
void reset_occupancy(); // Source initialization preserves old figure/ball data
bool operator==(const RealityGrid&) const = default;
void stage_position(int figure, int x, int y); // afb0c/afb23 before occupancy is committed
uint8_t occupant(int x, int y, int side) const;
std::pair<int, int> position(int figure) const;
std::pair<int, int> ball() const { return ball_; }
std::pair<int, int> previous_ball() const { return previous_ball_; }
cli::Json checkpoint() const;
void restore_checkpoint(const cli::Json &);
bool place(int figure, int x, int y, int side);
void clear(int x, int y, int side); // caller clears old occupancy before a move
void reset_occupancy(); // Source initialization preserves old figure/ball data
bool operator==(const RealityGrid &) const = default;
void stage_position(int figure, int x, int y); // afb0c/afb23 before occupancy is committed
uint8_t occupant(int x, int y, int side) const;
std::pair<int, int> position(int figure) const;
std::pair<int, int> ball() const { return ball_; }
std::pair<int, int> previous_ball() const { return previous_ball_; }
private:
std::array<std::array<uint8_t, 0x478>, 2> occupied_{};
std::array<std::pair<int, int>, 24> positions_{};
+3 -3
View File
@@ -27,7 +27,7 @@ void put32(Bytes& d, size_t at, uint32_t x) {
// DeskDate2(date, buffer, 0): "TT.MM.JJJJ" of a day counter (day 0 = 1 July 2026; a
// four-year leap cycle that starts with the third year).
std::string date_text(uint32_t counter) {
std::string date_text(uint32_t counter, int start_year) {
static const int kDays[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int cycle = 3, years = 0, month = 7;
while (counter > uint32_t(364 + (cycle == 4))) {
@@ -45,7 +45,7 @@ std::string date_text(uint32_t counter) {
if (++month == 13) month = 1, ++years;
}
char buf[16];
std::snprintf(buf, sizeof buf, "%02d.%02d.%04d", day, month, 2026 + years);
std::snprintf(buf, sizeof buf, "%02d.%02d.%04d", day, month, start_year + years);
return buf;
}
@@ -133,7 +133,7 @@ Bytes save_header(const GameState& g) {
const int managers = g.memory.u8(::bmh::layout::ManagerCount);
Bytes h;
h.push_back(uint8_t(managers));
const std::string date = date_text(g.date);
const std::string date = date_text(g.date, g.display_start_year);
for (size_t i = 0; i < 11; i++) h.push_back(i < date.size() ? uint8_t(date[i]) : 0);
Bytes list(0xa0, 0);
for (int m = 0; m < managers && m < 4; m++) {
+1
View File
@@ -174,6 +174,7 @@ struct GameState {
// 3 (stadiums, *ba360): not used by the engine, kept for writing savegames.
std::vector<uint8_t> master_database_metadata, referee_names, stadium_names;
std::vector<uint16_t> player_cards; // *PlayerCards, per player: card counters per competition
int display_start_year = 2026; // Cosmetic Classic origin; does not alter scheduling.
uint32_t date = 0; // CalendarDay: day counter
// DaysIntoSeason (day of the season, the calendar index) moves with the day counter within
// a season: season_day() = date - season_start.
+35 -3
View File
@@ -1,12 +1,12 @@
# SPDX-License-Identifier: GPL-3.0-only
add_library(bmh_obw STATIC obw.cpp classic.cpp assets.cpp ../cli/json.cpp ../audio/container.cpp)
add_library(bmh_obw STATIC obw.cpp classic.cpp assets.cpp save.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)
target_link_libraries(openbmh_import PRIVATE bmh_obw)
target_link_libraries(openbmh_import PRIVATE bmh_content)
set_target_properties(openbmh_import PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}")
add_executable(obw_import_tests ../../tests/obw_import_tests.cpp)
target_link_libraries(obw_import_tests PRIVATE bmh_obw bmh_miniz)
target_link_libraries(obw_import_tests PRIVATE bmh_content bmh_miniz)
if(MSVC)
target_compile_options(bmh_obw PRIVATE /W4 /utf-8)
target_compile_options(openbmh_import PRIVATE /W4 /utf-8)
@@ -22,3 +22,35 @@ if(MSVC)
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)
add_library(bmh_content STATIC ../content/digest.cpp ../content/package.cpp ../content/save.cpp)
target_include_directories(bmh_content PUBLIC ..)
target_link_libraries(bmh_content PUBLIC bmh_obw PRIVATE bmh_miniz)
add_library(bmh_launcher STATIC ../launch/mods.cpp ../launch/process.cpp ../launch/launcher.cpp)
target_include_directories(bmh_launcher PUBLIC ..)
target_link_libraries(bmh_launcher PUBLIC bmh_content)
include(../launch/rmlui.cmake)
target_sources(bmh_launcher PRIVATE ../launch/launcher_rmlui.cpp)
target_link_libraries(bmh_launcher PRIVATE bmh_rmlui nfd)
add_executable(launcher_document_tests ../../tests/launcher_document_tests.cpp)
target_include_directories(launcher_document_tests PRIVATE ..)
target_link_libraries(launcher_document_tests PRIVATE RmlUi::Core)
add_test(NAME launcher_document_tests COMMAND launcher_document_tests "${launcher_assets}")
add_test(NAME launcher_unicode_document_tests COMMAND launcher_document_tests "${launcher_assets}" unicode)
if(MSVC)
target_compile_options(launcher_document_tests PRIVATE /utf-8)
endif()
add_executable(native_content_tests ../../tests/native_content_tests.cpp)
target_link_libraries(native_content_tests PRIVATE bmh_launcher)
add_test(NAME native_content_tests COMMAND native_content_tests)
add_executable(native_runtime_tests ../../tests/native_runtime_tests.cpp ${BMH_APP_SESSION_SDL_SOURCE} ${BMH_APP_CONTROLLER_SOURCE})
target_link_libraries(native_runtime_tests PRIVATE bmhui bmh_launcher openbmh_audio)
bmh_add_data_test(NAME native_runtime_tests COMMAND native_runtime_tests "${BMH_DATA}")
if(MSVC)
target_compile_options(bmh_content PRIVATE /W4 /utf-8)
target_compile_options(bmh_launcher PRIVATE /W4 /utf-8)
target_compile_options(native_content_tests PRIVATE /utf-8)
target_compile_options(native_runtime_tests PRIVATE /utf-8)
endif()
+60 -4
View File
@@ -109,7 +109,7 @@ cli::Json portrait_recipe(const std::string& legacy_name, const LeImage& exe) {
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;
A colors, index, images, fonts, audio, animations, palettes, supplemental;
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;
@@ -129,7 +129,21 @@ void import_assets(Documents& out, const std::filesystem::path& root, const Data
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);
const size_t end = 8 + size_t(le32(bytes, 4));
if (end > bytes.size())
fail("invalid indexed image stream length");
Palette effective = palette;
if (bytes.size() - end >= 768) {
A entries;
for (size_t i = 0; i < 256; ++i) {
auto channel = [&](size_t c) { return uint32_t(vga_dac_rgb8(bytes[end + i * 3 + c])); };
effective.argb[i] = 0xff000000u | channel(0) << 16 | channel(1) << 8 | channel(2);
entries.emplace_back(int64_t(effective.argb[i]));
}
palettes.emplace_back(O{{"name", name}, {"argb", std::move(entries)}});
} else if (end != bytes.size())
fail("truncated embedded palette");
image_entry(out, images, index, "asset:classic/" + name, name, image, effective);
atlases.emplace(name, std::move(image));
}
}
@@ -225,8 +239,29 @@ void import_assets(Documents& out, const std::filesystem::path& root, const Data
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)}});
// The in-game readme is content too; preserve its original byte encoding locally.
const bool english = str(get(parse(out, "manifest.json"), "provenance")) == "import:fltd";
const auto texts = load_textd(required(root, english ? "TEXTE.BLK" : "TEXTD.BLK"));
if (texts.strings.size() > 839) {
const auto name = texts[839];
if (!name.empty() && fs::path(name) == fs::path(name).filename()) {
if (const auto source = launch::find_file(root, name); source && fs::is_regular_file(*source)) {
if (fs::is_symlink(fs::symlink_status(*source)) || fs::file_size(*source) > 1024 * 1024)
fail("unsafe readme input");
const auto path = "assets/classic/documents/readme.bytes";
out[path] = binary(read_file(*source));
supplemental.emplace_back(O{{"name", lower(name)}, {"path", path}});
}
}
}
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)},
{"palettes", std::move(palettes)},
{"supplemental", std::move(supplemental)}});
put(out, "assets/index.json", O{{"schema", "asset-index@1.0"}, {"items", std::move(index)}});
}
@@ -274,6 +309,27 @@ void load_assets(const Documents& out, ClassicData& data) {
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 (resources.object()->contains("palettes"))
for (const auto &row : arr(get(resources, "palettes"))) {
const auto &colors = arr(get(row, "argb"));
if (colors.size() != 256)
fail("invalid embedded palette");
Palette palette;
for (size_t i = 0; i < 256; ++i) {
const auto n = num(colors[i]);
if (n < 0 || n > UINT32_MAX)
fail("invalid color");
palette.argb[i] = uint32_t(n);
}
if (!data.image_palettes.emplace(str(get(row, "name")), palette).second)
fail("duplicate embedded palette");
}
if (resources.object()->contains("supplemental"))
for (const auto &row : arr(get(resources, "supplemental"))) {
if (!data.supplemental.emplace(str(get(row, "name")), bytes(out.at(str(get(row, "path")))))
.second)
fail("duplicate supplemental content");
}
if (!data.images.contains("kb/29") || data.fonts.size() != 2 || data.audio.size() != 4) fail("incomplete classic media");
}
} // namespace bmh::obw
+108 -23
View File
@@ -276,7 +276,7 @@ void refresh_classic_inventory(Documents& out) {
using namespace detail;
A inventory;
for (const auto& [path, contents] : out)
if (path != "x-classic/inventory.json")
if (path != "x-classic/inventory.json" && path != "x-classic/seal.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)}});
}
@@ -287,52 +287,136 @@ static ClassicData decode_classic(const Documents& out) {
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");
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.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);
// Reconstruct the native Classic database fields directly. The original M3D
// byte stream is retained as import provenance only, never parsed at runtime.
const auto database = parse(out, "x-legacy/database.json");
const auto &counts = get(database, "counts");
if (num(get(counts, "clubs")) != 419 || num(get(counts, "players")) != 2574 ||
num(get(counts, "n42")) != 168 || num(get(counts, "n66")) != 3096)
fail("unsupported Classic database dimensions");
auto &db = data.database;
const auto &pools = arr(get(database, "pools"));
if (pools.size() != 4)
fail("invalid native name pools");
for (size_t i = 0; i < 4; ++i)
db.pools[i] = unhex(str(pools[i]));
const auto &tables = get(database, "tables");
const auto table = [&](const char *name, Bytes &target, size_t expected) {
target = unhex(str(get(tables, name)));
if (target.size() != expected)
fail(std::string("invalid Classic table size: ") + name);
};
table("player_bonus_values", db.raw_player_bonus_values, 3096 + 0x32);
table("database_metadata", db.raw_database_metadata, 100);
table("club_auxiliary_words", db.raw_club_auxiliary_words, 168 * 2);
table("club_badge_selectors", db.raw_club_badge_selectors, 419 * 2);
table("foreign_club_strength", db.raw_foreign_club_strength, 0xfb);
table("league_auxiliary_bytes", db.raw_league_auxiliary_bytes, 0xbd);
table("referee_properties", db.raw_referee_properties, 50);
table("club_kit_selectors", db.raw_club_kit_selectors, 419);
table("club_short_name_offsets", db.raw_club_short_name_offsets, 168);
table("club_name_offsets", db.raw_club_name_offsets, 419 * 2);
table("player_name_offsets", db.raw_player_name_offsets, 2574 * 2);
table("squad_list", db.squad_list, (3096 - 4) * 2 + 0x6c);
const auto name = [&](size_t pool, size_t offset) {
const auto &bytes = db.pools[pool];
if (offset >= bytes.size())
fail("native name offset outside pool");
const auto end = std::find(bytes.begin() + offset, bytes.end(), 0);
if (end == bytes.end())
fail("unterminated native name");
return std::string(bytes.begin() + offset, end);
};
for (size_t i = 0; i < 419; ++i)
db.club_names.push_back(name(0, le16(db.raw_club_name_offsets, i * 2)));
db.players.resize(2574);
std::set<size_t> player_ids;
for (const auto &player : items(out, "players")) {
const auto &raw = get(player, "x-legacy");
const auto id = num(get(raw, "player_index"));
if (id < 0 || id >= 2574 || !player_ids.insert(size_t(id)).second)
fail("invalid native player identity");
auto &value = db.players[size_t(id)];
value.name = name(1, le16(db.raw_player_name_offsets, size_t(id) * 2));
const auto word = [&](const char *key) {
const auto n = num(get(raw, key));
if (n < 0 || n > UINT32_MAX)
fail("invalid native player word");
return uint32_t(n);
};
value.w35c = word("condition_technique_form_word");
value.w368 = word("skill_word");
value.w364 = word("identity_word");
}
if (player_ids.size() != 2574)
fail("incomplete native player records");
const auto split = [&](size_t pool, std::vector<std::string> &values) {
size_t at = 0;
while (at < db.pools[pool].size()) {
auto value = name(pool, at);
at += value.size() + 1;
values.push_back(std::move(value));
}
};
split(2, db.referees);
split(3, db.stadiums);
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");
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");
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");
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");
if (data.texts.strings.size() != TEXT_COUNT)
fail("incomplete classic texts");
load_assets(out, data);
return data;
}
void validate_classic(const Documents& out) {
void validate_classic(const Documents &out) {
using namespace detail;
const auto manifest = parse(out, "manifest.json");
const auto& imported = get(manifest, "x-import");
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");
!*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(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");
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"))) {
@@ -345,7 +429,8 @@ void validate_classic(const Documents& out) {
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");
if (seen.size() + 1 + size_t(out.contains("x-classic/seal.json")) != 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.
+2 -13
View File
@@ -1,23 +1,12 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "import/obw.hpp"
#include "formats/font.hpp"
#include "formats/content.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;
};
using ClassicData = content::Classic;
void complete_classic(Documents& out, const std::filesystem::path& root,
const Database& database, const LeImage& executable,
+11 -3
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "import/obw.hpp"
#include "content/package.hpp"
#include "launch/archive.hpp"
#include "version.hpp"
@@ -53,6 +54,8 @@ int main(int argc, char** argv) {
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);
if (documents.contains("x-classic/seal.json"))
bmh::content::verify(documents);
std::cout << "Valid OBW content: " << documents.size() << " entries; no engine runtime test implied.\n";
return 0;
}
@@ -60,13 +63,18 @@ int main(int argc, char** argv) {
throw std::runtime_error("--data, --output and --start-date are required; see --help");
if (!directory && destination.extension() != ".obw")
throw std::runtime_error("archive output must use the .obw extension");
const auto documents = bmh::obw::import_installation(source, options);
auto documents = bmh::obw::import_installation(source, options);
if (!options.database_only)
bmh::content::seal(documents);
bmh::obw::write(documents, destination, directory);
std::cout << "Converted " << documents.size() << " documents to "
<< bmh::launch::path_to_utf8(destination) << "\n"
<< "Profile: " << (options.database_only ? "legacy-database-v1 (partial)" : "classic-installation-v1 (complete Classic content)")
<< "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";
<< "See manifest.json and x-legacy/import-report.json. Classic packages can be added to "
"the 0.2 portable mods directory.\n";
return 0;
} catch (const std::exception& error) {
std::cerr << "openbmh_import: " << error.what() << '\n';
+207
View File
@@ -0,0 +1,207 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "import/save.hpp"
#include "formats/executable_layout.hpp"
#include "game/career.hpp"
#include <algorithm>
#include <map>
namespace bmh::obw {
namespace {
struct Record {
int target;
uint32_t native_address;
size_t size;
};
} // namespace
Bytes normalize_english_save(const Savegame &source, const DbCounts &counts) {
if (source.version != "V2.20" || !source.checksum_ok)
throw FormatError("Invalid Football Limited V2.20 save");
const auto layout = save_layout(counts, true);
const Record records[] = {
{0, 0, 0}, // Cup_AdvanceCup_RuntimeField3
{1, 0, 0}, // LiveMatchday_FormatError_RuntimeField14
{2, 0, 0}, // ManagerRecords
{3, 0, 0}, // Loans
{4, 0, 0}, // ManagerMatchHistory
{6, 0, 0}, // ManagerAutomation
{7, 0, 0}, // Desktops
{8, 0, 0}, // CareerSession_DispatchToto_RuntimeField
{10, 0, 0}, // CalendarState_FormatError_RuntimeField3
{11, 0, 0}, // ActiveManager
{12, 0, 0}, // CareerSession_RuntimeError_RuntimeField4
{13, 0, 0}, // LeaguePresentationOptions
{14, 0, 0}, // FriendlyTeams
{15, 0, 0}, // FriendlyDays
{16, 0, 0}, // Cup_AdvanceCup_ExecutableField
{17, 0, 0}, // MatchdaySetup_IndoorTournamentDraw_RuntimeField
{18, 0, 0}, // Placements
{19, 0, 0}, // ActiveSelectors
{20, 0, 0}, // Career_CareerAddManager_RuntimeField2
{21, 0, 0}, // DeskActions_SubmitPoolsCoupon_RuntimeField
{22, 0, 0}, // NextDeskManager
{23, 0, 0}, // Savestate_Layout_ExecutableField8
{24, 0, 0}, // DeskPosition
{25, 0, 0}, // DeskRecords_Teams_RuntimeField
{26, 0, 0}, // CareerSession_FormatError_RuntimeField7
{27, 0, 0}, // Cup_AdvanceCup_RuntimeField6
{28, 0, 0}, // CurrentMatchday
{29, 0, 0}, // ClubPlayerDetail_InvalidArgument_RuntimeField3
{30, 0, 0}, // CoachActive
{31, 0, 0}, // OriginalManagerCount
{32, 0, 0}, // CareerSession_Invalid_RuntimeField2
{33, 0, 0}, // CareerDuration
{34, 0, 0}, // GameMode
{35, 0, 0}, // CompetitionSelection
{36, 0, 0}, // ManagerCount
{37, 0, 0}, // SavedCompetition
{38, 0, 0}, // Difficulty
{39, 0, 0}, // StockExchange
{40, 0, 0}, // FundBlock
{41, 0, 0}, // Coupon
{42, 0, 0}, // Savestate_Layout_ExecutableField2
{43, 0, 0}, // Savestate_Layout_ExecutableField
{44, 0, 0}, // AdGroupId
{45, 0, 0}, // OfferSlots
{46, 0, 0}, // ForeignClubStrength
{47, 0, 0}, // Career_Put_ExecutableField3
{48, 0, 0}, // ClubShortNameOffsets
{49, 0, 0}, // ClubKitSelectors
{50, 0, 0}, // Savestate_Layout_ExecutableField7
{51, 0, 0}, // ClubInfo_FormatError_RuntimeField
{52, 0, 0}, // Career_CareerManagersEnd_RuntimeField
{53, 0, 0}, // ClubInfo_FormatError_RuntimeField2
{54, 0, 0}, // DeskActions_Unsupported_RuntimeField
{55, 0, 0}, // Career_RemoveJoinLoans_RuntimeField
{56, 0, 0}, // ClubPlayerDetail_InvalidArgument_RuntimeField
{57, 0, 0}, // ManagerRatings
{58, 0, 0}, // DaysIntoSeason
{-1, ::bmh::layout::EnglishFaCupResults, 0x86}, // fa_results
{-1, ::bmh::layout::EnglishLeagueCupFirstRoundResults, 0x56}, // league_results
{-1, ::bmh::layout::EnglishLeagueCupQuarterFinalOtherLegResults, 0x3c}, // league_return
{-1, ::bmh::layout::EnglishLeagueCupField, 0xa4}, // league_field
{-1, ::bmh::layout::EnglishFaCupField, 0x134}, // fa_field
{61, 0, 0}, // CalendarDay
{62, 0, 0}, // SeasonIndex
{63, 0, 0}, // Savestate_Layout_ExecutableField5
{64, 0, 0}, // CompetitionCalendar
{65, 0, 0}, // Postponed
{66, 0, 0}, // LeagueTableDisplayModes
{67, 0, 0}, // CareerSession_FormatError_ExecutableField
{68, 0, 0}, // ManagerSettings
{69, 0, 0}, // CareerSession_DispatchOtherGames_RuntimeField
{70, 0, 0}, // CareerSession_AnyOf_ExecutableField
{71, 0, 0}, // Career_NewCareerMarketsAndMoods_RuntimeField2
{72, 0, 0}, // ManagerMailbox
{73, 0, 0}, // CareerSession_CloseLeagueFamily_ExecutableField
{74, 0, 0}, // Savestate_Layout_ExecutableField3
{75, 0, 0}, // Flags
{76, 0, 0}, // Formations
{77, 0, 0}, // PlayerDevelopmentBalance
{78, 0, 0}, // PlayerBonuses
{79, 0, 0}, // EditorList
{80, 0, 0}, // Field0
{81, 0, 0}, // Career_CompetitionPointersEnglish_RuntimeField13
{82, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField25
{83, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField22
{84, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField23
{85, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField19
{86, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField26
{87, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField21
{88, 0, 0}, // Career_CompetitionPointersEnglish_RuntimeField14
{89, 0, 0}, // Career_CompetitionPointersEnglish_RuntimeField17
{90, 0, 0}, // Savestate_Layout_ExecutableField4
{91, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField28
{92, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField31
{93, 0, 0}, // Teams
{94, 0, 0}, // MatchdayGroupWorkspace
{95, 0, 0}, // Savestate_Layout_ExecutableField6
{96, 0, 0}, // EventPasses
{97, 0, 0}, // LeagueResults
{98, 0, 0}, // LeagueRoundCounters
{99, 0, 0}, // TeamMorale
{100, 0, 0}, // ClubBadgeSelectors
{101, 0, 0}, // TeamFlags
{102, 0, 0}, // ClubIdentities
{103, 0, 0}, // PlayerNameOffsets
{104, 0, 0}, // MasterDatabaseMetadata
{105, 0, 0}, // ClubAuxiliaryWords
{106, 0, 0}, // LeagueRankHistory
{107, 0, 0}, // Titles
{108, 0, 0}, // Cup_AdvanceCup_RuntimeField6
{109, 0, 0}, // ClubAuxiliaryBytes
{110, 0, 0}, // CupTable
{111, 0, 0}, // SquadSlots
{112, 0, 0}, // PlayerConditionTechniqueForm
{113, 0, 0}, // PlayerCards
{114, 0, 0}, // PlayerSkillWords
{115, 0, 0}, // PlayerIdentityWords
{116, 0, 0}, // TacticsBoards
{117, 0, 0}, // TournamentName
{118, 0, 0}, // Career_EuropeanClub_ExecutableField
{119, 0, 0}, // Career_EuropeanClub_ExecutableField2
{120, 0, 0}, // Career_EuropeanClub_ExecutableField3
{121, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField24
{122, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField29
{123, 0, 0}, // ClubSeasonRecords
{124, 0, 0}, // ClubSeasonRecords
};
std::map<int, Bytes> decoded;
std::map<uint32_t, Bytes> native;
for (const auto &[address, size] : kEnglishCompetitionBlocks)
native[address] = Bytes(size, 0);
size_t offset = 0;
bool club_records = false;
for (const auto &record : records) {
if (record.target == 124 && !club_records)
continue;
const size_t size = record.target < 0 ? record.size : layout.at(size_t(record.target)).size;
if (offset + size > source.stream.size())
throw FormatError("V2.20 state is truncated");
Bytes bytes(source.stream.begin() + offset, source.stream.begin() + offset + size);
offset += size;
if (record.target == 123) {
if (size != 4)
throw FormatError("Invalid club record pointer");
club_records = le32(bytes, 0) != 0;
}
if (record.target >= 0)
decoded[record.target] = bytes;
uint32_t target = record.native_address;
if (record.target == 93)
target = ::bmh::layout::EnglishAdditionalCupField;
if (record.target == 94)
target = ::bmh::layout::EnglishAdditionalCupResults;
if (target)
for (auto &[at, block] : native)
if (target >= at && uint64_t(target) + bytes.size() <= uint64_t(at) + block.size())
std::copy(bytes.begin(), bytes.end(), block.begin() + (target - at));
}
Bytes normalized;
for (size_t i = 0; i < layout.size(); ++i) {
if (i == 124 && !club_records)
continue;
if (const auto it = decoded.find(int(i)); it != decoded.end())
normalized.insert(normalized.end(), it->second.begin(), it->second.end());
else
normalized.insert(normalized.end(), layout[i].size, 0);
}
// Four length-prefixed name pools, shared by both original editions.
for (int i = 0; i < 4; ++i) {
if (offset + 2 > source.stream.size())
throw FormatError("V2.20 name pool missing");
const size_t size = le16(source.stream, offset) + 2;
if (offset + size > source.stream.size())
throw FormatError("V2.20 name pool is truncated");
normalized.insert(normalized.end(), source.stream.begin() + offset,
source.stream.begin() + offset + size);
offset += size;
}
if (offset != source.stream.size())
throw FormatError("V2.20 state has unexpected trailing bytes");
std::vector<SaveState::ExtensionBlock> extension;
for (auto &[at, bytes] : native)
extension.push_back({at, std::move(bytes)});
append_save_extension(normalized, extension);
(void)SaveState(normalized, counts);
return normalized;
}
} // namespace bmh::obw
+9
View File
@@ -0,0 +1,9 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "formats/fbm.hpp"
#include "formats/savestate.hpp"
namespace bmh::obw {
// Translate the V2.20 state-block contract, including its native cup regions,
// to the existing in-memory Classic layout. No executable or FBM file is emitted.
Bytes normalize_english_save(const Savegame &, const DbCounts &counts = {});
} // namespace bmh::obw
+8
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "formats/audio_layout.hpp"
#include "launch/fltd.hpp"
#include <algorithm>
@@ -119,6 +120,13 @@ LeImage translate_fltd(const fs::path& fltd_exe, bool apply_supported_rules) {
}
}
}
// Bind the English audio driver's data explicitly; the general UI/table map
// does not cover its OPL voice slots or key-on frequency table.
for (uint32_t i = 0; i < 9; ++i)
put(layout::Audio_OriginalAudioAssets_RuntimeField + i * 16,
en(layout::EnglishAudioOperatorSlots + i * 16));
for (uint32_t i = 0; i < 96 * 2; ++i)
put(layout::Audio_OriginalAudioAssets_RuntimeField2 + i, en(layout::EnglishAudioNoteFrequencies + i));
LeImage out = LeImage::from_bytes(kDeBase, std::move(image));
if (apply_supported_rules) apply_rule_base(out);
return out;
+2 -1
View File
@@ -379,7 +379,8 @@ ResolvedGame resolve_game(const fs::path& input, const fs::path& cache) {
const fs::path marker = prepared / ".openbmh-english";
// the version of the translation (launch/fltd.cpp, fltd_map.inc): a cache built
// by another version is built again
constexpr const char* kTranslation = "english translation 13"; // 13: setup toggle rows, positive balance colour and desktop bar controls
constexpr const char *kTranslation =
"english translation 14"; // 14: bind native English OPL slots and note frequencies
std::string built;
{
std::ifstream in(marker);
+97
View File
@@ -0,0 +1,97 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "launch/launcher.hpp"
#include "launch/launcher_ui.hpp"
#include "launch/process.hpp"
#include "launch/game_data.hpp"
#include "launch/archive.hpp"
#include <atomic>
#include <future>
#include <mutex>
namespace bmh::launch {
int run_launcher(const std::filesystem::path &executable, const SaveMigrator &migrate) {
auto ui = make_launcher_ui();
ModLibrary library(executable.parent_path());
for (;;)
try {
const auto mods = library.list();
const auto action = ui->next(mods);
if (action.action == LauncherAction::end)
return 0;
if (action.action == LauncherAction::add) {
const auto source = ui->choose_folder("BMH-/Football-Limited-Installation wählen");
if (!source)
continue;
const auto check = check_game_directory(*source);
// Raw English installations are importable before legacy directory
// normalisation, so their old runtime "playable" flag is irrelevant.
if ((check.family != GameFamily::german && check.family != GameFamily::english) ||
!check.problems.empty()) {
std::string reason = check.unsupported;
for (const auto &problem : check.problems)
reason += "\n" + problem;
throw FormatError("Installation wird nicht unterstützt: " + reason);
}
AddMod initial;
initial.source = check.directory;
initial.saves = check.directory;
initial.name = check.family == GameFamily::english ? "FTDL-classic" : "BMH-classic";
const auto request = ui->configure_add(initial);
if (!request)
continue;
std::mutex mutex;
std::string text = "Import wird vorbereitet …";
std::atomic_bool cancelled = false;
ui->progress(text, true);
auto job = std::async(std::launch::async, [&] {
return library.add(*request, migrate, [&](const std::string &s) {
if (cancelled.load())
throw FormatError("Import abgebrochen");
std::lock_guard lock(mutex);
text = s;
});
});
while (job.wait_for(std::chrono::milliseconds(20)) != std::future_status::ready) {
if (ui->pump())
cancelled = true;
std::lock_guard lock(mutex);
ui->progress(text, true);
}
ui->finish_progress();
const auto report = job.get();
std::string summary =
"Mod importiert: " + report.mod.name +
"\nÜbernommene Spielstände/Einstellungen: " + std::to_string(report.migrated);
for (const auto &error : report.errors)
summary += "\n" + error;
ui->message(summary, false);
continue;
}
if (action.selection < 0 || size_t(action.selection) >= mods.size())
continue;
const auto &mod = mods[size_t(action.selection)];
if (action.action == LauncherAction::remove) {
if (ui->confirm_delete(mod.name))
library.remove(mod);
} else if (action.action == LauncherAction::rename) {
if (const auto name = ui->rename(mod.name))
library.rename(mod, *name);
} else if (action.action == LauncherAction::start) {
if (!mod.error.empty())
throw FormatError(mod.error);
(void)content::open(mod.directory / "content.obw");
const auto userdata = library.user_directory(mod);
ui->progress("Spiel läuft: " + mod.name, false);
const int code = run_child(executable,
{"--run-mod", path_to_utf8(mod.directory / "content.obw"),
"--save-directory", path_to_utf8(userdata)},
[&] { ui->pump(); });
ui->finish_progress();
if (code)
ui->message("Das Spiel wurde mit Fehlercode " + std::to_string(code) + " beendet.", true);
}
} catch (const std::exception &e) {
ui->finish_progress();
ui->message(e.what(), true);
}
}
} // namespace bmh::launch
+6
View File
@@ -0,0 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "launch/mods.hpp"
namespace bmh::launch {
int run_launcher(const std::filesystem::path &executable, const SaveMigrator &);
} // namespace bmh::launch
+561
View File
@@ -0,0 +1,561 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "launch/launcher_ui.hpp"
#include "launch/rml_path.hpp"
#include "launch/archive.hpp"
#include "launch/process.hpp"
#include "version.hpp"
#include <RmlUi/Core.h>
#include <RmlUi/Core/Elements/ElementFormControl.h>
#include <RmlUi/Core/Elements/ElementFormControlInput.h>
#include <RmlUi_Platform_SDL.h>
#include <RmlUi_Renderer_GL3.h>
#include <nfd.hpp>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <stdexcept>
namespace bmh::launch {
namespace {
std::string escape(std::string_view value) {
std::string result;
for (char c : value)
switch (c) {
case '&':
result += "&amp;";
break;
case '<':
result += "&lt;";
break;
case '>':
result += "&gt;";
break;
case '"':
result += "&quot;";
break;
case '\n':
result += "<br/>";
break;
default:
result += c;
}
return result;
}
[[noreturn]] void sdl_error(const char *operation) {
throw std::runtime_error(std::string(operation) + ": " + SDL_GetError());
}
int modifiers(Uint16 state) {
int result = 0;
if (state & KMOD_CTRL)
result |= Rml::Input::KM_CTRL;
if (state & KMOD_SHIFT)
result |= Rml::Input::KM_SHIFT;
if (state & KMOD_ALT)
result |= Rml::Input::KM_ALT;
if (state & KMOD_GUI)
result |= Rml::Input::KM_META;
#ifdef __APPLE__
// RmlUI text widgets use the Ctrl flag for editing shortcuts.
if (state & KMOD_GUI)
result |= Rml::Input::KM_CTRL;
#endif
if (state & KMOD_CAPS)
result |= Rml::Input::KM_CAPSLOCK;
if (state & KMOD_NUM)
result |= Rml::Input::KM_NUMLOCK;
return result;
}
struct Video {
SDL_Window *window = nullptr;
SDL_GLContext gl = nullptr;
bool loader = false;
Video() {
try {
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER) != 0)
sdl_error("Launcher video initialization");
SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
#ifdef __APPLE__
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
#else
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
#endif
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
window = SDL_CreateWindow("OpenBMH", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1100, 688,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI |
SDL_WINDOW_HIDDEN);
if (!window)
sdl_error("Launcher window");
SDL_SetWindowMinimumSize(window, 800, 540);
gl = SDL_GL_CreateContext(window);
if (!gl)
sdl_error("Launcher requires OpenGL 3.3 (macOS: 4.1)");
SDL_GL_MakeCurrent(window, gl);
SDL_GL_SetSwapInterval(1);
std::string error;
if (!RmlGL3::Initialize(&error))
throw std::runtime_error("Launcher graphics initialization: " + error);
loader = true;
SDL_StopTextInput();
} catch (...) {
close();
throw;
}
}
void close() {
if (loader)
RmlGL3::Shutdown();
if (gl)
SDL_GL_DeleteContext(gl);
if (window)
SDL_DestroyWindow(window);
SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER);
}
~Video() { close(); }
};
class RmlLauncher final : public LauncherUI, public Rml::EventListener {
Video video_;
rml::AssetFiles files_;
SystemInterface_SDL system_{video_.window};
RenderInterface_GL3 renderer_;
TextInputMethodEditor_SDL ime_;
Rml::Context *context_ = nullptr;
Rml::ElementDocument *document_ = nullptr;
bool initialized_ = false, closed_ = false, dirty_ = true;
bool answered_ = false, accepted_ = false, busy_ = false, cancelled_ = false;
bool cancellable_ = false, modal_visible_ = false;
int selected_ = -1;
std::string selected_name_;
std::vector<ModEntry> mods_;
std::optional<LauncherAction> action_;
Rml::Element *element(const char *id) const {
auto *value = document_->GetElementById(id);
if (!value)
throw std::runtime_error(std::string("Launcher element missing: ") + id);
return value;
}
void text(const char *id, const std::string &value) {
element(id)->SetInnerRML(escape(value));
dirty_ = true;
}
void display(const char *id, bool shown, const char *style = "block") {
element(id)->SetProperty("display", shown ? style : "none");
dirty_ = true;
}
void enabled(const char *id, bool active) {
auto *button = element(id);
if (active)
button->RemoveAttribute("disabled");
else
button->SetAttribute("disabled", "disabled");
button->SetPseudoClass("disabled", !active);
button->SetProperty("focus", active ? "auto" : "none");
dirty_ = true;
}
std::string value(const char *id) const {
auto *input = dynamic_cast<Rml::ElementFormControl *>(element(id));
if (!input)
throw std::runtime_error("Launcher input has the wrong type");
return input->GetValue();
}
void resize() {
int w = 0, h = 0, pixels_w = 0, pixels_h = 0;
SDL_GetWindowSize(video_.window, &w, &h);
SDL_GL_GetDrawableSize(video_.window, &pixels_w, &pixels_h);
if (w <= 0 || h <= 0 || pixels_w <= 0 || pixels_h <= 0)
return;
renderer_.SetViewport(pixels_w, pixels_h);
context_->SetDimensions({pixels_w, pixels_h});
const float scale = std::clamp(std::min(w / 1100.f, h / 688.f), .72f, 2.5f);
context_->SetDensityIndependentPixelRatio(float(pixels_w) / w * scale);
dirty_ = true;
}
void select(int index, bool focus = false) {
if (index < 0 || size_t(index) >= mods_.size())
index = -1;
selected_ = index;
selected_name_ = index >= 0 ? mods_[size_t(index)].name : std::string{};
for (size_t i = 0; i < mods_.size(); ++i) {
auto *row = document_->GetElementById("mod-" + std::to_string(i));
row->SetClass("selected", int(i) == selected_);
row->SetAttribute("aria-selected", int(i) == selected_ ? "true" : "false");
if (focus && int(i) == selected_) {
row->Focus(true);
row->ScrollIntoView();
}
}
enabled("start", selected_ >= 0);
enabled("delete", selected_ >= 0);
enabled("rename", selected_ >= 0);
}
bool modal_open() const { return modal_visible_; }
void close_modal() {
modal_visible_ = false;
display("overlay", false);
answered_ = false;
busy_ = false;
SDL_StopTextInput();
if (selected_ >= 0)
select(selected_, true);
else
element("add")->Focus(true);
}
void modal(const std::string &title, const std::string &body, const std::string &accept,
bool cancel = true, bool danger = false) {
text("modal-title", title);
element("modal-body")->SetInnerRML(body);
text("modal-error", "");
text("accept", accept);
element("accept")->SetClass("danger", danger);
element("accept")->SetClass("primary", !danger);
display("accept", !accept.empty(), "inline-block");
display("cancel", cancel, "inline-block");
answered_ = accepted_ = false;
display("overlay", true);
modal_visible_ = true;
context_->Update();
if (auto *input = document_->GetElementById("mod-name"))
input->Focus(true);
else
element(cancel ? "cancel" : "accept")->Focus(true);
context_->Update();
dirty_ = true;
}
void dispatch(const std::string &command) {
if (command == "cancel") {
if (busy_) {
if (cancellable_)
cancelled_ = true;
} else {
answered_ = true;
accepted_ = false;
}
} else if (command == "accept" && !busy_) {
answered_ = accepted_ = true;
} else if (command == "browse" && !busy_) {
try {
if (auto path =
choose_folder("Spielstandsordner wählen", path_from_utf8(value("save-folder")))) {
auto *input = dynamic_cast<Rml::ElementFormControl *>(element("save-folder"));
input->SetValue(path_to_utf8(*path));
}
} catch (const std::exception &e) {
text("modal-error", e.what());
}
} else if (!modal_open()) {
if (command == "add")
action_ = LauncherAction::add;
else if (command == "end")
action_ = LauncherAction::end;
else if (selected_ >= 0) {
if (command == "start")
action_ = LauncherAction::start;
else if (command == "rename")
action_ = LauncherAction::rename;
else if (command == "delete")
action_ = LauncherAction::remove;
}
}
dirty_ = true;
}
void ProcessEvent(Rml::Event &event) override {
const bool double_click = event.GetType() == "dblclick";
if (event.GetType() != "click" && !double_click)
return;
for (auto *target = event.GetTargetElement(); target && target != document_;
target = target->GetParentNode()) {
if (target->HasAttribute("data-row") && !modal_open()) {
select(target->GetAttribute<int>("data-row", -1));
if (double_click)
dispatch("start");
return;
}
if (target->HasAttribute("data-action")) {
if (double_click)
return;
if (!target->HasAttribute("disabled"))
dispatch(target->GetAttribute<Rml::String>("data-action", ""));
return;
}
}
}
void step(bool wait) {
// Modal visibility and refreshed rows must be laid out before queued
// pointer events are hit-tested against the new document state.
if (dirty_) context_->Update();
SDL_Event event;
const int timeout = dirty_ ? 0 : int(std::clamp(context_->GetNextUpdateDelay(), 0.0, .2) * 1000);
bool got = wait ? SDL_WaitEventTimeout(&event, timeout) != 0 : SDL_PollEvent(&event) != 0;
bool redraw = dirty_ || got || context_->GetNextUpdateDelay() <= 0;
while (got) {
if (event.type == SDL_QUIT ||
(event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE)) {
closed_ = answered_ = true;
accepted_ = false;
cancelled_ = true;
action_ = LauncherAction::end;
} else if (event.type == SDL_KEYDOWN && !event.key.repeat &&
event.key.keysym.sym == SDLK_ESCAPE) {
if (modal_open())
dispatch("cancel");
else
action_ = LauncherAction::end;
} else if (event.type == SDL_KEYDOWN && modal_open() && event.key.keysym.sym == SDLK_TAB) {
Rml::ElementList controls;
element("modal")->QuerySelectorAll(controls, "input, button");
std::erase_if(controls, [](auto *control) {
return !control->IsVisible() || control->HasAttribute("disabled");
});
if (!controls.empty()) {
const auto at = std::find(controls.begin(), controls.end(), context_->GetFocusElement());
const int current = at == controls.end() ? -1 : int(at - controls.begin());
const int step = event.key.keysym.mod & KMOD_SHIFT ? -1 : 1;
const int next = (current + step + int(controls.size())) % int(controls.size());
controls[size_t(next)]->Focus(true);
}
} else if (event.type == SDL_KEYDOWN && !modal_open() && !event.key.repeat &&
(event.key.keysym.sym == SDLK_UP || event.key.keysym.sym == SDLK_DOWN)) {
const int direction = event.key.keysym.sym == SDLK_UP ? -1 : 1;
if (!mods_.empty())
select(std::clamp(selected_ < 0 ? 0 : selected_ + direction, 0, int(mods_.size()) - 1),
true);
} else if (event.type == SDL_KEYDOWN && !event.key.repeat &&
(event.key.keysym.sym == SDLK_RETURN || event.key.keysym.sym == SDLK_SPACE) &&
context_->GetFocusElement() &&
context_->GetFocusElement()->HasAttribute("data-action")) {
auto *focused = context_->GetFocusElement();
if (!focused->HasAttribute("disabled"))
dispatch(focused->GetAttribute<Rml::String>("data-action", ""));
} else if (event.type == SDL_KEYDOWN && !event.key.repeat &&
event.key.keysym.sym == SDLK_RETURN) {
if (modal_open() && !busy_)
dispatch("accept");
else if (!modal_open() && selected_ >= 0)
dispatch("start");
} else if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) {
// Use the modifiers captured with this event, not SDL's final
// state after pumping a batch containing the key releases.
const auto key = RmlSDL::ConvertKey(event.key.keysym.sym);
if (event.type == SDL_KEYDOWN)
context_->ProcessKeyDown(key, modifiers(event.key.keysym.mod));
else
context_->ProcessKeyUp(key, modifiers(event.key.keysym.mod));
} else {
if (event.type == SDL_TEXTEDITING)
ime_.HandleEdit(event.edit);
// SDL2 reports mouse coordinates in window units on Retina/HiDPI.
int w = 0, h = 0, pw = 0, ph = 0;
SDL_GetWindowSize(video_.window, &w, &h);
SDL_GL_GetDrawableSize(video_.window, &pw, &ph);
if (w > 0 && h > 0) {
if (event.type == SDL_MOUSEMOTION) {
event.motion.x = int(double(event.motion.x) * pw / w);
event.motion.y = int(double(event.motion.y) * ph / h);
}
if (event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP) {
event.button.x = int(double(event.button.x) * pw / w);
event.button.y = int(double(event.button.y) * ph / h);
// Repeated clicks need a fresh hover target even when
// the pointer has not moved since a modal was closed.
context_->ProcessMouseMove(event.button.x, event.button.y,
RmlSDL::GetKeyModifierState());
}
}
RmlSDL::InputEventHandler(context_, video_.window, event);
}
if (event.type == SDL_WINDOWEVENT)
resize();
got = SDL_PollEvent(&event) != 0;
}
if (redraw) {
context_->Update();
renderer_.BeginFrame();
renderer_.Clear();
context_->Render();
renderer_.EndFrame();
SDL_GL_SwapWindow(video_.window);
dirty_ = false;
}
}
bool wait_modal() {
while (!answered_ && !closed_)
step(true);
answered_ = false;
return accepted_ && !closed_;
}
public:
RmlLauncher() {
if (!renderer_)
throw std::runtime_error("RmlUI could not create the OpenGL renderer");
try {
Rml::SetSystemInterface(&system_);
Rml::SetFileInterface(&files_);
Rml::SetRenderInterface(&renderer_);
Rml::SetTextInputHandler(&ime_);
initialized_ = Rml::Initialise();
if (!initialized_)
throw std::runtime_error("RmlUI initialization failed");
const auto assets = executable_path({}).parent_path() / "assets" / "launcher";
for (const char *weight : {"Regular", "Bold"})
if (!Rml::LoadFontFace(rml::asset_path(assets / (std::string("LatoLatin-") + weight + ".ttf"))))
throw std::runtime_error("Launcher font missing; extract the complete OpenBMH package");
context_ = Rml::CreateContext("launcher", {1100, 688});
if (!context_)
throw std::runtime_error("RmlUI launcher context failed");
document_ = context_->LoadDocument(rml::asset_path(assets / "launcher.rml"));
if (!document_)
throw std::runtime_error("Launcher layout missing; extract the complete OpenBMH package");
document_->AddEventListener("click", this);
document_->AddEventListener("dblclick", this);
text("version", std::string("v") + bmh::kOpenBmhVersion);
resize();
document_->Show();
SDL_ShowWindow(video_.window);
element("add")->Focus(true);
} catch (...) {
if (initialized_)
Rml::Shutdown();
throw;
}
}
~RmlLauncher() override {
if (initialized_)
Rml::Shutdown();
}
LauncherChoice next(const std::vector<ModEntry> &mods) override {
if (closed_)
return {LauncherAction::end, -1};
mods_ = mods;
std::string rows;
int selection = -1;
for (size_t i = 0; i < mods.size(); ++i) {
const auto &mod = mods[i];
if (mod.name == selected_name_)
selection = int(i);
rows += "<button id=\"mod-" + std::to_string(i) + "\" class=\"mod-row" +
(mod.error.empty() ? "" : " invalid") + "\" data-row=\"" + std::to_string(i) +
"\" title=\"" + escape(mod.error) + "\"><span class=\"name\">" + escape(mod.name) +
"</span><span class=\"type\">" + escape(mod.type) + "</span></button>";
}
if (mods.empty())
rows = "<div class=\"empty\">Keine Mods vorhanden.<div class=\"empty-detail\">Über Add eine "
"Installation hinzufügen.</div></div>";
element("mod-list")->SetInnerRML(rows);
text("mod-count", std::to_string(mods.size()) + (mods.size() == 1 ? " Mod" : " Mods"));
select(selection);
action_.reset();
while (!action_ && !closed_)
step(true);
return {action_.value_or(LauncherAction::end), selected_};
}
std::optional<std::filesystem::path> choose_folder(const std::string &title,
const std::filesystem::path &initial = {}) override {
(void)title;
NFD::Guard guard;
NFD::UniquePathU8 result;
const auto directory = path_to_utf8(initial.empty() ? executable_path({}).parent_path() : initial);
const auto status = NFD::PickFolder(result, directory.c_str());
SDL_RaiseWindow(video_.window);
dirty_ = true;
if (status == NFD_CANCEL)
return {};
if (status != NFD_OKAY)
throw std::runtime_error(std::string("Ordnerauswahl: ") + NFD::GetError());
return path_from_utf8(result.get());
}
std::optional<AddMod> configure_add(AddMod initial) override {
modal("Classic-Mod hinzufügen",
"<label>Bezeichnung</label><input id=\"mod-name\" type=\"text\" maxlength=\"100\" value=\"" +
escape(initial.name) +
"\"/><div class=\"fields\"><div class=\"year\"><label>Startjahr (nur "
"Anzeige)</label><input id=\"start-year\" type=\"text\" maxlength=\"4\" value=\"" +
std::to_string(initial.start_year) +
"\"/></div></div><div class=\"check-row\"><input id=\"migrate\" class=\"checkbox\" "
"type=\"checkbox\" " +
(initial.migrate ? "checked=\"checked\"" : "") +
"/><label for=\"migrate\">Spielstände/Einstellungen "
"übernehmen</label></div><label>Spielstandsordner</label><div class=\"browse-row\"><input "
"id=\"save-folder\" type=\"text\" value=\"" +
escape(path_to_utf8(initial.saves)) +
"\"/><button data-action=\"browse\">Auswählen …</button></div>",
"Importieren");
while (wait_modal()) {
try {
initial.name = value("mod-name");
ModLibrary::validate_name(initial.name);
const auto year = value("start-year");
size_t end = 0;
initial.start_year = std::stoi(year, &end);
if (end != year.size() || initial.start_year < 1900 || initial.start_year > 9998)
throw std::runtime_error("Startjahr muss zwischen 1900 und 9998 liegen.");
initial.migrate = element("migrate")->HasAttribute("checked");
initial.saves = path_from_utf8(value("save-folder"));
close_modal();
return initial;
} catch (const std::exception &e) {
text("modal-error", e.what());
}
}
close_modal();
return {};
}
std::optional<std::string> rename(const std::string &old) override {
modal("Mod umbenennen",
"<label>Bezeichnung</label><input id=\"mod-name\" type=\"text\" maxlength=\"100\" value=\"" +
escape(old) + "\"/>",
"Umbenennen");
std::optional<std::string> result;
while (wait_modal()) {
try {
auto name = value("mod-name");
ModLibrary::validate_name(name);
result = name;
break;
} catch (const std::exception &e) {
text("modal-error", e.what());
}
}
close_modal();
return result;
}
bool confirm_delete(const std::string &name) override {
modal("Mod löschen?",
"„" + escape(name) + "“<br/><br/>Spielstände und persönliche Einstellungen bleiben erhalten.",
"Löschen", true, true);
const bool result = wait_modal();
close_modal();
return result;
}
void message(const std::string &value, bool error) override {
if (closed_)
return;
modal(error ? "OpenBMH · Hinweis" : "OpenBMH", escape(value), "OK", false);
wait_modal();
close_modal();
}
void progress(const std::string &value, bool cancellable) override {
if (!busy_) {
modal(cancellable ? "Mod importieren" : "Spiel läuft", escape(value), "", cancellable);
busy_ = true;
cancelled_ = false;
cancellable_ = cancellable;
} else
text("modal-body", value);
}
bool pump() override {
step(false);
return cancelled_ || closed_;
}
void finish_progress() override {
if (busy_)
close_modal();
}
};
} // namespace
std::unique_ptr<LauncherUI> make_launcher_ui() { return std::make_unique<RmlLauncher>(); }
} // namespace bmh::launch
+27
View File
@@ -0,0 +1,27 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "launch/mods.hpp"
#include <memory>
#include <optional>
namespace bmh::launch {
enum class LauncherAction { start, add, remove, rename, end };
struct LauncherChoice {
LauncherAction action = LauncherAction::end;
int selection = -1;
};
class LauncherUI {
public:
virtual ~LauncherUI() = default;
virtual LauncherChoice next(const std::vector<ModEntry> &) = 0;
virtual std::optional<std::filesystem::path> choose_folder(const std::string &title,
const std::filesystem::path &initial = {}) = 0;
virtual std::optional<AddMod> configure_add(AddMod defaults) = 0;
virtual std::optional<std::string> rename(const std::string &) = 0;
virtual bool confirm_delete(const std::string &) = 0;
virtual void message(const std::string &, bool error) = 0;
virtual void progress(const std::string &, bool cancellable) = 0;
virtual bool pump() = 0; // cancellation requested
virtual void finish_progress() = 0;
};
std::unique_ptr<LauncherUI> make_launcher_ui();
} // namespace bmh::launch
+190
View File
@@ -0,0 +1,190 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "launch/mods.hpp"
#include "content/save.hpp"
#include "launch/archive.hpp"
#include <algorithm>
#include <cctype>
#include <chrono>
#include <set>
namespace bmh::launch {
namespace fs = std::filesystem;
namespace {
std::string fold(std::string s) {
for (auto &c : s)
c = char(std::tolower(static_cast<unsigned char>(c)));
return s;
}
std::string filename(const fs::path &p) { return path_to_utf8(p.filename()); }
void safe_directory(const fs::path &path) {
const auto status = fs::symlink_status(path);
if (fs::is_symlink(status) || (fs::exists(status) && !fs::is_directory(status)))
throw FormatError("Unsafe portable directory: " + path_to_utf8(path));
fs::create_directories(path);
}
} // namespace
ModLibrary::ModLibrary(fs::path root) : root_(fs::absolute(std::move(root)).lexically_normal()) {}
void ModLibrary::validate_name(const std::string &name) {
if (name.empty() || name.size() > 100 || name == "." || name == ".." || name.front() == '.' ||
name.back() == '.' || name.back() == ' ')
throw FormatError("Invalid mod name");
for (unsigned char c : name)
if (c < 32 || c == 127 || std::string("/\\:*?\"<>|").find(char(c)) != std::string::npos)
throw FormatError("Invalid character in mod name");
auto base = fold(name.substr(0, name.find('.')));
const std::set<std::string> reserved{"con", "prn", "aux", "nul", "com1", "com2", "com3", "com4",
"com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
"lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9"};
if (reserved.contains(base))
throw FormatError("Reserved mod name");
}
std::vector<ModEntry> ModLibrary::list() const {
std::vector<ModEntry> out;
const auto folder = root_ / "mods";
if (!fs::exists(fs::symlink_status(folder)))
return out;
if (fs::is_symlink(fs::symlink_status(folder)) || !fs::is_directory(folder))
throw FormatError("Unsafe mods directory");
for (const auto &entry : fs::directory_iterator(folder)) {
const auto name = filename(entry.path());
if (name.starts_with('.'))
continue;
if (!entry.is_directory() && !entry.is_symlink())
continue;
ModEntry mod;
mod.name = name;
mod.directory = entry.path();
try {
validate_name(name);
if (entry.is_symlink())
throw FormatError("Linked mod directories are not supported");
for (const auto &child : fs::directory_iterator(entry.path()))
if (child.path().filename() != "content.obw")
throw FormatError("Unexpected files in sealed Classic mod");
const auto content = content::open(entry.path() / "content.obw");
mod.content_id = content->content_id;
} catch (const std::exception &e) {
mod.error = e.what();
}
out.push_back(std::move(mod));
}
std::sort(out.begin(), out.end(),
[](const auto &a, const auto &b) { return fold(a.name) < fold(b.name); });
return out;
}
void ModLibrary::available(const std::string &name) const {
validate_name(name);
const auto folder = root_ / "mods";
if (fs::exists(fs::symlink_status(folder))) {
if (fs::is_symlink(fs::symlink_status(folder)) || !fs::is_directory(folder))
throw FormatError("Unsafe mods directory");
for (const auto &entry : fs::directory_iterator(folder))
if (fold(filename(entry.path())) == fold(name))
throw FormatError("A mod with this name already exists");
}
}
void ModLibrary::owned(const ModEntry &mod) const {
if (mod.directory.parent_path() != root_ / "mods" || filename(mod.directory) != mod.name ||
fs::is_symlink(fs::symlink_status(mod.directory)))
throw FormatError("Mod path is not owned by this library");
}
fs::path ModLibrary::user_directory(const ModEntry &mod) const {
if (mod.content_id.size() != 64 ||
mod.content_id.find_first_not_of("0123456789abcdef") != std::string::npos)
throw FormatError("Invalid mod identity");
safe_directory(root_ / "userdata");
const auto directory = root_ / "userdata" / mod.content_id;
safe_directory(directory);
return directory;
}
ImportReport ModLibrary::add(const AddMod &request, const SaveMigrator &migrate,
const ImportProgress &progress) {
available(request.name);
if (request.start_year < 1900 || request.start_year > 9998)
throw FormatError("Start year must be 1900–9998");
safe_directory(root_ / "mods");
const auto update = [&](const std::string &s) {
if (progress)
progress(s);
};
update("Installation wird konvertiert …");
obw::Options options;
options.start_date = std::to_string(request.start_year) + "-07-01";
options.title = "Classic installation";
auto docs = obw::import_installation(request.source, options);
const auto identity = content::seal(docs);
update("Konvertierte Inhalte werden geprüft …");
const auto staging =
root_ / "mods" /
(".import-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
if (!fs::create_directory(staging))
throw FormatError("Cannot reserve mod staging directory");
struct Cleanup {
fs::path p;
~Cleanup() {
std::error_code ec;
fs::remove_all(p, ec);
}
} cleanup{staging};
content::write_archive(docs, staging / "content.obw");
(void)content::open(staging / "content.obw");
ImportReport report;
report.mod = {request.name, "Classic", identity, {}, root_ / "mods" / path_from_utf8(request.name)};
const auto userdata = user_directory(report.mod);
// User data is retained separately, and never overwrites a previous migration.
if (request.migrate) {
const auto source = request.saves.empty() ? request.source : request.saves;
if (!fs::is_directory(source))
report.errors.push_back("Spielstandsordner ist nicht verfügbar");
else {
std::vector<fs::path> files;
for (const auto &entry : fs::directory_iterator(source))
if (entry.is_regular_file() && !entry.is_symlink())
files.push_back(entry.path());
std::sort(files.begin(), files.end());
for (const auto &input : files) {
const auto ext = fold(path_to_utf8(input.extension()));
if (ext != ".fbm" && ext != ".ein" && ext != ".men")
continue;
update("Übernahme: " + filename(input));
try {
auto destination = userdata / input.stem();
destination += ext == ".fbm" ? ".obs" : ext == ".ein" ? ".obsettings" : ".oblayout";
if (fs::exists(fs::symlink_status(destination)))
throw FormatError("Destination already exists; retained existing file");
if (ext == ".fbm") {
if (!migrate)
throw FormatError("Save migrator unavailable");
migrate(staging / "content.obw", input, destination);
} else {
auto bytes = read_file(input);
if (ext == ".ein" && bytes.size() != 180)
throw FormatError("Invalid settings length");
if (ext == ".men" && bytes.size() != 0x360)
throw FormatError("Invalid desktop layout length");
content::save_preferences(destination, ext == ".ein" ? "settings" : "layout", bytes,
false);
}
++report.migrated;
} catch (const std::exception &e) {
report.errors.push_back(filename(input) + ": " + e.what());
}
}
}
}
update("Mod wird eingetragen …");
available(request.name);
fs::rename(staging, report.mod.directory);
return report;
}
void ModLibrary::rename(const ModEntry &mod, const std::string &name) {
owned(mod);
if (name == mod.name)
return;
available(name);
fs::rename(mod.directory, root_ / "mods" / path_from_utf8(name));
}
void ModLibrary::remove(const ModEntry &mod) {
owned(mod);
fs::remove_all(mod.directory);
}
} // namespace bmh::launch
+41
View File
@@ -0,0 +1,41 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "content/package.hpp"
#include <functional>
namespace bmh::launch {
struct ModEntry {
std::string name, type = "Classic", content_id, error;
std::filesystem::path directory;
};
struct AddMod {
std::filesystem::path source, saves;
std::string name;
int start_year = 2026;
bool migrate = true;
};
using SaveMigrator =
std::function<void(const std::filesystem::path &content, const std::filesystem::path &source,
const std::filesystem::path &destination)>;
using ImportProgress = std::function<void(const std::string &)>;
struct ImportReport {
ModEntry mod;
size_t migrated = 0;
std::vector<std::string> errors;
};
class ModLibrary {
public:
explicit ModLibrary(std::filesystem::path portable_root);
std::vector<ModEntry> list() const;
ImportReport add(const AddMod &, const SaveMigrator &, const ImportProgress &progress = {});
void rename(const ModEntry &, const std::string &name);
void remove(const ModEntry &);
std::filesystem::path user_directory(const ModEntry &) const;
const std::filesystem::path &root() const { return root_; }
static void validate_name(const std::string &);
private:
std::filesystem::path root_;
void available(const std::string &) const;
void owned(const ModEntry &) const;
};
} // namespace bmh::launch
+115
View File
@@ -0,0 +1,115 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "launch/process.hpp"
#include "launch/archive.hpp"
#include <chrono>
#include <thread>
#include <stdexcept>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <spawn.h>
#include <sys/wait.h>
#include <cerrno>
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif
extern char **environ;
#endif
namespace bmh::launch {
std::filesystem::path executable_path(const std::filesystem::path &invocation) {
#ifdef _WIN32
std::vector<wchar_t> buffer(1024);
for (;;) {
const auto length = GetModuleFileNameW(nullptr, buffer.data(), DWORD(buffer.size()));
if (!length)
throw std::runtime_error("Cannot locate OpenBMH executable");
if (length < buffer.size())
return std::filesystem::path(std::wstring(buffer.data(), length));
if (buffer.size() > 32768)
throw std::runtime_error("Executable path is too long");
buffer.resize(buffer.size() * 2);
}
#elif defined(__APPLE__)
uint32_t size = 0;
_NSGetExecutablePath(nullptr, &size);
std::vector<char> buffer(size);
if (_NSGetExecutablePath(buffer.data(), &size) != 0)
throw std::runtime_error("Cannot locate OpenBMH executable");
return std::filesystem::canonical(path_from_utf8(buffer.data()));
#else
std::error_code error;
const auto path = std::filesystem::read_symlink("/proc/self/exe", error);
if (!error)
return path;
return std::filesystem::absolute(invocation).lexically_normal();
#endif
}
int run_child(const std::filesystem::path &executable, const std::vector<std::string> &args,
const std::function<void()> &pump) {
#ifdef _WIN32
const auto quote = [](const std::wstring &value) {
std::wstring out = L"\"";
size_t slashes = 0;
for (wchar_t c : value) {
if (c == L'\\') {
++slashes;
continue;
}
if (c == L'\"')
out.append(slashes * 2 + 1, L'\\');
else
out.append(slashes, L'\\');
out += c;
slashes = 0;
}
out.append(slashes * 2, L'\\');
out += L'\"';
return out;
};
auto command = quote(executable.wstring());
for (const auto &a : args) {
command += L' ';
command += quote(path_from_utf8(a).wstring());
}
STARTUPINFOW start{};
start.cb = sizeof(start);
PROCESS_INFORMATION process{};
if (!CreateProcessW(executable.c_str(), command.data(), nullptr, nullptr, FALSE, 0, nullptr,
executable.parent_path().c_str(), &start, &process))
throw std::runtime_error("Cannot start OpenBMH game process");
CloseHandle(process.hThread);
while (WaitForSingleObject(process.hProcess, 20) == WAIT_TIMEOUT)
if (pump)
pump();
DWORD code = 1;
GetExitCodeProcess(process.hProcess, &code);
CloseHandle(process.hProcess);
return int(code);
#else
const auto binary = path_to_utf8(executable);
std::vector<std::string> storage{binary};
storage.insert(storage.end(), args.begin(), args.end());
std::vector<char *> argv;
for (auto &s : storage)
argv.push_back(s.data());
argv.push_back(nullptr);
pid_t pid;
const int error = posix_spawn(&pid, binary.c_str(), nullptr, nullptr, argv.data(), environ);
if (error)
throw std::runtime_error("Cannot start OpenBMH game process (" + std::to_string(error) + ")");
int status = 0;
for (;;) {
const auto result = waitpid(pid, &status, WNOHANG);
if (result == pid)
break;
if (result < 0 && errno != EINTR)
throw std::runtime_error("Cannot wait for game process");
if (pump)
pump();
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
return WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
#endif
}
} // namespace bmh::launch
+11
View File
@@ -0,0 +1,11 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <filesystem>
#include <functional>
#include <string>
#include <vector>
namespace bmh::launch {
std::filesystem::path executable_path(const std::filesystem::path &invocation);
int run_child(const std::filesystem::path &, const std::vector<std::string> &,
const std::function<void()> &pump);
} // namespace bmh::launch
+35
View File
@@ -0,0 +1,35 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <filesystem>
#include <string>
#include <cstdio>
#include <RmlUi/Core/FileInterface.h>
namespace bmh::rml {
// RmlUI parses document locations as URLs. Native Windows backslashes make
// URL::GetPath() empty, so relative image sources lose their asset directory.
inline std::string asset_path(const std::filesystem::path &path) {
const auto utf8 = path.generic_u8string();
return {utf8.begin(), utf8.end()};
}
// RmlUI paths are UTF-8. The Windows narrow fopen API uses the system code page.
class AssetFiles : public Rml::FileInterface {
public:
Rml::FileHandle Open(const Rml::String &path) override {
#ifdef _WIN32
const std::u8string utf8(path.begin(), path.end());
return reinterpret_cast<Rml::FileHandle>(_wfopen(std::filesystem::path(utf8).c_str(), L"rb"));
#else
return reinterpret_cast<Rml::FileHandle>(std::fopen(path.c_str(), "rb"));
#endif
}
void Close(Rml::FileHandle file) override { std::fclose(reinterpret_cast<FILE *>(file)); }
size_t Read(void *buffer, size_t size, Rml::FileHandle file) override {
return std::fread(buffer, 1, size, reinterpret_cast<FILE *>(file));
}
bool Seek(Rml::FileHandle file, long offset, int origin) override {
return std::fseek(reinterpret_cast<FILE *>(file), offset, origin) == 0;
}
size_t Tell(Rml::FileHandle file) override { return size_t(std::ftell(reinterpret_cast<FILE *>(file))); }
};
} // namespace bmh::rml
+41
View File
@@ -0,0 +1,41 @@
# SPDX-License-Identifier: GPL-3.0-only
# A shared visual layer for the launcher and future modern screens.
set(BUILD_SHARED_LIBS OFF CACHE BOOL "Build dependencies statically" FORCE)
foreach(feature IN ITEMS ZLIB BZIP2 PNG HARFBUZZ BROTLI)
set(FT_DISABLE_${feature} ON CACHE BOOL "Keep the bundled font engine minimal" FORCE)
endforeach()
set(SKIP_INSTALL_ALL ON)
FetchContent_Declare(freetype
GIT_REPOSITORY https://github.com/freetype/freetype.git
GIT_TAG VER-2-13-3 GIT_SHALLOW TRUE GIT_SUBMODULES "")
FetchContent_MakeAvailable(freetype)
if(NOT TARGET Freetype::Freetype)
add_library(Freetype::Freetype ALIAS freetype)
endif()
set(RMLUI_SAMPLES OFF CACHE BOOL "" FORCE)
set(RMLUI_LUA_BINDINGS OFF CACHE BOOL "" FORCE)
set(RMLUI_SVG_PLUGIN OFF CACHE BOOL "" FORCE)
set(RMLUI_LOTTIE_PLUGIN OFF CACHE BOOL "" FORCE)
FetchContent_Declare(rmlui
GIT_REPOSITORY https://github.com/mikke89/RmlUi.git
GIT_TAG 6.3 GIT_SHALLOW TRUE)
FetchContent_MakeAvailable(rmlui)
add_library(bmh_rmlui STATIC
${rmlui_SOURCE_DIR}/Backends/RmlUi_Platform_SDL.cpp
${rmlui_SOURCE_DIR}/Backends/RmlUi_Renderer_GL3.cpp)
target_include_directories(bmh_rmlui PUBLIC ${rmlui_SOURCE_DIR}/Backends)
target_compile_definitions(bmh_rmlui PUBLIC RMLUI_SDL_VERSION_MAJOR=2 RMLUI_NUM_MSAA_SAMPLES=0)
target_link_libraries(bmh_rmlui PUBLIC RmlUi::Core ${BMH_SDL_TARGET} PRIVATE ${CMAKE_DL_LIBS})
# The background is project artwork, and the unmodified fonts come from the
# pinned dependency. All assets are located relative to the executable at runtime.
set(launcher_assets "${CMAKE_BINARY_DIR}/assets/launcher")
file(MAKE_DIRECTORY "${launcher_assets}")
foreach(asset IN ITEMS launcher.rml theme.rcss stadium.tga)
configure_file("${CMAKE_SOURCE_DIR}/assets/launcher/${asset}" "${launcher_assets}/${asset}" COPYONLY)
endforeach()
foreach(weight IN ITEMS Regular Bold)
configure_file("${rmlui_SOURCE_DIR}/Samples/assets/LatoLatin-${weight}.ttf"
"${launcher_assets}/LatoLatin-${weight}.ttf" COPYONLY)
endforeach()
install(DIRECTORY "${launcher_assets}/" DESTINATION assets/launcher COMPONENT Runtime)
+2 -1
View File
@@ -478,7 +478,7 @@ DeskDate desk_date(uint32_t counter, const LeImage& exe) {
d.day -= month_days();
if (++d.month == 13) { d.month = 1; ++years; }
}
d.year = 2026 + years;
d.year = exe.display_start_year() + years;
return d;
}
@@ -518,6 +518,7 @@ DeskState desk_from_game(const GameState& g, const LeImage& exe, uint64_t revisi
// runtime (0x165) suppresses this consumer while manual mailbox access remains valid.
if (d.runtime_club != kNoTeam && d.manager_slot >= 0 && d.manager_slot < 32 && g.memory.has(::bmh::layout::MailboxRecipientMask))
d.mailbox_notification_pending = (g.memory.u32(::bmh::layout::MailboxRecipientMask) & (uint32_t(1) << d.manager_slot)) != 0;
d.date.year += g.display_start_year - exe.display_start_year();
project_table_position(d, g);
if (!current_groups && g.date == 0 && g.season == 0 && g.season_day() == 0 && g.texts) {
const size_t title = (::bmh::layout::DeskState_DeskFromGame_TextPointer - ::bmh::layout::TextPointerTable) / 4 + 33;
+30 -13
View File
@@ -11,11 +11,12 @@
#include "ui/host_path.hpp"
#include "ui/setup.hpp"
#include "formats/fbm.hpp"
#include "content/save.hpp"
namespace bmh::ui {
namespace {
constexpr uint32_t kTextBase = ::bmh::layout::TextPointerTable;
constexpr size_t kFilenameBytes = 251; // Host filename limit, including the four-byte .FBM suffix.
constexpr size_t kHostFilenameBytes = 255; // Includes the selected native or legacy extension.
std::string path_to_utf8(const std::filesystem::path& path) {
const auto value = path.u8string();
return std::string(value.begin(), value.end());
@@ -23,11 +24,10 @@ std::string path_to_utf8(const std::filesystem::path& path) {
std::filesystem::path path_from_utf8(std::string_view value) {
return std::filesystem::path(std::u8string(value.begin(), value.end()));
}
bool valid_filename(std::string_view value) {
return !value.empty() && value.size() <= kFilenameBytes && value != "." && value != ".." &&
std::all_of(value.begin(), value.end(), [](unsigned char c) {
return c >= 32 && c != 127 && c != '/' && c != '\\';
});
bool valid_filename(std::string_view value, size_t maximum) {
return !value.empty() && value.size() <= maximum && value != "." && value != ".." &&
std::all_of(value.begin(), value.end(),
[](unsigned char c) { return c >= 32 && c != 127 && c != '/' && c != '\\'; });
}
std::string_view text_at(const TextDb& texts, uint32_t address) {
if (address < kTextBase || ((address - kTextBase) & 3u) != 0)
@@ -38,13 +38,21 @@ void rect(Image& image, int x, int y, int w, int h, uint8_t color) {
for (int yy = std::max(0, y); yy < std::min(image.height, y + h); ++yy)
for (int xx = std::max(0, x); xx < std::min(image.width, x + w); ++xx) image.at(xx, yy) = color;
}
bool has_file_kind_extension(const std::filesystem::path& path, SaveLoadFileKind kind) {
bool has_file_kind_extension(const std::filesystem::path &path, SaveLoadFileKind kind, bool native) {
std::string ext = path_to_utf8(path.extension());
std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return char(std::tolower(c)); });
if (native)
return ext == (kind == SaveLoadFileKind::menu_layout ? ".oblayout"
: kind == SaveLoadFileKind::settings ? ".obsettings"
: ".obs");
return ext == (kind == SaveLoadFileKind::menu_layout ? ".men" :
kind == SaveLoadFileKind::settings ? ".ein" : ".fbm");
}
std::string_view file_kind_extension(SaveLoadFileKind kind) {
std::string_view file_kind_extension(SaveLoadFileKind kind, bool native) {
if (native)
return kind == SaveLoadFileKind::menu_layout ? ".oblayout"
: kind == SaveLoadFileKind::settings ? ".obsettings"
: ".obs";
return kind == SaveLoadFileKind::menu_layout ? ".MEN" :
kind == SaveLoadFileKind::settings ? ".EIN" : ".FBM";
}
@@ -85,13 +93,14 @@ SaveLoadScreen::SaveLoadScreen(const std::filesystem::path& data, std::filesyste
throw FormatError("save/load: unsupported state");
if (widgets_.width != 77 || widgets_.height != 112 || font_.height != 8 || footer_font_.height != 6)
throw FormatError("save/load: unsupported Original font or widget atlas");
native_ = bool(content::find(data));
std::error_code ec;
if (std::filesystem::is_directory(directory_, ec)) {
for (std::filesystem::directory_iterator it(directory_, ec), end; !ec && it != end; it.increment(ec)) {
std::error_code file_error;
const auto status = it->symlink_status(file_error);
if (!file_error && std::filesystem::is_regular_file(status) &&
has_file_kind_extension(it->path(), file_kind_))
has_file_kind_extension(it->path(), file_kind_, native_))
entries_.push_back({it->path()});
}
std::sort(entries_.begin(), entries_.end(), [](const auto& a, const auto& b) {
@@ -183,7 +192,13 @@ bool SaveLoadScreen::info_press(int x, int y) {
if (file_kind_ != SaveLoadFileKind::game || pending_ || info_ || x <= 52 || x >= 200 || y <= 40 ||
y >= 192 || !select_row(y)) return false;
try {
const auto saved = load_savegame(entries_.at(size_t(selected_)).path);
Savegame saved;
if (native_) {
saved.plain_header = content::save_information(entries_.at(size_t(selected_)).path);
saved.version = "V2.24";
saved.checksum_ok = true;
} else
saved = load_savegame(entries_.at(size_t(selected_)).path);
const auto& h = saved.plain_header;
if (!saved.checksum_ok || saved.version != "V2.24" || h.size() < 172 || h[0] < 1 || h[0] > 4)
throw FormatError("save/load: invalid native information header");
@@ -303,10 +318,11 @@ void SaveLoadScreen::request_action() {
entries_[size_t(selected_)].path, false, file_kind_, origin_item_id_};
return;
}
if (!valid_filename(filename_)) {
if (!valid_filename(filename_, kHostFilenameBytes - file_kind_extension(file_kind_, native_).size())) {
feedback_ = "UNGUELTIGER DATEINAME"; return;
}
auto path = directory_ / path_from_utf8(filename_ + std::string(file_kind_extension(file_kind_)));
auto path =
directory_ / path_from_utf8(filename_ + std::string(file_kind_extension(file_kind_, native_)));
// Selecting an existing mixed-case extension must overwrite that same file.
if (selected_ >= 0 && size_t(selected_) < entries_.size() &&
path_to_utf8(entries_[size_t(selected_)].path.stem()) == filename_)
@@ -380,7 +396,8 @@ bool SaveLoadScreen::key(std::string_view value) {
bool SaveLoadScreen::text(std::string_view value) {
if (info_ || mode_ != SaveLoadMode::save || !filename_focus_ || pending_ || value.empty()) return false;
const std::string next = (filename_selected_ ? std::string{} : filename_) + std::string(value);
if (!valid_filename(next)) return false;
if (!valid_filename(next, kHostFilenameBytes - file_kind_extension(file_kind_, native_).size()))
return false;
filename_ = next; filename_selected_ = false;
overwrite_armed_ = false; feedback_.clear(); return true;
}
+1
View File
@@ -67,6 +67,7 @@ private:
TextDb texts_;
SpriteFont sprite_font_;
Font footer_font_;
bool native_ = false;
bool gradient_text_ = true;
std::vector<SaveLoadEntry> entries_;
int selected_ = 0, scroll_ = 0;
+21 -11
View File
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "ui/settings.hpp"
#include "formats/content.hpp"
#include <algorithm>
#include <cctype>
@@ -304,18 +305,27 @@ SettingsReadmeScreen::SettingsReadmeScreen(const std::filesystem::path& data,
// DOS resolves it case-insensitively; also try its uppercase spelling on
// case-sensitive host filesystems.
const std::filesystem::path source_name(texts_[839]);
std::ifstream file(data / source_name, std::ios::binary);
if (!file) {
auto uppercase_name = source_name.string();
std::transform(uppercase_name.begin(), uppercase_name.end(), uppercase_name.begin(),
[](unsigned char c) { return char(std::toupper(c)); });
file.open(data / uppercase_name, std::ios::binary);
if (const auto resource = content::find(data / source_name)) {
const auto it = resource->content->supplemental.find(resource->key);
if (it == resource->content->supplemental.end())
return;
file_available_ = true;
content_.assign(it->second.begin(), it->second.begin() + std::min(size_t(20000), it->second.size()));
} else {
std::ifstream file(data / source_name, std::ios::binary);
if (!file) {
auto uppercase_name = source_name.string();
std::transform(uppercase_name.begin(), uppercase_name.end(), uppercase_name.begin(),
[](unsigned char c) { return char(std::toupper(c)); });
file.open(data / uppercase_name, std::ios::binary);
}
if (!file)
return;
file_available_ = true;
std::array<char, 20000> bytes{};
file.read(bytes.data(), std::streamsize(bytes.size()));
content_.assign(bytes.data(), size_t(file.gcount()));
}
if (!file) return;
file_available_ = true;
std::array<char, 20000> bytes{};
file.read(bytes.data(), std::streamsize(bytes.size()));
content_.assign(bytes.data(), size_t(file.gcount()));
pages_.emplace_back();
int x = 0, baseline = 19;
bool emphasized = false, new_page_before_next_byte = false;
+3
View File
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "ui/setup.hpp"
#include "formats/content.hpp"
#include <algorithm>
#include <cctype>
@@ -30,6 +31,8 @@ void copy_rect(Image& dst, const Image& src, int sx, int sy, int dx, int dy,
} // namespace
std::filesystem::path asset_path(const std::filesystem::path& directory, const std::string& name) {
if (content::find(directory / name))
return directory / name;
std::filesystem::path found;
for (const auto& e : std::filesystem::directory_iterator(directory)) {
if (e.is_regular_file() && folded(e.path().filename().string()) == folded(name)) {
+9
View File
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "ui/sportschau.hpp"
#include "formats/content.hpp"
#include <algorithm>
#include <array>
@@ -89,6 +90,14 @@ Image load_kb(const std::filesystem::path& data_directory, const char* file) {
}
std::optional<Palette> load_optional_embedded_palette(const std::filesystem::path& path) {
if (const auto resource = content::find(path)) {
auto name = std::filesystem::path(resource->key);
name.replace_extension();
const auto it = resource->content->image_palettes.find(name.generic_string());
if (it == resource->content->image_palettes.end())
return std::nullopt;
return it->second;
}
const Bytes bytes = read_file(path);
if (bytes.size() < 8) throw FormatError("sportschau: VGA palette source is truncated");
const size_t rle_end = 8 + size_t(le32(bytes, 4));