// SPDX-License-Identifier: GPL-3.0-only #include "modern/content/statistics.hpp" #include #include #include #include #include #include #include #include #include "formats/executable_layout.hpp" #include "game/messages.hpp" #include "game/schedule.hpp" #include "game/table.hpp" #include "modern/content/ui_contract.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; J error(const char* code) { return O{{"ok", false}, {"error", code}}; } std::string season_label(int start_year) { const int next = (start_year + 1) % 100; return std::to_string(start_year) + "/" + (next < 10 ? "0" : "") + std::to_string(next); } std::string iso_date(uint32_t counter, int display_start_year) { const AlmanacDate d = almanac_date(counter, display_start_year); char out[16]; std::snprintf(out, sizeof out, "%04d-%02d-%02d", d.year, d.month, d.day); return out; } // Every season of the career: the finished ones decoded, then the running one. std::vector seasons_of(const ModernState& g) { std::vector out; for (const auto& [name, bytes] : g.almanac.finished) out.push_back(decode_almanac_season(bytes)); if (g.almanac.current.season >= 0) out.push_back(g.almanac.current); return out; } // A competition as the statistics name it: leagues by the world's league id, cups by // their cup id, the indoor Masters apart from the single tournaments. struct Competition { std::string id, name, type; int order = 0; // leagues first (by index), then cups (by cup id) }; std::string cup_name(const ModernState& g, int cup) { // The indoor tournament's text names the venue of the next tournament (with a // placeholder); the statistics list all tournaments under one name. if (cup == 0xb) return "Hallenturnier"; std::string name; try { if (g.texts) name = almanac_utf8(message_text(g, ::bmh::layout::DeskState_FormatError_ExecutableField3 + uint32_t(cup + 1) * 4)); } catch (const std::exception&) { name.clear(); } return name.empty() ? "Pokal " + std::to_string(cup) : name; } Competition league_competition(const AlmanacSeason& s, int league) { Competition c; c.type = "league"; c.order = league; for (const auto& l : s.leagues) if (l.index == league) c.id = l.id, c.name = l.name; if (c.id.empty()) c.id = "league:" + std::to_string(league); if (c.name.empty()) c.name = "Liga " + std::to_string(league + 1); return c; } Competition cup_competition(const ModernState& g, int cup, bool masters) { Competition c; c.type = "cup"; c.order = 100 + cup * 2 + (masters ? 1 : 0); c.id = "cup:" + std::to_string(cup) + (masters ? ":masters" : ""); c.name = masters ? "Hallen-Masters" : cup_name(g, cup); return c; } Competition competition_of(const ModernState& g, const AlmanacSeason& s, const AlmanacMatch& m) { return m.type == 0 ? league_competition(s, m.league) : cup_competition(g, m.type - 1, false); } Competition competition_of(const ModernState& g, const AlmanacSeason& s, const AlmanacWinner& w) { return w.type == 0 ? league_competition(s, w.league) : cup_competition(g, w.type - 1, w.detail == 1); } J club_json(const AlmanacSeason& s, uint16_t club) { if (club >= s.clubs.size()) return nullptr; return O{{"id", s.clubs[club].id}, {"name", s.clubs[club].name}}; } std::string player_name(const AlmanacPlayer& p) { return p.first.empty() ? p.last : p.first + " " + p.last; } 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; } J competitions(const ModernState& g, const std::vector& seasons) { std::map>> found; // id -> seasons auto note = [&](const Competition& c, const std::string& season) { auto& entry = found[c.id]; entry.first = c; if (entry.second.empty() || entry.second.back() != season) entry.second.push_back(season); }; for (const auto& s : seasons) { const std::string label = season_label(s.start_year); for (const auto& m : s.matches) note(competition_of(g, s, m), label); for (const auto& w : s.winners) note(competition_of(g, s, w), label); } std::vector>> list; for (auto& [id, entry] : found) list.push_back(std::move(entry)); std::sort(list.begin(), list.end(), [](const auto& a, const auto& b) { return a.first.order < b.first.order; }); A out; for (const auto& [c, labels] : list) { A season_list; for (const auto& l : labels) season_list.push_back(l); out.push_back(O{{"id", c.id}, {"name", c.name}, {"type", c.type}, {"seasons", std::move(season_list)}}); } return O{{"ok", true}, {"competitions", std::move(out)}}; } J winners(const ModernState& g, const std::vector& seasons, const std::string& only) { std::map> found; for (const auto& s : seasons) { std::map edition; // several indoor tournaments in a season for (const auto& w : s.winners) { const Competition c = competition_of(g, s, w); if (!only.empty() && c.id != only) continue; auto& entry = found[c.id]; entry.first = c; entry.second.push_back(O{{"season", season_label(s.start_year)}, {"year", s.start_year}, {"edition", ++edition[c.id]}, {"date", iso_date(w.date, s.display_start_year)}, {"winner", club_json(s, w.winner)}, {"runner_up", w.runner_up == 0xffff ? J(nullptr) : club_json(s, w.runner_up)}}); } } std::vector> list; for (auto& [id, entry] : found) list.push_back(std::move(entry)); std::sort(list.begin(), list.end(), [](const auto& a, const auto& b) { return a.first.order < b.first.order; }); A out; for (auto& [c, rows] : list) out.push_back(O{{"id", c.id}, {"name", c.name}, {"type", c.type}, {"winners", std::move(rows)}}); return O{{"ok", true}, {"competitions", std::move(out)}}; } struct PlayerRow { std::string id, name, club_id, club_name; int appearances = 0, goals = 0, assists = 0, yellow = 0, second_yellow = 0, red = 0; uint64_t last = 0; // order of the player's last match (his club is the club of that match) }; J player_stats(const ModernState& g, const std::vector& seasons, const std::string& competition, const std::string& season, const std::string& sort, size_t limit) { std::map rows; uint64_t order = 0; for (const auto& s : seasons) { if (!season.empty() && season_label(s.start_year) != season) continue; for (const auto& m : s.matches) { ++order; if (competition_of(g, s, m).id != competition) continue; auto row = [&](uint16_t player, int side) -> PlayerRow* { if (player >= s.players.size()) return nullptr; const AlmanacPlayer& p = s.players[player]; PlayerRow& r = rows[p.id]; r.id = p.id, r.name = player_name(p); if (order >= r.last) { const uint16_t club = side ? m.away : m.home; r.club_id = s.clubs.at(club).id, r.club_name = s.clubs.at(club).name, r.last = order; } return &r; }; for (int side = 0; side < 2; ++side) { const auto& lineup = m.lineup[size_t(side)]; for (size_t k = 0; k < std::min(11, lineup.size()); ++k) if (PlayerRow* r = row(lineup[k], side)) ++r->appearances; } for (const auto& e : m.events) { switch (e.kind) { case AlmanacEventKind::Goal: if (PlayerRow* r = row(e.player, e.side)) ++r->goals; if (PlayerRow* r = row(e.other, e.side)) ++r->assists; break; case AlmanacEventKind::YellowCard: if (PlayerRow* r = row(e.player, e.side)) ++r->yellow; break; case AlmanacEventKind::SecondYellow: if (PlayerRow* r = row(e.player, e.side)) ++r->second_yellow; break; case AlmanacEventKind::RedCard: if (PlayerRow* r = row(e.player, e.side)) ++r->red; break; case AlmanacEventKind::Substitution: if (PlayerRow* r = row(e.player, e.side)) ++r->appearances; break; default: break; } } } } auto key = [&](const PlayerRow& r) { if (sort == "assists") return r.assists; if (sort == "yellow") return r.yellow; if (sort == "red") return r.red + r.second_yellow; return r.goals; }; std::vector list; for (auto& [id, r] : rows) if (key(r) > 0) list.push_back(std::move(r)); std::sort(list.begin(), list.end(), [&](const PlayerRow& a, const PlayerRow& b) { if (key(a) != key(b)) return key(a) > key(b); if (a.appearances != b.appearances) return a.appearances < b.appearances; // fewer games ranks first return a.name < b.name; }); A out; int rank = 0, previous = -1; for (size_t i = 0; i < list.size() && (limit == 0 || i < limit); ++i) { const PlayerRow& r = list[i]; if (key(r) != previous) rank = int(i) + 1, previous = key(r); out.push_back(O{{"rank", rank}, {"player", O{{"id", r.id}, {"name", r.name}}}, {"club", O{{"id", r.club_id}, {"name", r.club_name}}}, {"appearances", r.appearances}, {"goals", r.goals}, {"assists", r.assists}, {"yellow", r.yellow}, {"second_yellow", r.second_yellow}, {"red", r.red}}); } return O{{"ok", true}, {"competition", competition}, {"season", season.empty() ? J(nullptr) : J(season)}, {"sort", sort}, {"players", std::move(out)}}; } } // namespace cli::Json query_statistics(const ModernState& g, const cli::Json& request) { const J* kind = field(request, "kind"); if (!kind || !kind->string()) return error("invalid_statistics_request"); try { const auto seasons = seasons_of(g); if (*kind->string() == "competitions") return competitions(g, seasons); if (*kind->string() == "winners") { const J* only = field(request, "competition"); if (only && !only->string()) return error("invalid_statistics_request"); return winners(g, seasons, only ? *only->string() : std::string()); } if (*kind->string() == "player_stats") { const J* competition = field(request, "competition"); const J* season = field(request, "season"); const J* sort = field(request, "sort"); const J* limit = field(request, "limit"); if (!competition || !competition->string() || (season && !season->string() && !std::holds_alternative(season->value)) || (sort && !sort->string()) || (limit && (!limit->integer() || *limit->integer() < 0))) return error("invalid_statistics_request"); const std::string order = sort ? *sort->string() : "goals"; if (order != "goals" && order != "assists" && order != "yellow" && order != "red") return error("invalid_statistics_request"); return player_stats(g, seasons, *competition->string(), season && season->string() ? *season->string() : "", order, limit ? size_t(*limit->integer()) : 50); } return error("invalid_statistics_request"); } catch (const std::exception&) { return error("statistics_unavailable"); } } // --- the almanac view of the Modern UI (DataSource::read_almanac; the demo's request kinds) ------ namespace { J almanac_person(const AlmanacSeason& s, uint16_t player) { if (player == kAlmanacNone || player >= s.players.size()) return nullptr; const AlmanacPlayer& p = s.players[player]; return O{{"id", p.id}, {"name", player_name(p)}}; } J almanac_side(const ModernState& g, const AlmanacSeason& s, uint16_t club, int8_t manager) { J m = nullptr; if (manager >= 0 && size_t(manager) < s.managers.size()) { const AlmanacManager& a = s.managers[size_t(manager)]; std::string id = a.index >= 0 && size_t(a.index) < g.manager_ids.size() ? g.manager_ids[size_t(a.index)] : std::string{}; if (id.empty()) id = "manager:slot-" + std::to_string(a.index); m = O{{"id", id}, {"name", a.name}}; } return O{{"id", s.clubs[club].id}, {"name", s.clubs[club].name}, {"crest", nullptr}, {"manager", std::move(m)}}; } std::string match_id(const AlmanacSeason& s, size_t index) { return "match:" + std::to_string(s.start_year) + "-" + std::to_string(index); } // One recorded match in the form the almanac screen reads. The score after 90 minutes and the // extra time are told apart by the goal minutes; a line-up shorter than eleven is not known (null). J almanac_match(const ModernState& g, const AlmanacSeason& s, size_t index) { static constexpr const char* kKinds[8] = {"goal", "yellow", "red", "second_yellow", "injury", "substitution", "shootout", "miss"}; const AlmanacMatch& m = s.matches[index]; const Competition c = competition_of(g, s, m); const std::string type = m.type == 0 ? "league" : m.type - 1 == 10 ? "friendly" : "cup"; int regulation[2] = {0, 0}; for (const auto& e : m.events) if (e.kind == AlmanacEventKind::Goal && e.minute <= 90 && e.side < 2) ++regulation[e.side]; const bool extra = m.decided >= 1, shootout = m.decided == 2; J lineups = O{}; for (int side = 0; side < 2; ++side) { const auto& l = m.lineup[size_t(side)]; if (l.size() < 11) { std::get(lineups.value)[side ? "away" : "home"] = nullptr; continue; } A starters, bench; for (size_t i = 0; i < l.size(); ++i) (i < 11 ? starters : bench).push_back(almanac_person(s, l[i])); std::get(lineups.value)[side ? "away" : "home"] = O{{"starters", std::move(starters)}, {"bench", std::move(bench)}}; } A events; for (const auto& e : m.events) events.push_back(O{{"kind", kKinds[size_t(e.kind) & 7]}, {"minute", int(e.minute)}, {"side", e.side ? "away" : "home"}, {"player", almanac_person(s, e.player)}, {"other", almanac_person(s, e.other)}, {"detail", int(e.detail)}}); return O{{"id", match_id(s, index)}, {"date", iso_date(m.date, s.display_start_year)}, {"season", season_label(s.start_year)}, {"competition", O{{"id", c.id}, {"name", c.name}, {"type", type}}}, {"round", int(m.round)}, {"home", almanac_side(g, s, m.home, m.home_manager)}, {"away", almanac_side(g, s, m.away, m.away_manager)}, {"result", O{{"regulation", extra ? J(A{J(regulation[0]), J(regulation[1])}) : J(A{J(int(m.home_goals)), J(int(m.away_goals))})}, {"extra", extra ? J(A{J(int(m.home_goals) - regulation[0]), J(int(m.away_goals) - regulation[1])}) : J(nullptr)}, {"penalties", shootout ? J(A{J(int(m.home_shootout)), J(int(m.away_shootout))}) : J(nullptr)}, {"final", A{J(int(m.home_goals)), J(int(m.away_goals))}}, {"extra_played", extra}, {"penalties_played", shootout}}}, {"referee", m.referee > 0 && m.referee < s.referees.size() ? J(s.referees[m.referee]) : J(nullptr)}, {"attendance", int64_t(m.attendance)}, {"weather", O{{"temperature", int(m.temperature)}, {"rain", int(m.rain)}}}, {"lineups", std::move(lineups)}, {"events", std::move(events)}}; } } // namespace cli::Json query_almanac(const ModernState& g, const cli::Json& request) { const J* kind = field(request, "kind"); if (!kind || !kind->string()) return error("invalid_almanac_request"); try { const auto seasons = seasons_of(g); const std::string k = *kind->string(); if (k == "index") { std::set years; std::string first, last; size_t count = 0; for (const auto& s : seasons) for (const auto& m : s.matches) { const std::string d = iso_date(m.date, s.display_start_year); years.insert(std::stoi(d.substr(0, 4))); if (first.empty() || d < first) first = d; if (d > last) last = d; ++count; } A listed; for (int y : years) listed.push_back(y); return O{{"ok", true}, {"years", std::move(listed)}, {"match_count", int64_t(count)}, {"first_date", first.empty() ? J(nullptr) : J(first)}, {"last_date", last.empty() ? J(nullptr) : J(last)}}; } if (k == "calendar") { const J* year = field(request, "year"); if (!year || !year->integer()) return error("invalid_almanac_request"); std::map> days; for (const auto& s : seasons) for (size_t i = 0; i < s.matches.size(); ++i) { const AlmanacMatch& m = s.matches[i]; const std::string d = iso_date(m.date, s.display_start_year); if (std::stoi(d.substr(0, 4)) != *year->integer()) continue; auto& day = days[d]; ++day.first; if (m.decided >= 1 || m.home_goals + m.away_goals >= 4) day.second.push_back(match_id(s, i)); } A listed; for (auto& [d, day] : days) listed.push_back(O{{"date", d}, {"count", day.first}, {"highlights", std::move(day.second)}}); return O{{"ok", true}, {"year", *year->integer()}, {"days", std::move(listed)}}; } if (k == "day") { const J* date = field(request, "date"); if (!date || !date->string()) return error("invalid_almanac_request"); A matches; for (const auto& s : seasons) for (size_t i = 0; i < s.matches.size(); ++i) if (iso_date(s.matches[i].date, s.display_start_year) == *date->string()) matches.push_back(almanac_match(g, s, i)); return O{{"ok", true}, {"date", *date->string()}, {"matches", std::move(matches)}}; } if (k == "match") { const J* id = field(request, "id"); if (!id || !id->string()) return error("invalid_almanac_request"); for (const auto& s : seasons) for (size_t i = 0; i < s.matches.size(); ++i) if (match_id(s, i) == *id->string()) return O{{"ok", true}, {"match", almanac_match(g, s, i)}}; return error("almanac_match_not_found"); } return error("invalid_almanac_request"); } catch (const std::exception&) { return error("almanac_unavailable"); } } // --- the statistics screen of the Modern UI (DataSource::read_statistics; the demo's filters) --- namespace { constexpr const char* kSections[9] = {"Möglichkeiten", "Transferhistorie", "Analytics", "Ewige Tabelle", "WM-Statistiken", "Saisonfinanzen", "Serien u. Rekorde", "Sieger", "Minuten-Statistik"}; constexpr const char* kWorldViews[6] = {"Sieger", "Gruppen", "Torschützen", "Finalrunde", "Tabelle", "Historie"}; // The first league of the countries with leagues, in the screen's order (de, es, it, fr, en); // kEternal maps the eternal table's values (de, es, en, fr, it) to it. struct Country { const char* code; const char* name; int league; }; constexpr Country kCountries[5] = {{"de", "Deutschland", 0}, {"es", "Spanien", 5}, {"it", "Italien", 8}, {"fr", "Frankreich", 7}, {"en", "England", 6}}; constexpr int kEternal[5] = {0, 1, 4, 3, 2}; J cell(const std::string& text) { return O{{"text", text}}; } J numeric(int64_t v) { return O{{"text", std::to_string(v)}, {"value", v}}; } J club_cell(const AlmanacClub& c) { return O{{"text", c.name}, {"club", c.id}}; } J nation_cell(const AlmanacClub& c) { return O{{"text", c.name}, {"nation", c.id}}; } // The world's nation of the league's clubs; without a world "nation:". std::string country_nation(const Country& c) { if (const World* w = current_world()) for (const auto& l : w->leagues) if (l.index == c.league && !l.members.empty()) if (const WorldClub* club = w->club(l.members.front()); club && !club->nation.empty()) return club->nation; return std::string("nation:") + c.code; } void headings(O& out, std::initializer_list names) { A& cols = std::get(out["columns"].value); for (const char* n : names) cols.push_back(cell(n)); } void row(O& out, A cells) { std::get(out["rows"].value).push_back(O{{"cells", std::move(cells)}}); } // The ids of a league's clubs as the running game has them. std::set league_club_ids(const ModernState& g, int league) { std::set ids; if (league < 0) return ids; const int first = league_first_team(league); for (int t = first; t < first + int(kLeagueSizes[league]); ++t) { const std::string id = t < int(g.world_club_id.size()) ? g.world_club_id[size_t(t)] : std::string{}; ids.insert(id.empty() ? "team:" + std::to_string(t) : id); } return ids; } void eternal_table(O& out, const std::vector& seasons, int league) { headings(out, {"Verein", "Sp.", "S", "U", "N", "Punkte", "Tore"}); struct Sum { AlmanacClub club; int played = 0, won = 0, drawn = 0, lost = 0, points = 0, gf = 0, ga = 0; }; std::map sums; for (const auto& s : seasons) for (const auto& t : s.tables) { if (t.league != league) continue; for (const auto& r : t.rows) { Sum& x = sums[s.clubs[r.club].id]; x.club = s.clubs[r.club]; x.played += r.played, x.won += r.won, x.drawn += r.drawn, x.lost += r.lost, x.points += r.points; x.gf += r.goals_for, x.ga += r.goals_against; } } std::vector list; for (auto& [id, x] : sums) list.push_back(x); std::stable_sort(list.begin(), list.end(), [](const Sum& a, const Sum& b) { return a.points != b.points ? a.points > b.points : a.gf - a.ga > b.gf - b.ga; }); for (const auto& x : list) row(out, A{club_cell(x.club), numeric(x.played), numeric(x.won), numeric(x.drawn), numeric(x.lost), numeric(x.points), cell(std::to_string(x.gf) + ":" + std::to_string(x.ga))}); } // The national tournaments: cup 6 is the final round (a final), cup 7 the qualification. bool national_match(const AlmanacMatch& m) { return m.type == 7 || m.type == 8; } bool world_tournaments(O& out, const ModernState& g, const std::vector& seasons, int view) { if (view == 0) { headings(out, {"WM / EM", "Sieger", "Finalist", "Finale"}); for (auto s = seasons.rbegin(); s != seasons.rend(); ++s) for (const auto& w : s->winners) { if (w.type != 7) continue; std::string final_score = "—"; for (const auto& m : s->matches) if (m.type == 7 && ((m.home == w.winner && m.away == w.runner_up) || (m.away == w.winner && m.home == w.runner_up))) final_score = std::to_string(m.home_goals) + ":" + std::to_string(m.away_goals); const std::string when = std::to_string(s->start_year + 1); row(out, A{J(O{{"text", cup_name(g, 6) + " " + when}, {"season", when}, {"winner", s->clubs[w.winner].id}}), nation_cell(s->clubs[w.winner]), w.runner_up == 0xffff ? cell("—") : nation_cell(s->clubs[w.runner_up]), cell(final_score)}); } return true; } if (view == 2) { headings(out, {"Spieler", "Land", "Tore"}); struct Scorer { int goals = 0; J player, nation; }; std::map scorers; for (const auto& s : seasons) for (const auto& m : s.matches) { if (!national_match(m)) continue; for (const auto& e : m.events) { if (e.kind != AlmanacEventKind::Goal || e.player == kAlmanacNone || e.player >= s.players.size()) continue; const AlmanacPlayer& p = s.players[e.player]; Scorer& x = scorers[p.id]; ++x.goals; x.player = O{{"text", player_name(p)}, {"player", p.id}}; x.nation = nation_cell(s.clubs[e.side ? m.away : m.home]); } } std::vector list; for (auto& [id, x] : scorers) list.push_back(x); std::stable_sort(list.begin(), list.end(), [](const Scorer& a, const Scorer& b) { return a.goals > b.goals; }); for (size_t i = 0; i < list.size() && i < 20; ++i) row(out, A{list[i].player, list[i].nation, numeric(list[i].goals)}); return true; } if (view == 4 || view == 5) { headings(out, {"Land", "Spiele", "Siege", "Punkte"}); struct Rec { AlmanacClub club; int games = 0, wins = 0, points = 0; }; std::map recs; for (const auto& s : seasons) for (const auto& m : s.matches) { if (!national_match(m)) continue; for (int side = 0; side < 2; ++side) { Rec& r = recs[s.clubs[side ? m.away : m.home].id]; r.club = s.clubs[side ? m.away : m.home]; const int own = side ? m.away_goals : m.home_goals, other = side ? m.home_goals : m.away_goals; ++r.games; if (own > other) ++r.wins, r.points += 3; else if (own == other) r.points += 1; } } std::vector list; for (auto& [id, r] : recs) list.push_back(r); std::stable_sort(list.begin(), list.end(), [](const Rec& a, const Rec& b) { return a.points > b.points; }); for (const auto& r : list) row(out, A{nation_cell(r.club), numeric(r.games), numeric(r.wins), numeric(r.points)}); return true; } return false; // groups, final round: not yet } void series_and_records(O& out, const ModernState& g, const std::vector& seasons, int league) { headings(out, {"Serie / Rekord", "Verein", "Wert"}); const auto ids = league_club_ids(g, league); struct Run { int unbeaten = 0, wins = 0, scoring = 0, best_unbeaten = 0, best_wins = 0, best_scoring = 0; AlmanacClub club; }; std::map runs; struct Best { AlmanacClub club; std::array value{}; }; // home wins, away wins, goals in one season std::map season_best; int biggest = -1, crowd = -1; J biggest_club = cell("—"), crowd_club = cell("—"); std::string big_score; for (const auto& s : seasons) { std::map this_season; for (const auto& m : s.matches) { if (m.type != 0 || m.league != league) continue; for (int side = 0; side < 2; ++side) { const AlmanacClub& c = s.clubs[side ? m.away : m.home]; if (!ids.count(c.id)) continue; const int own = side ? m.away_goals : m.home_goals, other = side ? m.home_goals : m.away_goals; Run& r = runs[c.id]; r.club = c; r.unbeaten = own >= other ? r.unbeaten + 1 : 0; r.wins = own > other ? r.wins + 1 : 0; r.scoring = own > 0 ? r.scoring + 1 : 0; r.best_unbeaten = std::max(r.best_unbeaten, r.unbeaten); r.best_wins = std::max(r.best_wins, r.wins); r.best_scoring = std::max(r.best_scoring, r.scoring); Best& x = this_season[c.id]; x.club = c; if (own > other) ++x.value[size_t(side)]; x.value[2] += own; if (own - other > biggest) biggest = own - other, biggest_club = club_cell(c), big_score = std::to_string(own) + " : " + std::to_string(other); if (side == 0 && int(m.attendance) > crowd) crowd = int(m.attendance), crowd_club = club_cell(c); } } for (auto& [id, x] : this_season) { Best& b = season_best[id]; b.club = x.club; for (size_t k = 0; k < 3; ++k) b.value[k] = std::max(b.value[k], x.value[k]); } } const auto best_run = [&](int Run::*value, const char* name) { int best = 0; J who = cell("—"); for (const auto& [id, r] : runs) if (r.*value > best) best = r.*value, who = club_cell(r.club); if (best > 0) row(out, A{cell(name), who, numeric(best)}); }; const auto best_season = [&](size_t k, const char* name) { int best = 0; J who = cell("—"); for (const auto& [id, b] : season_best) if (b.value[k] > best) best = b.value[k], who = club_cell(b.club); if (best > 0) row(out, A{cell(name), who, numeric(best)}); }; best_run(&Run::best_unbeaten, "Ungeschlagen"); best_run(&Run::best_wins, "Siege in Folge"); best_season(0, "Heimsiege"); best_season(1, "Auswärtssiege"); best_season(2, "Tore in einer Saison"); if (biggest > 0) row(out, A{cell("Höchster Sieg"), biggest_club, cell(big_score)}); best_run(&Run::best_scoring, "Längste Torserie"); if (crowd > 0) row(out, A{cell("Meiste Zuschauer"), crowd_club, numeric(crowd)}); } void winners_by_season(O& out, const std::vector& seasons, int category, int country) { struct Title { const char* text; const char* trophy; int type; int league; int detail; }; std::vector titles; if (category == 0) { const Country& c = kCountries[country]; titles.push_back({"Meisterschaft", c.league == 0 ? "championship" : "", 0, c.league, 0}); if (c.league == 0) titles.push_back({"DFB-Pokal", "dfb-cup", 1, -1, 0}); out["note"] = std::string(c.name) + " · Titelträger im Saisonvergleich"; } else if (category == 1) { titles = {{"Champions League", "champions-league", 2, -1, 0}, {"Pokalsieger", "cup-winners", 3, -1, 0}, {"UEFA-Cup", "uefa-cup", 4, -1, 0}}; out["note"] = "Europäische Titelträger im Saisonvergleich"; } else { titles = {{"Sieger", "indoor-masters", 12, -1, 1}, {"Finalist", "", 12, -1, 2}}; out["note"] = "Hallenmasters · Sieger und Finalisten"; } headings(out, {"Saison"}); for (const auto& t : titles) std::get<A>(out["columns"].value).push_back(O{{"text", t.text}, {"trophy", t.trophy}}); for (auto s = seasons.rbegin(); s != seasons.rend(); ++s) { A cells{cell(season_label(s->start_year))}; bool any = false; for (const auto& t : titles) { J value = cell("—"); for (const auto& w : s->winners) { if (w.type != t.type || (t.type == 0 && w.league != t.league)) continue; if (t.detail >= 1 && w.detail != 1) continue; const uint16_t c = t.detail == 2 ? w.runner_up : w.winner; if (c != 0xffff) value = club_cell(s->clubs[c]), any = true; } cells.push_back(std::move(value)); } if (any) row(out, std::move(cells)); } } void minute_buckets(O& out, const std::vector<AlmanacSeason>& seasons, const std::string& own) { headings(out, {"Ereignis"}); for (int i = 0; i < 18; ++i) std::get<A>(out["columns"].value).push_back(cell(std::to_string(i * 5) + ".")); std::array<std::array<int, 18>, 4> counts{}; for (const auto& s : seasons) for (const auto& m : s.matches) { const int side = s.clubs[m.home].id == own ? 0 : s.clubs[m.away].id == own ? 1 : -1; if (side < 0) continue; for (const auto& e : m.events) { if (e.side != side || e.minute < 1 || e.minute > 90) continue; const size_t b = size_t(std::min(17, (e.minute - 1) / 5)); if (e.kind == AlmanacEventKind::Goal) ++counts[0][b], ++counts[1][b]; if (e.kind == AlmanacEventKind::Miss) ++counts[1][b]; if (e.kind == AlmanacEventKind::YellowCard) ++counts[2][b]; if (e.kind == AlmanacEventKind::RedCard || e.kind == AlmanacEventKind::SecondYellow) ++counts[3][b]; } } const char* names[4] = {"Tore", "Chancen", "Gelb", "Rot"}; for (size_t k = 0; k < 4; ++k) { A cells{cell(names[k])}; for (size_t b = 0; b < 18; ++b) cells.push_back(numeric(counts[k][b])); row(out, std::move(cells)); } } } // namespace cli::Json query_statistics_screen(const ModernState& g, int manager, const cli::Json& request) { const auto reject = [](const char* e) { return J(O{{"ok", false}, {"fictional", false}, {"error", e}}); }; const auto* o = request.object(); if (!o) return reject("invalid_statistics_request"); for (const auto& [key, value] : *o) if (key != "section" && key != "category" && key != "country" && key != "winner_country" && key != "absolute" && key != "curves") return reject("unknown_statistics_filter"); const auto integer = [&](const char* key, int fallback, int maximum) -> int { const J* v = field(request, key); if (!v) return fallback; return v->integer() && *v->integer() >= 0 && *v->integer() <= maximum ? int(*v->integer()) : -1; }; const int section = integer("section", 7, 8), category = integer("category", 0, 5), country = integer("country", 0, 5); if (section < 0 || category < 0 || country < 0 || (category != 0 && category != 1 && category != 5)) return reject("invalid_statistics_filter"); std::string winner_country = country_nation(kCountries[0]); if (const J* w = field(request, "winner_country")) { if (!w->string()) return reject("invalid_statistics_country"); winner_country = *w->string(); } int winner_index = -1; for (int i = 0; i < 5; ++i) if (country_nation(kCountries[i]) == winner_country) winner_index = i; if (winner_index < 0) return reject("invalid_statistics_country"); const J* abs = field(request, "absolute"); const bool absolute = abs && std::holds_alternative<bool>(abs->value) && std::get<bool>(abs->value); A curves; for (int i = 0; i < 6; ++i) curves.push_back(true); if (const J* c = field(request, "curves")) { if (!c->array() || c->array()->size() != 6) return reject("invalid_statistics_curves"); curves = *c->array(); } try { const auto seasons = seasons_of(g); const int team = manager >= 0 && size_t(manager) < g.manager_teams.size() ? g.manager_teams[size_t(manager)] : -1; const bool club = team >= 0 && team < league_clubs(); std::string own_id; if (club) { own_id = team < int(g.world_club_id.size()) ? g.world_club_id[size_t(team)] : std::string{}; if (own_id.empty()) own_id = "team:" + std::to_string(team); } const int own_league = club ? team_league(team) : -1; const int year = g.display_start_year + g.season; std::string manager_name; const size_t at = size_t(std::max(0, manager)) * 0xb0c + 0xa8; for (size_t i = 0; i < 30 && at + i < g.manager_records.size() && g.manager_records[at + i]; ++i) manager_name.push_back(char(g.manager_records[at + i])); A sections, views, countries, eternal; for (const char* s : kSections) sections.push_back(s); for (const char* v : kWorldViews) views.push_back(v); for (const auto& c : kCountries) countries.push_back(O{{"id", country_nation(c)}, {"name", c.name}}); for (int v = 0; v < 5; ++v) eternal.push_back(O{{"value", v}, {"nation", country_nation(kCountries[kEternal[v]])}, {"name", kCountries[kEternal[v]].name}}); eternal.push_back(O{{"value", 5}, {"name", "Absolut"}}); O out{{"ok", true}, {"fictional", false}, {"available", true}, {"section", section}, {"category", category}, {"country", country}, {"winner_country", winner_country}, {"absolute", absolute}, {"curves", curves}, {"title", kSections[section]}, {"season", season_label(year)}, {"previous_season", season_label(year - 1)}, {"year", year}, {"manager", manager_name.empty() ? "—" : almanac_utf8(manager_name)}, {"club", club ? J(own_id) : J(nullptr)}, {"columns", A{}}, {"rows", A{}}, {"countries", std::move(countries)}, {"sections", std::move(sections)}, {"world_views", std::move(views)}, {"series", A{}}, {"eternal_countries", std::move(eternal)}}; // the views without a record of their own yet: title chances, transfers, weekly curves, // season finances; the groups and final round of the national tournaments bool known = true; if (section == 3) { eternal_table(out, seasons, country == 5 ? own_league : kCountries[kEternal[country]].league); } else if (section == 4) { known = world_tournaments(out, g, seasons, country); } else if (section == 6) { if (club) series_and_records(out, g, seasons, own_league); } else if (section == 7) { winners_by_season(out, seasons, category, winner_index); } else if (section == 8) { if (club) minute_buckets(out, seasons, own_id); } else { known = false; } if (!known) out["reason"] = "not_recorded"; out["available"] = known && !std::get<A>(out["rows"].value).empty(); return J(std::move(out)); } catch (const std::exception&) { return reject("statistics_unavailable"); } } // --- 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_league_table(const ModernState& g, int league, int round, const std::vector<LiveGame>& games) { LeagueTable base; if (round > 1) base = compute_league_table(g, league, 0, round - 1, 7, 1); else base.league = league, base.size = int(kLeagueSizes[league]); const int first = league_first_team(league); LeagueTable t = base; for (const LiveGame& game : games) { const int club[2] = {game.home - first, game.away - first}; if (club[0] < 0 || club[0] >= t.size || club[1] < 0 || club[1] >= t.size) continue; const uint8_t goals[2] = {uint8_t(game.home_goals), uint8_t(game.away_goals)}; add_result(t, club, goals, 3, 1); } sort_table(t, 0); std::vector<int> order(size_t(t.size)); for (int i = 0; i < t.size; ++i) order[size_t(i)] = i; std::stable_sort(order.begin(), order.end(), [&](int a, int b) { return t.rank(a) < t.rank(b); }); A rows; for (int i : order) { const int played = t.games(i), won = t.wins[size_t(i)], lost = t.defeats[size_t(i)]; std::string name = size_t(first + i) < g.world_club_name.size() ? g.world_club_name[size_t(first + i)] : std::string{}; if (name.empty()) name = almanac_utf8(g.club_name(first + i)); rows.push_back(O{{"rank", t.rank(i) + 1}, {"previousRank", round > 1 ? J(base.rank(i) + 1) : J(nullptr)}, {"team", O{{"id", ui_team_id(g, first + i)}, {"name", name}}}, {"played", played}, {"won", won}, {"drawn", std::max(0, played - won - lost)}, {"lost", lost}, {"goalsFor", int(t.goals_for[size_t(i)])}, {"goalsAgainst", int(t.goals_against[size_t(i)])}, {"points", int(t.points[size_t(i)])}}); } const Competition c = league_competition(g.almanac.current, league); return O{{"competitionId", c.id}, {"name", c.name}, {"round", round}, {"rows", std::move(rows)}}; } 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 (only played matches are recorded) ((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; }); // the live tables: per league of a ticker match, the table before its matchday plus every // match of that round in this kickoff with its score at the frame's minute (the final // whistle uses the recorded result). A frame carries a league's table when it changed // there (all of them on the first frame). struct LiveLeague { int league = 0, round = 0; std::vector<const AlmanacMatch*> games; std::vector<std::array<int, 2>> teams; // runtime teams of each game std::string last; // the scores the table was last built from }; std::vector<LiveLeague> live_leagues; for (const Ref& r : human) { const AlmanacMatch& m = r.season->matches[r.index]; if (m.type != 0 || m.league >= kLeagueCount || m.round == 0) continue; if (std::any_of(live_leagues.begin(), live_leagues.end(), [&](const LiveLeague& l) { return l.league == m.league; })) continue; LiveLeague l; l.league = m.league, l.round = m.round; const int first = league_first_team(m.league); std::map<std::string, int> team; for (int t = first; t < first + int(kLeagueSizes[m.league]); ++t) team[ui_team_id(g, t)] = t; for (const std::vector<Ref>* list : {&human, &others}) for (const Ref& o : *list) { const AlmanacMatch& x = o.season->matches[o.index]; if (x.type != 0 || x.league != m.league || x.round != m.round) continue; const auto h = team.find(o.season->clubs[x.home].id), a = team.find(o.season->clubs[x.away].id); if (h == team.end() || a == team.end()) continue; l.games.push_back(&x); l.teams.push_back({h->second, a->second}); } live_leagues.push_back(std::move(l)); } const auto live_table = [&](LiveLeague& l, int minute, bool final_whistle) -> J { std::vector<LiveGame> games; std::string key; for (size_t k = 0; k < l.games.size(); ++k) { const AlmanacMatch& x = *l.games[k]; LiveGame game{l.teams[k][0], l.teams[k][1], 0, 0}; if (final_whistle) game.home_goals = x.home_goals, game.away_goals = x.away_goals; else for (const auto& e : x.events) if (e.kind == AlmanacEventKind::Goal && e.minute <= minute) ++(e.side ? game.away_goals : game.home_goals); if (minute > 0) games.push_back(game); key += std::to_string(game.home_goals) + ":" + std::to_string(game.away_goals) + ","; } if (key == l.last) return nullptr; l.last = key; return live_league_table(g, l.league, l.round, games); }; 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])}}}); } const char* phase = mo.phase ? mo.phase : mo.minute <= 45 ? "first_half" : mo.minute <= 90 ? "second_half" : mo.minute <= 120 ? "extra_time" : "shootout"; A standings; const bool final_whistle = mo.phase && (std::string(mo.phase) == "fulltime" || std::string(mo.phase) == "shootout_end"); for (LiveLeague& l : live_leagues) if (J table = live_table(l, mo.minute, final_whistle); !std::holds_alternative<std::nullptr_t>(table.value)) standings.push_back(std::move(table)); frames.push_back(O{{"sequence", int64_t(frames.size())}, {"minute", mo.minute}, {"phase", phase}, {"matches", std::move(scores)}, {"events", events}, {"standings", std::move(standings)}}); } 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"}}; } cli::Json almanac_matches_between(const ModernState& g, uint32_t from_date, uint32_t until_date) { A out; for (const auto& s : seasons_of(g)) for (size_t i = 0; i < s.matches.size(); ++i) if (s.matches[i].date >= from_date && s.matches[i].date <= until_date) out.push_back(almanac_match(g, s, i)); return out; } } // namespace bmh::modern