Compare commits

...
1 Commits
Author SHA1 Message Date
Codex 221478b629 Add sortable editor ratings and payroll comparisons (by Codex)
OBW Editor / editor (linux-x64, ubuntu-24.04) (push) Waiting to run
OBW Editor / editor (macos-arm64, macos-14) (push) Waiting to run
OBW Editor / editor (windows-x64, windows-2022) (push) Waiting to run
2026-10-23 05:26:10 +02:00
26 changed files with 1311 additions and 43 deletions

No files matched your search

+2 -2
View File
@@ -49,9 +49,9 @@ jobs:
if [[ "$RUNNER_OS" == "macOS" ]]; then args+=(-DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0); fi
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DOPENBMH_BUILD_EDITOR=ON -DBMH_DATA= "${args[@]}"
- name: Build editor and synthetic tests
run: cmake --build build --target openbmh_editor editor_core_tests --parallel 2
run: cmake --build build --target openbmh_editor editor_core_tests editor_comparison_tests --parallel 2
- name: Native editor core and MCP tests
run: ctest --test-dir build -C Release -R "^editor_(core_tests|version)$" --output-on-failure --output-junit editor-tests.xml
run: ctest --test-dir build -C Release -R "^editor_(core_tests|comparison_tests|version)$" --output-on-failure --output-junit editor-tests.xml
- name: Linux native GUI smoke
if: runner.os == 'Linux'
run: |
+2 -2
View File
@@ -1,8 +1,8 @@
# OpenBMH
The separate [OpenBMH Editor 0.5.0](docs/EDITOR.md) uses native RmlUI,
The separate [OpenBMH Editor 0.5.1](docs/EDITOR.md) uses native RmlUI,
supports German/English, three themes, image editing and a local MCP server.
Download its own `editor-v0.5.0` release or build with
Download its own `editor-v0.5.1` release or build with
`-DOPENBMH_BUILD_EDITOR=ON`. Edited worlds are independent of the Classic runtime.
A modern and faithful open source rebuild of the *Bundesliga Manager Hattrick* engine.
+29 -1
View File
@@ -142,7 +142,7 @@ button.quiet:hover { background-color: var(--hover); }
aside { width: 220dp; flex-shrink: 0; padding: 28dp 14dp 18dp; display: flex; flex-direction: column; background-color: var(--sidebar); border-right: 1dp var(--divider); }
.eyebrow { font-size: 11dp; font-weight: bold; letter-spacing: 1.5dp; color: var(--muted); text-transform: uppercase; }
#nav-label { padding: 0 14dp 18dp; }
#navigation { display: flex; flex-direction: column; gap: 5dp; }
#navigation { display: flex; flex-direction: column; gap: 5dp; min-height: 0; overflow-y: auto; }
.nav { width: 100%; display: flex; align-items: center; padding: 11dp 13dp; text-align: left; border-color: transparent; background-color: transparent; decorator: none; font-size: 15dp; }
.nav .glyph { width: 20dp; height: 20dp; margin-right: 16dp; flex-shrink: 0; }
.nav.selected { background-color: var(--selected); color: var(--accent); border-color: var(--accent-border); }
@@ -178,6 +178,29 @@ select option:hover, select option:checked { background-color: var(--selected);
.table-header button:hover { color: var(--text); }
.table-header button:first-child { flex: 2; }
.table-scroll { flex: 1; overflow-y: auto; }
.comparison-layout { flex: 1; display: flex; flex-direction: column; min-width: 0; min-height: 0; }
.comparison-bar { display: flex; align-items: center; gap: 12dp; margin-bottom: 14dp; flex-shrink: 0; }
.comparison-bar label, .comparison-bar span { color: var(--muted); font-size: 12dp; }
.comparison-bar span { margin-left: auto; }
#comparison-set { width: 310dp; }
.comparison-panel { min-height: 0; }
.comparison-x { flex: 1; min-height: 0; overflow-x: auto; overflow-y: hidden; display: flex; }
.comparison-table { flex-shrink: 0; display: flex; flex-direction: column; min-height: 0; }
.comparison-head { display: flex; flex-shrink: 0; align-items: stretch; background-color: var(--wash); border-bottom: 1dp var(--border); padding-right: 20dp; }
.comparison-head button { border: 0; border-radius: 0; decorator: none; background-color: transparent; color: var(--muted); font-size: 13dp; padding: 12dp 10dp; white-space: normal; }
.comparison-head button:disabled { opacity: 1; cursor: default; }
.comparison-head small { font-size: 11dp; }
.comparison-direction { width: 7dp; height: 7dp; border-bottom: 1.5dp var(--accent); border-right: 1.5dp var(--accent); transform: rotate(45deg); margin-left: 8dp; margin-bottom: 3dp; }
.comparison-direction.ascending { transform: rotate(225deg); margin-bottom: 0; }
.comparison-body { flex: 1; min-height: 0; overflow-y: auto; }
.comparison-row { display: flex; align-items: center; border: 0; border-bottom: 1dp var(--divider); border-radius: 0; decorator: none; background-color: transparent; padding: 0; min-height: 47dp; text-align: left; }
.comparison-cell { flex-shrink: 0; padding: 14dp 10dp; text-align: right; font-size: 14dp; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.comparison-cell.text { text-align: left; }
.comparison-name-text { display: block; overflow: hidden; text-overflow: ellipsis; }
.comparison-note { flex-shrink: 0; margin-top: 12dp; font-size: 12dp; line-height: 1.6; color: var(--muted); }
.comparison-choices { display: flex; flex-wrap: wrap; max-height: 430dp; overflow-y: auto; margin-top: 16dp; gap: 6dp; }
.comparison-choices label { width: 31%; display: flex; align-items: center; padding: 10dp 4dp; font-size: 14dp; }
.comparison-choices input { flex-shrink: 0; margin-right: 10dp; border-radius: 4dp; }
.record { display: flex; align-items: center; width: 100%; min-height: 49dp; padding: 9dp 16dp; border: 0; border-bottom: 1dp var(--divider); border-radius: 0; background-color: transparent; decorator: none; text-align: left; }
.record:hover { background-color: var(--hover); }
.record.selected { background-color: var(--selected); border-left: 3dp var(--accent); padding-left: 13dp; }
@@ -240,5 +263,10 @@ scrollbarvertical slidertrack { background-color: transparent; }
scrollbarvertical sliderbar { background-color: var(--scrollbar); border-radius: 4dp; min-height: 30dp; }
scrollbarvertical sliderbar:hover { background-color: var(--scrollbar-hover); }
scrollbarvertical sliderarrowdec, scrollbarvertical sliderarrowinc { height: 0; }
scrollbarhorizontal { height: 10dp; margin: 3dp; }
scrollbarhorizontal slidertrack { background-color: transparent; }
scrollbarhorizontal sliderbar { background-color: var(--scrollbar); border-radius: 4dp; min-width: 40dp; }
scrollbarhorizontal sliderbar:hover { background-color: var(--scrollbar-hover); }
scrollbarhorizontal sliderarrowdec, scrollbarhorizontal sliderarrowinc { width: 0; }
button:focus, input:focus, select:focus, textarea:focus { border-color: var(--focus); }
.nav:focus { border-color: var(--focus); }
+31 -7
View File
@@ -1,10 +1,10 @@
# OpenBMH Editor 0.5.0
# OpenBMH Editor 0.5.1
Der eigenständige, native Editor verwendet **RmlUI, SDL2 und OpenGL**. Er bearbeitet Startdatenbanken, keine laufenden Spielstände. Das Spiel und seine Classic-Prüfung bleiben unverändert. Editor 0.5.0 hat eine eigene Versionsreihe und den Release-Tag `editor-v0.5.0`; die Spielversion ist 0.2.0.
Der eigenständige, native Editor verwendet **RmlUI, SDL2 und OpenGL**. Er bearbeitet Startdatenbanken, keine laufenden Spielstände. Das Spiel und seine Classic-Prüfung bleiben unverändert. Editor 0.5.1 hat eine eigene Versionsreihe und den Release-Tag `editor-v0.5.1`; die Spielversion ist 0.2.0.
## Starten und Daten öffnen
Das vollständige Paket `OpenBMHEditor-0.5.0-<plattform>.zip` entpacken und `OpenBMHEditor.exe` (Windows) beziehungsweise `OpenBMHEditor` (Linux/macOS) starten. `assets/editor` muss beim Programm bleiben. Auf macOS kann die unsignierte Anwendung über **Rechtsklick → Öffnen** gestartet werden. Eine Signatur/Notarisierung ist nicht Bestandteil dieser Version. `OpenBMHEditor --version` zeigt die Editorversion ohne Grafikstart.
Das vollständige Paket `OpenBMHEditor-0.5.1-<plattform>.zip` entpacken und `OpenBMHEditor.exe` (Windows) beziehungsweise `OpenBMHEditor` (Linux/macOS) starten. `assets/editor` muss beim Programm bleiben. Auf macOS kann die unsignierte Anwendung über **Rechtsklick → Öffnen** gestartet werden. Eine Signatur/Notarisierung ist nicht Bestandteil dieser Version. `OpenBMHEditor --version` zeigt die Editorversion ohne Grafikstart.
**Öffnen** bietet OBW-Dateien und entpackte Welten an. **BMH / FLTD importieren** liest einen Ordner mit einer unterstützten BMH- oder Football-Limited-Installation durch den bestehenden Konverter. Das Original wird nicht überschrieben. Eine bestehende Classic-OBW wird zunächst überprüft und dann in eine bearbeitbare Editorwelt übernommen.
@@ -25,6 +25,28 @@ Das vollständige Paket `OpenBMHEditor-0.5.0-<plattform>.zip` entpacken und `Ope
Shortcuts: Ctrl/Cmd+O, Ctrl/Cmd+S, Shift+Ctrl/Cmd+S, Ctrl/Cmd+Z und Shift+Ctrl/Cmd+Z. In Textfeldern gilt die lokale Text-Rückgängig-Funktion.
## Stärken und Gehälter vergleichen
**Wertevergleich** in der Seitenleiste (oder die gleichnamige Schaltfläche bei Spielern, Vereinen und Wettbewerben) öffnet eine Übersicht mit drei Ansichten: **Spieler**, **Mannschaften**, **Ligen**. Spieler zeigen ihre einzelnen Spielwerte und das Gehalt je Saison; Mannschaften und Ligen zeigen Durchschnittswerte, Spielergehaltssummen, das Durchschnittsgehalt und die Anzahl bekannter Gehälter. Ein Klick auf eine Zeile öffnet ihren Datensatz zur Bearbeitung.
- Auf einen Spaltenkopf klicken, um auf- oder absteigend zu sortieren. Sortiert wird der gesamte gefilterte Bestand vor der Aufteilung auf Seiten mit bis zu 200 Zeilen. Suche sowie Land-, Liga- und Vereinsfilter grenzen die Ansicht ein. Fehlende Zahlen stehen in beiden Sortierrichtungen hinten.
- **Spalten auswählen** blendet beliebige vorhandene Spielwerte ein. Bei vielen Spalten horizontal scrollen; Tabellenkopf und Werte bewegen sich gemeinsam. Die Wertebereiche stehen im Spaltenkopf, Gruppenwerte sind spielergewichtete Durchschnitte über bekannte Werte. Der gesamte Kader einschließlich Reserve zählt; reine Quellenduplikate mit `x-simulation.squad_role: source-only-duplicate` werden ausgeschlossen und ihre Anzahl angezeigt.
- Verschiedene Attributsysteme bleiben getrennt. Bei einem einzigen System werden dessen Spielwerte automatisch angezeigt. Bei mehreren ein **Attributsystem** wählen, um dessen Spieler und die daraus gebildeten Mannschafts-/Ligawerte zu vergleichen. Das FC-Attribut `strength` heißt in einem System mit `overall` **Körperkraft**; es wird nicht als Classic-Gesamtstärke interpretiert. Es wird keine neue Stärkeskala berechnet.
- **Gehälter gelten je Saison**, in der Währung und kleinsten Einheit aus dem OBW-Manifest. Berücksichtigt werden zum Saisonstart gültige Verträge des Spielers mit seiner aktuellen Mannschaft. Personalverträge, abgelaufene und zukünftige Verträge zählen nicht. Mehrere gleichzeitig gültige Verträge derselben Zuordnung sind unklar und werden nicht addiert. Ohne Vertragsangabe steht **—**, ein ausdrücklich gespeichertes Nullgehalt bleibt **0**.
- Unvollständige Gehaltssummen und Durchschnitte tragen ein **\***. Sie berücksichtigen nur bekannte Spielergehälter; die Spalte **Gehälter bekannt** zeigt die Abdeckung. Auch Spielwertdurchschnitte verwenden nur bekannte Werte (Anzahl per Tooltip). Classic-Grunddaten liefern häufig keine konkreten Verträge: Der Editor erfindet diese Gehälter nicht.
[Native Vorher-/Nachher-Bilder](qa/editor-comparison/README.md) dokumentieren die Ansichten und Spaltenauswahl.
Die Übersicht verändert weder Daten noch Undo-Historie. Änderungen und Rückgängig aktualisieren ihre Werte automatisch. Alle drei Themes und beide Sprachen werden unterstützt.
Über MCP liefert **`editor_compare`** dieselbe schreibgeschützte Übersicht. Beispielargumente:
```json
{"table":"players","sort":"attributes.overall","descending":true,"limit":200}
```
`table` ist `players`, `clubs` oder `leagues`. Weitere Sortierschlüssel sind `name`, `salary` (Spieler), `salary_total`, `salary_average`, `salary_known`, `player_count`, `club_count` sowie `attributes.<feld>`. `attribute_set` grenzt das System ein, `search`, `nation`, `competition`, `team` filtern, `offset`/`limit` blättern. Die Antwort enthält Originalskalen, Stichtag, Währung und Abdeckung. Gehälter bleiben Integer in kleinster Währungseinheit; das Durchschnittsgehalt wird auf diese Einheit gerundet. Das entsprechende Session-Kommando für Command-Scripts heißt `compare`.
## Optionen und MCP
**Optionen** bietet Deutsch/Englisch, Midnight Glass/Silver Glass/Matchday und den integrierten MCP-Server. Die Sprache ändert die Oberfläche; Namen und Quelldaten werden nicht übersetzt. Einstellungen werden im Benutzerprofil gespeichert.
@@ -41,7 +63,7 @@ Der MCP-Server ist standardmäßig aktiviert und bindet ausschließlich `127.0.0
Implementiert ist [MCP Streamable HTTP 2025-11-25](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports), mit Aushandlung von 2025-06-18; JSON-Antworten, ohne optionale SSE-Sitzungen. Neuere MCP-Versionen werden nicht als unterstützt beworben. Der Server prüft Token, Host und gegebenenfalls Origin. Oberfläche und Agent bearbeiten dieselbe Welt, verwenden dieselbe Validierung und dieselbe Undo-Historie. Für konkurrierende Änderungen `expected_revision` aus `editor_info`/`editor_get` mitsenden.
Werkzeuge: `editor_info`, `editor_open`, `editor_new`, `editor_list`, `editor_get`, `editor_apply`, `editor_rules`, `editor_validate`, `editor_history`, `editor_save`, `editor_undo`, `editor_redo`, `editor_roster_move`, `editor_roster_swap`, `editor_roster_order`, `editor_review_resolve`, `editor_image_import`, `editor_image_edit`, `editor_image_preview`, `editor_image_export`. Die eingeblendeten Tools enthalten Parameterschemata und Beschreibungen. Öffnen einer anderen Welt verwirft ungespeicherte Änderungen nur mit `discard: true`.
Werkzeuge: `editor_info`, `editor_open`, `editor_new`, `editor_list`, `editor_compare`, `editor_get`, `editor_apply`, `editor_rules`, `editor_validate`, `editor_history`, `editor_save`, `editor_undo`, `editor_redo`, `editor_roster_move`, `editor_roster_swap`, `editor_roster_order`, `editor_review_resolve`, `editor_image_import`, `editor_image_edit`, `editor_image_preview`, `editor_image_export`. Die eingeblendeten Tools enthalten Parameterschemata und Beschreibungen. Öffnen einer anderen Welt verwirft ungespeicherte Änderungen nur mit `discard: true`.
## Kompilieren
@@ -49,8 +71,8 @@ Voraussetzungen entsprechen dem Hauptprojekt: C++20-Compiler, Git, CMake ≥ 3.2
```sh
cmake -S . -B build-editor -G Ninja -DCMAKE_BUILD_TYPE=Release -DOPENBMH_BUILD_EDITOR=ON
cmake --build build-editor --target openbmh_editor editor_core_tests --parallel 2
ctest --test-dir build-editor -C Release -R '^editor_(core_tests|version)$' --output-on-failure
cmake --build build-editor --target openbmh_editor editor_core_tests editor_comparison_tests --parallel 2
ctest --test-dir build-editor -C Release -R '^editor_(core_tests|comparison_tests|version)$' --output-on-failure
```
macOS ARM zusätzlich bei der Konfiguration: `-DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0`. Unter Windows das Argument nach `-R` ohne einfache Shell-Anführungszeichen verwenden. Der Editor wird beim normalen Spiel-Build standardmäßig nicht mitgebaut.
@@ -71,8 +93,10 @@ Pakete baut `tools/package/make_editor_package.py --build build-editor --out dis
Extract the complete package and run **OpenBMHEditor**. Open an OBW archive or an unpacked world, import a supported BMH/Football Limited installation, or open the synthetic demo. Use the sidebar, searchable/filterable list and property inspector; **Apply** records one shared, undoable transaction. **Save** writes only an **OBW 1.1 editor world**, not a playable Classic mod or a legacy installation.
Use **Comparison** to inspect sortable player, team and league ratings and per-season salaries. Select attribute columns and filter by country, league, club or attribute system. Group ratings are player-weighted means; salary totals and means use known player contracts only and explicitly flag incomplete coverage. Missing values remain unknown. The read-only MCP tool `editor_compare` returns the same data.
The editor retains full squads, original image data, source claims and unknown extensions. Its 24-player view does not remove players. Image import offers normalized crop, arbitrary rotation and mirroring; re-editing uses the preserved source. Classic portraits keep their frozen appearance recipe. Unsupported editing areas are preserved rather than replaced.
In **Options**, switch the interface to **English**, choose one of the three themes, and enable/disable the integrated local MCP server. **Copy connection** provides the authenticated configuration. The server defaults to loopback port 8765; use port 0 for a free port. GUI and MCP share the same world, validation and undo history. It supports MCP Streamable HTTP 2025-11-25/2025-06-18 and optional stdio mode. Use `expected_revision` for concurrent edits.
Build with the three commands above, including `-DOPENBMH_BUILD_EDITOR=ON`. The native application requires OpenGL 3.3 (macOS 4.1) and the platform development dependencies documented in the main README. Editor 0.5.0 is unsigned and does not bundle any real-world dataset or proprietary game assets.
Build with the three commands above, including `-DOPENBMH_BUILD_EDITOR=ON`. The native application requires OpenGL 3.3 (macOS 4.1) and the platform development dependencies documented in the main README. Editor 0.5.1 is unsigned and does not bundle any real-world dataset or proprietary game assets.
+23 -1
View File
@@ -2,7 +2,7 @@
This additive profile is a native editing interchange. It does **not** change
`classic-installation-v1`, its seals, the Classic runtime or save files.
It is implemented by OpenBMH Editor 0.5.0, whose application version is separate
It is implemented by OpenBMH Editor 0.5.x, whose application version is separate
from the OBW format version and the OpenBMH 0.2.0 game version.
## Identification
@@ -61,6 +61,28 @@ Competition `trophy` and optional fallback remain logical asset references;
images are indexed just like crests and portraits. Arbitrary new competitions
can use their own trophy or a package-supplied generic trophy.
### Read-only comparisons (Editor 0.5.1)
The editor's `compare` command / `editor_compare` MCP tool projects ratings and
salaries without writing an additional OBW table. Player attributes retain their
set and range. Club and league attributes are player-weighted means of known
values within one set; mixed sets require a filter. Full rosters include reserves,
except source evidence explicitly marked
`x-simulation.squad_role: "source-only-duplicate"`. League membership uses a club's
explicit league, or an unambiguous league `members` reference as fallback.
`contracts.salary` is per season, in integer `manifest.currency` minor units.
Only contracts active on `manifest.start_date` and matching the player's current
team count; absent bounds are open and explicit date bounds are inclusive.
Multiple matching active contracts are ambiguous, not summed. Missing or invalid
salary remains null, independently of an explicit zero. Club/league payrolls
exclude staff and use known player salaries only. `salary_known`,
`salary_unknown`, `salary_ambiguous`, `salary_complete` and `salary_overflow`
describe coverage; a missing/empty/overflowed sum is null. Means of known salaries
round to the nearest minor unit. Attribute means separately report their sample
sizes in `attribute_counts`. No current date, invented contract or foreign-club
strength-band interpretation is substituted for missing data.
## Sources, conflicts and images
- `x-source/` can contain unchanged or losslessly gzipped normalized source
+51
View File
@@ -0,0 +1,51 @@
# Editor 0.5.1 — ratings and salaries
These are actual 1440×900 SDL2/OpenGL/RmlUI captures on Linux under Xvfb
with software OpenGL. All content is the synthetic `World::demo()` fixture:
52 invented players, two invented clubs, one league and 50 explicitly synthetic
per-season contracts (one unknown salary per club). No real-world data, original
game images, personal paths, settings or credentials are included. This editor
uses starting worlds, not a career save; reproduce the data with `--demo`.
| View | Evidence |
|---|---|
| Before, released Editor 0.5.0 | [Player inspector](before-players-0.5.0.png), without a ratings/payroll overview |
| Players, Midnight Glass / German | [Salary descending](players-midnight-de.png) |
| Teams, Silver Glass / English | [Player-weighted means, payroll and coverage](teams-silver-en.png) |
| Leagues, Matchday / German | [League aggregate](leagues-matchday-de.png) |
| Attribute selection | [Choose columns](columns-midnight-de.png) |
| Horizontal navigation | [Further attributes](players-scroll-midnight-de.png); header and values remain aligned |
The after views use Editor 0.5.1. The before capture uses the released 0.5.0
Linux executable and its own assets. No screenshot is a browser mockup.
Validation:
- `editor_core_tests`, `editor_comparison_tests`, `editor_version` pass locally.
The comparison suite checks 36 outcomes, including actual currency units,
unknown versus zero salaries, date/team selection, conflicting contracts,
staff exclusion, complete reserves, duplicate evidence, player-weighted means,
coverage, empty groups, numeric sorting across more than 200 rows, stable ties,
nulls last in both directions, different rating systems, overflow, read-only
session state, cache refresh after editing/undo and the shared MCP tool.
- `tests/editor_gui_smoke.py` performs real keyboard/mouse operations. It selects
a rating column via its label, sorts ratings and salaries, opens the first row
and edits it. MCP verifies the expected stable player/club/league identifier
changed, then undoes it. The existing inspector/search/JSON/undo/save checks
still pass. The comparison leaves the saved world clean.
- All three themes and both languages were inspected. Header arrows do not rely
on missing font glyphs; horizontal scrolling keeps column alignment.
- The completed private season was checked independently: 18,920 eligible
player rows, 545 teams, 32 leagues; 832 source-only duplicate rows excluded.
Every eligible player has one known current-team salary in that package.
These are dataset estimates, not verified real wages. No private rows or
screenshots are distributed in this public directory.
Build the targets and run the CTest commands in [the editor guide](../../EDITOR.md).
For the native input test, run `python3 tests/editor_gui_smoke.py <OpenBMHEditor>`
inside a graphical session or Xvfb with xdotool. `OpenBMHEditor --demo --page
comparison` opens the overview; the three buttons choose players, teams or
leagues. **Choose columns** selects additional attributes.
Windows/macOS native build and core tests run in the editor CI. The Linux
window checks do not establish human acceptance on those operating systems.
Binary file not shown.

After

Width:  |  Height:  |  Size: 203 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

+17 -1
View File
@@ -1,5 +1,21 @@
<!-- SPDX-License-Identifier: GPL-3.0-only -->
# OpenBMH Editor 0.5.0
# OpenBMH Editor 0.5.1
Adds **Ratings & salaries / Wertevergleich**: sortable player, team and league
overviews, searchable and filterable by country/league/club and attribute system.
Choose the attribute columns and scroll horizontally for additional metrics.
Click a row to open its existing editor. All three themes and both interface
languages are supported.
Player values retain their native scales. Group ratings are player-weighted
means; salaries are per-season amounts from contracts active at the world start
date. Partial wage bills are marked, unknown values stay unknown, explicit zero
salaries remain zero. All reserves are included; source-only duplicate evidence
is excluded. Different rating systems are not combined. The read-only MCP tool
`editor_compare` exposes the same results and pagination. Comparison caches
refresh after edits and undo/redo without changing the world.
## Initial editor 0.5.0
The first standalone editor release uses SDL2, RmlUI and OpenGL on Windows x64,
Linux x64 and macOS ARM64. Its version is independent of OpenBMH 0.2.0.
+8 -2
View File
@@ -1,6 +1,6 @@
# SPDX-License-Identifier: GPL-3.0-only
include(FetchContent)
set(OPENBMH_EDITOR_VERSION "0.5.0")
set(OPENBMH_EDITOR_VERSION "0.5.1")
file(WRITE "${CMAKE_BINARY_DIR}/editor-version.json" "{\"version\": \"${OPENBMH_EDITOR_VERSION}\"}\n")
set(JSON_BuildTests OFF CACHE BOOL "" FORCE)
FetchContent_Declare(editor_json GIT_REPOSITORY https://github.com/nlohmann/json.git
@@ -44,7 +44,7 @@ foreach(component editor_json editor_http editor_images editor_svg editor_xml)
endforeach()
file(APPEND "${CMAKE_BINARY_DIR}/editor-dependencies.json" "}\n")
add_library(bmh_editor_core STATIC archive.cpp world.cpp session.cpp images.cpp options.cpp mcp.cpp)
add_library(bmh_editor_core STATIC archive.cpp world.cpp session.cpp comparison.cpp images.cpp options.cpp mcp.cpp)
target_compile_definitions(bmh_editor_core PUBLIC OPENBMH_EDITOR_VERSION="${OPENBMH_EDITOR_VERSION}")
target_include_directories(bmh_editor_core PUBLIC .. ${editor_http_SOURCE_DIR})
target_link_libraries(bmh_editor_core PUBLIC nlohmann_json::nlohmann_json bmh_content
@@ -85,5 +85,11 @@ if(MSVC)
target_compile_options(editor_core_tests PRIVATE /utf-8)
endif()
add_test(NAME editor_core_tests COMMAND editor_core_tests)
add_executable(editor_comparison_tests ../../tests/editor_comparison_tests.cpp)
target_link_libraries(editor_comparison_tests PRIVATE bmh_editor_core)
if(MSVC)
target_compile_options(editor_comparison_tests PRIVATE /utf-8)
endif()
add_test(NAME editor_comparison_tests COMMAND editor_comparison_tests)
add_test(NAME editor_version COMMAND openbmh_editor --version)
set_tests_properties(editor_version PROPERTIES PASS_REGULAR_EXPRESSION "OpenBMH Editor ${OPENBMH_EDITOR_VERSION}")
+307
View File
@@ -0,0 +1,307 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/comparison.hpp"
#include "editor/world.hpp"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <limits>
namespace bmh::editor {
namespace {
bool date_valid(const std::string &date) {
if (date.size() != 10 || date[4] != '-' || date[7] != '-')
return false;
for (size_t i = 0; i < date.size(); ++i)
if (i != 4 && i != 7 && (date[i] < '0' || date[i] > '9'))
return false;
if (std::stoi(date.substr(0, 4)) < 1583)
return false;
return std::chrono::year_month_day{std::chrono::year(std::stoi(date.substr(0, 4))),
std::chrono::month(unsigned(std::stoi(date.substr(5, 2)))),
std::chrono::day(unsigned(std::stoi(date.substr(8, 2))))}
.ok();
}
bool source_duplicate(const Json &player) {
const auto simulation = player.value("x-simulation", Json::object());
return str(simulation, "squad_role") == "source-only-duplicate";
}
std::optional<int64_t> money(const Json &value) {
if (!value.is_number_integer() ||
(value.is_number_unsigned() && value.get<uint64_t>() > uint64_t(std::numeric_limits<int64_t>::max())))
return {};
const auto number = value.get<int64_t>();
return number >= 0 ? std::optional<int64_t>(number) : std::nullopt;
}
struct Mean {
long double sum = 0;
size_t count = 0;
void add(const Json &value) {
if (value.is_number() && std::isfinite(value.get<double>())) {
sum += value.get<double>();
++count;
}
}
Json value() const { return count ? Json(double(sum / count)) : Json(); }
};
struct Group {
size_t players = 0, known = 0, ambiguous = 0;
int64_t salary = 0;
bool overflow = false;
std::map<std::string, Mean> attributes;
void add(const Json &player) {
++players;
for (auto it = player["attributes"].begin(); it != player["attributes"].end(); ++it)
attributes[it.key()].add(it.value());
ambiguous += player.value("salary_ambiguous", size_t(0));
if (const auto amount = money(player["salary"])) {
++known;
if (salary > std::numeric_limits<int64_t>::max() - *amount)
overflow = true;
else
salary += *amount;
}
}
void write(Json &row, const Json &fields) const {
row["player_count"] = players;
row["salary_known"] = known;
row["salary_unknown"] = players - known;
row["salary_ambiguous"] = ambiguous;
row["salary_overflow"] = overflow;
row["salary_complete"] = players > 0 && known == players && !overflow;
row["salary_total"] = known && !overflow ? Json(salary) : Json();
// Salaries remain integer minor units. Round the mean to the nearest
// minor unit without overflowing the sum or inventing unknown wages.
row["salary_average"] =
known && !overflow
? Json(salary / int64_t(known) + (salary % int64_t(known) >= int64_t((known + 1) / 2)))
: Json();
row["attributes"] = Json::object();
row["attribute_counts"] = Json::object();
for (const auto &field : fields) {
const auto key = str(field, "key");
const auto found = attributes.find(key);
row["attributes"][key] = found == attributes.end() ? Json() : found->second.value();
row["attribute_counts"][key] = found == attributes.end() ? 0 : found->second.count;
}
}
};
} // namespace
Json comparison_data(const World &world, const Json &args) {
const auto table = str(args, "table", "players"), language = str(args, "language", "de");
if (table != "players" && table != "clubs" && table != "leagues")
throw Error("unknown_table");
if (language != "de" && language != "en")
throw Error("invalid_change");
std::map<std::string, const Json *> clubs, leagues;
std::map<std::string, std::set<std::string>> memberships;
for (const auto &league : world.rows("competitions"))
if (str(league, "type") == "league") {
const auto id = str(league, "id");
leagues[id] = &league;
for (const auto &member : league.value("members", Json::array()))
if (member.is_string())
memberships[member.get<std::string>()].insert(id);
}
for (const auto &club : world.rows("clubs"))
clubs[str(club, "id")] = &club;
auto league_for = [&](const std::string &id) {
const auto comp = clubs.contains(id) ? str(*clubs.at(id), "competition") : "";
if (leagues.contains(comp))
return comp;
const auto found = memberships.find(id);
return found != memberships.end() && found->second.size() == 1 ? *found->second.begin()
: std::string();
};
std::map<std::string, size_t> sets;
size_t excluded = 0;
for (const auto &player : world.rows("players")) {
if (source_duplicate(player)) {
++excluded;
continue;
}
++sets[str(player, "attribute_set")];
}
auto selected_set = str(args, "attribute_set");
if (!selected_set.empty() && !sets.contains(selected_set))
throw Error("invalid_attribute_set");
if (selected_set.empty() && sets.size() == 1)
selected_set = sets.begin()->first;
// Equal-looking numbers can have different meanings (FC physical strength
// versus Classic playing strength). Never average or sort mixed systems.
const bool mixed = selected_set.empty() && sets.size() > 1;
std::map<std::string, Json> fields;
if (!mixed) {
for (const auto &rule : world.rows("rules")) {
auto id = str(rule, "attribute_set", str(rule, "id"));
if (str(rule, "type") == "attribute_set" &&
(id == selected_set || id == "rule:" + selected_set)) {
const auto definitions = rule.value("fields", Json::object());
for (auto it = definitions.begin(); it != definitions.end(); ++it)
fields[it.key()] = {{"key", it.key()},
{"min", it.value().value("min", Json())},
{"max", it.value().value("max", Json())}};
}
}
for (const auto &player : world.rows("players"))
if (!source_duplicate(player) && str(player, "attribute_set") == selected_set) {
const auto attributes = player.value("attributes", Json::object());
for (auto it = attributes.begin(); it != attributes.end(); ++it)
if (it.value().is_number() && !fields.contains(it.key()))
fields[it.key()] = {{"key", it.key()}, {"min", nullptr}, {"max", nullptr}};
}
}
Json definitions = Json::array();
for (const auto &[_, field] : fields)
definitions.push_back(field);
Json available_sets = Json::array();
for (const auto &[id, count] : sets)
available_sets.push_back({{"id", id}, {"players", count}});
const auto date = str(world.manifest, "start_date");
std::map<std::pair<std::string, std::string>, std::vector<const Json *>> contracts;
if (date_valid(date))
for (const auto &contract : world.rows("contracts")) {
const auto start = str(contract, "start"), end = str(contract, "end");
// An absent date is an open bound. A malformed bound cannot be
// treated as evidence of an active employment contract.
const auto start_value = contract.value("start", Json()),
end_value = contract.value("end", Json());
if ((!start_value.is_null() && !start_value.is_string()) ||
(!end_value.is_null() && !end_value.is_string()) ||
(!start.empty() && (!date_valid(start) || start > date)) ||
(!end.empty() && (!date_valid(end) || end < date)))
continue;
contracts[{str(contract, "person"), str(contract, "team")}].push_back(&contract);
}
Json players = Json::array();
std::map<std::string, Group> club_groups, league_groups;
for (const auto &player : world.rows("players")) {
if (source_duplicate(player) ||
(!selected_set.empty() && str(player, "attribute_set") != selected_set))
continue;
const auto id = str(player, "id"), team = str(player, "team"), league = league_for(team);
const auto *club = clubs.contains(team) ? clubs.at(team) : nullptr;
Json row{{"id", id},
{"name", world.title(player, language)},
{"team", team},
{"nation", club ? str(*club, "nation") : ""},
{"competition", league},
{"positions", player.value("positions", Json::array())},
{"attribute_set", str(player, "attribute_set")},
{"player_count", 1},
{"attributes", Json::object()},
{"salary", nullptr},
{"salary_ambiguous", 0}};
const auto attributes = player.value("attributes", Json::object());
for (const auto &[key, _] : fields) {
const auto value = attributes.value(key, Json());
row["attributes"][key] = value.is_number() && std::isfinite(value.get<double>()) ? value : Json();
}
if (!team.empty()) {
const auto found = contracts.find({id, team});
if (found != contracts.end()) {
if (found->second.size() == 1) {
const auto salary = money(found->second.front()->value("salary", Json()));
if (salary)
row["salary"] = *salary;
} else
row["salary_ambiguous"] = 1;
}
}
if (club)
club_groups[team].add(row);
if (!league.empty())
league_groups[league].add(row);
players.push_back(std::move(row));
}
Json rows = Json::array();
if (table == "players")
rows = std::move(players);
else if (table == "clubs") {
for (const auto &[id, club] : clubs) {
Json row{{"id", id},
{"name", world.title(*club, language)},
{"nation", str(*club, "nation")},
{"competition", league_for(id)}};
club_groups[id].write(row, definitions);
rows.push_back(std::move(row));
}
} else
for (const auto &[id, league] : leagues) {
Json row{{"id", id},
{"name", world.title(*league, language)},
{"nation", str(*league, "nation")},
{"competition", id},
{"club_count", 0}};
for (const auto &[club_id, _] : clubs)
if (league_for(club_id) == id)
row["club_count"] = row["club_count"].get<size_t>() + 1;
league_groups[id].write(row, definitions);
rows.push_back(std::move(row));
}
const auto simulation = world.manifest.value("x-simulation", Json());
return {{"table", table},
{"items", std::move(rows)},
{"attributes", definitions},
{"attribute_sets", available_sets},
{"attribute_set", selected_set},
{"mixed_attribute_sets", mixed},
{"currency", world.manifest.value("currency", Json())},
{"date", date},
{"excluded_players", excluded},
{"fictional_completion",
simulation.is_object() && simulation.value("fictional_completion", Json()) == true}};
}
Json query_comparison(const Json &data, const Json &args) {
const auto search = folded(str(args, "search")), nation = str(args, "nation"),
league = str(args, "competition"), team = str(args, "team"), sort = str(args, "sort", "name");
const bool descending = args.value("descending", false);
bool valid_sort = sort == "name" || sort == "salary" || sort == "salary_total" ||
sort == "salary_average" || sort == "player_count" || sort == "club_count" ||
sort == "salary_known";
for (const auto &field : data["attributes"])
valid_sort |= sort == "attributes." + str(field, "key");
if (!valid_sort)
throw Error("invalid_comparison_sort");
auto value = [&](const Json &row) {
if (sort == "name")
return Json(folded(str(row, "name")));
if (sort.starts_with("attributes."))
return row["attributes"].value(sort.substr(11), Json());
return row.value(sort, Json());
};
std::vector<const Json *> matches;
for (const auto &row : data["items"]) {
if ((!nation.empty() && str(row, "nation") != nation) ||
(!league.empty() && str(row, "competition") != league) ||
(!team.empty() && str(row, "team", str(row, "id")) != team) ||
(!search.empty() && folded(str(row, "name")).find(search) == std::string::npos &&
folded(str(row, "id")).find(search) == std::string::npos))
continue;
matches.push_back(&row);
}
std::stable_sort(matches.begin(), matches.end(), [&](auto a, auto b) {
const auto av = value(*a), bv = value(*b);
if (av.is_null() != bv.is_null())
return !av.is_null(); // Unknown values are last in both directions.
if (av == bv)
return str(*a, "id") < str(*b, "id");
return descending ? av > bv : av < bv;
});
const auto offset = std::max<int64_t>(0, args.value("offset", int64_t(0)));
const auto limit = std::clamp<int64_t>(args.value("limit", int64_t(200)), 1, 200);
Json result = Json::object();
for (auto it = data.begin(); it != data.end(); ++it)
if (it.key() != "items")
result[it.key()] = it.value();
result["items"] = Json::array();
for (size_t i = size_t(std::min<int64_t>(offset, int64_t(matches.size())));
i < matches.size() && int64_t(result["items"].size()) < limit; ++i)
result["items"].push_back(*matches[i]);
result["total"] = matches.size();
result["offset"] = offset;
result["limit"] = limit;
return result;
}
} // namespace bmh::editor
+11
View File
@@ -0,0 +1,11 @@
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "editor/types.hpp"
namespace bmh::editor {
class World;
// Read-only projections. Session caches the unfiltered data at its revision;
// searching, sorting and paging always operate on the complete projection.
Json comparison_data(const World &, const Json &args);
Json query_comparison(const Json &data, const Json &args);
} // namespace bmh::editor
+26
View File
@@ -52,6 +52,7 @@ const std::map<std::string, std::string> commands{{"editor_info", "info"},
{"editor_open", "open"},
{"editor_new", "new"},
{"editor_list", "list"},
{"editor_compare", "compare"},
{"editor_get", "get"},
{"editor_apply", "apply"},
{"editor_validate", "validate"},
@@ -142,6 +143,31 @@ Json McpServer::tools() {
{"descending", field("boolean")},
{"unresolved_only", field("boolean")}},
{"table"}, true);
add("editor_compare",
"Read-only ratings and salary comparison for players, clubs or leagues. Attributes are native player "
"values "
"or player-weighted group means, within one attribute_set. Mixed systems need a filter for ratings. "
"Salary is integer world-currency minor units per season, from contracts active at "
"manifest.start_date "
"and matching the player's current team. Unknown/ambiguous salaries stay null. Group totals/means "
"cover "
"known player salaries only; salary_known/unknown/complete report coverage. All reserves are "
"included; "
"source-only duplicate evidence is excluded. Sorts the complete result before paging (max 200); "
"nulls last in both directions. Does not edit the world.",
{{"table", {{"type", "string"}, {"enum", {"players", "clubs", "leagues"}}}},
{"language", {{"type", "string"}, {"enum", {"de", "en"}}}},
{"attribute_set", field("string", "Optional set ID; automatic when only one system is present.")},
{"search", field("string")},
{"nation", id},
{"competition", id},
{"team", id},
{"sort", field("string", "name, player_count, club_count, salary, salary_total, salary_average, "
"salary_known, attributes.<key>")},
{"descending", field("boolean")},
{"offset", field("integer")},
{"limit", field("integer")}},
{}, true);
add("editor_get", "Read a complete row, including preserved extensions and sources.",
{{"table", table}, {"id", id}}, {"table", "id"}, true);
add("editor_apply",
+78 -17
View File
@@ -89,6 +89,49 @@ std::string tr(const std::string &language, const std::string &key) {
using Pair = std::pair<std::string, std::string>;
static const std::map<std::string, Pair> words{
{"data_areas", {"Datenbereiche", "World data"}},
{"comparison", {"Wertevergleich", "Comparison"}},
{"comparison_title", {"Stärken & Gehälter", "Ratings & salaries"}},
{"subtitle_comparison",
{"Spieler, Mannschaften und Ligen im Vergleich", "Compare players, teams and leagues"}},
{"teams", {"Mannschaften", "Teams"}},
{"leagues", {"Ligen", "Leagues"}},
{"physical_strength", {"Körperkraft", "Physical strength"}},
{"comparison_columns", {"Spalten auswählen", "Choose columns"}},
{"comparison_columns_hint",
{"Spielwerte einblenden. Weitere Spalten sind horizontal erreichbar.",
"Select attributes. Scroll horizontally to see further columns."}},
{"comparison_all_sets", {"Alle Spieler · Systeme getrennt", "All players · separate systems"}},
{"comparison_all_players", {"alle Spieler", "all players"}},
{"all_columns", {"Alle auswählen", "Select all"}},
{"no_columns", {"Keine auswählen", "Select none"}},
{"comparison_player_values", {"Originalskala des Datensatzes", "Dataset's original scale"}},
{"comparison_mean_values", {"Spielwerte: Durchschnitt je Spieler", "Attributes: mean per player"}},
{"comparison_known_values", {"bekannte Werte", "known values"}},
{"salary_season", {"Gehalt / Saison", "Salary / season"}},
{"salary_total", {"Gehaltssumme / Saison", "Total salary / season"}},
{"salary_average", {"Ø Gehalt / Spieler", "Mean salary / player"}},
{"salary_coverage", {"Gehälter bekannt", "Salaries known"}},
{"salary_missing", {"Gehälter unbekannt", "salaries unknown"}},
{"salary_ambiguous", {"mehrere aktive Verträge", "multiple active contracts"}},
{"comparison_salary_note",
{"Gehälter je Saison in Weltwährung. * Nur bekannte Gehälter; Summe/Ø unvollständig. Stichtag",
"Salaries per season in world currency. * Known salaries only; total/mean incomplete. As of"}},
{"comparison_scope_note",
{"Gesamter Kader inklusive Reserven. Fehlende Spielwerte bleiben leer; Ø nur aus bekannten Werten.",
"Full squads including reserves. Missing attributes stay blank; means use known values only."}},
{"comparison_mixed_note",
{"Für Stärken ein Attributsystem auswählen. Unterschiedliche Systeme werden nicht vermischt.",
"Choose an attribute set to compare ratings. Different systems are not mixed."}},
{"comparison_excluded", {"Quellenduplikate nicht eingerechnet", "source duplicates excluded"}},
{"comparison_fictional",
{"Der Datensatz enthält als fiktiv oder geschätzt gekennzeichnete Ergänzungen.",
"The dataset includes additions marked as fictional or estimated."}},
{"comparison_sort_hint", {"Spaltenkopf anklicken zum Sortieren", "Click a column heading to sort"}},
{"invalid_attribute_set",
{"Dieses Attributsystem ist nicht im Datenbestand.",
"This attribute set is not present in the dataset."}},
{"invalid_comparison_sort",
{"Diese Vergleichsspalte ist nicht verfügbar.", "This comparison column is unavailable."}},
{"invalid_manifest",
{"Die Kennzeichnung der Editorwelt ist ungültig.", "The editor world identification is invalid."}},
{"facilities", {"Ausstattung", "Facilities"}},
@@ -109,9 +152,11 @@ std::string tr(const std::string &language, const std::string &key) {
{"x", {"Links", "Left"}},
{"y", {"Oben", "Top"}},
{"open_folder", {"Entpackte Welt öffnen", "Open unpacked world"}},
{"subtitle_overview", {"Ein Arbeitsplatz für deine Fußballwelt", "A workspace for your football world"}},
{"subtitle_overview",
{"Ein Arbeitsplatz für deine Fußballwelt", "A workspace for your football world"}},
{"subtitle_nations", {"Länder, Verbände und Simulation", "Countries, associations and simulation"}},
{"subtitle_competitions", {"Ligen, Zuordnungen und Pokalbilder", "Leagues, membership and trophy images"}},
{"subtitle_competitions",
{"Ligen, Zuordnungen und Pokalbilder", "Leagues, membership and trophy images"}},
{"subtitle_clubs", {"Stammdaten, Farben und Spielstätten", "Details, colours and home grounds"}},
{"subtitle_players",
{"Spielerdaten und quellengerechte Spielwerte", "Player details and source-specific attributes"}},
@@ -120,7 +165,8 @@ std::string tr(const std::string &language, const std::string &key) {
{"subtitle_assets", {"Wappen, Porträts und Pokale", "Crests, portraits and trophies"}},
{"subtitle_review", {"Quellen vergleichen", "Compare sources"}},
{"subtitle_roster", {"Vollständige Kader ohne Datenverlust", "Complete squads without losing data"}},
{"subtitle_changes", {"Gemeinsame Historie von Oberfläche und MCP", "One history for the interface and MCP"}},
{"subtitle_changes",
{"Gemeinsame Historie von Oberfläche und MCP", "One history for the interface and MCP"}},
{"preservation_note",
{"Quellen, Bilder und Erweiterungen bleiben erhalten. Bearbeitungen "
"ändern keine Originalinstallation.",
@@ -136,12 +182,14 @@ std::string tr(const std::string &language, const std::string &key) {
"Drag a rectangle on the image or enter crop values. Without cropping, "
"the original resolution is retained."}},
{"video_failed",
{"Die Grafikausgabe benötigt OpenGL 3.3 (macOS: 4.1).", "The interface requires OpenGL 3.3 (macOS: 4.1)."}},
{"Die Grafikausgabe benötigt OpenGL 3.3 (macOS: 4.1).",
"The interface requires OpenGL 3.3 (macOS: 4.1)."}},
{"ui_assets_missing",
{"Editor-Oberfläche fehlt. Bitte das vollständige Paket entpacken.",
"Editor interface files are missing. Please extract the complete "
"package."}},
{"dialog_failed", {"Der Dateidialog konnte nicht geöffnet werden.", "The file dialog could not be opened."}},
{"dialog_failed",
{"Der Dateidialog konnte nicht geöffnet werden.", "The file dialog could not be opened."}},
{"invalid_attributes", {"Ungültige Spielwerte.", "Invalid player attributes."}},
{"app", {"OpenBMH Editor", "OpenBMH Editor"}},
{"editor_tagline", {"OBW-Dateneditor", "OBW world editor"}},
@@ -223,6 +271,7 @@ std::string tr(const std::string &language, const std::string &key) {
{"condition", {"Kondition", "Condition"}},
{"form", {"Form", "Form"}},
{"overall", {"Gesamtstärke", "Overall"}},
{"tacticalawareness", {"Taktisches Verständnis", "Tactical awareness"}},
{"potential", {"Potenzial", "Potential"}},
{"acceleration", {"Antritt", "Acceleration"}},
{"sprintspeed", {"Sprinttempo", "Sprint speed"}},
@@ -313,7 +362,8 @@ std::string tr(const std::string &language, const std::string &key) {
{"resolve", {"Auswahl übernehmen", "Use selected value"}},
{"resolved", {"Erledigt", "Resolved"}},
{"unresolved", {"Offen", "Open"}},
{"review_hint", {"Quellen vergleichen und eine Angabe auswählen.", "Compare sources and choose a value."}},
{"review_hint",
{"Quellen vergleichen und eine Angabe auswählen.", "Compare sources and choose a value."}},
{"roster_hint",
{"Verein wählen, Spieler verschieben oder zwei Spieler tauschen.",
"Choose a club, move a player or swap two players."}},
@@ -326,7 +376,8 @@ std::string tr(const std::string &language, const std::string &key) {
{"errors", {"Fehler", "Errors"}},
{"no_changes", {"Noch keine Änderungen", "No changes yet"}},
{"dirty_prompt", {"Änderungen speichern?", "Save changes?"}},
{"dirty_detail", {"Diese Welt enthält ungespeicherte Änderungen.", "This world has unsaved changes."}},
{"dirty_detail",
{"Diese Welt enthält ungespeicherte Änderungen.", "This world has unsaved changes."}},
{"delete_prompt", {"Datensatz wirklich löschen?", "Delete this record?"}},
{"new_name", {"Name des neuen Datensatzes", "Name of the new record"}},
{"new_title", {"Neue Fußballwelt", "New football world"}},
@@ -342,22 +393,27 @@ std::string tr(const std::string &language, const std::string &key) {
{"Speichern fehlgeschlagen. Die bisherige Datei bleibt erhalten.",
"Saving failed. The previous file is retained."}},
{"invalid_archive",
{"Das Archiv ist beschädigt oder wird nicht unterstützt.", "The archive is damaged or unsupported."}},
{"unsupported_archive", {"Dieses Archivformat wird nicht unterstützt.", "This archive format is unsupported."}},
{"Das Archiv ist beschädigt oder wird nicht unterstützt.",
"The archive is damaged or unsupported."}},
{"unsupported_archive",
{"Dieses Archivformat wird nicht unterstützt.", "This archive format is unsupported."}},
{"archive_limit",
{"Das Datenpaket überschreitet die unterstützten Grenzen.", "The data package exceeds the supported limits."}},
{"Das Datenpaket überschreitet die unterstützten Grenzen.",
"The data package exceeds the supported limits."}},
{"unsafe_path", {"Unzulässiger Dateipfad.", "Invalid file path."}},
{"size_limit", {"Die Datei ist zu groß.", "The file is too large."}},
{"missing_manifest", {"Keine OBW-Welt gefunden.", "No OBW world found."}},
{"not_world", {"Bitte eine OBW-Startdatenbank öffnen.", "Please open an OBW starting world."}},
{"unsupported_version", {"Diese Formatversion wird nicht unterstützt.", "This format version is unsupported."}},
{"unsupported_version",
{"Diese Formatversion wird nicht unterstützt.", "This format version is unsupported."}},
{"invalid_json", {"Die JSON-Daten sind ungültig.", "The JSON data is invalid."}},
{"invalid_table", {"Eine Datentabelle ist ungültig.", "A data table is invalid."}},
{"unknown_table", {"Unbekannter Datenbereich.", "Unknown data table."}},
{"missing_asset", {"Das Bild fehlt im Datenpaket.", "The image is missing from the package."}},
{"unsafe_asset", {"Das Bild kann nicht übernommen werden.", "The image cannot be imported."}},
{"invalid_image", {"Das Bild konnte nicht gelesen werden.", "The image could not be decoded."}},
{"image_dimensions", {"Das Bild hat nicht unterstützte Abmessungen.", "The image dimensions are unsupported."}},
{"image_dimensions",
{"Das Bild hat nicht unterstützte Abmessungen.", "The image dimensions are unsupported."}},
{"invalid_transform",
{"Der Bildzuschnitt oder Drehwinkel ist ungültig.", "The image crop or rotation is invalid."}},
{"external_svg_resource",
@@ -367,7 +423,8 @@ std::string tr(const std::string &language, const std::string &key) {
"SVG."}},
{"image_encode_failed",
{"Das bearbeitete Bild konnte nicht erstellt werden.", "The edited image could not be created."}},
{"obw_only", {"Es kann ausschließlich als .obw gespeichert werden.", "Only .obw output is supported."}},
{"obw_only",
{"Es kann ausschließlich als .obw gespeichert werden.", "Only .obw output is supported."}},
{"preserve_source",
{"Bitte unter einem neuen Namen speichern. Der Classic-Import bleibt "
"erhalten.",
@@ -381,8 +438,10 @@ std::string tr(const std::string &language, const std::string &key) {
{"Eine Kennung fehlt oder ist mehrfach vorhanden.", "An identifier is missing or duplicated."}},
{"missing_reference", {"Ein verknüpfter Datensatz fehlt.", "A referenced record is missing."}},
{"attribute_range",
{"Ein Spielwert liegt außerhalb seines Wertebereichs.", "An attribute is outside its declared range."}},
{"unknown_attribute_set", {"Das Attributsystem ist nicht definiert.", "The attribute set is not defined."}},
{"Ein Spielwert liegt außerhalb seines Wertebereichs.",
"An attribute is outside its declared range."}},
{"unknown_attribute_set",
{"Das Attributsystem ist nicht definiert.", "The attribute set is not defined."}},
{"missing_name", {"Ein Name fehlt.", "A name is missing."}},
{"missing_birthday", {"Das Geburtsdatum ist unbekannt.", "The date of birth is unknown."}},
{"review_open", {"Eine Quellenfrage ist noch offen.", "A source decision is still open."}},
@@ -392,7 +451,8 @@ std::string tr(const std::string &language, const std::string &key) {
"The record is still referenced. Please update its links first."}},
{"record_missing", {"Der Datensatz wurde nicht gefunden.", "The record was not found."}},
{"immutable_id",
{"Kennungen können nicht nachträglich geändert werden.", "Identifiers cannot be changed after creation."}},
{"Kennungen können nicht nachträglich geändert werden.",
"Identifiers cannot be changed after creation."}},
{"stale_revision",
{"Die Daten wurden inzwischen geändert. Bitte die Ansicht "
"aktualisieren.",
@@ -404,7 +464,8 @@ std::string tr(const std::string &language, const std::string &key) {
{"invalid_settings", {"Die Optionen sind ungültig.", "The options are invalid."}},
{"output_parent_missing", {"Der Zielordner existiert nicht.", "The output folder does not exist."}},
{"destination_exists", {"Die Zieldatei existiert bereits.", "The destination file already exists."}},
{"duplicate_entry", {"Das Archiv enthält doppelte Dateinamen.", "The archive contains duplicate entry names."}},
{"duplicate_entry",
{"Das Archiv enthält doppelte Dateinamen.", "The archive contains duplicate entry names."}},
{"server_failed",
{"MCP konnte nicht gestartet werden. Bitte den Port prüfen.",
"MCP could not be started. Please check the port."}},
+15
View File
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/session.hpp"
#include "content/digest.hpp"
#include "editor/comparison.hpp"
#include "editor/images.hpp"
#include <algorithm>
#include <limits>
@@ -435,6 +436,20 @@ Json Session::execute(const std::string &command, const Json &args) {
auto &w = world();
if (command == "list")
return w.query(args);
if (command == "compare") {
const Json key{{"table", str(args, "table", "players")},
{"attribute_set", str(args, "attribute_set")},
{"language", str(args, "language", "de")}};
if (comparison_revision_ != revision_ || comparison_key_ != key.dump()) {
auto data = comparison_data(w, key);
comparison_cache_ = std::move(data);
comparison_key_ = key.dump();
comparison_revision_ = revision_;
}
auto result = query_comparison(comparison_cache_, args);
result["revision"] = revision_;
return result;
}
if (command == "get") {
auto name = str(args, "table"), id = str(args, "id");
const auto *found = name == "manifest" ? &w.manifest : w.find(name, id);
+3
View File
@@ -34,6 +34,9 @@ class Session {
fs::path saved_path_;
fs::file_time_type saved_time_{};
uint64_t saved_size_ = 0;
Json comparison_cache_;
std::string comparison_key_;
std::optional<uint64_t> comparison_revision_;
World &world();
bool dirty() const;
Json info() const;
+380 -7
View File
@@ -14,6 +14,7 @@
#include <deque>
#include <functional>
#include <future>
#include <iomanip>
#include <nfd.hpp>
#include <sstream>
@@ -142,6 +143,10 @@ class EditorUi final : public Rml::EventListener {
std::map<std::string, Json> lookup_;
std::string page_ = "overview", selected_id_, search_, nation_, league_, team_, sort_ = "name", remembered_;
bool descending_ = false;
std::string comparison_table_ = "players", comparison_set_, comparison_sort_ = "name";
bool comparison_descending_ = false;
Json comparison_;
std::map<std::string, std::vector<std::string>> comparison_columns_;
int offset_ = 0;
size_t total_ = 0;
struct Field {
@@ -206,6 +211,7 @@ class EditorUi final : public Rml::EventListener {
{"clubs", "M4 3h16v10c0 5-8 9-8 9S4 18 4 13zM8 8h8M8 12h8"},
{"players", "M16 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0M4 22v-3c0-8 16-8 16 0v3"},
{"roster", "M3 3h18v18H3zM9 3v18M3 9h18M3 15h18"},
{"comparison", "M4 20h17M7 17v-5M12 17V7M17 17V3"},
{"stadiums", "M3 8c0-7 18-7 18 0v8c0 7-18 7-18 0zM3 8c0 7 18 7 18 0M8 "
"13v7M16 13v7"},
{"staff", "M5 22V3h13l-4 5 4 5H5"},
@@ -259,7 +265,7 @@ class EditorUi final : public Rml::EventListener {
lookup_[str(row, "id")] = row;
}
std::string choices(const std::string &name, const std::string &chosen, const std::string &empty = "",
const std::string &nation = "") const {
const std::string &nation = "", const std::string &competition = "") const {
std::string result =
"<option value=\"\"" + std::string(chosen.empty() ? " selected" : "") + ">" + escaped(empty) + "</option>";
std::vector<std::pair<std::string, std::string>> values;
@@ -271,6 +277,9 @@ class EditorUi final : public Rml::EventListener {
: id.starts_with("stadium:");
if (!matches || (!nation.empty() && str(row, "nation") != nation && id != chosen))
continue;
if (name == "clubs" && !competition.empty() && str(row, "competition") != competition &&
id != chosen)
continue;
values.emplace_back(id, title(row));
}
std::stable_sort(values.begin(), values.end(),
@@ -394,14 +403,14 @@ class EditorUi final : public Rml::EventListener {
button("save", t("save"), "primary", info_.value("loaded", false) ? "" : "disabled") +
button("options", t("options"), "quiet"));
std::string nav;
for (const std::string name : {"overview", "nations", "competitions", "clubs", "players", "roster", "stadiums",
"staff", "assets", "review", "changes"})
for (const std::string name : {"overview", "nations", "competitions", "clubs", "players", "roster",
"comparison", "stadiums", "staff", "assets", "review", "changes"})
nav += "<button class=\"nav " + std::string(name == page_ ? "selected" : "") +
"\" data-action=\"navigate\" data-value=\"" + name + "\">" + icon(name) + "<span>" +
escaped(t(name)) + "</span></button>";
html("navigation", nav);
label("page-kicker", "OpenBMH / " + t(page_));
label("page-title", t(page_));
label("page-title", t(page_ == "comparison" ? "comparison_title" : page_));
label("page-subtitle", page_ == "roster" ? t("roster_hint")
: page_ == "review" ? t("review_hint")
: t("subtitle_" + page_));
@@ -590,6 +599,10 @@ class EditorUi final : public Rml::EventListener {
html("page-actions", page_ == "review"
? button("validate", t("validate"))
: button("duplicate", t("duplicate")) + button("add", t("add"), "primary"));
if (table() == "players" || table() == "clubs" || table() == "competitions")
html("page-actions", button("compare-open", t("comparison")) +
button("duplicate", t("duplicate")) +
button("add", t("add"), "primary"));
std::string toolbar = "<input id=\"search\" type=\"text\" value=\"" + escaped(search_) + "\" placeholder=\"" +
escaped(t("search")) + "\"/>";
if (table() == "clubs" || table() == "players" || table() == "competitions")
@@ -679,6 +692,302 @@ class EditorUi final : public Rml::EventListener {
button("next", t("next"), "quiet", size_t(offset_) + listed_.size() < total_ ? "" : "disabled") +
"</div>");
}
std::string comparison_number(const Json &value, bool salary = false) const {
if (!value.is_number())
return "—";
std::string result;
if (salary) {
const auto currency = comparison_.value("currency", Json());
if (!currency.is_object() || str(currency, "code").empty() ||
!currency.value("minor_units", Json()).is_number_integer())
return t("unknown");
const auto decimals = currency["minor_units"].get<int>();
if (decimals < 0 || decimals > 9)
return t("unknown");
auto digits = std::to_string(value.get<int64_t>());
while (digits.size() <= size_t(decimals))
digits.insert(digits.begin(), '0');
const auto fraction = decimals ? digits.substr(digits.size() - decimals) : "";
digits.resize(digits.size() - decimals);
for (int i = int(digits.size()) - 3; i > 0; i -= 3)
digits.insert(size_t(i), options_.language == "de" ? "." : ",");
result = digits + (decimals ? (options_.language == "de" ? "," : ".") + fraction : "");
} else if (value.is_number_integer())
result = value.dump();
else {
std::ostringstream stream;
stream.imbue(std::locale::classic());
stream << std::fixed << std::setprecision(1) << value.get<double>();
result = stream.str();
if (options_.language == "de")
std::replace(result.begin(), result.end(), '.', ',');
}
return result;
}
std::string comparison_attribute(const std::string &key) const {
// In FC-derived systems strength means physical power, not overall.
if (key == "strength")
for (const auto &field : comparison_["attributes"])
if (str(field, "key") == "overall")
return t("physical_strength");
return t(key);
}
std::vector<std::string> &comparison_columns() {
auto key = str(comparison_, "attribute_set");
if (!comparison_columns_.contains(key)) {
auto &columns = comparison_columns_[key];
for (const std::string preferred :
{"overall", "potential", "strength", "technique", "form", "condition", "bonus"}) {
for (const auto &field : comparison_["attributes"])
if (str(field, "key") == preferred && columns.size() < 5)
columns.push_back(preferred);
}
if (columns.empty())
for (const auto &field : comparison_["attributes"])
if (columns.size() < 5)
columns.push_back(str(field, "key"));
}
return comparison_columns_.at(key);
}
void comparison_choose_columns() {
std::string body = "<p>" + escaped(t("comparison_columns_hint")) + "</p><div class=\"button-row\">" +
button("compare-all-columns", t("all_columns")) +
button("compare-no-columns", t("no_columns")) +
"</div><div class=\"comparison-choices\">";
const auto &chosen = comparison_columns();
size_t index = 0;
for (const auto &field : comparison_["attributes"]) {
const auto key = str(field, "key");
const bool checked = std::find(chosen.begin(), chosen.end(), key) != chosen.end();
const auto id = "comparison-column-" + std::to_string(index++);
body += "<label for=\"" + id + "\"><input type=\"checkbox\" id=\"" + id + "\"" +
(checked ? " checked" : "") + "/><span>" + escaped(comparison_attribute(key)) + "</span></label>";
}
modal(
t("comparison_columns"), body + "</div>", t("apply"),
[this] {
auto &chosen = comparison_columns();
chosen.clear();
size_t index = 0;
for (const auto &field : comparison_["attributes"]) {
if (el("comparison-column-" + std::to_string(index++))->HasAttribute("checked"))
chosen.push_back(str(field, "key"));
}
close_modal();
needs_refresh_ = true;
},
true, true);
}
void comparison() {
if (!info_.value("loaded", false)) {
overview();
return;
}
Json args{{"table", comparison_table_},
{"language", options_.language},
{"attribute_set", comparison_set_},
{"search", search_},
{"nation", nation_},
{"competition", league_},
{"team", team_},
{"sort", comparison_sort_},
{"descending", comparison_descending_},
{"offset", offset_},
{"limit", 200}};
try {
comparison_ = session_.execute("compare", args);
} catch (const Error &error) {
if (error.code != "invalid_attribute_set" && error.code != "invalid_comparison_sort")
throw;
// A world replaced through MCP can have different attribute sets.
comparison_set_.clear();
comparison_sort_ = "name";
args["attribute_set"] = "";
args["sort"] = "name";
comparison_ = session_.execute("compare", args);
}
listed_ = comparison_["items"];
total_ = comparison_["total"].get<size_t>();
if (listed_.empty() && offset_ > 0) {
offset_ = total_ ? int((total_ - 1) / 200 * 200) : 0;
args["offset"] = offset_;
comparison_ = session_.execute("compare", args);
listed_ = comparison_["items"];
}
const bool players = comparison_table_ == "players", leagues = comparison_table_ == "leagues";
std::string tabs;
for (const std::string scope : {"players", "clubs", "leagues"})
tabs += button("compare-scope", t(scope == "clubs" ? "teams" : scope),
scope == comparison_table_ ? "primary" : "", "data-value=\"" + scope + "\"");
html("page-actions", tabs);
std::string toolbar = "<input id=\"search\" type=\"text\" value=\"" + escaped(search_) +
"\" placeholder=\"" + escaped(t("search")) +
"\"/><select id=\"filter-nation\">" +
choices("nations", nation_, t("all_nations")) + "</select>";
if (!leagues)
toolbar += "<select id=\"filter-league\">" +
choices("competitions", league_, t("all_leagues"), nation_) + "</select>";
if (players)
toolbar += "<select id=\"filter-team\">" +
choices("clubs", team_, t("all_clubs"), nation_, league_) + "</select>";
html("toolbar", toolbar);
const auto automatic_profile =
comparison_["attribute_sets"].size() == 1
? str(comparison_, "attribute_set") + " · " + t("comparison_all_players")
: t("comparison_all_sets");
std::string profiles = "<option value=\"\"" +
std::string(comparison_set_.empty() ? " selected" : "") + ">" +
escaped(automatic_profile) + "</option>";
for (const auto &profile : comparison_["attribute_sets"]) {
const auto id = str(profile, "id");
if (!id.empty())
profiles += "<option value=\"" + escaped(id) + "\"" +
(id == comparison_set_ ? " selected" : "") + ">" + escaped(id) + " · " +
profile["players"].dump() + "</option>";
}
std::string body =
"<div class=\"comparison-layout\"><div class=\"comparison-bar\"><label>" +
escaped(t("attribute_set")) + "</label><select id=\"comparison-set\">" + profiles + "</select>" +
button("compare-columns", t("comparison_columns"), "",
comparison_["attributes"].empty() ? "disabled" : "") +
"<span>" + escaped(t(players ? "comparison_player_values" : "comparison_mean_values")) +
"</span></div>";
int width = 0;
std::string header;
struct Column {
std::string key, label;
int width;
};
std::vector<Column> columns{{"name",
t(players ? "players"
: leagues ? "leagues"
: "teams"),
230},
{"context",
t(players ? "team"
: leagues ? "nation"
: "competition"),
players ? 200 : 180}};
if (players)
columns.push_back({"positions", t("positions"), 95});
else {
if (leagues)
columns.push_back({"club_count", t("clubs"), 80});
columns.push_back({"player_count", t("players"), 85});
}
const auto &chosen = comparison_columns();
std::string primary_attribute;
for (const auto &field : comparison_["attributes"]) {
const auto key = str(field, "key");
if (std::find(chosen.begin(), chosen.end(), key) != chosen.end() &&
(primary_attribute.empty() || key == "strength" || key == "overall"))
primary_attribute = key;
if (primary_attribute == "overall")
break;
}
if (!primary_attribute.empty())
columns.push_back(
{"attributes." + primary_attribute, comparison_attribute(primary_attribute), 120});
const auto currency = str(comparison_.value("currency", Json()), "code", "?");
columns.push_back({players ? "salary" : "salary_total",
t(players ? "salary_season" : "salary_total") + " · " + currency, 165});
if (!players) {
columns.push_back({"salary_average", t("salary_average") + " · " + currency, 165});
columns.push_back({"salary_known", t("salary_coverage"), 105});
}
for (const auto &field : comparison_["attributes"]) {
const auto key = str(field, "key");
if (key != primary_attribute && std::find(chosen.begin(), chosen.end(), key) != chosen.end())
columns.push_back({"attributes." + key, comparison_attribute(key), 135});
}
for (const auto &column : columns) {
width += column.width;
const bool sortable = column.key != "context" && column.key != "positions";
std::string caption = escaped(column.label);
if (column.key == comparison_sort_)
caption += "<span class=\"comparison-direction" +
std::string(comparison_descending_ ? "" : " ascending") + "\"></span>";
if (column.key.starts_with("attributes."))
for (const auto &field : comparison_["attributes"])
if (str(field, "key") == column.key.substr(11) && field["min"].is_number() &&
field["max"].is_number())
caption += "<small>" + field["min"].dump() + "–" + field["max"].dump() + "</small>";
header += "<button class=\"comparison-cell" +
std::string(column.key == "name" || column.key == "context" ? " text" : "") +
"\" style=\"width:" + std::to_string(column.width) + "dp\"" +
(sortable ? " data-action=\"compare-sort\" data-value=\"" + escaped(column.key) + "\""
: " disabled") +
">" + caption + "</button>";
}
std::string rows;
for (const auto &row : listed_) {
rows += "<button class=\"comparison-row\" data-action=\"compare-edit\" data-value=\"" +
escaped(str(row, "id")) + "\">";
for (const auto &column : columns) {
std::string cell, hint;
if (column.key == "name") {
cell = "<span class=\"comparison-name-text\">" + escaped(str(row, "name")) + "</span>";
hint = str(row, "name") + " · " + str(row, "id");
} else if (column.key == "context")
cell = escaped(ref(row, players ? "team" : leagues ? "nation" : "competition"));
else if (column.key == "positions") {
for (const auto &position : row["positions"])
if (position.is_string())
cell += (cell.empty() ? "" : " / ") + escaped(t(position.get<std::string>()));
} else if (column.key.starts_with("attributes.")) {
const auto key = column.key.substr(11);
cell = comparison_number(row["attributes"].value(key, Json()));
if (!players)
hint =
row["attribute_counts"].value(key, size_t(0)) == row["player_count"].get<size_t>()
? t("comparison_mean_values")
: std::to_string(row["attribute_counts"].value(key, size_t(0))) + "/" +
row["player_count"].dump() + " · " + t("comparison_known_values");
} else if (column.key == "salary_known") {
cell = row["salary_known"].dump() + " / " + row["player_count"].dump();
hint = row["salary_unknown"].dump() + " · " + t("salary_missing") + "; " +
row["salary_ambiguous"].dump() + " · " + t("salary_ambiguous");
} else {
const bool salary = column.key.starts_with("salary");
cell = comparison_number(row.value(column.key, Json()), salary);
if (salary && !players && row.value(column.key, Json()).is_number() &&
!row.value("salary_complete", false))
cell += " *";
if (salary && players && row.value("salary_ambiguous", 0))
hint = t("salary_ambiguous");
}
rows += "<span class=\"comparison-cell" +
std::string(column.key == "name" || column.key == "context" ? " text" : "") +
"\" style=\"width:" + std::to_string(column.width) + "dp\" title=\"" + escaped(hint) +
"\">" + cell + "</span>";
}
rows += "</button>";
}
if (rows.empty())
rows = "<div class=\"empty\">" + escaped(t("empty")) + "</div>";
body += "<div class=\"list-panel comparison-panel\"><div class=\"comparison-x\" "
"id=\"comparison-x\"><div class=\"comparison-table\" style=\"width:" +
std::to_string(width + 20) + "dp\"><div class=\"comparison-head\">" + header +
"</div><div class=\"comparison-body\" id=\"table-scroll\">" + rows +
"</div></div></div></div>";
body += "<div class=\"comparison-note\">" + escaped(t("comparison_salary_note")) + " · " +
escaped(str(comparison_, "date")) + "<br/>" + escaped(t("comparison_scope_note"));
if (comparison_.value("mixed_attribute_sets", false))
body += "<br/>" + escaped(t("comparison_mixed_note"));
if (comparison_.value("excluded_players", size_t(0)))
body += " · " + comparison_["excluded_players"].dump() + " " + escaped(t("comparison_excluded"));
if (comparison_.value("fictional_completion", false))
body += "<br/>" + escaped(t("comparison_fictional"));
html("page-content", body + "</div></div>");
html("pagination", "<span>" + std::to_string(total_) + " " + escaped(t("records")) + " · " +
escaped(t("comparison_sort_hint")) + "</span><div class=\"button-row\">" +
button("previous", t("previous"), "quiet", offset_ > 0 ? "" : "disabled") +
"<span>" + std::to_string(offset_ + (total_ ? 1 : 0)) + "–" +
std::to_string(offset_ + listed_.size()) + "</span>" +
button("next", t("next"), "quiet",
size_t(offset_) + listed_.size() < total_ ? "" : "disabled") +
"</div>");
}
void changes() {
html("toolbar", "");
html("pagination", "");
@@ -698,6 +1007,8 @@ class EditorUi final : public Rml::EventListener {
html("page-content", body + "</div>");
}
void refresh() {
const float comparison_scroll =
doc_->GetElementById("comparison-x") ? el("comparison-x")->GetScrollLeft() : 0;
const auto *focus = context_->GetFocusElement();
const bool search_focused = focus && focus->GetId() == "search";
int selection_start = 0, selection_end = 0;
@@ -716,8 +1027,14 @@ class EditorUi final : public Rml::EventListener {
overview();
else if (page_ == "changes")
changes();
else if (page_ == "comparison")
comparison();
else
records();
if (page_ == "comparison" && doc_->GetElementById("comparison-x")) {
context_->Update();
el("comparison-x")->SetScrollLeft(comparison_scroll);
}
if (search_focused && doc_->GetElementById("search")) {
auto *input = dynamic_cast<Rml::ElementFormControlInput *>(el("search"));
input->Focus();
@@ -983,9 +1300,59 @@ class EditorUi final : public Rml::EventListener {
selected_id_.clear();
offset_ = 0;
search_.clear();
if (arg == "comparison") {
nation_.clear();
league_.clear();
team_.clear();
}
needs_refresh_ = true;
});
else if (action == "select")
else if (action == "compare-open" || action == "compare-scope")
leave_fields([this, action, arg] {
comparison_table_ =
action == "compare-open" ? (table() == "competitions" ? "leagues" : table()) : arg;
page_ = "comparison";
fields_.clear();
selected_id_.clear();
search_.clear();
nation_.clear();
league_.clear();
team_.clear();
offset_ = 0;
comparison_sort_ = "name";
comparison_descending_ = false;
needs_refresh_ = true;
});
else if (action == "compare-sort") {
comparison_descending_ = arg == comparison_sort_ ? !comparison_descending_ : true;
comparison_sort_ = arg;
offset_ = 0;
needs_refresh_ = true;
} else if (action == "compare-columns")
comparison_choose_columns();
else if (action == "compare-all-columns" || action == "compare-no-columns") {
for (size_t i = 0; i < comparison_["attributes"].size(); ++i) {
auto *checkbox = el("comparison-column-" + std::to_string(i));
if (action == "compare-all-columns")
checkbox->SetAttribute("checked", "");
else
checkbox->RemoveAttribute("checked");
}
} else if (action == "compare-set") {
if (value("comparison-set") != comparison_set_) {
comparison_set_ = value("comparison-set");
comparison_sort_ = "name";
offset_ = 0;
needs_refresh_ = true;
}
} else if (action == "compare-edit") {
page_ = comparison_table_ == "leagues" ? "competitions" : comparison_table_;
selected_id_ = arg;
sort_ = "name";
offset_ = 0;
search_.clear();
needs_refresh_ = true;
} else if (action == "select")
leave_fields([this, arg] {
selected_id_ = arg;
needs_refresh_ = true;
@@ -1061,9 +1428,11 @@ class EditorUi final : public Rml::EventListener {
} else if (action == "sort") {
descending_ = arg == sort_ ? !descending_ : false;
sort_ = arg;
offset_ = 0;
needs_refresh_ = true;
} else if (action == "next" || action == "previous") {
offset_ = std::max(0, offset_ + (action == "next" ? 1 : -1) * (roster24_ ? 24 : 200));
offset_ = std::max(0, offset_ + (action == "next" ? 1 : -1) *
(page_ != "comparison" && roster24_ ? 24 : 200));
needs_refresh_ = true;
} else if (action == "filters") {
const auto next_nation = doc_->GetElementById("filter-nation") ? value("filter-nation") : "";
@@ -1075,6 +1444,7 @@ class EditorUi final : public Rml::EventListener {
if (next_nation == nation_ && next_league == league_ && next_team == team_ && next_search == search_)
return;
auto old_nation = nation_;
auto old_league = league_;
nation_ = next_nation;
league_ = next_league;
team_ = next_team;
@@ -1082,7 +1452,8 @@ class EditorUi final : public Rml::EventListener {
if (old_nation != nation_) {
league_.clear();
team_.clear();
}
} else if (old_league != league_)
team_.clear();
selected_id_.clear();
offset_ = 0;
needs_refresh_ = true;
@@ -1270,6 +1641,8 @@ class EditorUi final : public Rml::EventListener {
auto id = target->GetId();
if (id.starts_with("filter-") || id == "search")
pending_.emplace_back("filters", "");
else if (id == "comparison-set")
pending_.emplace_back("compare-set", "");
else if (id == "image-aspect")
pending_.emplace_back("aspect", "");
else if (id.starts_with("image-") && id != "edit-preview")
+11
View File
@@ -532,6 +532,17 @@ World World::demo() {
{"attribute_set", "demo@1"},
{"attributes",
{{"strength", 68 + (n % 15)}, {"technique", 65 + n % 20}, {"condition", 90}, {"form", 70}}}});
// Synthetic per-season salaries make the comparison demo useful.
// The last player deliberately has no known contract.
if (n != 25)
w.rows("contracts")
.push_back({{"id", "contract:demo-" + std::to_string(i * 26 + n)},
{"name", "Demo contract"},
{"person", "player:demo-" + std::to_string(i * 26 + n)},
{"team", id},
{"start", "2026-07-01"},
{"end", "2027-06-30"},
{"salary", (40000 + 5000 * n + 10000 * i) * 100}});
}
}
w.rows("staff").push_back({{"id", "staff:referee-demo"},
+258
View File
@@ -0,0 +1,258 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "editor/comparison.hpp"
#include "editor/mcp.hpp"
#include "editor/session.hpp"
#include <cmath>
#include <iostream>
#include <limits>
using namespace bmh::editor;
namespace {
int checks = 0;
void check(bool value, const char *message) {
++checks;
if (!value)
throw std::runtime_error(message);
}
template <class Fn> void rejects(const char *code, Fn fn) {
try {
fn();
} catch (const Error &error) {
check(error.code == code, "unexpected rejection");
return;
}
throw std::runtime_error(std::string("accepted: ") + code);
}
Json find(const Json &items, const std::string &id) {
for (const auto &row : items)
if (str(row, "id") == id)
return row;
throw std::runtime_error("missing fixture row " + id);
}
World fixture() {
auto world = World::blank("Synthetic comparison");
world.rows("nations").push_back({{"id", "nation:de"}, {"name", "Testland"}});
world.rows("competitions") = Json::array({{{"id", "comp:first"},
{"name", {{"de", "Testliga"}, {"en", "Test league"}}},
{"nation", "nation:de"},
{"type", "league"},
{"members", {"club:north", "club:south"}}},
{{"id", "comp:empty"},
{"name", "Empty league"},
{"nation", "nation:de"},
{"type", "league"},
{"members", {"club:empty"}}},
{{"id", "comp:cup"},
{"name", "Not a league"},
{"nation", "nation:de"},
{"type", "cup"},
{"members", {"club:north"}}}});
for (const std::string id : {"north", "south", "empty"})
world.rows("clubs").push_back(
{{"id", "club:" + id}, {"name", id}, {"type", "club"}, {"nation", "nation:de"}});
// No club.competition: membership-only imported worlds must work too.
world.rows("rules").push_back(
{{"id", "rule:bmh-classic@1"},
{"type", "attribute_set"},
{"fields", {{"strength", {{"min", 0}, {"max", 99}}}, {"form", {{"min", 0}, {"max", 127}}}}}});
const Json ratings{90, 70, 50, nullptr, 90, 99};
const std::vector<std::string> ids{"a", "b", "c", "d", "free", "duplicate"};
for (size_t i = 0; i < ids.size(); ++i) {
const auto team = i < 2 || i == 5 ? Json("club:north") : i < 4 ? Json("club:south") : Json();
world.rows("players").push_back(
{{"id", "player:" + ids[i]},
{"name", ids[i]},
{"team", team},
{"born", "2000-01-01"},
{"positions", {"mid"}},
{"attribute_set", "bmh-classic@1"},
{"attributes", {{"strength", ratings[i]}, {"form", i ? Json(100) : Json()}}}});
}
world.rows("players")[1]["x-simulation"]["squad_role"] = "source-reserve";
world.rows("players")[5]["x-simulation"]["squad_role"] = "source-only-duplicate";
auto contract = [&](std::string id, std::string person, std::string team, int64_t salary,
std::string start = "2026-07-01", std::string end = "2027-06-30") {
world.rows("contracts")
.push_back({{"id", "contract:" + id},
{"name", id},
{"person", "player:" + person},
{"team", "club:" + team},
{"salary", salary},
{"start", start},
{"end", end}});
};
contract("a", "a", "north", 9000);
contract("b", "b", "north", 10000);
contract("c", "c", "south", 50000);
contract("c-conflict", "c", "south", 60000);
contract("d", "d", "south", 0); // Explicit zero is known, not missing.
contract("duplicate", "duplicate", "north", 99999999);
contract("a-expired", "a", "north", 1000000, "2025-07-01", "2026-06-30");
contract("a-future", "a", "north", 2000000, "2026-07-02", "2027-06-30");
contract("a-old-team", "a", "south", 3000000);
world.rows("staff").push_back({{"id", "staff:test"}, {"name", "Staff"}});
world.rows("contracts")
.push_back({{"id", "contract:staff"},
{"name", "Staff contract"},
{"person", "staff:test"},
{"team", "club:north"},
{"salary", 9999999}});
return world;
}
Json compare(const World &world, Json args = Json::object()) {
return query_comparison(comparison_data(world, args), args);
}
} // namespace
int main() {
const auto root = fs::temp_directory_path() / new_id("comparison-tests-");
fs::create_directory(root);
struct Cleanup {
fs::path root;
~Cleanup() {
std::error_code ec;
fs::remove_all(root, ec);
}
} cleanup{root};
try {
auto world = fixture();
const auto original_players = world.rows("players"), original_contracts = world.rows("contracts");
auto players = compare(world, {{"sort", "salary"}, {"descending", true}});
check(players["total"] == 5 && players["excluded_players"] == 1,
"all real rows, reserve included, source duplicate excluded");
check(players["items"][0]["id"] == "player:b" && players["items"][1]["salary"] == 9000,
"numeric salary sort and active current-team contracts");
check(players["items"][2]["salary"] == 0 && players["items"][3]["salary"].is_null(),
"zero before missing salary descending");
check(find(players["items"], "player:c")["salary_ambiguous"] == 1,
"conflicting active contracts stay unknown");
check(players["currency"]["minor_units"] == 2, "integer currency units retained");
players = compare(world, {{"sort", "salary"}});
check(players["items"][0]["id"] == "player:d" && players["items"][4]["salary"].is_null(),
"missing salary last ascending too");
auto rating = compare(
world, {{"sort", "attributes.strength"}, {"descending", true}, {"offset", 1}, {"limit", 1}});
check(rating["items"][0]["id"] == "player:free" && rating["total"] == 5,
"stable tie by ID and full-result sort before paging");
check(compare(world, {{"team", "club:north"}})["total"] == 2,
"team filter excludes source duplicate");
check(compare(world, {{"nation", "nation:de"}, {"competition", "comp:first"}})["total"] == 4,
"league and nation follow membership fallback");
auto teams =
compare(world, {{"table", "clubs"}, {"sort", "attributes.strength"}, {"descending", true}});
auto north = find(teams["items"], "club:north"), south = find(teams["items"], "club:south");
check(north["attributes"]["strength"] == 80 && north["salary_total"] == 19000,
"club means and player-only payroll");
check(north["salary_average"] == 9500 && north["salary_complete"] == true,
"mean wage and coverage complete");
check(south["attributes"]["strength"] == 50 && south["attribute_counts"]["strength"] == 1,
"unknown attributes excluded from mean denominator");
check(south["salary_total"] == 0 && south["salary_known"] == 1 && south["salary_unknown"] == 1 &&
south["salary_complete"] == false,
"partial payroll distinguished from complete zero");
check(find(teams["items"], "club:empty")["salary_total"].is_null(),
"empty team is not a zero-payroll team");
auto leagues = compare(world, {{"table", "leagues"}, {"language", "en"}});
auto league = find(leagues["items"], "comp:first");
check(leagues["total"] == 2 && league["club_count"] == 2 && league["player_count"] == 4,
"cups excluded; exact unique league population");
check(league["attributes"]["strength"] == 70,
"league strength is player-weighted, not a mean of club means");
check(league["salary_total"] == 19000 && league["salary_average"] == 6333 &&
league["salary_known"] == 3,
"league payroll uses known contracts once and integer rounded mean");
check(league["name"] == "Test league", "localized names");
check(world.rows("players") == original_players && world.rows("contracts") == original_contracts,
"comparison never changes source records");
auto classic = world;
classic.rows("contracts") = Json::array();
classic.manifest["currency"] = {{"code", "GBP"}, {"minor_units", 0}};
check(compare(classic)["items"][0]["salary"].is_null() &&
compare(classic)["currency"]["code"] == "GBP",
"Classic without contracts remains unknown in its actual currency");
world.rows("rules").push_back(
{{"id", "rule:fc@1"},
{"type", "attribute_set"},
{"attribute_set", "fc@1"},
{"fields", {{"overall", {{"min", 0}, {"max", 99}}}, {"strength", {{"min", 0}, {"max", 99}}}}}});
auto &modern = world.rows("players")[1];
modern["attribute_set"] = "fc@1";
modern["attributes"] = {{"overall", 85}, {"strength", 35}};
check(compare(world)["mixed_attribute_sets"] == true && compare(world)["attributes"].empty(),
"different strength systems are never implicitly combined");
rejects("invalid_comparison_sort", [&] { compare(world, {{"sort", "attributes.strength"}}); });
auto fc = compare(world, {{"table", "clubs"}, {"attribute_set", "fc@1"}});
check(find(fc["items"], "club:north")["attributes"]["overall"] == 85 &&
find(fc["items"], "club:north")["player_count"] == 1,
"attribute system filter also defines aggregation population");
rejects("invalid_attribute_set", [&] { compare(world, {{"attribute_set", "unknown@1"}}); });
rejects("unknown_table", [&] { compare(world, {{"table", "staff"}}); });
auto many = fixture();
many.rows("players") = Json::array();
many.rows("contracts") = Json::array();
for (int i = 0; i < 231; ++i)
many.rows("players").push_back({{"id", "player:" + std::to_string(i)},
{"name", std::to_string(i)},
{"attribute_set", "synthetic@1"},
{"attributes", {{"rating", i}}}});
const auto second_page =
compare(many, {{"sort", "attributes.rating"}, {"descending", true}, {"offset", 200}});
check(second_page["total"] == 231 && second_page["items"].size() == 31 &&
second_page["items"][0]["attributes"]["rating"] == 30,
"sorting spans all pages, no 200-row truncation");
auto overflow = fixture();
overflow.rows("contracts")[0]["salary"] = std::numeric_limits<int64_t>::max();
const auto extreme = find(compare(overflow, {{"table", "clubs"}})["items"], "club:north");
check(extreme["salary_overflow"] == true && extreme["salary_total"].is_null(),
"payroll overflow never wraps into a plausible negative value");
auto invalid = fixture();
invalid.rows("contracts")[0]["start"] = 20260701;
check(find(compare(invalid)["items"], "player:a")["salary"].is_null(),
"malformed contract dates are not silently treated as open bounds");
invalid.rows("contracts")[1]["salary"] = -1;
check(find(compare(invalid)["items"], "player:b")["salary"].is_null(),
"invalid salary is unknown, not a negative payroll credit");
invalid.manifest["start_date"] = nullptr;
check(find(compare(invalid)["items"], "player:d")["salary"].is_null(),
"unknown world date does not substitute the wall clock");
invalid.manifest["x-simulation"] = nullptr;
check(compare(invalid)["fictional_completion"] == false,
"unrecognized optional extension metadata does not break comparisons");
auto saved = fixture();
saved.save(root / "fixture.obw");
Session session;
session.execute("open", {{"path", utf8(root / "fixture.obw")}});
const auto info = session.execute("info");
const auto projection = session.execute("compare", {{"table", "clubs"}});
check(info == session.execute("info") && info["dirty"] == false,
"session comparison is read-only including revision and undo state");
session.execute("apply", {{"changes", Json::array({{{"table", "players"},
{"id", "player:a"},
{"set", {{"/attributes/strength", 80}}}}})}});
check(find(session.execute("compare", {{"table", "clubs"}})["items"],
"club:north")["attributes"]["strength"] == 75,
"cached comparison refreshes after an edit");
session.execute("undo");
check(session.execute("compare", {{"table", "clubs"}})["items"] == projection["items"],
"cached comparison refreshes after undo");
McpServer server(session);
const auto reply =
server.dispatch({{"jsonrpc", "2.0"},
{"id", 1},
{"method", "tools/call"},
{"params",
{{"name", "editor_compare"},
{"arguments", {{"table", "leagues"}, {"sort", "salary_total"}}}}}});
check(!reply["result"].value("isError", false) && reply["result"]["structuredContent"]["total"] == 2,
"MCP uses the same comparison projection");
bool read_only = false;
for (const auto &tool : McpServer::tools())
if (tool["name"] == "editor_compare")
read_only = tool["annotations"]["readOnlyHint"] == true;
check(read_only, "MCP comparison advertises read-only semantics");
std::cout << checks << " editor comparison checks passed\n";
return 0;
} catch (const std::exception &error) {
std::cerr << error.what() << '\n';
return 1;
}
}
+39 -1
View File
@@ -89,7 +89,45 @@ def main():
tool('editor_save', {'path': str(root / 'world.obw')})
assert (root / 'world.obw').is_file()
assert tool('editor_info')['dirty'] is False
print('Native RmlUI edit, JSON fields, search focus, shared undo/redo and OBW save passed.')
# Exercise the native comparison, not just its MCP projection:
# sort, open the first displayed row, edit its first property,
# and observe which stable record actually changed via MCP.
def compare_open():
click(100, 460); time.sleep(.25)
def first_property(table, identifier, expected, first_name=False):
click(330, 402); time.sleep(.2)
click(1150, 443); x('key', 'ctrl+a'); x('type', '--clearmodifiers', expected)
click(1300, 741)
for _ in range(40):
record = tool('editor_get', {'table': table, 'id': identifier})['record']
if record['name']['first' if first_name else 'default'] == expected:
break
time.sleep(.05)
else:
raise AssertionError('Comparison opened the wrong row: ' + identifier)
tool('editor_undo'); time.sleep(.3)
compare_open()
click(730, 288) # Attribute chooser: hide all, select Strength via its label.
click(495, 405)
click(900, 461)
click(1080, 575)
click(835, 345) # Sort the remaining rating column descending.
first_property('players', 'player:demo-14', 'Rating Descending', True)
compare_open()
click(978, 345) # Salary descending: highest known demo wage.
first_property('players', 'player:demo-50', 'Salary Descending', True)
compare_open()
click(978, 345) # Ascending; missing salary must remain last.
first_property('players', 'player:demo-0', 'Salary Ascending', True)
compare_open()
click(1274, 153) # Teams.
click(946, 345) # Total salary descending.
first_property('clubs', 'club:south', 'Payroll Descending')
compare_open()
click(1378, 153) # Leagues; its row opens the competition editor.
first_property('competitions', 'comp:demo', 'League Comparison')
assert tool('editor_info')['dirty'] is False
print('Native RmlUI edit, search, undo/save and sorted player/team/league comparison passed.')
except Exception:
log.flush()
print((root / 'app.log').read_text())
+2 -2
View File
@@ -116,8 +116,8 @@ def main():
(stage / 'dependencies.cmake').write_text('\n'.join(cache) + '\n')
(stage / 'SOURCE_MANIFEST.json').write_text(json.dumps(manifest, indent=2) + '\n')
(stage / 'BUILD_SOURCE.txt').write_text('cmake -S project -B build -C dependencies.cmake -G Ninja -DCMAKE_BUILD_TYPE=Release\n'
'cmake --build build --target openbmh_editor editor_core_tests\n'
'ctest --test-dir build -R "^editor_(core_tests|version)$" --output-on-failure\n'
'cmake --build build --target openbmh_editor editor_core_tests editor_comparison_tests\n'
'ctest --test-dir build -R "^editor_(core_tests|comparison_tests|version)$" --output-on-failure\n'
'Native compiler, CMake and OS development libraries: see project/docs/EDITOR.md.\n')
zip_tree(stage, args.out / (source_name + '.zip'))
print(args.out / (source_name + '.zip'))
+18
View File
@@ -45,6 +45,24 @@ SKIP_DIRECTORIES = {".git", "__pycache__", ".cache", "_deps", "node_modules"}
# The latter are reviewed against docs/qa/editor-poc/README.md; no game material.
# Keep prior reviewed hashes if an asset is intentionally revised in history.
PROJECT_ARTWORK = {
"docs/qa/editor-comparison/before-players-0.5.0.png": {
"e061cf1fcbafffc2950037f2f4bf24f28c00fe835988b56b198d88bce33b97e2",
},
"docs/qa/editor-comparison/players-midnight-de.png": {
"ab1debb1e282d5462eab1a570137477884b2c773a900ec45a74783d50693367d",
},
"docs/qa/editor-comparison/teams-silver-en.png": {
"ad8e8274f21465686b8c499ad44344ea4705cbec520560b12f8d7dde878204ea",
},
"docs/qa/editor-comparison/leagues-matchday-de.png": {
"f24cd278b30ce3ccecc7320ae105ea5d0394e759c8045a76e75851259a487ada",
},
"docs/qa/editor-comparison/columns-midnight-de.png": {
"74d825609b862c7dc60dc5182a32c010df73177b10d849079b02a2b4dc2d1620",
},
"docs/qa/editor-comparison/players-scroll-midnight-de.png": {
"8e23a0fe6ea31ca6050fd5f157016948e0bad2f83093dcc3c53a3ba855c3bb40",
},
"docs/qa/editor-poc/clubs-midnight-de.png": {
"2921aa67a870633c96f46328a82bc3022e5489b38d551c5314f13c7e59446070",
"aa53e9cdd9ac8f6bf18b514862ac704ff9003bd1b62466cad2ebc329b09703dc",