From 201eef88e41ab6b724c38017f0ecf4f4f6d879cc Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 23 Oct 2026 23:49:13 +0200 Subject: [PATCH] Record every match in a football almanac (Modern, M8) Modern careers keep every match they play: season, date, competition type, league or cup stage, matchday, both clubs by world id with their human managers, result with extra time and shoot-out, referee, attendance, weather, both line-ups and all events (goals with assists and kind, misses, cards, injuries, substitutions, shoot-out kicks). Events come from the group event log the engine keeps for every match, substitutions from the players on the pitch after each minute; nothing draws random numbers (a 60-turn Modern run is unchanged). Player indices reused for a new person get a new stable id. Saves hold finished seasons as immutable history/season-.bin files plus the running season; modern-state@1.1 adds league names and the id counter. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 3 + docs/new_engine/README.md | 1 + docs/new_engine/almanach.md | 56 ++++ docs/new_engine/datenformat.md | 8 + docs/new_engine/ui-schnittstelle.md | 1 + src/modern/content/world_expand.cpp | 9 + src/modern/content/world_save.cpp | 26 +- src/modern/game/almanac.cpp | 497 ++++++++++++++++++++++++++++ src/modern/game/almanac.hpp | 179 ++++++++++ src/modern/game/modern_state.hpp | 4 + src/modern/game/season.cpp | 2 + src/modern/game/turn_driver.cpp | 21 +- tests/modern_almanac_tests.cpp | 84 +++++ tests/modern_season_sim.cpp | 52 ++- 14 files changed, 935 insertions(+), 8 deletions(-) create mode 100644 docs/new_engine/almanach.md create mode 100644 src/modern/game/almanac.cpp create mode 100644 src/modern/game/almanac.hpp create mode 100644 tests/modern_almanac_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 333a9a5..758626f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1167,6 +1167,9 @@ add_test(NAME quit_confirmation_unit_tests COMMAND quit_confirmation_unit_tests) add_executable(modern_camp_tests tests/modern_camp_tests.cpp) target_link_libraries(modern_camp_tests PRIVATE bmh_season_modern) add_test(NAME modern_camp_tests COMMAND modern_camp_tests) +add_executable(modern_almanac_tests tests/modern_almanac_tests.cpp) +target_link_libraries(modern_almanac_tests PRIVATE bmh_season_modern) +add_test(NAME modern_almanac_tests COMMAND modern_almanac_tests) add_executable(modern_calendar_tests tests/modern_calendar_tests.cpp) target_link_libraries(modern_calendar_tests PRIVATE bmh_season_modern) diff --git a/docs/new_engine/README.md b/docs/new_engine/README.md index e6134e8..0d8130f 100644 --- a/docs/new_engine/README.md +++ b/docs/new_engine/README.md @@ -59,5 +59,6 @@ Für 0.3 gilt außerdem: | M5 | Datenrevision 1.4 des Modern-Datensatzes (privat), Wirtschaftsprüfung | offen | | M6 | Modern-Spielstände (`modern-career-v1`), Projektionen für die UI | Spielstände erledigt (Rundreise identisch); Projektionen offen | | M7 | Balance-Läufe und Anpassungen | offen | +| M8 | Fußball-Almanach: alle Spiele mit Ereignissen und Aufstellungen ([Almanach](almanach.md)) | Engine erledigt (Aufzeichnung, Spielstand, IDs); UI und Projektionen offen | Details und Abnahmekriterien stehen in [Phasen](phasen.md). diff --git a/docs/new_engine/almanach.md b/docs/new_engine/almanach.md new file mode 100644 index 0000000..3142b7a --- /dev/null +++ b/docs/new_engine/almanach.md @@ -0,0 +1,56 @@ +# Fußball-Almanach + +Michaels Wunsch: Die Modern-Engine hebt **jedes je gespielte Spiel** auf, damit das Spiel einen „Fußball-Almanach“ mit starken Statistiken bekommt (ewige Torjäger, direkte Vergleiche, Rekorde, Serien, Zuschauer, Schiedsrichter …). Nur Modern; Classic bleibt unverändert. + +Code: `src/modern/game/almanac.hpp/.cpp`. Datenformat: [F10](datenformat.md#f10--almanach). + +## Was aufgezeichnet wird + +Pro Spiel (`AlmanacMatch`): + +| Feld | Inhalt | +|---|---| +| Saison | `season` (gespielte Saisons), `start_year` (Kalenderjahr des Saisonbeginns) im Saisonkopf | +| Datum | Tageszähler des Kalenders; `almanac_date(zähler, display_start_year)` liefert Tag/Monat/Jahr wie der Schreibtisch | +| Spieltyp | `type`: 0 Liga, sonst Pokal-ID + 1 (DFB-Pokal, Europapokale, Länderspiele, Freundschaftsspiele, Hallenturnier, Relegation …) | +| Wettbewerb | `league` (Ligaindex, im Saisonkopf mit Welt-ID und Namen) bzw. `stage` (Pokalstufe = Eintrag der Pokaltabelle) | +| Spieltag | `round`: Liga-Spieltag ab 1 bzw. Runde innerhalb der Pokalstufe ab 1 | +| Vereine | Heim/Gast als stabile Welt-IDs (Vereinstabelle der Saison) | +| Menschliche Manager | je Seite der Manager (Index und Name) oder −1 für Computer; Grundlage für spätere Vereinswechsel | +| Ergebnis | Tore nach regulärer Zeit bzw. Verlängerung, Elfmeterschießen getrennt, `decided` (0 regulär, 1 Verlängerung, 2 Elfmeter) | +| Schiedsrichter, Zuschauer, Wetter | Name (Tabelle der Saison), Zuschauerzahl, Temperatur in °C, Regen 0–7 | +| Aufstellungen | je Seite die 11 Startspieler, dann die Bank (nur Ligavereine; Länder- und Amateurteams haben in der Engine keine Kader) | +| Ereignisse | Minute, Seite, Spieler und ggf. zweiter Spieler: Tor (mit Vorlage und Art: Spiel, Elfmeter/Freistoß, Nachschuss, Ecke), Fehlschuss, Gelb, Gelb-Rot, Rot, Verletzung, Wechsel (ein/aus), Elfmeter im Elfmeterschießen | + +## Woher die Daten kommen (keine Wirkung auf das Spiel) + +- Tore, Fehlschüsse, Karten, Verletzungen: das Ereignisprotokoll der Spielgruppe (`MatchGroup::log`), das die Engine wie das Original für **jedes** Spiel führt. +- Elfmeterschießen: die Show-Ereignisse der Match-Engine (das Protokoll hat keine Elfmeter); Modern sammelt sie jetzt immer. +- Wechsel: Vergleich der Spieler auf dem Platz nach jeder Minute. Damit werden auch Wechsel des menschlichen Managers (Bildschirm, Halbzeit) erfasst. +- Aufstellung, Schiedsrichter, Wetter, Spieltag: beim Anpfiff; Ergebnis und Zuschauer nach dem Spieltag. +- Der Almanach zieht keine Zufallszahlen und ändert nichts, was die Saisonlogik liest. Geprüft: Ein Modern-Lauf über 60 Züge ist mit und ohne Almanach identisch. + +## Identitäten + +- **Vereine** tauschen beim Auf- und Abstieg ihre Laufzeitnummer; der Almanach speichert deshalb die Welt-ID (`world_club_id`). +- **Spieler**: Die Engine verwendet den Platz eines Spielers für eine neue Person wieder (Karriereende/Abgang in den Pool mit neuen Werten, Jugendspieler). Dort vergibt `new_player_identity` eine neue ID `player:gen-`. Der Zähler wird mitgespeichert. Wie im Original behält die neue Person den Namen des Platzes; die ID trennt die Karrieren. +- Spieler ohne Welt-ID (Classic-Daten) heißen `player:legacy-`, Vereine `team:`. + +## Speicherung + +- Jede Saison hat ihre eigenen Tabellen (Ligen, Vereine, Spieler, Manager, Schiedsrichter) und ist damit für sich lesbar. +- Abgeschlossene Saisons liegen im Spielstand als `history/season-.bin` und werden nie wieder geschrieben; die laufende als `history/current.bin`. Beide stehen in `state/integrity.json`. +- Binärformat Version 1 (Little Endian): `OBAL`, u16 Version, Saisonkopf, Tabellen, Spiele. Text: u16 Länge + UTF-8. Einzelheiten in `encode_almanac_season`. +- Größe: etwa 0,5 MB pro Saison im (komprimierten) Spielstand, mit allen Ereignissen und Aufstellungen. Ein Spielstand nach einer Saison ist ~700 KB statt ~210 KB. + +## Für die UI (Codex) + +- `ModernState::almanac`: `finished` (Dateiname + Bytes je Saison, mit `decode_almanac_season` lesen) und `current` (laufende Saison). +- Auswertungen (Torjäger aller Zeiten, Bilanzen, Rekorde) baut die Engine als Projektionen, sobald die Almanach-Oberfläche feststeht. Bis dahin kann die UI direkt auf den Saisons rechnen. `modern_season_sim` zeigt am Laufende ein Beispiel (`print_almanac`: Prüfung Tore gegen Ergebnis, Top-Torschützen über alle Saisons). +- Namen sind UTF-8; Wettbewerbsnamen für Pokale kommen wie im Ergebnisbildschirm aus den Texten (`type - 1` = Pokal-ID). + +## Offen + +- Kader der Länder- und Amateurteams, damit auch deren Aufstellungen aufgezeichnet werden. +- Projektionen für die Almanach-Oberfläche. +- Bessere Kompression der abgeschlossenen Saisons (heute schnellste ZIP-Stufe). diff --git a/docs/new_engine/datenformat.md b/docs/new_engine/datenformat.md index ab4e9ea..d51b808 100644 --- a/docs/new_engine/datenformat.md +++ b/docs/new_engine/datenformat.md @@ -21,6 +21,7 @@ Status: *geplant* (noch nicht in der Engine), *umgesetzt* (Engine liest/prüft e | F7 | Finanzen | Finanzangaben für Vereine ohne Classic-Startregel | M5 | geplant | | F8 | Spielstand | `save_profile: modern-career-v1` | M6 | Engine erledigt: Spielstand nennt seine Welt (ID, Revision), enthält nur die Karriere | | F9 | Schiedsrichter | eigener Schiedsrichter-Pool der Welt, mehr als 49 | M5 | Engine erledigt (Pool aus `staff`, neu: `perception`); Daten folgen mit 1.4 | +| F10 | Almanach | alle gespielten Spiele im Spielstand (`history/…`) | M8 | Engine erledigt (Aufzeichnung, Spielstand); UI offen | ## F1 · Manifest @@ -127,6 +128,13 @@ Die bestehende Regel `rule:training-camps` (Typ `training_camps`) bleibt und wir - Test ohne neuen Datensatz: `MODERN_EXTRA_REFEREES=N modern_season_sim …`. - **Editor:** Schiedsrichterliste anzeigen und bearbeiten (Name, Nation, Strenge, Wahrnehmung), neue Schiedsrichter anlegen; Prüfung auf eindeutige IDs, Werte 0–3 und höchstens 255 Schiedsrichter. +## F10 · Almanach + +- Ein Modern-Spielstand enthält alle gespielten Spiele der Karriere: `history/season-.bin` je abgeschlossener Saison (unveränderlich) und `history/current.bin` für die laufende. Beschreibung: [Almanach](almanach.md). +- `state/modern.json` (Schema jetzt `modern-state@1.1`) bekommt dazu `league_ids`, `league_names` und `generated_players` (Zähler der neu vergebenen Spieler-IDs `player:gen-`). +- Die Integritätsprüfung deckt `history/` mit ab. +- **Editor:** keine Änderung (öffnet keine Spielstände). Eine Welt muss nichts liefern; sinnvoll sind stabile Vereins- und Spieler-IDs, die sich zwischen Datenrevisionen nicht ändern. + ## Modern-Prüfung (Engine und Editor) Eine Welt ist als Modern-Welt spielbar, wenn: diff --git a/docs/new_engine/ui-schnittstelle.md b/docs/new_engine/ui-schnittstelle.md index 721be6d..44463f0 100644 --- a/docs/new_engine/ui-schnittstelle.md +++ b/docs/new_engine/ui-schnittstelle.md @@ -51,6 +51,7 @@ bmh::modern::app::ModernSession session(path, seed); // erweitert den | Trainingslager | siehe unten | Schwerpunkte setzen, buchen | M4 | | Post | `Mail[]`: Datum, Absender, Betreff, Text | Gelesen markieren | M3 | | Spieltag | Fortschritt und Ereignisse über den bestehenden Match-Kern | Weiter, Eingriffe | M3 | +| Fußball-Almanach | `ModernState::almanac`: alle Spiele aller Saisons ([Almanach](almanach.md)); Auswertungs-Projektionen folgen, sobald die Oberfläche feststeht | – | M8 (Daten vorhanden) | Alles, was hier noch fehlt (Transfers, Finanzen, Stadion, Umfeld und weitere Menüs), folgt nach demselben Muster. Jedes neue Menü der UI bekommt in diesem diff --git a/src/modern/content/world_expand.cpp b/src/modern/content/world_expand.cpp index ef1410f..13eefe1 100644 --- a/src/modern/content/world_expand.cpp +++ b/src/modern/content/world_expand.cpp @@ -394,6 +394,15 @@ ExpandReport expand_to_world(ModernState& g, const World& world) { g.world_club_id.assign(size_t(new_total), {}); g.world_club_name.assign(size_t(new_total), {}); g.world_club_short.assign(size_t(new_total), {}); + g.world_league_id.clear(), g.world_league_name.clear(); + for (const WorldLeague& l : world.leagues) { + if (size_t(l.index) >= g.world_league_id.size()) { + g.world_league_id.resize(size_t(l.index) + 1); + g.world_league_name.resize(size_t(l.index) + 1); + } + g.world_league_id[size_t(l.index)] = l.id; + g.world_league_name[size_t(l.index)] = l.name; + } for (int n = 0; n < new_total; ++n) if (const WorldClub* c = club_at[size_t(n)]) { g.world_club_id[size_t(n)] = c->id; diff --git a/src/modern/content/world_save.cpp b/src/modern/content/world_save.cpp index 63da6b5..5cfcd4c 100644 --- a/src/modern/content/world_save.cpp +++ b/src/modern/content/world_save.cpp @@ -59,14 +59,20 @@ void save_world_career(const std::filesystem::path& path, const World& world, co {"world", O{{"id", world.id}, {"data_revision", world.data_revision}, {"title", world.title}}}}); put(docs, "state/career.json", encode_native_state(state)); put(docs, "state/modern.json", - O{{"schema", "modern-state@1.0"}, + O{{"schema", "modern-state@1.1"}, {"club_ids", strings(state.world_club_id)}, {"club_names", strings(state.world_club_name)}, {"club_short_names", strings(state.world_club_short)}, {"player_ids", strings(state.world_player_id)}, {"player_first", strings(state.player_first)}, {"player_last", strings(state.player_last)}, - {"player_nations", strings(state.player_nation)}}); + {"player_nations", strings(state.player_nation)}, + {"league_ids", strings(state.world_league_id)}, + {"league_names", strings(state.world_league_name)}, + {"generated_players", int64_t(state.almanac.generated_players)}}); + // 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); put(docs, "state/rng.json", O{{"schema", "classic-rng@1.0"}, {"watcom", generator(random.seed(), random.calls())}, @@ -76,7 +82,7 @@ void save_world_career(const std::filesystem::path& path, const World& world, co put(docs, "state/information.json", encode_native_bytes(modern::save_header(state))); O checks; for (const auto& [name, value] : docs) - if (name.starts_with("state/")) checks[name] = content::sha256(value); + if (name.starts_with("state/") || name.starts_with("history/")) checks[name] = content::sha256(value); put(docs, "state/integrity.json", O{{"schema", "save-integrity@1.0"}, {"entries", std::move(checks)}}); content::write_archive(docs, path, overwrite); } @@ -94,13 +100,13 @@ SavedWorldCareer load_world_career(const std::filesystem::path& path, const Worl if (str(get(integrity, "schema")) != "save-integrity@1.0") fail("unsupported save integrity"); O checks; for (const auto& [name, value] : docs) - if (name.starts_with("state/") && name != "state/integrity.json") checks[name] = content::sha256(value); + if ((name.starts_with("state/") || name.starts_with("history/")) && name != "state/integrity.json") checks[name] = content::sha256(value); if (cli::dump_json(get(integrity, "entries")) != cli::dump_json(checks)) fail("damaged Modern save"); SavedWorldCareer out; out.state = ModernState(decode_native_state(parse(docs, "state/career.json"))); const auto modern = parse(docs, "state/modern.json"); - if (str(get(modern, "schema")) != "modern-state@1.0") fail("unsupported Modern state"); + if (str(get(modern, "schema")) != "modern-state@1.1") fail("unsupported Modern state"); out.state.world_club_id = strings(get(modern, "club_ids")); out.state.world_club_name = strings(get(modern, "club_names")); out.state.world_club_short = strings(get(modern, "club_short_names")); @@ -108,6 +114,16 @@ SavedWorldCareer load_world_career(const std::filesystem::path& path, const Worl out.state.player_first = strings(get(modern, "player_first")); out.state.player_last = strings(get(modern, "player_last")); out.state.player_nation = strings(get(modern, "player_nations")); + out.state.world_league_id = strings(get(modern, "league_ids")); + out.state.world_league_name = strings(get(modern, "league_names")); + out.state.almanac.generated_players = uint32_t(num(get(modern, "generated_players"))); + 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 + out.state.almanac.finished.emplace_back(name, bytes); + } + if (const auto it = docs.find("history/current.bin"); it != docs.end()) + out.state.almanac.current = decode_almanac_season(it->second); if (out.state.world_player_id.size() != out.state.players.size() || out.state.world_club_id.size() != out.state.club_ids.size()) fail("Modern names do not match the saved state"); diff --git a/src/modern/game/almanac.cpp b/src/modern/game/almanac.cpp new file mode 100644 index 0000000..adfd339 --- /dev/null +++ b/src/modern/game/almanac.cpp @@ -0,0 +1,497 @@ +// SPDX-License-Identifier: GPL-3.0-only +#include "modern/game/almanac.hpp" + +#include +#include +#include +#include + +#include "formats/binary.hpp" +#include "game/match_engine.hpp" +#include "game/presentation.hpp" +#include "modern/game/cup.hpp" +#include "modern/game/matchday.hpp" +#include "modern/game/modern_state.hpp" + +namespace bmh::modern { + +namespace { + +constexpr size_t kManagerRecord = 0xB0C; +constexpr uint32_t kVersion = 1; + +// Original single-byte text (ISO 646-DE) to UTF-8, as the interfaces show it. +std::string utf8(std::string_view original) { + static constexpr std::string_view german[] = {"Ä", "Ö", "Ü", "ä", "ö", "ü", "ß"}; + static constexpr std::string_view codes = "[\\]{|}~"; + std::string out; + for (char c : original) { + const size_t i = codes.find(c); + if (i != std::string_view::npos) out += german[i]; + else if (static_cast(c) < 128) out += c; + else out += '?'; + } + return out; +} + +const std::string& entry(const std::vector& names, size_t i) { + static const std::string none; + return i < names.size() ? names[i] : none; +} + +AlmanacClub club_of(const ModernState& g, int team) { + AlmanacClub c; + c.id = entry(g.world_club_id, size_t(team)); + if (c.id.empty()) c.id = "team:" + std::to_string(team); + c.name = entry(g.world_club_name, size_t(team)); + if (c.name.empty()) c.name = utf8(g.club_name(team)); + return c; +} + +AlmanacManager manager_of(const ModernState& g, int manager) { + AlmanacManager m; + m.index = manager; + const size_t at = size_t(manager) * kManagerRecord + 0xa8; // the manager's name (30 bytes) + for (size_t i = 0; i < 30 && at + i < g.manager_records.size() && g.manager_records[at + i]; ++i) + m.name.push_back(char(g.manager_records[at + i])); + m.name = utf8(m.name); + return m; +} + +std::string referee_name(const ModernState& g, int referee) { + const size_t at = size_t(referee) * 2; + if (at + 1 >= g.master_database_metadata.size()) return "#" + std::to_string(referee); + const size_t offset = size_t(g.master_database_metadata[at] | g.master_database_metadata[at + 1] << 8); + std::string name; + for (size_t i = offset; i < g.referee_names.size() && g.referee_names[i]; ++i) name.push_back(char(g.referee_names[i])); + return utf8(name); +} + +AlmanacSeason& current_season(ModernState& g) { + Almanac& a = g.almanac; + if (a.current.season != g.season) { + if (a.current.season >= 0 && !a.current.matches.empty()) + a.finished.emplace_back("history/season-" + std::to_string(a.current.start_year) + ".bin", + encode_almanac_season(a.current)); + a.current = AlmanacSeason{}; + a.current.season = g.season; + a.current.display_start_year = g.display_start_year; + a.current.start_year = g.display_start_year + g.season; + a.current.referees.push_back({}); // index 0: no referee + for (size_t l = 0; l < g.world_league_id.size(); ++l) + a.current.leagues.push_back({int(l), g.world_league_id[l], entry(g.world_league_name, l)}); + a.current.index(); + } + return a.current; +} + +// --- binary form ----------------------------------------------------------------------- + +struct Writer { + std::string out; + void u8(uint32_t v) { out.push_back(char(v & 0xff)); } + void u16(uint32_t v) { u8(v); u8(v >> 8); } + void u32(uint32_t v) { u16(v); u16(v >> 16); } + void str(const std::string& s) { + if (s.size() > 0xffff) throw FormatError("almanac: text too long"); + u16(uint32_t(s.size())); + out += s; + } +}; + +struct Reader { + const std::string& in; + size_t at = 0; + uint32_t u8() { + if (at >= in.size()) throw FormatError("almanac: truncated season"); + return uint8_t(in[at++]); + } + uint32_t u16() { const uint32_t lo = u8(); return lo | u8() << 8; } + uint32_t u32() { const uint32_t lo = u16(); return lo | u16() << 16; } + std::string str() { + const size_t n = u16(); + if (at + n > in.size()) throw FormatError("almanac: truncated season"); + std::string s = in.substr(at, n); + at += n; + return s; + } +}; + +} // namespace + +uint16_t AlmanacSeason::club(const AlmanacClub& c) { + const auto it = club_at_.find(c.id); + if (it != club_at_.end()) return it->second; + if (clubs.size() >= 0xffff) throw FormatError("almanac: too many clubs in a season"); + clubs.push_back(c); + return club_at_[c.id] = uint16_t(clubs.size() - 1); +} + +uint16_t AlmanacSeason::player(const AlmanacPlayer& p) { + const auto it = player_at_.find(p.id); + if (it != player_at_.end()) return it->second; + if (players.size() >= kAlmanacNone) throw FormatError("almanac: too many players in a season"); + players.push_back(p); + return player_at_[p.id] = uint16_t(players.size() - 1); +} + +int8_t AlmanacSeason::manager(const AlmanacManager& m) { + for (size_t i = 0; i < managers.size(); ++i) + if (managers[i] == m) return int8_t(i); + if (managers.size() >= 0x7f) throw FormatError("almanac: too many managers in a season"); + managers.push_back(m); + return int8_t(managers.size() - 1); +} + +uint8_t AlmanacSeason::referee(const std::string& name) { + const auto it = referee_at_.find(name); + if (it != referee_at_.end()) return it->second; + if (referees.size() >= 0xff) throw FormatError("almanac: too many referees in a season"); + referees.push_back(name); + return referee_at_[name] = uint8_t(referees.size() - 1); +} + +void AlmanacSeason::index() { + club_at_.clear(), player_at_.clear(), referee_at_.clear(); + for (size_t i = 0; i < clubs.size(); ++i) club_at_[clubs[i].id] = uint16_t(i); + for (size_t i = 0; i < players.size(); ++i) player_at_[players[i].id] = uint16_t(i); + for (size_t i = 1; i < referees.size(); ++i) referee_at_[referees[i]] = uint8_t(i); +} + +AlmanacDate almanac_date(uint32_t counter, int display_start_year) { + // As the desk counts (desk_date): day 0 is 1 July, the fourth year of the cycle is a + // leap year (the first February the calendar reaches is in the first leap year). + static constexpr int kDays[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + AlmanacDate d; + int cycle = 3, years = 0; + while (counter > uint32_t(364 + (cycle == 4))) { + if (cycle == 4) { cycle = 0; --counter; } + ++years, counter -= 365, ++cycle; + } + d.month = 7; + auto month_days = [&] { return d.month == 2 ? 28 + (cycle == 4) : kDays[d.month]; }; + while (counter > uint32_t(month_days())) { + counter -= uint32_t(month_days()); + if (++d.month == 13) d.month = 1, ++years; + } + d.day = int(counter) + 1; + if (d.day > month_days()) { + d.day -= month_days(); + if (++d.month == 13) d.month = 1, ++years; + } + d.year = display_start_year + years; + return d; +} + +std::string encode_almanac_season(const AlmanacSeason& s) { + Writer w; + w.out = "OBAL"; + w.u16(kVersion); + w.u16(uint32_t(int16_t(s.season))), w.u16(uint32_t(s.start_year)), w.u16(uint32_t(s.display_start_year)); + w.u16(uint32_t(s.leagues.size())); + for (const auto& l : s.leagues) w.u8(uint32_t(l.index)), w.str(l.id), w.str(l.name); + w.u16(uint32_t(s.clubs.size())); + for (const auto& c : s.clubs) w.str(c.id), w.str(c.name); + w.u32(uint32_t(s.players.size())); + for (const auto& p : s.players) w.str(p.id), w.str(p.first), w.str(p.last), w.str(p.nation); + w.u8(uint32_t(s.managers.size())); + for (const auto& m : s.managers) w.u8(uint32_t(uint8_t(int8_t(m.index)))), w.str(m.name); + w.u16(uint32_t(s.referees.size())); + for (const auto& r : s.referees) w.str(r); + w.u32(uint32_t(s.matches.size())); + for (const AlmanacMatch& m : s.matches) { + w.u32(m.date); + w.u8(m.type), w.u8(m.league), w.u8(m.stage), w.u8(m.round); + w.u16(m.home), w.u16(m.away); + w.u8(uint8_t(m.home_manager)), w.u8(uint8_t(m.away_manager)); + w.u8(m.home_goals), w.u8(m.away_goals), w.u8(m.home_shootout), w.u8(m.away_shootout); + w.u8(m.decided), w.u8(m.referee); + w.u32(m.attendance); + w.u8(uint8_t(m.temperature)), w.u8(m.rain); + for (const auto& side : m.lineup) { + if (side.size() > 0xff) throw FormatError("almanac: line-up too long"); + w.u8(uint32_t(side.size())); + for (uint16_t p : side) w.u16(p); + } + if (m.events.size() > 0xffff) throw FormatError("almanac: too many events in a match"); + w.u16(uint32_t(m.events.size())); + for (const AlmanacEvent& e : m.events) + w.u8(uint32_t(e.kind)), w.u8(e.minute), w.u8(e.side), w.u8(e.detail), w.u16(e.player), w.u16(e.other); + } + return std::move(w.out); +} + +AlmanacSeason decode_almanac_season(const std::string& bytes) { + if (bytes.size() < 6 || bytes.compare(0, 4, "OBAL") != 0) throw FormatError("almanac: not an almanac season"); + Reader r{bytes, 4}; + if (r.u16() != kVersion) throw FormatError("almanac: unknown season version"); + AlmanacSeason s; + s.season = int16_t(r.u16()), s.start_year = int(r.u16()), s.display_start_year = int(r.u16()); + for (uint32_t n = r.u16(); n > 0; --n) { + AlmanacLeague l; + l.index = int(r.u8()), l.id = r.str(), l.name = r.str(); + s.leagues.push_back(std::move(l)); + } + for (uint32_t n = r.u16(); n > 0; --n) { + AlmanacClub c; + c.id = r.str(), c.name = r.str(); + s.clubs.push_back(std::move(c)); + } + for (uint32_t n = r.u32(); n > 0; --n) { + AlmanacPlayer p; + p.id = r.str(), p.first = r.str(), p.last = r.str(), p.nation = r.str(); + s.players.push_back(std::move(p)); + } + for (uint32_t n = r.u8(); n > 0; --n) { + AlmanacManager m; + m.index = int8_t(r.u8()), m.name = r.str(); + s.managers.push_back(std::move(m)); + } + for (uint32_t n = r.u16(); n > 0; --n) s.referees.push_back(r.str()); + for (uint32_t n = r.u32(); n > 0; --n) { + AlmanacMatch m; + m.date = r.u32(); + m.type = uint8_t(r.u8()), m.league = uint8_t(r.u8()), m.stage = uint8_t(r.u8()), m.round = uint8_t(r.u8()); + m.home = uint16_t(r.u16()), m.away = uint16_t(r.u16()); + m.home_manager = int8_t(r.u8()), m.away_manager = int8_t(r.u8()); + m.home_goals = uint8_t(r.u8()), m.away_goals = uint8_t(r.u8()); + m.home_shootout = uint8_t(r.u8()), m.away_shootout = uint8_t(r.u8()); + m.decided = uint8_t(r.u8()), m.referee = uint8_t(r.u8()); + m.attendance = r.u32(); + m.temperature = int8_t(r.u8()), m.rain = uint8_t(r.u8()); + for (auto& side : m.lineup) + for (uint32_t k = r.u8(); k > 0; --k) side.push_back(uint16_t(r.u16())); + for (uint32_t k = r.u16(); k > 0; --k) { + AlmanacEvent e; + e.kind = AlmanacEventKind(r.u8()); + e.minute = uint8_t(r.u8()), e.side = uint8_t(r.u8()), e.detail = uint8_t(r.u8()); + e.player = uint16_t(r.u16()), e.other = uint16_t(r.u16()); + if (uint8_t(e.kind) > uint8_t(AlmanacEventKind::Miss)) throw FormatError("almanac: unknown event kind"); + m.events.push_back(e); + } + if (m.home >= s.clubs.size() || m.away >= s.clubs.size()) throw FormatError("almanac: unknown club in a match"); + s.matches.push_back(std::move(m)); + } + if (r.at != bytes.size()) throw FormatError("almanac: trailing bytes after the season"); + s.index(); + return s; +} + +void new_player_identity(ModernState& g, int player) { + if (player < 0 || size_t(player) >= g.players.size()) return; + if (g.world_player_id.size() < g.players.size()) g.world_player_id.resize(g.players.size()); + // The new person keeps the name of the index, as in the original (its name pool entry). + g.world_player_id[size_t(player)] = "player:gen-" + std::to_string(++g.almanac.generated_players); +} + +// --- recording ------------------------------------------------------------------------- + +AlmanacRecorder::AlmanacRecorder(ModernState& g, const std::vector& groups) : g_(g), groups_(groups) { + AlmanacSeason& season = current_season(g); + for (size_t gi = 0; gi < groups.size(); ++gi) { + const MatchGroup& group = groups[gi]; + if (group.desc.size() < 0xd0) continue; + for (int m = 0; m < group.matches(); ++m) { + if (group.void_mask() >> m & 1) continue; + const size_t f = size_t(m) * 2; + if (f + 1 >= group.fixtures.size()) continue; + const int home = group.fixtures[f], away = group.fixtures[f + 1]; + const int teams = world_layout().total_teams(); + if (home < 0 || away < 0 || home >= teams || away >= teams || home == no_team() || away == no_team()) continue; + Running r; + r.group = gi, r.match = m; + AlmanacMatch& rec = r.record; + rec.date = g.date; + rec.type = group.desc[0]; + const uint32_t id = le32(group.desc, 0xcc); + if (rec.type == 0) { + rec.league = uint8_t(id); + if (id < g.league_rounds.size()) rec.round = uint8_t(g.league_rounds[id] + 1); + } else if (id >= kCupTable && id < kCupTable + kCupEntries * kCupEntrySize && (id - kCupTable) % kCupEntrySize == 0) { + rec.stage = uint8_t(modern::cup_entry_index(id)); + rec.round = uint8_t(modern::cup_round(g.memory, rec.stage) + 1); + } + rec.home = season.club(club_of(g, home)); + rec.away = season.club(club_of(g, away)); + if (const int hm = g.manager_of(home); hm >= 0) rec.home_manager = season.manager(manager_of(g, hm)); + if (const int am = g.manager_of(away); am >= 0) rec.away_manager = season.manager(manager_of(g, am)); + rec.temperature = int8_t(group.desc.at(0x30 + size_t(m))); + rec.rain = group.desc.at(0x50 + size_t(m)); + if (const int ref = group.desc.at(0x10 + size_t(m)); ref > 0) rec.referee = season.referee(referee_name(g, ref)); + for (int side = 0; side < 2; ++side) { + const int team = side ? away : home; + if (team >= league_clubs()) continue; // only league clubs have squads + const SquadRange range = squad_range(team); + for (size_t s = 0; s < range.count; ++s) { + const uint16_t e = g.squad_slots.at(range.first + s); + const int player = e & 0x0fff; + if (player == 0x0fff) continue; + if (s < 11 || (e & 0x4000)) rec.lineup[size_t(side)].push_back(player_ref(player)); + } + r.eleven[size_t(side)] = on_pitch(team); + } + running_.push_back(std::move(r)); + } + } +} + +uint16_t AlmanacRecorder::player_ref(int player) { + AlmanacPlayer p; + p.id = entry(g_.world_player_id, size_t(player)); + if (p.id.empty()) p.id = "player:legacy-" + std::to_string(player); + p.first = entry(g_.player_first, size_t(player)); + p.last = entry(g_.player_last, size_t(player)); + if (p.last.empty()) p.last = utf8(g_.player_name(player)); + p.nation = entry(g_.player_nation, size_t(player)); + return g_.almanac.current.player(p); +} + +// The players on the pitch: the first 11 slots that still carry a line-up flag (a player +// sent off or injured loses it; a substitute takes the slot of the player he replaces). +std::vector AlmanacRecorder::on_pitch(int team) const { + std::vector out; + if (team < 0 || team >= league_clubs()) return out; + const SquadRange range = squad_range(team); + for (size_t s = 0; s < std::min(11, range.count); ++s) { + const uint16_t e = g_.squad_slots.at(range.first + s); + if ((e & 0x0fff) != 0x0fff && (e & 0xf000)) out.push_back(uint16_t(e & 0x0fff)); + } + std::sort(out.begin(), out.end()); + return out; +} + +void AlmanacRecorder::after_minute(int minute) { + for (size_t i = 0; i < running_.size(); ++i) { + Running& r = running_[i]; + const MatchGroup& group = groups_.at(r.group); + for (int side = 0; side < 2; ++side) { + const int team = group.fixtures.at(size_t(r.match) * 2 + size_t(side)); + std::vector now = on_pitch(team); + auto& before = r.eleven[size_t(side)]; + if (now == before) continue; + std::vector came, left; + std::set_difference(now.begin(), now.end(), before.begin(), before.end(), std::back_inserter(came)); + std::set_difference(before.begin(), before.end(), now.begin(), now.end(), std::back_inserter(left)); + // A player still in the first 11 slots left without a substitute (sent off or + // injured); the others went to the bench for the players who came on. + const SquadRange range = squad_range(team); + std::vector replaced; + for (uint16_t p : left) { + bool in_eleven = false; + for (size_t s = 0; s < std::min(11, range.count) && !in_eleven; ++s) + in_eleven = (g_.squad_slots.at(range.first + s) & 0x0fff) == p; + if (!in_eleven) replaced.push_back(p); + } + for (size_t k = 0; k < came.size(); ++k) { + AlmanacEvent e; + e.kind = AlmanacEventKind::Substitution; + e.minute = uint8_t(std::clamp(minute, 0, 255)); + e.side = uint8_t(side); + e.player = player_ref(came[k]); + if (k < replaced.size()) e.other = player_ref(replaced[k]); + pending_.push_back(e); + pending_match_.push_back(i); + } + before = std::move(now); + } + } +} + +void AlmanacRecorder::finish(const std::vector& shown) { + std::vector> events(running_.size()); + std::map, size_t> by_match; + for (size_t i = 0; i < running_.size(); ++i) by_match[{running_[i].group, running_[i].match}] = i; + auto ref = [&](int player) { return player >= 0 && player < 0x0fff ? player_ref(player) : kAlmanacNone; }; + // Goals, misses, cards and injuries: the event log of each group (Matches), which the + // engine keeps for every match. A pair of words per entry: player + code * 0x1000, then + // team * 0x80 + value (the minute; for the second pair of a chance the distance). + // 0 goal, 1 miss: followed by the assistant pair, code 2 open play, 7 penalty / free + // kick, 8 follow-up, 9 corner + // 3 yellow card, 4 second yellow, 5 red card, 6 injury + std::map, size_t> by_team; // (group, team) -> running match + for (size_t i = 0; i < running_.size(); ++i) + for (int side = 0; side < 2; ++side) + by_team[{running_[i].group, groups_.at(running_[i].group).fixtures.at(size_t(running_[i].match) * 2 + size_t(side))}] = i; + for (size_t gi = 0; gi < groups_.size(); ++gi) { + const auto& log = groups_[gi].log; + for (size_t w = 0; w + 1 < log.size(); w += 2) { + const int code = log[w] >> 12, player = log[w] & 0x0fff; + const int team = log[w + 1] >> 7, value = log[w + 1] & 0x7f; + const bool chance = code == 0 || code == 1; + int assistant = 0x0fff, detail = 0; + if (chance && w + 3 < log.size()) { + const int follow = log[w + 2] >> 12; + assistant = log[w + 2] & 0x0fff; + detail = follow == 2 ? 0 : std::clamp(follow - 6, 0, 3); + w += 2; + } + const auto it = by_team.find({gi, team}); + if (it == by_team.end()) continue; + AlmanacEvent e; + e.minute = uint8_t(value); + e.side = groups_[gi].fixtures.at(size_t(running_[it->second].match) * 2) == team ? 0 : 1; + e.player = ref(player); + switch (code) { + case 0: case 1: + e.kind = code == 0 ? AlmanacEventKind::Goal : AlmanacEventKind::Miss; + e.detail = uint8_t(detail); + e.other = ref(assistant); + break; + case 3: e.kind = AlmanacEventKind::YellowCard; break; + case 4: e.kind = AlmanacEventKind::SecondYellow; break; + case 5: e.kind = AlmanacEventKind::RedCard; break; + case 6: e.kind = AlmanacEventKind::Injury; break; + default: continue; + } + events[it->second].push_back(e); + } + } + // The kicks of a shoot-out (the log has none): the show events of the match engine. + for (const ShowEvent& s : shown) { + if (s.what != Show::PenaltyKick) continue; + const auto it = by_match.find({size_t(s.group), int(s.match)}); + if (it == by_match.end()) continue; + AlmanacEvent e; + e.kind = AlmanacEventKind::ShootoutKick; + e.minute = uint8_t(std::clamp(s.minute, 0, 255)); + e.side = s.side; + e.detail = s.flag ? 1 : 0; + e.player = ref(s.player); + events[it->second].push_back(e); + } + // Substitutions after the shown events of their minute (an injury, then its substitute). + for (size_t k = 0; k < pending_.size(); ++k) { + auto& list = events[pending_match_[k]]; + const auto at = std::upper_bound(list.begin(), list.end(), pending_[k].minute, + [](uint8_t minute, const AlmanacEvent& e) { return minute < e.minute; }); + list.insert(at, pending_[k]); + } + AlmanacSeason& season = g_.almanac.current; + for (size_t i = 0; i < running_.size(); ++i) { + Running& r = running_[i]; + const MatchGroup& group = groups_.at(r.group); + const int m = r.match; + if (group.results.empty() && (size_t(m) >= group.cup_results.size() || group.cup_results[size_t(m)] == 0xCCCC)) continue; + if (!group.results.empty() && group.results.at(size_t(m)) == 0xCC) continue; + int home = 0, away = 0; + if (!modern::match_score(group, m, home, away)) continue; + AlmanacMatch& rec = r.record; + rec.events = std::move(events[i]); + if (group.results.empty()) rec.decided = uint8_t(group.cup_results[size_t(m)] >> 10 & 3); + // After a shoot-out the stored score includes its goals (CupTie2): the goals of the + // match are those of the log, the rest were scored in the shoot-out. + if (rec.decided == 2) { + int goals[2] = {0, 0}; + for (const AlmanacEvent& e : rec.events) + if (e.kind == AlmanacEventKind::Goal) ++goals[e.side]; + rec.home_shootout = uint8_t(std::max(0, home - goals[0])); + rec.away_shootout = uint8_t(std::max(0, away - goals[1])); + } + rec.home_goals = uint8_t(std::max(0, home - rec.home_shootout)); + rec.away_goals = uint8_t(std::max(0, away - rec.away_shootout)); + if (size_t(m) < group.spectators.size()) rec.attendance = group.spectators[size_t(m)]; + season.matches.push_back(std::move(rec)); + } +} + +} // namespace bmh::modern diff --git a/src/modern/game/almanac.hpp b/src/modern/game/almanac.hpp new file mode 100644 index 0000000..35da92a --- /dev/null +++ b/src/modern/game/almanac.hpp @@ -0,0 +1,179 @@ +// SPDX-License-Identifier: GPL-3.0-only +#pragma once +// The football almanac of a Modern career (docs/new_engine/almanach.md, data format F10). +// +// Every match the engine plays is kept: season, date, competition, matchday or cup stage, +// both clubs with their human managers, the result (extra time, penalties), referee, +// attendance, weather, both line-ups and every event with its minute (goals with the +// assistant, cards, injuries, substitutions, shoot-out kicks). The almanac only watches: +// it draws no random numbers and changes nothing the season core reads. +// +// Identities are the stable ones of the world (club and player ids), not runtime indices: +// clubs swap their runtime index on promotion, and a player index is reused for a new +// person when a player retires or a youth player is created (new_player_identity). Each +// season keeps its own tables of the clubs, players, managers and referees it mentions, so a +// finished season is self-contained and never changes again; a save holds every finished +// season as one compact binary file (history/season-.bin) plus the running one. + +#include +#include +#include +#include +#include +#include + +namespace bmh { +struct MatchGroup; +struct ShowEvent; +} + +namespace bmh::modern { + +struct ModernState; + +enum class AlmanacEventKind : uint8_t { + Goal = 0, // player scorer, other assistant (or none), detail: chance kind (0 open + // play, 1 penalty / free kick, 2 follow-up, 3 corner) + YellowCard = 1, + RedCard = 2, + SecondYellow = 3, // yellow-red + Injury = 4, + Substitution = 5, // player comes on, other leaves (none when the slot was empty) + ShootoutKick = 6, // player takes the kick, detail 1 = scored + Miss = 7, // a chance without a goal: player shooter, other assistant, detail kind +}; + +constexpr uint16_t kAlmanacNone = 0xffff; // no player in an event or line-up entry + +struct AlmanacEvent { + AlmanacEventKind kind = AlmanacEventKind::Goal; + uint8_t minute = 0; // 1-based match minute (121 for the shoot-out) + uint8_t side = 0; // 0 home, 1 away (the acting team) + uint8_t detail = 0; + uint16_t player = kAlmanacNone, other = kAlmanacNone; // indices into the season's players + + bool operator==(const AlmanacEvent&) const = default; +}; + +// Competition of a match: a league (0-8 in Classic order, the world's league ids in the +// season header) or a cup (the cup id of the cup table: German cup, European cups, national +// team competitions, friendlies, indoor tournament, ...), with its stage entry. +struct AlmanacMatch { + uint32_t date = 0; // day counter of the calendar (almanac_date) + uint8_t type = 0; // descriptor type: 0 league, else cup id + 1 + uint8_t league = 0xff; // league index for type 0 + uint8_t stage = 0xff; // cup stage entry (cup table index) for cups + uint8_t round = 0; // league matchday 1.., or the round within the cup stage 1.. + uint16_t home = 0, away = 0; // indices into the season's clubs + int8_t home_manager = -1, away_manager = -1; // indices into the season's managers, -1 computer + uint8_t home_goals = 0, away_goals = 0; // after regular / extra time, without the shoot-out + uint8_t home_shootout = 0, away_shootout = 0; // shoot-out goals (decided == 2) + uint8_t decided = 0; // 0 regular time, 1 extra time, 2 penalties + uint8_t referee = 0; // index into the season's referees (0 = none) + uint32_t attendance = 0; + int8_t temperature = 0; // degrees Celsius + uint8_t rain = 0; // 0-7 as the engine draws it (snow when cold) + std::array, 2> lineup; // home, away: 11 starters, then the bench + std::vector events; // in match order + + bool operator==(const AlmanacMatch&) const = default; +}; + +struct AlmanacClub { + std::string id, name; // world club id (or team: without a world), UTF-8 name + bool operator==(const AlmanacClub&) const = default; +}; +struct AlmanacPlayer { + std::string id, first, last, nation; + bool operator==(const AlmanacPlayer&) const = default; +}; +struct AlmanacManager { + int index = -1; // manager slot of the career (human managers) + std::string name; + bool operator==(const AlmanacManager&) const = default; +}; +struct AlmanacLeague { + int index = -1; + std::string id, name; + bool operator==(const AlmanacLeague&) const = default; +}; + +struct AlmanacSeason { + int season = -1; // seasons played before (GameState::season) + int start_year = 0; // calendar year the season starts in + int display_start_year = 0; // year of day counter 0 (almanac_date) + std::vector leagues; + std::vector clubs; + std::vector players; + std::vector managers; + std::vector referees; // index 0 = none + std::vector matches; // in the order played + + bool operator==(const AlmanacSeason&) const = default; + + // Index of an entry, appending it when it is new (the lookups are rebuilt after decoding). + uint16_t club(const AlmanacClub& c); + uint16_t player(const AlmanacPlayer& p); + int8_t manager(const AlmanacManager& m); + uint8_t referee(const std::string& name); + void index(); // rebuilds the lookups from the tables + +private: + std::map club_at_, player_at_; + std::map referee_at_; +}; + +struct Almanac { + // Finished seasons, encoded (encode_almanac_season) and never changed again: the file + // name in the save and its bytes. + std::vector> finished; + AlmanacSeason current; + // Counter of the identities new_player_identity gave out (saved with the career). + uint32_t generated_players = 0; + + bool operator==(const Almanac& o) const { + return finished == o.finished && current == o.current && generated_players == o.generated_players; + } +}; + +struct AlmanacDate { int year = 0, month = 0, day = 0; }; +// The calendar date of a day counter (day 0 = 1 July of display_start_year), as the desk shows it. +AlmanacDate almanac_date(uint32_t counter, int display_start_year); + +// Binary form of a season (format version 1, little-endian; docs/new_engine/almanach.md). +std::string encode_almanac_season(const AlmanacSeason& season); +// Throws FormatError when the bytes are not an almanac season of a known version. +AlmanacSeason decode_almanac_season(const std::string& bytes); + +// A player index now belongs to a new person (retirement or youth player): gives it a new +// stable identity so the almanac does not merge the two careers. +void new_player_identity(ModernState& g, int player); + +// --- Recording (the Modern turn driver) --------------------------------------------------- +// One matchday as the turn driver plays it: begin after kick-off (line-ups, rounds), the +// minutes for substitutions, finish with the match engine's show events before the +// matchday's results are processed. +class AlmanacRecorder { +public: + AlmanacRecorder(ModernState& g, const std::vector& groups); + void after_minute(int minute); + void finish(const std::vector& events); + +private: + struct Running { + size_t group = 0; + int match = 0; + AlmanacMatch record; + std::array, 2> eleven; // runtime players on the pitch per side + }; + ModernState& g_; + const std::vector& groups_; + std::vector running_; + std::vector pending_; // substitutions found by after_minute, per running match + std::vector pending_match_; + + uint16_t player_ref(int player); + std::vector on_pitch(int team) const; +}; + +} // namespace bmh::modern diff --git a/src/modern/game/modern_state.hpp b/src/modern/game/modern_state.hpp index 3b4575f..6950c6b 100644 --- a/src/modern/game/modern_state.hpp +++ b/src/modern/game/modern_state.hpp @@ -15,6 +15,7 @@ #include "game/state.hpp" #include "game/world_layout.hpp" +#include "modern/game/almanac.hpp" #include "modern/game/training_camps.hpp" namespace bmh::modern { @@ -45,9 +46,12 @@ struct ModernState : GameState { std::vector world_club_id, world_club_name, world_club_short; // per team std::vector world_player_id, player_first, player_last; // per player std::vector player_nation; // nation id per player + std::vector world_league_id, world_league_name; // per league index // Training camps (M4): Classic data gives the eight original resorts, a Modern world its catalogue. std::vector camp_maps; std::vector training_camps; + // The football almanac (docs/new_engine/almanach.md): every match of the career. + Almanac almanac; ModernState() { season_hooks = &modern::season_hooks(); } // Takes over a state built by shared code (save loading, career setup). diff --git a/src/modern/game/season.cpp b/src/modern/game/season.cpp index af58499..384396c 100644 --- a/src/modern/game/season.cpp +++ b/src/modern/game/season.cpp @@ -681,6 +681,7 @@ bool youth_academy_player(ModernState& g, int m, GameRandom& game, WatcomRandom& const int band = league == 0 ? 0 : league == 1 ? 1 : league < 4 ? 2 : 3; const int level = game.range(kLevel[band][0], kLevel[band][1]); modern::generate_player(g, player, level | 0x3000, game, rand); + modern::new_player_identity(g, player); // the youth player is a new person (almanac) // PendingOfferAnswer(manager, player | 0xf000, -1, squad start) int slot = -1; for (size_t q = own.first; q < own.first + 24 && slot < 0; q++) @@ -1089,6 +1090,7 @@ bool release_player(ModernState& g, int slot, GameRandom& game, WatcomRandom& ra if (g.squad_slots.at(size_t(s)) == 0x0FFF) free = s; const uint32_t skills = g.players.at(size_t(player)).w35c; // RegeneratePlayer regenerate_player(g, player, 0x32, game, rand); + modern::new_player_identity(g, player); // a new person for the almanac Player& p = g.players.at(size_t(player)); p.w35c = skills; g.player_bonus.at(size_t(player)) &= 0x80; diff --git a/src/modern/game/turn_driver.cpp b/src/modern/game/turn_driver.cpp index ffaa41f..bd93d31 100644 --- a/src/modern/game/turn_driver.cpp +++ b/src/modern/game/turn_driver.cpp @@ -5,7 +5,9 @@ #include #include +#include #include +#include #include "modern/game/desk.hpp" #include "modern/game/driver.hpp" @@ -163,7 +165,15 @@ bool run_current_matchday(TurnDriver& driver, ModernState& g, GameRandom& game, if (manager_match_played) engine.original_sound(3); // EndPhase / ReadButtons, crowd. } std::vector sportschau_show_events; - if (driver.sportschau.fixture) engine.show = &sportschau_show_events; + // The almanac reads goals, cards and shoot-out kicks of every match from the show + // events, so Modern always collects them (appending draws no random numbers). + engine.show = &sportschau_show_events; + std::optional almanac; + try { + almanac.emplace(g, driver.groups); + } catch (const std::exception& e) { + std::fprintf(stderr, "almanac: matchday not recorded: %s\n", e.what()); + } engine.month = context.month; engine.buttons = read_buttons(g); engine.reality_rules = driver.reality_rules; @@ -246,6 +256,7 @@ bool run_current_matchday(TurnDriver& driver, ModernState& g, GameRandom& game, }; auto after_minute = [&](int minute) { collect_goals(minute); + if (almanac) almanac->after_minute(minute); if (driver.live_minute) driver.live_minute(minute, engine, driver.groups, g); }; turn_step = "play_matchday"; @@ -256,6 +267,14 @@ bool run_current_matchday(TurnDriver& driver, ModernState& g, GameRandom& game, if (manager_match_scored) events.push_back(audio_event(driver, TurnAudioKind::goal)); if (manager_match_played) events.push_back(audio_event(driver, TurnAudioKind::full_time_whistle)); + turn_step = "almanac"; + if (almanac) { + try { + almanac->finish(sportschau_show_events); + } catch (const std::exception& e) { + std::fprintf(stderr, "almanac: matchday not recorded: %s\n", e.what()); + } + } turn_step = "finish_event"; modern::store_group_descriptors(g, driver.groups, true); modern::finish_event(g, driver.groups, driver.calendar_entry, engine.buttons, diff --git a/tests/modern_almanac_tests.cpp b/tests/modern_almanac_tests.cpp new file mode 100644 index 0000000..df34041 --- /dev/null +++ b/tests/modern_almanac_tests.cpp @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: GPL-3.0-only +// The football almanac (docs/new_engine/almanach.md, M8) on synthetic data: the binary +// season round trip, damaged input, the calendar dates and new player identities. +#include +#include + +#include "formats/binary.hpp" +#include "modern/game/almanac.hpp" +#include "modern/game/modern_state.hpp" + +using namespace bmh; +using namespace bmh::modern; + +namespace { +int failures = 0; +void check(bool ok, const char* what) { + if (!ok) { + std::fprintf(stderr, "FAIL: %s\n", what); + ++failures; + } +} + +AlmanacSeason sample() { + AlmanacSeason s; + s.season = 3, s.start_year = 2029, s.display_start_year = 2026; + s.leagues.push_back({0, "comp:bundesliga", "Bundesliga"}); + s.referees.push_back({}); + const uint16_t home = s.club({"club:sued", "FC Südstadt"}); + const uint16_t away = s.club({"club:nord", "SV Nordstadt"}); + const uint16_t a = s.player({"player:1", "Anton", "Beispiel", "nation:de"}); + const uint16_t b = s.player({"player:gen-7", "", "Größer", "nation:de"}); + AlmanacMatch m; + m.date = 400, m.type = 2, m.stage = 5, m.round = 2, m.home = home, m.away = away; + m.home_manager = s.manager({0, "Testmanager"}); + m.home_goals = 1, m.away_goals = 1, m.home_shootout = 5, m.away_shootout = 3, m.decided = 2; + m.referee = s.referee("Schiri A"); + m.attendance = 75000, m.temperature = -3, m.rain = 6; + m.lineup[0] = {a, b}; + m.events.push_back({AlmanacEventKind::Goal, 12, 0, 3, a, b}); + m.events.push_back({AlmanacEventKind::SecondYellow, 77, 1, 0, b, kAlmanacNone}); + m.events.push_back({AlmanacEventKind::Substitution, 80, 0, 0, b, a}); + m.events.push_back({AlmanacEventKind::ShootoutKick, 121, 1, 1, a, kAlmanacNone}); + s.matches.push_back(m); + return s; +} +} // namespace + +int main() { + const AlmanacSeason s = sample(); + const std::string bytes = encode_almanac_season(s); + const AlmanacSeason back = decode_almanac_season(bytes); + check(back == s, "season round trip"); + check(encode_almanac_season(back) == bytes, "stable encoding"); + + AlmanacSeason grown = back; // the lookups survive decoding: no duplicate entries + check(grown.club({"club:sued", "FC Südstadt"}) == 0 && grown.clubs.size() == 2, "club lookup after decode"); + check(grown.referee("Schiri A") == 1 && grown.referees.size() == 2, "referee lookup after decode"); + + bool refused = false; + try { decode_almanac_season(bytes.substr(0, bytes.size() - 3)); } catch (const FormatError&) { refused = true; } + check(refused, "truncated season refused"); + refused = false; + try { decode_almanac_season(bytes + "x"); } catch (const FormatError&) { refused = true; } + check(refused, "trailing bytes refused"); + refused = false; + try { decode_almanac_season("OBAL\x09\x00"); } catch (const FormatError&) { refused = true; } + check(refused, "unknown version refused"); + + // Day 0 is 1 July of the display start year; the calendar's first leap year comes after one year. + const AlmanacDate d0 = almanac_date(0, 2026), d1 = almanac_date(183, 2026), d2 = almanac_date(365, 2026); + check(d0.year == 2026 && d0.month == 7 && d0.day == 1, "date of day 0"); + check(d1.year == 2026 && d1.month == 12 && d1.day == 31, "date of day 183"); + check(d2.year == 2027 && d2.month == 7 && d2.day == 1, "date of day 365"); + + ModernState g; + g.players.resize(5); + new_player_identity(g, 3); + new_player_identity(g, 3); + check(g.world_player_id.size() == 5 && g.world_player_id[3] == "player:gen-2" && g.almanac.generated_players == 2, + "new player identities"); + + if (failures == 0) std::printf("modern almanac tests passed\n"); + return failures == 0 ? 0 : 1; +} diff --git a/tests/modern_season_sim.cpp b/tests/modern_season_sim.cpp index 1ad5bbe..1795c5d 100644 --- a/tests/modern_season_sim.cpp +++ b/tests/modern_season_sim.cpp @@ -91,6 +91,51 @@ int g_high_scores = 0; // matches with 13-15 goals (outside shoot-outs) int g_human_team = -1, g_human_for = 0, g_human_against = 0, g_human_matches = 0; int g_league_goals = 0, g_league_matches = 0; +// The almanac of the run (docs/new_engine/almanach.md): size, consistency of the recorded +// goals with the results, and the top scorers over all seasons by stable player id. +void print_almanac(const modern::ModernState& g) { + std::vector seasons; + size_t bytes = 0; + for (const auto& [name, data] : g.almanac.finished) { + seasons.push_back(modern::decode_almanac_season(data)); + bytes += data.size(); + } + if (g.almanac.current.season >= 0) { + const std::string data = modern::encode_almanac_season(g.almanac.current); + bytes += data.size(); + if (!(modern::decode_almanac_season(data) == g.almanac.current)) std::printf("almanac: current season does not round-trip\n"); + seasons.push_back(g.almanac.current); + } + size_t matches = 0, events = 0, mismatched = 0, without_lineup = 0; + std::map> scorers; // player id -> goals, name + for (const auto& s : seasons) { + matches += s.matches.size(); + for (const auto& m : s.matches) { + events += m.events.size(); + int goals[2] = {0, 0}; + for (const auto& e : m.events) { + if (e.kind != modern::AlmanacEventKind::Goal) continue; + ++goals[e.side]; + if (e.player == modern::kAlmanacNone) continue; + const auto& p = s.players.at(e.player); + auto& row = scorers[p.id]; + ++row.first; + row.second = (p.first.empty() ? "" : p.first + " ") + p.last; + } + if (goals[0] != m.home_goals || goals[1] != m.away_goals) ++mismatched; + if (m.lineup[0].empty() && m.lineup[1].empty()) ++without_lineup; + } + } + std::printf("almanac: %zu seasons, %zu matches, %zu events, %zu bytes uncompressed, %u new player identities\n", + seasons.size(), matches, events, bytes, g.almanac.generated_players); + std::printf("almanac: %zu matches whose goal events differ from the result, %zu without line-ups\n", mismatched, without_lineup); + std::vector> top; + for (const auto& [id, row] : scorers) top.emplace_back(row.first, row.second + " (" + id + ")"); + std::sort(top.begin(), top.end(), [](const auto& a, const auto& b) { return a.first > b.first; }); + for (size_t i = 0; i < std::min(5, top.size()); ++i) + std::printf("almanac top scorer %zu: %d goals, %s\n", i + 1, top[i].first, top[i].second.c_str()); +} + // Read only the current season's first-league results. A complete German Bundesliga // season has 34 rounds x 9 fixtures = 306 matches. Unlike the historical snapshot // counters, this includes background fixtures played while seeking the next desk. @@ -407,13 +452,16 @@ int main(int argc, char** argv) { h.player_last == g.player_last && h.world_player_id == g.world_player_id; const bool same_layout = world_layout().league_teams == layout.league_teams && world_layout().total_slots == layout.total_slots; - std::printf("save check at turn %d: state %s, names %s, layout %s, %ju bytes\n", played, + const bool same_almanac = h.almanac == g.almanac && h.world_league_id == g.world_league_id; + std::printf("save check at turn %d: state %s, names %s, layout %s, almanac %s, %ju bytes\n", played, same_state ? "same" : "DIFFERS", same_names ? "same" : "DIFFER", - same_layout ? "same" : "DIFFERS", uintmax_t(std::filesystem::file_size(file))); + same_layout ? "same" : "DIFFERS", same_almanac ? "same" : "DIFFERS", + uintmax_t(std::filesystem::file_size(file))); } } } print_first_league_results(g, "run end"); + if (modern::current_world()) print_almanac(g); if (std::getenv("SIM_ADVERTISING")) std::printf("%d advertising contracts accepted (SIM_ADVERTISING=1)\n", ad_contracts); if (std::getenv("SIM_INTERVENE")) std::printf("%d interventions (substitution at minute 30, re-rated)\n", interventions); if (sim_contracts_env && std::string(sim_contracts_env) == "1")