From 73af2a657df5fa0ee4624d2405653da81669e4bf Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 6 Nov 2026 11:21:31 +0100 Subject: [PATCH] Explain the stadium, transfer, contract and application code in comments Function and section comments for ui/stadium, ui/preparation_flow, the transfer market, contract, outgoing and incoming transfer screens, and for app/main, app/window_actions and app/desktop_actions. Comment lines only; full build and runnable tests unchanged. Co-Authored-By: Claude Sonnet 5.5 --- src/app/desktop_actions.cpp | 77 +++++++ src/app/main.cpp | 397 +++++++++++++++++++++++++++++++++++ src/app/window_actions.cpp | 64 ++++++ src/ui/contracts.cpp | 85 ++++++++ src/ui/incoming_transfer.cpp | 59 ++++++ src/ui/outgoing_transfer.cpp | 55 +++++ src/ui/preparation_flow.cpp | 251 ++++++++++++++++++++++ src/ui/stadium.cpp | 209 ++++++++++++++++++ src/ui/transfer_market.cpp | 84 ++++++++ 9 files changed, 1281 insertions(+) diff --git a/src/app/desktop_actions.cpp b/src/app/desktop_actions.cpp index ee1729b..1957a3c 100644 --- a/src/app/desktop_actions.cpp +++ b/src/app/desktop_actions.cpp @@ -13,6 +13,8 @@ namespace bmh::app { +// Builds the desk request that opens menu `kind` for the observed manager; the item id is +// taken from the desk item of that kind. ui::DeskRequest DesktopActions::menu(const ui::DeskState& observed, int kind) { ui::DeskRequest request; request.kind = ui::DeskRequestKind::open_menu; @@ -24,6 +26,8 @@ ui::DeskRequest DesktopActions::menu(const ui::DeskState& observed, int kind) { return request; } +// Runs `action` as a transaction on the desk settings owner; the checkpoint is restored +// if the action fails. bool DeskSettingsActions::apply(uint64_t& revision, const std::function& action) { return detail::apply_window(session_, revision, session_.desk_settings_checkpoint(revision), [&](CareerSession::DeskSettingsCheckpoint before) { @@ -31,6 +35,7 @@ bool DeskSettingsActions::apply(uint64_t& revision, const std::function& }, action); } +// Opens the desk settings screen; `acknowledge` receives the projection on success. std::optional DeskSettingsActions::open( const ui::DeskRequest& request, uint64_t& revision, std::string& error, const OpenAccept& acknowledge) { std::optional result; @@ -43,6 +48,7 @@ std::optional DeskSettingsActions::open( return result; } +// Sends any settings action (write, file, close) to the session in one transaction. std::optional DeskSettingsActions::dispatch( const CareerSession::DeskSettingsAction& request, uint64_t& revision, std::string& error, const Accept& acknowledge) { @@ -56,16 +62,19 @@ std::optional DeskSettingsActions::dispatch return result; } +// Dispatches a settings write for the owner identified by `sequence`. std::optional DeskSettingsActions::write(uint64_t sequence, const ui::SettingsWriteRequest& request, uint64_t& revision, std::string& error, const Accept& acknowledge) { return dispatch(CareerSession::DeskSettingsWrite{sequence, request}, revision, error, acknowledge); } +// Dispatches a settings file (save/load) request for the owner `sequence`. std::optional DeskSettingsActions::file(uint64_t sequence, const ui::SaveLoadRequest& request, uint64_t& revision, std::string& error, const Accept& acknowledge) { return dispatch(CareerSession::DeskSettingsFile{sequence, request}, revision, error, acknowledge); } +// Dispatches the close of the settings owner, built from the observed desk request. std::optional DeskSettingsActions::close(uint64_t sequence, uint64_t owner_revision, const ui::DeskRequest& observed, uint64_t& revision, std::string& error, const Accept& acknowledge) { @@ -73,6 +82,8 @@ std::optional DeskSettingsActions::close(ui return dispatch(CareerSession::DeskSettingsClose{owner}, revision, error, acknowledge); } +// Applies one edit (row, column, operation) to the settings cells; the request carries +// the observed cells so that a stale view is detected. bool DeskSettingsActions::edit(const ui::SettingsState& observed, int row, int column, ui::SettingsEdit operation, uint64_t& revision, std::string& error) { ui::SettingsWriteRequest request; @@ -85,11 +96,13 @@ bool DeskSettingsActions::edit(const ui::SettingsState& observed, int row, int c return apply(revision, [&] { return session_.dispatch_settings(request, revision, error); }); } +// Runs `action` as a transaction restoring the balance checkpoint on failure. bool BalanceActions::apply(uint64_t& revision, const std::function& action) { return detail::apply_window(session_, revision, session_.balance_checkpoint(), [&](CareerSession::BalanceCheckpoint before) { session_.restore_balance_checkpoint(std::move(before)); }, action); } +// Opens the balance (finance plan) screen over `underlay`. std::optional BalanceActions::open(const ui::DeskRequest& request, uint64_t& revision, const Image& underlay, std::string& error, const OpenAccept& acknowledge) { std::optional result; @@ -102,6 +115,7 @@ std::optional BalanceActions::open(const ui::DeskRequest& requ return result; } +// Sends a balance screen request to the session in one transaction. std::optional BalanceActions::dispatch(const ui::BalanceRequest& request, uint64_t& revision, std::string& error, const Accept& acknowledge) { std::optional result; @@ -114,13 +128,20 @@ std::optional BalanceActions::dispatch(const ui: return result; } +// Draft helpers for the console balance plan (thin wrappers around the game functions): +// open a draft for a manager, BalancePlanDraft BalanceActions::open_draft(int manager) const { return bmh::open_balance_plan(session_.state(), manager); } +// switch its view, void BalanceActions::cycle_draft(BalancePlanDraft& draft) const { cycle_balance_view(session_.state(), draft); } +// reset it, void BalanceActions::reset_draft(BalancePlanDraft& draft) const { reset_balance_plan(session_.state(), draft); } +// and edit one row. BalanceEditStatus BalanceActions::edit_draft(BalancePlanDraft& draft, int row, int32_t value) const { return edit_balance_plan(session_.state(), draft, row, value); } +// Closes the draft inside a transaction and always increases the revision. Returns the +// warning flag reported by the close. bool BalanceActions::close_draft(const BalancePlanDraft& draft, uint64_t& revision) { bool warning = false; apply(revision, [&] { @@ -131,11 +152,13 @@ bool BalanceActions::close_draft(const BalancePlanDraft& draft, uint64_t& revisi return warning; } +// Runs `action` as a transaction restoring the other-games checkpoint on failure. bool OtherGamesActions::apply(uint64_t& revision, const std::function& action) { return detail::apply_window(session_, revision, session_.other_games_checkpoint(), [&](CareerSession::OtherGamesCheckpoint before) { session_.restore_other_games_checkpoint(std::move(before)); }, action); } +// Opens the other-games screen over `underlay`. std::optional OtherGamesActions::open(const ui::DeskRequest& request, uint64_t& revision, const Image& underlay, std::string& error, const OpenAccept& acknowledge) { std::optional result; @@ -148,6 +171,8 @@ std::optional OtherGamesActions::open(const ui::DeskRequest return result; } +// Sends an other-games request to the session; `team_info` presents club information +// when the screen asks for it. std::optional OtherGamesActions::dispatch(const ui::OtherGamesRequest& request, uint64_t& revision, std::string& error, const TransferOfferTeamInfoPresenter& team_info, const Accept& acknowledge) { std::optional result; @@ -160,11 +185,13 @@ std::optional OtherGamesActions::dispatch(con return result; } +// Runs `action` as a transaction restoring the top scorers checkpoint on failure. bool TopScorersActions::apply(uint64_t& revision, const std::function& action) { return detail::apply_window(session_, revision, session_.top_scorers_checkpoint(), [&](CareerSession::TopScorersCheckpoint before) { session_.restore_top_scorers_checkpoint(std::move(before)); }, action); } +// Opens the top scorers screen over `underlay`; the revision is increased on opening. std::optional TopScorersActions::open(const ui::DeskRequest& request, uint64_t& revision, const Image& underlay, std::string& error, const OpenAccept& acknowledge) { std::optional result; @@ -178,6 +205,7 @@ std::optional TopScorersActions::open(const ui::DeskRequest return result; } +// Sends a top scorers request to the session in one transaction. std::optional TopScorersActions::dispatch(const ui::TopScorersRequest& request, uint64_t& revision, std::string& error, const Accept& acknowledge) { std::optional result; @@ -190,11 +218,13 @@ std::optional TopScorersActions::dispatch(con return result; } +// Runs `action` as a transaction restoring the opportunities checkpoint on failure. bool OpportunitiesActions::apply(uint64_t& revision, const std::function& action) { return detail::apply_window(session_, revision, session_.opportunities_checkpoint(), [&](CareerSession::OpportunitiesCheckpoint before) { session_.restore_opportunities_checkpoint(std::move(before)); }, action); } +// Opens the opportunities screen over `underlay`; the revision is increased on opening. std::optional OpportunitiesActions::open(const ui::DeskRequest& request, uint64_t& revision, const Image& underlay, std::string& error, bool national_source_case, int stable_identity, const OpenAccept& acknowledge) { @@ -209,6 +239,7 @@ std::optional OpportunitiesActions::open(const ui::DeskR return result; } +// Sends an opportunities request to the session in one transaction. std::optional OpportunitiesActions::dispatch(const ui::OpportunitiesRequest& request, uint64_t& revision, std::string& error, const Accept& acknowledge) { std::optional result; @@ -221,6 +252,8 @@ std::optional OpportunitiesActions::dispat return result; } +// Stores a changed statistics display preference (expected flags to target flags) and +// increases the revision; throws if the revision counter is exhausted. bool OpportunitiesActions::preference(const ui::AnalyticsRequest& request, uint64_t& revision, std::string& error, const std::function& acknowledge) { return apply(revision, [&] { @@ -233,15 +266,18 @@ bool OpportunitiesActions::preference(const ui::AnalyticsRequest& request, uint6 }); } +// Builds the request that closes the observed opportunities screen. ui::OpportunitiesRequest OpportunitiesActions::close_request(const ui::OpportunitiesState& observed) { return {observed.identity, ui::OpportunitiesAction::close, observed.mode}; } +// Runs `action` as a transaction restoring the manager join checkpoint on failure. bool ManagerJoinActions::apply(uint64_t& revision, const std::function& action) { return detail::apply_window(session_, revision, session_.manager_join_checkpoint(), [&](CareerSession::ManagerJoinCheckpoint before) { session_.restore_manager_join_checkpoint(std::move(before)); }, action); } +// Commits a new manager joining the career; `acknowledge` receives the initialization result. bool ManagerJoinActions::commit(uint64_t& revision, std::string& error, const std::function& acknowledge) { return apply(revision, [&] { @@ -252,6 +288,7 @@ bool ManagerJoinActions::commit(uint64_t& revision, std::string& error, }); } +// Sends a mailbox action (via the native transaction wrapper) and acknowledges it. bool MailboxActions::dispatch(const ui::MailboxActionRequest& request, uint64_t& revision, std::string& error, const std::function& acknowledge) { return detail::apply_native(session_, revision, [&] { @@ -261,6 +298,7 @@ bool MailboxActions::dispatch(const ui::MailboxActionRequest& request, uint64_t& }); } +// Acknowledges the closing of the mailbox. bool MailboxActions::close(const ui::MailboxCloseRequest& request, uint64_t& revision, std::string& error, const std::function& acknowledge) { return detail::apply_native(session_, revision, [&] { @@ -270,6 +308,7 @@ bool MailboxActions::close(const ui::MailboxCloseRequest& request, uint64_t& rev }); } +// Builds a mailbox action request for the observed message (entry index and raw entry). ui::MailboxActionRequest MailboxActions::request(int manager, uint64_t revision, ui::MailboxActionKind kind, const ui::MailboxMessage& observed) { ui::MailboxActionRequest request; @@ -281,6 +320,7 @@ ui::MailboxActionRequest MailboxActions::request(int manager, uint64_t revision, return request; } +// Sends a menu layout save/load request and acknowledges it. bool MenuLayoutActions::dispatch(const ui::SaveLoadRequest& request, uint64_t& revision, std::string& error, const std::function& acknowledge) { return detail::apply_native(session_, revision, [&] { @@ -290,16 +330,22 @@ bool MenuLayoutActions::dispatch(const ui::SaveLoadRequest& request, uint64_t& r }); } +// Sets one environment item through set_impl (normal UI path). std::optional EnvironmentActions::set(const ui::EnvironmentRequest& request, uint64_t& revision, std::string& error, const Notice& notice, const std::function& acknowledge) { return set_impl(request, revision, error, notice, acknowledge, false); } +// Console variant of set(): the staged state is published even if nothing changed. std::optional EnvironmentActions::set_console(const ui::EnvironmentView& observed, int item, int level, uint64_t& revision, std::string& error, const Notice& notice) { return set_impl(request(observed, item, level), revision, error, notice, {}, true); } +// Shared implementation. The request must match the current revision, manager slot +// (0..3), active manager and club, otherwise error is "stale_environment_owner". The change +// is made on a staged copy; a notice callback may abort it. The revision increases only +// when something changed. Returns nothing if the transaction was not accepted. std::optional EnvironmentActions::set_impl(const ui::EnvironmentRequest& request, uint64_t& revision, std::string& error, const Notice& notice, const std::function& acknowledge, bool publish_console_result) { @@ -339,6 +385,7 @@ std::optional EnvironmentActions::set_impl(const ui::Environm return result; } +// Builds a set_item request for `item` and `level` bound to the observed view. ui::EnvironmentRequest EnvironmentActions::request(const ui::EnvironmentView& observed, int item, int level) { ui::EnvironmentRequest request; request.kind = ui::EnvironmentRequestKind::set_item; @@ -351,10 +398,12 @@ ui::EnvironmentRequest EnvironmentActions::request(const ui::EnvironmentView& ob return request; } +// Runs `action` through the native transaction wrapper. bool RescheduleActions::apply(uint64_t& revision, const std::function& action) { return detail::apply_native(session_, revision, action); } +// Moves a league match to `day` or undoes a move; any other combination is invalid. RescheduleStatus RescheduleActions::change(GameState& state, int manager, const LeagueMatchRef& match, int day, ui::RescheduleActionKind kind) { if (kind == ui::RescheduleActionKind::move) return reschedule_league_match(state, manager, match, day); @@ -362,6 +411,9 @@ RescheduleStatus RescheduleActions::change(GameState& state, int manager, const return RescheduleStatus::invalid_match; } +// Handles a UI reschedule action: the owner must be the open menu 7 for the current +// revision and active manager, and the match must be among the eligible (or already moved) +// matches. The state changes only when the move succeeds. RescheduleStatus RescheduleActions::dispatch(const ui::RescheduleAction& request, uint64_t& revision, const std::function& acknowledge) { auto status = RescheduleStatus::invalid_match; @@ -385,6 +437,7 @@ RescheduleStatus RescheduleActions::dispatch(const ui::RescheduleAction& request return status; } +// Moves a match directly (console path); the revision increases on success. RescheduleStatus RescheduleActions::move(int manager, const LeagueMatchRef& match, int day, uint64_t& revision) { auto status = RescheduleStatus::invalid_match; apply(revision, [&] { @@ -396,6 +449,7 @@ RescheduleStatus RescheduleActions::move(int manager, const LeagueMatchRef& matc return status; } +// Console undo; the revision always increases, whatever the result of the undo. void RescheduleActions::undo_console(int manager, int day, uint64_t& revision) { apply(revision, [&] { // Keep the Console's existing accepted-command revision after its own @@ -406,6 +460,8 @@ void RescheduleActions::undo_console(int manager, int day, uint64_t& revision) { }); } +// Sends a contract request to the session. If an exception follows an accepted request, +// the pending contract quote is cleared before rethrowing. bool ContractActions::dispatch(const ui::ContractRequest& request, uint64_t& revision, ui::ContractActionResult& result, std::string& error, const std::function& acknowledge) { bool accepted = false; @@ -423,6 +479,7 @@ bool ContractActions::dispatch(const ui::ContractRequest& request, uint64_t& rev } } +// Creates a contract request of `kind` bound to the observed manager, club and revision. ui::ContractRequest ContractActions::bind(const ui::ContractsState& observed, ui::ContractActionKind kind, uint64_t request_id) { ui::ContractRequest request; @@ -434,6 +491,7 @@ ui::ContractRequest ContractActions::bind(const ui::ContractsState& observed, return request; } +// Request for a player's contract demands (row and player id). ui::ContractRequest ContractActions::demands(const ui::ContractsState& observed, const ui::ContractPlayer& player, uint64_t request_id) { auto request = bind(observed, ui::ContractActionKind::request_demands, request_id); @@ -442,6 +500,7 @@ ui::ContractRequest ContractActions::demands(const ui::ContractsState& observed, return request; } +// Request that sets team bonus `index` to `percent`, keeping the other proposed premiums. ui::ContractRequest ContractActions::team_bonus(const ui::ContractsState& observed, int index, uint8_t percent, uint64_t request_id) { auto request = bind(observed, ui::ContractActionKind::submit_bonuses, request_id); @@ -450,6 +509,7 @@ ui::ContractRequest ContractActions::team_bonus(const ui::ContractsState& observ return request; } +// Request to insure a player (quote, insurance form in the term column, months). ui::ContractRequest ContractActions::insurance(const ui::ContractsState& observed, int row, int player, uint64_t quote, uint8_t form, uint8_t months, uint64_t request_id) { auto request = bind(observed, ui::ContractActionKind::insure_player, request_id); @@ -458,6 +518,8 @@ ui::ContractRequest ContractActions::insurance(const ui::ContractsState& observe return request; } +// Request for a contract offer. With years > 0 it is an offer for that term (salary and +// the matching demand); with 0 years only the bonuses are submitted. ui::ContractRequest ContractActions::offer(const ui::ContractsState& observed, int row, int player, uint64_t quote, const std::array& bonuses, int years, uint32_t salary, const std::array& demands, uint64_t request_id) { @@ -472,10 +534,12 @@ ui::ContractRequest ContractActions::offer(const ui::ContractsState& observed, i return request; } +// Runs `action` through the native transaction wrapper. bool FriendlyActions::apply(uint64_t& revision, const std::function& action) { return detail::apply_native(session_, revision, action); } +// Converts the UI's friendly match request into the engine's booking request. FriendlyBookingRequest FriendlyActions::booking_request(const ui::FriendlyMatchRequest& observed) { FriendlyBookingQuote quote; quote.status = FriendlyQuoteStatus::quoted; @@ -493,6 +557,7 @@ FriendlyBookingRequest FriendlyActions::booking_request(const ui::FriendlyMatchR observed.accept_cost, observed.approving_manager}; } +// Builds the acknowledgement for the UI from the booking outcome and the new revision. ui::FriendlyBookingAck FriendlyActions::acknowledgement(const ui::FriendlyMatchRequest& request, const FriendlyBookingResult& outcome, uint64_t revision) const { ui::FriendlyBookingAck ack; @@ -505,6 +570,9 @@ ui::FriendlyBookingAck FriendlyActions::acknowledgement(const ui::FriendlyMatchR return ack; } +// Books a friendly match (club or national). The request must be a book request for the +// current revision, otherwise the quote is stale. After booking, the planner count must +// have grown by 2, else the booking is rolled back and planner_mismatch is set. FriendlyActions::Booking FriendlyActions::book(const ui::FriendlyMatchRequest& request, uint64_t& revision, bool national, const Accept& acknowledge) { Booking result; @@ -532,11 +600,14 @@ FriendlyActions::Booking FriendlyActions::book(const ui::FriendlyMatchRequest& r return result; } +// Books a club friendly. FriendlyActions::Booking FriendlyActions::book_club(const ui::FriendlyMatchRequest& request, uint64_t& revision, const Accept& acknowledge) { return book(request, revision, false, acknowledge); } +// Books a national team friendly. FriendlyActions::Booking FriendlyActions::book_national(const ui::FriendlyMatchRequest& request, uint64_t& revision, const Accept& acknowledge) { return book(request, revision, true, acknowledge); } +// Console booking from an existing quote; the revision increases when it was booked. FriendlyBookingResult FriendlyActions::book_console(const FriendlyBookingQuote& quote, uint16_t day, bool accept_opponent, int consenting_manager, bool accept_cost, int approving_manager, uint64_t& revision) { FriendlyBookingResult result; @@ -550,19 +621,25 @@ FriendlyBookingResult FriendlyActions::book_console(const FriendlyBookingQuote& return result; } +// Quote functions (thin wrappers over the game functions): club friendly quote, FriendlyBookingQuote FriendlyActions::quote(int manager, int opponent, bool home) const { return quote_friendly_match(session_.state(), manager, opponent, home); } +// national friendly quote (uses the random generator), NationalFriendlyQuote FriendlyActions::national_quote(const NationalFriendlyOwner& owner, int opponent, bool home) { return quote_national_friendly_match(session_.state(), owner, opponent, home, session_.rand()); } +// whether a club friendly can be played on a day, FriendlyDateStatus FriendlyActions::date_status(const FriendlyBookingQuote& quote, uint16_t day) const { return friendly_match_date_status(session_.state(), quote, day); } +// the same for a national friendly, FriendlyDateStatus FriendlyActions::national_date_status(const NationalFriendlyQuote& quote, const NationalFriendlyOwner& owner, uint16_t day) const { return national_friendly_match_date_status(session_.state(), quote, owner, session_.rand(), day); } +// and the owner identity of a national friendly built from the request (the last two +// fields are fixed constants). NationalFriendlyOwner FriendlyActions::national_owner(const ui::FriendlyMatchRequest& request) { return {request.quote_id, request.revision, request.manager_slot, 0x165, 6}; } diff --git a/src/app/main.cpp b/src/app/main.cpp index d4cfc9c..0054132 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -91,6 +91,8 @@ namespace fs = std::filesystem; using namespace bmh; // Why the game cannot start: a message box, and the same text on stderr. +// Reports a fatal startup problem: prints it to stderr and shows it in a message box. +// Called for failures before or while the window is being set up. static void show_start_error(const std::string& text) { std::fprintf(stderr, "%s\n", text.c_str()); SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "OpenBMH", text.c_str(), nullptr); @@ -98,6 +100,9 @@ static void show_start_error(const std::string& text) { // Reattach the native editor when an in-game filename field takes focus. Cocoa // owns a field-editor responder in addition to SDL's TEXTINPUT enable flag. +// Moves the platform text-input rectangle over the save-file name field (logical canvas +// coordinates 106,209 to 262,219 converted to window pixels) and restarts text input. +// Called when an in-game filename field gains focus. static void focus_filename_input(SDL_Renderer* renderer) { int left, top, right, bottom; SDL_RenderLogicalToWindow(renderer, 106, 209, &left, &top); @@ -112,6 +117,7 @@ static void focus_filename_input(SDL_Renderer* renderer) { // The game is a Windows GUI program (no console window on double-click). Started from a // console, it writes --version, --help and start errors there (kernel32 AttachConsole). extern "C" __declspec(dllimport) int __stdcall AttachConsole(unsigned long process_id); +// Windows only: reconnects stdout/stderr to the parent console when they are not valid streams. static void attach_parent_console() { // (an output redirected to a file or pipe stays there; a GUI program without one has no // valid stream, fileno < 0) @@ -126,6 +132,12 @@ static void attach_parent_console() { static void attach_parent_console() {} #endif +// ===================================================================================== +// Startup and option parsing +// ===================================================================================== +// Program entry. Order of work: parse the command line, find and validate the game data, +// start the optional debug log, then build the window/renderer/audio and the presenter +// lambdas, and finally run the main event loop. int main(int argc, char** argv) { attach_parent_console(); const std::vector args = launch::utf8_arguments(argc, argv); // (file names beyond the code page) @@ -134,11 +146,16 @@ int main(int argc, char** argv) { bool muted = false, music_enabled = true, debug_mode = false; int live_frame_ms = 0; bool live_frame_ms_explicit = false; + // Optional environment default for the pause per live-match frame; --live-frame-ms below + // may override it. if (const char* configured = std::getenv("BMH_LIVE_FRAME_MS")) { live_frame_ms = std::clamp(std::atoi(configured), 0, 1000); live_frame_ms_explicit = true; } float volume = 1.0F; + // Option loop (index 0 is the program name). Options that take a value only match when + // another argument follows ("value"); a first plain argument that does not start with + // "--" is taken as the game location unless --data already set it. for (size_t i = 1; i < args.size(); ++i) { const auto is = [&](const char* name) { return args[i] == name; }; const bool value = i + 1 < args.size(); @@ -172,6 +189,7 @@ int main(int argc, char** argv) { data = launch::path_from_utf8(args[i]); } } + // Start the video session now; a failure is reported to the user and ends the program. std::optional video; try { video.emplace(); } catch (const std::exception& error) { show_start_error(error.what()); return 1; } @@ -201,6 +219,8 @@ int main(int argc, char** argv) { return 1; } } + // Validate the chosen game data; the resolved directory (possibly an unpacked cache copy) + // replaces `data` from here on. 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()); @@ -220,6 +240,11 @@ int main(int argc, char** argv) { SDL_version linked; SDL_GetVersion(&linked); app::debug::log("SDL " + std::to_string(linked.major) + "." + std::to_string(linked.minor) + "." + std::to_string(linked.patch) + ", platform " + SDL_GetPlatform()); } + // ===================================================================================== + // Window, renderer, audio and shared UI state + // ===================================================================================== + // Everything below lives inside this try block; an exception thrown during setup or the + // main loop ends in the catch handler at the end of main. try { const Palette palette = load_palette(ui::asset_path(data, "M3PC.COL")); ui::StartupFlow flow(data, save_directory); @@ -234,12 +259,17 @@ int main(int argc, char** argv) { SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0"); const std::string window_title = std::string("OpenBMH ") + bmh::kOpenBmhVersion + (english_game ? " - Football Limited (experimental)" : ""); + // 960x720 initial window = 3 times the 320x240 game canvas; resizable and high-DPI aware. SDL_Window* window = SDL_CreateWindow(window_title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 960, 720, SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); if (!window) throw FormatError(SDL_GetError()); + // Prefer a vsynced renderer, fall back to the software renderer. SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC); if (!renderer) renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE); if (!renderer) throw FormatError(SDL_GetError()); + // The game always draws a 320x240 canvas; SDL scales it to the window and maps mouse + // coordinates back to these logical units. SDL_RenderSetLogicalSize(renderer, 320, 240); + // Streaming texture that holds the current canvas as ARGB (filled from `pixels`). SDL_Texture* texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, 320, 240); if (!texture) throw FormatError(SDL_GetError()); app::PitchPointer pitch_pointer; @@ -278,11 +308,13 @@ int main(int argc, char** argv) { app::OriginalMouseSound mouse_sound(playback); const auto season_texts = load_textd(ui::asset_path(data, "TEXTD.BLK")); const auto process_clock_origin = std::chrono::steady_clock::now(); + // Seconds since this process started; the time source for the process timer. const auto process_source_seconds = [&] { return uint64_t(std::chrono::duration_cast( std::chrono::steady_clock::now()-process_clock_origin).count()); }; ui::ProcessTimer process_timer; + // Identifies which session/manager/day a process timer belongs to. struct ProcessTimerOwner { uint64_t session; int manager; @@ -291,6 +323,7 @@ int main(int argc, char** argv) { }; std::optional process_timer_owner; std::optional process_timer_frame; + // Returns the image with the process timer bar painted on it while the timer runs. const auto process_timer_image = [&](Image image) { if (!process_timer.paused() && process_timer_frame) ui::ProcessTimer::paint(image, *process_timer_frame, season_exe); @@ -298,6 +331,9 @@ int main(int argc, char** argv) { }; // Sample writes only y0. Nested synchronous presenters poll the // same Desk-owned clock without re-entering Session/Flow dispatch. + // Samples the process timer. When the bar changed and update_texture is set, only the + // top pixel row of the texture is refreshed (and presented if `present`). Returns true + // once the timer has expired. const auto poll_process_timer = [&](bool update_texture, bool present) { const auto sample = process_timer.sample(process_source_seconds()); const bool changed_bar = sample && !sample->expired && @@ -318,7 +354,10 @@ int main(int argc, char** argv) { } return sample && sample->expired; }; + // `running` ends every loop below; `dirty` requests a redraw of the flow screen. bool running = true, dirty = true; + // Remembers the current left mouse press (position, time, screen, source tick, revision) + // so the matching release can be judged against it later. struct Press { int x, y; uint32_t time; @@ -328,6 +367,7 @@ int main(int argc, char** argv) { }; std::optional press; std::optional right_press_screen; + // Converts the engine's transfer offer list into the UI's IncomingTransferDecisionView. auto transfer_view = [](const GameState& state, const TransferOfferListView& offers, int viewer_manager) { ui::IncomingTransferDecisionView view; view.valid = offers.valid; @@ -367,6 +407,8 @@ int main(int argc, char** argv) { return view; }; std::optional season_backdrop; + // Paints a 320x240 indexed image through the palette into the texture and presents it. + // Also sets the window title and remembers the image as the backdrop for later dialogs. auto present_season = [&](const Image& image, const char* title, const Palette* palette_override = nullptr) { SDL_SetWindowTitle(window, title); @@ -379,6 +421,7 @@ int main(int argc, char** argv) { SDL_RenderCopy(renderer, texture, nullptr, nullptr); SDL_RenderPresent(renderer); }; + // Plays the highscore point animation of the desk, one rendered frame per step, if active. const auto present_desk_record_points = [&] { if(!flow.desk_records_points_active())return; while(flow.advance_desk_records_point()) @@ -387,6 +430,10 @@ int main(int argc, char** argv) { present_season(flow.render(),"OpenBMH - highscore"); dirty=false; }; + // Modal contracts screen shown when a player's contract expires. Runs its own event loop + // and applies the player's contract actions to a staged copy of the game state. + // Returns 1 if the expired player was renewed, 0 if not, -2 on quit or error (the staged + // state and random generator are then restored). auto contract_expiry_presenter = [&](GameState& staged, WatcomRandom& random, int manager, int expired_row) -> int { const GameState before = staged; @@ -398,6 +445,7 @@ int main(int argc, char** argv) { ui::ContractsScreen screen(data, std::move(initial)); bool renewed_expired_player = false; bool dirty_contracts = true; + // Modal sub-loop: polls events itself instead of returning to the main loop. while (running) { if (dirty_contracts) { present_season(screen.render(), "OpenBMH - contracts"); @@ -413,6 +461,7 @@ int main(int argc, char** argv) { random = random_before; return -2; } + // Clicks act on button release. if (event.type == SDL_MOUSEBUTTONUP && (event.button.button == SDL_BUTTON_LEFT || event.button.button == SDL_BUTTON_RIGHT)) { changed |= screen.click(event.button.x, event.button.y, @@ -425,11 +474,15 @@ int main(int argc, char** argv) { if (event.key.keysym.sym == SDLK_ESCAPE) changed |= screen.key("ESC"); else if (event.key.keysym.sym == SDLK_BACKSPACE) changed |= screen.key("BACKSPACE"); } + // The screen asks for an engine action (quote, offer, bonuses, insurance); it is validated + // and executed on the staged state, then acknowledged to the screen. Any exception rolls + // the staged state back. if (const ui::ContractRequest* pending = screen.pending()) { const ui::ContractRequest request = *pending; const auto old_game = staged; const auto old_random = random; try { + // Reject requests that do not belong to the current club or row range. if (request.manager_slot != manager || request.runtime_club != staged.manager_teams.at(size_t(manager)) || request.row < 0 || request.row >= 24) throw FormatError("Vertragsaktion gehört nicht zum aktuellen Verein"); @@ -444,6 +497,7 @@ int main(int argc, char** argv) { if (request.term_column >= 4 || request.quote_id != screen.state().quote_id || request.row != screen.state().quote_row || !screen.state().demands || request.demand != (*screen.state().demands)[request.term_column] || + // Stale quote, wrong row or implausibly high salary: refuse. request.monthly_salary > 200000) throw FormatError("Vertragsangebot ist nicht mehr aktuell"); const bool accepted = contract_offer(staged, manager, request.row, @@ -485,6 +539,7 @@ int main(int argc, char** argv) { if (renewed_expired_player && !screen.result_page_open()) return 1; dirty_contracts |= changed; } + // Keep audio streaming while idle, then yield the CPU briefly. if (playback.needs_pump()) playback.pump(audio_error); SDL_Delay(10); } @@ -497,11 +552,14 @@ int main(int argc, char** argv) { return -2; } }; + // Reads the plain-background and text-gradient switches for the end-of-season dialogs. auto game_end_options = [&](const GameState& state) { return ui::GameEndRenderOptions{ state.memory.has(::bmh::layout::PlainBackground) && state.memory.u8(::bmh::layout::PlainBackground) != 0, (!state.memory.has(::bmh::layout::TextGradientDisabled) || state.memory.u8(::bmh::layout::TextGradientDisabled) == 0) && season_exe.u8(::bmh::layout::TextGradientMode) == 2}; }; + // Blocks until a fresh left or right mouse press (pending mouse events are flushed first) + // or quit. auto wait_season_ack = [&] { // Source SDLFlushEvents2/SDLFlushEvents flush pending mouse events, then wait for // a new left/right press. Physical keyboard ESC is not event8. @@ -516,6 +574,7 @@ int main(int argc, char** argv) { SDL_Delay(10); } }; + // Same acknowledgement wait as above, used by the Sportschau screens. auto wait_sportschau_ack = [&] { // Source SDLFlushEvents2 flushes pending mouse input, then accepts fresh // left/right input. Keyboard Escape is not an Original ACK here. @@ -530,6 +589,7 @@ int main(int argc, char** argv) { SDL_Delay(10); } }; + // Waits `ticks` units of 20 ms; only a window close request interrupts it. auto source_tick_wait = [&](unsigned ticks) { for (unsigned i = 0; running && i < ticks; ++i) { SDL_Delay(20); // Source timer unit used by the traced intro path. @@ -539,6 +599,8 @@ int main(int argc, char** argv) { running = false; // platform close is the only intro-loop escape } }; + // Waits `count` original-display refresh periods using the high-resolution counter so + // the pacing is the same on 60/120/144 Hz monitors; only a close request interrupts it. auto wait_source_retraces = [&](unsigned count) { // Keep the VGA cadence on 60/120/144-Hz host displays alike. constexpr auto refresh_hz = ui::kOriginalRefreshHz; @@ -555,7 +617,9 @@ int main(int argc, char** argv) { } } }; + // --- Sportschau (results show) presenters: the engine calls these hooks synchronously. --- SportschauPresentationHooks sportschau_presenter; + // Plays the Sportschau intro animation frames with fanfare, then waits for a click. sportschau_presenter.intro = [&](const GameState&, const SportschauIntroView&) { if (!running) return; // PaletteOverride installs KB132's embedded palette; SportschauIntro restores the @@ -580,6 +644,7 @@ int main(int argc, char** argv) { "OpenBMH - sportschau_intro_ack", intro_colors); wait_sportschau_ack(); }; + // Builds the render options (panel background, gradient text) for Sportschau screens. const auto sportschau_context = [&](const GameState& state) { ui::SportschauReportContext context; context.solid_panel_background = state.memory.has(::bmh::layout::SolidPanelBackground) && state.memory.u8(::bmh::layout::SolidPanelBackground) != 0; @@ -587,12 +652,14 @@ int main(int argc, char** argv) { season_exe.u8(::bmh::layout::TextGradientMode) == 2; return context; }; + // Shows the matchday intro screen for a fixed time; a left click skips it. sportschau_presenter.kickoff = [&](const GameState&, const MatchdayIntroView& view) { if (!running) return; present_season(matchday_intro.render(view), "OpenBMH - matchday_intro", matchday_intro.palette_override() ? &*matchday_intro.palette_override() : nullptr); // SDLGetTicks reads BIOS ticks at BDA46c (PIT1193182 /65536 Hz), // unlike the separate 20ms units of DecodeTaxAnimationScript2. Source waits36 ticks. + // 36 ticks of the DOS BIOS timer (1193182 Hz / 65536) converted to milliseconds. constexpr Uint32 duration = (36ull * 65536 * 1000 + 1193181) / 1193182; const Uint32 start = SDL_GetTicks(); SDL_FlushEvents(SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP); @@ -610,6 +677,8 @@ int main(int argc, char** argv) { }; std::optional sportschau_replay_screen; size_t sportschau_step_index = 0; + // Shows one step of the report replay (log entries growing minute by minute). + // Returns true when the replay should stop (quit) or be skipped by a left click. sportschau_presenter.replay.step = [&](const GameState& state, const SportschauFixtureView& fixture, const SportschauReportStep& step) { if (!running) return true; @@ -621,6 +690,7 @@ int main(int argc, char** argv) { if (!sportschau_replay_screen) throw FormatError("sportschau: missing report owner"); bool skip = false; SDL_Event input; + // Only minute pauses accept input; other steps just look for a close request. if (step.minute_wait) { while (quit_confirmation.poll(&input)) { if (input.type == SDL_QUIT) running = false; @@ -640,6 +710,8 @@ int main(int argc, char** argv) { if (step.chance_wait) source_tick_wait(50); return skip; }; + // Plays one highlight (header, optional set piece, shot animation) of the replay, using + // the memory-driven delays, then restores the report screen. sportschau_presenter.replay.scene = [&](const GameState& state, const SportschauFixtureView& fixture, const SportschauSceneView& scene) { if (!running) return; @@ -654,6 +726,7 @@ int main(int argc, char** argv) { const auto colors = live_screen.shot_palette(palette, scene.shot, scene.groups, state); const std::string id = std::to_string(fixture.group) + "_" + std::to_string(fixture.fixture) + "_" + std::to_string(scene.report_step.visible_log_entries); + // Waits a configured number of ticks read from the game memory row (small values halved). const auto delay = [&](int row) { const uint32_t address = ::bmh::layout::Main_FormatError_ExecutableFieldUnsigned + uint32_t(row * 9); const int raw = state.memory.has(address) ? state.memory.u8(address) : 0; @@ -691,6 +764,7 @@ int main(int argc, char** argv) { present_season(sportschau_replay_screen->render_report(restored), ("OpenBMH - sportschau_scene_restored_" + id).c_str()); }; + // Shows the full match report of a fixture and waits for acknowledgement. sportschau_presenter.fixture = [&](const GameState& state, const SportschauFixtureView& fixture) { if (!running) return; ui::SportschauMatchReport screen(data, fixture, sportschau_context(state)); @@ -698,6 +772,7 @@ int main(int argc, char** argv) { wait_sportschau_ack(); sportschau_replay_screen.reset(); }; + // Shows the competition winner screen. sportschau_presenter.winner = [&](const GameState& state, const CompetitionWinnerView& view) { if (!running) return; const auto& colors = competition_winner.palette_override(view.title); @@ -706,18 +781,22 @@ int main(int argc, char** argv) { std::to_string(view.team)).c_str(), colors ? &*colors : nullptr); wait_sportschau_ack(); // SDLFlushEvents2 waits for a mouse press; ESC is ignored. }; + // Shows the team-of-the-matchday (eleven) screen. sportschau_presenter.awards = [&](const GameState& state, const SportschauAwardsView& view) { if (!running) return; present_season(sportschau_eleven.render(view, sportschau_context(state).gradient_text), ("OpenBMH - sportschau_eleven_" + std::to_string(view.group)).c_str()); wait_sportschau_ack(); }; + // Shows the team information screen. sportschau_presenter.team_info = [&](const GameState& state, const SportschauTeamInfoView& view) { if (!running) return; present_season(sportschau_team_info.render(view, sportschau_context(state).gradient_text), ("OpenBMH - sportschau_teaminfo_" + std::to_string(view.group)).c_str()); wait_sportschau_ack(); }; + // Modal dialog for the season tax event (question, notice or outcome). Returns true if the + // player answered Yes. A button counts only when pressed and released on the same button. auto show_tax = [&](const GameState& state, const SeasonTaxEvent& event) -> bool { if (!running) return false; const size_t base = size_t(event.manager_slot) * 0xb0c; @@ -741,6 +820,7 @@ int main(int argc, char** argv) { ? "OpenBMH - season_tax_question" : event.kind == SeasonTaxEventKind::notice ? "OpenBMH - season_tax_notice" : "OpenBMH - season_tax_outcome"); auto pressed = ui::GameEndTaxDialog::Button::none; + // Modal sub-loop (own event polling). while (running) { SDL_Event input; while (quit_confirmation.poll(&input)) { @@ -768,6 +848,7 @@ int main(int argc, char** argv) { } return false; }; + // Hooks for the season tax events: question via show_tax, notices and the animation below. SeasonTaxHooks tax_presenter; tax_presenter.choose = show_tax; tax_presenter.observe = [&](const GameState& state, const SeasonTaxEvent& event) { @@ -792,6 +873,7 @@ int main(int argc, char** argv) { season_backdrop = animation.drawing_frame(); } }; + // Waits without consuming gameplay input; only a quit request is handled. auto wait_promotion_time = [&](Uint32 milliseconds) { const auto start = SDL_GetTicks(); while (running && Uint32(SDL_GetTicks() - start) < milliseconds) { @@ -803,6 +885,8 @@ int main(int argc, char** argv) { if (running) SDL_Delay(10); } }; + // Presents the promotion/relegation table animation (39 steps) unless the manager's + // animation-skip flag is set. SeasonPromotionHook promotion_presenter = [&](const GameState& state, const SeasonPromotionEvent& event) { if (!running) return; auto view = ui::season_promotion_from_game(state, event, season_exe, season_texts); @@ -819,6 +903,9 @@ int main(int argc, char** argv) { for (int step = 1; running && step <= 38; ++step) show_step(step); if (running) wait_promotion_time(50 * 20); }; + // Shows a yes/no/acknowledge dialog over a backdrop and runs a modal loop until answered. + // Questions are bound to the process timer (expiry answers No); timed notices close + // after 70*3*20 ms. Returns `unsupported` when the program is quitting. auto present_pending_dialog = [&](const GameState& state, ui::TaxDialogProjection view, const Image& backdrop, const char* title, std::optional effective_options = {}) -> PendingOfferAnswer { @@ -896,6 +983,7 @@ int main(int argc, char** argv) { } return PendingOfferAnswer::unsupported; }; + // Asks whether a loaned player should be returned. Returns 1 yes, 0 no, -1 cancelled. auto loan_return_presenter = [&](GameState& state, WatcomRandom&, int manager, const std::string& question) -> int { if (!running) return -1; @@ -907,6 +995,7 @@ int main(int argc, char** argv) { if (answer == PendingOfferAnswer::no) return 0; return -1; }; + // Builds the hooks that present pending transfer/contract offers over the given backdrop. auto make_pending_offer_hooks = [&](Image backdrop) { auto pending_backdrop = std::make_shared(std::move(backdrop)); PendingOfferHooks hooks; @@ -915,6 +1004,7 @@ int main(int argc, char** argv) { *pending_backdrop, question.kind == PendingOfferQuestionKind::salary_demand ? "OpenBMH - pending_offer_salary_question" : "OpenBMH - pending_offer_severance_question"); }; + // Lets the player pick one of the incoming transfer bids (modal; reacts to mouse press). hooks.select_transfer = [&, pending_backdrop](const GameState& staged, const TransferOfferListView& offers) { ui::IncomingTransferScreen screen(data, ui::pending_offer_transfer_decision_from_game(staged, offers), @@ -945,8 +1035,10 @@ int main(int argc, char** argv) { *pending_backdrop, "OpenBMH - pending_offer_notice") == PendingOfferAnswer::unsupported) throw std::runtime_error("pending offer presenter stopped"); }; + // Shows a program-error screen and waits for a left or right press; throws on quit. hooks.program_error = [&, pending_backdrop](const GameState& staged, uint16_t code) { ui::ProgramErrorScreen screen(data,code,game_end_options(staged)); + // The modal loop owns the input now: drop any press recorded by the main loop. press.reset(); SDL_FlushEvents(SDL_MOUSEMOTION,SDL_MOUSEBUTTONUP); present_season(screen.render(),"OpenBMH - program_error"); @@ -967,6 +1059,7 @@ int main(int argc, char** argv) { }; return hooks; }; + // Builds the hooks for transfer-market sales to a human buyer (only notices are shown). auto make_market_sale_hooks = [&](Image backdrop) { auto market_backdrop = std::make_shared(std::move(backdrop)); HumanBuyerSaleHooks hooks; @@ -979,12 +1072,17 @@ int main(int argc, char** argv) { }; return hooks; }; + // Forward declarations: the club, player and statistics presenters call each other, so + // they are assigned further below. std::function present_club_information; std::function(app::ClubModalServices&,const ClubPlayerDetailSelection&,const Image&)> present_player_detail; + // Modal offer editor for a returned loan player. Returns -1 if unsupported or quitting, + // 0 if cancelled, 1 once the offer was submitted/closed. auto loan_return_offer_presenter = [&](GameState& staged, GameRandom& game_random, WatcomRandom& watcom_random, app::ClubModalServices& services, int manager, int source_slot, int list_entry, const HumanBuyerSaleHooks& sale_hooks) -> int { + // Only valid for manager slots 0..3 and list entries 40..43; anything else is unsupported. if (!running || manager < 0 || manager >= 4 || list_entry < 40 || list_entry >= 44 || source_slot != 2928 + list_entry || !staged.memory.has(::bmh::layout::EditorList + uint32_t(list_entry) * 0x58 + 0x57)) return -1; @@ -1022,6 +1120,7 @@ int main(int argc, char** argv) { if (event.type == SDL_MOUSEMOTION) continue; if (event.type == SDL_MOUSEBUTTONDOWN) { action = screen.click(event.button.x, event.button.y, + // clicks > 1 tells the screen it is a double click. event.button.button == SDL_BUTTON_RIGHT, event.button.clicks > 1); } else if (event.type == SDL_KEYDOWN) { const char* name = SDL_GetKeyName(event.key.keysym.sym); @@ -1084,6 +1183,7 @@ int main(int argc, char** argv) { draw(); } } + // Keep audio streaming while idle, then yield the CPU briefly. if (playback.needs_pump()) playback.pump(audio_error); SDL_Delay(10); } @@ -1096,14 +1196,18 @@ int main(int argc, char** argv) { std::function present_club_statistics; bool poach_selection_active=false; std::optional poach_card_selection; + // Modal club information screen for `team`. Returns true when it was left normally (or + // the process timer expired), false when the program is quitting. present_club_information = [&](app::ClubModalServices& services, int team) -> bool { if (!running) return false; //ClubInfoFromGame owns the opening DOWN and consumes its paired UP inside // this synchronous loop. The parent must not retain a held press // after that UP has already been consumed by the child. + // The child loop consumes the matching release itself. press.reset(); ui::ClubInfoView selected_view = ui::ClubInfoView::data_a; std::unique_ptr club_screen; + // Rebuilds the club screen from the current game state. const auto redraw = [&] { std::string error; ClubInfoEntry snapshot; @@ -1115,6 +1219,7 @@ int main(int argc, char** argv) { projection.view = selected_view; club_screen = std::make_unique(data, std::move(projection)); }; + // Presents the club screen; the window title encodes the view state. const auto show = [&] { auto title = "OpenBMH - cup_club_info_" + std::to_string(team) + "_" + std::to_string(int(selected_view)) + "_category_" + @@ -1127,6 +1232,7 @@ int main(int argc, char** argv) { }; redraw(); show(); SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + // True when the process timer ran out and no button is currently held down. const auto deadline_expired = [&] { return !club_screen->pressed_button() && poll_process_timer(true, true); }; @@ -1191,12 +1297,15 @@ int main(int argc, char** argv) { } return false; }; + // Opens the player detail card for a row chosen in the club list. The runtime input mode + // byte is switched for the card and restored afterwards (RAII helper below). present_club_player = [&](app::ClubModalServices& services, const ui::ClubInfoRequest& selected, const Image& parent_image) { if (!running) return false; const ClubPlayerDetailSelection selection{selected.runtime_team, selected.player_id, selected.rendered_row, selected.physical_row, selected.human_loan_index}; const uint8_t prior_mode = services.runtime_byte(::bmh::layout::CareerSession_DispatchPoachUi_ExecutableField); const uint8_t input_mode = club_player_detail_input_mode(prior_mode); + // Restores the saved runtime byte when the card is left, including by exception. struct PlayerInputModeRestore { app::ClubModalServices& services; uint8_t prior; @@ -1206,11 +1315,14 @@ int main(int argc, char** argv) { if(!present_player_detail)throw FormatError("generic player presenter unavailable"); return present_player_detail(services,selection,parent_image).value_or(false); }; + // Modal player detail card. Returns the card's close-parent flag, or std::nullopt when + // the program is quitting. present_player_detail = [&](app::ClubModalServices& services,const ClubPlayerDetailSelection& selection,const Image& parent_image) -> std::optional { if(!running)return std::nullopt; press.reset(); //ClubPlayerDetailFromGame now owns physical hold/release through its own Source wait. const uint8_t input_mode=services.runtime_byte(::bmh::layout::CareerSession_DispatchPoachUi_ExecutableField); size_t rebuild_count = 0; + // Asks the engine to redraw the player's data and projects it for the card. const auto rebuild = [&] { std::string error; auto redraw = services.redraw_player(selection); @@ -1218,6 +1330,7 @@ int main(int argc, char** argv) { return ui::club_player_detail_from_game(services.state(), std::move(redraw), season_exe); }; ui::ClubPlayerDetailScreen card(data, rebuild(), parent_image); + // Presents the card; the window title encodes selection and statistics state. const auto show = [&] { const auto title = "OpenBMH - cup_player_detail_" + std::to_string(selection.runtime_team) + "_" + std::to_string(selection.player_id) + (card.in_statistics() ? "_player_statistics_" : "_card_") + @@ -1225,6 +1338,8 @@ int main(int argc, char** argv) { "_rebuild_" + std::to_string(rebuild_count); present_season(card.render(), title.c_str()); }; + // Waits until the left button is up, but only if the engine recorded a long hold before + // the card opened. const auto wait_prior_left_release = [&] { if (input_mode == 0) return; // Source waits only for an already set CareerSession_InitializeClubModalRuntime_ExecutableField (>25 held ticks), @@ -1242,12 +1357,15 @@ int main(int argc, char** argv) { services.set_runtime_byte(::bmh::layout::CareerSession_InitializeClubModalRuntime_ExecutableField, 0); // Source consumes the owned hold flag. }; show(); wait_prior_left_release(); + // Source tick at which a left button hold began (for the card's hold shortcut). std::optional held_left_since; SDL_PumpEvents(); // ClubPlayerDetailFromGame consumes the opening DOWN when bbcde!=0. Only its // selection mode retains that inherited DOWN as a hold candidate. if (input_mode == 0 && (SDL_GetMouseState(nullptr, nullptr) & SDL_BUTTON_LMASK)) held_left_since = ui::pointer_hold_source_ticks(SDL_GetTicks64()); + // Executes a request coming from the card. A returned value means the card is left + // (true/false = close the parent screens too). const auto apply_request = [&](ui::ClubPlayerDetailRequest request) -> std::optional { switch (request.kind) { case ui::ClubPlayerDetailRequestKind::none: return std::nullopt; @@ -1293,6 +1411,7 @@ int main(int argc, char** argv) { } return std::nullopt; }; + // Applies the process-timer deadline to the card unless a mouse release is still awaited. const auto expire_card = [&]() -> std::optional { if (card.source_mouse_wait_release_pending()) return std::nullopt; if (poll_process_timer(true, true) && card.process_timer_expired()) @@ -1328,6 +1447,8 @@ int main(int argc, char** argv) { if (!running) return std::nullopt; if (changed && request.kind == ui::ClubPlayerDetailRequestKind::none) show(); } + // While the button is held, report the elapsed source ticks to the card; forget the hold + // when the physical button is up. if (held_left_since) { SDL_PumpEvents(); if (!(SDL_GetMouseState(nullptr, nullptr) & SDL_BUTTON_LMASK)) held_left_since.reset(); @@ -1339,16 +1460,19 @@ int main(int argc, char** argv) { } return std::nullopt; }; + // Modal team statistics screen with a mode toggle; leaves on close, right press or timer. present_club_statistics = [&](app::ClubModalServices& services, int team, const Image& parent_frame) { if (!running) return; auto mode = ui::TeamStatisticsMode::combined; std::unique_ptr statistics; + // Rebuilds the statistics screen for the current mode. const auto rebuild = [&] { auto projection = ui::team_statistics_from_game(services.state(), team, mode, season_exe, season_texts); statistics = std::make_unique(data, std::move(projection), parent_frame); }; + // Presents the statistics screen; the window title encodes team, mode and pressed button. const auto show = [&] { auto title = "OpenBMH - cup_team_statistics_" + std::to_string(team) + "_mode_" + std::to_string(int(mode)); @@ -1358,6 +1482,7 @@ int main(int argc, char** argv) { }; rebuild(); show(); SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); + // True when the process timer ran out and no button is currently held down. const auto deadline_expired = [&] { return !statistics->pressed_button() && poll_process_timer(true, true); }; @@ -1367,6 +1492,7 @@ int main(int argc, char** argv) { while (quit_confirmation.poll(&input)) { if (input.type == SDL_QUIT) { running = false; return; } if (deadline_expired()) return; + // A right press leaves at once without waiting for its release. if (input.type == SDL_MOUSEBUTTONDOWN && input.button.button == SDL_BUTTON_RIGHT) return; // ExpireQuestion right DOWN: do not wait for release. if (input.type == SDL_MOUSEMOTION) { @@ -1389,6 +1515,9 @@ int main(int argc, char** argv) { SDL_Delay(10); } }; + // Selector the engine calls while the player chooses a player to poach: shows league table + // pages, the range dialog, club info and player cards in nested modal loops. Returns the + // chosen player, or std::nullopt when closed or the process timer expired. app::CareerSession::PoachPlayerSelector poach_player_selector = [&](app::CareerSession& staged,app::ClubModalServices&,int manager, uint64_t& selection_revision,const Image& transfer_backdrop) @@ -1398,6 +1527,7 @@ int main(int argc, char** argv) { std::string error; auto page=staged.current_league_table_dispatch(error); if(!page)throw FormatError(error); + // Local variant of present_season that throws if an SDL render call fails. const auto present=[&](const Image& frame,const std::string& title) { SDL_SetWindowTitle(window,title.c_str());season_backdrop=frame; const auto painted=process_timer_image(frame); @@ -1408,12 +1538,14 @@ int main(int argc, char** argv) { SDL_RenderPresent(renderer); }; std::unique_ptr table; + // Rebuilds the league table screen from the current engine page. const auto rebuild=[&] { auto tables=ui::league_tables_from_game(staged.state(),manager); tables[size_t(page->identity.league)]=page->page; table=std::make_unique(data,std::move(tables),page->identity.league, ui::LeagueTableScreen::FamilyMode{page->identity,1}); }; + // Presents the table; a freshly forecast page is acknowledged to the engine once shown. const auto show_table=[&] { present(table->render(),"OpenBMH - poach_table_"+std::to_string(page->identity.league)); if(page->phase==Phase::forecast_pending_present) { @@ -1425,6 +1557,8 @@ int main(int argc, char** argv) { rebuild(); // Retain forecast pixels, refresh only the stale-request token. } }; + // Modal table range dialog. Digit, ENTER, BACKSPACE and SPACE keys are queued and fed to + // the dialog only while it is ready for input; returns its accept/cancel outcome. const auto run_range=[&](Image backdrop,ui::TableRangeDialogProfile profile) -> ui::TableRangeDialogOutcome { ui::LeagueTableRangeDialog dialog(data,std::move(backdrop),std::move(profile)); @@ -1476,6 +1610,7 @@ int main(int argc, char** argv) { if(dialog.key(key))show(); if(outcome)break; } + // Feed the dialog whole 20 ms source units elapsed since the last anchor. const Uint32 now=SDL_GetTicks(),units=Uint32(now-clock_anchor)/20; if(units) { clock_anchor+=units*20; @@ -1489,6 +1624,8 @@ int main(int argc, char** argv) { rebuild();show_table(); poach_selection_active=true;poach_card_selection.reset(); struct ResetSelection { bool& active;~ResetSelection(){active=false;} } reset{poach_selection_active}; + // When the process timer runs out and no table action or release is pending, closes the + // selection as if the close control had been used. Returns true if it did. const auto deadline_expired=[&] { if(table->pending_family_action() || table->source_mouse_wait_release_pending() || !poll_process_timer(true,true))return false; @@ -1570,6 +1707,8 @@ int main(int argc, char** argv) { // skipped reveal still presents every overview; a normal reveal ACK or // the right press leaving an overview does not skip subsequent groups. bool group_reveal_skipped = false; + // Presents a cup draw: the reveal animation (draw phase) or the overview of a round. + // In the overview a left click on a club opens its club info, a right click leaves. SeasonCupDrawHook cup_draw_presenter = [&](const GameState& state, const SeasonCupDrawEvent& event) { if (!running) return; if (event.phase == SeasonCupDrawPhase::draw) { @@ -1585,6 +1724,7 @@ int main(int argc, char** argv) { if (!view.source_eligible) return; ui::CupDrawScreen screen(data, std::move(view)); bool first_draw_frame = true; + // Presents the current draw frame; the first frame or flagged steps flush queued mouse events. const auto show_draw = [&] { const auto title = "OpenBMH - cup_draw_" + std::to_string(screen.revealed_count()); present_season(screen.render(), title.c_str()); @@ -1664,6 +1804,9 @@ int main(int argc, char** argv) { SDL_Delay(10); } }; + // End-of-game highscore presentation: an interactive calculator when the signature is 0, + // otherwise the table is updated on disk and shown when `display` is set; ends with the + // final screen. auto show_highscore = [&](const GameState& state, bool display) { if (!running) return; const auto options = game_end_options(state); @@ -1742,15 +1885,25 @@ int main(int argc, char** argv) { }; std::optional timed_notice_presented_at; std::optional timed_notice_release; + // ===================================================================================== + // Handling FlowResults (requests from the UI flow) + // ===================================================================================== + // Called by the main loop for every ui::FlowResult. It handles quitting and the process + // timer, then passes the request to app::serve_flow_request() together with the + // presenter lambdas defined inside, which the engine may call back synchronously. auto handle = [&](const ui::FlowResult& r) { pitch_pointer.show({}, renderer); + // A quit request must be confirmed by the player; otherwise the desk reports it as cancelled. if (r.request == ui::FlowRequest::end_session && !quit_confirmation.confirm()) { flow.reject_desk_action(english_game ? "Quit cancelled." : "Beenden abgebrochen."); dirty = true; return; } + // Play the sounds the desk queued during this action. if (const auto* desk = flow.desktop()) for (const auto id : desk->take_sound_ids()) app::original_audio_command(playback, id); + // Process timer: kickoff and quitting stop it; opening the menus 10, 11, 19 and 29 + // (save/load, settings, new manager) pauses it. if (r.request == ui::FlowRequest::kickoff || r.request == ui::FlowRequest::end_session) { // DeskDate clears CareerSession_DispatchStrengths_ExecutableField2 before returning to the match caller. process_timer.stop(); process_timer_owner.reset(); process_timer_frame.reset(); @@ -1760,6 +1913,7 @@ int main(int argc, char** argv) { // ApplySettingsFile suspends save/load, settings and new-manager waits. process_timer.pause(process_source_seconds()); process_timer_frame.reset(); } + // Confirmed quit: end the program at once, without advancing the calendar or saving. if (r.request == ui::FlowRequest::end_session) { // DeskDate's confirmed socket exit tears down the running // session without a calendar turn, RNG draw, or implicit save. @@ -1771,12 +1925,15 @@ int main(int argc, char** argv) { bool live_skipped = false; uint64_t live_overview_sequence = 0; std::optional outcome_backdrop; + // Live-match intervention: opens the lineup/pitch screen for the clicked team and runs it + // until closed. Returns true if the intervention was completed successfully. auto present_live_lineup = [&](int minute, MatchEngine& engine, std::vector& groups, GameState& state, uint64_t& live_revision, int selected_team, int selected_opponent, const app::LiveLineupDispatcher& dispatch, const app::LiveTacticsDispatcher& dispatch_tactic, const app::LivePitchDispatcher& dispatch_pitch, const app::LiveInterventionScopeDispatcher& dispatch_scope, bool live_skipped, bool event_origin) -> bool { + // Shows the engine's notice about a refused substitution as a dialog over the pitch. const auto show_live_substitution_notice = [&](const app::LiveSubstitutionResult& result, const Image& backdrop, const char* parent_title) { if (result.status != app::LiveSubstitutionStatus::source_notice) return; @@ -1793,6 +1950,8 @@ int main(int argc, char** argv) { }; bool completed = false; const int selected_manager = selected_team >= 0 ? state.manager_of(selected_team) : -1; + // Only for a human-managed team, and only when started from a match event or while the + // match is not being skipped past its first two minutes. if ((event_origin || (!live_skipped && minute > 2)) && selected_team >= 0 && selected_manager >= 0) { bool scope_started = false, scope_finished = false; std::string scope_error; @@ -1815,12 +1974,15 @@ int main(int argc, char** argv) { // pitch page and strand its navigation request after return. ui::PitchScreen screen(data, std::move(live_lineup), ui::pitch_extras_from_game(state, season_exe, live_revision, selected_opponent)); + // Window title depends on which page (bit 8 of the display word) is showing. const auto live_title = [&] { return (screen.extras().native_display_word & 8) ? "OpenBMH - live_pitch" : "OpenBMH - live_lineup"; }; SDL_SetWindowTitle(window, live_title()); bool closed = false; + // Executes a request from the pitch screen: player info card or a substitution/order + // change through the engine, then refreshes or reports the result on the screen. const auto apply_live_pitch = [&](const ui::PitchRequest& action) { if (action.kind == ui::PitchRequestKind::none) return; pitch_pointer.show({}, renderer); @@ -1861,7 +2023,10 @@ int main(int argc, char** argv) { } SDL_SetWindowTitle(window, live_title()); }; + // left_held/right_held pair a release with its press. left_release_consumed is set when the + // screen already acted on the press, so the release must not act a second time. bool left_held = false, left_release_consumed = false, right_held = false; + // Modal sub-loop: draws the pitch every pass and polls events itself. while (running && !closed) { pitch_pointer.show(screen.pointer_cursor(palette), renderer); const Image image = screen.render(); @@ -1881,6 +2046,7 @@ int main(int argc, char** argv) { if (modal.type == SDL_MOUSEBUTTONDOWN && modal.button.button == SDL_BUTTON_LEFT) { left_held = true; const auto action = screen.pointer_down(modal.button.x, modal.button.y); + // Release barrier: remember whether this press already triggered its action. left_release_consumed = screen.take_source_down_release_barrier(); // Native page/order controls act on DOWN. ACK before // polling another event; their UP cannot toggle twice. @@ -1910,6 +2076,7 @@ int main(int argc, char** argv) { } if (!redrawn && !closed) SDL_Delay(8); } + // Leaving: quitting aborts the live intervention, otherwise it is finished normally. if (!running) { dispatch_scope(app::LiveInterventionBoundary::abort, 2, selected_manager, selected_team, scope_error); @@ -1937,24 +2104,30 @@ int main(int argc, char** argv) { } return completed; }; + // Callback type through which the overview screen asks the engine for its actions. using RunningOverviewDispatcher = std::function( const app::CareerSession::LiveOverviewAction&, std::string&, const app::TransferOfferTeamInfoPresenter&)>; + // Presents the overview shown while the matchday is running (league table, other games, + // statistics) in its own loop, driven by the engine's overview dispatcher. const auto present_running_overview = [&](std::optional projection, const GameState& state, uint64_t& live_revision, const RunningOverviewDispatcher& dispatch_overview, const PhaseResultRequest* phase_result) { const int manager = projection->owner.manager_slot; std::unique_ptr table_screen; + // Only one of table/pairings/strengths/cup screen exists at a time, matching projection->kind. std::unique_ptr pairings_screen; std::unique_ptr strengths_screen; std::unique_ptr cup_screen; const auto overview_clock_start = std::chrono::steady_clock::now(); + // Seconds since the overview opened, converted to source units for the pairings screen. const auto overview_source_seconds = [&] { const auto milliseconds = std::chrono::duration_cast( std::chrono::steady_clock::now() - overview_clock_start).count(); return ui::league_pairings_source_seconds(uint64_t(milliseconds)); }; + // Creates the screen that matches the current projection kind (throws if its data is missing). const auto rebuild_screen = [&] { table_screen.reset(); pairings_screen.reset(); strengths_screen.reset(); cup_screen.reset(); if (projection->kind == app::CareerSession::LiveOverviewKind::league_table && @@ -1982,6 +2155,8 @@ int main(int argc, char** argv) { throw FormatError("live overview: Source presenter projection is missing"); } }; + // Window title of the overview; inside a phase result it also carries the phase end minute + // and group index. const auto overview_title = [&]() -> std::string { if (phase_result) { const std::string prefix = "OpenBMH - phase_"; @@ -2006,6 +2181,7 @@ int main(int argc, char** argv) { } return "OpenBMH - live_overview"; }; + // Draws the active overview screen and presents it. const auto render_overview = [&] { const Image image = table_screen ? table_screen->render() : pairings_screen ? pairings_screen->render() @@ -2023,13 +2199,18 @@ int main(int argc, char** argv) { rebuild_screen(); render_overview(); bool closed = false; + // The mouse press currently held; once the overview is closed its release is still + // swallowed here so it does not reach whatever is shown next. std::optional down; + // Modal table range dialog (same key queueing as the poach table version): returns its + // accept/cancel outcome. const auto run_table_range = [&](const Image& backdrop, ui::TableRangeDialogProfile profile) -> ui::TableRangeDialogOutcome { ui::LeagueTableRangeDialog dialog(data, backdrop, std::move(profile)); std::deque keys; Uint32 clock_anchor = SDL_GetTicks(); std::optional outcome; + // Presents the range dialog and lets it report an outcome and restart its tick clock. const auto show_dialog = [&] { const Image image = dialog.render(); SDL_SetWindowTitle(window, "OpenBMH - live_table_range"); @@ -2088,6 +2269,8 @@ int main(int argc, char** argv) { if (!outcome) throw FormatError("live table range presenter stopped"); return *outcome; }; + // Sends an action of the overview to the engine and applies the answer: close, switch to + // another overview kind, or run the range dialog and send its result back (recursive). std::function dispatch_action; dispatch_action = [&](const app::CareerSession::LiveOverviewAction& action) { const Image previous_table = table_screen ? table_screen->render() : Image{}; @@ -2141,7 +2324,10 @@ int main(int argc, char** argv) { dispatch_action(app::CareerSession::LiveOverviewAction{ack}); } }; + // Drop stale key releases left over from the match. SDL_FlushEvent(SDL_KEYUP); + // Modal sub-loop. After closing it keeps polling until the held button's release has + // arrived, so that release is not seen by the caller. while (running && (!closed || down)) { SDL_Event input; bool redrawn = false; @@ -2179,6 +2365,7 @@ int main(int argc, char** argv) { else cup_screen->release(input.button.x, input.button.y); } + // Whichever screen exists reports a pending request through its own accessor. std::optional action; if (table_screen && table_screen->pending_family_action()) action = *table_screen->pending_family_action(); @@ -2195,6 +2382,7 @@ int main(int argc, char** argv) { } if (!running || (closed && !down)) break; if (closed) { SDL_Delay(8); continue; } + // The pairings screen has a timer in source seconds that may raise a request by itself. if (pairings_screen && pairings_screen->tick_source_seconds(overview_source_seconds())) { if (pairings_screen->pending()) dispatch_action(app::CareerSession::LiveOverviewAction{*pairings_screen->pending()}); @@ -2205,14 +2393,22 @@ int main(int argc, char** argv) { } return running && closed; }; + // State used by the live-match presenters below. ui::LiveScoreReveal live_score_reveal; std::optional live_chance_context; std::unique_ptr reality_field; ui::RealityReporterLayoutState reality_layout; Image reality_pristine, reality_surface; Palette reality_colors; + // Hand the flow result to the controller. The arguments after the audio ones are the + // presenter callbacks the engine may call synchronously (live frame, incoming transfers, + // transfer decisions, season checkpoints, tax, highscore, promotion, cup draw, offers, + // club/player screens, notices, poaching, contracts, ...). The returned message is + // printed to stderr by the caller; "career_complete" ends the program. const std::string message = app::serve_flow_request(flow, r, session, data, save_directory, seed, revision, playback, audio_session, music_enabled, + // Callback per simulated match minute: shows the live matchday frame (unless skipped) + // and waits frame_delay ms, taken from --live-frame-ms or from the game's own speed setting. [&](int minute, const std::vector& groups, const GameState& state) { if (!running) return; bool live_frame_shown = false; @@ -2234,6 +2430,8 @@ int main(int argc, char** argv) { if (live_frame_shown && !live_skipped && frame_delay > 0) SDL_Delay(Uint32(frame_delay)); }, + // Callback for an incoming transfer offer: modal decision screen. Returns the chosen bid + // index, or -1 for decline, nothing to choose or quit. [&](const GameState& state, const TransferOfferListView& offers) -> int { if (!running) return -1; auto view = transfer_view(state, offers, offers.seller_manager); @@ -2247,6 +2445,7 @@ int main(int argc, char** argv) { // Only this modal's input is dispatched; desk actions and saves // cannot run against a partially processed calendar day. while (running) { + // The introductory notice disappears after 4260 ms or on any key. if (offer_screen.notice_active() && SDL_GetTicks() - notice_started >= 4260) offer_dirty |= offer_screen.dismiss_notice(); if (!offer_screen.notice_active() && offers.offer_count == 0) return -1; @@ -2286,6 +2485,8 @@ int main(int argc, char** argv) { } return -1; }, + // Callback that presents a transfer decision already settled by the engine: last-week + // dialog, confirmation, or the animated evaluation of the bids. Clicks cannot change it. [&](const GameState& state, const TransferDecisionEvent& decision) { if (!running) return; if (decision.kind == TransferDecisionEventKind::last_week) { @@ -2347,6 +2548,8 @@ int main(int argc, char** argv) { SDL_Delay(10); } }, + // Callback at season-transition checkpoints; only the one for the German entrants does + // anything: it shows the entrant screens, each closed by a mouse release. [&](const char* checkpoint, const GameState& state) { if (!running || std::strcmp(checkpoint, "the German entrants (CompetitionWinnerScreen)") != 0) return; // SeasonEntrantsFromGame / CompetitionWinnerScreen: show the three owned Original @@ -2375,7 +2578,10 @@ int main(int argc, char** argv) { if (!dismissed) SDL_Delay(10); } } + // Further callbacks: tax, highscore, promotion and cup draw presenters (defined above). }, tax_presenter, show_highscore, promotion_presenter, cup_draw_presenter, + // Pending-offer hooks exist only for kickoff; market sale hooks for kickoff and for + // transfer market / outgoing transfer submenu actions. r.request == ui::FlowRequest::kickoff ? make_pending_offer_hooks(flow.render()) : PendingOfferHooks{}, app::PendingOfferEntryPolicy::normal_interactive, @@ -2384,12 +2590,15 @@ int main(int argc, char** argv) { std::holds_alternative(r.submenu_action)) )) ? make_market_sale_hooks(flow.render()) : HumanBuyerSaleHooks{}, app::HumanBuyerMarketEntryPolicy::normal_interactive, + // Callback: club information screen (true if the program is still running). [&](app::ClubModalServices& services,int team,const Image&) { return present_club_information(services,team) && running; + // Next callback: player detail card. }, [&](app::ClubModalServices& services,const ClubPlayerDetailSelection& selection,const Image& parent) { // Direct1b556 already owns persistent bbcde=1. The shared //ClubPlayerDetailFromGame presenter never restores a temporary club mode here. return present_player_detail(services,selection,parent).has_value() && running; + // Next callback: stadium construction payment notice, shown over the investment detail. }, [&](const GameState& staged, const ConstructionNotice& notice) { if (!flow.stadium()) throw std::runtime_error("construction notice has no stadium owner"); // The Original payment notices restore the investment detail, @@ -2406,6 +2615,7 @@ int main(int argc, char** argv) { ? "OpenBMH - stadium_funds_notice" : "OpenBMH - stadium_sponsor_notice"; if (present_pending_dialog(staged, view, backdrop, title, effective_options) == PendingOfferAnswer::unsupported) throw std::runtime_error("construction notice presenter stopped"); + // Next callback: season ticket compensation notice. }, [&](const GameState& staged, const SeasonTicketCompensationNotice& notice) { if (!flow.stadium()) throw std::runtime_error("compensation notice has no stadium owner"); const Image backdrop = flow.stadium()->construction_notice_backdrop(); @@ -2417,6 +2627,8 @@ int main(int argc, char** argv) { ui::GameEndRenderOptions{owner.plain_background, owner.gradient_text}) == PendingOfferAnswer::unsupported) throw std::runtime_error("compensation notice presenter stopped"); }, sportschau_presenter, + // Callback: advertising contract renewal. A question gives renew/decline; a sponsor's + // refusal is a notice that gives acknowledged; anything else aborts. [&](const GameState& staged, const AdvertisingRenewal& renewal, const Image& backdrop) -> app::CareerSession::AdvertisingRenewalPresentation { if (!running) return app::CareerSession::AdvertisingRenewalPresentation::abort; @@ -2437,12 +2649,15 @@ int main(int argc, char** argv) { } return app::CareerSession::AdvertisingRenewalPresentation::abort; }, poach_player_selector, + // Callback: shows the poaching attempt's notices one after another. [&](const GameState& staged,const PoachStart& attempt,const Image& backdrop) { for(const auto& message:attempt.messages) if(present_pending_dialog(staged,ui::poach_notice_from_game(staged,attempt,message),backdrop, "OpenBMH - poach_notice")==PendingOfferAnswer::unsupported) throw FormatError("poach: notice presenter stopped"); }, contract_expiry_presenter, + // Callback: national friendly question. Returns yes/no, or std::nullopt when unsupported + // or the program is quitting. [&](const GameState& staged,ui::TaxDialogProjection view,const Image& backdrop) ->std::optional { if(!running)return {}; @@ -2454,7 +2669,16 @@ int main(int argc, char** argv) { press.reset(); if(answer==PendingOfferAnswer::unsupported)return {}; return answer==PendingOfferAnswer::yes; + // The loan-return presenters (defined above), then the live match observer. }, loan_return_presenter, loan_return_offer_presenter, + // ===================================================================================== + // Live match observer + // ===================================================================================== + // Called by the engine once per simulated minute of a live match. Besides pausing, it is + // where the player interacts: ESC or window close skips the live display, P pauses, the + // keys for overview/table/settings open their modal screens (key letters come from the + // game executable), clicks on the top strip open an overview or the settings, and clicks + // on the scoreboard rows open the lineup (left) or tactics (right) of that team. [&](int minute, MatchEngine& engine, std::vector& groups, GameState& state, uint64_t& live_revision, const app::LiveLineupDispatcher& dispatch, @@ -2463,6 +2687,7 @@ int main(int argc, char** argv) { const app::LiveInterventionScopeDispatcher& dispatch_scope) { if (!running) return; bool quit = false; + // Shows the engine's notice about a refused substitution as a dialog. const auto show_live_substitution_notice = [&](const app::LiveSubstitutionResult& result, const Image& backdrop, const char* parent_title) { if (result.status != app::LiveSubstitutionStatus::source_notice) return; @@ -2480,6 +2705,10 @@ int main(int argc, char** argv) { SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); SDL_SetWindowTitle(window, parent_title); }; + // Opens the tactics screen for the team on the clicked scoreboard row (side 0 = home, + // row positions come from the game executable, 32 pixels tall, at most 4 rows). Only for + // human-managed teams, after minute 2 and when the display is not skipped. The + // intervention scope is begun first and finished or aborted afterwards. const auto open_live_tactics = [&](int side, int y) { const auto frame = ui::live_matchday_frame(minute, groups, state); int selected_team = -1; @@ -2506,6 +2735,7 @@ int main(int argc, char** argv) { ui::tactics_from_game(tactics_game, season_exe, live_revision)); SDL_SetWindowTitle(window, "OpenBMH - live_tactics"); bool closed = false; + // A click counts only when the release matches the press (same button and position). std::optional tactics_down; bool source_completed = false; while (running && !closed) { @@ -2545,6 +2775,8 @@ int main(int argc, char** argv) { } if (!redrawn && !closed) SDL_Delay(8); } + // Closing through the screen's own close control finishes the intervention; leaving any + // other way (or quitting) aborts it. if (scope_active && source_completed) { if (!dispatch_scope(app::LiveInterventionBoundary::finish, 8, selected_manager, selected_team, scope_error)) { @@ -2566,8 +2798,11 @@ int main(int argc, char** argv) { std::fprintf(stderr, "live tactics: %s\n", e.what()); } }; + // The pause key is stored in the executable; pausing is only offered when it is P. const uint8_t source_pause_key = season_exe.u8(::bmh::layout::Main_Screen_RuntimeField); const bool source_pause_is_p = source_pause_key == 'p' || source_pause_key == 'P'; + // Shows the current live frame as paused and waits until P is pressed again (key repeats + // ignored) or the program quits. const auto pause_live_match = [&] { if (!source_pause_is_p) return; const auto frame = ui::live_matchday_frame(minute, groups, state); @@ -2598,6 +2833,7 @@ int main(int argc, char** argv) { } if (running) SDL_SetWindowTitle(window, "OpenBMH - live_matchday"); }; + // Redraws the live matchday frame after a modal screen has closed. const auto restore_live_frame = [&] { if (!running) return; const Image image = live_screen.render(ui::live_matchday_frame(minute, groups, state)); @@ -2609,6 +2845,9 @@ int main(int argc, char** argv) { SDL_RenderCopy(renderer, texture, nullptr, nullptr); SDL_RenderPresent(renderer); }; + // Opens the overview selected by key_slot through the session and runs it via + // present_running_overview. The sequence counter numbers the overviews opened in this + // match; the overview is taken from the first live group. const auto show_live_overview = [&](int key_slot) { if (!running || live_skipped || live_overview_sequence == UINT64_MAX) return; const int manager = state.memory.has(::bmh::layout::ActiveManager) ? state.memory.u8(::bmh::layout::ActiveManager) : -1; @@ -2645,6 +2884,8 @@ int main(int argc, char** argv) { }, nullptr); if (running && closed) restore_live_frame(); }; + // Modal settings screen inside a live match. `trigger` is the mouse press that opened it, + // so that its release can be matched. Every change is dispatched to the session. const auto show_live_settings = [&](std::optional trigger = std::nullopt) { if (!running || live_skipped || !state.memory.has(::bmh::layout::ActiveManager)) return; const int manager = state.memory.u8(::bmh::layout::ActiveManager); @@ -2664,6 +2905,7 @@ int main(int argc, char** argv) { app::original_audio_command(playback, 1); // SavePathInDirectory before the live settings modal. ui::SettingsScreen screen(data, projection->state); std::unique_ptr readme; + // Draws the settings screen, or its readme viewer when that is open. const auto render_settings = [&] { const Image image = readme ? readme->render() : screen.render(); SDL_SetWindowTitle(window, readme ? "OpenBMH - settings_readme" : "OpenBMH - live_settings"); @@ -2675,6 +2917,8 @@ int main(int argc, char** argv) { SDL_RenderPresent(renderer); }; render_settings(); + // Modal save/load screen for settings files opened from the settings screen; the result is + // dispatched to the session and the settings screen is shown again afterwards. const auto show_settings_file = [&] { const auto* pending = screen.pending_file(); if (!pending) return; @@ -2685,6 +2929,7 @@ int main(int argc, char** argv) { menu_request.manager_slot, live_revision, screen.render(), !state.memory.has(::bmh::layout::PlainBackground) || state.memory.u8(::bmh::layout::PlainBackground) == 0, ui::SaveLoadFileKind::settings, menu_request.origin_item_id); + // Draws the settings file screen. const auto render_file = [&] { const Image image = file_screen.render(); SDL_SetWindowTitle(window, "OpenBMH - live_settings_file"); @@ -2696,6 +2941,7 @@ int main(int argc, char** argv) { SDL_RenderPresent(renderer); }; render_file(); + // Give the filename field the native text input focus. focus_filename_input(renderer); bool finished = false; while (running && !finished) { @@ -2706,10 +2952,12 @@ int main(int argc, char** argv) { if (file_input.type == SDL_MOUSEBUTTONUP && (file_input.button.button == SDL_BUTTON_LEFT || file_input.button.button == SDL_BUTTON_RIGHT)) { + // clicks >= 2 reports a double click. file_changed |= file_screen.click(file_input.button.x, file_input.button.y, file_input.button.button == SDL_BUTTON_RIGHT, file_input.button.clicks >= 2); + // Only keys the file screen understands are forwarded; Ctrl/Cmd+A means select all. } else if (file_input.type == SDL_KEYDOWN && !file_input.key.repeat) { std::string_view key; switch (file_input.key.keysym.sym) { @@ -2756,6 +3004,9 @@ int main(int argc, char** argv) { } if (running) render_settings(); }; + // settings_down tracks the held press so its release is matched. readme_release_barrier is + // set when the readme was closed by a press: that press's release must not act on the + // settings screen. bool closed = false; bool readme_release_barrier = false; std::optional settings_down = trigger; @@ -2788,6 +3039,8 @@ int main(int argc, char** argv) { (input.button.button == SDL_BUTTON_LEFT || input.button.button == SDL_BUTTON_RIGHT)) { settings_down = input.button; + // The footer buttons (x 1..54, y 188..223) act on the matching release; other controls + // act on the press itself. const bool footer_button = input.button.button == SDL_BUTTON_LEFT && input.button.x >= 1 && input.button.x < 55 && input.button.y >= 188 && input.button.y < 224; @@ -2873,8 +3126,11 @@ int main(int argc, char** argv) { if (running && closed) app::original_match_audio_command(playback, state, 3); if (running && closed) restore_live_frame(); }; + // True at the first minute of a phase (1, then 21 indoors or 46/91/106 outdoors); the + // pause and overview keys and strip clicks are ignored then. const bool source_phase_start = minute == 1 || (state.indoor ? minute == 21 : (minute == 46 || minute == 91 || minute == 106)); + // Poll this minute's events directly (the live display is its own input loop). SDL_Event event; while (quit_confirmation.poll(&event)) { if (event.type == SDL_QUIT) { quit = true; live_skipped = true; } @@ -2892,6 +3148,7 @@ int main(int argc, char** argv) { else if (!source_phase_start && event.type == SDL_KEYDOWN && !event.key.repeat && season_exe.u8(::bmh::layout::Main_FileScreen_RuntimeField3) == 's' && event.key.keysym.sym == SDLK_s) show_live_settings(); + // Press on the top strip (x 0..63, y 50..64) opens an overview or the settings. else if (event.type == SDL_MOUSEBUTTONDOWN && (event.button.button == SDL_BUTTON_LEFT || event.button.button == SDL_BUTTON_RIGHT) && event.button.x >= 0 && event.button.x <= 63 && @@ -2915,6 +3172,7 @@ int main(int argc, char** argv) { } } } + // Press on a scoreboard side: right = tactics, left = lineup of the clicked row's team. else if (const auto side = app::live_matchday_board_side(event, minute, state.indoor)) { if (event.button.button == SDL_BUTTON_RIGHT) { open_live_tactics(*side, event.button.y); @@ -2942,6 +3200,8 @@ int main(int argc, char** argv) { } } if (quit) running = false; + // Next callback: environment/settings notice dialog. Returns false when the program is + // quitting or the dialog could not be shown. }, [&](const GameState& staged, ui::TaxDialogProjection view, const Image& backdrop) { if (!running) return false; const bool settings_notice = flow.in_settings() && flow.pending_settings(); @@ -2954,6 +3214,8 @@ int main(int argc, char** argv) { SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); } return shown; + // Next callback: a lineup change forced by a live match event; runs the same lineup + // screen as the click on the scoreboard. It must complete unless the program quits. }, [&](const LiveMatchEvent& event, MatchEngine& engine, std::vector& groups, GameState& state, uint64_t& live_revision, const app::LiveLineupDispatcher& dispatch, @@ -2967,11 +3229,22 @@ int main(int argc, char** argv) { if (!running) return; // SDL_QUIT aborts the Source scope without failing the event. if (!completed) throw FormatError("The Source event line-up did not complete."); + // ===================================================================================== + // Live match animation callbacks + // ===================================================================================== + // The following callbacks each show one kind of match event (ball movement, chance, shot, + // set piece, booking, penalty shootout, reality mode) and then pause. The pause is + // --live-frame-ms when given, otherwise a value saved in the game memory: values below 6 + // are halved and each unit is 20 ms. Only a window close request is consumed here; other + // input stays queued for the per-minute observer. + // + // Callback: ball movement frames of one displacement. }, [&](const LiveBallEvent& event, const std::vector& groups, const GameState& state) { if (!running || live_skipped) return; const auto frame = live_score_reveal.project(ui::live_matchday_frame(event.minute, groups, state)); if (frame.matches.empty()) return; + // Local helper: paints an image with the normal palette and presents it. const auto present = [&](const Image& image) { for (size_t i = 0; i < pixels.size(); ++i) pixels[i] = palette.argb[image.pixels[i]]; SDL_UpdateTexture(texture, nullptr, pixels.data(), 320 * 4); @@ -2980,6 +3253,7 @@ int main(int argc, char** argv) { SDL_RenderPresent(renderer); }; const int count = ui::LiveMatchdayScreen::ball_frame_count(event.displacement); + // Converts the saved pause number at the given row into milliseconds. const auto source_delay = [&](int pause) { const uint32_t address = ::bmh::layout::Main_FormatError_ExecutableFieldUnsigned + uint32_t(pause * 9); const int saved = state.memory.has(address) ? state.memory.u8(address) : 0; @@ -3013,6 +3287,7 @@ int main(int argc, char** argv) { SDL_SetWindowTitle(window, "OpenBMH - live_matchday"); present(live_screen.render(frame)); } + // Next callback: a scoring chance, shown as a preview and again as its result. }, [&](const LiveChanceEvent& event, const std::vector& groups, const GameState& state) { if (!running || live_skipped) return; @@ -3040,6 +3315,7 @@ int main(int argc, char** argv) { live_chance_context.reset(); return; } + // Pause row: 12 for the preview, 1 after a goal, otherwise 2. const int pause = event.stage == LiveChanceStage::preview ? 12 : (event.goal ? 1 : 2); const uint32_t address = ::bmh::layout::Main_FormatError_ExecutableFieldUnsigned + uint32_t(pause * 9); const int saved = state.memory.has(address) ? state.memory.u8(address) : 0; @@ -3047,6 +3323,8 @@ int main(int argc, char** argv) { (saved < 6 ? saved / 2 : saved) * 20; if (delay > 0) SDL_Delay(Uint32(delay)); if (event.stage == LiveChanceStage::result) live_chance_context.reset(); + // Next callback: shot animation, drawn with the shot's own palette. After the frames it + // either waits for a click or applies the saved pause. }, [&](const LiveShotEvent& event, const std::vector& groups, const GameState& state) { if (!running || live_skipped) return; @@ -3105,6 +3383,7 @@ int main(int argc, char** argv) { const int delay = live_frame_ms_explicit ? live_frame_ms : (saved < 6 ? saved / 2 : saved) * 20; if (delay > 0) SDL_Delay(Uint32(delay)); } + // Next callback: set piece animation frames (first frame held 40 retraces at 70 Hz). }, [&](const LiveSetPieceEvent& event, const std::vector& groups, const GameState& state) { if (!running || live_skipped) return; @@ -3132,6 +3411,7 @@ int main(int argc, char** argv) { if (delay>0) SDL_Delay(Uint32(delay)); } if (running && !live_frame_ms_explicit) SDL_Delay(200); // LiveMatchdayFrame + // Next callback: booking/injury box; pause row 3 for kind 0, otherwise 4. }, [&](const LiveBookingEvent& event, const std::vector& groups, const GameState& state) { if (!running || live_skipped) return; @@ -3158,6 +3438,8 @@ int main(int argc, char** argv) { if (delay>0) SDL_Delay(Uint32(delay)); // EventImpl clears the box after its pause; no Source click wait here. SDL_SetWindowTitle(window,"OpenBMH - live_matchday");present(live_screen.render(frame)); + // Next callback: penalty shootout step; the saved pause is repeated 4 times for the + // preview and twice for the result. }, [&](const LiveShootoutEvent& event, const std::vector& groups, const GameState& state) { if (!running || live_skipped) return; @@ -3179,6 +3461,9 @@ int main(int argc, char** argv) { const int saved=state.memory.has(::bmh::layout::Main_FormatError_RuntimeField6)?state.memory.u8(::bmh::layout::Main_FormatError_RuntimeField6):0; const int delay=live_frame_ms_explicit?live_frame_ms:(saved<6?saved/2:saved)*20; for (int i=0;i0) SDL_Delay(Uint32(delay)); + // Next callback: reality mode (running commentary with a moving field). Stages: begin + // (builds the screens), one call per round, settling and end. Returns true when the + // player ended it with ESC or a right press, or when the program quits. }, [&](const LiveRealityEvent& event, const std::vector& groups, const GameState& state) -> bool { if (!running || live_skipped) return false; @@ -3227,6 +3512,7 @@ int main(int argc, char** argv) { size_t index=0; for (const auto& motion:event.tick.motion->frames) { auto backdrop=reality_pristine; + // Keep the first 129 rows of the current surface on the fresh backdrop. std::copy_n(reality_surface.pixels.begin(),320*129,backdrop.pixels.begin()); reality_surface=reality_field->render(motion,backdrop); present(reality_surface,reality_colors,"OpenBMH - live_reality_round_"+ @@ -3237,6 +3523,7 @@ int main(int argc, char** argv) { } else { present(reality_surface,reality_colors,"OpenBMH - live_reality_report_"+round_identity); } + // Only ESC or a right press is taken from the queue as the exit; other input stays. SDL_PumpEvents();SDL_Event input; if (quit_confirmation.peep(&input,1,SDL_GETEVENT,SDL_QUIT,SDL_QUIT)>0) {running=false;return true;} // Consume only the Source exit for this scene. Other input remains @@ -3250,6 +3537,8 @@ int main(int argc, char** argv) { quit_confirmation.peep(&input,1,SDL_GETEVENT,SDL_MOUSEBUTTONDOWN,SDL_MOUSEBUTTONDOWN);return true; } return false; + // Next callback: results viewer at the end of a match phase; throws if it was stopped + // before being acknowledged. }, [&](const PhaseResultRequest& request, const std::vector& groups, const GameState& state) { if (!running) throw FormatError("phase results: presentation stopped"); @@ -3264,9 +3553,12 @@ int main(int argc, char** argv) { }, &request); if (!closed) throw FormatError("phase results: viewer stopped before Source ACK"); }, true); + // In -debug mode every request and its outcome is logged. if (app::debug::enabled()) app::debug::log("request " + std::to_string(int(r.request)) + (message.empty() ? std::string(" ok") : " -> " + message)); + // The controller reports the end of the career by this message: leave the main loop. if (message == "career_complete") { running = false; return; } if (!message.empty()) std::fprintf(stderr, "engine: %s\n", message.c_str()); + // Autosave problems are reported but do not stop the game. if (session) { const auto autosave_error = session->take_autosave_error(); if (!autosave_error.empty()) std::fprintf(stderr, "autosave: %s\n", autosave_error.c_str()); @@ -3286,9 +3578,11 @@ int main(int argc, char** argv) { dirty = true; } } + // Forget the presentation time once no timed notice is open. if(!flow.timed_notice_open())timed_notice_presented_at.reset(); SDL_SetWindowTitle(window, ("OpenBMH - " + flow.screen_name()).c_str()); }; + // Flashes the formation-saved feedback image, then shows the restored screen. const auto present_formation_save_feedback = [&] { for (bool restored : {false, true}) { const auto feedback = flow.pitch_formation_save_feedback(restored); @@ -3302,6 +3596,8 @@ int main(int argc, char** argv) { if (!restored) SDL_Delay(ui::PitchScreen::formation_save_flash_ms); } }; + // Called every loop pass. If the left button has been held long enough on the pitch + // screen at the position where it was pressed, triggers the hold action once. const auto service_pitch_hold = [&] { if (!press || press->pitch_hold_attempted || !flow.in_pitch() || press->screen != flow.screen_name() || press->revision != revision) return; @@ -3318,11 +3614,14 @@ int main(int argc, char** argv) { handle(held); }; const auto pairings_clock_start = std::chrono::steady_clock::now(); + // Seconds since the loop started in the pairings screen's source units. const auto pairings_source_seconds = [&] { const auto milliseconds = std::chrono::duration_cast( std::chrono::steady_clock::now() - pairings_clock_start).count(); return ui::league_pairings_source_seconds(uint64_t(milliseconds)); }; + // Milliseconds since the same clock started; the base for the table, balance and + // calculator timers below. const auto balance_source_milliseconds = [&] { return uint64_t(std::chrono::duration_cast( std::chrono::steady_clock::now()-pairings_clock_start).count()); @@ -3330,9 +3629,11 @@ int main(int argc, char** argv) { // DecodeTaxAnimationScript2 multiplies its argument by 20 before host timer's // millisecond conversion. This is the host unit scale, not a claim // of parity with the Original DOS clock's quantization. + // Elapsed time in 20 ms source units. const auto family_table_source_units = [&] { return balance_source_milliseconds() / 20; }; + // Tells the flow the table frame has reached the screen; it may answer with a request. const auto mark_family_table_presented = [&] { const auto acknowledged = flow.in_toto_calculator() ? flow.after_toto_present(family_table_source_units()) @@ -3340,6 +3641,7 @@ int main(int argc, char** argv) { if (acknowledged.request != ui::FlowRequest::none) handle(acknowledged); else dirty |= acknowledged.changed; }; + // Redraws the league table or toto screen when dirty, then marks it as presented. const auto present_family_table_redraw = [&] { if ((!flow.in_family_table() && flow.screen_name() != "toto") || !dirty) return; const auto image = process_timer_image(flow.render()); @@ -3351,6 +3653,8 @@ int main(int argc, char** argv) { dirty = false; mark_family_table_presented(); }; + // A key typed for the table range dialog or toto calculator, tagged with its owner so + // that keys for a screen that has since changed are dropped. struct TableRangeKey { std::string key; ui::StrengthsIdentity identity; @@ -3358,6 +3662,8 @@ int main(int argc, char** argv) { uint64_t toto_revision = 0; }; std::deque table_range_keys; + // Collects typed digits, ENTER, BACKSPACE and SPACE for those screens. Returns true when + // the event belongs to them (unsupported keys are swallowed too). const auto queue_table_range_event = [&](const SDL_Event& event) { if (!flow.in_toto_calculator() && (!flow.in_family_table_range_dialog() || !flow.league_family_identity())) return false; @@ -3381,6 +3687,8 @@ int main(int argc, char** argv) { // been established for this modal. Unsupported keys stay owned. return true; }; + // Called every loop pass while a table or toto screen is open: advances its timers, + // redraws, and feeds queued keys whenever the screen is ready for input. const auto service_family_table = [&] { if (!flow.in_family_table() && flow.screen_name() != "toto") { table_range_keys.clear(); return; } const auto tick = flow.in_toto_calculator() @@ -3403,8 +3711,10 @@ int main(int argc, char** argv) { } } }; + // Which balance screen state was last presented (to avoid redrawing identical frames). std::optional presented_balance; bool presented_balance_notice=false; + // Presents the balance screen only when its identity or notice state changed. const auto present_balance_redraw = [&] { if (!flow.in_balance()) { presented_balance.reset();presented_balance_notice=false; return; } const auto identity=flow.balance()->state().identity; @@ -3417,6 +3727,7 @@ int main(int argc, char** argv) { flow.mark_balance_presented_source_milliseconds(balance_source_milliseconds()); presented_balance=identity;presented_balance_notice=notice;dirty=false; }; + // Called every loop pass: advances the balance screen's millisecond timer. const auto service_balance_timer = [&] { present_balance_redraw(); const auto tick=flow.tick_balance_source_milliseconds(balance_source_milliseconds()); @@ -3426,21 +3737,26 @@ int main(int argc, char** argv) { // KB6 waits start after the pressed/final calculator image reaches SDL. // Keep a matching physical UP until the four-tick press is over; N's // last calculator frame stays visible through its fifty-tick wait. + // Pending release of a button pressed on the stadium calculator. struct CalculatorRelease { SDL_MouseButtonEvent button; uint64_t scope = 0, sequence = 0; }; std::optional calculator_release; std::optional calculator_tick_anchor; + // A calculator key tagged with the owner state it was typed for. struct CalculatorKey { std::string key; uint64_t revision = 0, scope = 0, sequence = 0; }; std::deque calculator_keys; + // Queues a key for the current stadium calculator owner. const auto queue_calculator_key = [&](std::string key) { const auto& owner = flow.stadium()->state(); calculator_keys.push_back({std::move(key), owner.revision, owner.scope, owner.sequence}); }; + // Collects typed digits, ENTER, BACKSPACE and SPACE for the stadium calculator; returns + // true when the event is consumed. const auto queue_calculator_event = [&](const SDL_Event& event) { if (event.type == SDL_TEXTINPUT) { const std::string_view text(event.text.text); @@ -3458,6 +3774,7 @@ int main(int argc, char** argv) { // Digits arrive separately through SDL_TEXTINPUT. return true; }; + // Starts the calculator's wait clock once its frame has reached the screen. const auto mark_stadium_calculator_presented = [&] { if (!flow.in_stadium() || !flow.stadium()->calculator_source_waiting()) { calculator_tick_anchor.reset(); @@ -3466,6 +3783,8 @@ int main(int argc, char** argv) { flow.mark_stadium_calculator_presented(); if (!calculator_tick_anchor) calculator_tick_anchor = balance_source_milliseconds(); }; + // Called every loop pass while the stadium screen is open: converts elapsed time into + // source ticks for the calculator's waits and feeds queued keys. const auto service_stadium_calculator = [&] { if (!flow.in_stadium()) { calculator_release.reset(); calculator_tick_anchor.reset(); @@ -3492,6 +3811,8 @@ int main(int argc, char** argv) { } if (!flow.stadium()->calculator_source_waiting()) { calculator_tick_anchor.reset(); + // The remembered release is delivered only if the calculator owner is unchanged and still + // waits for the key release. if (calculator_release) { const auto release = *calculator_release; calculator_release.reset(); @@ -3513,7 +3834,9 @@ int main(int argc, char** argv) { handle(flow.send_key(input.key)); } }; + // Which pairings page was last presented (to avoid redrawing identical frames). std::optional presented_pairings; + // Presents the league pairings screen when its page identity changed. const auto present_pairings_redraw = [&] { if (!flow.in_league_pairings()) { presented_pairings.reset(); return; } const auto identity = flow.league_pairings()->state().identity; @@ -3528,6 +3851,7 @@ int main(int argc, char** argv) { presented_pairings = identity; dirty = false; }; + // Called every loop pass: advances the pairings screen's second timer. const auto service_pairings_timer = [&] { present_pairings_redraw(); const auto tick = flow.tick_league_pairings_source_seconds(pairings_source_seconds()); @@ -3539,8 +3863,12 @@ int main(int argc, char** argv) { }; //PresentManagerDialog presents its question before polling2de66. Bind the actual //freshly drawn frame, never an old texture or a preceding modal ACK. + // Frame identities: each tuple names the owner state (session, manager, scope, sequence, + // revision, ...) of a modal question that was actually drawn. A process-timer deadline + // is applied only to a frame that has been presented, never to a stale one. using StadiumQuestionFrame = std::array; std::optional presented_stadium_question; + // Identity of the stadium tip/quote question currently open, if any. const auto stadium_question_frame = [&]() -> std::optional { if (!session || !flow.in_stadium()) return {}; const auto& question=flow.stadium()->state(); @@ -3548,7 +3876,10 @@ int main(int argc, char** argv) { const auto& state=flow.stadium()->state(); return StadiumQuestionFrame{session->session_id(),uint64_t(state.manager_slot),state.scope,state.sequence,state.revision}; }; + // Records the current stadium question frame as presented. const auto mark_stadium_question_presented = [&] { presented_stadium_question=stadium_question_frame(); }; + // If the presented stadium question has expired, hands the expiry to the flow. Returns + // true when it did. const auto service_stadium_deadline = [&] { const auto owner=stadium_question_frame(); if (!owner || owner!=presented_stadium_question) return false; @@ -3558,12 +3889,14 @@ int main(int argc, char** argv) { handle(expired); return true; }; + // Same check from the idle path, but not while the question's button is being held. const auto service_idle_stadium_deadline = [&] { // OriginalMouseSound/Sample can synthesize event8 on expiry, including idle. // ExpireQuestion's held-button helper must return before57ef7 answers. if (flow.in_stadium() && !flow.stadium()->construction_tip_held()) service_stadium_deadline(); }; + // Same idea for the national friendly picker. using NationalPickerFrame = std::pair; std::optional presented_national_picker; const auto national_picker_frame = [&]() -> std::optional { @@ -3573,6 +3906,7 @@ int main(int argc, char** argv) { const auto mark_national_picker_presented = [&] { presented_national_picker=national_picker_frame(); }; using FriendlyPickerFrame = std::array; std::optional presented_friendly_picker; + // Identity of the friendly opponent picker currently open, if any. const auto friendly_picker_frame = [&]() -> std::optional { const auto* picker=flow.friendly_opponent_picker(); if (!session || !picker || !flow.desktop()) return {}; @@ -3581,6 +3915,7 @@ int main(int argc, char** argv) { uint64_t(desk.runtime_club),desk.revision,uint64_t(picker->selected_league())}; }; const auto mark_friendly_picker_presented = [&] { presented_friendly_picker=friendly_picker_frame(); }; + // Same idea for the friendly match calendar. using FriendlyCalendarFrame = std::array; std::optional presented_friendly_calendar; const auto friendly_calendar_frame = [&]() -> std::optional { @@ -3590,6 +3925,7 @@ int main(int argc, char** argv) { uint64_t(quote.runtime_team),quote.revision,quote.request_id}; }; const auto mark_friendly_calendar_presented = [&] { presented_friendly_calendar=friendly_calendar_frame(); }; + // Same idea for the friendly match question. using FriendlyQuestionFrame = std::array; std::optional presented_friendly_question; const auto friendly_question_frame = [&]() -> std::optional { @@ -3602,6 +3938,8 @@ int main(int argc, char** argv) { uint64_t(question->active_question()->source_manager_flags)}; }; const auto mark_friendly_question_presented = [&] { presented_friendly_question=friendly_question_frame(); }; + // If the presented friendly question has expired, hands the expiry to the flow. Returns + // true when it did. const auto service_friendly_question_deadline = [&] { const auto owner=friendly_question_frame(); if(!owner||owner!=presented_friendly_question||!poll_process_timer(false,false))return false; @@ -3609,6 +3947,10 @@ int main(int argc, char** argv) { if(expired.request==ui::FlowRequest::none&&!expired.changed)return false; handle(expired);return true; }; + // Called every loop pass and before each event. On the desktop it starts or resumes the + // process timer for the current session/manager/day and polls it. It does nothing until + // the modal frames above have been presented and while a button is held. On expiry the + // flow is told with the current logical mouse position. const auto service_process_timer = [&] { // SDLFlushEvents3's notice owns its wait. Keep the desk clock polling, // but hand its outer expiry back only after this notice restores. @@ -3660,6 +4002,9 @@ int main(int argc, char** argv) { if (expired.request != ui::FlowRequest::none || expired.changed) handle(expired); } }; + // ===================================================================================== + // Opening screen + // ===================================================================================== // OpenBMH deviates from the original: display the repository-owned title // at its native resolution until a complete left/right click, without loading balls. { @@ -3667,6 +4012,8 @@ int main(int argc, char** argv) { title_screen.present(); bool opening_confirmed = false; std::optional opening_press; + // Only a complete click confirms: press and release of the same button. Losing focus + // forgets the press; expose and resize events redraw the title picture. while (running && !opening_confirmed) { SDL_Event opening_event; while (quit_confirmation.poll(&opening_event)) { @@ -3696,13 +4043,28 @@ int main(int argc, char** argv) { SDL_FlushEvents(SDL_MOUSEMOTION, SDL_MOUSEBUTTONUP); season_backdrop.reset(); dirty = true; + // Text input stays on for the whole session so SDL_TEXTINPUT events arrive. SDL_StartTextInput(); + // filename_input_active: the save/load filename field already has focus. + // setup_button_down: [0] left, [1] right button pressed while on the setup screen. bool filename_input_active = false; std::array setup_button_down{}; + // ===================================================================================== + // Main event loop + // ===================================================================================== + // Each pass: keep the filename field focused on the save/load screen, expire timed + // notices, service the timers, then drain the SDL event queue through + // quit_confirmation.poll(). SDL_QUIT ends the loop. Mouse down, up and motion, text and + // key events are translated into StartupFlow calls (pointer_down, click or hold, + // move_action, text, send_key); every FlowResult is passed to handle(), which serves + // the request. After the queue is empty the loop services holds and timers again, plays + // queued sounds, pumps audio, redraws the 320x240 canvas if dirty, presents it and + // sleeps 10 ms. while (running) { const bool filename_open = flow.screen_name() == "save_load"; if (filename_open && !filename_input_active) focus_filename_input(renderer); filename_input_active = filename_open; + // A timed notice closes by itself after 70*3*20 ms. if(timed_notice_presented_at && flow.timed_notice_open() && SDL_GetTicks64()-*timed_notice_presented_at>=70*3*20) handle(flow.expire_timed_notice()); @@ -3714,6 +4076,7 @@ int main(int argc, char** argv) { running = false; break; } + // Losing focus forgets the pressed setup buttons; regaining it restores text input. if (e.type == SDL_WINDOWEVENT) { if (e.window.event == SDL_WINDOWEVENT_FOCUS_LOST) setup_button_down.fill(false); if (e.window.event == SDL_WINDOWEVENT_FOCUS_GAINED) { @@ -3733,6 +4096,7 @@ int main(int argc, char** argv) { if (flow.screen_name() == "setup" && !owned) continue; } } + // Swallow the release of the press that dismissed a timed notice. if(e.type==SDL_MOUSEBUTTONUP&&timed_notice_release&&e.button.button==*timed_notice_release) { timed_notice_release.reset();continue; } @@ -3743,6 +4107,7 @@ int main(int argc, char** argv) { timed_notice_release=e.button.button;press.reset(); handle(flow.expire_timed_notice());continue; } + // Keyboard input is ignored while a timed notice is open. if(flow.timed_notice_open()&&(e.type==SDL_KEYDOWN||e.type==SDL_TEXTINPUT))continue; // InLeaguePairings handles a changed league selector before5147b's // timer. Preserve that precedence without moving other inputs. @@ -3765,10 +4130,13 @@ int main(int argc, char** argv) { service_family_table(); service_stadium_calculator(); service_idle_stadium_deadline(); + // Keys for the table range dialog or toto calculator are queued, not dispatched at once. if (queue_table_range_event(e)) { service_family_table(); continue; } + // While the stadium calculator is in a timed wait, its keys are queued and its release + // is remembered; no other input is processed (release barrier). if (flow.in_stadium() && flow.stadium()->calculator_source_waiting()) { // DecodeTaxAnimationScript2 delays without consuming keyboard input. Retain // FIFO keys for this accepted calculator owner, including @@ -3783,19 +4151,24 @@ int main(int argc, char** argv) { // completes. SDL_QUIT was serviced above this barrier. continue; } + // The open calculator owns all keyboard input. if (flow.in_stadium() && flow.stadium()->calculator_open() && queue_calculator_event(e)) { service_stadium_calculator(); continue; } + // ESC asks to quit (after confirmation) unless it is a close key in a menu or view. if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE && !flow.in_preparation_menu() && !flow.in_results_view() && !flow.in_readonly_view() && quit_confirmation.confirm()) running = false; + // Remember the left press so its release can be judged as a click or a 2 second hold. if (e.type == SDL_MOUSEBUTTONDOWN && e.button.button == SDL_BUTTON_LEFT) press = Press{e.button.x, e.button.y, SDL_GetTicks(), flow.screen_name(), ui::pointer_hold_source_ticks(SDL_GetTicks64()), revision}; + // Remember where the right press began, to detect releases without a matching press. if (e.type == SDL_MOUSEBUTTONDOWN && e.button.button == SDL_BUTTON_RIGHT) right_press_screen = flow.screen_name(); + // Screens that react to the press itself get pointer_down() now. if(!selector_consumed&&e.type==SDL_MOUSEBUTTONDOWN&&(flow.desktop()||flow.in_balance()||flow.in_desk_records()||flow.in_achievements()||flow.in_indoor_standings()||flow.in_reschedule_calendar()||flow.in_league_pairings()||flow.in_family_table()||flow.in_toto_calculator()||flow.in_stadium()||flow.in_environment()||flow.in_strengths()||flow.in_top_scorers()||flow.in_opportunities()||flow.in_statistics_menu()||flow.in_statistics_page()||flow.in_analytics()||flow.in_other_games()||flow.in_pitch()||flow.in_settings())&& (e.button.button==SDL_BUTTON_LEFT||e.button.button==SDL_BUTTON_RIGHT)) { handle(flow.pointer_down(e.button.x,e.button.y,e.button.button==SDL_BUTTON_RIGHT)); @@ -3805,6 +4178,8 @@ int main(int argc, char** argv) { // copy must succeed before their Present starts a wait // or commits a staged forecast random stream. present_family_table_redraw(); + // Screens with held controls are redrawn at once, so the pressed state is visible before + // the release arrives. } else if(flow.in_balance()||flow.in_desk_records()||flow.in_achievements()||flow.in_indoor_standings()||flow.in_reschedule_calendar()||flow.in_league_pairings()||flow.in_stadium()||flow.in_environment()||flow.in_strengths()||flow.in_top_scorers()||flow.in_opportunities()||flow.in_statistics_menu()||flow.in_statistics_page()||flow.in_analytics()||flow.in_other_games()||flow.in_pitch()||flow.in_settings()||flow.friendly_question_screen()) { //48529/ExpireQuestion/67e80 present the held control before waiting //for its release. The existing UP ownership remains intact. @@ -3846,6 +4221,8 @@ int main(int argc, char** argv) { SDL_RenderPresent(renderer); dirty = false; } + // Mouse release. Order: an expired question that owns this release, then right-button + // releases whose press was consumed elsewhere (orphaned releases), then click or hold. if (e.type == SDL_MOUSEBUTTONUP && (e.button.button == SDL_BUTTON_LEFT || e.button.button == SDL_BUTTON_RIGHT)) { if(e.button.button==SDL_BUTTON_LEFT&&service_friendly_question_deadline()) { press.reset();continue; // The expired question owns this UP, not its returned calendar/desk. @@ -3860,6 +4237,7 @@ int main(int argc, char** argv) { // ClubInfoFromGame consumes the right press and clears CareerSession_BeginFriendlyOpponentTable_ExecutableField2 // before returning. Its release is not another Source8 // cancel event in the parent OpenTransferEditor input loop. + // owned: the right press began on this same screen. const bool owned = right_press_screen && *right_press_screen == flow.screen_name(); const bool source_wait_release = flow.source_mouse_wait_release_pending(); // Menu6's right DOWN closes1e06b immediately. Its real @@ -3879,9 +4257,12 @@ int main(int argc, char** argv) { } if (!owned) { flow.consume_orphaned_pitch_release(); continue; } } + // A left release is a hold (2000 ms or more, same position, same screen) only on screens + // that support it; everywhere else it is a click. const bool held = e.button.button == SDL_BUTTON_LEFT && !flow.in_pitch() && !flow.friendly_question_screen() && !flow.friendly_question_release_pending() && !flow.in_family_table() && !flow.in_balance() && !flow.in_desk_records() && !flow.in_achievements() && !flow.in_indoor_standings() && !flow.in_reschedule_calendar() && !flow.in_top_scorers() && !flow.in_opportunities() && !flow.in_statistics_menu() && !flow.in_statistics_page() && !flow.in_analytics() && !flow.in_other_games() && press && e.button.x == press->x && e.button.y == press->y && press->screen == flow.screen_name() && SDL_GetTicks() - press->time >= 2000; const auto released = held ? flow.hold(e.button.x, e.button.y, 2000) + // clicks >= 2 reports a double click. : flow.click(e.button.x, e.button.y, e.button.button == SDL_BUTTON_RIGHT, e.button.clicks >= 2); present_formation_save_feedback(); // JA of the manager confirmation is shown pushed in briefly before the @@ -3894,6 +4275,7 @@ int main(int argc, char** argv) { present_desk_record_points(); press.reset(); } + // Moving away from the pressed position cancels the hold candidate. if (e.type == SDL_MOUSEMOTION) { if (press && (e.motion.x != press->x || e.motion.y != press->y)) press.reset(); const auto moved = flow.move_action(e.motion.x, e.motion.y); @@ -3903,6 +4285,7 @@ int main(int argc, char** argv) { // keyboard/mouse event, even when both are already queued. present_family_table_redraw(); } + // Typed characters go to the flow; a FormatError only produces a message. if (e.type == SDL_TEXTINPUT) { try { dirty |= flow.text(e.text.text); @@ -3911,11 +4294,14 @@ int main(int argc, char** argv) { std::fprintf(stderr, "input: %s\n", err.what()); } } + // Ctrl/Cmd+A selects all in the filename field. if (e.type == SDL_KEYDOWN && flow.screen_name() == "save_load" && e.key.keysym.sym == SDLK_a && (e.key.keysym.mod & (KMOD_CTRL | KMOD_GUI))) { handle(flow.send_key("SELECT_ALL")); continue; } + // Only keys the current screen type uses are forwarded to the flow (by name); on the + // desktop the letters A-Z are shortcuts. if (e.type == SDL_KEYDOWN && (e.key.keysym.sym == SDLK_RETURN || e.key.keysym.sym == SDLK_BACKSPACE || (flow.screen_name() == "save_load" && (e.key.keysym.sym == SDLK_UP || e.key.keysym.sym == SDLK_DOWN || e.key.keysym.sym == SDLK_PAGEUP || e.key.keysym.sym == SDLK_PAGEDOWN)) || @@ -3940,6 +4326,7 @@ int main(int argc, char** argv) { } if (!running) break; } + // Queue drained: service holds, timers and sounds, then draw. if (!running) break; service_pitch_hold(); if (!running) break; @@ -3951,11 +4338,14 @@ int main(int argc, char** argv) { service_idle_stadium_deadline(); if (const auto* desk = flow.desktop()) for (const auto id : desk->take_sound_ids()) app::original_audio_command(playback, id); + // Keep the audio options in step with the game's settings. if (session) playback.set_original_options(app::original_audio_options(session->state(), music_enabled)); if (playback.needs_pump()) { playback.pump(audio_error); if (!audio_error.empty()) std::fprintf(stderr, "audio: %s\n", audio_error.c_str()); } + // Present the frame. Tables redraw through their own path so that their acknowledgement + // is tied to a freshly drawn frame. if (flow.in_family_table()) { // Family ACKs belong to a freshly rendered, successfully // copied image. Do not ACK an old texture at the routine @@ -3980,6 +4370,7 @@ int main(int argc, char** argv) { throw std::runtime_error(std::string("Source modal texture: ") + SDL_GetError()); dirty = false; } + // Update the custom pitch cursor, then present the canvas texture. pitch_pointer.show(flow.pitch_pointer_cursor(palette), renderer); const int cleared = SDL_RenderClear(renderer); const int copied = SDL_RenderCopy(renderer, texture, nullptr, nullptr); @@ -4002,8 +4393,13 @@ int main(int argc, char** argv) { presented_balance=identity;presented_balance_notice=notice; } } + // Limit the loop to roughly 100 passes per second. SDL_Delay(10); } + // ===================================================================================== + // Shutdown + // ===================================================================================== + // Stop text input, release the SDL objects, detach the mouse sound and close audio. SDL_StopTextInput(); pitch_pointer.clear(); SDL_DestroyTexture(texture); @@ -4012,6 +4408,7 @@ int main(int argc, char** argv) { mouse_sound.detach(); // Remove event producers before closing the audio device. playback.shutdown(); return 0; + // Any exception from setup or the main loop is printed and ends with exit code 1. } catch (const std::exception& e) { std::fprintf(stderr, "error: %s\n", e.what()); return 1; diff --git a/src/app/window_actions.cpp b/src/app/window_actions.cpp index fbe3306..6e81675 100644 --- a/src/app/window_actions.cpp +++ b/src/app/window_actions.cpp @@ -16,6 +16,9 @@ namespace bmh::app { using detail::apply_window; +// Runs `action` as a transaction on the league family state. Returns true if the action +// succeeded; if it returns false or throws, the checkpoint and the revision are restored +// (an exception is rethrown). bool LeagueFamilyActions::apply(uint64_t& revision, const std::function& action) { auto before = session_.league_family_checkpoint(); const auto old_revision = revision; @@ -31,6 +34,8 @@ bool LeagueFamilyActions::apply(uint64_t& revision, const std::function& return false; } +// Opens the league pairings screen from the desk (menu kind 1, using the desk item of +// kind 1). Returns its state, or nothing with `error` set if the session refused. std::optional LeagueFamilyActions::open_pairings( const ui::DeskState& observed, uint64_t& revision, std::string& error) { ui::DeskRequest request; @@ -48,6 +53,7 @@ std::optional LeagueFamilyActions::open_pairings( return result; } +// Sends one pairings screen event (kind and value) to the session inside a transaction. std::optional LeagueFamilyActions::pairings( const ui::LeaguePairingsIdentity& observed, LeaguePairingsAction kind, int value, uint64_t& revision, std::string& error) { @@ -63,16 +69,19 @@ std::optional LeagueFamilyActions::pairin return result; } +// Builds the desk request that opens menu 1 (pairings) for the manager of `identity`. ui::DeskRequest LeagueFamilyActions::pairings_entry(const ui::StrengthsIdentity& identity, uint64_t revision) { return {ui::DeskRequestKind::open_menu, identity.manager, 0, 1, -1, revision}; } +// Builds the pairings request that selects `league`. ui::LeaguePairingsRequest LeagueFamilyActions::pairings_selection( const ui::LeaguePairingsIdentity& identity, int league) { return {identity, {LeaguePairingsAction::select_league, league, -1}}; } +// Turns a fresh strengths request into an `open` request bound to `identity`. ui::StrengthsRequest LeagueFamilyActions::strengths_entry(const ui::StrengthsRequest& fresh, const ui::StrengthsIdentity& identity) { auto request = fresh; @@ -81,6 +90,9 @@ ui::StrengthsRequest LeagueFamilyActions::strengths_entry(const ui::StrengthsReq return request; } +// Runs `action` as a transaction on the transfer state. Before it, the game state, random +// generators, offer editor, poach state, club modal runtime and revision are copied; they +// are all restored if the action returns false or throws (then rethrown). bool TransferActions::apply(uint64_t& revision, const std::function& action) { auto state = session_.g_; const auto game = session_.game_; @@ -90,6 +102,7 @@ bool TransferActions::apply(uint64_t& revision, const std::function& act const auto owner_revision = session_.transfer_offer_revision_; auto runtime = session_.club_modal_runtime_; const auto old_revision = revision; + // Puts every saved piece back into the session. const auto restore = [&] { session_.g_ = std::move(state); session_.game_ = game; @@ -110,12 +123,17 @@ bool TransferActions::apply(uint64_t& revision, const std::function& act return false; } +// Handles a transfer market request. In the normal interactive policy the session does +// the work (with the sale hooks and the review callback). The other policy is an older +// path that only allows listing a player and submitting a bid; it bumps the revision +// only if the state or random stream really changed. `acknowledge` is called on success. std::optional TransferActions::market( const ui::TransferMarketRequest& request, const HumanBuyerSaleHooks& hooks, uint64_t& revision, std::string& error, HumanBuyerMarketEntryPolicy policy, const MarketAccept& acknowledge, const std::function& review) { std::optional result; + // Body of the transaction; returning false rolls everything back. apply(revision, [&] { const auto old_revision = revision; if (policy == HumanBuyerMarketEntryPolicy::normal_interactive) { @@ -156,6 +174,9 @@ std::optional TransferActions::market( return result; } +// Checks a market request against the current state. Returns a German error text if the +// request is stale or invalid, or an empty string if it may proceed. Bonus values may be +// at most 255 (interactive policy) or 100 (legacy policy). std::string TransferActions::rejection(const ui::TransferMarketRequest& request, uint64_t revision, HumanBuyerMarketEntryPolicy policy) const { const auto& state = session_.state(); @@ -186,6 +207,7 @@ std::string TransferActions::rejection(const ui::TransferMarketRequest& request, return {}; } +// Opens the transfer offer editor for a market request (one transaction). std::optional TransferActions::open_offer( const ui::TransferMarketRequest& request, uint64_t& revision, std::string& error, const OfferAccept& acknowledge) { @@ -199,6 +221,7 @@ std::optional TransferActions::open_ return result; } +// Asks the session for a preview (quote) of a market request without committing it. std::optional TransferActions::preview( const ui::TransferMarketRequest& request, uint64_t& revision, std::string& error, const PreviewAccept& acknowledge) { @@ -212,6 +235,8 @@ std::optional TransferActions::pre return result; } +// Sends an action of the outgoing offer editor to the session; the team and player +// information presenters are used when it opens those screens. std::optional TransferActions::offer( const ui::OutgoingTransferRequest& request, const HumanBuyerSaleHooks& hooks, uint64_t& revision, std::string& error, const TransferOfferTeamInfoPresenter& team_info, @@ -226,6 +251,7 @@ std::optional TransferActions::offer return result; } +// Starts a poaching attempt for the given manager and squad slot. std::optional TransferActions::poach(int manager, int slot, uint64_t& revision, std::string& error) { std::optional result; @@ -236,6 +262,8 @@ std::optional TransferActions::poach(int manager, return result; } +// Builds the request to list the squad player `item` on the market (as a loan if `loan`), +// bound to the observed state's manager, club and revision. ui::TransferMarketRequest TransferActions::listing(const ui::TransferMarketState& observed, const ui::TransferMarketSquadItem& item, bool loan) { ui::TransferMarketRequest request; @@ -251,6 +279,8 @@ ui::TransferMarketRequest TransferActions::listing(const ui::TransferMarketState return request; } +// Builds the request to open an offer for the market entry `item`; an existing own bid +// is used as the starting point. ui::TransferMarketRequest TransferActions::opening(const ui::TransferMarketState& observed, const ui::TransferMarketItem& item, bool loan) { ui::TransferMarketRequest request; @@ -268,6 +298,7 @@ ui::TransferMarketRequest TransferActions::opening(const ui::TransferMarketState return request; } +// Builds a request from the offer editor's current state plus the changed field and value. ui::OutgoingTransferRequest TransferActions::editor(const ui::OutgoingTransferEditorState& observed, ui::OutgoingTransferRequestKind kind, ui::OutgoingTransferField field, uint32_t value) { ui::OutgoingTransferRequest request; @@ -287,11 +318,13 @@ ui::OutgoingTransferRequest TransferActions::editor(const ui::OutgoingTransferEd return request; } +// Runs `action` as a transaction restoring the bank checkpoint on failure. bool BankActions::apply(uint64_t& revision, const std::function& action) { return apply_window(session_, revision, session_.bank_checkpoint(), [&](CareerSession::BankCheckpoint before) { session_.restore_bank_checkpoint(std::move(before)); }, action); } +// Sends a bank request to the session; `acknowledge` is called when it was accepted. bool BankActions::dispatch(const ui::BankRequest& request, uint64_t& revision, std::string& error, const std::function& acknowledge) { return apply(revision, [&] { @@ -301,6 +334,7 @@ bool BankActions::dispatch(const ui::BankRequest& request, uint64_t& revision, s }); } +// Creates a bank request of `kind` bound to the observed manager, club and revision. ui::BankRequest BankActions::bind(const ui::BankState& observed, ui::BankRequestKind kind) { ui::BankRequest request; request.kind = kind; @@ -310,12 +344,14 @@ ui::BankRequest BankActions::bind(const ui::BankState& observed, ui::BankRequest return request; } +// Request to move `amount` to the deposit account. ui::BankRequest BankActions::savings(const ui::BankState& observed, int32_t amount) { auto request = bind(observed, ui::BankRequestKind::move_to_deposit); request.amount = amount; return request; } +// Request for an investment action on asset index `asset` with `count` units. ui::BankRequest BankActions::investment(const ui::BankState& observed, ui::BankRequestKind kind, int asset, int count) { auto request = bind(observed, kind); @@ -324,6 +360,8 @@ ui::BankRequest BankActions::investment(const ui::BankState& observed, ui::BankR return request; } +// Request for a bank credit: carries the saved credit, the player's edits, whether the +// fees are accepted and the counterparty. ui::BankRequest BankActions::credit(const ui::BankState& observed, const BankCreditContext& context, const BankCreditDraft& draft, bool accept_fees, int counterparty) { auto request = bind(observed, ui::BankRequestKind::bank_credit); @@ -334,11 +372,14 @@ ui::BankRequest BankActions::credit(const ui::BankState& observed, const BankCre return request; } +// Runs `action` as a transaction restoring the stadium checkpoint on failure. bool StadiumActions::apply(uint64_t& revision, const std::function& action) { return apply_window(session_, revision, session_.stadium_checkpoint(), [&](CareerSession::StadiumCheckpoint before) { session_.restore_stadium_checkpoint(std::move(before)); }, action); } +// Sends a stadium request to the session with the notice hooks; `acknowledge` is called +// when it was accepted. bool StadiumActions::dispatch(const ui::StadiumRequest& request, uint64_t& revision, std::string& error, const ConstructionNoticeHook& construction, const SeasonTicketCompensationNoticeHook& compensation, const std::function& acknowledge) { @@ -349,6 +390,7 @@ bool StadiumActions::dispatch(const ui::StadiumRequest& request, uint64_t& revis }); } +// Creates a stadium request bound to the observed club, revision, scope and sequence. ui::StadiumRequest StadiumActions::request(const ui::StadiumState& observed, ui::StadiumRequestKind kind, int object, int option, int32_t price, bool accept_tip) { ui::StadiumRequest request; @@ -366,6 +408,8 @@ ui::StadiumRequest StadiumActions::request(const ui::StadiumState& observed, ui: return request; } +// Sets the ticket price for the observed desk's club; the stable club identity is filled +// in when the club index is valid. bool DeskActions::ticket_price(const ui::DeskState& observed, int price, uint64_t& revision, std::string& error) { TicketPriceRequest request; @@ -378,11 +422,13 @@ bool DeskActions::ticket_price(const ui::DeskState& observed, int price, return session_.dispatch_ticket_price(request, revision, error); } +// Runs `action` as a transaction restoring the lineup checkpoint on failure. bool LineupActions::apply(uint64_t& revision, const std::function& action) { return apply_window(session_, revision, session_.lineup_checkpoint(), [&](CareerSession::LineupCheckpoint before) { session_.restore_lineup_checkpoint(std::move(before)); }, action); } +// Sends a lineup request to the session; `acknowledge` is called when accepted. bool LineupActions::lineup(const ui::LineupRequest& request, uint64_t& revision, std::string& error, const std::function& acknowledge) { return apply(revision, [&] { @@ -392,6 +438,7 @@ bool LineupActions::lineup(const ui::LineupRequest& request, uint64_t& revision, }); } +// Sends a pitch request to the session; `acknowledge` is called when accepted. bool LineupActions::pitch(const ui::PitchRequest& request, uint64_t& revision, std::string& error, const std::function& acknowledge) { return apply(revision, [&] { @@ -401,10 +448,13 @@ bool LineupActions::pitch(const ui::PitchRequest& request, uint64_t& revision, s }); } +// Sends a pitch swap request to the session as one transaction. bool LineupActions::pitch_swap(const ui::PitchRequest& request, uint64_t& revision, std::string& error) { return apply(revision, [&] { return session_.dispatch_pitch_swap(request, revision, error); }); } +// Changes one order value (`aspect`) of a player. Only valid for the observed revision; +// on success the revision is increased. bool LineupActions::order(const ui::LineupState& observed, const ui::LineupPlayer& player, int aspect, int value, uint64_t& revision) { return apply(revision, [&] { @@ -415,6 +465,9 @@ bool LineupActions::order(const ui::LineupState& observed, const ui::LineupPlaye }); } +// Tries the requested pitch move on a copy of the state and tells whether the player ends +// up paired with `second_row` (requested), with another player (other_pair) or whether the +// move is invalid. LineupActions::PairTarget LineupActions::pair_target(const ui::PitchRequest& request, int second_row) const { auto preview = session_.state(); if (!move_pitch_player_source(preview, request.manager_slot, request.runtime_club, @@ -426,6 +479,7 @@ LineupActions::PairTarget LineupActions::pair_target(const ui::PitchRequest& req ? PairTarget::requested : PairTarget::other_pair; } +// Creates a lineup request that prepares the lineup of the observed state. ui::LineupRequest LineupActions::prepare(const ui::LineupState& observed) { ui::LineupRequest request; request.kind = ui::LineupRequestKind::prepare_lineup; @@ -435,6 +489,7 @@ ui::LineupRequest LineupActions::prepare(const ui::LineupState& observed) { return request; } +// Creates a request to swap two players of the lineup. ui::LineupRequest LineupActions::swap(const ui::LineupState& observed, const ui::LineupPlayer& first, const ui::LineupPlayer& second) { auto request = prepare(observed); @@ -445,6 +500,8 @@ ui::LineupRequest LineupActions::swap(const ui::LineupState& observed, return request; } +// Creates a pitch request of `kind` bound to the observed lineup. The observed live mode +// must be known, otherwise a FormatError is thrown. ui::PitchRequest LineupActions::bind_pitch(const ui::PreparationState& observed, ui::PitchRequestKind kind) { if (!observed.pitch || !observed.pitch->indoor.has_value()) throw FormatError("pitch: missing observed live mode"); @@ -457,6 +514,7 @@ ui::PitchRequest LineupActions::bind_pitch(const ui::PreparationState& observed, return request; } +// Creates a request to swap two players on the pitch (including their current positions). ui::PitchRequest LineupActions::swap_pitch(const ui::PreparationState& observed, const ui::LineupPlayer& first, const ui::LineupPlayer& second) { auto request = bind_pitch(observed, ui::PitchRequestKind::swap_players); @@ -466,6 +524,7 @@ ui::PitchRequest LineupActions::swap_pitch(const ui::PreparationState& observed, return request; } +// Creates a request to switch the pitch page (toggles the 0x000c bits of the display word). ui::PitchRequest LineupActions::page(const ui::PreparationState& observed) { auto request = bind_pitch(observed, ui::PitchRequestKind::select_pitch_page); request.expected_mode = uint8_t(observed.pitch->mode); @@ -477,6 +536,8 @@ ui::PitchRequest LineupActions::page(const ui::PreparationState& observed) { return request; } +// Creates a request to load or save a formation in `slot`; saving copies the position +// bytes of the 11 players on the pitch. ui::PitchRequest LineupActions::formation(const ui::PreparationState& observed, ui::PitchRequestKind kind, int slot) { auto request = bind_pitch(observed, kind); @@ -492,6 +553,7 @@ ui::PitchRequest LineupActions::formation(const ui::PreparationState& observed, return request; } +// Creates a request to move a player to the given depth and lane. ui::PitchRequest LineupActions::move(const ui::PreparationState& observed, const ui::LineupPlayer& player, int depth, int lane) { auto request = bind_pitch(observed, ui::PitchRequestKind::move_player); @@ -502,6 +564,8 @@ ui::PitchRequest LineupActions::move(const ui::PreparationState& observed, const return request; } +// Creates a request that advances one of the three automatic weights (index 0..2) by one +// step; each weight is a 2-bit value that wraps around after 3. ui::PitchRequest LineupActions::weight(const ui::PreparationState& observed, int index) { if (index < 0 || index > 2) throw FormatError("pitch: invalid automatic weight index"); auto request = bind_pitch(observed, ui::PitchRequestKind::set_automatic_weight); diff --git a/src/ui/contracts.cpp b/src/ui/contracts.cpp index ab251e7..1a7bc94 100644 --- a/src/ui/contracts.cpp +++ b/src/ui/contracts.cpp @@ -15,10 +15,14 @@ namespace bmh::ui { namespace { +// Record sizes: one manager record, the per-manager block of player board entries (24 slots) +// and one board entry (per-player data such as contract, insurance and premiums). constexpr size_t kManagerRecord = 0xb0c; constexpr size_t kBoard = 0x840; constexpr size_t kBoardSlot = 0x58; +// Copies a block from a widget/atlas image to the target; throws on out-of-range rectangles. +// With `transparent` set, palette index 0 is skipped. void copy_region(Image& target, const Image& source, int sx, int sy, int x, int y, int width, int height, bool transparent = false) { if (sx < 0 || sy < 0 || x < 0 || y < 0 || width < 0 || height < 0 || sx + width > source.width || sy + height > source.height || x + width > target.width || y + height > target.height) @@ -29,14 +33,18 @@ void copy_region(Image& target, const Image& source, int sx, int sy, int x, int } } +// Forward declaration; fill() is defined below and is used by frame(). void fill(Image& target, int x, int y, int width, int height, uint8_t color); +// Tiles the 16x16 background pattern stored in the executable over a rectangle. void pattern(Image& out, const LeImage& exe, int x, int y, int width, int height) { for (int yy = 0; yy < height; ++yy) for (int xx = 0; xx < width; ++xx) out.at(x + xx, y + yy) = exe.u8(::bmh::layout::Advertising_PatternRect_RuntimeField + size_t(yy % 16) * 16 + size_t(xx % 16)); } +// Draws a panel in the original style: optional drop shadow, tiled pattern inside, four 4x4 corners +// and edge strips (copied in pieces of at most 74 pixels horizontally and 96 vertically). void frame(Image& out, const LeImage& exe, const Image& widgets, int x, int y, int width, int height, bool shadow = true) { if (shadow) { fill(out, x + 2, y + height, width, 2, 0x40); fill(out, x + width, y + 2, 2, height, 0x40); } pattern(out, exe, x + 4, y + 4, width - 7, height - 7); @@ -56,6 +64,7 @@ void frame(Image& out, const LeImage& exe, const Image& widgets, int x, int y, i } } +// Fills a rectangle with one palette index; throws if it leaves the image. void fill(Image& target, int x, int y, int width, int height, uint8_t color) { if (x < 0 || y < 0 || width < 0 || height < 0 || x + width > target.width || y + height > target.height) throw FormatError("contracts: invalid fill bounds"); @@ -63,6 +72,8 @@ void fill(Image& target, int x, int y, int width, int height, uint8_t color) { std::fill_n(target.pixels.begin() + size_t(y + row) * size_t(target.width) + size_t(x), size_t(width), color); } +// Formats a number right-aligned in `width` characters; with `grouped`, '.' is inserted as thousands separator +// and the result is padded with spaces for missing separators so columns stay aligned. // FormatGroupedDigits: '%' is the original bitmap font's blank padding glyph. std::string original_number(uint32_t value, int width, bool grouped = false) { std::string digits = std::to_string(value); @@ -78,14 +89,19 @@ std::string original_number(uint32_t value, int width, bool grouped = false) { } return digits; } +// Amount with the currency text ' EU', e.g. for the contract panels. std::string money(uint32_t value, int width = 5) { return original_number(value, width, true) + " EU"; } +// Number with thousands separators and no padding. std::string plain_number(uint32_t value) { return original_number(value, 0, true); } } +// Builds the contracts view data for one manager: club, manager identity (name, portrait, badge) and one row +// per squad player with remaining months, monthly salary, insurance data and the premium values of the board entry. +// The team premiums are the per-component minimum over all players. Called when the screen opens and after each acknowledgement. ContractsState contracts_from_game(const GameState& game, int manager_slot, uint64_t revision) { if (manager_slot < 0 || manager_slot >= 4 || size_t(manager_slot) >= game.manager_teams.size() || size_t(manager_slot) * kManagerRecord + kManagerRecord > game.manager_records.size()) @@ -131,15 +147,19 @@ ContractsState contracts_from_game(const GameState& game, int manager_slot, uint view.name = original_to_utf8(game.player_name(player)); view.age = source.age(); view.position = source.position(); + // Remaining contract in months (255 is shown with a special text by render_roster). view.remaining_months = game.tactics.at(at + 0x0c); view.current_monthly_salary = uint32_t(game.tactics.at(at + 0x50)) | uint32_t(game.tactics.at(at + 0x51)) << 8 | uint32_t(game.tactics.at(at + 0x52)) << 16 | uint32_t(game.tactics.at(at + 0x53)) << 24; view.insurance = game.tactics.at(at + 0x43); + // Insurance can be taken out only if there is none yet, flags 0x60 are clear and the player has no marker/injury in the top bits of w35c. view.insurance_available = view.insurance == 0 && (game.tactics.at(at + 0x0b) & 0x60) == 0 && (source.w35c >> 27) == 0; + // Top bit of the byte at 0x4f blocks new contract offers for this player; the low 7 bits belong to the insurance fee. view.offer_blocked = (game.tactics.at(at + 0x4f) & 0x80) != 0; + // 15-bit insurance fee: byte 0x4e plus the low 7 bits of byte 0x4f. view.insurance_fee = uint16_t(game.tactics.at(at + 0x4e)) | uint16_t(game.tactics.at(at + 0x4f) & 0x7f) << 8; for (size_t premium = 0; premium < view.team_premiums.size(); ++premium) @@ -163,6 +183,7 @@ ContractsState contracts_from_game(const GameState& game, int manager_slot, uint return state; } +// Serialises a ContractRequest as JSON (kind, ids, quote, term, demand, salary, bonuses). std::string contract_request_json(const ContractRequest& r) { const char* kind = "demands"; switch (r.kind) { @@ -184,6 +205,7 @@ std::string contract_request_json(const ContractRequest& r) { return out.str(); } +// Serialises the contracts state (players, demands, feedback) as JSON for diagnostics and tests. std::string contracts_state_json(const ContractsState& s) { std::ostringstream out; out << "{\"manager_slot\":" << s.manager_slot << ",\"runtime_club\":" << s.runtime_club @@ -210,6 +232,8 @@ std::string contracts_state_json(const ContractsState& s) { return out.str(); } +// Loads fonts, textures and executable data, validates the state, and loads the club badge image +// (the widget image is used as the badge atlas when the club has a fallback badge). ContractsScreen::ContractsScreen(const std::filesystem::path& data, ContractsState state) : state_(std::move(state)), exe_(load_le(asset_path(data, "BMH.exe"))), font_(load_font(asset_path(data / "F", "BMH3.FNT"))), @@ -231,6 +255,8 @@ ContractsScreen::ContractsScreen(const std::filesystem::path& data, ContractsSta else badge_atlas_ = load_vga(asset_path(data / "W", std::to_string(state_.badge_sprite >> 3) + ".VGA")); } +// Draws UTF-8 text with the small font at a baseline; nothing is drawn if it does not fit left of `right`. +// The colour index may be replaced by the executable's vertical text gradient when gradient text is enabled. void ContractsScreen::text(Image& out, int x, int baseline, std::string_view value, uint8_t color, int right) const { std::string bytes = utf8_to_original(value); const int limit = right < 0 ? out.width : std::min(right, out.width); @@ -247,6 +273,8 @@ void ContractsScreen::text(Image& out, int x, int baseline, std::string_view val if (mask.at(xx, yy)) out.at(x + xx, top + yy) = state_.gradient_text && exe_.u8(::bmh::layout::TextGradientMode) == 2 && gradient < 32 ? exe_.u8(::bmh::layout::Advertising_Text_RuntimeField + gradient * 6 + std::min(yy, 5)) : color; } +// Queues a request for the session: stamps it with a unique id, the state revision, manager and club. +// Only one request can be pending; further input is ignored until it is acknowledged or rejected. void ContractsScreen::emit(ContractRequest request) { if (pending_) return; request.request_id = state_.request_id_base + next_request_id_++; @@ -256,6 +284,10 @@ void ContractsScreen::emit(ContractRequest request) { pending_ = request; } +// Opens the number-entry calculator over the current screen. `target` selects what is edited: +// 0..6 = a bonus/premium (0..2 percent, max 20; 3..6 max 1000), -2 = insurance months (max 60), +// other negative = the salary offer (max 200000). Sets the maximum, six preset buttons and the initial value; +// presets above the maximum are marked UINT32_MAX (hidden) and the last two presets are 0 and the maximum. void ContractsScreen::open_calculator(int target, Page return_page, uint32_t initial) { calculator_backdrop_ = render(); calculator_bonus_index_ = target; @@ -271,6 +303,8 @@ void ContractsScreen::open_calculator(int target, Page return_page, uint32_t ini calculator_max_ = 60; for (size_t i = 0; i < 6; ++i) calculator_presets_[i] = 12u + uint32_t(i) * 6u; } else { + // Salary offer: presets are spaced by a step derived from the initial value (about a tenth, rounded to a power of ten) + // starting three steps below the value rounded down to thousands. calculator_max_ = 200000;initial=std::min(initial,calculator_max_); uint32_t factor=1000, step=0; while(!step && factor) {step=factor*((initial/factor)/10);if(!step)factor/=10;} @@ -288,6 +322,8 @@ void ContractsScreen::open_calculator(int target, Page return_page, uint32_t ini editing_salary_ = true; } +// Typed characters while the calculator is open: digits are appended unless the maximum would be exceeded, +// backspace removes the last digit. Returns true if the input changed. bool ContractsScreen::text(std::string_view value) { if (pending_ || !editing_salary_) return false; bool changed = false; @@ -304,6 +340,9 @@ bool ContractsScreen::text(std::string_view value) { return changed; } +// Draws the roster page: background (or plain bars), title, club name, column header, and one row per player. +// The three roster tabs share the layout of the lineup screen; tab_ 0 and 1 show attribute/status and statistics pages, +// tab_ 2 and 3 show age, monthly salary, remaining months and insurance. // LineupScreen, contract mode: the same roster as lineup, including its // original fixed-width number strings, jersey marks, and bitmap icons. Image ContractsScreen::render_roster() const { @@ -312,12 +351,15 @@ Image ContractsScreen::render_roster() const { fill(out, 0, 4, 320, 13, 0x44); fill(out, 1, 5, 318, 11, 0x39); fill(out, 0, 228, 320, 10, 0x44); fill(out, 1, 229, 318, 8, 0x39); } + // Draws a string in the original encoding; with `right` it is centred between x and right. auto original_text = [&](int x, int y, std::string_view raw, uint8_t color, int right = -1) { const int width = font_.text_width(raw); if (right >= 0) x += (right - x) / 2 - width / 2; text(out, x, y, original_to_utf8(raw), color, -1); }; + // Fixed-width number helper (width characters, optional thousands grouping). const auto fixed = [](uint32_t value, int width, bool grouped = false) { return original_number(value, width, grouped); }; + // Three-character number padded with '%' (used for appearance and goal counters). const auto count = [](uint64_t value) { auto s = std::to_string(value); if(s.size()<3)s.insert(0,3-s.size(),'%'); return s; }; const auto title = original_to_utf8(texts_[(::bmh::layout::Contracts_RenderRoster_TextPointer2 - ::bmh::layout::TextPointerTable) / 4]); sprite_font_.draw(out, SpriteFont::centered_title_x(sprite_font_.text_width(title)), 13, title, 5); @@ -325,6 +367,8 @@ Image ContractsScreen::render_roster() const { const auto header = tab_ == 0 ? texts_[(::bmh::layout::ClubInfo_Render_TextPointer3 - ::bmh::layout::TextPointerTable) / 4] : tab_ == 1 ? texts_[(::bmh::layout::ClubInfo_Render_TextPointer4 - ::bmh::layout::TextPointerTable) / 4] : exe_.cstring(exe_.u32(::bmh::layout::Contracts_RenderRoster_TextPointer)); original_text(0, 26, header, 0x51); int baseline = 36; + // Rows start at baseline 36 with 7 pixels per row; the baseline grows by 2 where the status bits (0xc000) of the + // slot change from the previous player (a visual gap). `preceding` remembers the previous slot word. uint16_t preceding = 0; for (size_t visual = 0; visual < state_.players.size(); ++visual) { const auto& p = state_.players[visual]; const auto& s = p.source; const auto& a = s.attributes; @@ -336,6 +380,7 @@ Image ContractsScreen::render_roster() const { original_text(4, baseline, std::string(1, char('0' + jersey % 10)), color); if (jersey >= 10) original_text(0, baseline, exe_.cstring(::bmh::layout::ClubInfo_Render_TextPointer), color); } + // Name colour: selected row, hovered row, blocked contract (tab 2 only) or alternating row colours. const uint8_t name_color = p.row == state_.selected_row ? 0x27 : p.row == hovered_row_ ? 0x3e : tab_ == 2 && (p.offer_blocked || (p.board_flags & 0x20)) ? 0xf7 : visual % 2 ? 0x67 : 0x6b; original_text(13, baseline, s.name, name_color); @@ -351,6 +396,7 @@ Image ContractsScreen::render_roster() const { if (tab_ == 2 || tab_ == 3) { values += fixed(a.age(), 2) + texts_[(::bmh::layout::Contracts_RenderRoster_TextPointer3 - ::bmh::layout::TextPointerTable) / 4]; const uint32_t numerator = state_.currency_numerator, denominator = state_.currency_denominator; + // Amount scaled with the currency multiplier/divisor followed by the currency suffix. const auto currency = [&](uint32_t value, int width) { return fixed(uint32_t(value * numerator) / denominator, width, true) + exe_.cstring(::bmh::layout::CurrencySuffixText); }; values += currency(p.current_monthly_salary, 6) + exe_.cstring(::bmh::layout::Contracts_RenderRoster_ExecutableField2); values += p.remaining_months == 255 ? exe_.cstring(::bmh::layout::Contracts_RenderRoster_ExecutableField3) : fixed(p.remaining_months, 2) + exe_.cstring(::bmh::layout::Contracts_RenderRoster_ExecutableField4); @@ -378,6 +424,7 @@ Image ContractsScreen::render_roster() const { } else { original_text(65, baseline, fixed(a.age(), 2) + texts_[(::bmh::layout::ClubInfo_Render_TextPointer5 - ::bmh::layout::TextPointerTable) / 4], 0x6c); for (int skill = 0; skill < 7; ++skill) copy_region(out, atlas_, 256 + a.skill(Player::Skill(skill)) * 16, 32, 87 + skill * 10, baseline - 5, 16, 5, true); + // Reads a little-endian 16-bit value from the player's board entry. auto word = [&](int at) { return uint16_t(s.board[at] | uint16_t(s.board[at + 1]) << 8); }; original_text(165, baseline, fixed(s.bonus & 127, 3) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField5) + count(s.statistics ? s.statistics->appearances[0] : s.board[7]) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField5) + count(s.statistics ? s.statistics->appearances[2] : s.board[9]) + exe_.cstring(::bmh::layout::ClubInfo_Render_ExecutableField5) + count(s.statistics ? s.statistics->total : word(0x48)) + exe_.cstring(::bmh::layout::ClubInfo_Raw_ExecutableField2) + @@ -388,6 +435,8 @@ Image ContractsScreen::render_roster() const { return out; } +// Renders the complete screen. The base is the roster, or the saved backdrop while the calculator or the +// result dialog is shown; on top come the tab buttons and the negotiation panel, calculator or result notice. Image ContractsScreen::render() const { Image out(320, 240); if (page_ == Page::result && result_backdrop_) out = *result_backdrop_; @@ -399,6 +448,7 @@ Image ContractsScreen::render() const { } const auto selected = std::find_if(state_.players.begin(), state_.players.end(), [&](const auto& p) { return p.row == state_.selected_row; }); + // Tab captions come from text entries 117..120; the fourth tab (team premiums) exists only in mode three. const std::array tabs{original_to_utf8(texts_[117]),original_to_utf8(texts_[118]),original_to_utf8(texts_[119]),original_to_utf8(texts_[120])}; for (int i = 0; i < (state_.mode_three?4:3); ++i) { const int x = i * 60 + 2, w = i == 3 ? 71 : 51; @@ -414,9 +464,11 @@ Image ContractsScreen::render() const { sprite_font_.draw(out, dest_x + w/2 - sprite_font_.text_width(tabs[size_t(i)])/2, dest_y+7, tabs[size_t(i)], exe_.u8(::bmh::layout::Advertising_Button_RuntimeField + (i==tab_))); } + // Draws a framed panel. auto panel = [&](int x, int y, int w, int h, bool shadow = true) { frame(out, exe_, widgets_, x, y, w, h, shadow); }; + // Draws a button of width w: 31 pixel left part, repeated strips and the right end, with the label centred. auto button = [&](int x, int y, int w, std::string_view label) { fill(out, x + 2, y + 10, w, 2, 0x40); fill(out, x + w, y + 2, 2, 10, 0x40); copy_region(out, widgets_, 24, 74, x, y, 31, 10); @@ -426,11 +478,15 @@ Image ContractsScreen::render() const { const int font = exe_.u8(::bmh::layout::Advertising_Button_RuntimeField); sprite_font_.draw(out, x + (w - sprite_font_.text_width(label)) / 2, y + 7, label, font); }; + // Looks up a text from the original text table by its pointer-table address. auto db = [&](uint32_t address) { return original_to_utf8(texts_[(address-::bmh::layout::TextPointerTable)/4]); }; + // Draws text centred between two x positions. auto centered = [&](int left,int right,int y,std::string_view value,uint8_t color) { const int x=left+(right-left)/2-font_.text_width(utf8_to_original(value))/2; text(out,x,y,value,color,-1); }; + // Negotiation panel: player offer page or premium page. It is placed at y=22 for team premiums or for players + // in rows >= 13, otherwise at y=130, so the selected player's row stays visible. const bool negotiating = page_ == Page::player_offer || page_ == Page::team_premiums; if (negotiating) { const bool team = page_ == Page::team_premiums && team_premium_mode_; @@ -452,20 +508,27 @@ Image ContractsScreen::render() const { if(page_==Page::player_offer && selected!=state_.players.end()) { text(out,5,top+46,db(::bmh::layout::Contracts_Out_ExecutableField14),106,-1);text(out,5,top+54,db(::bmh::layout::Contracts_Out_TextPointer5),106,-1); if(state_.mode_three)text(out,5,top+72,db(::bmh::layout::Contracts_Out_TextPointer6),106,-1); + // Four contract-term columns (1..4 years), 60 pixels wide from x=70: the entered salary offer for the chosen term, + // the club's demand for each term (UINT32_MAX = no quote yet) and, in mode three, the insurance row. for(int term=0;term<4;++term) { const int left=70+60*term; centered(left,left+60,top+37,std::to_string(term+1)+db(::bmh::layout::Contracts_Out_ExecutableField15)+(term?exe_.cstring(::bmh::layout::ClubPlayerDetail_RenderCard_TextPointer):""),107); if(salary_offer_set_ && term==offer_term_) centered(left,left+60,top+46,money(offer_salary_),108); + // Demand is shown in a different colour (251) if no quote exists or the player cannot receive offers. const uint32_t demand=state_.demands?(*state_.demands)[size_t(term)]:UINT32_MAX; centered(left,left+60,top+54,demand==UINT32_MAX?db(::bmh::layout::Contracts_Out_ExecutableField16):money(demand), demand==UINT32_MAX || selected->offer_blocked || (selected->board_flags&0x60)?251:95); if(state_.mode_three) { centered(left,left+55,top+64,db(::bmh::layout::ClubPlayerDetail_Copy_TextPointer6+term*4),107); + // Insurance fee shown per insurance term column; the active insurance term is highlighted. const uint32_t fee=(((uint32_t(term*10+10)*selected->current_monthly_salary)/1000)*10); centered(left,left+60,top+72,original_number(fee,5,true)+db(::bmh::layout::ClubPlayerDetail_Copy_ExecutableField4),selected->insurance && ((selected->insurance>>6)&3)==term?39:106); } } } else { + // Premium page: seven bonus lines. The shown amount is the percentage (rate times 1 for the first three lines, + // times 5 for the others) of the basis salary: the player's monthly salary, or for the team page a value derived from + // the summed salaries and the number of players. uint32_t base=0; int occupied=0; if(team)for(const auto& p:state_.players){base+=p.current_monthly_salary;++occupied;} else if(selected!=state_.players.end())base=selected->current_monthly_salary; @@ -484,6 +547,8 @@ Image ContractsScreen::render() const { button(5,top+76,51,db(::bmh::layout::Contracts_Out_ExecutableField17));button(90,top+76,80,db(::bmh::layout::Contracts_Out_ExecutableField18)); if(!team&&state_.mode_three)button(261,top+76,51,db(page_==Page::player_offer?::bmh::layout::Contracts_Out_ExecutableField2: ::bmh::layout::Contracts_Out_ExecutableField)); } else if (page_ == Page::calculator) { + // Calculator: background image at (10,10), drop shadow, label, 15 keys (digits and the letters D, R, C, J, N), + // 8 preset buttons and the current input right-aligned. Key and preset positions come from tables in the executable. copy_region(out, calculator_, 0, 0, 10, 10, 113, 136); fill(out,123,12,2,136,0x40);fill(out,12,146,113,2,0x40); const auto label=calculator_bonus_index_==-2?db(::bmh::layout::Contracts_Out_ExecutableField19):calculator_bonus_index_<0?db(::bmh::layout::Contracts_Out_ExecutableField14):db(::bmh::layout::Contracts_Out_ExecutableField4+calculator_bonus_index_*4); @@ -502,6 +567,7 @@ Image ContractsScreen::render() const { const auto value=plain_number(salary_input_); text(out,116-font_.text_width(value),120,value,0,-1); } else if (page_ == Page::result) { + // Result page: the manager's answer is shown as the original-style notice dialog over the saved backdrop. TaxDialogProjection notice; notice.manager_name=utf8_to_original(state_.manager_name); notice.portrait=state_.manager_portrait; @@ -515,6 +581,11 @@ Image ContractsScreen::render() const { return out; } +// Handles a mouse click on the current page and returns true if the screen changed. +// Result page: the OK button closes the notice. Roster: right click on a name asks for the player's demands +// (a request that the session acknowledges), the tab row switches tabs, left click on a name shows player info. +// Calculator: keys, presets and accept/cancel. Offer and premium pages: term columns, premium lines and the buttons +// at top+76 (back, send, switch page). bool ContractsScreen::click(int x, int y, bool right) { if (page_ == Page::result) { if (x >= 95 && x <= 220 && y >= 166 && y <= 176) { page_ = result_return_; result_backdrop_.reset(); state_.feedback.clear(); return true; } @@ -538,6 +609,8 @@ bool ContractsScreen::click(int x, int y, bool right) { if(right && page_==Page::calculator){page_=calculator_return_;calculator_backdrop_.reset();editing_salary_=false;return true;} if(right && page_!=Page::roster){page_=Page::roster;return true;} if (page_ == Page::calculator) { + // Applies the calculator value for the edited target: bonus (stored as value, or value/5 for the lines from 3), + // insurance (creates an insure_player request, max 60 months) or the salary offer for the chosen term. auto accept_calculator = [&]() { if (calculator_bonus_index_ >= 0) { const auto selected_player = std::find_if(state_.players.begin(), state_.players.end(), [&](const auto& p) { return p.row == state_.selected_row; }); @@ -562,6 +635,7 @@ bool ContractsScreen::click(int x, int y, bool right) { salary_input_ = 0; return true; } + // Digit keys type, then the editing keys in order: backspace, reset to initial value, clear, accept, cancel. // Key positions are read from the original calculator hitbox table. for (int i = 0; i < 15; ++i) { const int key_x = 10 + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField + size_t(i) * 2); @@ -663,6 +737,8 @@ bool ContractsScreen::click(int x, int y, bool right) { return false; } +// Called when the pointer-hold timer fires: on the roster it behaves like a right click (opens the talk with the +// player under the pointer), on the calculator and the negotiation pages it discards the local input and goes back. bool ContractsScreen::process_timer_expired(int pointer_x, int pointer_y) { //InstallDefaultHooks(0x80) dispatches event8 against the actual name-column row: //outside the list it returns; over a player it enters the normal talk. @@ -688,6 +764,7 @@ bool ContractsScreen::process_timer_expired(int pointer_x, int pointer_y) { return false; // result notices retain their separate physical input owner } +// Pointer movement over the roster names (x 0..60): updates the hovered row; returns true if it changed. bool ContractsScreen::move(int x,int y) { if (page_ != Page::roster || pending_) return false; int next=-1, baseline=36; @@ -700,6 +777,7 @@ bool ContractsScreen::move(int x,int y) { hovered_row_=next;return true; } +// Keyboard input: Esc goes back one page or closes the screen (ignored in the calculator), digits, backspace and clear edit the calculator value. bool ContractsScreen::key(std::string_view key) { if (key == "ESC" || key == "ESCAPE") { if (page_ == Page::calculator) return false; @@ -718,6 +796,8 @@ bool ContractsScreen::key(std::string_view key) { return false; } +// Session reply to a demands request: checks that it matches the pending request and player, takes over the new +// state with the demands and quote id, resets the form and opens the player offer page. void ContractsScreen::acknowledge_quote(const ContractsState& state) { if (!pending_ || pending_->kind != ContractActionKind::request_demands || state.revision <= state_.revision || state.manager_slot != state_.manager_slot || state.runtime_club != state_.runtime_club || !state.demands || @@ -742,6 +822,7 @@ void ContractsScreen::acknowledge_quote(const ContractsState& state) { page_ = Page::player_offer; } +// Session reply to an offer (or bonus) request: takes over the new state and shows the manager's answer as result page. void ContractsScreen::acknowledge_offer(const ContractsState& state) { if (!pending_ || (pending_->kind != ContractActionKind::submit_offer && pending_->kind != ContractActionKind::submit_bonuses) || state.revision <= state_.revision || state.manager_slot != state_.manager_slot || state.runtime_club != state_.runtime_club) @@ -757,6 +838,7 @@ void ContractsScreen::acknowledge_offer(const ContractsState& state) { result_return_=Page::roster;page_ = Page::result; } +// Session reply to a bonus request: takes over the new state; the result page is shown only if there is a message. void ContractsScreen::acknowledge_bonus_offer(const ContractsState& state) { if (!pending_ || pending_->kind != ContractActionKind::submit_bonuses || state.revision <= state_.revision || state.manager_slot != state_.manager_slot || state.runtime_club != state_.runtime_club) @@ -766,6 +848,7 @@ void ContractsScreen::acknowledge_bonus_offer(const ContractsState& state) { state_ = state; state_.request_id_base = base; pending_.reset(); result_return_=Page::roster;page_ = state.feedback.empty() ? Page::roster : Page::result; } +// Session reply to an insurance request: checks quote and player identity, takes over the state, back to the offer page. void ContractsScreen::acknowledge_insurance(const ContractsState& state) { if (!pending_ || pending_->kind != ContractActionKind::insure_player || state.revision <= state_.revision || state.manager_slot != state_.manager_slot || state.runtime_club != state_.runtime_club || @@ -780,6 +863,7 @@ void ContractsScreen::acknowledge_insurance(const ContractsState& state) { calculator_backdrop_.reset(); editing_salary_ = false; } +// Session rejection of the pending request: shows the reason as feedback; a rejected insurance returns to the offer page. void ContractsScreen::reject(std::string feedback) { if (!pending_) throw FormatError("contracts: no action to reject"); const auto kind = pending_->kind; @@ -787,6 +871,7 @@ void ContractsScreen::reject(std::string feedback) { if (kind == ContractActionKind::insure_player) page_ = Page::player_offer; } +// State as JSON for tests: contracts state plus calculator input, selected term, editing flag and page. std::string ContractsScreen::state_json() const { auto out = contracts_state_json(state_); out.pop_back(); diff --git a/src/ui/incoming_transfer.cpp b/src/ui/incoming_transfer.cpp index 25feec0..fcbfde5 100644 --- a/src/ui/incoming_transfer.cpp +++ b/src/ui/incoming_transfer.cpp @@ -19,18 +19,23 @@ namespace bmh::ui { namespace { +// Addresses of the three possible screen titles (generic, player purchase, player loan), the text pointer table base +// and the byte size of one manager record. constexpr uint32_t kTitleText = ::bmh::layout::TitleText; constexpr uint32_t kPurchaseTitleText = ::bmh::layout::PurchaseTitleText; constexpr uint32_t kLoanTitleText = ::bmh::layout::LoanTitleText; constexpr uint32_t kTextBase = ::bmh::layout::TextPointerTable; constexpr size_t kManagerRecord = 0xb0c; +// Returns the TEXTD string for a text-table address; throws if the address is not a table entry. std::string_view text_at(const TextDb& texts, uint32_t address) { if (address < kTextBase || (address - kTextBase) % 4 != 0) throw FormatError("incoming transfer: invalid original text address"); return texts[(address - kTextBase) / 4]; } +// Copies a block from a source image to the target; throws on invalid bounds. +// Pixels equal to `transparent_index` (if >= 0) are skipped. void copy_region(Image& target, const Image& source, int sx, int sy, int x, int y, int width, int height, int transparent_index = -1) { if (sx < 0 || sy < 0 || x < 0 || y < 0 || width < 0 || height < 0 || @@ -43,6 +48,8 @@ void copy_region(Image& target, const Image& source, int sx, int sy, int x, int } } +// Formats a number right-aligned in `width` characters ('%' padding, as the original font expects); +// with `grouping` it adds thousands separators and compensates with leading spaces so columns line up. std::string source_number(uint32_t value, int width, bool grouping = true) { std::string digits = std::to_string(value); const int actual = int(digits.size()); @@ -58,18 +65,21 @@ std::string source_number(uint32_t value, int width, bool grouping = true) { return digits; } +// Amount converted with the currency numerator/denominator (if the denominator is non-zero) and suffixed with ' EU'. std::string source_money(uint32_t value, int width, uint32_t numerator, uint32_t denominator) { if (denominator != 0) value = uint32_t((uint64_t(value) * uint64_t(numerator)) / uint64_t(denominator)); return source_number(value, width, true) + " EU"; } +// Badge sprite selector of a club (low 9 bits of its 16-bit entry), or -1 if the club is out of range. int team_badge(const GameState& game, int team) { if (team < 0 || team >= 168 || size_t(team) * 2 + 2 > game.club_heap_78.size()) return -1; return (int(game.club_heap_78[size_t(team) * 2]) | int(game.club_heap_78[size_t(team) * 2 + 1]) << 8) & 0x1ff; } +// Badge selector of the club managed by the given manager slot, or -1 if unavailable. int manager_badge(const GameState& game, int manager) { if (manager < 0 || size_t(manager) >= game.manager_teams.size() || size_t(manager) * kManagerRecord + 0x223 > game.manager_records.size()) return -1; @@ -78,17 +88,22 @@ int manager_badge(const GameState& game, int manager) { return team_badge(game, team); } +// Seller club token with the high flag bits removed (low 12 bits); negative values are returned unchanged. int source_seller_team_token(const IncomingTransferDecisionState& state) { const int token = state.seller_team_token >= 0 ? state.seller_team_token : state.seller; return token >= 0 ? (token & 0x0fff) : token; } +// True if the seller token uses the neutral fallback badge instead of a club badge. bool source_neutral_seller_token(int token) { return original_badge_fallback(token); } } // namespace namespace { +// Shared builder of the decision view: validates the context (list entry 0..39, or 0..43 for the editor that also +// serves poach rows; 40..43 only for the pending-offer variant), fills player, seller, quote, currency and viewer data, +// and checks every bid slot. Throws FormatError on any inconsistency. IncomingTransferDecisionState incoming_transfer_decision_from_game_impl( const GameState& game, const IncomingTransferDecisionView& view, bool pending_offer_source) { // the outgoing offer editor also runs on the special rows 40..43 when poaching @@ -119,6 +134,7 @@ IncomingTransferDecisionState incoming_transfer_decision_from_game_impl( out.seller_name = (view.seller == 0x0fff || view.seller == kNoTeam) ? std::string() : game.club_name(view.seller); // ClubName2 derives this label from the seller team token. A club is // named directly; the player-pool token resolves to the original adviser. + // Negotiator label: the seller club, or a default adviser text when the player has no seller club (pool token). out.negotiator_name = (view.seller == 0x0fff || view.seller == kNoTeam) ? (game.texts ? (*game.texts)[925] : "SPIELERBERATER") : out.seller_name; @@ -151,6 +167,7 @@ IncomingTransferDecisionState incoming_transfer_decision_from_game_impl( out.manager_portrait = game.manager_records[size_t(manager) * kManagerRecord + 0x221]; // The KB31 panel uses its static manager artwork and does not draw // this portrait. Source notices can use portrait 12..14 as well. + // Portraits 12..14 are valid only for the pending-offer and editor variants. if (out.manager_portrait > ((pending_offer_source || out.source_outgoing_editor_context) ? 14 : 11)) throw FormatError("incoming transfer: invalid viewer portrait"); out.notice_badge_fallback=source_badge_fallback(pending_offer_source?pending_team:game.manager_teams[size_t(manager)]); @@ -159,6 +176,7 @@ IncomingTransferDecisionState incoming_transfer_decision_from_game_impl( for (int i = 0; i < 4; ++i) { auto& offer = out.offers[size_t(i)]; if (offer.present) { + // Special buyer slot (manager 4) allowed only for the pending-offer variant in bid slot 0. const bool spare_buyer = pending_offer_source && i == 0 && offer.buyer_manager == 4 && pending_offer_spare_buyer(game, view.list_entry - 40, offer.buyer); if (offer.bid_index != i || offer.buyer < 0 || size_t(offer.buyer) >= game.club_ids.size() || @@ -182,11 +200,14 @@ IncomingTransferDecisionState incoming_transfer_decision_from_game_impl( } } // namespace +// Builds the decision view for an ordinary listing (not the pending-offer variant). IncomingTransferDecisionState incoming_transfer_decision_from_game( const GameState& game, const IncomingTransferDecisionView& view) { return incoming_transfer_decision_from_game_impl(game, view, false); } +// Builds the decision view for the pending-offer variant: only the special list entries 40..43 are accepted and they must +// hold exactly one bid (slot 0). Copies the offer list into a decision view and defers to the shared builder. IncomingTransferDecisionState incoming_transfer_pending_decision_from_game( const GameState& game, const TransferOfferListView& source) { if (!source.valid || source.list_entry < 40 || source.list_entry >= 44 || @@ -213,6 +234,7 @@ IncomingTransferDecisionState incoming_transfer_pending_decision_from_game( // DispatchClubPlayerPendingOffers owns pending-action notices through PendingOfferHooks::notice. // Its Source continuation redraws the chooser after SDLFlushEvents3, so this // special adapter must not create the generic retry overlay a second time. + // No generic notice here: the caller shows the pending-action notices itself (see the comment above). view.notice_text_address = 0; for (size_t i = 0; i < view.offers.size(); ++i) { const auto& from = source.offers[i]; @@ -234,6 +256,7 @@ IncomingTransferDecisionState incoming_transfer_pending_decision_from_game( return incoming_transfer_decision_from_game_impl(game, view, true); } +// Serialises the decision view (player, seller, quote, bid slots) as JSON for diagnostics and tests. std::string incoming_transfer_decision_json(const IncomingTransferDecisionState& state) { std::ostringstream out; out << "{\"screen\":\"incoming_transfer_decision\",\"pending_offer_source\":" @@ -283,6 +306,8 @@ std::string incoming_transfer_decision_json(const IncomingTransferDecisionState& return out.str(); } +// Loads fonts and images, validates the view (list entry range, assets, preferred bid present, only bid 0 for the +// pending variant) and loads the buyer-side and seller-side badge images. A notice text from the state is shown first. IncomingTransferScreen::IncomingTransferScreen(const std::filesystem::path& data, IncomingTransferDecisionState state, bool gradient_text) @@ -312,6 +337,7 @@ IncomingTransferScreen::IncomingTransferScreen(const std::filesystem::path& data // SourceBadgeFallback chooses the neutral fallback from the raw team token before // indexing ClubBadgeSelectors. A real selector can itself be 90..137 and must still // load its W atlas, so do not classify seller art by selector value. + // Seller badge: neutral fallback tiles come from the widget image; real club badges from the per-club image file. seller_badge_atlas_ = source_neutral_seller_token(source_seller_team_token(state_)) || state_.seller_badge_sprite < 0 ? widgets_ : load_vga(asset_path(data / "W", std::to_string(state_.seller_badge_sprite >> 3) + ".VGA")); @@ -322,11 +348,14 @@ IncomingTransferScreen::IncomingTransferScreen(const std::filesystem::path& data } } +// Draws text at a baseline (convenience wrapper around draw_top). void IncomingTransferScreen::draw_body(Image& out, int x, int baseline, std::string_view text, uint8_t color) const { draw_top(out, x, baseline - body_.baseline, text, color); } +// Draws body-font text with its top at y; clipped texts are skipped. With gradient text on (mode 2) the glyph pixels +// take a per-row colour from the executable table instead of the plain colour. void IncomingTransferScreen::draw_top(Image& out, int x, int y, std::string_view text, uint8_t color) const { if (text.empty()) return; @@ -344,6 +373,7 @@ void IncomingTransferScreen::draw_top(Image& out, int x, int y, std::string_view gradient < 32 ? exe_.u8(::bmh::layout::Advertising_Text_RuntimeField + uint32_t(gradient * 6 + std::min(yy, 5))) : color; } +// Draws text with the larger heading font at a baseline. void IncomingTransferScreen::draw_heading(Image& out, int x, int baseline, std::string_view text, uint8_t color) const { const int top = baseline - heading_.baseline; @@ -351,8 +381,11 @@ void IncomingTransferScreen::draw_heading(Image& out, int x, int baseline, std:: heading_.draw(out, x, top, text, color); } +// Renders the screen at time 0 (no outcome animation progress). Image IncomingTransferScreen::render() const { return render_at_elapsed(0); } +// Starts the passive outcome display: row_count bid rows are resolved one after another, the row accepted_bid_index +// (or none, -1) is accepted; outcome_delay_disabled == 0 means the blinking delay is used, otherwise rows resolve at once. void IncomingTransferScreen::begin_outcome(int row_count, int accepted_bid_index, uint8_t outcome_delay_disabled) { if (row_count < 0 || row_count > int(state_.offers.size()) || accepted_bid_index < -1 || accepted_bid_index >= row_count || @@ -364,6 +397,7 @@ void IncomingTransferScreen::begin_outcome(int row_count, int accepted_bid_index outcome_dismissed_ = false; } +// Total duration of the outcome animation: 8 phases per resolved row, up to and including the accepted row. uint64_t IncomingTransferScreen::outcome_duration_ms() const { if (outcome_row_count_ < 0) return 0; const int rows = outcome_accepted_bid_index_ >= 0 @@ -371,6 +405,9 @@ uint64_t IncomingTransferScreen::outcome_duration_ms() const { return uint64_t(rows) * 8u * (outcome_speed_setting_ == 0 ? outcome_phase_ms : 0u); } +// Outcome animation state at a given time. Offer state machine: rows are resolved in order; each row shows a blinking +// question mark for 8 phases (colour alternates every phase), then the row becomes rejected (NEIN) or, if it is the +// accepted bid, accepted (OK) and the sequence stops. `complete` is set once the full duration has elapsed. IncomingTransferOutcomeFrame IncomingTransferScreen::outcome_frame_at(uint64_t elapsed_ms) const { IncomingTransferOutcomeFrame frame; if (outcome_row_count_ < 0 || outcome_dismissed_) return frame; @@ -400,6 +437,10 @@ IncomingTransferOutcomeFrame IncomingTransferScreen::outcome_frame_at(uint64_t e return frame; } +// Renders the whole screen at the given outcome time. Layout: background, the negotiation panel (320x206) at y=0x13, +// title, player line (baseline 25), quote line (baseline 32), seller/buyer headings (baselines 39 and 46), the seller badge, +// the asking fee and salary (baseline 123), and four bid rows (two text lines each, 0x11 pixels apart from baseline 0x95). +// Outcome marks are drawn at x=0xb2 and notices on top. In confirmation mode only the saved backdrop and the notice are drawn. Image IncomingTransferScreen::render_at_elapsed(uint64_t elapsed_ms) const { if (confirmation_mode_) { Image out = *confirmation_backdrop_; @@ -415,6 +456,7 @@ Image IncomingTransferScreen::render_at_elapsed(uint64_t elapsed_ms) const { const auto title = original_to_utf8(text_at(texts_, title_address)); sprite_font_.draw(out, SpriteFont::centered_title_x(sprite_font_.text_width(title)), 13, title, 5); sprite_font_.draw(out, 5, 235, original_to_utf8(state_.player_name), 5); + // Draws text centred between two x positions. auto centered = [&](int left, int right, int baseline, std::string_view text, uint8_t color) { const int width = body_.text_width(text); draw_body(out, left + (right - left) / 2 - width / 2, baseline, text, color); @@ -430,6 +472,7 @@ Image IncomingTransferScreen::render_at_elapsed(uint64_t elapsed_ms) const { centered(0, 319, 25, detail, 0x6a); // DrawnFirstBy(..., 0x40): draw the flat shadow two pixels right/down. + // Draws text with a flat dark shadow offset by 2 pixels right and down. auto shadow_text = [&](int x, int baseline, std::string_view text, uint8_t color) { if (x + 2 + body_.text_width(text) <= out.width && baseline + 2 < out.height) body_.draw(out, x + 2, baseline + 2 - body_.baseline, text, 0x40); @@ -441,6 +484,8 @@ Image IncomingTransferScreen::render_at_elapsed(uint64_t elapsed_ms) const { shadow_text(170, 46, state_.player_name, 0x5f); const bool source_neutral_badge = source_neutral_seller_token(source_seller_team_token(state_)); + // Neutral badge: a 40x40 bevelled frame (light top/left, dark bottom/right) with a neutral tile inside; otherwise the + // seller club's own 38x38 badge is cut from its image. if (source_neutral_badge) { // SourceBadgeFallback passes seller|0x8000. These Source token families route // through FormatError(type 14): frame first, then the neutral KB0 tile. @@ -457,6 +502,7 @@ Image IncomingTransferScreen::render_at_elapsed(uint64_t elapsed_ms) const { // OpenTransferEditor's seller view uses the single quoted line at baseline 32; // the separate "Angebot" strings are only drawn when param_3 == -1. + // Quote line: quoted fee, monthly salary and number of years in one text built from several table entries. std::string quote = std::string(text_at(texts_, ::bmh::layout::IncomingTransfer_RenderAtElapsed_TextPointer12)) + source_money(state_.quoted_fee, 1, state_.currency_numerator, state_.currency_denominator) + std::string(text_at(texts_, ::bmh::layout::IncomingTransfer_RenderAtElapsed_TextPointer13)) + @@ -480,6 +526,8 @@ Image IncomingTransferScreen::render_at_elapsed(uint64_t elapsed_ms) const { draw_body(out, 4, 0x99 + int(i) * 0x11, text_at(texts_, ::bmh::layout::IncomingTransfer_RenderAtElapsed_TextPointer9), 0x67); continue; } + // Contract length in whole years, rounded up from months. The first line shows buyer and years, the second fee and salary; + // loan offers use a different colour. const int years = (int(offer.contract_months) - 1) / 12 + 1; const uint8_t offer_color = offer.loan ? 0x69 : 0x6c; const std::string first = state_.buyer_names[i] + exe_.cstring(::bmh::layout::Fltd_Layout_TextPointer2) + @@ -515,6 +563,7 @@ Image IncomingTransferScreen::render_at_elapsed(uint64_t elapsed_ms) const { return out; } +// Switches to confirmation mode: shows the given text as a notice over a saved backdrop (320x240). void IncomingTransferScreen::show_confirmation(uint32_t original_text_address, const Image& backdrop) { if (backdrop.width != 320 || backdrop.height != 240 || state_.viewer_manager < 0 || state_.manager_portrait < 0 || state_.badge_sprite < 0) @@ -527,16 +576,19 @@ void IncomingTransferScreen::show_confirmation(uint32_t original_text_address, c confirmation_backdrop_ = backdrop; } +// Closes an ordinary notice; confirmation notices are closed by their button instead. Returns true if one was closed. bool IncomingTransferScreen::dismiss_notice() { if (confirmation_mode_ || !notice_active_) return false; notice_active_ = false; return true; } +// Remembers which mouse button went down (bit 1 left, bit 2 right); a click counts on release. void IncomingTransferScreen::pointer_down(bool right) { pointer_buttons_ |= right ? 2 : 1; } +// Mouse release: if the matching button was pressed, handles it as a click and returns its result. std::optional IncomingTransferScreen::pointer_up(int x, int y, bool right, uint64_t elapsed_ms) { const uint8_t button = right ? 2 : 1; if (!(pointer_buttons_ & button)) return std::nullopt; @@ -544,6 +596,10 @@ std::optional IncomingTransferScreen::pointer_up(int x, int y, bool right, return click(x, y, right, elapsed_ms); } +// Handles a click and returns the decision when one is made: the chosen bid slot 0..3, or -1 for right click (back). +// Order: confirmation button, outcome dismissal (right click once the animation is complete), notice dismissal, +// then the bid area (x 4..190, y from 0x8f, rows 0x11 pixels high). Empty slots, unsupported transactions +// (except in the pending variant) and clicks after an answer are ignored. std::optional IncomingTransferScreen::click(int x, int y, bool right, uint64_t elapsed_ms) { if (confirmation_mode_) { if (!right && x >= 95 && x <= 220 && y >= 166 && y <= 176) @@ -573,6 +629,7 @@ std::optional IncomingTransferScreen::click(int x, int y, bool right, uint6 return answer_; } +// Keyboard: any key closes a notice; Esc answers -1 (back). Ignored during confirmation and outcome display. std::optional IncomingTransferScreen::key(std::string_view name) { if (confirmation_mode_ || outcome_row_count_ >= 0) return std::nullopt; if (notice_active_) { dismiss_notice(); return std::nullopt; } @@ -581,6 +638,7 @@ std::optional IncomingTransferScreen::key(std::string_view name) { return std::nullopt; } +// State as JSON for tests: the decision JSON plus answer, notice, outcome and confirmation fields when active. std::string IncomingTransferScreen::state_json() const { auto json = incoming_transfer_decision_json(state_); if (answer_) { @@ -607,6 +665,7 @@ std::string IncomingTransferScreen::state_json() const { return json; } +// Draws the manager notice dialog (manager name, portrait, club badge and the notice text) over the screen. void IncomingTransferScreen::draw_notice(Image& out) const { if (state_.viewer_manager < 0 || state_.manager_portrait < 0 || state_.badge_sprite < 0) return; TaxDialogProjection notice; diff --git a/src/ui/outgoing_transfer.cpp b/src/ui/outgoing_transfer.cpp index 388d992..46827d4 100644 --- a/src/ui/outgoing_transfer.cpp +++ b/src/ui/outgoing_transfer.cpp @@ -17,19 +17,26 @@ namespace bmh::ui { namespace { +// Address of the text pointer table; text addresses used by this screen are converted to TEXTD indices relative to it. +// Calculator position on screen: its top-left corner is (103,55). constexpr uint32_t kTextBase = ::bmh::layout::TextPointerTable; constexpr int kCalculatorX = 103, kCalculatorY = 55; +// Footer buttons (Team-Info, Spieler-Info, Angebot, Abbruch): left x of each of the four, common y, width and +// height (the hit area includes the right and bottom edge). constexpr std::array kFooterButtonX{1, 80, 156, 232}; // FormatError3 stores the adjusted height 10 in the hit descriptor; ExpireQuestion's // right/bottom comparisons are inclusive, so the hit rectangle ends at y=225. constexpr int kFooterButtonY = 215, kFooterButtonWidth = 75, kFooterButtonHeight = 10; +// Returns the TEXTD string for a text-table address; throws if the address is not a table entry. std::string_view text_at(const TextDb& texts, uint32_t address) { if (address < kTextBase || (address - kTextBase) % 4 != 0) throw FormatError("outgoing transfer: invalid Source TEXTD address"); return texts[(address - kTextBase) / 4]; } +// Copies a block from a source image to the target; throws on invalid bounds. +// Pixels equal to `transparent` (if >= 0) are skipped. void copy_region(Image& target, const Image& source, int sx, int sy, int x, int y, int width, int height, int transparent = -1) { if (sx < 0 || sy < 0 || x < 0 || y < 0 || width < 0 || height < 0 || @@ -42,6 +49,7 @@ void copy_region(Image& target, const Image& source, int sx, int sy, int x, int } } +// Fills a rectangle with one palette index; throws if it leaves the image. void fill_rect(Image& out, int x, int y, int width, int height, uint8_t color) { if (x < 0 || y < 0 || width < 0 || height < 0 || x + width > out.width || y + height > out.height) throw FormatError("outgoing transfer: invalid Source rectangle"); @@ -49,12 +57,15 @@ void fill_rect(Image& out, int x, int y, int width, int height, uint8_t color) { std::fill_n(out.pixels.begin() + size_t(yy) * size_t(out.width) + size_t(x), width, color); } +// Number with '.' as thousands separator, no padding. std::string grouped(uint32_t value) { std::string digits = std::to_string(value); for (int at = int(digits.size()) - 3; at > 0; at -= 3) digits.insert(size_t(at), "."); return digits; } +// Formats a number right-aligned in `width` characters ('%' padding, as the original font expects); +// with `grouping` it adds thousands separators and compensates with leading spaces so columns line up. std::string source_number(uint32_t value, int width, bool grouping = true) { std::string digits = std::to_string(value); const int actual = int(digits.size()); @@ -70,20 +81,24 @@ std::string source_number(uint32_t value, int width, bool grouping = true) { return digits; } +// Amount converted with the currency numerator/denominator (if the denominator is non-zero) and suffixed with ' EU'. std::string source_money(uint32_t value, uint32_t numerator, uint32_t denominator) { if (denominator) value = uint32_t((uint64_t(value) * numerator) / denominator); return source_number(value, 1, true) + " EU"; } +// Text of a calculator value: as money for currency profiles, otherwise as a plain grouped number. std::string calculator_value(uint32_t value, const OutgoingTransferCalculatorProfile& profile, uint32_t numerator, uint32_t denominator) { return profile.currency ? source_money(value, numerator, denominator) : grouped(value); } +// True for the two money fields (fee and monthly salary); the other fields are contract years and bonuses. bool money_field(OutgoingTransferField field) { return field == OutgoingTransferField::fee || field == OutgoingTransferField::monthly_salary; } +// Name of an editor field for the JSON output. std::string field_name(OutgoingTransferField field) { switch (field) { case OutgoingTransferField::fee: return "fee"; @@ -101,6 +116,7 @@ std::string field_name(OutgoingTransferField field) { return "fee"; } +// Sets the panel title to the loan or purchase variant according to the initial action. OutgoingTransferEditorState with_source_title(OutgoingTransferEditorState state) { state.panel.title = state.initial_action_loan ? IncomingTransferTitle::player_loan : IncomingTransferTitle::player_purchase; @@ -108,6 +124,7 @@ OutgoingTransferEditorState with_source_title(OutgoingTransferEditorState state) } } // namespace +// Serialises a request (kind, identity, edited field, current values and the quoted values) as JSON. std::string outgoing_transfer_request_json(const OutgoingTransferRequest& request) { const char* kind = "none"; switch (request.kind) { @@ -141,6 +158,9 @@ std::string outgoing_transfer_request_json(const OutgoingTransferRequest& reques return out.str(); } +// Builds the screen and the shared panel and loads the assets. The projection is validated strictly: ids and bid slot +// (list entry 40..43 are poach entries), panel consistency, mode 1..3, image sizes, that the edited bid row belongs to +// the active manager and matches the editor values, and that every calculator profile and preset is within its bounds. OutgoingTransferScreen::OutgoingTransferScreen(const std::filesystem::path& data, OutgoingTransferEditorState state) : state_(with_source_title(std::move(state))), confirmed_state_(state_), data_(data), @@ -171,6 +191,7 @@ OutgoingTransferScreen::OutgoingTransferScreen(const std::filesystem::path& data ((int(row.contract_months) - 1) / 12 + 1) != state_.duration_years)) throw FormatError("outgoing transfer: editor fields do not match the active Native bid row"); } + // Checks one calculator profile: supported, minimum <= initial <= maximum, and all presets within the bounds. auto check_profile = [](const OutgoingTransferCalculatorProfile& profile) { if (!profile.supported || profile.minimum > profile.maximum || profile.initial < profile.minimum || profile.initial > profile.maximum) @@ -193,11 +214,13 @@ OutgoingTransferScreen::OutgoingTransferScreen(const std::filesystem::path& data closed_ = state_.closed; } +// Identifies the edited bid (manager, club, revision, list entry, slot, player, seller, bid slot); attached to every request. OutgoingTransferIdentity OutgoingTransferScreen::identity() const { return {state_.manager_slot, state_.runtime_club, state_.revision, state_.list_entry, state_.source_slot, state_.player, state_.seller, state_.bid_slot}; } +// Current value of an editor field. uint32_t OutgoingTransferScreen::field_value(OutgoingTransferField field) const { switch (field) { case OutgoingTransferField::fee: return state_.fee; @@ -215,6 +238,7 @@ uint32_t OutgoingTransferScreen::field_value(OutgoingTransferField field) const return 0; } +// Maximum allowed value of a field, taken from the money profiles (fee, salary) or the mode-3 profiles (years, bonuses). uint32_t OutgoingTransferScreen::field_maximum(OutgoingTransferField field) const { if (field == OutgoingTransferField::fee) return state_.money_calculators[0].maximum; if (field == OutgoingTransferField::monthly_salary) return state_.money_calculators[1].maximum; @@ -223,6 +247,7 @@ uint32_t OutgoingTransferScreen::field_maximum(OutgoingTransferField field) cons return index >= 1 && index < 8 ? state_.mode3_calculators[size_t(index)].maximum : 0; } +// Stores a value into an editor field. void OutgoingTransferScreen::set_field_value(OutgoingTransferField field, uint32_t value) { switch (field) { case OutgoingTransferField::fee: state_.fee = value; break; @@ -239,6 +264,8 @@ void OutgoingTransferScreen::set_field_value(OutgoingTransferField field, uint32 } } +// Builds a request of the given kind from the current identity, field values and the quoted values of the panel. +// The request is only returned; callers store it as pending. OutgoingTransferRequest OutgoingTransferScreen::make_request(OutgoingTransferRequestKind kind, OutgoingTransferField field, uint32_t value) const { @@ -258,6 +285,9 @@ OutgoingTransferRequest OutgoingTransferScreen::make_request(OutgoingTransferReq return request; } +// Closes the calculator. The value is clamped to the field's minimum/maximum. If accepted, it is stored (the four +// last bonus lines are kept divided by 5) and a quote_change request goes to the session, which recomputes the quote; +// if cancelled, money fields still send a quote_change with the old value and accepted=false, other fields send nothing. OutgoingTransferRequest OutgoingTransferScreen::commit_field(bool accepted) { if (!calculator_open_) return {}; const uint32_t old = field_value(active_field_); @@ -294,8 +324,11 @@ OutgoingTransferRequest OutgoingTransferScreen::commit_field(bool accepted) { return request; } +// Draws the two offer lines (fee at x=7, monthly salary at x=170, baseline 130) and, in mode 3, the right-hand list of +// contract years and the bonus lines (8 rows from y=0x8e, 9 pixels apart; the last four bonuses are shown multiplied by 5). void OutgoingTransferScreen::draw_editor_fields(Image& out) const { const auto& panel = state_.panel; + // Draws body-font text at a baseline, optionally through the vertical colour gradient of the executable. auto body_baseline = [&](int x, int baseline, std::string_view text, uint8_t color) { const int top = baseline - body_.baseline; const int width = body_.text_width(text); @@ -313,6 +346,7 @@ void OutgoingTransferScreen::draw_editor_fields(Image& out) const { if (mask.at(xx, yy)) out.at(x + xx, top + yy) = gradient < 32 ? exe_.u8(::bmh::layout::Advertising_Text_RuntimeField + uint32_t(gradient * 6 + std::min(yy, 5))) : color; }; + // Amount converted with the panel's currency factors, padded to `width`, with ' EU'. auto money_text = [&](uint32_t value, int width) { if (panel.currency_denominator) value = uint32_t((uint64_t(value) * panel.currency_numerator) / panel.currency_denominator); @@ -321,6 +355,7 @@ void OutgoingTransferScreen::draw_editor_fields(Image& out) const { // Keep the asking lines drawn by the shared Source panel at baseline 123. // OpenTransferEditor adds the selected bid on its own baseline-130 row. + // Draws a label plus (if editable) the amount, with a dark shadow offset by 2 pixels. auto offer_line = [&](uint32_t label_address, uint32_t value, int width, int x) { std::string line(text_at(texts_, label_address)); if (state_.editable) line += money_text(value, width); @@ -353,6 +388,9 @@ void OutgoingTransferScreen::draw_editor_fields(Image& out) const { } } +// Draws the number calculator if one is open: background at (103,55), shadow, title with the initial value, +// 15 keys (digits and the letters D, R, C, J, N) and the preset buttons at positions from tables in the executable, +// and the current input right-aligned. Does nothing otherwise. void OutgoingTransferScreen::draw_calculator(Image& out) const { constexpr int x0 = kCalculatorX, y0 = kCalculatorY; if (!calculator_open_ || !active_profile_.supported) return; @@ -364,6 +402,7 @@ void OutgoingTransferScreen::draw_calculator(Image& out) const { title = std::string(text_at(texts_, active_profile_.source_text_address)); title += calculator_value(active_profile_.initial, active_profile_, state_.panel.currency_numerator, state_.panel.currency_denominator); + // Body-font text at a baseline; the gradient is used only if requested and enabled. auto draw_body = [&](int x, int baseline, std::string_view text, uint8_t color, bool gradient) { const int top = baseline - body_.baseline; const int width = body_.text_width(text); @@ -404,6 +443,7 @@ void OutgoingTransferScreen::draw_calculator(Image& out) const { draw_body(x0 + 106 - body_.text_width(value), y0 + 110, value, 0x00, true); } +// Draws the four footer buttons (texts 230..233): drop shadow, left piece, repeated 8-pixel middle strips, right end and label. void OutgoingTransferScreen::draw_footer(Image& out) const { // OpenTransferEditor registers four FormatError3 controls from a216c/a216e/a2170. // The address stride in OutgoingTransfer_DrawFooter_TextPointer is exactly one TEXTD pointer (four bytes): @@ -433,6 +473,7 @@ void OutgoingTransferScreen::draw_footer(Image& out) const { } } +// Renders the shared panel and then the editor fields, calculator (if open) and footer on top. Image OutgoingTransferScreen::render() const { Image out = panel_.render(); draw_editor_fields(out); @@ -441,10 +482,16 @@ Image OutgoingTransferScreen::render() const { return out; } +// Called when the pointer-hold timer fires; handled like a right click (cancel/close). OutgoingTransferRequest OutgoingTransferScreen::process_timer_expired() { return click(0, 0, true); //BalanceFromGame/OpenTransferEditor event8; right path does not inspect coordinates. } +// Handles a click and returns a request for the session when one is needed (the screen then waits for the +// acknowledgement). Order: double click near the top toggles loan/purchase quote; with the calculator open, keys and +// presets edit the value and right click cancels it; otherwise right click cancels the screen, footer buttons send +// team info, player info, submit (only when editable) or cancel; clicks on the fee, salary or (mode 3) contract/bonus +// areas open the calculator. Opening the calculator is local state and sends no request. OutgoingTransferRequest OutgoingTransferScreen::click(int x, int y, bool right, bool double_click) { if (closed_ || pending_) return {}; if (double_click && !right && !calculator_open_ && y > 0x12 && y < 0x21) { @@ -460,6 +507,7 @@ OutgoingTransferRequest OutgoingTransferScreen::click(int x, int y, bool right, const int key_x = kCalculatorX + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField + size_t(i) * 2); const int key_y = kCalculatorY + exe_.u8(::bmh::layout::Advertising_Click_RuntimeField2 + size_t(i)); if (x < key_x || x >= key_x + 16 || y < key_y || y >= key_y + 14) continue; + // Keys 0-9 type digits; then D = delete last digit, R = back to the initial value, C = clear, J = accept, N = cancel. if (i < 10) { text(std::to_string(i)); return {}; } if (i == 10) { calculator_value_ /= 10; numeric_text_ = std::to_string(calculator_value_); return {}; } if (i == 11) { calculator_value_ = active_profile_.initial; numeric_text_.clear(); return {}; } @@ -537,6 +585,7 @@ OutgoingTransferRequest OutgoingTransferScreen::click(int x, int y, bool right, return {}; } +// Appends typed digits to the calculator input (at most 10 characters), clamped to the profile maximum. bool OutgoingTransferScreen::text(std::string_view input) { if (closed_ || pending_ || !calculator_open_ || input.empty()) return false; for (char c : input) if (c < '0' || c > '9') return false; @@ -552,6 +601,8 @@ bool OutgoingTransferScreen::text(std::string_view input) { return true; } +// Keyboard: Esc or N cancels (the calculator first, then the screen), J or Enter accepts the calculator or submits the bid, +// Backspace or D deletes a digit, C or Space clears, digits are typed. OutgoingTransferRequest OutgoingTransferScreen::key(std::string_view key_name) { if (closed_ || pending_) return {}; if (key_name == "ESC" || key_name == "ESCAPE" || (key_name == "N" && calculator_open_)) { @@ -584,6 +635,8 @@ OutgoingTransferRequest OutgoingTransferScreen::key(std::string_view key_name) { return {}; } +// Session acknowledgement: checks that the new projection is for the same bid (and not older) and replaces the state; +// the shared panel is recreated, the pending request and the calculator are cleared. void OutgoingTransferScreen::acknowledge(OutgoingTransferEditorState state) { // Recreate the common panel only after the owner supplies the exact next // projection and quote. The caller controls revision advancement. @@ -606,6 +659,7 @@ void OutgoingTransferScreen::acknowledge(OutgoingTransferEditorState state) { panel_ = IncomingTransferScreen(data_, state_.panel, state_.gradient_text); } +// Session rejection: restores the last confirmed state, reopens the screen and shows the reason as feedback. void OutgoingTransferScreen::reject_action(std::string reason) { pending_.reset(); state_ = confirmed_state_; @@ -617,6 +671,7 @@ void OutgoingTransferScreen::reject_action(std::string reason) { numeric_text_.clear(); } +// State as JSON for tests: identity, mode, values, calculator flag, feedback and the pending request. std::string OutgoingTransferScreen::state_json() const { std::ostringstream out; out << "{\"screen\":\"outgoing_transfer\",\"manager_slot\":" << state_.manager_slot diff --git a/src/ui/preparation_flow.cpp b/src/ui/preparation_flow.cpp index cd1ba31..b1ce8b8 100644 --- a/src/ui/preparation_flow.cpp +++ b/src/ui/preparation_flow.cpp @@ -11,6 +11,8 @@ namespace bmh::ui { +// Desk records page (desk menu kinds 25 and 26). Only opens while the desktop's pending request is exactly the +// given open_menu owner (same manager slot and revision) and no other child view is active; a mismatch throws. void StartupFlow::show_desk_records(DeskRecordsState state,const DeskRequest& owner) { if(!desktop_||!engine_attached_||in_preparation_menu()||in_readonly_view()||matchday_results_|| !desktop_->pending()||*desktop_->pending()!=owner||owner.kind!=DeskRequestKind::open_menu|| @@ -21,6 +23,10 @@ void StartupFlow::show_desk_records(DeskRecordsState state,const DeskRequest& ow desktop_->resolve_local_menu();desk_records_=std::move(screen); } +// finish_*_input family: called after a child page handled a click or key. If the page now holds a pending +// action, it is wrapped into a FlowResult request so the engine can answer it (the answer then comes back through +// the matching acknowledge_*/close_*/reject_* method below); without a pending action only the redraw flag is +// returned. The Strengths page additionally redirects its league-family actions (pairings, table, close). FlowResult StartupFlow::finish_strengths_input(bool changed) { if(const auto* pending=pending_strengths()) { if(pending->kind==StrengthsAction::pairings||pending->kind==StrengthsAction::table|| @@ -38,6 +44,7 @@ FlowResult StartupFlow::finish_strengths_input(bool changed) { } return {changed}; } +// Top scorers page: forward its pending action (metric, scope or close) as a request. FlowResult StartupFlow::finish_top_scorers_input(bool changed) { if(const auto* pending=pending_top_scorers()) { FlowResult result{changed,FlowRequest::top_scorers_action}; @@ -46,6 +53,7 @@ FlowResult StartupFlow::finish_top_scorers_input(bool changed) { } return {changed}; } +// Opportunities page: forward its pending action (mode change or close) as a request. FlowResult StartupFlow::finish_opportunities_input(bool changed) { if(const auto* pending=pending_opportunities()) { FlowResult result{changed,FlowRequest::opportunities_action}; @@ -53,6 +61,7 @@ FlowResult StartupFlow::finish_opportunities_input(bool changed) { } return {changed}; } +// Statistics menu (menu 23): forward the pending selection or close as a request. FlowResult StartupFlow::finish_statistics_menu_input(bool changed) { if(const auto* pending=pending_statistics_menu()) { FlowResult result{changed,FlowRequest::statistics_menu_action}; @@ -60,6 +69,7 @@ FlowResult StartupFlow::finish_statistics_menu_input(bool changed) { } return {changed}; } +// Statistics sub-pages without their own screen request type (all-time, world cup, finance, series): forwards the stored page action. FlowResult StartupFlow::finish_statistics_page_input(bool changed) { if(statistics_page_action_) { FlowResult result{changed,FlowRequest::statistics_page_action}; @@ -68,6 +78,7 @@ FlowResult StartupFlow::finish_statistics_page_input(bool changed) { } return {changed}; } +// Statistics rankings (history) page: forward the pending category selection or close as a request. FlowResult StartupFlow::finish_statistics_rankings_input(bool changed) { if(const auto* pending=pending_statistics_rankings()) { FlowResult result{changed,FlowRequest::statistics_rankings_action}; @@ -75,6 +86,7 @@ FlowResult StartupFlow::finish_statistics_rankings_input(bool changed) { } return {changed}; } +// Analytics page: forward the pending preference change or close as a request. FlowResult StartupFlow::finish_analytics_input(bool changed) { if (const auto* pending = pending_analytics()) { FlowResult result{changed, FlowRequest::analytics_action}; @@ -83,12 +95,14 @@ FlowResult StartupFlow::finish_analytics_input(bool changed) { } return {changed}; } +// Balance page: forward the pending calculator, close or close-confirmation action as a request. FlowResult StartupFlow::finish_balance_input(bool changed) { if(const auto* pending=pending_balance()) { FlowResult result{changed,FlowRequest::balance_action};result.balance_action=*pending;return result; } return {changed}; } +// Other games page: forward the pending view action (selector, round, mode, team info, close) as a request. FlowResult StartupFlow::finish_other_games_input(bool changed) { if (const auto* pending = pending_other_games_action()) { FlowResult result{changed, FlowRequest::other_games_action}; @@ -97,7 +111,15 @@ FlowResult StartupFlow::finish_other_games_input(bool changed) { } return {changed}; } +// Identity checks shared by the Strengths and Other games acknowledgements. Both compare the page identity that +// the engine echoed back against the desk as it was before the request, then require that the new desk differs +// from the old one only in its revision. namespace { +// Throws unless the desk acknowledgement belongs to the Strengths page identity: the new desk revision must be +// the old one plus one and equal to the page's revision; manager slot, runtime club and day counter must match +// the old desk; and the club identity must equal the desk's session identity key for that manager (at the +// national-coach desk that is the national team's identity, not the manager's own club identity). Afterwards the +// old desk with only the revision replaced must serialize identically to the new desk. void validate_strengths_preparation(const StrengthsIdentity& id,const DeskState& before,const PreparationState& next) { if(next.desktop.revision!=before.revision+1||next.desktop.revision!=id.revision|| id.manager!=before.manager_slot||id.runtime_club!=before.runtime_club||id.day_counter!=before.day_counter|| @@ -108,6 +130,9 @@ void validate_strengths_preparation(const StrengthsIdentity& id,const DeskState& if(desk_json(expected)!=desk_json(next.desktop))throw FormatError("strengths: unrelated desk state changed"); validate_preparation_context(next); } +// Same contract for the Other games page. Here the runtime team and the club identity are compared against the +// desk's runtime club and against the manager's own club_identity_key (not the session identity key used for +// Strengths), so for a national coach this key may differ from the runtime club the desk shows. void validate_other_games_preparation(const OtherGamesIdentity& id, const DeskState& before, const PreparationState& next) { if (next.desktop.revision != before.revision + 1 || next.desktop.revision != id.revision || @@ -123,6 +148,9 @@ void validate_other_games_preparation(const OtherGamesIdentity& id, const DeskSt validate_preparation_context(next); } } +// Opens the Strengths page (desk menu 2). The desktop's pending request must be this open_menu owner and the +// page identity must be a fresh one (sequence 0, with a scope); the desk acknowledgement is validated before +// the page, the new desk and the preparation state replace the old ones. It also starts the league family. void StartupFlow::show_strengths(StrengthsState page,PreparationState preparation,const DeskRequest& owner) { if(!desktop_||!engine_attached_||in_preparation_menu()||in_readonly_view()||matchday_results_|| !desktop_->pending()||*desktop_->pending()!=owner||owner.kind!=DeskRequestKind::open_menu|| @@ -136,6 +164,8 @@ void StartupFlow::show_strengths(StrengthsState page,PreparationState preparatio desktop_->resolve_local_menu();desktop_=std::move(desk);preparation_=std::move(next);strengths_=std::move(screen); league_family_identity_=strengths_->state().identity;league_family_child_=3; } +// League family (Strengths, pairings, table are siblings of one family): drops whichever child page is active +// and the family-table dialog and dispatch state so the next child can be installed. Needs an active child. void StartupFlow::replace_family_child() { if(!league_family_identity_||!league_family_child_) throw FormatError("league family: no active child to replace"); @@ -146,12 +176,17 @@ void StartupFlow::replace_family_child() { family_table_source_clock_anchor_valid_=false;family_table_reset_clock_after_present_=false; family_table_release_barrier_=false; } +// Returns the league-family request waiting for the engine, looking at the stored dispatch, the pairings page and the table, in that order. const LeagueFamilyRequest* StartupFlow::pending_league_family_action() const { if(family_table_dispatch_pending_)return &*family_table_dispatch_pending_; if(const auto* pairing=pending_pairings_family_action())return pairing; if(league_table_&&league_table_->pending_family_action())return &*league_table_->pending_family_action(); return nullptr; } +// Strengths page reached from inside the league family (switch of the family child). Every identity field that +// belongs to the family (manager, runtime club, club identity, day counter, family id, league group, source +// parameter, default league) must equal the stored family identity; a mismatch throws. The desk acknowledgement +// is then validated like for a normally opened Strengths page. void StartupFlow::show_family_strengths(StrengthsState page,PreparationState preparation) { if(!desktop_||!engine_attached_||!league_family_identity_|| page.identity.manager!=league_family_identity_->manager|| @@ -171,6 +206,9 @@ void StartupFlow::show_family_strengths(StrengthsState page,PreparationState pre replace_family_child();desktop_=std::move(desk);preparation_=std::move(next); strengths_=std::move(screen);league_family_identity_=page.identity;league_family_child_=3; } +// Opens the top scorers page (desk menu 20). Besides the owner checks, the page identity must match the desk +// (manager slot, runtime club, day counter, manager's own club identity) and carry revision + 1; the desk +// acknowledgement may differ from the old desk only in its revision. void StartupFlow::show_top_scorers(TopScorersState page,PreparationState preparation,const DeskRequest& owner) { if(!desktop_||!engine_attached_||in_preparation_menu()||in_readonly_view()||matchday_results_|| !desktop_->pending()||*desktop_->pending()!=owner||owner.kind!=DeskRequestKind::open_menu|| @@ -194,6 +232,9 @@ void StartupFlow::show_top_scorers(TopScorersState page,PreparationState prepara auto next=std::make_unique(std::move(preparation)); desktop_->resolve_local_menu();desktop_=std::move(desk);preparation_=std::move(next);top_scorers_=std::move(screen); } +// Top scorers: answer to a metric or scope change. The expected identity is the pending request's identity with +// revision and sequence each advanced by one, and the page's metric and scope must be the requested ones (or +// the unchanged ones). Close requests are refused here; they go through close_top_scorers. void StartupFlow::acknowledge_top_scorers(TopScorersState page,PreparationState preparation) { const auto* pending=pending_top_scorers(); auto expected_id=pending?pending->identity:TopScorersIdentity{}; @@ -217,6 +258,8 @@ void StartupFlow::acknowledge_top_scorers(TopScorersState page,PreparationState auto next=std::make_unique(std::move(preparation)); desktop_=std::move(desk);preparation_=std::move(next);top_scorers_=std::move(screen); } +// Top scorers: answer to a close request. Requires a pending close; the page identity must be the pending one +// advanced by one revision and one sequence, and the page must still show the same metric and scope. void StartupFlow::close_top_scorers(TopScorersState page,PreparationState preparation) { const auto* pending=pending_top_scorers(); if(!pending||!desktop_||!top_scorers_||pending->action!=TopScorersAction::close) @@ -237,10 +280,15 @@ void StartupFlow::close_top_scorers(TopScorersState page,PreparationState prepar auto next=std::make_unique(std::move(preparation)); desktop_=std::move(desk);preparation_=std::move(next);top_scorers_.reset(); } +// Top scorers: the engine refused the pending action; the page shows the reason and drops the request. void StartupFlow::reject_top_scorers(std::string reason) { if(!top_scorers_)throw FormatError("top scorers: missing rejection owner"); top_scorers_->reject_action(std::move(reason)); } +// Opens the Opportunities page (desk menu 23). It is opened either from the desktop's pending request or from +// the statistics menu that has returned to the idle desk (then the menu's owner must match). The identity is +// compared with the desk using the session identity key. Opening it closes any statistics sub-page and keeps +// the statistics menu, whose owner revision (and a national-friendly picker's) is moved to the new revision. void StartupFlow::show_opportunities(OpportunitiesState page,PreparationState preparation,const DeskRequest& owner) { const bool desktop_pending=desktop_&&desktop_->pending()&&*desktop_->pending()==owner; const bool returned_selector=statistics_menu_&&statistics_menu_->state().owner==owner&&desktop_&& @@ -275,6 +323,8 @@ void StartupFlow::show_opportunities(OpportunitiesState page,PreparationState pr } } } +// Statistics menu (menu 23): the selector from which the statistics sub-pages are entered. Needs the desktop's +// pending open_menu request as owner; the transfer-history count must be 0 to 25. void StartupFlow::show_statistics_menu(const DeskRequest& owner, int transfer_history_count) { if(!desktop_||!engine_attached_||in_preparation_menu()||in_readonly_view()||matchday_results_|| !desktop_->pending()||*desktop_->pending()!=owner||owner.kind!=DeskRequestKind::open_menu|| @@ -286,6 +336,9 @@ void StartupFlow::show_statistics_menu(const DeskRequest& owner, int transfer_hi auto screen=std::make_unique(data_,StatisticsMenuState{owner,desktop_->render(),transfer_history_count,desktop_->state().gradient_text}); statistics_menu_=std::move(screen); } +// Statistics sub-page 3 (all-time table). Allowed when the menu has just selected entry 3, or when the menu +// returned to the idle desk at the same revision; the page owner must equal the menu's owner. The same +// selected-or-returned test guards the other show_* statistics sub-pages below (entries 4, 5, 6, 7, 8, 1, 2). void StartupFlow::show_alltime_table(AllTimeTableState state) { const bool selected=statistics_menu_&&statistics_menu_->pending()&& !statistics_menu_->pending()->close&&statistics_menu_->pending()->selected_index==3; @@ -300,6 +353,8 @@ void StartupFlow::show_alltime_table(AllTimeTableState state) { world_cup_statistics_.reset();finance_totals_.reset();series_records_.reset(); statistics_rankings_.reset();analytics_.reset();minute_statistics_.reset();transfer_history_.reset(); } +// Statistics sub-page 4 (world cup). When it serves as the national friendly picker, the projection's +// can_select_opponent flag must agree with the picker state and the stored owners must still match the desk. void StartupFlow::show_world_cup_statistics(WorldCupStatisticsProjection state) { const bool selected=statistics_menu_&&statistics_menu_->pending()&& !statistics_menu_->pending()->close&&statistics_menu_->pending()->selected_index==4; @@ -318,6 +373,9 @@ void StartupFlow::show_world_cup_statistics(WorldCupStatisticsProjection state) statistics_rankings_.reset();analytics_.reset();minute_statistics_.reset();transfer_history_.reset(); } +// National friendly: opens the world cup page as an opponent picker, straight from the desk's menu-6 request. +// Only valid for the national coach (the manager slot has no club team and runtime_team is the no-team value). +// It stores a fresh request owner for the later booking. void StartupFlow::show_national_friendly_picker(WorldCupStatisticsProjection projection, const DeskRequest& owner, int runtime_team) { if (!desktop_ || !engine_attached_ || in_preparation_menu() || in_readonly_view() || matchday_results_ || @@ -344,6 +402,7 @@ void StartupFlow::show_national_friendly_picker(WorldCupStatisticsProjection pro alltime_table_.reset();finance_totals_.reset();series_records_.reset(); } +// Leaves the national friendly picker, through the statistics menu if that is still present. void StartupFlow::close_national_friendly_picker() { if(!national_friendly_picker_)return; if(statistics_menu_)close_statistics_menu(); @@ -355,6 +414,9 @@ void StartupFlow::close_national_friendly_picker() { } } +// National friendly: the calendar step after an opponent was picked. The booking and its quote must carry the +// picker's owner (sequence, revision, manager, team, desk menu), the quote must be in the quoted state, and the +// calendar state must belong to the same national coach on the current desk revision; otherwise throws. void StartupFlow::show_national_friendly_calendar(FriendlyMatchState state, FriendlyQuoteProjection quote, NationalFriendlyBookingRequest booking) { const NationalFriendlyOwner engine_owner{national_friendly_owner_.sequence, @@ -379,6 +441,7 @@ void StartupFlow::show_national_friendly_calendar(FriendlyMatchState state, statistics_menu_.reset(); friendly_match_=std::move(screen);pending_friendly_action_.reset(); } +// Statistics sub-page 5 (finance totals); same selected-or-returned owner test as the other sub-pages. void StartupFlow::show_finance_totals(FinanceTotals state) { const bool selected=statistics_menu_&&statistics_menu_->pending()&& !statistics_menu_->pending()->close&&statistics_menu_->pending()->selected_index==5; @@ -392,6 +455,7 @@ void StartupFlow::show_finance_totals(FinanceTotals state) { alltime_table_.reset();world_cup_statistics_.reset();series_records_.reset(); statistics_rankings_.reset();analytics_.reset();minute_statistics_.reset();transfer_history_.reset(); } +// Statistics sub-page 6 (series records); same selected-or-returned owner test as the other sub-pages. void StartupFlow::show_series_records(SeriesRecordsProjection state) { const bool selected=statistics_menu_&&statistics_menu_->pending()&& !statistics_menu_->pending()->close&&statistics_menu_->pending()->selected_index==6; @@ -405,6 +469,7 @@ void StartupFlow::show_series_records(SeriesRecordsProjection state) { alltime_table_.reset();world_cup_statistics_.reset();finance_totals_.reset(); statistics_rankings_.reset();analytics_.reset();minute_statistics_.reset();transfer_history_.reset(); } +// Closes an idle statistics sub-page and returns to the statistics menu's own close handling. void StartupFlow::close_statistics_page() { if(!in_statistics_page()||!statistics_menu_||!desktop_) throw FormatError("statistics page: no idle child to close"); @@ -412,6 +477,8 @@ void StartupFlow::close_statistics_page() { statistics_page_action_.reset(); close_statistics_menu(); } +// Statistics rankings (history) page. May open straight from the initial menu, from menu entry 7, or when +// returning to the menu at the same revision; it must start on category 0 and season 0 for the desk's manager. void StartupFlow::show_statistics_rankings(StatisticsRankingState state) { const auto* pending=statistics_menu_&&statistics_menu_->pending()?&*statistics_menu_->pending():nullptr; const bool initial_menu=statistics_menu_&&desktop_&&desktop_->pending()&& @@ -432,6 +499,7 @@ void StartupFlow::show_statistics_rankings(StatisticsRankingState state) { statistics_menu_->clear_pending();analytics_.reset();minute_statistics_.reset();transfer_history_.reset();statistics_rankings_=std::move(screen); alltime_table_.reset();world_cup_statistics_.reset();finance_totals_.reset();series_records_.reset();statistics_page_action_.reset(); } +// Statistics sub-page for menu entry 8 (minute statistics); same selected-or-returned owner test. void StartupFlow::show_minute_statistics(MinuteStatisticsProjection projection) { const auto* pending=statistics_menu_&&statistics_menu_->pending()?&*statistics_menu_->pending():nullptr; const bool selected_case8=pending&&!pending->close&&pending->selected_index==8; @@ -447,6 +515,7 @@ void StartupFlow::show_minute_statistics(MinuteStatisticsProjection projection) statistics_menu_->clear_pending();statistics_rankings_.reset();analytics_.reset();transfer_history_.reset();minute_statistics_=std::move(screen); alltime_table_.reset();world_cup_statistics_.reset();finance_totals_.reset();series_records_.reset();statistics_page_action_.reset(); } +// Statistics sub-page for menu entry 1 (transfer history); the vertical source origin must lie in 0..255. void StartupFlow::show_transfer_history(TransferHistoryProjection projection, const GameState& formatting_state, int source_origin_y) { const auto* pending=statistics_menu_&&statistics_menu_->pending()?&*statistics_menu_->pending():nullptr; @@ -465,6 +534,7 @@ void StartupFlow::show_transfer_history(TransferHistoryProjection projection, transfer_history_=std::move(screen); alltime_table_.reset();world_cup_statistics_.reset();finance_totals_.reset();series_records_.reset();statistics_page_action_.reset(); } +// Statistics sub-page for menu entry 2 (analytics); its owner must equal the menu's owner and it cannot open on top of Opportunities. void StartupFlow::show_analytics(AnalyticsState state) { const auto* pending=statistics_menu_&&statistics_menu_->pending()?&*statistics_menu_->pending():nullptr; const bool selected=pending&&!pending->close&&pending->selected_index==2; @@ -482,6 +552,8 @@ void StartupFlow::show_analytics(AnalyticsState state) { transfer_history_.reset();analytics_=std::move(screen); alltime_table_.reset();world_cup_statistics_.reset();finance_totals_.reset();series_records_.reset();statistics_page_action_.reset(); } +// Analytics: answer to a preference change. The returned flags must be the requested ones with the same +// underlay; the page owner must advance by exactly one revision, and the desk may differ only in its revision. void StartupFlow::acknowledge_analytics(AnalyticsState state,PreparationState preparation) { const auto* pending=pending_analytics(); if(!pending||!analytics_||!statistics_menu_||statistics_menu_->pending()|| @@ -509,15 +581,18 @@ void StartupFlow::acknowledge_analytics(AnalyticsState state,PreparationState pr } analytics_=std::move(next_screen);desktop_=std::move(next_desk);preparation_=std::move(next_preparation); } +// Closes the analytics page and then the statistics menu behind it. void StartupFlow::close_analytics() { if(!analytics_)throw FormatError("analytics: no active page"); analytics_.reset(); if(statistics_menu_)close_statistics_menu(); } +// Analytics: the engine refused the pending action. void StartupFlow::reject_analytics() { if(!analytics_||!analytics_->pending())throw FormatError("analytics: no pending action"); analytics_->reject(); } +// Rankings: answer to a category selection; the category must be the requested one and manager slot and underlay unchanged. void StartupFlow::acknowledge_statistics_rankings(StatisticsRankingState state) { const auto* pending=pending_statistics_rankings(); if(!pending||pending->kind!=StatisticsRankingsRequestKind::select_category||!statistics_rankings_|| @@ -527,15 +602,18 @@ void StartupFlow::acknowledge_statistics_rankings(StatisticsRankingState state) throw FormatError("statistics rankings: mismatched category acknowledgement"); statistics_rankings_->acknowledge_category(std::move(state)); } +// Closes the rankings page. void StartupFlow::close_statistics_rankings() { if(!statistics_rankings_)throw FormatError("statistics rankings: no active history view"); statistics_rankings_.reset(); } +// Rankings: the engine refused the pending action. void StartupFlow::reject_statistics_rankings() { if(!statistics_rankings_||!statistics_rankings_->pending()) throw FormatError("statistics rankings: no pending action"); statistics_rankings_->reject_action(); } +// Closes the statistics menu together with every statistics sub-page and the national friendly picker state. void StartupFlow::close_statistics_menu() { if(!statistics_menu_)throw FormatError("statistics menu: no active selector"); if(desktop_&&desktop_->pending())desktop_->resolve_local_menu(); @@ -543,11 +621,14 @@ void StartupFlow::close_statistics_menu() { alltime_table_.reset();world_cup_statistics_.reset();finance_totals_.reset();series_records_.reset();statistics_page_action_.reset(); national_friendly_picker_=false;national_friendly_owner_={};national_friendly_desk_owner_={}; } +// Statistics menu: the engine refused the pending selection; a reason is required. void StartupFlow::reject_statistics_menu(std::string reason) { if(!statistics_menu_||!statistics_menu_->pending()||reason.empty()) throw FormatError("statistics menu: rejection requires a pending selection"); statistics_menu_->reject(std::move(reason)); } +// Opportunities: answer to a mode change. Identity fields must equal the pending ones, with sequence and +// revision each one higher, and the mode must be the requested one; the desk may differ only in its revision. void StartupFlow::acknowledge_opportunities(OpportunitiesState page,PreparationState preparation) { const auto* pending=pending_opportunities(); if(!pending||!desktop_||pending->action==OpportunitiesAction::close|| @@ -572,6 +653,8 @@ void StartupFlow::acknowledge_opportunities(OpportunitiesState page,PreparationS statistics_menu_->update_owner(parent); } } +// Opportunities: answer to a close request. The identity must be the pending one advanced once. If the page was +// entered from the statistics menu, the menu is rebuilt with the new desk revision. void StartupFlow::close_opportunities(OpportunitiesState page,PreparationState preparation) { const auto* pending=pending_opportunities(); if(!pending||!desktop_||pending->action!=OpportunitiesAction::close)throw FormatError("opportunities: no close acknowledgement owner"); @@ -593,6 +676,8 @@ void StartupFlow::close_opportunities(OpportunitiesState page,PreparationState p } } } +// Closes an idle Opportunities page when the user switches to another statistics entry. The desk +// acknowledgement is checked like a normal close; the parent menu then gets the new revision. void StartupFlow::close_opportunities_for_statistics_parent(OpportunitiesState page,PreparationState preparation) { if(!opportunities_||!statistics_menu_||opportunities_->pending()||!desktop_) throw FormatError("opportunities: parent switch requires an idle active child"); @@ -614,10 +699,14 @@ void StartupFlow::close_opportunities_for_statistics_parent(OpportunitiesState p national_friendly_desk_owner_.revision=owner.revision; } } +// Opportunities: the engine refused the pending action. void StartupFlow::reject_opportunities(std::string reason) { if(!opportunities_||!opportunities_->pending())throw FormatError("opportunities: no pending action to reject"); opportunities_->reject(std::move(reason)); } +// Strengths: answer to a page action. All identity fields (including family id and sequence) must equal the +// pending request's, with sequence and revision one higher; league, group and team checks depend on the kind +// of action (league select, group toggle, team info for a team that is on the page). void StartupFlow::acknowledge_strengths(StrengthsState page,PreparationState preparation) { const auto* pending=pending_strengths(); if(!pending||!desktop_||pending->kind==StrengthsAction::close|| @@ -645,6 +734,7 @@ void StartupFlow::acknowledge_strengths(StrengthsState page,PreparationState pre desktop_=std::move(desk);preparation_=std::move(next);strengths_=std::move(screen); if(league_family_identity_)league_family_identity_=strengths_->state().identity; } +// Strengths: answer to a close request; the identity must be the pending one advanced by one revision and sequence. void StartupFlow::close_strengths(StrengthsState page,PreparationState preparation) { const auto* pending=pending_strengths(); if(!pending||!desktop_||pending->kind!=StrengthsAction::close) @@ -656,11 +746,14 @@ void StartupFlow::close_strengths(StrengthsState page,PreparationState preparati auto next=std::make_unique(std::move(preparation)); desktop_=std::move(desk);preparation_=std::move(next);strengths_.reset(); } +// Strengths: the engine refused the pending action. void StartupFlow::reject_strengths(std::string reason) { if(!strengths_)throw FormatError("strengths: missing rejection owner"); strengths_->reject_action(std::move(reason)); } +// Opens the Other games page (desk menu 5) in its detail mode with the first view byte value (0x80) and a +// participant offset of 0; identity compared with the desk (runtime club, day counter, revision + 1). void StartupFlow::show_other_games(OtherGamesState page, PreparationState preparation, const DeskRequest& owner) { if (!desktop_ || !engine_attached_ || in_preparation_menu() || in_readonly_view() || @@ -686,6 +779,10 @@ void StartupFlow::show_other_games(OtherGamesState page, PreparationState prepar other_games_ = std::move(screen); } +// Other games: answer to a view action. For each action kind the new projection must be exactly what that +// action implies (selected competition, linked page, wrapped round, toggled display mode, unchanged page after +// team info) and the participant offset and view byte are derived accordingly; the full identity, including +// the view byte, must then match the expected one. Close is refused here. void StartupFlow::acknowledge_other_games(OtherGamesState page, PreparationState preparation) { const auto* pending = pending_other_games_action(); if (!pending || !other_games_ || !desktop_ || pending->action == OtherGamesAction::close) @@ -797,6 +894,7 @@ void StartupFlow::acknowledge_other_games(OtherGamesState page, PreparationState other_games_ = std::move(screen); } +// Other games: answer to a close request; identity advanced once and the view byte left unchanged. void StartupFlow::close_other_games(OtherGamesState page, PreparationState preparation) { const auto* pending = pending_other_games_action(); if (!pending || !other_games_ || !desktop_ || pending->action != OtherGamesAction::close) @@ -814,6 +912,7 @@ void StartupFlow::close_other_games(OtherGamesState page, PreparationState prepa other_games_.reset(); } +// Other games: the engine refused the pending action. void StartupFlow::reject_other_games(std::string reason) { if (!other_games_) throw FormatError("other games: missing rejection owner"); other_games_->reject_action(std::move(reason)); @@ -821,6 +920,7 @@ void StartupFlow::reject_other_games(std::string reason) { +// League pairings page: forward a pending family action first, otherwise the pairings action, as a request. FlowResult StartupFlow::finish_league_pairings_input(bool changed) { if(const auto* family=pending_pairings_family_action()) { FlowResult result{changed,FlowRequest::league_family_action}; @@ -831,6 +931,7 @@ FlowResult StartupFlow::finish_league_pairings_input(bool changed) { } return {changed}; } +// Friendly match question dialog timed out: forwards its expiry as a close, a new action request, or only a redraw. FlowResult StartupFlow::expire_friendly_question(bool release_consumed) { const auto* question=friendly_question_screen(); if(!question||(!release_consumed&&question->question_held()))return {}; @@ -849,16 +950,19 @@ FlowResult StartupFlow::expire_friendly_question(bool release_consumed) { } return {before!=state_json()}; } +// True while a training camp, bank or advertising page shows a notice that disappears by itself. bool StartupFlow::timed_notice_open() const { return (training_camp_&&training_camp_->timed_notice_open()) || (bank_&&bank_->timed_notice_open()) || (advertising_&&advertising_->timed_notice_open()); } +// Dismisses the timed notice of whichever of those pages is active. FlowResult StartupFlow::expire_timed_notice() { const bool changed=training_camp_?training_camp_->expire_timed_notice(): bank_?bank_->expire_timed_notice():advertising_?advertising_->expire_timed_notice():false; return {changed}; } +// Timer expiry acts as the right click or back event for the active page; pages with a pending request are left alone so the acknowledgement stays owned. FlowResult StartupFlow::process_timer_expired(int pointer_x, int pointer_y) { // This is Source event8, not keyboard ESC or a guessed screen coordinate. // Timed keyboard/calculator owners must finish before their outer poll. @@ -982,6 +1086,7 @@ FlowResult StartupFlow::process_timer_expired(int pointer_x, int pointer_y) { return {}; // other modal callers retain their own input owner } +// Routes a mouse press to the active child page (checked in a fixed order); the submenu pages then forward their pending action through finish_*_input. FlowResult StartupFlow::pointer_down(int x,int y,bool right) { if(pitch_hold_release_barrier_&&!right)return {}; if(friendly_match_)return {friendly_match_->pointer_down(x,y,right)}; @@ -1165,6 +1270,9 @@ FlowResult StartupFlow::pointer_down(int x,int y,bool right) { } return {}; } +// Opens the Balance page (desk menu 28). The page identity must be at the desk's current revision (no advance) +// and carry the desk's session identity key for the manager, which at the national-coach desk is the national +// team's identity. The runtime club here is the desk's own. void StartupFlow::show_balance(BalanceState page,const DeskRequest& owner) { if(!desktop_||!engine_attached_||in_preparation_menu()||in_readonly_view()||balance_||matchday_results_|| !desktop_->pending()||*desktop_->pending()!=owner||owner.kind!=DeskRequestKind::open_menu||owner.menu_kind!=28|| @@ -1176,6 +1284,9 @@ void StartupFlow::show_balance(BalanceState page,const DeskRequest& owner) { auto screen=std::make_unique(data_,std::move(page)); desktop_->resolve_local_menu();balance_=std::move(screen); } +// Balance: answer to a calculator or preview action. The identity must equal the pending one with only the +// sequence advanced, must still match the desk (revision, club identity via the session identity key) and the +// close flag must agree with the action. Calculator position is local and is carried over. void StartupFlow::acknowledge_balance(BalanceState page) { const auto* pending=pending_balance(); if(!pending||pending->kind==BalanceAction::confirm_close||!balance_||!desktop_|| @@ -1194,6 +1305,8 @@ void StartupFlow::acknowledge_balance(BalanceState page) { page.calculator_y=balance_->state().calculator_y; balance_=std::make_unique(data_,std::move(page)); } +// Balance: answer to a close or close-confirmation. The identity must be the pending one advanced once and +// the pending identity must still match the desk; the new desk may differ from the old one only in the listed fields. void StartupFlow::close_balance(BalanceState page,PreparationState preparation) { const auto* pending=pending_balance();if(!pending||!balance_||!desktop_|| (pending->kind!=BalanceAction::close&&pending->kind!=BalanceAction::confirm_close)) @@ -1219,39 +1332,49 @@ void StartupFlow::close_balance(BalanceState page,PreparationState preparation) auto prep=std::make_unique(std::move(preparation)); desktop_=std::move(desk);preparation_=std::move(prep);balance_.reset(); } +// Balance: the engine refused the pending action; a reason is required. void StartupFlow::reject_balance(std::string reason) { if(!balance_||reason.empty())throw FormatError("balance: missing rejection owner"); balance_->reject_action(std::move(reason)); } +// Advances the balance page's time-driven part; reports a request if it changed state. FlowResult StartupFlow::tick_balance_source_milliseconds(uint64_t now) { if(!balance_||!balance_->tick_source_milliseconds(now))return {}; return finish_balance_input(true); } +// Tells the balance page that its frame was shown at the given time. void StartupFlow::mark_balance_presented_source_milliseconds(uint64_t now) { if(balance_)balance_->mark_presented_source_milliseconds(now); } +// Advances the stadium calculator by source ticks; forwards any resulting request. FlowResult StartupFlow::tick_stadium_calculator_source_ticks(unsigned ticks) { if (!stadium_ || !stadium_->calculator_advance_source_ticks(ticks)) return {}; PreparationRequest action; if (stadium_->pending()) action = *stadium_->pending(); return finish_preparation_input(std::move(action), true); } +// Tells the stadium calculator that its frame was shown. void StartupFlow::mark_stadium_calculator_presented() { if (stadium_) stadium_->calculator_mark_presented(); } +// Ends the stadium construction tip when its time is up. FlowResult StartupFlow::expire_stadium_tip() { if (!stadium_) return {}; const auto request = stadium_->expire_construction_tip(); if (request.kind == StadiumRequestKind::none) return {}; return finish_preparation_input(request, true); } +// Advances the pairings page's clock; forwards a request if it changed state. FlowResult StartupFlow::tick_league_pairings_source_seconds(uint64_t now) { if (!league_pairings_ || !league_pairings_->tick_source_seconds(now)) return {}; return finish_league_pairings_input(true); } +// Tells the pairings page that its frame was shown at the given time. void StartupFlow::mark_league_pairings_presented_source_seconds(uint64_t now) { if (league_pairings_) league_pairings_->mark_presented_source_seconds(now); } +// Opens the league pairings page from the desk's menu-1 request; identity (manager, runtime club, revision, +// sequence 0) must match the desk. void StartupFlow::show_league_pairings(LeaguePairingsState page) { if(!desktop_||!engine_attached_||in_preparation_menu()||in_readonly_view()||matchday_results_|| !desktop_->pending()||desktop_->pending()->kind!=DeskRequestKind::open_menu||desktop_->pending()->menu_kind!=1|| @@ -1261,6 +1384,10 @@ void StartupFlow::show_league_pairings(LeaguePairingsState page) { auto next=std::make_unique(data_,std::move(page)); desktop_->resolve_local_menu();league_pairings_=std::move(next); } +// Pairings page entered as a member of the league family (with a StrengthsIdentity). If a family is already +// active, manager, runtime club, club identity, day counter, source parameter and family id must equal the +// stored family identity. If no family is active yet, the entry must come from the desk's pending menu-1 +// request with a fresh identity (no family sequence, scope or sequence). Pairings is family child 2. void StartupFlow::show_family_league_pairings(LeaguePairingsState page,StrengthsIdentity identity) { if(!desktop_||!engine_attached_||matchday_results_|| (league_family_identity_&&(identity.manager!=league_family_identity_->manager|| @@ -1282,6 +1409,10 @@ void StartupFlow::show_family_league_pairings(LeaguePairingsState page,Strengths league_pairings_=std::move(screen);league_family_identity_=identity;league_family_child_=2; if(desktop_->pending())desktop_->resolve_local_menu(); } +// Pairings: answer to a page action. Revision, manager, runtime club, club identity and scope must equal the +// pending identity and the sequence must advance by one. Inside a family the supplied family identity must +// also equal the stored one (child 2, same family id, sequence, default league, group) apart from the fields +// that legitimately follow the page; outside a family a family identity is refused. void StartupFlow::acknowledge_league_pairings(LeaguePairingsState page, std::optional family) { const auto* pending=pending_league_pairings(); @@ -1309,6 +1440,9 @@ void StartupFlow::acknowledge_league_pairings(LeaguePairingsState page, auto next=std::make_unique(data_,std::move(page));league_pairings_=std::move(next); } } +// Pairings: answer to a close request. The new desk (an engine projection) must be exactly one revision ahead +// of the pending identity, belong to the same manager and runtime club and keep teams, day and season +// unchanged; the page is then dropped and the desk replaced. void StartupFlow::close_league_pairings(PreparationState state) { const auto* pending=pending_league_pairings(); if(!pending||pending->event.kind!=LeaguePairingsAction::close||!desktop_||!engine_attached_|| @@ -1323,11 +1457,14 @@ void StartupFlow::close_league_pairings(PreparationState state) { auto next_preparation=std::make_unique(std::move(state)); desktop_=std::move(next_desk);preparation_=std::move(next_preparation);league_pairings_.reset(); } +// Pairings: the engine refused the pending action. void StartupFlow::reject_league_pairings(std::string reason) { if(!league_pairings_)throw FormatError("pairings: missing rejection owner"); league_pairings_->reject_action(std::move(reason)); } +// Transfer market: answer to a hover quote. The desk revision may stay or advance by one, the quote must carry +// the new revision, and the new desk may differ from the old one only in its revision. void StartupFlow::acknowledge_transfer_market_preview(PreparationState state, TransferMarketPreview quote) { const auto* request = pending_transfer_market(); if (!request || request->kind != TransferMarketRequestKind::preview_quote || @@ -1350,6 +1487,9 @@ void StartupFlow::acknowledge_transfer_market_preview(PreparationState state, Tr preparation_ = std::move(next_preparation); } +// Opens the outgoing offer editor (or the poach editor) from the pending transfer market request. The editor +// must repeat the request's manager, runtime club, list entry, source slot and player, and the new desk must be +// exactly one revision ahead. void StartupFlow::show_transfer_offer(PreparationState preparation, OutgoingTransferEditorState editor) { const auto* request = pending_transfer_market(); const bool poach=request && request->kind==TransferMarketRequestKind::open_poach; @@ -1372,6 +1512,9 @@ void StartupFlow::show_transfer_offer(PreparationState preparation, OutgoingTran desktop_ = std::move(next_desktop); preparation_ = std::move(next_preparation); } +// Transfer offer editor: answer to an editor action. The editor's manager, runtime club, list entry, source +// slot, player and seller must equal the request's, and the revision may advance by at most one. A closed editor +// returns to a refreshed market page. void StartupFlow::acknowledge_transfer_offer(PreparationState preparation, OutgoingTransferEditorState editor) { const auto* request = pending_transfer_offer(); if (!request || !desktop_ || !engine_attached_ || !preparation.transfer_market || @@ -1399,12 +1542,14 @@ void StartupFlow::acknowledge_transfer_offer(PreparationState preparation, Outgo desktop_ = std::move(next_desktop); preparation_ = std::move(next_preparation); } +// Transfer offer editor: the engine refused the pending action; a reason is required. void StartupFlow::reject_transfer_offer(std::string reason) { if (!pending_transfer_offer() || reason.empty()) throw FormatError("transfer offer: rejection requires a pending editor action"); outgoing_transfer_->reject_action(std::move(reason)); } +// Draws whichever child page is active; the order here decides which page wins when several exist. Image StartupFlow::render() const { if (indoor_standings_) return indoor_standings_->render(); if(achievements_)return achievements_->render(); @@ -1433,6 +1578,8 @@ Image StartupFlow::render() const { desktop_ ? desktop_->render() : manager_ ? manager_->render() : setup_.render(); } +// Opens the environment page (desk menu 24). Only for an ordinary club desk (a national-team desk is refused); +// the projection must carry the owner's manager slot and revision and the desk's runtime club. void StartupFlow::show_environment(EnvironmentView state, const DeskRequest& owner) { if (!desktop_ || !engine_attached_ || !preparation_ || in_preparation_menu() || in_readonly_view() || matchday_results_ || !desktop_->pending() || *desktop_->pending() != owner || @@ -1448,6 +1595,7 @@ void StartupFlow::show_environment(EnvironmentView state, const DeskRequest& own environment_ = std::move(next); } +// Opens the achievements page (desk menu 4); the state must repeat the owner request exactly. void StartupFlow::show_achievements(AchievementsState state,const DeskRequest& owner) { if(!desktop_||!engine_attached_||!desktop_->pending()||*desktop_->pending()!=owner|| owner.kind!=DeskRequestKind::open_menu||owner.menu_kind!=4||owner.manager_slot!=desktop_->state().manager_slot|| @@ -1458,6 +1606,9 @@ void StartupFlow::show_achievements(AchievementsState state,const DeskRequest& o desktop_->resolve_local_menu();achievements_=std::move(next); } +// Environment: answer to a page action. The owner must be the one stored when the page opened. If the revision +// advanced by one, a matching desk (same manager, runtime club, day, options) must come with it; if not, the +// revision must be unchanged and no desk may be supplied. void StartupFlow::acknowledge_environment(EnvironmentView state, std::optional preparation) { const bool changed = environment_ && environment_->pending() && state.revision == environment_->state().revision + 1; if (!environment_ || !environment_->pending() || !desktop_ || !preparation_ || @@ -1486,11 +1637,13 @@ void StartupFlow::acknowledge_environment(EnvironmentView state, std::optional

state().revision; } +// Environment: the engine refused the pending action. void StartupFlow::reject_environment_action(std::string reason) { if (!environment_ || !environment_->pending()) throw FormatError("environment: no pending action to reject"); environment_->reject_action(std::move(reason)); } +// Opens the contracts page (desk menu 27); manager slot, runtime club and revision must equal the desk's. void StartupFlow::show_contracts(ContractsState state) { if (!desktop_ || !engine_attached_ || in_preparation_menu() || in_readonly_view() || matchday_results_ || !desktop_->pending() || desktop_->pending()->kind != DeskRequestKind::open_menu || @@ -1503,6 +1656,9 @@ void StartupFlow::show_contracts(ContractsState state) { contracts_ = std::move(screen); } +// Contracts: answer to a demand request. The pending request must be request_demands, the revision advances by +// exactly one, and the new desk (an engine projection) must equal the old one in teams, runtime club, day, +// season, name, portrait, badge and options. void StartupFlow::acknowledge_contract_quote(ContractsState state, DeskState desk, PreparationState preparation) { if (!contracts_ || !contracts_->pending() || contracts_->pending()->kind != ContractActionKind::request_demands || !desktop_ || !engine_attached_ || @@ -1527,18 +1683,23 @@ void StartupFlow::acknowledge_contract_quote(ContractsState state, DeskState des contracts_ = std::move(next_contracts); } +// Contracts: answer to a submitted offer; shares the checks of acknowledge_contract_mutation. void StartupFlow::acknowledge_contract_offer(ContractsState state, DeskState desk, PreparationState preparation) { acknowledge_contract_mutation(std::move(state), std::move(desk), std::move(preparation), ContractActionKind::submit_offer); } +// Contracts: answer to submitted bonuses; shares the checks of acknowledge_contract_mutation. void StartupFlow::acknowledge_contract_bonuses(ContractsState state, DeskState desk, PreparationState preparation) { acknowledge_contract_mutation(std::move(state), std::move(desk), std::move(preparation), ContractActionKind::submit_bonuses); } +// Contracts: answer to an insurance request; shares the checks of acknowledge_contract_mutation. void StartupFlow::acknowledge_contract_insurance(ContractsState state, DeskState desk, PreparationState preparation) { acknowledge_contract_mutation(std::move(state), std::move(desk), std::move(preparation), ContractActionKind::insure_player); } +// Common check for contract changes. The pending request kind must equal the expected one and the desk and +// revision rules are the same as for demand quotes (one revision ahead, other desk fields unchanged). void StartupFlow::acknowledge_contract_mutation(ContractsState state, DeskState desk, PreparationState preparation, ContractActionKind expected) { if (!contracts_ || !contracts_->pending() || contracts_->pending()->kind != expected || !desktop_ || !engine_attached_ || @@ -1566,12 +1727,16 @@ void StartupFlow::acknowledge_contract_mutation(ContractsState state, DeskState contracts_ = std::move(next_contracts); } +// Contracts: the engine refused the pending request; a reason is required. void StartupFlow::reject_contract_action(std::string reason) { if (!contracts_ || !contracts_->pending() || reason.empty()) throw FormatError("contracts: rejection requires a pending request"); contracts_->reject(std::move(reason)); } +// Turns a request from the desk into a flow action: end session and kickoff are passed on, the save and load +// menus open locally, and the preparation menus (3, 13 to 18, 22) open their screen from the stored +// preparation state. Anything else is forwarded as a desk action to the engine. FlowResult StartupFlow::route_desk(DeskRequest action) { if (action.kind == DeskRequestKind::none) return {}; if (action.kind == DeskRequestKind::end_session) return {true, FlowRequest::end_session, action}; @@ -1648,6 +1813,10 @@ FlowResult StartupFlow::route_desk(DeskRequest action) { action, std::move(entry)}; } +// Common tail of input handling for the preparation pages (lineup, pitch, player card, training, camp, bank, +// stadium, toto, transfer market, tactics). Opens local child pages (player card, pitch), closes a page that +// asked to close (copying its state back into the preparation state), and otherwise forwards the pending +// request to the engine. FlowResult StartupFlow::finish_preparation_input(PreparationRequest action, bool changed) { if (player_card_) { if (player_card_->close_requested()) { player_card_.reset(); return {true, FlowRequest::submenu_closed}; } @@ -1721,21 +1890,27 @@ FlowResult StartupFlow::finish_preparation_input(PreparationRequest action, bool {}, std::move(action)}; } +// True when the given request is the lineup page's pending request (compared through its JSON form). bool StartupFlow::matches_pending_lineup(const LineupRequest& request) const { return lineup_ && lineup_->pending() && lineup_request_json(*lineup_->pending()) == lineup_request_json(request); } +// True when the given request is the pitch page's pending request (compared through its JSON form). bool StartupFlow::matches_pending_pitch(const PitchRequest& request) const { return pitch_ && pitch_->pending() && pitch_request_json(*pitch_->pending()) == pitch_request_json(request); } +// True when the given request is the stadium page's pending request (compared through its JSON form). bool StartupFlow::matches_pending_stadium(const StadiumRequest& request) const { return stadium_ && stadium_->pending() && stadium_request_json(*stadium_->pending()) == stadium_request_json(request); } +// Stores a preparation state while the attached desk is idle. The desk in it must be an engine projection that +// serializes identically to the current desk (same revision); every screen is built once beforehand so a bad +// projection throws before anything is replaced. void StartupFlow::attach_preparation_context(PreparationState state) { if (!desktop_ || !engine_attached_ || desktop_->pending() || in_preparation_menu() || in_readonly_view() || state.desktop.source != "engine_projection" || desk_json(state.desktop) != desk_json(desktop_->state())) @@ -1753,6 +1928,7 @@ void StartupFlow::attach_preparation_context(PreparationState state) { preparation_ = std::make_unique(std::move(state)); } +// Shows the matchday results on an idle, prepared engine desk; only one results page at a time. void StartupFlow::show_matchday_results(MatchdayResults results) { if (!desktop_ || !engine_attached_ || desktop_->pending() || !preparation_ || in_preparation_menu() || in_readonly_view() || matchday_results_) @@ -1761,6 +1937,7 @@ void StartupFlow::show_matchday_results(MatchdayResults results) { matchday_results_ = std::move(screen); } +// Opens the league table screen (desk menu 0) outside the league family; every table must belong to the desk's manager slot. void StartupFlow::show_league_tables(std::array tables, int initial_league) { if (!desktop_ || !engine_attached_ || in_preparation_menu() || in_readonly_view() || matchday_results_ || !desktop_->pending() || desktop_->pending()->kind != DeskRequestKind::open_menu || @@ -1772,6 +1949,10 @@ void StartupFlow::show_league_tables(std::array tables, int desktop_->resolve_local_menu(); league_table_ = std::move(screen); } +// Table page entered as a member of the league family (family child 1). An active family requires manager, +// runtime club, club identity, day counter, source parameter, family id and default league to equal the stored +// identity; without an active family the entry must come from the desk's pending menu-0 request with a fresh +// identity. When a preparation state is supplied, its desk acknowledgement is validated like for Strengths. void StartupFlow::show_family_league_tables(std::array tables, int initial_league,StrengthsIdentity identity, std::optional preparation) { @@ -1808,6 +1989,13 @@ void StartupFlow::show_family_league_tables(std::array tabl if(desk) {desktop_=std::move(desk);preparation_=std::move(next);} if(desktop_->pending())desktop_->resolve_local_menu(); } +// Installs a Table page (and optionally a range dialog) answering a family request, with the longest chain of +// checks in this file. In order: the dialog profile and its stage must come together; the identity must match +// the stored family, and the desk's manager slot, runtime club and session identity key (at the national-coach +// desk the identity key belongs to the national team, while the desk's own runtime club is separate); +// the request that authorizes this answer must be the one currently owned by the active child, with the family +// sequence advanced by one; for the Table child, the kind of request decides whether a modal or forecast must +// follow; the dialog profile must be plausible; and a changed desk must pass the Strengths preparation check. void StartupFlow::show_family_table_dispatch(std::array tables, int initial_league, StrengthsIdentity identity, std::optional dialog, @@ -1838,6 +2026,7 @@ void StartupFlow::show_family_table_dispatch(std::array tab identity.day_counter!=desktop_->state().day_counter||identity.source_param2!=0|| identity.revision!=desktop_->state().revision||identity.family_sequence||identity.scope||identity.sequence)) throw FormatError("league family: invalid Table dispatch desktop entry"); + // Family already active: find the pending request of the current child that authorizes this answer. if(league_family_identity_) { const auto& prior=*league_family_identity_; if(league_family_child_==0) { @@ -1988,6 +2177,10 @@ void StartupFlow::show_family_table_dispatch(std::array tab family_table_source_clock_anchor_=0; if(friendly_entry)friendly_table_active_=true; } +// Table page: answer to a league selector or league-group toggle that keeps the same league, handled in place +// so the visible table frame is kept. The accepted identity must equal the old request's identity in every field +// except the family sequence (plus one) and the league group (flipped only for a toggle); no dialog, dispatch +// or forecast may be pending. Any difference throws. void StartupFlow::acknowledge_family_selector(const LeagueFamilyRequest& old_request, const StrengthsIdentity& accepted_identity) { const auto* pending=pending_league_family_action(); @@ -2028,6 +2221,9 @@ void StartupFlow::acknowledge_family_selector(const LeagueFamilyRequest& old_req family_table_source_clock_anchor_=0; } +// Called after the family table frame was shown. With a range dialog open it reports the dialog outcome as a +// table_range_result request; with a forecast waiting it reports table_forecast_presented. Either request is +// stored as the pending dispatch the engine has to answer. FlowResult StartupFlow::after_family_table_present(uint64_t absolute_source_units) { if(family_table_dispatch_pending_||!in_family_table())return {}; if(family_table_range_dialog_) { @@ -2057,12 +2253,15 @@ FlowResult StartupFlow::after_family_table_present(uint64_t absolute_source_unit } return {}; } +// Toto page: reports whether showing its frame changed the page. FlowResult StartupFlow::after_toto_present(uint64_t source_units) { return {toto_ && toto_->after_present(source_units)}; } +// Toto page: advances its time-driven state. FlowResult StartupFlow::tick_toto_source_units(uint64_t source_units) { return {toto_ && toto_->tick_source_units(source_units)}; } +// Family table range dialog: feeds it the time elapsed since the last tick (needs a valid clock anchor and no pending dispatch). FlowResult StartupFlow::tick_family_table_source_units(uint64_t absolute_source_units) { if(!family_table_range_dialog_||family_table_dispatch_pending_||!family_table_source_clock_anchor_valid_|| family_table_reset_clock_after_present_)return {}; @@ -2072,12 +2271,17 @@ FlowResult StartupFlow::tick_family_table_source_units(uint64_t absolute_source_ return {family_table_range_dialog_->tick_source_units(uint32_t(std::min(elapsed, std::numeric_limits::max())))}; } +// Family table range dialog: cancels it on the back event unless a dispatch is already pending. FlowResult StartupFlow::cancel_family_table_from_source_event() { if(!family_table_range_dialog_||family_table_dispatch_pending_)return {}; const bool changed=family_table_range_dialog_->cancel_from_source_event(); if(changed)family_table_reset_clock_after_present_=true; return {changed}; } +// Starts the league family at the desk (child 0). The identity must be a fresh one for the desk's manager slot, +// runtime club, day and revision, and its club identity must equal the desk's session identity key for that +// manager (at the national-coach desk this is the national team's identity, which can differ from the manager's +// own club identity). void StartupFlow::begin_league_family(StrengthsIdentity identity) { if(!desktop_||!engine_attached_||league_family_identity_||identity.manager!=desktop_->state().manager_slot|| identity.runtime_club!=desktop_->state().runtime_club||identity.day_counter!=desktop_->state().day_counter|| @@ -2089,6 +2293,7 @@ void StartupFlow::begin_league_family(StrengthsIdentity identity) { throw FormatError("league family: invalid manager identity"); league_family_identity_=identity;league_family_child_=0; } +// Friendly table: answer to choosing the own club's row; the pending family request must still be the stored one. void StartupFlow::acknowledge_friendly_own_club(const LeagueFamilyRequest& pending,StrengthsIdentity accepted) { const auto* action=pending_league_family_action(); if(!friendly_table_active_||!league_table_||!league_family_identity_||!action||*action!=pending|| @@ -2097,6 +2302,9 @@ void StartupFlow::acknowledge_friendly_own_club(const LeagueFamilyRequest& pendi league_table_->acknowledge_friendly_own_club(accepted);league_family_identity_=accepted; family_table_release_barrier_=false; } +// Friendly table: answer to choosing an opponent. The request must be a select_opponent; the opponent must be +// a real team other than the own one, in the requested league, and the friendly state must agree with the new +// desk (revision, manager slot, runtime club). The family is then closed and the friendly page opened. void StartupFlow::complete_friendly_opponent_table(const LeagueFamilyRequest& pending, FriendlyMatchState friendly,PreparationState preparation) { const auto* action=pending_league_family_action(); @@ -2113,6 +2321,9 @@ void StartupFlow::complete_friendly_opponent_table(const LeagueFamilyRequest& pe close_league_family(close,std::move(preparation)); friendly_match_=std::move(screen);pending_friendly_action_.reset(); } +// League family: answer to a close request from any child. The request must come from the active child and +// carry the stored manager, runtime club and family id; the new desk must be one revision ahead and keep teams, +// day and season. All family children and dialog state are then dropped. void StartupFlow::close_league_family(const LeagueFamilyRequest& pending,PreparationState state) { if(pending.kind!=LeagueFamilyRequestKind::close||pending.target_child!=0||!desktop_|| !league_family_identity_||pending.from_child!=league_family_child_|| @@ -2141,6 +2352,8 @@ void StartupFlow::close_league_family(const LeagueFamilyRequest& pending,Prepara friendly_table_active_=false; family_table_release_barrier_=false; } +// League family: the engine refused a request. A stored dispatch (range dialog result or forecast) is undone +// locally; otherwise the active child (table, pairings or strengths) shows the reason. void StartupFlow::reject_league_family(std::string reason) { if(reason.empty())throw FormatError("league family: rejection requires a reason"); if(family_table_dispatch_pending_) { @@ -2171,6 +2384,8 @@ void StartupFlow::reject_league_family(std::string reason) { else throw FormatError("league family: missing pending child request"); } +// Opens the calendar (desk menus 7 and 8). The current day of the calendar must have the desk's season day +// and day counter; the owner must be the desk's pending request. void StartupFlow::show_calendar(CalendarState state, const DeskRequest& owner) { if (!desktop_ || !engine_attached_ || in_preparation_menu() || in_readonly_view() || matchday_results_ || !desktop_->pending() || *desktop_->pending() != owner || owner.kind != DeskRequestKind::open_menu || @@ -2187,6 +2402,7 @@ void StartupFlow::show_calendar(CalendarState state, const DeskRequest& owner) { calendar_ = std::move(screen); } +// Opens the indoor standings (desk menu 9); the state must repeat the owner request exactly. void StartupFlow::show_indoor_standings(IndoorStandingsState state, const DeskRequest& owner) { if (!desktop_ || !engine_attached_ || in_preparation_menu() || in_readonly_view() || matchday_results_ || !desktop_->pending() || *desktop_->pending() != owner || owner.kind != DeskRequestKind::open_menu || @@ -2198,6 +2414,8 @@ void StartupFlow::show_indoor_standings(IndoorStandingsState state, const DeskRe indoor_standings_ = std::move(next); } +// Calendar: answer to a reschedule. The owner must be menu 7 for the same manager and revision as the new +// desk, which must be newer than the calendar's owner and equal the preparation state's desk. void StartupFlow::acknowledge_reschedule(CalendarState state, DeskRequest owner, DeskState desktop, PreparationState preparation) { if (!calendar_ || !pending_reschedule_action() || owner.menu_kind != 7 || @@ -2213,11 +2431,14 @@ void StartupFlow::acknowledge_reschedule(CalendarState state, DeskRequest owner, preparation_ = std::move(next_preparation); } +// Calendar: the engine refused the pending reschedule. void StartupFlow::reject_reschedule() { if (!calendar_ || !pending_reschedule_action()) throw FormatError("calendar: no pending reschedule action"); calendar_->reject_reschedule(); } +// Friendly match booking for a club (desk menu 6). The state's runtime team must equal the desk's own runtime +// club; the national coach has no club team and uses the national friendly picker and calendar above instead. void StartupFlow::show_friendly_match(FriendlyMatchState state, int menu_kind) { if (!desktop_ || !engine_attached_ || in_preparation_menu() || in_readonly_view() || matchday_results_ || !desktop_->pending() || desktop_->pending()->kind != DeskRequestKind::open_menu || @@ -2232,6 +2453,7 @@ void StartupFlow::show_friendly_match(FriendlyMatchState state, int menu_kind) { pending_friendly_action_.reset(); } +// Opens the mailbox (desk menu 63); manager slot and revision must equal the desk's. void StartupFlow::show_mailbox(MailboxState state) { if (!desktop_ || !engine_attached_ || in_preparation_menu() || in_readonly_view() || matchday_results_ || !desktop_->pending() || desktop_->pending()->kind != DeskRequestKind::open_menu || @@ -2244,6 +2466,8 @@ void StartupFlow::show_mailbox(MailboxState state) { mailbox_ = std::move(screen); } +// Opens the settings page (desk menu 19). With an owner sequence the new state is one revision ahead of the +// desk and the owner must be the matching menu-19 request; without one the revisions are equal. void StartupFlow::show_settings(SettingsState state, uint64_t owner_sequence, DeskRequest owner) { if (!desktop_ || !engine_attached_ || in_preparation_menu() || in_readonly_view() || matchday_results_ || !desktop_->pending() || desktop_->pending()->kind != DeskRequestKind::open_menu || @@ -2262,6 +2486,7 @@ void StartupFlow::show_settings(SettingsState state, uint64_t owner_sequence, De if (owner_sequence) settings_desk_owner_.revision = state.revision; } +// Opens the advertising page (desk menu 21); manager slot, runtime club and revision must equal the desk's. void StartupFlow::show_advertising(AdvertisingState state) { if (!desktop_ || !engine_attached_ || in_preparation_menu() || in_readonly_view() || matchday_results_ || !desktop_->pending() || desktop_->pending()->kind != DeskRequestKind::open_menu || @@ -2274,6 +2499,9 @@ void StartupFlow::show_advertising(AdvertisingState state) { ++advertising_generation_; } +// Advertising: answer to a page action. The request, the old desk and the new state must share manager slot and +// runtime club, the state must be exactly one revision ahead, and the new desk must keep teams, day, season, +// name, portrait, badge and options. Only an accepted offer reopens the offers list. void StartupFlow::acknowledge_advertising(AdvertisingState state, DeskState desk, PreparationState preparation) { if (!advertising_ || !advertising_->pending() || !desktop_ || !engine_attached_) throw FormatError("advertising: acknowledgement requires a pending action"); @@ -2306,12 +2534,16 @@ void StartupFlow::acknowledge_advertising(AdvertisingState state, DeskState desk ++advertising_generation_; } +// Advertising: the engine refused the pending action; a reason is required. void StartupFlow::reject_advertising_action(std::string reason) { if (!advertising_ || !advertising_->pending() || reason.empty()) throw FormatError("advertising: rejection requires a pending action"); advertising_->reject_action(std::move(reason)); } +// Input tail for the read-only pages (mailbox, calendar, table, settings, advertising): a close request closes +// the page (the mailbox first reports a close request to the engine), and a changed page with a pending +// action forwards that action as a request. FlowResult StartupFlow::finish_readonly_input(bool changed) { if (mailbox_ && mailbox_->close_requested()) { if (!pending_mailbox_close_) @@ -2350,6 +2582,8 @@ FlowResult StartupFlow::finish_readonly_input(bool changed) { return {changed}; } +// Mailbox: answer to a mailbox action. The new state must be one revision ahead of the desk and the pending +// request, and the new desk must keep manager slot, runtime club, day, season, name, portrait, badge and options. void StartupFlow::acknowledge_mailbox(MailboxState state, PreparationState preparation) { if (!mailbox_ || !mailbox_->pending() || !desktop_ || !engine_attached_ || state.manager_slot != desktop_->state().manager_slot || @@ -2378,10 +2612,13 @@ void StartupFlow::acknowledge_mailbox(MailboxState state, PreparationState prepa mailbox_ = std::move(screen); } +// Mailbox: the engine refused the pending action. void StartupFlow::reject_mailbox(std::string reason) { if (mailbox_) mailbox_->reject(std::move(reason)); } +// Settings: answer to a settings action. The state must be one revision ahead of the pending request and match +// the desk's manager slot; the new desk must keep teams, runtime club, day, season, name, portrait, badge and options. void StartupFlow::acknowledge_settings(SettingsState state, DeskState desk, PreparationState preparation) { if (!settings_ || !settings_->pending() || !desktop_ || !engine_attached_ || desk.source != "engine_projection" || state.manager_slot != desktop_->state().manager_slot || @@ -2408,6 +2645,7 @@ void StartupFlow::acknowledge_settings(SettingsState state, DeskState desk, Prep settings_ = std::move(next_settings); } +// Settings: the mouse release that belonged to a notice was consumed. void StartupFlow::acknowledge_settings_notice_release() { if (settings_ && !save_load_) { settings_release_barrier_ = false; @@ -2415,10 +2653,13 @@ void StartupFlow::acknowledge_settings_notice_release() { } } +// Settings: the engine refused the pending action. void StartupFlow::reject_settings(std::string reason) { if (settings_) settings_->reject(std::move(reason)); } +// Settings: answer to a file operation started from the settings page. A save/load child with a pending +// settings-file request must exist, and the new state must be one revision ahead of the settings page. void StartupFlow::acknowledge_settings_file(SettingsState state, DeskState desk, PreparationState preparation) { if (!settings_ || !save_load_ || !save_load_->pending() || save_load_->pending()->file_kind != SaveLoadFileKind::settings || !desktop_ || @@ -2439,6 +2680,7 @@ void StartupFlow::acknowledge_settings_file(SettingsState state, DeskState desk, settings_ = std::move(next_settings); } +// Settings: the engine refused the pending file operation; both the file child and the page show the reason. void StartupFlow::reject_settings_file(std::string reason) { if (!settings_ || !save_load_ || !save_load_->pending() || save_load_->pending()->file_kind != SaveLoadFileKind::settings) @@ -2447,11 +2689,14 @@ void StartupFlow::reject_settings_file(std::string reason) { settings_->reject_file(std::move(reason)); } +// Settings: drops a file request and its save/load child. void StartupFlow::cancel_settings_file() { if (settings_) settings_->cancel_file_request(); if (save_load_) save_load_.reset(); } +// Settings: answer to a close request. The page must have asked to close, and the new state must be newer than +// the desk, with the new desk agreeing with the preparation state. void StartupFlow::acknowledge_settings_closed(SettingsState state, DeskState desk, PreparationState preparation) { if (!settings_ || !settings_->close_requested() || !desktop_ || !engine_attached_ || state.manager_slot != desktop_->state().manager_slot || state.revision <= desktop_->state().revision || @@ -2466,10 +2711,14 @@ void StartupFlow::acknowledge_settings_closed(SettingsState state, DeskState des settings_release_barrier_ = false; // Main consumes a close release after the screen changed. } +// Settings: the engine refused the close. void StartupFlow::reject_settings_close(std::string reason) { if (settings_) settings_->reject_close(std::move(reason)); } +// Answer to an action on one of the preparation pages (lineup, pitch, training, camp, bank, stadium, toto, +// transfer market, tactics). The new desk must be newer and keep manager slot, runtime club, day, season, name, +// portrait, badge and options. All replacement screens are built first so a rejected answer changes nothing. void StartupFlow::acknowledge_preparation(PreparationState state, std::string transfer_notice) { if (!engine_attached_ || !preparation_ || !in_preparation_menu() || player_card_ || state.desktop.source != "engine_projection") throw FormatError("preparation acknowledgement: requires an attached engine and active menu"); @@ -2552,12 +2801,14 @@ void StartupFlow::acknowledge_preparation(PreparationState state, std::string tr pitch_entry_pending_=next_pitch_entry_pending; } +// Transfer market: the engine answered without changing anything. void StartupFlow::acknowledge_unchanged_transfer_market() { if (!in_preparation_menu() || !transfer_market_) throw FormatError("no transfer market action context"); transfer_market_->acknowledge_unchanged(); } +// The engine refused an action of the active preparation page; the page shows the reason (a pending pitch entry is undone). void StartupFlow::reject_preparation_action(std::string reason) { if (!in_preparation_menu()) throw FormatError("no preparation action context"); if (player_card_) throw FormatError("player card has no engine action"); diff --git a/src/ui/stadium.cpp b/src/ui/stadium.cpp index 48ada72..6d6fd0a 100644 --- a/src/ui/stadium.cpp +++ b/src/ui/stadium.cpp @@ -20,11 +20,13 @@ namespace bmh::ui { namespace { +// Fills a w*h rectangle with one palette index, clipped to the image. Used for panels, shadows and backgrounds. void fill(Image& im, int x, int y, int w, int h, uint8_t color) { for (int yy = std::max(0, y); yy < std::min(im.height, y + h); ++yy) for (int xx = std::max(0, x); xx < std::min(im.width, x + w); ++xx) im.at(xx, yy) = color; } +// Draws a 1-pixel rectangle outline (w*h, clipped to the image). Used for hover and press highlights. void outline(Image& im, int x, int y, int w, int h, uint8_t color) { if (w <= 0 || h <= 0) return; const int right = x + w - 1; @@ -38,6 +40,7 @@ void outline(Image& im, int x, int y, int w, int h, uint8_t color) { if (right >= 0 && right < im.width) im.at(right, yy) = color; } } +// Draws the 1-pixel panel border over the inclusive rectangle: 0x46 on top/left, 0x40 on bottom/right. void source_border(Image& im, int left, int top, int right, int bottom) { // PaintsFourBorderEdges draws these inclusive edges in this order. The bottom edge // overwrites the lower-left pixel from the first edge; the right edge @@ -47,6 +50,8 @@ void source_border(Image& im, int left, int top, int right, int bottom) { for (int x = left; x <= right; ++x) im.at(x, bottom) = 0x40; for (int y = top; y <= bottom; ++y) im.at(right, y) = 0x40; } +// Copies a w*h crop of src (starting at sx,sy) to dst at (x,y); pixels outside either image are skipped. +// With transparent=true, palette index 0 in the source is treated as the transparent key. void copy_crop(Image& dst, const Image& src, int sx, int sy, int x, int y, int w, int h, bool transparent = false) { for (int yy = 0; yy < h; ++yy) for (int xx = 0; xx < w; ++xx) { @@ -57,11 +62,14 @@ void copy_crop(Image& dst, const Image& src, int sx, int sy, int x, int y, int w if (!transparent || color != 0) dst.at(dx, dy) = color; } } +// Draws the 2-pixel dark (0x40) shadow strips below and to the right of a w*h box at (x,y). void source_shadow(Image& out, int x, int y, int w, int h) { // ColorBottomRightBevel draws its two inclusive rectangles after clipping to the screen. fill(out, x + 2, y + h, w, 2, 0x40); fill(out, x + w, y + 2, 2, h, 0x40); } +// Draws a dialog frame: optional shadow, a 16x16 background pattern read from the executable, the four +// corner pieces from the widget atlas, and the edge strips tiled in runs of 74 px (top/bottom) and 96 px (left/right). void source_frame(Image& out, const Image& atlas, const LeImage& exe, int x, int y, int w, int h, bool shadow = true) { if (shadow) { fill(out, x + 2, y + h, w, 2, 0x40); fill(out, x + w, y + 2, 2, h, 0x40); } @@ -82,6 +90,9 @@ void source_frame(Image& out, const Image& atlas, const LeImage& exe, copy_crop(out, atlas, 4, 8, x + w - 4, y + at, 4, n); } } +// Draws text with its baseline at `baseline` (skipped entirely if it would leave the screen vertically). +// In gradient mode (executable flag == 2) a color found in the 32-entry gradient table is recolored per glyph row +// from a 6-row gradient; color 0x40 and unknown colors are drawn plain. void draw_source_font(Image& out, const Font& font, const LeImage& exe, int x, int baseline, std::string_view text, uint8_t color, bool gradient) { const int y = baseline - font.baseline; @@ -92,6 +103,7 @@ void draw_source_font(Image& out, const Font& font, const LeImage& exe, int x, i } unsigned slot = 0; while (slot < 32 && exe.u8(::bmh::layout::Advertising_Text_RuntimeField2 + slot) != color) ++slot; + // color is not in the gradient table: fall back to a plain draw if (slot == 32) { font.draw(out, x, y, text, color); return; } Image mask(std::max(1, font.text_width(text)), font.height, 0); font.draw(mask, 0, 0, text, 1); @@ -100,13 +112,16 @@ void draw_source_font(Image& out, const Font& font, const LeImage& exe, int x, i if (mask.at(column, row) && x + column >= 0 && x + column < out.width) out.at(x + column, y + row) = exe.u8(::bmh::layout::Advertising_Text_RuntimeField + slot * 6 + size_t(std::min(row, 5))); } +// Reads a little-endian int32 from a manager record at byte offset `at` (bounds-checked). int32_t record_i32(const std::vector& bytes, size_t at) { return int32_t(uint32_t(bytes.at(at)) | uint32_t(bytes.at(at + 1)) << 8 | uint32_t(bytes.at(at + 2)) << 16 | uint32_t(bytes.at(at + 3)) << 24); } +// Reads a little-endian uint16 from a manager record at byte offset `at` (bounds-checked). uint16_t record_u16(const std::vector& bytes, size_t at) { return uint16_t(bytes.at(at) | uint16_t(bytes.at(at + 1)) << 8); } +// Reads the base price and construction duration of the 8 investments from the executable tables. StadiumInvestmentConstants investment_constants(const LeImage& exe) { StadiumInvestmentConstants constants; for (unsigned choice = 0; choice < 8; ++choice) { @@ -115,21 +130,27 @@ StadiumInvestmentConstants investment_constants(const LeImage& exe) { } return constants; } +// True if periphery object 0..13 can still be built: no construction running and not yet built +// (object 0 stays available until its level reaches 0xab). bool periphery_available(const StadiumState& state, int object) { return object >= 0 && object < 14 && state.days[size_t(object)] == 0 && (object == 0 ? state.level[0] < 0xab : state.level[size_t(object)] == 0); } +// Display name of an investment row (its original label text). std::string investment_name(const StadiumInvestmentRow& row) { return row.original_label; } +// Looks up a TEXTD string through a text pointer variable; empty if the id is out of range. std::string textd_string(const TextDb& textd, uint32_t pointer_variable) { const size_t id = text_id(pointer_variable); return id < textd.strings.size() ? textd[id] : std::string{}; } +// Same as textd_string, using the texts loaded in the game state; empty if none are loaded. std::string game_textd_string(const GameState& game, uint32_t pointer_variable) { if (!game.texts) return {}; return textd_string(*game.texts, pointer_variable); } +// Copies a stored name, replacing each ':' marker with the given separator text. std::string expand_original_club_label(std::string_view name, std::string_view separator) { std::string expanded; for (char byte : name) { @@ -138,6 +159,8 @@ std::string expand_original_club_label(std::string_view name, std::string_view s } return expanded; } +// Formats a duration: the number, then a unit text from TEXTD, an extra executable string when value != 1, +// and a trailing executable string. std::string original_duration_text(const GameState& game, const TextDb& textd, const LeImage& exe, int value, uint8_t format, uint32_t unit_address) { @@ -146,6 +169,7 @@ std::string original_duration_text(const GameState& game, const TextDb& textd, result += exe.cstring(::bmh::layout::CareerSession_FormatNumber_ExecutableField); return result; } +// Serializes a block expansion quote as a JSON object (part of the state dump). std::string block_quote_json(const StadiumBlockExpansionQuote& q) { std::ostringstream out; out << "{\"manager\":" << q.manager << ",\"manager_club\":" << q.manager_club @@ -163,6 +187,7 @@ std::string block_quote_json(const StadiumBlockExpansionQuote& q) { << ",\"base_weeks\":" << unsigned(q.base_weeks) << '}'; return out.str(); } +// True for the request kinds that belong to the block expansion editor (they carry block fields). bool block_request_kind(StadiumRequestKind kind) { switch (kind) { case StadiumRequestKind::expansion_select: @@ -174,6 +199,8 @@ bool block_request_kind(StadiumRequestKind kind) { default: return false; } } +// True if two quotes describe the same manager, club, slot, current block state, price table entry and limits. +// The target-dependent costs are deliberately not compared. bool same_block_quote_owner(const StadiumBlockExpansionQuote& a, const StadiumBlockExpansionQuote& b) { return a.manager == b.manager && a.manager_club == b.manager_club && a.slot == b.slot && @@ -183,6 +210,8 @@ bool same_block_quote_owner(const StadiumBlockExpansionQuote& a, a.company_price_percent == b.company_price_percent && a.price_per_1000 == b.price_per_1000 && a.max_places == b.max_places && a.base_weeks == b.base_weeks; } +// Recomputes a block expansion quote from (total places, features) and the constants and returns true only if +// every field of `q` matches and all ranges are valid. Used to validate quotes in acknowledgements. bool canonical_block_quote(const StadiumBlockExpansionQuote& q, uint32_t total, uint8_t features,const StadiumBlockExpansionConstants& constants) { const auto& prices=constants.price_per_1000;const auto& maxima=constants.max_places;const auto& weeks=constants.weeks; @@ -198,6 +227,7 @@ bool canonical_block_quote(const StadiumBlockExpansionQuote& q, uint32_t total, return false; const uint32_t current = uint32_t(q.current_capacity_thousands) * 1000u; const uint32_t added = total - current; + // Cost component = price_per_1000 * (places/1000) * multiplier / divisor; fails if the product exceeds int32. const auto component = [&](uint32_t places, uint32_t multiplier, uint32_t divisor, uint32_t& out) { const uint64_t value = uint64_t(q.price_per_1000) * (places / 1000u) * multiplier; @@ -205,6 +235,8 @@ bool canonical_block_quote(const StadiumBlockExpansionQuote& q, uint32_t total, out = uint32_t(value / divisor); return true; }; + // New places are charged in full; seats cost 45% and roof 30% of the per-place price. If the feature is + // already built (raw flag set), only the newly added places are charged for it, otherwise the whole block. uint32_t new_cost = 0, seats = 0, roof = 0; if (!component(added, 1, 1, new_cost) || ((features & 1) && !component((q.current_raw_flags & 1) ? added : total, 45, 100, seats)) || @@ -219,12 +251,15 @@ bool canonical_block_quote(const StadiumBlockExpansionQuote& q, uint32_t total, q.undiscounted_cost == sum && q.base_price == uint32_t(sum * uint32_t(q.company_price_percent) / 100u); } +// True if the editor mirrors its quote (target places, features) and the quote is canonical. +// header_text_variant must be in 3..10. bool valid_editor_projection(const StadiumBlockExpansionEditor& editor,const StadiumBlockExpansionConstants& constants) { return editor.total_target_places == editor.quote.total_target_places && editor.desired_features == editor.quote.desired_features && editor.header_text_variant >= 3 && editor.header_text_variant <= 10 && canonical_block_quote(editor.quote, editor.total_target_places, editor.desired_features,constants); } +// True if all 8 block overviews are identical (construction weeks, flags, capacity levels, capacities). bool same_block_overviews(const std::array& a, const std::array& b) { for (size_t i = 0; i < a.size(); ++i) @@ -233,6 +268,7 @@ bool same_block_overviews(const std::array& a, return false; return true; } +// Like same_block_overviews, but ignores the slot that was just changed. bool same_other_block_overviews(const std::array& a, const std::array& b, size_t changed_slot) { @@ -244,10 +280,13 @@ bool same_other_block_overviews(const std::array& a, } return true; } +// True if the presentation flags (backgrounds, dialog frame, gradient text) are identical. bool same_source_stadium_style(const StadiumState& a, const StadiumState& b) { return a.plain_background == b.plain_background && a.compact_dialog_frame == b.compact_dialog_frame && a.solid_panel_background == b.solid_panel_background && a.gradient_text == b.gradient_text; } +// True if style and the inputs of the ticket compensation (level, live round, refund rate, season tickets) +// are unchanged; allow_ticket_cap permits season_tickets to differ (they may be capped after a build). bool same_block_compensation_context(const StadiumState& a, const StadiumState& b, bool allow_ticket_cap = false) { return same_source_stadium_style(a, b) && @@ -255,6 +294,8 @@ bool same_block_compensation_context(const StadiumState& a, const StadiumState& a.ticket_refund_rate == b.ticket_refund_rate && (allow_ticket_cap || a.season_tickets == b.season_tickets); } +// Sum of the capacity levels (thousands of places) of all blocks that are not under construction, +// excluding the block that is just becoming busy. uint8_t source_usable_capacity_thousands(const std::array& blocks, size_t newly_busy_slot) { uint8_t usable = 0; @@ -264,9 +305,12 @@ uint8_t source_usable_capacity_thousands(const std::array(uint32_t(uint64_t(value))); } +// Refund owed for season tickets that no longer fit into the usable capacity: +// missing tickets * min(15, 17 - live round) weeks * refund rate, wrapped to int32. Zero if everything fits. int32_t source_immediate_compensation(uint16_t tickets, uint8_t usable_thousands, uint8_t live_round, int32_t rate) { const int32_t capacity = int32_t(usable_thousands) * 1000; @@ -275,14 +319,19 @@ int32_t source_immediate_compensation(uint16_t tickets, uint8_t usable_thousands const int32_t weeks = std::min(15, 17 - int32_t(live_round)); return source_wrap_i32(int64_t(missing) * int64_t(weeks) * int64_t(rate)); } +// Season tickets capped to the usable capacity (thousands * 1000). uint16_t source_ticket_cap(uint16_t tickets, uint8_t usable_thousands) { return uint16_t(std::min(tickets, uint32_t(usable_thousands) * 1000u)); } } +// Projects the live game state of the active manager into a StadiumState for the screen: balance, texts, +// periphery levels/days, seat blocks and the 8 investment rows with their options. +// Throws FormatError if the active manager or its record is invalid. StadiumState stadium_from_game(const GameState& game, const LeImage& exe, uint64_t revision, int construction_percent) { const int manager = int(game.memory.u8(::bmh::layout::ActiveManager)); + // Each manager has a fixed 0xb0c-byte record in manager_records; all record offsets below are relative to it. const size_t record = size_t(manager) * 0xb0c; if (size_t(manager) >= game.manager_teams.size() || record + 0x5d > game.manager_records.size()) throw FormatError("stadium: invalid active manager or truncated record"); @@ -290,9 +339,13 @@ StadiumState stadium_from_game(const GameState& game, const LeImage& exe, uint64 state.manager_slot = manager; state.runtime_club = game.manager_teams.at(size_t(manager)); state.revision = revision; + // balance is stored at record offset 0x314 state.balance = record_i32(game.manager_records, record + 0x314); state.balance_text = format_number(game, state.balance, 0x181); state.construction_percent = construction_percent; + // Title and footer texts. The footer is the stadium name followed by the capacity in seats. The name comes + // from the stadium-name pool (indexed through club_heap_bc) unless a runtime flag selects a fixed text; + // if no name is found, a TEXTD prefix plus the club name is used instead. if (state.runtime_club >= 0 && size_t(state.runtime_club) < game.club_ids.size()) { state.original_stadium_title = game.club_name(state.runtime_club); std::string footer_name; @@ -316,11 +369,13 @@ StadiumState stadium_from_game(const GameState& game, const LeImage& exe, uint64 format_number(game, int32_t(uint32_t(game.manager_records.at(record + 0x5c)) * 1000), 1) + game_textd_string(game, ::bmh::layout::Stadium_FormatError_ExecutableField3); } + // Presentation flags read from game memory (absent memory counts as off). state.plain_background = game.memory.has(::bmh::layout::PlainBackground) && game.memory.u8(::bmh::layout::PlainBackground) != 0; state.compact_dialog_frame = game.memory.has(::bmh::layout::CompactDialogFrame) && game.memory.u8(::bmh::layout::CompactDialogFrame) != 0; state.decorated_stadium_header = !state.plain_background; state.periphery_animation_tick = game.memory.has(::bmh::layout::CareerSession_Invalid_RuntimeField2) ? game.memory.u32(::bmh::layout::CareerSession_Invalid_RuntimeField2) : 0; state.periphery_balance_text = format_number(game, state.balance, 0x187) + exe.cstring(::bmh::layout::CareerSession_FormatNumber_ExecutableField); + // Pre-formatted price and duration texts of the 14 periphery objects. for (size_t i = 0; i < 14; ++i) { state.periphery_price_text[i] = format_number(game, int32_t(exe.u32(::bmh::layout::StadiumPriceTable + i * 4)), 0x187) + exe.cstring(::bmh::layout::CareerSession_FormatNumber_ExecutableField); @@ -329,10 +384,12 @@ StadiumState stadium_from_game(const GameState& game, const LeImage& exe, uint64 if (days != 1) state.periphery_duration_text[i] += exe.cstring(::bmh::layout::Stadium_FormatError_ExecutableField); state.periphery_duration_text[i] += exe.cstring(::bmh::layout::CareerSession_FormatNumber_ExecutableField); } + // Per-object build level (record +0) and remaining construction days (record +0x1e). for (size_t i = 0; i < state.level.size(); ++i) { state.level[i] = game.manager_records.at(record + i); state.days[i] = game.manager_records.at(record + 0x1e + i); } + // The 8 seat blocks: construction weeks (+0x34), flags (+0x44), capacity level (+0x4c), capacity (+0x54). for (unsigned i = 0; i < 8; ++i) { auto& block = state.blocks[i]; block.construction_weeks = game.manager_records.at(record + 0x34 + i); @@ -340,6 +397,8 @@ StadiumState stadium_from_game(const GameState& game, const LeImage& exe, uint64 block.capacity_level = game.manager_records.at(record + 0x4c + i); block.capacity = game.manager_records.at(record + 0x54 + i); } + // The 8 investment rows: status (+0x3c), remaining weeks (+0x2c), the available options and their price texts. + // The price of option n is the base price times (n + 1). const auto constants = investment_constants(exe); for (unsigned i = 0; i < 8; ++i) { auto& row = state.investments[i]; @@ -360,6 +419,9 @@ StadiumState stadium_from_game(const GameState& game, const LeImage& exe, uint64 return state; } +// Builds the data page projection for a manager (slot 0..4): ticket price, six history curves with their +// scale limits, the 3x7 statistics table texts and the required attendance text. +// Throws FormatError on invalid selectors or out-of-range record contents. StadiumDataProjection stadium_data_from_game(const GameState& game, const LeImage& exe, int manager, uint8_t flags) { if (manager < 0 || manager > 4) throw FormatError("stadium data: invalid manager"); @@ -368,6 +430,9 @@ StadiumDataProjection stadium_data_from_game(const GameState& game, const LeImag const size_t at = size_t(manager) * 0xb0c; const auto& r = game.manager_records; out.ticket_price = r.at(at + 0x26e); + // Curves: the executable assigns each curve a history selector (0..3) whose record counter gives the + // number of samples. Sample values are read from different record arrays per curve; the scale limits come + // from executable tables. for (int curve = 0; curve < 6; ++curve) { const int selector = exe.u8(::bmh::layout::Analytics_FormatError_RuntimeField2 + 6 + curve); if (selector < 0 || selector > 3) throw FormatError("stadium data: invalid Source history selector"); @@ -390,8 +455,10 @@ StadiumDataProjection stadium_data_from_game(const GameState& game, const LeImag out.minimum[size_t(curve)] = std::bit_cast(exe.u32(::bmh::layout::Analytics_FormatError_RuntimeField3 + 24 + curve * 4)); out.maximum[size_t(curve)] = std::bit_cast(exe.u32(::bmh::layout::Analytics_FormatError_RuntimeField4 + 24 + curve * 4)); } + // Maximum of curves 0 and 1 derives from the stadium capacity (record +0x5c, in thousands): x1000 and x20000. out.maximum[0] = int32_t(r.at(at + 0x5c)) * 1000; out.maximum[1] = int32_t(r.at(at + 0x5c)) * 20000; + // Formats a day counter as dd.mm.yy using the executable's separator string; '%' padding becomes '0'. const auto date_text = [&](uint32_t counter) { const auto date = desk_date(counter, exe); auto text = format_number(game, date.day, 2) + exe.cstring(::bmh::layout::OtherGamesState_ResultText_ExecutableField) + @@ -400,6 +467,8 @@ StadiumDataProjection stadium_data_from_game(const GameState& game, const LeImag std::replace(text.begin(), text.end(), '%', '0'); return text; }; + // Statistics table: 3 columns (kind) x 7 rows. Rows 0..3 hold a record value with date or an opponent name + // (row 1 and 3 hold the name, rows 0 and 2 the value), rows 4..6 are numeric: a count, a value divided by that count, and a third stored value. for (int kind = 0; kind < 3; ++kind) for (int row = 0; row < 7; ++row) { auto text = row == 1 || row == 3 ? std::string{} : message_text(game, ::bmh::layout::Stadium_StadiumDataFromGame_TextPointer); if (row < 4) { @@ -432,6 +501,9 @@ StadiumDataProjection stadium_data_from_game(const GameState& game, const LeImag return out; } +// Converts one curve of the data page into screen points (x, y). Without the fixed-scale flag (0x40) the +// values are normalised to 0..100 first. The graph is 83 px high with its baseline at y=101, and x spreads +// the samples over 298 px starting at x=13. std::vector> stadium_data_points(const StadiumDataProjection& data, const LeImage& exe, int curve) { if (curve < 0 || curve >= 6) throw FormatError("stadium data: invalid curve"); @@ -448,6 +520,7 @@ std::vector> stadium_data_points(const StadiumDataProjection } if (low > high) throw FormatError("stadium data: reversed Source graph scale"); const int selector = exe.u8(::bmh::layout::Analytics_FormatError_RuntimeField2 + 6 + curve); + // number of x slots the samples are spread over (at least 34 for selector 0, otherwise 17) const int horizon = std::max(int(values.size()), selector == 0 ? 34 : 17); std::vector> points; for (size_t sample = 0; sample < values.size(); ++sample) { @@ -461,6 +534,7 @@ std::vector> stadium_data_points(const StadiumDataProjection return points; } +// Only updates the construction percent; the investment options are reprojected by the owner of the game state. void stadium_apply_price_table(StadiumState& state, const LeImage& exe, int construction_percent) { (void)exe; // Options must be reprojected from the live GameState by the App owner; this @@ -468,6 +542,7 @@ void stadium_apply_price_table(StadiumState& state, const LeImage& exe, int cons state.construction_percent = construction_percent; } +// Serializes the full StadiumState as JSON (state dump for tests and tooling). std::string stadium_state_json(const StadiumState& s) { std::ostringstream out; out << "{\"manager_slot\":" << s.manager_slot << ",\"runtime_club\":" << s.runtime_club @@ -554,6 +629,7 @@ std::string stadium_state_json(const StadiumState& s) { return out.str(); } +// Serializes a request, including its kind name and the optional expected block quote, as JSON. std::string stadium_request_json(const StadiumRequest& r) { const char* kind = "none"; switch (r.kind) { @@ -598,6 +674,8 @@ std::string stadium_request_json(const StadiumRequest& r) { return out.str(); } +// Loads the executable, text database, graphics and fonts the screen needs and validates the scene sizes. +// Empty investment labels are filled from TEXTD (ids 734..741). Throws FormatError on unusable assets. StadiumScreen::StadiumScreen(const std::filesystem::path& data, StadiumState state) : state_(std::move(state)), data_(data), exe_(load_le(asset_path(data, "BMH.exe"))), texts_(load_textd(asset_path(data, "TEXTD.BLK"))), @@ -621,15 +699,19 @@ StadiumScreen::StadiumScreen(const std::filesystem::path& data, StadiumState sta rebuild_tip_dialog(); } +// Draws text in the screen font at a baseline position; gradient is applied only if the state enables it. void StadiumScreen::text_at(Image& out, int x, int baseline, std::string_view text, uint8_t color, bool gradient) const { draw_source_font(out, font_, exe_, x, baseline, text, color, gradient && state_.gradient_text); } +// Draws a button in the original style at (x,y) with size w*h; `selected` draws the pressed/active look. +// Wide buttons (w > 31) are assembled from left/middle/right slices of the widget atlas, narrow ones use a frame. void StadiumScreen::original_button(Image& out, int x, int y, int w, int h, std::string_view label, bool selected) const { // FormatError3's requested 9px height becomes 10px for these wide controls. + // wide buttons requested with height 9 are drawn 10 px high const int visible_h = w > 31 && h == 9 ? 10 : h; if (visible_h != 10 && !(w <= 31 && visible_h == 9)) throw FormatError("stadium: unsupported Original button height"); if (selected) { @@ -654,6 +736,8 @@ void StadiumScreen::original_button(Image& out, int x, int y, int w, int h, y + 7, original_to_utf8(label), exe_.u8(::bmh::layout::Advertising_Button_RuntimeField + int(selected))); } +// Creates a request stamped with the identity of the current state (manager, club, scope, sequence and revision). +// acknowledge() later checks these stamps against the engine's answer, so stale requests are rejected. StadiumRequest StadiumScreen::request(StadiumRequestKind kind, int object, int option, int32_t price, bool accept_tip) const { StadiumRequest r; @@ -664,6 +748,9 @@ StadiumRequest StadiumScreen::request(StadiumRequestKind kind, int object, int o return r; } +// Creates a request for the block expansion editor. It also carries the quote the editor currently shows +// (expected_block_quote), which the engine must still find unchanged. A zero total/features means 'keep the +// editor's current value'; set_total and toggle_feature always use the value passed in. StadiumRequest StadiumScreen::block_request(StadiumRequestKind kind, uint32_t total, uint8_t features) const { if (!block_request_kind(kind)) throw FormatError("stadium: invalid block expansion request kind"); @@ -685,6 +772,7 @@ StadiumRequest StadiumScreen::block_request(StadiumRequestKind kind, uint32_t to return r; } +// Creates the initial open request; it is also stored as pending until acknowledge() is called. StadiumRequest StadiumScreen::initialize() { if (pending_) throw FormatError("stadium: open already pending"); auto r = request(StadiumRequestKind::open); @@ -692,6 +780,8 @@ StadiumRequest StadiumScreen::initialize() { return r; } +// Rebuilds the modal dialogs (periphery quote and construction tip) over a snapshot of the current scene. +// Called after the state changes. void StadiumScreen::rebuild_tip_dialog() { tip_dialog_.reset(); periphery_dialog_.reset(); @@ -709,6 +799,8 @@ void StadiumScreen::rebuild_tip_dialog() { } } +// Renders the block expansion editor dialog (title, balance, duration, current and target places, per-feature +// icons and costs, total with discount, Build/Cancel buttons) over the given scene image. Image StadiumScreen::render_block_expansion(Image out) const { if (!state_.block_expansion) return out; const auto& editor = *state_.block_expansion; @@ -755,6 +847,8 @@ Image StadiumScreen::render_block_expansion(Image out) const { editor.new_places_cost_text, 0x6c, true); } + // Two feature rows: seats (bit 1) and roof (bit 2), each with an icon cropped from the interior atlas, + // an on/off status text and its cost. for (unsigned feature = 0; feature < 2; ++feature) { const uint8_t bit = uint8_t(1u << feature); const int icon_y = feature == 0 ? 73 : 89; @@ -774,6 +868,8 @@ Image StadiumScreen::render_block_expansion(Image out) const { return out; } +// Renders the numeric calculator window over the editor (only while it is open and not in its cancel wait). +// Its position (block_calculator_x_/y_) is draggable; key and preset positions come from executable tables. Image StadiumScreen::render_block_calculator(Image out) const { if (!block_calculator_open_ || block_calculator_cancel_wait_ || !state_.block_expansion) return out; const int x0 = block_calculator_x_, y0 = block_calculator_y_; @@ -784,6 +880,7 @@ Image StadiumScreen::render_block_calculator(Image out) const { const std::string title = texts_[1118]; const int width = font_.text_width(title); text_at(out, x0 + 8 + (105 - 8) / 2 - width / 2, y0 + 14, title, 0x62, true); + // key labels in index order: digits 0-9, D delete, R restore, C clear, J accept, N cancel constexpr std::string_view keys = "0123456789DRCJN"; for (int i = 0; i < 15; ++i) { const int x = x0 + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField + size_t(i) * 2); @@ -794,6 +891,8 @@ Image StadiumScreen::render_block_calculator(Image out) const { text_at(out, x + 5 + int(pressed), y + 9 + int(pressed), keys.substr(size_t(i), 1), 0x62, false); } const uint32_t current = uint32_t(editor.quote.current_capacity_thousands) * 1000; + // Preset buttons (indices 15..22): current capacity plus 0..5 thousand, the current capacity again, and the maximum. + // Presets above the maximum are not shown. std::array presets{}; for (uint32_t i = 0; i < 6; ++i) presets[i] = current + i * 1000; presets[6] = current; presets[7] = editor.quote.max_places; @@ -810,12 +909,15 @@ Image StadiumScreen::render_block_calculator(Image out) const { return out; } +// Renders the panorama view: opaque underlay, capacity-dependent stands sprite, then every built or +// under-construction periphery object back to front, with construction details, plus the hover info box. void StadiumScreen::render_panorama(Image& out) const { // ConstructionPricePercent uses KB70 as the opaque panorama underlay; KB35 is an atlas, // not a full-screen background. CopyCrop skips the Original zero key. copy_crop(out, periphery_overlay_, 0, 0, 18, 25, 279, 183); fill(out, 297, 32, 6, 183, 0x40); fill(out, 25, 208, 272, 7, 0x40); + // Draws sprite `slot`: its screen rectangle and atlas source position come from executable tables. const auto sprite = [&](unsigned slot) { const int x = exe_.u16(::bmh::layout::Stadium_PeripheryObjectContains_ExecutableField + slot * 8), y = exe_.u16(::bmh::layout::Stadium_RenderPanorama_RuntimeField + slot * 8); const int w = exe_.u16(::bmh::layout::Stadium_RenderPanorama_RuntimeField2 + slot * 8) - x + 1; @@ -825,7 +927,10 @@ void StadiumScreen::render_panorama(Image& out) const { }; unsigned capacity = 0; for (const auto& block : state_.blocks) capacity += block.capacity_level; + // total capacity level of 10 or more selects one of up to four stands sprites if (capacity > 9) sprite(14 + std::min(3u, (capacity - 10) / 10)); + // Paint order is given by an executable table. Objects 0..5 are shown while under construction, others only + // once built (level != 0). Busy objects additionally draw their construction parts. for (unsigned order = 0; order < 14; ++order) { const unsigned object = exe_.u8(::bmh::layout::Stadium_RenderPanorama_RuntimeField6 + order); const unsigned level = state_.level[object]; @@ -849,6 +954,7 @@ void StadiumScreen::render_panorama(Image& out) const { const int sx = 200 + exe_.u8(bounds), sy = exe_.u8(bounds + 1); const int w = exe_.u8(bounds + 2) - exe_.u8(bounds) + 1; const int h = exe_.u8(bounds + 3) - sy + 1; + // tile 8 is an animated part: it is mirrored depending on the animation tick and placed at a fixed position const bool flip = tile == 8 && ((state_.periphery_animation_tick >> (object == 2)) & 1); const int x = flip ? (object == 2 ? 28 : 104) : exe_.u16(at + 2); const int y = flip ? 127 : exe_.u16(at + 4); @@ -859,6 +965,8 @@ void StadiumScreen::render_panorama(Image& out) const { } } } + // Hover info box for the object under the pointer: title plus either remaining days (under construction) + // or price, duration and balance (available to build). if (periphery_hover_ < 0) return; const size_t object = size_t(periphery_hover_); copy_crop(out, periphery_overlay_, 8, 7, 26, 32, 180, 27); @@ -886,6 +994,7 @@ void StadiumScreen::render_panorama(Image& out) const { } } +// True if (x,y) lies inside the inclusive hit rectangle of a periphery object (from an executable table). bool StadiumScreen::periphery_object_contains(int object, int x, int y) const { if (object < 0 || object >= 14) return false; const size_t at = ::bmh::layout::Stadium_PeripheryObjectContains_ExecutableField + size_t(object) * 8; @@ -893,6 +1002,8 @@ bool StadiumScreen::periphery_object_contains(int object, int x, int y) const { x <= exe_.u16(at + 4) && y <= exe_.u16(at + 6); } +// Returns the periphery object at (x,y) or -1. Only active in the panorama view with investments enabled. +// Candidates are objects under construction, or buildable ones when future information is shown. int StadiumScreen::periphery_object_at(int x, int y) const { if (!panorama_ || !state_.investments_enabled) return -1; // Source hit order deliberately differs from the back-to-front paint order. @@ -905,6 +1016,8 @@ int StadiumScreen::periphery_object_at(int x, int y) const { return -1; } +// Renders the base scene: header, club title and footer, then either the panorama or the interior view with +// the 8 seat block rows and 8 investment icons, the three scene buttons and the feedback line. Image StadiumScreen::render_scene() const { Image out(320, 240); if (state_.decorated_stadium_header) out = header_background_; @@ -916,6 +1029,7 @@ Image StadiumScreen::render_scene() const { sprite_font_.text_width(original_to_utf8(title)) / 2, 13, original_to_utf8(title)); sprite_font_.draw(out, 5, 235, original_to_utf8(state_.original_stadium_footer.empty() ? state_.club_name : state_.original_stadium_footer)); + // Interior view layers, in order: shadow and interior picture, seat block rows (right column), investment icons. if (panorama_) render_panorama(out); else { // ConstructionPricePercent draws ColorBottomRightBevel, then the opaque KB38 crop. @@ -924,6 +1038,8 @@ Image StadiumScreen::render_scene() const { // Original's eight separate block rows (ConstructionPricePercent). These read-only facts // retain the block branch's real records and never act as facility rows. + // Seat block rows A-H: 100x24 px cells at x=219, stacked from y=22. Shows the label, then either the current + // usable capacity and maximum, or (future information) the new capacity or construction state. for (unsigned i = 0; i < state_.blocks.size(); ++i) { const int row_y = 22 + int(i) * 24; if (state_.solid_panel_background) { @@ -935,12 +1051,14 @@ Image StadiumScreen::render_scene() const { copy_crop(out, panel_, 219, row_y - 19, 220, row_y + 1, 98, 22); } source_border(out, 219, row_y, 318, row_y + 23); + // hover frame around the row under the pointer if (pressed_ == Pressed::none && hover_block_ == int(i)) outline(out, 219, row_y, 100, 24, 0x27); const auto& block = state_.blocks[i]; std::string label = texts_[text_id(::bmh::layout::Stadium_Out_TextPointer)]; if (label.size() > 6) label[6] = char('A' + i); text_at(out, 221, row_y + 7, label, 0x6b); if (block.capacity || block.capacity_level) { + // Normal mode: current usable capacity, maximum, and icons for the built features (flag bits 1 and 2). if (!future_information_) { const unsigned available = block.capacity ? 0 : block.capacity_level; const std::string current = format_number(GameState{}, int32_t(available * 1000), 0x85) + @@ -968,6 +1086,7 @@ Image StadiumScreen::render_scene() const { block.construction_weeks, 2, ::bmh::layout::Stadium_FormatError_RuntimeField); text_at(out, 221, row_y + 21, duration, 0x51); } + // future information: pending features are stored in flag bits 4 and 5 const unsigned pending_flags = (block.flags >> 4) & 3; if (pending_flags & 1) copy_crop(out, interior_, 180, 1, 307, row_y + 2, 10, 10, true); if (pending_flags & 2) copy_crop(out, interior_, 180, 12, 307, row_y + 12, 10, 10, true); @@ -975,6 +1094,8 @@ Image StadiumScreen::render_scene() const { } } + // Investment icons: 53x29 px sprites at positions from executable tables. The level (status bits 0..2, or the + // target level in bits 4..6 with future information) selects the sprite; level 0 shows the empty slot. for (unsigned choice = 0; choice < 8; ++choice) { const uint32_t x_table = ::bmh::layout::Stadium_Out_ExecutableField2 + choice * 2; const uint32_t y_table = ::bmh::layout::Stadium_Out_ExecutableField3 + choice * 2; @@ -984,6 +1105,7 @@ Image StadiumScreen::render_scene() const { const auto& row = state_.investments[choice]; unsigned visual_level = future_information_ ? (row.current_status >> 4) & 7 : 0; if (visual_level == 0) visual_level = row.current_status & 7; + // choices 2 and 3 have one sprite less (their level is shifted down by one) if (choice == 2 || choice == 3) { if (visual_level > 0) --visual_level; } @@ -1001,6 +1123,7 @@ Image StadiumScreen::render_scene() const { text_at(out, x + (0x35 - label_width) / 2, y + 0x1b, tier, 0x5f); } } + // hover/press frame around the icon if ((pressed_ == Pressed::investment && pressed_index_ == int(choice)) || (pressed_ == Pressed::none && hover_investment_ == int(choice))) outline(out, x, y, 0x35, 0x1d, 0x27); @@ -1012,6 +1135,8 @@ Image StadiumScreen::render_scene() const { } } } + // The three scene buttons at y=215: view switch (hidden when investments are disabled), future information + // switch, and data page. const std::array labels = panorama_ ? std::array{texts_[150], texts_[151], texts_[152]} : std::array{texts_[153], texts_[154], texts_[155]}; @@ -1028,6 +1153,8 @@ Image StadiumScreen::render_scene() const { return out; } +// Renders the investment dialog for the selected investment: title, balance, duration, and up to three +// option icons with tier label and price, plus Build/Cancel buttons. Image StadiumScreen::render_investment_dialog(Image out) const { if (!state_.selected_investment) return out; const unsigned choice = unsigned(*state_.selected_investment); @@ -1057,6 +1184,7 @@ Image StadiumScreen::render_investment_dialog(Image out) const { text_at(out, 148 - font_.text_width(variant), 70, variant, 0x6c); } + // Option cells: 60 px apart starting at x=5, sprite at y=74 (53x29 px), tier label at y=110, price at y=117. for (size_t i = 0; i < row.options.size() && i < 3; ++i) { const auto& option = row.options[i]; const int x = 5 + int(i) * 60; @@ -1086,6 +1214,8 @@ Image StadiumScreen::render_investment_dialog(Image out) const { return out; } +// Hit test for the data page controls. Returns 0..5 for the curve buttons, 6..7 for the scale buttons, +// 8..23 for ticket prices 10..25, or -1. int StadiumScreen::data_control_at(int x, int y) const { for (int curve = 0; curve < 6; ++curve) { const int bx = 27 + (curve % 2) * 120, by = 107 + (curve / 2) * 11; @@ -1102,6 +1232,8 @@ int StadiumScreen::data_control_at(int x, int y) const { return -1; } +// Renders the data page: header, graph frame and curves (with their toggle buttons and color keys), scale +// buttons, the statistics table, required attendance and the ticket price buttons (10..25). Image StadiumScreen::render_data() const { const auto& data = *state_.data; Image out = header_background_; @@ -1109,6 +1241,7 @@ Image StadiumScreen::render_data() const { fill(out, 0, 4, 320, 13, 0x44); fill(out, 1, 5, 318, 11, 0x39); } const auto title = original_to_utf8(state_.original_stadium_title.empty() ? state_.club_name : state_.original_stadium_title); sprite_font_.draw(out, 172 + 55 - sprite_font_.text_width(title) / 2, 13, title); + // Draws a clipped line from (x,y) to (end_x,end_y) with a Bresenham-style step loop. const auto line = [&](int x, int y, int end_x, int end_y, uint8_t color) { const int dx = std::abs(end_x - x), sx = x < end_x ? 1 : -1; const int dy = std::abs(end_y - y), sy = y < end_y ? 1 : -1; @@ -1119,9 +1252,12 @@ Image StadiumScreen::render_data() const { else if (dy) { y += sy; error += dx; if (error >= dy) { error -= dy; x += sx; } } } }; + // graph frame edges: coordinates and colors come from executable tables for (int edge = 0; edge < 4; ++edge) line(exe_.u16(::bmh::layout::Analytics_Render_RuntimeField3 + edge * 4 + 2), exe_.u8(::bmh::layout::Analytics_Render_RuntimeField2 + edge * 2 + 1) - 35, exe_.u16(::bmh::layout::Analytics_Render_RuntimeField3 + edge * 4), exe_.u8(::bmh::layout::Analytics_Render_RuntimeField2 + edge * 2) - 35, exe_.u8(::bmh::layout::Analytics_Render_RuntimeField + edge)); + // Per curve: color key, toggle button (selected when its flag bit is set or it is pressed) and, when shown, + // the polyline with a 3x3 marker per sample. for (int curve = 0; curve < 6; ++curve) { const int x = 27 + (curve % 2) * 120, y = 107 + (curve / 2) * 11; const uint8_t color = exe_.u8(::bmh::layout::Analytics_FormatError_RuntimeField + curve); @@ -1146,9 +1282,11 @@ Image StadiumScreen::render_data() const { else copy_crop(out, panel_, 0, 126, 1, 146, 318, 93); source_border(out, 0, 145, 319, 239); fill(out, 1, 227, 318, 12, 0x42); + // Draws text centred between the x positions left and right. const auto centered = [&](int left, int right, int baseline, std::string_view text, uint8_t color) { text_at(out, left + (right - left) / 2 - font_.text_width(text) / 2, baseline, text, color); }; + // Table header and rows: three columns 85 px apart. Rows 1 and 3 are 9 px high, others 7 px. for (int kind = 0; kind < 3; ++kind) centered(60 + kind * 85, 145 + kind * 85, 154, texts_[text_id(::bmh::layout::Stadium_CopyCrop_TextPointer + kind * 4)], 0x6a); int y = 164; @@ -1156,11 +1294,13 @@ Image StadiumScreen::render_data() const { text_at(out, 3, y, texts_[text_id(::bmh::layout::Stadium_CopyCrop_TextPointer2 + row * 4)], 0x6b); for (int kind = 0; kind < 3; ++kind) { const auto& text = data.table[size_t(row)][size_t(kind)]; + // texts starting with '(' are drawn one pixel lower const int shift = row < 4 && !text.empty() && text[0] == '(' ? 1 : 0; centered(60 + kind * 85, 145 + kind * 85, y + shift, text, 0x6c); } y += row == 1 || row == 3 ? 9 : 7; } + // Required attendance line and ticket price buttons at the bottom of the page. // TextId restores this seven-pixel region from TextId2's saved // background; it adds no field frame or shadow. const auto needed = texts_[text_id(::bmh::layout::Stadium_CopyCrop_TextPointer4)] + std::to_string(data.ticket_price) + texts_[text_id(::bmh::layout::Stadium_CopyCrop_TextPointer5)]; @@ -1173,6 +1313,8 @@ Image StadiumScreen::render_data() const { return out; } +// Renders the current frame. Priority: data page, then construction tip dialog, then the scene with the +// active editor/dialog, the calculator, or the periphery question on top. Image StadiumScreen::render() const { if (state_.data) return render_data(); if (state_.construction_tip_dialog && tip_dialog_) { @@ -1193,11 +1335,14 @@ Image StadiumScreen::render() const { return out; } +// Image shown behind a construction notice: the scene with the active block editor or investment dialog. Image StadiumScreen::construction_notice_backdrop() const { return state_.block_expansion ? render_block_expansion(render_scene()) : render_investment_dialog(render_scene()); } +// Text input for the block calculator (digits only). Appends digits to the value (clamped to the block's +// maximum, at most 10 digits). Returns true if the value changed. bool StadiumScreen::text(std::string_view input) { if (pending_ || calculator_source_waiting() || !block_calculator_open_ || !state_.block_expansion || input.empty()) return false; @@ -1221,6 +1366,7 @@ bool StadiumScreen::text(std::string_view input) { return true; } +// Moves the calculator window to (x,y), clamped so it stays on the 320x240 screen. Returns true if it moved. bool StadiumScreen::calculator_drag_to(int x, int y) { if (!block_calculator_open_ || block_calculator_cancel_wait_) return false; x = std::clamp(x, 0, 207); @@ -1230,11 +1376,15 @@ bool StadiumScreen::calculator_drag_to(int x, int y) { return true; } +// Called after the frame was shown: starts the key-press delay once a key (or the cancel wait) is visible. void StadiumScreen::calculator_mark_presented() { if (block_calculator_pressed_key_ >= 0 || block_calculator_cancel_wait_) block_calculator_presented_ = true; } +// Advances the calculator's wait timer by `ticks` (only counts after the frame was presented). When it reaches +// zero the key is released, the cancel wait closes the calculator, or a pending keyboard accept is applied. +// Returns true if the visible state changed. bool StadiumScreen::calculator_advance_source_ticks(unsigned ticks) { if (!calculator_source_waiting() || !block_calculator_presented_ || ticks == 0) return false; const unsigned before = block_calculator_ticks_; @@ -1257,15 +1407,19 @@ bool StadiumScreen::calculator_advance_source_ticks(unsigned ticks) { return block_calculator_ticks_ != before || before == 0; } +// True while the calculator is in a timed wait (key held down or cancel pending); input is ignored then. bool StadiumScreen::calculator_source_waiting() const { return block_calculator_ticks_ != 0 && (block_calculator_pressed_key_ >= 0 || block_calculator_cancel_wait_); } +// True while a calculator key is held by the mouse (not by the keyboard accept). bool StadiumScreen::calculator_waiting_for_key_release() const { return pressed_ == Pressed::block_calculator_key && !block_calculator_keyboard_j_; } +// Accepts the calculator value (J key or Enter). A value below the current capacity is first clamped up and the +// calculator stays open; otherwise a set_total request is issued and stored as pending. Returns {} when nothing is sent. StadiumRequest StadiumScreen::accept_block_calculator_value() { if (!state_.block_expansion || pending_ || calculator_source_waiting()) return {}; const uint32_t minimum = uint32_t(state_.block_expansion->quote.current_capacity_thousands) * 1000; @@ -1285,6 +1439,7 @@ StadiumRequest StadiumScreen::accept_block_calculator_value() { return result; } +// Executes the calculator key with index 0..14 (digits, D, R, C, J, N). Only J can return a request. StadiumRequest StadiumScreen::activate_block_calculator_key(int key_index) { if (!state_.block_expansion || !block_calculator_open_ || pending_) return {}; if (key_index >= 0 && key_index <= 9) { @@ -1314,6 +1469,7 @@ StadiumRequest StadiumScreen::activate_block_calculator_key(int key_index) { block_calculator_edited_ = true; return {}; case 13: return accept_block_calculator_value(); // J: accept + // N: sets the value to the 'cancelled' sentinel and starts a 50-tick wait before the calculator closes case 14: // N: cancel local calculator edit block_calculator_value_ = UINT32_MAX; block_calculator_text_ = std::to_string(block_calculator_value_); @@ -1327,6 +1483,10 @@ StadiumRequest StadiumScreen::activate_block_calculator_key(int key_index) { } } +// Handles a mouse button press at (x,y) and decides which control becomes `pressed_` (the request is only sent +// on release). Right button closes the current level (data page, editor or scene). Returns true if the press +// was used. Layers are checked from top to bottom: data page, tip dialog, calculator, block editor, +// periphery question, investment dialog, scene. bool StadiumScreen::pointer_down(int x, int y, bool right) { if (pending_ || calculator_source_waiting()) return false; pressed_ = Pressed::none; pressed_index_ = -1; pressed_x_ = x; pressed_y_ = y; @@ -1349,6 +1509,7 @@ bool StadiumScreen::pointer_down(int x, int y, bool right) { for (int i = 0; i < 15; ++i) { const int key_x = x0 + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField + size_t(i) * 2); const int key_y = y0 + exe_.u8(::bmh::layout::Advertising_Click_RuntimeField2 + size_t(i)); + // key hit box: 17x15 pixels if (x >= key_x && x <= key_x + 16 && y >= key_y && y <= key_y + 14) { if (i == 14) { // Source N jumps straight to4ad4e: restore the backdrop, @@ -1370,11 +1531,13 @@ bool StadiumScreen::pointer_down(int x, int y, bool right) { if (value > quote.max_places) continue; const int key_x = x0 + exe_.u16(::bmh::layout::Advertising_Click_RuntimeField + (i + 15) * 2); const int key_y = y0 + exe_.u8(::bmh::layout::Advertising_Click_RuntimeField2 + i + 15); + // preset button hit box: 54x15 pixels if (x >= key_x && x <= key_x + 53 && y >= key_y && y <= key_y + 14) { pressed_ = Pressed::block_calculator_preset; pressed_index_ = int(i); return true; } } + // top strip of the calculator window: starts dragging it if (x >= x0 && x <= x0 + 113 && y >= y0 && y <= y0 + 16) { pressed_ = Pressed::block_calculator_drag; return true; @@ -1389,6 +1552,8 @@ bool StadiumScreen::pointer_down(int x, int y, bool right) { pending_ = block_request(StadiumRequestKind::expansion_cancel); return true; } + // Editor hit boxes: Build button, Cancel button, amount field (opens the calculator), and the seats and roof + // rows (only if that feature is not already built). if (x >= 7 && x <= 76 && y >= 136 && y <= 145) pressed_ = Pressed::block_build; else if (x >= 107 && x <= 176 && y >= 136 && y <= 145) pressed_ = Pressed::block_cancel; else if (x >= 5 && x <= 99 && y >= 74 && y <= 99) pressed_ = Pressed::block_amount; @@ -1408,6 +1573,7 @@ bool StadiumScreen::pointer_down(int x, int y, bool right) { } if (state_.selected_investment) { if (right) return false; + // Investment dialog hit boxes: Build button, Cancel button, and the option cells (60 px wide, from x=5). if (x >= 7 && x <= 76 && y >= 136 && y <= 145) pressed_ = Pressed::build; else if (x >= 107 && x <= 176 && y >= 136 && y <= 145) pressed_ = Pressed::cancel; else if (y >= 74 && y <= 103 && x >= 5 && x < 5 + int(state_.investments[size_t(*state_.selected_investment)].options.size()) * 60) { @@ -1422,6 +1588,7 @@ bool StadiumScreen::pointer_down(int x, int y, bool right) { pending_ = request(StadiumRequestKind::close); return true; } + // Scene buttons row (y 215..224): view switch, future information and data page. if (y >= 215 && y <= 224) { if (x >= 2 && x < 117) { if (!state_.investments_enabled) return false; @@ -1430,6 +1597,7 @@ bool StadiumScreen::pointer_down(int x, int y, bool right) { if (x >= 125 && x < 215) { pressed_ = Pressed::scene_button; pressed_index_ = 1; return true; } if (x >= 224 && x < 314) { pressed_ = Pressed::scene_button; pressed_index_ = 2; return true; } } + // Investment icon grid in the interior view: 4 columns x 2 rows of 54x30 cells starting at (3,153). if (!panorama_ && y >= 153 && y <= 211 && x >= 3 && x <= 217) { const int col = (x - 3) / 54, row = (y - 153) / 30; const int choice = row * 4 + col; @@ -1445,6 +1613,7 @@ bool StadiumScreen::pointer_down(int x, int y, bool right) { } return false; } + // Seat block rows: 24 px tall starting at y=22; blocks under construction cannot be selected. if (!panorama_ && x >= 219 && x <= 319 && y >= 22 && y <= 213) { const int slot = (y - 22) / 24; if (slot >= 0 && slot < 8 && state_.blocks[size_t(slot)].construction_weeks == 0) { @@ -1456,6 +1625,9 @@ bool StadiumScreen::pointer_down(int x, int y, bool right) { return false; } +// Handles pointer movement. Without a pressed control it updates the hover highlight (investment icon, seat +// block row or panorama object). With a pressed control it cancels the press when the pointer leaves it, +// and drags the calculator window. Returns true if something visible changed. bool StadiumScreen::pointer_move(int x, int y) { if (calculator_source_waiting()) return false; if (pressed_ == Pressed::none) { @@ -1486,6 +1658,7 @@ bool StadiumScreen::pointer_move(int x, int y) { pressed_x_ = x; pressed_y_ = y; return true; } + // Is the pointer still inside the pressed control? These rectangles must match the ones in pointer_down. bool inside = false; switch (pressed_) { case Pressed::scene_button: @@ -1499,12 +1672,14 @@ bool StadiumScreen::pointer_move(int x, int y) { inside = x >= 5 + pressed_index_ * 60 && x < 5 + (pressed_index_ + 1) * 60 && y >= 74 && y <= 103; break; case Pressed::build: inside = x >= 7 && x <= 76 && y >= 136 && y <= 145; break; case Pressed::cancel: inside = x >= 107 && x <= 176 && y >= 136 && y <= 145; break; + // Yes/No buttons of the tip dialog case Pressed::tip_yes: inside = x >= 62 && x <= 137 && y >= 166 && y <= 176; break; case Pressed::tip_no: inside = x >= 175 && x <= 250 && y >= 166 && y <= 176; break; case Pressed::periphery_item: inside = panorama_ && future_information_ && periphery_object_at(x, y) == pressed_index_; break; case Pressed::periphery_yes: inside = periphery_dialog_ && periphery_dialog_->hit_test(x, y) == GameEndTaxDialog::Button::yes; break; case Pressed::periphery_no: inside = periphery_dialog_ && periphery_dialog_->hit_test(x, y) == GameEndTaxDialog::Button::no; break; + // bottom-left corner area case Pressed::close: inside = x < 50 && y > 218; break; case Pressed::block_row: inside = !panorama_ && x >= 219 && x <= 319 && y >= 22 && y <= 213 && (y - 22) / 24 == pressed_index_; break; @@ -1541,6 +1716,8 @@ bool StadiumScreen::pointer_move(int x, int y) { return false; } +// Handles a mouse button release. If the pointer is released inside the control that was pressed, the matching +// request is created, stored as pending and returned. Local actions (view switches, calculator input) return {}. StadiumRequest StadiumScreen::release(int x, int y, bool right) { if (pending_) return {}; if (calculator_source_waiting()) return {}; @@ -1578,12 +1755,14 @@ StadiumRequest StadiumScreen::release(int x, int y, bool right) { y >= block_calculator_y_ + exe_.u8(::bmh::layout::Advertising_Click_RuntimeField2 + size_t(index + 15)) && y <= block_calculator_y_ + exe_.u8(::bmh::layout::Advertising_Click_RuntimeField2 + size_t(index + 15)) + 14) || (pressed == Pressed::block_calculator_drag); if (!released_inside || down_x < 0 || down_y < 0) return {}; + // Stores the request as pending (blocks further input until acknowledge or reject_action) and returns it. const auto emit = [this](StadiumRequest result) { pending_ = result; return result; }; if (pressed == Pressed::data_control) { if (index < 6) return emit(request(StadiumRequestKind::toggle_data_curve, index)); if (index < 8) return emit(request(StadiumRequestKind::toggle_data_scale, index - 6)); return emit(request(StadiumRequestKind::set_data_ticket_price, index - 8 + 10)); } + // Scene buttons: 0 toggles panorama/interior, 1 toggles future information (both purely local), 2 requests the data page. if (pressed == Pressed::scene_button) { if (index == 0) { panorama_ = !panorama_; future_information_ = false; periphery_hover_ = -1; hover_investment_ = hover_block_ = -1; return {}; } if (index == 1) { future_information_ = !future_information_; periphery_hover_ = -1; hover_investment_ = hover_block_ = -1; return {}; } @@ -1608,6 +1787,8 @@ StadiumRequest StadiumScreen::release(int x, int y, bool right) { } if (pressed == Pressed::cancel && state_.selected_investment) return emit(request(StadiumRequestKind::cancel_investment, int(*state_.selected_investment))); + // Answer to the construction tip dialog. For blocks the editor request is used; for investments the price + // is the tip price on Yes and the option's base price on No. if (pressed == Pressed::tip_yes || pressed == Pressed::tip_no) { if (state_.block_expansion) { auto result = block_request(StadiumRequestKind::expansion_answer_tip); @@ -1634,6 +1815,7 @@ StadiumRequest StadiumScreen::release(int x, int y, bool right) { result.block_slot = index; return emit(std::move(result)); } + // Opens the calculator initialised with the quote's new places and resets all calculator state. if (pressed == Pressed::block_amount && state_.block_expansion) { block_calculator_open_ = true; block_calculator_value_ = state_.block_expansion->quote.new_places; @@ -1647,6 +1829,7 @@ StadiumRequest StadiumScreen::release(int x, int y, bool right) { block_calculator_edited_ = false; return {}; } + // Toggles the seats (bit 1) or roof (bit 2) feature of the editor. if (pressed == Pressed::block_seats || pressed == Pressed::block_roof) { if (!state_.block_expansion) return {}; const uint8_t bit = pressed == Pressed::block_seats ? 1 : 2; @@ -1660,6 +1843,7 @@ StadiumRequest StadiumScreen::release(int x, int y, bool right) { return emit(block_request(StadiumRequestKind::expansion_cancel)); if (pressed == Pressed::block_calculator_key) return activate_block_calculator_key(index); + // A preset button copies its value into the calculator (indices 0..5: current + n thousand, 6: current, 7: maximum). if (pressed == Pressed::block_calculator_preset && state_.block_expansion) { const auto& quote = state_.block_expansion->quote; const uint32_t current = uint32_t(quote.current_capacity_thousands) * 1000; @@ -1673,11 +1857,14 @@ StadiumRequest StadiumScreen::release(int x, int y, bool right) { return {}; } +// Convenience: a press immediately followed by a release at the same position. StadiumRequest StadiumScreen::click(int x, int y, bool right) { if (!pointer_down(x, y, right)) return {}; return release(x, y, right); } +// Handles a key press. Data page: ESC closes it. Calculator: Enter accepts, Backspace deletes, Space clears, +// digits are typed (each starts a short key-press wait). Scene: ESC closes the stadium (not during dialogs). StadiumRequest StadiumScreen::key(std::string_view key) { if (pending_ || calculator_source_waiting() || pressed_ != Pressed::none) return {}; if (state_.data) { @@ -1714,6 +1901,8 @@ StadiumRequest StadiumScreen::key(std::string_view key) { return {}; } +// Called when the shared process timer runs out. Answers pending questions with No, closes the calculator +// or editor, or closes the stadium. StadiumRequest StadiumScreen::process_timer_expired() { if (pending_ || calculator_source_waiting() || pressed_ != Pressed::none) return {}; //PresentManagerDialog forces button1 (No) after the shared process clock expires. @@ -1742,6 +1931,8 @@ StadiumRequest StadiumScreen::process_timer_expired() { return key("ESC"); // existing scene/data close owners } +// Answers an open question with No when the timer expires: periphery quote -> decline, block tip -> refuse tip, +// investment tip -> answer without the tip (base price). Returns {} if no such question is open. StadiumRequest StadiumScreen::expire_construction_tip() { if (pending_) return {}; // The existing deadline entry also owns the flags1 periphery question: @@ -1776,6 +1967,10 @@ StadiumRequest StadiumScreen::expire_construction_tip() { return r; } +// Applies the engine's answer to the pending request. The answer must carry the same identity (manager, club, +// scope) and exactly the next sequence and revision; otherwise the stale or forged answer is rejected with +// FormatError. Then the new state is validated per request kind (what the engine must have changed and what +// it must not have touched). Only after all checks are the dialogs rebuilt and the new state adopted. void StadiumScreen::acknowledge(StadiumState updated) { if (!pending_) throw FormatError("stadium: acknowledgement without a pending request"); const auto& req = *pending_; @@ -1798,6 +1993,7 @@ void StadiumScreen::acknowledge(StadiumState updated) { req.scope != state_.scope || req.sequence != state_.sequence) { throw FormatError("stadium: acknowledgement scope or sequence mismatch"); } + // Field contract: block requests carry only block fields, other requests none of them; only tip answers may accept a tip. const bool block_action = block_request_kind(req.kind); if ((!block_action && (req.block_slot != -1 || req.block_total_places != 0 || req.block_features != 0 || req.expected_block_quote)) || @@ -1811,6 +2007,7 @@ void StadiumScreen::acknowledge(StadiumState updated) { !same_block_compensation_context(state_, updated)) throw FormatError("stadium: immutable Source compensation context changed"); + // Block requests must refer to the editor quote that is currently shown (expected quote, slot, owner). const StadiumBlockExpansionEditor* old_editor = state_.block_expansion ? &*state_.block_expansion : nullptr; if (req.kind == StadiumRequestKind::expansion_select) { @@ -1829,6 +2026,7 @@ void StadiumScreen::acknowledge(StadiumState updated) { req.block_features != old_editor->desired_features))) throw FormatError("stadium: block request does not match the accepted editor quote"); } + // Only data page requests may change the data page; they must also leave no other modal open. const bool data_action = req.kind == StadiumRequestKind::open_data || req.kind == StadiumRequestKind::close_data || req.kind == StadiumRequestKind::toggle_data_curve || req.kind == StadiumRequestKind::toggle_data_scale || req.kind == StadiumRequestKind::set_data_ticket_price; @@ -1836,6 +2034,7 @@ void StadiumScreen::acknowledge(StadiumState updated) { (data_action && (!updated.opened || updated.selected_investment || updated.quoted_object || updated.block_expansion || updated.construction_tip_dialog))) throw FormatError("stadium: acknowledgement changed independent data modal context"); + // Per-kind validation of the new state against the old state and the request. bool valid = true; switch (req.kind) { case StadiumRequestKind::open: valid = updated.opened && !updated.data; break; @@ -1867,6 +2066,7 @@ void StadiumScreen::acknowledge(StadiumState updated) { valid = valid && expected == *updated.data; break; } + // request kinds that are never accepted as an engine answer case StadiumRequestKind::select_block: case StadiumRequestKind::prepare_block_offer: case StadiumRequestKind::decline_block_offer: @@ -1952,6 +2152,8 @@ void StadiumScreen::acknowledge(StadiumState updated) { !updated.selected_investment && !updated.quoted_object && same_block_overviews(state_.blocks, updated.blocks) && updated.balance == state_.balance; break; + // Confirm: a zero price builds directly; otherwise the engine must open an offer question (6..14 percent + // surcharge on the base price) with unchanged quote. case StadiumRequestKind::expansion_confirm: { if (!old_editor) { valid = false; break; } if (old_editor->quote.base_price == 0) { @@ -1980,6 +2182,9 @@ void StadiumScreen::acknowledge(StadiumState updated) { same_block_overviews(state_.blocks, updated.blocks) && updated.balance == state_.balance; break; } + // Answer to the offer question: the block row must either be unchanged or show the construction the answer + // implies (weeks in the allowed range for the chosen offer, capacity, pending flags), with balance, season + // tickets and ticket compensation updated accordingly. case StadiumRequestKind::expansion_answer_tip: { if (!old_editor || !old_editor->offer || !state_.construction_tip_dialog) { valid = false; break; } valid = old_editor->offer->decision == StandBlockOfferDecision::Pending && @@ -2009,6 +2214,7 @@ void StadiumScreen::acknowledge(StadiumState updated) { const bool offer_arithmetic_ok = !req.accept_tip || uint64_t(old_editor->quote.base_price) * uint32_t(100 + offer.percent) <= uint64_t(std::numeric_limits::max()); + // with the tip accepted, construction time lies between base_weeks minus half and base_weeks minus an eighth const uint8_t shortest = uint8_t(old_editor->quote.base_weeks - (old_editor->quote.base_weeks >> 1)); const uint8_t longest = uint8_t(old_editor->quote.base_weeks - @@ -2064,11 +2270,13 @@ void StadiumScreen::acknowledge(StadiumState updated) { if (acknowledged_close) close_requested_ = true; } +// Called when the engine refuses the pending request: drops it and shows the reason as feedback text. void StadiumScreen::reject_action(std::string reason) { if (!pending_ || reason.empty()) throw FormatError("stadium: rejection requires pending request and reason"); pending_.reset(); pressed_ = Pressed::none; pressed_index_ = -1; feedback_ = std::move(reason); } +// State dump: the StadiumState JSON extended with the screen's pending request, view flags and calculator state. std::string StadiumScreen::state_json() const { auto result = stadium_state_json(state_); result.pop_back(); return result + ",\"pending_action\":" + (pending_ ? stadium_request_json(*pending_) : "null") + @@ -2093,6 +2301,7 @@ std::string StadiumScreen::state_json() const { ",\"feedback\":" + (feedback_.empty() ? "null" : json_quote(feedback_)) + '}'; } +// True while a mouse button is held on a Yes/No button of one of the questions. bool StadiumScreen::construction_tip_held() const { // Both PresentManagerDialog questions retain their physical button until release. return pressed_ == Pressed::tip_yes || pressed_ == Pressed::tip_no || diff --git a/src/ui/transfer_market.cpp b/src/ui/transfer_market.cpp index 3ce3f92..e2eb506 100644 --- a/src/ui/transfer_market.cpp +++ b/src/ui/transfer_market.cpp @@ -15,16 +15,22 @@ namespace bmh::ui { namespace { +// Layout constants of the market projection: index of the first market pool word in the +// squad-slot array, number of list entries, base address and stride of one entry in the +// in-memory transfer list, and the byte size of one manager record. constexpr size_t kPoolFirst = 0xb70; constexpr int kMarketEntries = 40; constexpr uint32_t kTransferTable = ::bmh::layout::EditorList; constexpr uint32_t kTransferEntrySize = 0x58; constexpr size_t kManagerRecordSize = 0xb0c; +// Fills a rectangle with one palette index, clipped to the image. void rect(Image& out,int x,int y,int w,int h,uint8_t color) { for(int yy=std::max(0,y);yysource.width||sy+h>source.height) throw FormatError("transfer market: Original asset rectangle outside source"); @@ -33,9 +39,11 @@ void copy(Image& out,const Image& source,int sx,int sy,int x,int y,int w,int h,i if(pixel!=key&&x+xx>=0&&x+xx=0&&y+yy& v, size_t at) { return int32_t(uint32_t(v.at(at)) | uint32_t(v.at(at + 1)) << 8 | uint32_t(v.at(at + 2)) << 16 | uint32_t(v.at(at + 3)) << 24); } +// Label of an offer-form field: 0 = fee, 1 = monthly salary, 2 = contract years, 3.. = numbered bonuses. std::string field_name(int index) { if (index == 0) return "Ablöse"; if (index == 1) return "Monatsgehalt"; if (index == 2) return "Laufzeit (Jahre)"; return "Prämie " + std::to_string(index - 2); } +// Parses typed digits to a number; returns 0 for empty or malformed input. uint32_t parse_input(std::string_view input) { uint32_t value = 0; if (input.empty()) return 0; @@ -72,6 +84,9 @@ uint32_t parse_input(std::string_view input) { } } // namespace +// Builds the screen's data projection from the game state: balance, the 40-entry market list +// (listing seller, asking fee, bids), the manager's own squad rows, borrowed players and team +// averages. Called whenever a fresh projection is needed (screen open, after each acknowledged request). TransferMarketState transfer_market_from_game(const GameState& g, uint64_t revision) { const int manager = g.memory.u8(::bmh::layout::ActiveManager); if (manager < 0 || size_t(manager) >= g.manager_teams.size()) @@ -92,8 +107,10 @@ TransferMarketState transfer_market_from_game(const GameState& g, uint64_t revis state.club_name = g.club_name(state.runtime_club); state.source = "engine_projection"; + // Marks which players already appear in the market list (used for the squad's already_listed flag). std::vector listed_players(g.players.size(), false); for (int i = 0; i < kMarketEntries; ++i) { + // Market pool word: low 12 bits are the player id; 0x0fff means the entry is empty. const int player_id = g.squad_slots.at(kPoolFirst + size_t(i)) & 0x0fff; if (player_id == 0x0fff) continue; if (size_t(player_id) >= g.players.size()) throw FormatError("transfer market: pool player is outside attributes"); @@ -107,6 +124,7 @@ TransferMarketState transfer_market_from_game(const GameState& g, uint64_t revis item.age = player.age(); item.position = player.position(); item.strength = player.strength(); item.attributes=player;item.source_word=g.squad_slots.at(kPoolFirst+size_t(i)); item.nationality=uint8_t(player.nationality()+(size_t(player_id)>2):0)); + // Seller word: 0xffff means no club (listing without a seller); otherwise the low 15 bits are the club. const uint16_t seller_raw = g.memory.u16(entry + 8); if (seller_raw == 0xffff) { item.seller = -1; @@ -116,11 +134,14 @@ TransferMarketState transfer_market_from_game(const GameState& g, uint64_t revis item.seller_name = g.club_name(item.seller); item.own_listing = item.seller == state.runtime_club; } + // Asking fee as stored in the list entry, scaled as the original does (value/10000 times 0x30d4); must fit in int32. const uint64_t fee = uint64_t(g.memory.u32(entry + 0x2c) / 10000) * 0x30d4; if (fee > uint64_t(std::numeric_limits::max())) throw FormatError("transfer market: asking fee out of range"); item.asking_fee = int32_t(fee); item.salary_reference = g.memory.u32(entry + 0x30); item.salary_demand_percent = g.memory.u8(entry + 0x55); + // Each entry holds up to four bids; 0xffff marks a free bid slot. A bid by the active manager's own club + // is kept in full so the offer form can be pre-filled. for (int bid = 0; bid < 4; ++bid) { const uint16_t buyer = g.memory.u16(entry + uint32_t(bid) * 2); if (buyer == 0xffff) continue; @@ -132,6 +153,7 @@ TransferMarketState transfer_market_from_game(const GameState& g, uint64_t revis own.source_slot=item.source_slot; own.fee=int32_t(g.memory.u32(entry+0x1c+uint32_t(bid)*4)); own.annual_salary=int32_t(g.memory.u32(entry+0x0c+uint32_t(bid)*4)); + // Stored term is in months (low 7 bits); converted to whole years, rounded up. own.contract_years=uint8_t((int(g.memory.u8(entry+0x34+uint32_t(bid))&0x7f)-1)/12+1); for(size_t bonus=0;bonus{int32_t(g.memory.u32(::bmh::layout::CurrencyMultiplier)),int32_t(g.memory.u32(::bmh::layout::CurrencyDivisor))}; + // Roster block shown on the left side of the screen (same data as the club info screen). state.roster.runtime_team=state.runtime_club;state.roster.original_club_name=state.club_name; state.roster.has_squad=true;state.roster.gradient_text=state.gradient_text; state.roster.decorated_background=state.decorated_background; @@ -167,11 +192,14 @@ TransferMarketState transfer_market_from_game(const GameState& g, uint64_t revis auto& averages=all?state.team_strengths:state.active_strengths; for(size_t n=0;n<5;++n)averages[n]=count[n]?uint16_t(sum[n]/count[n]):uint16_t(0); } + // Collect loan slots (up to 12) whose borrowing manager is the active one; these players are + // shown at the bottom of the roster in addition to the ordinary squad rows. std::vector borrowed; if(g.memory.has(::bmh::layout::Career_CareerManagersEnd_RuntimeField+23)&&g.memory.has(::bmh::layout::ClubInfo_FormatError_RuntimeField2+11)) for(int loan=0;loan<12;++loan)if(g.memory.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField+uint32_t(loan)*2)!=0x0fff&&g.memory.u8(::bmh::layout::ClubInfo_FormatError_RuntimeField2+uint32_t(loan))==manager)borrowed.push_back(loan); if(borrowed.size()>range.count)throw FormatError("transfer market: borrowed roster exceeds Source squad range"); const size_t ordinary_count=range.count-borrowed.size(); + // Ordinary squad rows first; rendered_row counts only non-empty rows and drives the alternating row colours. int rendered_row=0; for(size_t row=0;row= 0) p.statistics = player_club_statistics(g, state.runtime_club, p.player_id, *p.manager_board); state.roster.players.push_back(std::move(p)); } + // Borrowed players are appended after the ordinary rows and also get a snapshot preview for quotes. for(size_t index=0;index 40) throw FormatError("transfer market: too many list rows"); + // Keep the saved filter bits (low 11) and force bit 0x800 on. view_flags_=uint16_t((state_.source_view_flags & 0x7ff) | 0x800); + // The atlas image is 314 pixels wide; widen it to 320 so later copies can use fixed coordinates. if(atlas_.width==314){Image padded(320,atlas_.height);padded.blit(atlas_,0,0);atlas_=std::move(padded);} } +// Draws UTF-8 text with the bitmap font; text that would not fit completely is not drawn. void TransferMarketScreen::draw_text(Image& out, int x, int y, std::string_view value, uint8_t color) const { // User-facing strings and notices are UTF-8. The original bitmap font uses // the game's single-byte encoding, so convert only at this render boundary. @@ -333,11 +371,14 @@ void TransferMarketScreen::draw_text(Image& out, int x, int y, std::string_view font_.draw(out, x, y, encoded, color); } +// Stores the digits typed so far into the active offer field and clears the input buffer. void TransferMarketScreen::commit_numeric_field() { if (!numeric_input_.empty()) offer_values_.at(size_t(active_field_)) = parse_input(numeric_input_); numeric_input_.clear(); } +// Returns the indices of the visible market items: filtered by the position bits (bit 5 + position) +// of view_flags_ and sorted by position, then by descending strength. std::vector TransferMarketScreen::market_order() const { std::vector rows;std::vector keys; for(size_t n=0;n TransferMarketScreen::market_order() const { }; sort(sort,0,rows.size());return rows; } +// Returns (roster index, baseline y) for every roster row to draw. Rows start at y=36 with 7 pixels per +// row, 2 extra pixels where the status bits (0xc000) change; borrowed players are drawn from y=209 upwards. std::vector> TransferMarketScreen::roster_rows() const { std::vector> rows;int baseline=36,loan=0; for(size_t n=0;n> TransferMarketScreen::roster_rows() const { } return rows; } +// Draws text with the original font. If `right` is set the text is centred between x and right. +// The colour index may be replaced by a vertical gradient from the executable when gradient text is on. void TransferMarketScreen::original_text(Image& out,int x,int baseline,std::string_view value,uint8_t color,int right) const { const int width=font_.text_width(value);if(right>=0)x+=(right-x)/2-width/2; if(x<0||x+width>out.width||baseline<5||baseline>=out.height)return; @@ -382,6 +427,9 @@ void TransferMarketScreen::original_text(Image& out,int x,int baseline,std::stri for(int y=0;y<6;++y)for(int xx=0;xx31) use a 31 pixel left part, repeated +// middle strips and a right end from the widget image; narrow ones are built from corner and edge tiles. +// Active buttons look pressed (the frame is drawn on the other side). void TransferMarketScreen::button(Image& out,int x,int y,int width,std::string_view label,bool active) const { const int height=width>31?10:9; if(active){const uint8_t c=out.at(x,y+height);rect(out,x,y,width+1,2,c);rect(out,x,y,2,height+1,c);x+=2;y+=2;} @@ -402,6 +450,8 @@ void TransferMarketScreen::button(Image& out,int x,int y,int width,std::string_v if(mode==3)original_text(out,x,y+height/2+2,label,0,x+width); else sprite_font_.draw(out,x+width/2-sprite_font_.text_width(original_to_utf8(label))/2,y+height/2+2,original_to_utf8(label),mode); } +// Draws the left roster pane. `full` (Komplett) adds the extended columns; data_b_ switches between +// two data pages (the one with skill bars and statistics, and the one with attributes). void TransferMarketScreen::draw_roster(Image& out,bool full) const { const auto header=texts_[text_id(data_b_?::bmh::layout::ClubInfo_Render_TextPointer4: ::bmh::layout::ClubInfo_Render_TextPointer3)]; // LineupScreen renders the complete header, then19c1c restores the right @@ -411,10 +461,12 @@ void TransferMarketScreen::draw_roster(Image& out,bool full) const { const auto& p=state_.roster.players[size_t(row)];const auto& a=p.attributes; if(p.displayed_slot&0xc000) { const int jersey=(p.cards&31)+1; + // Jersey number: colour depends on the slot status bits (0x1000, borrowed, 0x8000). const uint8_t color=p.displayed_slot&0x1000?0xf3:p.borrowed?0x75:p.displayed_slot&0x8000?0x6c:0x68; original_text(out,4,baseline,std::to_string(jersey%10),color); if(jersey>=10)original_text(out,0,baseline,exe_.cstring(::bmh::layout::ClubInfo_Render_TextPointer),color); } + // Name colour: borrowed, pending offer, or alternating rows; 0x27 highlights the selected or marked player. uint8_t color=p.borrowed?0x65:p.offer_name_color?0x75:uint8_t(p.rendered_row%2?0x67:0x6b); if((selected_snapshot_&&state_.snapshot_previews.at(size_t(*selected_snapshot_)).snapshot_index==p.human_loan_index)|| (selected_squad_&&state_.squad.at(size_t(*selected_squad_)).row==p.physical_row)|| @@ -458,6 +510,8 @@ void TransferMarketScreen::draw_roster(Image& out,bool full) const { } } } +// Draws the roster plus, unless Komplett is on, the market list (six rows per page), the balance and +// quote preview, the strength bars and the filter buttons, then the bottom buttons. void TransferMarketScreen::draw_market_overview(Image& out) const { const bool full=(view_flags_&1)!=0; draw_roster(out,full); @@ -493,6 +547,8 @@ void TransferMarketScreen::draw_market_overview(Image& out) const { original_text(out,250,150,original_money(preview_->projected_balance),0x5f); original_text(out,242,150,exe_.cstring(::bmh::layout::TransferMarket_Rect_TextPointer),0x69); } + // Strength bars: shows the averages of the whole team (flag 0x400) or of the active players; + // the bar height is the share of the overall average clamped to 91..109 percent. const auto& average=(view_flags_&0x400)?state_.team_strengths:state_.active_strengths; for(int n=0;n<4;++n) { const int height=std::clamp(average[4]?average[size_t(n)]*100/average[4]:0,91,109)-90,x=228+n*23; @@ -502,12 +558,15 @@ void TransferMarketScreen::draw_market_overview(Image& out) const { original_text(out,236+n*23,172,padded(average[size_t(n)]),0x6b); } original_text(out,201,183,padded(average[4]),0x6b); + // Filter and mode buttons: positions and rectangles come from a table in the executable (6 bytes per entry). for(int n=4;n<13;++n)button(out,exe_.u16(::bmh::layout::TransferMarket_Click_RuntimeField + n*6),exe_.u16(::bmh::layout::TransferMarket_Click_RuntimeField2+n*6),exe_.u16(::bmh::layout::TransferMarket_Click_RuntimeField3+n*6),texts_[text_id(::bmh::layout::TransferMarket_Rect_TextPointer5)+size_t(n)],(view_flags_&(1u<first:int32_t(exe_.u32(::bmh::layout::CurrencyMultiplier)); const int32_t denominator=state_.currency?state_.currency->second:int32_t(exe_.u32(::bmh::layout::CurrencyDivisor)); @@ -517,6 +576,8 @@ std::string TransferMarketScreen::original_money(int32_t value) const { if(result.size()<9)result.insert(0,9-result.size(),'%'); return result+exe_.cstring(::bmh::layout::CurrencySuffixText); } +// Renders the complete 320x240 screen: frame (or plain bars), title, club name, the overview and a +// feedback line that replaces the club name line when set (shortened to fit 310 pixels). Image TransferMarketScreen::render() const { Image out=state_.decorated_background?frame_:Image(320,240); if(!state_.decorated_background){rect(out,0,4,320,13,0x44);rect(out,1,5,318,11,0x39);rect(out,0,228,320,10,0x44);rect(out,1,229,318,8,0x39);} @@ -537,6 +598,8 @@ Image TransferMarketScreen::render() const { return out; } +// Validates the offer form (fee and salary non-zero, 1..4 years, bonuses 0..100, not an own player) +// and creates a submit_bid request; the screen then waits for the session's acknowledgement. TransferMarketRequest TransferMarketScreen::make_bid() { if (pending_ || !selected_item_) return {}; if (offer_values_[0] == 0 || offer_values_[1] == 0 || offer_values_[2] < 1 || offer_values_[2] > 4) { @@ -564,6 +627,8 @@ TransferMarketRequest TransferMarketScreen::make_bid() { return request; } +// Creates a request to list the selected squad player (sell or loan). If the player is already listed, +// opens the offer review instead. TransferMarketRequest TransferMarketScreen::make_listing(bool loan) { if (pending_ || !selected_squad_) return {}; const auto& item = state_.squad.at(size_t(*selected_squad_)); @@ -582,6 +647,7 @@ TransferMarketRequest TransferMarketScreen::make_listing(bool loan) { return request; } +// Creates a quote-preview request for the selected market item (purchase), loan snapshot or squad player. TransferMarketRequest TransferMarketScreen::make_preview(bool purchase) { if(pending_)return {}; TransferMarketRequest request;request.kind=TransferMarketRequestKind::preview_quote; @@ -607,6 +673,7 @@ TransferMarketRequest TransferMarketScreen::make_preview(bool purchase) { } pending_=request;preview_.reset();return request; } +// Creates a request to review the bids on one of the player's own listings; refuses if there are none. TransferMarketRequest TransferMarketScreen::make_review(const TransferMarketItem& item) { if (pending_) return {}; if (item.offers == 0) { feedback_ = "Noch keine Angebote für diesen Spieler."; return {}; } @@ -618,6 +685,7 @@ TransferMarketRequest TransferMarketScreen::make_review(const TransferMarketItem request.bid.source_slot = item.source_slot; pending_ = request; feedback_.clear(); return request; } +// Creates a request to open the offer screen for the selected market item; own listings go to the review instead. TransferMarketRequest TransferMarketScreen::make_open_offer(bool loan) { if(pending_||!selected_item_)return {}; const auto& item=state_.items.at(size_t(*selected_item_)); @@ -630,6 +698,8 @@ TransferMarketRequest TransferMarketScreen::make_open_offer(bool loan) { request.selected_players.push_back({item.list_entry,item.source_slot,item.player,item.seller,-1}); pending_=request;return request; } +// Selection by position over the market rows (x 201..297, y 25..115, 15 px per row) or the roster +// names (x 9..60). A new selection requests a quote preview unless Komplett is on. TransferMarketRequest TransferMarketScreen::move(int x,int y) { if(pending_||close_requested_)return {}; if(!(view_flags_&1)&&x>=201&&x<=297&&y>=25&&y<115) { @@ -654,6 +724,9 @@ TransferMarketRequest TransferMarketScreen::move(int x,int y) { } selected_item_.reset();selected_squad_.reset();selected_snapshot_.reset();preview_.reset();return {}; } +// Handles a mouse click. Right click on the market pane turns the page, elsewhere closes the screen. +// Left click handles the Data/Komplett buttons, poach and filter buttons, marking of rows, and the action bar +// (y 202..212; the right part x>=254 means loan). TransferMarketRequest TransferMarketScreen::click(int x,int y,bool right) { if(pending_||close_requested_)return {}; if(right) { @@ -724,6 +797,8 @@ TransferMarketRequest TransferMarketScreen::click(int x,int y,bool right) { } return {}; } +// Keyboard shortcuts: Esc closes, B or Enter opens an offer for the selected market item, +// V or Enter lists the selected squad player. TransferMarketRequest TransferMarketScreen::key(std::string_view key) { if(pending_||close_requested_)return {}; if(key=="ESC"||key=="ESCAPE"){close_requested_=true;return {};} @@ -736,6 +811,7 @@ TransferMarketRequest TransferMarketScreen::key(std::string_view key) { return {}; } +// Accepts typed digits (at most 10) while the offer form is shown; returns whether the input was used. bool TransferMarketScreen::text(std::string_view value) { if (pending_ || close_requested_ || view_ != View::offer) return false; if (value.empty() || numeric_input_.size() + value.size() > 10 || @@ -743,6 +819,8 @@ bool TransferMarketScreen::text(std::string_view value) { numeric_input_.append(value); return true; } +// Session acknowledgement of a request: replaces the state with a newer revision of the same manager, +// clears the pending request and all selections and shows the notice. void TransferMarketScreen::acknowledge(TransferMarketState updated, std::string notice) { if (!pending_ || updated.manager_slot != state_.manager_slot || updated.runtime_club != state_.runtime_club || updated.revision <= state_.revision) throw FormatError("transfer market: acknowledgement requires same manager and newer revision"); @@ -750,10 +828,13 @@ void TransferMarketScreen::acknowledge(TransferMarketState updated, std::string view_ = View::market; numeric_input_.clear();marked_items_.clear();marked_squad_.clear(); feedback_ = std::move(notice); } +// Session acknowledgement when the request changed nothing: only releases the pending request. void TransferMarketScreen::acknowledge_unchanged() { if (!pending_) throw FormatError("transfer market: no pending request to acknowledge"); pending_.reset(); numeric_input_.clear(); feedback_.clear(); } +// Session acknowledgement of a quote preview: checks that the quote matches the pending request exactly +// (manager, club, slot, player, seller, kind), re-finds the selection in the new state and stores the quote. void TransferMarketScreen::acknowledge_preview(TransferMarketState updated,TransferMarketPreview quote) { if(!pending_||pending_->kind!=TransferMarketRequestKind::preview_quote|| updated.manager_slot!=state_.manager_slot||updated.runtime_club!=state_.runtime_club||updated.revision=0)selected_snapshot_=selected;else selected_squad_=selected; } +// Takes a fresh state after the offer screen has been left; clears selections and marks. void TransferMarketScreen::refresh_after_offer(TransferMarketState updated) { if (pending_ || updated.manager_slot != state_.manager_slot || updated.runtime_club != state_.runtime_club || updated.revision < state_.revision) @@ -789,10 +871,12 @@ void TransferMarketScreen::refresh_after_offer(TransferMarketState updated) { marked_items_.clear(); marked_squad_.clear(); feedback_.clear(); } +// Session rejection of the pending request: releases it and shows the reason as feedback. void TransferMarketScreen::reject_action(std::string reason) { if (!pending_ || reason.empty()) throw FormatError("transfer market: rejection requires pending request/reason"); pending_.reset(); feedback_ = std::move(reason); numeric_input_.clear(); } +// Serialises the screen state (view, selections, pending request, preview, visible rows) as JSON for tests. std::string TransferMarketScreen::state_json() const { std::ostringstream out; out << "{\"screen\":\"transfer_market\",\"view\":\""