Initial public OpenBMH 0.1 source (by Codex)

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

No files matched your search

+371
View File
@@ -0,0 +1,371 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/balance_plan.hpp"
#include <algorithm>
#include <cmath>
#include "game/prediction.hpp"
#include "game/schedule.hpp"
#include "game/table.hpp"
#include "game/week.hpp"
namespace bmh {
namespace {
constexpr size_t kRecordSize = 0xb0c;
constexpr uint32_t kPlanTicketPrice = ::bmh::layout::PlanTicketPrice; // one byte per manager
// BalancePlanRuntimeField: months left in the business year by calendar month (July: 12, June: 1)
constexpr int8_t kMonthsLeft[13] = {0, 6, 5, 4, 3, 2, 1, 12, 11, 10, 9, 8, 7};
// BalancePlanRuntimeField2: which rows can be changed; BalancePlanRuntimeField3: the class of the maximum
// (BalancePlanRuntimeField4: 30 million, 25, 100000, 2 million)
constexpr uint8_t kEditable[0x16] = {1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1};
constexpr uint8_t kMaximumClass[0x16] = {0, 0, 0, 0, 3, 0, 0, 0, 0, 3, 3, 3, 3, 0, 3, 3, 0, 0, 0, 1, 2, 1};
constexpr int32_t kMaximum[4] = {30000000, 25, 100000, 2000000};
// BalancePlanRuntimeField5: monthly running costs of the stadium facilities (BMHExeXa)
constexpr uint16_t kFacilityCost[22] = {2000, 3000, 3000, 8000, 4000, 3000, 2500, 2500, 2500, 2500, 2600,
2600, 2600, 2600, 13000, 9000, 9000, 8000, 1000, 1500, 1500, 2000};
// BalancePlanRuntimeField6: monthly income of the first six facilities (FacilityIncome)
constexpr uint16_t kFacilityIncome[6] = {0, 5000, 5000, 4800, 2400, 8000};
// BalancePlanRuntimeField7: catering income per visitor of the facilities 0-13 (BookMoney)
constexpr uint8_t kPerVisitor[14] = {0, 10, 10, 3, 5, 15, 3, 3, 3, 3, 2, 2, 2, 2};
// Rec32: price units of the six funds (BMH.exe+MonthRuntimeField10)
constexpr int32_t kShareUnits[6] = {15, 18, 21, 24, 27, 30};
int32_t rec32(const GameState& g, int m, size_t o) {
const size_t at = size_t(m) * kRecordSize + o;
const auto& r = g.manager_records;
return int32_t(uint32_t(r.at(at)) | uint32_t(r.at(at + 1)) << 8 | uint32_t(r.at(at + 2)) << 16 | uint32_t(r.at(at + 3)) << 24);
}
void set_rec32(GameState& g, int m, size_t o, int32_t v) {
for (int i = 0; i < 4; i++) g.manager_records.at(size_t(m) * kRecordSize + o + size_t(i)) = uint8_t(uint32_t(v) >> (8 * i));
}
uint8_t rec8(const GameState& g, int m, size_t o) { return g.manager_records.at(size_t(m) * kRecordSize + o); }
int32_t mem32(const GameState& g, uint32_t a) { return g.memory.has(a + 3) ? int32_t(g.memory.u32(a)) : 0; }
int32_t wrap(int64_t v) { return int32_t(uint32_t(uint64_t(v))); }
// Add32: the level of a facility (facility 0: its size step)
uint32_t facility_level(const GameState& g, int m, int k) {
const uint8_t v = rec8(g, m, size_t(k));
return k == 0 ? uint32_t((v - 1) / 0x55 + 1) & 0xff : 1;
}
// DailyInterest2(0): the interest of one day without booking it - negative is income
// (balance 1 %, fixed deposit 2 % a year), positive an expense (overdraft 12 %, beyond the
// credit line 18 %). The divisor is -36500.
int32_t daily_interest_preview(const GameState& g, int m) {
constexpr int32_t kAnnual = -0x8e94;
const int32_t balance = rec32(g, m, 0x314), deposit = rec32(g, m, 0x318), credit = rec32(g, m, 0x31c);
int32_t result = 0;
if (balance < 0) {
const int32_t with_credit = wrap(int64_t(balance) + credit);
if (with_credit < 0) result = wrap(int64_t(with_credit) * 0x12) / kAnnual;
int32_t below = wrap(-int64_t(credit));
if (below < balance) below = balance;
result = wrap(int64_t(result) + wrap(int64_t(below) * 0xc) / kAnnual);
} else {
result = balance / kAnnual;
}
return wrap(int64_t(result) + wrap(int64_t(deposit / 10000) * 20000) / kAnnual);
}
// SharesAndLoans(manager, flags, months): flags 1 the dividends of the manager's funds and
// the loans he gave to other managers (income), 2 the loans he took (expense, negative);
// flag 4 multiplies by the months (loans: at most their remaining months).
int32_t shares_and_loans(const GameState& g, int m, int flags, int months) {
int32_t sum = 0;
if (flags & 1) {
for (int k = 0; k < 6; k++) {
const uint32_t unit = g.memory.u32(::bmh::layout::FundBlock + uint32_t(k) * 0x1c) * uint32_t(kShareUnits[k]) / 10000;
sum = wrap(int64_t(sum) + int64_t(unit * g.memory.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(m) * 2 + uint32_t(k) * 0x1c)));
}
if (flags & 4) sum = wrap(int64_t(sum) * months);
}
const int managers = g.memory.u8(::bmh::layout::ManagerCount);
for (int c = 0; c <= managers; c++) {
uint32_t row = uint32_t(c) * 0x18 + uint32_t(m) * 0x78;
int32_t amount = mem32(g, ::bmh::layout::Loans + row + 8);
if (amount != 0 && (flags & 2)) {
if (!(flags & 4)) {
sum = wrap(int64_t(sum) - amount);
} else {
int left = uint8_t(g.memory.u8(::bmh::layout::Loans + row + 0xc) - g.memory.u8(::bmh::layout::Loans + row + 0x10));
sum = wrap(int64_t(sum) - int64_t(std::min(left, months)) * amount);
}
}
if (c == 0) continue;
row = uint32_t(m + 1) * 0x18 + uint32_t(c - 1) * 0x78;
amount = mem32(g, ::bmh::layout::Loans + row + 8);
if (amount != 0 && (flags & 1)) {
if (!(flags & 4)) {
sum = wrap(int64_t(sum) + amount);
} else {
int left = uint8_t(g.memory.u8(::bmh::layout::Loans + row + 0xc) - g.memory.u8(::bmh::layout::Loans + row + 0x10));
sum = wrap(int64_t(sum) + int64_t(std::min(left, months)) * amount);
}
}
}
return sum;
}
// MonthlyPay(manager, 0xb): a month of the squad's pay - bonus base (+0x4e), salary
// (+0x50) and the bonus each player can expect (ContractOffer with the fitness correction)
// for the predicted final rank (Void5 mode 4). Changes scratch tables: `g` is a copy.
int32_t monthly_pay(GameState& g, int m, uint8_t flags = 0xb) {
const int team = g.manager_teams.at(size_t(m));
std::array<uint8_t, 24> buf{};
const int predicted = table_prediction(g, team, 4, buf);
const int rank = predicted == 0 ? 0xb : predicted + 1;
const SquadRange range = squad_range(team);
int32_t sum = 0;
for (int s = 0; s < 0x18; s++) {
const size_t slot = size_t(m) * 0x840 + size_t(s) * 0x58;
if (g.tactics.at(slot + 0x3d) == 0xff) continue;
const int32_t bonus = int32_t((g.tactics.at(slot + 0x4e) | g.tactics.at(slot + 0x4f) << 8) & 0x7fff);
const int32_t salary = int32_t(uint32_t(g.tactics.at(slot + 0x50)) | uint32_t(g.tactics.at(slot + 0x51)) << 8 |
uint32_t(g.tactics.at(slot + 0x52)) << 16 | uint32_t(g.tactics.at(slot + 0x53)) << 24);
// a board row whose squad slot is empty (0xfff) makes the original read a player
// beyond the table; the port counts no expected bonus for it
const size_t player = g.squad_slots.at(range.first + size_t(s)) & 0xfff;
const int32_t expected = (flags & 1) && player < g.players.size() ? int32_t(expected_bonus(g, m, rank, s, int(player), true)) : 0;
sum = wrap(int64_t(sum) + ((flags & 2) ? salary : 0) +
((flags & 1) ? expected : 0) + ((flags & 8) ? bonus : 0));
}
return sum;
}
// BMHExeXa: the facilities' monthly running costs
int32_t facility_costs(const GameState& g, int m) {
int32_t sum = 0;
for (int i = 0; i < 0xe; i++) sum += kFacilityCost[i];
for (int i = 0xe; i < 0x16; i++) sum += (rec8(g, m, 0x2e + size_t(i)) & 7) * kFacilityCost[i];
return sum;
}
// FacilityIncome: the facilities' monthly income
int32_t facility_income(const GameState& g, int m) {
int32_t sum = 0;
for (int k = 0; k < 6; k++)
if (rec8(g, m, size_t(k)) != 0) sum += int32_t(facility_level(g, m, k)) * kFacilityIncome[k];
return sum;
}
// BookMoney(manager, gate, 1): kiosks and restaurants of one home game, without the
// random factor
uint32_t catering_per_game(const GameState& g, int m, int32_t gate) {
uint32_t sum = 0;
for (int k = 0; k < 14; k++)
if (rec8(g, m, size_t(k)) != 0) sum += kPerVisitor[k] * uint32_t(gate) * facility_level(g, m, k) / 100;
return sum;
}
// OpenBMH deviates from the original: omits the discontinued youth-group cost categories and uses league-specific youth-academy limits.
// TeamLeague3 (supported rule profile patch): the youth academy limit of the league
int32_t youth_limit(const GameState& g, int m) {
const int league = team_league(g.manager_teams.at(size_t(m)));
return league == 0 ? 1500000 : league == 1 ? 1000000 : league <= 3 ? 580000 : 280000;
}
// The redraw of BalanceFromGame2 (with its continuation Redraw and the patch at
// Redraw2): recomputes the items if `refresh` asks for it, then the spectator income
// and the totals.
void redraw(const GameState& source, BalancePlanDraft& d) {
const int m = d.manager;
const int view = int(d.view);
auto& r = d.rows;
r[3] = view < 2 ? rec32(source, m, 0x868) : 0;
int32_t home = r[kBalanceLeagueHomeGames] + r[kBalanceOtherHomeGames]; // local_48
if (view == 0) home = 0;
if (view < 2) {
const int month = month_code(source.date);
d.months_left = month >= 1 && month <= 12 ? kMonthsLeft[month] : 0;
d.days_left = 0x16d - source.season_day();
const bool first_of_month = source.date == 0 || month_code(source.date - 1) != month;
if (source.season_day() != 0 && month == 7 && first_of_month) d.months_left = d.days_left = 0;
home -= int8_t(rec8(source, m, 0x28c)) + int8_t(rec8(source, m, 0x28d)) + int8_t(rec8(source, m, 0x28e));
if (home < 0) home = 0;
} else {
d.months_left = 12;
d.days_left = 0x16d;
}
const int months = int8_t(d.months_left);
if (d.refresh != 0) {
if (view < 2) {
for (int i = 0; i < kBalanceItems; i++) r[size_t(i)] = rec32(source, m, 0x85c + size_t(i) * 4);
r[7] = wrap(int64_t(rec32(source, m, 0x33c)) + rec32(source, m, 0x334) + rec32(source, m, 0x338));
} else {
std::fill(r.begin(), r.begin() + kBalanceItems, 0);
}
if (view != 0 && months != 0)
for (int i = 0; i < kBalanceItems; i++) r[size_t(i)] = wrap(int64_t(r[size_t(i)]) + d.adjustments[size_t(i)] * 12 / months);
if (d.refresh != 2) r[kBalanceAverageGate] = r[kBalanceGateSoFar];
if (view != 0) {
GameState g = source; // scratch copy, see the header
const int32_t interest = wrap(int64_t(int16_t(d.days_left)) * daily_interest_preview(g, m));
if (interest < 1) r[5] = wrap(int64_t(r[5]) - interest);
else r[0x10] = wrap(int64_t(r[0x10]) + interest);
r[5] = wrap(int64_t(r[5]) + shares_and_loans(g, m, 5, months));
r[0x10] = wrap(int64_t(r[0x10]) - shares_and_loans(g, m, 6, months));
// advertising: shirt (+0xadc) and TV (+0xae8) contracts, the 14 boards (+0xa34);
// free boards are expected to bring 80 % of the average board
r[0] = wrap(int64_t(r[0]) + int64_t(rec32(g, m, 0xadc)) * months);
r[2] = wrap(int64_t(r[2]) + int64_t(months) * rec32(g, m, 0xae8));
int boards = 0;
for (int s = 0; s < 0xe; s++) {
const int32_t v = rec32(g, m, 0xa34 + size_t(s) * 0xc);
if (v != 0) boards++;
r[1] = wrap(int64_t(r[1]) + int64_t(v) * months);
}
if (g.memory.u8(::bmh::layout::GameMode) == 1 || (g.memory.u8(::bmh::layout::CareerDuration) == 1 && g.date == 0)) boards = 0xe;
if (boards != 0 && boards < 0xe) {
int32_t missing = (r[1] / boards) * (0xe - boards);
if (months != 0) missing /= months;
r[1] = wrap(int64_t(r[1]) + int64_t(months) * ((int64_t(missing) * 0x50) / 100));
}
r[7] = wrap(int64_t(r[7]) + int64_t(monthly_pay(g, m)) * months);
r[8] = wrap(int64_t(r[8]) + int64_t(facility_costs(g, m)) * months);
r[4] = wrap(int64_t(r[4]) + int64_t(facility_income(g, m)) * months);
const uint32_t catering = catering_per_game(g, m, r[kBalanceAverageGate]);
r[4] = wrap(int64_t(r[4]) + int64_t((catering * uint32_t(home)) / 12) * months);
// running costs Spending: the patch counts only the youth academy (index 1),
// with the whole league limit while +0x880 is below it
const uint32_t costs = ::bmh::layout::Spending + uint32_t(m) * 0x24;
if (mem32(g, costs + 4) != 0 && int64_t(months) * mem32(g, costs + 4) != 0) {
const int32_t limit = youth_limit(g, m);
if (uint32_t(rec32(g, m, 0x880)) < uint32_t(limit)) r[9] = wrap(int64_t(r[9]) + limit);
}
for (int k = 0; k < 3; k++) r[size_t(10 + k)] = wrap(int64_t(r[size_t(10 + k)]) + int64_t(months) * mem32(g, costs + 0xc + uint32_t(k) * 4));
for (int k = 0; k < 2; k++) r[size_t(14 + k)] = wrap(int64_t(r[size_t(14 + k)]) + int64_t(months) * rec32(g, m, 0x854 + size_t(k) * 4));
}
d.refresh = 0;
}
// the view "real" leaves out the season tickets of the remaining league home games
int32_t season_tickets = 0;
if (view == 1) {
int32_t sold = int32_t(uint16_t(rec8(source, m, 0x2ac) | rec8(source, m, 0x2ad) << 8));
if (r[kBalanceAverageGate] < sold) sold = r[kBalanceAverageGate];
int32_t games = r[kBalanceLeagueHomeGames] - int8_t(rec8(source, m, 0x28c));
if (games < 0) games = 0;
season_tickets = wrap(int64_t((sold * 0x46) / 100) * r[kBalanceTicketPrice] * games);
}
r[3] = wrap(int64_t(r[3]) + (int64_t(home) * r[kBalanceTicketPrice] * r[kBalanceAverageGate] - season_tickets));
double total = 0;
for (int i = 0; i < kBalanceItems; i++) {
if (r[size_t(i)] < 0) r[size_t(i)] = 0;
total += double(r[size_t(i)]) * (i < 7 ? 1 : -1);
}
d.depreciation = view < 2 ? rec32(source, m, 0x30c) : 0;
d.total = total - double(d.depreciation);
}
} // namespace
// StadiumRequiredAttendance: Source's monthly preview differs from booked month_change totals.
// Prediction may touch scratch tables; both pay previews run on an owned copy.
int32_t stadium_required_attendance(const GameState& source, int manager) {
if (manager < 0 || manager > 4) throw FormatError("stadium attendance: invalid manager");
GameState g = source;
const int team = g.manager_teams.at(size_t(manager));
const int league = team > 0x164 ? 0 : team_league(team);
if (league < 0 || league >= kLeagueCount)
throw FormatError("stadium attendance: manager has no Source league");
const int home_games = league_matchdays(league) / 2;
if (home_games <= 0) throw FormatError("stadium attendance: invalid Source league home count");
const int m = manager;
int32_t costs = wrap(int64_t(facility_costs(g, m)) + rec32(g, m, 0x854) + rec32(g, m, 0x858));
costs = wrap(int64_t(costs) + monthly_pay(g, m, 0xa));
for (int k = 0; k < 6; ++k) {
int32_t value = mem32(g, ::bmh::layout::Spending + uint32_t(m) * 0x24 + uint32_t(k) * 4);
if (k == 0 || k == 2) value = 0; // OpenBMH deviates from the original: omits the discontinued youth-group cost categories and uses league-specific youth-academy limits.
// supported rule profile MonthlyExpenses
if (k == 1 && value != 0)
value = uint32_t(rec32(g, m, 0x880)) < uint32_t(youth_limit(g, m)) ? youth_limit(g, m) : 0;
costs = wrap(int64_t(costs) + value);
}
costs = wrap(int64_t(costs) - shares_and_loans(g, m, 2, 0) + int(rec8(g, m, 0x179)) * 1000);
if (costs < 0) costs = 0;
int32_t income = facility_income(g, m);
for (int i = 0; i < 16; ++i) income = wrap(int64_t(income) + rec32(g, m, 0xa34 + size_t(i) * 12));
constexpr int days[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; // DeskState_DeskDate_RuntimeField
const int month = month_code(g.date);
if (month < 1 || month > 12) throw FormatError("stadium attendance: invalid Source month");
income = wrap(int64_t(income) + shares_and_loans(g, m, 1, 0) -
int64_t(daily_interest_preview(g, m)) * days[month]);
const int32_t bonus = monthly_pay(g, m, 9);
int32_t needed = wrap(int64_t(wrap(int64_t(costs) - income)) * 12 + bonus) / home_games;
const int price = rec8(g, m, 0x26e);
if (price != 0) needed /= price;
return std::max(needed, int32_t(0));
}
BalancePlanDraft open_balance_plan(const GameState& g, int manager) {
BalancePlanDraft d;
d.manager = manager;
const int m = manager;
d.view = BalanceView(std::clamp(int(int8_t(rec8(g, m, 0x310))), 0, 2));
const int league = team_league(g.manager_teams.at(size_t(m)));
auto& r = d.rows;
r[kBalanceLeagueHomeGames] = league < kLeagueCount ? league_matchdays(league) / 2 : 0;
r[kBalanceOtherHomeGames] = rec32(g, m, 0x2f8);
r[kBalanceAverageGate] = rec32(g, m, 0x2fc);
uint8_t ticket = g.memory.has(kPlanTicketPrice + uint32_t(m)) ? g.memory.u8(kPlanTicketPrice + uint32_t(m)) : 0;
if (ticket == 0) ticket = rec8(g, m, 0x26e);
r[kBalanceTicketPrice] = ticket;
r[kBalanceAccount] = rec32(g, m, 0x314);
// the average gate of the last league home games (+0x340, count +0x283)
int32_t sum = 0;
const int games = rec8(g, m, 0x283);
for (int i = 0; i < games; i++) sum = wrap(int64_t(sum) + rec32(g, m, 0x340 + size_t(i) * 4));
r[kBalanceGateSoFar] = games != 0 ? sum / games : sum;
if (rec32(g, m, 0x300) != 0) r[kBalanceAverageGate] = rec32(g, m, 0x304) / rec32(g, m, 0x300);
for (int i = 0; i < kBalanceItems; i++) d.adjustments[size_t(i)] = rec32(g, m, 0x2b0 + size_t(i) * 4);
d.refresh = 2;
redraw(g, d);
return d;
}
void cycle_balance_view(const GameState& g, BalancePlanDraft& d) {
d.view = BalanceView((int(d.view) + 1) % 3);
d.refresh = d.rows[kBalanceAverageGate] != 0 ? 2 : 1;
redraw(g, d);
}
void reset_balance_plan(const GameState& g, BalancePlanDraft& d) {
d.adjustments.fill(0);
d.refresh = 1;
redraw(g, d);
}
int32_t balance_row_maximum(const BalancePlanDraft& d, int row) {
if (row < 0 || row >= 0x16 || !kEditable[row]) return -1;
(void)d; // the input dialog BalanceFromGame only offers other step sizes for the gate
return kMaximum[kMaximumClass[row]];
}
BalanceEditStatus edit_balance_plan(const GameState& g, BalancePlanDraft& d, int row, int32_t value) {
if (row < 0 || row >= 0x16 || !kEditable[row]) return BalanceEditStatus::not_editable;
if (d.view == BalanceView::so_far) return BalanceEditStatus::view_so_far;
if (value < 0 || value > balance_row_maximum(d, row)) return BalanceEditStatus::out_of_range;
if (row < kBalanceItems)
d.adjustments[size_t(row)] = wrap(int64_t(d.adjustments[size_t(row)]) +
wrap(int64_t(int8_t(d.months_left)) * (int64_t(value) - d.rows[size_t(row)])) / 12);
d.rows[size_t(row)] = value;
if (row > 0x11) d.refresh = 2;
redraw(g, d);
return BalanceEditStatus::changed;
}
bool close_balance_plan(GameState& g, const BalancePlanDraft& d) {
const int m = d.manager;
const bool warning = double(rec32(g, m, 0x314)) + d.total < -4000000.0; // BalancePlanRuntimeField8
for (int i = 0; i < kBalanceItems; i++) set_rec32(g, m, 0x2b0 + size_t(i) * 4, d.adjustments[size_t(i)]);
set_rec32(g, m, 0x308, int32_t(std::lround(d.total)));
if (g.memory.has(kPlanTicketPrice + uint32_t(m))) g.memory.set8(kPlanTicketPrice + uint32_t(m), uint8_t(d.rows[kBalanceTicketPrice]));
set_rec32(g, m, 0x2f8, d.rows[kBalanceOtherHomeGames]);
set_rec32(g, m, 0x2fc, d.rows[kBalanceAverageGate]);
set_rec32(g, m, 0x310, int32_t(d.view));
return warning;
}
} // namespace bmh
+91
View File
@@ -0,0 +1,91 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// OpenBMH deviates from the original: uses the supported staff and youth-academy cost categories.
// The balance plan ("Bilanz", desk menu 28, mode III; H2 p. 26-27; BMH.exe V2.24 + supported rule profile
// patch): the screen BalanceFromGame2 projects the club's income and expenses for the business
// year and lets the manager change every item. When he leaves the screen the resulting
// profit/loss becomes the plan figure (manager record +0x308). On the 16th Bundesliga
// matchday the plan is handed to the DFB (+0x308 -> +0x320, matchday.cpp); from then on it
// lifts or lowers the advertising offers (weekly.cpp, plan / 100000 within -10..10) and at
// the end of the season the DFB punishes a result more than 1 million below the plan
// (season.cpp, SeasonEvent).
//
// The screen has three views (left button, captions BalancePlan_DrawButtons_TextPointer):
// so_far "bisher" - the booked figures of the season so far (record +0x85c..), no changes
// real "real" - booked figures plus a projection for the months left
// future "zukunft" - a projection for twelve months
// The manager's changes are kept per item normalised to twelve months (record +0x2b0, the
// screen's local_c8) and are added again on the next visit; "Werte akt." (right button)
// drops them.
//
// The screen's state is a BalancePlanDraft (the locals of BalanceFromGame2); the functions below
// are its event handlers. Projections run on a copy of the GameState: the wage projection
// (MonthlyPay -> table prediction) writes scratch tables, and a console must be able to
// look at the plan without changing the game.
#include <array>
#include <cstdint>
#include "game/state.hpp"
namespace bmh {
constexpr int kBalanceItems = 18; // 0-6 income, 7-17 expenses (labels BalancePlan_DrawRows_TextPointer5)
// Rows after the items (labels BalancePlan_DrawRows_TextPointer4): league home games, other home games, average
// gate (calculated), ticket price, average gate so far, account balance.
enum BalanceRow : int {
kBalanceLeagueHomeGames = 0x12,
kBalanceOtherHomeGames = 0x13,
kBalanceAverageGate = 0x14,
kBalanceTicketPrice = 0x15,
kBalanceGateSoFar = 0x16,
kBalanceAccount = 0x17,
kBalanceRows = 0x18,
};
enum class BalanceView : uint8_t { so_far = 0, real = 1, future = 2 };
struct BalancePlanDraft {
int manager = -1;
BalanceView view = BalanceView::so_far; // local_14 (record +0x310)
std::array<int32_t, kBalanceRows> rows{}; // local_178[0..20], local_124, local_120, local_11c
std::array<int32_t, kBalanceItems> adjustments{}; // local_c8 (record +0x2b0)
int refresh = 2; // local_18: 0 keep the items, 1 recompute, 2 recompute keeping the gate
int months_left = 0; // local_24
int days_left = 0; // local_34
int64_t depreciation = 0; // "Abschreibungen": record +0x30c in the views so_far/real
double total = 0; // GEWINN (> 0) / VERLUST (< 0), the plan figure on leaving
};
// BalanceFromGame2 up to its first redraw: the draft of `manager` with the stored view, the
// stored changes and the projection of that view.
// StadiumRequiredAttendance: minimum average attendance at the current stadium entry price.
// Pure preview, using a copy for Source prediction scratch writes; no RNG.
int32_t stadium_required_attendance(const GameState&, int manager);
BalancePlanDraft open_balance_plan(const GameState& g, int manager);
// The left button: the next view (so_far -> real -> future -> so_far), projected again.
void cycle_balance_view(const GameState& g, BalancePlanDraft& draft);
// The right button "Werte akt.": drops the manager's changes and projects again.
void reset_balance_plan(const GameState& g, BalancePlanDraft& draft);
enum class BalanceEditStatus : uint8_t {
changed,
view_so_far, // "Bitte den linken Button auf REAL oder ZUKUNFT stellen" (BalancePlan_BalanceFromGame_TextPointer)
not_editable, // spectator income, league home games, gate so far, balance
out_of_range,
};
// Range of a row in the number input (BalanceFromGame): 0 .. maximum.
int32_t balance_row_maximum(const BalancePlanDraft& draft, int row);
// A click on a row and a new value: items keep the change in `adjustments` (scaled to twelve
// months); the home games, the gate and the ticket price project the plan again.
BalanceEditStatus edit_balance_plan(const GameState& g, BalancePlanDraft& draft, int row, int32_t value);
// Leaving the screen: writes the changes (+0x2b0), the plan figure (+0x308), the other home
// games and the gate (+0x2f8/+0x2fc), the view (+0x310) and the ticket price of the plan
// (PlanTicketPrice). Returns true when the DFB demands a better balance (account + plan below
// -4 million, message BalancePlan_BalanceFromGame_TextPointer2) - the plan is stored nevertheless.
bool close_balance_plan(GameState& g, const BalancePlanDraft& draft);
} // namespace bmh
+257
View File
@@ -0,0 +1,257 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/bank_credit.hpp"
#include <bit>
#include <cmath>
#include <cstring>
#include <limits>
#include <stdexcept>
#include <utility>
#include "game/matchday.hpp"
namespace bmh {
namespace {
constexpr uint32_t kLoans = ::bmh::layout::Loans;
constexpr size_t kRecord = 0xb0c;
int32_t signed_word(uint32_t v) { return std::bit_cast<int32_t>(v); }
uint32_t word(int32_t v) { return std::bit_cast<uint32_t>(v); }
int32_t add(int32_t a, int32_t b) { return signed_word(word(a) + word(b)); }
int32_t sub(int32_t a, int32_t b) { return signed_word(word(a) - word(b)); }
int32_t mul(int32_t a, int32_t b) { return signed_word(word(a) * word(b)); }
int32_t divide(int32_t a, int32_t b) {
if (!b || (a == std::numeric_limits<int32_t>::min() && b == -1))
throw std::invalid_argument("invalid native credit division");
return a / b;
}
uint32_t read_record(const GameState& g, size_t at) {
uint32_t v = 0;
for (int i = 0; i < 4; ++i) v |= uint32_t(g.manager_records.at(at + i)) << (i * 8);
return v;
}
// Amount: signed IMUL/IDIV, x87 intermediate, QWORD store,
// exact-zero floor, then Amount2's explicit rounding toward zero.
int32_t amount(const BankCreditContext& c, uint32_t months, int32_t principal) {
if (months > 48 || c.rate_table[months] <= 100 || c.divisor != 100.0)
throw std::invalid_argument("invalid native credit factors");
const int32_t factor = c.rate_table[months];
const int32_t base = divide(mul(principal, factor), 100);
const int32_t den = divide(10000, factor - 100);
const long double intermediate = (static_cast<long double>(base) / c.divisor)
* den / c.divisor;
double raw = static_cast<double>(intermediate);
if (raw == 0 && principal != 0) raw = 1;
raw = std::trunc(raw);
if (!std::isfinite(raw) || raw < std::numeric_limits<int32_t>::min()
|| raw > std::numeric_limits<int32_t>::max())
throw std::invalid_argument("invalid native credit amount");
return static_cast<int32_t>(raw);
}
void balance(const BankCreditContext& c, BankCreditDraft& d) {
int32_t result = add(c.cash, signed_word(d.values[0]));
result = sub(result, signed_word(c.saved[0]));
result = sub(result, signed_word(d.values[6]));
result = add(result, d.refund);
result = sub(result, d.fees);
d.values[7] = word(sub(result, d.interest_adjustment));
}
}
BankCreditContext bank_credit_context(const GameState& g, const LeImage& exe, int manager, int counterparty) {
BankCreditContext c;
if (manager < 0 || size_t(manager) >= g.manager_teams.size()
|| g.manager_records.size() < (size_t(manager) + 1) * kRecord) return c;
// case 5: another human manager lends (row lender + 1 of the borrower's matrix)
if (counterparty < 0 || counterparty > 4 || counterparty - 1 == manager ||
(counterparty > 0 && size_t(counterparty - 1) >= g.manager_teams.size())) return c;
c.counterparty = counterparty;
const uint32_t at = kLoans + uint32_t(manager) * 0x78 + uint32_t(counterparty) * 0x18;
try {
for (size_t i = 0; i < c.saved.size(); ++i) c.saved[i] = g.memory.u32(at + uint32_t(i) * 4);
for (size_t i = 0; i < c.rate_table.size(); ++i) c.rate_table[i] = exe.u8(::bmh::layout::BankCredit_BankCreditContext_RuntimeField3 + uint32_t(i));
const uint64_t bits = uint64_t(exe.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField)) | uint64_t(exe.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField2)) << 32;
c.divisor = std::bit_cast<double>(bits);
const size_t rec = size_t(manager) * kRecord;
c.cash = signed_word(read_record(g, rec + 0x314));
c.overdraft = signed_word(read_record(g, rec + 0x31c));
if (counterparty > 0) {
const size_t lender = size_t(counterparty - 1) * kRecord;
c.lender_liquidity = add(signed_word(read_record(g, lender + 0x314)), signed_word(read_record(g, lender + 0x31c)));
}
c.available = c.divisor == 100.0 && c.saved[3] <= 48 && c.saved[4] <= 48;
for (auto factor : c.rate_table) c.available = c.available && factor > 100;
} catch (const std::out_of_range&) { return {}; }
return c;
}
bool change_bank_credit_interest(GameState& g, int manager, uint8_t new_rate) {
if (manager < 0 || size_t(manager) >= g.manager_teams.size() || !g.credit_rate_table_available)
return false;
const uint32_t at = kLoans + uint32_t(manager) * 0x78;
for (uint32_t i = 0; i < 24; ++i) if (!g.memory.has(at + i)) return false;
try {
const int32_t principal = signed_word(g.memory.u32(at));
const int32_t term = signed_word(g.memory.u32(at + 12));
const int32_t elapsed = signed_word(g.memory.u32(at + 16));
const int32_t remaining = sub(principal, mul(divide(principal, term), elapsed));
const int32_t adjusted = divide(remaining, 100);
const int32_t next_principal = mul(adjusted, 100 - int32_t(new_rate));
const int32_t next_term = sub(term, elapsed);
BankCreditContext c;
c.rate_table = g.credit_rate_table;
c.divisor = g.credit_divisor;
const uint32_t payment = word(amount(c, uint32_t(next_term), next_principal));
g.memory.set32(at, word(next_principal));
g.memory.set32(at + 12, word(next_term));
g.memory.set32(at + 16, 0);
g.memory.set32(at + 20, 0);
g.memory.set32(at + 8, payment);
g.memory.set32(at + 4, payment * uint32_t(next_term));
return true;
} catch (const std::exception&) { return false; }
}
BankCreditDraft bank_credit_draft(const BankCreditContext& c) {
BankCreditDraft d;
for (size_t i = 0; i < c.saved.size(); ++i) d.values[i] = c.saved[i];
// Source clears the working paid field after its first rendering. The UI
// still uses the saved field for that initial display.
d.values[5] = 0;
d.values[7] = word(c.cash);
return d;
}
BankCreditBounds bank_credit_bounds(const BankCreditContext& c, const BankCreditDraft& d, int field) {
if (!c.available || (field != 0 && field != 1 && field != 3 && field != 6 && !(field == 2 && c.counterparty))
|| (field == 6 && !c.saved[0])) return {};
try {
const auto& v = d.values;
int32_t accrued = 0;
if (v[0]) {
const uint32_t elapsed = v[4] ? v[4] : 1;
accrued = sub(mul(amount(c, elapsed, signed_word(v[0])), signed_word(elapsed)),
signed_word(v[5]));
}
const int32_t liquidity = add(c.cash, c.overdraft);
int32_t lo = 0, hi = 0;
if (field == 0) {
lo = 1000;
hi = sub(12000000, accrued);
// case 5: no more than the lender can pay out (balance + credit line)
if (c.counterparty && c.lender_liquidity < hi) hi = sub(c.lender_liquidity, accrued);
}
if (field == 2) {
// case 5 only: the monthly payment within 20 % of the annuity (Amount
// with the term and the net principal); the input starts at the annuity of
// the whole principal
const int32_t rate = amount(c, v[3], signed_word(v[0] - v[6]));
lo = sub(rate, rate / 5);
hi = add(rate, rate / 5);
if (lo >= hi || lo < 0) return {};
return {word(lo), word(hi), word(amount(c, v[3], signed_word(v[0]))), true};
}
if (field == 1) { lo = c.cash < accrued ? sub(accrued, liquidity) : liquidity; hi = accrued; }
if (field == 3) {
lo = 1;
hi = amount(c, v[3], signed_word(v[0] - v[6])) == 0 ? 0 : 48;
}
if (field == 6) { hi = liquidity < accrued ? liquidity : signed_word(v[0]); }
// Source checks availability before overriding the principal bounds.
if (lo >= hi) return {};
if (field == 0 && lo < signed_word(c.saved[0])) { lo = signed_word(c.saved[0]); hi = 12000000; }
if (lo < 0 || hi < 0 || lo >= hi) return {};
return {word(lo), word(hi), word(lo - (lo == 1)), true};
} catch (const std::invalid_argument&) { return {}; }
}
bool edit_bank_credit(const BankCreditContext& c, BankCreditDraft& draft, int field, uint32_t value) {
const auto bounds = bank_credit_bounds(c, draft, field);
if (!bounds.available || value < bounds.minimum || value > bounds.maximum) return false;
BankCreditDraft d = draft;
try {
if (!d.interest_adjustment) {
d.principal_paid = c.saved[3]
? mul(signed_word(c.saved[4]), divide(signed_word(c.saved[0]), signed_word(c.saved[3])))
: mul(signed_word(c.saved[0]), signed_word(c.saved[4]));
}
d.values[field] = value;
// fees only for the bank (case 4)
d.fees = !c.counterparty && c.saved[0] && (d.values[6] || d.values[3] != c.saved[3]) ? 5000 : 0;
if (!d.interest_adjustment && (field == 0 || field == 3 || field == 6)) {
const int32_t term = c.saved[3] ? signed_word(c.saved[3]) : 1;
const int32_t saved_p = signed_word(c.saved[0]);
const int32_t remaining = sub(saved_p, d.principal_paid);
const int32_t interest = sub(sub(amount(c, 1, saved_p), saved_p),
sub(amount(c, 1, remaining), remaining));
d.interest_adjustment = divide(mul(interest, signed_word(c.saved[3] - c.saved[4])), term);
d.refund = mul(signed_word(c.saved[4]), divide(saved_p, term));
d.values[4] = d.values[5] = 0;
d.principal_paid = 0;
}
if (field != 2 && field != 3 && field != 6) d.values[3] = 48;
const int32_t net = signed_word(d.values[0] - d.values[6]);
// a monthly payment set in case 5 stays; every other edit computes the annuity
if (field != 2) d.values[2] = net ? word(amount(c, d.values[3], net)) : 0;
if (d.fees) d.fees = add(d.fees, sub(amount(c, 1, signed_word(d.values[6])), signed_word(d.values[6])));
d.values[1] = d.values[2] * d.values[3];
d.initial_display = false;
d.edits.push_back({field, value});
balance(c, d);
} catch (const std::invalid_argument&) { return false; }
draft = std::move(d);
return true;
}
BankCreditResult commit_bank_credit(GameState& g, const LeImage& exe, int manager,
const std::array<uint32_t, 6>& expected, const std::vector<BankCreditEdit>& edits, bool accept_fees,
int counterparty) {
if (manager < 0 || size_t(manager) >= g.manager_teams.size()) return {BankCreditStatus::invalid_manager};
const auto c = bank_credit_context(g, exe, manager, counterparty);
if (!c.available) return {BankCreditStatus::invalid_state};
if (c.saved != expected) return {BankCreditStatus::stale_request};
if (edits.empty()) return {BankCreditStatus::no_change};
if (edits.size() > 4096) return {BankCreditStatus::invalid_request};
auto d = bank_credit_draft(c);
for (const auto& edit : edits)
if (!edit_bank_credit(c, d, edit.field, edit.value)) return {BankCreditStatus::invalid_request};
// only the bank charges (and asks for) fees and the interest adjustment
const int32_t fees = c.counterparty ? 0 : add(d.fees, d.interest_adjustment);
const int lender = c.counterparty - 1;
if (fees && !accept_fees) return {BankCreditStatus::confirmation_required, fees, d.refund};
auto resulting_record = c.saved;
if (!d.values[1]) resulting_record.fill(0);
else {
for (size_t i = 0; i < 5; ++i) resulting_record[i] = d.values[i];
resulting_record[0] -= d.values[6];
if (signed_word(resulting_record[1]) < signed_word(resulting_record[0]))
resulting_record[1] += resulting_record[0];
if (signed_word(resulting_record[0]) < 1) resulting_record[0] = 1;
if (d.refund) resulting_record[4] = resulting_record[5] = 0;
}
if (!fees && !d.refund && c.saved[0] - d.values[0] + d.values[6] == 0
&& resulting_record == c.saved) return {BankCreditStatus::no_change};
GameState staged = g;
if (fees) book_money(staged, manager, fees, true, false);
if (d.refund) {
d.values[4] = 0;
// the repaid part comes back from the bank or from the lender
if (lender >= 0) book_money(staged, lender, d.refund, true, false);
book_money(staged, manager, sub(0, d.refund), true, false);
}
const int32_t principal_change = signed_word(c.saved[0] - d.values[0] + d.values[6]);
book_money(staged, manager, principal_change, true, false);
if (lender >= 0) book_money(staged, lender, sub(0, principal_change), true, false);
const uint32_t at = kLoans + uint32_t(manager) * 0x78 + uint32_t(c.counterparty) * 0x18;
if (!d.values[1]) {
for (uint32_t i = 0; i < 6; ++i) staged.memory.set32(at + i * 4, 0);
} else {
d.values[0] -= d.values[6];
if (signed_word(d.values[1]) < signed_word(d.values[0])) d.values[1] += d.values[0];
if (signed_word(d.values[0]) < 1) d.values[0] = 1;
for (uint32_t i = 0; i < 5; ++i) staged.memory.set32(at + i * 4, d.values[i]);
if (d.refund) staged.memory.set32(at + 20, 0);
}
g = std::move(staged);
return {BankCreditStatus::accepted, fees, d.refund};
}
} // namespace bmh
+70
View File
@@ -0,0 +1,70 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <array>
#include <cstdint>
#include <vector>
#include "formats/le.hpp"
#include "game/state.hpp"
namespace bmh {
// MaxSharesToBuy case 4 (the bank) and case 5 (another manager lends). Row c of
// each manager's native 0x78-byte loan matrix (Loans + borrower * 0x78 + c * 0x18)
// is the credit from the bank (c = 0) or from manager c - 1, and contains principal,
// total, monthly payment, term, elapsed months and payments made. Case 5 differs only
// in: the principal is limited by the lender's balance plus credit line, the monthly
// payment (field 2) can be set within 20 % of the annuity, there are no fees and no
// fee question, and every booking is mirrored on the lender. The original asks the
// lender nothing. Projection and draft editing are read-only.
struct BankCreditContext {
int counterparty = 0; // 0 the bank, else lender manager + 1
int32_t lender_liquidity = 0; // case 5: lender balance (+0x314) + credit line (+0x31c)
std::array<uint32_t, 6> saved{};
std::array<uint8_t, 49> rate_table{};
double divisor = 0;
int32_t cash = 0, overdraft = 0;
bool available = false;
};
struct BankCreditEdit {
int field = -1;
uint32_t value = 0;
friend bool operator==(const BankCreditEdit&, const BankCreditEdit&) = default;
};
struct BankCreditDraft {
std::array<uint32_t, 8> values{};
int32_t fees = 0, interest_adjustment = 0, refund = 0, principal_paid = 0;
bool initial_display = true;
std::vector<BankCreditEdit> edits;
};
struct BankCreditBounds {
uint32_t minimum = 0, maximum = 0, initial = 0;
bool available = false;
};
BankCreditContext bank_credit_context(const GameState&, const LeImage&, int manager, int counterparty = 0);
// ChangeBankCreditInterest: apply the automatic interest change to the bank loan record.
bool change_bank_credit_interest(GameState&, int manager, uint8_t new_rate);
BankCreditDraft bank_credit_draft(const BankCreditContext&);
BankCreditBounds bank_credit_bounds(const BankCreditContext&, const BankCreditDraft&, int field);
bool edit_bank_credit(const BankCreditContext&, BankCreditDraft&, int field, uint32_t value);
enum class BankCreditStatus {
accepted, no_change, invalid_manager, invalid_state, invalid_request,
stale_request, confirmation_required
};
struct BankCreditResult {
BankCreditStatus status = BankCreditStatus::invalid_request;
int32_t fees = 0, refund = 0;
};
// Replay the local Source edits against the current native record before
// booking; fees and refund are derived here, never trusted from a UI amount.
BankCreditResult commit_bank_credit(GameState&, const LeImage&, int manager,
const std::array<uint32_t, 6>& expected, const std::vector<BankCreditEdit>& edits,
bool accept_fees, int counterparty = 0);
} // namespace bmh
+689
View File
@@ -0,0 +1,689 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/career.hpp"
#include <algorithm>
#include "game/messages.hpp"
#include "game/schedule.hpp"
namespace bmh {
namespace {
constexpr size_t kPoolSlots = 2928; // CareerRuntimeField: the clubs' squads end here
constexpr size_t kTailFrom = 2928 + 40;
constexpr size_t kTailTo = 2972; // CareerRuntimeField2
constexpr size_t kExtraSlots = 3096; // CareerSession_DataDirectory_RuntimeField4: 54 extra players from here
constexpr size_t kSquadSlots = 3096 + 54;
constexpr int kLeagueTeams = 138; // CareerSession_DispatchLineup_RuntimeField
// LeagueSizes: clubs per league; LeagueStrengthRanges: (minimum, maximum) strength per league.
// (the clubs per league are kLeagueSizes, schedule.hpp)
constexpr int kLeagueStrength[9][2] = {{71, 93}, {49, 71}, {28, 49}, {28, 49}, {10, 28},
{85, 95}, {90, 95}, {75, 95}, {80, 95}};
} // namespace
void generate_player(GameState& g, int id, int level_flags, GameRandom& game, WatcomRandom& rand) {
Player& p = g.players.at(size_t(id));
const bool keep_age = (level_flags & 0x1000) != 0, exact = (level_flags & 0x2000) != 0;
const int level = int16_t(level_flags & 0x0fff);
uint32_t w = 0x3000000; // goalkeepers
if ((p.w364 & 3) != 0) {
w = uint32_t(game.range(0, 7)) << 24;
w += uint32_t(game.range(0, 7)) << 21;
}
const int lo = exact ? level : level - level / 10, hi = exact ? level : level + level / 10;
const int condition = std::clamp(int(int16_t(game.range(lo, hi))), 10, 0x63); // ClampInteger
w += uint32_t(condition) << 14;
const int technique = std::clamp(int(int16_t(game.range(lo, hi))), 10, 0x63);
w += uint32_t(technique) << 7;
p.w35c = w + uint32_t(game.range(0x23, 0x41));
p.w368 = (p.w368 & 0xff03c000u) + uint32_t(rand.range(0, 0x3fff));
p.w364 &= ~(0x1fu << 21);
if (!keep_age) p.w364 |= uint32_t(game.range(2, 5)) << 21;
}
std::vector<uint16_t> startup_squad_list(const Database& db) {
std::vector<uint16_t> slots(kSquadSlots, 0x0fff);
for (size_t i = 0; i + 1 < db.squad_list.size() && i / 2 < slots.size(); i += 2)
slots[i / 2] = uint16_t(db.squad_list[i] | db.squad_list[i + 1] << 8);
std::copy_backward(slots.begin() + long(kTailFrom), slots.begin() + long(kTailFrom + (kSquadSlots - kTailTo)), slots.end());
return slots;
}
void startup_players(GameState& g, GameRandom& game, WatcomRandom& rand) {
for (size_t i = 0; i < 0x36; i++) {
const int level = rand.range(i < 0x16 ? 0x14 : 0x46, 0x5a);
generate_player(g, int16_t(g.squad_slots.at(kExtraSlots + i)), int16_t(level), game, rand);
}
int previous = 0, index = -1; // local_18, local_1c
for (int team = 0; team < kLeagueTeams; team++) {
const int league = team_league(team);
index = league == previous ? index + 1 : 0;
previous = league;
const uint32_t count = uint32_t(kLeagueSizes[league]);
const uint32_t range = uint32_t(kLeagueStrength[league][1] - kLeagueStrength[league][0]);
const int level = int16_t(int((count - uint32_t(index)) * range * 100) / int(count) / 100) + kLeagueStrength[league][0];
const SquadRange r = squad_range(team);
for (size_t s = r.first; s < r.first + r.count; s++) {
const int id = g.squad_slots.at(s) & 0x0fff;
if (id != 0x0fff) generate_player(g, id, level | 0x1000, game, rand);
}
}
}
} // namespace bmh
#include "formats/le.hpp"
#include "formats/savestate.hpp"
namespace bmh {
GameState startup_state(const LeImage& exe, const Database& db, const Bytes& m3_men, const Bytes& m3_dat) {
const DbCounts counts;
const std::vector<SaveBlock> layout = save_layout(counts, true);
Bytes stream;
for (const SaveBlock& b : layout) {
Bytes data(b.size, 0);
auto put = [&](const Bytes& src, size_t at = 0) {
for (size_t i = 0; i < src.size() && at + i < data.size(); i++) data[at + i] = src[i];
};
if (!b.heap) {
for (size_t i = 0; i < b.size; i++)
if (exe.contains(b.address + uint32_t(i))) data[i] = exe.u8(b.address + uint32_t(i));
}
switch (b.address) {
case ::bmh::layout::PlayerBonuses: if (b.heap) put(db.raw_player_bonus_values); break;
case ::bmh::layout::ClubBadgeSelectors: if (b.heap) put(db.raw_club_badge_selectors); break;
case ::bmh::layout::ClubIdentities: if (b.heap) put(db.raw_club_name_offsets); break;
case ::bmh::layout::PlayerNameOffsets: if (b.heap) put(db.raw_player_name_offsets); break;
case ::bmh::layout::MasterDatabaseMetadata: if (b.heap) put(db.raw_database_metadata); break;
case ::bmh::layout::ClubAuxiliaryWords: if (b.heap) put(db.raw_club_auxiliary_words); break;
case ::bmh::layout::ForeignClubStrength: put(db.raw_foreign_club_strength); break;
case ::bmh::layout::Career_Put_ExecutableField3: put(db.raw_league_auxiliary_bytes); break;
case ::bmh::layout::RefereeProperties: put(db.raw_referee_properties); break;
case ::bmh::layout::ClubKitSelectors: put(db.raw_club_kit_selectors); break;
case ::bmh::layout::ClubShortNameOffsets: put(db.raw_club_short_name_offsets); break;
case ::bmh::layout::ClubSeasonRecords: if (!b.heap) data[0] = 1; break; // the pointer: records allocated
case ::bmh::layout::NextDeskManager:
for (size_t m = 0; m < 4; m++) data[m * 2] = uint8_t(m), data[m * 2 + 1] = 0;
break;
case ::bmh::layout::ManagerAutomation:
for (size_t m = 0; m < 4; m++) data[m * 5] = 1;
break;
case ::bmh::layout::ActiveManager: data[0] = 4; break;
case ::bmh::layout::Desktops:
for (size_t k = 0; k < 5; k++) put(m3_men, k * 0x360);
break;
case ::bmh::layout::Formations:
put(m3_dat);
for (size_t k = 1; k < 4; k++)
for (size_t i = 0; i < 0x160; i++) data[k * 0x160 + i] = data[i];
break;
case ::bmh::layout::SquadSlots:
if (b.heap) {
const std::vector<uint16_t> slots = startup_squad_list(db);
for (size_t i = 0; i < slots.size() && 2 * i + 1 < data.size(); i++)
data[2 * i] = uint8_t(slots[i]), data[2 * i + 1] = uint8_t(slots[i] >> 8);
}
break;
case ::bmh::layout::PlayerConditionTechniqueForm:
case ::bmh::layout::PlayerSkillWords:
case ::bmh::layout::PlayerIdentityWords:
if (b.heap) {
for (size_t i = 0; i < db.players.size() && 4 * i + 3 < data.size(); i++) {
uint32_t w = b.address == ::bmh::layout::PlayerConditionTechniqueForm ? db.players[i].w35c : b.address == ::bmh::layout::PlayerSkillWords ? db.players[i].w368 : db.players[i].w364;
if (b.address == ::bmh::layout::PlayerSkillWords && i + 32 >= db.players.size())
w = (w & 0x07ffffffu) | uint32_t(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField4 - uint32_t(db.players.size() - i))) << 27;
for (int k = 0; k < 4; k++) data[4 * i + size_t(k)] = uint8_t(w >> (8 * k));
}
}
break;
default: break;
}
stream.insert(stream.end(), data.begin(), data.end());
}
for (const Bytes& pool : db.pools) {
stream.push_back(uint8_t(pool.size()));
stream.push_back(uint8_t(pool.size() >> 8));
stream.insert(stream.end(), pool.begin(), pool.end());
}
const SaveState save(stream, counts);
GameState g = GameState::from_save(save, counts);
competition_pointers(g.memory, exe); // CompetitionPointers
return g;
}
} // namespace bmh
#include "game/matchday.hpp"
#include "game/season.hpp"
#include "game/week.hpp"
namespace bmh {
void new_career_markets_and_moods(GameState& g, GameRandom& game, WatcomRandom& rand) {
StaticMemory& mem = g.memory;
for (uint32_t k = 0; k < 12; k++) {
if (k < 6) mem.set32(::bmh::layout::FundBlock + k * 0x1c, (1u << k) * 100000);
const size_t s = size_t(k) * 0x5c;
const uint32_t value = k * 2000 + 10000;
for (int i = 0; i < 4; i++) g.stocks.at(s + size_t(i)) = uint8_t(value >> (8 * i));
g.stocks.at(s + 0x4e) = uint8_t(k * 20 + 100), g.stocks.at(s + 0x4f) = uint8_t((k * 20 + 100) >> 8);
}
stir_random(game, rand);
const int first = game.range(0, 1);
if (g.texts) {
auto name = [&](int record, uint32_t pointer) {
const std::string& t = (*g.texts)[(pointer - ::bmh::layout::TextPointerTable) / 4];
const size_t at = size_t(record) * 0xb0c + 0xa8;
for (size_t i = 0; i <= t.size(); i++) g.manager_records.at(at + i) = i < t.size() ? uint8_t(t[i]) : 0;
};
name(first, ::bmh::layout::Career_NewCareerMarketsAndMoods_ExecutableField);
name(1 - first, ::bmh::layout::Career_NewCareerMarketsAndMoods_ExecutableField2);
name(2, ::bmh::layout::Career_NewCareerMarketsAndMoods_ExecutableField3);
name(3, ::bmh::layout::Career_NewCareerMarketsAndMoods_ExecutableField4);
}
for (int day = 0; day < 30; day++) stock_market(g, game);
for (uint32_t i = 0; i < 900; i++) mem.set8(::bmh::layout::Titles + i, 0xff);
for (uint32_t i = 0; i < 4; i++) mem.set8(::bmh::layout::Career_NewCareerMarketsAndMoods_RuntimeField2 + i, uint8_t(1 << i));
for (uint32_t i = 0; i < 0x2c; i++) mem.set16(::bmh::layout::Career_NewCareerMarketsAndMoods_RuntimeField + i * 0x58, 0xfff);
reset_club_moods(g, game, rand, true);
}
bool new_career_players(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report) {
for (size_t slot = 0; slot < 2928; slot++) {
const int id = g.squad_slots.at(slot) & 0x0fff;
if (id == 0x0fff) continue;
Player& p = g.players.at(size_t(id));
p.w364 |= uint32_t(rand.range(4, 0x10)) << 21;
p.w368 = (p.w368 & 0xffffc000u) + uint32_t(rand.range(0, 0x3fff));
}
for (int slot = 3096; slot < 3096 + 0x36; slot++)
if (!release_player(g, slot, game, rand, report)) return false;
return !report.unsupported;
}
bool new_career_before_dialog(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report) {
// CareerFirstSteps2 clears all four pending offers immediately before calling
// InitializeCareer. Raw executable BSS starts at zero, which is a valid offer
// for manager/player zero in ResolvePendingOffer, rather than the empty sentinel.
for (uint32_t offer = 0; offer < 4; ++offer)
g.memory.set32(::bmh::layout::OfferSlots + offer * 4, 0xffffffff);
new_career_markets_and_moods(g, game, rand);
return new_career_players(g, game, rand, report);
}
} // namespace bmh
#include "game/lineup.hpp"
#include "game/national.hpp"
#include "game/weekly.hpp"
namespace bmh {
namespace {
constexpr size_t kRecord = 0xb0c;
uint16_t team_of(const GameState& g, int m) {
const size_t at = size_t(m) * kRecord + 0x290;
return uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8);
}
// FindManagerForClub: a club of a human manager (manager slot 4 counts when manager 0 coaches
// the national team).
bool human_club(const GameState& g, int team) {
const int managers = g.memory.u8(::bmh::layout::ManagerCount);
for (int m = 0; m < managers; m++)
if (team_of(g, m) == uint16_t(team)) return true;
return team_of(g, 0) == 0x165 && team_of(g, 4) == uint16_t(team);
}
// OpenBMH deviates from the original: skips reserved calendar positions when assigning a joining manager to a club.
// The supported rule profile patch reserves club places whose calendar word (CompetitionCalendar, read with the
// club id as index) has the bits 0x4001.
bool reserved_place(const GameState& g, int team) {
return team >= 0 && (g.memory.u16(::bmh::layout::CompetitionCalendar + uint32_t(team) * 2) & 0x4001) == 0x4001;
}
// EuropeanClub: only the active prefixes of the three European lists count.
bool european_club(const GameState& g, int team) {
for (const auto& entry : {std::pair<uint32_t, uint32_t>{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25, ::bmh::layout::Career_EuropeanClub_ExecutableField},
{::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14, ::bmh::layout::Career_EuropeanClub_ExecutableField2}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19, ::bmh::layout::Career_EuropeanClub_ExecutableField3}})
for (uint32_t i = 0; i < g.memory.u8(entry.second); ++i)
if (g.memory.u16(entry.first + i * 2) == uint16_t(team)) return true;
return false;
}
// RemoveJoinTransfers: remove a joining club's sale entries and parallel bid fields.
void remove_join_transfers(GameState& g, int team) {
StaticMemory& mem = g.memory;
for (uint32_t row = 0; row < 44; ++row) {
const uint32_t base = ::bmh::layout::EditorList + row * 0x58;
if ((mem.u16(base + 8) & 0x7fff) == uint16_t(team)) {
g.squad_slots.at(kPoolSlots + row) = kEmptySlot;
continue;
}
int bid = 0;
while (bid < 4 && mem.u16(base + uint32_t(bid) * 2) != uint16_t(team)) ++bid;
if (bid == 4) continue;
const uint32_t found = uint32_t(bid);
if (bid != 3) {
for (uint32_t k = found; k < 3; ++k) {
mem.set16(base + k * 2, mem.u16(base + (k + 1) * 2));
mem.set32(base + 0xc + k * 4, mem.u32(base + 0xc + (k + 1) * 4));
mem.set32(base + 0x1c + k * 4, mem.u32(base + 0x1c + (k + 1) * 4));
mem.set8(base + 0x34 + k, mem.u8(base + 0x34 + k + 1));
for (uint32_t b = 0; b < 7; ++b)
mem.set8(base + 0x38 + k * 7 + b, mem.u8(base + 0x38 + (k + 1) * 7 + b));
}
++bid; // The Source terminator is found + 1, not always the last bid.
}
mem.set16(base + uint32_t(bid) * 2, 0xffff);
if (row > 39) {
g.squad_slots.at(kPoolSlots + row + 40) = kEmptySlot;
mem.set32(::bmh::layout::Career_RemoveJoinTransfers_RuntimeField + row * 4, 0xffffffff);
}
}
}
// ConfirmManager: clean loans only after the final club swap/remapping.
bool remove_join_loans(GameState& g, int team, MinuteReport& report) {
StaticMemory& mem = g.memory;
for (uint32_t i = 0; i < 200; ++i) {
const uint32_t at = ::bmh::layout::Career_RemoveJoinLoans_RuntimeField + i * 4, loan = mem.u32(at);
if (loan == 0) continue;
const int owner = int((loan >> 12) & 0x3ff), borrower = int((loan >> 22) & 0x3ff);
if (owner == team) mem.set32(at, 0);
else if (borrower == team) {
mem.set32(at, 0);
if (human_club(g, owner)) {
uint32_t k = 0;
while (k < 12 && mem.u16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + k * 2) != (loan & 0xfff)) ++k;
if (k == 12) {
report.fail("joining-manager loan has no human owner entry (PresentLoanReturn(0x3c))");
return false;
}
mem.set16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + k * 2, kEmptySlot);
}
}
}
return true;
}
void put32(std::vector<uint8_t>& v, size_t o, uint32_t x) {
for (int i = 0; i < 4; i++) v.at(o + size_t(i)) = uint8_t(x >> (8 * i));
}
// CareerAddManager2(team, mode): condition and technique of every player of a league club around
// a level of its league (mode 0 random W(min, max), 1 min + 3, 2 the middle + 1, 3 max - 3).
void set_club_strength(GameState& g, int team, int mode, WatcomRandom& rand) {
if (team >= kLeagueTeams) return;
const int league = team_league(team);
const int lo = kLeagueStrength[league][0], hi = kLeagueStrength[league][1];
int level = mode;
switch (mode) {
case 0: level = rand.range(lo, hi); break;
case 1: level = lo + 3; break;
case 2: level = (hi + lo) / 2 + 1; break;
case 3: level = hi - 3; break;
default: break;
}
level = int16_t(level);
const SquadRange r = squad_range(team);
for (size_t s = r.first; s < r.first + r.count; s++) {
const int id = g.squad_slots.at(s) & 0x0fff;
if (id == 0x0fff) continue;
Player& p = g.players.at(size_t(id));
const int condition = std::clamp(rand.range(level - 6, level + 6), 0, 99); // ClampInteger
const int technique = std::clamp(rand.range(level - 6, level + 6), 0, 99);
p.w35c = (p.w35c & 0xffe0007fu) | uint32_t(condition) << 14 | uint32_t(technique) << 7;
}
}
// CareerAddManager3(record, league, mode): the stadium of a human club - eight stand blocks
// (Career_BuildStadium_RuntimeField4[league] thousand places each), the facilities of the league
// (Career_BuildStadium_RuntimeField, levels W(Career_BuildStadium_RuntimeField2, Career_BuildStadium_RuntimeField3) << 2) and eight block values W(100, 140).
// Mode 1 (CareerDuration) builds everything one step better.
void build_stadium(GameState& g, const LeImage& exe, int m, int league, int mode, WatcomRandom& rand) {
uint8_t* rec = &g.manager_records.at(size_t(m) * kRecord);
for (int k = 0; k < 8; k++) {
rec[0x4c + k] = uint8_t(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField4 + uint32_t(league)) + (mode == 1 ? 1 : 0));
rec[0x5c] = uint8_t(rec[0x5c] + rec[0x4c + k]);
}
for (int i = 0; i < 0x16; i++) {
const uint8_t level = mode == 1 ? 3 : exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField + uint32_t(i + league * 0x17));
if (i == 0x10 || i == 0x11 || level == 0) continue;
if (i == 0) {
rec[0] = uint8_t(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField + uint32_t(league * 0x17)) + (mode == 1 ? 0x55 : 0));
} else {
rec[i] = uint8_t(rand.range(exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField2 + uint32_t(i * 5)), exe.u8(::bmh::layout::Career_BuildStadium_RuntimeField3 + uint32_t(i * 5))) << 2);
}
if (i > 0xd) rec[i + 0x2e] = uint8_t(level + (mode == 1 ? 1 : 0));
}
rec[0x3f] = rec[0x3e] = uint8_t((mode == 1) + 1);
for (int k = 0x16; k < 0x1e; k++) rec[k] = uint8_t(rand.range(100, 0x8c));
}
} // namespace
// StartingSponsors: in mode GameMode == 1 or in the one-year mode before
// the first season day, the three sponsor contracts start at the value for the
// selected league and difficulty. Use GameState.date: memory CalendarDay can be
// stale in the port after a new-career/season transition.
void starting_sponsors(GameState& g, int m) {
const StaticMemory& mem = g.memory;
if (!(mem.u8(::bmh::layout::GameMode) == 1 || (mem.u8(::bmh::layout::CareerDuration) == 1 && g.date == 0))) return;
const size_t rec = size_t(m) * kRecord;
int league = g.manager_records.at(rec + 0x210);
if (league > 2) league--;
const int v = (((league * -20 + 80) * 60000 + 1000000) / 12 * (mem.u8(::bmh::layout::Difficulty) * -5 + 0xaa)) / 3000000 * 10000;
for (size_t o : {size_t(0xae8), size_t(0xadc), size_t(0xa34)}) put32(g.manager_records, rec + o, uint32_t(v));
for (size_t o : {size_t(0xaed), size_t(0xae1), size_t(0xa39)}) g.manager_records.at(rec + o) = 1;
}
void career_managers_begin(GameState& g, bool adding) {
g.memory.add_block(::bmh::layout::CareerSession_FormatError_RuntimeField6, 1);
g.memory.set8(::bmh::layout::CareerSession_FormatError_RuntimeField6, 1);
const size_t rec = 4 * kRecord;
put32(g.manager_records, rec + 0x314, 1000000);
put32(g.manager_records, rec + 0x324, 1000000);
for (size_t i = 0; i < 0xd; i++) g.manager_records.at(rec + 0xc5 + i) = 2;
if (adding) {
const size_t count = g.memory.u8(::bmh::layout::ManagerCount);
g.manager_teams.resize(count);
for (size_t m = 0; m < count; ++m) g.manager_teams[m] = team_of(g, int(m));
} else g.manager_teams.assign(g.memory.u8(::bmh::layout::ManagerCount), 0);
// ConfirmManager(0) posts PostSeasonNotice(0xff) immediately after the accepted
// new-career options dialog. The join path starts at a nonzero manager slot and
// must not repeat these three introduction messages.
if (adding || g.manager_teams.empty() || g.manager_teams.size() > 4) return;
post_text(g, -1, 1001); // CareerRuntimeField3
post_text(g, -1, 1002); // CareerRuntimeField4
post_text(g, -1, 1003); // CareerRuntimeField5
}
bool career_add_manager(GameState& g, const LeImage& exe, int m, const CareerManager& choice, bool adding,
GameRandom& game, WatcomRandom& rand, MinuteReport& report) {
// Reject malformed requests before changing records or consuming either RNG.
if (!g.memory.has(::bmh::layout::ManagerCount) || m < 0 || m >= 4 ||
g.memory.u8(::bmh::layout::ManagerCount) > 4 || m >= g.memory.u8(::bmh::layout::ManagerCount) ||
size_t(m) >= g.manager_teams.size() || g.manager_records.size() < 5 * kRecord ||
choice.team < 0 || choice.team >= 168 || size_t(choice.team) >= g.club_ids.size() ||
choice.league < 0 || choice.league > 4 || choice.strength < 0 || choice.strength > 2 ||
choice.portrait < 0 || choice.portrait > 11 || choice.name.size() > 24 ||
g.tactics.size() < size_t(m + 1) * 0x840 ||
g.manager_ratings.size() < size_t(m + 1) * 0x3c ||
g.manager_results.size() < g.manager_teams.size() * 0x690 ||
g.squad_slots.size() < kSquadSlots || g.club_ids.size() < 168 ||
g.team_morale.size() < 168 || g.team_flags.size() < 168 ||
g.club_heap_bc.size() < 168 * 2 || g.club_heap_78.size() < 168 * 2 ||
g.club_heap_b8.size() < 168 || g.position_history.size() < 138 * 0x1a ||
(!g.club_table.empty() && g.club_table.size() < 168 * 0x4a) ||
g.player_bonus.size() < g.players.size() || g.player_cards.size() < g.players.size() ||
!exe.contains(::bmh::layout::Career_CareerAddManager_ExecutableField) || !exe.contains(::bmh::layout::Career_BuildStadium_RuntimeField3 + 0x15 * 5) ||
!exe.contains(::bmh::layout::Career_BuildStadium_RuntimeField + 4 * 0x17 + 0x15)) {
report.fail("invalid career manager choice or slot");
return false;
}
for (int other = 0; other < m; ++other)
if (g.manager_teams[size_t(other)] == choice.team) {
report.fail("career manager club is already managed");
return false;
}
for (size_t slot = 0; slot < kPoolSlots; ++slot) {
const uint16_t player = g.squad_slots[slot] & 0x0fff;
if (player != kEmptySlot && size_t(player) >= g.players.size()) {
report.fail("invalid career manager squad player");
return false;
}
}
StaticMemory& mem = g.memory;
const size_t rec = size_t(m) * kRecord;
std::vector<uint8_t>& r = g.manager_records;
for (size_t i = 0; i < 0x12; i++) r.at(rec + 0x1f6 + i) = 1;
for (size_t i = 0; i < 10; i++) r.at(rec + 0x8b6 + i) = 0xff;
r.at(rec + 0x1f6) = 0x40;
// the values of the dialog (ManagerScreen2)
for (size_t i = 0; i < 0x19; i++) r.at(rec + 0xa8 + i) = i < choice.name.size() ? uint8_t(choice.name[i]) : 0;
r.at(rec + 0x290) = uint8_t(choice.team), r.at(rec + 0x291) = uint8_t(choice.team >> 8);
r.at(rec + 0x221) = uint8_t(choice.portrait);
r.at(rec + 0x210) = uint8_t(choice.league);
g.manager_teams.at(size_t(m)) = int16_t(choice.team);
int place = 1 + m; // the club's place in the first league
if (!adding && mem.u8(::bmh::layout::CareerDuration) <= 1) mem.set8(::bmh::layout::Career_CareerAddManager_RuntimeField, 0);
else place = m + 9;
while (reserved_place(g, place) || human_club(g, place) || (adding && european_club(g, place))) place++; // CareerAddManager4
int league = r.at(rec + 0x210); // local_18
const int team = int16_t(team_of(g, m));
if (adding) remove_join_transfers(g, team);
if (team_league(team) != league) {
int other = place;
if (league != 0) {
const int first = league_first_team(league), last = first + 12; // CareerRuntimeField6 (league * 18 in DE)
do other = int16_t(game.range(first, last));
while (human_club(g, other)); // ReservedPlace2
// ReservedPlace: the next of 13 places that is neither reserved nor human
int c = other;
for (int k = 0; k < 13; k++) {
if (!reserved_place(g, c) && !human_club(g, c)) {
other = c;
break;
}
if (++c > last) c -= 13;
}
}
if (adding) remove_join_transfers(g, other);
clubs_change_places(g, team, other);
set_club_strength(g, team, 0, rand);
place = 0;
}
if (league == 0 && place != 0) {
if (adding) remove_join_transfers(g, place);
clubs_change_places(g, int16_t(team_of(g, m)), place);
}
set_club_strength(g, int16_t(team_of(g, m)), choice.strength + 1, rand);
const int club = int16_t(team_of(g, m));
if (adding && !remove_join_loans(g, club, report)) return false;
g.team_morale.at(size_t(club)) |= 0x80;
r.at(rec + 0x26f) = 0x32;
if (league > 2) league--;
starting_sponsors(g, m);
r.at(rec + 0x26e) = uint8_t(std::max(20 - 2 * league, 14));
build_stadium(g, exe, m, league, mem.u8(::bmh::layout::CareerDuration), rand);
if (league > 2) league = 2;
for (uint32_t i = 0; i < 3; i++) {
const uint32_t base = ::bmh::layout::Career_CareerAddManager_RuntimeField2 + uint32_t(m) * 0x24;
mem.set8(base + i, uint8_t(0x52 - league * 15));
mem.set8(base + 3 + i, 6);
mem.set8(base + 6 + i, uint8_t(league));
mem.set32(base + 0x18 + i * 4, 5000);
}
const SquadRange squad = squad_range(club);
r.at(rec + 0x288) = 0x16;
for (size_t i = 0; i < 0xd; i++) r.at(rec + 0xc5 + i) = 2;
for (size_t i = 0; i < 6; i++) r.at(rec + 0x8aa + 2 * i) = 0x26, r.at(rec + 0x8ab + 2 * i) = 0x02;
for (size_t i = 0; i < 0x3c; i++) g.manager_ratings.at(size_t(m) * 0x3c + i) = 100;
const int players = adding ? squad_count(g, club, 2) : 20;
for (int i = 0; i < players; i++) {
const size_t slot = squad.first + size_t(i);
Player& p = g.players.at(size_t(g.squad_slots.at(slot) & 0x0fff));
p.w364 &= ~(0x1fu << 21);
p.w364 |= uint32_t(rand.range(4, 9)) << 21;
new_board_entry(g, m, i, int(slot), rand);
g.tactics.at(size_t(m) * 0x840 + size_t(i) * 0x58 + 0xd) = 100;
}
// Deviation from the original: a new career fills exactly 20 board rows (local_28 = 0x14),
// but new_career_players runs before the dialog and may already have moved a free agent
// into the chosen club (transfer_bid, "straight to the club"). That 21st player had no
// board row - no salary, and team_rating divides by his base pay (the original crashes
// once he plays). The remaining occupied rows get their entry the same way; with the
// usual 20 players nothing changes and no random number is drawn.
if (!adding)
for (size_t i = 20; i < squad.count && i < 24; i++) {
const size_t slot = squad.first + i;
const int id = g.squad_slots.at(slot) & 0x0fff;
if (id == 0x0fff) continue;
Player& p = g.players.at(size_t(id));
p.w364 &= ~(0x1fu << 21);
p.w364 |= uint32_t(rand.range(4, 9)) << 21;
new_board_entry(g, m, int(i), int(slot), rand);
g.tactics.at(size_t(m) * 0x840 + i * 0x58 + 0xd) = 100;
}
for (size_t i = 0; i < 0x690; i++) g.manager_results.at(size_t(m) * 0x690 + i) = 0xff;
const uint8_t level = mem.u8(::bmh::layout::Difficulty);
const uint32_t money = level == 0 ? 50000000u : 4000000u - level * 200000u;
put32(r, rec + 0x314, money);
put32(r, rec + 0x324, money);
r.at(rec + 0x219) = r.at(rec + 0x218) = 0xf;
put32(r, rec + 0x31c, uint32_t(400000 - league * 100000));
put32(r, rec + 0x310, 1);
auto_lineup(g, club, 100);
return !report.unsupported;
}
void career_managers_end(GameState& g, bool adding) {
g.memory.add_block(::bmh::layout::CareerSession_FormatError_RuntimeField6, 1);
g.memory.set8(::bmh::layout::CareerSession_FormatError_RuntimeField6, 0);
if (!adding)
for (uint32_t i = 0; i < 12; i++) g.memory.set16(::bmh::layout::Career_CareerManagersEnd_RuntimeField + i * 2, 0xfff);
}
} // namespace bmh
namespace bmh {
// The English counterpart of CompetitionPointers: the Football Limited GermanRoundTable. The cup table
// (translated to CupTable, launch/fltd.hpp) is the English one; its entries 0-24 have the
// same roles as in German, so their arrays are the German ones (same sizes). Different:
// entry 0 (FA Cup qualifying stage) and the English-only competitions - entry 28 (FA Cup
// proper), 25-27 (League Cup) and 35 - which use memory blocks at their English addresses
// (english_competition_blocks); there are no indoor tournaments and no Masters.
namespace {
// English round-string pointer tables -> the German ones the engine knows (cup.cpp)
uint32_t german_round_table(uint32_t en) {
switch (en) {
case ::bmh::layout::Career_GermanRoundTable_ExecutableField2: return ::bmh::layout::CareerSession_RuntimeError_RuntimeField; // 4 teams
case ::bmh::layout::Career_GermanRoundTable_ExecutableField3: return ::bmh::layout::CareerSession_RuntimeError_RuntimeField2; // 6
case ::bmh::layout::Career_GermanRoundTable_ExecutableField: return ::bmh::layout::CareerSession_RuntimeError_ExecutableField2; // 20
case ::bmh::layout::Career_GermanRoundTable_ExecutableField4: return ::bmh::layout::CareerSession_RuntimeError_RuntimeField3; // 12
default: return en;
}
}
void competition_pointers_english(StaticMemory& mem, const LeImage& exe) {
auto entry = [](uint32_t k) { return ::bmh::layout::CupTable + k * 0x28; };
english_competition_blocks(mem);
for (uint32_t k = 1; k < 0xf; k++) {
uint32_t b = k;
if (k > 9) b -= 9;
if (k > 0xc) b -= 3;
mem.set_pointer(entry(k) + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField);
mem.set_pointer(entry(k), ::bmh::layout::Field0 + b * 8 - 8);
mem.set_pointer(entry(k) + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13 + (b - 1) * 0xc);
}
uint32_t k = 7;
for (uint32_t i = 0; i < 8; i += 2, k++) {
if (k == 10) k = 0xc;
mem.set_pointer(entry(k), ::bmh::layout::Field0 + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField10 + i)) * 2);
mem.set_pointer(entry(k) + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13 + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField11 + i)) * 2);
}
const std::pair<uint32_t, uint32_t> single[] = {
{::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField2, ::bmh::layout::CareerSession_RuntimeError_RuntimeField2}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField3, ::bmh::layout::Field0}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13},
{::bmh::layout::CupTable, kEnglishFaQualifyingField}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField, kEnglishFaResults},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField2, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField3, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField22}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField4, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField23}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField5, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField30}};
for (const auto& [at, to] : single) mem.set_pointer(at, to);
for (uint32_t i = 0; i < 2; i++) mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField5 + i * 4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + i * 0x10);
for (uint32_t i = 0; i < 4; i++) {
const uint32_t e = entry(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField12 + i));
mem.set_pointer(e, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14 + i * 8 + 0x30);
mem.set_pointer(e + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + i * 0x18 + 0x20);
mem.set_pointer(e + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField);
}
mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField6, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField15);
for (uint32_t i = 0; i < 2; i++) mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField7 + i * 4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + 0x80 + i * 0xc);
const std::pair<uint32_t, uint32_t> more[] = {
{::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField8, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField16}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField9, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField18}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField6, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField7, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField26}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField8, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField21},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField9, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField20}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField10, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField27}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField11, ::bmh::layout::ReplayFixtures}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField12, ::bmh::layout::ReplayResults}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField13, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField14, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField15, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField16, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField29}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField17, ::bmh::layout::FriendlyTeams}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField18, ::bmh::layout::FriendlyDays},
// the English-only cup entry table (entries 25-28 and 35)
{entry(28), ::bmh::layout::EnglishFaCupProperField}, {entry(28) + 0xc, ::bmh::layout::EnglishFaCupStageResults}, // FA Cup proper
{entry(25), ::bmh::layout::EnglishLeagueCupFirstRoundField}, {entry(25) + 0xc, ::bmh::layout::EnglishLeagueCupFirstRoundResults}, // League Cup
{entry(26), ::bmh::layout::EnglishLeagueCupQuarterFinalField}, {entry(26) + 0xc, ::bmh::layout::EnglishLeagueCupQuarterFinalResults}, {entry(26) + 0x10, ::bmh::layout::EnglishLeagueCupQuarterFinalOtherLegResults},
{entry(27), ::bmh::layout::EnglishLeagueCupSemiFinalField}, {entry(27) + 0xc, ::bmh::layout::EnglishLeagueCupSemiFinalResults},
{entry(35) + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField}, {entry(35), ::bmh::layout::EnglishAdditionalCupField}, {entry(35) + 0xc, ::bmh::layout::EnglishAdditionalCupResults}};
for (const auto& [at, to] : more) mem.set_pointer(at, to);
// round tables the English table holds itself (static pointers to English strings)
for (uint32_t e = 0; e < 0x24; e++) {
const uint32_t at = entry(e) + 8;
const uint32_t p = mem.u32(at);
if (p >= ::bmh::layout::EnDataStart && p < ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField) mem.set_pointer(at, german_round_table(p));
}
}
} // namespace
void english_competition_blocks(StaticMemory& mem) {
for (const auto& [at, size] : kEnglishCompetitionBlocks)
if (!mem.has(at)) mem.add_block(at, size);
}
void competition_pointers(StaticMemory& mem, const LeImage& exe) {
if (kEnglishCompetitions) {
competition_pointers_english(mem, exe);
return;
}
auto entry = [](uint32_t k) { return ::bmh::layout::CupTable + k * 0x28; };
// the cups of the leagues 1..14 (entries 1..14)
for (uint32_t k = 1; k < 0xf; k++) {
uint32_t b = k;
if (k > 9) b -= 9;
if (k > 0xc) b -= 3;
mem.set_pointer(entry(k) + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField);
mem.set_pointer(entry(k), ::bmh::layout::Field0 + b * 8 - 8);
mem.set_pointer(entry(k) + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13 + (b - 1) * 0xc);
}
// entries 7, 8, 9, 12 (Career_CompetitionPointersEnglish_RuntimeField10 pairs)
uint32_t k = 7;
for (uint32_t i = 0; i < 8; i += 2, k++) {
if (k == 10) k = 0xc;
mem.set_pointer(entry(k), ::bmh::layout::Field0 + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField10 + i)) * 2);
mem.set_pointer(entry(k) + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13 + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField11 + i)) * 2);
}
const std::pair<uint32_t, uint32_t> single[] = {
{::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField2, ::bmh::layout::CareerSession_RuntimeError_RuntimeField2}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField3, ::bmh::layout::Field0}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField13}, {::bmh::layout::CupTable, ::bmh::layout::Field}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField, ::bmh::layout::Career_CompetitionPointers_ExecutableField},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField2, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField25}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField3, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField22}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField4, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField23}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField5, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField30}};
for (const auto& [at, to] : single) mem.set_pointer(at, to);
for (uint32_t i = 0; i < 2; i++) mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField5 + i * 4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + i * 0x10);
for (uint32_t i = 0; i < 4; i++) {
const uint32_t e = entry(exe.u8(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField12 + i));
mem.set_pointer(e, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField14 + i * 8 + 0x30);
mem.set_pointer(e + 0xc, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + i * 0x18 + 0x20);
mem.set_pointer(e + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField);
}
mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField6, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField15);
for (uint32_t i = 0; i < 2; i++) mem.set_pointer(::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField7 + i * 4, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField17 + 0x80 + i * 0xc);
const std::pair<uint32_t, uint32_t> more[] = {
{::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField8, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField16}, {::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField9, ::bmh::layout::Career_CompetitionPointersEnglish_RuntimeField18}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField6, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField19}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField7, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField26}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField8, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField21},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField9, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField20}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField10, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField27}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField11, ::bmh::layout::ReplayFixtures}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField12, ::bmh::layout::ReplayResults}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField13, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28},
{::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField14, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField15, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField16, ::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField29}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField17, ::bmh::layout::FriendlyTeams}, {::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField18, ::bmh::layout::FriendlyDays}};
for (const auto& [at, to] : more) mem.set_pointer(at, to);
// the indoor tournaments and the Masters (entries 25..29)
for (uint32_t i = 0; i < 5; i++) {
const uint32_t e = entry(0x19 + i);
mem.set_pointer(e + 8, ::bmh::layout::CareerSession_RuntimeError_RuntimeField);
mem.set_pointer(e + 0xc, ::bmh::layout::MatchdayGroupWorkspace + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointers_RuntimeField4 + i)) * 2);
mem.set_pointer(e, ::bmh::layout::Teams + uint32_t(exe.u8(::bmh::layout::Career_CompetitionPointers_RuntimeField5 + i)) * 2);
}
mem.set_pointer(::bmh::layout::Career_CompetitionPointers_RuntimeField2, ::bmh::layout::CareerSession_RuntimeError_RuntimeField);
mem.set_pointer(::bmh::layout::Career_CompetitionPointers_RuntimeField, ::bmh::layout::Teams);
mem.set_pointer(::bmh::layout::Career_CompetitionPointers_RuntimeField3, ::bmh::layout::MatchdayGroupWorkspace);
}
} // namespace bmh
+156
View File
@@ -0,0 +1,156 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#pragma once
// OpenBMH deviates from the original: uses the supported player-generation ranges and excludes reserved calendar positions when assigning managers.
// The start of a new career (BMH.exe V2.24 + supported rule profile patch).
//
// The original starts every career at program start: CareerFirstSteps2 loads the data files
// (TEXTD.BLK, M3.MEN, M3.DAT, M3D.MAN), gives every player new values and then calls
// InitializeCareer, which sets up shares, funds, club moods, ages and skills, shows the
// options and manager dialogs (SetupScreen2) inside ConfirmManager and finally prepares the
// first season. Loading a savegame from the options screen replaces all of that.
//
// The game generator starts at 0 (CareerSession_Save_RuntimeField is not initialised), the Watcom generator
// at the clock value of srand() - recordings capture it.
#include <cstdint>
#include <utility>
#include <string>
#include "formats/m3d.hpp"
#include "game/match_engine.hpp"
#include "game/random.hpp"
#include "game/state.hpp"
namespace bmh {
// OpenBMH deviates from the original: uses the supported player-generation ranges and excludes reserved calendar positions when assigning managers.
// GeneratePlayer with the supported rule profile patch GeneratePlayer2: new values for player `id` around
// `level` (low 12 bits of `level_flags`; 0x1000 = leave the age at 0, 0x2000 = exactly
// the level instead of +-10 %):
// - w35c bits 21-26: G(0, 7) << 3 | G(0, 7) for field players, 0x18 for goalkeepers
// (two game draws, high part first);
// - condition and technique G(level - level / 10, level + level / 10), each cut to
// 10..99; form G(35, 65); bits 27-31 cleared;
// - w368: skills W(0, 0x3fff), bits 18-23 (cards) cleared;
// - w364: age bits cleared, then (without 0x1000) G(2, 5) = 18..21 years.
void generate_player(GameState& g, int id, int level_flags, GameRandom& game, WatcomRandom& rand);
// The part of CareerFirstSteps2 after loading M3D.MAN: the 54 players of the extra slots
// (CareerSession_DataDirectory_RuntimeField4 ..) get W(20 or 70, 90) as level (the first 22 from 20), then the players
// of every league club get the level of its place in the database order of its league,
// from the league's maximum (first club) down towards its minimum (LeagueStrengthRanges pairs,
// club counts LeagueSizes), keeping the age at 0 for InitializeCareer.
void startup_players(GameState& g, GameRandom& game, WatcomRandom& rand);
// The squad list as CareerFirstSteps2 leaves it: all slots 0xfff, the database list read
// over them and its tail (from slot CareerRuntimeField + 40) moved up to slot CareerRuntimeField2
// (memmove; the four slots before keep their values).
std::vector<uint16_t> startup_squad_list(const Database& db);
} // namespace bmh
namespace bmh {
class LeImage;
// The memory of the original after loading the data files in CareerFirstSteps2, as a GameState
// (built like a savegame: every saved block from the program's data object - zero where
// it is uninitialised - with the data of M3.MEN, M3.DAT and M3D.MAN read over it):
// manager order 0..3, option byte 0 of each manager 1, active manager 4, M3.MEN five
// times (Desktops), the first 0x160 bytes of M3.DAT four times (the other three
// parts of the file are overwritten), the nationality of the last 32 players from
// CareerRuntimeField7. The player values are those of the database; startup_players follows.
GameState startup_state(const LeImage& exe, const Database& db, const Bytes& m3_men, const Bytes& m3_dat);
// CompetitionPointers (part of startup_state): the pointers of the competition table CupTable
// (36 entries of 0x28 bytes: +0 the teams, +8 the rounds, +0xc the results) to the tables of
// the leagues, cups and tournaments.
void competition_pointers(StaticMemory& mem, const LeImage& exe);
// The memory of the English-only competitions (Football Limited, kEnglishCompetitions):
// blocks at their English addresses, which no German address uses. FA Cup results (67
// matches) and fields (68 clubs: the 20 Premier League clubs, the 48 of the qualifying
// stage, the proper rounds), the League Cup (44 clubs, three entries) and entry 35.
constexpr uint32_t kEnglishFaResults = ::bmh::layout::EnglishFaCupResults; // 0x86 bytes, entry 0 +0x0c
constexpr uint32_t kEnglishFaField = ::bmh::layout::EnglishFaCupField; // 68 clubs: 20 + kEnglishFaQualifyingField
constexpr uint32_t kEnglishFaQualifyingField = ::bmh::layout::EnglishFaCupQualifyingField; // the 48 of the qualifying stage (entry 0)
constexpr uint32_t kEnglishLeagueCupField = ::bmh::layout::EnglishLeagueCupField; // 44 clubs: 20 + 24 at layout field (entry 25)
constexpr std::pair<uint32_t, uint32_t> kEnglishCompetitionBlocks[] = {
{::bmh::layout::EnglishFaCupResults, 0x1ba}, // FA Cup: results EnglishFaCupResults, stage results EnglishFaCupStageResults, field EnglishFaCupField, proper EnglishFaCupProperField
{::bmh::layout::EnglishLeagueCupField, 0x136}, // League Cup: fields EnglishLeagueCupField/EnglishLeagueCupFirstRoundField/EnglishLeagueCupQuarterFinalField/EnglishLeagueCupSemiFinalField, results EnglishLeagueCupFirstRoundResults/EnglishLeagueCupQuarterFinalResults/EnglishLeagueCupSemiFinalResults/EnglishLeagueCupQuarterFinalOtherLegResults
{::bmh::layout::EnglishAdditionalCupResults, 0x48}, // entry 35: results EnglishAdditionalCupResults, field EnglishAdditionalCupField
};
void english_competition_blocks(StaticMemory& mem);
} // namespace bmh
namespace bmh {
// InitializeCareer up to the options dialog (SetupScreen2, called first in ConfirmManager(0)):
// - funds (price (1 << k) * 100 000) and shares (value k * 2000 + 10 000, price
// k * 20 + 100);
// - stir_random; G(0, 1) chooses which of the two computer manager names (Career_NewCareerMarketsAndMoods_ExecutableField /
// aeafc) the records 0 and 1 get, records 2 and 3 get Career_NewCareerMarketsAndMoods_ExecutableField3 / Career_NewCareerMarketsAndMoods_ExecutableField4 (needs
// g.texts; skipped without);
// - 30 days of share prices (stock_market);
// - Titles (900 bytes) 0xff, Career_NewCareerMarketsAndMoods_RuntimeField2 = 1, 2, 4, 8, the transfer list's 44
// entries empty (player 0xfff);
// - club moods (reset_club_moods, career mode);
// - every club player (squad slots 0 .. CareerRuntimeField) gets an age W(4, 16) and new
// skills W(0, 0x3fff);
// - the 54 extra players leave for the free agents (release_player, MonthChange).
// Returns false if a step is not supported (report).
bool new_career_before_dialog(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report);
// Its two parts: up to the club moods, and the ages, skills and extra players.
void new_career_markets_and_moods(GameState& g, GameRandom& game, WatcomRandom& rand);
bool new_career_players(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report);
} // namespace bmh
namespace bmh {
// A manager as confirmed in his dialog (ManagerScreen2; the UI's ManagerChoice): the dialog
// writes name (record +0xa8), club (+0x290), start league 0..4 (+0x210) and portrait
// (+0x221) into the record and returns the strength 0 (lower third) .. 2 (upper third).
struct CareerManager {
std::string name; // ISO 646-DE bytes, at most 24
int team = 0; // club id at the moment of the confirmation
int league = 0; // start league 0..4
int strength = 1; // 0 lower, 1 middle, 2 upper third
int portrait = 0; // 0..11
};
// ConfirmManager before the first dialog: manager slot 4 (the national team's) gets the
// training plan 2 and 1 000 000 money.
void career_managers_begin(GameState& g, bool adding = false);
// StartingSponsors initializes the three sponsor contracts for mode I, or for a
// one-year career before season day 0. The date check uses GameState.date,
// because the serialized CalendarDay mirror can be stale during startup/reset.
void starting_sponsors(GameState& g, int manager);
// OpenBMH deviates from the original: uses the supported player-generation ranges and excludes reserved calendar positions when assigning managers.
// The body of ConfirmManager's loop for manager `m` (`adding` = a manager joins a running
// game, param_1 != 0): the record is prepared and the dialog's values entered, then
// - the club moves to its place: in a league other than the chosen start league it
// changes places with a club of that league (G(first, first + 12), supported rule profile ReservedPlace2
// / ReservedPlace skip clubs of humans and reserved places), which gets new values
// (CareerAddManager2(club, 0)); in the first league with a club place m + 1 (m + 9 when
// adding; supported rule profile CareerAddManager4 skips reserved and human places);
// - the club's players get condition and technique around the chosen strength
// (CareerAddManager2, W(level - 6, level + 6));
// - record values: morale flag, board patience, stadium (CareerAddManager3, StartingSponsors),
// training plan, ratings, money (4 000 000 - level * 200 000; 50 000 000 at level 0),
// credit line, the first 20 players (or the whole squad when adding) on the tactics
// board with a new age W(4, 9), and an automatic line-up.
// The optional file of CareerAddManager (bonus codes) is not read. Needs the program image
// for its tables (Career_BuildStadium_RuntimeField4, Career_BuildStadium_RuntimeField, Career_BuildStadium_RuntimeField2).
bool career_add_manager(GameState& g, const LeImage& exe, int m, const CareerManager& choice, bool adding,
GameRandom& game, WatcomRandom& rand, MinuteReport& report);
// ConfirmManager after the loop: clear CareerSession_FormatError_RuntimeField6; only a new career empties the twelve
// human loan entries Career_CareerManagersEnd_RuntimeField. Joining preserves unrelated entries.
void career_managers_end(GameState& g, bool adding);
} // namespace bmh
+89
View File
@@ -0,0 +1,89 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/club_info.hpp"
#include <stdexcept>
namespace bmh {
ClubInfoEntry prepare_club_info_entry(GameState& g, int team) {
if (team < 0 || (team >= 138 && team != kNoTeam))
throw std::invalid_argument("club info: team has no squad");
const SquadRange range = squad_range(team);
if (range.first > g.squad_slots.size() || range.count > g.squad_slots.size() - range.first)
throw std::invalid_argument("club info: truncated squad range");
size_t occupied = 0;
for (size_t row = 0; row < range.count; ++row) {
const int id = g.squad_slots[range.first + row] & 0x0fff;
if (id == 0x0fff) continue;
if (size_t(id) >= g.players.size())
throw std::invalid_argument("club info: invalid player ID");
++occupied;
}
// Allocate the owned pre-cleanup drawing rows before the first engine write.
ClubInfoEntry entry;
entry.displayed_slots.assign(g.squad_slots.begin() + range.first,
g.squad_slots.begin() + range.first + range.count);
// SquadCount(team,2) counts occupied IDs over the complete range. PrepareLineupEntry
// scans that count-sized prefix, even if the supplied map is sparse.
int last = int(occupied) - 1;
while (last >= 0 && (g.squad_slots[range.first + size_t(last)] & 0xc000) == 0) --last;
for (int row = 0; row <= last && row < 17; ++row) {
auto& slot = g.squad_slots[range.first + size_t(row)];
slot = uint16_t((slot & 0x3fff) | (row < 11 ? 0x8000 : 0x4000));
}
entry.displayed_slots.assign(g.squad_slots.begin() + range.first,
g.squad_slots.begin() + range.first + range.count);
// PrepareClubInfoEntry clears bits13..15 for injured players over the entire range.
// Empty slots are a dummy ID in Original; preserve the sentinel explicitly.
for (size_t row = 0; row < range.count; ++row) {
auto& slot = g.squad_slots[range.first + row];
const int id = slot & 0x0fff;
if (id != 0x0fff && ((g.players[size_t(id)].w364 >> 16) & 0x1f) != 0)
slot &= 0x1fff;
}
return entry;
}
uint8_t set_club_info_category(GameState& g, int team, int requested) {
constexpr size_t scan_count = 0x147;
if (team < 0 || size_t(team) >= g.team_morale.size() ||
g.team_morale.size() < scan_count || requested < 0 || requested > 2)
throw std::invalid_argument("club info: invalid category request or club table");
const size_t manager_count = g.memory.has(::bmh::layout::ManagerCount)
? g.memory.u8(::bmh::layout::ManagerCount) : g.manager_teams.size();
if (manager_count > 4 || manager_count > g.manager_teams.size())
throw std::invalid_argument("club info: truncated manager teams");
const bool national = !g.manager_teams.empty() && g.manager_teams.front() == kNoTeam;
constexpr size_t national_club = 4 * 0xb0c + 0x290;
if (national && g.manager_records.size() < national_club + 2)
throw std::invalid_argument("club info: truncated national manager record");
// FindManagerForClub matches the first ManagerCount teams, irrespective of manager name,
// then the fifth record when the first manager is the national coach.
const auto human = [&](int club) {
for (size_t m = 0; m < manager_count; ++m)
if (g.manager_teams[m] == club) return true;
return national && (g.manager_records[national_club] |
uint16_t(g.manager_records[national_club + 1]) << 8) == club;
};
uint8_t category = uint8_t(requested);
uint8_t seen = 0;
if (category == 2) {
for (size_t club = 0; club < scan_count; ++club) {
if ((g.team_morale[club] >> 6) != 2) continue;
++seen;
if (seen != 4 || category != 2) continue;
if (!human(team)) category = 0;
else {
// Source local10 stays0: every search restarts at the first club.
for (size_t other = 0; other < scan_count; ++other) {
if ((g.team_morale[other] >> 6) == 2 && !human(int(other))) {
g.team_morale[other] = uint8_t((g.team_morale[other] & 0x3f) | 0x40);
--seen;
break;
}
}
}
}
}
g.team_morale[size_t(team)] = uint8_t((g.team_morale[size_t(team)] & 0x3f) | (category << 6));
return category;
}
}
+16
View File
@@ -0,0 +1,16 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/state.hpp"
namespace bmh {
// ClubInfoFromGame -> LineupScreen(..., param11=1): PrepareLineupEntry before
// drawing, PrepareClubInfoEntry after drawing. No player selection or RNG.
// Applies to computer and human domestic squads and the national squad.
// Invalid team/range/player IDs throw before any mutation.
struct ClubInfoEntry {
std::vector<uint16_t> displayed_slots; // normalized flags before post-draw injury cleanup
};
ClubInfoEntry prepare_club_info_entry(GameState& g, int team);
// ClubInfoFromGame numeric icon -> SetClubInfoCategory. Returns the applied raw
// category (0..2); may demote another computer club's category2 to1.
uint8_t set_club_info_category(GameState& g, int team, int requested);
}
+220
View File
@@ -0,0 +1,220 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/club_player_detail.hpp"
#include <algorithm>
#include <stdexcept>
#include "game/matchday.hpp"
#include "game/month.hpp"
#include "game/national.hpp"
#include "game/lineup.hpp"
#include "game/weekly.hpp"
namespace bmh {
namespace {
constexpr size_t kRecord = 0xb0c, kBoard = 0x840, kBoardRow = 0x58;
uint16_t record_word(const GameState& g, size_t manager, size_t offset) {
const size_t at = manager * kRecord + offset;
if (at + 2 > g.manager_records.size()) throw std::invalid_argument("player detail: truncated manager record");
return uint16_t(g.manager_records[at] | uint16_t(g.manager_records[at + 1]) << 8);
}
int source_manager(const GameState& g, int club) {
const size_t count = g.memory.has(::bmh::layout::ManagerCount) ? g.memory.u8(::bmh::layout::ManagerCount) : g.manager_teams.size();
if (count > 4 || count > g.manager_teams.size()) throw std::invalid_argument("player detail: invalid manager count");
for (size_t m = 0; m < count; ++m) if (g.manager_teams[m] == club) return int(m);
if (count && g.manager_teams[0] == kNoTeam && record_word(g, 4, 0x290) == club) return 4;
return -1;
}
int club_of_slot(int slot) {
if (slot < 0) return -1;
if (slot < 90 * 24) return slot / 24;
if (slot < 90 * 24 + 48 * 16) return (slot - 90 * 8) / 16;
if (slot >= 3072 && slot < 3096) return kNoTeam;
return -1;
}
std::array<uint8_t, kBoardRow> board_copy(const GameState& g, int manager, int row) {
const size_t at = size_t(manager) * kBoard + size_t(row) * kBoardRow;
if (at + kBoardRow > g.tactics.size()) throw std::invalid_argument("player detail: truncated manager board");
std::array<uint8_t, kBoardRow> out{};
std::copy_n(g.tactics.begin() + static_cast<std::ptrdiff_t>(at), out.size(), out.begin());
return out;
}
} // namespace
ClubPlayerDetailContext club_player_detail_context(const GameState& g, const ClubPlayerDetailSelection& s) {
if ((s.origin != ClubPlayerDetailOrigin::squad && s.origin != ClubPlayerDetailOrigin::market_pool) ||
s.player_id < 0 || size_t(s.player_id) >= g.players.size() ||
size_t(s.player_id) >= g.player_cards.size() || size_t(s.player_id) >= g.player_bonus.size())
throw std::invalid_argument("player detail: invalid player identity");
ClubPlayerDetailContext out;
out.selection = s;
out.active_manager = g.memory.has(::bmh::layout::ActiveManager) ? g.memory.u8(::bmh::layout::ActiveManager) : 0;
if (out.active_manager < 0 || size_t(out.active_manager) >= g.manager_teams.size())
throw std::invalid_argument("player detail: invalid active manager");
if (s.origin == ClubPlayerDetailOrigin::market_pool) {
if (s.runtime_team != -1 || s.physical_row != -1 || s.human_loan_index != -1 ||
s.market_pool_slot < kClubPlayerDetailMarketPoolFirst ||
s.market_pool_slot >= kClubPlayerDetailMarketPoolFirst + kClubPlayerDetailMarketPoolCount ||
s.rendered_row < 0 || s.rendered_row >= kClubPlayerDetailMarketPoolCount ||
size_t(s.market_pool_slot) >= g.squad_slots.size())
throw std::invalid_argument("player detail: invalid transfer-market slot");
out.source_slot = s.market_pool_slot;
out.displayed_slot = g.squad_slots[size_t(out.source_slot)];
if (out.displayed_slot == kEmptySlot || (out.displayed_slot & 0x0fff) != s.player_id)
throw std::invalid_argument("player detail: stale transfer-market identity");
out.market_pool = true;
out.source_manager = -1;
out.primary_club = -1;
} else {
if (s.rendered_row < 0 || s.rendered_row >= 24 || s.runtime_team < 0 ||
(s.runtime_team >= 138 && s.runtime_team != kNoTeam))
throw std::invalid_argument("player detail: invalid runtime club");
const auto range = squad_range(s.runtime_team);
if (range.first + range.count > g.squad_slots.size()) throw std::invalid_argument("player detail: truncated squad");
out.source_manager = source_manager(g, s.runtime_team);
out.primary_club = s.runtime_team;
}
if (s.origin == ClubPlayerDetailOrigin::market_pool) {
// The validated pool identity is already loaded. National resolution
// below may select a real squad copy; offers never imply a board.
} else if (s.human_loan_index >= 0) {
const auto range = squad_range(s.runtime_team);
if (s.human_loan_index >= 12 || s.physical_row != -1 || s.runtime_team == kNoTeam || out.source_manager < 0)
throw std::invalid_argument("player detail: invalid human loan row");
const uint32_t loan = uint32_t(s.human_loan_index);
const uint32_t player_at = ::bmh::layout::Career_CareerManagersEnd_RuntimeField + loan * 2, owner_at = ::bmh::layout::ClubInfo_FormatError_RuntimeField2 + loan, board_at = ::bmh::layout::ClubInfo_FormatError_RuntimeField + loan * kBoardRow;
if (!g.memory.has(player_at + 1) || !g.memory.has(owner_at) || !g.memory.has(board_at + kBoardRow - 1) ||
g.memory.u16(player_at) != s.player_id || g.memory.u8(owner_at) != out.source_manager)
throw std::invalid_argument("player detail: stale human loan identity");
out.human_loan = true;
out.source_slot = int(range.first) + s.rendered_row;
out.displayed_slot = uint16_t(s.player_id);
out.board.emplace();
for (size_t i = 0; i < kBoardRow; ++i) (*out.board)[i] = g.memory.u8(board_at + uint32_t(i));
} else {
const auto range = squad_range(s.runtime_team);
if (s.human_loan_index != -1 || s.physical_row < 0 || size_t(s.physical_row) >= range.count)
throw std::invalid_argument("player detail: invalid physical row");
out.source_slot = int(range.first) + s.physical_row;
out.displayed_slot = g.squad_slots[size_t(out.source_slot)];
if ((out.displayed_slot & 0x0fff) != s.player_id) throw std::invalid_argument("player detail: stale physical identity");
}
if (!out.human_loan) {
if (g.manager_teams[size_t(out.active_manager)] == kNoTeam) {
const auto national = squad_range(kNoTeam);
if (national.first + national.count > g.squad_slots.size()) throw std::invalid_argument("player detail: truncated national squad");
bool selected = false;
for (size_t row = 0; row < national.count; ++row)
if ((g.squad_slots[national.first + row] & 0x0fff) == s.player_id) selected = true;
out.national_mode = selected ? 2 : 1;
// ClubPlayerDetailFromGame remaps BOTH modes to the first matching slot below
// LargeSquadClubCount, including pool slots, before resolving club/owner/board.
size_t slot = 0;
while (slot < national.first && (g.squad_slots[slot] & 0x0fff) != s.player_id) ++slot;
if (slot == national.first) throw std::invalid_argument("player detail: national player has no source slot before national squad");
out.source_slot = int(slot);
out.primary_club = club_of_slot(out.source_slot);
out.secondary_club = selected ? kNoTeam : -1;
out.displayed_slot = g.squad_slots[slot];
out.source_manager = out.primary_club < 0 ? -1 : source_manager(g, out.primary_club);
}
if (out.national_mode != 0 && out.primary_club == int(record_word(g, 4, 0x290)) && g.memory.has(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField3)) {
const uint8_t owner = g.memory.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField3); // literal SquadRange override
out.source_manager = owner == 0xff ? -1 : owner;
}
if (out.source_manager >= 0) {
const auto owner_range = squad_range(out.primary_club);
const int row = out.source_slot - int(owner_range.first);
if (row < 0 || size_t(row) >= owner_range.count) throw std::invalid_argument("player detail: board row outside owner squad");
out.board = board_copy(g, out.source_manager, row);
}
}
for (int loan = 0; loan < 200; ++loan) {
const uint32_t at = ::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(loan) * 4;
if (!g.memory.has(at + 3)) continue;
const uint32_t value = g.memory.u32(at);
if (value == 0 || (value & 0x0fff) != uint32_t(s.player_id)) continue;
out.loan_record = loan;
out.loan_duration = g.memory.has(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(loan)) ? g.memory.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField + uint32_t(loan)) : 0;
if (out.human_loan || out.national_mode == 0) {
out.primary_club = int((value >> 12) & 0x3ff);
out.secondary_club = int((value >> 22) & 0x3ff);
}
break;
}
if (out.human_loan && out.loan_record < 0) throw std::invalid_argument("player detail: missing packed human loan record");
out.attributes = g.players[size_t(s.player_id)];
out.cards = g.player_cards[size_t(s.player_id)];
out.bonus = g.player_bonus[size_t(s.player_id)];
out.original_name = g.player_name(s.player_id);
const uint8_t national_override = g.memory.has(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField2) ? uint8_t(g.memory.u8(::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField2) & 10) : 0;
const bool national_label = !out.human_loan && out.national_mode != 0 && national_override == 0 &&
out.attributes.nationality() + ((out.bonus & 0x80) >> 2) == 0;
for (int offer = 0; !national_label && offer < 4; ++offer) {
const uint32_t at = ::bmh::layout::OfferSlots + uint32_t(offer) * 4;
if (!g.memory.has(at + 3)) continue;
const uint32_t value = g.memory.u32(at);
if ((out.source_manager < 0 || int(value & 31) == out.source_manager) &&
int((value >> 10) & 0x0fff) == s.player_id) { out.active_offer = offer; break; }
}
// ClubPlayerDetail_InvalidArgument_RuntimeField2/nationality select the label and the ResolvePendingOffer fallback, not the
// ClubPlayerDetailRedraw dispatch: any existing action remains national in modes1/2.
out.national_action_available = !out.human_loan && out.national_mode != 0 &&
(national_label || out.active_offer >= 0);
return out;
}
ClubPlayerDetailRedraw club_player_detail_redraw(const GameState& g, const ClubPlayerDetailSelection& selection,
const LeImage& original, GameRandom& game, WatcomRandom& rand,
bool portrait_available) {
ClubPlayerDetailRedraw out;
out.context = club_player_detail_context(g, selection);
std::array<uint8_t, 5> feature_count{};
for (size_t i = 0; i < feature_count.size(); ++i) {
feature_count[i] = original.u8(::bmh::layout::ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField2 + uint32_t(i));
if (feature_count[i] == 0) throw std::invalid_argument("player detail: empty Original portrait feature range");
}
const uint32_t named_players = original.u32(::bmh::layout::ClubPlayerDetail_ClubPlayerDetailRedraw_RuntimeField);
out.portrait_available = portrait_available;
if (portrait_available) {
uint32_t seed = 0x14344;
if (uint32_t(selection.player_id) < named_players)
for (size_t i = 0; i < out.context.original_name.size(); ++i)
seed += uint32_t(int32_t(int8_t(out.context.original_name[i]))) * uint32_t(i) * 10;
game.set_seed(int32_t(seed));
game.range(0, 100);
out.portrait_base = uint8_t(game.range(0, 3));
for (size_t i = 0; i < out.portrait_features.size(); ++i)
out.portrait_features[i] = uint8_t(game.range(0, feature_count[i] - 1));
const uint64_t before = game.calls();
stir_random(game, rand);
out.portrait_burn_count = uint16_t(game.calls() - before);
}
if (!out.context.human_loan) {
uint32_t value = 0, salary = 0;
market_value(g, out.context.source_slot, 0, 100, value, salary, 0, 0, rand);
out.market_value = ((value + (value >> 2)) / 10000) * 10000;
}
return out;
}
bool club_player_detail_national_action(GameState& g, const ClubPlayerDetailSelection& selection,
WatcomRandom& rand, MinuteReport& report) {
const auto context = club_player_detail_context(g, selection);
if (!context.national_action_available)
throw std::invalid_argument("player detail: national action is not offered by Source");
const auto national = squad_range(kNoTeam);
bool applied = true;
if (context.national_mode == 1)
applied = add_to_squad(g, context.active_manager, context.source_slot, int(national.first), rand) >= 0;
else if (!g.memory.has(::bmh::layout::MatchEventsDisabled) || g.memory.u8(::bmh::layout::MatchEventsDisabled) == 0)
applied = remove_from_seller(g, kNoTeam, selection.player_id, report);
auto_lineup(g, kNoTeam, 0xe4); // ClubPlayerDetailFromGame follows either action with this call.
return applied;
}
} // namespace bmh
+92
View File
@@ -0,0 +1,92 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <array>
#include <cstdint>
#include <optional>
#include <string>
#include "formats/le.hpp"
#include "game/random.hpp"
#include "game/state.hpp"
namespace bmh {
enum class ClubPlayerDetailOrigin : uint8_t { squad, market_pool };
// The list owns all row identities. A loan row has physical_row==-1 and its
// explicit Source Career_CareerManagersEnd_RuntimeField index. rendered_row is the visible list index, which
// may differ from a filtered/sorted market-pool entry.
struct ClubPlayerDetailSelection {
int runtime_team = -1;
int player_id = -1;
int rendered_row = -1;
int physical_row = -1;
int human_loan_index = -1;
ClubPlayerDetailOrigin origin = ClubPlayerDetailOrigin::squad;
int market_pool_slot = -1; // Actual Native CareerRuntimeField+entry identity, never a visible row.
};
struct ClubPlayerDetailContext {
ClubPlayerDetailSelection selection;
int source_slot = -1; // Resolved Source slot; national prelude may remap any origin.
int source_manager = -1;
int primary_club = -1;
int secondary_club = -1;
int loan_duration = 0;
int loan_record = -1;
// Literal local1c from ClubPlayerDetailFromGame:0 ordinary,1 national nomination candidate,
// 2 currently selected national player.
uint8_t national_mode = 0;
int active_manager = -1;
int active_offer = -1; // ResolvePendingOffer fallback; -1 for a direct national label.
Player attributes;
uint16_t displayed_slot = 0x0fff;
uint16_t cards = 0;
uint8_t bonus = 0;
std::string original_name;
std::optional<std::array<uint8_t, 0x58>> board;
bool human_loan = false;
bool market_pool = false;
bool national_action_available = false;
};
// OpenTransferEditor passes actual slots CareerRuntimeField + entry (0..39) for ordinary
// transfer-market pool cards. It never turns the entry into a squad row.
constexpr int kClubPlayerDetailMarketPoolFirst = 0xb70;
constexpr int kClubPlayerDetailMarketPoolCount = 40;
// Resolves runtime club, explicit row and Source loan/national ownership without
// changing GameState or either random generator. Invalid/stale identities throw.
ClubPlayerDetailContext club_player_detail_context(const GameState&,
const ClubPlayerDetailSelection&);
struct ClubPlayerDetailRedraw {
ClubPlayerDetailContext context;
bool portrait_available = false;
uint8_t portrait_base = 0;
std::array<uint8_t, 5> portrait_features{};
uint16_t portrait_burn_count = 0;
// Human-loan fields2..5 use Source ClubPlayerDetail_Copy_TextPointer8 and do not compute a market value.
std::optional<uint32_t> market_value;
};
// One actual ClubPlayerDetailFromGame card rebuild: Copy2/21213 portrait draws, followed
// by422ac/42307/PlayerCardMarketValue market valuation. Pure renderer calls consume this owned
// result repeatedly and never draw RNG. The caller passes Source heap gate.
ClubPlayerDetailRedraw club_player_detail_redraw(const GameState&,
const ClubPlayerDetailSelection&,
const LeImage& original,
GameRandom&, WatcomRandom&,
bool portrait_available = true);
// ClubInfoFromGame temporarily uses (bbcde!=2), then restores its caller's value.
constexpr uint8_t club_player_detail_input_mode(uint8_t prior) { return prior != 2; }
struct MinuteReport;
// The actual Source nomination/remove button. Returns false if the national
// squad is full; the Source lineup refresh still follows the attempted add.
bool club_player_detail_national_action(GameState&, const ClubPlayerDetailSelection&,
WatcomRandom&, MinuteReport&);
} // namespace bmh
+782
View File
@@ -0,0 +1,782 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/cup.hpp"
#include <algorithm>
#include <array>
#include <string>
#include <utility>
#include <vector>
#include "game/driver.hpp"
#include "game/lineup.hpp"
#include "game/matchday.hpp"
#include "game/matchday_setup.hpp"
#include "game/messages.hpp"
#include "game/schedule.hpp"
#include "game/table.hpp"
namespace bmh {
// After the fifth indoor tournament (the end of AdvanceCup for competition 0xb): the
// field of the Masters.
// MastersQualification2: the holders of the three titles of last season (Cup_AdvanceCup_RuntimeField6[0..2],
// u16 club ids) qualify directly, each once (list Cup_MastersQualification_RuntimeField, count CupRuntimeField);
// they head the team list (Teams).
// IndoorStandingsFromGame(0): the clubs 0-39 are sorted by their Masters points (Cup_AdvanceCup_ExecutableField,
// Games descending); IndoorTournamentDraw only resets the tournament (no draw while
// CupRuntimeField != 0); the best clubs not qualified yet fill the list up to eight, which
// is shuffled (PrepareEvent, one game draw per club). The strength class Cup_AdvanceCup_RuntimeField3
// stays that of the last tournament.
// The test "qualified yet" (MastersQualification) scans Cup_MastersQualification_RuntimeField[0 .. CupRuntimeField), but
// CupRuntimeField also counts the clubs filled in from the points list, which never enter
// Cup_MastersQualification_RuntimeField: the scan runs over the stale entries 2 and 3 (0 unless an earlier Masters
// had three direct qualifiers) and from entry 4 into the invitation counters that follow
// (MatchdaySetup_IndoorTournamentDraw_RuntimeField, u16 per club). A club whose id equals one of those values (team 0 with a
// 0 there, small ids with an invitation count) is skipped although it has the points.
// The list is not in the savegame; the replay keeps it in memory, starting at 0.
void masters_qualification(GameState& g, GameRandom& game) {
StaticMemory& mem = g.memory;
constexpr uint32_t kTeams = ::bmh::layout::Teams, kDirect = ::bmh::layout::Cup_MastersQualification_RuntimeField;
if (!mem.has(kDirect)) mem.add_block(kDirect, 8);
// MastersQualification: whether club t is in Cup_MastersQualification_RuntimeField[0 .. count)
auto listed = [&](uint16_t t, size_t count) {
for (size_t k = 0; k < count; k++)
if (mem.u16(kDirect + uint32_t(k) * 2) == t) return true;
return false;
};
size_t count = 0; // CupRuntimeField
for (uint32_t k = 0; k < 3; k++) {
const uint16_t t = mem.u16(::bmh::layout::Cup_AdvanceCup_RuntimeField6 + k * 2);
if (k == 0 || !listed(t, count)) mem.set16(kDirect + uint32_t(count++) * 2, t);
}
for (size_t k = 0; k < count; k++) mem.set16(kTeams + uint32_t(k) * 2, mem.u16(kDirect + uint32_t(k) * 2));
int16_t order[0x28];
uint32_t points[0x28];
for (int i = 0; i < 0x28; i++) order[i] = int16_t(i), points[i] = mem.u16(::bmh::layout::Cup_AdvanceCup_ExecutableField + uint32_t(i) * 2);
quicksort_by_key(order, points, 0x28);
indoor_tournament_reset(g);
for (int i = 0; count < 8; i++) {
const uint16_t t = uint16_t(order[i]);
if (!listed(t, count)) mem.set16(kTeams + uint32_t(count++) * 2, t);
}
for (uint32_t i = 0; i < 8; i++) { // PrepareEvent(8, teams)
const uint32_t j = uint32_t(game.range(0, 7));
const uint16_t a = mem.u16(kTeams + i * 2);
mem.set16(kTeams + i * 2, mem.u16(kTeams + j * 2));
mem.set16(kTeams + j * 2, a);
}
for (uint32_t k = 0; k < 8; k++) {
const int manager = g.manager_of(mem.u16(kTeams + k * 2));
if (manager < 0) continue;
post_composed(g, manager, kMastersQualificationText); // MastersQualificationText
book_money(g, manager, -150000, true, true);
}
const std::string name = message_text(g, ::bmh::layout::Cup_MastersQualification_TextPointer);
if (g.tournament_name.size() < 0x24) g.tournament_name.resize(0x24, 0);
for (size_t i = 0; i <= name.size() && i < 0x24; i++) g.tournament_name[i] = i < name.size() ? uint8_t(name[i]) : 0;
}
namespace {
void put32(Bytes& b, size_t o, uint32_t v) {
for (int i = 0; i < 4; i++) b.at(o + i) = uint8_t(v >> (8 * i));
}
// Replays of postponed league matches: cup entry type 9 plays the matches whose replay day
// (table Postponed, 40 entries of 6 bytes: day, round, league, match) is today.
constexpr uint32_t kPostponed = ::bmh::layout::Postponed;
constexpr uint32_t kReplayFixtures = ::bmh::layout::ReplayFixtures; // team list of the type 9 entry (home, away)
constexpr uint32_t kReplayResults = ::bmh::layout::ReplayResults; // its result array (u16 per match)
// AddBlock: the fixtures of today's replays; the entry's team count (+0x1a) and played
// counter (+0x1d) restart.
void prepare_replays(GameState& g, uint32_t e, int day) {
StaticMemory& mem = g.memory;
mem.add_block(kReplayFixtures, 0x50);
mem.add_block(kReplayResults, 0x12);
mem.set8(e + 0x1d, 0);
mem.set8(e + 0x1a, 0);
for (uint32_t i = 0; i < 0x12; i++) mem.set8(kReplayResults + i, 0xcc);
int k = 0;
for (int n = 0; n < 0x28; n++) {
const uint32_t at = kPostponed + uint32_t(n) * 6;
if (mem.u16(at) != day) continue;
const int league = mem.u8(at + 3);
const std::vector<Fixture> fx = generate_fixtures(league_table_teams(league), mem.u8(at + 2) + 1, league_matchdays(league) / 2,
league_first_team(league));
const Fixture& f = fx.at(mem.u8(at + 4));
mem.set16(kReplayFixtures + uint32_t(k++) * 2, uint16_t(f.home));
mem.set16(kReplayFixtures + uint32_t(k++) * 2, uint16_t(f.away));
mem.set8(e + 0x1a, uint8_t(mem.u8(e + 0x1a) + 2));
}
}
// EndCompetition(id): takes a competition off the list of running ones (ActiveSelectors).
void remove_competition(StaticMemory& mem, int id) {
for (int i = 0; i < 8; i++) {
if (int8_t(mem.u8(::bmh::layout::ActiveSelectors + uint32_t(i))) != id) continue;
for (int j = i; j < 7; j++) mem.set8(::bmh::layout::ActiveSelectors + uint32_t(j), mem.u8(::bmh::layout::Cup_RemoveCompetition_RuntimeField + uint32_t(j)));
mem.set8(::bmh::layout::Cup_RemoveCompetition_RuntimeField2, 0x14);
return;
}
}
// UndoReschedule(day, 0, 0): today's replay results go back into the league result table and
// their entries are freed; then EndCompetition(9) takes the competition off the list of
// running competitions (ActiveSelectors).
void store_replays(GameState& g, int day) {
StaticMemory& mem = g.memory;
int k = 0;
for (int n = 0; n < 0x28; n++) {
const uint32_t at = kPostponed + uint32_t(n) * 6;
if (mem.u16(at) != day) continue;
const uint16_t r = mem.u16(kReplayResults + uint32_t(k++) * 2);
const uint8_t result = uint8_t(((r >> 5) << 4) | (r & 0xf));
g.results.at(size_t(mem.u8(at + 4)) + size_t(mem.u8(at + 2)) * 10 + size_t(mem.u8(at + 3)) * 0x17C) = result;
mem.set16(at, 0);
}
remove_competition(mem, 9);
}
// Size of the round string table a cup group plays with (pointer at entry +8).
int group_table_teams(const StaticMemory& mem, uint32_t e) {
switch (mem.pointer(e + 8)) {
case ::bmh::layout::CareerSession_RuntimeError_RuntimeField: return 4;
case ::bmh::layout::CareerSession_RuntimeError_RuntimeField2: return 6;
case ::bmh::layout::CareerSession_RuntimeError_RuntimeField3: return 12;
case ::bmh::layout::CareerSession_RuntimeError_ExecutableField3: return 16;
case ::bmh::layout::CareerSession_RuntimeError_ExecutableField: return 18;
case ::bmh::layout::CareerSession_RuntimeError_ExecutableField2: return 20;
}
return 0;
}
// AddResult(entry, 0): the table of a cup group from its result array (u16 per match,
// 0xCCCC = not played), indexed by draw position. Bit 7 of the flags: three points for a
// win. The ranks are sorted like the league tables (AddResult2) after the last two rounds
// and after later rounds with results.
LeagueTable group_table(const StaticMemory& mem, uint32_t e) {
LeagueTable t;
const uint8_t flags = mem.u8(e + 0x14);
const int teams = mem.u8(e + 0x1a), rounds = mem.u8(e + 0x1b), played = mem.u8(e + 0x1d);
t.size = teams;
const int three_points = flags >> 7;
int last = played - 1, before_last = 0x80;
if (last > 1) before_last = played - 2;
if (last < 0) last = 0;
sort_table(t, 0);
const uint32_t results = mem.pointer(e + 0x0c);
for (int r = 0; r < rounds; r++) {
const std::vector<Fixture> fx = generate_fixtures(group_table_teams(mem, e), r + 1, rounds / ((flags & 1) + 1), 0);
bool counted = false;
for (int s = 0; s < teams; s += 2) {
const uint16_t u = mem.u16(results + uint32_t(s / 2 + r * teams / 2) * 2);
if (u == 0xcccc) continue;
const uint8_t goals[2] = {uint8_t((u >> 5) & 0x1f), uint8_t(u & 0x1f)};
const int club[2] = {fx.at(size_t(s / 2)).home, fx.at(size_t(s / 2)).away};
add_result(t, club, goals, 3, three_points);
counted = true;
}
if (before_last == r || last == r || (last < r && counted)) sort_table(t, 0);
}
return t;
}
// The end of a group stage (AdvanceCup): the qualifiers place by place (all group
// winners, then the runners-up, ...) until the stage's quota (+0x1f) is reached; a place
// taken only partly keeps its best clubs by the table key. Group winner and runner-up are
// noted in +0x22 / +0x24 of every group. Returns the qualifiers and in `loser_pair` the
// first two clubs of the first group ordered by the last table's second place (for a final
// of two).
std::vector<uint16_t> group_qualifiers(StaticMemory& mem, uint32_t e, std::array<uint16_t, 2>& loser_pair) {
const int groups = mem.u8(e + 0x1e) & 0xF;
int quota = int8_t(mem.u8(e + 0x1f));
std::vector<uint16_t> teams;
std::vector<uint32_t> keys;
LeagueTable t;
for (int place = 0; quota > 0; place++) {
for (int grp = 0; grp < groups; grp++) {
uint32_t ge = e;
while ((mem.u8(ge + 0x1e) >> 4) != grp) ge += kCupEntrySize;
t = group_table(mem, ge);
int idx = 0;
while (idx < mem.u8(ge + 0x1a) && t.rank(idx) != place) idx++;
const uint16_t team = mem.u16(mem.pointer(ge) + uint32_t(idx) * 2);
if (place == 0) mem.set16(ge + 0x22, team);
if (place == 1) mem.set16(ge + 0x24, team);
keys.push_back(sort_key(t, idx, 0));
teams.push_back(team);
quota--;
}
}
const uint32_t list = mem.pointer(e);
loser_pair[0] = t.rank(0) == 1 ? mem.u16(list) : mem.u16(list + 2);
const int wanted = int8_t(mem.u8(e + 0x1f));
const int cut = wanted - wanted % groups;
for (; quota < 0; quota++) {
uint32_t worst = keys.back();
size_t at = 0;
for (int k = cut; k < wanted; k++)
if (keys[size_t(k)] < worst) at = size_t(k), worst = keys[size_t(k)];
if (worst < keys.back()) {
std::swap(teams.back(), teams[at]);
std::swap(keys.back(), keys[at]);
}
teams.pop_back();
keys.pop_back();
}
return teams;
}
} // namespace
LeagueTable cup_group_table(const StaticMemory& mem, uint32_t entry_address) {
return group_table(mem, entry_address);
}
int cup_group_schedule_teams(const StaticMemory& mem, uint32_t entry_address) {
return group_table_teams(mem, entry_address);
}
void end_competition(StaticMemory& mem, int id) { remove_competition(mem, id); }
void prepare_friendlies(GameState& g) {
StaticMemory& mem = g.memory;
if (!mem.has(::bmh::layout::FriendlyDays) || !mem.has(::bmh::layout::FriendlyTeams) || !mem.has(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24)) return;
const int today = g.season_day(); // DaysIntoSeason
int count = 0; // local_c: two teams per friendly
for (int i = 0; i < 0x1e; i++) {
if (int16_t(mem.u16(::bmh::layout::FriendlyDays + uint32_t(i) * 2)) != int16_t(today)) continue;
for (int c = 0; c < 2; c++)
mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField24 + uint32_t(c + count) * 2, mem.u16(::bmh::layout::FriendlyTeams + uint32_t(i * 2 + c) * 2));
mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField29 + uint32_t(count >> 1) * 2, 0xcccc);
mem.set16(::bmh::layout::FriendlyDays + uint32_t(i) * 2, 0);
count += 2;
if (i < 0x1d) {
// the planned ones after it move up (the last place keeps its copy)
for (int k = i; k < 0x1d; k++) {
mem.set32(::bmh::layout::FriendlyTeams + uint32_t(k) * 4, mem.u32(::bmh::layout::Cup_PrepareFriendlies_RuntimeField + uint32_t(k) * 4));
mem.set16(::bmh::layout::FriendlyDays + uint32_t(k) * 2, mem.u16(::bmh::layout::Cup_PrepareFriendlies_RuntimeField2 + uint32_t(k) * 2));
}
i--;
// the planner's entry 30 counts them (two per friendly); only decreased here,
// not for the last place (as in the original)
const uint32_t planned = cup_entry_address(30) + 0x1a;
mem.set8(planned, uint8_t(mem.u8(planned) - 2));
}
}
mem.set8(cup_entry_address(24) + 0x1a, uint8_t(count)); // today's friendlies (CupRuntimeField2)
}
int find_cup(const StaticMemory& mem, int id) {
for (int i = 0; i < kCupEntries; i++)
if (int16_t(mem.u16(cup_entry_address(i) + 0x18)) == id) return i;
return -1;
}
int cup_round(const StaticMemory& mem, int entry) {
const uint32_t e = cup_entry_address(entry);
const uint8_t flags = mem.u8(e + 0x14), played = mem.u8(e + 0x1d);
if (!(flags & 4)) return played;
return played / ((flags & 1) + 1);
}
int cup_round_offset(const StaticMemory& mem, int entry, int round) {
if (round == 0) return 0;
const int teams = mem.u8(cup_entry_address(entry) + 0x1a);
return teams * 2 - teams / (1 << (round - 1));
}
void rebuild_replay_lists(GameState& g, uint32_t competitions) {
for (int bit = 5; bit < 0x13; bit++) {
if (!((competitions >> bit) & 1)) continue;
const int entry = find_cup(g.memory, bit - 5);
if (entry >= 0 && int16_t(g.memory.u16(cup_entry_address(entry) + 0x18)) == 9)
prepare_replays(g, cup_entry_address(entry), g.season_day());
}
}
void setup_cup_groups(GameState& g, int id, std::vector<MatchGroup>& groups, MinuteReport& report) {
const StaticMemory& mem = g.memory;
int entry = find_cup(mem, id);
if (entry < 0) {
report.fail("cup " + std::to_string(id) + " not in the cup table");
return;
}
const int type = int16_t(mem.u16(cup_entry_address(entry) + 0x18));
if (type == 9) prepare_replays(g, cup_entry_address(entry), g.season_day());
if (type == 10) prepare_friendlies(g);
if (type > 9 && mem.u8(cup_entry_address(entry) + 0x1a) != 0) {
// AddCompetition: onto the list of running competitions (ActiveSelectors, 0x14 = free)
for (uint32_t i = 0; i < 8; i++) {
if (int8_t(mem.u8(::bmh::layout::ActiveSelectors + i)) == type) break;
if (g.memory.u8(::bmh::layout::ActiveSelectors + i) == 0x14) {
g.memory.set8(::bmh::layout::ActiveSelectors + i, uint8_t(type));
break;
}
}
}
// (the friendlies 10, the promotion play-off 0xd and the indoor tournament 0xb only join
// the running list above)
if (type > 0xb && type != 0xd && mem.u8(cup_entry_address(entry) + 0x1a) != 0) {
report.fail("cup " + std::to_string(id) + ": preparation of this competition (AddBlock/2631b/26175)");
return;
}
// skip the stages that are completed (bounded: a broken chain would loop for ever)
for (int steps = 0; cup_round(mem, entry) >= mem.u8(cup_entry_address(entry) + 0x1b); ++steps) {
const int next = int8_t(mem.u8(cup_entry_address(entry) + 0x16));
if (steps > 0x24 || next < 0 || next >= 0x24) {
report.fail("cup " + std::to_string(id) + ": stage chain without an open stage (entry " + std::to_string(entry) +
", round " + std::to_string(cup_round(mem, entry)) + " of " +
std::to_string(mem.u8(cup_entry_address(entry) + 0x1b)) + ", next " + std::to_string(next) + ")");
return;
}
entry = next;
}
const int parallel = mem.u8(cup_entry_address(entry) + 0x1e) & 0xF;
if (mem.u32(cup_entry_address(entry)) == 0) return;
for (int k = 0; k < parallel; k++) {
const uint32_t e = cup_entry_address(entry);
const uint8_t flags = mem.u8(e + 0x14);
const int teams = mem.u8(e + 0x1a);
if (teams == 0) continue; // (the original then looks at the same entry again)
MatchGroup grp;
grp.desc = group_descriptor(g, groups.size());
grp.desc.at(0) = uint8_t(type + 1);
grp.desc.at(1) = flags;
// competition 11 is the German indoor tournament; in the English game the same entry
// is the League Cup ("Koka Kola Cup"), an ordinary cup on grass (EN Put32)
if (type == 0xb && !kEnglishCompetitions) g.indoor = true;
put32(grp.desc, 0xcc, e);
// the first leg of a two-legged knockout tie is never decided on the day
if ((flags & 5) == 5 && mem.u8(e + 0x1d) % 2 == 0) grp.desc.at(1) &= 0xF7;
int matches = 0, first = 0; // local_1c; the result index is `first` / 2
const uint32_t list = mem.pointer(e);
if (!(flags & 4)) {
// a group: GenerateFixtures on the cup's round strings (+8), round = played + 1, the
// draw positions index the group's team list; two-legged groups play the rounds
// of the string table twice, home and away swapped
matches = teams / 2;
const int played = mem.u8(e + 0x1d);
first = uint8_t(matches * played * 2);
const int rounds = mem.u8(e + 0x1b) / ((flags & 1) + 1);
int table_teams = 0;
switch (mem.pointer(e + 8)) {
case ::bmh::layout::CareerSession_RuntimeError_RuntimeField: table_teams = 4; break;
case ::bmh::layout::CareerSession_RuntimeError_RuntimeField2: table_teams = 6; break;
case ::bmh::layout::CareerSession_RuntimeError_RuntimeField3: table_teams = 12; break;
case ::bmh::layout::CareerSession_RuntimeError_ExecutableField3: table_teams = 16; break;
case ::bmh::layout::CareerSession_RuntimeError_ExecutableField: table_teams = 18; break;
case ::bmh::layout::CareerSession_RuntimeError_ExecutableField2: table_teams = 20; break;
}
if (table_teams == 0) {
report.fail("cup group with unknown round strings");
return;
}
for (const Fixture& f : generate_fixtures(table_teams, played + 1, rounds, 0)) {
if (int(grp.fixtures.size()) >= matches * 2) break;
grp.fixtures.push_back(int16_t(mem.u16(list + uint32_t(f.home) * 2)));
grp.fixtures.push_back(int16_t(mem.u16(list + uint32_t(f.away) * 2)));
}
// the fixtures are kept in the descriptor itself (+0x88; +0x7c points there)
for (size_t i = 0; i < grp.fixtures.size(); i++) {
grp.desc.at(0x88 + i * 2) = uint8_t(grp.fixtures[i]);
grp.desc.at(0x89 + i * 2) = uint8_t(uint16_t(grp.fixtures[i]) >> 8);
}
} else {
const int round = cup_round(mem, entry);
matches = teams / (1 << (round + 1));
first = cup_round_offset(mem, entry, round);
for (int i = 0; i < matches * 2; i++) grp.fixtures.push_back(int16_t(mem.u16(list + uint32_t(first + i) * 2)));
}
grp.desc.at(2) = uint8_t(matches);
if (type == 0 && matches == 1) grp.desc.at(1) &= 0xFD; // the national cup final
// MatchdayNeedsManagerDesks: a human manager's club notes its side (record +0x28a)
for (int i = 0; i < matches * 2; i++)
for (size_t mgr = 0; mgr < g.manager_teams.size(); mgr++)
if (g.manager_teams[mgr] == grp.fixtures[size_t(i)]) g.manager_records.at(mgr * 0xB0C + 0x28a) = uint8_t(i % 2);
for (int leg = 0; leg < 2; leg++) {
if (leg == 1 && !(flags & 1)) break;
const uint32_t results = mem.pointer(e + 0x0c + uint32_t(leg) * 4);
if (results == 0) continue;
grp.cup_result_address[leg] = results + uint32_t(first / 2) * 2;
std::vector<uint16_t>& r = leg == 0 ? grp.cup_results : grp.cup_other_leg;
for (int i = 0; i < matches; i++) r.push_back(mem.u16(grp.cup_result_address[leg] + uint32_t(i) * 2));
}
groups.push_back(grp);
entry++;
}
}
} // namespace bmh
namespace bmh {
void store_cup_results(GameState& g, const MatchGroup& grp) {
if (grp.desc.at(0) == 0 || grp.cup_result_address[0] == 0) return;
for (size_t i = 0; i < grp.cup_results.size(); i++)
g.memory.set16(grp.cup_result_address[0] + uint32_t(i) * 2, grp.cup_results[i]);
}
namespace {
// NationalTournamentEnd, at the end of the international tournament (competition type 4): the
// honours list of the tournaments (Placements, 4 bytes per tournament, newest first)
// moves one place on and gets the first four (final winner and loser Cup_NationalTournamentEnd_RuntimeField/2dce,
// third place match Cup_NationalTournamentEnd_RuntimeField3/2df6) as national team index | 0x80. A Bundestrainer's
// association (manager slot 0 holds team 0x165) pays 400000 for taking part and the
// premium of the place (CupRuntimeField3).
void national_tournament_end(GameState& g) {
StaticMemory& mem = g.memory;
const int teams[4] = {int16_t(mem.u16(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField)), int16_t(mem.u16(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField2)), int16_t(mem.u16(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField3)),
int16_t(mem.u16(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField4))};
static constexpr int32_t kPremium[4] = {1000000, 600000, 300000, 200000}; // CupRuntimeField3
if (mem.has(::bmh::layout::Placements))
for (int i = 0x4c - 1; i >= 0; i--) mem.set8(::bmh::layout::Cup_NationalTournamentEnd_RuntimeField5 + uint32_t(i), mem.u8(::bmh::layout::Placements + uint32_t(i)));
const bool coach = !g.manager_teams.empty() && g.manager_teams[0] == kNoTeam;
if (coach) book_money(g, 0, -400000, true, true);
for (int i = 0; i < 4; i++) {
if (teams[i] == kNoTeam && coach) book_money(g, 0, -kPremium[i], true, true);
// (0x8a + 0x1e + 0xbd = 0x165: CareerSession_DispatchLineup_RuntimeField + CareerSession_InstallLeagueSizes_RuntimeField6 + ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3)
if (mem.has(::bmh::layout::Placements)) mem.set8(::bmh::layout::Placements + uint32_t(i), uint8_t((teams[i] - kNoTeam) | 0x80));
}
}
// cup_tie on the result arrays of a stage (CupTie(results0, results1, index, flags))
int stage_tie(const StaticMemory& mem, uint32_t e, int index) {
MatchGroup grp;
grp.desc.assign(0xd0, 0);
grp.desc.at(1) = mem.u8(e + 0x14);
const uint32_t r0 = mem.pointer(e + 0x0c), r1 = mem.pointer(e + 0x10);
grp.cup_results.assign(size_t(index) + 1, 0);
grp.cup_results[size_t(index)] = mem.u16(r0 + uint32_t(index) * 2);
if (r1 != 0) {
grp.cup_other_leg.assign(size_t(index) + 1, 0);
grp.cup_other_leg[size_t(index)] = mem.u16(r1 + uint32_t(index) * 2);
}
return cup_tie(grp, index);
}
void swap16(StaticMemory& mem, uint32_t a, uint32_t b) {
const uint16_t x = mem.u16(a);
mem.set16(a, mem.u16(b));
mem.set16(b, x);
}
// Getenv(teams, offset): Source home advantage followed by an unstable-free
// descending sort on each tie's combined league weight. Kept in this Core module so
// finish_cup can expose the Original draw before the inner sort and retain its outer sort.
void order_national_cup_ties(GameState& g, int teams, int offset) {
StaticMemory& mem = g.memory;
const uint32_t list = mem.pointer(cup_entry_address(0)) + uint32_t(offset) * 2;
static constexpr uint8_t kWeight[10] = {3, 1, 0, 0, 2, 0, 0, 0, 7, 0};
const int lower = league_first_team(2);
std::vector<uint8_t> weights;
weights.reserve(size_t(teams / 2));
auto team = [&](int i) { return int16_t(mem.u16(list + uint32_t(i) * 2)); };
auto swap_pair = [&](int a, int b) {
swap16(mem, list + uint32_t(a) * 2, list + uint32_t(b) * 2);
swap16(mem, list + uint32_t(a + 1) * 2, list + uint32_t(b + 1) * 2);
};
for (int i = 0; i < teams; i += 2) {
if (lower <= team(i + 1) && team(i) < lower)
swap16(mem, list + uint32_t(i) * 2, list + uint32_t(i + 1) * 2);
auto league = [](int t) { return t > 0x164 ? 0 : team_league(t); };
const int la = league(team(i)), lb = league(team(i + 1));
weights.push_back(uint8_t(kWeight[la < 10 ? la : 9] + kWeight[lb < 10 ? lb : 9]));
}
for (int i = 0; i < teams / 2 - 1; ++i)
for (int j = i + 1; j < teams / 2; ++j)
if (weights[size_t(i)] < weights[size_t(j)]) {
std::swap(weights[size_t(i)], weights[size_t(j)]);
swap_pair(i * 2, j * 2);
}
}
bool source_cup_draw_enabled(const StaticMemory& mem, int competition) {
// CupDrawFromGame: outside leagues 4..7 the leagues must be enabled, then the
// competition's display option must be clear. The follow-up package targets comp0.
if (competition < 4 || competition > 7) {
if (!mem.has(::bmh::layout::CompetitionSelection) || (mem.u8(::bmh::layout::CompetitionSelection) & 1) == 0) return false;
}
const uint32_t option = ::bmh::layout::LeaguePresentationOptions + uint32_t(competition + 5) * 9;
return mem.has(option) && mem.u8(option) == 0;
}
void observe_cup_draw(const GameState& g, int entry, SeasonCupDrawPhase phase,
const SeasonCupDrawHook& hook) {
if (!hook) return;
const StaticMemory& mem = g.memory;
const uint32_t address = cup_entry_address(entry);
SeasonCupDrawEvent event;
event.phase = phase;
event.entry_address = address;
event.competition = mem.u8(address + 0x18);
event.round = cup_round(mem, entry);
event.offset = cup_round_offset(mem, entry, event.round);
event.count = size_t(mem.u8(address + 0x1a)) >> event.round;
const uint32_t first = mem.pointer(address) + uint32_t(event.offset) * 2;
event.participants.reserve(event.count);
for (size_t i = 0; i < event.count; ++i)
event.participants.push_back(mem.u16(first + uint32_t(i) * 2));
hook(g, event);
}
} // namespace
void advance_cup(GameState& g, int id, WatcomRandom& rand, MinuteReport& report, GameRandom* game,
const SeasonCupDrawHook& cup_draw, const CompetitionWinnerHook& winner_display) {
StaticMemory& mem = g.memory;
int entry = find_cup(mem, id);
if (entry < 0) return;
const int type = int16_t(mem.u16(cup_entry_address(entry) + 0x18));
if (type == 9) return store_replays(g, g.season_day());
// EndCompetition(type), re-added at the next preparation; the English Put32 keeps its
// League Cup (type 0xb) running like the other cups
if (type == 0xb && !kEnglishCompetitions) remove_competition(mem, type);
if (type == 10) {
// the friendlies: off the running list, the day's calendar entry masked with 0xffe
// (0x4001 becomes 0) and no teams left in today's entry (CupRuntimeField2)
remove_competition(mem, type);
const uint32_t day = ::bmh::layout::CompetitionCalendar + uint32_t(g.season_day()) * 2;
if (mem.has(day)) mem.set16(day, uint16_t(mem.u16(day) & 0xffe));
mem.set8(cup_entry_address(24) + 0x1a, 0);
return;
}
if (type > 8 && type != 0xd && type != 0xb) {
report.fail("cup " + std::to_string(id) + ": processing of this competition (AdvanceCup)");
return;
}
while (cup_round(mem, entry) >= mem.u8(cup_entry_address(entry) + 0x1b))
entry = int8_t(mem.u8(cup_entry_address(entry) + 0x16));
uint32_t e = cup_entry_address(entry);
std::vector<uint16_t> winners, losers;
std::array<uint16_t, 2> loser_pair{};
if (!(mem.u8(e + 0x14) & 4)) {
// a group stage: every group (the consecutive entries up to the one without a
// parallel link, +0x17) counts the round
for (uint32_t ge = e;; ge += kCupEntrySize) {
mem.set8(ge + 0x1d, uint8_t(mem.u8(ge + 0x1d) + 1));
if (mem.u8(ge + 0x17) == 0) break;
}
if (mem.u8(e + 0x1d) < mem.u8(e + 0x1b)) return;
winners = group_qualifiers(mem, e, loser_pair);
} else {
const int round = cup_round(mem, entry);
const int slots = mem.u8(e + 0x1a) / (1 << round); // local_3c: teams in this round
const int first = cup_round_offset(mem, entry, round);
mem.set8(e + 0x1d, uint8_t(mem.u8(e + 0x1d) + 1)); // (unless CupRuntimeField4)
const uint32_t list = mem.pointer(e);
if ((mem.u8(e + 0x14) & 1) && mem.u8(e + 0x1d) % 2 != 0) {
// after the first leg: the pairs turn round, the results go to the second array
for (int i = 0; i < slots; i += 2) {
swap16(mem, list + uint32_t(first + i) * 2, list + uint32_t(first + i + 1) * 2);
const uint32_t k = uint32_t((first + i) / 2) * 2;
swap16(mem, mem.pointer(e + 0x0c) + k, mem.pointer(e + 0x10) + k);
}
return;
}
for (int i = 0; i < slots; i += 2) {
int t = stage_tie(mem, e, (first + i) / 2);
if (t > 1) t = 1;
winners.push_back(mem.u16(list + uint32_t(first + i + t) * 2));
losers.push_back(mem.u16(list + uint32_t(first + i + 1 - t) * 2));
}
}
// CupRuntimeField5[type] < 5 (national cup and the three European cups): a human manager's
// club that goes through counts one more round in his season record (ManagerOf,
// record +0xda + season * 3 + 1 national / 2 European)
if (type >= 0 && type <= 3)
for (uint16_t t : winners) {
const int manager = g.manager_of(t);
if (manager < 0) continue;
const size_t at = size_t(manager) * 0xB0C + 0xda + size_t(std::min(g.season, 0x31)) * 3 + (type > 0 ? 2 : 1);
g.manager_records.at(at) = uint8_t(g.manager_records.at(at) + 1);
}
if (cup_round(mem, entry) == mem.u8(e + 0x1b)) {
// the stage is over
if (mem.u8(e + 0x16) == 0) {
// The last stage of the competition. A single final notes its winner (+0x22) and
// loser (+0x24); competition 0xc leaves the running list.
if (winners.size() == 1) {
mem.set16(e + 0x22, winners[0]);
if (!losers.empty()) mem.set16(e + 0x24, losers[0]);
}
if (type == 0xc) remove_competition(mem, 0xc);
// CupRuntimeField5: the title of the competition (0xFF: none)
static constexpr uint8_t kTitle[14] = {1, 2, 3, 4, 5, 0xff, 6, 0xff, 8, 0xff, 0xff, 0xff, 0xff, 0xff};
const uint8_t title = type >= 0 && type < 14 ? kTitle[type] : 0xff;
if (title != 0xff && !winners.empty()) {
if (type == 4) national_tournament_end(g); // NationalTournamentEnd
// CompetitionWinnerScreen(0, title, winner): the winner screen (unless switched off,
// Cup_AdvanceCup_RuntimeField; no draws) clears CareerSession_BeginFriendlyOpponentTable_ExecutableField2. A human manager's club counts
// the title in his record: +0x8a6 national cup, +0x8a8 European cups.
if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && winner_display)
winner_display(g, {title, winners[0]});
if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && mem.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2)) mem.set8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2, 0);
const int manager = g.manager_of(winners[0]);
if (manager >= 0 && type >= 0 && type < 4) {
const size_t at = size_t(manager) * 0xB0C + (type == 0 ? 0x8a6 : 0x8a8);
const uint16_t n = uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8);
g.manager_records.at(at) = uint8_t(n + 1), g.manager_records.at(at + 1) = uint8_t((n + 1) >> 8);
}
// ListTitleHoldersAf(winner, title): the list of title holders (Titles)
mem.set16(::bmh::layout::Titles + uint32_t(title) * 100 + uint32_t(std::min<int>(g.season, 0x31)) * 2, winners[0]);
}
if (type == 0 && !winners.empty()) {
// the national cup: winner (Cup_AdvanceCup_RuntimeField5) and the previous holder
// (Career_CompetitionPointersEnglish_ExecutableField28 = Cup_AdvanceCup_RuntimeField6); Cup_AdvanceCup_RuntimeField2 = 0 if the holder won again, else 2
mem.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField5, winners[0]);
mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField28, mem.u16(::bmh::layout::Cup_AdvanceCup_RuntimeField6));
if (mem.has(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31)) mem.set16(::bmh::layout::Career_CompetitionPointersEnglish_ExecutableField31, 0xcccc);
if (mem.has(::bmh::layout::Cup_AdvanceCup_RuntimeField2)) mem.set8(::bmh::layout::Cup_AdvanceCup_RuntimeField2, mem.u16(::bmh::layout::Cup_AdvanceCup_RuntimeField6) == winners[0] ? 0 : 2);
}
// a linked stage (+0x17) takes the runner-up (the indoor tournament's final group
// notes it in the group for third place)
if (mem.u8(e + 0x17) != 0 && winners.size() > 1)
mem.set16(cup_entry_address(mem.u8(e + 0x17)) + 0x22, winners[1]);
// (the indoor tournament only: the English League Cup has no Masters; its winner
// would go to EN CupRuntimeField6 for Europe - not ported, see docs/fltd.md)
if (type != 0xb || kEnglishCompetitions) return;
// the indoor tournament: the four places (CupRuntimeField7 picks them from the list
// champion..fourth) earn points for the Masters (CupRuntimeField8 x strength class
// Cup_AdvanceCup_RuntimeField3, clubs of the first two leagues only), then the next tournament is
// drawn; after five tournaments the Masters follow
int held = mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField4);
if (held > 4) {
// the end of the Masters: CompetitionWinnerScreen(0, 7, winner) shows the winner (unless
// switched off, Cup_AdvanceCup_RuntimeField; no draws) and clears CareerSession_BeginFriendlyOpponentTable_ExecutableField2;
// ListTitleHoldersAf(winner, 7) enters it in the list of title holders (Titles,
// 50 seasons per competition); Cup_AdvanceCup_RuntimeField7 = winner; a human manager's club
// gets a message and 250 000; EndCompetition removes the competition
const uint16_t winner = mem.u16(e + 0x22);
if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && winner_display)
winner_display(g, {7, winner});
if (mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && mem.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2)) mem.set8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2, 0);
mem.set16(::bmh::layout::Titles + 7 * 100 + uint32_t(std::min<int>(g.season, 0x31)) * 2, winner);
if (mem.has(::bmh::layout::Cup_AdvanceCup_RuntimeField7)) mem.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField7, winner);
const int manager = g.manager_of(winner);
if (manager >= 0) {
post_composed(g, manager, kMastersWinnerText); // MastersWinnerText
book_money(g, manager, -250000, true, true);
}
remove_competition(mem, type);
return;
}
static constexpr uint8_t kPlaceOrder[4] = {0, 2, 1, 3}; // CupRuntimeField7
static constexpr uint8_t kPlacePoints[5] = {0, 6, 4, 2, 1}; // CupRuntimeField8
for (int i = 0; i < 4 && size_t(kPlaceOrder[i]) < winners.size(); i++) { // Uint32T
const int team = winners[kPlaceOrder[i]];
if (team < kLeagueSizes[0] + kLeagueSizes[1]) {
const uint32_t at = ::bmh::layout::Cup_AdvanceCup_ExecutableField + uint32_t(team) * 2;
mem.set16(at, uint16_t(mem.u16(at) + kPlacePoints[i + 1] * mem.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField3)));
}
}
mem.set8(::bmh::layout::Cup_AdvanceCup_RuntimeField4, uint8_t(++held));
if (!game) {
report.fail("indoor tournament: the next draw needs the game generator");
return;
}
if (held >= 5) {
masters_qualification(g, *game);
return;
}
indoor_tournament_draw(g, *game, rand); // (CupRuntimeField = 0)
return;
}
uint32_t last = e;
const int seeded = mem.u8(e + 0x20);
if (seeded != 0) {
// clubs seeded directly into the next stage stand before the team lists
const int groups = mem.u8(e + 0x1e) & 0xF;
int left = seeded;
for (int k = 0; left != 0; k++)
for (int grp = 0; grp < groups; grp++) {
uint32_t ge = e;
while ((mem.u8(ge + 0x1e) >> 4) != grp) ge += kCupEntrySize;
last = ge;
if (left != 0) {
winners.push_back(mem.u16(mem.pointer(ge) - 2 - uint32_t(k) * 2));
left--;
}
}
}
entry = int8_t(mem.u8(last + 0x16));
e = cup_entry_address(entry);
}
const int count = int(winners.size()); // local_14
if (mem.u8(e + 0x14) & 0x20) {
// the draw
for (int i = 0; i < count; i++) {
const int a = rand.range(0, count - 1);
const int b = rand.range(0, count - 1);
std::swap(winners[size_t(b)], winners[size_t(a)]);
}
}
if (!(mem.u8(e + 0x14) & 4)) {
// a group stage: the teams go round the groups, taken from the end
// groups of two (third place and final): the losers of the ties are added (local_88)
if (mem.u8(e + 0x1a) == 2)
for (int i = 0; i < 2 && size_t(i) < losers.size(); i++) winners.push_back(losers[size_t(i)]);
const int groups = mem.u8(e + 0x1e) & 0xF;
int left = int(winners.size());
uint32_t ge = e;
for (int slot = 0; slot < mem.u8(e + 0x1a); slot++)
for (int grp = 0; grp < groups; grp++) {
ge = e;
while ((mem.u8(ge + 0x1e) >> 4) != grp) ge += kCupEntrySize;
mem.set16(mem.pointer(ge) + uint32_t(slot) * 2, winners.at(size_t(--left)));
}
// AdvanceCup leaves any entrants beyond the regular group slots in the reserved
// list immediately before the final linked group's team list (entry +0x20 is the
// source guard). The Source consumes the remaining local list backwards.
if (mem.u8(ge + 0x20) != 0) {
for (int slot = 0; left > 0; ++slot)
for (int grp = 0; grp < groups; ++grp)
if (left > 0)
mem.set16(mem.pointer(ge) - 2 - uint32_t(slot) * 2, winners.at(size_t(--left)));
}
if (mem.u8(e + 0x1a) == 2) {
// the first club of this group and the second of the linked group change places
const uint32_t a = mem.pointer(e), b = mem.pointer(cup_entry_address(mem.u8(e + 0x17))) + 2;
const uint16_t x = mem.u16(a);
mem.set16(a, mem.u16(b));
mem.set16(b, x);
}
} else {
const int next_round = cup_round(mem, entry);
const int offset = cup_round_offset(mem, entry, next_round);
const uint32_t to = mem.pointer(e);
int first_pair = 0;
if (next_round == mem.u8(e + 0x1b) && mem.u8(e + 0x20) != 0) {
first_pair = mem.u8(e + 0x20);
for (int i = 0; i < first_pair; ++i)
mem.set16(to - 2 - uint32_t(i) * 2, winners.at(size_t(i)));
}
for (int i = first_pair; i < count / 2; i++) {
mem.set16(to + uint32_t(offset + i * 2) * 2, winners[size_t(i)]);
mem.set16(to + uint32_t(offset + i * 2 + 1) * 2, winners[size_t(count - 1 - i)]);
}
if (e == cup_entry_address(0)) {
const bool eligible = type == 0 && count > 2 && (mem.u8(e + 0x14) & 0x20) != 0 &&
source_cup_draw_enabled(mem, type);
if (eligible) {
// CupDrawFromGame displays the just-written shuffled order first.
observe_cup_draw(g, entry, SeasonCupDrawPhase::draw, cup_draw);
// It then performs Getenv and CupGroupOverviewEffects before returning.
order_national_cup_ties(g, count, offset);
cup_overview_effects(g); // simulation effects occur even without an observer
observe_cup_draw(g, entry, SeasonCupDrawPhase::overview, cup_draw);
}
// AdvanceCup performs this outer sort after CupDrawFromGame returns (including
// its hidden-display early return). It is idempotent after the inner sort.
order_national_cup_ties(g, count, offset);
}
}
// Career_EuropeanClub_ExecutableField / Career_EuropeanClub_ExecutableField2 / Career_EuropeanClub_ExecutableField3: clubs left in the European cups
const uint32_t left_at[4] = {0, ::bmh::layout::Career_EuropeanClub_ExecutableField, ::bmh::layout::Career_EuropeanClub_ExecutableField2, ::bmh::layout::Career_EuropeanClub_ExecutableField3};
if (type >= 1 && type <= 3 && mem.has(left_at[type])) mem.set8(left_at[type], uint8_t(count));
}
} // namespace bmh
+91
View File
@@ -0,0 +1,91 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#pragma once
// Cup competitions (BMH.exe V2.24 + supported rule profile patch).
//
// All cups are described by the table at CupTable: 36 entries of 0x28 bytes, one per stage
// (knockout rounds of a cup, a group of a group stage, a final, ...). Entries of the same
// cup share the id at +0x18 and are linked:
// +0x00 pointer to the team list (u16 team ids; for knockout stages the pairs of each
// round follow each other, round r starting at cup_round_offset(r))
// +0x08 pointer to the round strings of group stages (fixture tables, see schedule.hpp)
// +0x0c pointer to the results of the first/only leg, +0x10 of the second leg (u16 per
// match: bits 0-4 away goals, 5-9 home goals, 10-15 phase; 0xCCCC not played)
// +0x14 flags: bit 0 two legs, bit 2 knockout, bit 3 the tie is decided on the day
// (extra time), bit 1 away-side penalty for league-style chances, ...
// +0x16 index of the next stage, +0x17 index of the parallel group of this stage
// +0x18 cup id (0 national cup, 1-3 European cups, 4.. further competitions)
// +0x1a number of teams, +0x1b number of rounds (legs), +0x1d legs played so far
// +0x1e low nibble: number of parallel groups, high nibble: index of this group
// Match group descriptors of cups have type = cup id + 1 and point to their table entry
// (descriptor +0xcc) instead of holding a league number.
#include <cstdint>
#include <vector>
#include "game/match_engine.hpp"
#include "game/table.hpp"
#include "game/season.hpp"
#include "game/sportschau_presentation.hpp"
#include "game/state.hpp"
namespace bmh {
constexpr uint32_t kCupTable = ::bmh::layout::CupTable;
constexpr int kCupEntries = 36;
constexpr uint32_t kCupEntrySize = 0x28;
inline uint32_t cup_entry_address(int index) { return kCupTable + uint32_t(index) * kCupEntrySize; }
inline int cup_entry_index(uint32_t address) { return int((address - kCupTable) / kCupEntrySize); }
// FindCup(id, 0): the first table entry of a cup, -1 if there is none.
int find_cup(const StaticMemory& mem, int id);
// CupRound: the current round of a stage (legs played, halved for two-legged ties).
int cup_round(const StaticMemory& mem, int entry);
// CupRoundOffset: index of the first team of knockout round `round` in the team list.
int cup_round_offset(const StaticMemory& mem, int entry, int round);
// AddResult's group-table calculation. Exposes the existing Core projection
// as a read-only value for Source overview observers and renderers.
LeagueTable cup_group_table(const StaticMemory& mem, uint32_t entry_address);
// Team count selected by the Source group round-schedule pointer at entry +8.
int cup_group_schedule_teams(const StaticMemory& mem, uint32_t entry_address);
// SetupCupGroups: the match groups of cup `id` for today, appended to `groups`.
void setup_cup_groups(GameState& g, int id, std::vector<MatchGroup>& groups, MinuteReport& report);
// The lists of today's postponed-match replays (blocks ReplayFixtures/ReplayResults, not in the savegame) as
// the preparation of the matchday built them (prepare_replays, no draws): needed when a game
// saved at the pre-match desk of a replay day is continued.
void rebuild_replay_lists(GameState& g, uint32_t competitions);
// EndCompetition(id): takes a competition off the list of running ones (ActiveSelectors).
void end_competition(StaticMemory& mem, int id);
// PrepareFriendlies: the friendlies (competition 10, cup table entry 24) of today: the planned ones
// (entry 30: team pairs FriendlyTeams, season days FriendlyDays, 30 places) of this season day
// go into the day's fixture list (Career_CompetitionPointersEnglish_ExecutableField24) with an open result (0xcccc) and leave the plan.
void prepare_friendlies(GameState& g);
} // namespace bmh
namespace bmh {
// Writes the results of a cup group (current leg) back into the result array in memory.
void store_cup_results(GameState& g, const MatchGroup& grp);
// AdvanceCup for knockout stages: after a matchday of cup `id` the legs played go up;
// after the first leg of a two-legged tie the pairs turn round (home and away swapped,
// the results moved to the other leg's array). After a complete round the winners
// (cup_tie) meet in the next round - drawn if the stage has flag 0x20 (WatcomRandom) -
// or, when the stage is over, fill the next linked stage, including qualifiers and direct
// seeds for group and knockout formats; group match simulation and competition-specific
// finals remain outside this routine.
// The indoor tournament draws its next tournament at the end (game generator, `game`).
void advance_cup(GameState& g, int id, WatcomRandom& rand, MinuteReport& report, GameRandom* game = nullptr,
const SeasonCupDrawHook& cup_draw = {}, const CompetitionWinnerHook& winner = {});
// The end of the fifth indoor tournament: the field of the Masters (MastersQualification2,
// IndoorStandingsFromGame(0)), see cup.cpp.
void masters_qualification(GameState& g, GameRandom& game);
} // namespace bmh
+129
View File
@@ -0,0 +1,129 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/desk.hpp"
#include <algorithm>
#include <array>
#include <string>
#include <vector>
#include "game/matchday.hpp"
#include "game/messages.hpp"
#include "game/prediction.hpp"
#include "game/schedule.hpp"
#include "game/week.hpp"
namespace bmh {
namespace {
constexpr size_t kRecord = 0xB0C;
// DeskRuntimeField: which of the 0x36 desk buttons exist, for the pseudo club 0x165 and per
// game mode (GameMode; the table for mode m starts at DeskRuntimeField + m * 0x36).
constexpr uint8_t kButtons[0xa2] = {
0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1,
1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1,
0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1,
1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 0};
int16_t rd16(const std::vector<uint8_t>& v, size_t o) { return int16_t(v.at(o) | v.at(o + 1) << 8); }
} // namespace
void update_prestige(GameState& g, int manager) {
static const uint8_t kWeight[4] = {25, 50, 15, 10}; // DeskRuntimeField2
std::vector<uint8_t>& r = g.manager_records;
const size_t rec = size_t(manager) * kRecord;
r.at(rec + 0x211) = 0;
for (int k = 0; k < 4; k++) {
int value = 0; // local_c
switch (k) {
case 0: value = (rd16(r, rec + 0x8b2) * 100) / 0x44c; break;
case 1: value = (rd16(r, rec + 0x8aa) * 100) / 0x44c; break;
case 2: {
const int32_t balance = int32_t(r.at(rec + 0x314) | r.at(rec + 0x315) << 8 | r.at(rec + 0x316) << 16 |
uint32_t(r.at(rec + 0x317)) << 24);
value = std::clamp(balance / 50000 + 0x32, 0, 100);
break;
}
case 3: value = r.at(rec + 0x26f); break;
}
r.at(rec + 0x211) = uint8_t(r.at(rec + 0x211) + int8_t((kWeight[k] * value) / 100));
}
}
void save_game_draws(WatcomRandom& rand) {
const int high = rand.range(0, 0x8fff), low = rand.range(0, 0x8fff);
(void)high, (void)low; // the savegame id high * layout field + low + 1 (DeskRuntimeField3, list ab790)
rand.range(0, 0xff); // DeskRuntimeField4 = r + 'n', the check byte at the end of the file
rand.range(0, 0xff); // the key byte of the header
}
void enter_desk(GameState& g, int manager, GameRandom& game, WatcomRandom& rand,
const DeskAutosaveHook& autosave) {
const int team = g.manager_teams.at(size_t(manager));
// HasNoEquivalentCondition: button states (block Desktops, 0x10 bytes per button, 0x360 per manager)
const int mode = g.memory.has(::bmh::layout::GameMode) ? g.memory.u8(::bmh::layout::GameMode) : 0;
const int mode2 = g.memory.has(::bmh::layout::CareerDuration) ? g.memory.u8(::bmh::layout::CareerDuration) : 0;
if (g.memory.has(::bmh::layout::Desktops))
for (int b = 1; b < 0x36; b++) {
const uint32_t at = ::bmh::layout::Desktops + uint32_t(b) * 0x10 + uint32_t(manager) * 0x360 + 1;
uint8_t v = uint8_t(g.memory.u8(at) & 0xf);
// EN AlwaysHidesRecordIndoorTableIncluding always hides record 10 (IndoorTable), including
// Modus III. DE HasNoEquivalentCondition has no equivalent condition.
if ((kEnglishCompetitions && b == 10) ||
(team == kNoTeam && kButtons[b] == 0) || (mode < 3 && kButtons[mode * 0x36 + b] == 0) ||
(b == 0x16 && mode2 == 1 && g.date < 0x16e))
v |= 0x10;
g.memory.set8(at, v);
}
stir_random(game, rand); // StirRandom
if (team != kNoTeam) {
std::array<uint8_t, 24> buf;
table_prediction(g, team, 1, buf);
}
// The autosave: at the first manager's desk a new month code (CareerSession_PairingsRuntimeDraw_ExecutableField5) counts one
// more month (DeskRuntimeField5); every Desk_EnterDesk_RuntimeField months (a setting, byte 0x61 of block
// LeaguePresentationOptions, 0 = off) the game saves itself as AUTOSAVE (MakeSavegame)
if (manager == 0) {
const int month = month_code(g.date);
if (g.autosave_month != month) g.autosave_month = month, g.autosave_months++;
}
const int period = g.memory.has(::bmh::layout::LeaguePresentationOptions) ? g.memory.u8(::bmh::layout::Desk_EnterDesk_RuntimeField) : 0;
if (period != 0 && g.autosave_months != 0 && g.autosave_months % period == 0) {
if (autosave) autosave(g, rand);
else save_game_draws(rand); // unpresented/headless legacy model
g.autosave_months = 0;
}
// (the warnings of Fill are display only)
update_prestige(g, manager);
// At the "Saisonende" desk (CareerSession_RuntimeError_RuntimeField4): the main sponsor's minimal goal (record
// +0x176, a table place). Missed: "Ihnen entgehen Sponsorgelder, da Sie das Minimalziel
// (<goal>. Platz) nicht erreicht haben." Reached: (4 - league) * 50000 per place better
// than the goal plus one (the third divisions count as the second), booked as income.
std::vector<uint8_t>& r = g.manager_records;
const size_t rec = size_t(manager) * 0xB0C;
const int goal = r.at(rec + 0x176);
if (g.memory.has(::bmh::layout::CareerSession_RuntimeError_RuntimeField4) && g.memory.u8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4) != 0 && goal != 0) {
const int place = int16_t(table_position(g, team)) + 1; // TablePosition
std::string text;
if (goal < place) {
text = message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer5) + format_number(g, goal, 1) + message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer6);
} else {
int league = int8_t(r.at(rec + 0x210)); // CareerSession_BeginFriendlyOpponentTable_RuntimeField2
if (league > 2) league--;
const int32_t amount = (4 - league) * 50000 * (goal - place + 1);
book_money(g, manager, -amount, true, true); // BookMoney2 with FinanceStatisticsEnabled
text = message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer2) + format_number(g, amount, 0x101) + message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer) +
format_number(g, place, 1) + message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer3) + format_number(g, goal, 1) +
message_text(g, ::bmh::layout::Desk_SaveGameDraws_TextPointer4);
}
post_composed(g, manager, text);
r.at(rec + 0x176) = 0;
}
}
} // namespace bmh
+29
View File
@@ -0,0 +1,29 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// Entering a human manager's desk (DeskDate, the part before the desk screen).
#include "game/random.hpp"
#include "game/state.hpp"
#include <functional>
namespace bmh {
// DeskDate up to the screen: the desk buttons (HasNoEquivalentCondition), the random stir when a
// screen is entered (StirRandom), the table prediction with its season goal messages
// (Void5 mode 1), the autosave every Desk_EnterDesk_RuntimeField months and the manager's
// prestige (UpdatePrestige).
// Source save operation at the desk boundary. A successful writer owns exactly
// the normal four Save draws; failure before opening the file owns none.
using DeskAutosaveHook = std::function<void(const GameState&, WatcomRandom&)>;
void enter_desk(GameState& g, int manager, GameRandom& game, WatcomRandom& rand,
const DeskAutosaveHook& autosave = {});
// The draws of saving a game (MakeSavegame): the savegame id (two WatcomRandom(0, 0x8fff))
// and two bytes WatcomRandom(0, 0xff). Everything else the save writes is not saved itself.
void save_game_draws(WatcomRandom& rand);
// UpdatePrestige: prestige of a human manager (record +0x211), a weighted sum of his two
// manager ratings (+0x8b2 25 %, +0x8aa 50 %), his money (15 %) and record +0x26f (10 %).
void update_prestige(GameState& g, int manager);
} // namespace bmh
File diff suppressed because it is too large. Load diff
+616
View File
@@ -0,0 +1,616 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// OpenBMH deviates from the original: supports designated set-piece records and the supported transfer-editor rules.
// Actions a human manager can take at his desk that change the game state and draw random
// numbers (BMH.exe V2.24 + supported rule profile patch). The screens themselves belong to the UI; these
// functions are what happens when the manager confirms.
#include <array>
#include <cstdint>
#include <functional>
#include <optional>
#include <string>
#include <vector>
#include "game/random.hpp"
#include "game/state.hpp"
#include "game/human_buyer_sale.hpp"
#include "game/club_player_detail.hpp"
namespace bmh {
struct MinuteReport;
class LeImage;
// The eight training camp resorts of BookTrainingCamp (names DeskActionsRuntimeField7).
constexpr int kTrainingCampResorts = 8;
// Resort names, qualities and prices are edition content, not shared rules.
// Install the loaded executable's tables after creating or loading a GameState.
void configure_training_camp_data(GameState&, const LeImage&);
// DeskDate / menu 6 friendship booking. `manager_home` selects which team is first in
// the saved pair; the manager of the home team pays the source cost. The national-team
// source-qualified overload below handles pseudo-team ratings and their W/G RNG separately.
enum class FriendlyQuoteStatus : uint8_t { quoted, invalid_manager, invalid_opponent, invalid_state };
enum class FriendlyDateStatus : uint8_t {
available, available_with_calendar_event, current_or_past, unavailable,
plan_full, invalid_quote, invalid_date
};
enum class FriendlyBookingStatus : uint8_t {
booked, declined, opponent_declined, insufficient_funds, invalid_manager, invalid_opponent,
invalid_date, date_unavailable, plan_full, stale_quote, invalid_request
};
struct FriendlyBookingQuote {
FriendlyQuoteStatus status = FriendlyQuoteStatus::invalid_opponent;
int manager = -1;
int opponent = -1;
int manager_team = -1;
bool manager_home = true;
int home_team = -1;
int away_team = -1;
int payer_manager = -1;
int opponent_manager = -1;
int32_t cost = 0;
uint8_t planner_count = 0;
bool operator==(const FriendlyBookingQuote&) const = default;
};
struct FriendlyBookingRequest {
FriendlyBookingQuote quote;
uint16_t season_day = 0;
bool accept_opponent = false;
int consenting_manager = -1;
bool accept_cost = false;
int approving_manager = -1;
};
struct FriendlyBookingResult : FriendlyBookingQuote {
FriendlyBookingStatus status = FriendlyBookingStatus::invalid_request;
};
// Source-qualified menu-6 national friendly owner. The UI/session supplies the
// revision and request identity; the engine binds them to the selected runtime nation.
struct NationalFriendlyOwner {
uint64_t request_id = 0;
uint64_t revision = 0;
int manager = -1;
int runtime_team = kNoTeam;
int menu_kind = -1;
bool operator==(const NationalFriendlyOwner&) const = default;
};
struct NationalFriendlyQuote {
FriendlyBookingQuote terms;
NationalFriendlyOwner owner;
int own_rating = 0;
int opponent_rating = 0;
uint32_t watcom_seed_before = 0;
uint32_t watcom_seed_after = 0;
uint64_t watcom_calls_before = 0;
uint64_t watcom_calls_after = 0;
bool operator==(const NationalFriendlyQuote&) const = default;
};
struct NationalFriendlyBookingRequest {
NationalFriendlyQuote quote;
NationalFriendlyOwner owner;
uint16_t season_day = 0;
bool accept_opponent = false;
int consenting_manager = -1;
bool accept_cost = false;
int approving_manager = -1;
bool operator==(const NationalFriendlyBookingRequest&) const = default;
};
struct NationalFriendlyBookingResult : FriendlyBookingResult {
bool national_bonus_awarded = false;
};
// Pure source-derived quote for the pre-calendar price/venue prompt. It performs no writes
// or RNG draws. Bind this quote to the UI request ID/revision until the user chooses a day.
FriendlyBookingQuote quote_friendly_match(const GameState& g, int manager, int opponent,
bool manager_home);
// Original menu-6 national quote. A successful accepted quote advances W exactly for
// QuoteNationalFriendlyMatch's ratings. Preview runs the same calculation on a copy and never advances W.
NationalFriendlyQuote quote_national_friendly_match(const GameState& g,
const NationalFriendlyOwner&, int opponent, bool manager_home, WatcomRandom& rand);
NationalFriendlyQuote preview_national_friendly_match(const GameState& g,
const NationalFriendlyOwner&, int opponent, bool manager_home, const WatcomRandom& rand);
FriendlyDateStatus national_friendly_match_date_status(const GameState&,
const NationalFriendlyQuote&, const NationalFriendlyOwner&, const WatcomRandom&,
uint16_t season_day);
NationalFriendlyBookingResult book_national_friendly_match(GameState&,
const NationalFriendlyBookingRequest&, const WatcomRandom&, GameRandom&);
// Conservative saved-state projection for days 0..365. `available_with_calendar_event` is
// the source color class for a selectable day whose calendar word has 0x1c0 set. The
// original calendar also carries a transient, sequentially projected bit 15 that is not in
// GameState; dates with ambiguous neighboring calendar flags may therefore be over-rejected.
FriendlyDateStatus friendly_match_date_status(const GameState& g,
const FriendlyBookingQuote& quote,
uint16_t season_day);
// Book the accepted quote on the chosen day atomically. The quote is recomputed and must
// still match; approval is explicit. A successful home booking permanently debits the fee
// and records expense-other (+0x8a0). No RNG is used for club-vs-club bookings.
FriendlyBookingResult book_friendly_match(GameState& g, const FriendlyBookingRequest& request);
// UI-free human transfer actions (menu 17). List-entry indices address the 44-entry
// transfer table; money and contracts are stored in the normal engine state.
enum class TransferActionStatus : uint8_t {
accepted, pending, rejected, offer_too_low, blocked_by_board, insufficient_funds, no_squad_room,
invalid_manager, invalid_player, invalid_request, allocator_blocked, unsupported
};
struct TransferBidRequest {
int manager = -1;
int list_entry = -1;
int player = -1; // expected player identity; rejects a recycled list slot
int32_t fee = 0;
int32_t annual_salary = 0;
uint8_t contract_years = 1;
std::array<uint32_t, 7> bonuses{};
// Exact absolute SquadSlots player-pool index observed by the selected market row.
// The Source-qualified submit requires this explicitly; the legacy overload
// ignores it and preserves its historical request contract.
int source_slot = -1;
// Poaching: list entries 40..43 and the SubmitTransferBidSourceHumanBuyer branches for them (immediate
// decision, a human seller is asked, the DFB fee on a refusal; src/game/poach.hpp).
bool poach = false;
// OpenTransferEditor's loan checkbox is encoded in the high bit of the submitted
// offer term, independently of its 1..4 year duration.
bool loan = false;
// DayStepRest2's buy-back row from Range2 is a distinct 40..43 Source entry;
// it uses ordinary fee/qualification rules and is not poaching.
bool loan_return_entry = false;
};
struct TransferActionResult {
TransferActionStatus status = TransferActionStatus::invalid_request;
int player = -1;
int list_entry = -1;
int32_t fee = 0;
int32_t annual_salary = 0;
};
// Authenticated lender snapshot -> real borrower squad identity. This is preview
// only; the snapshot never becomes a listing/sale row.
struct TransferMarketSnapshotPreview {
int snapshot_index=-1,displayed_row=-1,source_slot=-1,player=-1;
bool operator==(const TransferMarketSnapshotPreview&) const = default;
};
std::optional<TransferMarketSnapshotPreview> transfer_market_snapshot_preview(
const GameState&,int manager,int runtime_club,int snapshot_index);
// TransferMarketScreen quote identity: ordinary Native slot, or an explicitly authenticated
// lender snapshot mapped by the read-only resolver above.
struct TransferMarketPreviewRequest {
int manager=-1,runtime_club=-1,source_slot=-1,expected_player=-1,seller=-1;
bool purchase=false,loan=false;
int snapshot_index=-1;
};
struct TransferMarketPreviewResult {
bool supported=false;
uint32_t fee=0,salary=0;
int32_t delta=0,projected_balance=0;
std::string reason;
};
// No Native writes or G draws. W is0 or1 (42307 fallback). The owner stages W
// and rolls it back on unsupported/exception; repeated-hover caching belongs
// to that owner, not to this primitive or a render method.
TransferMarketPreviewResult quote_transfer_market_preview_source(
const GameState& g,const TransferMarketPreviewRequest& request,WatcomRandom& rand);
// Exact ordinary OpenTransferEditor/KB31 state owner. UI events contain calculator
// results in Native units; all quotes and Native row writes belong here.
struct TransferOfferEditorRequest {
int manager=-1,runtime_club=-1,list_entry=-1,source_slot=-1,expected_player=-1;
uint16_t expected_seller_word=0xffff;
int expected_bid_slot=-1; // Source's first FFFF or matching own word; -1 if full.
bool loan=false;
// Poaching (Abwerben, Reset button 4): the special list entry 40..43 that
// Range2 prepared for the player (src/game/poach.hpp); SubmitTransferBidSourceHumanBuyer then decides at once.
bool poach=false;
// Explicit owner for DayStepRest2 -> Range2 return offers in entries40..43.
// This does not select the poaching branch or its DFB/188% rules.
bool loan_return_entry=false;
};
struct TransferOfferInputProfile {
uint32_t minimum=0,maximum=0,initial=0,source_text_address=0;
std::array<std::optional<uint32_t>,8> presets{};
bool supported=false,currency=false;
};
struct TransferOfferEditorState {
bool supported=false,closed=false,existing=false,editable=false,quote_loan=false;
// OpenTransferEditor local1c: set only after initializing a selected FFFF row.
// Existing-own and full read-only openings keep it false until needed.
bool initialized_empty_bid=false;
std::string reason;
TransferOfferEditorRequest request;
int bid_slot=-1;
std::optional<ClubPlayerDetailSelection> player_info_selection; // Source local40 retained at opening.
uint8_t percent=0,term=0,years=1,mode=0;
uint32_t fee=0,salary=0,asking_fee=0,asking_salary=0,quoted_fee=0,quoted_salary=0;
std::array<uint8_t,7> bonuses{};
std::array<TransferOfferInputProfile,2> money_profiles{};
std::array<TransferOfferInputProfile,8> mode3_profiles{}; // years, seven bonuses
std::array<uint8_t,0x58> native_entry{}; // stale event guard, owned copy
};
enum class TransferOfferEditorField : uint8_t { fee,salary,years,bonus0,bonus1,bonus2,bonus3,bonus4,bonus5,bonus6,toggle_quote_loan };
struct TransferOfferEditorEvent {
TransferOfferEditorField field=TransferOfferEditorField::fee;
uint32_t value=0;
bool accepted=true; // calculator Cancel; fee/salary still redraw Source quote
};
TransferOfferEditorState open_transfer_offer_editor_source(GameState&,
const TransferOfferEditorRequest&,GameRandom&,WatcomRandom&);
TransferOfferEditorState edit_transfer_offer_editor_source(GameState&,
const TransferOfferEditorState&,const TransferOfferEditorEvent&,GameRandom&,WatcomRandom&);
// OpenTransferEditor TeamInfo return: 1c5b7 -> 1c186 -> 1c18b. Rescan and
// redraw the current row, preserving initial percent/G. A first empty selection
// initializes only fee/salary/term once; all seven Native bonus bytes survive.
TransferOfferEditorState resume_transfer_offer_team_info_source(GameState&,
const TransferOfferEditorState&,WatcomRandom&);
// OpenTransferEditor:6936..6953 resolves the direct footer's actual player slot.
// Unmanaged sellers use the Native pool slot; managed sellers use the first
// masked-ID match in their real 24/16-slot squad. The opened owner retains
// Source local40; stale retained rows reject instead of silently reselecting.
ClubPlayerDetailSelection transfer_offer_player_info_selection_source(const GameState&,
const TransferOfferEditorState&);
// After player information returns: zero return flags preserve the entire editor and quote;
// otherwise rescan/requote by rebuilding the quote without repeating the initial G draw.
TransferOfferEditorState resume_transfer_offer_player_info_source(GameState&,
const TransferOfferEditorState&,uint8_t player_info_primary_refresh,uint8_t player_info_secondary_refresh,WatcomRandom&);
TransferOfferEditorState cancel_transfer_offer_editor_source(const GameState&,
const TransferOfferEditorState&);
struct TransferOfferEditorSubmitResult {
TransferOfferEditorState editor;
TransferActionResult action;
};
TransferOfferEditorSubmitResult submit_transfer_offer_editor_source(GameState&,
const TransferOfferEditorState&,WatcomRandom&,const HumanBuyerSaleHooks&,MinuteReport&);
// Submit a manager bid on an existing list entry. A full-value fee and salary meeting
// the demand complete an immediate agreement; lower viable offers persist for weekly review.
TransferActionResult submit_transfer_bid(GameState& g, const TransferBidRequest& request, WatcomRandom& rand);
// Explicit opt-in Source SubmitTransferBidSourceHumanBuyer ordinary bid-submit path. Unlike the legacy
// overload, the caller owns staged Native/W state, supplies the exact source
// pool slot, actual career mode is present in Native, and the session provides
// its allocator/entry ownership plus Original notice presenter. Source-approved
// AI/free-agent purchases use the exact shared settlement; other sellers retain
// a pending bid. Unsupported contexts require caller rollback.
TransferActionResult submit_transfer_bid_source_human_buyer(GameState& g,
const TransferBidRequest& request, WatcomRandom& rand,
const HumanBuyerSaleHooks& hooks, MinuteReport& report);
// Put one of the manager's squad rows on the list. The request consumes the original
// listing-price RNG and returns the new stable entry index through the result.
TransferActionResult list_manager_player(GameState& g, int manager, int squad_row,
WatcomRandom& rand, MinuteReport& report);
enum class TrainingCampBookingBlock { none, booked_this_week, visit_limit, invalid_request };
// SetTrainingCampFocus: persist the four focus sliders (+0xc1..+0xc4) without drawing or
// applying training. Rejects an invalid manager or any value outside the original 0..15 range.
bool set_training_camp_focus(GameState& g, int manager, const std::array<uint8_t, 4>& focus);
// BookTrainingCamp controller gates, before payment and training effects.
TrainingCampBookingBlock training_camp_booking_block(const GameState& g, int manager);
// Text: price of a stay at `resort` for the manager's team - the resort's base
// price (DeskActions_ConfigureTrainingCampData_RuntimeField2 of the loaded game) plus 5 000 per player of the squad
// (QuoteNationalFriendlyMatch with 0xff, the player count). Draws nothing.
int32_t training_camp_price(const GameState& g, int manager, int resort);
// BookTrainingCamp on "Buchen": the price is booked (BookMoney2, not forced). If the money is
// there, record +0x890 (training camp expenses) grows by it, record +0x21f counts the stays
// (bit 7 = "already in a camp this week", cleared by the day step) and the camp takes
// effect (training_camp_effect). Returns false if the booking failed. The four focus
// sliders (record +0xc1..+0xc4, 0..15) are set on the screen before.
// The screen allows a booking only if bit 7 of +0x21f is clear and fewer than 3 stays
// were made (+0x21f & 0x7f < 3) - checked by the caller.
bool book_training_camp(GameState& g, int manager, int resort, WatcomRandom& rand);
// OpenBMH deviates from the original: supports designated set-piece records and the supported transfer-editor rules.
// TrainingCampEffect (with the supported rule profile patch TrainingCampEffect2 / TrainingCampEffect3 / TrainingCampEffect4): the
// effect of a training camp. The team morale rises by 12 * quality * 20 % (clamped to
// 0..47), then every player of the squad may improve in condition, technique, form,
// familiarity (tactics board +0xf) and freshness (board +0x0e bits 0-5). See the .cpp.
// Ends with the message DeskActionsRuntimeField8 (SystemIdentity, no draws).
void training_camp_effect(GameState& g, int manager, int resort, WatcomRandom& rand);
} // namespace bmh
namespace bmh {
// The stock exchange screen MaxSharesToBuy (bank button). The twelve shares are entries of
// 0x5c bytes in GameState::stocks (StockExchange): +0x00 long-term value (u32, price * 100),
// +0x04 + manager * 4 the amount the manager paid for his shares (u32), +0x16 trend byte,
// +0x4e current price (u16), +0x50 + manager * 2 shares held (u16), +0x59 age of the trend.
constexpr int kStocks = 12;
// Largest number of shares of `stock` the manager may buy: (money + credit line) / price,
// with at most 9999 shares of one company.
int max_shares_to_buy(const GameState& g, int manager, int stock);
// Buying `count` shares: the price times count plus 1.5 % fee is booked (BookMoney2, not
// forced) - but only while the paid amount of all shares held stays below 5 % of the
// money (record +0x314 / 20), else the message Bank_OriginalToUtf8_TextPointer8 ("too much") and nothing
// happens (returns false). Record +0x324 (stock balance) falls by the amount.
bool buy_shares(GameState& g, int manager, int stock, int count);
// Selling `count` shares at the current price: the paid amount shrinks by its average per
// share, the money (forced booking) and record +0x324 rise.
void sell_shares(GameState& g, int manager, int stock, int count);
// The "Tip" button (costs 5 000, booked forced with statistics): 0 (sell) .. 4 (buy),
// from the trend byte and the price against the long-term value, then with chance 1/3
// moved by -2, 0 or +2 (WatcomRandom(0, 2) twice). The text is Bank_FormatError_RuntimeField19[tip].
int stock_tip(GameState& g, int manager, int stock, WatcomRandom& rand);
} // namespace bmh
namespace bmh {
// The stadium screen ConstructionPricePercent (stadium button) - the parts that draw numbers or book.
// The manager record holds 14 periphery objects (+0x00..+0x0d condition, +0x1e..+0x2b
// construction weeks), eight Facility/Maintain investments (+0x0e.. condition,
// +0x2c.. construction weeks, +0x3c.. current/pending level), and eight stand blocks
// (+0x34.. construction weeks, +0x44.. seat/roof flags, +0x4c.. current capacity in
// thousands, +0x54.. future capacity). These are distinct Source branches.
// On opening: the game generator restarts from the saved seed CareerSession_Invalid_RuntimeField2 and draws the
// building company's discount, DeskActionsRuntimeField9 = 100 - G(r / 100, r / 100 + 5) with r =
// record +0x8b4 (int16). Returns the price percentage (100 - discount).
int construction_price_percent(const GameState& g, int manager, GameRandom& game);
// The offer for periphery object `object` (0..13) when it is clicked: the game generator
// restarts from CareerSession_Invalid_RuntimeField2, draws G(0, 100) once per object before it and then the
// price percentage G(85, 115); price = base (StadiumPriceTable) * percentage / 1 000 000 *
// 10 000.
int32_t periphery_offer(const GameState& g, int object, GameRandom& game);
// PayConstruction: pays a construction. With `sponsor` and a sponsor share (record +0x171)
// the price is reduced once - by ((share >> 5) + 3) * 10 % below a limit of ((share >> 2)
// & 7) * 325 000 + 26 000, else by WatcomRandom(2, 4) * 5 % ("Der Sponsor fühlt sich
// ausgenutzt") - and the share is cleared. Booked with statistics, not forced.
enum class ConstructionNoticeKind { SponsorContribution, SponsorExploited, InsufficientFunds };
struct ConstructionNotice {
int manager = -1;
ConstructionNoticeKind kind = ConstructionNoticeKind::InsufficientFunds;
uint32_t gross_price = 0, subsidy = 0;
int percent = 0;
};
using ConstructionNoticeHook = std::function<void(const GameState&, const ConstructionNotice&)>;
// PayConstruction presents the sponsor notice before clearing+171. A genuine
// BookMoney2 refusal presents funds after that clearing. Presenter exceptions
// propagate; the caller owns the whole transaction checkpoint/rollback.
bool pay_construction(GameState& g, int manager, uint32_t price, bool sponsor, WatcomRandom& rand,
const ConstructionNoticeHook& notice = {});
// "Ja" on the offer: pay_construction(price, sponsor) and the construction time of the
// object (CareerSession_DispatchStadium_RuntimeField2[object * 5]) is entered at record +0x1e + object.
bool build_periphery(GameState& g, int manager, int object, uint32_t price, WatcomRandom& rand,
const ConstructionNoticeHook& notice = {});
enum class StandBlockOfferDecision : uint8_t { Pending, Declined, Accepted };
struct StandBlockOffer {
int percent = 0;
uint32_t base_price = 0;
uint32_t offered_price = 0; // quoted +percent price; the amount shown before Yes/No
uint32_t price = 0; // amount to pay: base price until Accepted
int base_days = 0;
int construction_days = 0; // original duration until Accepted
StandBlockOfferDecision decision = StandBlockOfferDecision::Pending;
};
// PrepareStandBlockOffer, before its Yes/No prompt: consumes exactly W(6,14) and returns the
// percentage and quoted price. The quote is a value; displaying it consumes no more RNG.
// The path has not been compared with a matching original recording.
StandBlockOffer prepare_stand_block_offer(uint32_t base_price, int construction_days, WatcomRandom& rand);
// Resolve the PrepareStandBlockOffer answer once. No leaves the base price/time and draws nothing;
// Yes applies the quoted price and consumes exactly W(days>>3, days>>1) to shorten time.
// Repeated resolution is ignored, so a duplicated input cannot consume another draw.
bool resolve_stand_block_offer(StandBlockOffer& offer, bool accept, WatcomRandom& rand);
// ConstructionPricePercent choices 0..7: TEXTD734..741. Choices 8..15 are separate stand
// expansion editors and must never use the Facility/Maintain record arithmetic.
enum class StadiumInvestment : uint8_t {
Floodlights = 0, Scoreboard, PitchHeating, VipLounge, Pitch, Comfort, Condition, Safety
};
struct StadiumInvestmentConstants {
std::array<uint32_t, 8> price{}; // EXE CareerSession_DispatchStadium_RuntimeField[choice], not CareerSession_DispatchStadium_RuntimeField[choice+8]
std::array<uint8_t, 8> weeks{}; // EXE CareerSession_DispatchStadium_RuntimeField2[(choice+14)*5]
};
struct StadiumInvestmentOption {
uint8_t current_status = 0, current_level = 0, increment = 0, target_level = 0;
uint32_t base_price = 0;
uint8_t base_weeks = 0;
bool operator==(const StadiumInvestmentOption&) const = default;
};
// Pure projection. Busy or terminal investments have no options. Invalid owner,
// constants or a nonzero idle high nibble raise FormatError. Heating/VIP offer
// one tier unless (raw status &7)==2, including raw0. Ordinary tiers start at
// the full raw status byte and stop before5; bit3 yields no ordinary options.
// target_level is the accepted level after weekly completion's &7 narrowing.
std::vector<StadiumInvestmentOption> stadium_investment_options_source(
const GameState&, int manager, StadiumInvestment, int construction_percent,
const StadiumInvestmentConstants&);
// Revalidate the owned option against the current record and trusted Original
// constants before payment. Both resolved tip answers build: Declined means no
// tip, not cancel. Source sponsor draws/consumption can precede payment refusal;
// only successful payment writes +2c/+3c. No actual block capacity/flags
// (+34/+44/+54), GameRandom or weekly compensation is touched.
bool build_stadium_investment_source(GameState&, int manager, StadiumInvestment,
int construction_percent, const StadiumInvestmentConstants&,
const StadiumInvestmentOption&, const StandBlockOffer& resolved_tip, WatcomRandom&,
const ConstructionNoticeHook& notice = {});
// LeagueTableRangeDialog: persist the active 11-match pools coupon. The stake sits at
// Coupon + manager*0x14 and picks at +8..+0x12. Money is only charged by
// settle_pools_coupon at matchday end; this confirmation itself draws no RNG.
// BuildPoolsCoupon makes the screen unavailable unless all eleven fixtures exist.
// BalanceFromGame bounds stake to 10,000..400,000 (zero clears it).
bool submit_pools_coupon(GameState& g, int manager, uint32_t stake,
const std::array<uint8_t, 11>& tips);
} // namespace bmh
namespace bmh {
// Source-backed advertising contracts (DeskActionsOperation/CheckAdvertisingRenewal). Offers are
// generated elsewhere and live in the manager's saved +0x8cc pool. Projection
// is read-only: it never generates offers or consumes RNG.
enum class AdvertisingOfferStatus : uint8_t {
available, accepted, invalid_manager, invalid_display_slot, invalid_state, no_offers,
unavailable_target, unsupported_extension, insufficient_boards, stale_offer,
malformed_offer, invalid_request
};
struct AdvertisingOfferCandidate {
int raw_slot = -1; // saved pool index, 0..9 (TV: 0..4)
std::array<uint8_t, 12> bytes{}; // complete source offer record
uint32_t monthly_amount = 0; // DWORD +0
uint8_t bundle_units = 0; // byte +4 (DWORD word 1, low byte)
uint8_t months = 0; // byte +5
uint8_t sponsor_id = 0xff; // byte +7
bool present = false;
bool can_accept = false;
};
struct AdvertisingOfferList {
AdvertisingOfferStatus status = AdvertisingOfferStatus::invalid_request;
int manager = -1;
int display_slot = -1; // 0..13 boards, 14 shirt, 15 television
int contract_slot = -1; // physical manager-record row backing display_slot
std::array<uint8_t, 12> contract_bytes{}; // exact selected row for request binding
int pool_group = -1; // 0 boards, 1 shirt, 2 television
int free_boards = 0;
std::vector<AdvertisingOfferCandidate> offers;
};
struct AdvertisingOfferRequest {
int manager = -1;
int display_slot = -1; // screen row after source sort (0..15)
int contract_slot = -1; // physical row identity from the UI projection
std::array<uint8_t, 12> expected_contract{};
int raw_slot = -1;
std::array<uint8_t, 12> expected_offer{}; // binds UI choice to the projected offer
bool operator==(const AdvertisingOfferRequest&) const = default;
};
struct AdvertisingOfferResult {
AdvertisingOfferStatus status = AdvertisingOfferStatus::invalid_request;
int manager = -1;
int display_slot = -1;
int contract_slot = -1;
int raw_slot = -1;
};
// A group of identical offers may require several boards. Empty boards and rows
// marked replaceable by source flag +6 bit 7 count toward capacity.
AdvertisingOfferList advertising_offers(const GameState& g, int manager, int display_slot);
// Accept an existing offer atomically. Board rows are source-sorted before the
// bundle is installed; the group byte at +4 receives AdGroupId and that counter
// advances once. Shirt/TV offers replace their corresponding slot. This commit
// books no immediate cash and draws no RNG. Option-extension offers are excluded.
AdvertisingOfferResult accept_advertising_offer(GameState& g,
const AdvertisingOfferRequest& request);
// CheckAdvertisingRenewal: a click on a contract whose months ran out (sponsor set, months 0 - the
// month change posted "kann verlängert werden", Month_MonthChange_TextPointer). The sponsor's demand (word
// +8, the club attraction it wants) is scaled by W(95, 105) % (WatcomRandom); if it stays
// below the club's attraction (ClubAttraction) the manager is asked "Möchten Sie den Vertrag
// mit <sponsor> verlängern ?" (DeskActions_CheckAdvertisingRenewal_TextPointer/DeskActions_CheckAdvertisingRenewal_TextPointer2), otherwise the sponsor declines ("Die Firma
// <sponsor> wird den Vertrag nicht verlängern.", DeskActions_CheckAdvertisingRenewal_TextPointer3..DeskActions_CheckAdvertisingRenewal_TextPointer5, a mailbox message) and the
// place becomes free. Step one draws the random number and settles the refusal; step two
// applies the manager's answer: yes = the old duration again (byte +6 & 0x7f), no = free.
// Either way byte +6 is cleared and the other boards of the same bundle (group byte +4)
// get a copy of the result.
struct AdvertisingRenewal {
enum class Status : uint8_t { invalid, not_expired, declined_by_sponsor, offered } status = Status::invalid;
int contract_slot = -1; // 0-13 boards, 14 shirt, 15 TV
std::string question; // the original question text (offered)
std::string notice; // the sponsor's refusal (declined_by_sponsor)
};
AdvertisingRenewal check_advertising_renewal(GameState& g, int manager, int display_slot, WatcomRandom& rand);
bool answer_advertising_renewal(GameState& g, int manager, int contract_slot, bool renew);
// CheckAdvertisingRenewal advertising spend fields (manager record +0x850/+0x854/+0x858,
// delivery countdown +0x287). Projection is read-only; only goods purchasing draws.
struct AdvertisingSpendingView {
int manager = -1;
int target_slot = -1; // 16 merchandise, 17 press budget, 18 fan-work budget
uint32_t current_amount = 0;
uint32_t maximum_amount = 0;
uint8_t delivery_weeks = 0;
bool available = false;
};
enum class AdvertisingSpendingStatus : uint8_t {
accepted, no_change, insufficient_funds, delivery_pending,
invalid_manager, invalid_target, invalid_amount, stale_request, invalid_state
};
struct AdvertisingSpendingRequest {
int manager = -1;
int target_slot = -1;
uint32_t amount = 0;
uint32_t expected_amount = 0;
uint8_t expected_delivery_weeks = 0;
bool operator==(const AdvertisingSpendingRequest&) const = default;
};
struct AdvertisingSpendingResult {
AdvertisingSpendingStatus status = AdvertisingSpendingStatus::invalid_state;
bool changed = false;
uint32_t message_address = 0;
};
AdvertisingSpendingView advertising_spending(const GameState& g, int manager, int target_slot);
AdvertisingSpendingResult set_advertising_spending(GameState& g,
const AdvertisingSpendingRequest& request,
WatcomRandom& rand);
} // namespace bmh
namespace bmh {
// The funds of the same screen (block FundBlock in GameState::memory, six entries of 0x1c
// bytes): +0x00 price of a unit ((1 << k) * 100 000), +0x04 + manager * 4 the amount the
// manager paid (u32), +0x14 + manager * 2 units held (u16, at most 10 per fund).
constexpr int kFunds = 6;
// Units of fund `fund` the manager can buy: (money + credit line) / (price * 1.05), at most
// 10 minus the units held.
int max_fund_units(const GameState& g, int manager, int fund);
// Buying `count` units: price * count plus 5 % fee is booked (not forced) - record +0x324
// falls by it, record +0x30c rises by the fee and by price * count / 9. Every fund but
// the first costs a surcharge as well: count * G(price / 40, price / 10), paid (forced) and
// added to +0x30c, with the message CareerSession_Int32T_TextPointer2. Returns the surcharge.
int32_t buy_fund_units(GameState& g, int manager, int fund, int count, GameRandom& game);
// Selling `count` units at the price: the paid amount shrinks by its average per unit, the
// money (forced) and +0x324 rise, +0x30c falls by price * count / 9.
void sell_fund_units(GameState& g, int manager, int fund, int count);
// The fixed-term deposit (record +0x318): a positive amount moves money from the account
// to the deposit, a negative one back (both booked forced; +0x324 changes by the same).
// The deposit earns interest in daily_interest.
void move_to_deposit(GameState& g, int manager, int32_t amount);
// OpenBMH deviates from the original: supports designated set-piece records and the supported transfer-editor rules.
// NormalizePitchSetPieceSource (supported rule profile patch), when the line-up screen opens (PitchScreen, desk menu 3 and
// before matches): a manager record without the set-piece marker 0x3253 at +0xb0a gets it,
// with the takers cleared (+0xafc..+0xaff = 0, +0xb08 = designated-taker signature).
void open_lineup_screen(GameState& g, int manager);
} // namespace bmh
+279
View File
@@ -0,0 +1,279 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "game/driver.hpp"
#include <algorithm>
#include <array>
#include <vector>
#include "game/matchday.hpp"
#include "game/matchday_setup.hpp"
#include "game/season.hpp"
namespace bmh {
int cup_tie(const MatchGroup& grp, int m) {
const uint16_t r = grp.cup_results.at(size_t(m));
int home = r >> 5 & 0x1F, away = r & 0x1F;
int other_home = 0, other_away = 0;
if (!grp.cup_other_leg.empty()) {
other_home = grp.cup_other_leg.at(size_t(m)) >> 5 & 0x1F;
other_away = grp.cup_other_leg.at(size_t(m)) & 0x1F;
}
// this match's home team was the away team of the other leg
if ((grp.flags() & 0x10) && other_home + away == home + other_away && (r >> 11) == 0) {
away *= 2; // away goals of this match ...
other_away *= 2; // ... and of the other leg count double
}
const int home_total = home + other_away, away_total = other_home + away;
return (unsigned(home_total) < unsigned(away_total) ? 1 : 0) + (home_total == away_total ? 2 : 0);
}
bool cup_screen_shown(const std::vector<uint8_t>& buttons, int cup_id, int minute) {
if (buttons.empty()) return true;
const int kind = (minute > 45) + 1;
const int row = cup_id + 5;
if (row == 0x12) return buttons.at(size_t(0x12 + kind)) == 0 || buttons.at(size_t(0x1b + kind)) == 0;
return buttons.at(size_t(kind + row * 9)) == 0;
}
void play_phase(MatchEngine& engine, std::vector<MatchGroup>& groups, int first, int last, int stoppage, int phase,
MinuteReport& report, const std::function<void(int)>& after_minute) {
for (MatchGroup& grp : groups) grp.ended = 0, grp.phase = phase;
for (int minute = first; minute <= last + stoppage && !report.unsupported; minute++) {
bool running = false;
for (const MatchGroup& grp : groups)
for (int m = 0; m < grp.matches(); m++)
if (!((grp.void_mask() | grp.ended) >> m & 1)) running = true;
if (!running) break; // the original leaves the phase after a minute without matches
report = engine.minute(minute, last, stoppage);
if (after_minute) after_minute(minute);
}
}
namespace {
void set_void(MatchGroup& grp, int m) {
const uint32_t v = grp.void_mask() | 1u << m;
for (int i = 0; i < 4; i++) grp.desc.at(0xb8 + size_t(i)) = uint8_t(v >> (8 * i));
}
} // namespace
namespace {
bool group_played(const MatchGroup& grp) {
for (int m = 0; m < grp.matches(); m++)
if (grp.ended >> m & 1) return true;
return false;
}
bool result_visible(GameState& g, const MatchGroup& grp, int last,
const std::vector<uint8_t>& buttons, PhaseResultKind& kind,
int& competition_id) {
const uint32_t id = le32(grp.desc, 0xcc);
if (id < 0x15) {
kind = PhaseResultKind::League;
competition_id = int(id);
return league_screen_shown(buttons, 2, last, int(id));
}
kind = PhaseResultKind::Cup;
competition_id = int16_t(g.memory.u16(id + 0x18));
return cup_screen_shown(buttons, competition_id, last);
}
PhaseResultRequest make_result_request(const MatchGroup& grp, uint64_t phase_id,
uint32_t group_index, uint64_t revision,
PhaseResultKind kind, int competition_id, int last) {
PhaseResultRequest req;
req.phase_id = phase_id;
req.group_index = group_index;
req.revision = revision;
req.kind = kind;
req.competition_id = competition_id;
req.phase_end_minute = last;
req.matches.reserve(size_t(grp.matches()));
for (int m = 0; m < grp.matches(); ++m) {
PhaseResultMatch score;
score.home_team = grp.fixtures.at(size_t(m * 2));
score.away_team = grp.fixtures.at(size_t(m * 2 + 1));
score.score_known = match_score(grp, m, score.home_score, score.away_score);
req.matches.push_back(score);
}
return req;
}
void finish_group_phase(GameState& g, MatchGroup& grp, int last, GameRandom& game) {
const bool full_time = last == 90 || last == 120 || last == 40;
if (!full_time) return;
const bool final_phase = last == 40 || last == 120;
for (int m = 0; m < grp.matches(); m++) {
if ((grp.flags() & 8) && cup_tie(grp, m) == 2) {
uint16_t& r = grp.cup_results.at(size_t(m));
if (r != 0xCCCC) r = uint16_t((final_phase ? 2 : 1) * 0x400 + (r & 0x3FF));
if (final_phase) finish_match(g, grp, m, last, game);
continue;
}
if (grp.void_mask() >> m & 1) continue;
finish_match(g, grp, m, last, game);
set_void(grp, m);
}
}
PhaseEndOutput rejected(const char* why) {
PhaseEndOutput out;
out.status = PhaseEndStatus::Rejected;
out.reason = why;
return out;
}
PhaseEndOutput advance_phase_end(PhaseEndCursor& c) {
while (c.next_group < c.groups->size()) {
MatchGroup& grp = c.groups->at(c.next_group);
if (c.phase_played) {
PhaseResultKind kind;
int competition_id = 0;
if (result_visible(*c.state, grp, c.last, c.buttons, kind, competition_id)) {
c.pending = make_result_request(grp, c.phase_id, c.next_group, c.revision,
kind, competition_id, c.last);
// CupGroupOverviewEffects initializes the cup viewer before presenting it.
// Keep this once at entry, so closing cannot erase viewer edits.
if (kind == PhaseResultKind::Cup) cup_overview_effects(*c.state);
PhaseEndOutput out;
out.status = PhaseEndStatus::Waiting;
out.request = c.pending;
return out;
}
}
finish_group_phase(*c.state, grp, c.last, *c.game);
++c.next_group;
}
c.complete = true;
c.pending.reset();
PhaseEndOutput out;
out.status = PhaseEndStatus::Complete;
return out;
}
} // namespace
PhaseEndOutput begin_phase_end(PhaseEndCursor& c, uint64_t phase_id, GameState& g,
std::vector<MatchGroup>& groups, int last,
const std::vector<uint8_t>& buttons, GameRandom& game,
WatcomRandom& rand, MinuteReport& report) {
if (c.initialized) {
const bool same = c.phase_id == phase_id && c.state == &g && c.groups == &groups && c.last == last &&
c.buttons_source == &buttons && c.game == &game && c.rand == &rand && c.report == &report;
if (!c.complete) {
if (!same) return rejected("phase already active with different identity or borrowed objects");
if (c.pending) {
PhaseEndOutput out;
out.status = PhaseEndStatus::Waiting;
out.request = c.pending;
return out;
}
return rejected("active phase has no pending result");
}
if (same) {
PhaseEndOutput out;
out.status = PhaseEndStatus::Complete;
return out;
}
}
c.initialized = true;
c.complete = false;
// Original local_48 belongs to EndPhase, not to a group. Preserve this
// gate throughout the barrier even as each acknowledged group settles.
c.phase_played = std::any_of(groups.begin(), groups.end(), group_played);
c.phase_id = phase_id;
c.revision = 1;
c.next_group = 0;
c.last = last;
c.buttons = buttons;
c.buttons_source = &buttons;
c.state = &g;
c.groups = &groups;
c.game = &game;
c.rand = &rand;
c.report = &report;
c.pending.reset();
c.last_ack.reset();
c.after_last_ack.reset();
return advance_phase_end(c);
}
PhaseEndOutput continue_phase_end(PhaseEndCursor& c, const std::optional<PhaseResultReply>& reply) {
if (!c.initialized) return rejected("phase not started");
if (!reply) {
if (c.complete) return rejected("phase already complete");
if (!c.pending) return rejected("no result is pending");
PhaseEndOutput out;
out.status = PhaseEndStatus::Waiting;
out.request = c.pending;
return out;
}
if (c.last_ack && reply->phase_id == c.last_ack->phase_id &&
reply->group_index == c.last_ack->group_index && reply->revision == c.last_ack->revision) {
return *c.after_last_ack;
}
if (c.complete) return rejected("phase already complete");
if (!c.pending || reply->phase_id != c.pending->phase_id ||
reply->group_index != c.pending->group_index || reply->revision != c.pending->revision)
return rejected("stale or mismatched result acknowledgement");
MatchGroup& grp = c.groups->at(c.pending->group_index);
if (c.pending->kind == PhaseResultKind::League) {
stir_random(*c.game, *c.rand);
}
finish_group_phase(*c.state, grp, c.last, *c.game);
c.next_group = c.pending->group_index + 1;
c.last_ack = *reply;
++c.revision;
c.pending.reset();
PhaseEndOutput out = advance_phase_end(c);
c.after_last_ack = out;
return out;
}
void end_phase(GameState& g, std::vector<MatchGroup>& groups, int last, const std::vector<uint8_t>& buttons,
GameRandom& game, WatcomRandom& rand, MinuteReport& report,
const std::function<void(const PhaseResultRequest&, const std::vector<MatchGroup>&,
const GameState&)>& presenter) {
PhaseEndCursor cursor;
PhaseEndOutput out = begin_phase_end(cursor, 1, g, groups, last, buttons, game, rand, report);
while (out.status == PhaseEndStatus::Waiting && out.request) {
const PhaseResultRequest& req = *out.request;
if (presenter) presenter(req, groups, g);
out = continue_phase_end(cursor, PhaseResultReply{req.phase_id, req.group_index, req.revision});
}
}
void play_matchday(MatchEngine& engine, GameState& g, std::vector<MatchGroup>& groups,
const std::vector<uint8_t>& buttons, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
const std::function<void(int)>& after_minute, int stop_at) {
// EndPhase calls of the matchday: outdoors two halves (4 minutes of stoppage in the
// second) and extra time; the indoor tournament (CareerSessionRuntimeField) plays 2 x 20 minutes
const int outdoor[4][4] = {{1, 45, 0, 0}, {46, 90, 4, 0}, {91, 105, 0, 1}, {106, 120, 1, 1}};
const int indoor[2][4] = {{1, 20, 0, 0}, {21, 40, 0, 0}};
engine.indoor = g.indoor;
std::vector<std::array<int, 4>> phases;
if (g.indoor)
for (const auto& p : indoor) phases.push_back({p[0], p[1], p[2], p[3]});
else
for (const auto& p : outdoor) phases.push_back({p[0], p[1], p[2], p[3]});
for (const auto& p : phases) {
play_phase(engine, groups, p[0], p[1], p[2], p[3], report, after_minute);
if (report.unsupported) return;
if (p[1] == stop_at) return;
end_phase(g, groups, p[1], buttons, game, rand, report, engine.phase_results);
if (report.unsupported) return;
// FinishEvent / BuildSideRecords: EvaluatePoolsCoupon(0) after the second half (outdoors)
if (!g.indoor && p[1] == 90) evaluate_pools_coupon(g, groups);
}
// CupTie2: penalty shoot-outs
for (MatchGroup& grp : groups)
for (int m = 0; m < grp.matches() && !report.unsupported; m++)
if ((grp.flags() & 8) && !grp.cup_results.empty() && (grp.cup_results[size_t(m)] >> 11) != 0)
engine.penalty_shootout(grp, m, report);
}
} // namespace bmh
+131
View File
@@ -0,0 +1,131 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// The matchday driver after the kick-off (FinishEvent + BuildSideRecords, BMH.exe V2.24).
//
// The driver plays the phases one after another with EndPhase(first, last,
// stoppage, phase):
// 1..45 (no stoppage), 46..90 (+ up to 4), then 91..105 and 106..120 (+ up to 1,
// phase 1 = extra time; indoor tournaments play 1..20 and 21..40 instead).
// A phase ends when every match has ended; a phase in which no match is running draws
// nothing. At the end of a phase (end_phase):
// - if any match played in the phase, the result screen of every group is called
// unless switched off at the desk, including groups already settled in regular
// time; leaving a league screen stirs the random numbers (stir_random),
// - at full time (90, 120, and 40 indoors) every match gets FinishMatch and is marked
// done, except cup ties decided on the day (descriptor flag 8) that are still level
// on aggregate (cup_tie): they go into extra time, after 120 minutes into the
// penalty shoot-out (CupTie2).
#include <cstdint>
#include <functional>
#include <optional>
#include <string>
#include <vector>
#include "game/match_engine.hpp"
#include "game/random.hpp"
#include "game/state.hpp"
namespace bmh {
// CupTie: state of a cup tie after match m of a group: 0 the home side is through,
// 1 the away side, 2 still level. Two-legged ties add the other leg (its home team is
// this match's away team); with descriptor flag 0x10 away goals count double while the
// match is in regular time.
int cup_tie(const MatchGroup& grp, int m);
// Whether the result screen of a cup (CupGroupOverviewEffects with a phase end minute) is shown.
bool cup_screen_shown(const std::vector<uint8_t>& buttons, int cup_id, int minute);
// One phase: minutes first..last+stoppage until every match has ended. `after_minute`
// is called after each simulated minute (for checks). Stops early if the engine reports
// an unsupported path.
void play_phase(MatchEngine& engine, std::vector<MatchGroup>& groups, int first, int last, int stoppage, int phase,
MinuteReport& report, const std::function<void(int minute)>& after_minute = {});
// The end of EndPhase for a phase that ended at minute `last`.
void end_phase(GameState& g, std::vector<MatchGroup>& groups, int last, const std::vector<uint8_t>& buttons,
GameRandom& game, WatcomRandom& rand, MinuteReport& report,
const std::function<void(const PhaseResultRequest&, const std::vector<MatchGroup>&,
const GameState&)>& presenter = {});
// Nonblocking end-of-phase result barrier. The cursor borrows the original mutable
// objects for its whole lifetime; do not copy/move it or independently mutate those
// objects while pending. Native viewer actions use the owning synchronous App dispatcher;
// it must preserve group identity and never resume simulation. Cup entry effects precede
// presentation; league exit RNG and match settlement belong to the single ACK.
// Only presentation metadata and a bounded last-ACK record are owned.
enum class PhaseResultKind { League, Cup };
struct PhaseResultMatch {
int home_team = 0;
int away_team = 0;
bool score_known = false;
int home_score = 0;
int away_score = 0;
};
struct PhaseResultRequest {
uint64_t phase_id = 0;
uint32_t group_index = 0;
uint64_t revision = 0;
PhaseResultKind kind = PhaseResultKind::League;
int competition_id = 0;
int phase_end_minute = 0;
std::vector<PhaseResultMatch> matches;
};
struct PhaseResultReply {
uint64_t phase_id = 0;
uint32_t group_index = 0;
uint64_t revision = 0;
};
enum class PhaseEndStatus { Waiting, Complete, Rejected };
struct PhaseEndOutput {
PhaseEndStatus status = PhaseEndStatus::Complete;
std::optional<PhaseResultRequest> request;
const char* reason = nullptr;
};
struct PhaseEndCursor {
PhaseEndCursor() = default;
PhaseEndCursor(const PhaseEndCursor&) = delete;
PhaseEndCursor& operator=(const PhaseEndCursor&) = delete;
PhaseEndCursor(PhaseEndCursor&&) = delete;
PhaseEndCursor& operator=(PhaseEndCursor&&) = delete;
bool initialized = false;
bool complete = false;
bool phase_played = false; // EndPhase local_48, frozen for all groups
uint64_t phase_id = 0;
uint64_t revision = 0;
uint32_t next_group = 0;
int last = 0;
std::vector<uint8_t> buttons; // copied presentation settings
const std::vector<uint8_t>* buttons_source = nullptr; // identity for repeated begin
GameState* state = nullptr; // borrowed, original object
std::vector<MatchGroup>* groups = nullptr; // borrowed, original objects
GameRandom* game = nullptr; // borrowed, original generator
WatcomRandom* rand = nullptr; // borrowed, original generator
MinuteReport* report = nullptr; // borrowed
std::optional<PhaseResultRequest> pending;
std::optional<PhaseResultReply> last_ack;
std::optional<PhaseEndOutput> after_last_ack;
};
// First call starts/resumes the phase; repeating begin with the same phase while waiting
// polls the identical request. A completed cursor may be reused for a later phase.
PhaseEndOutput begin_phase_end(PhaseEndCursor& cursor, uint64_t phase_id, GameState& g,
std::vector<MatchGroup>& groups, int last,
const std::vector<uint8_t>& buttons, GameRandom& game,
WatcomRandom& rand, MinuteReport& report);
// An empty reply polls without effects. Only an exact current (phase, group, revision)
// reply resumes the group. Duplicate last ACK returns its cached continuation; older or
// mismatched replies are rejected without state/RNG/cursor advancement.
PhaseEndOutput continue_phase_end(PhaseEndCursor& cursor,
const std::optional<PhaseResultReply>& reply = std::nullopt);
// All phases of a matchday (not indoor): regular time, extra time where needed.
// `stop_at` (45, 90, 105 or 120) stops at the whistle of that phase, before its result
// screens and match bookkeeping (end_phase); 0 plays everything.
void play_matchday(MatchEngine& engine, GameState& g, std::vector<MatchGroup>& groups,
const std::vector<uint8_t>& buttons, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
const std::function<void(int minute)>& after_minute = {}, int stop_at = 0);
} // namespace bmh
+103
View File
@@ -0,0 +1,103 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/environment.hpp"
#include <algorithm>
#include "game/messages.hpp"
#include "game/schedule.hpp"
#include "game/week.hpp"
namespace bmh {
namespace {
constexpr uint32_t kSpending = ::bmh::layout::Spending; // + manager * 0x24 + item * 4
constexpr size_t kRecordSize = 0xb0c;
constexpr size_t kYouthPaid = 0x880; // youth expenses booked this season
// EnvironmentRuntimeField: the step of each item in thousands (items 3..5: 5 000 per level)
constexpr int kUnit[kEnvironmentItems] = {2, 4, 5, 5, 5, 5};
uint32_t spending_at(int manager, int item) { return kSpending + uint32_t(manager) * 0x24 + uint32_t(item) * 4; }
// TeamLeague3: the academy's season price by the club's league
int32_t youth_price(const GameState& g, int manager) {
const int league = team_league(g.manager_teams.at(size_t(manager)));
return league == 0 ? 1500000 : league == 1 ? 1000000 : league <= 3 ? 580000 : 280000;
}
// YouthOpen: July (unless the Bundesliga is past its 17th round) or August
bool youth_open(const GameState& g) {
const int month = month_code(g.date);
if (month == 7) return !(g.league_rounds.at(0) > 0x11);
return month == 8;
}
bool youth_paid(const GameState& g, int manager) {
const size_t at = size_t(manager) * kRecordSize + kYouthPaid;
const uint32_t paid = uint32_t(g.manager_records.at(at)) | uint32_t(g.manager_records.at(at + 1)) << 8 |
uint32_t(g.manager_records.at(at + 2)) << 16 | uint32_t(g.manager_records.at(at + 3)) << 24;
return paid >= uint32_t(youth_price(g, manager));
}
} // namespace
EnvironmentState environment_state(const GameState& g, int manager) {
EnvironmentState s;
for (int i = 0; i < kEnvironmentItems; i++) {
s.monthly[size_t(i)] = int32_t(g.memory.u32(spending_at(manager, i)));
// the stars (SizeT7): staff value / step, the academy 6 when on, 0/2 none
if (i >= 3) s.level[size_t(i)] = std::clamp(s.monthly[size_t(i)] / (kUnit[i] * 1000), 0, 6);
else if (i == kYouthAcademy) s.level[size_t(i)] = s.monthly[size_t(i)] != 0 ? 6 : 0;
}
s.youth_price = youth_price(g, manager);
s.youth_paid = youth_paid(g, manager);
s.youth_open = youth_open(g);
return s;
}
EnvironmentResult set_environment(GameState& g, int manager, int item, int level, std::string* message) {
if (manager < 0 || size_t(manager) >= g.manager_teams.size() || item < 0 || item >= kEnvironmentItems || level < 0 ||
level > 6 || !g.memory.has(spending_at(manager, item) + 3))
return EnvironmentResult::invalid;
const uint32_t at = spending_at(manager, item);
const int32_t before = int32_t(g.memory.u32(at));
int32_t value = 0;
EnvironmentResult result = EnvironmentResult::changed;
if (item >= 3) {
value = level * kUnit[item] * 1000;
} else if (item == kYouthAcademy) {
// YouthPrice: a click on an active academy means "off"
int wanted = level;
if (before != 0 && wanted != 0) wanted = 0;
const int32_t price = youth_price(g, manager);
if (!youth_paid(g, manager)) {
if (wanted == 0) {
value = 0;
} else if (!youth_open(g)) {
value = 0;
result = EnvironmentResult::too_late;
if (message) *message = message_text(g, ::bmh::layout::Environment_SetEnvironment_ExecutableField); // "Zu spät für diese Saison..."
} else {
value = price;
}
} else {
// paid this season: stays on; a click meant as "off" brings the second string of
// the same text block (*Environment_SetEnvironment_ExecutableField + 0x42)
value = price;
if (wanted == 0) {
result = EnvironmentResult::contract_runs;
if (message) {
*message = message_text_following(g, ::bmh::layout::Environment_SetEnvironment_ExecutableField);
// OpenBMH-authored notice when an edition has no academy tail text.
if (message->empty()) *message = "This academy contract stays active until the season ends.";
}
}
}
}
g.memory.set32(at, uint32_t(value));
if (result == EnvironmentResult::changed && value == before) result = EnvironmentResult::unchanged;
return result;
}
} // namespace bmh
+47
View File
@@ -0,0 +1,47 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// OpenBMH deviates from the original: enables the supported youth academy and represents staff levels in monthly increments of five thousand.
// The club environment ("Umfeld", desk menu 24, H2 p. 93; supported rule profile manual p. 107, 111):
// the screen Image with the supported rule profile patch (SizeT7 / EnvironmentOperation /
// YouthPrice / YouthOpen). Six monthly running costs per manager live at
// Spending + manager * 0x24 (u32 each); the month change books them
// (month.cpp monthly_expenses) and the staff values steer training, injuries and healing.
//
// item 0, 2 the original's two other youth age groups: the patch always sets 0
// item 1 the youth academy (supported rule profile): on or off. On it is the league's season price
// (TeamLeague3: 1.5 M, 1 M, 580 000, 280 000), paid in full at the next month
// change while record +0x880 (youth expenses this season) is below it. It can
// be switched on in July and August only ("Zu spät für diese Saison...") and
// not switched off once paid ("Der Vertrag läuft bis zum Saisonende.").
// item 3..5 co-trainer, doctor, physio: level 0..6 times 5 000 a month (EnvironmentRuntimeField)
//
// A click on a tile sets the level from the mouse position (supported rule profile: one click per value).
#include <array>
#include <cstdint>
#include <string>
#include "game/state.hpp"
namespace bmh {
constexpr int kEnvironmentItems = 6;
enum EnvironmentItem : int { kYouthAcademy = 1, kCoTrainer = 3, kDoctor = 4, kPhysio = 5 };
struct EnvironmentState {
std::array<int32_t, kEnvironmentItems> monthly{}; // Spending values
std::array<int, kEnvironmentItems> level{}; // the stars the screen draws (0..6)
int32_t youth_price = 0; // the season price of the academy for the club's league
bool youth_paid = false; // record +0x880 reached the price: cannot be switched off
bool youth_open = false; // July/August: the academy can still be switched on
};
EnvironmentState environment_state(const GameState& g, int manager);
enum class EnvironmentResult : uint8_t { changed, unchanged, too_late, contract_runs, invalid };
// A click on `item` at `level` (0..6; for the academy any level > 0 means "on" and a click on
// an active academy switches it off). `message` gets the original's message box text, if any.
EnvironmentResult set_environment(GameState& g, int manager, int item, int level, std::string* message = nullptr);
} // namespace bmh
+211
View File
@@ -0,0 +1,211 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/highscore.hpp"
#include <algorithm>
#include <bit>
#include <fstream>
#include <stdexcept>
#include <utility>
#include "game/weekly.hpp"
namespace bmh {
namespace {
constexpr size_t kRecord = 0xb0c;
// OpenBMH deviates from the original: reads the supported edition-specific high-score format from the loaded image.
// supported rule profile executable HighscoreRuntimeField..a5144, verified against the installed LE image.
constexpr std::array<uint8_t, 8> kHistoryWeights{3, 5, 4, 30, 20, 10, 5, 40};
constexpr std::array<uint8_t, 4> kNationalWeights{30, 20, 10, 5};
constexpr std::array<uint8_t, 3> kTitleWeights{40, 30, 50};
int32_t signed32(uint32_t v) { return std::bit_cast<int32_t>(v); }
uint16_t rec16(const GameState& g, int m, size_t offset) {
const size_t at = size_t(m) * kRecord + offset;
return uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8);
}
uint32_t rec32(const GameState& g, int m, size_t offset) {
return uint32_t(rec16(g, m, offset)) | uint32_t(rec16(g, m, offset + 2)) << 16;
}
uint8_t rec8(const GameState& g, int m, size_t offset) {
return g.manager_records.at(size_t(m) * kRecord + offset);
}
std::string record_name(const GameState& g, int m) {
std::string name;
for (size_t i = 0; i < 30; ++i) {
const auto c = rec8(g, m, 0xa8 + i);
if (!c) return name;
name.push_back(char(c));
}
throw std::invalid_argument("highscore: unterminated manager name");
}
// HighscoreScore(0x1f,0,0xff), deliberately using the Source global asset-manager.
int32_t net_assets(const GameState& g, int m) {
uint32_t sum = rec32(g, m, 0x314) + rec32(g, m, 0x318);
for (uint32_t k = 0; k < 6; ++k)
sum += uint32_t(g.memory.u16(::bmh::layout::Advertising_OriginalShareAdjustment_RuntimeField + uint32_t(m) * 2 + k * 0x1c)) *
g.memory.u32(::bmh::layout::FundBlock + k * 0x1c);
for (size_t k = 0; k < 12; ++k) {
const size_t at = k * 0x5c;
const uint32_t held = uint16_t(g.stocks.at(at + 0x50 + size_t(m) * 2) |
g.stocks.at(at + 0x51 + size_t(m) * 2) << 8);
const uint32_t price = uint16_t(g.stocks.at(at + 0x4e) | g.stocks.at(at + 0x4f) << 8);
sum += held * price;
}
for (uint32_t k = 0; k < 5; ++k)
sum -= g.memory.u32(::bmh::layout::Analytics_SourceAssetMaskE_RuntimeField + uint32_t(m) * 0x78 + k * 0x18);
return signed32(sum);
}
uint32_t read32(const uint8_t* p) {
return uint32_t(p[0]) | uint32_t(p[1]) << 8 | uint32_t(p[2]) << 16 | uint32_t(p[3]) << 24;
}
void put32(uint8_t* p, uint32_t v) {
for (int k = 0; k < 4; ++k) p[k] = uint8_t(v >> (8 * k));
}
std::string read_name(const uint8_t* p) {
size_t n = 0;
while (n < 30 && p[n]) ++n;
if (n == 30) throw std::invalid_argument("highscore: unterminated file name");
return {reinterpret_cast<const char*>(p), n};
}
void put_name(uint8_t* p, const std::string& s) {
if (s.size() >= 30 || s.find('\0') != std::string::npos)
throw std::invalid_argument("highscore: name does not fit Source row");
// strcpy preserves bytes beyond the terminator of an existing row.
std::copy(s.begin(), s.end(), p);
p[s.size()] = 0;
}
} // namespace
HighscoreScore highscore_score(const GameState& g, int manager, HighscoreContext context) {
if (manager < 0 || size_t(manager) >= g.manager_teams.size())
throw std::invalid_argument("highscore: manager is outside active slots");
HighscoreScore result;
const int team = g.manager_teams.at(size_t(manager));
if (team == kNoTeam) {
// CareerSession_DispatchLineup_RuntimeField+CareerSession_InstallLeagueSizes_RuntimeField6+ClubPlayerDetail_ClubPlayerDetailFromGame_RuntimeField3 == kNoTeam in the supported Original database;
// national honours store (team-kNoTeam)|0x80, so Germany's index is0.
for (uint32_t year = 0; year < 20; ++year)
for (uint32_t place = 0; place < 4; ++place) {
const uint8_t v = g.memory.u8(::bmh::layout::Placements + year * 4 + place);
if ((v & 0x80) && (v & 0x7f) == 0)
result.history += int32_t(kNationalWeights[place]) * 10;
}
} else {
if (g.season < 0) throw std::invalid_argument("highscore: negative season index");
const int asset_manager = context == HighscoreContext::SeasonBoundary
? int(g.manager_teams.size()) : int(g.memory.u8(::bmh::layout::ActiveManager));
result.assets = std::min(net_assets(g, asset_manager) / 50000, 100);
result.patience = rec8(g, manager, 0x26f);
GameState facility_state = g; // facility_rating's public API takes mutable state.
int second = 0;
result.facilities = facility_rating(facility_state, manager, &second) * 4;
result.team = int(uint16_t(team_average(g, team, 0x2ff).value)) / 10;
const uint32_t count = std::min(uint32_t(g.season) + 1, 50u);
uint32_t history = 0;
for (uint32_t year = 0; year < count; ++year) {
const size_t at = 0xda + year * 3;
const uint8_t v = rec8(g, manager, at + 2);
history += uint32_t(rec8(g, manager, at)) + uint32_t(rec8(g, manager, at + 1)) * 2 +
uint32_t(kHistoryWeights[v >> 5]) * (v & 0x1f);
}
result.history = int32_t((history & 0xffff) / count);
}
uint32_t total = uint32_t(result.assets) + uint32_t(result.patience) +
uint32_t(result.facilities) + uint32_t(result.team) + uint32_t(result.history);
for (size_t k = 0; k < 3; ++k)
result.titles += int32_t(kTitleWeights[k]) * rec16(g, manager, 0x8a4 + k * 2);
total += uint32_t(result.titles);
result.total = std::max(signed32(total), 0);
return result;
}
HighscoreRow highscore_candidate(const GameState& g, int manager, HighscoreContext context) {
if (g.memory.u16(::bmh::layout::CareerSession_FormatError_RuntimeField7) == 0) return {};
HighscoreRow row;
row.score = highscore_score(g, manager, context).total;
row.club_name = g.club_name(g.manager_teams.at(size_t(manager)));
row.manager_name = record_name(g, manager);
for (size_t k = 0; k < 3; ++k) row.titles[k] = rec16(g, manager, 0x8a4 + k * 2);
return row;
}
void insert_highscore(HighscoreTable& rows, const HighscoreRow& candidate) {
size_t target = rows.size();
for (size_t k = 0; k < rows.size(); ++k)
if (rows[k].manager_name == candidate.manager_name && rows[k].club_name == candidate.club_name) {
target = k;
break;
}
if (target == rows.size() && rows.back().score < candidate.score) target = rows.size() - 1;
if (target == rows.size()) return;
rows[target] = candidate;
// Swap uses these pairwise swaps; preserve equal-score ordering exactly.
for (size_t a = 0; a < 4; ++a)
for (size_t b = a + 1; b < 5; ++b)
if (rows[a].score < rows[b].score) std::swap(rows[a], rows[b]);
}
HighscoreProjection make_highscore_projection(const GameState& g, HighscoreTable rows, HighscoreContext context) {
HighscoreProjection out;
out.signature = g.memory.u16(::bmh::layout::CareerSession_FormatError_RuntimeField7);
out.ranked = out.signature != 0;
out.rows = std::move(rows);
if (!out.ranked) return out;
// GameEndAlternateScoreScreen gates the entire manager loop using slot0, not each candidate's team.
if (!g.manager_teams.empty() &&
(g.manager_teams[0] != kNoTeam || (g.memory.u8(::bmh::layout::CompetitionSelection) & 1) == 0))
for (size_t m = 0; m < g.manager_teams.size(); ++m)
insert_highscore(out.rows, highscore_candidate(g, int(m), context));
return out;
}
HighscoreBytes encode_highscore_table(const HighscoreTable& rows) {
HighscoreBytes bytes{};
for (size_t k = 0; k < rows.size(); ++k) {
uint8_t* p = bytes.data() + k * 72;
std::copy(rows[k].original_bytes.begin(), rows[k].original_bytes.end(), p);
put32(p, uint32_t(rows[k].score));
put_name(p + 4, rows[k].club_name);
put_name(p + 0x22, rows[k].manager_name);
for (size_t t = 0; t < 3; ++t) {
p[0x40 + t * 2] = uint8_t(rows[k].titles[t]);
p[0x41 + t * 2] = uint8_t(rows[k].titles[t] >> 8);
}
}
return bytes;
}
HighscoreTable decode_highscore_table(const HighscoreBytes& bytes) {
HighscoreTable rows{};
for (size_t k = 0; k < rows.size(); ++k) {
const uint8_t* p = bytes.data() + k * 72;
std::copy(p, p + 72, rows[k].original_bytes.begin());
rows[k].score = signed32(read32(p));
rows[k].club_name = read_name(p + 4);
rows[k].manager_name = read_name(p + 0x22);
for (size_t t = 0; t < 3; ++t) rows[k].titles[t] = uint16_t(p[0x40 + t * 2] | p[0x41 + t * 2] << 8);
}
return rows;
}
std::filesystem::path highscore_file(const std::filesystem::path& base, uint16_t signature, const std::string& prefix) {
if (!signature) throw std::invalid_argument("highscore: signature0 has no ranked file");
return base / (prefix + std::to_string(signature));
}
HighscoreTable load_highscore_table(const std::filesystem::path& file) {
std::ifstream in(file, std::ios::binary);
if (!in) {
HighscoreTable empty{};
save_highscore_table(file, empty); // Read creates a zero table on a missing file.
return empty;
}
HighscoreBytes bytes{};
in.read(reinterpret_cast<char*>(bytes.data()), bytes.size());
return decode_highscore_table(bytes);
}
bool save_highscore_table(const std::filesystem::path& file, const HighscoreTable& rows) {
const auto bytes = encode_highscore_table(rows);
std::ofstream out(file, std::ios::binary | std::ios::trunc);
if (!out) return false;
out.write(reinterpret_cast<const char*>(bytes.data()), bytes.size());
return bool(out);
}
} // namespace bmh
+61
View File
@@ -0,0 +1,61 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <array>
#include <cstdint>
#include <filesystem>
#include <string>
#include "game/state.hpp"
namespace bmh {
// HighscoreOperation / GameEndAlternateScoreScreen. Names retain Original ISO646-DE bytes.
struct HighscoreRow {
int32_t score = 0;
std::string club_name;
std::string manager_name;
std::array<uint16_t, 3> titles{};
// Preserve unused/trailing bytes of an existing Source row when saving it again.
std::array<uint8_t, 72> original_bytes{};
};
using HighscoreTable = std::array<HighscoreRow, 5>;
using HighscoreBytes = std::array<uint8_t, 360>;
struct HighscoreProjection {
uint16_t signature = 0; // CareerSession_FormatError_RuntimeField7: any nonzero signature selects its own ranked file.
bool ranked = false; // signature0 selects Source's alternate visualization.
HighscoreTable rows{};
};
struct HighscoreScore {
int32_t assets = 0;
int32_t patience = 0;
int32_t facilities = 0;
int32_t team = 0;
int32_t history = 0;
int32_t titles = 0;
int32_t total = 0;
};
enum class HighscoreContext { ActiveManager, SeasonBoundary };
// Assets in HighscoreScore use global ActiveManager even when scoring another manager. At the
// season boundary DailyInterest's preceding manager loop leaves ActiveManager=manager_count.
// Pass that context explicitly without modifying the caller's continuation state.
HighscoreScore highscore_score(const GameState& g, int manager,
HighscoreContext context = HighscoreContext::ActiveManager);
HighscoreRow highscore_candidate(const GameState& g, int manager,
HighscoreContext context = HighscoreContext::ActiveManager);
void insert_highscore(HighscoreTable& rows, const HighscoreRow& candidate);
HighscoreProjection make_highscore_projection(const GameState& g, HighscoreTable rows = {},
HighscoreContext context = HighscoreContext::ActiveManager);
HighscoreBytes encode_highscore_table(const HighscoreTable& rows);
HighscoreTable decode_highscore_table(const HighscoreBytes& bytes);
// The caller supplies the configured installation base and Original TEXTD889 prefix.
std::filesystem::path highscore_file(const std::filesystem::path& base,
uint16_t signature, const std::string& prefix = "high/h.");
HighscoreTable load_highscore_table(const std::filesystem::path& file);
bool save_highscore_table(const std::filesystem::path& file, const HighscoreTable& rows);
} // namespace bmh
+125
View File
@@ -0,0 +1,125 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <cstddef>
#include <cstdint>
#include <functional>
#include <optional>
#include <string>
#include "game/random.hpp"
#include "game/state.hpp"
namespace bmh {
struct MinuteReport;
// The unsaved PendingOfferAnswer observation is owned by CareerSession. Missing evidence
// is unsupported; zero is never an implicit default.
enum class HumanBuyerSaleAllocatorGate : uint8_t { unsupported, zero, blocked };
// OpenTransferEditor owns this unsaved transient: its ordinary AI-seller entry starts at
// zero, while targeted human-seller processing may mark a list entry. The
// session must supply this only after observing the actual ordinary UI entry.
enum class HumanBuyerSaleDirectMode : uint8_t { unsupported, ordinary_ai_purchase };
enum class HumanBuyerSaleStatus : uint8_t {
moved, funds_refused, allocator_blocked, no_room, unsupported
};
// DispatchClubPlayerPendingOffers supplies param8 independently of FindManagerForClub's active-count
// lookup. Only the checked national pending caller may bind a retained raw
// owner or use parked record4 for a human buyer/movement board.
struct SourcePendingOwner {
int manager = -1;
int team = -1;
};
struct HumanBuyerSaleRequest {
int list_entry = -1;
int bid_slot = -1;
uint32_t list_address = 0;
size_t source_pool_slot = 0;
int expected_seller = -1;
int expected_buyer = -1;
int expected_active_manager = -1;
// -1 identifies a normal list row. Pending callers provide the explicit raw
// OfferSlots slot; the shared helper never manufactures raw+40 from this value.
int raw_offer_slot = -1;
// Poaching (src/game/poach.hpp): a direct sale on the special row 40..43 that
// Range2 prepared; no raw OfferSlots slot belongs to it.
bool poach = false;
// DayStepRest2/Range2 return-to-borrower re-offer on a special entry. This is
// a separate non-poaching Source owner and requires its exact OfferSlots marker.
bool loan_return_entry = false;
// The day step's list decision (TransferListCountdown -> Void2) passes buyer and seller
// managers to SettleHumanBuyerSale explicitly; whoever is on turn (ActiveManager) is not bound to
// them. Set for that caller: the active-manager checks below do not apply.
bool day_step = false;
// Only raw pending entries with reduced national runtime and a matching
// saved order/owner/record/pool qualify. Accounts use param8; movement still
// uses FindManagerForClub. Never changes ordinary/day-step/poach defaults.
std::optional<SourcePendingOwner> source_pending_owner = std::nullopt;
};
struct HumanBuyerSaleNotice {
int manager = -1;
int list_entry = -1;
int raw_offer_slot = -1;
uint32_t source_text_address = 0;
std::string original_message;
uint16_t source_flags = 0;
};
struct HumanBuyerSalePaid {
int list_entry = -1;
int bid_slot = -1;
int raw_offer_slot = -1;
int player = -1;
int seller = -1;
int buyer = -1;
int seller_manager = -1; // SettleHumanBuyerSale accounting seller (DispatchClubPlayerPendingOffers param8)
int buyer_manager = -1;
uint32_t raw_fee = 0;
uint32_t adjusted_fee = 0;
uint32_t salary = 0;
uint8_t term = 0;
};
struct HumanBuyerSaleHooks {
HumanBuyerSaleAllocatorGate allocator_gate = HumanBuyerSaleAllocatorGate::unsupported;
HumanBuyerSaleDirectMode direct_mode = HumanBuyerSaleDirectMode::unsupported;
std::function<void(const GameState&, const HumanBuyerSaleNotice&)> notice;
// Optional source caller acknowledgement after all deterministic transaction
// validation and immediately before SettleHumanBuyerSale. The direct adapter uses this
// for SubmitTransferBidSourceHumanBuyer's DeskActions_SubmitTransferBidImpl_ExecutableField ACK; pending callers leave it empty.
std::function<void(const GameState&, const HumanBuyerSaleRequest&)> before_accounts;
// Used only by the Void2 pending caller to preserve its severance/ACK/news
// sequence between SettleHumanBuyerSale and Fail. The direct SubmitTransferBidSourceHumanBuyer caller leaves
// this empty. It does not own list cleanup or Weekly_PendingSettleHumanBuyer_RuntimeField/DeskActions_EditorFail_RuntimeField2.
std::function<void(GameState&, const HumanBuyerSalePaid&)> after_paid_accounts;
// PresentManagerDialog yes/no question to a manager (poaching: the human seller agrees to the fee,
// the buyer accepts the fee the DFB sets). Required only for poaching.
std::function<bool(const GameState&, int manager, const std::string& text)> confirm;
};
struct HumanBuyerSaleResult {
HumanBuyerSaleStatus status = HumanBuyerSaleStatus::unsupported;
int player = -1;
int seller = -1;
int buyer = -1;
int seller_manager = -1; // SettleHumanBuyerSale accounting seller (DispatchClubPlayerPendingOffers param8)
int buyer_manager = -1;
uint32_t raw_fee = 0;
uint32_t adjusted_fee = 0;
};
// Shared exact SettleHumanBuyerSale account/subsidy and Fail ownership/board/history
// composition. Caller supplies explicit list and pool coordinates (ordinary
// 0..39 or special 40..43), owns staging, notices and any source-specific
// caller work. A successful move removes matching-player pool entries through
// ReleasePlayer. This helper never rewrites bids, performs caller-wide list/pool
// cleanup, or sets Weekly_PendingSettleHumanBuyer_RuntimeField/DeskActions_EditorFail_RuntimeField2. Unsupported boundaries require caller rollback.
HumanBuyerSaleResult settle_human_buyer_sale(GameState&, const HumanBuyerSaleRequest&,
const HumanBuyerSaleHooks&, WatcomRandom&, MinuteReport&);
} // namespace bmh
+547
View File
@@ -0,0 +1,547 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/league_pairings.hpp"
#include <algorithm>
#include <bit>
#include <cstdint>
#include <stdexcept>
#include "game/matchday.hpp"
#include "game/matchday_setup.hpp"
#include "game/match_engine.hpp"
#include "game/schedule.hpp"
#include "game/source_tip.hpp"
#include "game/table.hpp"
namespace bmh {
namespace {
void require(bool value,const char* reason) {
if(!value) throw std::invalid_argument(reason);
}
void clear_computer_tip(LeaguePairingsOwner& owner) {
owner.computer_tip_active=false;owner.computer_tip_league=owner.computer_tip_round=-1;
owner.computer_tip_original.fill(0);owner.computer_tip_results.clear();
}
void prepare_computer_tip(GameState& g,LeaguePairingsOwner& owner,
const LeaguePairingsConstants& c,GameRandom& game) {
const uint32_t preferences_at=::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(owner.manager);
require(!owner.filter_active&&!owner.postponed_active&&
(g.memory.u8(preferences_at)&0x0f)<=3,
"pairings: Computer Tip supports only ordinary/search modes 0..3");
require(owner.round>=0&&size_t(owner.league)<g.league_rounds.size()&&
int(g.league_rounds[size_t(owner.league)])<=owner.round,
"pairings: Computer Tip requires a current/future Source round");
require(g.memory.has(::bmh::layout::CurrentMatchday)&&g.results.size()>=kResultsSize,
"pairings: Computer Tip Native seed/results unavailable");
const auto page=league_pairings_view_source(g,owner,c);
const size_t expected=league_fixtures(owner.league,owner.round+1).size();
require(page.rows.size()==expected&&page.total_rows==int(expected),
"pairings: Computer Tip requires the complete ordinary fixture row set");
for(const auto& row:page.rows)
require(row.raw_result==0xcc,"pairings: Computer Tip requires every visible result to be 0xcc");
const int32_t source_seed=std::bit_cast<int32_t>(g.memory.u32(::bmh::layout::CurrentMatchday));
require(source_seed>=0&&source_seed<=10000,
"pairings: Computer Tip rejects an unqualified signed Native seed");
const size_t first=result_index(owner.league,owner.round+1,0);
require(first+10<=g.results.size(),"pairings: Computer Tip ten-byte Source backup is unavailable");
std::array<uint8_t,10> original{};
if(owner.computer_tip_active) {
require(owner.computer_tip_league==owner.league&&owner.computer_tip_round==owner.round&&
owner.computer_tip_results.size()==expected,
"pairings: stale Computer Tip forecast identity");
original=owner.computer_tip_original;
for(size_t i=0;i<10;++i)
require(g.results[first+i]==original[i],"pairings: Native result slice changed under Computer Tip");
} else {
std::copy_n(g.results.begin()+static_cast<std::ptrdiff_t>(first),10,original.begin());
}
struct Input { const LeaguePairingsRow* row; int home_rating,away_rating,home_secondary,away_secondary; };
std::vector<Input> inputs;inputs.reserve(expected);
for(const auto& row:page.rows) {
require(row.source_round==owner.round&&row.fixture_index>=0&&
size_t(row.fixture_index)<expected&&original[size_t(row.fixture_index)]==0xcc,
"pairings: Computer Tip fixture is outside the original 10-byte unplayed slice");
inputs.push_back({&row,
team_average(g,row.home.runtime_team,0x3f3).value,
team_average(g,row.away.runtime_team,0x3f3).value,
team_average(g,row.home.runtime_team,0x3fc).value,
team_average(g,row.away.runtime_team,0x3fc).value});
}
// Work on a copy so any arithmetic/validation failure leaves the staged G
// object untouched. set_seed preserves its cumulative Source call count.
GameRandom staged_game=game;staged_game.set_seed(source_seed);
std::vector<LeaguePairingsTipResult> results;results.reserve(expected);
for(const auto& input:inputs) {
const auto& row=*input.row;
results.push_back({owner.league,row.source_round,row.fixture_index,
row.home.runtime_team,row.home.club_identity,row.away.runtime_team,row.away.club_identity,
row.raw_result,source_tip_result(staged_game,c.computer_tip_gap,input.home_rating,input.away_rating,
input.home_secondary,input.away_secondary)});
}
game=staged_game;owner.computer_tip_active=true;
owner.computer_tip_league=owner.league;owner.computer_tip_round=owner.round;
owner.computer_tip_original=original;owner.computer_tip_results=std::move(results);
g.memory.set8(preferences_at,uint8_t(g.memory.u8(preferences_at)|0x10));
}
int filtered_fixture_count(int league,int team) {
int count=0;
for(int round=0;round<league_matchdays(league);++round)
for(const auto& fixture:league_fixtures(league,round+1))
if(fixture.home==team||fixture.away==team)++count;
return count;
}
int postponed_fixture_count(const GameState& g,int league) {
int count=0;
for(int round=0;round<league_matchdays(league);++round) {
const auto fixtures=league_fixtures(league,round+1);
for(size_t slot=0;slot<fixtures.size();++slot)
if(league_pairings_postponed_source(g.results.at(result_index(league,round+1,int(slot)))))++count;
}
require(count<=255,"pairings: Mode8 Source byte-counter overflow is outside the supported boundary");
return count;
}
void validate(const GameState& g,const LeaguePairingsOwner& o) {
const bool national=o.runtime_club==kNoTeam;
require(o.supported&&!o.closed&&o.manager>=0&&o.manager<4&&
size_t(o.manager)<g.manager_teams.size()&&g.memory.has(::bmh::layout::ActiveManager)&&
g.memory.u8(::bmh::layout::ActiveManager)==o.manager&&g.manager_teams[size_t(o.manager)]==o.runtime_club&&
(national||(o.runtime_club>=0&&o.runtime_club<138))&&
size_t(o.runtime_club)<g.club_ids.size()&&
g.club_ids[size_t(o.runtime_club)]==o.club_identity,
"pairings: stale or unsupported manager identity");
require(o.league>=0&&o.league<9&&o.round>=0&&o.round<league_matchdays(o.league)&&
o.league_group<=1&&size_t(o.league)<g.league_rounds.size()&&
g.league_rounds[size_t(o.league)]<=league_matchdays(o.league),
"pairings: unsupported league/round");
require(o.active_group>=-1&&(!o.active_phase||o.active_group>=0),
"pairings: invalid active presentation phase");
require(g.memory.has(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&&
(((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0c)==0)||
(g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0f)==4||
(g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0f)==8)&&
g.memory.has(::bmh::layout::LeagueTableDisplayModes+uint32_t(o.manager)*2+1),
"pairings: missing preferences or unsupported saved list mode");
require(g.results.size()>=kResultsSize&&g.club_ids.size()>=138&&g.league_rounds.size()>=9&&
g.memory.has(::bmh::layout::Postponed+0xef)&&g.memory.has(::bmh::layout::CompetitionCalendar+365*2+1),
"pairings: incomplete Native schedule");
const auto selection_valid=[&](int team,int identity) {
return team<0 ? team>=-2&&identity==-1 :
team<138&&team_league(team)==o.league&&g.club_ids.at(size_t(team))==identity;
};
require(selection_valid(o.search_first,o.search_first_identity)&&
selection_valid(o.search_second,o.search_second_identity)&&
(o.search_first!=-1 || (o.search_second==-1&&!o.search_second_click))&&
(o.search_first!=-2 || (o.search_second==-2&&!o.search_second_click))&&
(o.search_first==-1 || (g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0f)==2)&&
(!o.search_second_click || (o.search_first>=0&&o.search_second>=-1)),
"pairings: stale or invalid search selection");
const uint8_t mode=uint8_t(g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager))&0x0f);
const bool mode8=mode==8;
if(mode8) {
require(o.postponed_active&&!o.filter_active&&o.filter_team==-1&&o.filter_identity==-1&&o.filter_offset==0&&
o.search_first==-1&&o.search_second==-1&&o.search_first_identity==-1&&o.search_second_identity==-1&&
!o.search_second_click&&o.postponed_offset>=0&&o.postponed_offset%10==0,
"pairings: invalid postponed-list owner");
const int count=postponed_fixture_count(g,o.league);
require((count==0&&o.postponed_offset==0)||(count>0&&o.postponed_offset<count),
"pairings: stale or unreachable postponed-list window");
} else require(!o.postponed_active&&o.postponed_offset==0,
"pairings: stale postponed-list owner");
if(o.computer_tip_active) {
const size_t expected=league_fixtures(o.league,o.round+1).size();
require(mode<=3&&!o.filter_active&&!o.postponed_active&&
o.computer_tip_league==o.league&&o.computer_tip_round==o.round&&
o.round>=int(g.league_rounds.at(size_t(o.league)))&&
o.computer_tip_results.size()==expected&&g.memory.has(::bmh::layout::CurrentMatchday),
"pairings: invalid Computer Tip owner scope");
const size_t first=result_index(o.league,o.round+1,0);
require(first+10<=g.results.size(),"pairings: Computer Tip result backup is unavailable");
for(size_t n=0;n<10;++n)
require(g.results[first+n]==o.computer_tip_original[n],
"pairings: Computer Tip original result slice changed");
const auto fixtures=league_fixtures(o.league,o.round+1);
require(fixtures.size()==expected,"pairings: Computer Tip fixture count changed");
for(size_t n=0;n<expected;++n) {
const auto& tip=o.computer_tip_results[n];const auto& fixture=fixtures[n];
require(tip.league==o.league&&tip.source_round==o.round&&tip.fixture_index==int(n)&&
tip.home_runtime_team==fixture.home&&tip.away_runtime_team==fixture.away&&
tip.home_club_identity==g.club_ids.at(size_t(fixture.home))&&
tip.away_club_identity==g.club_ids.at(size_t(fixture.away))&&
tip.original_result==0xcc&&o.computer_tip_original[n]==0xcc,
"pairings: stale Computer Tip fixture identity");
}
} else require(o.computer_tip_league==-1&&o.computer_tip_round==-1&&
o.computer_tip_results.empty(),"pairings: stale inactive Computer Tip data");
if(o.filter_active) {
require(mode==4&&o.search_first==-1&&o.search_second==-1&&
o.search_first_identity==-1&&o.search_second_identity==-1&&!o.search_second_click&&
o.filter_offset>=0&&o.filter_offset%10==0&&o.filter_team>=-2,
"pairings: invalid Source club-filter mode");
if(o.filter_team>=0) {
require(o.filter_team<138&&team_league(o.filter_team)==o.league&&
g.club_ids.at(size_t(o.filter_team))==o.filter_identity&&
(o.filter_offset==0||o.filter_offset<filtered_fixture_count(o.league,o.filter_team)),
"pairings: stale or out-of-range filtered club");
} else {
require(o.filter_team==-2&&o.filter_identity==-1&&o.filter_offset==0,
"pairings: invalid unselected club filter");
}
} else {
require(o.filter_team==-1&&o.filter_identity==-1&&o.filter_offset==0&&mode!=4&&(!mode8||o.postponed_active),
"pairings: stale club-filter selection");
}
}
void page_preferences(GameState& g,const LeaguePairingsOwner& o,const LeaguePairingsConstants& c) {
const uint32_t word=::bmh::layout::LeagueTableDisplayModes+uint32_t(o.manager)*2;
uint16_t flags=uint16_t((g.memory.u16(word)&0xfc0f)|0x170);
if(c.points_mode.at(size_t(o.league))) flags|=0x80;
g.memory.set16(word,flags);
// Move clears the temporary Computer-Tip selection after every redraw.
const uint32_t byte=::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager);
g.memory.set8(byte,uint8_t(g.memory.u8(byte)&0xef));
}
int current_round(const GameState& g,int league) {
return std::min<int>(g.league_rounds.at(size_t(league)),league_matchdays(league)-1);
}
LeaguePairingsTeam team_view(const GameState& g,int team,int played) {
LeaguePairingsTeam out; out.runtime_team=team;out.club_identity=g.club_ids.at(size_t(team));
if(played) {
const int r=played-1;
const size_t at=(size_t(team)*13+size_t(r/3))*2;
require(at+1<g.position_history.size(),"pairings: missing Source rank history");
const unsigned word=g.position_history[at]|unsigned(g.position_history[at+1])<<8;
out.previous_rank=int((word>>((r%3)*5))&31)+1;
}
constexpr std::array<uint16_t,5> flags{0x1f1,0x1f2,0x1f4,0x1f8,0x1ff};
for(size_t n=0;n<flags.size();++n)out.strength[n]=team_average(g,team,flags[n]).value;
return out;
}
uint32_t round_date(const GameState& g,int league,int round,const LeaguePairingsConstants& c) {
require(c.domestic_league_count>0&&c.domestic_league_count<=9,
"pairings: unsupported Source calendar constants");
require(c.calendar_class.at(size_t(league))<32,"pairings: invalid calendar mask shift");
const uint32_t mask=league>=c.domestic_league_count?0x10u:1u<<c.calendar_class.at(size_t(league));
for(int day=0;day<366;++day) {
if(day_competitions(g,g.memory.u16(::bmh::layout::CompetitionCalendar+uint32_t(day)*2))&mask) {
if(round--==0)return (g.season_start+uint32_t(day))&0xffff;
}
}
// LeaguePairingsPlayedSource returns FFFF; 333f3 adds CalendarState_FormatError_RuntimeField3 and truncates to16 bits.
return (g.season_start+0xffffu)&0xffff;
}
}
bool league_pairings_played_source(uint8_t raw) {return (raw&0xcc)!=0xcc;}
bool league_pairings_postponed_source(uint8_t raw) {return (raw&0xcf)>0xcc;}
std::optional<LeaguePairingsActivePacket> league_pairings_active_packet_source(
const GameState& g,const LeaguePairingsOwner& owner,const std::vector<MatchGroup>& groups,
std::span<const uint8_t> referee_profiles) {
validate(g,owner);
// Mode4's armed -2 sentinel still uses the ordinary selected-round list.
// A selected filter and Mode8 explicitly clear local74 in Move.
if(owner.postponed_active||(owner.filter_active&&owner.filter_team>=0))return std::nullopt;
const auto fixtures=league_fixtures(owner.league,owner.round+1);
int found=-1;
for(size_t n=0;n<groups.size();++n) {
const auto& group=groups[n];
if(group.fixtures.size()>=2&&group.fixtures[0]==fixtures.front().home&&
group.fixtures[1]==fixtures.front().away)found=int(n);
}
if(found<0)return std::nullopt;
const auto& group=groups[size_t(found)];
require(group.fixtures.size()==fixtures.size()*2,
"pairings: incomplete active fixture vector");
LeaguePairingsActivePacket packet;
packet.league=owner.league;packet.round=owner.round;packet.group_index=found;
packet.rows.reserve(fixtures.size());
for(size_t n=0;n<fixtures.size();++n) {
const auto& fixture=fixtures[n];
require(group.fixtures[n*2]==fixture.home&&group.fixtures[n*2+1]==fixture.away,
"pairings: active fixture order does not match the selected round");
require(group.desc.size()>0x50+n,
"pairings: incomplete active referee/weather descriptor");
const uint8_t referee=group.desc[0x10+n];
require(size_t(referee)<referee_profiles.size()&&size_t(referee)*2+1<g.master_database_metadata.size(),
"pairings: missing active referee identity/profile");
const size_t name=size_t(g.master_database_metadata[size_t(referee)*2])|
size_t(g.master_database_metadata[size_t(referee)*2+1])<<8;
require(name<g.referee_names.size(),"pairings: active referee name offset is outside its Native pool");
const auto first=g.referee_names.begin()+name;
const auto end=std::find(first,g.referee_names.end(),uint8_t(0));
require(end!=g.referee_names.end(),"pairings: active referee name has no terminator");
LeaguePairingsActiveRow row;
row.source_round=owner.round;row.fixture_index=int(n);
row.home_runtime_team=fixture.home;row.home_club_identity=g.club_ids.at(size_t(fixture.home));
row.away_runtime_team=fixture.away;row.away_club_identity=g.club_ids.at(size_t(fixture.away));
row.referee_index=referee;row.referee_profile=referee_profiles[size_t(referee)];
row.weather=group.desc[0x50+n];row.temperature=int8_t(group.desc[0x30+n]);
row.referee_name.assign(first,end);packet.rows.push_back(std::move(row));
}
return packet;
}
void validate_league_pairings_active_packet_source(const GameState& g,const LeaguePairingsOwner& owner,
const LeaguePairingsActivePacket& packet) {
validate(g,owner);
require(!owner.postponed_active&&!(owner.filter_active&&owner.filter_team>=0)&&
packet.league==owner.league&&packet.round==owner.round&&packet.group_index>=0&&
packet.group_index==owner.active_group,"pairings: stale active descriptor owner");
const auto fixtures=league_fixtures(owner.league,owner.round+1);
require(packet.rows.size()==fixtures.size(),"pairings: incomplete active presentation rows");
for(size_t n=0;n<fixtures.size();++n) {
const auto& row=packet.rows[n];const auto& fixture=fixtures[n];
require(row.source_round==owner.round&&row.fixture_index==int(n)&&
row.home_runtime_team==fixture.home&&row.away_runtime_team==fixture.away&&
row.home_club_identity==g.club_ids.at(size_t(fixture.home))&&
row.away_club_identity==g.club_ids.at(size_t(fixture.away)),
"pairings: stale active row fixture identity");
require(size_t(row.referee_index)*2+1<g.master_database_metadata.size(),
"pairings: missing active referee name identity");
const size_t at=size_t(g.master_database_metadata[size_t(row.referee_index)*2])|
size_t(g.master_database_metadata[size_t(row.referee_index)*2+1])<<8;
require(at<g.referee_names.size(),"pairings: stale active referee name offset");
const auto first=g.referee_names.begin()+at;
const auto end=std::find(first,g.referee_names.end(),uint8_t(0));
require(end!=g.referee_names.end()&&row.referee_name==std::string(first,end),
"pairings: stale active referee name");
}
}
LeaguePairingsOwner open_league_pairings_source(GameState& g,int manager,const LeaguePairingsConstants& c) {
require(manager>=0&&manager<4&&size_t(manager)<g.manager_teams.size(),"pairings: unsupported manager");
LeaguePairingsOwner out;out.manager=manager;out.runtime_club=g.manager_teams[size_t(manager)];
const bool national=out.runtime_club==kNoTeam;
require((national||(out.runtime_club>=0&&out.runtime_club<138))&&
size_t(out.runtime_club)<g.club_ids.size(),"pairings: unsupported or unowned manager");
out.club_identity=g.club_ids[size_t(out.runtime_club)];
// TeamLeague2 maps the Original national runtime team 0x165 to league 0.
out.league=national?0:team_league(out.runtime_club);
require(size_t(out.league)<g.league_rounds.size(),"pairings: missing Native round counter");
out.round=current_round(g,out.league);out.title_round=g.league_rounds.at(size_t(out.league));out.supported=true;
if((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(manager))&0x0f)==8)out.postponed_active=true;
validate(g,out);page_preferences(g,out,c);
return out;
}
LeaguePairingsOwner edit_league_pairings_source(GameState& g,const LeaguePairingsOwner& before,
const LeaguePairingsEvent& e,const LeaguePairingsConstants& c,GameRandom& game,WatcomRandom& rand) {
validate(g,before);auto out=before;
if(e.kind!=LeaguePairingsAction::computer_tip)clear_computer_tip(out);
const auto reset=[&] {const uint32_t at=::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager);
g.memory.set8(at,uint8_t((g.memory.u8(at)&0xf0)|1));
out.search_first=out.search_second=out.search_first_identity=out.search_second_identity=-1;
out.search_second_click=false;
out.filter_team=out.filter_identity=-1;out.filter_offset=0;out.filter_active=false;
out.postponed_active=false;out.postponed_offset=0;};
switch(e.kind) {
case LeaguePairingsAction::presentation_redraw:
require(before.active_group>=0&&(e.value==0||e.value==1)&&bool(e.value)!=before.active_phase,
"pairings: invalid active presentation redraw");
out.active_phase=bool(e.value);break;
case LeaguePairingsAction::reset: out.round=current_round(g,out.league);out.title_round=g.league_rounds.at(size_t(out.league));reset();break;
case LeaguePairingsAction::previous:
if(out.postponed_active) {if(out.postponed_offset>=10)out.postponed_offset-=10;break;}
if((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager))&3)==0) {
if(out.filter_active&&out.filter_offset>=10)out.filter_offset-=10;
break;
}
out.round=(out.round+league_matchdays(out.league)-1)%league_matchdays(out.league);out.title_round=out.round;break;
case LeaguePairingsAction::next:
if(out.postponed_active) {
const auto page=league_pairings_view_source(g,before,c);
if(page.rows.size()==10&&out.postponed_offset+10<page.total_rows)out.postponed_offset+=10;
else if(page.rows.size()==10&&out.postponed_offset==0&&page.total_rows==10)
throw std::invalid_argument("pairings: bounded Mode8 exact-ten non-progress rejected");
break;
}
if((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager))&3)==0) {
if(out.filter_active&&out.filter_team>=0&&
out.filter_offset+10<filtered_fixture_count(out.league,out.filter_team))out.filter_offset+=10;
break;
}
out.round=(out.round+1)%league_matchdays(out.league);out.title_round=out.round;break;
case LeaguePairingsAction::toggle_group:
require(g.memory.has(::bmh::layout::CalendarState_FormatError_RuntimeField2)&&g.memory.u8(::bmh::layout::CalendarState_FormatError_RuntimeField2)==0,
"pairings: secondary leagues disabled");
out.league_group^=1;
require(size_t(out.manager)*0xb0c+0x210<g.manager_records.size(),
"pairings: missing manager league preference");
out.league=out.league_group?5:g.manager_records.at(size_t(out.manager)*0xb0c+0x210);
require(out.league>=0&&out.league<9,"pairings: invalid manager league preference");
[[fallthrough]];
case LeaguePairingsAction::select_league:
if(e.kind==LeaguePairingsAction::select_league) {
require(e.value>=0&&e.value<9,"pairings: invalid league selection");out.league=e.value;
}
if(out.league!=before.league) {
// LeagueMatchdays: retained round must be in the league and at/before
// its next round. Directparam0 does not apply the automatic reset.
if(out.round>=league_matchdays(out.league)||out.round>g.league_rounds.at(size_t(out.league)))
out.round=current_round(g,out.league);
out.title_round=out.round;
reset();
}
break;
case LeaguePairingsAction::team_info:
case LeaguePairingsAction::search_team: {
require(!out.filter_active&&!(e.kind==LeaguePairingsAction::search_team&&out.postponed_active),
"pairings: filtered rows cannot open ordered search");
require((e.kind==LeaguePairingsAction::search_team)==(out.search_first!=-1),
"pairings: row action does not match Source search ownership");
const auto view=league_pairings_view_source(g,before,c);bool found=false;
for(const auto& row:view.rows)for(const auto* team:{&row.home,&row.away})
found|=team->runtime_team==e.value&&team->club_identity==e.expected_club_identity;
require(found,"pairings: stale fixture team identity");
if(e.kind==LeaguePairingsAction::team_info)break;
if(!out.search_second_click) {
out.search_first=e.value;out.search_first_identity=e.expected_club_identity;
out.search_second=-1;out.search_second_identity=-1;out.search_second_click=true;
} else {
out.search_second=e.value;out.search_second_identity=e.expected_club_identity;
// LeagueMatchdays2 scans directed home/away fixtures in ascending round
// then row order. A missing self-pair keeps round and local30=1.
for(int round=0;round<league_matchdays(out.league);++round) {
const auto fixtures=league_fixtures(out.league,round+1);
if(std::any_of(fixtures.begin(),fixtures.end(),[&](const auto& fixture) {
return fixture.home==out.search_first&&fixture.away==out.search_second;
})) {
out.round=out.title_round=round;out.search_second_click=false;break;
}
}
}
break;
}
case LeaguePairingsAction::search:
out.filter_team=out.filter_identity=-1;out.filter_offset=0;out.filter_active=false;
out.postponed_active=false;out.postponed_offset=0;
out.title_round=out.round; // local34 was clamped during the prior draw.
g.memory.set8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager),
uint8_t((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager))&0xf0)|2));
out.search_first=out.search_second=-2;
out.search_first_identity=out.search_second_identity=-1;out.search_second_click=false;
break;
case LeaguePairingsAction::filter_by_club:
out.postponed_active=false;out.postponed_offset=0;out.title_round=out.round;
g.memory.set8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager),
uint8_t((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager))&0xf0)|4));
out.search_first=out.search_second=out.search_first_identity=out.search_second_identity=-1;
out.search_second_click=false;
out.filter_team=-2;out.filter_identity=-1;out.filter_offset=0;out.filter_active=true;
break;
case LeaguePairingsAction::postponed_list:
g.memory.set8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager),
uint8_t((g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager))&0xf0)|8));
out.search_first=out.search_second=out.search_first_identity=out.search_second_identity=-1;
out.search_second_click=false;out.filter_team=out.filter_identity=-1;out.filter_offset=0;
out.filter_active=false;out.postponed_active=true;out.postponed_offset=0;
break;
case LeaguePairingsAction::computer_tip:
prepare_computer_tip(g,out,c,game);break;
case LeaguePairingsAction::filter_club: {
require(out.filter_active,"pairings: club selection outside Source filter mode");
const auto visible=league_pairings_view_source(g,before,c);bool found=false;
for(const auto& row:visible.rows)for(const auto* team:{&row.home,&row.away})
found|=team->runtime_team==e.value&&team->club_identity==e.expected_club_identity;
require(found,"pairings: stale filtered-row team identity");
out.filter_team=e.value;out.filter_identity=e.expected_club_identity;
while(out.filter_offset>=filtered_fixture_count(out.league,out.filter_team)&&out.filter_offset>0)
out.filter_offset-=10;
break;
}
case LeaguePairingsAction::close:
reset();g.memory.set8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager),
uint8_t(g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager))&0xef));
out.active_phase=false;out.active_group=-1;
out.closed=true;stir_random(game,rand);return out;
case LeaguePairingsAction::unsupported:
throw std::invalid_argument("pairings: Original Zusatzaktion ist noch nicht verfügbar");
}
validate(g,out);
const uint32_t at=::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(out.manager);
if(e.kind!=LeaguePairingsAction::computer_tip)
g.memory.set8(at,uint8_t(g.memory.u8(at)&0xef));
return out;
}
LeaguePairingsView league_pairings_view_source(const GameState& g,const LeaguePairingsOwner& o,
const LeaguePairingsConstants& c) {
validate(g,o);LeaguePairingsView out;out.owner=o;out.played_rounds=g.league_rounds.at(size_t(o.league));
out.total_rounds=league_matchdays(o.league);out.preferences=g.memory.u8(::bmh::layout::CareerSession_CloseLeagueFamily_ExecutableField+uint32_t(o.manager));
const bool postponed=o.postponed_active;
if(!postponed)out.match_date=round_date(g,o.league,o.round,c);
auto append_row=[&](int round,size_t n,const Fixture& fixture) {
LeaguePairingsRow row;
row.source_round=round;row.fixture_index=int(n);
row.home=team_view(g,fixture.home,out.played_rounds);
row.away=team_view(g,fixture.away,out.played_rounds);
row.raw_result=g.results.at(result_index(o.league,round+1,int(n)));
if(o.computer_tip_active) {
const auto match=std::find_if(o.computer_tip_results.begin(),o.computer_tip_results.end(),
[&](const auto& tip) {return tip.league==o.league&&tip.source_round==round&&
tip.fixture_index==int(n)&&tip.home_runtime_team==row.home.runtime_team&&
tip.home_club_identity==row.home.club_identity&&
tip.away_runtime_team==row.away.runtime_team&&
tip.away_club_identity==row.away.club_identity;});
if(match!=o.computer_tip_results.end()) {
require(row.raw_result==match->original_result,
"pairings: Native result changed under Computer Tip forecast");
row.computer_tip_result=match->predicted_result;
}
}
if(postponed) {
for(uint32_t k=0;k<40;++k) {
const uint32_t at=::bmh::layout::Postponed+k*6;const uint16_t day=g.memory.u16(at);
if(day&&g.memory.u8(at+3)==o.league&&g.memory.u8(at+2)==round&&g.memory.u8(at+4)==n) {
row.postponed_queue_slot=uint8_t(k);row.postponed_day=day;
row.postponed_date=g.season_start+day;break;
}
}
} else if(!league_pairings_played_source(row.raw_result)&&row.raw_result!=0xcc) {
for(uint32_t k=0;k<40;++k) {
const uint32_t at=::bmh::layout::Postponed+k*6;const uint16_t day=g.memory.u16(at);
if(day&&g.memory.u8(at+3)==o.league&&g.memory.u8(at+2)==round&&g.memory.u8(at+4)==n) {
row.postponed_date=g.season_start+day;break;
}
}
}
if(!o.active_phase&&!postponed&&!(o.filter_active&&o.filter_team>=0)&&round>=out.total_rounds/2) {
const uint8_t raw=g.results.at(result_index(o.league,round+1-out.total_rounds/2,int(n)));
if(league_pairings_played_source(raw))row.first_leg_result=raw;
}
if(o.filter_active&&o.filter_team>=0&&row.raw_result==0xcc)
row.scheduled_date=round_date(g,o.league,round,c);
out.rows.push_back(std::move(row));
};
if(postponed) {
out.page_offset=o.postponed_offset;
for(int round=0;round<out.total_rounds;++round) {
const auto fixtures=league_fixtures(o.league,round+1);
for(size_t n=0;n<fixtures.size();++n) {
const auto raw=g.results.at(result_index(o.league,round+1,int(n)));
if(!league_pairings_postponed_source(raw))continue;
if(out.total_rows>=o.postponed_offset&&out.rows.size()<10)append_row(round,n,fixtures[n]);
++out.total_rows;
}
}
} else if(o.filter_active&&o.filter_team>=0) {
out.page_offset=o.filter_offset;
for(int round=0;round<out.total_rounds;++round) {
const auto fixtures=league_fixtures(o.league,round+1);
for(size_t n=0;n<fixtures.size();++n) {
if(fixtures[n].home!=o.filter_team&&fixtures[n].away!=o.filter_team)continue;
if(out.total_rows>=o.filter_offset&&out.rows.size()<10)append_row(round,n,fixtures[n]);
++out.total_rows;
}
}
} else {
const auto fixtures=league_fixtures(o.league,o.round+1);
out.total_rows=int(fixtures.size());
for(size_t n=0;n<fixtures.size();++n)append_row(o.round,n,fixtures[n]);
}
return out;
}
} // namespace bmh
+119
View File
@@ -0,0 +1,119 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <array>
#include <optional>
#include <span>
#include <string>
#include <vector>
#include "game/state.hpp"
#include "game/random.hpp"
namespace bmh {
struct MatchGroup;
// Normal LeagueScreenShown(2,0)->Move(0) only. The App owns the staged Native/W/G
// transaction. No mutator here calls a presenter, advances a day, or saves.
struct LeaguePairingsConstants {
std::array<uint8_t,9> points_mode{}, calendar_class{};
std::array<uint8_t,10> computer_tip_gap{};
uint8_t domestic_league_count=0;
};
struct LeaguePairingsTipResult {
int league=-1,source_round=-1,fixture_index=-1;
int home_runtime_team=-1,home_club_identity=-1,away_runtime_team=-1,away_club_identity=-1;
uint8_t original_result=0xcc,predicted_result=0xcc;
bool operator==(const LeaguePairingsTipResult&) const=default;
};
struct LeaguePairingsOwner {
int manager=-1, runtime_club=-1, club_identity=-1, league=-1, round=-1, title_round=-1;
uint8_t league_group=0;
bool supported=false, closed=false;
// Move local28 and its current active descriptor. Process-only;
// neither field is serialized or changes the league fixture/result arrays.
bool active_phase=false;
int active_group=-1;
// Move locals60/50/30. -1 means ordinary row TeamInfo, -2 is the
// freshly armed search sentinel. Saved preference2 alone does not arm it.
int search_first=-1,search_second=-1;
int search_first_identity=-1,search_second_identity=-1;
bool search_second_click=false;
// Move mode4 has a separate single-club filter; its selection is not
// the ordered two-team search state above. -2 is freshly armed, -1 inactive.
int filter_team=-1,filter_identity=-1,filter_offset=0;
bool filter_active=false;
// Move mode8 owns a separate postponed-result list and ten-row page.
int postponed_offset=0;
bool postponed_active=false;
// KI-Tipp is a one-redraw runtime forecast, keyed to the actual fixture
// identities. Its ten-byte original slice includes unplayed/padding bytes;
// the forecast never writes that slice back to serialized Native results.
bool computer_tip_active=false;
int computer_tip_league=-1,computer_tip_round=-1;
std::array<uint8_t,10> computer_tip_original{};
std::vector<LeaguePairingsTipResult> computer_tip_results;
bool operator==(const LeaguePairingsOwner&) const=default;
};
struct LeaguePairingsTeam {
int runtime_team=-1, club_identity=-1;
int previous_rank=-1; // TablePosition, already 1-based; absent before round1.
std::array<int,5> strength{}; // 1f1,1f2,1f4,1f8,1ff, Void6.
};
struct LeaguePairingsActiveRow {
int source_round=-1,fixture_index=-1;
int home_runtime_team=-1,home_club_identity=-1,away_runtime_team=-1,away_club_identity=-1;
uint8_t referee_index=0,referee_profile=0,weather=0;
int8_t temperature=0;
std::string referee_name; // Original bytes from MasterDatabaseMetadata -> ba370.
bool operator==(const LeaguePairingsActiveRow&) const=default;
};
struct LeaguePairingsActivePacket {
int league=-1,round=-1,group_index=-1;
std::vector<LeaguePairingsActiveRow> rows;
bool operator==(const LeaguePairingsActivePacket&) const=default;
};
struct LeaguePairingsRow {
LeaguePairingsTeam home,away;
uint8_t raw_result=0xcc;
std::optional<uint8_t> computer_tip_result;
std::optional<uint32_t> postponed_date,scheduled_date;
std::optional<uint16_t> postponed_day;
std::optional<uint8_t> postponed_queue_slot;
std::optional<uint8_t> first_leg_result;
// Native/source coordinates survive a multi-round filtered projection.
int source_round=-1,fixture_index=-1;
};
struct LeaguePairingsView {
LeaguePairingsOwner owner;
int played_rounds=0, total_rounds=0;
int total_rows=0,page_offset=0;
uint8_t preferences=0;
uint32_t match_date=0xffff;
std::vector<LeaguePairingsRow> rows;
};
enum class LeaguePairingsAction { reset,previous,next,select_league,toggle_group,team_info,close,unsupported,search,search_team,filter_by_club,filter_club,postponed_list,computer_tip,presentation_redraw };
struct LeaguePairingsEvent {
LeaguePairingsAction kind=LeaguePairingsAction::unsupported;
int value=-1;
int expected_club_identity=-1; // stable team identity for TeamInfo/search/filter.
};
LeaguePairingsOwner open_league_pairings_source(GameState&,int manager,const LeaguePairingsConstants&);
LeaguePairingsOwner edit_league_pairings_source(GameState&,const LeaguePairingsOwner&,
const LeaguePairingsEvent&,const LeaguePairingsConstants&,GameRandom&,WatcomRandom&);
// Pure, bounded Source projection; renderers never call a Native/RNG mutator.
LeaguePairingsView league_pairings_view_source(const GameState&,const LeaguePairingsOwner&,
const LeaguePairingsConstants&);
// Read only active process descriptors, never reconstruct weather/referees from
// saved bytes or run event preparation. Last first-pair match follows Move.
std::optional<LeaguePairingsActivePacket> league_pairings_active_packet_source(
const GameState&,const LeaguePairingsOwner&,const std::vector<MatchGroup>&,
std::span<const uint8_t> referee_profiles);
void validate_league_pairings_active_packet_source(const GameState&,const LeaguePairingsOwner&,
const LeaguePairingsActivePacket&);
bool league_pairings_played_source(uint8_t raw);
bool league_pairings_postponed_source(uint8_t raw);
} // namespace bmh
+866
View File
@@ -0,0 +1,866 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/lineup.hpp"
#include <cstdlib>
#include <stdexcept>
#include <algorithm>
#include <utility>
namespace bmh {
namespace {
// Position type by formation depth x (table at layout field).
constexpr int8_t kTypeByDepth[24] = {0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 0, 1, 2, 2};
// Position type of bench slots by slot index (table at layout field); 9 = any.
constexpr int8_t kTypeBySlot[24] = {2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 0, 1, 2, 2, 3, 3, 9, 9, 9, 9, 9, 9, 9};
constexpr int16_t kUnavailable = -32000; // 0x8300
constexpr int kMismatchWeight = 0x40; // local_54 for computer teams
constexpr size_t kManagerRecordSize = 0xB0C;
constexpr size_t kManagerBoardSize = 0x840;
constexpr size_t kBoardRowSize = 0x58;
constexpr size_t kFormationManagerSize = 0x160;
constexpr size_t kNativeFormationBlockSize = 0x580;
uint8_t formation_byte(const GameState& g, size_t index) {
// The native byte table runs directly into the tactics block at 0x580.
// Int2 indexes through that contiguous memory for manager 3's
// indoor formations and reserve rows.
if (index < kNativeFormationBlockSize) return g.formations.at(index);
return g.tactics.at(index - kNativeFormationBlockSize);
}
bool pitch_context_valid(const GameState& g, int manager, int team) {
if (manager < 0 || manager > 3 || team < 0 || team >= 138 || g.lineups_frozen ||
!g.memory.has(::bmh::layout::ActiveManager) || !g.memory.has(::bmh::layout::GameMode) ||
g.memory.u8(::bmh::layout::ActiveManager) != manager || g.memory.u8(::bmh::layout::GameMode) < 1 || g.memory.u8(::bmh::layout::GameMode) > 3 ||
size_t(manager) >= g.manager_teams.size() || g.manager_teams[size_t(manager)] != team ||
g.manager_of(team) != manager || size_t(team) >= g.team_flags.size() ||
size_t(team) >= g.club_ids.size() || size_t(team + 1) * 2 > g.club_heap_78.size() ||
g.manager_records.size() < size_t(manager + 1) * kManagerRecordSize ||
g.manager_options.size() < size_t(manager + 1) * 5 ||
g.tactics.size() < size_t(manager + 1) * kManagerBoardSize ||
g.formations.size() < size_t(manager + 1) * kFormationManagerSize ||
g.player_cards.size() != g.players.size())
return false;
const size_t record = size_t(manager) * kManagerRecordSize;
const uint16_t record_team = uint16_t(g.manager_records[record + 0x290] |
uint16_t(g.manager_records[record + 0x291]) << 8);
if (record_team != uint16_t(team)) return false;
const SquadRange range = squad_range(team);
if ((range.count != 16 && range.count != 24) || range.first + range.count > g.squad_slots.size())
return false;
bool empty_seen = false;
std::array<bool, 0x1000> seen{};
size_t occupied = 0;
for (size_t row = 0; row < range.count; ++row) {
const uint16_t slot = g.squad_slots[range.first + row];
const size_t id = slot & 0x0fff;
if (id == 0x0fff) { empty_seen = true; continue; }
if (empty_seen || id >= g.players.size() || seen[id]) return false;
seen[id] = true;
++occupied;
}
if (occupied < 11) return false;
const size_t board = size_t(manager) * kManagerBoardSize;
for (size_t row = 0; row < 11; ++row) {
const uint16_t slot = g.squad_slots[range.first + row];
const size_t id = slot & 0x0fff;
const int depth = int8_t(g.tactics[board + row * kBoardRowSize + 0x41]);
const int lane = int8_t(g.tactics[board + row * kBoardRowSize + 0x42]);
if (id >= g.players.size() || (slot & 0xc000) != 0x8000 ||
depth < 0 || depth > 19 || lane < 0 || lane > 8)
return false;
const bool fit = ((g.players[id].w364 >> 16) & 0x1f) == 0;
if (fit) for (size_t prior = 0; prior < row; ++prior) {
const size_t prior_id = g.squad_slots[range.first + prior] & 0x0fff;
if (((g.players[prior_id].w364 >> 16) & 0x1f) != 0) continue;
const size_t other = board + prior * kBoardRowSize;
if (int8_t(g.tactics[other + 0x41]) == depth &&
int8_t(g.tactics[other + 0x42]) == lane)
return false;
}
}
return true;
}
bool optimized_pitch_valid(const GameState& g, int manager, int team) {
if (!pitch_context_valid(g, manager, team)) return false;
const SquadRange range = squad_range(team);
const size_t board = size_t(manager) * kManagerBoardSize;
std::array<bool, 0x1000> seen{};
for (size_t row = 0; row < 11; ++row) {
const uint16_t slot = g.squad_slots[range.first + row];
const size_t id = slot & 0x0fff;
const int depth = int8_t(g.tactics[board + row * kBoardRowSize + 0x41]);
const int lane = int8_t(g.tactics[board + row * kBoardRowSize + 0x42]);
if (id >= g.players.size() || seen[id] || (slot & 0xc000) != 0x8000 ||
depth < 0 || depth > 19 || lane < 0 || lane > 8)
return false;
seen[id] = true;
}
return true;
}
// Abs2-based detail score in Int2. Both preference fields come
// from the w35c value loaded from PlayerConditionTechniqueForm: +21 for depth and +24 for lane.
int16_t detailed_position_value(int16_t base, const Player& player, int x, int y, int detail) {
if (detail == 0 || player.position() == 0) return base;
const int role = player.position();
const int preferred_y = int(player.w35c >> 24 & 7);
const int preferred_x = int(player.w35c >> 21 & 7) + (role - 1) * 7 + (role == 2);
const int delta_y = std::abs(y - preferred_y);
const int delta_x = std::abs(x - preferred_x);
const int loss = (detail * delta_y + (detail + 1) * delta_x) >> 1;
return int16_t(((100 - loss) * int(base)) / 100);
}
bool run_pitch_optimizer(GameState& staged, int manager, int team, int formation) {
if (staged.lineups_frozen || formation < 0 || formation > 7) return false;
try {
auto_lineup(staged, team, 0xe4);
} catch (...) {
return false;
}
return staged.manager_options[size_t(manager) * 5] == formation + 1 &&
optimized_pitch_valid(staged, manager, team);
}
} // namespace
void prepare_lineup_entry(GameState& g, int team) {
const int manager = g.manager_of(team);
const SquadRange range = squad_range(team);
if (manager < 0 || team < 0 || range.count < 11 || range.first + range.count > g.squad_slots.size())
throw std::invalid_argument("prepare_lineup_entry: unsupported manager squad");
const size_t badge = size_t(team) * 2;
if (badge + 1 >= g.club_heap_78.size())
throw std::invalid_argument("prepare_lineup_entry: incomplete club badge table");
// SquadCount(team, 2) counts occupied IDs over the whole squad range.
// Original team rows are compact; reject a sparse map rather than applying
// its count as a row bound to a different layout.
size_t players = 0;
for (size_t row = 0; row < range.count; ++row)
players += (g.squad_slots[range.first + row] & 0x0fff) != 0x0fff;
if (players < 11) throw std::invalid_argument("prepare_lineup_entry: too few players");
for (size_t row = 0; row < players; ++row) {
const int id = g.squad_slots[range.first + row] & 0x0fff;
if (id == 0x0fff || size_t(id) >= g.players.size())
throw std::invalid_argument("prepare_lineup_entry: sparse or invalid squad");
}
// PrepareLineupEntry scans backward for the last row with either field/bench
// marker, then reassigns those marker bits by row, through row 16 only.
int last = -1;
for (int row = int(players) - 1; row >= 0; --row)
if (g.squad_slots[range.first + size_t(row)] & 0xc000) { last = row; break; }
for (int row = 0; row <= last && row < 17; ++row) {
uint16_t& slot = g.squad_slots[range.first + size_t(row)];
slot = uint16_t((slot & 0x3fff) | (row < 11 ? 0x8000 : 0x4000));
}
}
bool set_pitch_automatic_weight_source(GameState& g, int manager_slot, int runtime_club,
int weight_index, uint8_t old_weights, uint8_t new_weights) {
if (!pitch_context_valid(g, manager_slot, runtime_club) || weight_index < 0 || weight_index > 2 ||
g.memory.u8(::bmh::layout::GameMode) == 1)
return false;
const size_t at = size_t(manager_slot) * kManagerRecordSize + 0x288;
if (g.manager_records[at] != old_weights) return false;
const unsigned shift = unsigned(weight_index * 2);
const uint8_t mask = uint8_t(3u << shift);
const uint8_t next_field = uint8_t((((old_weights >> shift) & 3u) + 1u) & 3u);
const uint8_t expected = uint8_t((old_weights & uint8_t(~mask)) | uint8_t(next_field << shift));
if (new_weights != expected) return false;
try {
GameState staged = g;
staged.manager_records[at] = new_weights;
g = std::move(staged);
return true;
} catch (...) {
return false;
}
}
bool move_pitch_player_source(GameState& g, int manager_slot, int runtime_club,
int row, int player_id, uint16_t slot,
int old_depth, int old_lane, int new_depth, int new_lane) {
if (!pitch_context_valid(g, manager_slot, runtime_club) || row < 0 || row >= 11 ||
old_depth < 0 || old_depth > 19 || old_lane < 0 || old_lane > 8 ||
new_depth < 0 || new_depth > 19 || new_lane < 0 || new_lane > 8 ||
(old_depth == new_depth && old_lane == new_lane))
return false;
const SquadRange range = squad_range(runtime_club);
const size_t record = range.first + size_t(row);
const size_t board = size_t(manager_slot) * kManagerBoardSize;
const size_t row_at = board + size_t(row) * kBoardRowSize;
if (g.squad_slots[record] != slot || (slot & 0x0fff) != player_id ||
player_id < 0 || size_t(player_id) >= g.players.size() || (slot & 0xc000) != 0x8000 ||
((g.players[size_t(player_id)].w364 >> 16) & 0x1f) != 0 ||
int8_t(g.tactics[row_at + 0x41]) != old_depth ||
int8_t(g.tactics[row_at + 0x42]) != old_lane)
return false;
int exact_occupant = -1;
int indoor_partner = -1;
for (int other = 0; other < 11; ++other) {
if (other == row) continue;
const uint16_t other_slot = g.squad_slots[range.first + size_t(other)];
const size_t other_id = other_slot & 0x0fff;
if (other_id >= g.players.size() || ((g.players[other_id].w364 >> 16) & 0x1f) != 0) continue;
const size_t other_at = board + size_t(other) * kBoardRowSize;
const int depth = int8_t(g.tactics[other_at + 0x41]);
const int lane = int8_t(g.tactics[other_at + 0x42]);
if (depth == new_depth && lane == new_lane) {
exact_occupant = other;
break;
}
const int dx = std::abs(new_depth - depth);
const int dy = std::abs(new_lane - lane);
if (dx < 2 && dy < 2) {
if (!g.indoor) return false; // Outdoor source branch refuses adjacent targets.
// PitchScreen keeps the last eligible hall neighbor encountered.
// The exact-coordinate branch above remains the ordinary swap path.
indoor_partner = other;
}
}
try {
GameState staged = g;
auto* selected = staged.tactics.data() + row_at;
if (exact_occupant >= 0) {
auto* occupied = staged.tactics.data() + board + size_t(exact_occupant) * kBoardRowSize;
const uint8_t occupied_depth = occupied[0x41], occupied_lane = occupied[0x42];
occupied[0x41] = selected[0x41];
occupied[0x42] = selected[0x42];
selected[0x41] = occupied_depth;
selected[0x42] = occupied_lane;
} else {
// PitchScreen clears this row, its old hall partner and every
// reciprocal reference to either before installing the new move.
for (size_t other = 0; other < 24; ++other) {
auto* candidate = staged.tactics.data() + board + other * kBoardRowSize;
if (other == size_t(row) ||
(indoor_partner >= 0 && other == size_t(indoor_partner)) ||
candidate[0x3f] == uint8_t(row) ||
(indoor_partner >= 0 && candidate[0x3f] == uint8_t(indoor_partner)))
candidate[0x3f] = 0xff;
}
selected[0x41] = uint8_t(new_depth);
selected[0x42] = uint8_t(new_lane);
if (g.indoor && indoor_partner >= 0) {
auto* partner = staged.tactics.data() + board + size_t(indoor_partner) * kBoardRowSize;
selected[0x3f] = uint8_t(indoor_partner);
partner[0x3f] = uint8_t(row);
}
}
staged.manager_options[size_t(manager_slot) * 5] = 0; // successful placement selects manual AA.
g = std::move(staged);
return true;
} catch (...) {
return false;
}
}
bool apply_pitch_formation_source(GameState& g, int manager_slot, int runtime_club,
int formation, uint8_t expected_weights) {
if (!pitch_context_valid(g, manager_slot, runtime_club) || formation < 0 || formation > 7)
return false;
const size_t record = size_t(manager_slot) * kManagerRecordSize;
if (g.manager_records[record + 0x288] != expected_weights ||
(g.manager_records[record + 0x218 + size_t(g.indoor)] & uint8_t(1u << formation)) == 0)
return false;
try {
GameState staged = g;
staged.manager_options[size_t(manager_slot) * 5] = uint8_t(formation + 1);
if (!run_pitch_optimizer(staged, manager_slot, runtime_club, formation)) return false;
g = std::move(staged);
return true;
} catch (...) {
return false;
}
}
bool save_pitch_formation_source(GameState& g, int manager_slot, int runtime_club,
int formation, uint8_t expected_weights,
const std::array<uint8_t, 22>& formation_positions) {
if (!pitch_context_valid(g, manager_slot, runtime_club) || formation < 4 || formation > 7)
return false; // Ordinary Source access exposes only the four own slots for saving.
const size_t record = size_t(manager_slot) * kManagerRecordSize;
const size_t board = size_t(manager_slot) * kManagerBoardSize;
const size_t table = size_t(manager_slot) * kFormationManagerSize +
(g.indoor ? 0xb0 : 0) + size_t(formation) * 0x16;
const size_t mask = record + 0x218 + size_t(g.indoor);
if (g.manager_records[record + 0x288] != expected_weights ||
table + formation_positions.size() > g.formations.size())
return false;
for (size_t row = 0; row < 11; ++row) {
const uint16_t slot = g.squad_slots[squad_range(runtime_club).first + row];
const int depth = int8_t(g.tactics[board + row * kBoardRowSize + 0x41]);
const int lane = int8_t(g.tactics[board + row * kBoardRowSize + 0x42]);
if ((slot & 0xc000) != 0x8000 || depth < 0 || depth > 19 || lane < 0 || lane > 8 ||
formation_positions[row] != uint8_t(depth) ||
formation_positions[11 + row] != uint8_t(lane))
return false;
}
try {
GameState staged = g;
std::copy(formation_positions.begin(), formation_positions.end(), staged.formations.begin() + std::ptrdiff_t(table));
staged.manager_records[mask] |= uint8_t(1u << formation);
staged.manager_options[size_t(manager_slot) * 5] = uint8_t(formation + 1);
if (!run_pitch_optimizer(staged, manager_slot, runtime_club, formation)) return false;
g = std::move(staged);
return true;
} catch (...) {
return false;
}
}
static void auto_lineup_impl(GameState& g, int team, int mode, int manager) {
if (team >= 138 && team != kNoTeam) return; // teams without squads
if (g.lineups_frozen) return; // LineupRuntimeField (the season change)
const bool improve_from_reserves = (mode & 0x80) != 0;
mode &= 0x7F;
// HumanManagerLetsAssistantPickTeamWhen: a human manager lets the assistant pick the team when his option byte 0
// is set; its value - 1 is the formation, taken from the manager's own formation set.
int formation = 0, set = 0;
int weight = kMismatchWeight, familiarity = 0, detail = 0;
if (manager >= 0) {
const uint8_t raw_option = manager < 4 ? g.manager_options.at(size_t(manager) * 5) : 0;
const int option = int8_t(raw_option - 1);
if (raw_option == 0) {
// Int2: with a manual human line-up, modes below 100 only
// copy formation coordinates to a transient scratch table; mode
// 0x65 (101) and all other modes below 100 return without mutating
// the saved line-up. GameState has no such scratch table, so that
// non-persistent coordinate copy is intentionally not represented.
// The source enters DispatchLiveOverview only when the club-table bit in
// *ClubBadgeSelectors agrees with CareerSessionRuntimeField. We retain that boundary rather
// than applying the human normalizer to a different game mode.
const size_t club_word = size_t(team) * 2;
if (club_word + 1 >= g.club_heap_78.size())
throw std::invalid_argument("auto_lineup: incomplete club badge table");
uint16_t badge_word = uint16_t(g.club_heap_78[club_word] |
uint16_t(g.club_heap_78[club_word + 1]) << 8);
const bool mode_mismatch = ((badge_word >> 9) & 1) != unsigned(g.indoor);
if (mode_mismatch) {
// Int2 does not reject a manual club on a mode transition.
// It clears the stored badge selector to bit 0, sets its indoor bit
// from CareerSessionRuntimeField, and falls through to the ordinary assistant
// scorer with formation 0. Keep the manager's assistant scoring
// parameters below; AA itself remains off.
badge_word = uint16_t((badge_word & 0x01ff) | (unsigned(g.indoor) << 9));
g.club_heap_78[club_word] = uint8_t(badge_word);
g.club_heap_78[club_word + 1] = uint8_t(badge_word >> 8);
formation = 0;
set = manager;
const uint8_t style = g.manager_records.at(size_t(manager) * 0xB0C + 0x288);
weight = 1 << ((style & 3) + 4);
familiarity = (style >> 4) & 3;
if (g.level >= 6) detail = (style >> 2) & 3;
} else {
if (mode == 0x65 || mode < 100) return;
const SquadRange range = squad_range(team);
const size_t board_base = size_t(manager) * 0x840;
if (range.count < 11 || range.first + range.count > g.squad_slots.size() ||
g.tactics.size() < board_base + 0x840 || g.player_cards.size() != g.players.size())
throw std::invalid_argument("auto_lineup: incomplete manual line-up state");
size_t player_count = 0;
for (size_t row = 0; row < range.count; ++row)
player_count += (g.squad_slots[range.first + row] & 0x0fff) != 0x0fff;
// DispatchLiveOverview works on whatever count the squad has: a short squad simply
// fields fewer players. That happens to the national team outside the world
// mode, which nobody nominates, when its human coach takes it over on an
// international day (SwapManagerSlots2 -> Int2(0x165, 0xe4)).
if (player_count > range.count)
throw std::invalid_argument("auto_lineup: manual line-up has an invalid squad size");
for (size_t row = 0; row < player_count; ++row) {
const size_t id = g.squad_slots[range.first + row] & 0x0fff;
if (id == 0x0fff || id >= g.players.size())
throw std::invalid_argument("auto_lineup: manual line-up has a sparse squad");
}
auto board = [&](size_t row) { return g.tactics.data() + board_base + row * 0x58; };
auto fit = [&](size_t row) {
const int id = g.squad_slots[range.first + row] & 0x0fff;
return id != 0x0fff && size_t(id) < g.players.size() &&
(g.players[size_t(id)].w364 >> 16 & 0x1f) == 0;
};
// DispatchLiveOverview / Fit: move a fit player from the end of the
// roster into each injured row in the first 17 slots. Coordinates
// stay with the destination board row after the full 0x58-byte swap.
for (size_t row = 0; row < 17 && row < player_count; ++row) {
if (fit(row)) continue;
size_t replacement = player_count;
while (replacement > 0) {
--replacement;
if (fit(replacement)) break;
}
if (!fit(replacement) || replacement <= row) break;
std::swap(g.squad_slots[range.first + row], g.squad_slots[range.first + replacement]);
std::swap_ranges(board(row), board(row) + 0x58, board(replacement));
std::swap(board(row)[0x41], board(replacement)[0x41]);
std::swap(board(row)[0x42], board(replacement)[0x42]);
}
// DispatchLiveOverview: clear old status nibbles; fit players in the first
// 11 rows start, the next six are bench. Invalid fit-player
// coordinates are initialized to (0,0) as in the original.
for (size_t row = 0; row < player_count; ++row) {
uint16_t& slot = g.squad_slots[range.first + row];
slot &= 0x0fff;
if (fit(row) && row < 17) {
slot |= uint16_t(row < 11 ? 0x8000 : 0x4000);
const int8_t x = int8_t(board(row)[0x41]), y = int8_t(board(row)[0x42]);
if (row < 11 && (x < 0 || x > 19 || y < 0 || y > 8)) {
board(row)[0x42] = 0;
board(row)[0x41] = board(row)[0x42];
}
}
}
// GatedByParamLive updates only players in flagged rows, preserving the
// card's high bits and replacing its slot index in low five bits.
for (size_t row = 0; row < player_count; ++row) {
const uint16_t slot = g.squad_slots[range.first + row];
if ((slot & 0xc000) == 0) continue;
const size_t id = slot & 0x0fff;
g.player_cards[id] = uint16_t((g.player_cards[id] & 0xffe0) | row);
}
return;
}
}
if (raw_option != 0) {
if (option == -1) throw std::invalid_argument("auto_lineup: invalid human formation option");
formation = option;
set = manager;
const uint8_t style = g.manager_records.at(size_t(manager) * 0xB0C + 0x288); // assistant settings
weight = 1 << ((style & 3) + 4);
familiarity = (style >> 4) & 3;
if (g.level >= 6) detail = (style >> 2) & 3;
}
} else {
formation = g.formation(team);
}
// formation table (block Formations): x at +0..10, y at +11..21; the original walks on past 11
const size_t table = size_t(formation) * 0x16 + (g.indoor ? 0xb0 : 0) + size_t(set) * 0x160;
auto board = [&](int slot) -> uint8_t* { return &g.tactics.at(size_t(manager) * 0x840 + size_t(slot) * 0x58); };
g.team_flags.at(team) &= 0xFFFE;
SquadRange range = squad_range(team);
if (manager >= 0)
for (size_t s = 0; s < range.count; s++) board(int(s))[0x3f] = 0xFF;
int count = int(range.count);
bool first_eleven_only = mode == 0x65 || mode < 100;
if (first_eleven_only) count = 11;
int16_t value[24];
int16_t best_score[24];
for (int i = 0; i < 24; i++) value[i] = best_score[i] = kUnavailable;
int found = 0;
for (; found < count; found++) {
uint16_t& slot = g.squad_slots.at(range.first + found);
int id = slot & 0x0FFF;
if (id == 0x0FFF) break;
const Player& p = g.players.at(id);
if ((p.w364 >> 16 & 0x1F) == 0) {
value[found] = int16_t(p.form() / 3 + p.condition() + p.technique());
if (manager >= 0 && familiarity != 0) {
// players not used to their place on the board are worth less
int16_t f = int16_t(board(found)[0xf] - 0x19);
if (f > 0x2d) f = int16_t(f * 2 - 0x19);
value[found] = int16_t(value[found] - (f * familiarity) / 2);
}
}
slot &= 0x3FFF; // clear line-up and bench flags
}
int players = first_eleven_only ? 11 : found;
for (int pos = 0; pos < players; pos++) {
int type;
if (pos < 11) type = kTypeByDepth[formation_byte(g, table + size_t(pos))];
else type = kTypeBySlot[pos];
int best = -1;
for (int j = pos; j < players; j++) {
uint16_t entry = g.squad_slots.at(range.first + j);
int id = entry & 0x0FFF;
if (value[j] == kUnavailable || (entry & 0xC000) != 0 || id == 0x0FFF) continue;
int player_type = g.players.at(id).position();
int mismatch;
if (type == 9) mismatch = 0;
else if ((player_type == 0) != (type == 0)) mismatch = int16_t(weight) * 25;
else mismatch = int16_t(weight) * (player_type > type ? player_type - type : type - player_type);
const Player& candidate = g.players.at(size_t(id));
int16_t position_value = value[j];
// Int2 reads the coordinate pointers only inside local_20's
// level-6, non-goalkeeper branch. Normal and keeper/bench paths must
// not require bytes beyond the eleven formation coordinates.
if (detail != 0 && candidate.position() != 0) {
const int x = formation_byte(g, table + size_t(pos));
const int y = formation_byte(g, table + 0xb + size_t(pos));
position_value = detailed_position_value(value[j], candidate, x, y, detail);
}
int score = int16_t(position_value - mismatch);
if (best_score[pos] < score) {
best = j;
best_score[pos] = int16_t(score);
}
}
if (best == -1) continue;
if (type != 9) {
if (manager >= 0) {
// the chosen player gets the place on the board
board(best)[0x41] = formation_byte(g, table + size_t(pos));
board(best)[0x42] = formation_byte(g, table + 0xb + size_t(pos));
}
if (value[best] != kUnavailable) g.squad_slots.at(range.first + best) |= uint16_t(pos < 11 ? 0x8000 : 0x4000);
}
if (best != pos) {
// SquadSlotsBoardEntriesChangePlaces: squad slots and the board entries change places
std::swap(g.squad_slots.at(range.first + pos), g.squad_slots.at(range.first + best));
if (manager >= 0) std::swap_ranges(board(pos), board(pos) + 0x58, board(best));
std::swap(value[pos], value[best]);
}
}
// Int2, local_34: bit 7 requests a second pass for field rows
// 1..10. Compare reserves against each first-pass score using the base
// value and role penalty, without the detailed coordinate penalty.
// The keeper is excluded; first-eleven-only modes have no reserve range.
if (improve_from_reserves) {
for (int pos = 1; pos < 11; ++pos) {
const int type = kTypeByDepth[formation_byte(g, table + size_t(pos))];
int16_t best = best_score[pos];
int replacement = -1;
for (int row = 11; row < players; ++row) {
const int id = g.squad_slots.at(range.first + row) & 0x0fff;
if (value[row] == kUnavailable || id == 0x0fff) continue;
const int role = g.players.at(id).position();
if (role == 0) continue;
const int16_t score = int16_t(value[row] - std::abs(role - type) * weight);
if (best < score) {
replacement = row;
best = score;
}
}
if (replacement < 0) continue;
uint16_t& reserve = g.squad_slots.at(range.first + replacement);
uint16_t& field = g.squad_slots.at(range.first + pos);
reserve = uint16_t((reserve & 0x1fff) | 0x8000);
field = uint16_t((field & 0x1fff) | (replacement < 17 ? 0x4000 : 0));
std::swap(field, reserve);
if (manager >= 0) {
std::swap_ranges(board(pos), board(pos) + 0x58, board(replacement));
board(pos)[0x41] = formation_byte(g, table + size_t(pos));
board(pos)[0x42] = formation_byte(g, table + 0xb + size_t(pos));
}
std::swap(value[pos], value[replacement]);
}
}
// Indoors a human manager's first eleven play in pairs that change together: every board
// place without a partner (+0x3f = 0xFF) takes the next free one at most one field away
// (both +0x41 and +0x42), both note each other's index.
if (g.indoor && manager >= 0)
for (int i = 0; i < 10; i++) {
if (board(i)[0x3f] != 0xFF) continue;
for (int j = i + 1; j <= 10; j++) {
if (board(j)[0x3f] != 0xFF) continue;
if (std::abs(int(int8_t(board(i)[0x42])) - int8_t(board(j)[0x42])) > 1 ||
std::abs(int(int8_t(board(i)[0x41])) - int8_t(board(j)[0x41])) > 1)
continue;
board(i)[0x3f] = uint8_t(j);
board(j)[0x3f] = uint8_t(i);
break;
}
}
// OpenBMH deviates from the original: disables the foreign-player limit in the supported rule profile.
// (foreign-player limit ForeignPlayerLimitEnabled is off in the supported rule profile)
// After a full line-up every player in the eleven or on the bench notes his squad slot
// (relative to the squad start) in bits 0-4 of his card word (*PlayerCards).
if (!first_eleven_only && !g.player_cards.empty())
for (int s = 0; s < found; s++) {
const uint16_t entry = g.squad_slots.at(range.first + s);
if (entry & 0xC000) {
uint16_t& cards = g.player_cards.at(entry & 0x0FFF);
cards = uint16_t((cards & 0xFFE0) | s);
}
}
}
void auto_lineup(GameState& g, int team, int mode) {
auto_lineup_impl(g,team,mode,g.manager_of(team));
}
void auto_lineup_parked_club_source(GameState& g, int team, int mode) {
constexpr size_t record = 4*0xb0c+0x290;
if (team<0 || team>=138 || g.manager_teams.size()!=1 || g.manager_teams[0]!=kNoTeam ||
!g.memory.has(::bmh::layout::CoachActive) || g.memory.u8(::bmh::layout::CoachActive)==0 ||
!g.memory.has(::bmh::layout::ManagerCount) || g.memory.u8(::bmh::layout::ManagerCount)!=1 ||
!g.memory.has(::bmh::layout::OriginalManagerCount) || g.memory.u8(::bmh::layout::OriginalManagerCount)<1 || g.memory.u8(::bmh::layout::OriginalManagerCount)>4 ||
record+2>g.manager_records.size() ||
(int(g.manager_records[0x290]) | int(g.manager_records[0x291])<<8)!=kNoTeam ||
(int(g.manager_records[record]) | int(g.manager_records[record+1])<<8)!=team ||
g.tactics.size()<5*0x840)
throw std::invalid_argument("auto_lineup: invalid FindManagerForClub parked club context");
auto_lineup_impl(g,team,mode,4);
}
void quicksort_by_key(int16_t* items, uint32_t* keys, int count, bool ascending) {
while (count > 1) {
uint32_t pivot = keys[count >> 1];
int i = -1, j = count;
for (;;) {
if (!ascending) {
do i++; while (pivot < keys[i]);
do j--; while (keys[j] < pivot);
} else {
do i++; while (keys[i] < pivot);
do j--; while (pivot < keys[j]);
}
if (j <= i) break;
std::swap(keys[i], keys[j]);
std::swap(items[i], items[j]);
}
quicksort_by_key(items, keys, i, ascending);
items += i;
keys += i;
count -= i;
}
}
bool substitute(GameState& g, int team, int off, int mode, WatcomRandom& rand) {
if (!(team < 138 || team == kNoTeam)) return false;
const int manager = g.manager_of(team);
int used = g.team_flags.at(team) >> 5 & 7; // substitutions so far
if (mode == 10) {
// a random change of a human team only when the assistant may substitute (option 1)
if (manager >= 0 && !g.manager_option(manager, 1)) return false;
if (used >= kMaxSubstitutions - 1) return false;
}
SquadRange range = squad_range(team);
int first = int(range.first);
int last_bench = team > 0x59 ? 16 : 17;
// --- candidates on the bench ------------------------------------------------------------
int16_t slot[24];
uint32_t score[24];
int n = 0;
for (int s = 11; s < last_bench; s++) {
uint16_t entry = g.squad_slots.at(first + s);
int id = entry & 0x0FFF;
if (id == 0x0FFF) break;
const Player& p = g.players.at(id);
if (!(entry & 0x4000) || (p.w364 >> 16 & 0x1F) != 0 || (p.w364 >> 12 & 1) != 0) continue;
int type = p.position();
if (type == 0 && mode != 20) continue;
int base;
if (mode < 20) {
if (mode < 10) {
if (mode > 7) mode = 7; // the original clamps its parameter here for good
int trait = int(p.w35c >> 21 & 7);
base = 0x70 - (trait > mode ? trait - mode : mode - trait) * 16;
} else {
base = rand.range(0, 99);
}
} else {
if (off == first + s) continue;
if (mode != 20) {
int t = mode - 20;
base = 0x300 - (t > type ? t - type : type - t) * 256;
} else {
base = (type == 0) << 12;
}
}
int strength = p.strength(false); // Strength(w35c, 0)
score[n] = uint32_t(type + int16_t(base + strength) * 4);
slot[n] = int16_t(s);
n++;
}
if (n == 0) return false;
quicksort_by_key(slot, score, n);
int on = slot[0] + first;
int on_type = int(score[0] & 3);
// --- the player to take off (tactical and random changes) ------------------------------
if (mode < 20) {
n = 0;
for (int s = 0; s < 11; s++) {
uint16_t entry = g.squad_slots.at(first + s);
if (!(entry & kSlotInLineup)) continue;
const Player& p = g.players.at(entry & 0x0FFF);
int type = p.position();
// The original compares the relative slot with the absolute index of the
// substitute here, which only matters for team 0.
if (s == on) continue;
if (!(type != 0 || (on_type == 0 && rand.range(0, 3) == 0))) continue;
if (!(type == 0 || on_type != 0)) continue;
int v;
if (mode < 10) {
int trait = int(p.w35c >> 21 & 7);
v = (trait > mode ? trait - mode : mode - trait) << 5;
} else {
v = (type > on_type ? type - on_type : on_type - type) << 6;
}
uint32_t junk = uint32_t(p.form() / 3 - p.technique()) - uint32_t(p.condition());
score[n] = uint32_t(int32_t(int16_t(v + (0x14A - int16_t(junk)))));
slot[n] = int16_t(s);
n++;
}
if (n == 0) return false;
quicksort_by_key(slot, score, n);
off = slot[0] + first;
}
if (used == kMaxSubstitutions) return false;
// --- the change itself -----------------------------------------------------------------
used++;
std::swap(g.squad_slots.at(on), g.squad_slots.at(off)); // SquadSlotsBoardEntriesChangePlaces
if (manager >= 0) {
// the two tactics board slots are swapped too
auto board = g.tactics.begin() + long(size_t(manager) * 0x840);
std::swap_ranges(board + long(size_t(on - first) * 0x58), board + long(size_t(on - first + 1) * 0x58),
board + long(size_t(off - first) * 0x58));
}
g.squad_slots.at(on) &= 0x1FFF;
g.squad_slots.at(off) &= 0x1FFF;
g.players.at(g.squad_slots.at(off) & 0x0FFF).w364 |= 0x1000; // the substitute has played
g.squad_slots.at(off) |= 0x8000;
g.squad_slots.at(on) |= 0x4000;
if (manager >= 0) {
// human teams: the re-sort uses a formation after the attitude (mode / 2 for the
// tactical changes, else the manager's setting, record +0xd2): option byte 0 is set
// to 4 - attitude for the call and restored afterwards
int attitude = mode < 9 ? mode >> 1 : int8_t(g.manager_records.at(size_t(manager) * 0xB0C + 0xd2)); // (mode as clamped above)
if (attitude > 3) attitude = 3;
uint8_t& option = g.manager_options.at(size_t(manager) * 5);
const uint8_t saved = option;
option = uint8_t(4 - attitude);
auto_lineup(g, team, 0x65);
option = saved;
} else {
auto_lineup(g, team, 0x65);
}
g.team_flags.at(team) = uint16_t((g.team_flags.at(team) & 0xFF1F) | used << 5);
return true;
}
bool manual_substitution(GameState& g, int team, int field_slot, int bench_slot) {
const SquadRange range = squad_range(team);
if (field_slot < 0 || field_slot >= 11 || bench_slot < 11 || size_t(bench_slot) >= range.count) return false;
const size_t off = range.first + size_t(field_slot), on = range.first + size_t(bench_slot);
const uint16_t out = g.squad_slots.at(off), in = g.squad_slots.at(on);
if ((out & 0x0FFF) == 0x0FFF || !(out & kSlotInLineup)) return false;
// the substitute: on the bench (slot flag 0x4000) and not yet played in this match
// (w364 bit 12, set when he came on - a player taken off may not come back)
if ((in & 0x0FFF) == 0x0FFF || !(in & 0x4000) || (g.players.at(in & 0x0FFF).w364 & 0x1000)) return false;
int used = g.team_flags.at(team) >> 5 & 7;
if (used >= kMaxSubstitutions) return false;
used++;
std::swap(g.squad_slots.at(on), g.squad_slots.at(off)); // SquadSlotsBoardEntriesChangePlaces
const int manager = g.manager_of(team);
if (manager >= 0) {
// the board entries change places too, but the place on the pitch stays with the slot
auto board = g.tactics.begin() + long(size_t(manager) * 0x840);
auto a = board + long(size_t(field_slot) * 0x58), b = board + long(size_t(bench_slot) * 0x58);
const uint8_t x = a[0x41], y = a[0x42];
std::swap_ranges(a, a + 0x58, b);
a[0x41] = x, a[0x42] = y;
}
g.squad_slots.at(on) &= 0x1FFF;
g.squad_slots.at(off) &= 0x1FFF;
g.players.at(g.squad_slots.at(off) & 0x0FFF).w364 |= 0x1000; // the substitute has played
g.squad_slots.at(off) |= kSlotInLineup;
g.squad_slots.at(on) |= 0x4000;
g.team_flags.at(team) = uint16_t((g.team_flags.at(team) & 0xFF1F) | used << 5);
return true;
}
} // namespace bmh
namespace bmh {
bool initialize_pitch_set_piece_source(GameState& g, int manager_slot, int runtime_club) {
if (!pitch_context_valid(g, manager_slot, runtime_club)) return false;
const size_t rec = size_t(manager_slot) * kManagerRecordSize;
if (uint16_t(g.manager_records[rec + 0xb0a] | uint16_t(g.manager_records[rec + 0xb0b]) << 8) != 0x3253) {
g.manager_records[rec + 0xafc] = g.manager_records[rec + 0xafd] = 0;
g.manager_records[rec + 0xafe] = g.manager_records[rec + 0xaff] = 0;
g.manager_records[rec + 0xb08] = g.manager_records[rec + 0xb09] = 0;
g.manager_records[rec + 0xb0a] = 0x53; g.manager_records[rec + 0xb0b] = 0x32;
}
return true;
}
bool normalize_pitch_set_piece_source(GameState& g, int manager_slot, int runtime_club) {
if (!initialize_pitch_set_piece_source(g, manager_slot, runtime_club)) return false;
const size_t rec = size_t(manager_slot) * kManagerRecordSize;
const auto member = [&](uint16_t stored) {
if (!stored || stored > 0x0fff) return false;
const int id = int(stored) - 1;
const auto range = squad_range(runtime_club);
for (size_t i = 0; i < range.count; ++i)
if ((g.squad_slots[range.first + i] & 0x0fff) == id) return true;
return false;
};
for (size_t off : {size_t(0xafc), size_t(0xafe), size_t(0xb08)}) {
uint16_t value = uint16_t(g.manager_records[rec + off] | uint16_t(g.manager_records[rec + off + 1]) << 8);
if (!member(value)) g.manager_records[rec + off] = g.manager_records[rec + off + 1] = 0;
}
return true;
}
bool set_pitch_set_piece_taker_source(GameState& g, int manager_slot, int runtime_club,
int selector, int row, int player_id, uint16_t slot,
uint16_t expected_old_value) {
if (!pitch_context_valid(g, manager_slot, runtime_club) || selector < 2 || selector > 4 ||
row < 0) return false;
const auto range = squad_range(runtime_club);
const size_t at = range.first + size_t(row), rec = size_t(manager_slot) * kManagerRecordSize;
if (size_t(row) >= range.count || at >= range.first + range.count || g.squad_slots[at] != slot || (slot & 0xc000) == 0 ||
(slot & 0x0fff) != player_id || player_id < 0 || size_t(player_id) >= g.players.size() ||
((g.players[size_t(player_id)].w364 >> 16) & 0x1f) != 0 ||
uint16_t(g.manager_records[rec + 0xb0a] | uint16_t(g.manager_records[rec + 0xb0b]) << 8) != 0x3253)
return false;
static constexpr size_t offsets[] = {0, 0, 0xafc, 0xafe, 0xb08};
const size_t field = rec + offsets[selector];
const uint16_t current = uint16_t(g.manager_records[field] | uint16_t(g.manager_records[field + 1]) << 8);
if (current != expected_old_value) return false;
const uint16_t encoded = uint16_t(player_id + 1);
g.manager_records[field] = uint8_t(encoded); g.manager_records[field + 1] = uint8_t(encoded >> 8);
return true;
}
bool auto_pitch_set_piece_takers_source(GameState& g, int manager_slot, int runtime_club,
const std::array<uint16_t, 3>& expected_old_values) {
if (!pitch_context_valid(g, manager_slot, runtime_club)) return false;
const size_t rec = size_t(manager_slot) * kManagerRecordSize;
if (uint16_t(g.manager_records[rec + 0xb0a] | uint16_t(g.manager_records[rec + 0xb0b]) << 8) != 0x3253)
return false;
static constexpr size_t offsets[] = {0xafc, 0xafe, 0xb08};
for (size_t i = 0; i < 3; ++i) {
const auto off = offsets[i];
if (uint16_t(g.manager_records[rec + off] | uint16_t(g.manager_records[rec + off + 1]) << 8) != expected_old_values[i])
return false;
}
for (const auto off : offsets) g.manager_records[rec + off] = g.manager_records[rec + off + 1] = 0;
return true;
}
bool set_player_order_source(GameState& g, int manager_slot, int runtime_club, int row, int player, int aspect, int value) {
if (manager_slot < 0 || size_t(manager_slot) >= g.manager_teams.size() || g.manager_teams[size_t(manager_slot)] != runtime_club ||
aspect < 0 || aspect > 3 || row < 0 || row >= 24)
return false;
const SquadRange range = squad_range(runtime_club);
if (size_t(row) >= range.count || range.first + size_t(row) >= g.squad_slots.size()) return false;
const uint16_t slot = g.squad_slots[range.first + size_t(row)];
// only a starter on the pitch can be selected in the ORDER view
if ((slot & 0x0fff) != uint16_t(player) || !(slot & 0x8000)) return false;
const size_t at = size_t(manager_slot) * 0x840 + size_t(row) * 0x58 + 2 + size_t(aspect);
if (at >= g.tactics.size()) return false;
g.tactics[at] = uint8_t(std::clamp(value, kOrderMin, kOrderMax)); // ClampInteger(&v, 2, 0x28)
return true;
}
} // namespace bmh
+116
View File
@@ -0,0 +1,116 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// OpenBMH deviates from the original: disables the foreign-player limit and supports owner-bound designated set-piece selection.
// Automatic line-up of computer teams, port of Int2.
//
// The squad of a team is a run of squad slots (squad_range). The first 11 slots are the
// starting line-up in formation order (slot i plays at formation position i, see
// GameState::formation_position), the following slots are the bench and reserves.
// Slot flags: 0x8000 in the starting line-up, 0x4000 on the bench.
//
// The optimiser draws no random numbers. For every fit player (no injury, w364 bits
// 16-20 zero) it computes a base value
// value = condition + technique + form / 3
// and then fills the positions one after another: position p takes the remaining player
// with the best value - mismatch, where mismatch is
// 0 for bench slots of type 9 (reserves)
// 64 * 25 if exactly one of player and position is a goalkeeper
// 64 * |player position - position type| otherwise
// Position types come from the formation depth for the first 11 slots (table layout field:
// 0 goalkeeper, 1 defence, 2 midfield, 3 attack) and from table layout field for the bench.
// The chosen player is swapped into slot p and flagged 0x8000 (slots 0-10) or 0x4000.
//
// Ported: assistant training-camp familiarity penalty and detailed position scoring at
// difficulty >= 6. The foreign-player limit (ForeignPlayerLimitEnabled) is off in supported rule profile.
#include <cstdint>
#include <array>
#include "game/random.hpp"
#include "game/state.hpp"
namespace bmh {
// Games: in-place quicksort (Hoare partition, middle element as pivot) of `keys`
// descending (ascending if `ascending`), comparing as unsigned 32-bit, moving `items`
// along. Ported exactly because the order of equal keys depends on the algorithm.
void quicksort_by_key(int16_t* items, uint32_t* keys, int count, bool ascending = false);
// Maximum number of substitutions per match (CareerSession_DispatchLiveSubstitution_ExecutableField).
constexpr int kMaxSubstitutions = 3;
// Injure: substitution for a computer team.
// off absolute squad slot of the player to take off, used only for mode >= 20
// mode < 10 tactical change towards trait value `mode` (w35c bits 21-23)
// 10 random change (called during the match), keeps the last substitution
// for emergencies
// 20+t replace the player in `off` (injured or booked) by a bench player of
// position type t (t = 0 prefers a goalkeeper)
// Picks the best fit bench player (not injured, not yet played), for modes < 20 also the
// player to take off, swaps them, re-sorts the eleven (auto_lineup mode 0x65) and counts
// the substitution in the team flags (bits 5-7). Returns false if nothing was changed.
// Draws from `rand` like the original.
bool substitute(GameState& g, int team, int off, int mode, WatcomRandom& rand);
// A substitution the manager makes himself during his live match (the line-up screen
// PitchScreen opened from the match, "AUFSTELLUNG AUTO"): the player in line-up slot
// `field_slot` (0-10, relative to the squad) leaves, the bench player in `bench_slot` (11..)
// takes his place on the pitch and on the tactics board (the place, board bytes
// 0x41/0x42, stays with the slot). The flags and the counter are those of `substitute`:
// the incoming player has played (w364 bit 12), the slots get 0x8000 / 0x4000, the team flags
// count the change. Returns false (nothing changed) for an empty or not lined-up field slot,
// a bench player who already played or after kMaxSubstitutions. Rate the side again
// afterwards (MatchEngine::rerate_team). No random numbers.
bool manual_substitution(GameState& g, int team, int field_slot, int bench_slot);
// mode as in the original: < 100 only re-sorts the current first 11 slots (used right
// before a match, AutoLineup), 100 picks from the whole squad, 101 (0x65) re-sorts the
// first 11 after a substitution. Bit 0x80 additionally improves field rows 1-10
// from the reserves after the first positional selection, as in the original.
void auto_lineup(GameState& g, int team, int mode);
// Explicit FindManagerForClub record4 lookup for the club parked during a national
// takeover. Validate the raw record/board; never extend the active manager list.
void auto_lineup_parked_club_source(GameState& g, int team, int mode);
// PrepareLineupEntry: re-flag the already chosen field and bench rows on lineup-screen entry.
// This does not rank, replace or otherwise choose players and consumes no RNG.
void prepare_lineup_entry(GameState& g, int team);
// Deterministic Source pitch actions for a live, mode-bound human-manager
// desk (outdoor or indoor). Each helper stages the complete GameState and returns
// true only after a complete Source action can be committed; false is a
// neutral rejection with Native state untouched. None consumes W/G RNG.
// The caller still owns active-screen, revision, prepared-entry and ACK checks.
bool set_pitch_automatic_weight_source(GameState& g, int manager_slot, int runtime_club,
int weight_index, uint8_t old_weights, uint8_t new_weights);
bool move_pitch_player_source(GameState& g, int manager_slot, int runtime_club,
int row, int player_id, uint16_t slot,
int old_depth, int old_lane, int new_depth, int new_lane);
bool apply_pitch_formation_source(GameState& g, int manager_slot, int runtime_club,
int formation, uint8_t expected_weights);
bool save_pitch_formation_source(GameState& g, int manager_slot, int runtime_club,
int formation, uint8_t expected_weights,
const std::array<uint8_t, 22>& formation_positions);
// OpenBMH deviates from the original: disables the foreign-player limit and supports owner-bound designated set-piece selection.
// supported rule profile NormalizePitchSetPieceSource/NormalizePitchSetPieceSource3/NormalizePitchSetPieceSource2/NormalizePitchSetPieceSource4: deterministic, owner-bound
// set-piece presentation state. Stored takers are player_id+1; zero is AUTO.
bool normalize_pitch_set_piece_source(GameState& g, int manager_slot, int runtime_club);
bool initialize_pitch_set_piece_source(GameState& g, int manager_slot, int runtime_club);
bool set_pitch_set_piece_taker_source(GameState& g, int manager_slot, int runtime_club,
int selector, int row, int player_id, uint16_t slot,
uint16_t expected_old_value);
bool auto_pitch_set_piece_takers_source(GameState& g, int manager_slot, int runtime_club,
const std::array<uint16_t, 3>& expected_old_values);
// ORDER (PitchScreen with desk flag 0x20, H2 p. 43): the four instructions of a starter on
// the tactics board, bytes +2..+5 - 0 defensive/offensive, 1 running, 2 commitment, 3 fighting
// (the live scene reads +5, rating.cpp). A click in a bar sets the value from the mouse
// position or moves it by one; ClampInteger keeps it within 2..40. `row` is the board/squad
// row of the manager's club, `player` its expected player. Returns false (nothing changed)
// for a stale or invalid request.
constexpr int kOrderMin = 2, kOrderMax = 40;
bool set_player_order_source(GameState& g, int manager_slot, int runtime_club, int row, int player, int aspect, int value);
} // namespace bmh
+166
View File
@@ -0,0 +1,166 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "game/match.hpp"
#include <cstdlib>
#include <stdexcept>
#include "game/rating.hpp"
#include "game/schedule.hpp"
namespace bmh {
namespace {
// Average monthly temperature in °C, indexed directly by CareerSession_PairingsRuntimeDraw_ExecutableField5 (1-12; table at
// MatchRuntimeField4, 13 entries; the month code indexes it directly, not modulo 12).
constexpr int8_t kMonthTemperature[13] = {2, 0, 8, 12, 15, 21, 26, 26, 18, 11, 6, 2, 0};
// Temperature offset of a team's home region (table at MatchRuntimeField3, index = team_region()):
// 0 top leagues, 1-4 regional leagues, from 10 on the foreign countries (7 clubs each).
// The last entries lie beyond the table in the original and are kept as found there.
constexpr int8_t kRegionTemperature[48] = {0, -1, 5, 0, 0, 5, 0, -1, -5, -4, -2, 0, 0, -3, -1, -1,
-1, 6, 6, 4, -3, 4, -6, 7, 0, 0, 0, 0, 0, 2, 0, -3,
8, 8, 8, 8, 10, 9, 3, 11, -29, 15, 10, 0, -27, 15, 10, 0};
// Crowd factor per league in thousands (table at layout field): the home side gets its bonus if
// the attendance exceeds a random value in [factor * 1000 + 3000, factor * 1000 + 6000].
constexpr uint8_t kLeagueCrowd[10] = {27, 12, 7, 7, 3, 27, 27, 27, 27, 27};
// First league that counts as a regional league (LeaguePairings_LeaguePairingsConstants_RuntimeField).
constexpr int kFirstRegionalLeague = 5;
// Number of cup-only teams before the amateur blocks (CareerSession_InstallLeagueSizes_RuntimeField6).
constexpr int kCupTeams = 30;
int clamp(int v, int lo, int hi) { return v < lo ? lo : v > hi ? hi : v; }
// BuildSideRecords2 evaluated at kick-off (score 0:0, minute 0) for a computer team:
// start from 2 (home) or 1 (away), one step more defensive if the opponent's attack/
// midfield value (byte 2) is more than 10 higher, one step more offensive if it is more
// than 10 lower - but only for match_index != 0 (the original compares the match index
// where the minute was probably meant). A 1/201 roll picks a special event code that is
// not stored.
int initial_attitude(const SideRecord& own, const SideRecord& other, int side, int match_index, WatcomRandom& rand) {
int substitution = -1; // cannot happen at minute 0
return attitude_update(own.b.data(), other.b.data(), side, match_index, 0, 0, 0, rand, substitution);
}
} // namespace
int attitude_update(const uint8_t* own, const uint8_t* other, int side, int match_index, int own_goals, int opp_goals,
int minute, WatcomRandom& rand, int& substitution_mode) {
int own2 = int8_t(own[2]), other2 = int8_t(other[2]);
int base = 2 - side;
if (own2 + 10 < other2) base = 1 - side;
int low = base; // attitude (low byte of uVar5 in the original)
int high = 0; // "special" code (high byte), only used for the substitution request
if (other2 < own2 - 10 && match_index != 0) low = base + 1;
if (own_goals < opp_goals && opp_goals - 2 <= own_goals) { // behind by one or two
low = low + 1 + (minute > 80 ? 1 : 0);
high = minute > 80 ? 8 : 6;
}
if (opp_goals < own_goals && own_goals - 1 <= opp_goals) { // ahead by one
if (minute > 75) low--;
if (own2 < other2 || (match_index != 0 && minute > 80)) low--;
high = minute > 80 ? 1 : 3;
}
low = int8_t(low);
if (low < 0) low = 0;
if (low > 3) low = 3;
if (high == 0 && rand.range(0, 200) == 0) high = 0x0B;
substitution_mode = -1;
if (minute > 60 && high != 0 && rand.range(0, 60) == 0) substitution_mode = high - 1; // Injure(team, 0, high - 1)
return low;
}
int region_temperature(int region) { return region >= 0 && region < 48 ? kRegionTemperature[region] : 0; }
int month_temperature(int month) { return kMonthTemperature[month >= 0 && month <= 12 ? month : 0]; }
int team_region(int team) {
if (team == kNoTeam) return 0;
int t = team;
for (int league = 0; league < kLeagueCount; league++) {
t -= kLeagueSizes[league];
if (t < 0) return league >= kFirstRegionalLeague ? league - kFirstRegionalLeague + 1 : 0;
}
if (t - kCupTeams >= 0) return (t - kCupTeams) / 7 - kFirstRegionalLeague + 10;
return 0;
}
void rate_side(GameState& g, const MatchSetup& m, int side, int previous6, WatcomRandom& rand, uint8_t* r, GameRandom* game) {
int team = side ? m.away : m.home, opponent = side ? m.home : m.away;
const int manager = g.manager_of(team); // local_14
// (the original also has a special case for the pseudo team 0x165 of a human manager,
// which does not play league or cup matches)
// --- modifier for byte 2 ---------------------------------------------------------------
int modifier = 0;
if (side != 0 && m.climate_effect) {
int region = team_region(team);
if (region != team_region(opponent)) {
int expected = rand.range(0, 6) + month_temperature(m.month) + region_temperature(region) - 3;
// Abs2 on the temperature byte read unsigned (frost counts as 200+)
int deviation = std::abs(int(uint8_t(m.temperature)) - expected);
// The original subtracts byte 6 of the record MatchRuntimeField points to at that
// moment, both operands as signed chars (a balance above 127 counts negative).
modifier = int8_t(int8_t(deviation / 2) - int8_t(previous6));
}
}
if (side == 0) {
int league = team > 0x164 ? 0 : team_league(team); // TeamLeague2
int base = kLeagueCrowd[league < 10 ? league : 9] * 1000;
if (unsigned(rand.range(base + 3000, base + 6000)) < unsigned(m.spectators)) {
// a human manager's side with record +0x289 set suffers more from a full house
modifier -= manager >= 0 && g.manager_records.at(size_t(manager) * 0xB0C + 0x289) != 0 ? 9 : 6;
}
}
modifier = clamp(int8_t(modifier), -10, 10);
// --- Uint8T3: ratings, fit-player scaling, balance ------------------------------
// one context for all six profiles: profiles 4 and 5 see the stale technique of profile 3
RatingContext weather{g.chance_rain, g.chance_temperature};
weather.rand = &rand; // clubs without squad draw their ratings
weather.game = game; // human teams: motivation draws
weather.live_scene = g.live_scene;
for (int i = 0; i < 6; i++) r[i] = uint8_t(team_rating(g, team, kRatingProfiles[i], weather));
using namespace avg;
TeamAverage condition = team_average(g, team, LINEUP_ONLY | ALL_POSITIONS | CONDITION, &rand);
TeamAverage technique = team_average(g, team, LINEUP_ONLY | ALL_POSITIONS | TECHNIQUE, &rand);
int players = technique.players; // count of the last call, like local_10
if (players < 11 && players > 2)
for (int i = 1; i < 4; i++) r[i] = uint8_t((players - 3) * r[i] / 10);
r[6] = uint8_t(clamp((condition.value - technique.value) * 4 + 100, 0, 200));
r[2] = uint8_t(clamp(r[2] - modifier, 0, 99));
// (the original lets two cheat codes, CareerSession_FormatError_RuntimeField9, set a human side's six ratings to
// fixed values; not ported)
if (manager < 0) {
int rhythm = r[6] >> 1; // computer teams: half the balance, at least 50
r[7] = uint8_t(rhythm < 50 ? 50 : rhythm);
} else {
// human teams: record +0xd9 (signed) * 5 plus the balance, scaled to 0-100
const int8_t d9 = int8_t(g.manager_records.at(size_t(manager) * 0xB0C + 0xd9));
r[7] = uint8_t((d9 * 5 + r[6]) * 100 / 0xFF);
}
}
std::array<SideRecord, 2> build_side_records(GameState& g, const MatchSetup& m, WatcomRandom& rand, GameRandom* game) {
std::array<SideRecord, 2> rec{};
int previous6 = 0; // byte 6 of the record built last (MatchRuntimeField still points to it)
for (int side = 0; side < 2; side++) {
SideRecord& r = rec[side];
rate_side(g, m, side, previous6, rand, r.b.data(), game);
previous6 = r.b[6];
// --- BuildSideRecords2 at 0:0 ----------------------------------------------------------
// Bug in the original: for the home side the away record is not built yet. The 18
// bytes come from malloc without clearing (ManagerOf2 flag 0), so the home side
// compares against leftover heap contents. That cannot be derived from the game
// state; OpenBMH uses a cleared record (0) as a deterministic stand-in.
const int manager = g.manager_of(side ? m.away : m.home);
if (manager >= 0 && !g.manager_option(manager, 2))
r.b[8] = g.manager_records.at(size_t(manager) * 0xB0C + 0xd2); // the manager's own setting
else
r.b[8] = uint8_t(initial_attitude(r, rec[1 - side], side, m.match_index, rand));
}
return rec;
}
} // namespace bmh
+132
View File
@@ -0,0 +1,132 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// Match simulation - structure of the original, port in progress.
//
// This header records what is known about the original's match engine so the port can
// follow it step by step. Everything below refers to BMH.exe V2.24 function addresses.
//
// ---------------------------------------------------------------------------------------
// Matchday flow (FinishEvent)
// ---------------------------------------------------------------------------------------
// 1. For every competition playing today a "match group" descriptor (0xD0 bytes, up to 6
// in table MatchdayGroupDescriptors) is set up by FixturesFromGenerateFixtures: the fixtures from generate_fixtures(),
// the number of matches, and a pointer to the result bytes in block LeagueResults.
// 2. Per match an 18-byte record is allocated (two 9-byte "side" records, home first)
// and filled by BuildSideRecords3 (see "Side record").
// 3. Teams with fewer than 8 fit players lose 0:2 and are fined 200 000.
// 4. The match loop EndPhase(first_minute, last_minute, max_stoppage, phase) runs
// for 1..45, 46..90 (+ up to 4 minutes stoppage), and for cup ties 91..105 and
// 106..120. Indoor tournaments (CareerSessionRuntimeField set) play 1..20 and 21..40.
//
// ---------------------------------------------------------------------------------------
// Side record (9 bytes per team and match, BuildSideRecords3 / Uint8T3)
// ---------------------------------------------------------------------------------------
// [0..5] six ratings from TeamRating(team, weight table at layout field + i * 10): the
// line-up is walked, every player adds a position-dependent value to one of
// 4 x 3 buckets (goalkeeper / defence / midfield / attack x left/centre/right),
// the buckets are weighted and averaged; result capped at 110.
// [1..3] are scaled by (players - 3) / 10 if fewer than 11 players are fit.
// [2] additionally reduced by a home/away and fatigue modifier clamped to -10..+10.
// [6] (avg condition - avg technique) * 4 + 100, clamped 0..200
// (team_average with flags 0x1F1 and 0x1F2).
// [7] human teams: (manager bonus * 5 + [6]) * 100 / 255, else [6] / 2 (min 50);
// clamped to 44..80 where it is used as the chance rhythm (MatchRuntimeField2).
// [8] read as "local_a4" together with byte 0x11 of the other side.
//
// ---------------------------------------------------------------------------------------
// Per minute, per match, per side (EndPhase, around 0x382xx)
// ---------------------------------------------------------------------------------------
// - After the regular time every running match ends with probability 1/2 per minute
// (Watcom rand, WatcomRandom::range(0, 1)).
// - Random events (injuries, cards) are triggered with WatcomRandom::range(0, 220) <
// rhythm - 30 and EventImpl.
// - Chance roll: GameRandom::range(0, pressure * 4 + 44) compared against
// side[8] + other[0x11] + 3 + 14 * indoor; above means no chance this minute.
// - Otherwise the chance quality is built from side[2], GameRandom::range(0, rhythm) / 10,
// minute dependent bonus GameRandom::range(6, 12) while minute < side[6] (50..130),
// the opponent's [0xB] and [0xF] bytes and GameRandom::range(0, 100); the difference
// indexes the table at layout field (index 5..24) which gives the goal threshold, tested
// against GameRandom::range(0, pressure * 4 + 56).
//
// ---------------------------------------------------------------------------------------
// Randomness and reproducibility
// ---------------------------------------------------------------------------------------
// Goals are decided by GameRandom (GameRandom), but its seed comes from
// CurrentMatchday = WatcomRandom::range(0, 10000) (AdvanceTurn) or the saved CareerSession_Invalid_RuntimeField2,
// and WatcomRandom (seeded from the clock at program start) also decides stoppage time
// and random events. A matchday can therefore only be reproduced bit-exactly when both
// generator states at kick-off are known (e.g. read from memory in the DOSBox debugger).
#include <array>
#include <cstdint>
#include "game/random.hpp"
#include "game/state.hpp"
namespace bmh {
// The 9-byte record of one team in one match (see "Side record" above).
struct SideRecord {
std::array<uint8_t, 9> b{};
uint8_t goalkeeping() const { return b[0]; }
uint8_t attitude() const { return b[8]; } // 0 defensive .. 3 all-out attack
};
// Per-match input of the side record setup that comes from the match group descriptor.
struct MatchSetup {
int home = 0, away = 0; // team ids
int match_index = 0; // position inside the match group (affects the attitude quirk)
bool climate_effect = false; // descriptor flag bit 1 (set for league matchdays)
int temperature = 0; // descriptor byte 0x30 + match: temperature at the venue in °C
int spectators = 0; // result of the spectator calculation (Attendance)
int month = 0; // CareerSession_PairingsRuntimeDraw_ExecutableField5, index into the monthly temperature table
};
// Builds both side records of a match like BuildSideRecords does at kick-off: for the home
// side and then the away side it runs BuildSideRecords3 (ratings, home/climate modifier,
// condition-technique balance, rhythm) followed by BuildSideRecords2 at 0:0 (initial attitude).
// Order matters: the home attitude is computed while the away record is still empty.
//
// Draws from `rand` exactly like the original (home bonus roll, climate roll for away
// teams from other regions, and the 1/201 attitude roll per side). Teams of human
// managers also draw from `game` (see team_rating) and may keep their own attitude.
std::array<SideRecord, 2> build_side_records(GameState& g, const MatchSetup& m, WatcomRandom& rand,
GameRandom* game = nullptr);
// BuildSideRecords3 for one side: recomputes bytes 0-7 of a side record (byte 8, the attitude,
// is left alone). Used at kick-off and during the match after line-up changes.
// previous6 byte 6 of the record MatchRuntimeField points to when the original calls it
// (at kick-off the previously built record, during the match the side's own)
void rate_side(GameState& g, const MatchSetup& m, int side, int previous6, WatcomRandom& rand, uint8_t* record,
GameRandom* game = nullptr);
// Attitude of a computer team (BuildSideRecords2), 0 defensive .. 3 all-out attack.
// own/other the two side records (byte 2 = attack/midfield strength is compared)
// side 0 home, 1 away (home starts one step more offensive)
// match_index position in the match group; the "much stronger" step is skipped for
// match 0 (the original tests the match index where the minute was meant)
// own_goals/opp_goals, minute: behind by 1-2 -> +1 (+2 after minute 80),
// ahead by 1 -> -1 after minute 75, another -1 if weaker or late
// Draws from `rand`: 1/201 "special" roll when no score rule applied, and after minute 60
// a 1/61 roll that asks for a substitution: substitution_mode is then the mode for
// substitute() (special code - 1), otherwise -1.
int attitude_update(const uint8_t* own, const uint8_t* other, int side, int match_index, int own_goals, int opp_goals,
int minute, WatcomRandom& rand, int& substitution_mode);
// OpenBMH deviates from the original: uses the enhanced injury selection and suspension rules.
// InjurePlayer(slot, type, match, manager) with its supported rule profile continuation: injures the
// player in the absolute squad slot. The type passed in is replaced by a drawn one
// (WatcomRandom(0, 999)); returns the type. A human manager's club doctor shortens the
// absence. Players with w364 bits 13-15 set are protected.
int injure_player(GameState& g, int slot, int type, bool match, int manager, WatcomRandom& rand);
// Region of a team for the climate effect (TeamRegion): 0 for the top five leagues,
// 1..4 for the four regional leagues, higher values for amateur teams (7 per region).
int team_region(int team);
// Temperature offset of a region (MatchRuntimeField3[region]) and the average temperature of a
// month (MatchRuntimeField4[CareerSession_PairingsRuntimeDraw_ExecutableField5]).
int region_temperature(int region);
int month_temperature(int month);
} // namespace bmh
File diff suppressed because it is too large. Load diff
+270
View File
@@ -0,0 +1,270 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#pragma once
// Minute-by-minute match simulation, port of the match loop EndPhase.
//
// A matchday consists of up to six match groups (one per competition). Every minute the
// original walks all groups, all matches of a group and both sides of a match:
//
// 1. End of match: after the regular time (last_minute) each running match ends with
// probability 1/2 per minute (WatcomRandom), at last_minute + stoppage at the latest.
// At the end of the first half (minute 45 with no stoppage) this also ends the half.
// 2. Per side, event roll: WatcomRandom::range(0, 220) < rhythm - 30 (indoor:
// range(0, 10) > 7) calls the foul/card/injury routine EventImpl.
// 3. Per side, chance roll: GameRandom::range(0, 44 + 4 * away_penalty) must not exceed
// home attitude + away attitude + 3 (+14 indoor). away_penalty is 1 for the away
// side on league matchdays (descriptor flag bit 1), else 0.
// 4. Chance quality from the side records, the opponent's defence and randomness
// decides via the table at layout field whether a real chance arises; then the kind of
// chance (normal, penalty 1/6, free kick 1/7), shooter and assistant (PickTaker),
// the goalkeeper and finally the goal roll.
//
#include <cstddef>
#include <cstdint>
#include <functional>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "formats/binary.hpp"
#include "game/presentation.hpp"
#include "game/random.hpp"
#include "game/reality_scene.hpp"
#include "game/state.hpp"
namespace bmh {
struct PhaseResultRequest;
// One match group (the original's 0xD0-byte descriptor at MatchdayGroupDescriptors + group * 0xD0 plus the
// heap arrays it points to).
struct MatchGroup {
Bytes desc; // raw descriptor, per-match bytes at 0x10/0x30/0x50
std::vector<int> fixtures; // home, away team id per match (descriptor +0x7c)
std::vector<uint8_t> results; // league: home << 4 | away per match (descriptor +0x08)
// Cups have no league result pointer; each match has a u16 instead (descriptor +0x80,
// one array per leg): bits 0-4 away goals, 5-9 home goals, 10-15 phase
// (0 regular time, 1 extra time). 0xCCCC = not played. See MatchScore.
std::vector<uint16_t> cup_results;
// Two-legged ties: the other leg (descriptor +0x84, its match order follows this leg).
std::vector<uint16_t> cup_other_leg;
// Where the result arrays live in the original (LE addresses, 0 = none): +0x80, +0x84.
uint32_t cup_result_address[2] = {0, 0};
int phase = 0; // param_4 of EndPhase, stored with cup goals
std::vector<uint8_t> records; // 18 bytes per match (descriptor +0x0c)
std::vector<uint8_t> end_minute; // minute a match ended (descriptor +0x04)
std::vector<uint32_t> spectators; // attendance per match (descriptor +0xb4)
std::vector<uint16_t> log; // event log (Matches, descriptor +0x98)
uint32_t ended = 0; // matches ended in the current phase (local_dc)
uint32_t kickoff_void_mask = 0; // local_70: fixtures excluded from all post-match effects
int matches() const { return int(fixtures.size() / 2); }
uint8_t flags() const { return desc.at(1); }
uint32_t void_mask() const { return le32(desc, 0xb8); } // matches not played (b6424)
};
struct MinuteReport {
bool unsupported = false;
std::string reason; // first unsupported path taken
void fail(const std::string& why) {
if (!unsupported) reason = why;
unsupported = true;
}
};
// Exact Source event which requests the watched manager's live line-up (PitchScreen).
// The identity is captured after the event has changed the slot, before play resumes.
struct LiveMatchEvent {
size_t group_index = 0;
int match_index = -1;
int side = -1;
int team = -1;
int opponent = -1;
int player = -1;
int kind = -1; // 1 straight red, 2 injury
int minute = 0; // MatchEngine minute is already 1-based; Source receives minute+1.
int manager_slot = -1;
};
// BallFrameCount: an already computed Watcom ball position, at the synchronous
// chance presentation boundary. Observers receive no mutable engine references.
struct LiveBallEvent {
int minute = 0;
int group = 0;
int match = 0;
int displacement = 0; // home positive, away negative; a goal uses +/-52
};
enum class LiveChanceStage { preview, result };
// Read-only Source chance presentation. The preview precedes the score write;
// the result follows the optional shot/set-piece RNG path. Neither hook decides play.
struct LiveChanceEvent {
LiveChanceStage stage = LiveChanceStage::preview;
int minute = 0, group = 0, match = 0, side = 0, kind = 0;
int shooter = 0xfff, assistant = 0xfff, distance = 0;
bool goal = false, ticker = false, deflected = false;
};
// SetPieceAnimation/Range4: retain the picture values from the existing
// Watcom draws. A presenter cannot change the shot or draw additional randomness.
struct LiveShotEvent {
int minute = 0, group = 0, match = 0, acting_side = 0;
int lane = 0, height = 0, end_lane = 0, end_height = 0, keeper_delay = 0;
bool miss = false, mirror_sprites = false;
};
struct LiveSetPieceDraw { int low = 0, high = 0, value = 0; };
// An owned observation of the existing LiveSetPieceFrames draws. The UI replays these
// values to reconstruct figures; it has no GameRandom/WatcomRandom reference.
struct LiveSetPieceEvent {
int minute = 0, group = 0, match = 0, source_side = 0, kind = 0, distance = 0;
std::vector<LiveSetPieceDraw> draws;
};
// EventImpl/SDLPumpEvents presentation, after the card/injury is recorded and before
// substitution decisions. Source kind: 0 yellow, 1 red, 2 injury, 3 second yellow.
struct LiveBookingEvent {
int minute = 0, group = 0, match = 0, side = 0, kind = 0;
int team = -1, player = 0xfff, season_yellows = 0, ban = 0;
};
enum class LiveShootoutStage { start, preview, end };
// CupTie2/PenaltyShootout: header/text before each existing kick and after the lottery.
// Scores are owned presentation values; observers cannot write cup results.
struct LiveShootoutEvent {
LiveShootoutStage stage = LiveShootoutStage::start;
int minute = 0x79, group = 0, match = 0, side = 3, player = 0xfff;
int home_goals = 0, away_goals = 0, round = 0, of = 5;
};
// EventImpl(slot,1,side) stores this request in bdb14/16/18 rather than opening
// a screen or substituting during a Reality scene. The scene owner must drain
// it after the scene ends (RealityReporterPanel). No request means those globals stay put.
struct DeferredRealityChange {
bool human = false;
int team = -1; // opponent for a human request, own team for automatic
int slot = -1; // absolute squad slot; Source 0xff for a human request
int mode = -1; // position+20 for automatic; manager index for human
};
struct ForcedMatchEvent {
uint8_t code = 0; // Source return: yellow=1, straight red=3, second yellow=2;
// bit7 requests the watched human's post-scene screen
std::optional<DeferredRealityChange> change;
};
enum class LiveRealityStage { begin, round, settling, end };
// Owned Source observation: presentation receives neither RNG nor mutable scene.
// A true round response requests Source's post-animation exit boundary.
struct LiveRealityEvent {
LiveRealityStage stage = LiveRealityStage::begin;
int minute = 0, group = 0, match = 0, side = 0;
RealitySceneTick tick;
};
struct MatchEngine {
MatchEngine(GameState& s, std::vector<MatchGroup>& gr, GameRandom& gm, WatcomRandom& r, std::vector<uint8_t> refs)
: state(s), groups(gr), game(gm), rand(r), referees(std::move(refs)), last_pick_quality(s.last_pick_quality) {}
GameState& state;
std::vector<MatchGroup>& groups;
GameRandom& game;
WatcomRandom& rand;
std::vector<uint8_t> referees; // RefereeProperties, bits 3-4: strictness (from M3D.MAN)
bool indoor = false; // CareerSessionRuntimeField: adds 14 to the chance threshold
bool alternate_event_roll = false; // AlternateEventRoll: alternative event roll range(0, 10) > 7
bool match_events_disabled = false; // MatchEventsDisabled: disables the foul/event routine
bool live_scene_visible = false; // LiveSceneVisible (live scene enabled)
bool live_desk_disabled = false; // LiveDeskDisabled: no live desk (both live modes off)
int month = 0; // CareerSession_PairingsRuntimeDraw_ExecutableField5, for the climate effect when re-rating
bool trace = false; // print events and chances to stderr (debugging)
// What the original would show (presentation.hpp); filled only when set. Appending
// draws no random numbers and changes nothing else.
std::vector<ShowEvent>* show = nullptr;
// The substitution screen (PitchScreen) a watched human team gets after a red card or an
// injury when the assistant may not substitute. An installed live_event presenter handles
// that boundary synchronously; leave_screens preserves the legacy headless path.
bool leave_screens = false;
// Synchronous Source presenter for an actual red-card/injury event. While this runs,
// MatchEngine::event and the outer minute loop retain references into `groups`;
// implementations must not replace, resize, reorder, or otherwise invalidate that
// vector or its MatchGroup objects. The supported live scope mutates only match/player
// state and restores group contents in place on abort. Empty keeps the existing
// leave_screens/headless behavior.
std::function<void(const LiveMatchEvent&)> live_event;
std::function<void(const LiveBallEvent&)> live_ball;
std::function<void(const LiveChanceEvent&)> live_chance;
std::function<void(const LiveShotEvent&)> live_shot;
std::function<void(const LiveSetPieceEvent&)> live_set_piece;
std::function<void(const LiveBookingEvent&)> live_booking;
std::function<void(const LiveShootoutEvent&)> live_shootout;
// Source sound IDs only, emitted at actual presentation boundaries. This
// observer has no access to game/random generators and never decides play.
std::function<void(uint8_t)> original_sound;
const LeImage* reality_rules = nullptr; // borrowed executable, stable during minute()
std::function<bool(const LiveRealityEvent&)> live_reality;
// EndPhase's existing group result barrier, before its single Source ACK.
// A presenter receives owned scores and const context, never either RNG.
std::function<void(const PhaseResultRequest&, const std::vector<MatchGroup>&,
const GameState&)> phase_results;
// Button settings of the desk (block LeaguePresentationOptions, 0xb4 bytes, saved in the .FBM and the .EIN
// files); several switch live-match animations that draw random numbers.
std::vector<uint8_t> buttons;
int button(uint32_t address) const {
return buttons.empty() ? 0 : buttons.at(address - ::bmh::layout::LeaguePresentationOptions);
}
// Simulates one minute of the phase [first_minute, last_minute + stoppage].
MinuteReport minute(int minute, int last_minute, int stoppage);
// CupTie2 for match m of a group whose tie is level after extra time: the
// penalty shoot-out (PenaltyShootout, kicks Range5); the result is stored with
// phase 2. A match shown live (or in the ticker) animates every kick.
void penalty_shootout(MatchGroup& g, int m, MinuteReport& report);
// EndPhase after the line-up or substitution screen the manager opened during his live
// match (RerateTeam / PitchScreen): his side of that match is rated again
// (BuildSideRecords3). The changes themselves are made on the state before.
void rerate_team(int team, MinuteReport& report);
// Real card effects for the selected Reality offender. Mode1 skips the
// injury roll and random slot selection, suppresses booking message boxes,
// and defers changes. `g` must be a stable member of `groups` as for minute().
ForcedMatchEvent forced_event(MatchGroup& g, int m, int side, int minute,
int absolute_slot, MinuteReport& report);
// Source scene generators shared by live chances and ShotAnimation replay.
// They own the Watcom draws; UI consumers receive immutable observations.
void shot_animation(bool miss, bool follow_up, int acting_side, int group, int match, int minute); // SetPieceAnimation
void set_piece_animation(int kind, int distance, int side, int group, int match, int minute); // LiveSetPieceFrames
private:
void side(MatchGroup& g, int m, int& side, int minute, int& own_attitude, int& opp_attitude, MinuteReport& report);
void event(MatchGroup& g, int m, int side, int minute, MinuteReport& report); // EventImpl
ForcedMatchEvent event_impl(MatchGroup& g, int m, int side, int minute,
int fixed_slot, MinuteReport& report);
bool substitute(int team, int off, int mode, MinuteReport& report); // Injure
bool injure(int slot, bool match, int manager, MinuteReport& report); // InjurePlayer
void rerate(MatchGroup& g, int m, int side, MinuteReport& report); // BuildSideRecords3
int pick_player(int team, int mode, int exclude, MinuteReport& report, int preset = -1); // PickTaker
int pick_taker(int team, int mode, int exclude, int kind, MinuteReport& report); // DesignatedSlot
int designated_slot(int team, int offset, int exclude) const; // Emit
// the match the next ShowEvent belongs to (set where a side, an event or a shoot-out
// starts)
int show_group = 0, show_match = 0, show_minute = 0;
void emit(ShowEvent e) {
if (!show) return;
e.group = uint8_t(show_group), e.match = uint8_t(show_match), e.minute = int16_t(show_minute);
show->push_back(std::move(e));
}
void show_at(const MatchGroup& g, int m, int minute) {
show_group = int(&g - groups.data()), show_match = m, show_minute = minute;
}
int& last_pick_quality; // MatchEngineRuntimeField (a global: GameState::last_pick_quality)
int last_shooter_slot = 0; // MatchEngineRuntimeField2
int last_assist_slot = 0; // MatchEngineRuntimeField3
// Stack slot local_1c of PlayerValue as seen from PickTaker (see
// RatingContext::stale_condition): the condition of the last candidate rated with it.
int pick_stack_condition = 0;
// local_84 of EndPhase: quality of the last assistant picked (free kicks use it).
int stale_assistant_quality = 0;
int stale_set_piece_score = 0; // local_9c, retained for Source Reality restart2
RealityScene reality_runtime; // persistent grid, cue slots and MatchEngine_Minute_ExecutableField during matchday
};
} // namespace bmh
+815
View File
@@ -0,0 +1,815 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/matchday.hpp"
#include <algorithm>
#include <array>
#include <bit>
#include <cstdlib>
#include "game/cup.hpp"
#include "game/schedule.hpp"
#include "game/sportschau_presentation.hpp"
#include "game/table.hpp"
namespace bmh {
namespace {
// Competition class of each descriptor type (MatchEngineRuntimeField9): 0 league (cards count per
// team), 1-4 cup competitions with their own card counters, 0xFF = none.
constexpr uint8_t kCompetitionClass[24] = {0, 1, 2, 2, 2, 3, 3, 3, 3, 255, 0, 255,
4, 255, 255, 255, 255, 255, 255, 1, 0, 0, 0, 0};
// Clubs per league (LeagueSizes): five leagues of 18, four regional leagues of 12.
// (the clubs per league are kLeagueSizes, schedule.hpp)
// Three points for a win in every league (CareerSession_BeginFriendlyOpponentTable_RuntimeField, index 9 = "no league" reads the
// following table byte 18, also non-zero).
constexpr bool kThreePoints[10] = {true, true, true, true, true, true, true, true, true, true};
constexpr size_t kClubRecord = 0x4a;
constexpr size_t kManagerRecord = 0xB0C;
constexpr size_t kBoard = 0x840, kBoardSlot = 0x58;
uint32_t rd32(const std::vector<uint8_t>& v, size_t o) {
return uint32_t(v.at(o) | v.at(o + 1) << 8 | v.at(o + 2) << 16 | uint32_t(v.at(o + 3)) << 24);
}
void wr32(std::vector<uint8_t>& v, size_t o, uint32_t x) {
for (int i = 0; i < 4; i++) v.at(o + i) = uint8_t(x >> (8 * i));
}
uint16_t rd16(const std::vector<uint8_t>& v, size_t o) { return uint16_t(v.at(o) | v.at(o + 1) << 8); }
void wr16(std::vector<uint8_t>& v, size_t o, uint16_t x) {
v.at(o) = uint8_t(x);
v.at(o + 1) = uint8_t(x >> 8);
}
int competition_class(int type) { return type >= 0 && type < 24 ? kCompetitionClass[type] : 255; }
// TeamLeague2: league (0-8) of a club id, 9 for clubs outside the leagues.
int league_of(int team) {
if (team > 0x164) return 0;
int end = 0;
for (int l = 0; l < 9; l++) {
end += kLeagueSizes[l];
if (team < end) return l;
}
return 9;
}
// ClubRecord: record result `idx` of a club. The value of a result is
// home * home_weight - away * away_weight; `lower` keeps the smallest instead of the
// largest value. The stored result uses away_weight 1 if it was negative.
void club_record(GameState& g, int club, int idx, int home, int away, bool lower, int home_weight, int away_weight, int opponent) {
size_t base = size_t(club) * kClubRecord;
uint8_t& r = g.club_table.at(base + 0x15 + idx);
int old_value = (r >> 4) * home_weight - (r & 0x0F) * away_weight;
int new_value = home * home_weight - away * away_weight;
if (!lower ? new_value <= old_value : old_value <= new_value) return;
if (away_weight < 0) away_weight = 1;
r = uint8_t((uint8_t(home * home_weight) << 4) + uint8_t(away * away_weight));
wr16(g.club_table, base + 0x2a + idx * 2, g.club_ids.at(opponent));
wr16(g.club_table, base + 0x3a + idx * 2, uint16_t(std::min<uint32_t>(g.date, 0xFFFF)));
}
} // namespace
bool match_score(const MatchGroup& g, int m, int& home, int& away) {
if (!g.results.empty()) {
home = g.results.at(m) >> 4;
away = g.results.at(m) & 0x0F;
return true;
}
if (g.cup_results.size() == size_t(g.matches())) {
home = g.cup_results[m] >> 5 & 0x1F;
away = g.cup_results[m] & 0x1F;
return true;
}
return false;
}
int sportschau_source_setting_index(const GameState& state, const MatchGroup& group) {
const uint32_t id = le32(group.desc, 0xcc);
if (id <= 0x14) return id < 5 ? int(id) : std::min(int(id) + 12, 0x13);
const uint32_t source = id + 0x18;
return state.memory.has(source) ? int(uint8_t(state.memory.u8(source) + 5)) : -1;
}
SportschauFixtureView sportschau_fixture_view(const GameState& state, const MatchGroup& group,
int group_index, int fixture_index,
const std::vector<ShowEvent>& show_events) {
SportschauFixtureView view;
if (group_index < 0 || group_index > 0xff || fixture_index < 0 || fixture_index > 0xff ||
size_t(fixture_index * 2 + 1) >= group.fixtures.size())
return view;
view.group = uint8_t(group_index);
view.fixture = uint8_t(fixture_index);
view.competition_type = group.desc.at(0);
view.fixture_flags = group.desc.at(1);
view.source_footer_variant = state.indoor ? 2 : ((group.desc.at(1) & 8) != 0 ? 1 : 0);
view.has_replay_progression_mode = state.memory.has(::bmh::layout::ReplayProgressionMode);
if (view.has_replay_progression_mode) view.replay_progression_mode = state.memory.u8(::bmh::layout::ReplayProgressionMode);
view.has_replay_chance_mode = state.memory.has(::bmh::layout::ReplayChanceMode);
if (view.has_replay_chance_mode) view.replay_chance_mode = state.memory.u8(::bmh::layout::ReplayChanceMode);
view.source_selection_available = state.sportschau_selection_available;
view.competition_id = le32(group.desc, 0xcc);
view.source_setting_index = int16_t(sportschau_source_setting_index(state, group));
view.home_team = int16_t(group.fixtures.at(size_t(fixture_index * 2)));
view.away_team = int16_t(group.fixtures.at(size_t(fixture_index * 2 + 1)));
view.source_selected = view.source_selection_available && sportschau_selected(state, view.home_team);
if (size_t(fixture_index) < group.end_minute.size())
view.source_played_minute = group.end_minute[size_t(fixture_index)];
auto as_bytes = [](const std::string& s) {
return std::vector<uint8_t>(s.begin(), s.end());
};
auto set_team = [&](int team, std::vector<uint8_t>& full, std::vector<uint8_t>& short_name,
bool& short_name_available,
bool& requires_font_fit, bool& requires_longest_word, uint16_t& badge_word) {
const std::string name = state.club_name(team);
full = as_bytes(name);
if (team >= 0 && size_t(team) * 2 + 1 < state.club_heap_78.size())
badge_word = uint16_t(state.club_heap_78[size_t(team) * 2] |
uint16_t(state.club_heap_78[size_t(team) * 2 + 1]) << 8);
if (team >= 0 && team < 0xa8) {
requires_font_fit = true;
if (state.memory.has(::bmh::layout::ClubShortNameOffsets + uint32_t(team))) {
const uint8_t source = state.memory.u8(::bmh::layout::ClubShortNameOffsets + uint32_t(team));
const size_t offset = source >> 4;
const size_t length = (source & 0x0f) + 1;
if (offset <= full.size()) {
short_name_available = true;
const size_t count = std::min(length, full.size() - offset);
short_name.assign(full.begin() + std::ptrdiff_t(offset),
full.begin() + std::ptrdiff_t(offset + count));
}
}
} else {
short_name = full;
short_name_available = !short_name.empty();
requires_font_fit = true;
requires_longest_word = true;
}
};
set_team(view.home_team, view.home_name, view.home_short_name, view.home_short_name_available,
view.home_name_requires_font_fit, view.home_name_requires_longest_word, view.home_badge_word);
set_team(view.away_team, view.away_name, view.away_short_name, view.away_short_name_available,
view.away_name_requires_font_fit, view.away_name_requires_longest_word, view.away_badge_word);
int home = 0, away = 0;
view.score_known = match_score(group, fixture_index, home, away);
if (view.score_known) {
view.home_goals = uint8_t(home);
view.away_goals = uint8_t(away);
}
uint16_t ordinal = 0;
for (size_t i = 0; i + 1 < group.log.size(); i += 2) {
const uint16_t code_player = group.log[i];
const uint16_t team_value = group.log[i + 1];
const int team = team_value >> 7;
if (team != view.home_team && team != view.away_team) continue;
SportschauLogEvent event;
event.group = view.group;
event.fixture = view.fixture;
event.event_ordinal = ordinal++;
event.source_word_index = uint16_t(i);
event.source_code_player_word = code_player;
event.source_team_value_word = team_value;
event.source_code = uint8_t(code_player >> 12);
event.player_id = uint16_t(code_player & 0x0fff);
event.team_id = int16_t(team);
event.source_value = uint8_t(team_value & 0x7f);
event.consumes_following_pair = event.source_code == 0 || event.source_code == 1;
event.has_following_word = i + 2 < group.log.size();
event.has_following_pair = i + 3 < group.log.size();
if (event.has_following_word) {
event.following_code_player_word = group.log[i + 2];
const int player = event.following_code_player_word & 0x0fff;
if (player != 0x0fff) event.following_player_name = as_bytes(state.player_name(player));
}
if (event.has_following_pair) event.following_team_value_word = group.log[i + 3];
if (event.player_id != 0x0fff) event.player_name = as_bytes(state.player_name(event.player_id));
view.log_events.push_back(std::move(event));
}
for (const ShowEvent& event : show_events)
if (event.group == view.group && event.match == view.fixture) view.show_events.push_back(event);
return view;
}
bool book_money(GameState& g, int manager, int32_t amount, bool force, bool statistics) {
if (g.level == 0) return true;
size_t rec = size_t(manager) * kManagerRecord;
const uint32_t balance = rd32(g.manager_records, rec + 0x314);
const uint32_t credit = rd32(g.manager_records, rec + 0x31c);
// BookMoney2 adds the Native dwords before a signed comparison and subtracts
// the amount in the same 32-bit register width. Preserve that wrap without
// C++ signed-overflow undefined behavior at the account limits.
if (!force && amount >= 0 && std::bit_cast<int32_t>(balance + credit) < amount) return false;
wr32(g.manager_records, rec + 0x314, balance - uint32_t(amount));
if (statistics) {
if (amount < 0)
wr32(g.manager_records, rec + 0x874, rd32(g.manager_records, rec + 0x874) - uint32_t(amount));
else
wr32(g.manager_records, rec + 0x8a0, rd32(g.manager_records, rec + 0x8a0) + uint32_t(amount));
}
return true;
}
uint32_t pay_bonus(GameState& g, int manager, int board_slot, int index, bool pay) {
size_t slot = size_t(manager) * kBoard + size_t(board_slot) * kBoardSlot;
uint32_t rate = g.tactics.at(slot + 0x12 + index);
if (rate == 0) return 0;
uint32_t factor = index > 2 ? 5 : 1;
uint32_t amount = factor * (rate * rd32(g.tactics, slot + 0x50)) / 100;
if (pay) {
size_t rec = size_t(manager) * kManagerRecord;
uint32_t tax = g.manager_records.at(rec + 0x172);
if (tax != 0) amount -= ((tax >> 5 & 7) + 3) * amount * 10 / 100;
book_money(g, manager, int32_t(amount), true);
wr32(g.manager_records, rec + 0x334, rd32(g.manager_records, rec + 0x334) + amount);
}
return amount;
}
void player_statistic(GameState& g, int type, int player, int manager, int slot, int kind, int minute) {
int cls = (type == 0xb && manager >= 0 && !g.manager_teams.empty() && g.manager_teams[0] == kNoTeam)
? 3
: int8_t(competition_class(type));
if (cls < 0 || cls >= 4) return;
Player& p = g.players.at(player);
const uint32_t w364 = p.w364;
const size_t board = manager >= 0 ? size_t(manager) * kBoard + size_t(slot) * kBoardSlot : 0;
if (kind == 0) { // appearance
if (cls == 3 && (g.player_bonus.at(player) & 0x7F) < 0x7F) g.player_bonus.at(player)++;
if (manager >= 0) {
pay_bonus(g, manager, slot, 2, true);
if (cls < 3) g.tactics.at(board + 7 + cls)++;
wr16(g.tactics, board + 0x48, uint16_t(rd16(g.tactics, board + 0x48) + 1));
}
if (cls == 0) p.w364 = (w364 & 0x03FFFFFFu) | ((w364 >> 26) + 1) << 26; // league games
} else if (kind == 1) { // goal
if (manager >= 0) {
pay_bonus(g, manager, slot, 0, true);
wr16(g.tactics, board + 0x4a, uint16_t(rd16(g.tactics, board + 0x4a) + 1));
if (cls == 0) g.manager_records.at(size_t(manager) * kManagerRecord + 0x1ae + std::min(minute, 89) / 5)++;
}
// league goals in bits 2-7 (a 64th goal carries into bit 8, as in the original)
if (cls == 0) p.w364 = (w364 & 0xFFFFFF03u) | ((((w364 >> 2) & 0x3F) << 2) + 4);
} else if (kind == 2) { // assist
if (manager >= 0) wr16(g.tactics, board + 0x4c, uint16_t(rd16(g.tactics, board + 0x4c) + 1));
if (cls == 0) p.w368 = (p.w368 & 0xFF03FFFFu) | ((((p.w368 >> 18) & 0x3F) + 1) << 18);
}
}
void finish_match(GameState& g, MatchGroup& grp, int m, int minute, GameRandom& game) {
if (grp.end_minute.at(m) == 0) grp.end_minute.at(m) = uint8_t(minute);
for (int side = 0; side < 2; side++) {
int manager = g.manager_of(grp.fixtures.at(m * 2 + side));
if (manager < 0) continue;
int home = 0, away = 0;
match_score(grp, m, home, away);
int own = side ? away : home, opp = side ? home : away;
int points = 0;
if (own == opp) points = 1;
if (int8_t(own) > int8_t(opp)) points = 2;
for (int slot = 0; slot < 24; slot++) {
size_t at = size_t(manager) * kBoard + size_t(slot) * kBoardSlot;
int start = int8_t(g.tactics.at(at + 0x10)); // minute the player came on
for (int i = 0; i < points; i++) pay_bonus(g, manager, slot, 1, true);
if (start >= 126) continue;
// Getting used to the place: a quarter of the minutes played (half in the
// competitions 5 and 7), at most 99.
int8_t delta = int8_t((minute - start) / 4);
if (grp.desc.at(0) == 5 || grp.desc.at(0) == 7) delta = int8_t(delta / 2);
if (g.indoor) start = int8_t(start) >> 2;
int used = int8_t(g.tactics.at(at + 0xf)) + delta;
g.tactics.at(at + 0xf) = uint8_t(std::clamp(used, 0, 99));
// The player's own place (bytes 0/1) moves one step towards the board place.
if (game.range(0, 90) < minute - start) {
for (int k = 0; k < 2; k++) {
uint8_t& cur = g.tactics.at(at + k);
uint8_t target = g.tactics.at(at + 0x41 + k);
if (cur < target) cur++;
if (cur > target) cur--;
}
}
}
}
}
void update_club_table(GameState& g, int home, int away, int hg, int ag) {
if (g.indoor || g.club_table.empty()) return;
const size_t H = size_t(home) * kClubRecord, A = size_t(away) * kClubRecord;
auto add16 = [&](size_t o, int v) { wr16(g.club_table, o, uint16_t(rd16(g.club_table, o) + v)); };
// Only the first league and the regional leagues keep points in this table (the
// condition tests the home club only).
const bool league = home < kLeagueSizes[0] || (home >= 90 && home < 138);
const int win_points = kThreePoints[league_of(home)] ? 3 : 2;
if (league) {
add16(H + 0x20, hg);
add16(H + 0x22, ag);
add16(A + 0x20, ag);
add16(A + 0x22, hg);
}
uint8_t h[21], a[21]; // streaks: t * 3 + (0 all, 1 home, 2 away)
std::copy_n(g.club_table.begin() + H, 21, h);
std::copy_n(g.club_table.begin() + A, 21, a);
club_record(g, home, 2, hg, ag, false, 1, 0, away); // most goals scored at home
club_record(g, away, 7, hg, ag, false, 1, 0, home); // most goals conceded away
club_record(g, home, 3, hg, ag, false, 0, -1, away); // most goals conceded at home
club_record(g, away, 6, hg, ag, false, 0, -1, home); // most goals scored away
auto bump = [](uint8_t* s, int t, int j) { s[t * 3 + j]++, s[t * 3]++; };
auto clear = [](uint8_t* s, int t, int j) { s[t * 3 + j] = 0, s[t * 3] = 0; };
// streak 5: without conceding, 6: without scoring
if (ag == 0) bump(h, 5, 1), bump(a, 6, 2);
else clear(h, 5, 1), clear(a, 6, 2);
if (hg == 0) bump(h, 6, 1), bump(a, 5, 2);
else clear(h, 6, 1), clear(a, 5, 2);
if (ag < hg) { // home win
if (league) {
add16(H + 0x1e, win_points);
add16(H + 0x24, 1);
add16(A + 0x28, 1);
}
bump(h, 0, 1);
for (int t = 1; t < 4; t++) clear(h, t, 1);
club_record(g, home, 0, hg, ag, false, 1, 1, away); // biggest home win
club_record(g, away, 5, hg, ag, false, 1, 1, home); // biggest away defeat
bump(h, 4, 1);
clear(a, 0, 2), clear(a, 2, 2), clear(a, 4, 2);
bump(a, 1, 2), bump(a, 3, 2);
} else if (hg == ag) { // draw
if (league) {
add16(H + 0x1e, 1);
add16(A + 0x1e, 1);
add16(H + 0x26, 1);
add16(A + 0x26, 1);
}
clear(h, 0, 1), clear(h, 1, 1);
for (int t = 2; t < 5; t++) bump(h, t, 1);
clear(a, 0, 2), clear(a, 1, 2);
for (int t = 2; t < 5; t++) bump(a, t, 2);
} else { // away win
if (league) {
add16(A + 0x1e, win_points);
add16(H + 0x28, 1);
add16(A + 0x24, 1);
}
bump(a, 0, 2);
for (int t = 1; t < 4; t++) clear(a, t, 2);
clear(h, 0, 1), clear(h, 2, 1), clear(h, 4, 1);
bump(a, 4, 2);
bump(h, 1, 1), bump(h, 3, 1);
club_record(g, home, 1, hg, ag, true, 1, 1, away); // biggest home defeat
club_record(g, away, 4, hg, ag, true, 1, 1, home); // biggest away win
}
std::copy_n(h, 21, g.club_table.begin() + H);
std::copy_n(a, 21, g.club_table.begin() + A);
// Human managers keep their club's best streaks (manager record +0x5e).
for (int side = 0; side < 2; side++) {
int club = side ? away : home;
const uint8_t* s = side ? a : h;
for (size_t k = 0; k < g.manager_teams.size(); k++) {
if (g.manager_teams[k] != club) continue;
for (int i = 0; i < 21; i++) {
uint8_t& best = g.manager_records.at(k * kManagerRecord + 0x5e + i);
if (best < s[i]) best = s[i];
}
}
}
}
void update_morale(GameState& g, int team, int own_goals, int opp_goals, int side, WatcomRandom& rand) {
uint8_t& morale = g.team_morale.at(team);
const int value = morale & 0x3F;
int sign = 1;
int diff = int16_t(side + (own_goals - opp_goals) + (5 - value / 5));
int step = std::abs(25 - value) / 5;
if (diff < 0 || (diff == 0 && value > 25)) {
sign = -1;
diff = -diff;
}
// Far from the middle (25) morale moves slowly towards the extremes.
if ((sign == 1 && value > 12) || (sign == -1 && value < 37)) step = 5 - step;
if (int16_t(step) == 0) step = 1;
diff = std::clamp(diff, 1, 3);
int range = int16_t(step * diff);
if (range > 12) range = 12;
if (range == 0) return;
int v = int16_t(value + sign * int16_t(rand.range(1, range)));
v = std::clamp(v, 0, 0x2f);
morale = uint8_t(v | (morale & 0xC0));
}
void develop_players(GameState& g, const MatchGroup& grp, int m, GameRandom& game, WatcomRandom& rand) {
const int type = grp.desc.at(0);
for (int side = 0; side < 2; side++) {
const int team = grp.fixtures.at(m * 2 + side);
if (!(team < 168 || team == kNoTeam)) continue;
const uint8_t cls = (type == 0xb && team == kNoTeam) ? 3 : uint8_t(competition_class(type));
const int manager = g.manager_of(team);
const SquadRange range = squad_range(team);
// 1 in 11: the team gets the next trend of the rotation (none/down, neutral, up);
// the rotation is steered by the balance of all attribute changes so far.
if (game.range(0, 10) == 0) {
if (g.development_balance < -50) g.trend_rotation = 2;
if (g.development_balance > 50) g.trend_rotation = 0;
uint16_t& f = g.team_flags.at(team);
f = uint16_t(((f & 0xFFF8) + g.trend_rotation * 2) & 0xFFFF);
if (++g.trend_rotation == 3) g.trend_rotation = 0;
}
const int8_t trend = int8_t(((g.team_flags.at(team) >> 1) & 3) - 1);
int capped = 0; // local_30: attributes that hit 99 (carries over between players)
for (size_t s = range.first; s < range.first + range.count; s++) {
const int player = g.squad_slots.at(s) & 0x0FFF;
if (player == 0xFFF) break;
Player& p = g.players.at(player);
const int odds = manager >= 0 ? 6 : 3;
if (trend != 0 && game.range(0, 3) == 0) {
int8_t d = trend;
if (rand.range(0, 4) == 0) d = int8_t(-trend);
// form (shift 0, kept within 35-65), technique (7), condition (14)
uint32_t w = p.w35c;
for (int sh = 0; sh < 15; sh += 7) {
if (sh >= 7 && capped == 0 && game.range(0, odds) != 0) continue;
const int8_t old = int8_t((w >> sh) & 0x7F);
int8_t v = int8_t(old + d);
if (capped != 0 || game.range(0, 1) != 0) v = int8_t(v + d);
if (sh != 0) {
if (v < 0) v = 0;
if (v > 99) {
// Quirk of the original: the first attribute to pass 99 restarts
// the loop - 99 is written to the form and technique and
// condition are processed (again).
if (capped == 0) sh = 0;
v = 99;
capped++;
} else if (capped != 0) {
capped--;
}
} else {
v = int8_t(std::clamp<int>(v, 0x23, 0x41));
}
if (sh != 0) g.development_balance += v - old;
w = (w & ~(0x7Fu << sh)) + (uint32_t(int32_t(v)) << sh);
}
p.w35c = w;
// the seven skills follow the team trend (1 in 9 each)
uint32_t k = p.w368;
for (int sh = 0; sh < 13; sh += 2) {
if (game.range(0, 8) != 0) continue;
int v = int((p.w368 >> sh) & 3) + trend;
v = std::clamp(v, 0, 3);
k = (k & ~(3u << sh)) + (uint32_t(v) << sh);
}
p.w368 = k;
}
if (p.w364 & 0x1000) // played in this match
player_statistic(g, type, player, manager, int(s - range.first), 0, 0x5a);
if (p.w35c >> 27) continue; // injured players are handled elsewhere
if (cls != 0xFF) {
const int duration = (p.w364 >> 16) & 0xF;
if (duration != 0 && !(p.w364 & 0x100000)) {
// injury (not a ban) heals by one match; in cups the card counter restarts
if (cls != 0) {
if (p.w368 >> 24 & 1) p.w368 &= 0xF8FFFFFFu;
else p.w368 = (p.w368 & 0xF8FC3FFFu) | 0x4000u;
}
p.w364 = (p.w364 & 0xFFE0FFFFu) | uint32_t(duration - 1) << 16;
} else if (cls == 0) {
// league: every fifth yellow card (booked in this match) bans for one match
int yellow = (p.w368 >> 14) & 0xF;
if ((g.squad_slots.at(s) & 0x1000) && yellow > 4 && yellow % 5 == 0) p.w364 |= 0x10000u;
}
}
g.squad_slots.at(s) &= 0xCFFF; // clear the booked/substituted slot flags
if (cls == 0) continue;
// Cups: move the card counters of this competition into the player's card word
// and load those of the next competition (the w368 card bits are shared).
if (p.w368 >> 24 & 1) p.w368 |= 0xC000u;
uint16_t& cards = g.player_cards.at(player);
switch (cls) {
case 1: p.w364 = (p.w364 & 0xFFFFFCFFu) | ((p.w368 >> 14) & 3) << 8; break;
case 2: p.w364 = (p.w364 & 0xFFFFF3FFu) | ((p.w368 >> 14) & 3) << 10; break;
case 3: cards = uint16_t((cards & 0x3FFF) | (p.w368 & 0xC000)); break;
case 4: cards = uint16_t((cards & 0xCFFF) | ((p.w368 >> 14) & 3) << 12); break;
default: break;
}
p.w368 = (p.w368 & 0xF8FC3FFFu) | uint32_t((cards >> 5) & 0xF) << 14 | uint32_t((cards >> 9) & 7) << 24;
if (p.w35c >> 27 == 0) p.w364 = (p.w364 & 0xFFE0FFFFu) | ((p.w364 >> 13) & 7) << 16;
}
}
}
void process_group(GameState& g, const MatchGroup& grp, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
int group_index, const SportschauFixtureHook& sportschau,
const std::vector<ShowEvent>* show_events, const SportschauReplayHooks* replay) {
auto owned = grp;
process_group(g, owned, game, rand, report, group_index, sportschau, show_events, replay, nullptr);
}
void process_group(GameState& g, MatchGroup& grp, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
int group_index, const SportschauFixtureHook& sportschau,
const std::vector<ShowEvent>* show_events, const SportschauReplayHooks* replay,
const SportschauRatingTables* ratings) {
const int type = grp.desc.at(0);
auto store_awards = [&] {
if (group_index < 0 || group_index >= 6) return;
const uint32_t base = ::bmh::layout::MatchdayGroupDescriptors + uint32_t(group_index) * 0xd0;
for (size_t i = 0; i < 11; ++i) {
if (g.memory.has(base + 0x70 + uint32_t(i)))
g.memory.set8(base + 0x70 + uint32_t(i), grp.desc.at(0x70 + i));
if (g.memory.has(base + 0x9c + uint32_t(i * 2 + 1)))
g.memory.set16(base + 0x9c + uint32_t(i * 2), le16(grp.desc, 0x9c + i * 2));
}
};
if (ratings) {
// FinishEvent/BuildSideRecords reset eleven score bytes, retaining old slot ids.
std::fill_n(grp.desc.begin() + 0x70, 11, uint8_t(0));
store_awards();
}
// The original walks the fixtures with a pointer (puVar2) that only moves on in the
// morale step of a played match. After a match that was not played, the club records and
// the morale of every following match are therefore booked on the teams of the match
// before it (the player development and the manager records use the match index).
size_t cursor = 0;
for (int m = 0; m < grp.matches(); m++) {
// The original keeps local_70 (kickoff_void_mask) separately from the descriptor:
// desc+0xb8 also gains ended-match bits as the minute loop runs. Its fixture pointer
// advances only for played matches, so a void fixture must not advance `cursor`.
if (grp.kickoff_void_mask & (1u << m)) continue;
// A postponed league match can also retain its 0xCD result byte.
if (!grp.results.empty() && (grp.results.at(size_t(m)) & 0xCC) == 0xCC) continue;
int home = 0, away = 0;
if (!match_score(grp, m, home, away)) {
report.fail("matchday processing needs the score");
return;
}
const int ht = grp.fixtures.at(cursor), at = grp.fixtures.at(cursor + 1);
cursor += 2;
if (type == 0 || type == 10) update_club_table(g, ht, at, home, away);
// MatchdayIntro sits between table updates and morale. Core owns its enabled
// replay scene draws; the old fixture callback remains a pure observer.
if ((sportschau || replay || ratings) && group_index >= 0) {
const auto view = sportschau_fixture_view(g, grp, group_index, m,
show_events ? *show_events : std::vector<ShowEvent>{});
if (replay) present_sportschau_replay(g, grp, view, game, rand, *replay);
if (ratings) { rate_sportschau_players(g, grp, view, rand, *ratings); store_awards(); }
if (sportschau) sportschau(g, view);
}
update_morale(g, ht, home, away, 0, rand);
update_morale(g, at, away, home, 1, rand);
manager_match_record(g, grp, m, home, away, report);
if (report.unsupported) return;
develop_players(g, grp, m, game, rand);
}
}
void stir_random(GameRandom& game, WatcomRandom& rand) {
int n = int16_t(rand.range(100, 300));
for (int i = 0; i < n; i++) game.range(0, 1);
}
bool league_screen_shown(const std::vector<uint8_t>& buttons, int param_1, int param_2, int league) {
if (param_2 == 0 || param_2 >= 200) return true; // called from the desk: always shown
int kind = param_1 - 1;
if (param_1 == 2 && (param_2 == 90 || param_2 == 120)) kind = 2;
int row = league;
if (league > 4) row = std::min(league + 12, 19);
if (param_2 == 45 && kind == 0) return false;
return buttons.at(size_t(kind + row * 9)) == 0;
}
int table_position(const GameState& g, int team) {
if (team >= 138) return 2;
int league = league_of(team);
int rounds = league < int(g.league_rounds.size()) ? g.league_rounds[league] : 0;
if (rounds == 0) return -1;
unsigned u = unsigned(rounds - 1);
int word = int16_t(rd16(g.position_history, (size_t(u / 3) + size_t(team) * 13) * 2));
return (word >> ((u % 3) * 5)) & 0x1F;
}
void rate_manager(GameState& g, int manager, int rating, int competition) {
uint8_t* hist = g.manager_ratings.data() + size_t(competition) * 10 + size_t(manager) * 0x3c;
std::copy_backward(hist, hist + 9, hist + 10); // Int16T: shift the last 9 up
hist[0] = uint8_t(rating);
int sum = 0;
for (int s = 0; s < 10; s++) sum = int16_t(sum + ((100 - 10 * s) * hist[s]) / 100);
wr16(g.manager_records, size_t(manager) * kManagerRecord + 0x8aa + size_t(competition) * 2, uint16_t(sum));
}
void manager_match_record(GameState& g, const MatchGroup& grp, int m, int home_goals, int away_goals, MinuteReport& report) {
const int type = grp.desc.at(0);
for (size_t k = 0; k < g.manager_teams.size(); k++) {
const size_t rec = k * kManagerRecord;
int side = -1, opponent = 0;
for (int s = 0; s < 2; s++)
if (g.manager_teams[k] == grp.fixtures.at(m * 2 + s)) {
side = s;
opponent = grp.fixtures.at(m * 2 + 1 - s);
break;
}
if (side < 0) continue;
// opponent id as the original keeps it: its low byte (0xFE for ids >= 256)
const int opp = opponent < 0x100 ? opponent : 0xFE;
// last results (home | away << 4) and fixtures, newest first
std::copy_backward(g.manager_records.begin() + rec + 0x212, g.manager_records.begin() + rec + 0x217,
g.manager_records.begin() + rec + 0x218);
std::copy_backward(g.manager_records.begin() + rec + 0x292, g.manager_records.begin() + rec + 0x2a6,
g.manager_records.begin() + rec + 0x2aa);
g.manager_records.at(rec + 0x212) = uint8_t(home_goals + (away_goals << 4));
for (int i = 0; i < 2; i++) wr16(g.manager_records, rec + 0x292 + i * 2, uint16_t(grp.fixtures.at(m * 2 + i)));
int own = side ? away_goals : home_goals, against = side ? home_goals : away_goals;
int rating = side ? 110 : 90; // an away game counts more
if (uint8_t(own) > uint8_t(against)) {
// league win bonus from the sponsor (record +0x173 thousands, less for
// higher +0x210 levels)
int bonus = g.manager_records.at(rec + 0x173);
if (type == 0 && bonus != 0) {
int level = g.manager_records.at(rec + 0x210);
if (level > 2) level--;
int32_t amount = (4 - level) * bonus * 1000;
if (g.level != 0) {
wr32(g.manager_records, rec + 0x314, rd32(g.manager_records, rec + 0x314) + uint32_t(amount));
wr32(g.manager_records, rec + 0x874, rd32(g.manager_records, rec + 0x874) + uint32_t(amount));
}
}
rating += 20;
}
if (uint8_t(own) < uint8_t(against)) rating -= 20;
// MatchdayRuntimeField (u16 every 4 bytes): competitions that rate the manager. A league match
// counts the table place; a cup match its weight plus twice the rounds played in the
// stage and in every earlier one (link +0x15). All go into the league history (0).
static const uint16_t kRatingWeight[14] = {1, 12, 16, 20, 18, 0, 0, 0, 0, 14, 1, 0, 12, 10};
const uint16_t weight = type < 14 ? kRatingWeight[type] : 0;
if (weight != 0) {
if (type != 0) {
int add = weight;
uint32_t e = le32(grp.desc, 0xcc);
for (int guard = 0; guard < 64; guard++) {
add += g.memory.u8(e + 0x1d) * 2;
const int8_t previous = int8_t(g.memory.u8(e + 0x15));
if (previous == -1) break;
e = cup_entry_address(previous);
}
rating += int16_t(add);
} else {
int league = league_of(g.manager_teams[k]);
int size = league < 9 ? kLeagueSizes[league] : 0;
rating += (size - table_position(g, g.manager_teams[k])) * 4;
}
rating = std::clamp(int16_t(rating), int16_t(0), int16_t(200));
rate_manager(g, int(k), rating, 0);
}
if (opp < 0xa8) {
size_t at = k * 0x690 + size_t(opp) * 10 + (side == 1 ? 5 : 0);
std::copy_backward(g.manager_results.begin() + at, g.manager_results.begin() + at + 4,
g.manager_results.begin() + at + 5);
g.manager_results.at(at) = uint8_t(own + (against << 4));
}
}
}
// TicketPriceDraws: per human manager on a first league matchday. It once let the three
// ticket prices drift; in this version its stores were turned into comparisons (CMP
// instead of MOV), so only the random numbers remain.
void ticket_price_draws(const GameState& g, int manager, WatcomRandom& rand) {
uint8_t step[0x2c];
int b = 4;
for (int i = 0; i < 0x2c; i++) {
step[i] = uint8_t(b);
if (b != 0 && rand.range(0, 8) == 0) b--;
}
(void)g;
(void)manager;
const int round = g.league_rounds.empty() ? 0 : g.league_rounds[0];
for (int i = 0; i < 3; i++) {
// the direction terms depend on the prices, but only as values, not as draw counts
if (rand.range(0, 4) == 0) rand.range(0, 2);
rand.range(0, 30);
rand.range(0, 2);
if (rand.range(0, 4) == 0) rand.range(0, 2);
if (rand.range(0, 3) != 0) rand.range(1, 18);
rand.range(1, step[round < 0x2c ? round : 0x2b]);
}
}
// ManagerOf(manager, 0, value): the manager's position of this season.
static void store_season_position(GameState& g, int manager, int value) {
int season = std::min(g.season, 0x31);
g.manager_records.at(size_t(manager) * kManagerRecord + 0xda + size_t(season) * 3) = uint8_t(value);
}
// StoreStrengthHistory: strength and position history of a human manager's club (38 entries).
static void store_strength_history(GameState& g, int manager) {
const size_t rec = size_t(manager) * kManagerRecord;
const int team = g.manager_teams.at(manager);
int n = g.manager_records.at(rec + 0x284);
if (n < 0x26) {
g.manager_records.at(rec + 0x284) = uint8_t(n + 1);
} else {
std::copy(g.manager_records.begin() + rec + 0x223, g.manager_records.begin() + rec + 0x248,
g.manager_records.begin() + rec + 0x222);
std::copy(g.manager_records.begin() + rec + 0x249, g.manager_records.begin() + rec + 0x26e,
g.manager_records.begin() + rec + 0x248);
n = 0x25;
}
g.manager_records.at(rec + 0x222 + n) = uint8_t(team_average(g, team, 0xFF).value);
int pos = table_position(g, team);
if (pos == -1) pos = (kLeagueSizes[g.manager_records.at(rec + 0x210)] - 1) >> 1;
g.manager_records.at(rec + 0x248 + n) = uint8_t(pos);
}
void advance_league_rounds(GameState& g, uint32_t competitions, WatcomRandom& rand, MinuteReport& report,
const CompetitionWinnerHook& winner) {
// CalendarFirstLeague / CalendarLeagueCounts: first league and league count of competition bits 0-7
const uint8_t* kFirst = kGroupLeague; // (schedule.hpp: the groups of the loaded game)
const uint8_t* kCount = kGroupLeagues;
for (int bit = 0; bit < 19; bit++) {
if (!(competitions >> bit & 1)) continue;
if (bit >= 5) {
report.fail("cup round bookkeeping (AdvanceCup)");
return;
}
const int end = bit < 4 ? bit + 1 : 8;
for (int c = bit; c < end; c++) {
for (int league = kFirst[c]; league < kFirst[c] + kCount[c]; league++) {
if (league == 0) {
for (size_t m = 0; m < g.manager_teams.size(); m++) {
ticket_price_draws(g, int(m), rand);
const size_t rec = m * kManagerRecord;
if (g.league_rounds.at(0) == 0x10) wr32(g.manager_records, rec + 0x320, rd32(g.manager_records, rec + 0x308));
uint8_t& d = g.manager_records.at(rec + 0x220); // point deduction countdown
if (d >> 5 == 1) d = (d & 0x1F) < 2 ? 0 : uint8_t((d & 0xE0) | ((d & 0x1F) - 1));
}
}
const int round = g.league_rounds.at(league);
g.league_rounds.at(league) = uint8_t(round + 1);
LeagueTable t = compute_league_table(g, league, 0, league_matchdays(league), 7, kThreePoints[league] ? 1 : 0);
const int first = league_first_team(league);
for (int i = 0; i < t.size; i++) {
const int team = first + i;
const int rank = t.rank(i);
size_t at = (size_t(round / 3) + size_t(team) * 13) * 2;
wr16(g.position_history, at, uint16_t(rd16(g.position_history, at) | rank << ((round % 3) * 5)));
const int manager = g.manager_of(team);
if (manager >= 0) {
int base = first;
if (league_first_team(3) <= base) base -= 18;
store_season_position(g, manager, base + rank + 1);
store_strength_history(g, manager);
}
}
// OnceSecondDivisionLeagueHasPlayedAll, once the second division (league 2) has played all its rounds
// (in the last competition of the loop, after each of its leagues): the
// clubs placed 1-2 in leagues 2 and 3 (TablePosition, positions counted from 0)
// go into the team list of the promotion play-off (Teams), its results
// (MatchdayGroupWorkspace) are cleared and competition MatchdayRuntimeField2 (0xd) starts
if (c + 1 == end && g.league_rounds.at(2) == league_matchdays(2)) {
uint32_t n = 0;
for (int l = 2; l < 4; l++)
for (int team = league_first_team(l); team < league_first_team(l) + kLeagueSizes[l]; team++) {
const uint8_t pos = uint8_t(table_position(g, team));
if (pos != 0 && pos < 3) g.memory.set16(::bmh::layout::Teams + n++ * 2, uint16_t(team));
}
for (uint32_t i = 0; i < 0x20; i++) g.memory.set8(::bmh::layout::MatchdayGroupWorkspace + i, 0xcc);
for (uint32_t i = 0; i < 8; i++) { // AddCompetition(0xd)
if (int8_t(g.memory.u8(::bmh::layout::ActiveSelectors + i)) == 0xd) break;
if (g.memory.u8(::bmh::layout::ActiveSelectors + i) == 0x14) {
g.memory.set8(::bmh::layout::ActiveSelectors + i, 0xd);
break;
}
}
}
// the first division is over: its leader (OnTableJust(0, 0) on the table just
// computed) is champion - the winner screen (CompetitionWinnerScreen(0, 0), clears
// CareerSession_BeginFriendlyOpponentTable_ExecutableField2), the list of title holders (ListTitleHoldersAf(club, 0)), a human
// champion's record (+0x8a4) and Cup_AdvanceCup_RuntimeField6
if (league == 0 && g.league_rounds.at(0) == league_matchdays(0)) {
int champion = -1;
for (int i = 0; i < t.size && champion < 0; i++)
if (t.rank(i) == 0) champion = first + i;
if (champion < 0) champion = 0; // (OnTableJust returns 0 when none is found)
if (g.memory.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && winner)
winner(g, {0, uint16_t(champion)});
if (g.memory.u8(::bmh::layout::Cup_AdvanceCup_RuntimeField) == 0 && g.memory.has(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2)) g.memory.set8(::bmh::layout::CareerSession_BeginFriendlyOpponentTable_ExecutableField2, 0);
g.memory.set16(::bmh::layout::Titles + uint32_t(std::min<int>(g.season, 0x31)) * 2, uint16_t(champion));
const int manager = g.manager_of(champion);
if (manager >= 0) {
const size_t at = size_t(manager) * kManagerRecord + 0x8a4;
wr16(g.manager_records, at, uint16_t(rd16(g.manager_records, at) + 1));
}
g.memory.set16(::bmh::layout::Cup_AdvanceCup_RuntimeField6, uint16_t(champion));
}
}
}
}
}
} // namespace bmh
+102
View File
@@ -0,0 +1,102 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// What happens to a matchday after the final whistle (BMH.exe V2.24 + supported rule profile patch).
//
// The matchday driver (the function around 0x39xxx that calls EndPhase for every
// phase) continues after the last phase with, per match group and match:
// 1. UpdateClubTable league record of both clubs (points, goals, streaks, records)
// 2. morale both teams' morale moves towards the result (Watcom rand)
// 3. ManagerMatchRecord a human manager's match record, bonuses and rating
// 4. DevelopPlayers player development: team trends move form/technique/condition and
// skills (game RNG), appearances, injuries heal by one matchday,
// yellow card bans, card counters per competition
// Before that, the end of every phase calls FinishMatch per match: it stores the end
// minute and lets a human manager's players get used to their places on the tactics
// board and earn their bonus (game RNG).
#include <cstdint>
#include <vector>
#include "game/match_engine.hpp"
#include "game/random.hpp"
#include "game/sportschau_presentation.hpp"
#include "game/state.hpp"
namespace bmh {
// Score of match m of a group (MatchScore, read mode): league result byte or the cup
// result of the current leg. Returns false if the score is not known.
bool match_score(const MatchGroup& g, int m, int& home, int& away);
// BookMoney2: books `amount` from a human manager's account (record +0x314). Without
// `force` a payment larger than balance + credit (+0x31c) is refused (the original shows a
// message). Game level 0 has no money at all.
// With `statistics` (the caller sets FinanceStatisticsEnabled) the amount is also added to the
// income (+0x874, negative amounts) or expense (+0x8a0) statistics.
bool book_money(GameState& g, int manager, int32_t amount, bool force, bool statistics = false);
// PayBonus: bonus of one player on the tactics board: the board's bonus rate for
// `index` (slot byte 0x12 + index: 0 goal, 1 point, 2 appearance, ...) times the player's
// bonus base (slot +0x50) / 100, five-fold for index > 2. With `pay` the tax (record
// +0x172) is deducted and the amount is paid. Returns the amount.
uint32_t pay_bonus(GameState& g, int manager, int board_slot, int index, bool pay);
// PlayerStatistic: statistics of one player. kind 0 appearance, 1 goal, 2 assist.
// competition_type = descriptor byte 0; `manager` = human manager of the player's team
// or -1; `slot` = the player's slot relative to the squad start (tactics board index).
void player_statistic(GameState& g, int competition_type, int player, int manager, int slot, int kind, int minute);
// FinishMatch for match m at the end of a phase lasting `minute` minutes.
void finish_match(GameState& g, MatchGroup& grp, int m, int minute, GameRandom& game);
// UpdateClubTable: league record of home and away club after a result.
void update_club_table(GameState& g, int home, int away, int home_goals, int away_goals);
// Morale step of the matchday driver for one side (0 home, 1 away) of a finished match.
void update_morale(GameState& g, int team, int own_goals, int opp_goals, int side, WatcomRandom& rand);
// DevelopPlayers: player development and bookkeeping for both teams of match m.
void develop_players(GameState& g, const MatchGroup& grp, int m, GameRandom& game, WatcomRandom& rand);
// Steps 1, 2 and 4 for every match of a group that was played (voided matches, e.g.
// awarded 0:2, are skipped). Human records and bonuses use manager_match_record.
void process_group(GameState& g, const MatchGroup& grp, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
int group_index = -1, const SportschauFixtureHook& sportschau = {},
const std::vector<ShowEvent>* show_events = nullptr,
const SportschauReplayHooks* replay = nullptr);
// Loaded Source caller retains mutable descriptor award ownership; legacy raw
// probes without executable policy keep their existing immutable input API.
void process_group(GameState& g, MatchGroup& grp, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
int group_index, const SportschauFixtureHook& sportschau,
const std::vector<ShowEvent>* show_events, const SportschauReplayHooks* replay,
const SportschauRatingTables* ratings);
// ManagerMatchRecord: a human manager's record of match m (last results and fixtures, league
// win bonus, the manager rating via ManagerMatchRecord2 and the results per opponent).
void manager_match_record(GameState& g, const MatchGroup& grp, int m, int home_goals, int away_goals, MinuteReport& report);
// TablePosition: current table position of a team (-1 before the first round).
int table_position(const GameState& g, int team);
// ManagerMatchRecord2: adds a match rating (0-200) to a manager's history of competition
// `competition` and stores the weighted average in the manager record (+0x8aa).
void rate_manager(GameState& g, int manager, int rating, int competition);
// StirRandom: when a result or table screen (LeagueScreenShown) is left, the game stirs its
// random numbers: WatcomRandom(100, 300) game draws are thrown away.
void stir_random(GameRandom& game, WatcomRandom& rand);
// LeagueScreenShown(param_1, param_2): whether the screen is shown at all. param_1 1 = table,
// 2 = results; param_2 = the phase end minute (90 / 120 / 45 ...); league = descriptor
// +0xcc (CareerSession_BeginFriendlyOpponentTable_RuntimeField2). The desk buttons (block LeaguePresentationOptions, 9 bytes per league) switch it off.
bool league_screen_shown(const std::vector<uint8_t>& buttons, int param_1, int param_2, int league);
// The rest of AdvanceTurn after a matchday: for every competition bit of the day (bits
// 0-4 = leagues) the round counter LeagueRoundCounters advances, the table is recomputed and
// each club's rank is added to the position history (*LeagueRankHistory); human managers get their
// season position and strength history updated. This API accepts league bits only;
// finish_event dispatches bits 5+ separately through advance_cup.
void advance_league_rounds(GameState& g, uint32_t competitions, WatcomRandom& rand, MinuteReport& report,
const CompetitionWinnerHook& winner = {});
// TicketPriceDraws: the random draws of a human manager's (disabled) ticket price drift.
void ticket_price_draws(const GameState& g, int manager, WatcomRandom& rand);
} // namespace bmh
File diff suppressed because it is too large. Load diff
+155
View File
@@ -0,0 +1,155 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#pragma once
// Before the first minute of a matchday (BMH.exe V2.24 + supported rule profile patch).
//
// When "Weiter" reaches a day with a calendar event, AdvanceTurn prepares the matchday:
// 1. DayCompetitions2 builds one match group per league playing today (FixturesFromGenerateFixtures):
// fixtures of the next round, the result bytes of that round, and per match the
// weather and the referee (MatchWeather). Every team is then prepared for the match
// (PrepareTeam: cards of this competition, injuries, line-up flags) and gets an
// automatic line-up (Int2 mode 100). CycleManagerOptions advances the human
// managers' option byte 0 to the next enabled setting.
// 2. CurrentMatchday = WatcomRandom(0, 10000); PrepareEvent shuffles the order in which
// the human managers see their pre-match desks (one game draw per manager).
// 3. The matchday driver FinishEvent (called through the supported rule profile wrapper
// MatchdaySetupOperation) starts: "played" flags are cleared, the human tactics boards note who
// starts, every group's unplayed result bytes are set to 0:0 (anything else voids
// the match), and per match the attendance (Attendance) and the side records
// (BuildSideRecords3 + BuildSideRecords2) are computed.
// After that the minute loop (match_engine.hpp) runs.
//
// Ported for league matchdays of computer teams. Cups, indoor tournaments, the winter
// break postponements, human teams in a match (pre-match desk, own stadium, income) and
// Teams with fewer than 8 fit players receive the original 0:2 forfeit award.
#include <cstdint>
#include <vector>
#include "game/match_engine.hpp"
#include "game/random.hpp"
#include "game/state.hpp"
namespace bmh {
// Globals of the original that the preparation reads but that are not part of GameState.
struct MatchdayContext {
int month = 0; // CareerSession_PairingsRuntimeDraw_ExecutableField5: index into the monthly temperature table
int season_day = 0; // DaysIntoSeason: day since 1 July (winter break test)
int weekday = 0; // CareerSession_PairingsRuntimeDraw_ExecutableField6: weekday code of the day (the last DeskDate2 call of the day step)
// RefereeProperties: 50 referees from M3D.MAN; bit 7 marks "already chosen today".
std::vector<uint8_t>* referees = nullptr;
// the national team day (DayCompetitions -> national-only flag): AdvanceTurn skips the Bundestrainer
// check of the other days (no take-over, no hand-back)
bool national_team_day = false;
};
// The 0xD0-byte descriptor of match group `index` as it is left in memory (block MatchdayGroupDescriptors) from
// the previous matchday: the preparation only overwrites what it needs, so for example
// the referee bytes of matches without referee keep old values.
Bytes group_descriptor(const GameState& g, size_t index);
// Writes the descriptors back (the per-match bytes, void mask, attendance, league/cup).
void store_group_descriptors(GameState& g, const std::vector<MatchGroup>& groups, bool with_log = false);
// MatchWeather: temperature (descriptor +0x30), rain (+0x50) and referee (+0x10) of
// match m of a group.
void match_weather(MatchGroup& grp, int m, const MatchdayContext& ctx, GameRandom& game, WatcomRandom& rand);
// PrepareTeam: prepares the squad of `team` before a match of a competition of class
// `cls` (MatchEngineRuntimeField9[type]: 0 league, 1-4 cups with their own card counters, 0xFF none).
// `index` is the team's position in the flat fixture list (home 0, away 1, ...).
void prepare_team(GameState& g, int team, int cls, int index);
// DayCompetitions2(..., 1): builds the match groups of the competitions in `competitions`
// (SavedCompetition) and prepares all teams. Returns the groups in the order of the original.
// DayCompetitions: the competitions of a day from its calendar entry (CompetitionCalendar): the low
// 15 bits, with special entries mapped (0x4001 group -> 0x8000, 0x4002 -> layout field indoor
// tournament, 0x4004 -> layout field, 0x4006 -> national-only flag or nothing) and the four league
// groups 0x1e00 rotating with the season.
uint32_t day_competitions(const GameState& g, uint16_t entry);
// IndoorTournamentDraw: the draw of an indoor tournament (eight clubs, the host names it).
void indoor_tournament_draw(GameState& g, GameRandom& game, WatcomRandom& rand);
// The part of IndoorTournamentDraw that also runs before the Masters (CupRuntimeField != 0, no draw):
// before the first tournament the Masters points (Cup_AdvanceCup_ExecutableField) and invitations
// (MatchdaySetup_IndoorTournamentDraw_RuntimeField) are cleared; the name becomes "In ", the results of block MatchdayGroupWorkspace 0xCC and
// the played counters of the cup entries 25-29 0.
void indoor_tournament_reset(GameState& g);
std::vector<MatchGroup> setup_matchday(GameState& g, uint32_t competitions, const MatchdayContext& ctx,
GameRandom& game, WatcomRandom& rand, MinuteReport& report);
// MatchdayNeedsManagerDesks / AdvanceTurn: after preparation and manager-order shuffling,
// F6 (MatchdaySetup_MatchdayNeedsManagerDesks_RuntimeField == 0) admits the whole manager desk loop only if a manager plays.
// Postponed/already played league fixtures do not count. Opening/closing season
// desks, national friendlies and the Source auto-continue latch retain their gates.
// Read-only; callers still simulate an event whose desks are skipped.
bool matchday_needs_manager_desks(const GameState&, uint16_t calendar_entry,
const std::vector<MatchGroup>&);
// CycleManagerOptions: option byte 0 of every human manager moves on to the next setting that
// is enabled in the manager record (+0x218, a bit mask of settings 1-8).
void cycle_manager_options(GameState& g);
// MatchModeBits plus the flags added by BuildSideRecords: the "mode bits" passed to the
// attendance. Bits 0-4 a crowd interest value (per competition type, rising towards the
// end of the league season), 0x20 random spread, 0x80 no league match, 0x100 cup of
// class 1, 0x200 other cups.
int match_mode_bits(const GameState& g, const MatchGroup& grp, const MatchdayContext& ctx, MinuteReport& report);
// Attendance: attendance of a match. For a human home club also the gate and kiosk
// income, the attendance statistics of its record and a possible riot (message, damage).
// competition_type = byte 0 of the group descriptor (MatchdaySetupRuntimeField14). Bits 0x180
// select cup gate sharing, including the away human manager's income/statistics.
int attendance(GameState& g, int home, int away, int bits, int temperature, int rain, int competition_type,
GameRandom& game, WatcomRandom& rand, MinuteReport& report);
// PrepareEvent(ManagerCount, NextDeskManager): shuffles the order of the human managers' pre-match
// desks in place - the order of the matchday before is shuffled again, not 0, 1, ... - and
// returns it (manager indices). One game draw per manager: entry i swaps with entry G(0, n - 1).
std::vector<int> shuffle_manager_order(GameState& g, GameRandom& game);
// The start of FinishEvent up to the first minute: flags, void masks, attendance and side
// records for every match of every group, including the live match choice (AutoLineup) and
// the man marking of human managers (KickOff). Human teams draw from `game` in their
// ratings (team_rating).
void kick_off(GameState& g, std::vector<MatchGroup>& groups, const MatchdayContext& ctx, WatcomRandom& rand,
GameRandom& game, MinuteReport& report, bool select_sportschau = false,
uint16_t club_threshold = 90);
} // namespace bmh
namespace bmh {
// CurrentMatchday = WatcomRandom(0, 10000), drawn by AdvanceTurn after the preparation (kept
// in the savegame).
inline void draw_matchday_number(GameState& g, WatcomRandom& rand) {
const int v = rand.range(0, 10000);
if (g.memory.has(::bmh::layout::CurrentMatchday)) g.memory.set32(::bmh::layout::CurrentMatchday, uint32_t(v));
}
} // namespace bmh
namespace bmh {
// BuildPoolsCoupon, at a human manager's pre-match desk: the pools coupon (block DeskActions_SubmitPoolsCoupon_RuntimeField) - up
// to 11 of today's matches between clubs of similar strength (team_average 0x1ff within
// 17); CareerSession_DispatchToto_RuntimeField = their number.
// Teams without a squad (national teams) draw their average from `rand` (TeamRating).
void build_pools_coupon(GameState& g, const std::vector<MatchGroup>& groups, WatcomRandom* rand = nullptr);
// EvaluatePoolsCoupon(0) at full time of that matchday: the results of the coupon's matches,
// MatchdaySetup_EvaluatePoolsCoupon_RuntimeField[i] = 1 home win, 0 draw, 2 away win.
void evaluate_pools_coupon(GameState& g, const std::vector<MatchGroup>& groups);
// EvaluatePoolsCoupon(1) at the end of the matchday: with 11 matches on the coupon every human
// manager's tip (Coupon + manager * 0x14: stake u32, tips +8..+0x12) is settled - the
// stake is booked (BookMoney2, may fail: "Ihr Tototipp wurde nicht berücksichtigt ..."
// MatchdaySetup_SettlePoolsCoupon_TextPointer), the hits counted (+0x13), from 9 on the stake times the quota
// (MatchdaySetupRuntimeField13: 10, 20, 50) is won (+4) and booked; the stake is cleared. The coupon's
// matches are counted again in the groups of the matchday (CareerSession_DispatchToto_RuntimeField; the outcomes stay
// those read after the second half, PoolsOpenFlag / MatchdaySetup_EvaluatePoolsCoupon_RuntimeField). The toto screen
// it shows (LeagueTableRangeDialog) draws nothing.
void settle_pools_coupon(GameState& g, const std::vector<MatchGroup>& groups);
} // namespace bmh
+82
View File
@@ -0,0 +1,82 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// The static data of the original (its data object, LE addresses GermanDataSegmentBegin-layout field) as far
// as the savegame stores it.
//
// Many parts of the original work on small global tables that point at each other, e.g.
// the cup table at CupTable whose entries hold pointers to team lists and result arrays in
// other globals. Porting every one of them into a typed field would lose that structure,
// so they are kept here as raw memory addressed like in the original. The pointers stored
// in such tables are guest linear addresses: data address + kGuestDataBase.
//
// Blocks that GameState also decodes into typed fields (squads, players, results, ...)
// must be read and written through those fields; their copies here are not kept current.
#include <cstdint>
#include <cstdio>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#include "formats/savestate.hpp"
namespace bmh {
// Offset between the LE addresses of the data object and the guest linear addresses the
// original stores in pointers (DOS/4GW loads the data object at relocated data-segment base).
constexpr uint32_t kGuestDataBase = 0x1a2000;
class StaticMemory {
public:
StaticMemory() = default;
// All non-heap blocks of a savegame.
explicit StaticMemory(const SaveState& save) {
for (const SaveBlock& b : save.blocks())
if (!b.heap && b.size != 0 && !blocks_.count(b.address))
blocks_[b.address].assign(save.stream().begin() + b.offset, save.stream().begin() + b.offset + b.size);
}
// A global the savegame does not store (e.g. a work list the original rebuilds before
// use): created zeroed unless it is there already.
void add_block(uint32_t address, size_t size) {
if (!has(address)) blocks_[address].assign(size, 0);
}
bool has(uint32_t address) const {
auto it = blocks_.upper_bound(address);
if (it == blocks_.begin()) return false;
--it;
return address - it->first < it->second.size();
}
uint8_t& at(uint32_t address) {
auto it = blocks_.upper_bound(address);
if (it != blocks_.begin()) {
--it;
if (address - it->first < it->second.size()) return it->second[address - it->first];
}
throw std::out_of_range("static memory: address " + hex(address) + " is not in the savegame");
}
uint8_t u8(uint32_t a) const { return const_cast<StaticMemory*>(this)->at(a); }
uint16_t u16(uint32_t a) const { return uint16_t(u8(a) | u8(a + 1) << 8); }
uint32_t u32(uint32_t a) const { return uint32_t(u16(a) | uint32_t(u16(a + 2)) << 16); }
void set8(uint32_t a, uint8_t v) { at(a) = v; }
void set16(uint32_t a, uint16_t v) { at(a) = uint8_t(v), at(a + 1) = uint8_t(v >> 8); }
void set32(uint32_t a, uint32_t v) { set16(a, uint16_t(v)), set16(a + 2, uint16_t(v >> 16)); }
// A pointer stored in the original's memory, as an LE data address (0 stays 0).
uint32_t pointer(uint32_t a) const {
uint32_t p = u32(a);
return p == 0 ? 0 : p - kGuestDataBase;
}
void set_pointer(uint32_t a, uint32_t address) { set32(a, address == 0 ? 0 : address + kGuestDataBase); }
private:
static std::string hex(uint32_t v) {
char b[16];
std::snprintf(b, sizeof b, "0x%x", v);
return b;
}
std::map<uint32_t, std::vector<uint8_t>> blocks_;
};
} // namespace bmh
+153
View File
@@ -0,0 +1,153 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/messages.hpp"
#include <algorithm>
#include <cstdio>
namespace bmh {
namespace {
uint32_t rd32(const std::vector<uint8_t>& v, size_t o) {
return uint32_t(v.at(o) | v.at(o + 1) << 8 | v.at(o + 2) << 16) | uint32_t(v.at(o + 3)) << 24;
}
void wr32(std::vector<uint8_t>& v, size_t o, uint32_t x) {
for (int i = 0; i < 4; i++) v.at(o + size_t(i)) = uint8_t(x >> (8 * i));
}
} // namespace
void post_message(GameState& g, int64_t recipients, const std::vector<uint8_t>& text) {
std::vector<uint8_t>& box = g.mailbox;
if (box.size() < kMailboxEntries * kMailboxEntry) return; // no mailbox loaded
size_t index = 0;
while (index < kMailboxEntries && rd32(box, index * kMailboxEntry) != 0) index++;
size_t at;
if (index == kMailboxEntries) {
// DropOldestMessage: drop the oldest entry, unread ones count as newer
uint32_t best = 0x7FFFFFFF, key = 0;
size_t oldest = 0;
for (size_t k = 0; k < kMailboxEntries; k++) {
const size_t e = k * kMailboxEntry;
if (rd32(box, e + 4) != 0) key = 0xF0000;
key |= uint32_t(box[e + 8]) << 8 | box[e + 9];
if (key < best) best = key, oldest = k;
}
if (oldest != kMailboxEntries - 1)
std::copy(box.begin() + long((oldest + 1) * kMailboxEntry), box.end(), box.begin() + long(oldest * kMailboxEntry));
at = (kMailboxEntries - 1) * kMailboxEntry;
box[at] = 0;
} else {
at = index * kMailboxEntry;
}
uint32_t mask;
if (recipients == -1) mask = (0xFFFFFFFFu >> (32 - g.manager_teams.size())) | 0x80000000u;
else if (recipients & 0x80000000) mask = uint32_t(recipients);
else mask = 1u << uint32_t(recipients);
// PostMessage ORs the recipient mask into MailboxRecipientMask. It is a runtime
// global absent from normal FBMs; add_block deliberately keeps it out of
// save serialization while preserving the Source address and bit layout.
g.memory.add_block(::bmh::layout::MailboxRecipientMask, 4);
g.memory.set32(::bmh::layout::MailboxRecipientMask, g.memory.u32(::bmh::layout::MailboxRecipientMask) | mask);
wr32(box, at, mask);
wr32(box, at + 4, 0);
const uint16_t date = uint16_t(std::min<uint32_t>(g.date, 0xFFFF));
box[at + 8] = uint8_t(date >> 8);
box[at + 9] = uint8_t(date);
for (size_t i = 0; i < kMailboxText; i++) box[at + 10 + i] = i < text.size() ? text[i] : 0;
}
void post_text(GameState& g, int64_t recipients, size_t text_id) {
if (!g.texts) return;
post_message(g, recipients, g.texts->raw(text_id, kMailboxText));
}
void post_composed(GameState& g, int64_t recipients, const std::string& text) {
post_message(g, recipients, std::vector<uint8_t>(text.begin(), text.end()));
}
int compare_mailbox(const std::vector<uint8_t>& ours, const std::vector<uint8_t>& theirs, std::string* first) {
int diffs = 0;
for (size_t k = 0; k < kMailboxEntries && (k + 1) * kMailboxEntry <= std::min(ours.size(), theirs.size()); k++) {
const size_t e = k * kMailboxEntry;
bool same = std::equal(ours.begin() + long(e), ours.begin() + long(e + 10), theirs.begin() + long(e));
for (size_t i = 10; i < kMailboxEntry && same; i++) {
if (ours[e + i] != theirs[e + i]) same = false;
if (theirs[e + i] == 0) break; // end of the text
}
if (rd32(theirs, e) == 0 && rd32(ours, e) == 0) same = true; // both empty
if (!same) {
if (diffs == 0 && first) {
char b[64];
std::snprintf(b, sizeof b, "entry %zu", k);
*first = b;
}
diffs++;
}
}
return diffs;
}
} // namespace bmh
namespace bmh {
std::string message_text(const GameState& g, uint32_t pointer_variable) {
return g.texts ? (*g.texts)[text_id(pointer_variable)] : std::string();
}
std::string message_text_following(const GameState& g, uint32_t pointer_variable) {
if (!g.texts) return {};
const size_t id = text_id(pointer_variable);
if (id >= g.texts->offsets.size()) return {};
const auto& bytes = g.texts->blob;
size_t at = g.texts->offsets[id];
if (at >= bytes.size()) return {};
while (at < bytes.size() && bytes[at] != 0) ++at;
if (at == bytes.size()) return {};
++at;
std::string text;
while (at < bytes.size() && bytes[at] != 0) text.push_back(char(bytes[at++]));
return text;
}
std::string format_number(const GameState& g, int32_t value, int flags) {
if (flags & 0x100) {
// ConvertCurrency: currency conversion (1/1 unless the savegame says otherwise)
const int32_t mul = g.memory.has(::bmh::layout::CurrencyMultiplier) ? int32_t(g.memory.u32(::bmh::layout::CurrencyMultiplier)) : 1;
const int32_t div = g.memory.has(::bmh::layout::CurrencyDivisor) ? int32_t(g.memory.u32(::bmh::layout::CurrencyDivisor)) : 1;
if (div != 0) value = value * mul / div;
}
// FormatGroupedDigits: digits from the right; with grouping (bit 0x40 clear) a dot before the
// 4th, 8th and 12th character; padded to the width (bits 0-5), leading blanks for the
// dots a wide field reserves
const bool group = !(flags & 0x40);
const int width = flags & 0x3F;
int blanks = group && width > 3 ? (width - 4) / 3 + 1 : 0;
const bool negative = value < 0;
uint32_t v = negative ? uint32_t(-int64_t(value)) : uint32_t(value);
std::string reversed;
int dots = 0;
while (v != 0) {
const size_t n = reversed.size();
if (group && (n == 3 || n == 7 || n == 11)) reversed.push_back('.'), blanks--, dots++;
reversed.push_back(char('0' + v % 10));
v /= 10;
}
if (!group) blanks = 0;
while (int(reversed.size()) < width + dots - (negative ? 1 : 0)) reversed.push_back(reversed.empty() ? '0' : '%');
for (int i = 0; i < blanks; i++) reversed.push_back(' ');
if (negative) reversed.push_back('-');
std::string s(reversed.rbegin(), reversed.rend());
if (flags & 0x100) {
// FLTD FormatAmount uses the pound prefix at CurrencyPrefixText.
if (g.currency_suffix == " &") s = "& " + s;
else s += g.currency_suffix; // CurrencySuffixText
}
return s;
}
std::string format_amount(const GameState& g, int32_t value) { return format_number(g, value, 0x101); }
} // namespace bmh
+70
View File
@@ -0,0 +1,70 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#pragma once
// The managers' mailbox (heap block *ManagerMailbox, saved in the savegame).
//
// 40 entries of 0xA0 bytes (PostMessage):
// +0x00 u32 recipients: bit n = human manager n, bit 31 = a general message
// +0x04 u32 read by (bit per manager)
// +0x08 date (CalendarDay) as big-endian u16
// +0x0a 0x96 bytes of text, copied blindly from the source - for texts taken straight
// from TEXTD.BLK the following texts come along; for composed messages the rest
// of the caller's buffer (not reproducible, see compare_mailbox)
// When the box is full the oldest entry (read ones first) is dropped (DropOldestMessage).
#include <cstdint>
#include <string>
#include <vector>
#include "game/state.hpp"
namespace bmh {
constexpr size_t kMailboxEntries = 40;
constexpr size_t kMailboxEntry = 0xA0;
constexpr size_t kMailboxText = 0x96;
// PostMessage. recipients: a manager index, -1 = all managers, or a mask with bit 31 set.
void post_message(GameState& g, int64_t recipients, const std::vector<uint8_t>& text);
// A text of TEXTD.BLK as the original posts it (0x96 bytes from its start).
void post_text(GameState& g, int64_t recipients, size_t text_id);
// A composed message (only the text itself is known; the rest of the entry is zero).
void post_composed(GameState& g, int64_t recipients, const std::string& text);
// Differences between two mailboxes, comparing the text of each entry only up to its NUL
// (the bytes after it may be stack contents of the original).
int compare_mailbox(const std::vector<uint8_t>& ours, const std::vector<uint8_t>& theirs, std::string* first = nullptr);
} // namespace bmh
namespace bmh {
// Text id of a pointer variable of the text table TextPointerTable (e.g. Weekly_AdvertisingOffers_TextPointer).
constexpr size_t text_id(uint32_t pointer_variable) { return (pointer_variable - ::bmh::layout::TextPointerTable) / 4; }
} // namespace bmh
namespace bmh {
// Text of a pointer variable of the text table (TEXTD.BLK), empty without texts.
std::string message_text(const GameState& g, uint32_t pointer_variable);
// The next NUL-delimited string in the same loaded text block; empty if absent.
std::string message_text_following(const GameState& g, uint32_t pointer_variable);
// Contract warning loaded from the selected game image.
inline std::string kContractEndsSoonText;
inline std::string kMastersQualificationText;
inline std::string kMastersWinnerText;
inline std::string kIndoorInvitationText;
inline std::string kChampionshipBonusText;
inline std::string kFriendlyPayerPrefixText;
// FormatNumber(buf, value, 0x101, ""): an amount of money as the messages show it: the
// value converted with CurrencyMultiplier / CurrencyDivisor, digits grouped by dots, then " EU".
std::string format_amount(const GameState& g, int32_t value);
// FormatNumber(buf, value, flags, ""): bits 0-5 the field width, bit 0x40 no dot grouping,
// bit 0x100 an amount of money (converted, " EU" appended).
std::string format_number(const GameState& g, int32_t value, int flags);
} // namespace bmh
+1007
View File
File diff suppressed because it is too large. Load diff
+83
View File
@@ -0,0 +1,83 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// The month change (DayStepRest2), run by the day step (DayStepRest) of the first day of
// a month in the full game (CompetitionSelection bit 0), after the training / weekly processing:
//
// 1. advertising contracts of the human managers count down (record +0xa34, 18 x 0xC)
// 2. new players on the transfer list (CareerFirstSteps): free agents of the pool and players
// the computer clubs want to sell
// 3. loaned players whose time is up return to their clubs (table Career_RemoveJoinLoans_RuntimeField)
// 4. per human manager: the monthly ratings (ManagerMatchRecord2), expenses minus income, and the
// monthly bookkeeping of every squad player on the tactics board (contract months,
// mood, value history, retirement wishes)
// 5. share prices grow, dividends and loans between managers are booked (MonthChange2)
//
// Monthly bookkeeping uses Watcom draws; player moves also require the game RNG.
// Human decisions use caller-supplied contract/loan presenters. Missing context
// and invalid state report through MinuteReport, rather than guessing a decision.
#include <array>
#include <cstdint>
#include "game/match_engine.hpp"
#include "game/random.hpp"
#include "game/state.hpp"
namespace bmh {
// `game` is needed when a player leaves at the end of his contract (MonthChange).
void month_change(GameState& g, WatcomRandom& rand, MinuteReport& report, GameRandom* game = nullptr);
// CareerFirstSteps: new players on the transfer list (part of the month change; also at the
// start of a season).
void new_transfer_list_entries(GameState& g, WatcomRandom& rand, MinuteReport& report);
// AddToSquad(slot, loan, percent, &fee, &salary, years, extra): market value (fee) and
// salary of the player in an absolute squad slot, from strength, age, position and
// experience; `percent` scales the fee, `years` - 1 steps of expected development raise
// it, `extra` * (11 - age) percent change the salary. A fee below 50000 is replaced by W(50000,
// 80000); a loan (1) costs a quarter.
void market_value(const GameState& g, int slot, int loan, int percent, uint32_t& fee, uint32_t& salary, int years,
int extra, WatcomRandom& rand);
// ContractBonuses, the salary page of the contract talks (contracts screen InstallDefaultHooks): the
// four demands for 1-4 years when the talks open, AddToSquad with the level + 100 percent
// and the salary rise for the years beyond the current contract, times the player's mood
// (+0xd) / 100. Opened from the desk (`from_desk`, param_5 0x80) a player of 36 or more
// at the end of the term, or one flagged 0x20 / 0x40, wants no contract (no-contract sentinel).
std::array<uint32_t, 4> contract_demands(GameState& g, int manager, int row, bool from_desk, WatcomRandom& rand);
// ContractBonuses "OK" with an offer for `column` + 1 years against that column's demand: W(8, 12)
// (loyalty from the months at the club, +0x11) and - unless the player asked himself
// (`request`, param_5 0x40) - W(80, 100). The offer plus 80 % of the expected bonus
// (ContractOffer) must reach that percentage of the demand, and the offer itself 61 %.
// Accepted: salary, term and mood (+0x50, +0xc, +0xd) change, AddToSquad for the term.
// Rejected: the player is offended (+0x4f bit 7, mood + 5); for the row whose contract
// ended (`screen_row`) he will not talk again (+0xb bit 6). Returns whether he accepted.
bool contract_offer(GameState& g, int manager, int row, int column, uint32_t offer, uint32_t demand, bool request,
bool screen_row, WatcomRandom& rand,
const std::array<uint8_t, 7>* proposed_bonuses = nullptr);
// ContractBonuses "Prämien" page. `row == -1` edits the squad's shared proposal; each
// stored row is raised to the requested value. A bonus-only submission is accepted only
// when it does not lower any player's current rate, and must change at least one rate.
bool contract_bonuses(GameState& g, int manager, int row, const std::array<uint8_t, 7>& rates);
struct ContractInsuranceResult {
bool accepted = false;
uint16_t monthly_fee = 0;
};
// ContractBonuses insurance button: one-time per player, duration 1..60 months, and insurance
// category bound to the selected 1..4 year term. This action consumes no RNG.
ContractInsuranceResult contract_insurance(GameState& g, int manager, int row, int insurance_type,
uint8_t months);
// SearchProfileNews(manager, list entry, player, 1): tells a human manager about a new player on
// the transfer list that matches his search profile (record +0x1f6 .. +0x207).
void search_profile_news(GameState& g, int manager, uint32_t list, int player);
// Put an existing squad slot on the shared transfer list (human desk action).
bool list_transfer_player(GameState& g, int slot, WatcomRandom& rand, MinuteReport& report);
} // namespace bmh
+234
View File
@@ -0,0 +1,234 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/national.hpp"
#include <algorithm>
#include <cstring>
#include "game/lineup.hpp"
#include "game/match_engine.hpp"
#include "game/month.hpp"
#include "game/weekly.hpp"
namespace bmh {
namespace {
constexpr size_t kManagerRecord = 0xb0c;
constexpr size_t kBoard = 0x840; // one manager's tactics board (24 x 0x58)
constexpr size_t kBoardSlot = 0x58;
constexpr uint32_t kDesktops = ::bmh::layout::Desktops; // desktop layouts, 0x360 per manager slot
constexpr size_t kDesktop = 0x360;
constexpr size_t kPoolSlots = 0xb70; // CareerRuntimeField: the clubs' squads end here
constexpr uint8_t kNominated[4] = {3, 5, 7, 5}; // NationalRuntimeField: keepers, defence, midfield, attack
// the manager's team (record +0x290) as the port caches it
void refresh_manager_teams(GameState& g) {
for (size_t m = 0; m < g.manager_teams.size(); m++) {
const size_t at = m * kManagerRecord + 0x290;
g.manager_teams[m] = int16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8);
}
}
// a byte of the original's static data, created on first use (not every one is saved)
uint8_t& static_byte(GameState& g, uint32_t address) {
if (!g.memory.has(address)) g.memory.add_block(address, 1);
return g.memory.at(address);
}
} // namespace
void swap_manager_slots(GameState& g, int a, int b) {
if (a == b) return;
std::swap_ranges(g.manager_records.begin() + long(size_t(a) * kManagerRecord),
g.manager_records.begin() + long(size_t(a + 1) * kManagerRecord),
g.manager_records.begin() + long(size_t(b) * kManagerRecord));
std::swap_ranges(g.tactics.begin() + long(size_t(a) * kBoard), g.tactics.begin() + long(size_t(a + 1) * kBoard),
g.tactics.begin() + long(size_t(b) * kBoard));
if (g.memory.has(kDesktops))
for (size_t i = 0; i < kDesktop; i++) {
const uint32_t pa = kDesktops + uint32_t(size_t(a) * kDesktop + i);
const uint32_t pb = kDesktops + uint32_t(size_t(b) * kDesktop + i);
const uint8_t t = g.memory.u8(pa);
g.memory.set8(pa, g.memory.u8(pb));
g.memory.set8(pb, t);
}
refresh_manager_teams(g);
}
int add_to_squad(GameState& g, int manager, int from_slot, int squad_start, WatcomRandom& rand) {
// FirstFreeSlotSquad(start, 0x18): the first free slot of the squad
int slot = -1;
for (int s = squad_start; s < squad_start + 24; s++)
if (g.squad_slots.at(size_t(s)) == kEmptySlot) {
slot = s;
break;
}
if (slot < 0) return -1; // (the original shows the message PendingOffer_FormatError_ExecutableField)
g.squad_slots.at(size_t(slot)) = g.squad_slots.at(size_t(from_slot));
new_board_entry(g, manager, slot - squad_start, slot, rand);
return slot;
}
void new_board_entry(GameState& g, int manager, int index, int slot, WatcomRandom& rand) {
uint8_t* e = &g.tactics.at(size_t(manager) * kBoard + size_t(index) * kBoardSlot);
std::memset(e + 7, 0, 3);
std::memset(e + 0x19, 0, 0x24);
e[10] = 2;
for (int k = 0; k < 4; k++) e[2 + k] = index < 2 ? 1 : uint8_t(rand.range(2, 0x27));
e[0x3f] = 0xff;
e[0x46] = 0xff, e[0x47] = 0x0f; // u16 0xfff
e[0x44] = 0xff, e[0x45] = 0x0f;
e[0] = 10;
e[1] = 4;
e[0xe] = 0x59;
e[0xf] = uint8_t(rand.range(0x28, 0x3c));
e[0x11] = 0;
e[0x43] = 0;
e[0x4e] = 0, e[0x4f] = 0;
e[0x3d] = index < 11 ? 0 : index <= 0x10 ? 1 : 2;
e[0xc] = 0x18;
// AddToSquad(slot, 0, W(95, 105), &fee, &salary (+0x50), 2 years, no extra)
const int percent = rand.range(0x5f, 0x69);
uint32_t fee = 0, salary = 0;
market_value(g, slot, 0, percent, fee, salary, 2, 0, rand);
for (int k = 0; k < 4; k++) e[0x50 + k] = uint8_t(salary >> (8 * k));
std::memset(e + 0x12, 0, 7);
}
bool national_team_day(GameState& g, WatcomRandom& rand, MinuteReport& report) {
StaticMemory& mem = g.memory;
const SquadRange national = squad_range(kNoTeam);
// NationalSquadEmptied: the national squad is emptied
for (size_t s = national.first; s < national.first + national.count; s++) g.squad_slots.at(s) = kEmptySlot;
// SwapManagerSlots2 (called whether or not a take-over is already in effect): a manager flagged
// as Bundestrainer takes the national team over in slot 0. ActiveManager is what the day
// step's manager loop (DayStepRest) leaves: the number of managers.
(void)mem;
(void)report;
national_coach_take_over(g, int(g.manager_teams.size()), uint16_t(g.date - g.season_start));
const uint8_t coach = static_byte(g, ::bmh::layout::CoachActive); // CoachActive
if (coach == 0) swap_manager_slots(g, 4, 0); // slot 0 becomes the spare slot 4
// the strongest available German players per position (NationalRuntimeField of each), kept in
// ascending order: a stronger one pushes the weakest out
int16_t best[4][7] = {}, slots[4][7] = {};
for (size_t s = 0; s < kPoolSlots; s++) {
const int id = g.squad_slots.at(s) & 0xfff;
if (id == 0xfff) continue;
const Player& p = g.players.at(size_t(id));
const bool fit = (p.w35c >> 27) == 0 || ((p.w364 >> 16) & 0x1f) == 0;
if (!fit || nationality(g, id) != 0) continue;
const int pos = int(p.w364 & 3);
int16_t strength = int16_t(p.strength(false)); // Strength(w35c, 0)
if (pos > 1) strength = int16_t(strength + ((p.w364 >> 2) & 0x3f) + (((p.w368 >> 18) & 0x3f) >> 1));
if (s > 0x86f) strength = int16_t((strength * 0xb) / 10); // (the clubs from slot 0x870 on)
int i = 0;
// NationalTeamDay caps the insertion index at the positional quota. Guard
// before indexing: the full seven-player row has no C++ eighth element.
while (i < kNominated[pos] && strength > best[pos][i]) i++;
if (i == 0) continue;
const int j = i - 1;
// Int16T: entries 1..j move down one place, the new one takes place j
for (int k = 0; k < j; k++) best[pos][k] = best[pos][k + 1], slots[pos][k] = slots[pos][k + 1];
best[pos][j] = strength;
slots[pos][j] = int16_t(s);
}
// PendingOfferAnswer for each, weakest first, into the board of slot 0
for (int pos = 0; pos < 4; pos++)
for (int k = 0; k < kNominated[pos]; k++) add_to_squad(g, 0, slots[pos][k], int(national.first), rand);
// Int2(0x165, 0xe4) with manager 0's option byte (ManagerAutomation) at 1
const uint8_t option = g.manager_options.at(0);
g.manager_options.at(0) = 1;
try {
auto_lineup(g, kNoTeam, 0xe4);
} catch (const std::exception& ex) {
report.fail(std::string("national team line-up: ") + ex.what());
}
if (coach == 0) swap_manager_slots(g, 4, 0);
g.manager_options.at(0) = option;
return coach != 0; // (with a Bundestrainer his desk follows: AdvanceTurn's local_28 = 4)
}
// ---------------------------------------------------------------------------------------
// The Bundestrainer (national coach). A manager flagged in his record (+0x21c), every
// manager in the world game without leagues (CompetitionSelection == 2) and the only manager of a
// one-manager game coaches the national team on international days: SwapManagerSlots2 moves his
// slot 0 to the spare slot 4 and puts the national team's record (kept in slot 4 between the
// international periods) into slot 0; NationalCoachHandBack swaps them back. CoachActive tells
// whether the swap is in effect, OriginalManagerCount keeps the number of managers meanwhile.
namespace {
void set_manager_count(GameState& g, int managers) {
static_byte(g, ::bmh::layout::ManagerCount) = uint8_t(managers); // ManagerCount
g.manager_teams.assign(size_t(managers), 0); // (the typed copy, one entry per manager)
}
} // namespace
void national_coach_take_over(GameState& g, int active_manager, uint16_t source_season_day) {
StaticMemory& mem = g.memory;
int managers = int(g.manager_teams.size());
static_byte(g, ::bmh::layout::OriginalManagerCount) = uint8_t(managers); // OriginalManagerCount = ManagerCount
static_byte(g, ::bmh::layout::ClubPlayerDetail_InvalidArgument_RuntimeField3) = uint8_t(active_manager); // ClubPlayerDetail_InvalidArgument_RuntimeField3 = ActiveManager
// DaysIntoSeason == 1 (the first day after the saved season origin): the national team's
// mood byte loses its top bit before coach eligibility is checked.
const bool first_day = source_season_day == 1;
if (first_day) g.team_morale.at(kNoTeam) &= 0x7f;
const bool world_only = mem.u32(::bmh::layout::CompetitionSelection) == 2;
// (the loop bound is ManagerCount itself, which a take-over sets to 1)
for (int m = 0; m < managers; m++) {
uint8_t* rec = &g.manager_records.at(size_t(m) * kManagerRecord);
if (rec[0x21c] == 0 && !world_only && managers != 1) continue;
// the national team's record (slot 4) gets the coach's portrait (+0x221) and name
// (+0xa8, StrcpySoHallReplacesItsCurrentTournament = strcpy)
uint8_t* spare = &g.manager_records.at(4 * kManagerRecord);
spare[0x221] = rec[0x221];
for (size_t i = 0;; i++) {
spare[0xa8 + i] = rec[0xa8 + i];
if (rec[0xa8 + i] == 0) break;
}
managers = 1;
set_manager_count(g, 1);
swap_manager_slots(g, 4, 0); // SwapManagerSlots(4, 0)
uint8_t* coach = &g.manager_records.at(0);
coach[0x290] = uint8_t(kNoTeam & 0xff), coach[0x291] = uint8_t(kNoTeam >> 8); // CupDraw_FormatError_RuntimeField2 = 0x165
coach[0x218] = g.manager_records.at(4 * kManagerRecord + 0x218); // NationalRuntimeField2 = NationalRuntimeField3
g.manager_teams.at(0) = kNoTeam;
auto_lineup(g, kNoTeam, 0xe4); // Int2(0x165, 0xe4)
static_byte(g, ::bmh::layout::CoachActive) = 1;
if (first_day) g.team_morale.at(kNoTeam) |= 0x80;
}
}
void national_coach_hand_back(GameState& g) {
if (static_byte(g, ::bmh::layout::CoachActive) == 0) return;
const int managers = static_byte(g, ::bmh::layout::OriginalManagerCount);
set_manager_count(g, managers); // ManagerCount = OriginalManagerCount
swap_manager_slots(g, 4, 0); // SwapManagerSlots(4, 0) (refreshes the typed teams)
static_byte(g, ::bmh::layout::CoachActive) = 0;
}
bool national_coach_active(const GameState& g) { return !g.manager_teams.empty() && g.manager_teams[0] == kNoTeam; }
void national_coach_after_load(GameState& g) {
// NationalCoachAfterLoad's end, loading as well as saving: the take-over is done again
if (g.memory.has(::bmh::layout::CoachActive) && g.memory.u8(::bmh::layout::CoachActive) != 0)
national_coach_take_over(g, g.memory.has(::bmh::layout::ActiveManager) ? g.memory.u8(::bmh::layout::ActiveManager) : 0,
uint16_t(g.date - g.season_start));
}
GameState national_coach_save_form(const GameState& g) {
// NationalCoachAfterLoad's start: the slots swapped back, CoachActive kept at 1
GameState s = g;
if (s.memory.has(::bmh::layout::CoachActive) && s.memory.u8(::bmh::layout::CoachActive) != 0) {
national_coach_hand_back(s);
s.memory.set8(::bmh::layout::CoachActive, 1);
}
return s;
}
} // namespace bmh
+65
View File
@@ -0,0 +1,65 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// The national team (BMH.exe V2.24 + supported rule profile patch), team id 0x165 (kNoTeam), squad slots
// 0xc00-0xc17 (LargeSquadClubCount).
//
// With the world game on (CompetitionSelection bit 1) the calendar holds national team days (entry
// 0x4006, DayCompetitions -> national-only flag). On such a day AdvanceTurn calls NationalTeamDay, which
// nominates the squad: the manager slots are swapped so that slot 0 is a spare one
// (SwapManagerSlots(4, 0); a Bundestrainer instead takes slot 0 over with the national team,
// SwapManagerSlots2), the 3 goalkeepers, 5 defenders, 7 midfielders and 5 forwards
// (NationalRuntimeField) of the highest strength among the available German players of all clubs
// join the national squad with a fresh tactics board entry (PendingOfferAnswer), the national team
// gets its line-up (Int2(0x165, 0xe4)) and the slots are swapped back. Without a
// Bundestrainer the day then prepares an empty matchday (no desk, no match).
#include "game/random.hpp"
#include "game/state.hpp"
namespace bmh {
struct MinuteReport;
// SwapManagerSlots(a, b): manager slots a and b change places - the manager records (0xb0c
// bytes), the tactics boards (0x840) and the desktop layouts (block Desktops, 0x360).
void swap_manager_slots(GameState& g, int a, int b);
// PendingOfferAnswer(manager, from_slot, -1, squad_start): the player of the absolute squad slot
// `from_slot` gets the first free slot of the squad starting at `squad_start` (24 slots;
// the slot value is copied with its flags) and a fresh entry on the tactics board of
// manager slot `manager`: neutral settings, familiarity W(40, 60), the four attribute
// bytes W(2, 39) each (1 for the first two places) and the salary of a 2-year contract
// at W(95, 105) percent (AddToSquad). Returns the new absolute slot, -1 if the squad is full.
int add_to_squad(GameState& g, int manager, int from_slot, int squad_start, WatcomRandom& rand);
// The board part of PendingOfferAnswer (also called with a given place `index`): the entry of
// the player in absolute squad slot `slot` on the tactics board of `manager`.
void new_board_entry(GameState& g, int manager, int index, int slot, WatcomRandom& rand);
// NationalTeamDay: the national team day (see above). Returns whether a Bundestrainer manages
// the national team (CoachActive) - then his desk follows (AdvanceTurn: local_28 = 4).
bool national_team_day(GameState& g, WatcomRandom& rand, MinuteReport& report);
// The Bundestrainer (national coach), see national.cpp. SwapManagerSlots2: notes the number of
// managers (OriginalManagerCount) and `active_manager` (ClubPlayerDetail_InvalidArgument_RuntimeField3 = ActiveManager); a manager
// flagged in his record (+0x21c), every manager in the world game without leagues
// (CompetitionSelection == 2) and the only manager of a one-manager game takes the national team over:
// the national team's record (slot 4) gets his name and portrait, the number of managers
// becomes 1, slots 4 and 0 change places, slot 0 manages team 0x165 and copies +0x218 from
// slot 4, the national team gets its line-up (Int2(0x165, 0xe4)) and
// CoachActive = 1.
// `source_season_day` is the 16-bit value visible in DaysIntoSeason at this exact Source call
// site. It is not always `g.season_day()`: DailyInterest advances the counter before
// quiet-day rest but after rest on the completed-event path.
void national_coach_take_over(GameState& g, int active_manager, uint16_t source_season_day);
// NationalCoachHandBack: with CoachActive set the slots change places again, the number of managers
// is restored from OriginalManagerCount and CoachActive cleared.
void national_coach_hand_back(GameState& g);
// CupDraw_FormatError_RuntimeField2 == 0x165: slot 0 manages the national team.
bool national_coach_active(const GameState& g);
// NationalCoachAfterLoad (saving and loading): the savegame holds the slots swapped back with
// CoachActive still 1; afterwards (and so after loading) SwapManagerSlots2 takes over again.
void national_coach_after_load(GameState& g);
// The state as NationalCoachAfterLoad writes it (for the savegame writer and comparisons).
GameState national_coach_save_form(const GameState& g);
} // namespace bmh
+395
View File
@@ -0,0 +1,395 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/other_games.hpp"
#include <algorithm>
#include <array>
#include <stdexcept>
#include <utility>
#include "formats/binary.hpp"
#include "game/cup.hpp"
#include "game/schedule.hpp"
namespace bmh {
namespace {
constexpr uint32_t kActiveSelectors = ::bmh::layout::ActiveSelectors;
constexpr uint32_t kSelectorCount = 8;
constexpr size_t kTextCompetitionNames = (::bmh::layout::CupDraw_FormatError_ExecutableField6 - ::bmh::layout::TextPointerTable) / 4;
constexpr size_t kTextCompetitionButtonNames = (::bmh::layout::OtherGames_Layout_ExecutableField - ::bmh::layout::TextPointerTable) / 4;
constexpr size_t kTextRoundHeadings = (::bmh::layout::CupDraw_FormatError_ExecutableField4 - ::bmh::layout::TextPointerTable) / 4;
constexpr size_t kTextGroupRound = (::bmh::layout::Calendar_Information_TextPointer2 - ::bmh::layout::TextPointerTable) / 4;
constexpr size_t kTextGroupCaption = (::bmh::layout::CupDraw_FormatError_ExecutableField5 - ::bmh::layout::TextPointerTable) / 4;
[[noreturn]] void invalid(const char* why) { throw FormatError(std::string("other games: ") + why); }
std::string text(const TextDb& texts, size_t index) {
if (index >= texts.strings.size()) invalid("missing Source TEXTD entry");
return texts.strings[index];
}
bool in_descriptor_table(int entry) { return entry >= 0 && entry < kCupEntries; }
// Bounded port of FindCup's literal scan cursor. On a matching descriptor, its +0x17 link
// wins, else +0x16; a zero link falls back to entry0 in Source. The scan cursor itself advances
// only on a nonmatch and returns the just-followed pointer immediately when the cursor is0.
// Malformed/no-match paths fail closed instead of returning Source's invalid one-past-table ptr.
int resolve_linked_entry(const StaticMemory& memory, int competition, int ordinal) {
if (ordinal < 0 || ordinal >= kCupEntries) invalid("linked occurrence outside Source bounds");
int cursor = 0, current = 0, remaining = ordinal;
std::vector<uint8_t> seen(size_t(kCupEntries) * kCupEntries * kCupEntries, 0);
for (size_t step = 0; step < seen.size(); ++step) {
if (!in_descriptor_table(cursor) || !in_descriptor_table(current))
invalid("Source linked resolver left descriptor table");
const size_t key = (size_t(cursor) * kCupEntries + size_t(current)) * kCupEntries + size_t(remaining);
if (seen[key]) invalid("cycle in Source linked resolver");
seen[key] = 1;
const uint32_t address = cup_entry_address(current);
if (!memory.has(address + 0x19)) invalid("truncated Source descriptor ID");
if (int16_t(memory.u16(address + 0x18)) == competition) {
if (remaining == 0) return current;
const int parallel = int8_t(memory.u8(address + 0x17));
const int next = int8_t(memory.u8(address + 0x16));
if (parallel != 0) current = parallel;
else if (next != 0) current = next;
else invalid("Source linked occurrence reaches its no-link fallback");
if (!in_descriptor_table(current)) invalid("invalid Source linked descriptor link");
--remaining;
if (cursor == 0) return current;
} else {
++cursor;
if (cursor >= kCupEntries) invalid("Source linked resolver cursor wrapped without a match");
current = cursor;
}
}
invalid("Source linked resolver exceeded bounded traversal");
}
std::vector<OtherGamesLinkedPage> source_linked_pages(const StaticMemory& memory, int selected) {
std::vector<OtherGamesLinkedPage> pages;
int first = selected;
std::array<bool, kCupEntries> seen{};
while (in_descriptor_table(first)) {
if (seen[size_t(first)]) invalid("cycle while locating first Source group selector");
seen[size_t(first)] = true;
const uint8_t group = memory.u8(cup_entry_address(first) + 0x1e);
if ((group >> 4) == 0) break;
if (first == 0) invalid("Source group selector would walk before descriptor table");
--first; // InDescriptorTable moves one adjacent descriptor left until group index0.
}
while (true) {
if (!in_descriptor_table(first) || seen[size_t(first)]) {
// The first adjacent scan above marks visited entries; reset its cycle guard before
// following signed previous-stage links.
if (!in_descriptor_table(first)) invalid("invalid Source first group descriptor");
}
seen[size_t(first)] = true;
const int previous = int8_t(memory.u8(cup_entry_address(first) + 0x15));
if (previous == -1) break;
if (!in_descriptor_table(previous) || seen[size_t(previous)]) invalid("invalid Source previous-stage link");
first = previous;
}
// InDescriptorTable suppresses the linked-page selector before enumerating groups when the first
// stage has no +0x16 continuation.
if (memory.u8(cup_entry_address(first) + 0x16) == 0) return pages;
int stage = first;
std::array<bool, kCupEntries> stage_seen{};
while (in_descriptor_table(stage)) {
if (stage_seen[size_t(stage)]) invalid("cycle in Source linked-stage selector");
stage_seen[size_t(stage)] = true;
int group_entry = stage;
const uint8_t count = memory.u8(cup_entry_address(stage) + 0x1e) & 0x0f;
for (int group = 0; group < count; ++group) {
if (!in_descriptor_table(group_entry)) invalid("parallel group left descriptor table");
const uint32_t address = cup_entry_address(group_entry);
pages.push_back({int(pages.size()), group_entry, int16_t(memory.u16(address + 0x18)),
int(memory.u8(address + 0x1e) >> 4), int(count)});
const bool has_adjacent = memory.u8(address + 0x17) != 0;
if (group + 1 < count && !has_adjacent)
invalid("parallel group count lacks adjacent Source entry");
// Source checks +0x17 after every emitted sibling, including the final one; when
// present it advances to the adjacent descriptor before reading its +0x16 stage.
if (has_adjacent) ++group_entry;
}
const int next = int8_t(memory.u8(cup_entry_address(group_entry) + 0x16));
if (next == 0) break;
if (!in_descriptor_table(next)) invalid("invalid Source next-stage selector link");
stage = next;
}
return pages;
}
void validate_team(const GameState& game, uint16_t team) {
// CupGroupOverviewEffects indexes ClubIdentities directly; this screen has no empty-club fallback.
if (team == 0x0fff) invalid("Source row references the empty-club sentinel");
if (team >= game.club_ids.size()) invalid("club id outside loaded name table");
}
OtherGamesRow make_row(const GameState& game, int home, int away, uint16_t result, int match) {
if (home < 0 || home > 0xffff || away < 0 || away > 0xffff) invalid("invalid team id");
const uint16_t h = uint16_t(home), a = uint16_t(away);
validate_team(game, h);
validate_team(game, a);
OtherGamesRow row;
row.home_team = home;
row.away_team = away;
row.home_name = game.club_name(home);
row.away_name = game.club_name(away);
row.source_result = result;
row.played = result != 0xcccc;
if (row.played) {
row.home_goals = (result >> 5) & 0x1f;
row.away_goals = result & 0x1f;
}
row.source_match = match;
return row;
}
OtherGamesClubMetadata source_metadata(const GameState& game, int team) {
OtherGamesClubMetadata out;
bool manager_owned = game.manager_of(team) >= 0;
constexpr size_t kNationalOriginalClub = 4 * 0xb0c + 0x290;
if (!manager_owned && !game.manager_teams.empty() && game.manager_teams[0] == kNoTeam &&
game.manager_records.size() >= kNationalOriginalClub + 2) {
const int original_club = int(uint16_t(game.manager_records[kNationalOriginalClub] |
uint16_t(game.manager_records[kNationalOriginalClub + 1]) << 8));
manager_owned = original_club == team;
}
if (team >= 168 && !manager_owned) {
const size_t at = size_t(team - 168);
if (at >= game.foreign_strength.size()) invalid("missing Source foreign-strength byte");
out.foreign_strength = game.foreign_strength[at];
return out;
}
if (team >= 168 && team != kNoTeam)
invalid("manager-controlled foreign-club row needs live TeamRating W-generator context");
constexpr std::array<uint16_t, 5> kFlags{0x0f1, 0x0f2, 0x0f4, 0x0f8, 0x0ff};
for (size_t i = 0; i < kFlags.size(); ++i)
out.averages[i] = team_average(game, team, kFlags[i]).value;
out.has_squad_values = true;
return out;
}
void attach_source_values(const GameState& game, OtherGamesRow& row) {
row.home_metadata = source_metadata(game, row.home_team);
row.away_metadata = source_metadata(game, row.away_team);
}
void add_second_leg_and_winner(OtherGamesRow& row, uint16_t second, bool present,
bool visible, uint8_t flags) {
row.source_second_leg = second;
row.second_leg_array_present = present;
row.second_leg_visible = visible;
if (present) {
// The second fixture is reversed relative to the primary row: its low field belongs
// to the first displayed club and its high field to the second displayed club.
row.second_leg_home_goals = second & 0x1f;
row.second_leg_away_goals = (second >> 5) & 0x1f;
}
if (row.source_result == 0xcccc) return;
int home = row.home_goals;
int away = row.away_goals;
// CupTie reads the second result whenever the descriptor has an array pointer,
// independently of whether its separate detail line is visible or contains 0xcccc.
const uint16_t winner_second = present ? second : 0;
const int home_total = home + (winner_second & 0x1f);
const int away_total = away + ((winner_second >> 5) & 0x1f);
home = home_total;
away = away_total;
if ((flags & 0x10) && home == away && (row.source_result >> 11) == 0) {
home += winner_second & 0x1f;
away += row.away_goals;
}
row.source_winner = home > away ? 0 : away > home ? 1 : 2;
}
} // namespace
OtherGamesProjection other_games_from_game(const GameState& game, const TextDb& texts,
int competition, int linked_page, int requested_round,
OtherGamesDisplayMode display_mode, int participant_offset,
bool source_new_selection) {
const StaticMemory& memory = game.memory;
if (competition < 0 || competition >= 0x14) invalid("unsupported competition selector");
if (linked_page < 0 || linked_page >= kCupEntries) invalid("invalid linked-page index");
if (!memory.has(kActiveSelectors) || !memory.has(kActiveSelectors + kSelectorCount - 1))
invalid("missing live active-competition selector list");
OtherGamesProjection out;
for (uint32_t i = 0; i < kSelectorCount; ++i) {
const uint8_t id = memory.u8(kActiveSelectors + i);
if (id == 0x14) {
out.selectors.push_back({int(i), -1, {}, false});
continue;
}
if (id > 0x14 || !in_descriptor_table(find_cup(memory, id)))
invalid("active selector has no supported competition descriptor");
out.selectors.push_back({int(i), int(id), text(texts, kTextCompetitionButtonNames + id), true});
}
int entry = resolve_linked_entry(memory, competition, linked_page);
if (source_new_selection) {
std::array<bool, kCupEntries> advanced{};
while (in_descriptor_table(entry)) {
if (advanced[size_t(entry)]) invalid("cycle while advancing completed Source stages");
advanced[size_t(entry)] = true;
const uint32_t at = cup_entry_address(entry);
const uint8_t next = memory.u8(at + 0x16);
if (next == 0) break;
const int count = memory.u8(at + 0x1b);
if (cup_round(memory, entry) < count) break;
if (!in_descriptor_table(next)) invalid("completed stage points outside descriptor table");
entry = next;
}
}
const uint32_t address = cup_entry_address(entry);
const uint8_t flags = memory.u8(address + 0x14);
const int team_count = memory.u8(address + 0x1a);
const int rounds = memory.u8(address + 0x1b);
const int live_round = cup_round(memory, entry);
if (team_count < 0 || team_count > 0x40 || rounds <= 0 || rounds > 0x40)
invalid("descriptor dimensions outside Source bounds");
const int round = requested_round < 0 ? std::min(live_round, rounds - 1) : requested_round;
if (round < 0 || round >= rounds) invalid("requested round outside descriptor");
out.competition = competition;
out.descriptor_competition = int16_t(memory.u16(address + 0x18));
out.linked_page = linked_page;
out.entry_index = entry;
out.entry_address = address;
out.flags = flags;
out.knockout = (flags & 4) != 0;
out.two_legs = (flags & 1) != 0;
out.current_round = live_round;
out.round = round;
out.rounds = rounds;
out.group_index = memory.u8(address + 0x1e) >> 4;
out.group_count = memory.u8(address + 0x1e) & 0xf;
out.title = text(texts, kTextCompetitionNames + size_t(competition));
out.linked_pages = source_linked_pages(memory, entry);
int round_text = ((flags & 4) ? round : 0) + 1 + memory.u8(address + 0x1c);
if (memory.u8(address + 0x1c) == 1 && round == 0) --round_text;
if (round_text < 0 || round_text >= 32) invalid("Source round-heading index outside table");
out.round_heading = text(texts, kTextRoundHeadings + size_t(round_text));
if (kTextRoundHeadings + size_t(round_text) == kTextGroupRound && out.round_heading.size() > 0x10)
out.round_heading[0x10] = char('1' + linked_page);
if (kTextRoundHeadings + size_t(round_text) == kTextGroupCaption && out.round_heading.size() > 0x19)
out.round_heading[0x19] = char('0' + (linked_page == 0 ? 1 : linked_page));
// Source +0x1a is participants in this round. The detail/compact toggle is gated on this
// value, and detail mode's ordinary window is 16 participant slots (eight matches).
out.source_participant_count = team_count >> (round & 31);
out.display_mode_toggle_available = out.source_participant_count > 0x10;
if (display_mode != OtherGamesDisplayMode::compact && display_mode != OtherGamesDisplayMode::detail)
invalid("unknown Source display mode");
const OtherGamesDisplayMode effective_mode = out.source_participant_count <= 0x10
? OtherGamesDisplayMode::detail : display_mode;
out.display_mode = effective_mode;
if (participant_offset < 0 || participant_offset > 0x7f || participant_offset % 0x10 != 0)
invalid("participant window offset is not a Source 16-slot boundary");
// Compact draws the whole round, but the caller separately retains local14.
// Detail redraw only ORs CareerSession_DispatchOtherGames_RuntimeField's high bit; it never resets a retained cursor,
// even when a Source ID-versus-slot selection quirk leaves it past this list.
if (effective_mode == OtherGamesDisplayMode::compact) participant_offset = 0;
out.participant_offset = participant_offset;
out.round_arrows_visible = effective_mode == OtherGamesDisplayMode::detail && rounds > 1;
// CupGroupOverviewEffects selects the second-leg result array only for descriptors with the exact
// two-leg/knockout flags and when the displayed round has reached that leg.
const uint8_t played = memory.u8(address + 0x1d);
const bool second_leg = out.knockout && (played % 2 != 0 || round < played / 2) && (flags & 5) == 5;
// CupGroupOverviewEffects gates the fixture panel if this knockout round is in the future, or any
// descriptor in its +0x15 predecessor chain has not completed all its source rounds.
int predecessor = int8_t(memory.u8(address + 0x15));
std::array<bool, kCupEntries> seen_predecessors{};
while (predecessor != -1) {
if (!in_descriptor_table(predecessor) || seen_predecessors[size_t(predecessor)])
invalid("invalid/cyclic predecessor descriptor chain");
seen_predecessors[size_t(predecessor)] = true;
const uint32_t pred = cup_entry_address(predecessor);
if (cup_round(memory, predecessor) < memory.u8(pred + 0x1b)) out.unfinished_predecessor = true;
predecessor = int8_t(memory.u8(pred + 0x15));
}
out.fixtures_available = !out.unfinished_predecessor && (!out.knockout || round <= live_round);
out.display_mode_toggle_available = out.fixtures_available && out.source_participant_count > 0x10;
if (out.descriptor_competition == 12) out.scheduled_day_mode = true;
// Source paints TEXTD1186 and returns before touching team/result/schedule arrays for a
// blocked future or unfinished stage. Preserve that boundary for incomplete live records.
if (!out.fixtures_available) return out;
const uint32_t team_list = memory.pointer(address);
const uint32_t first_results = memory.pointer(address + 0x0c);
const uint32_t second_results = memory.pointer(address + 0x10);
if (team_count != 0 && team_list == 0) invalid("missing Source team list");
if (team_count != 0 && first_results == 0) invalid("missing Source result list");
if (out.knockout && second_leg && second_results == 0) invalid("missing Source second-leg results");
int participant_base = 0;
std::vector<Fixture> group_fixtures;
if (out.knockout) {
participant_base = uint8_t(cup_round_offset(memory, entry, round));
} else {
const int table_teams = cup_group_schedule_teams(memory, address);
if (table_teams <= 0) invalid("unsupported Source group-round schedule table");
const int rounds_per_leg = rounds / ((flags & 1) + 1);
if (rounds_per_leg <= 0) invalid("invalid group schedule leg count");
group_fixtures = generate_fixtures(table_teams, round + 1, rounds_per_leg, 0);
}
int row_participants = out.knockout ? out.source_participant_count : team_count;
int visible_participants = row_participants;
if (out.knockout && effective_mode == OtherGamesDisplayMode::detail)
visible_participants = std::min(visible_participants, 0x10);
const int begin = participant_offset;
const int end = out.knockout ? std::min(row_participants, begin + visible_participants) : row_participants;
if (out.scheduled_day_mode && !memory.has(::bmh::layout::CalendarState_FormatError_RuntimeField3)) invalid("missing live Source date for scheduled competition");
for (int p = out.knockout ? begin : 0; p + 1 < end; p += 2) {
int home = -1, away = -1, match = p / 2;
size_t result_slot = 0;
if (out.knockout) {
const int slot = participant_base + p;
if (!memory.has(team_list + uint32_t(slot) * 2 + 1)) invalid("truncated Source knockout team list");
home = memory.u16(team_list + uint32_t(slot) * 2);
away = memory.u16(team_list + uint32_t(slot + 1) * 2);
result_slot = size_t(slot / 2);
} else {
const int fixture = p / 2;
if (size_t(fixture) >= group_fixtures.size()) invalid("group fixture count does not match descriptor");
const Fixture& f = group_fixtures[size_t(fixture)];
if (!memory.has(team_list + uint32_t(f.home) * 2 + 1) ||
!memory.has(team_list + uint32_t(f.away) * 2 + 1)) invalid("truncated Source group team list");
home = memory.u16(team_list + uint32_t(f.home) * 2);
away = memory.u16(team_list + uint32_t(f.away) * 2);
result_slot = size_t(round) * size_t(team_count / 2) + size_t(fixture);
}
const uint32_t result_address = first_results + uint32_t(result_slot * 2);
if (!memory.has(result_address + 1)) invalid("truncated Source result list");
const uint16_t result = memory.u16(result_address);
OtherGamesRow row = make_row(game, home, away, result, match);
if (out.scheduled_day_mode) {
row.kind = OtherGamesRowKind::scheduled_competition;
row.played = false;
row.home_goals = row.away_goals = 0;
row.scheduled_source_day = uint32_t(memory.u16(::bmh::layout::CalendarState_FormatError_RuntimeField3)) +
uint32_t(int32_t(int16_t(result)));
} else if (out.knockout) {
uint16_t second = 0xcccc;
const bool second_present = second_results != 0;
if (second_results != 0) {
const uint32_t second_address = second_results + uint32_t(result_slot * 2);
if (!memory.has(second_address + 1)) invalid("truncated Source second-leg result list");
second = memory.u16(second_address);
}
add_second_leg_and_winner(row, second, second_present, second_leg, flags);
}
attach_source_values(game, row);
out.rows.push_back(std::move(row));
}
if (!out.knockout && team_count > 2) out.group_tables.push_back(cup_group_table(memory, address));
return out;
}
} // namespace bmh
+121
View File
@@ -0,0 +1,121 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <cstdint>
#include <array>
#include <string>
#include <vector>
#include "formats/textd.hpp"
#include "game/state.hpp"
#include "game/table.hpp"
namespace bmh {
enum class OtherGamesRowKind : uint8_t { match, scheduled_competition };
// Source local20==0 (`compact`) draws the complete round in dense six-pixel rows;
// local20==1 (`detail`) draws a 16-participant window in the taller 16-pixel layout.
enum class OtherGamesDisplayMode : uint8_t { compact, detail };
struct OtherGamesClubMetadata {
bool has_squad_values = false;
std::array<int, 5> averages{};
// -1 for squad-backed clubs, otherwise the raw ForeignClubStrength byte for foreign-club rendering.
int foreign_strength = -1;
};
// One Source row in the ordinary CupGroupOverviewEffects desk view. Names and text are kept in
// Original encoding so the presentation layer can pass them through the existing FNT3 path.
struct OtherGamesRow {
OtherGamesRowKind kind = OtherGamesRowKind::match;
int home_team = -1;
int away_team = -1;
std::string home_name;
std::string away_name;
uint16_t source_result = 0xcccc; // primary +0x0c result, always retained by Source
uint16_t source_second_leg = 0xcccc; // reversed +0x10 result, shown only in Source's local4c case
bool second_leg_array_present = false;
bool second_leg_visible = false;
bool played = false;
int home_goals = 0;
int away_goals = 0;
int second_leg_home_goals = 0;
int second_leg_away_goals = 0;
// CupTie result encoding: 0 home, 1 away, 2 tied; -1 when primary is 0xcccc.
int source_winner = -1;
// Competition id 12 stores signed day offsets, not scorewords.
uint32_t scheduled_source_day = 0;
// Void6 metadata is kept per side; foreign-club labels are formatted by the UI with the
// Original EXE strings, while these values remain source-faithful raw data.
OtherGamesClubMetadata home_metadata;
OtherGamesClubMetadata away_metadata;
// The zero-based match in the descriptor's current round. This is presentation metadata,
// not a writable result-array index supplied by the UI.
int source_match = -1;
};
struct OtherGamesSelector {
int slot = -1;
int competition = -1;
std::string title;
bool active = false;
};
struct OtherGamesLinkedPage {
int ordinal = -1;
int entry_index = -1;
int competition = -1;
int group_index = 0;
int group_count = 0;
};
struct OtherGamesProjection {
int competition = -1;
int descriptor_competition = -1;
int linked_page = 0;
int entry_index = -1;
uint32_t entry_address = 0;
uint8_t flags = 0;
bool knockout = false;
bool two_legs = false;
int current_round = 0;
int round = 0;
int rounds = 0;
int group_index = 0;
int group_count = 0;
std::string title;
std::string round_heading;
std::vector<OtherGamesSelector> selectors;
// InDescriptorTable's flattened linked-stage/group selector. The ordinal is the value retained by
// Source CareerSession_FormatError_RuntimeField8 and consumed by FindCup on the next draw.
std::vector<OtherGamesLinkedPage> linked_pages;
// Source's toggle gate uses participants in the displayed round (>16), before rows are
// paired into matches. Detail mode shows a 16-participant window; compact mode shows all.
int source_participant_count = 0;
int participant_offset = 0;
bool display_mode_toggle_available = false;
OtherGamesDisplayMode display_mode = OtherGamesDisplayMode::detail;
bool round_arrows_visible = false;
bool fixtures_available = true;
bool unfinished_predecessor = false;
bool scheduled_day_mode = false;
std::vector<LeagueTable> group_tables;
std::vector<OtherGamesRow> rows;
};
// Const projection of the ordinary menu-5 call to CupGroupOverviewEffects. This API intentionally models
// only the visible values: Original entry separately updates serialized CareerSession_FormatError_RuntimeField3/selector-12 state,
// while complete/compact and page navigation persist the active manager's CareerSession_DispatchOtherGames_RuntimeField byte. It is
// therefore not evidence that the entire Original menu interaction is Native-neutral.
// `linked_page` follows the descriptor's Source +0x17 parallel-group link, then +0x16 next-stage
// link. `round == -1` selects CupRound's live round; otherwise it is range-checked.
// `participant_offset` is Source's low-seven-bit display cursor (multiples of 16). The
// displayed-round group row list remains complete; the mode/offset applies to knockout rows.
OtherGamesProjection other_games_from_game(const GameState& game, const TextDb& texts,
int competition = 0, int linked_page = 0,
int round = -1,
OtherGamesDisplayMode display_mode = OtherGamesDisplayMode::detail,
int participant_offset = 0,
bool source_new_selection = true);
} // namespace bmh
+117
View File
@@ -0,0 +1,117 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <functional>
#include <string>
#include "game/club_player_detail.hpp"
#include "game/transfer_allocator.hpp"
#include "game/weekly.hpp"
namespace bmh {
// Explicit manual DispatchClubPlayerPendingOffers answers; absence never means NEIN.
enum class PendingOfferAnswer { yes, no, unsupported };
enum class PendingOfferQuestionKind { salary_demand, severance };
struct PendingOfferQuestion {
PendingOfferQuestionKind kind = PendingOfferQuestionKind::salary_demand;
int manager = -1;
int raw_offer_slot = -1;
int offered_player = -1;
int clicked_player = -1; // original identity, never remapped to offered_player
int clicked_source_slot = -1; // fixed throughout this DispatchClubPlayerPendingOffers invocation
std::string current_clicked_name; // PlayerName reads this fixed slot at each question
uint32_t amount = 0;
uint16_t source_flags = 1; // PresentManagerDialog: salary1, severance0x305
std::string original_message; // Original-encoded text, not UTF-8
};
enum class PendingOfferTransferChoiceKind { bid, decline, unsupported };
struct PendingOfferTransferChoice {
PendingOfferTransferChoiceKind kind = PendingOfferTransferChoiceKind::unsupported;
int raw_bid_slot = -1;
};
struct PendingOfferNotice {
int manager = -1;
int raw_offer_slot = -1;
uint32_t text_address = 0;
std::string original_message;
};
// PendingOfferAnswer reads the unsaved EXE byte MatchEventsDisabled. The caller must copy its observed
// value into this per-dispatch context; neither an absent save byte nor a
// default value is evidence that the allocator is enabled.
using PendingOfferAllocatorGate = TransferAllocatorContext;
struct PendingOfferHooks {
std::function<PendingOfferAnswer(const GameState&, const PendingOfferQuestion&)> answer;
std::function<PendingOfferTransferChoice(const GameState&, const TransferOfferListView&)> select_transfer;
// Read-only owned notices/ACKs; installing it changes neither bytes nor RNG.
std::function<void(const GameState&, const PendingOfferNotice&)> notice;
PendingOfferAllocatorGate human_buyer_allocator_gate = PendingOfferAllocatorGate::unsupported;
// PresentLoanReturn is a full-screen diagnostic, distinct from SystemIdentity notices.
// Returning acknowledges it; throwing leaves App retryable.
std::function<void(const GameState&, uint16_t)> program_error;
};
struct PendingOfferResult {
bool completed = false;
int processed = 0;
int salary_accepted = 0;
int transferred = 0;
int buyer_funds_refused = 0;
int buyer_allocator_blocked = 0;
int buyer_no_room = 0;
bool forced_acceptance = false; // sticky local18 from DispatchClubPlayerPendingOffers
};
// AdvanceTurn's post-desk caller has transient state which is not saved in FBM. The
// App must own and explicitly identify the supported interactive mode; the
// default/unsupported value never means that missing transient bytes were zero.
enum class PendingOfferDeskRuntimeMode { unsupported, normal_interactive };
struct PendingOfferDeskRequest {
PendingOfferDeskRuntimeMode runtime_mode = PendingOfferDeskRuntimeMode::unsupported;
int manager_count = -1; // caller's validated desk-loop count
int manager_position = -1; // current position in the saved NextDeskManager permutation
};
// ClubPlayerDetailFromGame's ordinary pending action -> DispatchClubPlayerPendingOffers, not the legacy answer_offers.
// Resolve the clicked slot/board once; execute every active-owner raw offer0..3.
// Intended for a staged GameState + both RNGs owned by the caller: an unsupported
// hook/path reports failure and may follow earlier batch effects, so discard the
// staged state/RNGs on report.unsupported. A distinct human buyer is supported only
// for ordinary sales and an explicitly supplied unsaved PendingOfferAnswer gate. Funds refusal,
// a gate-suppressed allocator and a full buyer squad are expected Source partial
// outcomes; their counters distinguish them from an actual transfer. Loans and
// unported error30/31/32 boundaries remain unsupported. No legacy weekly caller changes.
PendingOfferResult process_player_card_pending_offers(GameState&, const ClubPlayerDetailSelection&,
GameRandom&, WatcomRandom&, const PendingOfferHooks&, MinuteReport&);
// AdvanceTurn post-desk adapter. It validates native manager
// count/order/cursor, restores ActiveManager from NextDeskManager, anchors the DispatchClubPlayerPendingOffers batch at
// the first raw owned offer whose player exists in an ordinary owned squad slot,
// and preserves offers for other managers. Missing offered players require the
// explicit PresentLoanReturn presenter, then scanning continues in raw order. A genuine
// national takeover uses its current national squad for owner0 and the retained
// raw club record for an ordered owner1..3; the active manager list stays reduced.
// DispatchClubPlayerPendingOffers keeps the first resolved anchor board for all salary questions.
// Verified old-club offers missing from the national squad retain M121's quiet
// cleanup improvement. A present national player follows Source's actual salary
// and transfer path, including its national-board quirk. On the last desk
// only, it performs Source's global four-entry pool/offer cleanup and sets DeskPosition
// to the completed manager count before the caller starts simulation. As with the
// manual batch API, callers must stage GameState and both RNGs and discard on
// unsupported; no weekly or replay wrapper behavior changes.
PendingOfferResult process_natural_pending_offers_after_desk(GameState&,
const PendingOfferDeskRequest&, GameRandom&, WatcomRandom&,
const PendingOfferHooks&, MinuteReport&);
// AdvanceTurn's reduced-count national nomination desk has a distinct post-desk
// owner rule: it restores NextDeskManager[0] even though the active national runtime has
// one manager. Validate the precise 4006 calendar/competition identity, then
// reuse the post-desk AdvanceTurn/DispatchClubPlayerPendingOffers sequence above, including owned offers.
// The saved order prefix is preserved and bounded by the saved original count,
// rather than interpreted as a count-one permutation. Call on staged state and
// both RNGs; unavailable/declined presenters require complete caller rollback.
PendingOfferResult process_national_nomination_pending_after_desk(GameState&,
const PendingOfferDeskRequest&, GameRandom&, WatcomRandom&,
const PendingOfferHooks&, MinuteReport&);
} // namespace bmh
+177
View File
@@ -0,0 +1,177 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/poach.hpp"
#include <algorithm>
#include "game/messages.hpp"
#include "game/month.hpp"
#include "game/weekly.hpp"
namespace bmh {
namespace {
constexpr size_t kRecordSize = 0xb0c;
constexpr size_t kAttempts = 0x8b6; // five player ids, 0xffff free
constexpr uint32_t kTransferList = ::bmh::layout::EditorList; // 44 rows of 0x58 bytes
constexpr uint32_t kListRow = 0x58;
constexpr size_t kPoolFirst = 0xb70; // CareerRuntimeField: squad slot of list row 0
constexpr uint32_t kOfferSlots = ::bmh::layout::OfferSlots; // OfferSlots: 4 words, -1 free
constexpr int kBigSquadClubs = 90; // TeamsWithSquads
// Attempt: how many players of each position a club wants (MonthRuntimeField4 / MonthRuntimeField5)
constexpr int8_t kWantedBig[4] = {2, 6, 7, 5}, kWantedSmall[4] = {2, 4, 5, 4};
uint16_t attempt(const GameState& g, int m, int i) {
const size_t at = size_t(m) * kRecordSize + kAttempts + size_t(i) * 2;
return uint16_t(g.manager_records.at(at) | g.manager_records.at(at + 1) << 8);
}
// PoachAttemptsLeft(player, club): the asking percentage of the club for the player, or -1 with
// the reason in `messages`. A club of a human manager asks 100 %.
int club_asking_percent(const GameState& g, int player, int club, std::vector<std::string>& messages, WatcomRandom& rand) {
if (g.manager_of(club) >= 0) return 100;
const Player& p = g.players.at(size_t(player));
const int position = int(p.w364 & 3);
const int strength = p.strength(true); // Strength(w35c, 1)
const int8_t* wanted = club < kBigSquadClubs ? kWantedBig : kWantedSmall;
// SquadCount(club, 0): the fit players
if (squad_count(g, club, 0) < (club < kBigSquadClubs ? 3 : 0) + 0xe) {
messages.push_back(message_text(g, ::bmh::layout::Poach_ClubAskingPercent_TextPointer) + g.club_name(club) + message_text(g, ::bmh::layout::Poach_ClubAskingPercent_TextPointer2));
return -1;
}
int sum[4], count[4];
for (int k = 0; k < 4; k++) {
// QuoteNationalFriendlyMatch with 0x607 + the position bit: sum of the fit players and their number
const TeamAverage a = team_average(g, club, uint16_t((1 << (k + 4)) + 0x607));
sum[k] = int16_t(a.value);
count[k] = int8_t(a.players);
}
const int short_of = int16_t(wanted[position] - count[position]); // local_24
if (short_of >= 3 || (short_of == 0 && position == 0)) {
// the club needs him (a club always keeps its second goalkeeper)
messages.push_back(g.club_name(club) + message_text(g, ::bmh::layout::Poach_ClubAskingPercent_TextPointer3));
return -1;
}
int percent = short_of < 0 ? short_of * 0x18 + 0x8c : short_of * 16 + 0x82; // local_34
if (percent < 0x5a) percent = 0x5a;
int averages = 0;
for (int k = 0; k < 4; k++) averages = int16_t(averages + sum[k] / count[k]);
const int team = averages / 4;
int relative = team != 0 ? int16_t(strength * 100 / team) : 100; // local_30
if (relative < 0x65) {
percent -= std::clamp(100 - relative, 0, 0x14); // ClampInteger
} else {
const int over = int16_t(relative - 100) >> 1;
percent = int16_t(percent + int16_t(over * over));
}
if (short_of != 0 && percent >= 0x100) {
messages.push_back(message_text(g, ::bmh::layout::Poach_ClubAskingPercent_TextPointer4)); // FINANCIAL FAIRPLAY
return -1;
}
if (percent > 0xbe) percent = 0xbe;
return uint8_t(rand.range(0xc, 0x14) + percent);
}
} // namespace
int poach_attempts_left(const GameState& g, int manager) {
int left = 0;
for (int i = 0; i < 5; i++)
if (attempt(g, manager, i) == 0xffff) left++;
return left;
}
PoachStart start_poach(GameState& g, int manager, int squad_slot, WatcomRandom& rand) {
PoachStart out;
out.manager = manager;
out.squad_slot = squad_slot;
const size_t rec = size_t(manager) * kRecordSize;
if (attempt(g, manager, 4) != 0xffff) {
out.status = PoachStatus::attempts_used;
out.messages.push_back(message_text(g, ::bmh::layout::CareerSession_DispatchPoachUi_TextPointer2));
return out;
}
if (g.manager_records.at(rec + 0x220) >> 5 == 1) { // PushBack
out.status = PoachStatus::transfer_ban;
out.messages.push_back(message_text(g, ::bmh::layout::CareerSession_DispatchPoachUi_TextPointer));
return out;
}
if (squad_slot < 0 || size_t(squad_slot) >= kPoolFirst || g.squad_slots.at(size_t(squad_slot)) == 0xfff) return out;
out.player = g.squad_slots.at(size_t(squad_slot)) & 0xfff;
out.club = slot_team(squad_slot); // SlotTeam
if (out.club < 0 || out.club == g.manager_teams.at(size_t(manager))) return out;
// BoughtEntry: a player on loan (table Career_RemoveJoinLoans_RuntimeField)
for (int k = 0; k < 200; k++) {
const uint32_t e = g.memory.u32(::bmh::layout::Career_RemoveJoinLoans_RuntimeField + uint32_t(k) * 4);
if (e != 0 && int(e & 0xfff) == out.player) {
out.status = PoachStatus::on_loan;
out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer));
return out;
}
}
for (int i = 0; i < 5; i++)
if (attempt(g, manager, i) == out.player) {
out.status = PoachStatus::tried_before;
out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer2));
return out;
}
// PlayerOnTransferListFirstPoolSlots: the player is on the transfer list (first 44 pool slots)
for (size_t s = kPoolFirst; s < kPoolFirst + 0x2c; s++)
if ((g.squad_slots.at(s) & 0xfff) == out.player) {
out.status = PoachStatus::on_transfer_list;
out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer3));
return out;
}
const int percent = club_asking_percent(g, out.player, out.club, out.messages, rand);
if (percent < 0) {
out.status = PoachStatus::club_refuses;
out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer5));
return out;
}
out.asking_percent = percent;
// RowWhose: a special row whose OfferSlots word is free
int k = 0;
while (k < 4 && g.memory.u32(kOfferSlots + uint32_t(k) * 4) != 0xffffffffu) k++;
if (k == 4) {
out.status = PoachStatus::market_busy;
out.messages.push_back(message_text(g, ::bmh::layout::Poach_StartPoach_TextPointer4));
finish_poach(g, out);
return out;
}
out.offer_row = k;
const int demand = rand.range(0x50, 100);
// Range2(slot, 0, percent, demand, 0, k): the row like a market row of the club.
// (Its salary floor for a club of a human manager searches the buyer's own squad for
// the player and so never applies; the 0x8000 flag of the club word is kept.)
const uint32_t row = kTransferList + uint32_t(0x28 + k) * kListRow;
uint16_t club_word = uint16_t(out.club);
if (g.manager_of(out.club) >= 0) club_word |= 0x8000;
g.memory.set16(row + 8, club_word);
for (int b = 0; b < 4; b++) g.memory.set16(row + uint32_t(b) * 2, 0xffff);
g.memory.set8(row + 0x54, uint8_t(percent));
g.memory.set8(row + 0x55, uint8_t(demand));
uint32_t fee = 0, salary = 0;
market_value(g, squad_slot, 0, uint8_t(percent), fee, salary, 1, 0, rand);
g.memory.set32(row + 0x2c, fee);
g.memory.set32(row + 0x30, salary);
g.squad_slots.at(kPoolFirst + 0x28 + size_t(k)) = uint16_t(out.player);
out.status = PoachStatus::ready;
return out;
}
void finish_poach(GameState& g, const PoachStart& poach) {
if (poach.offer_row >= 0) {
g.squad_slots.at(kPoolFirst + 0x28 + size_t(poach.offer_row)) = 0xfff;
g.memory.set32(kOfferSlots + uint32_t(poach.offer_row) * 4, 0xffffffffu);
}
for (int i = 0; i < 5; i++)
if (attempt(g, poach.manager, i) == 0xffff) {
const size_t at = size_t(poach.manager) * kRecordSize + kAttempts + size_t(i) * 2;
g.manager_records.at(at) = uint8_t(poach.player);
g.manager_records.at(at + 1) = uint8_t(poach.player >> 8);
break;
}
}
} // namespace bmh
+66
View File
@@ -0,0 +1,66 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// Poaching ("Abwerben", transfer screen menu 17, H2 p. 70; BMH.exe V2.24 + supported rule profile patch):
// the manager picks a player of another club in the league tables and makes him an offer
// that is decided at once. Button 4 of the transfer screen Reset:
//
// - at most five attempts per season: the players tried are kept in manager record
// +0x8b6 (5 words, 0xffff free; cleared at the season start, season.cpp) - CareerSession_DispatchPoachUi_TextPointer2
// - not with a transfer ban (record +0x220 >> 5 == 1, PushBack, CareerSession_DispatchPoachUi_TextPointer)
// - not for a player on loan (BoughtEntry, Poach_StartPoach_TextPointer), not twice for the same player
// (Poach_StartPoach_TextPointer2), not for a player on the transfer list (PlayerOnTransferListFirstPoolSlots, Poach_StartPoach_TextPointer3)
// - the club must let him go (PoachAttemptsLeft): its squad must be big enough, the position
// must not be short (and a club keeps its second goalkeeper); the asking percentage
// follows how much the club needs him and how good he is compared with the team
// - the offer uses one of the special list rows 40..43 (RowWhose: a row whose
// OfferSlots word is free, else "Transfermarkt überlastet"), prepared like a market
// row by Range2: asking percentage, demand W(80, 100), market value and salary.
//
// The offer itself is the ordinary offer editor (desk_actions.hpp, OpenTransferEditor) on that
// row with `poach` set; its submit (SubmitTransferBidSourceHumanBuyer) decides at once. finish_poach frees the
// row again and counts the attempt, as the original does when the editor returns.
#include <string>
#include <vector>
#include "game/random.hpp"
#include "game/state.hpp"
namespace bmh {
enum class PoachStatus : uint8_t {
ready, // the offer row is prepared: open the offer editor on it
attempts_used, // five attempts this season (CareerSession_DispatchPoachUi_TextPointer2)
transfer_ban, // the DFB has banned all transfers (CareerSession_DispatchPoachUi_TextPointer)
invalid, // no player, or a player of the own club
on_loan, // "Dieser Spieler ist nur ausgeliehen!" (Poach_StartPoach_TextPointer)
tried_before, // "Nur 1 Abwerbeversuch pro Spieler pro Saison!" (Poach_StartPoach_TextPointer2)
on_transfer_list, // Poach_StartPoach_TextPointer3
club_refuses, // PoachAttemptsLeft refused (its reason, then Poach_StartPoach_TextPointer5)
market_busy, // no free special row (Poach_StartPoach_TextPointer4); the attempt counts
};
struct PoachStart {
PoachStatus status = PoachStatus::invalid;
std::vector<std::string> messages; // the original's message boxes, in order
int manager = -1;
int squad_slot = -1; // absolute SquadSlots slot of the player at his club
int player = -1;
int club = -1;
int offer_row = -1; // k (0..3); the list row is 40 + k, its pool slot 0xb70 + 40 + k
int asking_percent = 0;
};
// Attempts left this season (record +0x8b6).
int poach_attempts_left(const GameState& g, int manager);
// Button 4 after the player was picked (FriendlyMatchScreen returned `squad_slot`): the checks,
// PoachAttemptsLeft, RowWhose and Range2. Draws W(12, 20) (asking percentage), W(80,
// 100) (demand) and what the market value draws. `market_busy` counts the attempt itself.
PoachStart start_poach(GameState& g, int manager, int squad_slot, WatcomRandom& rand);
// When the offer editor has returned: the pool slot of the row is emptied, its OfferSlots
// word freed and the attempt recorded in +0x8b6.
void finish_poach(GameState& g, const PoachStart& poach);
} // namespace bmh
+205
View File
@@ -0,0 +1,205 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/prediction.hpp"
#include <string>
#include <stdexcept>
#include "game/matchday.hpp"
#include "game/messages.hpp"
#include "game/schedule.hpp"
#include "game/table.hpp"
namespace bmh {
namespace {
constexpr size_t kRecord = 0xB0C; // manager record
constexpr size_t kBoard = 0x840; // tactics board of a manager
constexpr size_t kBoardSlot = 0x58; // one slot of the board
// Static league tables of V2.24 (not part of the savegame):
// (European places per league, CareerSession_InstallLeagueSizes_RuntimeField, are kLeagueEurope of the loaded game; league 0 uses 4)
// (the relegation places per league, CareerSession_InstallLeagueSizes_RuntimeField2, are kLeagueRelegation of the loaded game)
constexpr int kLeagueTeams = 138; // CareerSession_DispatchLineup_RuntimeField: clubs in the league system
// Text of a pointer variable of the text table TextPointerTable.
} // namespace
int table_prediction(GameState& g, int team, int mode, std::array<uint8_t, 24>& buf, int* size_word) {
buf.fill(1);
int league = team_league(team); // local_30
if (league >= kLeagueCount) return 0; // reads CareerRuntimeField6[0] = 0 as the round count
const int rounds = int8_t(g.league_rounds.at(size_t(league))); // local_1c
const int matchdays = league_matchdays(league); // LeagueMatchdayCounts
if (rounds < 2 || matchdays <= rounds) return 0;
const int manager = g.manager_of(team); // local_18, 0xFF = none
// (Fill would refresh the desk warning flags PredictionRuntimeField.. here; they are
// run-time only and not needed by the game logic.)
const size_t rec = size_t(manager) * kRecord;
const int size = kLeagueSizes[league]; // local_2c
if (size_word) *size_word = size; // (stored as a word, see the header)
if (team >= kLeagueTeams) return 9;
const int pos = team - league_first_team(league); // local_24
const int target[3] = {0, league == 0 ? 4 : kLeagueEurope[league], size - kLeagueRelegation[league]};
int from = 0; // local_10
if (mode > 3) {
from = rounds - 5 * (mode >> 2);
if (from < 0) from = 0;
}
auto per_game = [&](const LeagueTable& t, int club) {
const int games = t.games(club);
return games ? t.points[club] * 500 / games : 0; // the original divides by zero here
};
int own_rate = 1500; // local_34: three points per remaining game
if (mode != 1) own_rate = per_game(compute_league_table(g, league, from, rounds, 3, 0), pos);
const LeagueTable full = compute_league_table(g, league, 0, rounds, 7, 0);
int points[20] = {}, remaining[20] = {}; // acStack_60, acStack_4c
for (int c = 0; c < size; c++) {
points[c] = full.points[c];
remaining[c] = int8_t(matchdays - full.games(c));
}
// The scratch table the rates of the other clubs are read from: the recent form table
// for mode >= 4, otherwise still the full table.
const LeagueTable rates = mode > 3 ? compute_league_table(g, league, from, rounds, 3, 0) : full;
uint16_t own = uint16_t(points[pos] * 500 + remaining[pos] * own_rate); // local_28 (low word)
int ahead = size; // local_20: ranks that are out of reach
if (mode == 1) {
ahead = 0;
for (int c = 0; c < size; c++) ahead += int(own) < points[c] * 500;
}
for (int r = 0; r < ahead; r++) buf.at(size_t(r)) = 0;
int league_index = league; // local_30 is changed by the league name of message 1
if (mode == 1) {
for (int k = 0; k < 3; k++) {
if (buf.at(size_t(target[k])) != 0) continue;
if (manager >= 0 && (g.manager_records.at(rec + 0x28b) >> k & 1)) continue;
// the goal can no longer be reached
if (manager >= 0) g.manager_records.at(rec + 0x28b) |= uint8_t(1 << k);
std::string msg = g.club_name(team) + message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer2);
if (k == 0) msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer3);
if (k == 1) {
std::string tail;
if (league_index == 0) {
tail = message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer4);
} else if (league_index == 2 || league_index == 3) {
tail = message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer5);
} else {
msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer6);
if (league_index > 2) league_index--;
msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer + uint32_t(league_index) * 4); // league name
tail = message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer7);
}
msg += tail;
}
if (k == 2) msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer8);
if (manager >= 0) post_composed(g, manager, msg);
}
own = uint16_t(points[pos] * 500);
}
int behind = 0; // local_14: clubs that can no longer catch up
for (int c = 0; c < size; c++) {
if (c == pos) continue;
int rate;
if (mode == 1) rate = 1500;
else if (mode == 2) rate = 0;
else rate = int16_t(per_game(rates, c));
if (uint16_t(points[c] * 500 + remaining[c] * rate) < own) behind++;
}
int r = 0;
for (; r < behind; r++) buf.at(size_t(size - r - 1)) = 0xFF;
if (mode != 1) {
if (r == size) r++; // cannot happen: the club itself is never counted
buf.at(size_t(size - r - 1)) = 1;
}
if (mode == 1) {
for (int k = 0; k < 3; k++) {
if (buf.at(size_t(target[k])) != 0xFF) continue;
if (manager >= 0 && (g.manager_records.at(rec + 0x28b) >> (k + 3) & 1)) continue;
// the goal is secured (or relegation avoided / certain)
if (manager >= 0) g.manager_records.at(rec + 0x28b) |= uint8_t(1 << (k + 3));
std::string msg = g.club_name(team) + message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer9);
if (k == 0) msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer10);
else if (k == 1)
msg += message_text(g, league_index == 0 ? ::bmh::layout::Prediction_TablePrediction_TextPointer11 : (league_index == 2 || league_index == 3) ? ::bmh::layout::Prediction_TablePrediction_TextPointer12 : ::bmh::layout::Prediction_TablePrediction_TextPointer13);
else msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer14);
msg += message_text(g, ::bmh::layout::Prediction_TablePrediction_TextPointer15);
// without a manager the original posts to "manager" 0xFE; not needed here
if (manager >= 0) post_composed(g, manager, msg);
}
}
int first = 0;
while (first < 24 && buf[size_t(first)] == 0) first++;
return (first + 1) & 0xFF;
}
static uint32_t season_bonus_impl(GameState& g, int manager, int team, int board_slot, int rank, bool pay) {
const int league = team_league(team);
uint32_t amount = 0;
if (league == 0 && rank == 0) amount = pay_bonus(g, manager, board_slot, 3, pay);
if (amount == 0 && rank < 5) amount = pay_bonus(g, manager, board_slot, 4, pay);
if (amount == 0 && rank < 10) amount = pay_bonus(g, manager, board_slot, 5, pay);
if (amount == 0 && league < kLeagueCount && rank < kLeagueSizes[league] - kLeagueRelegation[league])
amount = pay_bonus(g, manager, board_slot, 6, pay);
return amount;
}
uint32_t season_bonus(GameState& g, int manager, int board_slot, int rank, bool pay) {
return season_bonus_impl(g,manager,g.manager_teams.at(size_t(manager)),board_slot,rank,pay);
}
static uint32_t expected_bonus_impl(GameState& g, int manager, int team, int rank, int board_slot, int player, bool fitness) {
static const uint8_t kPerSeason[3] = {0, 34, 25}; // PredictionRuntimeField2: -, points, appearances
static const uint8_t kGoals[4] = {0, 2, 4, 8}; // PredictionRuntimeField3: goals by position
const int position = int(g.players.at(size_t(player)).w364 & 3);
if (rank == 0xFF) {
std::array<uint8_t, 24> buf;
const int r = table_prediction(g, team, 4, buf);
rank = r == 0 ? 0xB : r + 1;
}
const size_t slot = size_t(manager) * kBoard + size_t(board_slot) * kBoardSlot;
const uint32_t base = uint32_t(g.tactics.at(slot + 0x50) | g.tactics.at(slot + 0x51) << 8 |
g.tactics.at(slot + 0x52) << 16) | uint32_t(g.tactics.at(slot + 0x53)) << 24;
uint32_t sum = 0;
for (int k = 0; k < 3; k++) {
uint32_t times = k == 0 ? kGoals[position] : kPerSeason[k];
if (fitness && k != 1) {
// the fitness correction: a player weaker than the team average (QuoteNationalFriendlyMatch
// flags 499) earns goal and appearance bonuses less often - PredictionRuntimeField4 per gap
static const uint8_t kPerGap[3] = {1, 0, 5}; // PredictionRuntimeField4
const uint32_t w = g.players.at(size_t(player)).w35c;
int gap = int16_t(team_average(g, team, 499).value -
int((((w >> 14) & 0x7F) + ((w >> 7) & 0x7F)) >> 1));
if (gap < -1) gap = -1;
const int t = int(times) - kPerGap[k] * gap;
times = t < 0 ? 0 : uint32_t(t);
}
sum += g.tactics.at(slot + 0x12 + size_t(k)) * base / 100 * times / 12;
}
return season_bonus_impl(g, manager, team, board_slot, rank & 0xFF, false) / 12 + sum;
}
uint32_t expected_bonus(GameState& g, int manager, int rank, int board_slot, int player, bool fitness) {
return expected_bonus_impl(g,manager,g.manager_teams.at(size_t(manager)),rank,board_slot,player,fitness);
}
uint32_t expected_bonus_parked_club_source(GameState& g, int rank, int board_slot, int player, bool fitness) {
constexpr size_t team_at=4*kRecord+0x290;
if(g.manager_teams!=std::vector<int>{kNoTeam} || !g.memory.has(::bmh::layout::CoachActive) ||
g.memory.u8(::bmh::layout::CoachActive)==0 || !g.memory.has(::bmh::layout::ManagerCount) || g.memory.u8(::bmh::layout::ManagerCount)!=1 ||
!g.memory.has(::bmh::layout::OriginalManagerCount) || g.memory.u8(::bmh::layout::OriginalManagerCount)<1 || g.memory.u8(::bmh::layout::OriginalManagerCount)>4 ||
g.manager_records.size()<5*kRecord ||
(int(g.manager_records[0x290]) | int(g.manager_records[0x291])<<8)!=kNoTeam ||
board_slot<0 || board_slot>=24 || g.tactics.size()<5*kBoard)
throw std::invalid_argument("expected_bonus: invalid FindManagerForClub parked club context");
const int team=int(g.manager_records[team_at]) | int(g.manager_records[team_at+1])<<8;
if(team<0 || team>=kLeagueTeams)
throw std::invalid_argument("expected_bonus: parked record4 has no ordinary club");
return expected_bonus_impl(g,4,team,rank,board_slot,player,fitness);
}
} // namespace bmh
+54
View File
@@ -0,0 +1,54 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// Table prediction and bonus expectations of human managers (BMH.exe V2.24).
//
// table_prediction Void5 which final ranks a club can still reach / has secured
// expected_bonus ContractOffer bonus a player on the tactics board can expect
// season_bonus SeasonBonus the board's season bonus (title, Europe, staying up)
//
// team_rating (rating.cpp) uses them for the players of human managers: a player who can
// expect a large bonus relative to his base pay tries harder (+5 with some probability).
// As a side effect the prediction posts the "still possible" / "no longer possible"
// messages about the season goals (champion, Europe, relegation) to the manager, once per
// goal and season (bits 0-5 of manager record +0x28b).
#include <array>
#include <cstdint>
#include "game/state.hpp"
namespace bmh {
// Void5(team, mode, buf). Fills buf[0..23], one entry per final rank:
// 0 the rank can no longer be reached (at least that many clubs stay ahead)
// 1 the predicted rank (modes other than 1)
// 0xFF a rank the club cannot fall to any more
// and returns the first rank (1-based) that is not 0, i.e. the best reachable rank.
// mode 1: maximum points = points + 3 per remaining game for every club (and messages);
// mode 2: the club's own points per game projected, the others stay where they are;
// mode 3: every club projected with its own points per game;
// mode >= 4: as 3, but the points per game over the last 5 * (mode / 4) matchdays.
// `size_word` receives the league size, which the original stores as a word in its frame
// (local_2c) unless it returns early (before the second matchday etc.; then it stays
// untouched). The side ratings read that stack word as a stale value, see team_rating.
// Returns 0 before the second matchday and after the last one (and for leagues >= 9),
// 9 for clubs outside the league system (ids from 138 on).
int table_prediction(GameState& g, int team, int mode, std::array<uint8_t, 24>& buf, int* size_word = nullptr);
// ContractOffer(manager, predicted rank, board slot, player, 0): goal, point and appearance
// bonus of the board slot, each weighted by how often it is earned (goals by position:
// PredictionRuntimeField3, points 34, appearances 25 per season), plus the season bonus for the
// predicted rank, all divided by 12. `rank` 0xFF means: predict it (table_prediction mode 4).
// Only the variant without the fitness correction (last argument 0) is ported.
uint32_t expected_bonus(GameState& g, int manager, int rank, int board_slot, int player, bool fitness = false);
// Checked FindManagerForClub record4 variant for a club parked during national takeover.
// Read the actual club from record4 without adding it to the active manager list.
uint32_t expected_bonus_parked_club_source(GameState& g, int rank, int board_slot, int player, bool fitness = false);
// SeasonBonus(manager, board slot, rank, 0): season bonus of the slot for a final rank:
// title (league 0 only, rank 0), top 5, top 10, staying up (bonus indices 3-6 of the slot,
// the first one that is set and applies). Not paid.
uint32_t season_bonus(GameState& g, int manager, int board_slot, int rank, bool pay = false);
} // namespace bmh
+70
View File
@@ -0,0 +1,70 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// What the original shows during a matchday, as events for the UI (BMH.exe V2.24 + supported rule profile).
//
// The match engine reproduces the random numbers of the original's live desk, its message
// boxes and animations, but draws nothing. Where the original would show something it
// appends a ShowEvent (MatchEngine::show, when set) with the values the original computes
// for the picture - the UI renders from these and never draws random numbers itself, so
// rendering, hovering or replaying a frame cannot change the game.
//
// The event descriptions document the observed match activity; the
// screen coordinates are those of the 320x240 work screen PresentationRuntimeField unless noted.
//
// Booking EventImpl, layout field-layout field: the message box of a foul. Shown when
// MatchEngineRuntimeField12 is set and the offender's team (or, for flag 0x80, the
// opponent) is watched: team flag 0x80 (live desk; for a yellow card only
// without button MatchEngine_EventImpl_ExecutableField) or 0x40 (ticker; button MatchEngine_EventImpl_ExecutableField2 for a
// yellow, MatchEngine_EventImpl_ExecutableField3 otherwise switches it off). Text: LiveMatchday_FormatError_TextPointer2[kind]
// (0 yellow, 1 red, 2 injury, 3 second yellow) + the player's name, for a
// yellow card also his yellow cards of the season (Cstring); the side's
// colours (Button(side | 0x40)), the scoreboard of the match flashes
// (DcThat(6, group, match)), the text is drawn at (0x5f, 0x27)
// (DrawnFirstBy), a whistle (PauseMusic(0x11), not for injuries), a delay
// (AdvanceStep(3 + (kind != 0))) and the box waits for a click
// (PatternRect). `shown` tells whether the box appears; the event is
// appended for every foul so that a ticker can list it.
// Substitution Injure after a foul: `player` leaves, `other` comes on.
// Chance the live desk after a chance (layout field-layout field, EndPhase): kind 0 open
// play, 1 penalty / free kick, 2 follow-up, 3 corner; the shooter, the
// assistant, the distance shown (MatchEngineRuntimeField15, kind 1), the goal. The text
// is the shooter's name (+ LiveMatchday_FormatError_ExecutableField3), the distance (LiveMatchday_FormatError_TextPointer12 /
// LiveMatchday_FormatError_TextPointer13 "m"); halved indoors (MatchEngine_Minute_ExecutableField4).
// SetPiece LiveSetPieceFrames(kind, distance) with MatchEngineRuntimeField6 = `side` (1 = the picture
// is mirrored): the ball's spot (a, b = x, y in the scene's 1000-wide
// coordinates), the kicker's run-up timer (c) and, for kind 3, the flight
// time of the ball (d).
// ShotOnGoal SetPieceAnimation(miss, follow_up) + Range4: `side` (0 left / 1 right
// lane of MatchEngineRuntimeField4), a = height of the shot, b = lane (x), c = the ball's
// end height, d = the goalkeeper's first reaction frame and its delay
// (d >> 8); `flag` bit 0 = follow-up picture, bit 1 = mirrored.
// PenaltyKick PenaltyShootout live: "<n>. Elfmeter" (LiveMatchday_FormatError_TextPointer4 / LiveMatchday_FormatError_TextPointer5) + the
// taker's name at (0x49, 0x5f), the kick animated (SetPiece kind 2 and
// ShotOnGoal follow-up), then the score of the shoot-out (a : b);
// c = the round (1-5, then sudden death).
// ShootoutEnd PenaltyShootout live: the text LiveMatchday_FormatError_TextPointer6 at (0x49, 0x5f).
#include <cstdint>
#include <string>
namespace bmh {
enum class Show : uint8_t { Booking, Substitution, Chance, SetPiece, ShotOnGoal, PenaltyKick, ShootoutEnd };
struct ShowEvent {
Show what;
int16_t minute = 0; // PresentationRuntimeField2 (0x79 = 121 for the shoot-out)
uint8_t group = 0; // match group (descriptor index) and match within it
uint8_t match = 0;
uint8_t side = 0; // 0 home, 1 away (of the acting team; SetPiece: MatchEngineRuntimeField6)
uint8_t kind = 0; // Booking: 0 yellow, 1 red, 2 injury, 3 second yellow; Chance /
// SetPiece: the chance kind
uint8_t flag = 0; // Booking: shown in a box; Chance / PenaltyKick: goal; ShotOnGoal: see above
int16_t team = -1;
int16_t player = 0xFFF; // offender, shooter, taker, player leaving
int16_t other = 0xFFF; // assistant, player coming on
int32_t a = 0, b = 0, c = 0, d = 0; // per kind, see above
std::string text; // the composed text as the original builds it (ISO 646-DE)
};
} // namespace bmh
+63
View File
@@ -0,0 +1,63 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// Both random generators of the original (docs/RNG.md). Must stay bit-exact.
//
// Both classes count their draws; the match engine tests compare these counts with
// recordings of the original, minute by minute.
#include <cstdint>
namespace bmh {
// Debugging aid: called before every draw of a generator (0 the game generator, 1 Watcom).
inline void (*draw_hook)(int generator) = nullptr;
// Watcom C runtime rand()/srand(); random(lo, hi) = WatcomRandom.
// Seeded from the clock at program start, so its sequence is not reproducible from a
// savegame; recordings capture its state (RandomRuntimeField) directly.
class WatcomRandom {
public:
explicit WatcomRandom(uint32_t seed = 1) : seed_(seed) {}
void srand(uint32_t seed) { seed_ = seed; }
uint32_t seed() const { return seed_; }
uint64_t calls() const { return calls_; }
int rand() {
calls_++;
if (draw_hook) draw_hook(1);
seed_ = seed_ * 0x41C64E6Du + 0x3039u;
return int(seed_ >> 16 & 0x7FFF);
}
int range(int lo, int hi) {
int n = hi - lo + 1;
if (n < 1) return lo;
int32_t prod = int32_t(uint32_t(rand()) * uint32_t(n));
// arithmetic shift with rounding toward zero, as compiled by Watcom
return (prod < 0 ? -((-prod) >> 15) : prod >> 15) + lo;
}
private:
uint32_t seed_;
uint64_t calls_ = 0;
};
// Game's own deterministic generator, GameRandom; seed CareerSession_Save_RuntimeField lives in the savegame.
// All arithmetic is signed 32 bit with wrap-around (shl/imul/idiv in the original).
class GameRandom {
public:
explicit GameRandom(int32_t seed = 0) : seed_(seed) {}
int32_t seed() const { return seed_; }
void set_seed(int32_t seed) { seed_ = seed; }
uint64_t calls() const { return calls_; }
int32_t range(int32_t lo, int32_t hi) {
calls_++;
if (draw_hook) draw_hook(0);
seed_ = int32_t(uint32_t(seed_) * 16u + 0xA7u) % 4000000;
int32_t prod = int32_t(uint32_t(seed_) * uint32_t(hi - lo + 1));
return prod / 4000000 + lo;
}
private:
int32_t seed_;
uint64_t calls_ = 0;
};
} // namespace bmh
+240
View File
@@ -0,0 +1,240 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "game/rating.hpp"
#include <array>
#include <cstdlib>
#include <stdexcept>
#include "game/prediction.hpp"
namespace bmh {
int player_value(const GameState& g, int player, uint16_t attrs, int scale, int team, const RatingContext& ctx, int x, int y) {
if (player == 0xFFF) return 0;
const Player& p = g.players.at(player);
const uint32_t w1 = p.w35c, w3 = p.w364;
int sum = 0, weight = 0, form_term = 0;
// local_1c / local_20, only set when selected (see RatingContext::stale_condition)
int condition = ctx.stale_condition >= 0 ? ctx.stale_condition : 0;
int technique = ctx.stale_technique >= 0 ? ctx.stale_technique : 0;
int skill[7] = {-1, -1, -1, -1, -1, -1, -1}; // selected skills * 5 (local_38, local_2c, ...)
for (int bit = 0; bit < 16; bit++) {
if (!((int16_t(attrs) >> bit) & 1)) continue;
if (bit < 2) {
weight += 100;
int v = bit == 0 ? int(w1 >> 14 & 0x7F) : int(w1 >> 7 & 0x7F);
(bit == 0 ? condition : technique) = v;
sum += v;
} else if (bit == 2) {
form_term += int(w1 & 0x7F) / 8 - 6;
} else if (bit == 3 || bit == 4) {
int pos = int(w3 & 3);
sum += bit == 3 ? 9 - 3 * pos : 3 * pos;
weight += 9;
} else if (bit == 12) {
int v = int(w3 >> 2 & 0x3F) * 3;
sum += v > 20 ? 20 : v;
weight += 20;
}
if (bit > 4 && bit < 12) { // the seven skills, bit 5 = skill 0
int v = int(p.w368 >> (bit * 2 - 10) & 3) * 5;
skill[bit - 5] = v;
sum += v;
weight += 15;
}
}
int multiplier = 100;
if (attrs & 3) {
int bonus = g.player_bonus.at(player) & 0x7F;
if (bonus != 0) multiplier = (bonus > 50 ? 50 : bonus) / 2 + 100;
multiplier = multiplier + form_term - (6 - ((g.team_morale.at(team) & 0x3F) >> 2));
// Imbalance between condition and technique costs extra in certain match situations.
if (condition < technique && (ctx.chance_rain > 2 || int8_t(ctx.chance_temperature) < 0)) multiplier -= ctx.chance_rain * 3;
if (technique < condition && int8_t(ctx.chance_temperature) > 25) multiplier -= int8_t(ctx.chance_temperature) - 25;
}
// Human managers from game level 4 on: the place on the tactics board counts. Field
// players get skill bonuses for fitting places and lose for the distance between the
// place and their preferred depth/lane (w35c bits 21-22 and 24-25), and for age.
if (g.level > 3 && x != 0xFF && (w3 & 3) != 0 && g.manager_of(team) >= 0) {
static const int kDepthBias[4] = {0, 4, 10, 16}; // RatingRuntimeField
if (x < 31) {
// tackling near the own goal, teamplay + passing in midfield, speed on the wings
if (skill[4] != -1 && x != 0 && x < 4 && y > 2 && y < 6)
multiplier = (technique < condition ? multiplier - 5 : multiplier - 10) + skill[4];
if (skill[0] != -1 && skill[3] != -1 && x > 9 && x < 13 && y > 2 && y < 6)
multiplier = (condition < technique ? multiplier - 10 : multiplier - 20) + skill[0] + skill[3];
if (skill[1] != -1 && x > 11 && (y < 2 || y > 6)) multiplier = multiplier - 7 + skill[1];
} else {
x = ((x - 30) * 10) / 14; // between the grid lines
}
if (y > 30) {
y = 4 - ((12 - (y - 30)) * 10) / 25;
y = y < 0 ? 0 : y > 8 ? 8 : y;
}
int depth = std::abs(int(w1 >> 21 & 3) + kDepthBias[w3 & 3] - 3 - x);
int lane = std::abs(int((w1 >> 24 & 3) << 3) / 7 - y);
multiplier -= (depth >> 1) + (lane >> 1);
int age = int(w3 >> 21 & 0x1F); // age - 16
if (age > 14) multiplier -= age - 14;
if (age < 6) multiplier -= 6 - age;
}
if (w1 >> 27) weight += weight / 20; // players with bits 27-31 set count 5 % less
if (weight == 0) return 0;
return scale * (sum * multiplier / 100) / weight;
}
namespace {
// The corrections of TeamRating for a player of a human manager (layout field-layout field),
// applied to his player_value `v`:
// - from game level 5 on (not for the goalkeeper group): minus the distance between the
// slot's own place (bytes 0/1) and the place he is put on, times the group weight / 100,
// plus 3
// - +5 if G(20, 100) < expected bonus * 100 / base pay: a good bonus motivates
// - levels 8 and 9: minus level - 6
// - slot byte 0x0f above 70: minus (value - 50) / 4
// - with the live scene, half of slot byte 5 (10 = neutral): minus W(0, 10 - value)
// below 10, minus W(0, value) above 10
int human_correction(GameState& g, RatingContext& ctx, int manager, int rank, int board_slot, int player, int group,
int weight, int x, int y, int board_depth, int board_live, int v) {
const size_t board = size_t(manager) * 0x840 + size_t(board_slot) * 0x58;
if (group != 0 && g.level > 4) {
v = int16_t(v - std::abs(g.tactics.at(board) - x) * weight / 100);
v = v - std::abs(g.tactics.at(board + 1) - y) * weight / 100 + 3;
}
if (!ctx.game || !ctx.rand) throw std::invalid_argument("team_rating: a human team needs both generators");
const uint32_t base = uint32_t(g.tactics.at(board + 0x50) | g.tactics.at(board + 0x51) << 8 |
g.tactics.at(board + 0x52) << 16) | uint32_t(g.tactics.at(board + 0x53)) << 24;
if (base == 0) throw std::invalid_argument("team_rating: board slot without base pay (the original divides by zero)");
const uint32_t motivation = expected_bonus(g, manager, rank, board_slot, player) * 100u / base;
if (uint32_t(ctx.game->range(0x14, 100)) < motivation) v += 5;
if (g.level > 7) v -= g.level - 6;
if (board_depth > 0x46) v = int16_t(v) - (board_depth - 0x32) / 4;
if (board_live < 10) v -= ctx.rand->range(0, 10 - board_live);
if (board_live > 10) v -= ctx.rand->range(0, board_live);
return v;
}
} // namespace
int team_rating(GameState& g, int team, const RatingProfile& profile, RatingContext& ctx, int* keeper) {
if (team >= 168 && team != kNoTeam) {
// Clubs without squad: per group a random value around the level of the club
// (ForeignClubStrength bits 5-7 -> RatingRuntimeField2), +2 if the group's strength bit is set
// (bit 3, 3, 2, 1 for goal, defence, midfield, attack: RatingRuntimeField3) and a style
// offset (RatingRuntimeField4: bit 0 clear = +6 defence -6 attack, set = the opposite).
static const uint8_t kLevel[8] = {55, 61, 65, 67, 70, 73, 76, 80};
static const uint8_t kStrongBit[4] = {3, 3, 2, 1};
static const int8_t kStyle[8] = {0, 6, 0, -6, 0, -6, 0, 6};
if (!ctx.rand) throw std::invalid_argument("team_rating: a team without squad needs the Watcom generator");
const uint8_t s = g.foreign_strength.at(size_t(team - 168));
int16_t total = 0;
for (int i = 0; i < 4; i++) {
const int level = kLevel[s >> 5];
const int strong = ((s >> kStrongBit[i]) & 1) * 2;
const int v = strong + ctx.rand->range(level, level + 3) - 1 + kStyle[(s & 1) * 4 + i];
total = int16_t(total + profile.weight[i] * int16_t(v) / 100);
}
return total;
}
// Human managers: the predicted final rank (Void5 in mode 1 before the tenth
// round of the manager's league, mode 2 after it) for the expected bonus. Mode 1 may
// post the season goal messages.
const int manager = team == kNoTeam ? -1 : g.manager_of(team); // local_5a
int rank = 0; // local_5e
if (manager >= 0) {
const size_t rec = size_t(manager) * 0xB0C;
const int league = g.manager_records.at(rec + 0x210);
const int mode = (league < int(g.league_rounds.size()) && g.league_rounds[size_t(league)] > 9) + 1;
std::array<uint8_t, 24> buf;
int size_word = -1;
const int r = table_prediction(g, g.manager_teams.at(size_t(manager)), mode, buf, &size_word);
rank = r == 0 ? 0xB : r + 1;
// Void5 (3 arguments) is called from the same frame as the player values
// (PlayerValue, 6 arguments): its league size word (local_2c, [ESP+0xfc]) lands in
// the slot of their technique (local_20). Profiles without the technique attribute
// (4, 5) compare the condition against it (see RatingContext::stale_technique); it
// matters only when the chance weather's rain byte exceeds 2.
if (size_word >= 0 && !(profile.attrs & attr::TECHNIQUE)) ctx.stale_technique = size_word;
}
int board_depth = 0x32; // local_76: slot byte 0x0f of the board
int board_live = 10; // local_62: half of slot byte 5, only with the live scene
static const int8_t kGroupDepth[4] = {1, 8, 13, 22}; // RatingRuntimeField5: group if x < value
static const int8_t kNominal[4] = {1, 4, 4, 2}; // RatingRuntimeField6: nominal 1-4-4-2
int16_t bucket[12] = {}; // local_84: 4 groups x 3 lanes
uint8_t count[12] = {}; // local_6c
uint8_t in_group[4] = {}; // RatingRuntimeField7
int8_t missing = 11; // local_18: 11 - line-up size
if (keeper) *keeper = 0xFFF;
SquadRange range = squad_range(team);
for (size_t s = range.first; s < range.first + range.count; s++) {
uint16_t slot = g.squad_slots.at(s);
int player = slot & 0x0FFF;
if (player == 0xFFF) break; // the original stops at the first empty slot
if (!(slot & kSlotInLineup)) continue;
g.players.at(player).w364 |= 0x1000; // mark as having played
missing--;
int x = 0, y = 0;
const int board_slot = int(s - range.first);
g.formation_position(team, board_slot, x, y);
const size_t board = size_t(manager) * 0x840 + size_t(board_slot) * 0x58;
if (manager >= 0) {
board_depth = g.tactics.at(board + 0xf);
if (ctx.live_scene) board_live = g.tactics.at(board + 5) / 2;
}
for (int group = 0; group < 4; group++) {
if (x >= kGroupDepth[group]) continue;
in_group[group]++;
int lane = (group == 1 || group == 2) ? y / 3 : 0;
if (profile.weight[group] != 0) {
int v = player_value(g, player, profile.attrs, 100, team, ctx, x, y);
// the next call finds this player's condition/technique on the stack
if (profile.attrs & attr::CONDITION) ctx.stale_condition = g.players[player].condition();
if (profile.attrs & attr::TECHNIQUE) ctx.stale_technique = g.players[player].technique();
if (manager >= 0) v = human_correction(g, ctx, manager, rank, board_slot, player, group, profile.weight[group], x, y, board_depth, board_live, v);
int16_t value = int16_t(v);
if (value < 0) value = 0;
bucket[group * 3 + lane] = int16_t(bucket[group * 3 + lane] + value);
count[group * 3 + lane]++;
if (group == 0) {
if (y == 4) {
if (keeper) *keeper = player;
} else {
bucket[lane] = 0; // a goalkeeper off the centre does not count
}
if (g.players[player].position() != 0) bucket[lane] = int16_t(bucket[lane] / 6); // not a keeper
}
}
break;
}
}
if (missing < 0) missing = 0; // the original reports an internal error (0x6f) here
if (profile.weight[0] != 0 && bucket[0] == 0)
for (int i = 0; i < 9; i++) bucket[i] = 0; // no goalkeeper: goal, defence and 2 mid buckets are void
int total = 0; // local_34, used as a short
for (int group = 0; group < 4; group++) {
int8_t diff = int8_t(in_group[group] - kNominal[group]);
for (int lane = 0; lane < 3; lane++) {
int i = group * 3 + lane;
if (profile.weight[group] == 0 || count[i] == 0) continue;
if (diff != 0) bucket[i] = int16_t(bucket[i] * (diff * 10 + 100) / 100);
bucket[i] = int16_t(profile.weight[group] * bucket[i] / 100);
if (group == 1 || group == 2) count[i] = uint8_t(count[i] * 3);
total = int16_t(total) + bucket[i] / count[i];
}
}
if (missing != 0) total = int16_t(total) * 100 / (missing * 10 + 100);
if (int16_t(total) > 110) total = 110;
return total;
}
} // namespace bmh
+106
View File
@@ -0,0 +1,106 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// Player and team ratings used by the match engine.
//
// Ported from BMH.exe V2.24:
// player_value PlayerValue weighted value of one player for a set of attributes
// team_rating TeamRating rating of a line-up for one of six rating profiles
//
// For the teams of human managers the players are placed by the tactics board (block
// TacticsBoards) and their values are corrected by the board settings, the expected bonus
// (prediction.hpp) and random motivation draws.
#include <cstdint>
#include "game/random.hpp"
#include "game/state.hpp"
namespace bmh {
// Attribute bits of player_value (the "param_2" of PlayerValue). Each selected
// attribute adds value/weight to a weighted mean:
namespace attr {
constexpr uint16_t CONDITION = 1 << 0; // KO, weight 100
constexpr uint16_t TECHNIQUE = 1 << 1; // TE, weight 100
constexpr uint16_t FORM = 1 << 2; // not averaged: (form / 8 - 6) percent on the multiplier
constexpr uint16_t DEFENSIVE = 1 << 3; // 9 - 3 * position (goalkeeper 9 .. forward 0), weight 9
constexpr uint16_t OFFENSIVE = 1 << 4; // 3 * position, weight 9
constexpr uint16_t TEAMPLAY = 1 << 5; // skill * 5, weight 15 (bits 5-11 = the 7 skills)
constexpr uint16_t SPEED = 1 << 6;
constexpr uint16_t SHOOTING = 1 << 7;
constexpr uint16_t PASSING = 1 << 8;
constexpr uint16_t TACKLING = 1 << 9;
constexpr uint16_t FREE_KICK = 1 << 10;
constexpr uint16_t CORNER = 1 << 11;
constexpr uint16_t EXPERIENCE = 1 << 12; // min(3 * (w364 bits 2-7), 20), weight 20
} // namespace attr
// Match context globals the original reads while rating (ChanceRain, ChanceTemperature).
// They are per-match values of the running match; outside a match they keep whatever the
// last match left behind. Zero is the value after program start.
struct RatingContext {
int chance_rain = 0;
int chance_temperature = 0;
// local_1c of PlayerValue is only written when the condition attribute (bit 0) is
// selected; otherwise it holds whatever the previous call at the same stack depth left
// there. For the free kick taker (attributes 0x0802) that is the condition of the last
// candidate of the shooter pick just before. -1 = unknown, 0 is used.
int stale_condition = -1;
// local_20, the same for the technique (bit 1). Rating profiles 4 and 5 of the side
// record select the condition but not the technique, so the condition/technique
// comparison uses the technique of the player rated last with profile 3.
// (Now and then the original finds a larger value there: nothing in the program writes
// the slot in between, so a hardware interrupt on the stack must have - not modelled.)
int stale_technique = -1;
// Watcom generator for clubs without squad, whose ratings are drawn (TeamRating).
WatcomRandom* rand = nullptr;
// Game generator, needed for the players of human managers (the bonus motivation).
GameRandom* game = nullptr;
// LiveSceneVisible: the live scene is shown; then the board's slot byte 5 counts.
bool live_scene = false;
};
// PlayerValue for computer teams:
// player player id (0xFFF gives 0)
// attrs attribute bits (namespace attr)
// scale result scale, normally 100
// team team the player plays for (its morale counts)
// Result: scale * (sum * multiplier / 100) / weight, where multiplier =
// 100 + bonus/2 + form term - (6 - morale/4), with extra rules for KO/TE imbalance.
// x, y place on the tactics board (FormationPosition), 0xFF = none; only used for
// human managers from game level 4 on
int player_value(const GameState& g, int player, uint16_t attrs, int scale, int team, const RatingContext& ctx = {},
int x = 0xFF, int y = 0);
// The six rating profiles of the side record (table at layout field): weights for the
// goalkeeper, defence, midfield and attack groups plus the player_value attributes.
struct RatingProfile {
int16_t weight[4];
uint16_t attrs;
};
constexpr RatingProfile kRatingProfiles[6] = {
{{80, 10, 10, 0}, 0x0007}, // 0 goalkeeping: KO TE form
{{25, 55, 10, 10}, 0x0267}, // 1 defence: + teamplay speed tackling
{{20, 15, 45, 20}, 0x0367}, // 2 midfield: + passing
{{10, 10, 30, 50}, 0x0067}, // 3 attack: KO TE form teamplay speed
{{0, 33, 33, 34}, 0x0481}, // 4 KO shooting free kick
{{0, 33, 33, 34}, 0x0A01}, // 5 KO tackling corner
};
// TeamRating for computer teams. Walks the line-up (squad slots flagged in-line-up,
// stopping at the first empty slot), puts every player into a group by formation depth
// (x < 1 goalkeeper, < 8 defence, < 13 midfield, < 22 attack) and a lane (defence and
// midfield: left/centre/right = y / 3), sums player_value per bucket, corrects each group
// by 10 % per player above/below the nominal 1-4-4-2, weights and averages the buckets,
// scales down for fewer than 11 players and caps the result at 110.
//
// Side effects like the original: sets bit 12 of w364 for every line-up player and
// returns the goalkeeper's player id in *keeper (0xFFF if none) (RatingRuntimeField8).
// `ctx` carries the stale locals from call to call (see RatingContext) and is updated.
int team_rating(GameState& g, int team, const RatingProfile& profile, RatingContext& ctx, int* keeper = nullptr);
inline int team_rating(GameState& g, int team, const RatingProfile& profile) {
RatingContext ctx;
return team_rating(g, team, profile, ctx);
}
} // namespace bmh
+223
View File
@@ -0,0 +1,223 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "game/reality_ball.hpp"
#include "game/reality_duel.hpp"
#include <algorithm>
#include <cstdlib>
namespace bmh {
namespace {
int source_char(int v) { return int(int8_t(v)); }
int source_short(int v) { return int(int16_t(v)); }
int value(const GameState& state,const RealitySetup& scene,int figure,uint16_t attrs,int scale,
int team,int x,int y,const RatingContext& context) {
return player_value(state,scene.players.at(size_t(figure)).player,attrs,scale,team,context,x+30,y+30);
}
void validate(const GameState& state,const RealitySetup& scene,int actor) {
if (actor<0 || actor>=22 || scene.attacking_side<0 || scene.attacking_side>1 ||
actor/11!=scene.attacking_side || !scene.motion.figures[size_t(actor)].active)
throw FormatError("Reality ball: invalid actor/side");
for (int id=0;id<22;++id) if (scene.motion.figures[size_t(id)].active) {
const int player=scene.players[size_t(id)].player;
if (player<0 || size_t(player)>=state.players.size() || size_t(player)>=state.player_bonus.size())
throw FormatError("Reality ball: missing player attributes/bonus");
}
for (int team:scene.teams) if (team<0 || size_t(team)>=state.team_morale.size())
throw FormatError("Reality ball: missing team morale");
}
int blockers(const RealitySetup& scene,const RealityPath& path,int side,bool select,WatcomRandom& rand,RealityBallDecision& result) {
const auto line=reality_line_occupants(scene,path,side,select,rand);
result.line_selected[size_t(side)]=line.selected;return line.count;
}
} // namespace
RealityBallDecision decide_reality_ball(const GameState& state,const RealitySetup& scene,int actor,
const RealityBallHistory& history,const RatingContext& rating,WatcomRandom& rand) {
validate(state,scene,actor);RealityBallDecision result;result.actor=actor;result.side=scene.attacking_side;
const int side=result.side,team=scene.teams[size_t(side)];const auto start=scene.grid.position(actor);
const auto ball=scene.grid.ball();const auto goal=reality_goal_path(ball.first,ball.second,side ? 0 : 42);
result.original_x=start.first;result.original_y=start.second;
const auto goal_target=goal.points[goal.count-1];const auto& tactics=scene.tactics[size_t(side)];
result.previous_actor=actor!=history.current_actor ? history.current_actor : history.previous_actor;
result.target_x=ball.first;result.target_y=ball.second;
const int distance=42-std::abs(side*42-start.first);result.goal_distance=distance;
const int own_blocked=blockers(scene,goal,side,true,rand,result);
const int other_blocked=blockers(scene,goal,1-side,true,rand,result);
const int blocked=own_blocked+other_blocked;
result.goal_blockers=blocked;
result.opponent_nearby=uint8_t(reality_nearby(scene,start.first,start.second,1-side,3,true));
result.teamplay=source_char(value(state,scene,actor,0x20,30,team,start.first,start.second,rating));
result.shooting=source_char(value(state,scene,actor,0x80,30,team,start.first,start.second,rating));
result.passing=source_char(value(state,scene,actor,0x100,15,team,start.first,start.second,rating));
result.opponent_at_actor=scene.grid.occupant(start.first,start.second,1-side);
int best=source_short(-2*(distance/(tactics[2]+1))+60+rand.range(10,20));
const auto& player=state.players[size_t(scene.players[size_t(actor)].player)];
result.speed_ability=source_char(int((player.w35c>>14)&127)+int((player.w368>>3)&3)*10);
best+=25-int((player.w368>>4)&3)*3-blocked*10;
if (!result.opponent_nearby && rand.range(7,9)<distance) best=0;
const int center=std::abs(start.second-12);best-=center*3;
// Preserve left-to-right short-circuit order, even when the draw's other
// spatial predicates will subsequently fail.
if ((distance<4 && center<6) || (distance<rand.range(5,7) && !blocked && center<8) ||
distance>36 || actor%11==0) best=100;
if (result.opponent_at_actor) best-=5;
if (!distance && start.second!=12) best=0;
if (distance>int(tactics[2])*3+10) best=0;
result.airborne=uint8_t(rand.range(0,1)!=0);
if (result.shooting+3<rand.range(0,int(goal.count)*2+10)) {
result.scatter_x=rand.range(0,4)-2;result.scatter_y=rand.range(0,4)-2;
}
if ((blocked || (history.airborne && rand.range(0,1)!=0)) &&
(result.opponent_at_actor || blocked>2 || rand.range(0,int(result.airborne)+1)==0) &&
(!result.opponent_at_actor || rand.range(0,3)==0)) {
result.blocked_attempt=true;
result.scatter_x=rand.range(0,4)-2;result.scatter_y=rand.range(0,4)-2;
}
if (source_short(best)>0) {
const auto target=goal.points[goal.count>20 ? 20 : goal.count-1];
result.target_x=uint8_t(target.first+result.scatter_x);result.target_y=uint8_t(target.second+result.scatter_y);
}
if (result.opponent_at_actor && result.shooting+20<rand.range(0,(distance<7 ? 50 : 0)+50)) {
result.intercepted=true;result.target_x=uint8_t(rand.range(0,8)+ball.first-4);
result.target_y=uint8_t(rand.range(0,8)+ball.second-4);
}
result.inaccurate=result.scatter_x || result.scatter_y;
int support_bias=source_char(center+result.teamplay-10);
if (distance<rand.range(4,8)) support_bias=0;
for (int id=side*11;id<side*11+11;++id) {
if (id==actor || !scene.motion.figures[size_t(id)].active) continue;
const auto target=scene.grid.position(id);const int target_distance=42-std::abs(side*42-target.first);
int score=support_bias+rand.range(3,16-result.passing/2)+(tactics[3]+1)*(distance-target_distance);
if (target_distance-5>distance) continue;
if (distance>12) score=source_short(score)+center/2;
if (distance<9) score-=center;
const int low=result.passing/2+3,high=result.passing/2+15;
const int separation=std::abs(distance-target_distance);
if (separation>rand.range(low,high) || std::abs(start.second-target.second)>rand.range(low,high)) continue;
const bool offside=reality_offside(scene,target.first);
if (offside && rand.range(0,3)!=0) continue;
const auto line=reality_path(start.first,start.second,target.first,target.second);
const int obstructions=blockers(scene,line,1-side,true,rand,result);
const int nearby=reality_nearby(scene,target.first,target.second,1-side,2,true);
score+=33-obstructions*2-nearby*15;
if (target_distance<8 && target_distance-3<distance) {
const auto onward=reality_path(target.first,target.second,goal_target.first,goal_target.second);
score+=12-4*blockers(scene,onward,1-side,false,rand,result);
}
if (source_short(best)>=source_short(score)) continue;
result.receiver=id;result.receiver_player=scene.players[size_t(id)].player;
const int loft_bias=source_char((3-int(tactics[4]))*2);
result.airborne=uint8_t(rand.range(separation>loft_bias+6,separation>loft_bias+3));
const int accuracy_draw=rand.range(0,2);
if (((((result.airborne!=0 || accuracy_draw==0) && (result.airborne==0 || accuracy_draw!=0)) || !obstructions)) &&
rand.range(0,40)<result.passing) {
result.scatter_x=0;result.scatter_y=0;result.inaccurate=false;
}
result.receiver_offside=offside;result.action=1;result.leading_run=false;
int target_x=target.first;const int direction=side ? -1 : 1;
if (target_distance>6 && result.passing+rand.range(0,1)*8>5) {
for (int step=0;step<2;++step) {
result.receiver_nearby=reality_nearby(scene,target.first+step,target.second,1-side,2,true);
if (result.receiver_nearby<=nearby+1 &&
(!step || (target_x+direction>=0 && target_x+direction<=42 &&
!scene.grid.occupant(target_x+direction,target.second,1-side)))) {
target_x+=direction;result.leading_run=true;score+=10;
}
}
}
result.target_x=uint8_t(target_x+result.scatter_x);result.target_y=uint8_t(target.second+result.scatter_y);best=score;
}
int dribble;
if (result.opponent_nearby==1 && blocked<=1) dribble=35;
else dribble=40-int(result.opponent_nearby)*(result.opponent_nearby<2 ? 25 : 20);
dribble+=center+distance-blocked*5+22;
if (distance<6) dribble-=10;
if (result.opponent_at_actor) {
bool behind=false;
for (int id=side*11+1;id<side*11+11;++id) {
const int x=scene.grid.position(id).first;
if (scene.motion.figures[size_t(id)].active && (side ? start.first<x : x<start.first)) behind=true;
}
if (!behind) dribble=5;
if (result.opponent_nearby>2) dribble-=rand.range(0,8)+15;
const int own=uint8_t(value(state,scene,actor,0x20e,100,team,start.first,start.second,rating));
const int opponent=uint8_t(source_char(value(state,scene,result.opponent_at_actor-1,0x20e,100,
scene.teams[size_t(1-side)],start.first,start.second,rating))+scene.tactics[size_t(1-side)][6]*10);
result.actor_duel=uint8_t(own);result.opponent_duel=uint8_t(opponent);
dribble+=(own-opponent)/2;
}
if (actor%11==0 && (distance<34 || result.opponent_nearby)) dribble=0;
result.score=source_short(best);result.dribble_score=source_short(dribble);
if (result.dribble_score>result.score) result.boundary=RealityBallBoundary::dribble_or_duel;
return result;
}
namespace {
RealityBallOutcome apply_ball_tail(const GameState& state,RealitySetup& scene,const RealityBallDecision& decision,
RealityBallHistory& history,const RatingContext& rating,uint8_t referee,WatcomRandom& rand,GameRandom& game,
const RealityDribbleDecision* dribble) {
if (!dribble && decision.boundary!=RealityBallBoundary::direct_move)
throw FormatError("Reality ball: dribble/duel continuation is not implemented");
validate(state,scene,decision.actor);
if (decision.side!=scene.attacking_side || decision.action<0 || decision.action>(dribble ? 2 : 1))
throw FormatError("Reality ball: invalid direct decision");
const int actor=decision.actor,side=decision.side;
const auto start=dribble ? std::pair{decision.original_x,decision.original_y} : scene.grid.position(actor);
const auto old_ball=scene.grid.ball();
auto target=std::pair{decision.target_x,decision.target_y};RealityBallOutcome outcome;outcome.action=decision.action;
auto actor_target=dribble ? std::pair{dribble->actor_target_x,dribble->actor_target_y} : start;
if (dribble) {
outcome.scene_status=dribble->scene_status;outcome.restart=dribble->restart;
outcome.event_stops_scene=dribble->event_stops_scene;outcome.lost_duel=dribble->lost_duel;
}
uint8_t airborne=decision.airborne;
if (history.airborne) {
const int control=source_short(value(state,scene,actor,6,100,scene.teams[size_t(side)],start.first,start.second,rating));
if (control<rand.range(0,120)) { target=start;actor_target=start;outcome.action=3;airborne=0; }
else outcome.received=true;
}
const auto path=reality_path(start.first,start.second,actor_target.first,actor_target.second);
const auto point=path.points[std::min(size_t(dribble ? dribble->steps : 2),path.count-1)];
if (outcome.action==2 && !outcome.lost_duel) target=point;
if (!scene.grid.place(actor,point.first,point.second,side) && !scene.grid.place(actor,start.first,start.second,side)) {
outcome.scene_status=3;outcome.needs_reporter=false;return outcome; // Source returns before reporter
}
const auto accepted=scene.grid.position(actor);scene.motion.figures[size_t(actor)].next_x=accepted.first;
scene.motion.figures[size_t(actor)].next_y=accepted.second;
history.previous_actor=outcome.action==1 ? actor : decision.previous_actor;history.current_actor=actor;
if (outcome.action==0) outcome.shot_ready=true;
if (target.first>42) {
outcome.scene_status=1;target.first=std::clamp(source_char(target.first),0,42);
target.second=game.range(0,1) ? 14 : 10;
if (decision.blocked_attempt) outcome.restart=3;
}
if (target.second>24) { outcome.scene_status=2;target.second=std::clamp(source_char(target.second),0,24); }
if (outcome.action==0 && decision.goal_distance<37) {
outcome.shooter_row=actor;outcome.assistant_row=history.previous_actor;
outcome.shooter=scene.players[size_t(actor)].player;
if (history.previous_actor>=0 && history.previous_actor<22 && history.previous_actor/11==side)
outcome.assistant=scene.players[size_t(history.previous_actor)].player;
}
if (decision.receiver_offside && rand.range(0,(referee&3)*2+2)!=0) outcome.scene_status=3;
if (!scene.grid.place(22,target.first,target.second,2)) throw FormatError("Reality ball: invalid Source final ball");
auto& shadow=scene.motion.figures[22];shadow={true,old_ball.first,old_ball.second,target.first,target.second,shadow.phase};
auto& ball=scene.motion.figures[23];ball.active=true;ball.old_x=old_ball.first;ball.old_y=old_ball.second;
ball.next_x=target.first;ball.next_y=target.second;scene.motion.ball_airborne=airborne!=0;history.airborne=airborne;
return outcome; // explicit InitializeRealityReporter / reporter-RNG boundary
}
} // namespace
RealityBallOutcome apply_reality_ball(const GameState& state,RealitySetup& scene,const RealityBallDecision& decision,
RealityBallHistory& history,const RatingContext& rating,uint8_t referee,WatcomRandom& rand,GameRandom& game) {
return apply_ball_tail(state,scene,decision,history,rating,referee,rand,game,nullptr);
}
RealityBallOutcome apply_reality_dribble(const GameState& state,RealitySetup& scene,const RealityDribbleDecision& decision,
RealityBallHistory& history,const RatingContext& rating,uint8_t referee,WatcomRandom& rand,GameRandom& game) {
if (decision.ball.boundary!=RealityBallBoundary::dribble_or_duel || decision.ball.action!=2 ||
decision.steps<1 || decision.steps>2)
throw FormatError("Reality dribble: invalid prepared decision");
return apply_ball_tail(state,scene,decision.ball,history,rating,referee,rand,game,&decision);
}
} // namespace bmh
+46
View File
@@ -0,0 +1,46 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/rating.hpp"
#include "game/reality_space.hpp"
namespace bmh {
struct RealityBallHistory {
int current_actor = 0xfff, previous_actor = 0xfff; // afb08/afb06
uint8_t airborne = 0; // afb72
};
enum class RealityBallBoundary { direct_move, dribble_or_duel };
struct RealityBallDecision {
RealityBallBoundary boundary = RealityBallBoundary::direct_move;
int actor = 0, side = 0, previous_actor = 0xfff;
int action = 0, score = 0, dribble_score = 0; // afb7a:0 shot,1 pass; source shorts
int goal_distance = 0, shooting = 0, passing = 0, teamplay = 0;
int original_x = 0, original_y = 0, goal_blockers = 0, speed_ability = 0;
uint8_t actor_duel = 0, opponent_duel = 0;
int receiver = -1, receiver_player = 0xfff, target_x = 0, target_y = 0;
uint8_t airborne = 0, opponent_at_actor = 0, opponent_nearby = 0;
std::array<uint8_t,2> line_selected{}; // afaec, one-based occupancy IDs
int scatter_x = 0, scatter_y = 0, receiver_nearby = 0;
bool intercepted = false, inaccurate = false, blocked_attempt = false;
bool receiver_offside = false, leading_run = false;
};
// ApplyRealityBall prefix through the shot/pass-vs-dribble decision. Caller must clear
// the actor's old occupancy, as DecideRealityBall does. Uses Source rating context/RNG;
// no fabricated foul/dribble outcome and no reporter text draws.
RealityBallDecision decide_reality_ball(const GameState&, const RealitySetup&, int actor,
const RealityBallHistory&, const RatingContext&, WatcomRandom&);
struct RealityBallOutcome {
int action = 0, scene_status = 0, restart = 0, shooter = 0xfff, assistant = 0xfff;
int shooter_row = 0xfff, assistant_row = 0xfff;
bool received = false, shot_ready = false, needs_reporter = true;
bool event_stops_scene = false, lost_duel = false;
};
// ApplyRealityBall's common tail for a selected shot/pass. Source Game/Watcom calls
// for airborne reception, boundary handling and pass offside are preserved.
// A dribble/duel decision is rejected before any mutation or additional draws.
RealityBallOutcome apply_reality_ball(const GameState&, RealitySetup&, const RealityBallDecision&,
RealityBallHistory&, const RatingContext&, uint8_t referee,
WatcomRandom&, GameRandom&);
} // namespace bmh
+97
View File
@@ -0,0 +1,97 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "game/reality_duel.hpp"
#include <algorithm>
#include <cstdlib>
namespace bmh {
namespace {
int source_manager(const GameState& state,int team) {
const int m=state.manager_of(team);if (m>=0) return m;
if (!state.manager_teams.empty() && state.manager_teams[0]==kNoTeam &&
state.manager_records.size()>=4*0xb0c+0x292 && le16(state.manager_records,4*0xb0c+0x290)==team) return 4;
return -1;
}
}
RealityFoulResult reality_foul(const GameState& state,const RealitySetup& scene,int offender,bool defending,
int ball_actor,uint8_t referee,bool muted,WatcomRandom& rand,const RealityForcedEvent& forced_event, const RealitySound& sound) {
if (offender<0 || offender>=22 || ball_actor<0 || ball_actor>=22)
throw FormatError("Reality foul: invalid figure");
const auto& placement=scene.players[size_t(offender)];const int slot=placement.squad_slot;
if (slot<0 || size_t(slot)>=state.squad_slots.size()) throw FormatError("Reality foul: missing Source squad slot");
const int player=state.squad_slots[size_t(slot)]&0xfff;
if (player==0xfff || size_t(player)>=state.players.size()) throw FormatError("Reality foul: missing Source player");
const int team=scene.teams[size_t(offender/11)],manager=source_manager(state,team);
const auto& p=state.players[size_t(player)];
int chance=std::clamp((int((p.w35c>>14)&127)-int((p.w35c>>7)&127))*4+100,0,200);
// Literal RealityFoul indexes by player ID minus squad start, not roster row.
const int board_row=std::clamp(player-int(squad_range(team).first),0,24);
if (manager>=0) {
const size_t at=size_t(manager)*0x840+size_t(board_row)*0x58+5;
if (at>=state.tactics.size()) throw FormatError("Reality foul: Source board row outside supplied memory");
chance=(int(state.tactics[at])+chance)*100/239;
}
RealityFoulResult result;if (rand.range(0,100)>=chance) return result;
result.cues.push_back({ball_actor,defending ? 19 : 18});
result.whistle=rand.range(0,1)==0 && !muted;
if (result.whistle && sound) sound(21); // RealityFoul, before the forced event.
result.result=2;
if (rand.range(0,(referee&3)+1)==0) return result;
result.cues.push_back({-1,20}); // RealityFoul does not assign MatchEngine_Minute_ExecutableField2 for this cue.
if (!forced_event) throw FormatError("Reality foul: real forced card/injury engine callback required");
result.event_result=forced_event(slot,offender>10);
result.event_kind=result.event_result&0x7f;
result.result=3;
if (result.event_result) {
result.cues.push_back({defending ? offender : ball_actor,21});result.event_stops_scene=true;
}
if (!defending) result.scene_status=4;
else {
const auto ball=scene.grid.ball();const int distance=42-std::abs(scene.attacking_side*42-ball.first);
result.restart=distance<7 && ball.second>3 && ball.second<21 ? 2 : 1;
}
return result;
}
RealityDribbleDecision continue_reality_dribble(const GameState& state,RealitySetup& scene,const LeImage& exe,const RealityBallDecision& decision,
uint8_t referee,bool muted,WatcomRandom& rand,const RealityForcedEvent& forced_event, const RealitySound& sound) {
if (decision.boundary!=RealityBallBoundary::dribble_or_duel || decision.actor<0 || decision.actor>=22 ||
decision.side!=scene.attacking_side) throw FormatError("Reality dribble: invalid continuation");
RealityDribbleDecision result;result.ball=decision;result.ball.action=2;result.ball.airborne=0;
result.ball.receiver_offside=false;
if (decision.speed_ability<rand.range(0,130)) result.steps=1;
auto foul=[&](int offender,bool defending) {
const auto f=reality_foul(state,scene,offender,defending,decision.actor,referee,muted,rand,forced_event,sound);
if (f.scene_status) result.scene_status=f.scene_status;if (f.restart) result.restart=f.restart;
result.event_stops_scene=result.event_stops_scene||f.event_stops_scene;
if(f.event_result)result.card_kind=f.event_kind;
result.cues.insert(result.cues.end(),f.cues.begin(),f.cues.end());return f.result;
};
if (decision.opponent_at_actor) {
bool attacking_foul=false;const int roll=rand.range(0,3);
if (roll==0) attacking_foul=true;
else if (roll!=3) {
const int own_roll=rand.range(0,10);const int other_roll=rand.range(0,10);
if (decision.actor_duel+own_roll<decision.opponent_duel+other_roll) attacking_foul=true;
}
if (attacking_foul) {
if (rand.range(0,1)!=0 || !(foul(decision.actor,false)&2)) result.lost_duel=true;
} else if (decision.goal_distance<rand.range(12,15) &&
(foul(decision.opponent_at_actor-1,true)&2)) result.lost_duel=true;
if (result.lost_duel) result.steps=1;
}
const auto ball=scene.grid.ball();const auto goal=reality_goal_path(ball.first,ball.second,decision.side ? 0 : 42);
auto target=goal.points[goal.count-1];
if (!(decision.goal_blockers<2 && decision.goal_distance<12 && decision.opponent_nearby<2)) {
const auto space=reality_seek_space(scene,exe,decision.actor,decision.side,0x11,0,goal);
target=space.found ? std::pair{space.x,space.y} : scene.grid.position(decision.actor);
}
scene.grid.stage_position(decision.actor,target.first,target.second);
result.actor_target_x=target.first;result.actor_target_y=target.second;
result.ball.target_x=result.lost_duel ? ball.first : target.first;
result.ball.target_y=result.lost_duel ? ball.second : target.second;
return result;
}
} // namespace bmh
+42
View File
@@ -0,0 +1,42 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <functional>
#include <vector>
#include "game/reality_ball.hpp"
namespace bmh {
// EventImpl(absolute squad slot,1,figure>10). Must execute the real forced
// card/injury routine and return its byte. No default substitute is supplied.
using RealityForcedEvent = std::function<uint8_t(int slot,int side)>;
using RealitySound = std::function<void(uint8_t)>;
struct RealityFoulCue { int actor = -1, code = 0; }; // -1: Source leaves that actor slot unchanged
struct RealityFoulResult {
uint8_t result = 0, event_result = 0;
uint8_t event_kind = 0; // MatchEngine_Minute_ExecutableField, return byte with bit7 stripped
int scene_status = 0, restart = 0;
bool whistle = false, event_stops_scene = false;
std::vector<RealityFoulCue> cues;
};
// RealityFoul up to/through the caller-owned forced-event boundary.
RealityFoulResult reality_foul(const GameState&,const RealitySetup&,int offender,bool defending,
int ball_actor,uint8_t referee,bool muted,WatcomRandom&,
const RealityForcedEvent&, const RealitySound& sound = {});
struct RealityDribbleDecision {
RealityBallDecision ball;
int actor_target_x = 0, actor_target_y = 0, steps = 2;
bool lost_duel = false;
int scene_status = 0, restart = 0;
bool event_stops_scene = false;
std::vector<RealityFoulCue> cues;
std::optional<uint8_t> card_kind; // MatchEngine_Minute_ExecutableField changes only on a nonzero forced return
};
// ApplyRealityBall dribble/duel continuation; never reruns the earlier selection draws.
RealityDribbleDecision continue_reality_dribble(const GameState&,RealitySetup&,const LeImage&,const RealityBallDecision&,
uint8_t referee,bool muted,WatcomRandom&,
const RealityForcedEvent& forced_event = {}, const RealitySound& sound = {});
RealityBallOutcome apply_reality_dribble(const GameState&,RealitySetup&,const RealityDribbleDecision&,
RealityBallHistory&,const RatingContext&,uint8_t referee,
WatcomRandom&,GameRandom&);
} // namespace bmh
+103
View File
@@ -0,0 +1,103 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/reality_match.hpp"
#include <algorithm>
#include "game/lineup.hpp"
namespace bmh {
namespace {
void validate_owner(const MatchEngine& engine,const RealityMatchScene& owner) {
if(owner.state_owner!=&engine.state||owner.rand_owner!=&engine.rand||owner.game_owner!=&engine.game||
owner.date!=engine.state.date||owner.group>=engine.groups.size()||owner.match<0||
owner.group_count!=engine.groups.size()||owner.fixture_owner!=&engine.groups[owner.group])
throw FormatError("Reality match: stale engine/fixture owner");
const auto& group=engine.groups[owner.group];
if(owner.match>=group.matches()||group.fixtures.at(size_t(owner.match)*2)!=owner.teams[0]||
group.fixtures.at(size_t(owner.match)*2+1)!=owner.teams[1])
throw FormatError("Reality match: fixture changed during scene");
}
}
void initialize_reality_match_scene(MatchEngine& engine,size_t group,int match,int side,int minute,
const LeImage& exe,RealitySceneContext context,RealityMatchScene& owner) {
if(group>=engine.groups.size()||match<0||match>=engine.groups[group].matches()||side<0||side>1||minute<1)
throw FormatError("Reality match: invalid Source fixture/minute");
if(owner.state_owner&&(!owner.scene.finished||!owner.settled))
throw FormatError("Reality match: previous scene/change has not completed");
const auto& fixture=engine.groups[group];
context.referee_index=fixture.desc.at(0x10+size_t(match));
context.referee_profile=engine.referees.at(context.referee_index);
context.numbers=engine.button(::bmh::layout::RealityMatch_FormatError_ExecutableField)==0;
const std::array<int,2> teams{fixture.fixtures[size_t(match)*2],fixture.fixtures[size_t(match)*2+1]};
owner.pending.reset();owner.settled=owner.settling=false;
owner.group=group;owner.group_count=engine.groups.size();owner.fixture_owner=&fixture;owner.match=match;owner.minute=minute;owner.teams=teams;
owner.date=engine.state.date;owner.state_owner=&engine.state;
owner.rand_owner=&engine.rand;owner.game_owner=&engine.game;
initialize_reality_scene(engine.state,teams,side,reality_formations(engine.state,teams),exe,
context,engine.rand,engine.game,owner.scene);
}
RealitySceneTick advance_reality_match_scene(MatchEngine& engine,RealityMatchScene& owner,const LeImage& exe,
MinuteReport& report,bool user_exit) {
validate_owner(engine,owner);
if(owner.scene.finished||owner.settled||owner.settling||report.unsupported)
throw FormatError("Reality match: round outside active Source scene");
// RealityReporterPanel resets bdb14 before each DecideRealityBall, not after scene completion.
owner.pending.reset();
const auto forced=[&](int slot,int side) {
auto& group=engine.groups[owner.group];
const int player=engine.state.squad_slots.at(size_t(slot))&0xfff;
const auto event=engine.forced_event(group,owner.match,side,owner.minute,slot,report);
if(report.unsupported)throw FormatError(report.reason);
if(event.change) {
const int kind=(event.code&0x7f)==4?2:(event.code&0x7f)==1?0:1;
const int team=owner.teams.at(size_t(side)),other=owner.teams.at(size_t(1-side));
owner.pending=RealityDeferredRequest{*event.change,
LiveMatchEvent{owner.group,owner.match,side,team,other,player,kind,owner.minute,
event.change->human?event.change->mode:engine.state.manager_of(team)},slot};
}
return event.code;
};
return advance_reality_scene(engine.state,owner.scene,exe,engine.rand,engine.game,forced,user_exit);
}
bool settle_reality_match_scene(MatchEngine& engine,RealityMatchScene& owner,MinuteReport& report) {
validate_owner(engine,owner);
if(!owner.scene.finished||owner.settling)
throw FormatError("Reality match: change before scene end or reentrant completion");
if(owner.settled||report.unsupported)return false;
if(!owner.pending){owner.settled=true;return false;}
const auto request=*owner.pending;const auto& event=request.event;const auto& change=request.source;
if(event.group_index!=owner.group||event.match_index!=owner.match||event.minute!=owner.minute||
event.side<0||event.side>1||event.team!=owner.teams[size_t(event.side)]||
event.opponent!=owner.teams[size_t(1-event.side)])
throw FormatError("Reality match: deferred request belongs to another fixture");
const auto range=squad_range(event.team);
if(request.offender_slot<int(range.first)||request.offender_slot>=int(range.first+range.count)||
(engine.state.squad_slots.at(size_t(request.offender_slot))&0xfff)!=event.player)
throw FormatError("Reality match: deferred offender slot changed");
if(change.human) {
if(change.team!=event.opponent||change.slot!=0xff||change.mode!=event.manager_slot||
change.mode<0||engine.state.manager_of(event.team)!=change.mode||
(event.kind!=1&&event.kind!=2))
throw FormatError("Reality match: invalid Source human request");
if(!engine.live_event&&!engine.leave_screens) {
report.fail("deferred Reality substitution screen of a human manager (PitchScreen)");return false;
}
} else if(change.team!=event.team||change.slot!=request.offender_slot||
change.mode!=engine.state.players.at(size_t(event.player)).position()+20) {
throw FormatError("Reality match: invalid Source automatic request");
}
owner.settling=true;
try {
if(change.human) {
if(engine.state.memory.has(::bmh::layout::ActiveManager))engine.state.memory.set8(::bmh::layout::ActiveManager,uint8_t(change.mode));
if(engine.live_event)engine.live_event(event);
} else {
// Exact Injure(team,absoluteSlot,position+20). This tail does not
// call BuildSideRecords3 again: the actual card routine already did so.
(void)substitute(engine.state,change.team,change.slot,change.mode,engine.rand);
}
validate_owner(engine,owner); // callbacks retain stable fixture identity
} catch(...) {owner.settling=false;throw;}
owner.settling=false;owner.pending.reset();owner.settled=true;return true;
}
} // namespace bmh
+38
View File
@@ -0,0 +1,38 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/match_engine.hpp"
#include "game/reality_scene.hpp"
namespace bmh {
struct RealityDeferredRequest {
DeferredRealityChange source; // literal bdb14/16/18
LiveMatchEvent event; // actual fixed offender, fixture, manager and minute
int offender_slot = -1;
};
// Owned bridge between one actual fixture and the independent Source scene.
// Requests survive scene end, but do not execute while its figures still move.
struct RealityMatchScene {
RealityScene scene;
size_t group = 0;
int match = -1, minute = 0;
std::array<int,2> teams{};
uint32_t date = 0;
const MatchGroup* fixture_owner = nullptr;
size_t group_count = 0;
const GameState* state_owner = nullptr;
const WatcomRandom* rand_owner = nullptr;
const GameRandom* game_owner = nullptr;
std::optional<RealityDeferredRequest> pending;
bool settled = false, settling = false;
};
void initialize_reality_match_scene(MatchEngine&,size_t group,int match,int side,int minute,
const LeImage&,RealitySceneContext,RealityMatchScene&);
RealitySceneTick advance_reality_match_scene(MatchEngine&,RealityMatchScene&,const LeImage&,
MinuteReport&,bool user_exit = false);
// RealityReporterPanel tail. Returns true for an executed request (even a legal automatic
// no-change). Empty/repeated completion is drawless. Missing human presenter
// preserves the request and reports the existing unsupported boundary; only
// explicit leave_screens allows the legacy headless skip.
bool settle_reality_match_scene(MatchEngine&,RealityMatchScene&,MinuteReport&);
} // namespace bmh
+168
View File
@@ -0,0 +1,168 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/reality_motion.hpp"
#include <algorithm>
#include <cstdlib>
#include <numeric>
namespace bmh {
int reality_direction(int x, int y) {
if (x < -42 || x > 42 || y < -24 || y > 24)
throw FormatError("Reality: direction outside the Source grid");
int ax = std::abs(x), ay = std::abs(y);
if (!(ay > 1 && ax > 1 && ax != ay)) {
if (ay < ax) ay *= 2;
else ax *= 2;
}
int direction = y == 0 ? 3 : std::abs(ax / ay);
if (direction > 2) direction = 3;
if (direction > 1) --direction;
if (y > 0 && direction == 0) direction = 4;
if (x < 0 && direction > 0 && direction != 4) direction += 4;
if (y > 0 && (direction == 1 || direction == 5)) direction += 2;
return direction;
}
std::pair<int, int> reality_project(const LeImage& exe, int x, int y) {
if (x < 0 || x > 42 || y < 0 || y > 24)
throw FormatError("Reality: position outside the Source grid");
// Int7: signed division truncates towards zero, including the horizon.
const int distance = (int(int16_t(exe.u16(::bmh::layout::RealityMotion_FormatError_RuntimeField4Unsigned + uint32_t(y * 2)))) - 2) * std::abs(21 - x) / 21;
return {153 + (x > 21 ? distance : -distance), exe.u8(::bmh::layout::RealityMotion_FormatError_RuntimeField5Unsigned + uint32_t(y))};
}
RealityMotionResult reality_motion(const RealityMotionInput& input, const LeImage& exe) {
RealityMotionResult result;
auto figures = input.figures;
// RealityFieldScreen copies the ground trajectory (22) to the elevated ball (23).
// Only its animation phase remains independent.
const auto ball_phase = figures[23].phase;
figures[23] = figures[22]; figures[23].phase = ball_phase;
std::array<int, 24> x{}, y{}, dx{}, dy{}, next_x{}, next_y{}, pose{}, phase{}, order{};
std::iota(order.begin(), order.end(), 0);
for (int i = 0; i < 24; ++i) {
const auto& figure = figures[size_t(i)];
// Source iterates all slots, but absent figures are not projected/drawn.
if (!figure.active) { result.phases_after[size_t(i)] = figure.phase; continue; }
const auto old = reality_project(exe, figure.old_x, figure.old_y);
const auto next = reality_project(exe, figure.next_x, figure.next_y);
x[size_t(i)] = old.first * 128; y[size_t(i)] = old.second * 128;
next_x[size_t(i)] = next.first; next_y[size_t(i)] = next.second;
dx[size_t(i)] = (next.first - old.first) * 128 / 10;
dy[size_t(i)] = (next.second - old.second) * 128 / 10;
pose[size_t(i)] = i < 22 ? exe.u8(::bmh::layout::RealityMotion_RealityMotion_RuntimeFieldUnsigned + uint32_t(reality_direction(
figure.next_x - figure.old_x, figure.next_y - figure.old_y) + (i > 10 ? 8 : 0))) : i - 14;
phase[size_t(i)] = figure.phase;
const int poses = exe.u8(::bmh::layout::RealityMotion_FormatError_RuntimeField7Unsigned + uint32_t(pose[size_t(i)]));
if (!poses || phase[size_t(i)] >= poses)
throw FormatError("Reality: animation phase outside the Source pose");
}
for (int tick = 0; tick < 11; ++tick) {
// Source's insertion sort uses final depth; equal depths keep slot order.
for (int group = 0; group < 8; ++group) {
const int start = exe.u8(::bmh::layout::RealityMotion_FormatError_RuntimeFieldUnsigned + uint32_t(group));
const int end = exe.u8(::bmh::layout::RealityMotion_FormatError_RuntimeField2Unsigned + uint32_t(group));
if (start > end || end > 24) throw FormatError("Reality: invalid Source depth-sort interval");
for (int index = start; index < end; ++index) {
int at = index;
while (at > 0 && next_y[size_t(order[size_t(at)])] < next_y[size_t(order[size_t(at - 1)])]) {
std::swap(order[size_t(at)], order[size_t(at - 1)]); --at;
}
}
}
auto& frame = result.frames[size_t(tick)];
for (int i : order) {
if (!figures[size_t(i)].active) continue;
const bool player = i < 22, away = i > 10;
int px = tick < 9 ? x[size_t(i)] / 128 : next_x[size_t(i)];
int py = tick < 9 ? y[size_t(i)] / 128 : next_y[size_t(i)];
int code = pose[size_t(i)], animation = phase[size_t(i)];
if (player) px += away ? 1 : -1;
if (!dx[size_t(i)] && !dy[size_t(i)]) {
animation = 0;
if (player) code = away ? 11 : 10;
} else if (i == 23 && input.ball_airborne) py -= exe.u8(::bmh::layout::RealityMotion_FormatError_RuntimeField3Unsigned + uint32_t(tick));
const int count = exe.u8(::bmh::layout::RealityMotion_FormatError_RuntimeField7Unsigned + uint32_t(code));
const int cell = exe.u8(::bmh::layout::RealityMotion_FormatError_RuntimeField6Unsigned + uint32_t(code)) + animation;
if (!count || cell < 0 || cell > 30) throw FormatError("Reality: invalid Source sprite cell");
frame.sprites[frame.count++] = {i, px, py, cell,
input.numbers && player ? i % 11 + 1 : 0, player && away};
if (tick < 9) phase[size_t(i)] = (animation + 1) % count;
x[size_t(i)] += dx[size_t(i)]; y[size_t(i)] += dy[size_t(i)];
}
}
for (int i = 0; i < 24; ++i) if (figures[size_t(i)].active)
result.phases_after[size_t(i)] = uint8_t(phase[size_t(i)]);
return result;
}
RealityPath reality_path(int x, int y, int target_x, int target_y) {
const auto valid = [](int xx, int yy) { return xx >= 0 && xx <= 42 && yy >= 0 && yy <= 24; };
if (!valid(x,y) || !valid(target_x,target_y)) throw FormatError("Reality: invalid path endpoint");
RealityPath path;
const int distance_x = std::abs(target_x-x), distance_y = std::abs(target_y-y);
const int length = std::max(distance_x,distance_y);
const int step_x = length ? distance_x*100/length : 0;
const int step_y = length ? distance_y*100/length : 0;
const int direction_x = target_x < x ? -1 : 1, direction_y = target_y < y ? -1 : 1;
int error_x = 0, error_y = 0;
while (x != target_x || y != target_y) {
path.points[path.count++] = {x,y};
// Preserve Source's finite array guard and duplicate terminal write.
if (path.count > 49) break;
if (x != target_x && (error_x += step_x) >= 100-step_x) { error_x -= 100;x += direction_x; }
if (y != target_y && (error_y += step_y) >= 100-step_y) { error_y -= 100;y += direction_y; }
}
path.points[path.count++] = {x,y};
return path;
}
RealityPath reality_goal_path(int x, int y, int goal_x) {
return reality_path(x,y,goal_x,y < 8 ? 11 : y > 16 ? 13 : 12);
}
bool RealityGrid::place(int figure, int x, int y, int side) {
if (figure < 0 || figure >= 24 || side < 0 || side > 2)
throw FormatError("Reality: invalid figure/occupancy side");
if (x < 0 || x > 42 || y < 0 || y > 24) return false;
if (side < 2) {
auto& cell = occupied_[size_t(side)][size_t(x*26+y)];
if (cell) return false;
cell = uint8_t(figure+1);
} else {
previous_ball_ = ball_; ball_ = {x,y};
}
positions_[size_t(figure)] = {x,y};
return true;
}
uint8_t RealityGrid::occupant(int x, int y, int side) const {
if (x < 0 || x > 42 || y < 0 || y > 24 || side < 0 || side > 1)
throw FormatError("Reality: invalid occupancy lookup");
return occupied_[size_t(side)][size_t(x*26+y)];
}
void RealityGrid::clear(int x, int y, int side) {
if (x < 0 || x > 42 || y < 0 || y > 24 || side < 0 || side > 1)
throw FormatError("Reality: invalid occupancy clear");
occupied_[size_t(side)][size_t(x*26+y)] = 0;
}
void RealityGrid::reset_occupancy() {
for (auto& side : occupied_) side.fill(0);
}
void RealityGrid::stage_position(int figure, int x, int y) {
if (figure < 0 || figure >= 24 || x < 0 || x > 42 || y < 0 || y > 24)
throw FormatError("Reality: invalid staged position");
positions_[size_t(figure)] = {x,y};
}
std::pair<int,int> RealityGrid::position(int figure) const {
if (figure < 0 || figure >= 24) throw FormatError("Reality: invalid figure lookup");
return positions_[size_t(figure)];
}
} // namespace bmh
+87
View File
@@ -0,0 +1,87 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <array>
#include <cstdint>
#include <utility>
#include "formats/le.hpp"
namespace bmh {
// RealityFieldScreen consumes positions chosen by the Reality simulation. This owned
// input is deliberately independent of GameState and both random generators.
struct RealityFigureMotion {
bool active = false;
int old_x = 0, old_y = 0, next_x = 0, next_y = 0;
uint8_t phase = 0;
bool operator==(const RealityFigureMotion&) const = default;
};
struct RealityMotionInput {
std::array<RealityFigureMotion, 24> figures{}; // 22 players, shadow, ball
bool ball_airborne = false;
bool numbers = true; // Source RealityMatch_FormatError_ExecutableField == 0
bool operator==(const RealityMotionInput&) const = default;
};
struct RealityMotionSprite {
int figure = 0, x = 0, y = 0, cell = 0, number = 0;
bool away_palette = false;
bool operator==(const RealityMotionSprite&) const = default;
};
struct RealityMotionFrame {
std::array<RealityMotionSprite, 24> sprites{};
size_t count = 0;
bool operator==(const RealityMotionFrame&) const = default;
};
struct RealityMotionResult {
std::array<RealityMotionFrame, 11> frames{};
std::array<uint8_t, 24> phases_after{};
bool operator==(const RealityMotionResult&) const = default;
};
// RealityDirection / Int7. Coordinates use the original 43 by 25 Reality grid.
int reality_direction(int x, int y);
std::pair<int, int> reality_project(const LeImage&, int x, int y);
RealityMotionResult reality_motion(const RealityMotionInput&, const LeImage&);
struct RealityPath {
std::array<std::pair<int, int>, 51> points{};
size_t count = 0;
bool operator==(const RealityPath&) const = default;
};
// RealityPath's integer line, including both endpoints. The goal helper uses the
// Source's three goal-mouth target rows (11, 12, 13).
RealityPath reality_path(int x, int y, int target_x, int target_y);
RealityPath reality_goal_path(int x, int y, int goal_x);
// Place. Each side has its own occupancy plane: opponents may share a cell,
// teammates may not. Ball placement records the previous cell without occupying
// either player plane. This is runtime scene state, not a Native save extension.
class RealityGrid {
public:
bool place(int figure, int x, int y, int side);
void clear(int x, int y, int side); // caller clears old occupancy before a move
void reset_occupancy(); // Source initialization preserves old figure/ball data
bool operator==(const RealityGrid&) const = default;
void stage_position(int figure, int x, int y); // afb0c/afb23 before occupancy is committed
uint8_t occupant(int x, int y, int side) const;
std::pair<int, int> position(int figure) const;
std::pair<int, int> ball() const { return ball_; }
std::pair<int, int> previous_ball() const { return previous_ball_; }
private:
std::array<std::array<uint8_t, 0x478>, 2> occupied_{};
std::array<std::pair<int, int>, 24> positions_{};
std::pair<int, int> ball_{}, previous_ball_{};
};
// Source scene globals persist across matchdays, but are not Native FBM data.
struct RealityResidue {
bool initialized = false, deflected = false;
uint8_t card_kind = 0;
int distance = 0;
std::array<uint8_t,5> cue_actors{};
RealityGrid grid;
bool operator==(const RealityResidue&) const = default;
};
} // namespace bmh
+166
View File
@@ -0,0 +1,166 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "game/reality_movement.hpp"
#include <algorithm>
#include <cstdlib>
namespace bmh {
namespace {
int source_short(int value) { return int(int16_t(value)); }
void validate(const GameState& state,const RealitySetup& scene,int figure,const RealityMoveContext& context) {
if (scene.attacking_side<0 || scene.attacking_side>1 || figure<0 || figure>=22 ||
!scene.motion.figures[size_t(figure)].active || context.goal_path.count<1 ||
context.goal_path.count>context.goal_path.points.size())
throw FormatError("Reality movement: invalid scene/player/path");
const int player=scene.players[size_t(figure)].player;
if (player<0 || size_t(player)>=state.players.size())
throw FormatError("Reality movement: missing Source player attributes");
}
int speed(const GameState& state,const RealitySetup& scene,int figure,WatcomRandom& rand) {
const auto& player=state.players[size_t(scene.players[size_t(figure)].player)];
const int ability=int((player.w35c>>14)&127)+int((player.w368>>3)&3)*10;
return ability<rand.range(0,130) ? 1 : 2;
}
std::pair<int,int> space(RealitySetup& scene,const LeImage& exe,int figure,int side,uint8_t flags,uint8_t mode,
const RealityMoveContext& context) {
const auto target=reality_seek_space(scene,exe,figure,side,flags,mode,context.goal_path);
if (target.found) scene.grid.stage_position(figure,target.x,target.y);
return scene.grid.position(figure);
}
void finish_move(RealitySetup& scene,int figure,int side,std::pair<int,int> start,std::pair<int,int> target,
int padding,RealityMoveResult& result,GameRandom& game) {
const auto path=reality_path(start.first,start.second,target.first,target.second);
const auto candidate=path.points[std::min(size_t(result.steps),path.count-1)];
// Source updates afb0c/afb23 BEFORE the movement-box/occupancy checks.
// A failed commit returns home from this candidate, not from the old cell.
scene.grid.stage_position(figure,candidate.first,candidate.second);
const auto& box=scene.players[size_t(figure)];
const bool within=candidate.first>=box.min_x-padding && candidate.first<=box.max_x+padding &&
candidate.second>=box.min_y-padding && candidate.second<=box.max_y+padding;
if ((result.score>=100 || within) && scene.grid.place(figure,candidate.first,candidate.second,side)) {
auto& motion=scene.motion.figures[size_t(figure)];motion.next_x=candidate.first;motion.next_y=candidate.second;
} else {
result.returned_to_box=true;
reality_return_to_box(scene,figure,side,uint8_t(result.steps),game);
}
}
} // namespace
RealityMoveContext reality_move_context(const RealitySetup& scene,const LeImage& exe) {
if (scene.attacking_side<0 || scene.attacking_side>1) throw FormatError("Reality movement: invalid attacking side");
const int side=scene.attacking_side;const auto [x,y]=scene.grid.ball();RealityMoveContext context;
context.goal_path=reality_goal_path(x,y,side ? 0 : 42);
context.attacking_nearby4=uint16_t(reality_nearby(scene,x,y,side,4,false));
context.attacking_area=uint8_t(reality_penalty_area(scene,exe,side));
context.attacking_nearby2=uint8_t(reality_nearby(scene,x,y,side,2,false));
context.defending_nearby3=uint16_t(reality_nearby(scene,x,y,1-side,3,false));
context.defending_nearby2_forward=uint8_t(reality_nearby(scene,x,y,1-side,2,true));
return context;
}
void reality_defensive_push(const RealitySetup& scene,RealityMoveContext& context,WatcomRandom& rand) {
if (scene.attacking_side<0 || scene.attacking_side>1) throw FormatError("Reality movement: invalid attacking side");
const auto count=context.goal_path.count;
const bool pushed=count<20 && count>6 && rand.range(0,8-int(context.defensive_push))==0 &&
scene.tactics[size_t(1-scene.attacking_side)][5]!=0;
context.defensive_push=pushed ? 10 : 0;
}
RealityMoveResult reality_move_attacker(const GameState& state,RealitySetup& scene,const LeImage& exe,int figure,
RealityMoveContext& context,WatcomRandom& rand,GameRandom& game) {
validate(state,scene,figure,context);const int side=figure/11;
if (side!=scene.attacking_side) throw FormatError("Reality movement: attacker on defending side");
const auto start=scene.grid.position(figure),ball=scene.grid.ball();RealityMoveResult result;std::pair<int,int> target;
if (figure%11==0) {
target={side*40+1,12};
if (std::abs(ball.first-start.first)<4 && std::abs(ball.second-start.second)<4) target=ball;
} else {
const int depth=42-std::abs(side*42-start.first);
const int distance=std::max(std::abs(ball.first-start.first),std::abs(ball.second-start.second));
const bool offside=reality_offside(scene,start.first);
result.steps=speed(state,scene,figure,rand);
result.score=!scene.grid.occupant(ball.first,ball.second,side) &&
(distance<3 || (distance<15 && !context.attacking_nearby2)) ?
100 : source_short(9-int(context.attacking_nearby4)*9);
target=ball;
if (!offside) {
int next_score=depth-int(context.attacking_area)*10+50;
if (depth<6) next_score=0;
if (source_short(result.score)<source_short(next_score)) {
if (depth<9 && context.attacking_area<3) target=context.goal_path.points[context.goal_path.count-1];
else {
target=space(scene,exe,figure,side,0x19,context.attacking_area,context);
if (target==start) { target=ball;next_score=100; }
}
result.score=next_score;
}
if (source_short(result.score)<100) {
int advanced=0;
for (int id=side*11;id<side*11+11;++id) {
const auto p=scene.grid.position(id);
if (scene.motion.figures[size_t(id)].active && p.first>8 && p.second<16) ++advanced;
}
next_score=int(context.attacking_nearby4)*4+(scene.tactics[size_t(side)][1]+4)*advanced;
if (context.goal_path.count>8 && source_short(result.score)<source_short(next_score)) {
target=space(scene,exe,figure,side,10,context.attacking_area,context);result.score=next_score;
}
}
} else { target={20,start.second};result.score=200; }
}
result.score=source_short(result.score);finish_move(scene,figure,side,start,target,0,result,game);
const auto end=scene.grid.position(figure);const int depth=42-std::abs(side*42-end.first);
// InitializeRealityReporter(figure,side,17) is an explicit caller-owned reporter boundary.
if (game.range(0,3)==0 && depth<15 && !reality_nearby(scene,end.first,end.second,1-side,3,false) &&
std::abs(end.first-ball.first)>2 && std::abs(end.second-ball.second)>2) result.reporter_code=17;
return result;
}
RealityMoveResult reality_move_defender(const GameState& state,RealitySetup& scene,const LeImage& exe,int figure,
RealityMoveContext& context,WatcomRandom& rand,GameRandom& game) {
validate(state,scene,figure,context);const int side=figure/11;
if (side==scene.attacking_side) throw FormatError("Reality movement: defender on attacking side");
const auto start=scene.grid.position(figure),ball=scene.grid.ball();RealityMoveResult result;
if (context.blocked_figure && context.blocked_figure-1==figure) {
if (!scene.grid.place(figure,start.first,start.second,side)) throw FormatError("Reality movement: uncleared blocked figure");
return result;
}
int distance=std::max(std::abs(ball.first-start.first),std::abs(ball.second-start.second)),padding=0;
std::pair<int,int> target=ball;
if (figure%11==0) {
const auto nearby=reality_nearby(scene,ball.first,ball.second,side,3,true);
if (!(distance<3 || (distance<rand.range(10,13) && !nearby &&
reality_line_occupants(scene,context.goal_path,side,false,rand).count<2)))
target=context.goal_path.points[context.goal_path.count-1];
result.score=100;
} else {
const uint8_t pressure=scene.tactics[size_t(side)][6];const int depth=std::abs(side*42-start.first);
if (!pressure || depth<18) result.steps=speed(state,scene,figure,rand);
const bool occupied=scene.grid.occupant(ball.first,ball.second,side)!=0;
if ((!pressure && depth>17) || occupied ||
(distance>2 && (context.defending_nearby2_forward || distance>3) &&
(distance>8 || context.defending_nearby3)))
result.score=source_short(18-(9-int(pressure)*6)*int(context.defending_nearby3));
else result.score=200;
if (result.score!=200) {
result.score=source_short(result.score+6-(2-int(pressure))*distance);
int next_score=depth+20;
if (depth<std::min(size_t(9),context.goal_path.count)) next_score=-100;
if (result.score<source_short(next_score)) {
const auto found=space(scene,exe,figure,side,0x20,1,context);
target=reality_on_path(context.goal_path,found.first,found.second) ? found : context.goal_path.points[context.goal_path.count-1];
result.score=source_short(next_score);
}
const auto support=reality_support(scene,start.first,start.second,1-side,int16_t(result.score),pressure);
if (support.found) { target={support.x,support.y};result.score=support.score; }
if (result.score<200) if (const auto marker=reality_marked_position(state,scene,figure)) { target=*marker;padding=5; }
}
if (result.score!=200 && context.defensive_push && std::abs(side*42-target.first)<std::abs(side*42-ball.first)) target.first=ball.first;
}
finish_move(scene,figure,side,start,target,padding,result,game);
if (figure%11==0)
context.keeper_player=(start.first<2 || start.first>40) && start.second>9 && start.second<15 ?
scene.players[size_t(figure)].player : 0xfff;
return result;
}
} // namespace bmh
+32
View File
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/reality_space.hpp"
namespace bmh {
// DecideRealityBall's per-iteration observations; no ball action is synthesized here.
struct RealityMoveContext {
RealityPath goal_path;
uint16_t attacking_nearby4 = 0, defending_nearby3 = 0;
uint8_t attacking_nearby2 = 0, attacking_area = 0, defending_nearby2_forward = 0;
uint8_t blocked_figure = 0, defensive_push = 0; // afb7c (one-based), afb87
int keeper_player = 0xfff; // RatingRuntimeField8, retained across non-keeper moves
};
RealityMoveContext reality_move_context(const RealitySetup&, const LeImage&);
// DecideRealityBall's first-defender branch, including its short-circuit draw order.
void reality_defensive_push(const RealitySetup&, RealityMoveContext&, WatcomRandom&);
struct RealityMoveResult {
int steps = 2, score = -100;
bool returned_to_box = false;
int reporter_code = 0; // InitializeRealityReporter code17 boundary; reporter RNG is NOT consumed here
};
// RealityMoveAttacker and RealityMoveAttacker2. Caller clears old occupancy as DecideRealityBall does.
// Positions/occupancy/next rendering coordinates and real movement RNG change.
// GameState is read-only. These are not yet called from MatchEngine/Main.
RealityMoveResult reality_move_attacker(const GameState&, RealitySetup&, const LeImage&, int figure,
RealityMoveContext&, WatcomRandom&, GameRandom&);
RealityMoveResult reality_move_defender(const GameState&, RealitySetup&, const LeImage&, int figure,
RealityMoveContext&, WatcomRandom&, GameRandom&);
} // namespace bmh
+165
View File
@@ -0,0 +1,165 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/reality_reporter.hpp"
#include <algorithm>
#include <cstdlib>
#include "game/messages.hpp"
namespace bmh {
namespace {
struct Node {
char token = 0;
int selector = 0, variants = 0;
std::string literal;
std::vector<std::vector<Node>> branches;
};
// Parse before evaluation: structural traversal cannot draw random numbers.
// The Source cursor skips entire unselected nested %x...#x expressions.
std::vector<Node> parse(std::string_view text,size_t& at,int depth) {
if(depth>32)throw FormatError("Reality reporter: template nesting too deep");
std::vector<Node> nodes;
while(at<text.size()&&text[at]!='#') {
Node n;
if(text[at]!='%') {
while(at<text.size()&&text[at]!='%'&&text[at]!='#')n.literal+=text[at++];
} else {
if(++at>=text.size())throw FormatError("Reality reporter: truncated token");
n.token=text[at++];
if(n.token=='x') {
if(at+2>text.size()||text[at]<'0'||text[at]>'9'||text[at+1]<'0'||text[at+1]>'9')
throw FormatError("Reality reporter: invalid selector digits");
n.selector=text[at]-'0';n.variants=text[at+1]-'0';at+=2;
for(;;) {
n.branches.push_back(parse(text,at,depth+1));
if(at>=text.size()||text[at++]!='#')throw FormatError("Reality reporter: missing branch terminator");
if(at<text.size()&&text[at]=='x'){++at;break;}
}
}
}
nodes.push_back(std::move(n));
}
return nodes;
}
std::string pool_name(const Bytes& pool,size_t offset) {
if(offset>=pool.size())throw FormatError("Reality reporter: missing referee name");
std::string out;for(;offset<pool.size()&&pool[offset];++offset)out+=char(pool[offset]);return out;
}
int player(const RealitySetup& scene,int one_based) {
if(one_based<1||one_based>22)throw FormatError("Reality reporter: missing selected figure");
return scene.players[size_t(one_based-1)].player;
}
std::string evaluate(const std::vector<Node>& nodes,const GameState& game,const RealitySetup& scene,
const LeImage& exe,const RealityReporterFrame& frame,const RealityReporterState& state,WatcomRandom& rand) {
std::string out;
for(const auto& node:nodes) {
if(!node.token)out+=node.literal;
else if(node.token=='x') {
const int index=node.selector+10*node.variants;
if(node.selector && index>=int(state.selectors.size()))throw FormatError("Reality reporter: selector outside Source context");
const int choice=node.selector?state.selectors[size_t(index)]:rand.range(1,node.variants);
const size_t branch=size_t(choice<2?0:choice-1);
// Source walks to #x without output when the selector exceeds the branches.
if(branch<node.branches.size())out+=evaluate(node.branches[branch],game,scene,exe,frame,state,rand);
} else if(node.token=='e')break;
else if(node.token=='a')out+=game.club_name(scene.teams[0]);
else if(node.token=='b')out+=game.club_name(scene.teams[1]);
else if(node.token=='c') {
if(state.current_player<0||state.current_player==0xfff)throw FormatError("Reality reporter: missing speaker");
out+=game.player_name(state.current_player);
} else if(node.token=='d') {
if(frame.receiver_player<0||frame.receiver_player==0xfff)throw FormatError("Reality reporter: missing receiver");
out+=game.player_name(frame.receiver_player);
} else if(node.token=='f')out+=game.player_name(player(scene,frame.line_selected[size_t(1-frame.player_side)]));
else if(node.token=='z')out+=game.player_name(player(scene,frame.opponent));
else if(node.token=='s') {
if(!frame.referee)out+=message_text(game,::bmh::layout::RealityReporter_Evaluate_TextPointer2);
else out+=message_text(game,::bmh::layout::RealityReporter_Evaluate_TextPointer)+pool_name(game.referee_names,le16(game.master_database_metadata,size_t(frame.referee)*2));
} else if(node.token=='0') {
int metres=(int(frame.distance_before)*25-12+rand.range(0,26))/10;
uint8_t value=uint8_t(metres);if(value>20)value=uint8_t((value/5)*5);
out+=format_number(game,value,1);
}
// All other Source percent tokens are consumed without output.
if(out.size()>=500)throw FormatError("Reality reporter: expanded text exceeds Source buffer");
}
return out;
}
} // namespace
RealityReporterState initialize_reality_reporter(const LeImage& exe) {
RealityReporterState state;
for(size_t i=0;i<state.selectors.size();++i)state.selectors[i]=exe.u8(::bmh::layout::RealityReporter_InitializeRealityReporter_RuntimeField+uint32_t(i));
return state;
}
std::string reality_reporter_text(const GameState& game,const RealitySetup& scene,const LeImage& exe,
const RealityReporterFrame& frame,const RealityReporterState& state,std::string_view text,WatcomRandom& rand) {
if(frame.player_side>1)
throw FormatError("Reality reporter: template needs its actual Source player side");
size_t at=0;const auto nodes=parse(text,at,0);
return evaluate(nodes,game,scene,exe,frame,state,rand);
}
RealityReporterResult report_reality(const GameState& game,const RealitySetup& scene,const LeImage& exe,
RealityReporterFrame& frame,RealityReporterState& state,int figure,int side,uint8_t code,WatcomRandom& rand) {
RealityReporterResult out;
if(figure==100){state.last_side=state.last_owner=state.last_player=state.last_action=-1;return out;}
if(figure<0||figure>=22||side<0||side>1||frame.player_side>1||code>21)
throw FormatError("Reality reporter: invalid figure/side/cue");
state.current_player=scene.players[size_t(figure)].player;
state.selectors[12]=frame.card_kind;
auto cue=[&](int value){out.codes.push_back(uint8_t(value));};
if(code)cue(code);
else {
const int area=reality_penalty_area(scene,exe,1-side,scene.grid.ball().first,scene.grid.ball().second);
const auto ball=scene.grid.ball(),old=scene.grid.previous_ball();
// InitializeRealityReporter uses signed chars for both differences; preserve byte wrapping.
const int dx=int8_t(std::abs(ball.first-old.first)),dy=int8_t(std::abs(ball.second-old.second));
if(dy<=dx&&!frame.incoming_bh)throw FormatError("Reality reporter: missing Source incoming BH");
const int high=dy>dx?dy:int(int8_t(*frame.incoming_bh));
// BL stays dx even when dy is smaller (verified at 69210..6926d).
const int low=dx;
state.selectors[2]=uint8_t(2-frame.airborne);
state.selectors[3]=uint8_t((high>2)+1+(high>9)*2);
state.selectors[4]=uint8_t(3-2*(low>=10&&dy<=4)+(dy>16));
state.selectors[5]=uint8_t(2-area);
state.selectors[6]=uint8_t(side==state.last_side?2-(frame.distance_before<frame.distance_after):2);
state.selectors[7]=uint8_t((frame.distance_after>6)+1);
state.selectors[8]=uint8_t((ball.first>42)+1+(ball.second<11||ball.second>13));
state.selectors[9]=frame.scene_status;
state.selectors[11]=uint8_t(2-int(frame.received));
if(low>7&&state.selectors[4]==3)state.selectors[4]=2;
if(frame.action==2&&frame.opponent)frame.action=uint8_t(frame.lost_duel?9:10);
if(frame.action==0&&frame.received&&frame.distance_before<6&&rand.range(0,1)!=0)frame.action=16;
if(!(frame.action!=0&&frame.action==state.last_action&&state.current_player==state.last_player)) {
if(state.last_owner!=-1&&state.current_player!=state.last_owner){cue(7);state.selectors[1]=2;state.last_player=state.current_player;}
state.selectors[1]=uint8_t(state.current_player==state.last_player&&state.selectors[1]!=1?1:2);
if(frame.action==0&&frame.distance_before>34)frame.action=8;
cue(frame.action);state.last_owner=state.current_player;
if(frame.action==0&&frame.intercepted)cue(13);
if(frame.action==1) {
state.last_owner=frame.receiver_player;
if(frame.blocked_attempt) {
if(!frame.inaccurate&&frame.line_selected[size_t(1-frame.player_side)])cue(6);
else if(frame.inaccurate&&rand.range(0,2)==0)cue(4);
}
if(!frame.inaccurate&&!frame.line_selected[size_t(1-frame.player_side)]&&frame.offside&&int(frame.distance_after)<int(frame.distance_before)-5)cue(5);
if(!frame.leading_run&&frame.distance_before<10)cue(15);
if(frame.distance_before<12) {
if(frame.receiver<0||frame.receiver>=22)throw FormatError("Reality reporter: missing pass target figure");
const auto target=scene.grid.position(frame.receiver);
const int enemy=scene.grid.occupant(target.first,target.second,1-side);
if(enemy){frame.opponent=uint8_t(enemy);cue(14);}
}
}
if(frame.scene_status)cue((frame.scene_status==3)+11);
}
}
if(code&&state.last_action==9){out.suppressed=true;return out;}
// %a/%b are fixed home/away afaf2/afaf4, independent of possession side.
for(uint8_t id:out.codes)out.text.push_back(reality_reporter_text(game,scene,exe,frame,state,exe.string_at_pointer(::bmh::layout::RealityReporter_FormatError_TextPointer+uint32_t(id)*4),rand));
state.last_action=frame.action;state.last_player=state.current_player;
if(frame.action==9){state.last_owner=player(scene,frame.opponent);state.last_player=state.last_owner;}
state.last_side=side;
return out;
}
} // namespace bmh
+44
View File
@@ -0,0 +1,44 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <string>
#include <string_view>
#include <vector>
#include "game/reality_space.hpp"
namespace bmh {
// Runtime locals/globals of InitializeRealityReporter. The scene owner supplies their actual
// values; this module neither advances the ball nor constructs a match result.
struct RealityReporterFrame {
uint8_t action = 3, opponent = 0, airborne = 0, scene_status = 0;
uint8_t distance_before = 0, distance_after = 0, referee = 0, player_side = 0;
bool lost_duel = false, received = false, inaccurate = false;
bool blocked_attempt = false, intercepted = false, offside = false, leading_run = false;
int receiver = -1, receiver_player = 0xfff;
std::array<uint8_t,2> line_selected{};
uint8_t card_kind = 0;
// InitializeRealityReporter leaves BH unchanged when dx>=dy. This is the caller's
// incoming register byte, not max(dx,dy); absence is an explicit boundary.
std::optional<uint8_t> incoming_bh;
};
struct RealityReporterState {
int last_side = -1, last_owner = -1, last_player = -1, last_action = -1;
int current_player = -1; // afaee, assigned even if the explicit cue is suppressed
std::array<uint8_t,13> selectors{}; // RealityReporter_InitializeRealityReporter_RuntimeField..MatchEngine_Minute_ExecutableField; reset keeps these unchanged
};
struct RealityReporterResult {
std::vector<uint8_t> codes;
std::vector<std::string> text; // Original single-byte text, ready for later layout
bool suppressed = false;
};
RealityReporterState initialize_reality_reporter(const LeImage&);
// RealityReporterText2/RealityReporterText: nested Original %xDD alternatives and entity tokens.
// Only chosen branches consume Watcom draws. No Game draw or Native write.
std::string reality_reporter_text(const GameState&,const RealitySetup&,const LeImage&,
const RealityReporterFrame&,const RealityReporterState&,std::string_view,WatcomRandom&);
// InitializeRealityReporter; figure100 resets the four history words only. code0 derives the
// normal cue sequence; codes1..21 request an explicit Source cue. May update
// action/opponent in the owned frame. Rendering must use the returned text.
RealityReporterResult report_reality(const GameState&,const RealitySetup&,const LeImage&,
RealityReporterFrame&,RealityReporterState&,int figure,int side,uint8_t code,WatcomRandom&);
} // namespace bmh
+179
View File
@@ -0,0 +1,179 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/reality_scene.hpp"
#include <algorithm>
#include <cstdlib>
#include "game/messages.hpp"
namespace bmh {
namespace {
bool goal_mouth(const RealityScene& scene,const LeImage& exe) {
const auto [x,y]=scene.setup.grid.ball();
return x==exe.u8(::bmh::layout::RealityScene_GoalMouth_RuntimeFieldUnsigned+uint32_t(scene.setup.attacking_side))&&y>=11&&y<=13;
}
void finish(RealityScene& scene,RealitySceneStop stop) {
scene.finished=true;
auto& out=scene.result;out.stop=stop;out.side=scene.setup.attacking_side;
out.return_flags=scene.return_flags;
if(stop!=RealitySceneStop::possession_ended&&!out.scene_status&&out.shooter_row!=0xfff)
out.return_flags|=1;
// RealityReporterPanel converts only a same-side assist; missing/cross-side stays fff.
if(out.shooter_row==0xfff||out.assistant_row==0xfff||out.shooter_row/11!=out.assistant_row/11)
out.assistant=out.assistant_row=0xfff;
else {
out.assistant=scene.setup.players.at(size_t(out.assistant_row)).player;
out.assistant_row%=11;
}
if(out.shooter_row!=0xfff) {
out.shooter=scene.setup.players.at(size_t(out.shooter_row)).player;
out.shooter_row%=11;
}
}
void prepare_report(RealityScene& scene,const RealityBallDecision& decision,const RealityBallOutcome& outcome) {
auto& frame=scene.reporter_frame;
frame.action=uint8_t(outcome.action);frame.opponent=decision.opponent_at_actor;
frame.airborne=scene.ball_history.airborne;frame.scene_status=uint8_t(outcome.scene_status);
frame.distance_before=uint8_t(decision.goal_distance);
frame.distance_after=uint8_t(42-std::abs(decision.side*42-scene.setup.grid.ball().first));
frame.player_side=uint8_t(decision.side);frame.lost_duel=outcome.lost_duel;
frame.received=outcome.received;frame.inaccurate=decision.inaccurate;
frame.blocked_attempt=decision.blocked_attempt;frame.intercepted=decision.intercepted;
frame.offside=decision.receiver_offside;frame.leading_run=decision.leading_run;
frame.receiver=decision.receiver;frame.receiver_player=decision.receiver_player;frame.line_selected=decision.line_selected;
// Verified 63e96: MOVZX EBX,byte(side), preserved by45bb5 and64d4d.
// Thus the normal ApplyRealityBall -> InitializeRealityReporter call enters with BH=0.
frame.incoming_bh=0;
}
}
void initialize_reality_scene(GameState& state,const std::array<int,2>& teams,int side,
const RealityFormations& positions,const LeImage& exe,const RealitySceneContext& context,
WatcomRandom& rand,GameRandom& game,RealityScene& scene) {
for(auto actor:context.retained_cue_actors)
if(actor>=22)throw FormatError("Reality scene: retained Source cue actor outside figures");
auto retained_setup=std::move(scene.setup);
scene={};scene.setup=std::move(retained_setup);scene.context=context;
initialize_reality(state,teams,side,positions,exe,rand,game,scene.setup);
scene.setup.motion.numbers=context.numbers;scene.setup.motion.ball_airborne=false;
scene.reporter=initialize_reality_reporter(exe);
scene.reporter_frame.referee=context.referee_index;scene.reporter_frame.card_kind=context.retained_card_kind;
scene.result.side=side;scene.result.deflected=context.retained_deflection;
scene.result.distance=context.retained_distance;
if(!scene.setup.ready){scene.result.scene_status=3;finish(scene,RealitySceneStop::unavailable);}
}
void exit_reality_scene_after_animation(RealityScene& scene) {
if (scene.finished || !scene.rounds) throw FormatError("Reality scene: exit outside post-animation boundary");
finish(scene,RealitySceneStop::user_exit);
}
RealitySceneTick advance_reality_scene(GameState& state,RealityScene& scene,const LeImage& exe,
WatcomRandom& rand,GameRandom& game,const RealityForcedEvent& forced_event,bool user_exit) {
if(scene.finished||!scene.setup.ready)throw FormatError("Reality scene: round requested after scene end");
RealitySceneTick tick;tick.round=scene.rounds;tick.side=scene.setup.attacking_side;
const auto done=[&](){tick.result=scene.result;tick.finished=scene.finished;return tick;};
if(goal_mouth(scene,exe)){finish(scene,RealitySceneStop::goal_mouth);return done();}
if(scene.result.restart){finish(scene,RealitySceneStop::boundary);return done();}
const int previous_side=scene.setup.attacking_side;
const auto [bx,by]=scene.setup.grid.ball();
for(int side=0;side<2;++side)
if(scene.setup.grid.occupant(bx,by,side)&&!scene.setup.grid.occupant(bx,by,1-side))
scene.setup.attacking_side=side;
const int side=scene.setup.attacking_side;tick.side=side;
if(scene.stagnation>3||previous_side!=side) {
if(scene.stagnation<4&&rand.range(0,1)) {
scene.return_flags^=0x80;
const int shift=int8_t(exe.u8(::bmh::layout::RealityScene_AdvanceRealityScene_RuntimeFieldUnsigned+uint32_t(side)));
for(auto& player:scene.setup.players) {
player.min_x=int16_t(player.min_x+shift);player.max_x=int16_t(player.max_x+shift);
}
scene.shot=false;scene.result.shot_attempted=false;
} else {
RealityReporterResult ended;
ended.text={message_text(state,::bmh::layout::RealityScene_AdvanceRealityScene_TextPointer)};tick.reports.push_back(std::move(ended));
finish(scene,RealitySceneStop::possession_ended);return done();
}
}
scene.reporter_frame.action=3;scene.reporter_frame.player_side=uint8_t(side);
uint8_t blocked=0;
int actor=-1;
if(!scene.first_round) {
// Source scans coordinate arrays0..21, not occupancy lookup/figure order.
for(int id=side*11;id<side*11+11;++id)
if(scene.setup.grid.position(id)==scene.setup.grid.ball()){actor=id;break;}
if(actor>=0) {
tick.ball_actor=actor;
const auto start=scene.setup.grid.position(actor);scene.setup.grid.clear(start.first,start.second,side);
const auto decision=decide_reality_ball(state,scene.setup,actor,scene.ball_history,scene.context.rating,rand);
std::vector<RealityFoulCue> cues;RealityBallOutcome outcome;auto effective=decision;
if(decision.boundary==RealityBallBoundary::dribble_or_duel) {
const auto dribble=continue_reality_dribble(state,scene.setup,exe,decision,scene.context.referee_profile,
scene.context.muted,rand,forced_event,scene.context.sound);
blocked=decision.opponent_at_actor;cues=dribble.cues;effective=dribble.ball;
if(dribble.card_kind)scene.context.retained_card_kind=scene.reporter_frame.card_kind=*dribble.card_kind;
outcome=apply_reality_dribble(state,scene.setup,dribble,scene.ball_history,scene.context.rating,
scene.context.referee_profile,rand,game);
} else outcome=apply_reality_ball(state,scene.setup,decision,scene.ball_history,scene.context.rating,
scene.context.referee_profile,rand,game);
scene.result.scene_status=uint8_t(outcome.scene_status);scene.result.restart=uint8_t(outcome.restart);
scene.result.shooter_row=outcome.shooter_row;scene.result.assistant_row=outcome.assistant_row;
scene.result.distance=decision.goal_distance;scene.result.deflected=decision.blocked_attempt;
scene.result.shot_attempted=scene.result.shot_attempted||outcome.shot_ready;scene.shot=outcome.shot_ready;scene.event_stop=outcome.event_stops_scene;
prepare_report(scene,effective,outcome);
if(outcome.needs_reporter) {
if(cues.empty())tick.reports.push_back(report_reality(state,scene.setup,exe,scene.reporter_frame,
scene.reporter,actor,side,0,rand));
else {
if(cues.size()>scene.context.retained_cue_actors.size())throw FormatError("Reality scene: too many Source foul cues");
for(size_t i=0;i<cues.size();++i) {
if(cues[i].actor>=0)scene.context.retained_cue_actors[i]=uint8_t(cues[i].actor);
tick.reports.push_back(report_reality(state,scene.setup,exe,scene.reporter_frame,scene.reporter,
scene.context.retained_cue_actors[i],side,uint8_t(cues[i].code),rand));
}
}
}
scene.stagnation=0;
}
}
if(actor<0)++scene.stagnation;
if(!scene.result.scene_status&&!goal_mouth(scene,exe)) {
auto context=reality_move_context(scene.setup,exe);
context.defensive_push=scene.defensive_push;context.blocked_figure=blocked;context.keeper_player=scene.result.keeper;
bool first_defender=true;
for(int id=side?21:0;id!=(side?-1:22);id+=side?-1:1) {
if(!scene.setup.motion.figures[size_t(id)].active)continue;
const int figure_side=id/11;
if(figure_side==side) {
if(scene.first_round||id==actor)continue;
const auto start=scene.setup.grid.position(id);scene.setup.grid.clear(start.first,start.second,figure_side);
const auto movement=reality_move_attacker(state,scene.setup,exe,id,context,rand,game);
tick.moved_figures.push_back(id);
if(movement.reporter_code)tick.reports.push_back(report_reality(state,scene.setup,exe,scene.reporter_frame,
scene.reporter,id,figure_side,uint8_t(movement.reporter_code),rand));
} else {
if(first_defender){reality_defensive_push(scene.setup,context,rand);first_defender=false;}
const auto start=scene.setup.grid.position(id);scene.setup.grid.clear(start.first,start.second,figure_side);
reality_move_defender(state,scene.setup,exe,id,context,rand,game);tick.moved_figures.push_back(id);
}
}
scene.defensive_push=context.defensive_push;scene.result.keeper=context.keeper_player;
}
scene.first_round=false;++scene.rounds;
if(!scene.event_stop) {
if (scene.return_flags < 2 && scene.context.sound) scene.context.sound(16); // RealityFieldScreen.
tick.motion=reality_motion(scene.setup.motion,exe);
const auto ball_phase=scene.setup.motion.figures[23].phase;
scene.setup.motion.figures[23]=scene.setup.motion.figures[22];scene.setup.motion.figures[23].phase=ball_phase;
for(size_t i=0;i<24;++i) {
auto& figure=scene.setup.motion.figures[i];figure.phase=tick.motion->phases_after[i];
if(i<23){figure.old_x=figure.next_x;figure.old_y=figure.next_y;}
}
}
if(scene.event_stop)finish(scene,RealitySceneStop::forced_event);
else if(user_exit)finish(scene,RealitySceneStop::user_exit);
else if(scene.shot)finish(scene,RealitySceneStop::shot);
else if(scene.result.scene_status||scene.result.restart)finish(scene,RealitySceneStop::boundary);
return done();
}
} // namespace bmh
+59
View File
@@ -0,0 +1,59 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/reality_duel.hpp"
#include "game/reality_movement.hpp"
#include "game/reality_reporter.hpp"
namespace bmh {
// Caller-owned persistent Source context. MatchEngine_Minute_ExecutableField2 is not cleared by ApplyRealityBall:
// code20 leaves its actor slot unchanged. Supply the retained five slots;
// carrying these between scenes is the eventual MatchEngine owner's job.
struct RealitySceneContext {
RatingContext rating;
uint8_t referee_index = 0, referee_profile = 0; // afb73 vs RefereeProperties[index]
bool muted = true, numbers = true;
std::array<uint8_t,5> retained_cue_actors{};
uint8_t retained_card_kind = 0;
bool retained_deflection = false; // MatchEngine_Minute_ExecutableField3 survives until the next ball actor
int retained_distance = 0; // MatchEngine_Minute_ExecutableField4 is also assigned only by a ball actor
RealitySound sound; // presentation observer, never serialized
};
enum class RealitySceneStop { none, unavailable, goal_mouth, possession_ended, shot, boundary, forced_event, user_exit };
struct RealitySceneResult {
RealitySceneStop stop = RealitySceneStop::none;
uint8_t return_flags = 0, scene_status = 0, restart = 0;
int side = 0, shooter = 0xfff, assistant = 0xfff;
int shooter_row = 0xfff, assistant_row = 0xfff, distance = 0, keeper = 0xfff;
bool deflected = false, shot_attempted = false; // MatchEngine_Minute_ExecutableField3 and bdb7b
};
struct RealityScene {
RealitySetup setup;
RealitySceneContext context;
RealityBallHistory ball_history;
RealityReporterState reporter;
RealityReporterFrame reporter_frame;
RealitySceneResult result;
uint8_t stagnation = 0, defensive_push = 0, return_flags = 0;
bool first_round = true, finished = false, shot = false, event_stop = false;
size_t rounds = 0;
};
struct RealitySceneTick {
size_t round = 0;
int side = 0, ball_actor = -1;
std::vector<int> moved_figures; // actual Source order, not a sorted view
std::vector<RealityReporterResult> reports; // one layout flush per call
std::optional<RealityMotionResult> motion; // omitted after a forced stop
RealitySceneResult result;
bool finished = false;
};
// RealityReporterPanel initialization and DecideRealityBall/RealityReporterPanel control flow. The real forced
// card callback runs at the existing Source boundary; any deferred change must
// be retained by that caller and settled after the returned scene finishes.
// MatchEngine calls this through the fixture-owned Reality adapter.
void initialize_reality_scene(GameState&,const std::array<int,2>&,int side,const RealityFormations&,
const LeImage&,const RealitySceneContext&,WatcomRandom&,GameRandom&,RealityScene&);
void exit_reality_scene_after_animation(RealityScene&);
RealitySceneTick advance_reality_scene(GameState&,RealityScene&,const LeImage&,WatcomRandom&,GameRandom&,
const RealityForcedEvent& forced_event = {},bool user_exit = false);
} // namespace bmh
+190
View File
@@ -0,0 +1,190 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/reality_setup.hpp"
#include <algorithm>
#include <optional>
namespace bmh {
namespace {
int manager(const GameState& state, int team) {
const int found = state.manager_of(team);
if (found >= 0) return found;
// FindManagerForClub's separate national-manager record is not in manager_teams.
if (!state.manager_teams.empty() && state.manager_teams[0] == kNoTeam &&
state.manager_records.size() >= 4*0xb0c+0x292 &&
le16(state.manager_records,4*0xb0c+0x290) == team) return 4;
return -1;
}
std::optional<std::pair<int,int>> marked_position(const GameState& state, const RealitySetup& setup, int figure) {
const int side = figure > 10, other = 1-side;
const int own_manager = manager(state,setup.teams[size_t(side)]);
const int other_manager = manager(state,setup.teams[size_t(other)]);
int target = 0xfff;
if (own_manager >= 0) {
target = le16(state.tactics,size_t(own_manager)*0x840+size_t(figure-side*11)*0x58+0x44);
for (int row = other*11; row < other*11+11; ++row)
if (setup.players[size_t(row)].player == target) { target = row;break; }
} else if (other_manager >= 0) {
for (int row = 0; row < 11; ++row)
if (le16(state.tactics,size_t(other_manager)*0x840+size_t(row)*0x58+0x46) ==
setup.players[size_t(figure)].player) { target = other*11+row;break; }
}
// RealityMarkedPosition also tests the unchanged low numeric target after a failed lookup.
if (target < 24 && setup.motion.figures[size_t(target)].active) {
if (target == 23) return std::pair{setup.motion.figures[23].next_x,setup.motion.figures[23].next_y};
return setup.grid.position(target);
}
if (target >= 24 && target < 34)
throw FormatError("Reality setup: legacy marker addresses an untracked Source figure");
return std::nullopt;
}
void validate(const GameState& state, const std::array<int,2>& teams, int side, const RealityFormations& positions) {
if (side < 0 || side > 1 || teams[0] == teams[1]) throw FormatError("Reality setup: invalid fixture");
for (int s = 0; s < 2; ++s) {
const int team = teams[size_t(s)];
if (team < 0) throw FormatError("Reality setup: invalid team");
const auto range = squad_range(team);
if (range.first+range.count > state.squad_slots.size() || range.count < 11)
throw FormatError("Reality setup: truncated squad");
const int m = manager(state,team);
if (m >= 0 && (state.manager_records.size() < size_t(m)*0xb0c+0xd9 ||
state.tactics.size() < size_t(m+1)*0x840))
throw FormatError("Reality setup: truncated manager/board");
for (const auto& p : positions[size_t(s)])
if (p.first < 0 || p.first > 30 || p.second < 0 || p.second > 8)
throw FormatError("Reality setup: prepared formation outside supported Source grid");
for (size_t row = 0; row < 11; ++row) {
const auto slot = state.squad_slots[range.first+row];
if (!(slot & kSlotInLineup)) continue;
const size_t player = slot & 0xfff;
if (player == 0xfff || player >= state.players.size() || player >= state.player_cards.size())
throw FormatError("Reality setup: invalid starting player");
if (m >= 0) {
const size_t board = size_t(m)*0x840+row*0x58;
if (state.tactics[board+2] > 38 || state.tactics[board+3] > 99 || state.tactics[board+4] > 99)
throw FormatError("Reality setup: unsupported player movement limits");
}
}
}
}
} // namespace
std::optional<std::pair<int,int>> reality_marked_position(const GameState& state, const RealitySetup& setup, int figure) {
if (figure < 0 || figure >= 22) throw FormatError("Reality: invalid marked player");
for (int side=0;side<2;++side) {
const int m=manager(state,setup.teams[size_t(side)]);
if (m>=0 && state.tactics.size()<size_t(m+1)*0x840)
throw FormatError("Reality: truncated marking board");
}
return marked_position(state,setup,figure);
}
RealityFormations reality_formations(const GameState& state, const std::array<int,2>& teams) {
RealityFormations result{};
for (int side = 0; side < 2; ++side) for (int row = 0; row < 11; ++row) {
const int m = manager(state,teams[size_t(side)]);
if (m >= 0) {
const size_t at = size_t(m)*0x840+size_t(row)*0x58;
result[size_t(side)][size_t(row)] = {int(int8_t(state.tactics.at(at+0x41))),int(int8_t(state.tactics.at(at+0x42)))};
} else {
int x = 0,y = 0;state.formation_position(teams[size_t(side)],row,x,y);
result[size_t(side)][size_t(row)] = {x,y};
}
}
return result;
}
void initialize_reality(GameState& state, const std::array<int,2>& teams, int attacking_side,
const RealityFormations& positions, const LeImage& exe, WatcomRandom& rand, GameRandom& game, RealitySetup& setup) {
validate(state,teams,attacking_side,positions);
setup.ready = false;setup.teams = teams;setup.attacking_side = attacking_side;
for (int side = 0; side < 2; ++side) {
const int m = manager(state,teams[size_t(side)]);
for (int option = 0; option < 7; ++option)
setup.tactics[size_t(side)][size_t(option)] = uint8_t(m < 0 ?
rand.range(0,exe.u8(::bmh::layout::RealitySetup_InitializeReality_RuntimeFieldUnsigned+uint32_t(option))) :
state.manager_records.at(size_t(m)*0xb0c+0xd2+size_t(option)));
}
setup.grid.reset_occupancy(); // SizeT2 clears only the two occupancy planes.
for (int pass = 0; pass < 2; ++pass) {
const int side = pass ^ attacking_side, team = teams[size_t(side)], m = manager(state,team);
const auto range = squad_range(team);
std::array<std::pair<int,int>,5> candidates{};size_t candidates_count = 0, formation_cursor = 0;
for (int row = 0; row < 11; ++row) {
const int figure = side*11+row;auto& info = setup.players[size_t(figure)];
auto& motion = setup.motion.figures[size_t(figure)];
motion.active = false;info.player = 0;
const uint16_t slot = state.squad_slots.at(range.first+size_t(row));
if (!(slot & kSlotInLineup)) continue;
// Source advances the prepared-formation cursor only for active rows.
const auto formation = positions[size_t(side)].at(formation_cursor++);
int x = int(int8_t(formation.first*14/10)), y = int(uint8_t(12-(4-formation.second)*25/10));
if (x) x = std::max(1,int(int8_t(x+(side == attacking_side ? setup.tactics[size_t(side)][0]*2+4 : setup.tactics[size_t(side)][0]-2))));
x = std::min(x,27);
if (side) { x = 42-x;y = 24-y; }
info.center_x = x;info.center_y = y;
const size_t board = m >= 0 ? size_t(m)*0x840+size_t(row)*0x58 : 0;
if (m < 0) {
info.min_x = x-4;info.max_x = x+4;info.min_y = y-2;info.max_y = y+2;
} else {
const int bias = state.tactics[board+2];
const int left = side ? bias : 38-bias, right = side ? 38-bias : bias;
info.min_x = x-(int(state.tactics[board+3])+19+left)*42/235;
info.max_x = x+(int(state.tactics[board+3])+19+right)*42/235;
const int vertical = (int(state.tactics[board+4])*2/3+5)*25/117;
info.min_y = y-vertical;info.max_y = y+vertical;
}
if (row && (info.max_x < 2 || info.min_x > 40 || info.max_y < 1 || info.min_y > 23))
throw FormatError("Reality setup: movement box cannot reach the Source pitch");
for (int tries = 0; tries < 30; ++tries) {
if (row) {
do { x = int(int8_t(rand.range(info.min_x,info.max_x))); } while (x < 2 || x > 40);
do { y = int(int8_t(rand.range(info.min_y,info.max_y))); } while (y < 1 || y > 23);
}
if (!setup.grid.occupant(x,y,side)) break;
}
if (m >= 0) {
int increment = setup.tactics[size_t(attacking_side)][6] != 0;
const int distance = int(int8_t(std::abs(x-info.center_x)+std::abs(y-info.center_y)));
if (distance > 6 && rand.range(0,distance) > 6) ++increment;
if (increment) state.tactics[board+0xf] = uint8_t(std::clamp(int(int8_t(state.tactics[board+0xf]))+increment,0,99));
}
if (side == attacking_side && x > 10 && x < 30 && candidates_count < candidates.size())
candidates[candidates_count++] = {x,y};
info.player = slot & 0xfff;info.squad_slot = int(range.first)+row;
info.card_value = state.player_cards.at(size_t(info.player)) & 31;
if (pass) if (const auto marker = marked_position(state,setup,figure)) { x = marker->first;y = marker->second; }
while (!setup.grid.place(figure,x,y,side)) {
const int next_x = int(int8_t(rand.range(x-1,x+1)));
const int next_y = int(int8_t(rand.range(y-1,y+1)));
x = std::clamp(next_x,0,42);
y = std::max(next_y,0);
// FormatError4's y>24 branch writes the packed x byte, leaving y
// outside the playable grid. Do not silently normalize this
// legacy spare-row/memory case into a different simulation.
if (y > 24)
throw FormatError("Reality setup: legacy collision enters an unsupported spare row");
}
motion.active = true;motion.old_x = motion.next_x = x;motion.old_y = motion.next_y = y;
}
if (candidates_count) {
const auto ball = candidates[size_t(rand.range(1,int(candidates_count))-1)];
setup.grid.place(22,ball.first,ball.second,2);
setup.motion.figures[22] = {true,ball.first,ball.second,ball.first,ball.second,0};
} else if (side == attacking_side) return;
}
// RealityReporterPanel draws all 24 initial phases only after a successful FormatError4.
for (int figure = 0; figure < 24; ++figure) {
const int pose = figure < 22 ? (figure > 10 ? 7 : 0) : figure-14;
setup.motion.figures[size_t(figure)].phase = uint8_t(game.range(0,exe.u8(::bmh::layout::RealityMotion_FormatError_RuntimeField7Unsigned+uint32_t(pose))-1));
}
setup.motion.figures[23].active = setup.motion.figures[22].active;
setup.motion.ball_airborne = false;
setup.motion.numbers = (state.memory.has(::bmh::layout::RealityMatch_FormatError_ExecutableField) ? state.memory.u8(::bmh::layout::RealityMatch_FormatError_ExecutableField) : exe.u8(::bmh::layout::RealityMatch_FormatError_ExecutableField)) == 0;
setup.ready = true;
}
} // namespace bmh
+37
View File
@@ -0,0 +1,37 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/reality_motion.hpp"
#include "game/state.hpp"
#include <optional>
namespace bmh {
using RealityFormations = std::array<std::array<std::pair<int,int>,11>,2>;
struct RealityPlacement {
int player = 0, squad_slot = -1, card_value = 0;
int center_x = 0, center_y = 0;
int min_x = 0, max_x = 0, min_y = 0, max_y = 0;
};
struct RealitySetup {
RealityGrid grid;
RealityMotionInput motion;
std::array<RealityPlacement,22> players{};
std::array<std::array<uint8_t,7>,2> tactics{};
std::array<int,2> teams{};
int attacking_side = 0;
bool ready = false;
};
// RealityMarkedPosition, shared by initialization and subsequent defensive movement.
std::optional<std::pair<int,int>> reality_marked_position(const GameState&, const RealitySetup&, int figure);
// Int2's interleaved prepared positions, supplied separately to the scene.
RealityFormations reality_formations(const GameState&, const std::array<int,2>& teams);
// RealityReporterPanel profile preparation + FormatError4 + initial sprite phases. This is a
// simulation operation: it consumes the real RNGs and can update board fatigue.
// It is not called by a renderer and is not yet connected to MatchEngine::side.
void initialize_reality(GameState&, const std::array<int,2>& teams, int attacking_side,
const RealityFormations&, const LeImage&, WatcomRandom&, GameRandom&, RealitySetup&);
} // namespace bmh
+167
View File
@@ -0,0 +1,167 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/reality_space.hpp"
#include <algorithm>
#include <cstdlib>
namespace bmh {
namespace {
void side_ok(int side) {
if (side < 0 || side > 1) throw FormatError("Reality space: invalid side");
}
void path_ok(const RealityPath& path) {
if (path.count > path.points.size()) throw FormatError("Reality space: truncated path");
for (size_t i = 0; i < path.count; ++i) {
const auto [x,y] = path.points[i];
if (x < 0 || x > 42 || y < 0 || y > 24)
throw FormatError("Reality space: path outside playable grid");
}
}
bool playable(int x,int y) { return x >= 0 && x <= 42 && y >= 0 && y <= 24; }
// RealityPath also receives movement-box centers outside the pitch. Unlike
// occupancy/projection, its signed-byte line does not clip those endpoints.
RealityPath box_path(int x,int y,int target_x,int target_y) {
const int ax=std::abs(target_x-x),ay=std::abs(target_y-y),length=std::max(ax,ay);
if (target_x < -128 || target_x > 127 || target_y < -128 || target_y > 127 || length > 127)
throw FormatError("Reality space: unsupported signed-byte box center");
RealityPath path;const int sx=length ? ax*100/length : 0,sy=length ? ay*100/length : 0;
const int dx=target_x<x ? -1 : 1,dy=target_y<y ? -1 : 1;int ex=0,ey=0;
while (x!=target_x || y!=target_y) {
path.points[path.count++]={x,y};
if (path.count>49) break;
if (x!=target_x && (ex+=sx)>=100-sx) { ex-=100;x+=dx; }
if (y!=target_y && (ey+=sy)>=100-sy) { ey-=100;y+=dy; }
}
path.points[path.count++]={x,y};return path;
}
} // namespace
bool reality_on_path(const RealityPath& path,int x,int y) {
path_ok(path);
return std::find(path.points.begin(),path.points.begin()+path.count,std::pair{x,y})!=path.points.begin()+path.count;
}
bool reality_offside(const RealitySetup& scene,int x) {
const int side=scene.attacking_side;side_ok(side);
const int ball_x=scene.grid.ball().first;
if ((side==1 && (x>20 || x>ball_x)) || (side==0 && (x<20 || x<ball_x))) return false;
int defenders=0;
for (int id=(1-side)*11;id<(1-side)*11+11;++id) {
if (!scene.motion.figures[size_t(id)].active) continue;
const int defender_x=scene.grid.position(id).first;
if ((side==0 && x<defender_x) || (side==1 && defender_x<x)) ++defenders;
if (defenders==2) return false;
}
return true;
}
int reality_nearby(const RealitySetup& scene,int x,int y,int side,int radius,bool forward) {
side_ok(side);
if (radius<0 || radius>255) throw FormatError("Reality space: invalid neighborhood radius");
const int left=forward && side==1 ? 0 : radius,right=forward && side==0 ? 0 : radius;
int count=0;
// RealityPenaltyArea deliberately counts all eleven coordinate slots, including
// inactive/stale ones; neither occupancy nor active flags are consulted.
for (int id=side*11;id<side*11+11;++id) {
const auto [px,py]=scene.grid.position(id);
if (std::abs(py-y)<=radius && px-x>=-left && px-x<=right) ++count;
}
return count;
}
int reality_penalty_area(const RealitySetup& scene,const LeImage& exe,int side,int x,int y) {
side_ok(side);
const int min_x=exe.u8(::bmh::layout::RealitySpace_RealityPenaltyArea_RuntimeField),max_x=exe.u8(::bmh::layout::RealitySpace_RealityPenaltyArea_RuntimeField2),min_y=exe.u8(::bmh::layout::RealitySpace_RealityPenaltyArea_RuntimeField3),max_y=exe.u8(::bmh::layout::RealitySpace_RealityPenaltyArea_RuntimeField4);
if (x!=-1) return min_x<=x && x<=max_x && min_y<=y && y<=max_y;
// Source only offsets the scan; the point-membership branch above uses
// the unmirrored literal bounds even for side1.
const int offset=side ? 30 : 0;
if (!playable(min_x+offset,min_y) || !playable(max_x+offset,max_y))
throw FormatError("Reality space: invalid Source penalty-area table");
int count=0;
for (int px=min_x+offset;px<=max_x+offset;++px)
for (int py=min_y;py<=max_y;++py) if (scene.grid.occupant(px,py,side)) ++count;
return count;
}
RealityLineOccupants reality_line_occupants(const RealitySetup& scene,const RealityPath& path,int side,bool select,WatcomRandom& rand) {
side_ok(side);path_ok(path);RealityLineOccupants result;
for (size_t i=0;i+1<path.count;++i) {
const auto [x,y]=path.points[i];const auto occupant=scene.grid.occupant(x,y,side);
if (!occupant) continue;
if (select && (!result.selected || rand.range(0,1)!=0)) result.selected=occupant;
++result.count;
}
return result;
}
RealitySpaceTarget reality_seek_space(const RealitySetup& scene,const LeImage& exe,int figure,int side,
uint8_t flags,uint8_t mode,const RealityPath& goal_path) {
side_ok(side);side_ok(scene.attacking_side);path_ok(goal_path);
if (figure<0 || figure>=22) throw FormatError("Reality space: invalid player");
const auto [x,y]=scene.grid.position(figure);
int left=2,right=3;
RealityPath player_goal;
if (flags&0x10) {
if (!goal_path.count) throw FormatError("Reality space: missing Source goal path");
const auto target=goal_path.points[goal_path.count-1];
player_goal=reality_path(x,y,target.first,target.second);
if (!(flags&8)) { if (side==0) left=0;else right=1; }
}
RealitySpaceTarget result;int best=-100;
for (int px=x-left;px<x+right;++px) for (int py=y-2;py<y+3;++py) {
if (!playable(px,py) || scene.grid.occupant(px,py,side)) continue;
int score=std::abs(scene.attacking_side*42-px)*2+(py>=5 && py<=19);
if (py==y) score+=2;
if (flags) {
if ((flags&8) && reality_offside(scene,px)) continue;
if (!(flags&0x20)) {
if (scene.grid.occupant(px,py,1-side)) continue;
score+=10-3*reality_nearby(scene,px,py,1-side,2,false);
}
score+=20-4*reality_nearby(scene,px,py,side,3,false);
if ((flags&0x10) && px!=x && mode<4)
score+=10*reality_on_path(player_goal,px,py)+15*reality_penalty_area(scene,exe,1-side,px,py);
}
if (flags&2) score+=std::abs(12-py)*(scene.tactics[size_t(side)][1]+4);
if (flags&0x20) score+=20*reality_on_path(goal_path,px,py);
const int source_score=int(int16_t(score));
if (source_score>best) { best=source_score;result={true,px,py,source_score,-1}; }
}
return result;
}
RealitySpaceTarget reality_support(const RealitySetup& scene,int x,int y,int side,int16_t minimum_score,uint8_t pressure) {
side_ok(side);RealitySpaceTarget result;int best=minimum_score;
for (int px=x-4;px<x+5;++px) for (int py=y-4;py<y+5;++py) {
if (!playable(px,py)) continue;
const int occupant=scene.grid.occupant(px,py,side);
if (!occupant || scene.grid.occupant(px,py,1-side)) continue;
int depth=std::abs(side*42-px);if (depth>25) depth+=10;
int score=depth+40;
if (!pressure) score+=depth;else if (depth>38) score=depth+120;
score-=2*std::max(std::abs(x-px),std::abs(y-py));
if (scene.grid.ball()==std::pair{px,py}) score+=32;
if (score>best) { best=score;result={true,px,py,score,occupant-1}; }
}
return result;
}
void reality_return_to_box(RealitySetup& scene,int figure,int side,uint8_t steps,GameRandom& game) {
side_ok(side);
if (figure<0 || figure>=22) throw FormatError("Reality space: invalid player");
const auto& box=scene.players[size_t(figure)];const auto old=scene.grid.position(figure);
const int cx=int(int8_t((box.min_x+box.max_x)/2)),cy=int(int8_t((box.min_y+box.max_y)/2));
const auto path=box_path(old.first,old.second,cx,cy);
auto [x,y]=path.points[std::min(size_t(steps),path.count-1)];
while (!scene.grid.place(figure,x,y,side)) {
const int next_x=int(int8_t(x+game.range(0,2)-1));
const int next_y=int(int8_t(y+game.range(0,2)-1));
x=std::clamp(next_x,0,42);y=std::clamp(next_y,0,24);
}
auto& motion=scene.motion.figures[size_t(figure)];motion.next_x=x;motion.next_y=y;
}
} // namespace bmh
+31
View File
@@ -0,0 +1,31 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/reality_setup.hpp"
namespace bmh {
// Source spatial decisions, still independent of the unfinished Reality loop.
bool reality_on_path(const RealityPath&, int x, int y); // RealityOffside
bool reality_offside(const RealitySetup&, int x); // RealityNearby, current attacking side
int reality_nearby(const RealitySetup&, int x, int y, int side, int radius, bool forward); // RealityPenaltyArea
int reality_penalty_area(const RealitySetup&, const LeImage&, int side, int x = -1, int y = -1); // RealityLineOccupants2
struct RealityLineOccupants { int count = 0; uint8_t selected = 0; };
// RealityLineOccupants excludes the terminal cell; sampling uses Watcom, not GameRandom.
RealityLineOccupants reality_line_occupants(const RealitySetup&, const RealityPath&, int side,
bool select, WatcomRandom&);
struct RealitySpaceTarget {
bool found = false;
int x = 0, y = 0, score = 0, figure = -1;
};
// RealitySeekSpace: caller supplies the existing ball-to-goal path, flags and mode.
RealitySpaceTarget reality_seek_space(const RealitySetup&, const LeImage&, int figure, int side,
uint8_t flags, uint8_t mode, const RealityPath& goal_path);
// RealitySupport: best unopposed occupied support cell within the Source 9x9 scan.
RealitySpaceTarget reality_support(const RealitySetup&, int x, int y, int side,
int16_t minimum_score, uint8_t pressure);
// RealityReturnToBox. The Source caller must clear the figure's old occupancy first.
// Updates runtime placement/next position and consumes Game RNG only on collision.
void reality_return_to_box(RealitySetup&, int figure, int side, uint8_t steps, GameRandom&);
} // namespace bmh
+243
View File
@@ -0,0 +1,243 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/reschedule.hpp"
#include <algorithm>
#include "game/matchday_setup.hpp"
#include "game/schedule.hpp"
#include "game/table.hpp"
namespace bmh {
namespace {
constexpr uint32_t kCalendar = ::bmh::layout::CompetitionCalendar; // u16 per season day
constexpr int kCalendarDays = 0x16e; // CalendarCell copies 0x16e words
constexpr uint32_t kPostponed = ::bmh::layout::Postponed; // 40 entries: u16 day, round, league, match
constexpr int kPostponedEntries = 0x28;
constexpr uint32_t kFriendlyTeams = ::bmh::layout::FriendlyTeams; // friendly plan: team pairs
constexpr uint32_t kFriendlyDays = ::bmh::layout::FriendlyDays; // friendly plan: days, 30 entries
constexpr int kFriendlyEntries = 30;
// MatchdaySetupRuntimeField3 / MatchdaySetupRuntimeField4: first and last day of the winter break.
constexpr int kWinterBreakFirst = 0x96, kWinterBreakLast = 0xc8;
// RescheduleLeagueMatch accepts replay days up to 0x11e; the draw loop wants the day after the
// target inside 0x15 .. 0x11e.
constexpr int kLastReplayDay = 0x11e, kFirstDayAfter = 0x15;
constexpr uint8_t kRescheduledMark = 0xce; // param_5 = -0x32
constexpr size_t kRecordSize = 0xb0c;
constexpr size_t kFloodlights = 0x0e; // manager record byte (RescheduleRuntimeField)
// LeagueCalendarBits: calendar bit of a league (the two leagues 2 and 3 share bit 2, the four
// leagues of 12 clubs bit 4; compare kGroupLeague in matchday_setup.cpp).
// (kLeagueBit: schedule.hpp, set from the groups of the loaded game; 0xff = not played)
size_t result_at(int league, int round, int match) { return size_t(match) + size_t(round) * 10 + size_t(league) * 0x17c; }
bool memory_ok(const GameState& g) {
return g.memory.has(kCalendar + kCalendarDays * 2 - 1) &&
g.memory.has(kPostponed + kPostponedEntries * 6 - 1) && g.memory.has(kFriendlyDays + kFriendlyEntries * 2 - 1) &&
g.memory.has(kFriendlyTeams + kFriendlyEntries * 4 - 1);
}
// The club of a human manager in league play, or -1.
int manager_team(const GameState& g, int manager) {
if (manager < 0 || size_t(manager) >= g.manager_teams.size()) return -1;
const int team = g.manager_teams[size_t(manager)];
if (team < 0 || team_league(team) >= kLeagueCount) return -1;
return team;
}
std::vector<Fixture> round_fixtures(int league, int round) {
return generate_fixtures(league_table_teams(league), round + 1, league_matchdays(league) / 2, league_first_team(league));
}
// DayConflict(team, other, word, day): 1 when `day` (calendar word `word` of the screen's
// copy) cannot take a match of `team`/`other`: the word is taken (anything but 0, 0x4001 or
// a word marked eligible with bit 15) or the friendly plan already has a match of one of the
// teams - or of the national team - on that day.
bool day_conflict(const GameState& g, int team, int other, uint16_t word, int day) {
if (word != 0 && word != 0x4001 && (word & 0x8000) == 0) return true;
for (int i = 0; i < kFriendlyEntries; i++) {
if (g.memory.u16(kFriendlyDays + uint32_t(i) * 2) != uint16_t(day)) continue;
for (int side = 0; side < 2; side++) {
const int t = int16_t(g.memory.u16(kFriendlyTeams + uint32_t(i) * 4 + uint32_t(side) * 2));
if (t == kNoTeam || t == team || t == other) return true;
}
}
return false;
}
// RescheduleTargetDays(day, team, league): entry + 1 of a replay of `team` in `league` on `day`, or 0
// (the last such entry, as the original keeps looking).
int team_replay_on(const GameState& g, int day, int team, int league) {
int found = 0;
for (int e = 0; e < kPostponedEntries; e++) {
const uint32_t at = kPostponed + uint32_t(e) * 6;
if (g.memory.u16(at) != uint16_t(day) || g.memory.u8(at + 3) != league) continue;
const Fixture f = round_fixtures(league, g.memory.u8(at + 2)).at(g.memory.u8(at + 4));
if (f.home == team || f.away == team) found = e + 1;
}
return found;
}
// The draw loop of CalendarCell in mode 2 on a copy of the calendar: a future day is marked
// (bit 15) when it is free (0, 0x4001 or a calendar event 0x1c0), neither it nor its two
// neighbours conflict for the club (the neighbours before it may already be marked), the
// day after it lies in 0x15 .. 0x11e and it is not in the winter break. The national team
// (manager 0 coaching team 0x165) also checks the club of the Bundestrainer, CupDraw_FormatError_RuntimeField3.
std::vector<uint16_t> marked_calendar(const GameState& g, int team) {
std::vector<uint16_t> cal(kCalendarDays);
for (int d = 0; d < kCalendarDays; d++) cal[size_t(d)] = g.memory.u16(kCalendar + uint32_t(d) * 2);
// DaysIntoSeason, the day of the season; its saved copy in g.memory is only the load day
const int today = g.season_day();
const bool national = !g.manager_teams.empty() && g.manager_teams[0] == kNoTeam && g.memory.has(::bmh::layout::DeskActions_NationalOpponentManager_RuntimeField);
for (int d = today + 1; d < kCalendarDays; d++) {
const uint16_t word = cal[size_t(d)];
if (word != 0 && word != 0x4001 && (word & 0x1c0) == 0) continue;
bool ok = true;
for (int i = std::max(0, d - 1); i <= std::min(kCalendarDays - 1, d + 1); i++) {
if (day_conflict(g, team, -1, cal[size_t(i)], i)) ok = false;
if (national && day_conflict(g, int16_t(g.memory.u16(::bmh::layout::CupDraw_FormatError_RuntimeField3)), -1, cal[size_t(i)], i)) ok = false;
}
if (d + 1 > kLastReplayDay || d + 1 < kFirstDayAfter) ok = false;
if (d >= kWinterBreakFirst && d <= kWinterBreakLast) ok = false;
if (team == kNoTeam && (word & 0x1c0) != 0) ok = false;
if (ok) cal[size_t(d)] |= 0x8000;
}
return cal;
}
} // namespace
std::vector<LeagueMatchRef> reschedulable_matches(const GameState& g, int manager) {
std::vector<LeagueMatchRef> out;
const int team = manager_team(g, manager);
if (team < 0 || !memory_ok(g)) return out;
const int league = team_league(team);
// The screen only reacts to the calendar bit of the club's league for bits 0-3
// (local_34 == bit); CalendarCell derives local_34 as league - (league > 2).
const int screen_bit = league > 2 ? league - 1 : league;
if (screen_bit > 3 || kLeagueBit[league] != screen_bit) return out;
// DaysIntoSeason, the day of the season; its saved copy in g.memory is only the load day
const int today = g.season_day();
const int matchdays = league_matchdays(league);
int round = -1;
for (int day = 0; day < kCalendarDays; day++) {
const uint32_t comps = day_competitions(g, g.memory.u16(kCalendar + uint32_t(day) * 2));
if (kLeagueBit[league] > 7 || !((comps >> kLeagueBit[league]) & 1)) continue;
++round; // local_58 - 1: the league days up to this one
if (day <= today || round == 0 || round + 2 >= matchdays) continue;
const std::vector<Fixture> fixtures = round_fixtures(league, round);
for (size_t m = 0; m < fixtures.size(); m++) {
const Fixture& f = fixtures[m];
if (f.home != team && f.away != team) continue;
// the screen picks the club's match of the day; only a home match can be moved
if (f.home == team && g.results.at(result_at(league, round, int(m))) == kNotPlayed)
out.push_back({day, round, league, int(m), f.home, f.away});
break;
}
}
return out;
}
std::vector<int> reschedule_target_days(const GameState& g, int manager, const LeagueMatchRef& match) {
std::vector<int> out;
const int team = manager_team(g, manager);
if (team < 0 || !memory_ok(g)) return out;
const std::vector<LeagueMatchRef> movable = reschedulable_matches(g, manager);
if (std::none_of(movable.begin(), movable.end(), [&](const LeagueMatchRef& m) {
return m.day == match.day && m.round == match.round && m.league == match.league && m.match == match.match;
}))
return out;
std::vector<uint16_t> cal = marked_calendar(g, team);
// floodlights: the day before the matchday (the Friday) is offered as well
if ((size_t(manager) + 1) * kRecordSize <= g.manager_records.size() &&
g.manager_records[size_t(manager) * kRecordSize + kFloodlights] != 0 && match.day > 0)
cal[size_t(match.day - 1)] |= 0x8000;
for (int d = 0; d < kCalendarDays; d++)
if ((cal[size_t(d)] & 0x8000) && d != match.day && d <= kLastReplayDay && team_replay_on(g, d, team, match.league) == 0)
out.push_back(d);
return out;
}
RescheduleStatus reschedule_league_match(GameState& g, int manager, const LeagueMatchRef& match, int day) {
if (manager_team(g, manager) < 0 || !memory_ok(g)) return RescheduleStatus::invalid_manager;
const std::vector<LeagueMatchRef> movable = reschedulable_matches(g, manager);
const auto it = std::find_if(movable.begin(), movable.end(), [&](const LeagueMatchRef& m) {
return m.day == match.day && m.round == match.round && m.league == match.league && m.match == match.match;
});
if (it == movable.end()) return RescheduleStatus::invalid_match;
const std::vector<int> days = reschedule_target_days(g, manager, *it);
if (std::find(days.begin(), days.end(), day) == days.end()) return RescheduleStatus::invalid_day;
// the first free entry of the postponed list
int slot = -1;
for (int e = 0; e < kPostponedEntries && slot < 0; e++)
if (g.memory.u16(kPostponed + uint32_t(e) * 6) == 0) slot = e;
if (slot < 0) return RescheduleStatus::no_free_slot;
// RescheduleLeagueMatch(day, league, match, slot, -0x32, round): eight replays on the day or a
// team clash with one of them refuse the move. Like the winter mode the original builds
// the other replay's fixtures with the parameters of this league and compares the low
// bytes of the team ids only.
const int league = it->league;
const Fixture own = round_fixtures(league, it->round).at(size_t(it->match));
int same_day = 0;
for (int e = 0; e < kPostponedEntries; e++) {
const uint32_t at = kPostponed + uint32_t(e) * 6;
if (g.memory.u16(at) != uint16_t(day)) continue;
if (++same_day == 8) return RescheduleStatus::day_full;
const Fixture other = round_fixtures(league, g.memory.u8(at + 2)).at(g.memory.u8(at + 4));
const uint8_t oh = uint8_t(other.home), oa = uint8_t(other.away), fh = uint8_t(own.home), fa = uint8_t(own.away);
if (fh == oh || fa == oa || fa == oh || fh == oa) return RescheduleStatus::team_clash;
}
const uint32_t at = kPostponed + uint32_t(slot) * 6;
g.memory.set16(at, uint16_t(day));
g.memory.set8(at + 2, uint8_t(it->round));
g.memory.set8(at + 3, uint8_t(league));
g.memory.set8(at + 4, uint8_t(it->match));
g.results.at(result_at(league, it->round, it->match)) = kRescheduledMark;
const uint32_t high = kCalendar + uint32_t(day) * 2 + 1;
g.memory.set8(high, g.memory.u8(high) | 0x40);
return RescheduleStatus::moved;
}
std::vector<LeagueMatchRef> moved_matches(const GameState& g, int manager) {
std::vector<LeagueMatchRef> out;
const int team = manager_team(g, manager);
if (team < 0 || !memory_ok(g)) return out;
const int league = team_league(team);
const int today = g.season_day();
// CalendarCell: a click on a replay day (calendar bit 0xe) finds the club's replay with
// RescheduleTargetDays(day, team, league) and calls UndoReschedule when its result byte is 0xCE
for (int e = 0; e < kPostponedEntries; e++) {
const uint32_t at = kPostponed + uint32_t(e) * 6;
const int day = g.memory.u16(at);
if (day == 0 || day <= today || g.memory.u8(at + 3) != league) continue;
if (team_replay_on(g, day, team, league) != e + 1) continue;
const int round = g.memory.u8(at + 2), m = g.memory.u8(at + 4);
if (round == 0 || round + 2 >= league_matchdays(league)) continue;
if ((g.results.at(result_at(league, round, m)) & 0xcf) != kRescheduledMark) continue;
const Fixture f = round_fixtures(league, round).at(size_t(m));
out.push_back({day, round, league, m, f.home, f.away});
}
std::sort(out.begin(), out.end(), [](const LeagueMatchRef& a, const LeagueMatchRef& b) { return a.day < b.day; });
return out;
}
bool undo_reschedule(GameState& g, int manager, int day) {
const std::vector<LeagueMatchRef> moved = moved_matches(g, manager);
if (std::none_of(moved.begin(), moved.end(), [&](const LeagueMatchRef& m) { return m.day == day; })) return false;
const int team = manager_team(g, manager);
// UndoReschedule(day, 1, team): every replay of the club on that day, whatever its league
for (int e = 0; e < kPostponedEntries; e++) {
const uint32_t at = kPostponed + uint32_t(e) * 6;
if (g.memory.u16(at) != uint16_t(day)) continue;
const int league = g.memory.u8(at + 3), round = g.memory.u8(at + 2), m = g.memory.u8(at + 4);
const Fixture f = round_fixtures(league, round).at(size_t(m));
if (f.home != team && f.away != team) continue;
g.results.at(result_at(league, round, m)) = kNotPlayed;
g.memory.set16(at, 0);
}
return true;
}
} // namespace bmh
+79
View File
@@ -0,0 +1,79 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// Rescheduling a home league match (desk menu 7, "Verlegen", H2 p. 49; BMH.exe V2.24 +
// supported rule profile patch). The original does it on the calendar screen CalendarCell with mode 2:
//
// 1. The manager clicks a matchday of his own league. The match of his club on that day
// is selected when it is a home match, still in the future, not on the first matchday
// and not on one of the last two matchdays.
// 2. The calendar then marks the days the match can move to (draw loop of CalendarCell,
// see reschedule_target_days). With floodlights (manager record +0x0e) the day before
// the matchday (the Friday) is offered as well.
// 3. A click on a marked day moves the match with RescheduleLeagueMatch(day, league, match, slot,
// -0x32, round): the match becomes a "replay" on that day (postponed list Postponed),
// its result byte becomes 0xCE and the calendar day gets bit 0x4000. On the original
// matchday the 0xCE turns into 0xCD (matchday_setup) and the match is played on the
// new day like a winter postponement.
// 4. A click on the new day of a moved match takes the move back (UndoReschedule(day, 1,
// team)): the entry is freed and the result byte is 0xCC again. The calendar keeps bit
// 0x4000, as in the original.
//
// Everything here works on the saved GameState only: no random numbers are drawn, so a
// rescheduled career stays deterministic.
#include <cstdint>
#include <vector>
#include "game/state.hpp"
namespace bmh {
// A league match: day of the season (index into the calendar CompetitionCalendar), the 0-based
// league round, the league and the index of the match in the fixture list of that round.
struct LeagueMatchRef {
int day = -1;
int round = -1;
int league = -1;
int match = -1;
int home = -1; // team ids
int away = -1;
bool operator==(const LeagueMatchRef&) const = default;
};
enum class RescheduleStatus : uint8_t {
moved,
invalid_manager, // no human manager with a club in league play
invalid_match, // not one of reschedulable_matches()
invalid_day, // not one of reschedule_target_days()
no_free_slot, // all 40 entries of the postponed list are used
day_full, // eight replays on that day already (message Controller_CalendarFromGame_TextPointer)
team_clash, // a team of the match already plays a replay that day (Controller_CalendarFromGame_TextPointer)
};
// The own home league matches that can be moved: future days, rounds 1 .. matchdays - 3
// (0-based), result byte still 0xCC (not played, not postponed). Only clubs of leagues
// 0-4 (calendar bits 0-3) take part: the lower leagues have no own calendar bit.
std::vector<LeagueMatchRef> reschedulable_matches(const GameState& g, int manager);
// The days `match` can be moved to (the days CalendarCell marks in mode 2), ascending.
// Days that already hold a replay of one of the teams in the same league are left out, as
// the second click refuses them (RescheduleTargetDays).
std::vector<int> reschedule_target_days(const GameState& g, int manager, const LeagueMatchRef& match);
// Moves `match` to `day` (RescheduleLeagueMatch with param_5 = -0x32). Returns moved on success; on
// failure nothing is changed.
RescheduleStatus reschedule_league_match(GameState& g, int manager, const LeagueMatchRef& match, int day);
// The own matches moved with reschedule_league_match that can still be taken back: their new
// day (`day`) is in the future, the result byte is 0xCE and the round is one the screen
// accepts (1 .. matchdays - 3). Winter postponements (0xCD) are not listed. Like the
// original the club need not be the home side: in a hot seat game the opponent's manager can
// take back a move as well.
std::vector<LeagueMatchRef> moved_matches(const GameState& g, int manager);
// Takes back the move of the club's match on `day` (one of moved_matches) - UndoReschedule with
// param_2 = 1: every replay on that day with the club gets result byte 0xCC and its entry is
// freed. Returns false if there is no such match.
bool undo_reschedule(GameState& g, int manager, int day);
} // namespace bmh
+199
View File
@@ -0,0 +1,199 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/save.hpp"
#include <cstdio>
#include <cstring>
#include <fstream>
#include "formats/savestate.hpp"
#include "game/career.hpp"
#include "game/national.hpp"
namespace bmh {
namespace {
void put(Bytes& d, const uint8_t* src, size_t n) {
for (size_t i = 0; i < n && i < d.size(); i++) d[i] = src[i];
}
void put(Bytes& d, const std::vector<uint8_t>& v) { put(d, v.data(), v.size()); }
void put16(Bytes& d, const std::vector<uint16_t>& v) {
for (size_t i = 0; i < v.size() && 2 * i + 1 < d.size(); i++) d[2 * i] = uint8_t(v[i]), d[2 * i + 1] = uint8_t(v[i] >> 8);
}
void put32(Bytes& d, size_t at, uint32_t x) {
for (int i = 0; i < 4 && at + size_t(i) < d.size(); i++) d[at + size_t(i)] = uint8_t(x >> (8 * i));
}
// DeskDate2(date, buffer, 0): "TT.MM.JJJJ" of a day counter (day 0 = 1 July 2026; a
// four-year leap cycle that starts with the third year).
std::string date_text(uint32_t counter) {
static const int kDays[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int cycle = 3, years = 0, month = 7;
while (counter > uint32_t(364 + (cycle == 4))) {
if (cycle == 4) cycle = 0, --counter;
++years, counter -= 365, ++cycle;
}
auto days = [&] { return month == 2 ? 28 + (cycle == 4) : kDays[month]; };
while (counter > uint32_t(days())) {
counter -= uint32_t(days());
if (++month == 13) month = 1, ++years;
}
int day = int(counter) + 1;
if (day > days()) {
day -= days();
if (++month == 13) month = 1, ++years;
}
char buf[16];
std::snprintf(buf, sizeof buf, "%02d.%02d.%04d", day, month, 2026 + years);
return buf;
}
} // namespace
Bytes save_stream(const GameState& live) {
// NationalCoachAfterLoad writes a Bundestrainer's game with the slots swapped back (national.hpp)
const bool coach = live.memory.has(::bmh::layout::CoachActive) && live.memory.u8(::bmh::layout::CoachActive) != 0;
const GameState swapped = coach ? national_coach_save_form(live) : GameState{};
const GameState& g = coach ? swapped : live;
const bool records = g.memory.has(::bmh::layout::ClubSeasonRecords) && g.memory.u32(::bmh::layout::ClubSeasonRecords) != 0;
Bytes stream;
for (const SaveBlock& b : save_layout(DbCounts{}, records)) {
Bytes d(b.size, 0);
if (b.heap) {
switch (b.address) {
case ::bmh::layout::PlayerBonuses: put(d, g.player_bonus); break;
case ::bmh::layout::TeamMorale: put(d, g.team_morale); break;
case ::bmh::layout::ClubBadgeSelectors: put(d, g.club_heap_78); break;
case ::bmh::layout::TeamFlags: put16(d, g.team_flags); break;
case ::bmh::layout::ClubIdentities: put16(d, g.club_ids); break;
case ::bmh::layout::PlayerNameOffsets: put16(d, g.player_name_offsets); break;
case ::bmh::layout::MasterDatabaseMetadata: put(d, g.master_database_metadata); break;
case ::bmh::layout::ClubAuxiliaryWords: put(d, g.club_heap_bc); break;
case ::bmh::layout::LeagueRankHistory: put(d, g.position_history); break;
case ::bmh::layout::ClubAuxiliaryBytes: put(d, g.club_heap_b8); break;
case ::bmh::layout::SquadSlots: put16(d, g.squad_slots); break;
case ::bmh::layout::PlayerCards: put16(d, g.player_cards); break;
case ::bmh::layout::ManagerMailbox: put(d, g.mailbox); break;
case ::bmh::layout::TournamentName: put(d, g.tournament_name); break;
case ::bmh::layout::ClubSeasonRecords: put(d, g.club_table); break;
case ::bmh::layout::PlayerConditionTechniqueForm:
case ::bmh::layout::PlayerSkillWords:
case ::bmh::layout::PlayerIdentityWords:
for (size_t i = 0; i < g.players.size(); i++) {
const Player& p = g.players[i];
put32(d, i * 4, b.address == ::bmh::layout::PlayerConditionTechniqueForm ? p.w35c : b.address == ::bmh::layout::PlayerSkillWords ? p.w368 : p.w364);
}
break;
default: break;
}
} else {
for (size_t i = 0; i < b.size; i++)
if (g.memory.has(b.address + uint32_t(i))) d[i] = g.memory.u8(b.address + uint32_t(i));
// the blocks GameState keeps in typed fields
switch (b.address) {
case ::bmh::layout::ManagerRecords: put(d, g.manager_records); break;
case ::bmh::layout::ManagerMatchHistory: put(d, g.manager_results); break;
case ::bmh::layout::ManagerRatings: put(d, g.manager_ratings); break;
case ::bmh::layout::LeagueResults: put(d, g.results); break;
case ::bmh::layout::LeagueRoundCounters: put(d, g.league_rounds); break;
case ::bmh::layout::TacticsBoards: put(d, g.tactics); break;
case ::bmh::layout::StockExchange: put(d, g.stocks); break;
case ::bmh::layout::ManagerAutomation: put(d, g.manager_options); break;
case ::bmh::layout::Formations: put(d, g.formations); break;
case ::bmh::layout::ForeignClubStrength: put(d, g.foreign_strength); break;
case ::bmh::layout::Difficulty: d[0] = uint8_t(g.level); break;
case ::bmh::layout::CalendarDay: put32(d, 0, g.date); break;
case ::bmh::layout::DaysIntoSeason: d[0] = uint8_t(g.date - g.season_start), d[1] = uint8_t((g.date - g.season_start) >> 8); break;
case ::bmh::layout::PlayerDevelopmentBalance: put32(d, 0, uint32_t(g.development_balance)); break;
case ::bmh::layout::SeasonIndex: d[0] = uint8_t(g.season), d[1] = uint8_t(uint16_t(g.season) >> 8); break;
default: break;
}
}
stream.insert(stream.end(), d.begin(), d.end());
}
for (const std::vector<uint8_t>* pool : {&g.club_names, &g.player_names, &g.referee_names, &g.stadium_names}) {
stream.push_back(uint8_t(pool->size()));
stream.push_back(uint8_t(pool->size() >> 8));
stream.insert(stream.end(), pool->begin(), pool->end());
}
// the English cup memory has no place in the original layout: OpenBMH extension
std::vector<SaveState::ExtensionBlock> extension;
for (const auto& [at, size] : kEnglishCompetitionBlocks)
if (g.memory.has(at) && g.memory.has(at + size - 1)) {
Bytes bytes(size);
for (uint32_t i = 0; i < size; ++i) bytes[i] = g.memory.u8(at + i);
extension.push_back({at, std::move(bytes)});
}
append_save_extension(stream, extension);
return stream;
}
Bytes save_header(const GameState& g) {
const int managers = g.memory.u8(::bmh::layout::ManagerCount);
Bytes h;
h.push_back(uint8_t(managers));
const std::string date = date_text(g.date);
for (size_t i = 0; i < 11; i++) h.push_back(i < date.size() ? uint8_t(date[i]) : 0);
Bytes list(0xa0, 0);
for (int m = 0; m < managers && m < 4; m++) {
const size_t rec = size_t(m) * 0xb0c;
const int team = int16_t(g.manager_records.at(rec + 0x290) | g.manager_records.at(rec + 0x291) << 8);
const bool national = team == 0x165;
const size_t at = size_t(m) * 0x28;
list[at] = national ? 0x1e : g.manager_records.at(rec + 0x210); // (0x1e: high byte of the loop word)
list[at + 1] = national ? 1 : 0;
for (size_t i = 0; i < 0x13; i++) list[at + 2 + i] = g.manager_records.at(rec + 0xa8 + i);
const size_t name = g.club_ids.at(size_t(team));
for (size_t i = 0; i < 0x13 && name + i < g.club_names.size(); i++) list[at + 0x15 + i] = g.club_names[name + i];
}
h.insert(h.end(), list.begin(), list.end());
return h;
}
Savegame make_savegame(const GameState& g, WatcomRandom& rand) {
Savegame s;
s.plain_header = save_header(g);
s.id1 = 0;
s.version = "V2.24";
const uint32_t hi = uint32_t(rand.range(0, 0x8fff)), lo = uint32_t(rand.range(0, 0x8fff));
s.id2 = lo + hi * 0x10000 + 1;
s.key = uint8_t(rand.range(0, 0xff) + 'n');
s.random = uint8_t(rand.range(0, 0xff));
s.stream = save_stream(g);
uint8_t sum = s.key;
for (uint8_t b : s.stream) sum = uint8_t(sum + b);
s.checksum = sum;
s.checksum_ok = true;
return s;
}
Bytes savegame_bytes(const Savegame& s) {
Bytes out = s.plain_header;
static const char magic[10] = {'K', 'R', 'O', 'N', '_', 'F', 'B', 'M', 0, 'k'};
out.insert(out.end(), magic, magic + 10);
for (int i = 0; i < 4; i++) out.push_back(uint8_t(s.id1 >> (8 * i)));
for (size_t i = 0; i < 6; i++) out.push_back(i < s.version.size() ? uint8_t(s.version[i]) : 0);
for (int i = 0; i < 4; i++) out.push_back(uint8_t(s.id2 >> (8 * i)));
out.push_back(s.random);
out.push_back(s.key);
Bytes enc = s.stream;
fbm_encrypt(enc.data(), enc.size(), s.key);
out.insert(out.end(), enc.begin(), enc.end());
out.push_back(s.checksum);
return out;
}
void write_savegame(const std::filesystem::path& path, const Savegame& s) {
const Bytes b = savegame_bytes(s);
std::ofstream f(path, std::ios::binary | std::ios::trunc);
if (!f) throw FormatError("cannot write " + path.string());
f.write(reinterpret_cast<const char*>(b.data()), std::streamsize(b.size()));
const bool written = bool(f);
f.close();
// Buffered final bytes can fail only at close, after write reported the
// complete size. The autosave caller must not publish that temporary file.
if (!written || !f) throw FormatError("short write " + path.string());
}
} // namespace bmh
+38
View File
@@ -0,0 +1,38 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// Writing savegames (MakeSavegame with FbmDecrypt2 and NationalCoachAfterLoad).
//
// A GameState keeps part of the savegame in typed fields (players, squads, records, ...)
// and the rest in StaticMemory; save_stream puts both back into the block order of the
// original, so that loading a savegame and saving it again gives the same stream.
#include <cstdint>
#include <filesystem>
#include "formats/binary.hpp"
#include "formats/fbm.hpp"
#include "game/random.hpp"
#include "game/state.hpp"
namespace bmh {
// The decrypted stream of a savegame: the 125 state blocks (NationalCoachAfterLoad, with the club
// records when their pointer ClubSeasonRecords is set) and the four name pools.
Bytes save_stream(const GameState& g);
// FbmDecrypt2: the plain header read by the load list - the number of managers, the date
// ("TT.MM.JJJJ") and per manager (0x28 bytes): start league, national team flag, his name
// and his club's name (0x13 bytes each). The original leaves stack bytes in the unused
// parts; they are zero here.
Bytes save_header(const GameState& g);
// MakeSavegame from the header on: "KRON_FBM", the previous id (here 0), "V2.24", the new
// id W(0, 0x8fff) << 16 + W(0, 0x8fff) + 1, the key byte W(0, 0xff) + 'n' and a random byte
// W(0, 0xff) (the four Watcom draws of saving), the encrypted stream and its checksum.
Savegame make_savegame(const GameState& g, WatcomRandom& rand);
// The file bytes of a savegame (inverse of load_savegame).
Bytes savegame_bytes(const Savegame& s);
void write_savegame(const std::filesystem::path& path, const Savegame& s);
} // namespace bmh
+157
View File
@@ -0,0 +1,157 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "game/schedule.hpp"
#include "formats/executable_layout.hpp"
#include "formats/le.hpp"
#include <stdexcept>
#include <utility>
namespace bmh {
namespace {
// Fixture content belongs to the selected installation. Explicit callers install
// the loaded tables before scheduling; no copied or generated fallback is used.
FixtureTableCache fixture_tables;
const char* round_string(int teams, int round) {
const auto table = fixture_tables.find(teams);
if (table == fixture_tables.end())
throw std::invalid_argument("fixture table is not installed for this league size");
if (round < 1 || size_t(round) > table->second.size())
throw std::out_of_range("fixture round out of range");
return table->second[size_t(round - 1)].c_str();
}
} // namespace
void set_fixture_tables(FixtureTableCache tables) {
if (tables.empty()) throw std::invalid_argument("fixture tables are empty");
for (const auto& [teams, rounds] : tables) {
if (teams != 4 && teams != 6 && teams != 12 && teams != 16 && teams != 18 && teams != 20)
throw std::invalid_argument("unsupported fixture table size");
if (rounds.size() != size_t(teams - 1))
throw std::invalid_argument("fixture table has an invalid round count");
for (const auto& round : rounds) {
if (round.size() != size_t(teams))
throw std::invalid_argument("fixture round has an invalid length");
uint32_t seen = 0;
for (unsigned char ch : round) {
const int team = int(ch) - 'a';
if (team < 0 || team >= teams || (seen & (uint32_t(1) << team)))
throw std::invalid_argument("fixture round has an invalid or duplicate team");
seen |= uint32_t(1) << team;
}
}
}
fixture_tables.swap(tables);
}
void install_fixture_tables(const LeImage& exe) {
struct Binding { int teams; uint32_t table; };
static constexpr Binding german[] = {
{4, layout::CareerSession_RuntimeError_RuntimeField},
{6, layout::CareerSession_RuntimeError_RuntimeField2},
{12, layout::CareerSession_RuntimeError_RuntimeField3},
{16, layout::CareerSession_RuntimeError_ExecutableField3},
{18, layout::CareerSession_RuntimeError_ExecutableField},
{20, layout::CareerSession_RuntimeError_ExecutableField2},
};
static constexpr Binding english[] = {
{4, layout::EnglishFourTeamFixtureTable},
{6, layout::EnglishSixTeamFixtureTable},
{12, layout::EnglishTwelveTeamFixtureTable},
{20, layout::EnglishTwentyTeamFixtureTable},
};
FixtureTableCache tables;
const auto read = [&](const auto& bindings) {
for (const auto& [teams, table] : bindings) {
if (!exe.contains(table) || !exe.contains(table + uint32_t(teams * 4 - 1)))
throw std::invalid_argument("fixture pointer table is outside the loaded image");
const uint32_t empty = exe.u32(table);
if (!exe.contains(empty) || exe.u8(empty) != 0)
throw std::invalid_argument("fixture table has no empty initial round");
auto& rounds = tables[teams];
for (int round = 1; round < teams; ++round) {
const uint32_t at = exe.u32(table + uint32_t(round * 4));
if (!exe.contains(at) || uint64_t(at) + uint64_t(teams) >= uint64_t(exe.base()) + exe.size())
throw std::invalid_argument("fixture round is outside the loaded image");
if (exe.u8(at + uint32_t(teams)) != 0)
throw std::invalid_argument("fixture round has no terminating NUL");
std::string text;
for (int i = 0; i < teams; ++i) text.push_back(char(exe.u8(at + uint32_t(i))));
rounds.push_back(std::move(text));
}
}
};
if (exe.u8(layout::LeagueSizes) == 20) read(english);
else read(german);
set_fixture_tables(std::move(tables));
}
int league_first_team(int league) {
int first = 0;
for (int l = 0; l < league; l++) first += kLeagueSizes[l];
return first;
}
int team_league(int team) {
int end = 0;
for (int l = 0; l < kLeagueCount; l++) {
end += kLeagueSizes[l];
if (team < end) return l;
}
return kLeagueCount;
}
std::vector<Fixture> generate_fixtures(int teams, int matchday, int rounds, int first_team) {
// GenerateFixtures: reduce the matchday into the first half, toggling home/away for every
// half season that is skipped.
bool swap = false;
while (matchday > rounds) {
matchday -= rounds;
swap = !swap;
}
const char* s = round_string(teams, matchday);
std::vector<Fixture> out;
// The original loops (rounds + 1) / 2 times, which equals teams / 2 for a full league.
for (int m = 0; m < (rounds + 1) / 2; m++) {
int a = s[2 * m] - 'a', b = s[2 * m + 1] - 'a';
if (swap) std::swap(a, b);
out.push_back({first_team + a, first_team + b});
}
return out;
}
int league_table_teams(int league) { return league < 5 ? kLeagueSizes[0] : kLeagueSizes[5]; }
void set_league_sizes(const uint8_t (&sizes)[kLeagueCount]) {
int total = 0;
for (int l = 0; l < kLeagueCount; l++) total += sizes[l];
const auto has_table = [](int teams) { return teams == 20 || teams == 18 || teams == 16 || teams == 12; };
if (total != 138 || !has_table(sizes[0]) || !has_table(sizes[5]))
throw std::invalid_argument("league sizes do not describe 138 league teams with fixture tables");
for (int l = 0; l < kLeagueCount; l++)
if (sizes[l] < 2 || sizes[l] > (l < 5 ? sizes[0] : sizes[5]))
throw std::invalid_argument("a league is larger than its fixture table");
for (int l = 0; l < kLeagueCount; l++) kLeagueSizes[l] = sizes[l];
}
void set_league_groups(const uint8_t (&first)[8], const uint8_t (&count)[8]) {
uint8_t bit[kLeagueCount];
for (int l = 0; l < kLeagueCount; l++) bit[l] = 0xff;
for (int b = 0; b < 8; b++) {
if (first[b] + count[b] > kLeagueCount) throw std::invalid_argument("calendar groups outside the leagues");
// (bits 4-7 are the four international leagues, all on calendar bit 4)
for (int l = first[b]; l < first[b] + count[b]; l++) bit[l] = uint8_t(b < 4 ? b : 4);
}
for (int b = 0; b < 8; b++) kGroupLeague[b] = first[b], kGroupLeagues[b] = count[b];
for (int l = 0; l < kLeagueCount; l++) kLeagueBit[l] = bit[l];
}
std::vector<Fixture> league_fixtures(int league, int matchday) {
const int teams = kLeagueSizes[league];
return generate_fixtures(league_table_teams(league), matchday, teams - 1, league_first_team(league));
}
} // namespace bmh
+138
View File
@@ -0,0 +1,138 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// League fixtures and results.
//
// Team ids
// Every club has an index into all per-club tables (names, stadiums, squads, ...).
// Leagues are contiguous ranges of these ids: league 0 is ids 0..17, league 1 the next
// 18 ids and so on (sizes in kLeagueSizes, LeagueSizes; team -> league is
// TeamLeague2). When a new game starts the clubs of a league are shuffled by swapping
// all their table entries (swap function around 0x685xx), so a team's position inside
// its league is its "draw position" for the fixture list. The master database order is
// therefore NOT the order used by a running game; always take names from the savegame.
//
// Fixtures (GenerateFixtures)
// The fixture list is not stored. For each league size there is a fixed table of
// "round strings" loaded from the executable: round r of the first half of the season is a
// string of letters, each consecutive pair "xy" is one match, home team = draw position
// x - 'a', away team = y - 'a'. The second half repeats the rounds with home and away
// swapped, and so on for leagues that play more than twice (the round index wraps).
//
// Results (block LeagueResults, 0xD5C bytes)
// results[league * 380 + (matchday - 1) * 10 + match] = home_goals << 4 | away_goals
// Room for 9 leagues x 38 matchdays x 10 matches. 0xCC marks a match not yet played
// (the whole block is filled with 0xCC at season start, FUN at layout field in the dump);
// the code also tests (value & 0xCF) against 0xCC/0xCD/0xCE for postponed matches.
#include <cstdint>
#include <map>
#include <string>
#include <vector>
namespace bmh {
class LeImage;
// Round strings are installation content. Sparse authored caches are supported
// for isolated callers; real sessions install the tables from their executable.
using FixtureTableCache = std::map<int, std::vector<std::string>>;
// Validates every supplied table before replacing the current cache. Throws
// std::invalid_argument for malformed rows, team ids, sizes or round counts.
void set_fixture_tables(FixtureTableCache tables);
void install_fixture_tables(const LeImage& exe);
// Number of teams per league, LeagueSizes of the loaded game: the German versions have 5
// leagues of 18 and 4 of 12; the English Football Limited 20 20 20 20 10 and the same four
// international leagues of 12 (both 138 league teams, so the squad layout is the same).
// The German sizes are the default; set_league_sizes() installs those of the loaded game
// (app::CareerSession does it from the EXE table). One game per process.
constexpr int kLeagueCount = 9;
inline uint8_t kLeagueSizes[kLeagueCount] = {18, 18, 18, 18, 18, 12, 12, 12, 12};
// Installs the league sizes of the loaded game; throws std::invalid_argument unless they
// add up to 138 (the league teams of every version) and every league has a fixture table (20, 18, 16, 12 or 10 teams).
void set_league_sizes(const uint8_t (&sizes)[kLeagueCount]);
// The calendar groups of the loaded game: competition bits 0-7 play the leagues
// kGroupLeague[bit] .. + kGroupLeagues[bit] - 1 (CalendarFirstLeague / CalendarLeagueCounts), and a league
// plays on calendar bit kLeagueBit[league] (LeagueCalendarBits). German: 3. Liga A and B share
// bit 2; English: every division has its own bit and the 10-team fifth league none (0xff
// in kLeagueBit, not played). Set with the league sizes from the EXE tables.
inline uint8_t kGroupLeague[8] = {0, 1, 2, 4, 5, 6, 7, 8};
inline uint8_t kGroupLeagues[8] = {1, 1, 2, 1, 1, 1, 1, 1};
inline uint8_t kLeagueBit[kLeagueCount] = {0, 1, 2, 2, 3, 4, 4, 4, 4};
void set_league_groups(const uint8_t (&first)[8], const uint8_t (&count)[8]);
// The promotion ladder of the loaded game (Void / English ClubName), set with
// the league sizes from the EXE tables:
// - kLeagueRelegation[league]: relegation places (CareerSession_InstallLeagueSizes_RuntimeField2; German 3 4 2 2 3, English
// 4 4 4 4 4),
// - kGroupBelow[group] .. + kGroupBelowCount[group] - 1: the league(s) a promotion group
// takes its promoted clubs from (CareerSession_InstallLeagueSizes_RuntimeField5 / CareerSession_InstallLeagueSizes_RuntimeField4; German 1 | 2 | 4 with the
// two Regionalligen in one group, English 1 | 2 | 3),
// - kLeagueSuffix[league]: the letter after a league's name (CareerSession_InstallLeagueSizes_RuntimeField3, two bytes per
// league; German A/B for the Regionalligen, English none),
// - kNewcomerFirst / kNewcomerCount: the clubs the lowest league is refilled from
// (CareerSession_DispatchLineup_RuntimeField / CareerSession_InstallLeagueSizes_RuntimeField6; German the 30 amateur clubs 138-167; the English game
// draws from its 12 further English clubs 138-149 - its later ids have no name - so the
// session counts only named clubs).
inline uint8_t kLeagueRelegation[kLeagueCount] = {3, 4, 2, 2, 3, 0, 0, 0, 0};
// European places per league for the table prediction (CareerSession_InstallLeagueSizes_RuntimeField; German 0 3 2 2 4 - league
// 0 uses 4 in the prediction -, English 0 4 4 4 4)
inline uint8_t kLeagueEurope[kLeagueCount] = {0, 3, 2, 2, 4, 0, 0, 0, 0};
inline uint8_t kGroupBelow[8] = {1, 2, 4, 5, 6, 7, 8, 0};
inline uint8_t kGroupBelowCount[8] = {1, 2, 1, 1, 1, 1, 1, 0};
inline char kLeagueSuffix[kLeagueCount] = {0, 0, 'A', 'B', 0, 0, 0, 0, 0};
inline int kNewcomerFirst = 0x8a, kNewcomerCount = 0x1e;
// The English competition structure (Football Limited): an FA Cup of 68 clubs with a
// qualifying stage (cup entries 0 and 28) and a League Cup (entries 25-27). Its cup memory
// lies partly in blocks of its own (career.hpp, english_competition_blocks). Set with the
// league sizes: a first league of 20 clubs is the English structure.
inline bool kEnglishCompetitions = false;
// First team id of a league (sum of the sizes of all previous leagues).
int league_first_team(int league);
// League of a team id, or kLeagueCount for teams outside league play (TeamLeague2).
int team_league(int team);
// The round-string table a league plays with (its team count): the original points leagues
// 0-4 at the table of the first league and 5-8 at the 12-team table (DE CareerFirstSteps2, EN
// LeagueTableTeams). The same as the league size except for the English fifth league (10 teams),
// which belongs to no calendar group and is never played.
int league_table_teams(int league);
struct Fixture {
int home; // team id
int away; // team id
};
// Matches of a league matchday (1-based), home/away as team ids. `rounds` is the number of
// rounds per half season, normally team count - 1 (the original passes matchdays / 2).
std::vector<Fixture> league_fixtures(int league, int matchday);
// Raw fixture generator, a direct port of GenerateFixtures:
// teams - league size, selects the round-string table
// matchday - 1-based
// rounds - rounds per half season (normally teams - 1)
// first_team - id of the league's first team, added to every draw position
std::vector<Fixture> generate_fixtures(int teams, int matchday, int rounds, int first_team);
constexpr uint8_t kNotPlayed = 0xCC;
constexpr size_t kResultsSize = 0xD5C;
struct Result {
bool played = false;
int home_goals = 0;
int away_goals = 0;
};
// Decodes one result byte of block LeagueResults.
inline Result decode_result(uint8_t v) {
if ((v & 0xCF) >= 0xCC) return {};
return {true, v >> 4, v & 0x0F};
}
// Index into the results block for a league match.
inline size_t result_index(int league, int matchday, int match) {
return size_t(league) * 0x17C + size_t(matchday - 1) * 10 + size_t(match);
}
} // namespace bmh
+1689
View File
File diff suppressed because it is too large. Load diff
+196
View File
@@ -0,0 +1,196 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#pragma once
// OpenBMH deviates from the original: uses the enhanced youth-academy season settlement and player-generation rules.
// From one season to the next (BMH.exe V2.24 + supported rule profile patch).
//
// On 1 July the "Weiter" loop (DailyInterest) ends the season: CareerSession_RuntimeError_RuntimeField4 = 1, the season
// bonuses (SeasonAwards) and the manager's desk "Saisonende". When he leaves it with
// "Anstoss" the offers still open for his players are answered (DispatchClubPlayerPendingOffers, from
// AdvanceTurn) and the new season is set up (the CareerSession_RuntimeError_RuntimeField4 branch of DailyInterest):
// season + 1 (SeasonIndex), the clubs' moods and flags (ClubBalance), the European
// cups and their foreign clubs (CareerSeasonSetup(1)), contracts (GameEndTaxAnimationScreen, Void),
// the league tables to the cups (CareerSeasonSetup(2)), the German clubs in Europe shown
// (SeasonOperation), the national cup draw (Getenv), promotion and relegation
// (CareerSeasonSetup3, SeasonEndSteps), the managers' season records (ManagerOf), the day steps
// up to the first Wednesday and the new transfer list (CareerFirstSteps); the season day
// DaysIntoSeason restarts at 0.
// Annual accounts expose the Original acknowledgement/decision boundary before
// booking tax. Headless callers without a selector use the Original NO branch.
#include <functional>
#include <array>
#include <vector>
#include "game/match_engine.hpp"
#include "game/random.hpp"
#include "game/state.hpp"
#include "game/transfer_allocator.hpp"
namespace bmh {
enum class SeasonTaxEventKind { notice, question, animation, outcome };
struct SeasonTaxEvent {
SeasonTaxEventKind kind = SeasonTaxEventKind::notice;
int manager_slot = -1;
int team = -1;
int32_t profit = 0;
int32_t legal_tax = 0;
int32_t paid_tax = 0;
int32_t fine = 0;
int animation_variant = 0;
bool caught = false;
std::string text; // owned Original-encoding text, prepared by the accounting engine
};
struct SeasonTaxHooks {
std::function<void(const GameState&, const SeasonTaxEvent&)> observe;
std::function<bool(const GameState&, const SeasonTaxEvent&)> choose;
};
// SeasonProfitTax continues GameEndTaxAnimationScreen's loop without reinitialising its local fine.
// This state lives for one annual-accounts pass across all human managers.
struct SeasonTaxState {
int32_t carried_fine = 0;
};
// CupDrawFromGame: the generated order, then Getenv/CupGroupOverviewEffects.
// Participants are owned copies of the current round at each boundary.
enum class SeasonCupDrawPhase { draw, overview };
struct SeasonCupDrawEvent {
SeasonCupDrawPhase phase = SeasonCupDrawPhase::draw;
uint32_t entry_address = ::bmh::layout::CupTable;
int competition = 0;
int round = 0;
int offset = 0;
uint8_t flags = 0;
bool group_stage = false;
int group_index = 0;
int group_count = 0;
size_t count = 0;
std::vector<uint16_t> participants;
struct GroupAverageSnapshot {
uint16_t runtime_id = 0;
std::array<int, 5> values{};
};
// Void6 calls TeamRating for owned foreign teams at the live Source
// boundary. The overview owns those values so a renderer never rerolls.
std::vector<GroupAverageSnapshot> group_average_snapshots;
};
using SeasonCupDrawHook = std::function<void(const GameState&, const SeasonCupDrawEvent&)>;
// DispatchClubPlayerPendingOffers (the loop at the end of AdvanceTurn): the offers for players of human
// manager `manager` (OfferSlots) are answered. A salary demand (a club tries to lure the
// player away) is accepted with `accept`: the board salary becomes the offered one and
// its percentage of the market salary is noted (+0xd). Declining it needs the transfer
// (IncomingTransferScreen) and is reported. A fee offer opens the negotiation screen (IncomingTransferScreen /
// OpenTransferEditor), which restarts the game generator from CareerSession_Invalid_RuntimeField2 and draws the
// negotiator's picture; with `game` the manager refuses the release (right click, the
// message box "Sie verweigern dem Spieler die Freigabe!"). A transfer_decision callback
// may accept a fee offer. Interactive Main uses process_natural_pending_offers_after_desk
// with its typed presenters and shared human-buyer settlement instead of this legacy API.
// (The offer slots are freed by free_offer_slots after all desks.)
void answer_offers(GameState& g, int manager, bool accept, WatcomRandom& rand, MinuteReport& report,
GameRandom* game = nullptr);
// The end of the desk loop of AdvanceTurn, after every manager's desk and answers: the four
// offer slots (transfer list entries 0x28..0x2b, OfferSlots) are freed.
void free_offer_slots(GameState& g);
// OpenBMH deviates from the original: uses the enhanced youth-academy season settlement and player-generation rules.
// YouthAcademyPlayer (supported rule profile youth academy, season accounts): when manager `m` paid the academy in
// full this season (+0x880) and has room, a young player of a computer club joins his squad
// with values by the league (see season.cpp). Returns whether one came.
bool youth_academy_player(GameState& g, int m, GameRandom& game, WatcomRandom& rand, MinuteReport& report);
// ClubBalance(0): every club's mood (TeamMorale, W(20, 30)) and flags (*TeamFlags): a random
// base, two levels from the final table position (title holders get the top one) with
// random exceptions, and two from the balance of its squad (CareerSeasonSetup4).
// CareerSeasonSetup4(team): bits 8-11 of the club flags from the balance of its squad (W draws).
void club_balance(GameState& g, int team, WatcomRandom& rand);
// The end of InitializeCareer (a new career, after the managers): the national team flag, every
// league club's balance (CareerSeasonSetup4) and automatic line-up (humans with the bit 0x80),
// the title holders of the cups, CareerSeasonSetup(3) (international tournament, European
// entrants, national cup field), the season tickets (CareerSeasonSetup2), Getenv(0x40, 0) and
// the players' season (CareerSeasonSetup3).
// `pause` is called at the screens the original waits at (as in season_transition).
bool career_season_setup(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
const std::function<void(const char*)>& pause = nullptr,
const SeasonCupDrawHook& cup_draw = {});
// CareerFirstSteps2 after InitializeCareer and the start of DailyInterest(0): the game generator's seed is
// saved (CareerSession_Invalid_RuntimeField2), the clubs of each league change places at random (Getenv2) and the
// transfer list gets its first players (CareerFirstSteps). The "Weiter" loop then prepares the
// first event (AdvanceTurn) up to the first desk.
bool career_first_steps(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report);
// ClubsChangePlaces(a, b): two clubs (ids below 168) change places in every table per club id.
void clubs_change_places(GameState& g, int a, int b);
// With `new_career` (ClubBalance(1), start of a career) both levels are 1 for every club and
// the position draws are skipped.
void reset_club_moods(GameState& g, GameRandom& game, WatcomRandom& rand, bool new_career = false);
// The CareerSession_RuntimeError_RuntimeField4 branch of DailyInterest (see above). Missing runtime context or
// invalid state is reported through MinuteReport; presenters are supplied by the caller.
// `pause` is called where the original waits for the manager (a screen): week_check compares
// the recorded pauses there.
enum class SeasonTransitionOutcome { NextSeason, CareerComplete, Failed };
// Void -> SeasonPromotionScreen: already computed local lists, before swaps.
// The arrays are owned; only their first `count` entries are displayed/swapped.
// In group 1 without play-offs, count may be smaller than relegated.size().
struct SeasonPromotionEvent {
int group = 0; // 0..3: first division, second, both third divisions, fourth
size_t count = 0;
std::vector<uint16_t> relegated;
std::vector<uint16_t> promoted;
};
using SeasonPromotionHook = std::function<void(const GameState&, const SeasonPromotionEvent&)>;
using SeasonHighscoreHook = std::function<void(const GameState&, bool display)>;
SeasonTransitionOutcome season_transition(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
const std::function<void(const char*)>& pause = {},
const SeasonHighscoreHook& highscore = {},
const SeasonTaxHooks& tax_hooks = {},
const SeasonPromotionHook& promotion_hook = {},
const SeasonCupDrawHook& cup_draw = {},
TransferAllocatorContext allocator = TransferAllocatorContext::unsupported);
// GameEndTaxAnimationScreen/SeasonProfitTax profit branch: show ACK, ask JA/NEIN, perform its exact RNG
// and sanctions, then store the carry values and debit tax plus any fine once.
// The caller supplies the already rounded seasonal profit, before ticket income.
void season_apply_profit_tax(GameState& g, int manager, int32_t profit,
GameRandom& game, WatcomRandom& rand,
const SeasonTaxHooks& hooks = {},
SeasonTaxState* continuation = nullptr);
// GameEndTaxAnimationScreen / SeasonProfitTax: progressive tax on a rounded seasonal profit.
// Exposed so the threshold and integer-rounding rules can be tested directly.
int32_t season_profit_tax(int32_t profit);
// GameEndTaxAnimationScreen: next-season tax refund after a lower profit; returns zero when
// the original conditions do not grant a refund.
int32_t season_profit_tax_refund(int32_t profit, int32_t previous_taxable_profit,
int32_t previous_tax_paid);
// SeasonAwards, on 1 July before the "Saisonende" desk: per league (< 5) the club of the
// top scorer (goals), of the best scorer (goals + assists, list Season_List_RuntimeField) and the fair
// play winner (fewest card points); a human manager's club gets the prize (SeasonRuntimeField26)
// with a message.
void season_awards(GameState& g);
// The side effects of the cup overview screen CupGroupOverviewEffects (otherwise display only): the
// running competitions' slot 4 (this year's international tournament), the manager's screen
// state and the friendlies 0xc while their entry 30 has teams.
void cup_overview_effects(GameState& g);
// CupGroupOverviewEffects's group cursor is owned by this stage entry; the national cup's
// existing overview path intentionally keeps its original effects unchanged.
void cup_group_overview_effects(GameState& g, int group_index);
// LeagueName: the name of a league below 5 (with its letter, e.g. for the third divisions).
std::string league_name(const GameState& g, int league);
// MonthChange(absolute squad slot): the player leaves his club for the free agents with new
// values (W and game draws) and an age W(4, 15); his club closes the gap (ReleasePlayer,
// with a human club its tactics board as well). False if the source ownership/state
// cannot be validated; the player movement and human board compaction are implemented.
bool release_player(GameState& g, int slot, GameRandom& game, WatcomRandom& rand, MinuteReport& report);
} // namespace bmh
+39
View File
@@ -0,0 +1,39 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "game/source_tip.hpp"
#include <bit>
#include <cstdint>
namespace bmh {
uint8_t source_tip_result(GameRandom& game, const std::array<uint8_t, 10>& gap,
int home_rating, int away_rating,
int home_secondary, int away_secondary) {
uint8_t home = uint8_t((away_secondary + 0x14 < home_secondary) + game.range(0, 1));
uint8_t away = uint8_t((away_secondary < home_secondary) + game.range(0, 1));
const uint32_t wrapped = uint32_t(home_rating) - uint32_t(away_rating);
const int32_t signed_difference = std::bit_cast<int32_t>(wrapped);
int32_t scaled = signed_difference / 10;
if (scaled < 0) scaled = -scaled;
uint8_t local_c = uint8_t(scaled);
if (home_rating > away_rating) {
if (local_c > 9) local_c = 9;
home = uint8_t(home + game.range(0, int(gap[local_c]) + 1));
}
if (home_rating < away_rating) {
// ComputeLeagueTableForecast negates the byte before clamping it to the gap table.
local_c = uint8_t(-int(local_c));
if (local_c > 9) local_c = 9;
away = uint8_t(away + game.range(0, int(gap[local_c])));
if (local_c < 5) home = uint8_t(home + 1);
}
for (;;) {
const int cap = game.range(2, 6);
if (int(home) + int(away) <= cap) break;
if (home) --home;
if (away) --away;
}
return uint8_t((home << 4) | away);
}
} // namespace bmh
+18
View File
@@ -0,0 +1,18 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <array>
#include <cstdint>
#include "game/random.hpp"
namespace bmh {
// ComputeLeagueTableForecast's pure score arithmetic after the caller has obtained the four
// QuoteNationalFriendlyMatch ratings. Each invocation consumes the same G draws, including
// the final goal-cap draw that terminates the loop.
uint8_t source_tip_result(GameRandom& game, const std::array<uint8_t, 10>& gap,
int home_rating, int away_rating,
int home_secondary, int away_secondary);
} // namespace bmh
+98
View File
@@ -0,0 +1,98 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/sportschau_presentation.hpp"
#include <algorithm>
#include "game/matchday.hpp"
#include "game/messages.hpp"
#include "game/season.hpp"
#include "game/weekly.hpp"
namespace bmh {
std::optional<MatchdayIntroView> matchday_intro_view(const GameState& state,
const std::vector<MatchGroup>& groups) {
if (groups.empty() || !state.memory.has(::bmh::layout::SportschauAwards_MatchdayIntroView_RuntimeField) || state.memory.u8(::bmh::layout::SportschauAwards_MatchdayIntroView_RuntimeField) != 0)
return std::nullopt;
MatchdayIntroView view; int previous_type = 100;
for (const auto& group : groups) {
const int type = group.desc.at(0);
// Original emits every league, but only the first adjacent cup type.
if (type != 0 && type == previous_type) continue;
previous_type = type;
std::string name;
if (type == 0) {
const uint32_t league = le32(group.desc, 0xcc);
if (league >= 9) throw FormatError("matchday intro: invalid Source league");
// LeagueName with TeamStatistics_SourceLeagueName_RuntimeField=1 includes the secondary-league prefix.
name = league < 5 ? league_name(state, int(league)) :
message_text(state, ::bmh::layout::SportschauAwards_MatchdayIntroView_TextPointer) + state.club_name(0x165 + int(league) - 4);
} else {
if (type > 14) throw FormatError("matchday intro: invalid Source competition type");
name = message_text(state, ::bmh::layout::DeskState_FormatError_ExecutableField3 + uint32_t(type) * 4);
// StrcpySoHallReplacesItsCurrentTournament is strcpy, so Hall replaces its current tournament name.
if (type == 12) name = message_text(state, ::bmh::layout::MatchdayResults_CompetitionName_TextPointer);
}
view.competition_names.push_back(std::move(name));
}
return view;
}
std::string sportschau_competition_title(const GameState& state, const MatchGroup& group) {
const uint32_t id = le32(group.desc, 0xcc);
int index = int(id);
if (id > 20) index = state.memory.u8(id + 0x18) + 9;
else if (index >= 9) index = std::min(index + 12, 19);
if (index < 5) return league_name(state, index);
if (index < 9) return state.club_name(0x165 + index - 4);
return message_text(state, ::bmh::layout::CupDraw_FormatError_ExecutableField6 + uint32_t(index - 9) * 4);
}
std::optional<SportschauTeamInfoView> sportschau_team_info_view(const GameState& state,
const MatchGroup& group, int group_index) {
const int setting = sportschau_source_setting_index(state, group);
if (!state.memory.has(::bmh::layout::SportschauAwards_SportschauTeamInfoView_RuntimeField) || state.memory.u8(::bmh::layout::SportschauAwards_SportschauTeamInfoView_RuntimeField) != 0 ||
setting < 0 || setting >= 20 || !state.memory.has(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(setting) * 9) ||
state.memory.u8(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(setting) * 9) != 0) return std::nullopt;
if (group_index < 0 || group_index > 255) throw FormatError("sportschau: invalid team info group");
SportschauTeamInfoView view;
view.group = uint8_t(group_index); view.competition_id = le32(group.desc, 0xcc);
view.competition_title = sportschau_competition_title(state, group);
// Eligible C4 already guarantees SportschauIntro's any-group predicate. B7
// controls loading KB57 even when C7 suppresses the intro animation.
view.source_backdrop_available = state.memory.has(::bmh::layout::Controller_FormatError_RuntimeField) && state.memory.u8(::bmh::layout::Controller_FormatError_RuntimeField) == 0;
for (size_t i = 0; i < 4; ++i) view.totals[i] = int32_t(le32(group.desc, 0xbc + i * 4));
return view;
}
std::optional<SportschauAwardsView> finish_sportschau_awards(GameState& state,
const MatchGroup& group, int group_index) {
for (size_t i = 0; i < 11; ++i) if (group.desc.at(0x70 + i) == 0) return std::nullopt;
// The award-statistic update is movzbl [descriptor+70], not the displayed slot word.
// Preserve the Original statistic even if its presentation is disabled.
for (size_t i = 0; i < 11; ++i) {
const int manager = state.manager_of(slot_team(group.desc.at(0x70 + i)));
if (manager >= 0) {
auto& counter = state.manager_records.at(size_t(manager) * 0xb0c + 0x21e);
counter = uint8_t(counter + 1);
}
}
const int setting = sportschau_source_setting_index(state, group);
if (!state.memory.has(::bmh::layout::SportschauAwards_FinishSportschauAwards_RuntimeField) || state.memory.u8(::bmh::layout::SportschauAwards_FinishSportschauAwards_RuntimeField) != 0 ||
setting < 0 || setting >= 20 || !state.memory.has(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(setting) * 9) ||
state.memory.u8(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(setting) * 9) != 0) return std::nullopt;
if (group_index < 0 || group_index > 255) throw FormatError("sportschau: invalid awards group");
SportschauAwardsView view;
view.group = uint8_t(group_index); view.competition_id = le32(group.desc, 0xcc);
view.competition_title = sportschau_competition_title(state, group);
view.source_backdrop_available = state.memory.has(::bmh::layout::Controller_FormatError_RuntimeField) && state.memory.u8(::bmh::layout::Controller_FormatError_RuntimeField) == 0;
for (size_t i = 0; i < 11; ++i) {
auto& p = view.players[i];
p.score = group.desc.at(0x70 + i); p.squad_slot = le16(group.desc, 0x9c + i * 2);
p.player_id = state.squad_slots.at(p.squad_slot) & 0xfff;
p.team_id = int16_t(slot_team(int16_t(p.squad_slot)));
p.player_name = state.player_name(p.player_id); p.club_name = state.club_name(p.team_id);
}
return view;
}
} // namespace bmh
+218
View File
@@ -0,0 +1,218 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// Immutable, source-word-preserving input to Sportschau presentation callbacks.
// Presentation callbacks remain immutable; Source replay and award work have
// separate Core owners, independent of whether a UI observer is installed.
#include <cstdint>
#include <array>
#include <cstddef>
#include <functional>
#include <optional>
#include <vector>
#include "game/presentation.hpp"
#include "game/match_engine.hpp"
namespace bmh {
struct GameState;
struct MatchGroup;
class WatcomRandom;
class LeImage;
// MatchdayIntro walks the group's flat 16-bit log in two-word steps. The third
// word it reads is a look-ahead into the next record, and some codes consume
// that next pair as a secondary player/distance. Keep both the decoded fields
// and exact words so a presenter cannot accidentally reinterpret the stream.
struct SportschauLogEvent {
uint8_t group = 0;
uint8_t fixture = 0;
uint16_t event_ordinal = 0; // ordinal after filtering this fixture's teams
uint16_t source_word_index = 0; // index of the first word in MatchGroup::log
uint16_t source_code_player_word = 0;
uint16_t source_team_value_word = 0;
uint8_t source_code = 0; // high four bits of the first word
uint16_t player_id = 0x0fff;
int16_t team_id = -1;
uint8_t source_value = 0; // low seven bits of the second word
bool consumes_following_pair = false; // source codes 0 (goal) and 1 (miss)
bool has_following_word = false;
bool has_following_pair = false;
uint16_t following_code_player_word = 0;
uint16_t following_team_value_word = 0;
std::vector<uint8_t> player_name; // Original encoded bytes
std::vector<uint8_t> following_player_name; // empty when no valid look-ahead player
};
struct SportschauFixtureView {
uint8_t group = 0;
uint8_t fixture = 0;
uint8_t competition_type = 0;
uint8_t fixture_flags = 0;
uint8_t source_footer_variant = 0; // MatchdayIntro local_44: 0 normal,1 extra-time,2 indoor
bool has_replay_progression_mode = false;
uint8_t replay_progression_mode = 0; // saved byte; controls selected-progressive scene path
bool has_replay_chance_mode = false;
uint8_t replay_chance_mode = 0; // saved byte; controls selected scene/panel restoration
bool source_selection_available = false;
bool source_selected = false; // ResetSportschauSelection(pair,1), resolved from pre-match state
uint32_t competition_id = 0;
int16_t source_setting_index = -1; // SportschauPresentationOperation(desc,5), or -1 if unavailable
int16_t home_team = -1;
int16_t away_team = -1;
uint8_t source_played_minute = 0; // descriptor +0x04, indexed by Source fixture ordinal
uint16_t home_badge_word = 0xffff; // raw ClubBadgeSelectors u16 consumed by SourceBadgeFallback
uint16_t away_badge_word = 0xffff;
bool score_known = false;
uint8_t home_goals = 0;
uint8_t away_goals = 0;
std::vector<uint8_t> home_name; // Original encoded bytes
std::vector<uint8_t> away_name; // Original encoded bytes
std::vector<uint8_t> home_short_name; // exact ClubShortNameOffsets substring for team ids < 168
std::vector<uint8_t> away_short_name;
bool home_short_name_available = false;
bool away_short_name_available = false;
bool home_name_requires_font_fit = true; // caller trims by two bytes until FNT3 width < 48
bool away_name_requires_font_fit = true;
bool home_name_requires_longest_word = false; // TextWidth foreign-team branch, team >= 168
bool away_name_requires_longest_word = false;
std::vector<SportschauLogEvent> log_events; // Source log order, fixture-filtered
std::vector<ShowEvent> show_events; // Distinct live-animation stream, not the report log
};
struct SportschauCompetitionView {
uint8_t group = 0;
uint8_t type = 0;
uint32_t id = 0;
int16_t source_setting_index = -1;
};
struct SportschauIntroView {
int group_index = -1; // -1 post-simulation, otherwise a Source group-entry point
std::vector<SportschauCompetitionView> groups;
};
// FinishEvent's pre-play KB136 competition list, independent of report selection.
struct MatchdayIntroView {
std::vector<std::string> competition_names; // Original encoded bytes
};
using MatchdayIntroHook = std::function<void(const GameState&, const MatchdayIntroView&)>;
std::optional<MatchdayIntroView> matchday_intro_view(const GameState&,
const std::vector<MatchGroup>&);
// Intro gets all group competition ids so App can evaluate Source's global
// setting-matrix eligibility test without guessing from the current fixture.
using SportschauIntroHook = std::function<void(const GameState&, const SportschauIntroView&)>;
using SportschauFixtureHook = std::function<void(const GameState&, const SportschauFixtureView&)>;
struct SportschauAwardPlayer {
uint16_t squad_slot = 0, player_id = 0x0fff;
int16_t team_id = -1;
uint8_t score = 0;
std::string player_name, club_name; // Original encoded bytes
};
struct SportschauAwardsView {
uint8_t group = 0;
uint32_t competition_id = 0;
std::string competition_title; // Void4, Original encoded bytes
bool source_backdrop_available = true; // SportschauIntro/5c1c7, independent of C7 animation
std::array<SportschauAwardPlayer, 11> players;
};
using SportschauAwardsHook = std::function<void(const GameState&, const SportschauAwardsView&)>;
// SportschauEleven: complete-eleven gate, Source manager counter, then pure viewer input.
// The statistic reads the score byte as a slot (confirmed in x86), whereas
// the displayed names use the separate u16 squad-slot array at descriptor+9c.
std::optional<SportschauAwardsView> finish_sportschau_awards(GameState& state,
const MatchGroup& group, int group_index);
struct SportschauTeamInfoView {
uint8_t group = 0;
uint32_t competition_id = 0;
std::string competition_title;
bool source_backdrop_available = true;
// Source descriptor +bc,+c0,+c4,+c8: yellow, red, spectators, goals.
std::array<int32_t, 4> totals{};
};
using SportschauTeamInfoHook = std::function<void(const GameState&, const SportschauTeamInfoView&)>;
std::string sportschau_competition_title(const GameState& state, const MatchGroup& group);
std::optional<SportschauTeamInfoView> sportschau_team_info_view(const GameState& state,
const MatchGroup& group, int group_index);
struct SportschauReportStep {
size_t visible_log_entries = 0;
uint8_t progress_minute = 0;
bool minute_wait = false;
bool chance_wait = false;
bool terminal_wait = false;
};
std::vector<SportschauReportStep> sportschau_report_steps(const SportschauFixtureView& fixture);
struct SportschauSceneView {
SportschauReportStep report_step;
int home_goals_before = 0, away_goals_before = 0;
std::vector<MatchGroup> groups; // owned single-group context; shot.group ==0
std::optional<LiveSetPieceEvent> set_piece;
LiveShotEvent shot;
};
struct SportschauReplayHooks {
// Return only the Source left=2 latch; Core applies it after a minute wait.
std::function<bool(const GameState&, const SportschauFixtureView&, const SportschauReportStep&)> step;
std::function<void(const GameState&, const SportschauFixtureView&, const SportschauSceneView&)> scene;
};
// CompetitionWinnerScreen(param1=0), called at title settlement before title-history writes.
struct CompetitionWinnerView { uint8_t title = 0; uint16_t team = 0; };
using CompetitionWinnerHook = std::function<void(const GameState&, const CompetitionWinnerView&)>;
struct SportschauPresentationHooks {
CompetitionWinnerHook winner;
MatchdayIntroHook kickoff;
SportschauIntroHook intro;
SportschauFixtureHook fixture;
SportschauReplayHooks replay;
SportschauAwardsHook awards;
SportschauTeamInfoHook team_info;
};
struct SportschauRatingTables {
std::array<int8_t, 4> position_limit{}, opponent_misses{}, chance_actor{}, own_chances{}, scorer_bonus{};
std::array<uint8_t, 4> award_begin{}, award_end{};
uint16_t domestic_teams = 0;
};
SportschauRatingTables sportschau_rating_tables(const LeImage& exe);
// MatchdayIntro, after replay and before morale/development. Updates eleven Source
// award scores and global squad-slot ids in the group's descriptor, not players.
void rate_sportschau_players(const GameState& state, MatchGroup& group,
const SportschauFixtureView& fixture, WatcomRandom& rand, const SportschauRatingTables& tables);
struct SportschauSourceOptions {
uint8_t intro_after_matchday = 0; // unsaved EXE byte CareerSession_SportschauSourceOptions_ExecutableField
uint8_t intro_each_group = 0; // unsaved EXE byte CareerSession_DispatchTransferOffer_ExecutableField2
uint16_t rated_club_threshold = 90; // EXE TeamsWithSquads, ResetSportschauSelection's extra fifty points
std::optional<SportschauRatingTables> ratings; // loaded EXE policy, not FBM data
};
// Read-only projection for one already-completed fixture. Source's flat log is
// filtered by the two fixture teams, while its pair stride and look-ahead words
// remain intact. This helper does not mutate Native state or either RNG.
SportschauFixtureView sportschau_fixture_view(const GameState& state, const MatchGroup& group,
int group_index, int fixture_index,
const std::vector<ShowEvent>& show_events);
int sportschau_source_setting_index(const GameState& state, const MatchGroup& group);
// ResetSportschauSelection modes0/2/1. Only the pre-match caller may rate candidates; foreign
// teams consume the real Watcom generator even with capacity A8 ==0.
void reset_sportschau_selection(GameState& state);
bool consider_sportschau_fixture(GameState& state, const MatchGroup& group,
int home, int away, WatcomRandom& rand);
bool sportschau_selected(const GameState& state, int home);
// MatchdayIntro/ShotAnimation: owns scene draws between table updates and morale.
// With no UI callbacks, it still consumes the same enabled Source scene work.
void present_sportschau_replay(GameState& state, const MatchGroup& group,
const SportschauFixtureView& fixture, GameRandom& game, WatcomRandom& rand,
const SportschauReplayHooks& hooks);
} // namespace bmh
+113
View File
@@ -0,0 +1,113 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/sportschau_presentation.hpp"
#include <algorithm>
#include <bit>
#include "formats/le.hpp"
namespace bmh {
SportschauRatingTables sportschau_rating_tables(const LeImage& exe) {
SportschauRatingTables t;
t.domestic_teams = exe.u16(::bmh::layout::CareerSession_DispatchLineup_RuntimeField);
for (size_t i = 0; i < 4; ++i) {
const auto offset = uint32_t(i);
t.position_limit[i] = std::bit_cast<int8_t>(exe.u8(::bmh::layout::SportschauRating_SportschauRatingTables_RuntimeField + offset));
t.opponent_misses[i] = std::bit_cast<int8_t>(exe.u8(::bmh::layout::SportschauRating_SportschauRatingTables_RuntimeField2 + offset));
t.chance_actor[i] = std::bit_cast<int8_t>(exe.u8(::bmh::layout::SportschauRating_SportschauRatingTables_RuntimeField3 + offset));
t.own_chances[i] = std::bit_cast<int8_t>(exe.u8(::bmh::layout::SportschauRating_SportschauRatingTables_RuntimeField4 + offset));
t.scorer_bonus[i] = std::bit_cast<int8_t>(exe.u8(::bmh::layout::SportschauRating_SportschauRatingTables_RuntimeField5 + offset));
t.award_begin[i] = exe.u8(::bmh::layout::SportschauRating_SportschauRatingTables_RuntimeField6 + offset);
t.award_end[i] = exe.u8(::bmh::layout::SportschauRating_SportschauRatingTables_RuntimeField7 + offset);
if (t.award_begin[i] >= t.award_end[i] || t.award_end[i] > 11 ||
(i && t.position_limit[i] <= t.position_limit[i - 1]))
throw FormatError("sportschau: invalid executable award tables");
}
return t;
}
void rate_sportschau_players(const GameState& state, MatchGroup& group,
const SportschauFixtureView& fixture, WatcomRandom& rand, const SportschauRatingTables& t) {
// F7, D7, E7 and selected status only gate presentation. G7/C4 gate the
// rating even with the report hidden or skipped (5cd8a, 5c389).
if (!state.memory.has(::bmh::layout::SportschauAwards_FinishSportschauAwards_RuntimeField) || state.memory.u8(::bmh::layout::SportschauAwards_FinishSportschauAwards_RuntimeField) != 0 ||
fixture.source_setting_index < 0 || fixture.source_setting_index > 19 ||
!state.memory.has(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(fixture.source_setting_index) * 9) ||
state.memory.u8(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(fixture.source_setting_index) * 9) != 0) return;
struct Actors {
uint8_t goals = 0, misses = 0;
std::vector<uint16_t> scorers, assistants, missed;
};
std::array<Actors, 2> actors;
auto add = [](std::vector<uint16_t>& ids, uint16_t id) {
if (ids.size() < 12) ids.push_back(id); // independent twelve-entry buffers
};
for (size_t i = 0; i + 1 < group.log.size(); i += 2) {
const int team = group.log[i + 1] >> 7;
if (team != fixture.home_team && team != fixture.away_team) continue;
auto& a = actors[size_t(team == fixture.away_team)];
const int code = group.log[i] >> 12;
const uint16_t player = group.log[i] & 0xfff;
if (code > 1) continue;
if (code == 0) { ++a.goals; add(a.scorers, player); }
else { ++a.misses; add(a.missed, player); }
const bool following = i + 2 < group.log.size();
const int following_code = following ? group.log[i + 2] >> 12 : 0;
const int kind = following && following_code > 6 ? following_code - 6 : 0;
i += 2; // both chance codes consume the next record, regardless of its team
if (i < group.log.size() && (following_code < 3 || following_code > 6)) {
const uint16_t assistant = group.log[i] & 0xfff;
if (assistant != 0xfff && (kind == 0 || kind == 3)) add(a.assistants, assistant);
}
}
for (size_t side = 0; side < 2; ++side) {
const int team = side ? fixture.away_team : fixture.home_team;
if (team < 0 || team >= t.domestic_teams) continue;
const auto squad = squad_range(team);
const auto& a = actors[side]; const auto& opponent = actors[1 - side];
for (size_t row = 0; row < squad.count; ++row) {
const uint16_t id = state.squad_slots.at(squad.first + row) & 0xfff;
if (id == 0xfff) continue;
const uint32_t flags = state.players.at(id).w364;
if ((flags & 0x1000) == 0 || ((flags >> 16) & 0x1f) != 0) continue;
int16_t score = int16_t(rand.range(0, 7) + 5);
int depth = 0, lane = 0;
state.formation_position(team, int(row), depth, lane);
size_t profile = 0;
while (profile < 4 && depth >= t.position_limit[profile]) ++profile;
if (profile == 4) throw FormatError("sportschau: formation depth outside award profiles");
auto plus = [&](int value) { score = std::bit_cast<int16_t>(uint16_t(uint16_t(score) + value)); };
plus((int(opponent.misses) - int(opponent.goals)) * t.opponent_misses[profile]);
int goals = 0;
if (t.chance_actor[profile]) {
if (profile == 1) plus(rand.range(0, 4));
goals = int(std::count(a.scorers.begin(), a.scorers.end(), id));
const int assists = int(std::count(a.assistants.begin(), a.assistants.end(), id));
const int misses = int(std::count(a.missed.begin(), a.missed.end(), id));
plus((goals + assists - misses) * t.chance_actor[profile]);
}
// SportschauRating_SportschauRatingTables_RuntimeField4 is a predicate, not a multiplier (5cf77..5cf8e).
if (t.own_chances[profile]) plus(int(a.goals) + int(a.misses));
plus(goals * t.scorer_bonus[profile]);
int minimum = 120; size_t selected = 0;
for (size_t slot = t.award_begin[profile]; slot < t.award_end[profile]; ++slot) {
const int prior = group.desc.at(0x70 + slot);
if (prior < minimum) { minimum = prior; selected = slot; }
}
// Equal scores replace the first minimum; score storage wraps to
// one byte. The u16 identity is a GLOBAL squad slot, not a player id.
if (score >= minimum) {
group.desc.at(0x70 + selected) = uint8_t(score);
const uint16_t slot = uint16_t(squad.first + row);
group.desc.at(0x9c + selected * 2) = uint8_t(slot);
group.desc.at(0x9d + selected * 2) = uint8_t(slot >> 8);
}
}
}
}
} // namespace bmh
+80
View File
@@ -0,0 +1,80 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/sportschau_presentation.hpp"
namespace bmh {
std::vector<SportschauReportStep> sportschau_report_steps(const SportschauFixtureView& fixture) {
std::vector<SportschauReportStep> steps{{0, 0, false, false}};
uint16_t cursor = 1;
size_t visible = 0;
int baseline = 66;
while (visible < fixture.log_events.size()) {
const auto& event = fixture.log_events[visible];
while (cursor < event.source_value)
steps.push_back({visible, uint8_t(cursor++), true, false});
++visible;
if (event.consumes_following_pair && visible < fixture.log_events.size() &&
fixture.log_events[visible].source_word_index == event.source_word_index + 2)
++visible;
if (baseline < 179)
steps.push_back({visible, uint8_t(cursor - 1), false, event.source_code < 2});
if (event.source_code != 1) baseline += 7;
}
while (cursor <= fixture.source_played_minute)
steps.push_back({visible, uint8_t(cursor++), true, false, true});
return steps;
}
void present_sportschau_replay(GameState& state, const MatchGroup& group,
const SportschauFixtureView& fixture, GameRandom& game, WatcomRandom& rand,
const SportschauReplayHooks& hooks) {
if (!fixture.source_selection_available || !fixture.source_selected ||
!fixture.has_replay_progression_mode || fixture.replay_progression_mode != 0 ||
!state.memory.has(::bmh::layout::Controller_FormatError_RuntimeField3) || state.memory.u8(::bmh::layout::Controller_FormatError_RuntimeField3) != 0 ||
fixture.source_setting_index < 0 || fixture.source_setting_index > 19 ||
!state.memory.has(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(fixture.source_setting_index) * 9) ||
state.memory.u8(::bmh::layout::Controller_FormatError_ExecutableField2 + uint32_t(fixture.source_setting_index) * 9) != 0) return;
bool progressive = true;
for (const auto& step : sportschau_report_steps(fixture)) {
if (!progressive) continue;
const bool skip = hooks.step && hooks.step(state, fixture, step);
if (step.minute_wait && !step.terminal_wait && skip) progressive = false;
if (!step.chance_wait || !progressive || !fixture.has_replay_chance_mode || fixture.replay_chance_mode != 0)
continue;
const SportschauLogEvent* chance = nullptr;
int home_before = 0, away_before = 0;
for (size_t i = 0; i < step.visible_log_entries; ++i) {
const auto& event = fixture.log_events[i];
const bool paired = event.consumes_following_pair && i + 1 < step.visible_log_entries &&
fixture.log_events[i + 1].source_word_index == event.source_word_index + 2;
if (i + (paired ? 2 : 1) == step.visible_log_entries) chance = &event;
else if (event.source_code == 0) {
if (event.team_id == fixture.home_team) ++home_before; else ++away_before;
}
if (paired) ++i;
}
if (!chance || chance->source_code > 1 || chance->group != fixture.group ||
chance->fixture != fixture.fixture || (chance->team_id != fixture.home_team &&
chance->team_id != fixture.away_team)) throw FormatError("sportschau: invalid Source chance owner");
const int side = chance->team_id == fixture.home_team ? 0 : 1;
const int kind = chance->has_following_word && (chance->following_code_player_word >> 12) > 6
? (chance->following_code_player_word >> 12) - 6 : 0;
if (kind > 3) throw FormatError("sportschau: unsupported Source set-piece code");
SportschauSceneView scene;
scene.report_step = step;
scene.home_goals_before = home_before; scene.away_goals_before = away_before;
scene.groups = {group};
std::vector<uint8_t> referees;
MatchEngine engine{state, scene.groups, game, rand, referees};
engine.live_set_piece = [&](const LiveSetPieceEvent& event) { scene.set_piece = event; };
engine.live_shot = [&](const LiveShotEvent& event) { scene.shot = event; };
if (kind) engine.set_piece_animation(kind, 0, 1 - side, 0, fixture.fixture, chance->source_value);
engine.shot_animation(chance->source_code == 1, kind == 2, side, 0, fixture.fixture, chance->source_value);
// The presentation adapter owns the unsaved music/ambience transition;
// the replay itself introduces no sound-related RNG or Native writes.
if (hooks.scene) hooks.scene(state, fixture, scene);
}
}
} // namespace bmh
+167
View File
@@ -0,0 +1,167 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "game/stadium_blocks.hpp"
#include "game/matchday.hpp"
#include <algorithm>
#include <limits>
namespace bmh {
namespace {
constexpr size_t kRecordSize = 0xb0c;
constexpr size_t kManagerClub = 0x290;
constexpr size_t kBuild = 0x34;
constexpr size_t kFlags = 0x44;
constexpr size_t kCapacity = 0x4c;
constexpr size_t kFutureCapacity = 0x54;
constexpr uint8_t kSeat = 1;
constexpr uint8_t kRoof = 2;
constexpr uint8_t kKnownFeatures = kSeat | kRoof;
bool slot_index(StadiumBlockSlot slot, size_t& out) {
const auto raw = static_cast<uint8_t>(slot);
if (raw >= 8) return false;
out = raw;
return true;
}
uint16_t record_u16(const std::vector<uint8_t>& records, size_t at) {
return uint16_t(records.at(at)) | uint16_t(records.at(at + 1)) << 8;
}
std::optional<uint32_t> checked_component(uint32_t price_per_1000, uint32_t places,
uint32_t multiplier, uint32_t divisor) {
const uint64_t units = places / 1000;
const uint64_t multiplied = uint64_t(price_per_1000) * units * multiplier;
if (multiplied > uint64_t(std::numeric_limits<int32_t>::max())) return std::nullopt;
return uint32_t(multiplied / divisor);
}
bool valid_resolved_offer(const StandBlockOffer& offer, const StadiumBlockExpansionQuote& quote) {
if (offer.percent < 6 || offer.percent > 14 || offer.base_price != quote.base_price ||
offer.base_days != quote.base_weeks || offer.base_days < 0 || offer.base_days > 255 ||
offer.offered_price != uint32_t(uint64_t(quote.base_price) * uint32_t(100 + offer.percent) / 100) ||
offer.price > uint32_t(std::numeric_limits<int32_t>::max()))
return false;
switch (offer.decision) {
case StandBlockOfferDecision::Declined:
return offer.price == offer.base_price && offer.construction_days == offer.base_days;
case StandBlockOfferDecision::Accepted:
// PrepareStandBlockOffer forms base_price * (100 + percent) in a signed
// 32-bit intermediate before dividing by 100. Do not accept a
// mathematically representable final uint32 when that Source
// intermediate would overflow. Declined offers do not use it.
return uint64_t(quote.base_price) * uint32_t(100 + offer.percent) <=
uint64_t(std::numeric_limits<int32_t>::max()) &&
offer.price == offer.offered_price &&
offer.construction_days <= offer.base_days - (offer.base_days >> 3) &&
offer.construction_days >= offer.base_days - (offer.base_days >> 1);
case StandBlockOfferDecision::Pending:
default:
return false;
}
}
} // namespace
std::optional<StadiumBlockExpansionQuote> quote_stadium_block_expansion(
const GameState& g, int manager, StadiumBlockSlot slot, uint32_t total_target_places,
uint8_t desired_features, int company_price_percent,
const StadiumBlockExpansionConstants& constants) {
size_t block = 0;
if (!slot_index(slot, block) || manager < 0 ||
size_t(manager) >= g.manager_teams.size() ||
(size_t(manager) + 1) * kRecordSize > g.manager_records.size())
return std::nullopt;
const int club = g.manager_teams[size_t(manager)];
const size_t rec = size_t(manager) * kRecordSize;
if (club < 0 || club == kNoTeam || record_u16(g.manager_records, rec + kManagerClub) != uint16_t(club))
return std::nullopt;
const uint8_t build_weeks = g.manager_records.at(rec + kBuild + block);
const uint8_t raw_flags = g.manager_records.at(rec + kFlags + block);
const uint8_t current_capacity = g.manager_records.at(rec + kCapacity + block);
const uint8_t future_capacity = g.manager_records.at(rec + kFutureCapacity + block);
const uint32_t maximum = constants.max_places[block];
const uint32_t unit_price = constants.price_per_1000[block];
const uint8_t duration = constants.weeks[block];
// Active construction and idle unknown bits are not editable A–H source states.
if (build_weeks != 0 || (raw_flags & uint8_t(~kKnownFeatures)) != 0 ||
(desired_features & uint8_t(~kKnownFeatures)) != 0 ||
(desired_features & uint8_t(raw_flags & kKnownFeatures)) != uint8_t(raw_flags & kKnownFeatures) ||
company_price_percent < 0 || company_price_percent > 427 || unit_price == 0 ||
maximum == 0 || maximum > 255000 || maximum % 1000 != 0 || duration == 0)
return std::nullopt;
const uint32_t current_places = uint32_t(current_capacity) * 1000;
if (total_target_places < current_places || total_target_places > maximum ||
total_target_places / 1000 > 255)
return std::nullopt;
const uint32_t new_places = total_target_places - current_places;
const auto new_cost = checked_component(unit_price, new_places, 1, 1);
if (!new_cost) return std::nullopt;
const uint32_t seats_places = (raw_flags & kSeat) != 0 ? new_places : total_target_places;
const uint32_t roof_places = (raw_flags & kRoof) != 0 ? new_places : total_target_places;
const auto seats_cost = (desired_features & kSeat) != 0
? checked_component(unit_price, seats_places, 45, 100) : std::optional<uint32_t>(0);
const auto roof_cost = (desired_features & kRoof) != 0
? checked_component(unit_price, roof_places, 30, 100) : std::optional<uint32_t>(0);
if (!seats_cost || !roof_cost) return std::nullopt;
const uint64_t sum = uint64_t(*new_cost) + *seats_cost + *roof_cost;
if (sum > uint64_t(std::numeric_limits<int32_t>::max()) ||
sum * uint32_t(company_price_percent) > uint64_t(std::numeric_limits<int32_t>::max()))
return std::nullopt;
const uint32_t price = uint32_t(sum * uint32_t(company_price_percent) / 100);
StadiumBlockExpansionQuote quote;
quote.manager = manager;
quote.manager_club = club;
quote.slot = slot;
quote.current_build_weeks = build_weeks;
quote.current_raw_flags = raw_flags;
quote.current_capacity_thousands = current_capacity;
quote.current_future_capacity_thousands = future_capacity;
quote.total_target_places = total_target_places;
quote.desired_features = desired_features;
quote.company_price_percent = company_price_percent;
quote.price_per_1000 = unit_price;
quote.max_places = maximum;
quote.new_places = new_places;
quote.new_places_cost = *new_cost;
quote.seats_cost = *seats_cost;
quote.roof_cost = *roof_cost;
quote.undiscounted_cost = uint32_t(sum);
quote.base_price = price;
quote.base_weeks = duration;
return quote;
}
bool build_stadium_block_expansion(
GameState& g, int manager, StadiumBlockSlot slot,
const StadiumBlockExpansionConstants& constants,
const StadiumBlockExpansionQuote& quote, const StandBlockOffer& resolved_offer,
WatcomRandom& rand, const ConstructionNoticeHook& payment_notice,
const SeasonTicketCompensationNoticeHook& compensation_notice) {
if (manager != quote.manager || slot != quote.slot || quote.base_price == 0 ||
!valid_resolved_offer(resolved_offer, quote))
return false;
const auto fresh = quote_stadium_block_expansion(g, manager, slot, quote.total_target_places,
quote.desired_features, quote.company_price_percent, constants);
if (!fresh || *fresh != quote) return false;
// Sponsor is always false for Original A–H construction. In particular this
// preserves +0x171 and prevents pay_construction's sponsor-only W draws.
if (!pay_construction(g, manager, resolved_offer.price, false, rand, payment_notice)) return false;
const size_t rec = size_t(manager) * kRecordSize;
const size_t block = static_cast<uint8_t>(slot);
g.manager_records.at(rec + kBuild + block) = resolved_offer.construction_days;
g.manager_records.at(rec + kFlags + block) = uint8_t(
g.manager_records.at(rec + kFlags + block) | uint8_t(quote.desired_features << 4));
g.manager_records.at(rec + kFutureCapacity + block) = uint8_t(quote.total_target_places / 1000);
season_ticket_compensation_source(g, manager, compensation_notice);
return true;
}
} // namespace bmh
+72
View File
@@ -0,0 +1,72 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "game/desk_actions.hpp"
#include "game/weekly.hpp"
#include <array>
#include <cstdint>
#include <optional>
namespace bmh {
// Source choices 8..15 map to eight independent A–H record slots. These must
// not be confused with StadiumInvestment's facilities 0..7.
enum class StadiumBlockSlot : uint8_t { A = 0, B, C, D, E, F, G, H };
struct StadiumBlockExpansionConstants {
std::array<uint32_t, 8> price_per_1000{};
std::array<uint8_t, 8> weeks{};
std::array<uint32_t, 8> max_places{};
};
// An immutable quote binds the Source owner and every record/table value that
// affects the quote. Commit recomputes this value before it touches money.
struct StadiumBlockExpansionQuote {
int manager = -1;
int manager_club = -1;
StadiumBlockSlot slot = StadiumBlockSlot::A;
uint8_t current_build_weeks = 0;
uint8_t current_raw_flags = 0;
uint8_t current_capacity_thousands = 0;
uint8_t current_future_capacity_thousands = 0;
uint32_t total_target_places = 0;
uint8_t desired_features = 0; // Source low bits: seats=1, roof=2.
int company_price_percent = 0;
uint32_t price_per_1000 = 0;
uint32_t max_places = 0;
uint32_t new_places = 0;
uint32_t new_places_cost = 0;
uint32_t seats_cost = 0;
uint32_t roof_cost = 0;
uint32_t undiscounted_cost = 0;
uint32_t base_price = 0;
uint8_t base_weeks = 0;
bool operator==(const StadiumBlockExpansionQuote&) const = default;
};
// Pure Source projection. Manual totals need not be multiples of 1000; only the
// eventual +54 byte is floored to thousands. The supported source boundary is
// 0..427 company percent, 0..255 thousand places, a positive duration, and
// trusted table maxima <=255000. Current/target placement must satisfy
// current<=target<=maximum; busy blocks, unknown idle feature bits, owner
// mismatches, disabled existing features, malformed constants and any
// intermediate that overflows Source's signed 32-bit arithmetic have no quote.
// A valid zero-price quote remains previewable; commit refuses to construct it.
std::optional<StadiumBlockExpansionQuote> quote_stadium_block_expansion(
const GameState& g, int manager, StadiumBlockSlot slot, uint32_t total_target_places,
uint8_t desired_features, int company_price_percent,
const StadiumBlockExpansionConstants& constants);
// Commit an already resolved tip decision exactly once. `Declined` proceeds at
// the base quote; `Accepted` uses its precomputed price and weeks. A zero-price
// quote never constructs. Notice exceptions propagate so the caller can restore
// its full transaction checkpoint.
bool build_stadium_block_expansion(
GameState& g, int manager, StadiumBlockSlot slot,
const StadiumBlockExpansionConstants& constants,
const StadiumBlockExpansionQuote& quote, const StandBlockOffer& resolved_offer,
WatcomRandom& rand, const ConstructionNoticeHook& payment_notice = {},
const SeasonTicketCompensationNoticeHook& compensation_notice = {});
} // namespace bmh
+232
View File
@@ -0,0 +1,232 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/state.hpp"
#include <stdexcept>
#include "game/rating.hpp"
namespace bmh {
namespace {
// Squad table layout constants of V2.24 (TeamsWithSquads, LargeSquadClubCount, NoTeamSquadStart).
constexpr int kBigSquadTeams = 90;
constexpr size_t kNoTeamSquadStart = 3072;
constexpr int kTeamsWithSquads = 168;
// C-style signed division by 8 as compiled by Watcom (rounds toward zero).
int div8(int x) { return x / 8; }
} // namespace
GameState GameState::from_save(const SaveState& save, const DbCounts& c) {
GameState g;
const SaveBlock& squads = save.block(::bmh::layout::SquadSlots);
for (size_t i = 0; i + 1 < squads.size; i += 2)
g.squad_slots.push_back(uint16_t(save.data(::bmh::layout::SquadSlots)[i] | save.data(::bmh::layout::SquadSlots)[i + 1] << 8));
auto word = [&](uint32_t block, size_t i) {
const uint8_t* p = save.data(block) + i * 4;
return uint32_t(p[0] | p[1] << 8 | p[2] << 16 | uint32_t(p[3]) << 24);
};
g.players.resize(c.players);
for (size_t i = 0; i < c.players; i++)
g.players[i] = Player{"", word(::bmh::layout::PlayerConditionTechniqueForm, i), word(::bmh::layout::PlayerSkillWords, i), word(::bmh::layout::PlayerIdentityWords, i)};
const SaveBlock& morale = save.block(::bmh::layout::TeamMorale);
g.team_morale.assign(save.data(::bmh::layout::TeamMorale), save.data(::bmh::layout::TeamMorale) + morale.size);
const SaveBlock& flags = save.block(::bmh::layout::TeamFlags);
for (size_t i = 0; i + 1 < flags.size; i += 2)
g.team_flags.push_back(uint16_t(save.data(::bmh::layout::TeamFlags)[i] | save.data(::bmh::layout::TeamFlags)[i + 1] << 8));
const SaveBlock& bonus = save.block(::bmh::layout::PlayerBonuses);
g.player_bonus.assign(save.data(::bmh::layout::PlayerBonuses), save.data(::bmh::layout::PlayerBonuses) + bonus.size);
const SaveBlock& form = save.block(::bmh::layout::Formations);
g.formations.assign(save.data(::bmh::layout::Formations), save.data(::bmh::layout::Formations) + form.size);
// Manager records: 5 x 0xB0C bytes, the team id is the i16 at +0x290.
int managers = save.data(::bmh::layout::ManagerCount)[0];
for (int m = 0; m < managers; m++) {
const uint8_t* p = save.data(::bmh::layout::ManagerRecords) + m * 0xB0C + 0x290;
g.manager_teams.push_back(int16_t(p[0] | p[1] << 8));
}
g.manager_records.assign(save.data(::bmh::layout::ManagerRecords), save.data(::bmh::layout::ManagerRecords) + save.block(::bmh::layout::ManagerRecords).size);
g.tactics.assign(save.data(::bmh::layout::TacticsBoards), save.data(::bmh::layout::TacticsBoards) + save.block(::bmh::layout::TacticsBoards).size);
g.level = save.data(::bmh::layout::Difficulty)[0];
g.manager_options.assign(save.data(::bmh::layout::ManagerAutomation), save.data(::bmh::layout::ManagerAutomation) + save.block(::bmh::layout::ManagerAutomation).size);
// Matchday bookkeeping. The club records are dumped twice (pointer, then the heap
// data if the pointer was set); the heap copy is the one needed.
for (const SaveBlock& b : save.blocks())
if (b.address == ::bmh::layout::TournamentName && b.heap)
g.tournament_name.assign(save.stream().begin() + b.offset, save.stream().begin() + b.offset + b.size);
else if (b.address == ::bmh::layout::ClubSeasonRecords && b.heap)
g.club_table.assign(save.stream().begin() + b.offset, save.stream().begin() + b.offset + b.size);
else if (b.heap && (b.address == ::bmh::layout::ClubAuxiliaryWords || b.address == ::bmh::layout::ClubBadgeSelectors || b.address == ::bmh::layout::ClubAuxiliaryBytes)) {
auto& v = b.address == ::bmh::layout::ClubAuxiliaryWords ? g.club_heap_bc : b.address == ::bmh::layout::ClubBadgeSelectors ? g.club_heap_78 : g.club_heap_b8;
v.assign(save.stream().begin() + b.offset, save.stream().begin() + b.offset + b.size);
} else if (b.heap && b.address == ::bmh::layout::MasterDatabaseMetadata) {
g.master_database_metadata.assign(save.stream().begin() + b.offset, save.stream().begin() + b.offset + b.size);
}
auto words16 = [&](uint32_t address) {
std::vector<uint16_t> v;
const SaveBlock& b = save.block(address);
for (size_t i = 0; i + 1 < b.size; i += 2) v.push_back(uint16_t(save.data(address)[i] | save.data(address)[i + 1] << 8));
return v;
};
g.club_ids = words16(::bmh::layout::ClubIdentities);
g.player_cards = words16(::bmh::layout::PlayerCards);
auto u32at = [&](uint32_t address) {
const uint8_t* p = save.data(address);
return uint32_t(p[0] | p[1] << 8 | p[2] << 16 | uint32_t(p[3]) << 24);
};
g.date = u32at(::bmh::layout::CalendarDay);
g.season_start = g.date - uint32_t(save.data(::bmh::layout::DaysIntoSeason)[0] | save.data(::bmh::layout::DaysIntoSeason)[1] << 8);
g.development_balance = int32_t(u32at(::bmh::layout::PlayerDevelopmentBalance));
// PlayerTrendRotation is not saved; it restarts at its initial value 0 after loading.
auto bytes = [&](uint32_t address) {
return std::vector<uint8_t>(save.data(address), save.data(address) + save.block(address).size);
};
g.manager_results = bytes(::bmh::layout::ManagerMatchHistory);
g.manager_ratings = bytes(::bmh::layout::ManagerRatings);
g.position_history = bytes(::bmh::layout::LeagueRankHistory);
g.league_rounds = bytes(::bmh::layout::LeagueRoundCounters);
g.results = bytes(::bmh::layout::LeagueResults);
g.stocks = bytes(::bmh::layout::StockExchange);
g.foreign_strength = bytes(::bmh::layout::ForeignClubStrength);
g.memory = StaticMemory(save);
// memory OpenBMH saves behind the trailer (the English cup blocks, career.hpp)
for (const auto& b : save.extension()) {
if (!g.memory.has(b.address)) g.memory.add_block(b.address, uint32_t(b.bytes.size()));
for (size_t i = 0; i < b.bytes.size(); ++i) g.memory.set8(b.address + uint32_t(i), b.bytes[i]);
}
g.mailbox = bytes(::bmh::layout::ManagerMailbox);
g.club_names = save.pool(0);
g.player_names = save.pool(1);
g.referee_names = save.pool(2);
g.stadium_names = save.pool(3);
g.player_name_offsets = words16(::bmh::layout::PlayerNameOffsets);
g.season = int16_t(save.data(::bmh::layout::SeasonIndex)[0] | save.data(::bmh::layout::SeasonIndex)[1] << 8);
return g;
}
int GameState::manager_of(int team) const {
for (size_t m = 0; m < manager_teams.size(); m++)
if (manager_teams[m] == team) return int(m);
return -1;
}
std::string GameState::club_name(int team) const {
team &= 0xFFF;
if (team == 0xFFF) return texts ? (*texts)[(::bmh::layout::NoClubText - ::bmh::layout::TextPointerTable) / 4] : std::string();
std::string s;
for (size_t i = club_ids.at(size_t(team)); i < club_names.size() && club_names[i] != 0; i++) s.push_back(char(club_names[i]));
return s;
}
std::string GameState::player_name(int player) const {
player &= 0xFFF;
if (player == 0xFFF) return texts ? (*texts)[(::bmh::layout::NoPlayerText - ::bmh::layout::TextPointerTable) / 4] : std::string();
std::string s;
for (size_t i = player_name_offsets.at(size_t(player)); i < player_names.size() && player_names[i] != 0; i++)
s.push_back(char(player_names[i]));
return s;
}
int GameState::formation(int team) const {
// FormationPosition: bit 4 selects bits 10-11 instead of bits 8-9
unsigned v = team_flags.at(team);
return int(v >> (((v >> 4) & 1) * 2 + 8) & 3);
}
void GameState::formation_position(int team, int slot, int& x, int& y) const {
int manager = manager_of(team);
if (manager >= 0) {
size_t at = size_t(manager) * 0x840 + size_t(slot) * 0x58;
x = int8_t(tactics.at(at + 0x41));
y = int8_t(tactics.at(at + 0x42));
return;
}
size_t base = (indoor ? 0xB0 : 0) + size_t(formation(team)) * 0x16 + size_t(slot);
x = formations.at(base);
y = formations.at(base + 11);
}
SquadRange squad_range(int team) {
if (team == kNoTeam) return {kNoTeamSquadStart, 24};
if (team < kBigSquadTeams) return {size_t(team) * 24, 24};
if (team < 138) return {size_t(team) * 16 + kBigSquadTeams * 8, 16};
return {0, 0};
}
TeamAverage team_average(const GameState& g, int team, uint16_t flags, WatcomRandom* rand) {
if (team >= kTeamsWithSquads && team != kNoTeam) {
// TeamRating(team, profile 2 at layout field): a random value around the club's level
if (!rand) throw std::invalid_argument("team_average: a team without squad needs the Watcom generator");
RatingContext ctx;
ctx.rand = rand;
TeamAverage r;
r.value = team_rating(const_cast<GameState&>(g), team, kRatingProfiles[2], ctx);
r.players = 0;
return r;
}
TeamAverage r;
int sum_condition = 0, sum_technique = 0, sum_form = 0, sum_morale = 0;
int counted = 0; // "local_14" in the original, a byte
SquadRange range = squad_range(team);
for (size_t s = range.first; s < range.first + range.count; s++) {
uint16_t slot = g.squad_slots.at(s);
if (slot == kEmptySlot) continue;
if ((flags & avg::LINEUP_ONLY) && !(slot & kSlotInLineup)) continue;
const Player& p = g.players.at(slot & 0x0FFF);
if ((flags & avg::FIT_ONLY) && (p.w364 >> 16 & 0x1F) != 0) continue;
// position filter: bit (position + 4) of the flags, evaluated on the signed flags
if (!((int16_t(flags) >> (p.position() + 4)) & 1)) continue;
int half = 0; // KO + TE of this player, for best_half_sum
if (flags & avg::CONDITION) {
half = p.condition();
sum_condition += p.condition();
}
if (flags & avg::TECHNIQUE) {
half += p.technique();
sum_technique += p.technique();
}
if (flags & avg::FORM) sum_form += p.form();
if (flags & avg::MORALE) sum_morale += (g.team_morale.at(team) & 0x3F) * 2;
if (r.best_half_sum < half / 2) r.best_half_sum = half / 2;
counted++;
}
r.players = counted + (counted == 0);
counted &= 0xFF;
if ((flags & 0x1F0) == 0x1F0) counted = 11;
int value = 0;
if ((flags & 3) == 0) {
if (flags == (avg::FORM | avg::MORALE)) value = (sum_morale + sum_form) / 2;
else value = (flags & avg::FORM) ? sum_form : sum_morale;
} else {
int attributes = 0;
if (flags & avg::CONDITION) value += sum_condition, attributes++;
if (flags & avg::TECHNIQUE) value += sum_technique, attributes++;
value /= attributes;
// form and morale scale the result by +-(average - 50) / 8 percent
if (sum_form != 0) value = (div8(sum_form / counted - 50) + 100) * value / 100;
if (sum_morale != 0) value = (div8(sum_morale / counted - 50) + 100) * value / 100;
}
if (!(flags & avg::NO_DIVIDE) && counted != 0) {
value /= counted;
if (value < 0) value = 0;
if (value > 99) value = 99;
}
if (value == 0) value = 1;
r.value = value;
return r;
}
} // namespace bmh
+279
View File
@@ -0,0 +1,279 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// In-memory game state used by the game logic.
//
// The original keeps its state in many global tables; GameState collects the ones the
// ported logic needs, decoded into typed vectors. It is filled from a savegame
// (SaveState) and will later be written back the same way.
#include <cstdint>
#include <array>
#include <functional>
#include <string>
#include <vector>
#include "formats/m3d.hpp"
#include "formats/savestate.hpp"
#include "formats/textd.hpp"
#include "game/memory.hpp"
#include "game/random.hpp"
#include "game/reality_motion.hpp"
namespace bmh {
struct TransferOfferListView;
struct TransferDecisionEvent;
struct HumanBuyerSaleHooks;
// Special team id used by the original for "no club" / the player pool (0x165).
constexpr int kNoTeam = 0x165;
// Squad slot values (u16 in table *SquadSlots):
// bits 0-11 player id, 0xFFF = empty slot
// bit 15 player is in the starting line-up
// bits 12-14 further flags (not yet decoded)
constexpr uint16_t kEmptySlot = 0x0FFF;
constexpr uint16_t kSlotInLineup = 0x8000;
struct GameState {
std::vector<uint16_t> squad_slots; // *SquadSlots, all squads back to back (see squad_range)
std::vector<Player> players; // *PlayerConditionTechniqueForm / *PlayerSkillWords / *PlayerIdentityWords, names not filled
std::vector<uint8_t> team_morale; // *TeamMorale, per team: bits 0-5 morale / 2, bits 6-7 flags
// *TeamFlags, per team u16. Bits 8-9 and 10-11 hold two formation numbers (0-3); bit 4
// selects which one is used (see formation()). Other bits not yet decoded.
std::vector<uint16_t> team_flags;
// *PlayerBonuses, per player: bits 0-6 a bonus value (0-50 used, raises the player's rating by
// up to 25 %; probably experience/routine), bit 7 a flag.
std::vector<uint8_t> player_bonus;
// Block Formations = contents of M3.DAT: formation tables, 2 sets (outdoor, indoor) of
// 0xB0 bytes = 8 formations x (11 x positions, 11 y positions). The engine uses 4.
std::vector<uint8_t> formations;
// Team id managed by each human manager (manager record +0x290, CupDraw_FormatError_RuntimeField2), one entry
// per human manager (ManagerCount).
std::vector<int> manager_teams;
bool indoor = false; // OpenBMH deviates from the original: retains designated set-piece selections in the supported manager-record extension.
// CareerSessionRuntimeField: indoor tournament in progress
// Block ManagerRecords: 5 manager records of 0xB0C bytes (raw). Known fields: +0x290 team id,
// +0x8ae staff value used by the club doctor, and from the supported rule profile patch the designated
// takers (player id + 1, u16) +0xafc penalty, +0xafe penalty follow-up, +0xb08 free
// kick, valid only if +0xb0a holds the marker 0x3253.
std::vector<uint8_t> manager_records;
// Block TacticsBoards: tactics board of each human manager, 0x840 bytes = 24 slots of 0x58
// bytes. Slot byte +0x41 = depth x, +0x42 = lane y (signed; x >= 31 and y >= 31 are
// positions between the grid lines), +0x43 = a flag read by the injury code.
std::vector<uint8_t> tactics;
// Block ManagerAutomation: 5 option bytes per human manager. Byte 1 (StateRuntimeField2): the assistant
// coach may substitute; byte 2 (StateRuntimeField3): the assistant coach sets the attitude.
std::vector<uint8_t> manager_options;
bool manager_option(int manager, int index) const {
size_t at = size_t(manager) * 5 + size_t(index);
return at < manager_options.size() && manager_options[at] != 0;
}
// OpenBMH deviates from the original: retains designated set-piece selections in the supported manager-record extension.
// CurrencySuffixText: the currency after a formatted amount, from the loaded EXE (supported rule profile " EU",
// CD and CLASSIC " DM", the English version " &" - the pound sign of its font). Set by the
// career session; " EU" until then.
std::string currency_suffix = " EU";
// Runtime-only resort content, loaded for every career and saved-game session.
// Direct engine callers supply their own content before using training camps.
std::array<int32_t, 8> training_camp_base_prices{};
std::array<std::array<uint8_t, 4>, 8> training_camp_quality{};
// Runtime-only copy of the executable credit factors (EXE +BankCredit_BankCreditContext_RuntimeField3), used by
// ChangeBankCreditInterest during weekly manager offers. Never serialized into FBM.
std::array<uint8_t, 49> credit_rate_table{};
double credit_divisor = 0;
bool credit_rate_table_available = false;
int level = 0; // Difficulty: game level; above 3 the tactics board rates players
// ChanceRain / ChanceTemperature: rain and temperature (descriptor +0x50 / +0x30) of the
// match whose chance the minute loop handled last. player_value reads them (bad weather
// and heat cost players whose condition and technique differ), also when the side
// records of the next matchday are built - the values stay from the last chance.
// Run-time globals, not saved.
int chance_rain = 0;
int chance_temperature = 0;
// MatchEngineRuntimeField17: the shooter of the last real chance (0xFFF none); the penalty
// shoot-out still reads it. Run-time global, not saved.
int last_shooter = 0xFFF;
// MatchEngineRuntimeField: quality of the last player picked (PickTaker), also read later.
int last_pick_quality = 0;
// LiveSceneVisible: the live scene is shown this matchday (1 - option CareerSession_DispatchLiveTactic_RuntimeField3, set
// when the matchday starts). Run-time global, not saved.
bool live_scene = false;
RealityResidue reality; // unsaved MatchEngine_Minute_ExecutableField2/MatchEngine_Minute_ExecutableField/MatchEngine_Minute_ExecutableField3/MatchEngine_Minute_ExecutableField4 and previous grid
// StateRuntimeField4 / MatchdaySetupRuntimeField12: home teams of the matches chosen for the live display at
// kick-off (AutoLineup, at most 4). Run-time globals, not saved.
std::vector<int> live_matches;
// ResetSportschauSelection: unsaved bd125 words / bd139 bytes, including insertion slot9.
// Reset clears priorities only; home words deliberately survive between days.
std::array<uint16_t, 10> sportschau_homes{};
std::array<uint8_t, 10> sportschau_priorities{};
bool sportschau_selection_available = false;
uint16_t sportschau_club_threshold = 90; // executable TeamsWithSquads, supplied by CareerSession
// MonthRuntimeField7: alternates 0/1 each time a computer club is looked for to put a
// player on the transfer list (Int5). Run-time static, starts at 0.
int list_toggle = 0;
// LineupRuntimeField: set while the players age at the season change (CareerSeasonSetup3); the
// automatic line-up (Int2) does nothing then.
bool lineups_frozen = false;
// InstallDefaultHooks(row): the contracts screen a human manager gets in the month change when
// the contract of the player in board row `row` has ended. Returns 1 when that contract
// was renewed (the screen may change other rows too), 0 when the player goes, -1 to stop
// (MinuteReport). Without it the month change reports the contract as not supported.
std::function<int(GameState&, int manager, int row)> contract_screen;
// DayStepRest2's borrower decision when an expiring loan can be kept: 1 = yes,
// 0 = no, negative = no dialog owner / abort before the month transaction commits.
std::function<int(GameState&, int manager, const std::string& question)> loan_return_screen;
// DayStepRest2's positive Month_ReturnLoans_TextPointer6 branch enters OpenTransferEditor on a temporary
// special row. The runtime owner must provide the real editor/settlement path.
std::function<int(GameState&, GameRandom&, WatcomRandom&, int manager,
int source_slot, int list_entry, const HumanBuyerSaleHooks&)> loan_return_offer_screen;
// How a human manager answers the JA/NEIN questions of the weekly offers (Bool,
// kinds 5, 8 and 10-15): false = NEIN.
bool offer_answer = false;
// Human transfer negotiation at the weekly list deadline. The callback receives the
// seller-manager slot, player, buyer club, fee and annual wage; absent a controller,
// an explicitly human-owned selling club declines rather than silently transferring.
std::function<bool(GameState&, int seller_manager, int player, int buyer, int32_t fee, int32_t salary)> transfer_decision;
// Optional synchronous human-seller selector for the original multi-bid screen
// (IncomingTransferScreen). Return a stable raw bid slot 0..3 or -1 to decline. The legacy
// bool callback above remains the default path when this presenter is absent.
std::function<int(const GameState&, const TransferOfferListView&)> transfer_offer_selector;
// Read-only presentation notification for IncomingTransferScreen's automatic decision
// animation and the subsequent successful-transfer confirmation. It never
// supplies a game decision; ranking, acceptance and transfer remain in Core.
std::function<void(const TransferDecisionEvent&)> transfer_decision_observer;
// DeskActions_EditorFail_RuntimeField2 gates the original explicit-decline notice in IncomingTransferScreen.
// Runtime context only; it is not a save field.
bool transfer_notice_suppressed = false;
// PoolsOpenFlag == 0xcc: the pools coupon of the desk (BuildPoolsCoupon) is not evaluated
// yet. The desk sets it (also again after loading a game there); EvaluatePoolsCoupon(0) at the
// end of the next second half evaluates the coupon and overwrites the byte, so later
// matchdays leave the results alone.
bool pools_open = true;
// DeskRuntimeField5 / SeasonRuntimeField27: the autosave counter of the desk (DeskDate): months
// seen at the first manager's desk and the month code last seen. Run-time statics:
// a freshly started game has 0/0, so its first desk already counts as a new month.
int autosave_months = 0;
int autosave_month = 0;
// --- matchday bookkeeping (see matchday.hpp) ------------------------------------------
// *ClubSeasonRecords: league record per club, 0x4a bytes (168 clubs):
// +0x00 7 streaks x 3 bytes (all, home, away): 0 wins, 1 defeats, 2 draws,
// 3 without a win, 4 unbeaten, 5 without conceding, 6 without scoring
// +0x15 8 record results (home goals << 4 | away goals), see matchday.cpp
// +0x1e points, +0x20 goals for, +0x22 goals against, +0x24 wins, +0x26 draws,
// +0x28 defeats (u16 each)
// +0x2a 8 x u16 opponent of the record (club_ids of the opponent)
// +0x3a 8 x u16 date of the record (CalendarDay, 0xFFFF at most)
std::vector<uint8_t> club_table;
std::vector<uint16_t> club_ids; // *ClubIdentities, per club (a name/identity number)
// Further heap tables per club, so far only moved when clubs change leagues
// (ClubsChangePlaces): *ClubAuxiliaryWords (u16 per club, 168), *ClubBadgeSelectors (u16 per team, 419), *ClubAuxiliaryBytes (168 bytes)
std::vector<uint8_t> club_heap_bc, club_heap_78, club_heap_b8;
// *MasterDatabaseMetadata (100 bytes from M3D.MAN) and the savegame trailer pools 2 (referees, *ba370) and
// 3 (stadiums, *ba360): not used by the engine, kept for writing savegames.
std::vector<uint8_t> master_database_metadata, referee_names, stadium_names;
std::vector<uint16_t> player_cards; // *PlayerCards, per player: card counters per competition
uint32_t date = 0; // CalendarDay: day counter
// DaysIntoSeason (day of the season, the calendar index) moves with the day counter within
// a season: season_day() = date - season_start.
uint32_t season_start = 0;
// *TournamentName (0x24 bytes, the text slot 590 rewritten at run time): the name of the
// indoor tournament, "In " followed by the longest word of the host club's name.
std::vector<uint8_t> tournament_name;
int season_day() const { return int(date) - int(season_start); }
int32_t development_balance = 0; // PlayerDevelopmentBalance: sum of attribute changes (steers trends)
int trend_rotation = 0; // PlayerTrendRotation: next team trend handed out (0-2)
// ManagerMatchHistory: per human manager and opponent club the last results, 5 per venue
// (0x690 bytes per manager = 168 clubs x 2 venues x 5, home | away << 4 as seen by
// the manager's club).
std::vector<uint8_t> manager_results;
// ManagerRatings: per manager 6 competitions x the last 10 match ratings (0-200); their
// weighted average is the manager's performance (record +0x8aa).
std::vector<uint8_t> manager_ratings;
// *LeagueRankHistory: table position history, 13 u16 per team, three 5-bit positions each;
// LeagueRoundCounters: number of positions recorded per league (9 leagues).
std::vector<uint8_t> position_history;
std::vector<uint8_t> league_rounds;
// Block LeagueResults: season results, 9 leagues x 38 matchdays x 10 matches (schedule.hpp).
std::vector<uint8_t> results;
int season = 0; // SeasonIndex: seasons played (index of the per-season manager records)
// Block StockExchange: 12 shares of 0x5c bytes (price, history, trend) for the stock market.
std::vector<uint8_t> stocks;
// ForeignClubStrength: strength byte of each club without a squad (ids from 168 on, the
// foreign clubs): bits 5-7 the level (table RatingRuntimeField2), bits 1-3 strong lines, bit 0 style.
std::vector<uint8_t> foreign_strength;
// The other static tables of the savegame, addressed like in the original (cups, ...).
StaticMemory memory;
// *ManagerMailbox: the managers' mailbox (40 entries of 0xA0 bytes, see messages.hpp).
std::vector<uint8_t> mailbox;
// TEXTD.BLK for the texts of messages (not part of the savegame; may be null).
const TextDb* texts = nullptr;
// *ba374: the club name pool (trailer pool 0 of the savegame); *ClubIdentities (club_ids)
// holds each club's offset into it.
std::vector<uint8_t> club_names;
// ClubName2: name of a club (0xFFF gives the text NoClubText, needs `texts`).
std::string club_name(int team) const;
// *PlayerNameOffsets / *ba36c: offset of each player's name in the player name pool (pool 1).
std::vector<uint16_t> player_name_offsets;
std::vector<uint8_t> player_names;
// PlayerName for a player id (0xFFF gives the text NoPlayerText, needs `texts`).
std::string player_name(int player) const;
static GameState from_save(const SaveState& save, const DbCounts& counts = {});
// Human manager index of a team, or -1 for computer teams (FindManagerForClub, without the
// special case for manager slot 4).
int manager_of(int team) const;
// Formation number (0-3) a computer team plays with (used by FormationPosition).
int formation(int team) const;
// Formation position of line-up slot `slot` (0-10): x = depth (0 goalkeeper .. ~21
// forward line), y = lane (0-8, 4 = centre). Human teams read their tactics board.
void formation_position(int team, int slot, int& x, int& y) const;
};
// Location of a team's squad inside squad_slots (SquadRange4):
// teams 0..89 (big squads) : 24 slots at team * 24
// teams 90..137 (small) : 16 slots at team * 16 + 90 * 8
// kNoTeam : 24 slots at 3072
struct SquadRange {
size_t first = 0;
size_t count = 0;
};
SquadRange squad_range(int team);
// Selection and value flags of team_average (the "param_2" of QuoteNationalFriendlyMatch).
namespace avg {
constexpr uint16_t CONDITION = 0x001; // KO
constexpr uint16_t TECHNIQUE = 0x002; // TE
constexpr uint16_t FORM = 0x004; // FO
constexpr uint16_t MORALE = 0x008; // team morale (same value for every player)
constexpr uint16_t GOALKEEPER = 0x010; // position filters, bit (position + 4)
constexpr uint16_t DEFENDER = 0x020;
constexpr uint16_t MIDFIELDER = 0x040;
constexpr uint16_t FORWARD = 0x080;
constexpr uint16_t ALL_POSITIONS = 0x0F0;
constexpr uint16_t LINEUP_ONLY = 0x100; // only slots flagged kSlotInLineup
constexpr uint16_t NO_DIVIDE = 0x200; // return the sum instead of the per-player average
constexpr uint16_t FIT_ONLY = 0x400; // skip players with w364 bits 16-20 != 0 (injured?)
} // namespace avg
struct TeamAverage {
int value = 1; // result, 1..99 unless NO_DIVIDE
int players = 0; // number of players that matched the filter (at least 1)
int best_half_sum = 0; // max over players of (KO + TE) / 2 for the selected attributes (CareerSession_FormatError_ExecutableField3)
};
// Port of QuoteNationalFriendlyMatch for league teams (id < 168) and kNoTeam.
//
// With CONDITION and/or TECHNIQUE the result is the average of the selected attributes,
// scaled by form and morale if those flags are set as well:
// value = mean(KO, TE) * (100 + (avg_form - 50) / 8) / 100 * (100 + (avg_morale - 50) / 8) / 100
// With only FORM and/or MORALE the result is the respective average (both: their mean).
// Quirk kept from the original: if all four position bits and LINEUP_ONLY are set
// (flags & 0x1F0 == 0x1F0), the divisor is fixed to 11 players instead of the real count.
// Teams without squads (ids from 168 on) take their value from TeamRating with the
// rating profile 2, which draws from `rand` (required for them); players is then 0.
TeamAverage team_average(const GameState& state, int team, uint16_t flags, WatcomRandom* rand = nullptr);
} // namespace bmh
+128
View File
@@ -0,0 +1,128 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "game/table.hpp"
#include <vector>
#include "game/lineup.hpp"
#include "game/schedule.hpp"
namespace bmh {
// AddResult3: one result (goals of both sides) for the two clubs (draw positions).
// flags 1 = count only the home side, 2 = only the away side.
void add_result(LeagueTable& t, const int club[2], const uint8_t goals_in[2], int flags, int win_bonus) {
if (club[0] > 0x13 || club[1] > 0x13) return;
const uint8_t goals[2] = {uint8_t(goals_in[0] & 0x1F), uint8_t(goals_in[1] & 0x1F)};
const int first = flags == 2 ? 1 : 0, last = flags == 1 ? 1 : 2;
for (int s = first; s < last; s++) {
const int c = club[s];
t.goals_for[c] = uint8_t(t.goals_for[c] + goals[s]);
t.goals_against[c] = uint8_t(t.goals_against[c] + goals[1 - s]);
t.rank_word[c]++; // games in bits 0-5
int outcome = 0, bonus = 0;
if (goals[s] > goals[1 - s]) {
outcome = 2;
bonus = win_bonus;
t.wins[c]++;
} else if (goals[s] == goals[1 - s]) {
outcome = 1;
} else {
t.defeats[c]++;
}
t.points[c] = int8_t(t.points[c] + outcome + bonus);
t.form[c] = (t.form[c] << 3) | uint32_t(s * 4 + outcome + 1);
}
}
// SortKey: sort key of a club; `parts` bits switch off points (1), goals scored
// (2) and goals conceded (4).
uint32_t sort_key(const LeagueTable& t, int c, int parts) {
uint32_t goals = 0;
int diff = 0x100, pts = 0, per_game = 0;
if (!(parts & 2)) {
diff = t.goals_for[c] + 0x100;
goals = t.goals_for[c];
}
if (!(parts & 4)) diff -= t.goals_against[c];
if (!(parts & 1)) {
pts = t.points[c] < 0 ? 0 : t.points[c];
per_game = pts * 2 + 0x80 - (t.rank_word[c] & 0x3F) * 2;
}
return uint32_t(pts) << 25 | uint32_t(per_game) << 17 | uint32_t(diff) << 8 | goals;
}
// AddResult2: sort (only if the keys are not already descending) and store the ranks;
// the old rank moves to bits 6-10.
void sort_table(LeagueTable& t, int parts) {
int16_t order[20];
uint32_t keys[20];
bool unsorted = false;
uint32_t previous = 0xFFFFFFFFu;
for (int c = 0; c < t.size; c++) {
order[c] = int16_t(c);
keys[c] = sort_key(t, c, parts);
if (previous < keys[c]) unsorted = true;
previous = keys[c];
}
if (unsorted) quicksort_by_key(order, keys, t.size, false);
for (int i = 0; i < t.size; i++) {
uint16_t& w = t.rank_word[order[i]];
w = uint16_t(((w >> 11) << 6) + i * 0x800 + (w & 0x3F));
}
}
int league_matchdays(int league) { return kLeagueSizes[league] * 2 - 2; }
LeagueTable compute_league_table(const GameState& g, int league, int from, int to, int flags, int points_mode) {
LeagueTable t;
t.league = league;
t.size = kLeagueSizes[league];
int parts = 0;
if (points_mode & 0xE) {
parts = points_mode >> 1;
points_mode &= 1;
}
const int first_team = league_first_team(league);
if (flags & 4) {
// a human manager's point deduction (manager record +0x220: 3 << 5 | points)
for (int c = 0; c < t.size; c++) {
int manager = g.manager_of(first_team + c);
if (manager < 0) continue;
uint8_t d = g.manager_records.at(size_t(manager) * 0xB0C + 0x220);
if (d >> 5 == 3) t.points[c] = int8_t(t.points[c] - (d & 0x1F));
}
flags &= ~4;
}
const int rounds_played = league < int(g.league_rounds.size()) ? g.league_rounds[league] : 0;
int last_round = uint8_t(rounds_played - 1); // local_1c
int before_last = 0x80; // local_10
if (last_round > 1) before_last = uint8_t(rounds_played - 2);
if (last_round > 0x7F) last_round = 0;
const int matchdays = league_matchdays(league);
if (to > matchdays) to = matchdays;
if (to == 0) to = 1;
for (int r = from; r < to; r++) {
std::vector<Fixture> fx = generate_fixtures(league_table_teams(league), r + 1, matchdays / 2, first_team);
bool counted = false;
for (size_t i = 0; i < fx.size(); i++) {
uint8_t b = g.results.at(size_t(league) * 0x17C + size_t(r) * 10 + i);
int club[2] = {fx[i].home - first_team, fx[i].away - first_team};
if ((b & 0xCC) == 0xCC) {
if (b == 0xCD)
for (int s = 0; s < 2; s++) t.form[club[s]] = t.form[club[s]] << 3 | 4;
continue;
}
const uint8_t goals[2] = {uint8_t(b >> 4), uint8_t(b & 0xF)};
add_result(t, club, goals, flags, points_mode);
counted = true;
}
if (to <= r + 2 || r == before_last || r == last_round || (last_round < r && counted)) sort_table(t, parts);
}
for (int c = 0; c < t.size; c++)
if (t.points[c] < 0) t.points[c] = 0;
return t;
}
} // namespace bmh
+57
View File
@@ -0,0 +1,57 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// League tables (BMH.exe V2.24).
//
// The original keeps no table: whenever one is needed (desk, table screen, season goals,
// position history) ComputeLeagueTable recomputes it from the result bytes of the season
// (block LeagueResults, see schedule.hpp) into a set of scratch arrays:
// TableRuntimeField goals for TableRuntimeField2 goals against
// TableRuntimeField3 points (signed) TableRuntimeField4 wins TableRuntimeField5 defeats
// TableRuntimeField6 u16: bits 0-5 games, 6-10 previous rank, 11-15 rank (0 = first)
// TableRuntimeField7 u32 form chain, 3 bits per game (newest lowest):
// venue << 2 | (0 defeat, 1 draw, 2 win) + 1; 4 = awarded/void
// all indexed by the club's draw position inside its league.
//
// AddResult3 adds one result, SortKey builds the sort key, AddResult2 sorts
// (descending, the quicksort Games) and stores the ranks.
#include <array>
#include <cstdint>
#include "game/state.hpp"
namespace bmh {
struct LeagueTable {
int league = 0;
int size = 0;
std::array<uint8_t, 20> goals_for{}, goals_against{};
std::array<int8_t, 20> points{};
std::array<uint8_t, 20> wins{}, defeats{};
std::array<uint16_t, 20> rank_word{}; // TableRuntimeField6
std::array<uint32_t, 20> form{};
int games(int club) const { return rank_word[club] & 0x3F; }
int rank(int club) const { return rank_word[club] >> 11; }
int previous_rank(int club) const { return rank_word[club] >> 6 & 0x1F; }
};
// The building blocks, also used for the cup group tables (AddResult):
// AddResult3 (flags 1 home side only, 2 away side only, 3 both), SortKey and
// AddResult2.
void add_result(LeagueTable& t, const int club[2], const uint8_t goals[2], int flags, int win_bonus);
uint32_t sort_key(const LeagueTable& t, int club, int parts);
void sort_table(LeagueTable& t, int parts);
// Matchdays of a league per season (LeagueMatchdayCounts = clubs * 2 - 2).
int league_matchdays(int league);
// ComputeLeagueTable(league, from, to, flags, points_mode): table over the matchdays
// from+1 .. to (clamped to the season). flags: 1 home games only, 2 away games only,
// 4 apply a human manager's point deduction (manager record +0x220). points_mode bit 0:
// three points for a win; bits 1-3 select the sort key parts (see sort_key).
// The ranks are recomputed after certain matchdays exactly as the original does, so the
// "previous rank" bits match its table screens.
LeagueTable compute_league_table(const GameState& g, int league, int from, int to, int flags, int points_mode);
} // namespace bmh
+72
View File
@@ -0,0 +1,72 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/table_forecast.hpp"
#include <bit>
#include <stdexcept>
#include "game/schedule.hpp"
#include "game/source_tip.hpp"
namespace bmh {
LeagueTableForecast compute_league_table_forecast(
const GameState& game, int league, int source_param2, int matchdays,
int flags, int normal_mode, int sort_extra,
const std::array<uint8_t, 10>& gap, const GameRandom& game_random) {
if (league < 0 || league >= kLeagueCount)
throw std::invalid_argument("table forecast: invalid league");
if (source_param2 != 0)
throw std::invalid_argument("table forecast: only Source param2 zero is reviewed");
const int source_matchdays = league_matchdays(league);
if (matchdays != source_matchdays)
throw std::invalid_argument("table forecast: matchday count differs from Source league");
if (flags < 0 || flags > 7)
throw std::invalid_argument("table forecast: unsupported Source aggregation flags");
if (normal_mode < 0 || normal_mode > 1 || sort_extra < 0 || sort_extra > 14 || (sort_extra & 1))
throw std::invalid_argument("table forecast: unsupported Source points/sort parameters");
if (game.league_rounds.size() < size_t(kLeagueCount) || game.results.size() < kResultsSize)
throw std::invalid_argument("table forecast: Native round/results inputs unavailable");
const int points_mode = normal_mode + sort_extra;
LeagueTableForecast out;
out.table = compute_league_table(game, league, 0, matchdays, flags, points_mode);
out.game_after = game_random;
const int raw_round = int(game.league_rounds[size_t(league)]);
out.first_simulated_round = raw_round + (source_param2 != 0);
const int first_team = league_first_team(league);
const int teams = league_table_teams(league);
int32_t source_seed = 0;
if (out.first_simulated_round < matchdays) {
if (!game.memory.has(::bmh::layout::TableForecast_InvalidArgument_RuntimeField))
throw std::invalid_argument("table forecast: Native Source seed unavailable for future rounds");
source_seed = std::bit_cast<int32_t>(game.memory.u32(::bmh::layout::CurrentMatchday));
if (source_seed < 0 || source_seed > 10000)
throw std::invalid_argument("table forecast: Native Source seed outside 0..10000");
}
for (int round = out.first_simulated_round; round < matchdays; ++round) {
const auto fixtures = generate_fixtures(teams, round + 1, matchdays / 2, first_team);
// ComputeLeagueTableForecast is invoked once per round and reseeds once at entry,
// before iterating that round's fixture pairs.
out.game_after.set_seed(source_seed);
for (const auto& fixture : fixtures) {
const int home_primary = team_average(game, fixture.home, 0x3f3).value;
const int home_secondary = team_average(game, fixture.home, 0x3fc).value;
const int away_primary = team_average(game, fixture.away, 0x3f3).value;
const int away_secondary = team_average(game, fixture.away, 0x3fc).value;
// GameRandom::set_seed deliberately preserves the cumulative call count.
const uint8_t encoded = source_tip_result(out.game_after, gap,
home_primary, away_primary, home_secondary, away_secondary);
const int clubs[2] = {fixture.home - first_team, fixture.away - first_team};
const uint8_t goals[2] = {uint8_t(encoded >> 4), uint8_t(encoded & 0x0f)};
add_result(out.table, clubs, goals, flags & 3, normal_mode);
}
if (matchdays < round + 3) sort_table(out.table, sort_extra >> 1);
++out.simulated_rounds;
}
return out;
}
} // namespace bmh
+31
View File
@@ -0,0 +1,31 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <array>
#include <cstdint>
#include "game/random.hpp"
#include "game/table.hpp"
namespace bmh {
// Scratch result of the Table screen's one-shot KI projection. `game_after`
// contains Source G after all per-ComputeLeagueTableForecast reseeds/draws; callers commit it
// only with the accepted UI/session transition. Native results and CurrentMatchday are
// never changed here.
struct LeagueTableForecast {
LeagueTable table;
GameRandom game_after{0};
int first_simulated_round = 0;
int simulated_rounds = 0;
};
// Only the reviewed E37 normal family entry (Source param2 == 0) is supported.
// All work is local: invalid input or a projection exception cannot mutate the
// caller's GameRandom or GameState.
LeagueTableForecast compute_league_table_forecast(
const GameState& game, int league, int source_param2, int matchdays,
int flags, int normal_mode, int sort_extra,
const std::array<uint8_t, 10>& gap, const GameRandom& game_random);
} // namespace bmh
+134
View File
@@ -0,0 +1,134 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "game/top_scorers.hpp"
#include <array>
#include <stdexcept>
#include <utility>
#include "game/schedule.hpp"
namespace bmh::game {
namespace {
constexpr size_t kManagerRecordSize = 0xb0c;
constexpr size_t kNationalBackupManager = 4;
constexpr size_t kManagerTeamOffset = 0x290;
[[noreturn]] void invalid(const std::string& reason) {
throw FormatError("top scorers: " + reason);
}
bool source_manager_owns(const GameState& g, int team, size_t manager_count) {
// FindManagerForClub checks every active manager in order, then attributes the
// national coach's original club to Source manager slot 4 when slot 0 is
// temporarily assigned to 0x165.
for (size_t manager = 0; manager < manager_count; ++manager) {
if (manager < g.manager_teams.size() && g.manager_teams[manager] == team) return true;
}
if (!g.manager_teams.empty() && g.manager_teams[0] == kNoTeam) {
const size_t original_at = kNationalBackupManager * kManagerRecordSize + kManagerTeamOffset;
if (original_at + 2 > g.manager_records.size())
invalid("truncated national-coach backup manager record");
const uint16_t original = uint16_t(g.manager_records[original_at] |
uint16_t(g.manager_records[original_at + 1]) << 8);
if (original == team) return true;
}
return false;
}
uint8_t metric_score(uint8_t goals, uint8_t assists, TopScorersMetric metric) {
switch (metric) {
case TopScorersMetric::goals: return goals;
case TopScorersMetric::assists: return assists;
case TopScorersMetric::scorer: return uint8_t(goals + assists);
}
invalid("unknown metric");
}
} // namespace
TopScorersProjection top_scorers_from_game(const GameState& g, int manager_slot,
TopScorersMetric metric,
TopScorersScope scope) {
switch (metric) {
case TopScorersMetric::goals:
case TopScorersMetric::assists:
case TopScorersMetric::scorer: break;
default: invalid("unknown metric");
}
switch (scope) {
case TopScorersScope::league:
case TopScorersScope::managers: break;
default: invalid("unknown scope");
}
const size_t manager_count = g.manager_teams.size();
if (manager_count == 0 || manager_count > 4 || manager_slot < 0 ||
size_t(manager_slot) >= manager_count || size_t(manager_slot) >= g.manager_teams.size())
invalid("manager slot is outside the active manager table");
const int manager_team = g.manager_teams[size_t(manager_slot)];
if (manager_team < 0)
invalid("manager has no supported domestic league");
// TeamLeague2 deliberately maps team IDs above 0x164 (including the
// national team 0x165) to league zero; ordinary cup-only teams map to 9.
const int league = manager_team > 0x164 ? 0 : team_league(manager_team);
if (league < 0 || league >= kLeagueCount)
invalid("manager team is outside Source's nine domestic leagues");
const int first_team = league_first_team(league);
const int team_count = kLeagueSizes[league];
if (first_team < 0 || first_team + team_count > 138 ||
g.club_ids.size() < size_t(first_team + team_count) || g.club_names.empty())
invalid("incomplete domestic club table");
TopScorersProjection result;
result.manager_slot = manager_slot;
result.league = league;
result.metric = metric;
result.scope = scope;
std::array<TopScorersRow, 10> rows{};
std::array<uint8_t, 10> scores{};
size_t used = 0;
for (int team = first_team; team < first_team + team_count; ++team) {
if (scope == TopScorersScope::managers && !source_manager_owns(g, team, manager_count)) continue;
const SquadRange range = squad_range(team);
if (range.first > g.squad_slots.size() || range.count > g.squad_slots.size() - range.first)
invalid("incomplete squad slots for domestic club " + std::to_string(team));
for (size_t offset = 0; offset < range.count; ++offset) {
const uint16_t slot = g.squad_slots[range.first + offset];
// TopScorersFromGame skips an empty squad position and continues through the
// fixed-size roster; a gap does not terminate Source traversal.
if ((slot & 0x0fff) == kEmptySlot) continue;
const int player = int(slot & 0x0fff);
if (size_t(player) >= g.players.size())
invalid("squad references missing player " + std::to_string(player));
const Player& p = g.players[size_t(player)];
const uint8_t goals = uint8_t((p.w364 >> 2) & 0x3f);
const uint8_t assists = uint8_t((p.w368 >> 18) & 0x3f);
const uint8_t score = metric_score(goals, assists, metric);
if (score == 0) continue;
size_t position = 0;
while (position < used && !(scores[position] < score)) ++position;
if (position >= rows.size()) continue;
const size_t new_used = used < rows.size() ? used + 1 : used;
for (size_t move = new_used; move > position + 1; --move) {
rows[move - 1] = std::move(rows[move - 2]);
scores[move - 1] = scores[move - 2];
}
const uint8_t source_goals = metric == TopScorersMetric::assists ? 0 : goals;
const uint8_t source_assists = metric == TopScorersMetric::goals ? 0 : assists;
rows[position] = TopScorersRow{0, player, team, int(range.first + offset), source_goals, source_assists, score,
g.player_name(player), g.club_name(team)};
scores[position] = score;
used = new_used;
}
}
result.rows.assign(rows.begin(), rows.begin() + used);
for (size_t i = 0; i < result.rows.size(); ++i) result.rows[i].rank = int(i + 1);
result.no_results = result.rows.empty();
return result;
}
} // namespace bmh::game
+48
View File
@@ -0,0 +1,48 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include "game/state.hpp"
namespace bmh::game {
enum class TopScorersMetric : uint8_t { goals, assists, scorer };
enum class TopScorersScope : uint8_t { league, managers };
struct TopScorersRow {
int rank = 0;
int player = -1;
int team = -1;
int squad_slot = -1;
// Values written to Original's scratch row: unused individual counters
// are zero unless their corresponding flag is selected.
uint8_t goals = 0;
uint8_t assists = 0;
uint8_t score = 0;
std::string player_name;
std::string team_name;
bool operator==(const TopScorersRow&) const = default;
};
struct TopScorersProjection {
int manager_slot = -1;
int league = -1;
TopScorersMetric metric = TopScorersMetric::goals;
TopScorersScope scope = TopScorersScope::league;
std::vector<TopScorersRow> rows;
bool no_results = true;
bool operator==(const TopScorersProjection&) const = default;
};
// Read-only port of Source TopScorersFromGame. It traverses the selected domestic
// league in runtime team order and each club in squad-slot order, inserting
// strictly ahead of lower scores (equal scores retain traversal order).
// It writes neither GameState nor the Source scratch result table and draws no RNG.
TopScorersProjection top_scorers_from_game(const GameState& game, int manager_slot,
TopScorersMetric metric,
TopScorersScope scope);
} // namespace bmh::game
+13
View File
@@ -0,0 +1,13 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// The step of the turn the engine is in: the turn driver names it when an exception (such as
// std::out_of_range, which carries no location) ends a turn, and a watchdog can read it while
// a turn runs (tests/cli_soak.cpp). Set at the coarse steps only.
#include <atomic>
namespace bmh {
inline std::atomic<const char*> turn_step{"start"};
} // namespace bmh
+10
View File
@@ -0,0 +1,10 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
namespace bmh {
// Unsaved EXE-owned context for PendingOfferAnswer's allocator behavior. Direct
// legacy/headless callers have no executable provenance and must stay unsupported.
enum class TransferAllocatorContext { unsupported, zero, blocked };
} // namespace bmh
+38
View File
@@ -0,0 +1,38 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include <cstdint>
#include "game/random.hpp"
#include "game/human_buyer_sale.hpp"
#include "game/state.hpp"
namespace bmh {
struct MinuteReport;
// ProjectTransferOfferList rates an existing bid. source_slot is the actual absolute SquadSlots
// index supplied by its caller, not an inferred pool index or player ID.
// The caller owns list/source-slot correspondence and any career-mode decision.
struct TransferBidRatingRequest {
int source_slot = -1;
int list_entry = -1;
int bid_slot = -1;
int expected_bidder = -1;
int expected_player = -1;
// Only checked DispatchClubPlayerPendingOffers entries40..43 may rate parked native buyer4.
std::optional<SourcePendingOwner> source_pending_owner = std::nullopt;
};
struct TransferBidRating {
bool supported = false;
uint32_t fee_pct = 0;
uint32_t salary_pct = 0;
};
// Exact RateTransferBidSource -> ProjectTransferOfferList composition: Source32 products/unsigned division,
// proposed human board with all seven bonuses/rankFF/fitness, then one W90..100.
// Does not write bids, perform settlement, read GameMode or consume G. Any borrowed
// board is restored before returning or propagating a validation failure.
// Unsupported inputs require caller-owned staging/rollback; no zero-basis guess.
TransferBidRating rate_transfer_bid_source(GameState&, const TransferBidRatingRequest&,
WatcomRandom&, MinuteReport&);
} // namespace bmh
+222
View File
@@ -0,0 +1,222 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "game/turn.hpp"
#include "game/trace.hpp"
#include "game/month.hpp"
#include "game/national.hpp"
#include "game/week.hpp"
#include "game/weekly.hpp"
namespace bmh {
bool full_game(const GameState& g) { return g.memory.has(::bmh::layout::CompetitionSelection) && (g.memory.u8(::bmh::layout::CompetitionSelection) & 1) != 0; }
void event_end(GameState& g) {
if (g.memory.has(::bmh::layout::Savestate_Layout_ExecutableField8)) g.memory.set8(::bmh::layout::Turn_EventEnd_RuntimeField, 1);
}
void day_stock_market(GameState& g, GameRandom& game) {
if (full_game(g)) stock_market(g, game);
}
bool month_step(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report) {
if (!full_game(g) || g.date == 0 || month_code(g.date - 1) == month_code(g.date)) return true;
month_change(g, rand, report, &game); // DayStepRest2
return !report.unsupported;
}
bool day_step_rest(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
uint16_t source_season_day, TransferAllocatorContext allocator) {
// DayStepRest tests CareerSession_PairingsRuntimeDraw_ExecutableField6 after DeskDate2(date - 1): the weekday of the
// previous day decides whether it is a training day
const int wd = weekday_code(g.date - 1);
const bool training = wd == 2 || wd == 6;
const bool month = full_game(g) && g.date > 0 && month_code(g.date - 1) != month_code(g.date);
// the Bundestrainer leaves the national team for the day's processing: on a training day
// the national squad trains first (FamiliarityDecay), then the slots are swapped back
// (NationalCoachHandBack); at the end he takes it over again (SwapManagerSlots2, ActiveManager left at
// the number of managers by the loop below)
const bool coach = (training || month) && national_coach_active(g);
if (coach) {
if (training) familiarity_decay(g, game, rand);
national_coach_hand_back(g);
}
if (training) {
if (full_game(g) && weekday_code(g.date) == 3) {
turn_step = "weekly_processing";
weekly_processing(g, game, rand, report, allocator); // DayStepRest3
if (report.unsupported) return false;
}
turn_step = "training";
familiarity_decay(g, game, rand);
for (size_t m = 0; m < g.manager_teams.size(); m++) train_squad(g, int(m), game, rand);
}
turn_step = "month_step";
const bool ok = month_step(g, game, rand, report);
if (coach) national_coach_take_over(g, int(g.manager_teams.size()), source_season_day);
return ok;
}
} // namespace bmh
#include "game/matchday_setup.hpp"
#include "game/season.hpp"
namespace bmh {
void plain_day(GameState& g, GameRandom& game, WatcomRandom& rand) {
day_stock_market(g, game);
g.date++;
daily_interest(g, rand);
}
bool empty_event_day(GameState& g, const MatchdayContext& ctx, GameRandom& game, WatcomRandom& rand, MinuteReport& report) {
setup_matchday(g, 0, ctx, game, rand, report);
turn_step = "prepare_event: matchday number";
draw_matchday_number(g, rand); // CurrentMatchday
shuffle_manager_order(g, game);
event_end(g);
g.date++;
daily_interest(g, rand);
return !report.unsupported;
}
bool is_season_end(const GameState& g) { return g.date > 0 && month_code(g.date) == 7 && month_code(g.date - 1) != 7; }
void season_end_day(GameState& g) {
if (national_coach_active(g)) national_coach_hand_back(g); // DailyInterest: NationalCoachHandBack first
if (g.memory.has(::bmh::layout::CareerSession_RuntimeError_RuntimeField4)) g.memory.set8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4, 1);
season_awards(g);
if (g.memory.has(::bmh::layout::EventPasses)) g.memory.set8(::bmh::layout::EventPasses, 0);
}
} // namespace bmh
#include "game/desk.hpp"
namespace bmh {
std::vector<MatchGroup> prepare_event(GameState& g, uint16_t calendar_entry, const MatchdayContext& ctx, GameRandom& game,
WatcomRandom& rand, MinuteReport& report) {
std::vector<MatchGroup> groups = setup_matchday(g, day_competitions(g, calendar_entry), ctx, game, rand, report);
draw_matchday_number(g, rand); // CurrentMatchday
turn_step = "prepare_event: manager order";
const std::vector<int> order = shuffle_manager_order(g, game);
for (size_t k = 0; k < order.size() && g.memory.has(::bmh::layout::NextDeskManager + uint32_t(k) * 2); k++)
g.memory.set16(::bmh::layout::NextDeskManager + uint32_t(k) * 2, uint16_t(order[k]));
return groups;
}
bool enter_event_desk(GameState& g, int position, const std::vector<MatchGroup>& groups, GameRandom& game,
WatcomRandom& rand, MinuteReport& report, bool prepare_pre_match_offer,
const DeskAutosaveHook& autosave) {
const int manager = g.manager_teams.size() > 1 ? g.memory.u16(::bmh::layout::NextDeskManager + uint32_t(position) * 2) : position;
if (g.memory.has(::bmh::layout::DeskPosition)) g.memory.set8(::bmh::layout::DeskPosition, uint8_t(position));
if (g.memory.has(::bmh::layout::ActiveManager)) g.memory.set8(::bmh::layout::ActiveManager, uint8_t(manager));
// AdvanceTurn(param1 != 0) suppresses only PreMatchOffer on the remaining
// desks of a loaded manager loop. Coupon preparation and desk entry still run.
// (an out-of-range access below names its step: the error reaches the player as text)
const char* step = "pre_match_offer";
try {
const bool offer = prepare_pre_match_offer
? pre_match_offer(g, manager, game, rand, report) : false;
step = "build_pools_coupon";
build_pools_coupon(g, groups, &rand); // BuildPoolsCoupon
step = "enter_desk";
enter_desk(g, manager, game, rand, autosave); // DeskDate
return offer;
} catch (const std::out_of_range& e) {
throw std::out_of_range(std::string(e.what()) + " (" + step + ", manager " + std::to_string(manager) + ")");
}
}
} // namespace bmh
#include "formats/binary.hpp"
#include "game/cup.hpp"
#include "game/matchday.hpp"
namespace bmh {
void finish_event(GameState& g, std::vector<MatchGroup>& groups, uint16_t calendar_entry, const std::vector<uint8_t>& buttons,
const std::vector<uint8_t>& saved_records, const std::vector<uint8_t>& saved_options, GameRandom& game,
WatcomRandom& rand, MinuteReport& report, const SeasonCupDrawHook& cup_draw,
const SportschauPresentationHooks* sportschau, const std::vector<ShowEvent>* show_events,
bool source_sportschau_replay, const SportschauRatingTables* ratings) {
if (report.unsupported) return;
for (size_t m = 0; m < g.manager_teams.size(); m++)
for (int s = 0; s < 24; s++)
for (int k = 0; k < 2; k++) {
const size_t at = m * 0x840 + size_t(s) * 0x58 + 0x44 + size_t(k) * 2;
g.tactics.at(at) = 0xFF, g.tactics.at(at + 1) = 0x0F;
}
auto show_intro = [&](int group_index) {
if (!sportschau || !sportschau->intro) return;
SportschauIntroView view;
view.group_index = group_index;
for (size_t i = 0; i < groups.size() && i <= 0xff; ++i) {
const MatchGroup& group = groups[i];
view.groups.push_back({uint8_t(i), group.desc.at(0), le32(group.desc, 0xcc),
int16_t(sportschau_source_setting_index(g, group))});
}
sportschau->intro(g, view);
};
show_intro(-1);
for (size_t group_index = 0; group_index < groups.size(); ++group_index) {
MatchGroup& grp = groups[group_index];
// FinishEvent sets DeskPosition to the current match-group index. Its final nonempty
// iteration leaves the last index visible to the following cup presentation.
if (g.memory.has(::bmh::layout::DeskPosition) && group_index <= 0xff)
g.memory.set8(::bmh::layout::DeskPosition, uint8_t(group_index));
if (group_index <= 0xff) show_intro(int(group_index));
if (ratings && !source_sportschau_replay) {
// FinishEvent/BuildSideRecords clear eleven scores outside the CareerSession_SportschauSourceOptions_ExecutableField gate.
// The loaded EXE owner still performs that reset when it skips
// MatchdayIntro entirely; old slot words remain untouched.
for (size_t i = 0; i < 11; ++i) {
grp.desc.at(0x70 + i) = 0;
const uint32_t address = ::bmh::layout::Turn_FinishEvent_ExecutableField + uint32_t(group_index) * 0xd0 + uint32_t(i);
if (group_index < 6 && g.memory.has(address)) g.memory.set8(address, 0);
}
}
process_group(g, grp, game, rand, report, int(group_index),
sportschau ? sportschau->fixture : SportschauFixtureHook{}, show_events,
source_sportschau_replay && sportschau ? &sportschau->replay : nullptr,
source_sportschau_replay ? ratings : nullptr);
if (report.unsupported) return;
if (source_sportschau_replay && ratings) {
const auto awards = finish_sportschau_awards(g, grp, int(group_index));
if (awards && sportschau && sportschau->awards) sportschau->awards(g, *awards);
if (sportschau && sportschau->team_info) {
const auto info = sportschau_team_info_view(g, grp, int(group_index));
if (info) sportschau->team_info(g, *info);
}
}
const uint32_t id = le32(grp.desc, 0xcc);
if (id < 0x15) {
if (league_screen_shown(buttons, 1, 90, int(id))) stir_random(game, rand);
const int round = g.league_rounds.at(id);
for (int m = 0; m < grp.matches(); m++) g.results.at(size_t(id) * 0x17C + size_t(round) * 10 + size_t(m)) = grp.results.at(size_t(m));
} else {
store_cup_results(g, grp);
}
}
// FinishEvent/BuildSideRecords call EvaluatePoolsCoupon(1) after every group's processing,
// before returning to AdvanceTurn's calendar/round advancement. Result evaluation
// at the second half is separate; pools_open does not gate this settlement.
settle_pools_coupon(g, groups);
for (size_t m = 0; m < g.manager_teams.size() && !saved_records.empty(); m++) {
for (size_t k = 0; k < 8; k++) g.manager_records.at(m * 0xB0C + 0xd2 + k) = saved_records.at(m * 0xB0C + 0xd2 + k);
g.manager_options.at(m * 5 + 2) = saved_options.at(m * 5 + 2);
}
const uint32_t competitions = day_competitions(g, calendar_entry);
advance_league_rounds(g, competitions & 0x1F, rand, report,
sportschau ? sportschau->winner : CompetitionWinnerHook{});
for (int bit = 5; bit < 0x13; bit++)
if ((competitions >> bit) & 1) advance_cup(g, bit - 5, rand, report, &game, cup_draw,
sportschau ? sportschau->winner : CompetitionWinnerHook{});
event_end(g);
}
} // namespace bmh
+103
View File
@@ -0,0 +1,103 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// The "Weiter" loop of the original (DailyInterest) - everything between two desks of the
// human managers: the day steps, the weekly and monthly processing, the matchdays with
// their preparation, the cups, the season end and the season change.
//
// Built up step by step from the parts verified with tests/week_check (which uses these
// functions, so every regression run checks them against the recordings).
#include "game/match_engine.hpp"
#include "game/random.hpp"
#include "game/season.hpp"
#include "game/sportschau_presentation.hpp"
#include "game/state.hpp"
#include "game/transfer_allocator.hpp"
namespace bmh {
// Whether the career plays the leagues (CompetitionSelection bit 0, "full game"); without them
// there is no weekly or monthly processing.
bool full_game(const GameState& g);
// DailyInterest: the daily share price run (DailyInterest3) only with the leagues on
// (CompetitionSelection bit 0) - the world game without leagues keeps its prices.
void day_stock_market(GameState& g, GameRandom& game);
// The end of AdvanceTurn: EventEnd(TurnRuntimeField), with the value layout field the program
// start leaves there, sets Turn_EventEnd_RuntimeField = 1.
void event_end(GameState& g);
// The rest of the day step DayStepRest after the date moved on: on a training day (the
// previous day's weekday code 2 or 6) the weekly processing (DayStepRest3, full game,
// when the new day has weekday code 3), the decay of the familiarity and every human
// manager's training; then the month change (DayStepRest2) when the month moved on.
// Returns false on a reported state/context failure; see MinuteReport::reason.
bool day_step_rest(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report,
uint16_t source_season_day,
TransferAllocatorContext allocator = TransferAllocatorContext::unsupported);
// The month change part alone (full game only, when the new day is in another month).
bool month_step(GameState& g, GameRandom& game, WatcomRandom& rand, MinuteReport& report);
} // namespace bmh
namespace bmh {
struct MatchdayContext;
// A day without an event (the "Weiter" loop): the shares move (DailyInterest3), then the
// date counts on and the daily interest is booked (the start of DayStepRest). The rest
// of the day step (day_step_rest) follows.
void plain_day(GameState& g, GameRandom& game, WatcomRandom& rand);
// A calendar entry whose competitions are all switched off (e.g. 0x4006 without the
// option CompetitionSelection bit 1) is still an event for DailyInterest: AdvanceTurn prepares an
// empty matchday (DayCompetitions2, the matchday number, the manager order) without a desk;
// then the date counts on (with the daily interest) as after any event.
bool empty_event_day(GameState& g, const MatchdayContext& ctx, GameRandom& game, WatcomRandom& rand, MinuteReport& report);
// 1 July (DailyInterest: CareerSession_PairingsRuntimeDraw_ExecutableField4 == 1, CareerSession_PairingsRuntimeDraw_ExecutableField5 == 7): the season is over -
// CareerSession_RuntimeError_RuntimeField4 = 1, the prizes for top scorers and fair play (SeasonAwards); no event is
// due any more (EventPasses = 0). The managers' "Saisonende" desk follows.
bool is_season_end(const GameState& g);
void season_end_day(GameState& g);
} // namespace bmh
#include <vector>
#include "game/desk.hpp"
namespace bmh {
// AdvanceTurn up to its desk loop for the day's calendar entry: the match groups
// (DayCompetitions2), the matchday number (CurrentMatchday) and the shuffled order of the
// managers' desks (PrepareEvent, kept in NextDeskManager).
std::vector<MatchGroup> prepare_event(GameState& g, uint16_t calendar_entry, const MatchdayContext& ctx, GameRandom& game,
WatcomRandom& rand, MinuteReport& report);
// One pass of that desk loop for the manager at `position` of the order: ActiveManager /
// DeskPosition, a pre-match offer (PreMatchOffer; true = its message box comes first), the
// pools coupon (BuildPoolsCoupon) and entering the desk (DeskDate).
bool enter_event_desk(GameState& g, int position, const std::vector<MatchGroup>& groups, GameRandom& game,
WatcomRandom& rand, MinuteReport& report, bool prepare_pre_match_offer = true,
const DeskAutosaveHook& autosave = {});
} // namespace bmh
namespace bmh {
// The end of a matchday after its last phase (the part of FinishEvent / AdvanceTurn after
// the matches): the human boards' substitution marks are cleared, every group is processed
// (process_group; a league's result screen - when shown - stirs the numbers, its results go
// into the season table, a cup's into its rounds), the managers' match settings changed
// during the matches (record +0xd2..+0xd9, option byte 2) return to `saved_records` /
// `saved_options` (taken at the kick-off), the leagues count their round and the cups of the
// day move on.
void finish_event(GameState& g, std::vector<MatchGroup>& groups, uint16_t calendar_entry, const std::vector<uint8_t>& buttons,
const std::vector<uint8_t>& saved_records, const std::vector<uint8_t>& saved_options, GameRandom& game,
WatcomRandom& rand, MinuteReport& report, const SeasonCupDrawHook& cup_draw = {},
const SportschauPresentationHooks* sportschau = nullptr,
const std::vector<ShowEvent>* show_events = nullptr,
bool source_sportschau_replay = false,
const SportschauRatingTables* ratings = nullptr);
} // namespace bmh
Loaded 100 of 613 files, more files were not shown because too many files have changed in this diff. Show more