Merge current Engine contracts before publishing post-match UI (by Codex)

This commit is contained in:
Codex committed 2026-10-27 09:56:28 +01:00
commit ef25407484
23 files changed
+1025 -22

No files matched your search

+5 -1
View File
@@ -12,6 +12,7 @@
#include <limits>
#include "app/window_actions.hpp"
#include "game/world_layout.hpp"
#include "cli/console/console.hpp"
#include "cli/console/detail.hpp"
#include "game/bank_credit.hpp"
@@ -324,7 +325,10 @@ void Console::register_money_commands() {
// condition byte to the next multiple of 85 (85, 170, 255; ageing lowers it), and an
// offer exists below 171. The other objects are built once.
std::string state = s.level[o] != 0 ? "built" : "-";
if (o == 0 && s.level[0] != 0) state = "stage " + std::to_string((s.level[0] - 1) / 85 + 1) + " of 3";
if (o == 0 && s.level[0] != 0) { // three stages in steps of 85; a Modern world: four in steps of 64
const int stages = bmh::world_layout().traffic_stages, step = stages == 4 ? 64 : 85;
state = "stage " + std::to_string((s.level[0] - 1) / step + 1) + " of " + std::to_string(stages);
}
rows.push_back({std::to_string(o), text(kPeripheryNames + int(o)), building ? "building" : state,
std::to_string(s.days[o])});
}
+3
View File
@@ -42,6 +42,9 @@ struct WorldLayout {
// national_start: team no_team() + n at national_start + (n - 1) * national_slots). Classic: none,
// the national teams play without players.
uint32_t national_start = 0, national_slots = 0;
// Stages of the traffic access (periphery object 0): Classic 3 (condition byte in steps of
// 0x55), a Modern world 4 (steps of 64; the Modern interface shows four).
int traffic_stages = 3;
int first_amateur() const { return league_teams; }
int first_foreign_cup() const { return league_teams + amateur_teams; }
+502 -3
View File
@@ -654,6 +654,13 @@ ModernSession::ModernSession(const std::filesystem::path &data, uint32_t watcom_
// saves from before the national squads end at the reserve: the national squads
// start empty (those teams play with their drawn rating until the next nomination)
if (g_.squad_slots.size() < world_layout().total_slots) g_.squad_slots.resize(world_layout().total_slots, 0x0fff);
// saves from before the four traffic stages keep the original's scale: convert each
// manager record's traffic access byte to its stage in the new scale
if (modern::four_traffic_stages() && g_.traffic_scale != 64) {
for (size_t rec = 0; rec + 0xb0c <= g_.manager_records.size(); rec += 0xb0c)
g_.manager_records[rec] = modern::traffic_from_original(g_.manager_records[rec]);
g_.traffic_scale = 64;
}
rand_ = saved.random;
game_ = saved.game;
native.emplace();
@@ -4320,6 +4327,7 @@ bool ModernSession::finish(ui::CareerInitializationResult& result, std::string&
// Both UI projections must reflect the freshly initialized driver cursor.
// Reuse its prepared groups; these projections do not prepare an event or draw RNG.
modern::ensure_ui_identities(g_); // career and manager ids of the interface contract
if (modern::four_traffic_stages()) g_.traffic_scale = 64; // the start built the traffic access in that scale
result.desktop = desktop_projection(1);
result.preparation = preparation_projection(1);
for (size_t m = 0; m < managers_.size(); ++m)
@@ -8387,7 +8395,7 @@ bool ModernSession::dispatch_stadium(const ui::StadiumRequest& supplied_request,
request.object >= 14 || !plain(request.object)) return invalid("invalid_periphery_offer");
const size_t object = size_t(request.object);
const uint8_t level = g_.manager_records[record + object];
if (g_.manager_records[record + 0x1e + object] != 0 || (object == 0 ? level >= 0xab : level != 0))
if (g_.manager_records[record + 0x1e + object] != 0 || (object == 0 ? !modern::traffic_buildable(level) : level != 0))
return invalid("periphery_unavailable");
const int32_t price = modern::periphery_offer(g_, request.object, game_);
if (price <= 0) return invalid("invalid_periphery_price");
@@ -8403,7 +8411,7 @@ bool ModernSession::dispatch_stadium(const ui::StadiumRequest& supplied_request,
if (request.kind == ui::StadiumRequestKind::build_periphery) {
const size_t object = size_t(request.object);
const uint8_t level = g_.manager_records[record + object];
if (g_.manager_records[record + 0x1e + object] != 0 || (object == 0 ? level >= 0xab : level != 0))
if (g_.manager_records[record + 0x1e + object] != 0 || (object == 0 ? !modern::traffic_buildable(level) : level != 0))
return invalid("periphery_unavailable");
// ConstructionPricePercent consumes this genuine JA even when PayConstruction's
// payment fails. The Source presenter runs before the quote
@@ -8752,6 +8760,29 @@ std::string ui_text(const cli::Json& j, const char* key) {
} // namespace
cli::Json ModernSession::read_live(const cli::Json& request) const {
using O = cli::Json::Object;
const auto fail = [](const char* e) { return cli::Json(O{{"ok", false}, {"error", e}}); };
if (!request.object()) return fail("invalid_live_query");
for (const auto& [key, value] : *request.object())
if (key != "kind" && key != "revision" && key != "sequence" && key != "fixture_id") return fail("invalid_live_query");
if (!ui_last_advance_) return fail("live_unavailable");
if (const cli::Json* r = ui_field(request, "revision"); r && (!r->integer() || uint64_t(*r->integer()) != ui_last_advance_revision_))
return fail("stale_live_revision");
cli::Json fixture = modern::live_fixture(g_, ui_last_advance_->first, ui_last_advance_->second, ui_last_advance_revision_);
const auto* f = std::get_if<O>(&fixture.value);
if (!f || !std::holds_alternative<bool>(f->at("ok").value) || !std::get<bool>(f->at("ok").value)) return fixture;
if (const cli::Json* id = ui_field(request, "fixture_id"); id && (!id->string() || *id->string() != *f->at("fixture_id").string()))
return fail("stale_live_fixture");
const std::string kind = ui_text(request, "kind").empty() ? "fixture" : ui_text(request, "kind");
if (kind == "fixture") return ui_field(request, "sequence") ? fail("invalid_live_query") : fixture;
if (kind != "frame") return fail("invalid_live_query");
const cli::Json* seq = ui_field(request, "sequence");
const auto& frames = *f->at("frames").array();
if (!seq || !seq->integer() || *seq->integer() < 0 || size_t(*seq->integer()) >= frames.size()) return fail("invalid_live_sequence");
return O{{"ok", true}, {"fixture_id", f->at("fixture_id")}, {"frame", frames[size_t(*seq->integer())]}};
}
cli::Json ModernSession::read_statistics_screen(const cli::Json& request) const {
using O = cli::Json::Object;
using A = cli::Json::Array;
@@ -8823,7 +8854,8 @@ cli::Json ModernSession::ui_read(const cli::Json& request, uint64_t revision) co
const std::string kind = ui_text(request, "kind"), request_id = ui_text(request, "requestId");
const int manager = context.manager;
if (manager < 0 || size_t(manager) >= g_.manager_teams.size() ||
(kind != "lineup" && kind != "tactics" && kind != "training" && kind != "bank" && kind != "contracts"))
(kind != "lineup" && kind != "tactics" && kind != "training" && kind != "bank" && kind != "contracts" &&
kind != "advertising" && kind != "stadium" && kind != "transfer"))
return modern::ui_read(g_, context, request);
if (const std::string wanted = ui_text(request, "managerId"); !wanted.empty() && wanted != modern::ui_manager_id(g_, manager))
return modern::ui_error(request_id, "manager_not_active", "Dieser Manager sitzt nicht am Schreibtisch.", revision, false);
@@ -8853,6 +8885,128 @@ cli::Json ModernSession::ui_read(const cli::Json& request, uint64_t revision) co
{"rows", std::move(rows)}, {"positions", std::move(positions)}, {"depthMax", 19}, {"laneMax", 8},
{"manual", g_.manager_options.size() > size_t(manager) * 5 && g_.manager_options[size_t(manager) * 5] == 0}});
}
if (kind == "transfer") {
// the transfer list (listed players with seller, asking fee, salary reference, offers, the own
// bid), the own squad (listed or not), account and credit line
ui::TransferMarketState mk;
try { mk = ui::transfer_market_from_game(g_, revision); } catch (const std::exception&) {
return modern::ui_error(request_id, "transfer_unavailable", "Der Transfermarkt ist hier nicht verfügbar.", revision, false);
}
static constexpr const char* kPositions[4] = {"gk", "def", "mid", "fwd"};
A listings, squad;
for (const auto& it : mk.items) {
cli::Json bid = nullptr;
if (it.own_bid)
bid = O{{"fee", modern::ui_money(it.own_bid->fee)}, {"annualSalary", modern::ui_money(it.own_bid->annual_salary)},
{"years", int(it.own_bid->contract_years)}};
listings.push_back(O{{"id", "listing:" + std::to_string(it.list_entry)}, {"playerId", modern::ui_player_id(g_, it.player)},
{"name", ui::original_to_utf8(it.name)}, {"age", it.age}, {"position", kPositions[it.position & 3]},
{"strength", it.strength},
{"sellerId", it.seller >= 0 ? cli::Json(modern::ui_team_id(g_, it.seller)) : cli::Json(nullptr)},
{"seller", ui::original_to_utf8(it.seller_name)}, {"askingFee", modern::ui_money(it.asking_fee)},
{"salaryReference", modern::ui_money(it.salary_reference)},
{"salaryDemandPercent", int(it.salary_demand_percent)}, {"offers", it.offers},
{"ownListing", it.own_listing}, {"ownBidPending", it.own_bid_pending}, {"ownBid", std::move(bid)}});
}
for (const auto& s : mk.squad)
squad.push_back(O{{"playerId", modern::ui_player_id(g_, s.player)}, {"name", ui::original_to_utf8(s.name)}, {"age", s.age},
{"position", kPositions[s.position & 3]}, {"strength", s.strength}, {"listed", s.already_listed}});
return modern::ui_snapshot(g_, context, request_id,
O{{"kind", "transfer"}, {"teamId", modern::ui_team_id(g_, team)}, {"listings", std::move(listings)}, {"squad", std::move(squad)},
{"cash", modern::ui_money(mk.balance)}, {"creditLine", modern::ui_money(mk.credit_line)}});
}
if (kind == "stadium") {
// the periphery (14 objects; the traffic access has three stages), the eight facilities with
// their level, the eight stand blocks (capacity in thousands, seats, roof) and the ticket price;
// building prices follow with the stadium quotes (they carry the day's construction percent)
ui::StadiumState st;
ui::StadiumDataProjection data;
try {
st = ui::stadium_from_game(g_, exe_, revision);
data = ui::stadium_data_from_game(g_, exe_, manager, 0x40);
} catch (const std::exception&) {
return modern::ui_error(request_id, "stadium_unavailable", "Das Stadion ist hier nicht verfügbar.", revision, false);
}
const auto text = [&](size_t id) { return g_.texts && id < g_.texts->strings.size() ? ui::original_to_utf8(g_.texts->strings[id]) : std::string{}; };
A periphery, facilities, blocks;
for (size_t o = 0; o < 14; ++o) {
const int level = st.level[o];
O row{{"id", "periphery:" + std::to_string(o)}, {"name", text(720 + o)}, {"constructionDays", int(st.days[o])}};
if (o == 0) row["stage"] = modern::traffic_stage(level), row["maxStage"] = world_layout().traffic_stages;
else row["built"] = level != 0;
periphery.push_back(std::move(row));
}
static constexpr const char* kFacilities[8] = {"floodlights", "scoreboard", "pitch_heating", "vip_lounge", "pitch", "comfort", "condition", "safety"};
for (size_t i = 0; i < 8; ++i) {
const auto& f = st.investments[i];
facilities.push_back(O{{"id", std::string("facility:") + kFacilities[i]}, {"name", text(734 + i)},
{"level", int(f.current_level)}, {"maxLevel", i == 2 || i == 3 ? 2 : 4},
{"constructionWeeks", int(f.construction_weeks)}, {"upgradeAvailable", f.available}});
}
for (size_t b = 0; b < st.blocks.size(); ++b) {
const auto& k = st.blocks[b];
blocks.push_back(O{{"id", "block:" + std::string(1, char('a' + b))}, {"name", text(742 + b)},
{"places", int64_t(k.capacity_level) * 1000},
{"maxPlaces", int64_t(exe_.u8(::bmh::layout::CareerSession_Invalid_RuntimeField + uint32_t(b))) * 1000},
{"seats", (k.flags & 1) != 0}, {"roof", (k.flags & 2) != 0},
{"constructionWeeks", int(k.construction_weeks)}, {"placesAfterConstruction", int64_t(k.capacity) * 1000}});
}
// the open offer of the stadium dialog (quote.request), answered by stadium.commit
cli::Json quote = nullptr;
if (stadium_.opened && stadium_.manager == manager) {
const std::string id = "quote:stadium-" + std::to_string(stadium_.scope);
if (stadium_.periphery_quote)
quote = O{{"id", id}, {"kind", "periphery"}, {"objectId", "periphery:" + std::to_string(stadium_.periphery_quote->first)},
{"price", modern::ui_money(stadium_.periphery_quote->second)}};
else if (stadium_.investment && stadium_.option)
quote = O{{"id", id}, {"kind", "facility"}, {"facilityId", std::string("facility:") + kFacilities[size_t(*stadium_.investment)]},
{"toLevel", int(stadium_.option->target_level)}, {"price", modern::ui_money(stadium_.option->base_price)},
{"weeks", int(stadium_.option->base_weeks)}, {"tipPercent", O{{"min", 6}, {"max", 14}}}};
}
return modern::ui_snapshot(g_, context, request_id,
O{{"kind", "stadium"}, {"teamId", modern::ui_team_id(g_, team)}, {"quote", std::move(quote)}, {"periphery", std::move(periphery)},
{"facilities", std::move(facilities)}, {"blocks", std::move(blocks)},
{"ticketPrice", modern::ui_money(data.ticket_price)}, {"ticketPriceRange", O{{"min", modern::ui_money(8)}, {"max", modern::ui_money(25)}}}});
}
if (kind == "advertising") {
// the 14 boards, the shirt and the TV rights with their contract, the open offers per place,
// the three budgets and the original's finance preview
ui::AdvertisingState a;
try { a = ui::advertising_from_game(g_, manager, revision); } catch (const std::exception&) {
return modern::ui_error(request_id, "advertising_unavailable", "Die Werbung ist hier nicht verfügbar.", revision, false);
}
const auto contract = [&](const ui::AdvertisingContract& c, const std::string& id, int display) {
A offers;
if (display >= 0 && display < 16)
for (const auto& o : a.offers[size_t(display)].offers) {
if (!o.present) continue;
const auto& names = display == 15 ? a.television_sponsor_names : a.board_sponsor_names;
offers.push_back(O{{"id", "offer:ad-" + std::to_string(display) + "-" + std::to_string(o.raw_slot)},
{"sponsor", o.sponsor_id < names.size() ? cli::Json(names[o.sponsor_id]) : cli::Json(nullptr)},
{"monthly", modern::ui_money(o.monthly_amount)}, {"boards", int(o.bundle_units)},
{"months", int(o.months)}, {"allowed", o.can_accept}});
}
return cli::Json(O{{"id", id}, {"active", c.active},
{"sponsor", c.active ? cli::Json(c.sponsor_name) : cli::Json(nullptr)},
{"monthly", modern::ui_money(c.monthly_amount)}, {"monthsRemaining", int(c.months_remaining)},
{"extensionMonths", int(c.extension_months)}, {"option", c.option_marker},
{"offers", std::move(offers)}});
};
A boards;
for (size_t i = 0; i < a.boards.size(); ++i) boards.push_back(contract(a.boards[i], "ad:board/" + std::to_string(i), int(i)));
A budgets;
static constexpr const char* kBudgets[3] = {"budget:merchandise", "budget:press", "budget:fans"};
for (size_t i = 0; i < 3; ++i)
budgets.push_back(O{{"id", kBudgets[i]}, {"label", a.spending_labels[i]}, {"current", modern::ui_money(a.spending[i].current_amount)},
{"maximum", modern::ui_money(a.spending[i].maximum_amount)}, {"deliveryWeeks", int(a.spending[i].delivery_weeks)},
{"available", a.spending[i].available}});
return modern::ui_snapshot(g_, context, request_id,
O{{"kind", "advertising"}, {"teamId", modern::ui_team_id(g_, team)}, {"boards", std::move(boards)},
{"shirt", contract(a.shirt, "ad:shirt", 14)}, {"television", contract(a.television, "ad:tv", 15)},
{"budgets", std::move(budgets)},
{"preview", O{{"income", modern::ui_money(a.finance_preview.income)}, {"expenses", modern::ui_money(a.finance_preview.expenses)},
{"balance", modern::ui_money(a.finance_preview.balance)}}}});
}
if (kind == "contracts") {
// per player: remaining months, monthly salary, insurance, the team bonuses; the open quote
// (quote.request) with the monthly demand for one to four years
@@ -8985,10 +9139,18 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision
const int saved_entry_manager = lineup_entry_manager_, saved_entry_club = lineup_entry_club_;
const auto saved_quote = contract_quote_;
const uint64_t saved_quote_id = next_contract_quote_id_, saved_contract_request = last_contract_request_id_;
const uint64_t saved_advertising_request = last_advertising_request_id_;
const StadiumRuntime saved_stadium = stadium_;
const uint64_t saved_stadium_scope = next_stadium_scope_;
const auto saved_offer_editor = transfer_offer_editor_;
const uint64_t saved_offer_revision = transfer_offer_revision_;
const auto restore = [&] {
g_ = saved_state; rand_ = saved_rand; game_ = saved_game; revision = previous;
lineup_entry_manager_ = saved_entry_manager, lineup_entry_club_ = saved_entry_club; // the board stays as it was
contract_quote_ = saved_quote, next_contract_quote_id_ = saved_quote_id, last_contract_request_id_ = saved_contract_request;
last_advertising_request_id_ = saved_advertising_request;
stadium_ = saved_stadium, next_stadium_scope_ = saved_stadium_scope;
transfer_offer_editor_ = saved_offer_editor, transfer_offer_revision_ = saved_offer_revision;
};
cli::Json answer;
std::string error;
@@ -9141,19 +9303,73 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision
} else if (kind == "session.advance") {
// payload {}: the kickoff of the desk - the calendar runs (matches without live view) to the
// next desk of a human manager, the season end desk or the end of the career
// contractExpiry {playerId: {action: "renew", years 1-4, monthlySalary: Money} | {action: "release"}}:
// the answers to contracts running out on the way (the original asks at that moment). A
// contract without an answer stops the run: it is rolled back and decision_pending names
// the player, the interface asks and sends the advance again with the answer.
struct Expiry { bool renew = false; int term = 0; uint32_t salary = 0; };
std::map<std::string, Expiry> answers;
if (const cli::Json* e = ui_field(*payload, "contractExpiry"); e && e->object())
for (const auto& [id, value] : *e->object()) {
Expiry x;
const std::string action = ui_text(value, "action");
if (action == "renew") {
const cli::Json* years = ui_field(value, "years");
const cli::Json* salary = ui_field(value, "monthlySalary");
int64_t cents = -1;
try { cents = salary ? std::stoll(ui_text(*salary, "minor")) : -1; } catch (const std::exception&) { cents = -1; }
if (!years || !years->integer() || *years->integer() < 1 || *years->integer() > 4 || cents < 0 || cents % 100)
return refuse("invalid_payload", "contractExpiry: renew braucht years 1-4 und monthlySalary.");
x.renew = true, x.term = int(*years->integer() - 1), x.salary = uint32_t(cents / 100);
} else if (action != "release") {
return refuse("invalid_payload", "contractExpiry: action ist renew oder release.");
}
answers[id] = x;
}
std::string pending_player;
auto previous_hook = g_.contract_screen;
const bool previous_installed = contract_expiry_presenter_installed_;
set_contract_expiry_presenter([&](modern::ModernState& state, WatcomRandom& random, int m, int row) -> int {
const int team = m >= 0 && size_t(m) < state.manager_teams.size() ? state.manager_teams[size_t(m)] : -1;
const SquadRange range = squad_range(team);
const int p = size_t(row) < range.count ? state.squad_slots[range.first + size_t(row)] & 0x0fff : 0x0fff;
const std::string id = p == 0x0fff ? std::string{} : modern::ui_player_id(state, p);
const auto it = answers.find(id);
if (it == answers.end()) { pending_player = id; return -2; } // ask the interface
if (!it->second.renew) return 0; // released
try {
const auto demands = modern::contract_demands(state, m, row, false, random);
const uint32_t demand = demands[size_t(it->second.term)];
if (demand == 0 || demand == UINT32_MAX) return 0;
return modern::contract_offer(state, m, row, it->second.term, it->second.salary, demand, false, true, random, nullptr) ? 1 : 0;
} catch (const std::exception&) {
return -2;
}
});
ui::DeskRequest kickoff;
kickoff.kind = ui::DeskRequestKind::advance_turn;
kickoff.manager_slot = manager;
kickoff.revision = revision;
const TurnAdvanceResult r = dispatch_kickoff(kickoff, revision, error);
g_.contract_screen = previous_hook; // the session's own presenter again
contract_expiry_presenter_installed_ = previous_installed;
if (r.kind == TurnDeskKind::Failed || r.kind == TurnDeskKind::WaitingAtDesk) {
restore();
g_.contract_screen = previous_hook;
if (!pending_player.empty()) {
cli::Json pending = refuse("decision_pending", "Ein Vertrag läuft aus: Verlängern oder freigeben?");
auto& message = std::get<cli::Json::Object>(std::get<cli::Json::Object>(pending.value)["message"].value);
message["args"] = cli::Json::Object{{"decision", "contract_expiry"}, {"playerId", pending_player}};
return pending;
}
const std::string reason = r.reason.empty() ? error : r.reason;
return refuse(r.kind == TurnDeskKind::WaitingAtDesk ? "decision_pending" : "advance_failed",
"Weiter nicht möglich: " + reason);
}
modern::ensure_ui_identities(g_);
revision = previous + 1;
ui_last_advance_ = std::make_pair(saved_state.date, g_.date); // what read_live replays
ui_last_advance_revision_ = revision;
const char* what = r.kind == TurnDeskKind::SeasonEndDesk ? "Saisonende." : r.kind == TurnDeskKind::CareerComplete
? "Die Karriere ist zu Ende." : "Weiter zum nächsten Termin.";
answer = modern::ui_command_result(request_id, previous, revision,
@@ -9161,6 +9377,95 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision
"statistics", "almanac"}, what);
if (r.kind == TurnDeskKind::CareerComplete)
std::get<cli::Json::Object>(answer.value)["outcome"] = "career_ended";
} else if ((kind == "quote.request" && (ui_text(*payload, "kind") == "periphery" || ui_text(*payload, "kind") == "facility")) ||
kind == "stadium.commit") {
// The stadium dialog of the original in two commands; it stays open in between:
// quote.request {kind: periphery, objectId} - opens the stadium, the building firm's offer
// quote.request {kind: facility, facilityId, increment 1-3} - a facility and how many levels
// stadium.commit {quoteId, accept, tip?} - builds (facilities: with or without the tip for
// faster building, as the original asks) or declines, and closes the stadium
const int team = g_.manager_teams[size_t(manager)];
if (team < 0 || team >= league_clubs()) return refuse("no_club", "Am Schreibtisch des Bundestrainers gibt es kein Stadion.");
bool ok = true;
const auto step = [&](ui::StadiumRequestKind k, int object = -1, int option = -1, int32_t price = 0, bool tip = false) {
if (!ok) return;
ui::StadiumRequest r;
r.kind = k, r.manager_slot = manager, r.runtime_club = team, r.revision = revision;
r.stable_club_identity = int(g_.club_ids.at(size_t(team)));
if (k != ui::StadiumRequestKind::open) r.scope = stadium_.scope, r.sequence = stadium_.sequence;
r.object = object, r.option = option, r.price = price, r.accept_tip = tip;
ok = dispatch_stadium(r, revision, error);
};
static constexpr const char* kFacilities[8] = {"floodlights", "scoreboard", "pitch_heating", "vip_lounge", "pitch", "comfort", "condition", "safety"};
if (kind == "quote.request") {
if (stadium_.opened && (stadium_.periphery_quote || stadium_.investment))
return refuse("quote_open", "Ein Stadionangebot ist noch offen (stadium.commit).");
if (!stadium_.opened) step(ui::StadiumRequestKind::open);
if (ui_text(*payload, "kind") == "periphery") {
int object = -1;
if (std::sscanf(ui_text(*payload, "objectId").c_str(), "periphery:%d", &object) != 1 || object < 0 || object >= 14) {
restore(); return refuse("unknown_object", "Unbekanntes Umfeldobjekt.");
}
step(ui::StadiumRequestKind::quote_periphery, object);
} else {
const std::string id = ui_text(*payload, "facilityId");
int facility = -1;
for (int i = 0; i < 8; ++i) if (id == std::string("facility:") + kFacilities[i]) facility = i;
const cli::Json* inc = ui_field(*payload, "increment");
if (facility < 0 || !inc || !inc->integer() || *inc->integer() < 1 || *inc->integer() > 3) {
restore(); return refuse("invalid_payload", "facilityId und increment (1 bis 3) nötig.");
}
step(ui::StadiumRequestKind::select_investment, facility);
if (ok) {
StadiumInvestmentConstants constants;
for (unsigned i = 0; i < 8; ++i) {
constants.price[i] = exe_.u32(::bmh::layout::CareerSession_DispatchStadium_RuntimeField + i * 4);
constants.weeks[i] = exe_.u8(::bmh::layout::CareerSession_DispatchStadium_RuntimeField2 + (14 + i) * 5);
}
const auto options = modern::stadium_investment_options_source(g_, manager, static_cast<StadiumInvestment>(facility),
stadium_.price_percent, constants);
const size_t option = size_t(*inc->integer() - 1);
if (option >= options.size()) { restore(); return refuse("level_unavailable", "So viele Stufen sind nicht möglich."); }
step(ui::StadiumRequestKind::select_investment_option, facility, int(option), int32_t(options[option].base_price));
}
}
if (!ok) { restore(); return refuse("stadium_refused", error); }
revision = previous + 1;
stadium_.revision = revision; // the open dialog continues at the command's one revision
answer = modern::ui_command_result(request_id, previous, revision, {"stadium"}, "Angebot liegt vor.");
std::get<cli::Json::Object>(answer.value)["outcome"] = "offer_pending";
} else {
const std::string quote = ui_text(*payload, "quoteId");
const cli::Json* accept = ui_field(*payload, "accept");
const cli::Json* tip = ui_field(*payload, "tip");
const bool yes = accept && std::holds_alternative<bool>(accept->value) && std::get<bool>(accept->value);
const bool with_tip = tip && std::holds_alternative<bool>(tip->value) && std::get<bool>(tip->value);
if (!stadium_.opened || quote != "quote:stadium-" + std::to_string(stadium_.scope))
return refuse("stale_quote", "Dieses Stadionangebot gilt nicht mehr.");
if (stadium_.periphery_quote) {
const auto [object, price] = *stadium_.periphery_quote;
step(yes ? ui::StadiumRequestKind::build_periphery : ui::StadiumRequestKind::decline_periphery, object, -1, price);
} else if (stadium_.investment && stadium_.option) {
const int facility = int(*stadium_.investment), option = stadium_.option_index;
const int32_t base = int32_t(stadium_.option->base_price);
if (!yes) {
step(ui::StadiumRequestKind::cancel_investment, facility);
} else {
step(ui::StadiumRequestKind::confirm_investment, facility, option, base);
if (ok && stadium_.tip)
step(ui::StadiumRequestKind::answer_construction_tip, facility, option,
int32_t(with_tip ? stadium_.tip->offered_price : stadium_.tip->base_price), with_tip);
}
} else {
return refuse("stale_quote", "Es liegt kein Stadionangebot vor.");
}
const std::string feedback = stadium_.feedback;
step(ui::StadiumRequestKind::close);
if (!ok) { restore(); return refuse("stadium_refused", error); }
revision = previous + 1;
answer = modern::ui_command_result(request_id, previous, revision, {"stadium", "desktop", "bank"},
!feedback.empty() ? feedback : yes ? "Der Bau beginnt." : "Abgelehnt.");
}
} else if (kind == "quote.request" || kind == "contract.offer") {
// quote.request {kind: "contract", playerId}: the player's demands for one to four years
// (draws a random number, as at the desk); contract.offer {quoteId, years 1-4,
@@ -9216,6 +9521,200 @@ cli::Json ModernSession::ui_command(const cli::Json& request, uint64_t& revision
: result.feedback);
if (!result.accepted) std::get<cli::Json::Object>(answer.value)["outcome"] = "offer_rejected";
}
} else if (kind == "advertising.accept" || kind == "budget.commit") {
// advertising.accept {offerId: "offer:ad-<display>-<pool slot>"}: an offer of the advertising read;
// budget.commit {budgetId: "budget:merchandise|press|fans", amount: Money}
const int team = g_.manager_teams[size_t(manager)];
if (team < 0 || team >= league_clubs()) return refuse("no_club", "Am Schreibtisch des Bundestrainers gibt es keine Werbung.");
const ui::AdvertisingState a = ui::advertising_from_game(g_, manager, revision);
ui::AdvertisingRequest r;
r.request_id = last_advertising_request_id_ + 1;
r.manager_slot = manager, r.runtime_club = team, r.revision = revision;
if (kind == "advertising.accept") {
const std::string id = ui_text(*payload, "offerId");
int display = -1, raw = -1;
if (std::sscanf(id.c_str(), "offer:ad-%d-%d", &display, &raw) != 2 || display < 0 || display >= 16)
return refuse("unknown_offer", "Unbekanntes Werbeangebot: " + id);
const auto& list = a.offers[size_t(display)];
const auto offer = std::find_if(list.offers.begin(), list.offers.end(), [&](const auto& o) { return o.present && o.raw_slot == raw; });
if (offer == list.offers.end() || !offer->can_accept) return refuse("unknown_offer", "Dieses Werbeangebot gibt es nicht (mehr).");
r.kind = ui::AdvertisingActionKind::accept_offer;
r.offer.manager = manager, r.offer.display_slot = display, r.offer.contract_slot = list.contract_slot;
r.offer.expected_contract = list.contract_bytes, r.offer.raw_slot = raw, r.offer.expected_offer = offer->bytes;
} else {
const std::string id = ui_text(*payload, "budgetId");
const int index = id == "budget:merchandise" ? 0 : id == "budget:press" ? 1 : id == "budget:fans" ? 2 : -1;
if (index < 0) return refuse("unknown_budget", "Unbekanntes Budget: " + id);
const cli::Json* amount = ui_field(*payload, "amount");
int64_t cents = -1;
try { cents = amount ? std::stoll(ui_text(*amount, "minor")) : -1; } catch (const std::exception&) { cents = -1; }
if (cents < 0 || cents % 100 || cents / 100 > UINT32_MAX) return refuse("invalid_amount", "amount in ganzen Euro (Money).");
const auto& view = a.spending[size_t(index)];
r.kind = ui::AdvertisingActionKind::set_spending;
r.spending.manager = manager, r.spending.target_slot = view.target_slot, r.spending.amount = uint32_t(cents / 100);
r.spending.expected_amount = view.current_amount, r.spending.expected_delivery_weeks = view.delivery_weeks;
}
if (!dispatch_advertising(r, revision, error)) { restore(); return refuse("advertising_refused", error); }
revision = previous + 1;
answer = modern::ui_command_result(request_id, previous, revision, {"advertising", "desktop", "bank"},
kind == "advertising.accept" ? "Werbevertrag abgeschlossen." : "Budget gesetzt.");
} else if (kind == "transfer.submit") {
// {action: "list", playerId, loan?}: an own player on the transfer list (or offered for loan)
// {action: "bid", listingId, fee, monthlySalary, years 1-4, loan?}: an offer on a listed player
// through the original's offer editor (open, set the fields, submit). A question to a human
// seller (poaching) is not supported yet and rolls back with decision_pending.
const int team = g_.manager_teams[size_t(manager)];
if (team < 0 || team >= league_clubs()) return refuse("no_club", "Am Schreibtisch des Bundestrainers gibt es keine Transfers.");
const std::string action = ui_text(*payload, "action");
const cli::Json* loan_field = ui_field(*payload, "loan");
const bool loan = loan_field && std::holds_alternative<bool>(loan_field->value) && std::get<bool>(loan_field->value);
std::vector<std::string> notices;
bool question = false;
HumanBuyerSaleHooks hooks;
hooks.notice = [&](const GameState&, const HumanBuyerSaleNotice& n) { notices.push_back(ui::original_to_utf8(n.original_message)); };
hooks.confirm = [&](const GameState&, int, const std::string&) -> bool { question = true; throw std::runtime_error("question"); };
const ui::TransferMarketState m = ui::transfer_market_from_game(g_, revision);
std::string feedback;
bool bid_pending = false;
try {
if (action == "list") {
const std::string id = ui_text(*payload, "playerId");
const auto item = std::find_if(m.squad.begin(), m.squad.end(), [&](const auto& s) { return modern::ui_player_id(g_, s.player) == id; });
if (item == m.squad.end()) return refuse("unknown_player", "Spieler nicht im Kader: " + id);
if (item->already_listed) return refuse("already_listed", "Der Spieler steht schon auf der Liste.");
ui::TransferMarketRequest r;
r.kind = ui::TransferMarketRequestKind::list_player;
r.offer_is_loan = loan;
r.manager_slot = m.manager_slot, r.runtime_club = m.runtime_club, r.revision = m.revision;
r.squad_row = item->row, r.expected_player = item->player;
r.selected_players.push_back({-1, m.roster.squad_start_offset + item->row, item->player, m.runtime_club, item->row});
if (!dispatch_transfer_market(r, hooks, revision, error)) { restore(); return refuse("transfer_refused", error); }
feedback = loan ? "Der Spieler wird zum Verleih angeboten." : "Der Spieler steht auf der Transferliste.";
} else if (action == "bid") {
int entry = -1;
if (std::sscanf(ui_text(*payload, "listingId").c_str(), "listing:%d", &entry) != 1) return refuse("unknown_listing", "listingId fehlt.");
const auto item = std::find_if(m.items.begin(), m.items.end(), [&](const auto& it) { return it.list_entry == entry; });
if (item == m.items.end()) return refuse("unknown_listing", "Dieser Listenplatz ist nicht (mehr) belegt.");
if (item->own_listing) return refuse("own_player", "Das ist ein eigener Spieler.");
const auto money_of = [&](const char* key) -> int64_t {
const cli::Json* v = ui_field(*payload, key);
try { return v ? std::stoll(ui_text(*v, "minor")) : -1; } catch (const std::exception&) { return -1; }
};
const int64_t fee = money_of("fee"), salary = money_of("monthlySalary");
const cli::Json* years = ui_field(*payload, "years");
if (fee < 0 || fee % 100 || salary < 0 || salary % 100 || !years || !years->integer() || *years->integer() < 1 || *years->integer() > 4)
return refuse("invalid_payload", "fee, monthlySalary (Money, ganze Euro) und years 1-4 nötig.");
ui::TransferMarketRequest open;
open.kind = ui::TransferMarketRequestKind::open_offer;
open.offer_is_loan = loan;
open.manager_slot = m.manager_slot, open.runtime_club = m.runtime_club, open.revision = m.revision;
if (item->own_bid) open.bid = *item->own_bid;
open.bid.manager = m.manager_slot, open.bid.list_entry = item->list_entry, open.bid.player = item->player;
open.bid.source_slot = item->source_slot;
open.selected_players.push_back({item->list_entry, item->source_slot, item->player, item->seller, -1});
auto opened = open_transfer_offer(open, revision, error);
if (!opened) { restore(); return refuse("transfer_refused", error); }
ui::OutgoingTransferEditorState e = opened->editor;
if (!e.editable) { restore(); return refuse("no_bid_slot", "Für diesen Spieler ist kein Angebot möglich."); }
const auto edit = [&](ui::OutgoingTransferRequestKind k, ui::OutgoingTransferField field, uint32_t value)
-> std::optional<TransferOfferEditorDispatch> {
ui::OutgoingTransferRequest r;
r.kind = k;
r.identity = {e.manager_slot, e.runtime_club, e.revision, e.list_entry, e.source_slot, e.player, e.seller, e.bid_slot};
r.field = field, r.value = value, r.quote_loan = e.quote_loan;
r.fee = e.fee, r.monthly_salary = e.monthly_salary, r.duration_years = e.duration_years, r.bonuses = e.bonuses;
r.quoted_fee = e.panel.quoted_fee, r.quoted_monthly_salary = e.panel.quoted_monthly_salary, r.quoted_years = e.panel.quoted_years;
auto d = dispatch_transfer_offer(r, hooks, revision, error);
if (d) e = d->editor;
return d;
};
// the screen stores the edited value and asks for a fresh quote, one field at a time
bool ok = true;
if (ok && e.fee != uint32_t(fee / 100)) { e.fee = uint32_t(fee / 100); ok = bool(edit(ui::OutgoingTransferRequestKind::quote_change, ui::OutgoingTransferField::fee, e.fee)); }
if (ok && e.monthly_salary != uint32_t(salary / 100)) {
e.monthly_salary = uint32_t(salary / 100);
ok = bool(edit(ui::OutgoingTransferRequestKind::quote_change, ui::OutgoingTransferField::monthly_salary, e.monthly_salary));
}
if (ok && e.duration_years != uint8_t(*years->integer())) {
e.duration_years = uint8_t(*years->integer());
ok = bool(edit(ui::OutgoingTransferRequestKind::quote_change, ui::OutgoingTransferField::duration_years, e.duration_years));
}
std::optional<TransferOfferEditorDispatch> sent;
if (ok) sent = edit(ui::OutgoingTransferRequestKind::submit, ui::OutgoingTransferField::fee, e.fee);
if (!sent) { restore(); return refuse("transfer_refused", error); }
const TransferActionStatus status = sent->action.status;
bid_pending = status == TransferActionStatus::pending;
if (!e.closed) edit(ui::OutgoingTransferRequestKind::cancel, ui::OutgoingTransferField::fee, e.fee); // a low offer keeps it open
feedback = status == TransferActionStatus::accepted ? "Angenommen: Der Spieler wechselt zu Ihrem Verein."
: status == TransferActionStatus::pending ? "Angebot abgegeben; die Antwort kommt mit der nächsten Woche."
: status == TransferActionStatus::offer_too_low ? "Das Angebot ist zu niedrig."
: "Das Angebot wurde abgelehnt.";
if (status != TransferActionStatus::accepted && status != TransferActionStatus::pending) {
revision = previous + 1;
answer = modern::ui_command_result(request_id, previous, revision, {"transfer"}, feedback);
std::get<cli::Json::Object>(answer.value)["outcome"] = "offer_rejected";
}
} else {
return refuse("invalid_payload", "action ist list oder bid.");
}
} catch (const std::exception& ex) {
restore();
if (question) return refuse("decision_pending", "Ein menschlicher Verkäufer müsste gefragt werden (noch nicht unterstützt).");
return refuse("transfer_refused", ex.what());
}
for (const auto& n : notices) feedback += (feedback.empty() ? "" : " ") + n;
if (std::holds_alternative<std::nullptr_t>(answer.value)) {
revision = previous + 1;
answer = modern::ui_command_result(request_id, previous, revision, {"transfer", "squad", "desktop"}, feedback);
if (bid_pending) std::get<cli::Json::Object>(answer.value)["outcome"] = "offer_pending";
}
} else if (kind == "toto.submit") {
// payload {stake: Money per column, columns: [[11 tips: 1 home, 0 draw, 2 away], ... up to 6]}
const cli::Json* stake = ui_field(*payload, "stake");
const cli::Json* columns = ui_field(*payload, "columns");
int64_t cents = -1;
try { cents = stake ? std::stoll(ui_text(*stake, "minor")) : -1; } catch (const std::exception&) { cents = -1; }
if (cents <= 0 || cents % 100 || !columns || !columns->array()) return refuse("invalid_payload", "stake (Money) und columns nötig.");
std::vector<std::array<uint8_t, 11>> tips;
for (const auto& column : *columns->array()) {
const auto* c = column.array();
if (!c || c->size() != 11) return refuse("invalid_payload", "Jede Spalte hat elf Tipps.");
std::array<uint8_t, 11> t{};
for (size_t i = 0; i < 11; ++i) {
if (!(*c)[i].integer() || *(*c)[i].integer() < 0 || *(*c)[i].integer() > 2) return refuse("invalid_payload", "Tipps sind 0, 1 oder 2.");
t[i] = uint8_t(*(*c)[i].integer());
}
tips.push_back(t);
}
if (!dispatch_pools_columns(manager, uint32_t(cents / 100), tips, revision, error)) { restore(); return refuse("toto_refused", error); }
revision = previous + 1;
answer = modern::ui_command_result(request_id, previous, revision, {"toto", "desktop"}, "Tippschein abgegeben.");
} else if (kind == "sponsor.answer") {
// payload {accept: bool}: the answer to the exclusive sponsor offer from a camp stay
const cli::Json* accept = ui_field(*payload, "accept");
if (!accept || !std::holds_alternative<bool>(accept->value)) return refuse("invalid_payload", "accept (true/false) nötig.");
std::string result;
if (!dispatch_exclusive_sponsor(manager, std::get<bool>(accept->value), revision, result, error)) {
restore(); return refuse(error.empty() ? "sponsor_refused" : error, "Kein Sponsorangebot offen.");
}
revision = previous + 1;
answer = modern::ui_command_result(request_id, previous, revision, {"sponsor", "advertising", "desktop"},
result == "started" ? "Der Exklusiv-Sponsor beginnt sofort." :
result == "queued" ? "Der Exklusiv-Sponsor beginnt, sobald die Fläche frei ist." :
"Angebot abgelehnt.");
} else if (kind == "ticket.commit") {
// payload {price: Money}: the admission price, 8 to 25 euros
const cli::Json* price = ui_field(*payload, "price");
int64_t cents = -1;
try { cents = price ? std::stoll(ui_text(*price, "minor")) : -1; } catch (const std::exception&) { cents = -1; }
if (cents < 800 || cents > 2500 || cents % 100) return refuse("invalid_amount", "Eintritt 8 bis 25 Euro in ganzen Euro.");
TicketPriceRequest r;
r.identity.manager_slot = manager, r.identity.runtime_club = g_.manager_teams[size_t(manager)], r.identity.revision = revision;
r.identity.stable_club_identity = int(g_.club_ids.at(size_t(r.identity.runtime_club)));
r.price = int(cents / 100);
if (!dispatch_ticket_price(r, revision, error)) { restore(); return refuse("ticket_refused", error); }
if (revision != previous) revision = previous + 1;
answer = modern::ui_command_result(request_id, previous, revision, {"stadium"}, "Eintrittspreis gesetzt.");
} else if (kind == "bank.commit") {
// payload {action: deposit|withdraw, amount: Money} or {action: buy|sell, assetId: stock:<n>|fund:<n>, count}
const std::string action = ui_text(*payload, "action");
+7
View File
@@ -4,6 +4,7 @@
#include "modern/content/projections.hpp"
#include "modern/content/statistics.hpp"
#include "modern/content/ui_contract.hpp"
#include "modern/game/traffic.hpp"
#include "modern/content/world_expand.hpp"
// The engine side of the UI's career handoff (src/ui/flow.hpp, ENGINE_BINDING.md).
//
@@ -834,6 +835,9 @@ public:
// The almanac screen (index, calendar, day, match; docs/new_engine/ui-anbindung.md). Read-only.
cli::Json read_almanac(const cli::Json& request) const { return query_almanac(g_, request); }
// The statistics screen for the manager at the desk (docs/new_engine/ui-anbindung.md). Read-only.
// The live ticker (DataSource::read_live): {kind: "fixture"} the recorded matches of the last
// session.advance, {kind: "frame", sequence} one of its frames; revision/fixture_id as in the demo.
cli::Json read_live(const cli::Json& request) const;
// Sections 1 (transfer history) and 2 (the six curves) come from the original's own records.
cli::Json read_statistics_screen(const cli::Json& request) const;
// The read queries of the new interface (docs/new_engine/ui-abfragen.md): status, leagues,
@@ -1001,6 +1005,9 @@ private:
// ui_command: answers by requestId (the command as JSON, the answer) for repeated commands,
// the last 64 in this process; after a restart expectedRevision prevents a second booking.
std::map<std::string, std::pair<std::string, cli::Json>> ui_answers_;
// the day counters around the last session.advance and the revision after it (read_live)
std::optional<std::pair<uint32_t, uint32_t>> ui_last_advance_;
uint64_t ui_last_advance_revision_ = 0;
std::vector<std::string> ui_answer_order_;
std::filesystem::path data_directory_;
+140
View File
@@ -747,4 +747,144 @@ cli::Json query_statistics_screen(const ModernState& g, int manager, const cli::
}
}
// --- the live ticker of the Modern UI: the recorded matches of the last kickoff ---------------
namespace {
// The ticker's lines for an event of the almanac (German, as the interface's demo).
std::pair<std::string, std::string> ticker_text(const AlmanacSeason& s, const AlmanacMatch& m, const AlmanacEvent& e,
int home, int away) {
const std::string team = s.clubs[e.side ? m.away : m.home].name;
const std::string who = e.player != kAlmanacNone && e.player < s.players.size() ? player_name(s.players[e.player]) : team;
const std::string other = e.other != kAlmanacNone && e.other < s.players.size() ? player_name(s.players[e.other]) : std::string{};
const std::string score = std::to_string(home) + ":" + std::to_string(away);
switch (e.kind) {
case AlmanacEventKind::Goal:
return {"Tor für " + team, who + " trifft zum " + score + "." + (other.empty() ? "" : " Vorlage: " + other + ".")};
case AlmanacEventKind::Miss: return {"Chance für " + team, who + " vergibt."};
case AlmanacEventKind::YellowCard: return {"Gelbe Karte", who + " (" + team + ") sieht Gelb."};
case AlmanacEventKind::SecondYellow: return {"Gelb-Rot", who + " (" + team + ") muss vom Platz."};
case AlmanacEventKind::RedCard: return {"Rote Karte", who + " (" + team + ") fliegt vom Platz."};
case AlmanacEventKind::Injury: return {"Verletzung", who + " (" + team + ") ist verletzt."};
case AlmanacEventKind::Substitution:
return {"Wechsel bei " + team, who + (other.empty() ? " kommt ins Spiel." : " kommt für " + other + ".")};
case AlmanacEventKind::ShootoutKick:
return {"Elfmeterschießen", who + (e.detail ? " verwandelt." : " verschießt.")};
}
return {"", ""};
}
const char* event_kind(AlmanacEventKind k) {
static constexpr const char* kKinds[8] = {"goal", "yellow", "red", "second_yellow", "injury", "substitution", "shootout", "miss"};
return kKinds[size_t(k) & 7];
}
} // namespace
cli::Json live_fixture(const ModernState& g, uint32_t after_date, uint32_t until_date, uint64_t revision) {
// the matches of the last kickoff (dates after_date <= d < until_date) from the almanac: the
// ones with a human manager are the ticker's matches (at most four), all others the conference
struct Ref { const AlmanacSeason* season; size_t index; };
const auto seasons = seasons_of(g);
std::vector<Ref> human, others;
for (const auto& s : seasons)
for (size_t i = 0; i < s.matches.size(); ++i) {
const AlmanacMatch& m = s.matches[i];
if (m.date < after_date || m.date >= until_date) continue; // played from the desk day on, before the next desk
((m.home_manager >= 0 || m.away_manager >= 0) && human.size() < 4 ? human : others).push_back({&s, i});
}
if (human.empty()) return O{{"ok", false}, {"error", "live_no_human_match"}};
A owners, matches, conference;
std::map<std::string, std::string> owner_match;
for (const Ref& r : human) {
const AlmanacSeason& s = *r.season;
const AlmanacMatch& m = s.matches[r.index];
const std::string id = match_id(s, r.index);
A match_owners;
for (int side = 0; side < 2; ++side) {
const int8_t mi = side ? m.away_manager : m.home_manager;
if (mi < 0 || size_t(mi) >= s.managers.size()) continue;
const AlmanacManager& a = s.managers[size_t(mi)];
std::string mid = a.index >= 0 && size_t(a.index) < g.manager_ids.size() ? g.manager_ids[size_t(a.index)] : std::string{};
if (mid.empty()) mid = "manager:slot-" + std::to_string(a.index);
if (owner_match.count(mid)) continue;
owner_match[mid] = id;
match_owners.push_back(mid);
const AlmanacClub& c = s.clubs[side ? m.away : m.home];
const size_t rec = size_t(std::max(0, a.index)) * 0xb0c + 0x221;
owners.push_back(O{{"id", mid}, {"portrait", rec < g.manager_records.size() ? int(g.manager_records[rec]) : 0},
{"name", a.name}, {"team", O{{"id", c.id}, {"name", c.name}, {"role", c.id.starts_with("nt:") ? "national" : "club"}}},
{"match_id", id}, {"view", nullptr}});
}
const Competition c = competition_of(g, s, m);
matches.push_back(O{{"id", id}, {"home", O{{"id", s.clubs[m.home].id}, {"name", s.clubs[m.home].name}}},
{"away", O{{"id", s.clubs[m.away].id}, {"name", s.clubs[m.away].name}}},
{"owners", std::move(match_owners)}, {"competition", c.name}});
}
for (const Ref& r : others) conference.push_back(almanac_match(g, *r.season, r.index));
// the frames: kickoff, every event of a ticker match in minute order, half time, the end
struct Moment { int minute; int order; const Ref* ref; const AlmanacEvent* event; const char* phase; };
std::vector<Moment> moments;
bool extra = false, shootout = false;
for (const Ref& r : human) {
const AlmanacMatch& m = r.season->matches[r.index];
extra |= m.decided >= 1, shootout |= m.decided == 2;
for (const auto& e : m.events) moments.push_back({e.minute, 1, &r, &e, nullptr});
}
moments.push_back({0, 0, nullptr, nullptr, "kickoff"});
moments.push_back({45, 2, nullptr, nullptr, "interval"});
moments.push_back({46, 0, nullptr, nullptr, "restart"});
moments.push_back({extra ? 120 : 90, 3, nullptr, nullptr, shootout ? "shootout_end" : "fulltime"});
std::stable_sort(moments.begin(), moments.end(), [](const Moment& a, const Moment& b) {
return a.minute != b.minute ? a.minute < b.minute : a.order < b.order;
});
struct Tally { int score[2] = {0, 0}, chances[2] = {0, 0}, yellow[2] = {0, 0}, red[2] = {0, 0}, shootout[2] = {0, 0}; };
std::vector<Tally> tally(human.size());
A frames, events;
for (const Moment& mo : moments) {
if (mo.event) {
const size_t k = size_t(mo.ref - human.data());
const AlmanacSeason& s = *mo.ref->season;
const AlmanacMatch& m = s.matches[mo.ref->index];
const AlmanacEvent& e = *mo.event;
Tally& t = tally[k];
const size_t side = e.side ? 1 : 0;
if (e.kind == AlmanacEventKind::Goal) ++t.score[side], ++t.chances[side];
if (e.kind == AlmanacEventKind::Miss) ++t.chances[side];
if (e.kind == AlmanacEventKind::YellowCard) ++t.yellow[side];
if (e.kind == AlmanacEventKind::RedCard || e.kind == AlmanacEventKind::SecondYellow) ++t.red[side];
if (e.kind == AlmanacEventKind::ShootoutKick && e.detail) ++t.shootout[side];
const auto [headline, body] = ticker_text(s, m, e, t.score[0], t.score[1]);
const std::string mid = match_id(s, mo.ref->index);
events.push_back(O{{"id", mid + ":event:" + std::to_string(events.size())}, {"sequence", int64_t(frames.size())},
{"match_id", mid}, {"minute", mo.minute}, {"kind", event_kind(e.kind)}, {"headline", headline},
{"body", body}, {"score", A{J(t.score[0]), J(t.score[1])}}, {"side", side ? "away" : "home"},
{"player", almanac_person(s, e.player)}, {"other", almanac_person(s, e.other)}});
}
A scores;
for (size_t k = 0; k < human.size(); ++k) {
const Tally& t = tally[k];
scores.push_back(O{{"match_id", match_id(*human[k].season, human[k].index)},
{"score", A{J(t.score[0]), J(t.score[1])}}, {"chances", A{J(t.chances[0]), J(t.chances[1])}},
{"yellow", A{J(t.yellow[0]), J(t.yellow[1])}}, {"red", A{J(t.red[0]), J(t.red[1])}},
{"shootout", A{J(t.shootout[0]), J(t.shootout[1])}},
{"players", A{J(11 - t.red[0]), J(11 - t.red[1])}}, {"standings", A{}}});
}
const char* phase = mo.phase ? mo.phase : mo.minute <= 45 ? "first_half" : mo.minute <= 90 ? "second_half"
: mo.minute <= 120 ? "extra_time" : "shootout";
frames.push_back(O{{"sequence", int64_t(frames.size())}, {"minute", mo.minute}, {"phase", phase},
{"matches", std::move(scores)}, {"events", events}});
}
const AlmanacSeason& first = *human.front().season;
return O{{"ok", true}, {"schema", "openbmh-live-fixture@1"}, {"source", "engine-recording"},
{"fixture_id", "live:" + std::to_string(first.start_year) + "-" + std::to_string(human.front().index)},
{"source_revision", int64_t(revision)}, {"date", iso_date(first.matches[human.front().index].date, first.display_start_year)},
{"role", owners.empty() ? "club" : std::get<O>(std::get<O>(owners.front().value).at("team").value).at("role")},
{"surface", "outdoor"}, {"duration", extra ? 120 : 90}, {"field_count", 11}, {"owners", std::move(owners)},
{"matches", std::move(matches)}, {"frames", std::move(frames)}, {"conference", std::move(conference)},
{"notice", "Aufzeichnung der Engine: die Spiele des letzten Anstoßes"}};
}
} // namespace bmh::modern
+7
View File
@@ -35,4 +35,11 @@ cli::Json query_almanac(const ModernState& g, const cli::Json& request);
// not_recorded (title chances, transfers, weekly curves, season finances).
cli::Json query_statistics_screen(const ModernState& g, int manager, const cli::Json& request);
// The live ticker (DataSource::read_live): the matches recorded between two day counters (the last
// kickoff) in the fixture form of the interface: the matches of human managers (at most four)
// with their owners, frames in minute order (kickoff, every event, half time, the end) with
// score, chances, cards and players per match, the event lines, and the other matches of the
// day as the conference. source: "engine-recording".
cli::Json live_fixture(const ModernState& g, uint32_t after_date, uint32_t until_date, uint64_t revision);
} // namespace bmh::modern
+20
View File
@@ -10,6 +10,7 @@
#include "formats/executable_layout.hpp"
#include "game/state.hpp"
#include "game/table.hpp"
#include "modern/content/projections.hpp"
#include "modern/content/world_package.hpp"
#include "modern/game/almanac.hpp"
#include "modern/game/desk_actions.hpp"
@@ -367,6 +368,25 @@ cli::Json ui_read(const ModernState& g, const UiContext& c, const cli::Json& req
if (kind == "session") return snapshot(request_id, std::move(m), session_data(g, c));
if (kind == "desktop") return snapshot(request_id, std::move(m), desktop_data(g, c, today));
if (kind == "camps") return snapshot(request_id, std::move(m), camps_data(g, c, std::to_string(c.state_revision)));
if (kind == "toto" || kind == "sponsor") {
// the existing projections (ui-abfragen.md), amounts as Money
J p = query_projection(g, c.manager, O{{"kind", kind}});
auto* o = std::get_if<O>(&p.value);
if (!o || !(*o)["ok"].value.index() || !std::get<bool>((*o)["ok"].value))
return failure(request_id, "unavailable", "Nicht verfügbar.", c.state_revision);
o->erase("ok");
const auto money = [](J& v) { if (v.integer()) v = ui_money(*v.integer()); };
if (kind == "toto") {
money((*o)["stake"]), money((*o)["cost"]);
auto& last = std::get<O>((*o)["last"].value);
money(last["paid"]), money(last["won"]);
} else {
for (const char* key : {"offer", "queued"})
if (auto* row = std::get_if<O>(&(*o)[key].value)) money((*row)["monthly"]);
}
(*o)["kind"] = kind;
return snapshot(request_id, std::move(m), std::move(p));
}
if (kind == "squad") {
const int team = requested_team(g, c, request);
if (team < 0 || !fields_players(g, team))
+1
View File
@@ -142,6 +142,7 @@ WorldLayout modern_layout(int league_clubs, int german_clubs) {
// no_team, filled on the international days from the players of its nationality
w.national_start = w.pool_end + w.no_team_slots + 54;
w.national_slots = kSquadSlots;
w.traffic_stages = 4; // the four stages of the Modern interface (modern/game/traffic.hpp)
w.total_slots = w.national_start + uint32_t(w.national_teams - 1) * w.national_slots;
return w;
}
+3 -1
View File
@@ -138,7 +138,8 @@ void save_world_career(const std::filesystem::path& path, const World& world, co
{"exclusive_sponsors", sponsors_json(state.exclusive_sponsors)},
{"career_id", state.career_id},
{"manager_ids", strings(state.manager_ids)},
{"manager_serial", int64_t(state.manager_serial)}});
{"manager_serial", int64_t(state.manager_serial)},
{"traffic_scale", int64_t(state.traffic_scale)}});
// The almanac: finished seasons unchanged, the running one encoded now.
for (const auto& [name, bytes] : state.almanac.finished) docs[name] = bytes;
if (state.almanac.current.season >= 0) docs["history/current.bin"] = encode_almanac_season(state.almanac.current);
@@ -193,6 +194,7 @@ SavedWorldCareer load_world_career(const std::filesystem::path& path, const Worl
out.state.career_id = str(get(modern, "career_id"));
out.state.manager_ids = strings(get(modern, "manager_ids"));
out.state.manager_serial = uint32_t(num(get(modern, "manager_serial")));
if (o->count("traffic_scale")) out.state.traffic_scale = uint8_t(num(get(modern, "traffic_scale")));
}
for (const auto& [name, bytes] : docs) {
if (!name.starts_with("history/season-")) continue;
+2 -1
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/traffic.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/environment.hpp"
#include "modern/game/balance_plan.hpp"
@@ -50,7 +51,7 @@ 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 ModernState& 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;
return k == 0 ? uint32_t(traffic_stage(v)) & 0xff : 1; // the traffic access by its stage (traffic.hpp)
}
// DailyInterest2(0): the interest of one day without booking it - negative is income
+2 -1
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/traffic.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/career.hpp"
@@ -446,7 +447,7 @@ void build_stadium(ModernState& g, const LeImage& exe, int m, int league, int mo
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));
rec[0] = traffic_from_original(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);
}
+3 -2
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/traffic.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/matchday_setup.hpp"
#include "game/trace.hpp"
@@ -108,7 +109,7 @@ int32_t catering_income(const ModernState& g, int manager, int32_t spectators, W
for (int k = 0; k < 14; k++) {
const uint8_t v = g.manager_records.at(rec + size_t(k));
if (v == 0) continue;
const uint32_t level = k == 0 ? uint32_t((v - 1) / 0x55 + 1) & 0xFF : 1; // Add32
const uint32_t level = k == 0 ? uint32_t(traffic_stage(v)) & 0xFF : 1; // Add32 (traffic.hpp)
sum += kPerVisitor[k] * uint32_t(spectators) * level / 100;
}
if (sum != 0) sum = uint32_t(rand.range(0x55, 0x73)) * sum / 100;
@@ -724,7 +725,7 @@ int attendance(ModernState& g, int home, int away, int bits, int temperature, in
for (int k = 0; k < 10; k++) {
const int v = r8(size_t(k));
// MatchdaySetupRuntimeField6[0] is overwritten with the step of the stadium size
const int32_t step = k == 0 ? int32_t(v / 0x55 * 25000) : kStadiumSteps[k];
const int32_t step = k == 0 ? int32_t(traffic_full_stages(v) * 25000) : kStadiumSteps[k];
if (step < n && (v == 0 || k == 0)) n -= n / rand.range(10, 20);
}
const int wet = int(uint32_t(100 - covered) * uint32_t(uint8_t(rain)) * 8) / 100;
+3
View File
@@ -82,6 +82,9 @@ struct ModernState : GameState {
std::string career_id;
std::vector<std::string> manager_ids;
uint32_t manager_serial = 0;
// The scale of the traffic access bytes (traffic.hpp): 0 the original's (steps of 0x55), 64 the
// four stages of a Modern world. Older Modern saves are converted when loaded.
uint8_t traffic_scale = 0;
// Players whose age the data set gives (birth date); the others carry a placeholder the
// career start replaces as in the original. Needed only while a career starts (not saved).
std::vector<bool> world_age_known;
+2 -1
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/traffic.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/environment.hpp"
#include "modern/game/month.hpp"
@@ -531,7 +532,7 @@ int32_t monthly_income(ModernState& g, int m) {
for (int k = 0; k < 6; k++) {
const uint8_t v = r.at(rec + size_t(k));
if (v == 0) continue;
const int level = k == 0 ? ((v - 1) / 0x55 + 1) & 0xFF : 1; // Add32
const int level = k == 0 ? traffic_stage(v) & 0xFF : 1; // Add32 (traffic.hpp)
sum += level * kFacilityIncome[k];
}
add32(r, rec + 0x86c, sum);
+51
View File
@@ -0,0 +1,51 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// The traffic access (Verkehrsanbindung, stadium periphery object 0, manager record +0x00):
// the only periphery object with stages. Its condition byte grows by one stage per finished
// build and sinks with the stadium's ageing; a stage counts while the byte is above the stage
// below it.
//
// The original has three stages in steps of 0x55 (85, 170, 255; a new build is offered below
// 0xab). A Modern world has four, as the Modern interface shows them: steps of 64 (64, 128,
// 192, 255; a build is offered below 193). Every stage weighs as much as one original stage
// (income per visitor, monthly income, the attendance step). Classic data in the Modern core
// keeps the original three (WorldLayout::traffic_stages).
#include <algorithm>
#include <cstdint>
#include "game/world_layout.hpp"
namespace bmh::modern {
inline bool four_traffic_stages() { return world_layout().traffic_stages == 4; }
inline int traffic_step() { return four_traffic_stages() ? 64 : 0x55; }
// The stage of a condition byte, 0 = none (the original's Add32 level).
inline int traffic_stage(int v) { return v <= 0 ? 0 : (v - 1) / traffic_step() + 1; }
// The completed stages (MatchdaySetup's size step: the original's v / 0x55; 255 is stage 4).
inline int traffic_full_stages(int v) {
if (!four_traffic_stages()) return v / 0x55;
return v >= 255 ? 4 : v / 64;
}
// Whether the building firm offers another stage.
inline bool traffic_buildable(int v) { return v < (four_traffic_stages() ? 3 * 64 + 1 : 0xab); }
// The condition byte after a finished build: the next full stage.
inline uint8_t traffic_after_build(int v) {
const int step = traffic_step();
return uint8_t(std::min(255, (v == 0 ? 1 : (v - 1) / step + 2) * step));
}
// The original's value of a stage boundary (the ageing message at each boundary).
inline bool traffic_stage_boundary(int v) { return v % traffic_step() == 0; }
// A condition byte of the original's scale (start tables, older Modern saves) in this world's scale.
inline uint8_t traffic_from_original(int v) {
if (!four_traffic_stages() || v == 0) return uint8_t(v);
return uint8_t(std::min(255, ((v - 1) / 0x55 + 1) * 64));
}
} // namespace bmh::modern
+4 -3
View File
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "formats/executable_layout.hpp"
#include "modern/game/traffic.hpp"
#include "modern/game/modern_state.hpp"
#include "modern/game/weekly.hpp"
#include "modern/game/club_player_detail.hpp"
@@ -171,7 +172,7 @@ int facility_rating(ModernState& g, int manager, int* second, WatcomRandom* rand
const uint8_t v = rec.b(size_t(i));
if (v == 0) continue;
int level;
if (i < 0xe || i == 0x10 || i == 0x11) level = i == 0 ? (v - 1) / 0x55 + 1 : 1;
if (i < 0xe || i == 0x10 || i == 0x11) level = i == 0 ? traffic_stage(v) : 1;
else level = rec.b(size_t(i) + 0x2e) & 7;
sum += (level & 0xFF) * kFacility[i * 5];
}
@@ -365,7 +366,7 @@ void facility_ageing(ModernState& g, int manager, GameRandom& game, WatcomRandom
if (weeks == 0 && rec.b(size_t(i)) != 0 && rec.b(0x1e + size_t(i)) == 0) {
uint8_t& v = rec.b(size_t(i));
v--;
if ((i == 0 && v % 0x55 == 0) || rec.b(0x1e + size_t(i)) + v == 0) {
if ((i == 0 && traffic_stage_boundary(v)) || rec.b(0x1e + size_t(i)) + v == 0) {
if (i < 0xe) {
message = true;
} else if (i < 0x16) {
@@ -388,7 +389,7 @@ void facility_ageing(ModernState& g, int manager, GameRandom& game, WatcomRandom
uint8_t& build = rec.b(0x1e + size_t(i));
if (build != 0 && --build == 0) {
uint8_t& v = rec.b(size_t(i));
if (i == 0) v = uint8_t((v == 0 ? 1 : (v - 1) / 0x55 + 2) * 0x55);
if (i == 0) v = traffic_after_build(v);
else v = uint8_t(rand.range(kFacility[i * 5 + 2], kFacility[i * 5 + 3]) << 2);
if (i > 0xd) {
rec.b(0x2e + size_t(i)) = uint8_t((rec.b(0x2e + size_t(i)) >> 4) & 7);