Modern UI contract: envelope, career and manager ids, session and desktop reads

First engine delivery for the Modern interface handoff (docs/new_ui/integration,
issue #15): ModernSession::ui_read answers in the draft envelope with careerId,
worldId, stateRevision, date, season, scope and Money in minor units. Careers and
human managers get persistent ids (saved in state/modern.json, older saves get
them on load). Reads: session and desktop. Engine decisions on the P0 points in
docs/new_engine/ui-anbindung.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ClaudeandClaude Opus 5.5 committed 2026-10-27 08:17:18 +01:00
1 parent 9061123c7e
commit 3336d01004
9 files changed
+342 -2

No files matched your search

+1 -1
View File
@@ -346,7 +346,7 @@ add_library(bmh_modern_content STATIC src/modern/content/world.cpp src/modern/co
src/modern/content/world_save.cpp
src/modern/content/world_expand.cpp
src/modern/content/statistics.cpp
src/modern/content/projections.cpp)
src/modern/content/projections.cpp src/modern/content/ui_contract.cpp)
target_link_libraries(bmh_modern_content PUBLIC bmh_content bmh_season_modern PRIVATE bmh_miniz)
if(MSVC)
target_compile_options(bmh_modern_content PRIVATE /W4 /utf-8)
+36
View File
@@ -0,0 +1,36 @@
# Anbindung der Modern-UI · Engine-Seite
Stand: 27. Oktober 2026. Gegenstück zur Übergabe in [new_ui/integration](../new_ui/integration/README.md)
(Issue #15). Hier stehen die Entscheidungen der Engine und was der Adapter bereits liefert.
## Antworten auf die Engine-Entscheidungen
| Punkt | Entscheidung |
|---|---|
| D21 Engine-Ref | Maßgeblich ist der Zweig `0.3` dieses Repositorys (`src/modern`, `docs/new_engine`). `main` ist Classic und bekommt keine Modern-Engine. |
| D01 Geld, Revision | Geld im Vertrag als `Money {minor, currency, minorUnits}` mit `minor` als Dezimalzeichenkette, `EUR`, `minorUnits 2`. Die Engine rechnet in ganzen Euro; der Adapter (`ui_money`) multipliziert genau einmal mit 100. Die UI bekommt nur noch `Money`. Revisionen sind Dezimalzeichenketten. |
| D02 IDs | `careerId`: `career:` plus 16 Hexziffern, beim Karrierestart vom System gezogen (kein Spielzufall) und im Spielstand gespeichert. `managerId`: `manager:<n>`, je Karriere hochgezählt, nie wiederverwendet, gespeichert je Managerplatz. `teamId`: die Welt-ID des Vereins bzw. der Nation; Teams ohne Welt-ID `team:<Index>`. `playerId`: die Welt-ID bzw. `player:gen-<n>` (Almanach). Spiel- und Ereignis-IDs folgen mit dem Live-/Almanach-Read. |
| D03 Wiederholung | Folgt mit den Commands: Jeder Command trägt `requestId` und `expectedRevision`. Die Revisionsprüfung verhindert doppelte Buchung auch nach einem Neustart; dieselbe `requestId` mit gleichem Inhalt liefert das gespeicherte Ergebnis, mit anderem Inhalt `duplicate_request`. |
| D04 Umschlag, Manager | Umschlag wie im Entwurf (`messageType`, `requestId`, `meta`, `data`). Ein Read darf `managerId` nennen; er muss der Manager am Schreibtisch sein, sonst `manager_not_active`. Lesen für einen wartenden Manager folgt, sobald die Session das ohne Platzwechsel kann. |
| D05 Angebote | Engine-Vorschauen, die Zufall ziehen (Transfer-, Bau-, Sponsorangebote), werden ausschließlich als Command `quote.request` angeboten, nie als Read. |
| D10 Menüs | `menuAvailability` im Desktop-Read: am Schreibtisch des Bundestrainers sind Toto, Bank, Trainingslager, Training und Stadion gesperrt (`reasonCode: national_desk`, wie `ui/desk_state.cpp`). Weitere Sperren der UI sind UI-Policy. |
Die übrigen Punkte werden mit dem jeweiligen Menü entschieden.
## Was der Adapter liefert
`src/modern/content/ui_contract.*`, über `ModernSession::ui_read(request, revision)`; die
Revision kommt vom Aufrufer (Konsole bzw. AppController), der Read ändert nichts.
| Read | Inhalt |
|---|---|
| `session` | `sessionState`, `activeManagerId`, alle menschlichen Manager (ID, Platz, Name, Team, Porträt, `active`/`waiting`) |
| `desktop` | Manager, Team (`TeamRef`), Kontostand (`accounts.cash`; Sparguthaben und Kredit folgen mit dem Bank-Read), nächstes Spiel, `menuAvailability` |
Fehler: `unknown_read`, `manager_not_active`, `no_active_manager`.
Noch nicht gefüllt: `nationId`, `crestAssetId` der Teams, `employments` (Amtszeiten), `strengthChoice`, `allowedCommands`.
## Reihenfolge
Nach der Übergabe (MVP_FOR_CLAUDE.md): A Schreibtisch (dieser Stand) → B Vorbereitung (Kader, Aufstellung, Taktik, Training, Lager) → C Geschäft (Bank, Stadion, Transfers, Verträge, Werbung) → D Live-Ticker → E Eingriff und Nachspiel → F Manager und Presse. Je Lieferung Read- und Command-Tests.
+3
View File
@@ -774,6 +774,7 @@ ModernSession::ModernSession(const std::filesystem::path &data, uint32_t watcom_
throw FormatError(saved_turn_error_);
if (!native)
capture_source_desk_callargs();
modern::ensure_ui_identities(g_); // saves from before the interface contract get their ids now
}
int ModernSession::runtime_club(int master) const { return runtime_club(g_, master); }
@@ -947,6 +948,7 @@ bool ModernSession::commit_manager_join(ui::CareerInitializationResult& result,
next.desktop = desktop_projection(next_revision); next.managers = managers_;
next.preparation = preparation_projection(next_revision);
ui::validate_preparation_context(next.preparation);
modern::ensure_ui_identities(g_); // the new manager's contract id
result = std::move(next); revision = next_revision; manager_join_.reset();
return true;
} catch (const std::exception& e) {
@@ -4317,6 +4319,7 @@ bool ModernSession::finish(ui::CareerInitializationResult& result, std::string&
capture_source_desk_callargs();
// 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
result.desktop = desktop_projection(1);
result.preparation = preparation_projection(1);
for (size_t m = 0; m < managers_.size(); ++m)
+13
View File
@@ -3,6 +3,7 @@
#pragma once
#include "modern/content/projections.hpp"
#include "modern/content/statistics.hpp"
#include "modern/content/ui_contract.hpp"
#include "modern/content/world_expand.hpp"
// The engine side of the UI's career handoff (src/ui/flow.hpp, ENGINE_BINDING.md).
//
@@ -835,6 +836,18 @@ public:
cli::Json read(const cli::Json& request) const {
return query_projection(g_, int(g_.memory.has(::bmh::layout::ActiveManager) ? g_.memory.u8(::bmh::layout::ActiveManager) : 0), request);
}
// The interface contract (docs/new_engine/ui-anbindung.md): a read in the contract's envelope
// for the manager at the desk, at the revision the caller holds. Read-only.
cli::Json ui_read(const cli::Json& request, uint64_t revision) const {
UiContext context;
context.state_revision = revision;
context.manager = int(g_.memory.has(::bmh::layout::ActiveManager) ? g_.memory.u8(::bmh::layout::ActiveManager) : 0);
const ui::DeskState desk = desktop_projection(revision);
context.next_opponent = desk.next_opponent;
context.next_competition = desk.next_competition_label;
context.next_away = desk.next_match_away;
return modern::ui_read(g_, context, request);
}
ModernState& state() { return g_; }
const TurnResultSnapshot& last_turn_results() const { return turn_driver_.last_results; }
// Owned presentation for the event completed by the last accepted kickoff.
+218
View File
@@ -0,0 +1,218 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "modern/content/ui_contract.hpp"
#include <algorithm>
#include <cstdio>
#include <random>
#include <string>
#include <variant>
#include "formats/executable_layout.hpp"
#include "game/table.hpp"
#include "modern/content/world_package.hpp"
#include "modern/game/almanac.hpp"
namespace bmh::modern {
namespace {
using J = cli::Json;
using A = J::Array;
using O = J::Object;
constexpr const char* kContractVersion = "bmh-modern-ui@draft1";
constexpr size_t kRecord = 0xb0c;
const std::string& entry(const std::vector<std::string>& v, size_t i) {
static const std::string none;
return i < v.size() ? v[i] : none;
}
const J* field(const J& request, const char* key) {
const auto* o = request.object();
if (!o) return nullptr;
const auto it = o->find(key);
return it == o->end() ? nullptr : &it->second;
}
std::string text_field(const J& request, const char* key) {
const J* v = field(request, key);
return v && v->string() ? *v->string() : std::string{};
}
J text(const std::string& s) { return O{{"key", nullptr}, {"text", s}, {"locale", "de"}, {"args", O{}}}; }
J available() { return O{{"status", "available"}, {"reasonCode", nullptr}, {"missingFields", A{}}}; }
J unavailable(const char* reason) { return O{{"status", "unavailable"}, {"reasonCode", reason}, {"missingFields", A{}}}; }
std::string iso(const AlmanacDate& d) {
char out[16];
std::snprintf(out, sizeof out, "%04d-%02d-%02d", d.year, d.month, d.day);
return out;
}
// Managers with a human at their desk: during the national coach's takeover the coach sits in
// slot 0 and the others wait (OriginalManagerCount keeps their number).
int human_managers(const ModernState& g) {
if (g.memory.has(::bmh::layout::CoachActive) && g.memory.u8(::bmh::layout::CoachActive) != 0 &&
g.memory.has(::bmh::layout::OriginalManagerCount))
return g.memory.u8(::bmh::layout::OriginalManagerCount);
return int(g.manager_teams.size());
}
std::string manager_name(const ModernState& g, int manager) {
std::string name;
const size_t at = size_t(manager) * kRecord + 0xa8;
for (size_t i = 0; i < 30 && at + i < g.manager_records.size() && g.manager_records[at + i]; ++i)
name.push_back(char(g.manager_records[at + i]));
return almanac_utf8(name);
}
int64_t money_of(const ModernState& g, int manager) {
const size_t at = size_t(manager) * kRecord + 0x314;
if (at + 3 >= g.manager_records.size()) return 0;
return int32_t(uint32_t(g.manager_records[at]) | uint32_t(g.manager_records[at + 1]) << 8 |
uint32_t(g.manager_records[at + 2]) << 16 | uint32_t(g.manager_records[at + 3]) << 24);
}
int team_of(const ModernState& g, int manager) {
return manager >= 0 && size_t(manager) < g.manager_teams.size() ? g.manager_teams[size_t(manager)] : -1;
}
std::string team_id(const ModernState& g, int team) {
std::string id = entry(g.world_club_id, size_t(team));
return id.empty() ? "team:" + std::to_string(team) : id;
}
// TeamRef of the contract: id, kind, name, shortName, nationId, crestAssetId, nameAsOf.
J team_ref(const ModernState& g, int team, const std::string& as_of) {
if (team < 0) return nullptr;
std::string name = entry(g.world_club_name, size_t(team)), short_name = entry(g.world_club_short, size_t(team));
if (name.empty()) name = almanac_utf8(g.club_name(team));
if (short_name.empty()) short_name = name;
const bool national = team >= no_team();
return O{{"id", team_id(g, team)}, {"kind", national ? "national" : "club"}, {"name", name},
{"shortName", short_name}, {"nationId", nullptr}, {"crestAssetId", nullptr}, {"nameAsOf", as_of}};
}
std::string manager_id(const ModernState& g, int manager) {
const std::string& id = entry(g.manager_ids, size_t(manager));
return id.empty() ? "manager:slot-" + std::to_string(manager) : id;
}
J manager_json(const ModernState& g, int manager, bool at_desk) {
const int team = team_of(g, manager);
const size_t at = size_t(manager) * kRecord;
const int portrait = at + 0x221 < g.manager_records.size() ? g.manager_records[at + 0x221] : 0;
return O{{"id", manager_id(g, manager)}, {"slot", manager}, {"name", manager_name(g, manager)},
{"control", "human"}, {"status", at_desk ? "active" : "waiting"},
{"teamId", team >= 0 ? J(team_id(g, team)) : J(nullptr)},
{"portraitGuiKey", "gui:manager/photo/" + std::to_string(portrait)}, {"portraitStyle", "photo"},
{"strengthChoice", nullptr}, {"employments", A{}}};
}
J meta(const ModernState& g, const UiContext& c) {
const AlmanacDate today = almanac_date(g.date, g.display_start_year);
const int start = g.display_start_year + g.season, next = (start + 1) % 100;
const std::string label = std::to_string(start) + "/" + (next < 10 ? "0" : "") + std::to_string(next);
const int team = team_of(g, c.manager);
const bool national = team == no_team();
const std::string revision = std::to_string(c.state_revision);
const World* world = current_world();
return O{{"contractVersion", kContractVersion}, {"draft", true}, {"sourceRevision", nullptr},
{"careerId", g.career_id.empty() ? J(nullptr) : J(g.career_id)},
{"worldId", world ? J(world->id) : J(nullptr)},
{"worldRevision", world ? J(world->data_revision) : J(nullptr)},
{"stateRevision", revision}, {"projectionRevision", revision}, {"locale", "de"},
{"date", iso(today)},
{"season", O{{"id", "season:" + std::to_string(start) + "-" + (next < 10 ? "0" : "") + std::to_string(next)},
{"startDate", iso(AlmanacDate{start, 7, 1})}, {"endDate", iso(AlmanacDate{start + 1, 6, 30})},
{"label", label}, {"completed", false}}},
{"scope", O{{"managerId", manager_id(g, c.manager)},
{"teamId", team >= 0 ? J(team_id(g, team)) : J(nullptr)},
{"role", national ? "national" : "club"},
{"scopeId", "scope:desk-" + revision + "-" + std::to_string(c.manager)},
{"allowedCommands", A{}}}},
{"availability", available()},
{"currency", O{{"code", "EUR"}, {"minorUnits", 2}}}};
}
J snapshot(const std::string& request_id, J meta_json, J data) {
return O{{"messageType", "snapshot"}, {"requestId", request_id}, {"meta", std::move(meta_json)}, {"data", std::move(data)}};
}
J failure(const std::string& request_id, const char* code, const std::string& message, uint64_t revision) {
return O{{"messageType", "error"}, {"requestId", request_id}, {"code", code}, {"message", text(message)},
{"currentRevision", std::to_string(revision)}, {"retryable", false}, {"stateChanged", false}};
}
J session_data(const ModernState& g, const UiContext& c) {
A managers;
for (int m = 0; m < human_managers(g); ++m) managers.push_back(manager_json(g, m, m == c.manager));
return O{{"kind", "session"}, {"sessionState", "desktop"}, {"activeManagerId", manager_id(g, c.manager)},
{"managers", std::move(managers)}};
}
J desktop_data(const ModernState& g, const UiContext& c, const std::string& today) {
const int team = team_of(g, c.manager);
const bool national = team == no_team();
O data{{"kind", "desktop"}, {"manager", manager_json(g, c.manager, true)}, {"team", team_ref(g, team, today)}};
// the account: the bank's savings and credit follow with the bank read
data["accounts"] = O{{"cash", ui_money(money_of(g, c.manager))}, {"savings", nullptr}, {"debt", nullptr},
{"netAssets", nullptr}};
J next = nullptr;
if (c.next_opponent && *c.next_opponent >= 0) {
J own = team_ref(g, team, today), other = team_ref(g, *c.next_opponent, today);
next = O{{"competition", text(c.next_competition)}, {"home", c.next_away ? other : own},
{"away", c.next_away ? own : other}, {"status", "scheduled"}, {"result", nullptr}};
}
data["nextFixture"] = std::move(next);
// ui/desk_state.cpp: at the national coach's desk there is no toto, bank, camp, training or stadium
O menus;
for (const char* menu : {"squad", "lineup", "tactics", "training", "camps", "transfer", "contracts", "bank", "balance",
"advertising", "environment", "stadium", "toto", "calendar", "statistics", "almanac"}) {
const std::string m = menu;
const bool closed = national && (m == "toto" || m == "bank" || m == "camps" || m == "training" || m == "stadium");
menus[m] = closed ? unavailable("national_desk") : available();
}
data["menuAvailability"] = std::move(menus);
return data;
}
} // namespace
void ensure_ui_identities(ModernState& g) {
if (g.career_id.empty()) {
std::random_device device;
const uint64_t value = uint64_t(device()) << 32 | device();
char id[32];
std::snprintf(id, sizeof id, "career:%016llx", static_cast<unsigned long long>(value));
g.career_id = id;
}
const size_t humans = size_t(std::max(0, human_managers(g)));
if (g.manager_ids.size() < humans) g.manager_ids.resize(humans);
for (auto& id : g.manager_ids)
if (id.empty()) id = "manager:" + std::to_string(++g.manager_serial);
}
cli::Json ui_money(int64_t euros) {
return O{{"minor", std::to_string(euros * 100)}, {"currency", "EUR"}, {"minorUnits", 2}};
}
cli::Json ui_read(const ModernState& g, const UiContext& c, const cli::Json& request) {
const std::string request_id = text_field(request, "requestId");
const std::string kind = text_field(request, "kind");
if (c.manager < 0 || c.manager >= int(g.manager_teams.size()))
return failure(request_id, "no_active_manager", "Kein Manager am Schreibtisch.", c.state_revision);
// A read names the manager it is for; it must be the one at the desk (the session decides
// who acts, not the request).
if (const std::string wanted = text_field(request, "managerId"); !wanted.empty() && wanted != manager_id(g, c.manager))
return failure(request_id, "manager_not_active", "Dieser Manager sitzt nicht am Schreibtisch.", c.state_revision);
J m = meta(g, c);
const std::string today = *std::get<O>(m.value).at("date").string();
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));
return failure(request_id, "unknown_read", "Unbekannte Abfrage: " + kind, c.state_revision);
}
} // namespace bmh::modern
+49
View File
@@ -0,0 +1,49 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
// The engine side of the Modern interface contract (docs/new_ui/integration, draft
// "bmh-modern-ui@draft1"; engine decisions in docs/new_engine/ui-anbindung.md).
//
// A read answers in the contract's envelope:
// {messageType: "snapshot", requestId, meta: {contractVersion, careerId, worldId, worldRevision,
// stateRevision, projectionRevision, locale, date, season, scope, availability, currency}, data}
// or {messageType: "error", requestId, code, message, currentRevision, retryable, stateChanged}.
//
// Reads never change the game, draw random numbers or move the revision. Money is the
// contract's Money {minor: decimal string, currency: "EUR", minorUnits: 2}: the engine keeps
// whole euros, converted here exactly once. Revisions are decimal strings.
//
// Read kinds so far: "session" (the human managers and who is at the desk) and "desktop"
// (the desk of the active manager: manager, team, account, next match, menu availability).
#include <cstdint>
#include <string>
#include "cli/json.hpp"
#include "modern/game/modern_state.hpp"
namespace bmh::modern {
// What the session adds to the state: the revision the interface acts on and the manager at
// the desk (runtime manager slot).
struct UiContext {
uint64_t state_revision = 0;
int manager = 0;
// The desk's next match as the session prepared it (DeskState): the opponent's runtime
// team (-1: none, nullopt: not known), the competition label, whether it is away.
std::optional<int> next_opponent;
std::string next_competition;
bool next_away = false;
};
// Gives a career without them its identities: a career id ("career:" + 16 hex digits, drawn
// from the system, not from a game generator) and an id per human manager slot
// ("manager:<n>", counted per career, never reused). Called after the career start, a join
// and loading; changes nothing that is already set.
void ensure_ui_identities(ModernState& g);
// The money of the engine (whole euros) as the contract's Money.
cli::Json ui_money(int64_t euros);
cli::Json ui_read(const ModernState& g, const UiContext& context, const cli::Json& request);
} // namespace bmh::modern
+10 -1
View File
@@ -135,7 +135,10 @@ void save_world_career(const std::filesystem::path& path, const World& world, co
{"league_names", strings(state.world_league_name)},
{"generated_players", int64_t(state.almanac.generated_players)},
{"pools", pools_json(state.pools)},
{"exclusive_sponsors", sponsors_json(state.exclusive_sponsors)}});
{"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)}});
// 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);
@@ -185,6 +188,12 @@ SavedWorldCareer load_world_career(const std::filesystem::path& path, const Worl
out.state.almanac.generated_players = uint32_t(num(get(modern, "generated_players")));
out.state.pools = pools_json(get(modern, "pools"));
out.state.exclusive_sponsors = sponsors_json(get(modern, "exclusive_sponsors"));
// interface identities (since 27 October 2026); older saves get them on load (ensure_ui_identities)
if (const auto* o = modern.object(); o && o->count("career_id")) {
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")));
}
for (const auto& [name, bytes] : docs) {
if (!name.starts_with("history/season-")) continue;
decode_almanac_season(bytes); // a damaged season fails here, not in the almanac screen
+5
View File
@@ -77,6 +77,11 @@ struct ModernState : GameState {
bool operator==(const ExclusiveSponsor&) const = default;
};
std::vector<ExclusiveSponsor> exclusive_sponsors;
// Identities of the interface contract (docs/new_engine/ui-anbindung.md): the career and the
// human managers per manager slot ("manager:<n>", never reused within a career).
std::string career_id;
std::vector<std::string> manager_ids;
uint32_t manager_serial = 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;
+7
View File
@@ -742,6 +742,13 @@ int main(int argc, char** argv) {
read({{"kind", "fixtures"}, {"league", 0}, {"matchday", 1}});
read({{"kind", "squad"}});
read({{"kind", "table"}, {"league", 42}});
// the interface contract (docs/new_engine/ui-anbindung.md)
for (const char* kind : {"session", "desktop", "nonsense"}) {
const auto request = cli::Json::Object{{"kind", kind}, {"requestId", std::string("request:sim-") + kind}};
std::printf("ui_read %s\n -> %s\n", kind, cli::dump_json(session.ui_read(request, revision)).c_str());
}
std::printf("ui_read wrong manager\n -> %s\n",
cli::dump_json(session.ui_read(cli::Json::Object{{"kind", "desktop"}, {"managerId", "manager:99"}}, revision)).c_str());
}
if (std::getenv("SIM_ADVERTISING")) std::printf("%d advertising contracts accepted (SIM_ADVERTISING=1)\n", ad_contracts);
if (std::getenv("SIM_CAMP")) std::printf("%d training camp stays (SIM_CAMP=%s)\n", camp_stays, std::getenv("SIM_CAMP"));