Split the career session into files by topic

career_session.cpp (9,000 lines) is now eight files: construction and turn,
club dialogs, league family, statistics, transfers, desk, match, management.
Every function moved unchanged. Helpers used by one topic live in its file,
the seven shared ones in the internal header career_session_internal.hpp.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
ClaudeandClaude committed 2026-11-11 08:57:58 +01:00
1 parent 81046f89f2
commit 33566566ac
11 files changed
+7658 -7564

No files matched your search

+14 -2
View File
@@ -132,9 +132,21 @@ endif()
# string literals. (Until 1.0.12 the MSVC build compiled these sources again for every
# consumer, which cost most of the build time; controller.cpp then got /utf-8 only from
# targets that set it.)
add_library(bmh_app_session OBJECT src/app/career_session.cpp src/app/window_actions.cpp src/app/desktop_actions.cpp)
# The career session is defined by topic in career_session*.cpp (the class: src/app/career_session.hpp).
set(BMH_APP_SESSION_SOURCES
src/app/career_session.cpp
src/app/career_session_club.cpp
src/app/career_session_league.cpp
src/app/career_session_statistics.cpp
src/app/career_session_transfer.cpp
src/app/career_session_desk.cpp
src/app/career_session_match.cpp
src/app/career_session_management.cpp
src/app/window_actions.cpp
src/app/desktop_actions.cpp)
add_library(bmh_app_session OBJECT ${BMH_APP_SESSION_SOURCES})
target_link_libraries(bmh_app_session PRIVATE bmhui)
add_library(bmh_app_session_sdl OBJECT src/app/career_session.cpp src/app/window_actions.cpp src/app/desktop_actions.cpp)
add_library(bmh_app_session_sdl OBJECT ${BMH_APP_SESSION_SOURCES})
target_link_libraries(bmh_app_session_sdl PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET})
add_library(bmh_app_controller_sdl OBJECT src/app/controller.cpp)
target_link_libraries(bmh_app_controller_sdl PRIVATE bmhui openbmh_audio ${BMH_SDL_TARGET})
+1 -1
View File
@@ -6,7 +6,7 @@ See [Compatibility decisions](COMPATIBILITY.md) for the overall policy. These en
describe deliberate changes; they are not a list of every known compatibility limit.
- [src/app/app_run.cpp](../src/app/app_run.cpp): display the repository-owned title at its native resolution until a complete left/right click, without loading balls.
- [src/app/career_session.cpp](../src/app/career_session.cpp): supports designated set-piece record initialization and validation.
- [src/app/career_session_match.cpp](../src/app/career_session_match.cpp): supports designated set-piece record initialization and validation.
- [src/app/quit_confirmation.hpp](../src/app/quit_confirmation.hpp): confirms application exit with a localized native dialog, with cancellation selected by default.
- [src/game/career.cpp](../src/game/career.cpp): skips reserved calendar positions when assigning a joining manager to a club.
- [src/game/career.hpp](../src/game/career.hpp): uses the supported player-generation ranges and excludes reserved calendar positions when assigning managers.
+15 -7561
View File
File diff suppressed because it is too large. Load diff
+193
View File
@@ -0,0 +1,193 @@
// SPDX-License-Identifier: GPL-3.0-only
// CareerSession: the club information dialogs (club, player list, player detail) and their services.
// (moved out of career_session.cpp unchanged; the class is declared in app/career_session.hpp)
#include "app/career_session_internal.hpp"
namespace bmh::app {
// Club-information modal family (enter, change category, player redraw, national action,
// pending offers): each member refuses to run while another modal owner is open and clears
// 'error' first. The ones that change state work on copies and assign them back only after
// success.
// Enter: opens the club info entry for 'team'; nullopt plus 'error' on an invalid team.
std::optional<ClubInfoEntry> CareerSession::enter_club_information(int team, std::string& error) {
if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ ||
top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; }
error.clear();
try { return prepare_club_info_entry(g_, team); }
catch (const std::invalid_argument& e) { error = e.what(); return std::nullopt; }
}
// Switches the club info category for 'team'; nullopt plus 'error' when it is invalid.
std::optional<uint8_t> CareerSession::change_club_information_category(int team, int requested,
std::string& error) {
if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ ||
top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; }
error.clear();
try { return set_club_info_category(g_, team, requested); }
catch (const std::invalid_argument& e) { error = e.what(); return std::nullopt; }
}
// Redraws a player detail card; random generators advance only if the redraw succeeded.
std::optional<ClubPlayerDetailRedraw> CareerSession::redraw_club_player_detail(
const ClubPlayerDetailSelection& selection, std::string& error) {
if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ ||
top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; }
error.clear();
auto next_game = game_;
auto next_rand = rand_;
try {
auto redraw = club_player_detail_redraw(g_, selection, exe_, next_game, next_rand);
game_ = next_game;
rand_ = next_rand;
return redraw;
} catch (const std::invalid_argument& e) {
error = e.what();
return std::nullopt;
}
}
// Applies the national-team add/remove action of a player card on a staged copy; the copy is
// committed only when the engine reports no reason. Returns whether the action was applied.
std::optional<bool> CareerSession::dispatch_club_player_national_action(
const ClubPlayerDetailSelection& selection, std::string& error) {
if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ ||
top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; }
error.clear();
auto next_state = g_;
auto next_rand = rand_;
MinuteReport report;
try {
const bool applied = club_player_detail_national_action(next_state, selection, next_rand, report);
if (!report.reason.empty()) { error = report.reason; return std::nullopt; }
g_ = std::move(next_state);
rand_ = next_rand;
return applied; // Source still refreshes the lineup when an add finds a full squad.
} catch (const std::invalid_argument& e) {
error = e.what();
return std::nullopt;
}
}
// Processes the pending transfer offers of a player card. Rejects a stale revision or a nested
// pending-offer/market dispatch, works on copies and commits them when at least one offer was
// processed. The revision is bumped here unless a calendar advance is active: then the outer
// driver publishes the revision when it returns.
std::optional<PendingOfferResult> CareerSession::dispatch_club_player_pending_offers(
const ClubPlayerDetailSelection& selection, uint64_t expected_revision,
const PendingOfferHooks& hooks, uint64_t& revision, std::string& error) {
if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ ||
top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; }
error.clear();
if (expected_revision != revision || pending_offer_dispatch_active_ || market_dispatch_active_ ||
revision == std::numeric_limits<uint64_t>::max()) {
error = "pending offer: stale or nested player-card action";
return std::nullopt;
}
auto next_state = g_;
auto next_game = game_;
auto next_rand = rand_;
pending_offer_dispatch_active_ = true;
struct Reset { bool& active; ~Reset() { active = false; } } reset{pending_offer_dispatch_active_};
MinuteReport report;
try {
const auto result = process_player_card_pending_offers(
next_state, selection, next_game, next_rand, pending_hooks_for_dispatch(hooks), report);
if (report.unsupported || !result.completed) {
error = report.reason.empty() ? "pending offer: manual decision incomplete" : report.reason;
return std::nullopt;
}
if (result.processed != 0) {
g_ = std::move(next_state);
game_ = next_game;
rand_ = next_rand;
// A nested cup modal belongs to the current calendar transaction;
// its outer driver publishes that revision when advancement returns.
if (!calendar_advance_active_) ++revision;
}
return result;
} catch (const std::exception& e) {
error = e.what();
return std::nullopt;
}
}
// Seeds the process-only byte map used by the club modals with their start values from the
// executable; these values are never written to a save.
void CareerSession::initialize_club_modal_runtime() {
// Setup clears the boot-only dialog mode before either creating or loading
// a career. This process flag is deliberately absent from native saves.
club_modal_runtime_.emplace(layout::CompactDialogFrame, 0);
// LE object4 has bb cdd/de/e1 in its zero-initialized virtual tail;
// CareerSession_InitializeClubModalRuntime_ExecutableField is file-backed zero. These are explicit process-start values,
// carried by this runtime owner across modal entry/return, not FBM bytes.
for(uint32_t address:{::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableFieldUnsigned,::bmh::layout::CareerSession_DispatchPoachUi_ExecutableFieldUnsigned,::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableField2Unsigned,::bmh::layout::CareerSession_InitializeClubModalRuntime_ExecutableFieldUnsigned})
club_modal_runtime_.emplace(address,exe_.u8(address));
}
// Collects the executable bytes and rating tables the Sportschau screen reads.
SportschauSourceOptions CareerSession::sportschau_source_options() const {
return {source_runtime_byte(g_, club_modal_runtime_, exe_, ::bmh::layout::CareerSession_SportschauSourceOptions_ExecutableField),
source_runtime_byte(g_, club_modal_runtime_, exe_, ::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableField2), exe_.u16(::bmh::layout::TeamsWithSquads),
sportschau_rating_tables(exe_)};
}
// Builds the service callbacks of the club modal on a given (staged) state, generators and
// runtime byte map, so the modal can run on a copy and be committed or dropped by the caller.
ClubModalServices CareerSession::staged_club_modal_services(GameState& state,
GameRandom& game,WatcomRandom& rand,std::map<uint32_t,uint8_t>& runtime) {
ClubModalServices services;
auto* g=&state; auto* gr=&game; auto* wr=&rand; auto* bytes=&runtime;
services.state=[g]() -> GameState& { return *g; };
services.enter_club=[g](int team) { return prepare_club_info_entry(*g,team); };
services.change_category=[g](int team,int category) { return set_club_info_category(*g,team,category); };
services.redraw_player=[this,g,gr,wr](const ClubPlayerDetailSelection& selection) {
auto next_game=*gr; auto next_rand=*wr;
auto result=club_player_detail_redraw(*g,selection,exe_,next_game,next_rand);
*gr=next_game; *wr=next_rand; return result;
};
services.national_action=[g,wr](const ClubPlayerDetailSelection& selection) {
auto next=*g; auto next_rand=*wr; MinuteReport report;
const bool applied=club_player_detail_national_action(next,selection,next_rand,report);
if(!report.reason.empty())throw FormatError(report.reason);
*g=std::move(next); *wr=next_rand; return applied;
};
services.pending_offers=[this,g,gr,wr](const ClubPlayerDetailSelection& selection,const PendingOfferHooks& hooks) {
auto next=*g; auto next_game=*gr; auto next_rand=*wr; MinuteReport report;
auto result=process_player_card_pending_offers(next,selection,next_game,next_rand,
pending_hooks_for_dispatch(hooks),report);
if(report.unsupported||!result.completed)
throw FormatError(report.reason.empty()?"TeamInfo: nested pending decision incomplete":report.reason);
*g=std::move(next); *gr=next_game; *wr=next_rand; return result;
};
services.runtime_byte=[this,g,bytes](uint32_t address) {
if(g->memory.has(address))return g->memory.u8(address);
if(const auto at=bytes->find(address);at!=bytes->end())return at->second;
// Explicit original initialization supplies the transient input owner.
// Never serialize an absent BSS byte or infer Native absence as zero.
return exe_.u8(address);
};
services.set_runtime_byte=[g,bytes](uint32_t address,uint8_t value) {
if(g->memory.has(address))g->memory.set8(address,value);
else (*bytes)[address]=value;
};
return services;
}
// Same services bound to the live state (non-transactional); pending offers go through
// dispatch_club_player_pending_offers. Throws when another modal owner is open.
ClubModalServices CareerSession::live_club_modal_services(uint64_t& revision) {
if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ ||
top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) throw FormatError("strengths_active");
auto services=staged_club_modal_services(g_,game_,rand_,club_modal_runtime_);
services.transactional=false;
// Existing cup/club caller keeps its separately owned pending transaction.
services.pending_offers=[this,&revision](const ClubPlayerDetailSelection& selection,const PendingOfferHooks& hooks) {
std::string error;
auto result=dispatch_club_player_pending_offers(selection,revision,hooks,revision,error);
if(!result)throw FormatError(error);
return *result;
};
return services;
}
} // namespace bmh::app
File diff suppressed because it is too large. Load diff
+164
View File
@@ -0,0 +1,164 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// Internal header of the career session: the includes and the helper functions that more than one of the
// career_session*.cpp files uses. Included only by those files (the helpers have internal linkage).
#include "formats/native_save_version.hpp"
#include "formats/badge_policy.hpp"
#include "game/calendar.hpp"
#include "formats/executable_layout.hpp"
#include "app/career_session.hpp"
#include "formats/league_visibility.hpp"
#include <stdexcept>
#include <system_error>
#include <algorithm>
#include <array>
#include <atomic>
#include <cctype>
#include <bit>
#include <fstream>
#include <limits>
#include <utility>
#include "formats/binary.hpp"
#include "formats/fbm.hpp"
#include "formats/savestate.hpp"
#include "game/career.hpp"
#include "game/cup.hpp"
#include "game/driver.hpp"
#include "game/desk.hpp"
#include "game/desk_actions.hpp"
#include "game/match.hpp"
#include "game/messages.hpp"
#include "game/prediction.hpp"
#include "game/schedule.hpp"
#include "game/bank_credit.hpp"
#include "game/matchday_setup.hpp"
#include "game/matchday.hpp"
#include "game/lineup.hpp"
#include "game/month.hpp"
#include "game/national.hpp"
#include "game/schedule.hpp"
#include "game/table.hpp"
#include "game/table_forecast.hpp"
#include "game/save.hpp"
#include "game/season.hpp"
#include "game/turn.hpp"
#include "game/week.hpp"
#include "game/weekly.hpp"
#include "ui/desk_state.hpp"
#include "ui/league_table.hpp"
#include "ui/other_games_state.hpp"
#include "ui/manager.hpp"
#include "ui/pending_offer.hpp"
#include "ui/training.hpp"
namespace bmh::app {
namespace {
// Reads one byte of the executable's data at 'address': from the game's memory image when the
// address is mapped there, else from the runtime override map, else from the loaded EXE.
uint8_t source_runtime_byte(const GameState& state,const std::map<uint32_t,uint8_t>& runtime,
const LeImage& exe,uint32_t address) {
if(state.memory.has(address))return state.memory.u8(address);
const auto found=runtime.find(address);return found==runtime.end()?exe.u8(address):found->second;
}
// Writes one byte to the memory image when the address is mapped there, otherwise into the
// runtime override map (the EXE image itself is never modified).
void source_runtime_set_byte(GameState& state,std::map<uint32_t,uint8_t>& runtime,
uint32_t address,uint8_t value) {
if(state.memory.has(address))state.memory.set8(address,value);
else runtime[address]=value;
}
// Little-endian 32-bit read built from four source_runtime_byte reads.
uint32_t source_runtime_u32(const GameState& state,const std::map<uint32_t,uint8_t>& runtime,
const LeImage& exe,uint32_t address) {
return uint32_t(source_runtime_byte(state,runtime,exe,address)) |
uint32_t(source_runtime_byte(state,runtime,exe,address+1))<<8 |
uint32_t(source_runtime_byte(state,runtime,exe,address+2))<<16 |
uint32_t(source_runtime_byte(state,runtime,exe,address+3))<<24;
}
// Writes the process scratch bytes (league, group, date pieces, strength sums) that the
// original leaves behind after drawing the pairings page, so later reads see the same values.
// Bytes go to the memory image when mapped there, else to the runtime map.
void pairings_runtime_draw(GameState& g,std::map<uint32_t,uint8_t>& runtime,
const ui::LeaguePairingsState& page,const LeImage& exe) {
const auto put=[&](uint32_t at,uint8_t v) {
if(g.memory.has(at))g.memory.set8(at,v);else runtime[at]=v;
};
const uint32_t tip_preference=::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(page.identity.manager);
const bool computer_tip=page.source.owner.computer_tip_active;
if(computer_tip)put(tip_preference,uint8_t(g.memory.u8(tip_preference)|0x10));
// Actual5147b entry/input globals; these are process bytes, not invented FBM blocks.
put(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField2,uint8_t(page.identity.league));put(::bmh::layout::CareerSession_AdvertisingSessionUnchanged_ExecutableField,page.source.owner.league_group);
put(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField,0);put(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2,0);
const auto date=[&](uint32_t counter) {
if(counter==0xffff)return; //21258's Wettbewerb-gesperrt branch changes no date scratch.
const auto d=ui::desk_date(counter,exe);
int cycle=3;uint32_t n=counter;
while(n>uint32_t(364+(cycle==4))) {if(cycle==4){cycle=0;--n;}n-=365;++cycle;}
put(::bmh::layout::CareerSession_PairingsRuntimeDraw_ExecutableField,uint8_t(28+(cycle==4)));
put(::bmh::layout::CareerSession_PairingsRuntimeDraw_ExecutableField4,uint8_t(d.day));put(::bmh::layout::CareerSession_PairingsRuntimeDraw_ExecutableField5,uint8_t(d.month));put(::bmh::layout::CareerSession_PairingsRuntimeDraw_ExecutableField6,uint8_t(d.weekday));
put(::bmh::layout::CareerSession_PairingsRuntimeDraw_ExecutableField2,uint8_t(d.year));put(::bmh::layout::CareerSession_PairingsRuntimeDraw_ExecutableField3,uint8_t(d.year>>8));
};
const bool selected_filter=page.source.owner.filter_active&&page.source.owner.filter_team>=0;
if(!selected_filter&&!page.source.owner.postponed_active)
date(page.source.match_date); //333f3 is absent in selected Mode4 and Mode8.
for(const auto& row:page.source.rows) {
if(row.scheduled_date)date(*row.scheduled_date);
else if(row.postponed_date)date(*row.postponed_date);
const uint8_t displayed=row.computer_tip_result.value_or(row.raw_result);
// In local28's referee phase, exact CC rows skip both 68164 calls.
// Preserve prior scratch when every row takes that branch; a mixed
// page leaves the last ordinary away-row value, in Source draw order.
if(page.source.owner.active_phase&&displayed==0xcc)continue;
//68164's final17295 call on the away team leaves Source CareerSession_FormatError_ExecutableField3.
const auto strength=team_average(g,row.away.runtime_team,0x1ff);
put(::bmh::layout::CareerSession_FormatError_ExecutableField3,uint8_t(strength.best_half_sum));put(::bmh::layout::CareerSession_FormatError_ExecutableField4,uint8_t(strength.best_half_sum>>8));
}
// Move clears its one-redraw local38 bit after the forecast has
// been projected. The returned page retains the pressed Original button.
if(computer_tip)put(tip_preference,uint8_t(g.memory.u8(tip_preference)&0xef));
}
// Compares the runtime-only fields of two states (callbacks by target type); used to check the
// strengths view left the game unchanged.
bool same_strengths_runtime_state(const GameState& a,const GameState& b) {
const auto same_callback=[](const auto& lhs,const auto& rhs) {
return bool(lhs)==bool(rhs)&&(!lhs||lhs.target_type()==rhs.target_type());
};
return a.indoor==b.indoor&&a.currency_suffix==b.currency_suffix&&a.level==b.level&&
a.chance_rain==b.chance_rain&&a.chance_temperature==b.chance_temperature&&
a.last_shooter==b.last_shooter&&a.last_pick_quality==b.last_pick_quality&&
a.live_scene==b.live_scene&&a.reality==b.reality&&a.live_matches==b.live_matches&&a.list_toggle==b.list_toggle&&
a.lineups_frozen==b.lineups_frozen&&a.texts==b.texts&&a.date==b.date&&
a.season_start==b.season_start&&a.development_balance==b.development_balance&&
a.trend_rotation==b.trend_rotation&&a.season==b.season&&a.transfer_notice_suppressed==b.transfer_notice_suppressed&&
a.offer_answer==b.offer_answer&&a.pools_open==b.pools_open&&a.autosave_months==b.autosave_months&&
a.autosave_month==b.autosave_month&&same_callback(a.contract_screen,b.contract_screen)&&
same_callback(a.loan_return_screen,b.loan_return_screen)&&
same_callback(a.loan_return_offer_screen,b.loan_return_offer_screen)&&
same_callback(a.transfer_decision,b.transfer_decision)&&
same_callback(a.transfer_offer_selector,b.transfer_offer_selector)&&
same_callback(a.transfer_decision_observer,b.transfer_decision_observer);
}
// Reinterprets the low byte of 'value' as a signed byte.
int8_t source_byte(int value) { return static_cast<int8_t>(uint8_t(value)); }
// True when a table request carries no stray fields (no target child, team, row or dialog reply;
// league id only if the selector variant is allowed) and the expected control index.
bool canonical_table_envelope(const ui::LeagueFamilyRequest& request,int control_index=-1,
bool allow_selector_league=false) {
return request.target_child==0&&request.runtime_team==-1&&request.expected_club_identity==-1&&
request.table_row_index==-1&&(allow_selector_league||request.league_id==-1)&&
request.control_index==control_index&&
!request.table_dialog_reply;
}
} // namespace
} // namespace bmh::app
File diff suppressed because it is too large. Load diff
+803
View File
@@ -0,0 +1,803 @@
// SPDX-License-Identifier: GPL-3.0-only
// CareerSession: club management: training, training camp, bank, stadium, toto.
// (moved out of career_session.cpp unchanged; the class is declared in app/career_session.hpp)
#include "app/career_session_internal.hpp"
namespace bmh::app {
namespace {
constexpr uint8_t kBlockSeat = 1;
constexpr uint8_t kBlockRoof = 2;
constexpr uint8_t kBlockFeatures = kBlockSeat | kBlockRoof;
// True for the stadium requests that belong to the block-expansion dialog (select, total,
// feature toggle, cancel, confirm, answer tip).
bool is_block_expansion_action(ui::StadiumRequestKind kind) {
return kind == ui::StadiumRequestKind::expansion_select ||
kind == ui::StadiumRequestKind::expansion_set_total ||
kind == ui::StadiumRequestKind::expansion_toggle_feature ||
kind == ui::StadiumRequestKind::expansion_cancel ||
kind == ui::StadiumRequestKind::expansion_confirm ||
kind == ui::StadiumRequestKind::expansion_answer_tip;
}
} // namespace
// Training group: one request changes the types, areas, automation byte or one player's
// intensity or focus of the active manager. The request carries the desired result; it is
// validated against the current projection (stale manager, plan limits, expected values), applied
// on a staged copy and committed with revision plus one. Manual edits clear the matching
// assistant flag and never draw random numbers; initialize and enabling automation run the
// automatic training. Returns false with a short error code in 'error' otherwise.
bool CareerSession::dispatch_training(const ui::TrainingRequest& request, uint64_t& revision,
std::string& error) {
if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ ||
top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; }
const int active = int(g_.memory.u8(::bmh::layout::ActiveManager));
if (request.manager_slot != active || request.manager_slot < 0 || request.manager_slot > 3 ||
size_t(request.manager_slot) >= g_.manager_teams.size() ||
request.runtime_club != g_.manager_teams[size_t(request.manager_slot)] || request.revision != revision) {
error = "stale_manager_or_revision";
return false;
}
try {
const ui::TrainingState current = ui::training_from_game(g_, exe_, revision);
if (current.manager_slot != request.manager_slot || current.runtime_club != request.runtime_club) {
error = "stale_manager_or_revision";
return false;
}
const size_t slot = size_t(request.manager_slot);
const size_t rec = slot * 0xb0c;
const size_t option_at = slot * 5 + 4;
if (g_.manager_records.size() < rec + 0xb0c || g_.manager_options.size() <= option_at) {
error = "invalid_training_state";
return false;
}
auto valid_plan = [](const std::array<uint8_t, 4>& types, const std::array<uint8_t, 9>& areas) {
int type_sum = 0, fitness = 0, skills = 0;
for (uint8_t value : types) { if (value < 1 || value > 3) return false; type_sum += value; }
for (size_t i = 0; i < areas.size(); ++i) {
const uint8_t value = areas[i];
if (value < 1 || value > 3) return false;
if (i < 2) fitness += value; else skills += value;
}
return type_sum <= 8 && fitness <= 4 && skills <= 18;
};
if (!valid_plan(request.desired_types, request.desired_areas)) {
error = "invalid_training_plan";
return false;
}
ui::TrainingRequestKind kind = request.kind;
auto types = current.types;
auto areas = current.areas;
uint8_t automation = current.automation;
bool run_automatic = false;
// NeedsInitialization initializes an uninitialized screen via Initialize;
// the four subordinate toggles exist only while the global flag is on.
// NeedsInitialization2 calls that same deterministic routine after an enabled
// automation toggle. Manual field edits only write their field and clear
// the matching assistant flag; they do not run training or draw RNG.
switch (kind) {
case ui::TrainingRequestKind::initialize:
if (!current.needs_initialization() || request.index != -1 || request.value != -1 ||
request.player_id != -1 || request.desired_types != types || request.desired_areas != areas ||
request.desired_automation != 0x9f) {
error = "invalid_training_initialization";
return false;
}
automation = 0x9f;
run_automatic = true;
break;
case ui::TrainingRequestKind::set_type:
if (current.needs_initialization() || request.index < 0 || request.index >= int(types.size()) ||
request.value < 1 || request.value > 3 || request.player_id != -1 ||
request.value == types[size_t(request.index)]) {
error = "invalid_training_type";
return false;
}
types[size_t(request.index)] = uint8_t(request.value);
automation = uint8_t(automation & ~uint8_t(1u << 1));
break;
case ui::TrainingRequestKind::set_area:
if (current.needs_initialization() || request.index < 0 || request.index >= int(areas.size()) ||
request.value < 1 || request.value > 3 || request.player_id != -1 ||
request.value == areas[size_t(request.index)]) {
error = "invalid_training_area";
return false;
}
areas[size_t(request.index)] = uint8_t(request.value);
automation = uint8_t(automation & ~uint8_t(1u << 2));
break;
case ui::TrainingRequestKind::set_player_intensity:
case ui::TrainingRequestKind::set_player_focus: {
if (current.needs_initialization() || request.index < 0 || request.index >= current.squad_capacity ||
request.player_id < 0 || request.player_id > 0x0ffe) {
error = "invalid_training_player";
return false;
}
const auto player = std::find_if(current.players.begin(), current.players.end(), [&](const auto& p) {
return p.row == request.index && p.player_id == request.player_id;
});
const SquadRange squad = squad_range(request.runtime_club);
if (player == current.players.end() || squad.count != size_t(current.squad_capacity) ||
squad.first + size_t(request.index) >= g_.squad_slots.size() ||
(g_.squad_slots[squad.first + size_t(request.index)] & 0x0fff) != request.player_id) {
error = "stale_training_player";
return false;
}
if (kind == ui::TrainingRequestKind::set_player_intensity) {
if (request.value < 1 || request.value > 3 || request.value == player->intensity) {
error = "invalid_training_intensity";
return false;
}
automation = uint8_t(automation & ~uint8_t(1u << 3));
} else if (request.value < 0 || request.value > 7 || request.value != (player->focus + 1) % 8) {
error = "invalid_training_focus";
return false;
}
break;
}
case ui::TrainingRequestKind::set_automation: {
if (current.needs_initialization() || request.index < 0 || request.index > 4 ||
(request.value != 0 && request.value != 1) || request.player_id != -1) {
error = "invalid_training_automation";
return false;
}
if (request.index != 0 && !(current.automation & 1)) {
error = "training_automation_group_hidden";
return false;
}
const uint8_t mask = uint8_t(1u << request.index);
automation = uint8_t(automation ^ mask);
if (((automation & mask) != 0) != (request.value != 0)) {
error = "stale_training_automation";
return false;
}
run_automatic = (automation & 1) != 0;
break;
}
case ui::TrainingRequestKind::none:
default:
error = "unsupported_training_request";
return false;
}
if (request.desired_types != types || request.desired_areas != areas ||
request.desired_automation != automation) {
error = "stale_training_projection";
return false;
}
GameState staged = g_;
std::copy(types.begin(), types.end(), staged.manager_records.begin() + rec + 0xc5);
std::copy(areas.begin(), areas.end(), staged.manager_records.begin() + rec + 0xc9);
staged.manager_options[option_at] = automation;
if (kind == ui::TrainingRequestKind::set_player_intensity ||
kind == ui::TrainingRequestKind::set_player_focus) {
const size_t board = slot * 0x840 + size_t(request.index) * 0x58 + 0x0a;
if (board >= staged.tactics.size()) {
error = "invalid_training_board";
return false;
}
if (kind == ui::TrainingRequestKind::set_player_intensity)
staged.tactics[board] = uint8_t((staged.tactics[board] & 0xfc) | request.value);
else
staged.tactics[board] = uint8_t((staged.tactics[board] & 0x03) | (request.value << 2));
}
if (run_automatic) auto_training(staged, request.manager_slot);
g_ = std::move(staged);
++revision;
error.clear();
return true;
} catch (const std::exception&) {
error = "invalid_training_state";
return false;
}
}
// Training camp group: set_focus changes the four focus bytes of the active manager (an unchanged
// or invalid focus is refused); book books a resort for the week after checking the focus the UI
// saw, the weekly/visit limits and the funds (the booking draws random numbers). Refused while a
// modal owner is open or when the manager slot, club or revision is stale; revision plus one on
// success, short error codes in 'error' otherwise.
bool CareerSession::dispatch_training_camp(const ui::TrainingCampRequest& request, uint64_t& revision,
std::string& error) {
if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ ||
top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; }
if (request.manager_slot < 0 || size_t(request.manager_slot) >= g_.manager_teams.size() ||
request.manager_slot != int(g_.memory.u8(::bmh::layout::ActiveManager)) ||
request.runtime_club != g_.manager_teams[size_t(request.manager_slot)] || request.revision != revision) {
error = "stale_manager_or_revision";
return false;
}
const size_t rec = size_t(request.manager_slot) * 0xb0c;
if (request.kind == ui::TrainingCampRequestKind::set_focus) {
const std::array<uint8_t, 4> current{
g_.manager_records.at(rec + 0xc1), g_.manager_records.at(rec + 0xc2),
g_.manager_records.at(rec + 0xc3), g_.manager_records.at(rec + 0xc4)};
if (request.focus == current) {
error = "focus_unchanged";
return false;
}
if (!set_training_camp_focus(g_, request.manager_slot, request.focus)) {
error = "invalid_focus_request";
return false;
}
++revision;
return true;
}
if (request.kind == ui::TrainingCampRequestKind::book) {
if (request.resort < 0 || request.resort >= kTrainingCampResorts) {
error = "invalid_resort";
return false;
}
const std::array<uint8_t, 4> current{
g_.manager_records.at(rec + 0xc1), g_.manager_records.at(rec + 0xc2),
g_.manager_records.at(rec + 0xc3), g_.manager_records.at(rec + 0xc4)};
if (request.focus != current) {
error = "stale_focus";
return false;
}
switch (training_camp_booking_block(g_, request.manager_slot)) {
case TrainingCampBookingBlock::booked_this_week: error = "booked_this_week"; return false;
case TrainingCampBookingBlock::visit_limit: error = "visit_limit"; return false;
case TrainingCampBookingBlock::invalid_request: error = "invalid_request"; return false;
case TrainingCampBookingBlock::none: break;
}
if (!book_training_camp(g_, request.manager_slot, request.resort, rand_)) {
error = "insufficient_funds";
return false;
}
++revision;
return true;
}
error = "unsupported_training_camp_request";
return false;
}
// Bank group: deposit moves, share and fund trades, stock tips and bank credit. Needs the active
// manager, club and current revision and no modal owner open. Every branch validates amounts and
// counts against the manager record and the stock/fund blocks, then applies the change to the
// live state and bumps the revision once. The notices of the last property purchase or credit
// refund are kept for the next projection. Returns false with a short error code otherwise.
bool CareerSession::dispatch_bank(const ui::BankRequest& request, uint64_t& revision, std::string& error) {
if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ ||
top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; }
error.clear();
if (revision == std::numeric_limits<uint64_t>::max()) {
error = "revision_exhausted"; return false;
}
const int active = int(g_.memory.u8(::bmh::layout::ActiveManager));
if (request.manager_slot != active ||
request.manager_slot < 0 || size_t(request.manager_slot) >= g_.manager_teams.size() ||
request.runtime_club != g_.manager_teams[size_t(request.manager_slot)] || request.revision != revision) {
error = "stale_manager_or_revision"; return false;
}
const size_t rec = size_t(request.manager_slot) * 0xb0c;
std::optional<ui::BankState::PropertyNotice> property_notice;
std::optional<ui::BankState::CreditNotice> credit_notice;
const auto read_signed = [&](size_t offset) {
const uint32_t v = uint32_t(g_.manager_records.at(rec + offset)) |
uint32_t(g_.manager_records.at(rec + offset + 1)) << 8 |
uint32_t(g_.manager_records.at(rec + offset + 2)) << 16 |
uint32_t(g_.manager_records.at(rec + offset + 3)) << 24;
return int32_t(v);
};
if (request.kind == ui::BankRequestKind::move_to_deposit) {
if (!request.amount || request.asset_index != -1 || request.count != 0 ||
int64_t(request.amount > 0 ? request.amount : -int64_t(request.amount)) > 99999999) {
error = "invalid_amount"; return false;
}
const int64_t available = request.amount > 0 ? read_signed(0x314) : read_signed(0x318);
if (available < 0 || int64_t(request.amount > 0 ? request.amount : -int64_t(request.amount)) > available) {
error = "amount_unavailable"; return false;
}
move_to_deposit(g_, request.manager_slot, request.amount);
} else if (request.kind == ui::BankRequestKind::buy_shares || request.kind == ui::BankRequestKind::sell_shares ||
request.kind == ui::BankRequestKind::stock_tip) {
if (request.asset_index < 0 || request.asset_index >= kStocks ||
g_.stocks.size() < size_t(kStocks) * 0x5c) { error = "invalid_stock"; return false; }
const size_t at = size_t(request.asset_index) * 0x5c;
const int price = int(uint16_t(g_.stocks.at(at + 0x4e) | uint16_t(g_.stocks.at(at + 0x4f)) << 8));
if (request.kind == ui::BankRequestKind::buy_shares) {
if (request.count <= 0 || request.count > 9999 || price <= 0 ||
request.count > max_shares_to_buy(g_, request.manager_slot, request.asset_index)) {
error = "invalid_share_count"; return false;
}
const int64_t raw = int64_t(price) * request.count;
const int64_t total = raw + raw * 15 / 1000;
if (total > int64_t(read_signed(0x314)) + read_signed(0x31c)) {
error = "insufficient_funds"; return false;
}
if (!buy_shares(g_, request.manager_slot, request.asset_index, request.count)) {
error = "investment_limit"; return false;
}
} else if (request.kind == ui::BankRequestKind::sell_shares) {
const size_t held_at = at + 0x50 + size_t(request.manager_slot) * 2;
const int held = int(uint16_t(g_.stocks.at(held_at) | uint16_t(g_.stocks.at(held_at + 1)) << 8));
if (request.count <= 0 || request.count > held) { error = "invalid_share_count"; return false; }
sell_shares(g_, request.manager_slot, request.asset_index, request.count);
} else {
if (request.count != 0 || request.amount != 0) { error = "invalid_tip_request"; return false; }
last_stock_tip_ = stock_tip(g_, request.manager_slot, request.asset_index, rand_);
}
} else if (request.kind == ui::BankRequestKind::buy_fund || request.kind == ui::BankRequestKind::sell_fund) {
if (request.amount != 0 || request.asset_index < 0 || request.asset_index >= kFunds || request.count <= 0 || request.count > 10 ||
g_.memory.u32(::bmh::layout::FundBlock + uint32_t(request.asset_index) * 0x1c) == 0) {
error = "invalid_fund_request"; return false;
}
const uint32_t fund_at = ::bmh::layout::FundBlock + uint32_t(request.asset_index) * 0x1c;
const uint16_t held = g_.memory.u16(fund_at + 0x14 + uint32_t(request.manager_slot) * 2);
if (request.kind == ui::BankRequestKind::buy_fund) {
if (request.count > max_fund_units(g_, request.manager_slot, request.asset_index)) {
error = "invalid_fund_count"; return false;
}
const int32_t additional_cost = buy_fund_units(g_, request.manager_slot, request.asset_index, request.count, game_);
if (request.asset_index != 0) {
const std::string text = message_text(g_, ::bmh::layout::CareerSession_Int32T_TextPointer2) + format_number(g_, additional_cost, 0x101) +
message_text(g_, ::bmh::layout::CareerSession_Int32T_TextPointer);
property_notice = ui::BankState::PropertyNotice{request.asset_index, additional_cost, ui::original_to_utf8(text)};
}
} else {
if (request.count > held) { error = "invalid_fund_count"; return false; }
sell_fund_units(g_, request.manager_slot, request.asset_index, request.count);
}
} else if (request.kind == ui::BankRequestKind::bank_credit) {
if (request.amount != 0 || request.asset_index != -1 || request.count != 0 || request.credit_edits.empty()) {
error = "invalid_credit_request"; return false;
}
if (request.credit_counterparty != 0) {
// Source case 5 scans configured human managers, excluding the borrower.
// A runtime national-manager entry is not an additional human lender.
const int configured = int(g_.memory.u8(::bmh::layout::ManagerCount));
if (request.credit_counterparty < 1 || request.credit_counterparty > 4) {
error = "invalid_credit_request"; return false;
}
const int lender = request.credit_counterparty - 1;
if (configured < 1 || configured > 4 || request.manager_slot >= configured ||
lender < 0 || lender >= configured || lender == request.manager_slot) {
error = "invalid_credit_request"; return false;
}
}
const auto result = commit_bank_credit(g_, exe_, request.manager_slot,
request.expected_credit, request.credit_edits, request.accept_credit_fees, request.credit_counterparty);
if (result.status != BankCreditStatus::accepted) {
error = result.status == BankCreditStatus::no_change ? "credit_no_change" :
result.status == BankCreditStatus::stale_request ? "stale_credit_request" :
result.status == BankCreditStatus::confirmation_required ? "credit_confirmation_required" :
"invalid_credit_request";
return false;
}
if (result.refund != 0) {
// "Die Bank" (CareerSession_Int32T_TextPointer3) or, in case 5, the lender's name (record +0xa8)
const int lender = request.credit_counterparty - 1;
std::string who = message_text(g_, ::bmh::layout::CareerSession_Int32T_TextPointer3);
if (lender >= 0) {
who.clear();
for (size_t i = 0; i < 26; ++i) {
const uint8_t ch = g_.manager_records.at(size_t(lender) * 0xb0c + 0xa8 + i);
if (!ch) break;
who += char(ch);
}
}
const std::string text = who + message_text(g_, ::bmh::layout::CareerSession_Int32T_TextPointer4) +
format_number(g_, result.refund, 0x101) + message_text(g_, ::bmh::layout::CareerSession_Int32T_TextPointer5);
credit_notice = ui::BankState::CreditNotice{result.refund, ui::original_to_utf8(text)};
}
} else {
error = "unsupported_bank_request"; return false;
}
last_property_notice_ = std::move(property_notice);
last_credit_notice_ = std::move(credit_notice);
++revision;
return true;
}
// True when a construction tip dialog is open and the process timer (when running) has no time
// left; read-only.
bool CareerSession::stadium_tip_deadline_expired() const {
if (!stadium_.opened || (!stadium_.tip &&
(!stadium_.block_expansion || !stadium_.block_expansion->tip))) return false;
const auto byte = [this](uint32_t address) {
if (g_.memory.has(address)) return g_.memory.u8(address);
const auto found = club_modal_runtime_.find(address);
return found == club_modal_runtime_.end() ? exe_.u8(address) : found->second;
};
const auto word = [&byte](uint32_t address) {
uint32_t value = 0;
for (unsigned i = 0; i < 4; ++i) value |= uint32_t(byte(address + i)) << (8 * i);
return value;
};
return word(::bmh::layout::CareerSession_DispatchStrengths_ExecutableField2) != 0 && int32_t(word(::bmh::layout::CareerSession_FormatError_ExecutableField2)) < 1;
}
// Stadium group: an owner (stadium_) is opened with a scope id and every later request must echo
// scope and sequence, the manager, club, stable club identity, game mode and revision. All
// actions (data page, periphery quote/build, block expansion editor with its tip, investments)
// run inside the apply lambda below; on failure the stadium checkpoint is restored, on success
// revision, sequence and the owner's revision advance. Exceptions restore the checkpoint and
// the revision and are rethrown. Short error codes in 'error' otherwise.
// Older periphery callers send no scope envelope; a compatibility step fills it in for their four
// original operations only.
bool CareerSession::dispatch_stadium(const ui::StadiumRequest& supplied_request, uint64_t& revision, std::string& error,
const ConstructionNoticeHook& notice_presenter,
const SeasonTicketCompensationNoticeHook& compensation_presenter) {
if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ ||
top_scorers_owner_ || top_scorers_dispatch_active_ || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; }
const int active = int(g_.memory.u8(::bmh::layout::ActiveManager));
auto request = supplied_request;
// Existing CLI periphery callers predate the UI scope envelope. Restrict
// this compatibility adapter to their four original operations and an
// entirely absent envelope; investments and close remain strictly owned.
const bool legacy_periphery = !request.stable_club_identity && request.scope == 0 && request.sequence == 0 &&
(request.kind == ui::StadiumRequestKind::open || request.kind == ui::StadiumRequestKind::quote_periphery ||
request.kind == ui::StadiumRequestKind::decline_periphery || request.kind == ui::StadiumRequestKind::build_periphery);
if (legacy_periphery && active >= 0 && active <= 3 && size_t(active) < g_.manager_teams.size() &&
request.runtime_club >= 0 && size_t(request.runtime_club) < g_.club_ids.size()) {
request.stable_club_identity = int(g_.club_ids[size_t(request.runtime_club)]);
if (request.kind != ui::StadiumRequestKind::open) {
request.scope = stadium_.scope; request.sequence = stadium_.sequence;
}
}
const bool block_action = is_block_expansion_action(request.kind);
if (!block_action && (request.block_slot != -1 || request.block_total_places != 0 ||
request.block_features != 0 || request.expected_block_quote)) {
error = "unexpected_block_expansion_fields"; return false;
}
if (request.manager_slot != active || active < 0 || active > 3 ||
size_t(active) >= g_.manager_teams.size() || request.runtime_club != g_.manager_teams[size_t(active)] ||
request.runtime_club < 0 || request.runtime_club >= 357 ||
size_t(request.runtime_club) >= g_.club_ids.size() ||
request.stable_club_identity != std::optional<int>(int(g_.club_ids[size_t(request.runtime_club)])) ||
request.revision != revision || revision == UINT64_MAX || !g_.memory.has(::bmh::layout::GameMode)) {
error = "stale_manager_or_revision"; return false;
}
const size_t record = size_t(active) * 0xb0c;
if (record + 0xb0c > g_.manager_records.size() ||
(int(g_.manager_records[record + 0x290]) | int(g_.manager_records[record + 0x291]) << 8) != request.runtime_club) {
error = "invalid_stadium_owner"; return false;
}
const int mode = g_.memory.u8(::bmh::layout::GameMode);
if (mode < 1 || mode > 3) { error = "invalid_stadium_mode"; return false; }
if (request.kind == ui::StadiumRequestKind::open) {
const bool legacy_reentry = legacy_periphery && !stadium_.data_open && !stadium_.investment && !stadium_.tip &&
!stadium_.block_expansion;
if ((stadium_.opened && !legacy_reentry) || request.scope != 0 || request.sequence != 0 || request.object != -1 ||
request.option != -1 || request.price != 0 || request.accept_tip || next_stadium_scope_ == UINT64_MAX) {
error = "invalid_stadium_open"; return false;
}
} else if (!stadium_.opened || stadium_.manager != active || stadium_.club != request.runtime_club ||
stadium_.stable_club != *request.stable_club_identity || stadium_.mode != mode ||
stadium_.revision != revision || request.scope != stadium_.scope ||
request.sequence != stadium_.sequence || stadium_.sequence == UINT64_MAX) {
error = "stale_stadium_scope"; return false;
}
auto before = stadium_checkpoint();
const uint64_t before_revision = revision;
try {
// Performs the validated stadium action and returns true on success; 'invalid' records the
// reason and returns false.
const auto apply = [&]() -> bool {
const auto invalid = [&error](const char* reason) { error = reason; return false; };
const auto plain = [&request](int object = -1) {
return request.object == object && request.option == -1 && request.price == 0 && !request.accept_tip;
};
const auto clear_investment = [this] {
stadium_.investment.reset(); stadium_.selection_status.reset(); stadium_.option.reset(); stadium_.tip.reset();
stadium_.option_index = -1; stadium_.text_variant = -1;
};
StadiumInvestmentConstants constants;
for (unsigned i = 0; i < 8; ++i) {
constants.price[i] = exe_.u32(::bmh::layout::CareerSession_DispatchStadium_RuntimeField + i * 4);
constants.weeks[i] = exe_.u8(::bmh::layout::CareerSession_DispatchStadium_RuntimeField2 + (14 + i) * 5);
}
const auto options = [&](StadiumInvestment investment) {
return stadium_investment_options_source(g_, active, investment, stadium_.price_percent, constants);
};
const auto selected_valid = [&]() {
if (!stadium_.investment || !stadium_.option || stadium_.option_index < 0) return false;
const auto current = options(*stadium_.investment);
return size_t(stadium_.option_index) < current.size() &&
current[size_t(stadium_.option_index)] == *stadium_.option;
};
if (request.kind == ui::StadiumRequestKind::open) {
StadiumRuntime opened;
opened.opened = true; opened.manager = active; opened.club = request.runtime_club;
opened.stable_club = *request.stable_club_identity; opened.mode = mode;
opened.scope = next_stadium_scope_++;
opened.price_percent = construction_price_percent(g_, active, game_);
if (opened.price_percent < 1 || opened.price_percent > 427) return invalid("invalid_stadium_discount");
stadium_ = std::move(opened);
return true;
}
if (request.kind == ui::StadiumRequestKind::close) {
if (stadium_.data_open || !plain() || stadium_.investment || stadium_.periphery_quote || stadium_.tip ||
stadium_.block_expansion)
return invalid("invalid_stadium_close");
stadium_.opened = false; stadium_.periphery_quote.reset(); clear_investment();
stadium_.feedback.clear(); return true;
}
const bool data_action = request.kind == ui::StadiumRequestKind::open_data ||
request.kind == ui::StadiumRequestKind::toggle_data_curve ||
request.kind == ui::StadiumRequestKind::toggle_data_scale ||
request.kind == ui::StadiumRequestKind::set_data_ticket_price ||
request.kind == ui::StadiumRequestKind::close_data;
if (data_action) {
if (stadium_.investment || stadium_.periphery_quote || stadium_.tip || stadium_.block_expansion ||
request.option != -1 || request.price != 0 || request.accept_tip)
return invalid("invalid_stadium_data_context");
if (request.kind == ui::StadiumRequestKind::open_data) {
if (stadium_.data_open || request.object != -1) return invalid("invalid_stadium_data_open");
const uint32_t flags_at = ::bmh::layout::Flags + uint32_t(active) * 3 + 1;
if (!g_.memory.has(flags_at)) return invalid("missing_stadium_data_flags");
stadium_.data_flags = g_.memory.u8(flags_at);
// Build the pure projection before accepting modal ownership.
(void)ui::stadium_data_from_game(g_, exe_, active, stadium_.data_flags);
stadium_.data_open = true;
} else {
if (!stadium_.data_open) return invalid("stadium_data_not_open");
if (request.kind == ui::StadiumRequestKind::toggle_data_curve) {
if (request.object < 0 || request.object > 5) return invalid("invalid_stadium_data_curve");
stadium_.data_flags ^= uint8_t(1u << request.object);
} else if (request.kind == ui::StadiumRequestKind::toggle_data_scale) {
if (request.object < 0 || request.object > 1) return invalid("invalid_stadium_data_scale");
stadium_.data_flags ^= 0xc0; // Either ABS or REL button toggles both Source bits.
} else if (request.kind == ui::StadiumRequestKind::set_data_ticket_price) {
if (request.object < 10 || request.object > 25) return invalid("invalid_stadium_data_ticket");
g_.manager_records[record + 0x26e] = uint8_t(request.object);
(void)ui::stadium_data_from_game(g_, exe_, active, stadium_.data_flags);
} else {
if (request.object != -1) return invalid("invalid_stadium_data_close");
g_.memory.set8(::bmh::layout::Flags + uint32_t(active) * 3 + 1, stadium_.data_flags);
stadium_.data_open = false;
}
}
stadium_.feedback.clear();
return true;
}
if (stadium_.data_open) return invalid("stadium_data_active");
if (mode == 1 && !legacy_periphery &&
(request.kind == ui::StadiumRequestKind::quote_periphery ||
request.kind == ui::StadiumRequestKind::build_periphery ||
request.kind == ui::StadiumRequestKind::decline_periphery))
return invalid("stadium_periphery_disabled");
if (request.kind == ui::StadiumRequestKind::quote_periphery) {
if (stadium_.investment || stadium_.periphery_quote || stadium_.block_expansion || request.object < 0 ||
request.object >= 14 || !plain(request.object)) return invalid("invalid_periphery_offer");
const size_t object = size_t(request.object);
const uint8_t level = g_.manager_records[record + object];
if (g_.manager_records[record + 0x1e + object] != 0 || (object == 0 ? level >= 0xab : level != 0))
return invalid("periphery_unavailable");
const int32_t price = periphery_offer(g_, request.object, game_);
if (price <= 0) return invalid("invalid_periphery_price");
stadium_.periphery_quote = std::make_pair(request.object, price);
stadium_.feedback.clear(); return true;
}
if (request.kind == ui::StadiumRequestKind::decline_periphery ||
request.kind == ui::StadiumRequestKind::build_periphery) {
if (stadium_.investment || stadium_.block_expansion || !stadium_.periphery_quote ||
request.option != -1 || request.accept_tip ||
request.object != stadium_.periphery_quote->first || request.price != stadium_.periphery_quote->second)
return invalid("stale_periphery_offer");
if (request.kind == ui::StadiumRequestKind::build_periphery) {
const size_t object = size_t(request.object);
const uint8_t level = g_.manager_records[record + object];
if (g_.manager_records[record + 0x1e + object] != 0 || (object == 0 ? level >= 0xab : level != 0))
return invalid("periphery_unavailable");
// ConstructionPricePercent consumes this genuine JA even when PayConstruction's
// payment fails. The Source presenter runs before the quote
// is cleared; payment/sponsor effects are not rolled back.
const bool built = build_periphery(g_, active, request.object,
uint32_t(request.price), rand_, notice_presenter);
stadium_.feedback = built || notice_presenter ? std::string{} : message_text(g_, ::bmh::layout::Advertising_FormatError_TextPointer18);
}
stadium_.periphery_quote.reset();
if (request.kind == ui::StadiumRequestKind::decline_periphery) stadium_.feedback.clear();
return true;
}
// A–H uses its own quote/commit domain and remains available in
// Source mode 1, where facilities are disabled. All request fields
// outside the typed block envelope must stay neutral.
if (block_action) {
if (request.object != -1 || request.option != -1 || request.price != 0 ||
(request.kind != ui::StadiumRequestKind::expansion_answer_tip && request.accept_tip))
return invalid("invalid_block_expansion_envelope");
const auto block_constants=stadium_block_expansion_constants(exe_);
const auto quote_block = [&](StadiumBlockSlot slot, uint32_t total, uint8_t features) {
return quote_stadium_block_expansion(g_, active, slot, total, features,
stadium_.price_percent, block_constants);
};
if (request.kind == ui::StadiumRequestKind::expansion_select) {
if (stadium_.investment || stadium_.periphery_quote || stadium_.block_expansion ||
request.block_slot < 0 || request.block_slot >= 8 || request.block_total_places != 0 ||
request.block_features != 0 || request.expected_block_quote)
return invalid("invalid_block_expansion_selection");
const auto slot = static_cast<StadiumBlockSlot>(request.block_slot);
const uint8_t raw = g_.manager_records.at(record + 0x44 + size_t(request.block_slot));
const uint32_t current = uint32_t(g_.manager_records.at(record + 0x4c + size_t(request.block_slot))) * 1000;
auto quote = quote_block(slot, current, uint8_t(raw & kBlockFeatures));
if (!quote) return invalid("block_expansion_unavailable");
StadiumRuntime::BlockExpansion draft;
draft.quote = *quote;
draft.total_target_places = current;
draft.desired_features = uint8_t(raw & kBlockFeatures);
game_.set_seed(int32_t(g_.memory.u32(::bmh::layout::CareerSession_Invalid_RuntimeField2)));
draft.header_text_variant = game_.range(3, 10); // Front, once on editor entry.
stadium_.block_expansion = std::move(draft);
stadium_.feedback.clear();
return true;
}
if (!stadium_.block_expansion || stadium_.investment || stadium_.periphery_quote ||
request.block_slot < 0 || request.block_slot >= 8 ||
request.block_slot != int(stadium_.block_expansion->quote.slot) ||
!request.expected_block_quote || *request.expected_block_quote != stadium_.block_expansion->quote)
return invalid("stale_block_expansion_quote");
auto& draft = *stadium_.block_expansion;
if (draft.tip) {
const auto& tip = *draft.tip;
const bool valid_tip = tip.decision == StandBlockOfferDecision::Pending &&
tip.base_price == draft.quote.base_price && tip.base_days == draft.quote.base_weeks &&
tip.price == tip.base_price && tip.percent >= 6 && tip.percent <= 14 &&
tip.offered_price == uint32_t(uint64_t(tip.base_price) * uint32_t(100 + tip.percent) / 100);
if (!valid_tip) return invalid("stale_block_expansion_tip");
}
auto fresh = quote_block(draft.quote.slot, draft.total_target_places, draft.desired_features);
if (!fresh || *fresh != draft.quote)
return invalid("block_expansion_source_changed");
const auto matches_draft = [&] {
return request.block_total_places == draft.total_target_places &&
request.block_features == draft.desired_features;
};
switch (request.kind) {
case ui::StadiumRequestKind::expansion_set_total: {
if (draft.tip || request.block_features != draft.desired_features)
return invalid("stale_block_expansion_draft");
auto next_quote = quote_block(draft.quote.slot, request.block_total_places, draft.desired_features);
if (!next_quote) return invalid("invalid_block_expansion_total");
draft.total_target_places = request.block_total_places;
draft.quote = *next_quote;
stadium_.feedback.clear();
return true;
}
case ui::StadiumRequestKind::expansion_toggle_feature: {
const uint8_t changed = uint8_t(request.block_features ^ draft.desired_features);
if (draft.tip || request.block_total_places != draft.total_target_places ||
(request.block_features & uint8_t(~kBlockFeatures)) != 0 ||
(changed != kBlockSeat && changed != kBlockRoof) ||
(request.block_features & uint8_t(draft.quote.current_raw_flags & kBlockFeatures)) !=
uint8_t(draft.quote.current_raw_flags & kBlockFeatures))
return invalid("invalid_block_expansion_feature");
auto next_quote = quote_block(draft.quote.slot, draft.total_target_places, request.block_features);
if (!next_quote) return invalid("invalid_block_expansion_feature");
draft.desired_features = request.block_features;
draft.quote = *next_quote;
stadium_.feedback.clear();
return true;
}
case ui::StadiumRequestKind::expansion_cancel:
if (draft.tip || !matches_draft()) return invalid("stale_block_expansion_cancel");
stadium_.block_expansion.reset();
stadium_.feedback.clear();
return true;
case ui::StadiumRequestKind::expansion_confirm: {
if (draft.tip || !matches_draft()) return invalid("stale_block_expansion_confirm");
if (draft.quote.base_price == 0) {
stadium_.block_expansion.reset();
stadium_.feedback.clear();
return true;
}
auto tip = prepare_stand_block_offer(draft.quote.base_price, draft.quote.base_weeks, rand_);
if (tip.offered_price > uint32_t(INT32_MAX))
return invalid("block_expansion_tip_price_overflow");
draft.tip = tip;
stadium_.feedback.clear();
return true;
}
case ui::StadiumRequestKind::expansion_answer_tip: {
if (!draft.tip || !matches_draft() || request.accept_tip &&
uint64_t(draft.tip->base_price) * uint32_t(100 + draft.tip->percent) >
uint64_t(INT32_MAX))
return invalid("invalid_block_expansion_tip_answer");
StandBlockOffer resolved = *draft.tip;
resolve_stand_block_offer(resolved, request.accept_tip, rand_);
const bool built = build_stadium_block_expansion(g_, active, draft.quote.slot,
block_constants, draft.quote, resolved, rand_, notice_presenter, compensation_presenter);
stadium_.block_expansion.reset();
stadium_.feedback = built || notice_presenter ? std::string{} : message_text(g_, ::bmh::layout::Advertising_FormatError_TextPointer18);
return true;
}
default:
return invalid("unsupported_block_expansion_request");
}
}
if (mode == 1) return invalid("stadium_investments_disabled");
if (request.kind == ui::StadiumRequestKind::select_investment) {
if (stadium_.investment || stadium_.periphery_quote || stadium_.block_expansion || request.object < 0 ||
request.object >= 8 || !plain(request.object)) return invalid("invalid_investment_selection");
const auto investment = static_cast<StadiumInvestment>(request.object);
const auto current = options(investment);
if (current.empty()) return invalid("investment_unavailable");
game_.set_seed(int32_t(g_.memory.u32(::bmh::layout::CareerSession_Invalid_RuntimeField2)));
stadium_.text_variant = game_.range(3, 10); // Front: exactly once at dialog entry.
stadium_.investment = investment; stadium_.selection_status = current.front().current_status;
stadium_.option_index = -1; stadium_.option.reset(); // Source iVar5=-1 until an explicit tier click.
stadium_.feedback.clear(); return true;
}
if (request.kind == ui::StadiumRequestKind::cancel_investment) {
if (!stadium_.investment || stadium_.tip || !plain(int(*stadium_.investment)))
return invalid("stale_investment_selection");
clear_investment(); stadium_.feedback.clear(); return true; // Initial Abbruch precedes W(6,14).
}
if (request.kind == ui::StadiumRequestKind::select_investment_option) {
if (!stadium_.investment || stadium_.tip || request.object != int(*stadium_.investment) ||
request.option < 0 || request.accept_tip || !stadium_.selection_status ||
g_.manager_records[record + 0x3c + size_t(*stadium_.investment)] != *stadium_.selection_status)
return invalid("stale_investment_selection");
const auto current = options(*stadium_.investment);
if (size_t(request.option) >= current.size() || request.price != int32_t(current[size_t(request.option)].base_price))
return invalid("stale_investment_price");
stadium_.option_index = request.option; stadium_.option = current[size_t(request.option)];
return true; // Pure tier choice: neither Source generator advances.
}
if (request.kind == ui::StadiumRequestKind::confirm_investment) {
if (stadium_.tip || !selected_valid() || request.object != int(*stadium_.investment) ||
request.option != stadium_.option_index || request.accept_tip ||
request.price != int32_t(stadium_.option->base_price)) return invalid("stale_investment_selection");
stadium_.tip = prepare_stand_block_offer(stadium_.option->base_price, stadium_.option->base_weeks, rand_);
if (stadium_.tip->offered_price > uint32_t(INT32_MAX)) return invalid("invalid_investment_tip_price");
return true;
}
if (request.kind == ui::StadiumRequestKind::answer_construction_tip) {
if (!stadium_.tip || !selected_valid() || request.object != int(*stadium_.investment) ||
request.option != stadium_.option_index || request.price != int32_t(request.accept_tip ?
stadium_.tip->offered_price : stadium_.tip->base_price)) return invalid("stale_construction_tip");
auto resolved = *stadium_.tip;
resolve_stand_block_offer(resolved, request.accept_tip, rand_);
const bool built = build_stadium_investment_source(g_, active, *stadium_.investment,
stadium_.price_percent, constants, *stadium_.option, resolved, rand_, notice_presenter);
// A genuine PayConstruction/BookMoney2 refusal consumes the answer and
// retains the sponsor share clearing and Source W draws.
// Interactive callers have already shown Source's timed funds
// notice; headless legacy callers retain their text feedback.
clear_investment();
stadium_.feedback = built || notice_presenter ? std::string{} : message_text(g_, ::bmh::layout::Advertising_FormatError_TextPointer18);
return true;
}
return invalid("unsupported_stadium_request");
};
if (!apply()) { restore_stadium_checkpoint(std::move(before)); return false; }
++revision; ++stadium_.sequence; stadium_.revision = revision;
error.clear(); return true;
} catch (...) {
restore_stadium_checkpoint(std::move(before)); revision = before_revision; throw;
}
}
// Submits a pools coupon for the active manager; only valid when the coupon has eleven matches.
// Revision plus one; false with a short error code otherwise.
bool CareerSession::dispatch_toto(const ui::TotoRequest& request, uint64_t& revision, std::string& error) {
if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ ||
top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return false; }
const int active = int(g_.memory.u8(::bmh::layout::ActiveManager));
if (request.kind != ui::TotoRequestKind::submit || request.manager_slot != active || request.manager_slot < 0 ||
size_t(request.manager_slot) >= g_.manager_teams.size() ||
request.runtime_club != g_.manager_teams[size_t(request.manager_slot)] || request.revision != revision) {
error = "stale_manager_or_revision"; return false;
}
if (g_.memory.u8(::bmh::layout::CareerSession_DispatchToto_RuntimeField) != 11) { error = "toto_coupon_requires_eleven_matches"; return false; }
if (!submit_pools_coupon(g_, request.manager_slot, request.stake, request.tips)) {
error = "invalid_toto_coupon"; return false;
}
++revision;
return true;
}
} // namespace bmh::app
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+669
View File
@@ -0,0 +1,669 @@
// SPDX-License-Identifier: GPL-3.0-only
// CareerSession: transfers: offer editor, poaching, transfer market.
// (moved out of career_session.cpp unchanged; the class is declared in app/career_session.hpp)
#include "app/career_session_internal.hpp"
namespace bmh::app {
namespace {
// Transfer editor / market group (helpers first). Projects the engine's transfer offer editor
// owner into the UI state: the quote fields, calculator profiles and, unless the editor is
// closed, the incoming-offer decision panel read from the four offer rows of the market list.
ui::OutgoingTransferEditorState transfer_offer_projection(const GameState& game,
const TransferOfferEditorState& owner, uint64_t revision, bool gradient) {
ui::OutgoingTransferEditorState out;
const auto& request = owner.request;
out.manager_slot = request.manager; out.runtime_club = request.runtime_club;
out.revision = revision; out.list_entry = request.list_entry; out.source_slot = request.source_slot;
out.player = request.expected_player;
out.seller = request.expected_seller_word == 0xffff ? 0x0fff : request.expected_seller_word & 0x7fff;
out.bid_slot = owner.bid_slot; out.source_mode = owner.mode;
out.editable = owner.editable; out.closed = owner.closed; out.quote_loan = owner.quote_loan;
out.initial_action_loan = request.loan;
out.gradient_text = gradient;
out.fee = owner.fee; out.monthly_salary = owner.salary; out.duration_years = owner.years;
out.bonuses = owner.bonuses;
const auto copy_profile = [](const TransferOfferInputProfile& p) {
return ui::OutgoingTransferCalculatorProfile{p.supported, p.currency, p.minimum, p.maximum,
p.initial, p.source_text_address, p.presets};
};
for (size_t n = 0; n < 2; ++n) out.money_calculators[n] = copy_profile(owner.money_profiles[n]);
for (size_t n = 0; n < 8; ++n) out.mode3_calculators[n] = copy_profile(owner.mode3_profiles[n]);
if (owner.closed) return out; // No modal is constructed after Source cleanup.
ui::IncomingTransferDecisionView view;
view.source_outgoing_editor_context = true;
view.valid = true; view.list_entry = request.list_entry; view.player = out.player;
view.seller = out.seller; view.seller_manager = out.seller == 0x0fff ? -1 : game.manager_of(out.seller);
view.viewer_manager = request.manager;
view.asking_fee = owner.asking_fee; view.asking_monthly_salary = owner.asking_salary;
view.quoted_fee = owner.quoted_fee; view.quoted_monthly_salary = owner.quoted_salary;
view.quoted_years = owner.years;
const uint32_t list = ::bmh::layout::EditorList + uint32_t(request.list_entry) * 0x58;
for (uint32_t n = 0; n < 4; ++n) {
auto& row = view.offers[n];
const auto buyer = game.memory.u16(list + n * 2);
row.bid_index = int(n); row.present = buyer != 0xffff;
row.buyer = row.present ? int(buyer) : -1;
row.buyer_manager = row.present ? game.manager_of(row.buyer) : -1;
row.fee = game.memory.u32(list + 0x1c + n * 4);
row.monthly_salary = game.memory.u32(list + 0x0c + n * 4);
const auto raw_term = game.memory.u8(list + 0x34 + n);
row.loan = (raw_term & 0x80) != 0; row.contract_months = raw_term & 0x7f;
row.eligible = row.present;
for (uint32_t k = 0; k < 7; ++k) row.bonuses[k] = game.memory.u8(list + 0x38 + n * 7 + k);
}
out.panel = ui::incoming_transfer_decision_from_game(game, view);
return out;
}
} // namespace
// Public wrapper so other code (loan return offers) can reuse the editor projection.
ui::OutgoingTransferEditorState loan_return_offer_editor_projection(
const GameState& game, const TransferOfferEditorState& owner, uint64_t revision, bool gradient) {
return transfer_offer_projection(game, owner, revision, gradient);
}
// Maps a UI field edit onto the engine's transfer offer editor edit and returns the new owner.
TransferOfferEditorState edit_transfer_offer_from_ui(GameState& game,
const TransferOfferEditorState& owner, const ui::OutgoingTransferRequest& request,
GameRandom& game_random, WatcomRandom& watcom_random) {
return edit_transfer_offer_editor_source(game, owner,
{TransferOfferEditorField(uint8_t(request.field)), request.value, request.accepted},
game_random, watcom_random);
}
// Transfer market request family (open offer, poach, editor events, quote preview, market
// actions): each entry validates the request revision, the active manager slot and the manager's
// club, refuses nested modals (market_dispatch_active_ and the other owners), works on copies of
// the state and both random generators and commits them only on success. The revision is
// advanced only where something observable changed. Failures return an empty optional and an
// error text.
// Opens the buyer's offer editor for a marked market row after checking the row identity
// against the market list in memory; the editor owner and its revision are stored on success.
std::optional<CareerSession::TransferOfferEditorDispatch> CareerSession::open_transfer_offer(
const ui::TransferMarketRequest& request, uint64_t& revision, std::string& error) {
if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ ||
top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; }
error.clear();
if (request.kind != ui::TransferMarketRequestKind::open_offer || transfer_offer_editor_ ||
market_dispatch_active_ || pending_offer_dispatch_active_ || calendar_advance_active_ ||
request.revision != revision || revision == std::numeric_limits<uint64_t>::max() ||
request.manager_slot < 0 || request.manager_slot >= 4 ||
size_t(request.manager_slot) >= g_.manager_teams.size() ||
!g_.memory.has(::bmh::layout::ActiveManager) || g_.memory.u8(::bmh::layout::ActiveManager) != request.manager_slot ||
request.runtime_club != g_.manager_teams[size_t(request.manager_slot)] ||
request.bid.manager != request.manager_slot || request.bid.list_entry < 0 || request.bid.list_entry >= 40 ||
request.bid.source_slot != 2928 + request.bid.list_entry || request.selected_players.size() > 1) {
error = "transfer offer: stale, nested or unsupported marked opening";
return std::nullopt;
}
const uint32_t list = ::bmh::layout::EditorList + uint32_t(request.bid.list_entry) * 0x58;
if (!g_.memory.has(list + 0x57)) { error = "transfer offer: missing Native list row"; return std::nullopt; }
const uint16_t seller_word = g_.memory.u16(list + 8);
if (!request.selected_players.empty()) {
const auto& selected = request.selected_players.front();
const int seller = seller_word == 0xffff ? -1 : int(seller_word & 0x7fff);
if (selected.squad_row != -1 || selected.source_slot != request.bid.source_slot ||
selected.list_entry != request.bid.list_entry || selected.player != request.bid.player ||
selected.seller != seller) {
error = "transfer offer: selected row does not match the Native market identity";
return std::nullopt;
}
}
int bid_slot = -1;
for (int n = 0; n < 4; ++n) {
const auto buyer = g_.memory.u16(list + uint32_t(n) * 2);
if (buyer == 0xffff || buyer == request.runtime_club) { bid_slot = n; break; }
}
const TransferOfferEditorRequest input{request.manager_slot, request.runtime_club, request.bid.list_entry,
request.bid.source_slot, request.bid.player, seller_word, bid_slot, request.offer_is_loan};
auto next_state = g_; auto next_game = game_; auto next_rand = rand_;
market_dispatch_active_ = true;
struct Reset { bool& active; ~Reset() { active = false; } } reset{market_dispatch_active_};
try {
auto owner = open_transfer_offer_editor_source(next_state, input, next_game, next_rand);
if (!owner.supported) { error = owner.reason; return std::nullopt; }
// Opening has Source G-seeding/G92..108 even for a full read-only list.
const auto next_revision = revision + 1;
TransferOfferEditorDispatch result;
result.preparation = preparation_projection(next_state, next_revision);
result.editor = transfer_offer_projection(next_state, owner, next_revision, result.preparation.desktop.gradient_text);
ui::OutgoingTransferScreen validate(data_directory_, result.editor);
g_ = std::move(next_state); game_ = next_game; rand_ = next_rand;
transfer_offer_editor_ = std::move(owner); transfer_offer_revision_ = next_revision; revision = next_revision;
return result;
} catch (const std::exception& e) { error = e.what(); return std::nullopt; }
}
// Starts a poaching attempt for a squad slot: the attempt draws random numbers, so the revision
// advances whenever the result is not invalid; a ready attempt also opens the offer editor on
// the special poach row and remembers the attempt in poach_.
std::optional<CareerSession::PoachDispatch> CareerSession::open_poach(
int manager_slot, int squad_slot, uint64_t& revision, std::string& error) {
if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ ||
top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; }
error.clear();
if (transfer_offer_editor_ || market_dispatch_active_ || pending_offer_dispatch_active_ || calendar_advance_active_ ||
revision == std::numeric_limits<uint64_t>::max() || manager_slot < 0 || manager_slot >= 4 ||
size_t(manager_slot) >= g_.manager_teams.size() || !g_.memory.has(::bmh::layout::ActiveManager) ||
g_.memory.u8(::bmh::layout::ActiveManager) != manager_slot) {
error = "poach: stale, nested or unsupported opening";
return std::nullopt;
}
auto next_state = g_; auto next_game = game_; auto next_rand = rand_;
market_dispatch_active_ = true;
struct Reset { bool& active; ~Reset() { active = false; } } reset{market_dispatch_active_};
try {
PoachDispatch result;
result.start = start_poach(next_state, manager_slot, squad_slot, next_rand);
if (result.start.status == PoachStatus::ready) {
const int row = 0x28 + result.start.offer_row;
const TransferOfferEditorRequest input{manager_slot, g_.manager_teams[size_t(manager_slot)], row, 2928 + row,
result.start.player, next_state.memory.u16(::bmh::layout::EditorList + uint32_t(row) * 0x58 + 8), 0, false, true};
auto owner = open_transfer_offer_editor_source(next_state, input, next_game, next_rand);
if (!owner.supported) { error = owner.reason; return std::nullopt; }
const auto next_revision = revision + 1;
TransferOfferEditorDispatch editor;
editor.preparation = preparation_projection(next_state, next_revision);
editor.editor = transfer_offer_projection(next_state, owner, next_revision, editor.preparation.desktop.gradient_text);
result.editor = std::move(editor);
transfer_offer_editor_ = std::move(owner);
transfer_offer_revision_ = next_revision;
poach_ = result.start;
revision = next_revision;
} else if (result.start.status != PoachStatus::invalid) {
++revision; // draws, and "Transfermarkt überlastet" counts the attempt
}
g_ = std::move(next_state); game_ = next_game; rand_ = next_rand;
return result;
} catch (const std::exception& e) { error = e.what(); return std::nullopt; }
}
// Closes the table opened only to choose a poach target: needs an unchanged table owner, then
// restores the display word and drops the family owner without a family close. False with
// 'error' if stale.
bool CareerSession::close_poach_table_selection(const ui::LeagueFamilyRequest& request,std::string& error) {
error.clear();
if(!poach_table_selection_ || request.kind!=ui::LeagueFamilyRequestKind::close || request.from_child!=1 ||
!canonical_table_envelope(request) || !league_family_owner_ || league_family_owner_->child!=1 ||
league_family_owner_->identity!=request.identity || !league_family_owner_->table ||
league_family_owner_->table->phase!=TableDispatchPhase::ready ||
save_stream(g_)!=league_family_owner_->native || club_modal_runtime_!=league_family_owner_->runtime ||
game_.seed()!=league_family_owner_->game_seed || game_.calls()!=league_family_owner_->game_calls ||
rand_.seed()!=league_family_owner_->rand_seed || rand_.calls()!=league_family_owner_->rand_calls) {
error="poach: stale Table selection close";return false;
}
const uint32_t at=::bmh::layout::LeagueTableDisplayModes+uint32_t(request.identity.manager)*2;
uint16_t word=uint16_t(g_.memory.u16(at)&0x0f7f);
if(source_runtime_byte(g_,club_modal_runtime_,exe_,::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField)!=0)word|=0x80;
g_.memory.set16(at,word);
if(g_.memory.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2))g_.memory.set8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2,0);else club_modal_runtime_[::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2]=0;
// FriendlyMatchScreen returns directly to19c1c. No21213 family close.
league_family_owner_.reset();return true;
}
// Poach flow driven by UI callbacks: checks the request is a pristine open_poach request of the
// current revision (320x240 backdrop, nothing else open), then reports attempts-used or
// transfer-ban notices, or lets the player pick a squad player in a table on a cloned session
// and opens the poach from that choice. The UI acknowledges through 'accept'; any failure,
// including a session changed by the acknowledgement, restores the checkpoint and revision.
bool CareerSession::dispatch_poach_ui(const ui::TransferMarketRequest& request,
const Image& backdrop, const PoachPlayerSelector& select, const PoachUiAccept& accept,
uint64_t& revision, std::string& error) {
error.clear();
if (!accept || request.kind!=ui::TransferMarketRequestKind::open_poach ||
!g_.memory.has(::bmh::layout::GameMode) || g_.memory.u8(::bmh::layout::GameMode)!=3 ||
request.revision!=revision || revision==UINT64_MAX || request.manager_slot<0 || request.manager_slot>3 ||
!g_.memory.has(::bmh::layout::ActiveManager) || g_.memory.u8(::bmh::layout::ActiveManager)!=request.manager_slot ||
size_t(request.manager_slot)>=g_.manager_teams.size() ||
request.runtime_club!=g_.manager_teams[size_t(request.manager_slot)] ||
request.bid.manager!=request.manager_slot || request.bid.list_entry!=-1 || request.bid.player!=-1 ||
request.bid.source_slot!=-1 || request.bid.fee!=0 || request.bid.annual_salary!=0 ||
request.bid.contract_years!=1 || request.bid.poach || std::any_of(request.bid.bonuses.begin(),request.bid.bonuses.end(),
[](uint32_t n){return n!=0;}) || request.squad_row!=-1 || request.expected_player!=-1 ||
request.preview_source_slot!=-1 || request.preview_seller!=-1 || request.preview_is_purchase ||
request.preview_is_loan || !request.selected_players.empty() ||
backdrop.width!=320 || backdrop.height!=240 || advertising_renewal_dispatch_active_ || pending_offer_dispatch_active_ || market_dispatch_active_ ||
calendar_advance_active_ || transfer_offer_editor_ || poach_ || manager_join_ || contract_quote_ ||
league_family_owner_ || league_pairings_draft_ || strengths_owner_ || top_scorers_owner_ ||
other_games_owner_ || balance_draft_ || stadium_.opened ||
(turn_driver_.stage!=TurnDriver::Stage::MatchdayDesks && turn_driver_.stage!=TurnDriver::Stage::SeasonEndDesk)) {
error="poach: stale or competing selection";return false;
}
const auto checkpoint=advertising_session_checkpoint(revision);
try {
const int manager=request.manager_slot;
const size_t record=size_t(manager)*0xb0c;
PoachDispatch result;
result.start.manager=manager;
// These three notices precede the Table modal in Reset.
if (record+0x8c0>g_.manager_records.size()) throw FormatError("poach: missing manager record");
const bool attempts_used=(g_.manager_records[record+0x8be] |
uint16_t(g_.manager_records[record+0x8bf])<<8)!=0xffff;
if(attempts_used) {
result.start.status=PoachStatus::attempts_used;
result.start.messages.push_back(message_text(g_,::bmh::layout::CareerSession_DispatchPoachUi_TextPointer2));
} else if(g_.manager_records[record+0x220]>>5==1) {
result.start.status=PoachStatus::transfer_ban;
result.start.messages.push_back(message_text(g_,::bmh::layout::CareerSession_DispatchPoachUi_TextPointer));
} else if(request.offer_is_loan) {
auto services=staged_club_modal_services(g_,game_,rand_,club_modal_runtime_);
services.set_runtime_byte(::bmh::layout::CareerSession_AdvertisingSessionUnchanged_ExecutableField,0);
services.set_runtime_byte(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField2,g_.manager_records[record+0x210]);
services.set_runtime_byte(::bmh::layout::CareerSession_DispatchPoachUi_ExecutableField,2);
result.start.messages.push_back(message_text(g_,::bmh::layout::CareerSession_DispatchPoachUi_TextPointer3));
} else {
if(!select) throw FormatError("poach: Source player selection presenter unavailable");
// The cloned Session owns the existing50775 controls implementation.
// begin_league_family(child1) itself does not call53435; only the
// host Table owner is reused, never prepare/close-family effects.
CareerSession staged=*this;
staged.poach_table_selection_=true;
uint64_t selection_revision=revision;
auto services=staged.staged_club_modal_services(staged.g_,staged.game_,staged.rand_,staged.club_modal_runtime_);
services.set_runtime_byte(::bmh::layout::CareerSession_AdvertisingSessionUnchanged_ExecutableField,0);
services.set_runtime_byte(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_RuntimeField2,g_.manager_records[record+0x210]);
services.set_runtime_byte(::bmh::layout::CareerSession_DispatchPoachUi_ExecutableField,2);
services.set_runtime_byte(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField,0);services.set_runtime_byte(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2,0);
//50775 control7 toggles this existing BSS byte. Materialize its
// actual current value in the staged runtime, including when it
// was read from the executable rather than persisted in Native.
services.set_runtime_byte(::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField,services.runtime_byte(::bmh::layout::CareerSession_AdvanceLeagueFamily_ExecutableField));
auto entry=staged.strengths_open_request(selection_revision);
if(!entry)throw FormatError("poach: missing Table selection identity");
entry->identity.league=g_.manager_records[record+0x210];entry->identity.league_group=0;
if(!staged.begin_league_family(entry->identity,1,selection_revision,error))throw FormatError(error);
market_dispatch_active_=true;
const auto live_baseline=advertising_session_checkpoint(revision);
const auto selection=select(staged,services,manager,selection_revision,backdrop);
if(!advertising_session_unchanged(live_baseline,revision))
throw FormatError("poach: selection changed the live session");
auto& next=staged.g_;
if(next.date!=g_.date || next.manager_teams!=g_.manager_teams ||
!next.memory.has(::bmh::layout::ActiveManager) || next.memory.u8(::bmh::layout::ActiveManager)!=manager)
throw FormatError("poach: selection changed its manager/calendar context");
market_dispatch_active_=false;
int slot=-1;
if(selection) {
if(selection->origin!=ClubPlayerDetailOrigin::squad || selection->human_loan_index!=-1)
throw FormatError("poach: selection is not an ordinary squad row");
const auto player=club_player_detail_context(next,*selection);
slot=player.source_slot;
if(slot<0 || slot>=0xb70 || slot_team(slot)!=selection->runtime_team ||
(next.squad_slots.at(size_t(slot))&0xfff)!=selection->player_id)
throw FormatError("poach: stale player selection");
}
// Preserve actual Table/ClubInfo/card effects, including a cancelled
// selection. No LeagueScreenShown entry and no family-close RNG stir.
g_=std::move(next);game_=staged.game_;rand_=staged.rand_;club_modal_runtime_=std::move(staged.club_modal_runtime_);
if(selection) {
auto opened=open_poach(manager,slot,revision,error);
if(!opened) throw FormatError(error);
result=std::move(*opened);
}
if(revision==checkpoint.revision) ++revision;
}
const auto accepted_baseline=advertising_session_checkpoint(revision);
accept(result,preparation_projection(revision));
if(!advertising_session_unchanged(accepted_baseline,revision))
throw FormatError("poach: UI acknowledgement changed the session");
return true;
} catch(const std::exception& e) {
restore_advertising_session_checkpoint(checkpoint);revision=checkpoint.revision;
error=e.what();return false;
}
}
// Applies one editor event (field quote change, submit, cancel, team info, player info) to the
// open offer editor: identity and quote must match the owner and the posted row must equal the
// single field change. Runs on copies; the revision rises only if state, runtime bytes or a
// random generator actually changed. A closing editor ends a poach attempt and clears the owner.
std::optional<CareerSession::TransferOfferEditorDispatch> CareerSession::dispatch_transfer_offer(
const ui::OutgoingTransferRequest& request, const HumanBuyerSaleHooks& presenters,
uint64_t& revision, std::string& error,
const TransferOfferTeamInfoPresenter& team_info,
const TransferOfferPlayerInfoPresenter& player_info) {
if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ ||
top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; }
error.clear();
if (!transfer_offer_editor_ || market_dispatch_active_ || pending_offer_dispatch_active_ || calendar_advance_active_ ||
request.identity.revision != revision || transfer_offer_revision_ != revision ||
revision == std::numeric_limits<uint64_t>::max()) {
error = "transfer offer: stale or nested editor event"; return std::nullopt;
}
const auto& current = *transfer_offer_editor_;
const auto& id = request.identity;
const int seller = current.request.expected_seller_word == 0xffff ? 0x0fff : current.request.expected_seller_word & 0x7fff;
if (id.manager_slot != current.request.manager || id.runtime_club != current.request.runtime_club ||
id.list_entry != current.request.list_entry || id.source_slot != current.request.source_slot ||
id.player != current.request.expected_player || id.seller != seller || id.bid_slot != current.bid_slot ||
request.quoted_fee != current.quoted_fee || request.quoted_monthly_salary != current.quoted_salary ||
request.quoted_years != current.years) {
error = "transfer offer: mismatched editor identity or quote"; return std::nullopt;
}
uint32_t fee = current.fee, salary = current.salary;
uint8_t years = current.years; auto bonuses = current.bonuses;
bool quote_loan = current.quote_loan;
const unsigned field = unsigned(request.field);
if (request.kind == ui::OutgoingTransferRequestKind::quote_change) {
if (field > unsigned(ui::OutgoingTransferField::quote_loan)) {
error = "transfer offer: invalid editor field"; return std::nullopt;
}
if (request.accepted) {
if (field == 0) fee = request.value;
else if (field == 1) salary = request.value;
else if (field == 2) years = uint8_t(request.value);
else if (field < 10) bonuses[field - 3] = uint8_t(field < 6 ? request.value : request.value / 5);
else quote_loan = !quote_loan;
}
} else if (request.kind != ui::OutgoingTransferRequestKind::submit && request.kind != ui::OutgoingTransferRequestKind::cancel &&
request.kind != ui::OutgoingTransferRequestKind::team_info &&
request.kind != ui::OutgoingTransferRequestKind::player_info) {
error = "transfer offer: unsupported editor event"; return std::nullopt;
}
if (request.fee != fee || request.monthly_salary != salary || request.duration_years != years ||
request.bonuses != bonuses || request.quote_loan != quote_loan) {
error = "transfer offer: posted row differs from the single Source field event"; return std::nullopt;
}
if(request.kind==ui::OutgoingTransferRequestKind::team_info&&!team_info) {
error="transfer offer: TeamInfo presenter unavailable"; return std::nullopt;
}
if(request.kind==ui::OutgoingTransferRequestKind::player_info&&!player_info) {
error="transfer offer: PlayerInfo presenter unavailable"; return std::nullopt;
}
auto next_state = g_; auto next_game = game_; auto next_rand = rand_;
auto next_runtime=club_modal_runtime_;
auto owner = current; TransferActionResult action;
auto hooks = presenters;
switch (turn_driver_.transfer_allocator_context) {
case PendingOfferAllocatorGate::zero: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::zero; break;
case PendingOfferAllocatorGate::blocked: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::blocked; break;
default: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::unsupported; break;
}
hooks.direct_mode = HumanBuyerSaleDirectMode::ordinary_ai_purchase;
hooks.before_accounts = {}; hooks.after_paid_accounts = {};
market_dispatch_active_ = true;
struct Reset { bool& active; ~Reset() { active = false; } } reset{market_dispatch_active_};
try {
if (request.kind == ui::OutgoingTransferRequestKind::quote_change) {
owner = edit_transfer_offer_from_ui(next_state, current, request, next_game, next_rand);
} else if (request.kind == ui::OutgoingTransferRequestKind::cancel) {
owner = cancel_transfer_offer_editor_source(next_state, current);
} else if(request.kind==ui::OutgoingTransferRequestKind::team_info) {
// Validate the complete old Native row before any modal effect.
const auto validation=cancel_transfer_offer_editor_source(next_state,current);
if(!validation.supported) {error=validation.reason;return std::nullopt;}
auto services=staged_club_modal_services(next_state,next_game,next_rand,next_runtime);
const auto parent=transfer_offer_projection(next_state,current,revision,
next_state.memory.u8(::bmh::layout::TextGradientDisabled)==0);
const Image backdrop=ui::OutgoingTransferScreen(data_directory_,parent).render();
if(!team_info(services,current.request.runtime_club,backdrop)) {
error="transfer offer: TeamInfo presenter stopped";return std::nullopt;
}
owner=resume_transfer_offer_team_info_source(next_state,current,next_rand);
} else if(request.kind==ui::OutgoingTransferRequestKind::player_info) {
const auto selection=transfer_offer_player_info_selection_source(next_state,current);
auto services=staged_club_modal_services(next_state,next_game,next_rand,next_runtime);
const auto parent=transfer_offer_projection(next_state,current,revision,
next_state.memory.u8(::bmh::layout::TextGradientDisabled)==0);
const Image backdrop=ui::OutgoingTransferScreen(data_directory_,parent).render();
services.set_runtime_byte(::bmh::layout::CareerSession_DispatchPoachUi_ExecutableField,1); // Source direct entry persists, unlike4f548.
if(!player_info(services,selection,backdrop)) {
error="transfer offer: PlayerInfo presenter stopped";return std::nullopt;
}
owner=resume_transfer_offer_player_info_source(next_state,current,
services.runtime_byte(::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableField),services.runtime_byte(::bmh::layout::CareerSession_DispatchTransferOffer_ExecutableField2),next_rand);
} else {
MinuteReport report;
auto submitted = submit_transfer_offer_editor_source(next_state, current, next_rand, hooks, report);
owner = std::move(submitted.editor); action = submitted.action;
if (report.unsupported) { error = report.reason; return std::nullopt; }
}
if (!owner.supported) { error = owner.reason; return std::nullopt; }
// a poaching editor that closes frees its special row and counts the attempt (Reset)
if (owner.closed && poach_) finish_poach(next_state, *poach_);
const bool changed = save_stream(next_state) != save_stream(g_) || next_runtime != club_modal_runtime_ ||
next_game.seed() != game_.seed() || next_game.calls() != game_.calls() ||
next_rand.seed() != rand_.seed() || next_rand.calls() != rand_.calls();
const auto next_revision = revision + uint64_t(changed);
TransferOfferEditorDispatch result;
result.preparation = preparation_projection(next_state, next_revision);
result.editor = transfer_offer_projection(next_state, owner, next_revision, result.preparation.desktop.gradient_text);
result.action = action;
if (!owner.closed) { ui::OutgoingTransferScreen validate(data_directory_, result.editor); }
g_ = std::move(next_state); game_ = next_game; rand_ = next_rand;
club_modal_runtime_=std::move(next_runtime);
if (owner.closed) { transfer_offer_editor_.reset(); poach_.reset(); } else transfer_offer_editor_ = std::move(owner);
transfer_offer_revision_ = next_revision; revision = next_revision;
return result;
} catch (const std::exception& e) { error = e.what(); return std::nullopt; }
}
// Quotes a purchase, lender snapshot or squad row preview (the listing identity is re-checked)
// using a copy of the W random stream; the stream and revision are updated only if the quote
// and its projection both succeed.
std::optional<CareerSession::TransferMarketPreviewDispatch> CareerSession::preview_transfer_market(
const ui::TransferMarketRequest& request, uint64_t& revision, std::string& error) {
if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ ||
top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; }
error.clear();
if (request.kind != ui::TransferMarketRequestKind::preview_quote ||
transfer_offer_editor_ || market_dispatch_active_ || pending_offer_dispatch_active_ || calendar_advance_active_ ||
request.revision != revision || revision == std::numeric_limits<uint64_t>::max() ||
request.manager_slot < 0 || request.manager_slot >= 4 ||
size_t(request.manager_slot) >= g_.manager_teams.size() ||
!g_.memory.has(::bmh::layout::ActiveManager) || g_.memory.u8(::bmh::layout::ActiveManager) != request.manager_slot ||
request.runtime_club != g_.manager_teams[size_t(request.manager_slot)]) {
error = "transfer market: stale or nested preview";
return std::nullopt;
}
if (request.preview_is_purchase) {
if (request.preview_snapshot_index != -1 || request.squad_row != -1 || request.bid.manager != request.manager_slot ||
request.bid.list_entry < 0 || request.bid.list_entry >= 40 ||
request.bid.source_slot != request.preview_source_slot ||
request.preview_source_slot != 0xb70 + request.bid.list_entry ||
request.bid.player != request.expected_player) {
error = "transfer market: mismatched preview listing identity";
return std::nullopt;
}
} else if (request.preview_snapshot_index >= 0) {
const auto identity = transfer_market_snapshot_preview(g_, request.manager_slot,
request.runtime_club, request.preview_snapshot_index);
if (!identity || identity->displayed_row != request.squad_row || identity->player != request.expected_player ||
identity->source_slot != request.preview_source_slot || request.preview_seller != request.runtime_club) {
error = "transfer market: mismatched lender snapshot identity";
return std::nullopt;
}
} else {
const auto range = squad_range(request.runtime_club);
if (request.preview_snapshot_index != -1 || request.squad_row < 0 || size_t(request.squad_row) >= range.count ||
request.preview_source_slot != int(range.first + size_t(request.squad_row)) ||
request.preview_seller != request.runtime_club) {
error = "transfer market: mismatched preview roster identity";
return std::nullopt;
}
}
auto next_rand = rand_;
market_dispatch_active_ = true;
struct Reset { bool& active; ~Reset() { active = false; } } reset{market_dispatch_active_};
try {
const TransferMarketPreviewRequest input{request.manager_slot, request.runtime_club,
request.preview_source_slot, request.expected_player, request.preview_seller,
request.preview_is_purchase, request.preview_is_loan, request.preview_snapshot_index};
const auto result = quote_transfer_market_preview_source(g_, input, next_rand);
if (!result.supported) {
error = result.reason.empty() ? "transfer market: unsupported Source preview" : result.reason;
return std::nullopt;
}
const bool changed = next_rand.seed() != rand_.seed() || next_rand.calls() != rand_.calls();
const auto next_revision = revision + uint64_t(changed);
TransferMarketPreviewDispatch dispatch;
dispatch.preparation = preparation_projection(next_revision);
if (!dispatch.preparation.transfer_market)
throw FormatError("transfer market: preview has no ordinary projection");
dispatch.quote = {request.manager_slot, request.runtime_club, request.preview_source_slot,
request.expected_player, request.preview_seller, next_revision,
result.delta, result.projected_balance, request.preview_is_purchase, request.preview_is_loan, request.preview_snapshot_index};
// Projection construction can throw. Keep the live W stream and revision
// unchanged until both the Source result and the projection are valid.
rand_ = next_rand;
revision = next_revision;
return dispatch;
} catch (const std::exception& e) {
error = e.what();
return std::nullopt;
}
}
// Direct market actions of a human manager: review offers, submit a bid, list a player. Needs
// a request of the current revision for the active manager's club; loans and marked batches are
// not accepted here. The allocator gate comes from the turn driver, never from the presenter.
// The staged copy is committed (revision plus one) only if something changed.
std::optional<TransferActionResult> CareerSession::dispatch_transfer_market(
const ui::TransferMarketRequest& request, const HumanBuyerSaleHooks& presenters,
uint64_t& revision, std::string& error,
const std::function<int(const GameState&, const TransferOfferListView&)>& review) {
if (balance_draft_ || balance_dispatch_active_ || strengths_owner_ || strengths_dispatch_active_ ||
top_scorers_owner_ || top_scorers_dispatch_active_ || stadium_.block_expansion || other_games_owner_ || other_games_dispatch_active_) { error = "strengths_active"; return std::nullopt; }
error.clear();
if (transfer_offer_editor_ || market_dispatch_active_ || pending_offer_dispatch_active_ || calendar_advance_active_ ||
request.revision != revision || revision == std::numeric_limits<uint64_t>::max() ||
request.manager_slot < 0 || request.manager_slot >= 4 ||
size_t(request.manager_slot) >= g_.manager_teams.size() ||
!g_.memory.has(::bmh::layout::ActiveManager) || g_.memory.u8(::bmh::layout::ActiveManager) != request.manager_slot ||
request.runtime_club != g_.manager_teams[size_t(request.manager_slot)]) {
error = "transfer market: stale or nested request";
return std::nullopt;
}
if (request.kind == ui::TransferMarketRequestKind::review_offers) {
if (!review || request.bid.manager != request.manager_slot || request.bid.list_entry < 0 ||
request.bid.list_entry >= 40 || request.bid.source_slot != 0xb70 + request.bid.list_entry ||
request.squad_row != -1 || !request.selected_players.empty()) {
error = "transfer market: invalid offer review"; return std::nullopt;
}
const auto view = project_transfer_offer_list(g_, request.bid.list_entry);
if (!view.valid || view.player != request.bid.player || view.seller != request.runtime_club ||
view.seller_manager != request.manager_slot) {
error = "transfer market: stale seller listing"; return std::nullopt;
}
} else if (request.kind == ui::TransferMarketRequestKind::submit_bid) {
if (request.bid.manager != request.manager_slot || request.squad_row != -1 ||
request.expected_player != -1 ||
std::any_of(request.bid.bonuses.begin(), request.bid.bonuses.end(),
[](uint32_t value) { return value > 255; })) {
error = "transfer market: invalid buyer request";
return std::nullopt;
}
} else if (request.kind == ui::TransferMarketRequestKind::list_player) {
const auto range = squad_range(request.runtime_club);
if (request.squad_row < 0 || size_t(request.squad_row) >= range.count ||
range.first + size_t(request.squad_row) >= g_.squad_slots.size() ||
request.expected_player < 0 || request.expected_player >= 0xfff ||
(g_.squad_slots[range.first + size_t(request.squad_row)] & 0xfff) != request.expected_player) {
error = "transfer market: stale seller row";
return std::nullopt;
}
} else {
error = "transfer market: unsupported action";
return std::nullopt;
}
// Reset sends an owned marked player through the same Size2
// listing for both VER-KAUFEN and VER-LEIHEN. Only a buyer's OpenTransferEditor
// offer owns the actual loan term; listing does not create a loan record.
if ((request.offer_is_loan && request.kind != ui::TransferMarketRequestKind::list_player) ||
request.selected_players.size() > 1) {
error = "transfer market: this caller does not own buyer loan or marked batch processing";
return std::nullopt;
}
if (!request.selected_players.empty()) {
const auto& selected = request.selected_players.front();
const bool matches = request.kind == ui::TransferMarketRequestKind::list_player
? selected.squad_row == request.squad_row && selected.player == request.expected_player &&
selected.seller == request.runtime_club &&
selected.source_slot == int(squad_range(request.runtime_club).first + size_t(request.squad_row))
: selected.list_entry == request.bid.list_entry && selected.source_slot == request.bid.source_slot &&
selected.player == request.bid.player && selected.squad_row == -1;
if (!matches) {
error = "transfer market: mismatched marked selection";
return std::nullopt;
}
}
auto next_state = g_;
auto next_game = game_;
auto next_rand = rand_;
auto hooks = presenters;
// A presenter cannot supply the allocator gate or insert the special
// pending caller's severance/ACK/news sequence into a direct purchase.
switch (turn_driver_.transfer_allocator_context) {
case PendingOfferAllocatorGate::zero: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::zero; break;
case PendingOfferAllocatorGate::blocked: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::blocked; break;
default: hooks.allocator_gate = HumanBuyerSaleAllocatorGate::unsupported; break;
}
// Reset -> OpenTransferEditor establishes DeskActions_EditorFail_RuntimeField2=0 at LAB1b67e before
// resolving the AI seller. This explicitly selected App entry supplies
// that transient ownership; a missing FBM byte is never the observation.
hooks.direct_mode = HumanBuyerSaleDirectMode::ordinary_ai_purchase;
hooks.before_accounts = {};
hooks.after_paid_accounts = {};
market_dispatch_active_ = true;
struct Reset { bool& active; ~Reset() { active = false; } } reset{market_dispatch_active_};
MinuteReport report;
try {
const auto before = save_stream(g_);
TransferActionResult result;
if (request.kind == ui::TransferMarketRequestKind::review_offers) {
const auto view = project_transfer_offer_list(next_state, request.bid.list_entry);
result.player = view.player; result.list_entry = view.list_entry;
result.status = TransferActionStatus::pending;
// VERKAUFEN on a listed player: "Wollen Sie <name> vom Transfermarkt holen?". Yes frees the list
// slot (the player stays in the squad), no goes on to the offers.
bool withdrawn = false;
if (request.ask_withdraw && hooks.confirm) {
const std::string question = message_text(next_state, ::bmh::layout::TransferMarket_WithdrawQuestion_TextPointer) +
next_state.player_name(view.player) +
message_text(next_state, ::bmh::layout::TransferMarket_WithdrawQuestion_TextPointer2);
if (hooks.confirm(next_state, request.manager_slot, question)) {
next_state.squad_slots.at(0xb70u + size_t(view.list_entry)) = 0xfff;
withdrawn = true;
}
}
const int selected = !withdrawn && view.offer_count ? review(next_state, view) : -1;
if (selected != -1) {
auto allocator = TransferAllocatorContext::unsupported;
if (turn_driver_.transfer_allocator_context == PendingOfferAllocatorGate::zero)
allocator = TransferAllocatorContext::zero;
else if (turn_driver_.transfer_allocator_context == PendingOfferAllocatorGate::blocked)
allocator = TransferAllocatorContext::blocked;
result = accept_manager_transfer_offer(next_state, request.manager_slot,
view.list_entry, view.player, selected, next_rand, report, allocator);
}
} else if (request.kind == ui::TransferMarketRequestKind::list_player)
result = list_manager_player(next_state, request.manager_slot, request.squad_row, next_rand, report);
else
result = submit_transfer_bid_source_human_buyer(next_state, request.bid, next_rand, hooks, report);
if (report.unsupported || result.status == TransferActionStatus::unsupported) {
error = report.reason.empty() ? "transfer market: unsupported Source sale" : report.reason;
return std::nullopt;
}
const bool changed = save_stream(next_state) != before ||
next_rand.seed() != rand_.seed() || next_rand.calls() != rand_.calls() ||
next_game.seed() != game_.seed() || next_game.calls() != game_.calls();
if (changed) {
// Pure projections reject inconsistent squad/board/training state
// before any staged notice effects become live.
(void)ui::preparation_from_game(next_state, exe_, revision + 1);
g_ = std::move(next_state);
game_ = next_game;
rand_ = next_rand;
++revision;
}
return result;
} catch (const std::exception& e) {
error = e.what();
return std::nullopt;
}
}
} // namespace bmh::app