Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe307dea41 | ||
|
|
245e213cca | ||
|
|
f21247a244 | ||
|
|
59be8b0b21 | ||
|
|
814583e482 | ||
|
|
e306c2c4a2 | ||
|
|
06e846416a | ||
|
|
678fce47f6 | ||
|
|
a7aa1d3713 | ||
|
|
500354cc39 | ||
|
|
856d38cc0c | ||
|
|
d9d05f83b4 | ||
|
|
c1121da116 |
No files matched your search
@@ -66,6 +66,12 @@ jobs:
|
||||
run: cmake --build build --config Release --parallel 2
|
||||
- name: Run synthetic tests and report data tests as skipped
|
||||
run: ctest --test-dir build -C Release --output-on-failure --output-junit test-results.xml
|
||||
- name: Windows Server launcher with WARP software graphics
|
||||
if: runner.os == 'Windows'
|
||||
env:
|
||||
SDL_VIDEODRIVER: windows
|
||||
OPENBMH_RML_DRIVER: warp
|
||||
run: build/launcher_gui_smoke.exe
|
||||
- name: Package products and licenses
|
||||
run: python3 tools/package/make_package.py --build build --out dist --platform ${{ matrix.platform }}
|
||||
- name: Package corresponding source and pinned dependencies
|
||||
|
||||
@@ -47,9 +47,19 @@ jobs:
|
||||
run: |
|
||||
args=()
|
||||
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[@]}"
|
||||
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DOPENBMH_BUILD_EDITOR=ON -DBMH_DATA= "${args[@]}"
|
||||
- name: Check portable Windows WebP instructions
|
||||
if: runner.os == 'Windows'
|
||||
shell: python
|
||||
run: |
|
||||
import json, pathlib, re
|
||||
commands = json.loads(pathlib.Path('build/compile_commands.json').read_text())
|
||||
simd = [c for c in commands if 'libwebp' in c['file'] and re.search(r'_sse(?:2|41)\.c$', c['file'])]
|
||||
assert simd, 'No WebP runtime-dispatched SIMD sources found'
|
||||
assert all(not re.search(r'/arch:AVX', c['command'], re.I) for c in simd), 'WebP SSE paths must run without AVX'
|
||||
print('WebP SSE paths retain the Windows x64 baseline and runtime CPU detection')
|
||||
- name: Build editor and synthetic tests
|
||||
run: cmake --build build --target openbmh_editor editor_core_tests editor_comparison_tests editor_regulations_tests --parallel 2
|
||||
run: cmake --build build --target openbmh_editor launcher_gui_smoke editor_core_tests editor_comparison_tests editor_regulations_tests --parallel 2
|
||||
- name: Native editor core and MCP tests
|
||||
run: ctest --test-dir build -C Release -R "^editor_(core_tests|comparison_tests|regulations_tests|version)$" --output-on-failure --output-junit editor-tests.xml
|
||||
- name: Linux native GUI smoke
|
||||
@@ -57,6 +67,10 @@ jobs:
|
||||
run: |
|
||||
xvfb-run -a -s '-screen 0 1600x1000x24' python3 tests/editor_gui_smoke.py build/OpenBMHEditor
|
||||
xvfb-run -a -s '-screen 0 1600x1000x24' build/OpenBMHEditor --demo --page players --settings build/test-options.json --screenshot build/editor.png --quit-after-ms 1800
|
||||
xvfb-run -a -s '-screen 0 1600x1000x24' python3 tests/editor_startup_smoke.py build/OpenBMHEditor --launcher build/launcher_gui_smoke
|
||||
- name: Windows Server native GUI and WARP fallback
|
||||
if: runner.os == 'Windows'
|
||||
run: python3 tests/editor_startup_smoke.py build/OpenBMHEditor.exe --launcher build/launcher_gui_smoke.exe
|
||||
- name: Package editor
|
||||
shell: bash
|
||||
run: |
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-only
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(OpenBMH VERSION 0.2.0 LANGUAGES CXX C)
|
||||
project(OpenBMH VERSION 0.2.1 LANGUAGES CXX C)
|
||||
if(APPLE)
|
||||
enable_language(OBJC OBJCXX)
|
||||
set(CMAKE_OBJCXX_STANDARD 20)
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# OpenBMH
|
||||
|
||||
The separate [OpenBMH Editor 0.5.2](docs/EDITOR.md) uses native RmlUI,
|
||||
The separate [OpenBMH Editor 0.5.4](docs/EDITOR.md) uses native RmlUI,
|
||||
supports German/English, three themes, image editing and a local MCP server.
|
||||
Download its own `editor-v0.5.2` release or build with
|
||||
Download its own `editor-v0.5.4` 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.
|
||||
@@ -17,7 +17,7 @@ This is an independent community project, with no affiliation with or endorsemen
|
||||
|
||||
Check the [releases page](https://github.com/Weyoune/openbmh/releases) for available packages and their platform notes. A Windows package uses the name `OpenBMH-<version>-windows-x64.zip`. Availability and native validation are stated for each release; source build instructions do not establish platform support on their own.
|
||||
|
||||
These instructions describe **0.2.0**, released separately from the editor. See the [0.2 release notes](docs/release/0.2/RELEASE_NOTES.md).
|
||||
These instructions describe **0.2.1**, released separately from the editor. See the [0.2 release notes](docs/release/0.2/RELEASE_NOTES.md).
|
||||
|
||||
1. Extract OpenBMH into a writable directory.
|
||||
2. Start `OpenBMH.exe` on Windows, or `OpenBMH` on Linux/macOS. Its RmlUI launcher initially has an empty **Name | Art** list. The night-stadium design uses a small version label in the lower-right corner.
|
||||
@@ -36,7 +36,7 @@ For direct startup or the console:
|
||||
|
||||
Both frontends use native content and saves. Use **Add** to migrate older files rather than passing an original executable or `.FBM` to the running game. The starting year changes the Classic year display; original weekday and scheduling rules are preserved. Modern worlds are reserved for a later version.
|
||||
|
||||
The launcher uses SDL2, RmlUI and OpenGL 3.3 (macOS: OpenGL 4.1); keep its `assets` directory next to the executable. Folder selection uses the operating system's dialog. See the [0.2 migration contract](docs/formats/obw/runtime-0.2.md) for compatibility and validation limits. Platform builds and automated tests are separate from human interactive acceptance on Windows and macOS.
|
||||
The launcher uses SDL2 and RmlUI, with Direct3D 11 and automatic WARP software fallback on Windows, OpenGL 3.3 on Linux and OpenGL 4.1 on macOS; keep its `assets` directory next to the executable. Folder selection uses the operating system's dialog. See the [0.2 migration contract](docs/formats/obw/runtime-0.2.md) for compatibility and validation limits. Platform builds and automated tests are separate from human interactive acceptance on Windows and macOS.
|
||||
|
||||
## Features and direction
|
||||
|
||||
|
||||
@@ -11,4 +11,5 @@
|
||||
<footer><div id="state"></div><div id="status-message"></div><div id="bottom-actions"></div></footer>
|
||||
</div>
|
||||
<div id="overlay"><div id="modal"><div class="modal-head"><h2 id="modal-title"></h2><button data-action="cancel-modal" class="close">×</button></div><div id="modal-content"></div><div id="modal-error"></div><div id="modal-buttons"></div></div></div>
|
||||
<div id="history-overlay" data-action="history-close"><div id="history-menu"></div></div>
|
||||
</body></rml>
|
||||
@@ -161,12 +161,21 @@ input[type=checkbox]:checked { background-color: var(--toggle-on); decorator: no
|
||||
input[type=range] { height: 24dp; padding: 0; }
|
||||
input[type=range] track { height: 4dp; background-color: var(--scrollbar); margin: 9dp 0; border-radius: 2dp; }
|
||||
input[type=range] bar { width: 16dp; height: 16dp; border-radius: 8dp; background-color: var(--accent); margin-top: 3dp; }
|
||||
select { padding-right: 25dp; }
|
||||
/* Modern Desktop pickers, in density-independent editor dimensions. The
|
||||
native RmlUI controls retain their values, input and change events. */
|
||||
select { padding-right: 30dp; cursor: pointer; background-color: transparent; decorator: linear-gradient(var(--control-top), var(--control-bottom)); box-shadow: inset 0 1dp #eff6fc12, 0 1dp 2dp #0002; }
|
||||
select:hover { background-color: var(--hover); decorator: none; }
|
||||
select selectvalue { padding: 0; }
|
||||
select selectarrow { width: 9dp; height: 9dp; margin-right: 9dp; margin-top: 11dp; decorator: none; border-bottom: 2dp var(--muted); border-right: 2dp var(--muted); transform: rotate(45deg); }
|
||||
select selectbox { background-color: var(--popup); color: var(--text); border: 1dp var(--border); border-radius: 8dp; padding: 5dp; max-height: 290dp; overflow-y: auto; }
|
||||
select option { font-size: 14dp; padding: 8dp; border-radius: 4dp; }
|
||||
select option:hover, select option:checked { background-color: var(--selected); color: var(--selected-text); }
|
||||
select selectarrow { width: 8dp; height: 8dp; margin-right: 13dp; margin-top: 11dp; decorator: none; border-bottom: 1.5dp var(--muted); border-right: 1.5dp var(--muted); transform: rotate(45deg); }
|
||||
select selectbox { width: 100%; min-width: 180dp; background-color: var(--popup); color: var(--text); border: 1dp var(--border); border-radius: 9dp; padding: 5dp; margin-top: 7dp; margin-bottom: 7dp; max-height: 320dp; overflow-y: auto; box-shadow: 0 9dp 28dp #0008; }
|
||||
select option { display: flex; align-items: center; min-height: 34dp; padding: 5dp 7dp; border-radius: 5dp; white-space: nowrap; cursor: pointer; }
|
||||
select option:hover { background-color: var(--hover); }
|
||||
select option:disabled { opacity: 0.35; cursor: unavailable; }
|
||||
.option-check { width: 6dp; height: 10dp; margin: 0 12dp 3dp 3dp; flex-shrink: 0; border-right: 1.5dp var(--accent); border-bottom: 1.5dp var(--accent); transform: rotate(45deg); opacity: 0; }
|
||||
option:checked .option-check { opacity: 1; }
|
||||
selectvalue .option-check { display: none; }
|
||||
.option-label { overflow: hidden; text-overflow: ellipsis; }
|
||||
.option-label, .option-check { pointer-events: none; focus: none; }
|
||||
#search { width: 250dp; margin-right: auto; }
|
||||
#filter-nation, #filter-league { width: 205dp; }
|
||||
#filter-team { width: 240dp; }
|
||||
@@ -220,6 +229,7 @@ select option:hover, select option:checked { background-color: var(--selected);
|
||||
textarea { height: 110dp; font-size: 12dp; line-height: 1.5; }
|
||||
.form-section { padding-top: 8dp; margin-bottom: 15dp; font-size: 12dp; font-weight: bold; color: var(--accent); }
|
||||
.form-help { font-size: 11dp; color: var(--muted); line-height: 1.5; margin-top: 6dp; }
|
||||
.connection-actions { margin-top: 20dp; }
|
||||
.inspector-actions { padding: 16dp 20dp; border-top: 1dp var(--divider); display: flex; gap: 8dp; flex-shrink: 0; }
|
||||
.inspector-actions button { flex: 1; }
|
||||
.empty { margin: auto; padding: 45dp; text-align: center; color: var(--muted); line-height: 1.7; }
|
||||
@@ -262,8 +272,17 @@ footer { height: 57dp; padding: 0 28dp; display: flex; align-items: center; gap:
|
||||
#modal-content { overflow-y: auto; line-height: 1.6; }
|
||||
#modal-buttons { margin-top: 23dp; display: flex; justify-content: flex-end; gap: 9dp; flex-shrink: 0; }
|
||||
#modal-error { color: var(--danger); font-size: 13dp; margin-top: 10dp; }
|
||||
#history-overlay { display: none; position: absolute; left: 0; top: 0; width: 100%; height: 100%; z-index: 10; }
|
||||
#history-menu { position: absolute; width: 248dp; padding: 6dp; border: 1dp var(--border); border-radius: 10dp; background-color: var(--popup); }
|
||||
#history-menu button { width: 100%; display: flex; align-items: center; text-align: left; padding: 10dp; border-color: transparent; decorator: none; font-size: 15dp; }
|
||||
.history-arrow { width: 28dp; flex-shrink: 0; display: flex; align-items: center; }
|
||||
.history-arrow .glyph { width: 20dp; height: 20dp; }
|
||||
#history-menu small { margin: 0 0 0 auto; padding-left: 16dp; }
|
||||
.image-layout { display: flex; gap: 24dp; }
|
||||
.image-stage { flex: 1; min-height: 360dp; background-color: var(--image-stage); border: 1dp var(--border); border-radius: 10dp; display: flex; align-items: center; justify-content: center; overflow: hidden; }
|
||||
.hero-image, .mini-logo { cursor: pointer; }
|
||||
.readonly-stage { height: 500dp; }
|
||||
.image-caption { margin-top: 12dp; word-break: break-all; }
|
||||
#crop-canvas { position: relative; }
|
||||
#edit-preview { display: block; }
|
||||
#crop-box { position: absolute; border: 2dp var(--crop); background-color: var(--crop-wash); pointer-events: none; }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"asset": "stadium.tga",
|
||||
"sha256": "fb8e5f1f86afe60de87b70a2f533690d1ef470241fa24ee4384ff000149edaab",
|
||||
"sha256": "8bd89b7db8dbd0e92707240c5367cb92f8f32c2903e08157d0f278ac2599d6cf",
|
||||
"origin": "Independently generated night-stadium artwork for OpenBMH. No original game assets.",
|
||||
"method": "Built-in image_gen edit; exported as uncompressed 24-bit TGA without changing pixels.",
|
||||
"distribution": "Project-supplied launcher artwork, distributed with OpenBMH under GPL-3.0-only.",
|
||||
@@ -11,5 +11,10 @@
|
||||
"Added two netted goals and corrected the pitch markings, including a single center circle."
|
||||
]
|
||||
},
|
||||
"prompt": "Use case: precise-object-edit.\nAsset type: clean stadium background artwork for the existing OpenBMH launcher, landscape approximately 16:10.\nEdit target: the provided image. Make only these two localized corrections; preserve the stadium bowl, seating tiers, roof and floodlights, camera framing, foreground railing, blue/navy palette, warm dusk glow, dreamlike cinematic style, overall exposure and dark middle area for the existing UI overlay.\n\n1. Remove the entire distant CITY SKYLINE above the far stadium rim: every building, tower, rooftop, tree silhouette and urban horizon. Seamlessly replace that band with the same dusk sky and clouds. Above the stadium's own roof/rim there must be SKY ONLY. Keep the stadium's structural roof supports and floodlights.\n\n2. Correct the FOOTBALL PITCH in the lower part of the image, preserving its overall placement and green lighting. It is a real association-football pitch seen from a slightly elevated MIDFIELD SIDELINE seat: the two short goal-line ends are LEFT and RIGHT, not near/far center. Draw one coherent rectangular pitch in consistent perspective with realistic football geometry (105 by 68 metres). Exactly ONE halfway line across the width at midfield, exactly ONE center circle centered on that line, appearing elliptical because of the low viewpoint. At EACH of the left and right short ends, add ONE clearly recognizable white football goal, with TWO uprights, ONE crossbar and netting receding behind the goal line. Goal width-to-height about 3:1 (7.32m x 2.44m); realistic size in relation to the pitch. Add correctly placed penalty areas, smaller six-yard goal areas, penalty spots and penalty arcs on BOTH ends, four corner arcs and subtle corner flags. Do not put penalty boxes across midfield. Do not add duplicate circles, fake stripes, random white line fragments, a center-front goal, or a running track. Adjust only the grass/lines/goal areas as needed to fit a sensible single pitch. Both goals and correct layout should be visible within the existing image framing, even if a future UI overlay may cover part of them.\n\nNo UI panels, lettering, logos, advertisements with text, watermarks, players or extra architecture. Keep the original stylized mood; accuracy of the football equipment and markings matters more than adding detail.\n\nGrass cleanup:\nEdit the attached stadium illustration. This is an intermediate cleanup of the grass only, before correct markings are added separately.\nCOMPLETELY REMOVE EVERY WHITE PAINTED LINE AND SPOT ON THE GRASS. The entire playing field in the bottom part of the image must be continuous UNMARKED GREEN GRASS. NO center circle, NO halfway line, NO penalty boxes, NO goal-area lines, NO arcs, NO white grass markings whatsoever. Repaint the whole grass surface, not just a thin stroke. White goal frames with nets at the left and right edges must remain, since these are objects, not paint on grass. Keep corner flags. Everything above the pitch and the foreground rail must be unchanged: sky without any city silhouette, stadium, stands, lights, same composition and night colors.\nThe immediate output must show two goals beside an EMPTY UNMARKED RECTANGLE OF GREEN TURF. No text, no UI.\n\nFinal markings:\nUse case: precise-object-edit.\nEdit only the unmarked GRASS in the supplied stadium image. Add a single realistic association-football pitch's thin white painted markings, in the existing perspective of a midfield sideline view, with the two goals at the LEFT and RIGHT ends.\nDraw one complete perspective rectangle for the touchlines and goal lines, the goal lines aligned with the two existing goal mouths. At its middle draw exactly ONE straight halfway line from far touchline to near touchline and exactly ONE complete elliptical center circle centered on it, with one small center spot. Draw a rectangular penalty area and a smaller six-yard goal area at EACH goal end, with a penalty spot and a penalty arc outside each penalty area facing midfield. Draw tiny quarter-circle corner arcs at the four corners. The lines must follow one coherent standard full-size football pitch layout and perspective; no extra arcs or duplicate midfield circles.\nThe middle of the field is between the two left/right goals; do not draw a second circle near the far sideline. The width-to-depth of the visible center ellipse should be about 5:1 due to foreshortening. All marks are thin, subtle white paint, grounded on the existing grass.\nPreserve the two existing netted goals, four corner flags, rail, sky with NO city, stands, floodlights, dark navy twilight style, composition, and every part above the grass exactly as they are. Do not add people, text, branding, UI or watermarks."
|
||||
"prompt": "Use case: precise-object-edit.\nAsset type: clean stadium background artwork for the existing OpenBMH launcher, landscape approximately 16:10.\nEdit target: the provided image. Make only these two localized corrections; preserve the stadium bowl, seating tiers, roof and floodlights, camera framing, foreground railing, blue/navy palette, warm dusk glow, dreamlike cinematic style, overall exposure and dark middle area for the existing UI overlay.\n\n1. Remove the entire distant CITY SKYLINE above the far stadium rim: every building, tower, rooftop, tree silhouette and urban horizon. Seamlessly replace that band with the same dusk sky and clouds. Above the stadium's own roof/rim there must be SKY ONLY. Keep the stadium's structural roof supports and floodlights.\n\n2. Correct the FOOTBALL PITCH in the lower part of the image, preserving its overall placement and green lighting. It is a real association-football pitch seen from a slightly elevated MIDFIELD SIDELINE seat: the two short goal-line ends are LEFT and RIGHT, not near/far center. Draw one coherent rectangular pitch in consistent perspective with realistic football geometry (105 by 68 metres). Exactly ONE halfway line across the width at midfield, exactly ONE center circle centered on that line, appearing elliptical because of the low viewpoint. At EACH of the left and right short ends, add ONE clearly recognizable white football goal, with TWO uprights, ONE crossbar and netting receding behind the goal line. Goal width-to-height about 3:1 (7.32m x 2.44m); realistic size in relation to the pitch. Add correctly placed penalty areas, smaller six-yard goal areas, penalty spots and penalty arcs on BOTH ends, four corner arcs and subtle corner flags. Do not put penalty boxes across midfield. Do not add duplicate circles, fake stripes, random white line fragments, a center-front goal, or a running track. Adjust only the grass/lines/goal areas as needed to fit a sensible single pitch. Both goals and correct layout should be visible within the existing image framing, even if a future UI overlay may cover part of them.\n\nNo UI panels, lettering, logos, advertisements with text, watermarks, players or extra architecture. Keep the original stylized mood; accuracy of the football equipment and markings matters more than adding detail.\n\nGrass cleanup:\nEdit the attached stadium illustration. This is an intermediate cleanup of the grass only, before correct markings are added separately.\nCOMPLETELY REMOVE EVERY WHITE PAINTED LINE AND SPOT ON THE GRASS. The entire playing field in the bottom part of the image must be continuous UNMARKED GREEN GRASS. NO center circle, NO halfway line, NO penalty boxes, NO goal-area lines, NO arcs, NO white grass markings whatsoever. Repaint the whole grass surface, not just a thin stroke. White goal frames with nets at the left and right edges must remain, since these are objects, not paint on grass. Keep corner flags. Everything above the pitch and the foreground rail must be unchanged: sky without any city silhouette, stadium, stands, lights, same composition and night colors.\nThe immediate output must show two goals beside an EMPTY UNMARKED RECTANGLE OF GREEN TURF. No text, no UI.\n\nFinal markings:\nUse case: precise-object-edit.\nEdit only the unmarked GRASS in the supplied stadium image. Add a single realistic association-football pitch's thin white painted markings, in the existing perspective of a midfield sideline view, with the two goals at the LEFT and RIGHT ends.\nDraw one complete perspective rectangle for the touchlines and goal lines, the goal lines aligned with the two existing goal mouths. At its middle draw exactly ONE straight halfway line from far touchline to near touchline and exactly ONE complete elliptical center circle centered on it, with one small center spot. Draw a rectangular penalty area and a smaller six-yard goal area at EACH goal end, with a penalty spot and a penalty arc outside each penalty area facing midfield. Draw tiny quarter-circle corner arcs at the four corners. The lines must follow one coherent standard full-size football pitch layout and perspective; no extra arcs or duplicate midfield circles.\nThe middle of the field is between the two left/right goals; do not draw a second circle near the far sideline. The width-to-depth of the visible center ellipse should be about 5:1 due to foreshortening. All marks are thin, subtle white paint, grounded on the existing grass.\nPreserve the two existing netted goals, four corner flags, rail, sky with NO city, stands, floodlights, dark navy twilight style, composition, and every part above the grass exactly as they are. Do not add people, text, branding, UI or watermarks.",
|
||||
"serialization": {
|
||||
"format": "uncompressed 24-bit TGA, bottom-to-top rows",
|
||||
"previous_sha256": "fb8e5f1f86afe60de87b70a2f533690d1ef470241fa24ee4384ff000149edaab",
|
||||
"reason": "Compatible row stride in the pinned Direct3D 11 loader; decoded RGB pixels are unchanged."
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 4.5 MiB After Width: | Height: | Size: 4.5 MiB |
@@ -1,10 +1,23 @@
|
||||
# OpenBMH Editor 0.5.2
|
||||
# OpenBMH Editor 0.5.4
|
||||
|
||||
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.2 hat eine eigene Versionsreihe und den Release-Tag `editor-v0.5.2`; die Spielversion ist 0.2.0.
|
||||
Der eigenständige, native Editor verwendet **RmlUI und SDL2**, unter Windows mit Direct3D 11, unter Linux/macOS mit OpenGL. Er bearbeitet Startdatenbanken, keine laufenden Spielstände. Das Spiel und seine Classic-Prüfung bleiben unverändert. Editor 0.5.4 hat eine eigene Versionsreihe und den Release-Tag `editor-v0.5.4`; die Spielversion ist 0.2.1.
|
||||
|
||||
## Windows-Start und Diagnose
|
||||
|
||||
Windows verwendet Direct3D 11 und wechselt bei fehlender Hardware automatisch auf
|
||||
den integrierten WARP-Renderer. Der Editor und der Spiel-Launcher benötigen dort
|
||||
keinen OpenGL-Treiber. Dieser Start wird auch mit erzwungenem WARP auf Windows
|
||||
Server 2022 geprüft. Zum gezielten Testen lässt sich `OPENBMH_RML_DRIVER=warp`
|
||||
setzen; die normale Auswahl erfolgt automatisch.
|
||||
|
||||
Startfehler erscheinen in einem nativen Dialog und werden zusätzlich unter
|
||||
`%LOCALAPPDATA%\OpenBMH\OpenBMHEditor-startup.log` protokolliert. Bei einem
|
||||
Aufruf aus PowerShell/CMD kann auch stderr umgeleitet werden. Headless- und
|
||||
MCP-Aufrufe zeigen keinen modalen Fehlerdialog und behalten ihre Prozesscodes.
|
||||
|
||||
## Starten und Daten öffnen
|
||||
|
||||
Das vollständige Paket `OpenBMHEditor-0.5.2-<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.4-<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.
|
||||
|
||||
@@ -13,6 +26,7 @@ Das vollständige Paket `OpenBMHEditor-0.5.2-<plattform>.zip` entpacken und `Ope
|
||||
## Bearbeiten
|
||||
|
||||
- Links einen Datenbereich auswählen; die Liste lässt sich durchsuchen, filtern, sortieren und seitenweise durchgehen. Rechts Änderungen mit **Anwenden** übernehmen. **Speichern** übernimmt auch die aktuellen Eingaben.
|
||||
- **Doppelklick** auf ein Land zeigt seine Ligen, auf eine Liga ihre Vereine und auf einen Verein dessen Spieler. Land, Liga und Verein werden als Filter übernommen. Ein einfacher Klick wählt weiterhin den Datensatz zum Bearbeiten aus. Nicht übernommene Eingaben werden vor dem Wechsel abgefragt.
|
||||
- Länder, Wettbewerbe, Vereine, Spieler, Kader, Stadien und Schiedsrichter lassen sich anlegen und bearbeiten. Referenzierte Datensätze werden erst nach Änderung ihrer Verknüpfungen gelöscht. Vereinswechsel zwischen Ligen aktualisieren auch deren Mitgliederlisten.
|
||||
- Spielwerte behalten ihre **quellenspezifischen Wertebereiche**. Ein Classic-Wert wird nicht auf eine erfundene 1–10-Skala umgerechnet. Neue Spieler ohne belegte Werte bleiben zunächst unbewertet.
|
||||
- Kader bleiben vollständig erhalten. Die Schaltfläche **24** schaltet lediglich die Seitengröße um. Spieler lassen sich über das Vereinsfeld verschieben, zum Tausch merken und mit einem anderen Spieler tauschen; die Pfeile ändern ihre Reihenfolge.
|
||||
@@ -20,11 +34,45 @@ Das vollständige Paket `OpenBMHEditor-0.5.2-<plattform>.zip` entpacken und `Ope
|
||||
- Rückgängig/Wiederholen gilt gemeinsam für native Oberfläche und MCP. Noch nicht angewendete Eingaben werden bei externen Änderungen nicht automatisch ersetzt; eine veraltete Änderung muss nach Aktualisierung erneut geprüft werden.
|
||||
- **Bilder** und die Bildaktionen am Datensatz unterstützen PNG, JPEG, WebP und eigenständige SVG. Vor dem Import: Ausschnitt ziehen oder Werte eingeben, frei drehen, spiegeln. Ein unveränderter Import behält seine Originalbytes. Bearbeitete Rasterbilder werden PNG, SVG bleibt Vektor. Das Original und die Transformationswerte bleiben für erneutes Bearbeiten im Paket. Classic-Porträts werden aus ihren eingefrorenen Rezepten angezeigt; eine Umbenennung ändert das Gesicht nicht.
|
||||
- Bildänderungen am Spieler, Verein oder Wettbewerb erhalten eine eigene Zuordnung. Gemeinsame Platzhalter und Bilder anderer Datensätze bleiben dabei erhalten. Im Bereich **Bilder** kann ein gemeinsam verwendetes Bild bewusst zentral bearbeitet werden.
|
||||
- Ein Klick auf ein Wappen, Porträt, einen Pokal oder ein Bild in der Liste öffnet eine große, schreibgeschützte **Bildvorschau**. **Zum Asset** öffnet den zugehörigen Eintrag im Bereich **Bilder**. Bei zusammengesetzten Classic-Porträts ohne einzelne Bilddatei führt die Schaltfläche zur allgemeinen Bildübersicht. Das Anschauen verändert keine Daten; beim Wechsel bleiben offene Eingaben durch die Übernehmen-/Verwerfen-Abfrage geschützt.
|
||||
|
||||
**Speichern** erzeugt ausschließlich `.obw` im Profil **`editor-world-v1`, Format 1.1**. Editorwelten sind **noch nicht im Classic-Spiel startbar**. Die Bezeichnung ist im Editor sichtbar. Unbekannte Erweiterungen, nicht bearbeitete Dokumente, Quellnachweise und Bilder bleiben erhalten. Noch nicht im Formular angebotene Regeln, Kalender- und Finanzdaten werden erhalten, aber nicht als vollständig editierbare Bereiche ausgegeben.
|
||||
|
||||
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.
|
||||
|
||||
## Zurück und Vorwärts
|
||||
|
||||
Ein **Rechtsklick** an beliebiger Stelle öffnet **Zurück / Vorwärts**. Dieselbe
|
||||
Navigation funktioniert mit **Alt+Links / Alt+Rechts** und den beiden seitlichen
|
||||
Maustasten. Nicht verfügbare Richtungen sind ausgegraut. Escape oder ein Klick
|
||||
außerhalb schließt das Menü.
|
||||
|
||||
Der Verlauf merkt Datenbereiche, Doppelklick-Absprünge, Vergleichsansichten und
|
||||
Asset-Verknüpfungen. Beim Zurückkehren werden Filter, Suche, Sortierung,
|
||||
Datensatzauswahl, Tabellenseite und Scrollpositionen wiederhergestellt.
|
||||
Filtereingaben und einfache Zeilenauswahl erzeugen keine einzelnen Verlaufsschritte.
|
||||
Offene Formulareingaben werden weiterhin vor dem Wechsel abgefragt; Abbrechen
|
||||
lässt die Position im Verlauf unverändert. Ein neuer Absprung nach Zurück ersetzt
|
||||
den bisherigen Vorwärtszweig. Das Öffnen einer anderen Welt, auch über MCP,
|
||||
setzt den Verlauf zurück. **Zurück** ist unabhängig von **Rückgängig** und ändert
|
||||
keine Daten.
|
||||
|
||||
Die Dropdowns verwenden die Gestaltung der Modern-Desktop-Untermenüs:
|
||||
leichte Verläufe, runde Popup-Listen, ein Häkchen am gewählten Wert und dieselbe
|
||||
Schriftgröße in geschlossenem Feld und Auswahlliste. Escape schließt zuerst die
|
||||
offene Auswahlliste. [Native Vergleichsbilder](qa/editor-navigation/README.md)
|
||||
zeigen die Darstellung in allen drei Themes.
|
||||
|
||||
## CPU im Leerlauf
|
||||
|
||||
Ab 0.5.4 zeichnet der Editor nur bei Eingaben, sichtbaren Änderungen oder von
|
||||
RmlUI angeforderten Zeitereignissen. Ein unveränderter Bildschirm benötigt keine
|
||||
fortlaufenden Frames. Textcursor, Animationen, Scrollen und externe MCP-Änderungen
|
||||
bleiben aktiv; minimierte Fenster zeichnen nicht. Die vorherige Dauerschleife
|
||||
konnte insbesondere mit dem WARP-Softwarerenderer unter Remote Desktop einen
|
||||
erheblichen Teil der CPU belegen. Import, Bildverarbeitung und andere tatsächliche
|
||||
Datenarbeit benötigen weiterhin Rechenzeit.
|
||||
|
||||
## 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.
|
||||
@@ -61,7 +109,7 @@ Unter **Darstellung** stehen die drei Farbwelten der modernen Untermenüs zur Au
|
||||
|
||||
Der MCP-Server ist standardmäßig aktiviert und bindet ausschließlich `127.0.0.1`, standardmäßig Port `8765`. Port `0` wählt einen freien Port. Status und tatsächlicher Port sind in Optionen sichtbar. **Verbindung kopieren** kopiert eine JSON-Konfiguration einschließlich Bearer-Token für HTTP-fähige MCP-Clients. Das Token bleibt lokal im Benutzerprofil und wird nur auf ausdrückliches Kopieren/CLI-Anfordern ausgegeben. Ein anderer bereits laufender Editor kann den Standardport belegen; dann einen anderen Port wählen.
|
||||
|
||||
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.
|
||||
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. `editor_info.world_generation` kennzeichnet die aktuell geladene Welt innerhalb der Sitzung: Öffnen/Neu erhöht den Wert, Bearbeiten, Speichern und Rückgängig behalten ihn bei. Er wird nicht im OBW gespeichert.
|
||||
|
||||
Werkzeuge: `editor_info`, `editor_open`, `editor_new`, `editor_list`, `editor_compare`, `editor_regulations`, `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`.
|
||||
|
||||
@@ -84,7 +132,7 @@ Das sind keine heutigen UEFA-Regeln und kein neuer Saison-Simulator.
|
||||
|
||||
## Kompilieren
|
||||
|
||||
Voraussetzungen entsprechen dem Hauptprojekt: C++20-Compiler, Git, CMake ≥ 3.24 und Ninja. Windows: Visual Studio 2022 C++ Build Tools / x64 Native Tools Prompt; macOS ARM: Xcode Command Line Tools, CMake und Ninja; Linux: GTK3-, X11- und OpenGL-Entwicklungspakete wie im Haupt-README. Die Grafikausgabe benötigt OpenGL 3.3, auf macOS OpenGL 4.1.
|
||||
Voraussetzungen entsprechen dem Hauptprojekt: C++20-Compiler, Git, CMake ≥ 3.24 und Ninja. Windows: Visual Studio 2022 C++ Build Tools / x64 Native Tools Prompt; macOS ARM: Xcode Command Line Tools, CMake und Ninja; Linux: GTK3-, X11- und OpenGL-Entwicklungspakete wie im Haupt-README. Windows nutzt Direct3D 11 mit automatischem WARP-Software-Fallback; Linux benötigt OpenGL 3.3, macOS OpenGL 4.1.
|
||||
|
||||
```sh
|
||||
cmake -S . -B build-editor -G Ninja -DCMAKE_BUILD_TYPE=Release -DOPENBMH_BUILD_EDITOR=ON
|
||||
@@ -116,6 +164,8 @@ Use **Regulations** to inspect promotion, relegation, playoffs, international qu
|
||||
|
||||
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.
|
||||
|
||||
Click a crest, portrait, trophy or list thumbnail to open a large read-only image preview. **View asset** opens its linked asset record; composed Classic portraits without a single image file lead to the image library. Viewing preserves the world and pending property edits.
|
||||
|
||||
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.2 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`. Windows uses Direct3D 11 with automatic WARP software fallback. Linux requires OpenGL 3.3; macOS requires OpenGL 4.1, plus the documented platform development dependencies. Editor 0.5.4 is unsigned and does not bundle any real-world dataset or proprietary game assets.
|
||||
@@ -1,6 +1,6 @@
|
||||
# Engine split: Classic, Classic Extended and Modern
|
||||
|
||||
Status: **concept and migration plan**. It prepares one shared match engine under three season engines. Nothing in this document changes the behaviour of the current release.
|
||||
Status: **concept and migration plan**. It prepares one shared match engine under the season engines of three game variants. Nothing in this document changes the behaviour of the current release.
|
||||
|
||||
## 1. Goal
|
||||
|
||||
@@ -8,27 +8,35 @@ OpenBMH will offer three game variants:
|
||||
|
||||
| Variant | Data | Season engine | Interface | State |
|
||||
|---|---|---|---|---|
|
||||
| **Classic** | Imported from the user's BMH or FLTD installation (OBW `runtime:classic-v1`) | The current engine: fixed calendar, 9 leagues, original competition structure and rules | Classic 320×200 interface | Essentially complete |
|
||||
| **Classic Extended** | Classic data plus extension data | Classic engine with optional, switchable extensions | Classic interface plus additional screens in the same style | Not started |
|
||||
| **Modern** | Typed OBW worlds (imported or own) | New engine: generated calendar, data-driven leagues and competitions, playable foreign leagues | New high-resolution interface (RmlUi) | Interface in progress |
|
||||
| **Classic** | Imported from the user's BMH or FLTD installation (OBW `runtime:classic-v1`) | Classic: fixed calendar, 9 leagues, original competition structure and rules | Classic 320×200 bitmap interface | Essentially complete |
|
||||
| **Classic Extended** | Classic data, optionally extended where the classic screens can show it | Working idea: Classic engine plus features **backported from Modern**, step by step (§4) | Classic bitmap interface, extended by hand per feature | Open; after Modern |
|
||||
| **Modern** | New OBW data set (imported and extended, or own worlds) | Modern: generated calendar, data-driven leagues and competitions, playable foreign leagues, leagues larger than 12 teams | New high-resolution interface (RmlUi), designed for many leagues | Interface in progress |
|
||||
|
||||
All three use **the same match engine**. A match between two given teams under the same rules is simulated by the same code in every variant; only what happens around it (calendar, competitions, finances, transfers, development) differs.
|
||||
|
||||
### 1.1 Where a change belongs
|
||||
|
||||
- **Classic** receives changes that work with the imported original assets and the original data layout: bug fixes, quality of life, small rule corrections, menus such as the environment menu of a later DIAMOND release.
|
||||
- **Modern** is where new features are designed first, without the limits of the original screens or data layout: more leagues, foreign leagues with more than 12 teams, a free calendar, new competitions and systems.
|
||||
- **Classic Extended** takes Modern features back into the Classic engine **one at a time**, where the bitmap interface can present them with reasonable manual work. The classic screens were never designed for variable structures, so Classic Extended will never offer every Modern feature; each backport is a decision of its own (§4).
|
||||
|
||||
## 2. Target architecture
|
||||
|
||||
```
|
||||
Classic UI Classic Extended UI Modern UI (RmlUi)
|
||||
\ | /
|
||||
+-------- app / protocol layer -------+ variant capabilities
|
||||
/ | \
|
||||
season: classic season: classic + extensions season: modern
|
||||
(GameState image) (GameState image + ext state) (typed OBW model)
|
||||
\ | /
|
||||
+------ match adapter (per engine) ---+
|
||||
|
|
||||
match engine (bmh_match: typed contract)
|
||||
|
|
||||
random sources, attribute set bmh-classic@1
|
||||
Classic UI (bitmap) Classic UI + extra screens Modern UI (RmlUi)
|
||||
| | |
|
||||
+---------------- app / protocol layer (capabilities) -------+
|
||||
| | |
|
||||
season: classic season: classic + backported features season: modern
|
||||
(GameState image) (GameState image + extension state) (typed OBW model)
|
||||
| | \ / |
|
||||
| | shared feature modules |
|
||||
| | (bmh_features, ports) |
|
||||
+------------------ match adapter (per engine) --------------+
|
||||
|
|
||||
match engine (bmh_match: typed contract)
|
||||
|
|
||||
random sources, attribute set bmh-classic@1
|
||||
```
|
||||
|
||||
### 2.1 Libraries
|
||||
@@ -37,11 +45,21 @@ All three use **the same match engine**. A match between two given teams under t
|
||||
|---|---|---|
|
||||
| `bmh_match` | Minute simulation, events, chances, cards, injuries during the match, substitutions, live interventions, the Reality scene and reporter | `random`, the match contract types; **not** `GameState`, calendar, finances |
|
||||
| `bmh_season_classic` | Today's `src/game` without the match core: turn driver, weekly/monthly/season processing, cups, transfers, finances, post-match effects | `bmh_match`, `bmhcore` formats |
|
||||
| `bmh_season_classic_ext` | Extension modules on top of Classic (§4) | `bmh_season_classic` |
|
||||
| `bmh_season_modern` | New season engine on the typed OBW model (§5) | `bmh_match`, `bmh_world` |
|
||||
| `bmh_world` | Typed OBW model, reader/writer, validator, importers (`src/import`) | `bmhcore` formats |
|
||||
| `bmh_season_classic_ext` | Classic Extended: registry of backported features, their state and hook points in the Classic turn (§4) | `bmh_season_classic`, `bmh_features` |
|
||||
| `bmh_features` | Season features written once for Modern and reusable by Classic Extended, each against small **ports** (interfaces) instead of a concrete state model | the match contract types only |
|
||||
| `bmh_season_modern` | New season engine on the typed OBW model (§5) | `bmh_match`, `bmh_features`, `bmh_world` |
|
||||
| `bmh_world` | Typed OBW model, reader/writer, validator (`src/content`, `src/import`) | `bmhcore` formats |
|
||||
|
||||
The dependency rule: **the match engine knows no season engine**, and no season engine reaches into another one's state.
|
||||
The dependency rules: **the match engine knows no season engine**; no season engine reaches into the state of another; **no season engine knows an interface**; a feature in `bmh_features` knows neither `GameState` nor the OBW model, only its ports.
|
||||
|
||||
### 2.2 Writing Modern features so they can be backported
|
||||
|
||||
Backporting is cheap only if a feature is written for it from the start:
|
||||
|
||||
- The rules of a feature (for example youth development, a staff system, sponsor negotiation) live in `bmh_features` and read and write the game only through a port: `PlayerRoster`, `ClubFinance`, `Calendar`, `Mailbox`, `RandomSources` and similar narrow interfaces.
|
||||
- Modern implements the ports on the typed model. Classic Extended implements the same ports as adapters on `GameState` plus its extension state.
|
||||
- A feature declares what it needs (ports, data fields, calendar events) and which presentation it needs (screens, messages). This declaration is the checklist for a backport: if the Classic adapter cannot provide a port, or no classic screen can show the result, the feature stays Modern-only.
|
||||
- Features that depend on Modern-only structures (generated calendar, generic competition stages, leagues of variable size) are marked as such and are not candidates.
|
||||
|
||||
## 3. The match contract
|
||||
|
||||
@@ -94,7 +112,7 @@ The match engine draws only through an injected `RandomSources` interface with t
|
||||
|
||||
### 3.5 Attribute set
|
||||
|
||||
The match engine consumes players in attribute set `bmh-classic@1` (OBW §5.3). Classic and Classic Extended already store exactly this. Modern may keep richer attributes for its own systems, but provides a `bmh-classic@1` projection for every player it sends into a match. A later, finer match model would be a **new version** of the match engine with its own attribute set, selectable per variant; it is not part of this plan.
|
||||
The match engine consumes players in attribute set `bmh-classic@1` (OBW §5.3). Classic already stores exactly this. Modern may keep richer attributes for its own systems, but provides a `bmh-classic@1` projection for every player it sends into a match. A later, finer match model would be a **new version** of the match engine with its own attribute set, selectable per variant; it is not part of this plan.
|
||||
|
||||
### 3.6 Versioning
|
||||
|
||||
@@ -102,22 +120,29 @@ The match engine consumes players in attribute set `bmh-classic@1` (OBW §5.3).
|
||||
|
||||
## 4. Classic Extended
|
||||
|
||||
Classic Extended is **Classic plus switchable extensions**:
|
||||
> **Working idea, not a decision.** Backporting Modern features into the Classic engine is the current idea for Classic Extended; the variant may take a different shape. What does not depend on it: the shared match engine (§3), the Modern engine driven only through the protocol, and features written against ports (§2.2), which keep several options open.
|
||||
|
||||
- It runs on the Classic season engine and the Classic save layout, plus one additional state block for extensions (`x-extended/` in OBW saves).
|
||||
- Each extension is a module with an id, a version, its own state, its rules and its screens. A career records which extensions it uses.
|
||||
- **Invariant:** with every extension switched off, Classic Extended produces exactly the Classic results. A test runs the Classic regression through the Extended engine with no extensions.
|
||||
- Extensions hook into defined points of the Classic turn (start/end of day, week, month, season; before/after matchday; desk actions), never into the middle of a Classic routine.
|
||||
- Its screens use the classic interface toolkit (`src/ui`), in the same resolution and style.
|
||||
- Candidates for first extensions: the environment ("Umfeld") menu of a later DIAMOND release (reviewed against our rule base, documented as a deviation), more statistics and history screens, quality-of-life automation, configurable rule values (roadmap 0.3).
|
||||
Classic Extended is the **Classic season engine plus backported Modern features**, presented in the classic bitmap interface.
|
||||
|
||||
- **Invariant:** with every backported feature switched off, Classic Extended produces exactly the Classic results. A test runs the Classic regression through the Extended engine with no features.
|
||||
- Each backported feature is a module with an id and version, its own state (`x-extended/` in OBW saves), the Classic adapters for its ports and its classic-style screens. A career records which features it uses; features can be switched on at career start and, where safe, later.
|
||||
- Features hook into defined points of the Classic turn (start/end of day, week, month and season; before/after a matchday; desk actions), never into the middle of a Classic routine.
|
||||
- **Data:** Classic Extended starts from Classic data. A feature may bring additional data, but only in a shape the classic screens can show. Structures that change the size of what the screens list (more or larger leagues, new competitions) are Modern-only unless a specific screen is redesigned for them.
|
||||
- **Interface cost per feature**, the main factor in each backport decision:
|
||||
1. The result fits existing screens (a new value on the player card, a message, a desk action): small.
|
||||
2. A new screen of fixed size in the classic style (a staff or youth screen): medium, new own artwork needed.
|
||||
3. A screen whose content grows with the data (longer tables, more league selectors, calendar views): large, often not worth it.
|
||||
- **Assets:** the original bitmaps of the user's installation plus new classic-style artwork. New artwork must be the project's own.
|
||||
- Order of work: a feature is built and settled in Modern first, then backported if its ports and its presentation fit (§2.2).
|
||||
|
||||
## 5. Modern
|
||||
|
||||
Modern is a new season engine on the typed OBW model (`docs/formats/OBW.md`):
|
||||
|
||||
- **Data set:** an OBW world that goes beyond the original structure, for example foreign leagues with more than 12 teams, more leagues (up to 32) and real-world competition formats. It can start from an imported Classic world and be extended, or be a world of its own.
|
||||
- **Calendar:** generated each season from `world/calendar.json` (series, windows, events) instead of a fixed day table; any season start, international windows, winter breaks per nation.
|
||||
- **Competitions:** the generic stage model (league, groups, league phase, knockout, playoff, final) with declarative slots and promotion/relegation; up to 32 leagues; foreign leagues are playable, not only simulated.
|
||||
- **Systems:** finances, transfers, contracts, youth, staff and development are rewritten on the typed model, reusing Classic formulas where they fit, documented where they differ.
|
||||
- **Competitions:** the generic stage model (league, groups, league phase, knockout, playoff, final) with declarative slots and promotion/relegation; foreign leagues are playable, not only simulated.
|
||||
- **Systems:** finances, transfers, contracts, youth, staff and development are rewritten on the typed model, reusing Classic formulas where they fit and documenting where they differ.
|
||||
- **Interface:** the RmlUi client through the app/protocol layer only.
|
||||
- Matches always go through the shared match contract (§3).
|
||||
|
||||
@@ -125,10 +150,10 @@ Modern does not have to reproduce Classic results; its quality gate is plausibil
|
||||
|
||||
## 6. Variant selection and saves
|
||||
|
||||
- The world or save manifest names the runtime: `requires: ["runtime:classic-v1"]`, `["runtime:classic-extended-v1"]` or `["runtime:modern-v1"]`, plus `match@1`.
|
||||
- `CareerSession` selects the season engine from the manifest; the protocol reports **capabilities** per variant, so interfaces and console clients only offer supported actions.
|
||||
- Conversions are **one-way**: Classic → Classic Extended (switch on extensions), Classic or Classic Extended → Modern (convert to the typed model). There is no way back, and the original file is kept.
|
||||
- Legacy `.FBM` saves stay Classic.
|
||||
- The world or save manifest names the runtime: `requires: ["runtime:classic-v1"]`, `["runtime:classic-extended-v1"]` (with the list of active features and their versions) or `["runtime:modern-v1"]`, plus `match@1`.
|
||||
- `CareerSession` selects the season engine from the manifest; the protocol reports **capabilities** per engine and feature, so interfaces and console clients only offer supported actions.
|
||||
- Conversions are **one-way**: Classic → Classic Extended (switch features on), Classic or Classic Extended → Modern (convert to the typed model; backported feature state maps to the Modern original of the feature). There is no way back, and the original file is kept.
|
||||
- **All variants save only in the OBW format** (`.obs`). Legacy `.FBM` saves are an import source only: they are converted into a Classic `.obs` career and never written.
|
||||
|
||||
## 7. Migration plan
|
||||
|
||||
@@ -141,23 +166,25 @@ Each step keeps the game playable and the Classic regression (`tools/regression/
|
||||
| 2 | Introduce `RandomSources`; the match core no longer touches the global streams directly | Regression identical |
|
||||
| 3 | Typed `MatchdaySetup`/`MatchdayResult`; Classic adapter builds the setup from `MatchGroup`/`GameState` and writes results back; move post-match effects out of the minute loop into `bmh_season_classic` | Regression identical; match contract tests |
|
||||
| 4 | Remove the remaining `GameState` dependencies from `bmh_match` (enforced by the build: `bmh_match` does not link `GameState`) | Build rule; regression identical |
|
||||
| 5 | Variant field in manifests, engine selection in `CareerSession`, capability reporting in the protocol | Classic unchanged; capability tests |
|
||||
| 6 | Classic Extended skeleton: extension registry, hook points, `x-extended` state, "all extensions off = Classic" test | Regression identical through Extended |
|
||||
| 7 | Modern season engine on `bmh_world`, first with one nation and the shared match engine, then the competition model, then foreign leagues | Modern plausibility runs |
|
||||
| 8 | First Classic Extended extensions; Modern feature growth | Per extension/feature |
|
||||
| 5 | Runtime field in manifests, engine selection in `CareerSession`, capability reporting in the protocol | Classic unchanged; capability tests |
|
||||
| 6 | `bmh_features` with the first ports; Modern season engine on `bmh_world`, first with one nation and the shared match engine, then the competition model, then foreign leagues and larger leagues | Modern plausibility runs |
|
||||
| 7 | Classic Extended skeleton: feature registry, hook points, `x-extended` state, Classic adapters for the first ports, "no features = Classic" test | Regression identical through Extended |
|
||||
| 8 | Backports one feature at a time, each with its interface cost assessed (§4) | Per feature: Classic regression with the feature off, plausibility with it on |
|
||||
| 9 | Classic → Modern conversion of worlds and careers | Converted careers playable |
|
||||
|
||||
Steps 1 to 4 are the actual split and the risky part; they are pure refactoring and must be done in small commits with the regression after each.
|
||||
Steps 1 to 4 are the actual split and the risky part; they are pure refactoring and must be done in small commits with the regression after each. Classic improvements continue in parallel on `bmh_season_classic`.
|
||||
|
||||
## 8. Tests
|
||||
|
||||
- **Match contract tests:** a fixed `MatchdaySetup` with fixed seeds yields a fixed `MatchdayResult` (golden files with synthetic teams, public).
|
||||
- **Classic regression:** unchanged scripts and expected outputs; run after every step.
|
||||
- **Extended identity:** Classic regression through the Extended engine with no extensions.
|
||||
- **Extended identity:** the Classic regression through the Extended engine with no features.
|
||||
- **Feature tests:** each module in `bmh_features` is tested once against fake ports, then through both adapters (Modern and Classic Extended).
|
||||
- **Modern plausibility:** bulk season simulations with goal, points and money distributions compared to Classic as a reference band.
|
||||
- **Dependency check:** the build fails if `bmh_match` includes season or `GameState` headers.
|
||||
- **Dependency checks:** the build fails if `bmh_match` includes season or `GameState` headers, if `bmh_features` includes `GameState` or OBW model headers, or if a season engine includes interface headers.
|
||||
|
||||
## 9. Open decisions
|
||||
|
||||
- Whether Classic Extended may change the save layout for its extensions only in OBW saves or also offer a legacy `.FBM` export (proposal: OBW only).
|
||||
- Whether Modern keeps `bmh-classic@1` as its only player attribute set at first (proposal: yes, richer attributes later).
|
||||
- Which team owns which variant: Classic and the split (engine/integration), Modern interface (UI), Classic Extended extensions (both, per module).
|
||||
- Which features become the first backport candidates (proposal: features of interface cost 1 or 2 that do not change league structure).
|
||||
- Whether Modern keeps `bmh-classic@1` as its only player attribute set at first (proposal: yes, richer attributes later as a new match engine version).
|
||||
- Ownership: the split and Classic (engine/integration), the Modern interface (UI), Modern features and their backports (shared, per feature).
|
||||
@@ -26,7 +26,7 @@ Some calendar operations need synchronous human decisions. Their presenters own
|
||||
|
||||
## Calendar and matches
|
||||
|
||||
The planned split into one shared match engine and three season engines (Classic, Classic Extended, Modern) is described in [ENGINE_SPLIT](ENGINE_SPLIT.md).
|
||||
The planned split into one shared match engine and the season engines of Classic, Classic Extended (Classic plus backported Modern features) and Modern is described in [ENGINE_SPLIT](ENGINE_SPLIT.md).
|
||||
|
||||
The turn driver moves between manager desks, match clocks and calendar events. Weekly, monthly and seasonal processing can produce decisions as well as simulation results. Match groups contain the day's competitions; a manager can intervene only in a group involving that manager's team. A multi-client match clock advances at a barrier shared by all seats.
|
||||
|
||||
@@ -57,8 +57,11 @@ of `OpenBMH`, keeping edition-specific process globals isolated. Portable mod co
|
||||
personal files have independent lifetimes. See [runtime-0.2](formats/obw/runtime-0.2.md).
|
||||
|
||||
The launcher layout and theme live in `assets/launcher/launcher.rml` and `theme.rcss`.
|
||||
They share the same RmlUI core, FreeType font engine and upstream SDL2/OpenGL renderer
|
||||
on all desktop platforms. The C++ view translates events into the existing launcher
|
||||
They share the same RmlUI core, FreeType font engine and SDL2 platform layer.
|
||||
Windows uses the pinned upstream Direct3D 11 renderer with hardware-to-WARP
|
||||
fallback, while Linux/macOS keep the upstream OpenGL renderer. Both the editor
|
||||
and launcher share window/device lifetime, resizing and capture through
|
||||
`src/launch/rml_video.*`. The C++ view translates events into the existing launcher
|
||||
interface; it does not own conversion rules or mod storage. This presentation layer
|
||||
can be reused by future modern screens. Classic game screens retain their current UI.
|
||||
The operating system supplies the folder picker through nativefiledialog-extended.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# Native read-only image preview
|
||||
|
||||
Editor 0.5.3, captured from the native RmlUI application at 1440×900.
|
||||
All pictures and records are authored synthetic demo data. No game installation,
|
||||
real crest, portrait, savegame or personal profile is included.
|
||||
|
||||
| View | Native screenshot |
|
||||
|---|---|
|
||||
| Before: small image in the club inspector | [Club inspector](before-club-image.png) |
|
||||
| After: large read-only preview, Midnight / German | [Midnight](preview-midnight-de.png) |
|
||||
| Silver / English | [Silver](preview-silver-en.png) |
|
||||
| Matchday / German | [Matchday](preview-matchday-de.png) |
|
||||
| Jump to the exact linked image record | [Linked asset](linked-asset.png) |
|
||||
|
||||
Clicking the inspector image or a list thumbnail opens the same viewer. Images
|
||||
retain their aspect ratio; there are no editing controls. Close, the window's
|
||||
close button and Escape return to the current form. **View asset** opens the
|
||||
linked asset, clearing unrelated country/league/team filters. Composed Classic
|
||||
portraits without a single backing asset offer the general image library.
|
||||
|
||||
`tests/editor_gui_smoke.py` exercises the actual mouse and keyboard path. MCP
|
||||
observes that opening/closing the preview leaves the world and history unchanged.
|
||||
The test also preserves a pending property draft, cancels a guarded asset jump,
|
||||
checks the selected club's exact asset, and opens the different asset from an
|
||||
unselected row. These checks complement the core, comparison and regulations
|
||||
tests. The synthetic demo starts unsaved; the asterisk in these captures reflects
|
||||
that initial state rather than a modification caused by the preview.
|
||||
|
After Width: | Height: | Size: 141 KiB |
|
After Width: | Height: | Size: 128 KiB |
|
After Width: | Height: | Size: 83 KiB |
|
After Width: | Height: | Size: 88 KiB |
|
After Width: | Height: | Size: 92 KiB |
@@ -0,0 +1,64 @@
|
||||
# Native navigation, pickers and idle rendering
|
||||
|
||||
Editor 0.5.4, native SDL2/RmlUI at 1440×900. The captures contain only generated
|
||||
demo records and project-authored geometric crests. No installation, real photo,
|
||||
savegame, personal profile or MCP token is included. Reproduce the initial
|
||||
database with `OpenBMHEditor --demo --page clubs`.
|
||||
|
||||
| View | Screenshot |
|
||||
|---|---|
|
||||
| Before: 0.5.3 controls and MCP button spacing | [Options before](before-options-0.5.3.png) |
|
||||
| After: Modern Desktop controls and separated Copy connection | [Options](options-midnight-de.png) |
|
||||
| Native dropdown, Midnight / German | [Midnight](dropdown-midnight-de.png) |
|
||||
| Native dropdown, Silver / English | [Silver](dropdown-silver-en.png) |
|
||||
| Native dropdown, Matchday / German | [Matchday](dropdown-matchday-de.png) |
|
||||
| Browser context menu, both directions available | [Back / Forward](history-midnight-de.png) |
|
||||
|
||||
The controls port the Modern Desktop submenu palettes, gradient buttons, rounded
|
||||
popup, selection checkmark, matching text size and hover treatment to RCSS. They
|
||||
retain RmlUI's native select values/events and scale with the editor. Escape
|
||||
cancels the open list before closing its dialog. The connection action now has
|
||||
20dp of space above it. Correct frame initialization preserves transparent
|
||||
offscreen layers for the popup shadows.
|
||||
|
||||
`tests/editor_gui_smoke.py` uses actual mouse/keyboard input and an MCP observer:
|
||||
|
||||
- Drill from the second of two leagues to its club and players. Back twice,
|
||||
then Forward twice; edit/undo the selected destinations to verify their IDs.
|
||||
- Cancel a draft when going Back, then apply it to the original player. The
|
||||
subsequent Back still visits the club, proving the cursor did not advance.
|
||||
- Navigate elsewhere after Back, verify that Forward stays unavailable, and
|
||||
exercise both mouse side buttons.
|
||||
- Follow a preview's exact image-asset link and return in both directions.
|
||||
- Reopen the same OBW through MCP. Its unchanged filename/IDs must not preserve
|
||||
history or unapplied fields from the previous world.
|
||||
- Change native dropdowns by keyboard, cancel one with Escape, apply both
|
||||
languages and all three themes. Options alone leaves the world untouched.
|
||||
- Leave the window idle for three seconds. Its CPU budget is 20% of one logical
|
||||
core, intentionally generous for software-rendered CI. Continuous repainting
|
||||
fails this check. The observed local idle use was below 1% of one core.
|
||||
|
||||
The core tests also verify that edits, undo and save retain `world_generation`,
|
||||
while opening another world increments it. Navigation does not alter data or
|
||||
the editing undo cursor. Scroll positions are restored after rebuilding a view;
|
||||
history is limited to the last 200 visited views in the current world.
|
||||
|
||||
## Idle measurement
|
||||
|
||||
The former loop updated/rendered/presented continuously, with only a 10ms delay
|
||||
after each frame. The new loop waits for input or the next requested RmlUI timer.
|
||||
MCP state is checked every 400ms without repainting an unchanged screen. Async
|
||||
work completion, resize/expose, screenshot and automated-exit deadlines still
|
||||
wake the loop. Minimized windows do not render.
|
||||
|
||||
[Measured CPU time](idle-cpu-linux.json) uses six-second idle samples after the
|
||||
window settles, software OpenGL and two renderer threads. The synthetic demo
|
||||
changed from 95.3% to below the 0.01s sampling resolution; a private supplied world
|
||||
changed from 136.0% to 0.17% of **one logical core**. Multithreaded rendering can
|
||||
exceed 100% on this scale; these figures are not Task Manager's whole-machine
|
||||
percentage. This measurement is separate from import or image-processing work.
|
||||
|
||||
Native startup, screenshot deadlines, Unicode paths and failure reporting are
|
||||
covered by `tests/editor_startup_smoke.py`. Windows/WARP runtime measurements
|
||||
with private data are kept in the private repository. Build success on macOS
|
||||
does not establish native human acceptance there.
|
||||
|
After Width: | Height: | Size: 112 KiB |
|
After Width: | Height: | Size: 109 KiB |
|
After Width: | Height: | Size: 117 KiB |
|
After Width: | Height: | Size: 122 KiB |
|
After Width: | Height: | Size: 145 KiB |
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"environment": {
|
||||
"os": "Debian 13 x64",
|
||||
"renderer": "Mesa software OpenGL",
|
||||
"display": "Xvfb 1600x1000",
|
||||
"window": "1440x900",
|
||||
"software_renderer_threads": 2,
|
||||
"cpu_unit": "percent of one logical core; sums all editor threads"
|
||||
},
|
||||
"before_version": "0.5.3",
|
||||
"after_version": "0.5.4",
|
||||
"before": [
|
||||
{
|
||||
"case": "demo",
|
||||
"duration_s": 6.000090104993433,
|
||||
"cpu_s": 5.720000000000001,
|
||||
"one_core_percent": 95.33190168660411
|
||||
},
|
||||
{
|
||||
"case": "diamond",
|
||||
"duration_s": 6.000068283872679,
|
||||
"cpu_s": 8.16,
|
||||
"one_core_percent": 135.99845224983366
|
||||
}
|
||||
],
|
||||
"after": [
|
||||
{
|
||||
"case": "demo",
|
||||
"duration_s": 6.000068521825597,
|
||||
"cpu_s": 0.0,
|
||||
"one_core_percent": 0.0
|
||||
},
|
||||
{
|
||||
"case": "diamond",
|
||||
"duration_s": 6.000067526940256,
|
||||
"cpu_s": 0.010000000000000009,
|
||||
"one_core_percent": 0.1666647909394367
|
||||
}
|
||||
]
|
||||
}
|
||||
|
After Width: | Height: | Size: 114 KiB |
@@ -1,5 +1,14 @@
|
||||
<!-- SPDX-License-Identifier: GPL-3.0-only -->
|
||||
# OpenBMH v0.2.0
|
||||
# OpenBMH v0.2.1
|
||||
|
||||
Fixes the launcher startup on Windows Server / Remote Desktop and computers
|
||||
without an OpenGL 3.3 driver. The Windows RmlUI launcher uses Direct3D 11, with
|
||||
automatic WARP software fallback; Linux and macOS keep their existing OpenGL
|
||||
renderer. Launch errors use a native Windows dialog and a diagnostic log under
|
||||
`%LOCALAPPDATA%/OpenBMH/OpenBMH-startup.log`. Game rules, saves and OBW content
|
||||
remain compatible with 0.2.0.
|
||||
|
||||
## Version 0.2.0
|
||||
|
||||
Version 0.2 makes the original-style game independent of the original installation
|
||||
after import. It supports Bundesliga Manager Hattrick and Football Limited Classic
|
||||
@@ -52,7 +61,8 @@ See the [runtime and migration contract](../../formats/obw/runtime-0.2.md).
|
||||
The build pipeline produces Windows x64, Linux x64 and macOS ARM64 ZIPs and a
|
||||
matching source ZIP with pinned dependency sources and build information.
|
||||
Builds and automated tests do not replace native interactive acceptance.
|
||||
The launcher requires OpenGL 3.3 (macOS: 4.1). Linux requires the platform libraries
|
||||
The launcher uses Direct3D 11 with WARP fallback on Windows, OpenGL 3.3 on Linux,
|
||||
and OpenGL 4.1 on macOS. Linux requires the platform libraries
|
||||
described in [BUILDING](../../BUILDING.md), including GTK3 for its folder picker.
|
||||
The macOS executable is unsigned and is not a notarised application bundle.
|
||||
|
||||
|
||||
@@ -1,5 +1,48 @@
|
||||
<!-- SPDX-License-Identifier: GPL-3.0-only -->
|
||||
# OpenBMH Editor 0.5.2
|
||||
# OpenBMH Editor 0.5.4
|
||||
|
||||
Adds browser-style **Back / Forward** navigation. Right-click anywhere in the
|
||||
editor to open the context menu; Alt+Left/Right and mouse side buttons use the
|
||||
same history. Returning to a view restores its filters, selected record, sorting,
|
||||
page and scroll positions. Unapplied inspector entries retain their confirmation
|
||||
dialog. Opening another world clears navigation; it does not undo data edits.
|
||||
|
||||
The editor now updates and renders on demand, instead of redrawing the entire
|
||||
window continuously while idle. Input, timed caret/animation updates and external
|
||||
MCP changes remain active. Minimized windows do not render. This is especially
|
||||
useful with Windows software rendering over Remote Desktop.
|
||||
|
||||
Dropdowns follow the Modern Desktop pickers: rounded themed buttons and popup
|
||||
lists, equal label/option font sizes, a checkmark for the current selection and
|
||||
subtle hover surfaces. Escape closes the open list before its dialog. Options
|
||||
also gives **Copy connection** more space below the MCP URL. All three themes
|
||||
and both interface languages are supported.
|
||||
|
||||
[Native screenshots and verification](../../qa/editor-navigation/README.md)
|
||||
include the controls and navigation.
|
||||
|
||||
## Editor 0.5.3
|
||||
|
||||
Fixes the Windows graphical startup on machines without an OpenGL 3.3 driver,
|
||||
including Windows Server / Remote Desktop. The editor and game launcher use the
|
||||
pinned RmlUI Direct3D 11 renderer with automatic WARP software fallback. No
|
||||
additional graphics runtime download is needed on the supported Windows systems.
|
||||
Linux/macOS retain their existing OpenGL rendering.
|
||||
|
||||
Windows also builds WebP without an AVX requirement, avoiding illegal instructions
|
||||
when displaying imported club images on older CPUs or virtual machines.
|
||||
|
||||
Double-click a country to see its competitions, a league to see its clubs, and
|
||||
a club to see its players. Destination lists inherit the corresponding filters;
|
||||
unapplied inspector entries are protected by the existing confirmation dialog.
|
||||
|
||||
Windows startup failures now produce a native dialog and a log in
|
||||
`%LOCALAPPDATA%/OpenBMH/OpenBMHEditor-startup.log`. Console redirection is
|
||||
retained and headless/MCP errors remain nonmodal. Native GUI startup, screenshots,
|
||||
Unicode paths and the actual launcher are now tested on Windows Server 2022
|
||||
with WARP forced, in addition to the existing core/MCP tests.
|
||||
|
||||
## Editor 0.5.2
|
||||
|
||||
Adds **Regulations / Regelwerk**, a read-only view of game and league rules.
|
||||
Inspect promotion/relegation places and destinations, playoff conditions,
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
#include "launch/file_dialog.hpp"
|
||||
#include "launch/game_data.hpp"
|
||||
#include "launch/launcher.hpp"
|
||||
#include "launch/startup_error.hpp"
|
||||
#include "content/package.hpp"
|
||||
#include "version.hpp"
|
||||
#include "app/live_matchday_events.hpp"
|
||||
@@ -75,8 +76,7 @@ using namespace bmh;
|
||||
|
||||
// Why the game cannot start: a message box, and the same text on stderr.
|
||||
static void show_start_error(const std::string& text) {
|
||||
std::fprintf(stderr, "%s\n", text.c_str());
|
||||
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "OpenBMH", text.c_str(), nullptr);
|
||||
rml::report_start_error("OpenBMH", text);
|
||||
}
|
||||
|
||||
// Reattach the native editor when an in-game filename field takes focus. Cocoa
|
||||
@@ -91,26 +91,8 @@ static void focus_filename_input(SDL_Renderer* renderer) {
|
||||
SDL_StartTextInput();
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
// The game is a Windows GUI program (no console window on double-click). Started from a
|
||||
// console, it writes --version, --help and start errors there (kernel32 AttachConsole).
|
||||
extern "C" __declspec(dllimport) int __stdcall AttachConsole(unsigned long process_id);
|
||||
static void attach_parent_console() {
|
||||
// (an output redirected to a file or pipe stays there; a GUI program without one has no
|
||||
// valid stream, fileno < 0)
|
||||
const bool out_free = _fileno(stdout) < 0, err_free = _fileno(stderr) < 0;
|
||||
if ((out_free || err_free) && AttachConsole(static_cast<unsigned long>(-1))) { // ATTACH_PARENT_PROCESS
|
||||
std::FILE* f = nullptr;
|
||||
if (out_free) freopen_s(&f, "CONOUT$", "w", stdout);
|
||||
if (err_free) freopen_s(&f, "CONOUT$", "w", stderr);
|
||||
}
|
||||
}
|
||||
#else
|
||||
static void attach_parent_console() {}
|
||||
#endif
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
attach_parent_console();
|
||||
rml::attach_parent_console();
|
||||
const std::vector<std::string> args = launch::utf8_arguments(argc, argv); // (file names beyond the code page)
|
||||
fs::path data, save_directory;
|
||||
uint32_t seed = uint32_t(std::chrono::system_clock::now().time_since_epoch().count());
|
||||
|
||||
@@ -70,7 +70,14 @@ struct OriginalSynth::State {
|
||||
unsigned tempo_tick{};
|
||||
std::function<void(std::uint8_t, std::uint8_t)> register_observer;
|
||||
std::function<void(std::uint8_t)> sample_observer;
|
||||
std::function<void(const OriginalNoteEvent&)> note_observer;
|
||||
|
||||
void observe_note(unsigned track, std::uint8_t channel, std::uint8_t instrument, std::uint8_t pitch,
|
||||
std::uint8_t duration, std::uint8_t volume, bool sample) {
|
||||
if (dry || !note_observer) return;
|
||||
note_observer(OriginalNoteEvent{stats.bar, stats.step, std::uint8_t(track), channel, instrument, pitch,
|
||||
duration, volume, sample});
|
||||
}
|
||||
void write(std::uint8_t reg, std::uint8_t value) noexcept {
|
||||
if (dry) return;
|
||||
++stats.register_writes;
|
||||
@@ -313,13 +320,19 @@ struct OriginalSynth::State {
|
||||
const auto pitch = code < 128 ? code : song.parts[cursor++];
|
||||
const auto duration = song.parts[cursor++];
|
||||
if (index == 9 && code < 128) {
|
||||
if (!dma_effect) start_sample(pitch, false);
|
||||
if (!dma_effect) {
|
||||
observe_note(index, 0, 0, pitch, 0, 0, true);
|
||||
start_sample(pitch, false);
|
||||
}
|
||||
} else if (t.channel < 9) {
|
||||
auto& c = channels[t.channel];
|
||||
if (!c.reserved) {
|
||||
if (c.instrument != t.instrument) instrument(t.channel, t.instrument);
|
||||
c.duration = duration;
|
||||
note(t.channel, std::uint8_t(pitch + t.transpose), song_level(t.volume));
|
||||
const auto played = std::uint8_t(pitch + t.transpose);
|
||||
const auto volume = song_level(t.volume);
|
||||
observe_note(index, t.channel, t.instrument, played, duration, volume, false);
|
||||
note(t.channel, played, volume);
|
||||
}
|
||||
if (++t.channel == t.end) t.channel = t.first;
|
||||
} else { fail(); return; }
|
||||
@@ -464,5 +477,14 @@ void OriginalSynth::set_register_observer(std::function<void(std::uint8_t, std::
|
||||
void OriginalSynth::set_sample_observer(std::function<void(std::uint8_t)> f) {
|
||||
if (state_) state_->sample_observer = std::move(f);
|
||||
}
|
||||
void OriginalSynth::set_note_observer(std::function<void(const OriginalNoteEvent&)> f) {
|
||||
if (state_) state_->note_observer = std::move(f);
|
||||
}
|
||||
bool OriginalSynth::song_timing(unsigned song, OriginalSongTiming& timing) const noexcept {
|
||||
if (!state_ || song >= state_->songs.size()) return false;
|
||||
const auto& s = state_->songs[song];
|
||||
timing = {s.tempo, s.end, s.repeat};
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace openbmh::audio
|
||||
@@ -31,6 +31,21 @@ struct OriginalAudioStats {
|
||||
std::uint32_t bar{}, step{}, song = 255;
|
||||
bool playing{}, ambient{}, failed{};
|
||||
};
|
||||
// Timing of one song: one sequencer step every `tempo` IRQ0 ticks, 16 steps per
|
||||
// bar; after bar `end` playback continues at bar `repeat` (end == repeat: stop).
|
||||
struct OriginalSongTiming {
|
||||
std::uint16_t tempo{}, end{}, repeat{};
|
||||
};
|
||||
// One note the music sequencer actually started (offline tools such as the MIDI
|
||||
// export). `pitch` is the index into the OPL note table with the track transpose
|
||||
// applied; `duration` counts sequencer steps until key-off (255 = held until the
|
||||
// channel's next note); `level` is the OPL output level 0..63. Sample notes
|
||||
// (track 9) carry the sample slot in `pitch` and no channel, duration or level.
|
||||
struct OriginalNoteEvent {
|
||||
std::uint32_t bar{}, step{};
|
||||
std::uint8_t track{}, channel{}, instrument{}, pitch{}, duration{}, level{};
|
||||
bool sample{};
|
||||
};
|
||||
|
||||
// The Original MIDILINK sequencer and one Sound Blaster PCM channel. IRQ0 uses
|
||||
// PIT divisor0x199a. SONG/TRCK/PART, OPL instruments, SFX priorities/lifetimes,
|
||||
@@ -58,6 +73,9 @@ public:
|
||||
void tick() noexcept;
|
||||
void set_register_observer(std::function<void(std::uint8_t, std::uint8_t)> observer);
|
||||
void set_sample_observer(std::function<void(std::uint8_t)> observer);
|
||||
void set_note_observer(std::function<void(const OriginalNoteEvent&)> observer);
|
||||
// Timing of song 0..2; false before load() or for another index.
|
||||
bool song_timing(unsigned song, OriginalSongTiming& timing) const noexcept;
|
||||
private:
|
||||
struct State;
|
||||
std::unique_ptr<State> state_;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "formats/executable_layout.hpp"
|
||||
#include "container.hpp"
|
||||
#include "music_fallback.hpp"
|
||||
#include "original.hpp"
|
||||
#include "playback.hpp"
|
||||
#include "formats/le.hpp"
|
||||
|
||||
@@ -19,6 +20,7 @@
|
||||
#include <charconv>
|
||||
#include <filesystem>
|
||||
#include <span>
|
||||
#include <sstream>
|
||||
#include <string_view>
|
||||
|
||||
namespace {
|
||||
@@ -77,10 +79,279 @@ openbmh::audio::OriginalAssets load_original_assets(const std::filesystem::path&
|
||||
return assets;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MIDI export of the Original music (for remastering with other instruments).
|
||||
//
|
||||
// The sequencer runs offline exactly as in the game; the note observer records
|
||||
// every note it starts. Each of the 16 song tracks becomes one MIDI track on the
|
||||
// MIDI channel of the same number, so track 9, the sample (drum) track, lands on
|
||||
// General MIDI channel 10. One sequencer step is a sixteenth note (16 steps per
|
||||
// bar, 96 ticks per quarter); the tempo follows from the song's IRQ0 divisor.
|
||||
// OPL pitches are converted through the note table of the user's executable.
|
||||
// An optional map file assigns General MIDI programs and drum notes:
|
||||
// inst <instrument> <program 0..127>
|
||||
// sample <slot> <drum note 0..127>
|
||||
// A template listing the instruments and samples a song uses is written next to
|
||||
// the MIDI file (OUTPUT.map.txt) so the assignment can be edited and re-run.
|
||||
struct MidiNote {
|
||||
std::uint32_t start{}, end{};
|
||||
std::uint8_t note{}, velocity{}, instrument{};
|
||||
bool sample{};
|
||||
};
|
||||
// Program per instrument and drum note per sample slot; -1 = not assigned.
|
||||
struct MidiMap {
|
||||
std::array<int, 256> program;
|
||||
std::array<int, 256> drum;
|
||||
MidiMap() { program.fill(-1); drum.fill(-1); }
|
||||
};
|
||||
// Default General MIDI program from how an instrument is played: low lines become
|
||||
// a bass, instruments that often sound in chords strings, high lines a trumpet and
|
||||
// the remaining lines a brass section. Only a starting point for the editable map.
|
||||
int guess_program(double mean_note, double chord_share) {
|
||||
if (mean_note < 50.0) return 33; // Electric Bass (finger)
|
||||
if (chord_share > 0.25) return 48; // String Ensemble 1
|
||||
return mean_note >= 70.0 ? 56 : 61; // Trumpet for high lines, else Brass Section
|
||||
}
|
||||
// Default drum note from the sample itself: zero crossings per second separate
|
||||
// dark (kick), middle (snare, tom) and bright (hi-hat, cymbal) sounds; the
|
||||
// length separates closed from open or crash sounds.
|
||||
int guess_drum(const openbmh::audio::PcmSample& pcm) {
|
||||
if (pcm.mono.empty() || !pcm.sample_rate) return 38;
|
||||
std::size_t crossings = 0;
|
||||
for (std::size_t i = 1; i < pcm.mono.size(); ++i)
|
||||
crossings += (pcm.mono[i - 1] < 0) != (pcm.mono[i] < 0);
|
||||
const double seconds = double(pcm.mono.size()) / pcm.sample_rate;
|
||||
const double rate = crossings / seconds;
|
||||
if (rate < 1200.0) return seconds < 0.6 ? 36 : 41; // Bass Drum 1 / Low Floor Tom
|
||||
if (rate < 4000.0) return seconds < 0.4 ? 38 : 45; // Acoustic Snare / Low Tom
|
||||
if (seconds < 0.15) return 42; // Closed Hi-Hat
|
||||
return seconds < 0.5 ? 46 : 49; // Open Hi-Hat / Crash Cymbal 1
|
||||
}
|
||||
bool read_midi_map(const std::filesystem::path& path, MidiMap& map, std::string& error) {
|
||||
std::ifstream in(path);
|
||||
if (!in) { error = "cannot read MIDI map"; return false; }
|
||||
std::string kind;
|
||||
unsigned line = 0;
|
||||
for (std::string text; std::getline(in, text);) {
|
||||
++line;
|
||||
if (const auto hash = text.find('#'); hash != std::string::npos) text.resize(hash);
|
||||
std::istringstream fields(text);
|
||||
int index = -1, value = -1;
|
||||
if (!(fields >> kind)) continue;
|
||||
if (!(fields >> index >> value) || index < 0 || index > 255 || value < 0 || value > 127 ||
|
||||
(kind != "inst" && kind != "sample")) {
|
||||
error = "invalid MIDI map line " + std::to_string(line); return false;
|
||||
}
|
||||
(kind == "inst" ? map.program : map.drum)[std::size_t(index)] = value;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool write_midi(const std::filesystem::path& path, const std::array<std::vector<MidiNote>, 16>& tracks,
|
||||
const MidiMap& map, std::uint32_t usec_per_quarter, std::uint32_t loop_start,
|
||||
std::uint32_t loop_end, std::string& error) {
|
||||
using Track = std::vector<std::uint8_t>;
|
||||
const auto vlq = [](Track& t, std::uint32_t value) {
|
||||
std::uint8_t bytes[5]; int n = 0;
|
||||
do { bytes[n++] = std::uint8_t(value & 0x7f); value >>= 7; } while (value);
|
||||
while (n--) t.push_back(std::uint8_t(bytes[n] | (n ? 0x80 : 0)));
|
||||
};
|
||||
const auto meta_text = [&vlq](Track& t, std::uint32_t delta, std::uint8_t type, const std::string& text) {
|
||||
vlq(t, delta); t.push_back(0xff); t.push_back(type); vlq(t, std::uint32_t(text.size()));
|
||||
t.insert(t.end(), text.begin(), text.end());
|
||||
};
|
||||
std::vector<Track> chunks;
|
||||
{ // Conductor track: tempo, 4/4, loop markers.
|
||||
Track t;
|
||||
t.insert(t.end(), {0x00, 0xff, 0x51, 0x03, std::uint8_t(usec_per_quarter >> 16),
|
||||
std::uint8_t(usec_per_quarter >> 8), std::uint8_t(usec_per_quarter)});
|
||||
t.insert(t.end(), {0x00, 0xff, 0x58, 0x04, 0x04, 0x02, 0x18, 0x08});
|
||||
std::uint32_t now = 0;
|
||||
if (loop_start != loop_end) {
|
||||
meta_text(t, loop_start, 0x06, "loop start"); now = loop_start;
|
||||
meta_text(t, loop_end - now, 0x06, "loop end"); now = loop_end;
|
||||
}
|
||||
t.insert(t.end(), {0x00, 0xff, 0x2f, 0x00});
|
||||
chunks.push_back(std::move(t));
|
||||
}
|
||||
for (unsigned index = 0; index < tracks.size(); ++index) {
|
||||
const auto& notes = tracks[index];
|
||||
if (notes.empty()) continue;
|
||||
const std::uint8_t channel = std::uint8_t(index);
|
||||
struct Event { std::uint32_t time; int order; std::uint8_t status, a, b; bool two; };
|
||||
std::vector<Event> events;
|
||||
int last_program = -1;
|
||||
for (const auto& n : notes) {
|
||||
if (!n.sample) {
|
||||
const int program = map.program[n.instrument];
|
||||
if (program != last_program) {
|
||||
events.push_back({n.start, 1, std::uint8_t(0xc0 | channel), std::uint8_t(program), 0, false});
|
||||
last_program = program;
|
||||
}
|
||||
}
|
||||
// Sample notes carry their slot in `instrument`; the map names the drum.
|
||||
const auto key = n.sample ? std::uint8_t(map.drum[n.instrument]) : n.note;
|
||||
events.push_back({n.start, 2, std::uint8_t(0x90 | channel), key, n.velocity, true});
|
||||
events.push_back({n.end, 0, std::uint8_t(0x80 | channel), key, 0, true});
|
||||
}
|
||||
// Note-offs before program changes before note-ons at the same time.
|
||||
std::stable_sort(events.begin(), events.end(), [](const Event& l, const Event& r) {
|
||||
return l.time != r.time ? l.time < r.time : l.order < r.order;
|
||||
});
|
||||
Track t;
|
||||
meta_text(t, 0, 0x03, index == 9 ? "track 9 (samples)" : "track " + std::to_string(index));
|
||||
std::uint32_t now = 0;
|
||||
for (const auto& e : events) {
|
||||
vlq(t, e.time - now); now = e.time;
|
||||
t.push_back(e.status); t.push_back(e.a);
|
||||
if (e.two) t.push_back(e.b);
|
||||
}
|
||||
t.insert(t.end(), {0x00, 0xff, 0x2f, 0x00});
|
||||
chunks.push_back(std::move(t));
|
||||
}
|
||||
std::ofstream out(path, std::ios::binary);
|
||||
if (!out) { error = "cannot create MIDI output"; return false; }
|
||||
const auto put16 = [&out](unsigned v) { const char b[] = {char(v >> 8), char(v)}; out.write(b, 2); };
|
||||
const auto put32 = [&out](std::uint32_t v) {
|
||||
const char b[] = {char(v >> 24), char(v >> 16), char(v >> 8), char(v)}; out.write(b, 4);
|
||||
};
|
||||
out.write("MThd", 4); put32(6); put16(1); put16(unsigned(chunks.size())); put16(96);
|
||||
for (const auto& t : chunks) {
|
||||
out.write("MTrk", 4); put32(std::uint32_t(t.size()));
|
||||
out.write(reinterpret_cast<const char*>(t.data()), std::streamsize(t.size()));
|
||||
}
|
||||
if (!out) { error = "failed while writing MIDI output"; return false; }
|
||||
return true;
|
||||
}
|
||||
int export_midi(openbmh::audio::OriginalAssets assets, unsigned song, const std::filesystem::path& output,
|
||||
unsigned loops, const std::filesystem::path& map_path) {
|
||||
using namespace openbmh::audio;
|
||||
MidiMap map;
|
||||
std::string error;
|
||||
if (!map_path.empty() && !read_midi_map(map_path, map, error)) { std::cerr << error << '\n'; return 1; }
|
||||
// MIDI note of every entry of the OPL note table: F-number and block give the
|
||||
// frequency (49716 Hz OPL clock), rounded to the nearest equal-tempered note.
|
||||
std::array<std::uint8_t, 96> midi_note{};
|
||||
for (unsigned i = 0; i < midi_note.size(); ++i) {
|
||||
const auto f = assets.tables.frequencies[i];
|
||||
const double hz = double(f & 0x3ff) * 49716.0 / std::pow(2.0, 20 - ((f >> 10) & 7));
|
||||
midi_note[i] = std::uint8_t(std::clamp(std::lround(69.0 + 12.0 * std::log2(hz / 440.0)), 0L, 127L));
|
||||
}
|
||||
// The song's own bank, kept for analysing its drum samples after the run.
|
||||
const std::vector<std::uint8_t> bank = assets.containers.at(song);
|
||||
OriginalSynth synth;
|
||||
if (!synth.load(std::move(assets), 22050, error)) {
|
||||
std::cerr << "Original audio rejected: " << error << '\n'; return 1;
|
||||
}
|
||||
OriginalSongTiming timing;
|
||||
if (!synth.song_timing(song, timing)) { std::cerr << "unknown song\n"; return 1; }
|
||||
constexpr std::uint32_t kTicksPerStep = 24; // 96 per quarter, a step is a sixteenth
|
||||
std::array<std::vector<MidiNote>, 16> tracks;
|
||||
// Last note per OPL channel: a new note on the channel ends the previous one.
|
||||
std::array<std::pair<int, std::size_t>, 9> sounding;
|
||||
sounding.fill({-1, 0});
|
||||
std::array<bool, 256> used_instrument{}, used_sample{};
|
||||
// The export ends after the first pass plus (loops - 1) passes of the loop
|
||||
// section; a song without a loop (end == repeat) ends after its last bar.
|
||||
const bool looping = timing.end != timing.repeat;
|
||||
const std::uint64_t last_step = std::uint64_t(timing.end) * 16 +
|
||||
(looping ? std::uint64_t(loops - 1) * (timing.end - timing.repeat) * 16 : 0);
|
||||
std::uint64_t tick = 0;
|
||||
synth.set_note_observer([&](const OriginalNoteEvent& e) {
|
||||
if (tick / timing.tempo >= last_step) return;
|
||||
const auto start = std::uint32_t(tick / timing.tempo) * kTicksPerStep;
|
||||
if (e.sample) {
|
||||
used_sample[e.pitch] = true;
|
||||
tracks[e.track].push_back({start, start + kTicksPerStep / 2, 0, 100, e.pitch, true});
|
||||
return;
|
||||
}
|
||||
used_instrument[e.instrument] = true;
|
||||
if (auto [track, index] = sounding[e.channel]; track >= 0) {
|
||||
auto& previous = tracks[std::size_t(track)][index];
|
||||
previous.end = std::min(previous.end, start);
|
||||
if (previous.end <= previous.start) previous.end = previous.start + 1;
|
||||
}
|
||||
// duration 0 releases in the step it starts; 255 holds until the next note.
|
||||
const std::uint32_t length = e.duration == 255 ? std::numeric_limits<std::uint32_t>::max() / 2
|
||||
: std::max<std::uint32_t>(e.duration * kTicksPerStep, kTicksPerStep / 4);
|
||||
tracks[e.track].push_back({start, start + length, midi_note[e.pitch],
|
||||
std::uint8_t(std::min(127, 1 + e.level * 2)), e.instrument, false});
|
||||
sounding[e.channel] = {int(e.track), tracks[e.track].size() - 1};
|
||||
});
|
||||
if (!synth.command(std::uint8_t(song))) { std::cerr << "Original command rejected\n"; return 1; }
|
||||
std::uint64_t steps = 0;
|
||||
for (; tick / timing.tempo < last_step; ++tick) {
|
||||
synth.tick();
|
||||
const auto stats = synth.stats();
|
||||
if (stats.failed) { std::cerr << "Original decoder failed during export\n"; return 1; }
|
||||
steps = tick / timing.tempo + 1;
|
||||
if (!stats.playing) break;
|
||||
}
|
||||
const auto song_end = std::uint32_t(std::min(steps, last_step)) * kTicksPerStep;
|
||||
const unsigned completed_loops = looping ? loops : 1;
|
||||
for (auto& notes : tracks)
|
||||
for (auto& n : notes) n.end = std::min(n.end, song_end);
|
||||
// One step lasts tempo * 6554 / 1193180 s; a quarter is four steps.
|
||||
const auto usec = std::uint32_t(std::lround(4.0 * timing.tempo * 6554.0 / 1193180.0 * 1e6));
|
||||
const std::uint32_t loop_start = timing.repeat * 16u * kTicksPerStep;
|
||||
const std::uint32_t loop_end = timing.end == timing.repeat ? loop_start : timing.end * 16u * kTicksPerStep;
|
||||
// Defaults for everything the map file leaves open (§ guess_program/guess_drum):
|
||||
// per instrument the mean note and the share of notes that start together with
|
||||
// another note of the same instrument (chords); per sample its sound.
|
||||
struct Usage { std::size_t notes{}, chord{}; double sum{}; int low{127}, high{0}; };
|
||||
std::array<Usage, 256> usage{};
|
||||
for (const auto& notes : tracks)
|
||||
for (std::size_t i = 0; i < notes.size(); ++i) {
|
||||
const auto& n = notes[i];
|
||||
if (n.sample) continue;
|
||||
auto& u = usage[n.instrument];
|
||||
++u.notes; u.sum += n.note; u.low = std::min<int>(u.low, n.note); u.high = std::max<int>(u.high, n.note);
|
||||
}
|
||||
for (const auto& a : tracks) for (const auto& n : a) {
|
||||
if (n.sample) continue;
|
||||
bool together = false;
|
||||
for (const auto& b : tracks) for (const auto& m : b)
|
||||
if (&m != &n && !m.sample && m.instrument == n.instrument && m.start == n.start) { together = true; break; }
|
||||
if (together) ++usage[n.instrument].chord;
|
||||
}
|
||||
Container container;
|
||||
std::span<const std::uint8_t> samp;
|
||||
if (parse_container(bank, container, error))
|
||||
for (const auto& c : container.chunks)
|
||||
if (c.id == "SAMP") samp = std::span<const std::uint8_t>(bank).subspan(c.payload_offset, c.payload_size);
|
||||
for (unsigned i = 0; i < 256; ++i) {
|
||||
if (used_instrument[i] && map.program[i] < 0) {
|
||||
const auto& u = usage[i];
|
||||
map.program[i] = guess_program(u.notes ? u.sum / u.notes : 60.0, u.notes ? double(u.chord) / u.notes : 0.0);
|
||||
}
|
||||
if (used_sample[i] && map.drum[i] < 0) {
|
||||
PcmSample pcm;
|
||||
map.drum[i] = !samp.empty() && decode_sample(samp, i, pcm, error) ? guess_drum(pcm) : 38;
|
||||
}
|
||||
}
|
||||
if (!write_midi(output, tracks, map, usec, loop_start, loop_end, error)) { std::cerr << error << '\n'; return 1; }
|
||||
auto template_path = output;
|
||||
template_path += ".map.txt";
|
||||
std::ofstream list(template_path);
|
||||
list << "# OpenBMH MIDI map for song " << song << ": edit and pass with --map FILE\n"
|
||||
<< "# inst <instrument> <General MIDI program 0..127>, sample <slot> <drum note>\n";
|
||||
for (unsigned i = 0; i < 256; ++i) if (used_instrument[i]) {
|
||||
const auto& u = usage[i];
|
||||
list << "inst " << i << ' ' << map.program[i] << " # " << u.notes << " notes, range " << u.low << '-'
|
||||
<< u.high << ", chords " << (u.notes ? 100 * u.chord / u.notes : 0) << "%\n";
|
||||
}
|
||||
for (unsigned i = 0; i < 256; ++i) if (used_sample[i]) list << "sample " << i << ' ' << map.drum[i] << '\n';
|
||||
std::size_t notes = 0;
|
||||
for (const auto& t : tracks) notes += t.size();
|
||||
std::cout << "exported Original song=" << song << " midi notes=" << notes << " tempo_us=" << usec
|
||||
<< " loops=" << completed_loops << " map=" << template_path.string() << '\n';
|
||||
return 0;
|
||||
}
|
||||
|
||||
int original_driver(int argc, char** argv) {
|
||||
using namespace openbmh::audio;
|
||||
const auto usage = [] {
|
||||
std::cerr << "usage: openbmh_sound --original DATA_DIR --export-song 0..2 OUTPUT.wav [--seconds 1..600] [--loops 1..16]\n"
|
||||
" openbmh_sound --original DATA_DIR --export-midi 0..2 OUTPUT.mid [--loops 1..16] [--map FILE]\n"
|
||||
" openbmh_sound --original DATA_DIR --export-id 10..22 OUTPUT.wav [--seconds 1..600]\n"
|
||||
" openbmh_sound --original DATA_DIR --play-id ID [--seconds 1..600]\n"
|
||||
" openbmh_sound --original DATA_DIR --play-all [--seconds 1..600]\n";
|
||||
@@ -88,6 +359,24 @@ int original_driver(int argc, char** argv) {
|
||||
};
|
||||
if (argc < 4) return usage();
|
||||
const std::string action = argv[3];
|
||||
if (action == "--export-midi") {
|
||||
unsigned song = 0, loops = 1;
|
||||
std::filesystem::path map;
|
||||
if (argc < 6 || !bounded_number(argv[4], 0, 2, song)) return usage();
|
||||
for (int at = 6; at < argc; at += 2) {
|
||||
if (at + 1 >= argc) return usage();
|
||||
const std::string option = argv[at];
|
||||
if (option == "--loops") {
|
||||
if (!bounded_number(argv[at + 1], 1, 16, loops)) return usage();
|
||||
} else if (option == "--map") map = argv[at + 1];
|
||||
else return usage();
|
||||
}
|
||||
try {
|
||||
return export_midi(load_original_assets(argv[2]), song, argv[5], loops, map);
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << "Original audio input: " << error.what() << '\n'; return 1;
|
||||
}
|
||||
}
|
||||
const bool song = action == "--export-song";
|
||||
const bool export_id = action == "--export-id";
|
||||
const bool play = action == "--play-id";
|
||||
@@ -180,6 +469,7 @@ int main(int argc, char** argv) {
|
||||
if (argc < 2) {
|
||||
std::cerr << "usage: openbmh_sound <container-file> [--play-test-tone | --play-sample INDEX | --export-sample INDEX OUTPUT.wav | --play-id ID | --export-id ID OUTPUT.wav]\n"
|
||||
" openbmh_sound --original DATA_DIR --export-song 0..2 OUTPUT.wav [--seconds N] [--loops N]\n"
|
||||
" openbmh_sound --original DATA_DIR --export-midi 0..2 OUTPUT.mid [--loops N] [--map FILE]\n"
|
||||
" openbmh_sound --original DATA_DIR --export-id 10..22 OUTPUT.wav [--seconds N]\n"
|
||||
" openbmh_sound --original DATA_DIR --play-id ID | --play-all [--seconds N]\n"
|
||||
" openbmh_sound --play-cue NAME | --export-cue NAME OUTPUT.wav\n"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-only
|
||||
include(FetchContent)
|
||||
set(OPENBMH_EDITOR_VERSION "0.5.2")
|
||||
set(OPENBMH_EDITOR_VERSION "0.5.4")
|
||||
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
|
||||
@@ -21,6 +21,9 @@ endforeach()
|
||||
set(SDL2IMAGE_PNG ON CACHE BOOL "" FORCE)
|
||||
set(SDL2IMAGE_JPG ON CACHE BOOL "" FORCE)
|
||||
set(SDL2IMAGE_WEBP ON CACHE BOOL "" FORCE)
|
||||
if(MSVC)
|
||||
set(WEBP_ENABLE_SIMD ON CACHE BOOL "Use WebP's runtime CPU selection" FORCE)
|
||||
endif()
|
||||
set(SDL2IMAGE_PNG_SAVE OFF CACHE BOOL "" FORCE)
|
||||
set(SDL2IMAGE_JPG_SAVE OFF CACHE BOOL "" FORCE)
|
||||
FetchContent_Declare(editor_images GIT_REPOSITORY https://github.com/libsdl-org/SDL_image.git
|
||||
@@ -33,6 +36,20 @@ set(PUGIXML_BUILD_SHARED_AND_STATIC_LIBS OFF CACHE BOOL "" FORCE)
|
||||
FetchContent_Declare(editor_xml GIT_REPOSITORY https://github.com/zeux/pugixml.git
|
||||
GIT_TAG v1.15 GIT_SHALLOW TRUE)
|
||||
FetchContent_MakeAvailable(editor_json editor_http editor_images editor_svg editor_xml)
|
||||
if(MSVC)
|
||||
# The pinned WebP CMake propagates /arch:AVX into SSE2 source files, even
|
||||
# though their runtime gate only checks SSE2. Compile its explicit SSE
|
||||
# intrinsics at the default x64 baseline, preserving CPU dispatch and all
|
||||
# upstream sources. Disabling SIMD is broken in this pinned MSVC build.
|
||||
get_target_property(webp_source_directory webpdsp SOURCE_DIR)
|
||||
get_target_property(webp_dsp_sources webpdsp SOURCES)
|
||||
foreach(source IN LISTS webp_dsp_sources)
|
||||
if(source MATCHES "_sse(2|41)\\.c$")
|
||||
set_source_files_properties("${source}" DIRECTORY "${webp_source_directory}"
|
||||
PROPERTIES COMPILE_FLAGS "")
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
file(WRITE "${CMAKE_BINARY_DIR}/editor-dependencies.json" "{\n")
|
||||
foreach(component editor_json editor_http editor_images editor_svg editor_xml)
|
||||
file(TO_CMAKE_PATH "${${component}_SOURCE_DIR}" component_path)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "editor/ui.hpp"
|
||||
#include "editor/version.hpp"
|
||||
#include "launch/startup_error.hpp"
|
||||
#include <SDL.h>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
@@ -14,7 +15,14 @@ void stop(int) { stopped = true; }
|
||||
} // namespace
|
||||
int main(int argc, char **argv) {
|
||||
using namespace bmh::editor;
|
||||
bmh::rml::attach_parent_console();
|
||||
std::string language = "de";
|
||||
bool graphical = true;
|
||||
for (int i = 1; i < argc; ++i)
|
||||
if (std::string_view(argv[i]) == "--headless" || std::string_view(argv[i]) == "--serve" ||
|
||||
std::string_view(argv[i]) == "--stdio-mcp" || std::string_view(argv[i]) == "--version" ||
|
||||
std::string_view(argv[i]) == "--help")
|
||||
graphical = false;
|
||||
try {
|
||||
bool headless = false, serve = false, stdio = false, demo = false, blank = false, validate = false,
|
||||
print = false;
|
||||
@@ -153,10 +161,14 @@ int main(int argc, char **argv) {
|
||||
}
|
||||
return has_errors ? 2 : 0;
|
||||
} catch (const Error &e) {
|
||||
std::cerr << Json{{"error", e.code}, {"message", tr(language, e.code)}, {"details", e.details}}.dump() << '\n';
|
||||
const auto message =
|
||||
Json{{"error", e.code}, {"message", tr(language, e.code)}, {"details", e.details}}.dump();
|
||||
std::cerr << message << '\n';
|
||||
if (graphical)
|
||||
bmh::rml::report_start_error("OpenBMHEditor", tr(language, e.code));
|
||||
return 1;
|
||||
} catch (const std::exception &e) {
|
||||
std::cerr << tr(language, "error") << ": " << e.what() << '\n';
|
||||
bmh::rml::report_start_error("OpenBMHEditor", tr(language, "error") + ": " + e.what(), graphical);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,9 @@
|
||||
#include <map>
|
||||
#include <random>
|
||||
#ifdef _WIN32
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <sys/stat.h>
|
||||
@@ -89,6 +91,14 @@ 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"}},
|
||||
{"navigation_back", {"Zurück", "Back"}},
|
||||
{"navigation_forward", {"Vorwärts", "Forward"}},
|
||||
{"navigation_left", {"Links", "Left"}},
|
||||
{"navigation_right", {"Rechts", "Right"}},
|
||||
{"drill_nations", {"Doppelklick: Ligen anzeigen", "Double-click to view leagues"}},
|
||||
{"drill_competitions",
|
||||
{"Doppelklick auf eine Liga: Vereine anzeigen", "Double-click a league to view clubs"}},
|
||||
{"drill_clubs", {"Doppelklick: Spieler anzeigen", "Double-click to view players"}},
|
||||
{"regulations", {"Regelwerk", "Regulations"}},
|
||||
{"regulations_title", {"Spiel- & Ligaregeln", "Game & league rules"}},
|
||||
{"subtitle_regulations",
|
||||
@@ -268,8 +278,7 @@ 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 konnte nicht initialisiert werden.", "Graphics initialization failed."}},
|
||||
{"ui_assets_missing",
|
||||
{"Editor-Oberfläche fehlt. Bitte das vollständige Paket entpacken.",
|
||||
"Editor interface files are missing. Please extract the complete "
|
||||
@@ -410,6 +419,8 @@ std::string tr(const std::string &language, const std::string &key) {
|
||||
{"amateur", {"Amateur", "Amateur"}},
|
||||
{"image_import", {"Bild importieren", "Import image"}},
|
||||
{"image_edit", {"Bild bearbeiten", "Edit image"}},
|
||||
{"image_view", {"Bildvorschau", "Image preview"}},
|
||||
{"view_asset", {"Zum Asset", "View asset"}},
|
||||
{"image_export", {"PNG exportieren", "Export PNG"}},
|
||||
{"angle", {"Drehwinkel", "Rotation"}},
|
||||
{"flip_x", {"Horizontal spiegeln", "Flip horizontally"}},
|
||||
|
||||
@@ -59,6 +59,7 @@ Json Session::info() const {
|
||||
Json result = world_ ? world_->statistics() : Json{{"title", ""}, {"counts", Json::object()}};
|
||||
result["loaded"] = bool(world_);
|
||||
result["revision"] = revision_;
|
||||
result["world_generation"] = world_generation_;
|
||||
result["dirty"] = dirty();
|
||||
result["can_undo"] = cursor_ > 0;
|
||||
result["can_redo"] = cursor_ < history_.size();
|
||||
@@ -67,6 +68,7 @@ Json Session::info() const {
|
||||
}
|
||||
void Session::replace(World value) {
|
||||
world_ = std::make_unique<World>(std::move(value));
|
||||
++world_generation_;
|
||||
history_.clear();
|
||||
cursor_ = 0;
|
||||
++revision_;
|
||||
|
||||
@@ -30,7 +30,7 @@ class Session {
|
||||
std::unique_ptr<World> world_;
|
||||
std::vector<Frame> history_;
|
||||
size_t cursor_ = 0;
|
||||
uint64_t revision_ = 0, state_ = 0, next_state_ = 1, saved_state_ = 0;
|
||||
uint64_t revision_ = 0, world_generation_ = 0, state_ = 0, next_state_ = 1, saved_state_ = 0;
|
||||
fs::path saved_path_;
|
||||
fs::file_time_type saved_time_{};
|
||||
uint64_t saved_size_ = 0;
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
#include "editor/images.hpp"
|
||||
#include "editor/version.hpp"
|
||||
#include "launch/rml_path.hpp"
|
||||
#include "launch/rml_video.hpp"
|
||||
#include <RmlUi/Core.h>
|
||||
#include <RmlUi/Core/Elements/ElementFormControl.h>
|
||||
#include <RmlUi/Core/Elements/ElementFormControlInput.h>
|
||||
#include <RmlUi/Core/Elements/ElementFormControlSelect.h>
|
||||
#include <RmlUi_Platform_SDL.h>
|
||||
#include <RmlUi_Renderer_GL3.h>
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
@@ -31,61 +32,20 @@ std::string button(const std::string &action, const std::string &label, const st
|
||||
return "<button data-action=\"" + escaped(action) + "\" class=\"" + css + "\" " + attributes + ">" +
|
||||
escaped(label) + "</button>";
|
||||
}
|
||||
struct Video {
|
||||
SDL_Window *window = nullptr;
|
||||
SDL_GLContext gl = nullptr;
|
||||
bool loader = false;
|
||||
Video() {
|
||||
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER) != 0)
|
||||
throw Error("video_failed");
|
||||
SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
|
||||
#ifdef __APPLE__
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
|
||||
#else
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
|
||||
#endif
|
||||
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
|
||||
window =
|
||||
SDL_CreateWindow("OpenBMH Editor", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1440, 900,
|
||||
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_HIDDEN);
|
||||
if (!window)
|
||||
throw Error("video_failed");
|
||||
SDL_SetWindowMinimumSize(window, 1080, 720);
|
||||
gl = SDL_GL_CreateContext(window);
|
||||
if (!gl)
|
||||
throw Error("video_failed");
|
||||
SDL_GL_MakeCurrent(window, gl);
|
||||
SDL_GL_SetSwapInterval(1);
|
||||
std::string error;
|
||||
if (!RmlGL3::Initialize(&error))
|
||||
throw Error("video_failed", {{"detail", error}});
|
||||
loader = true;
|
||||
SDL_StartTextInput();
|
||||
}
|
||||
~Video() {
|
||||
if (loader)
|
||||
RmlGL3::Shutdown();
|
||||
if (gl)
|
||||
SDL_GL_DeleteContext(gl);
|
||||
if (window)
|
||||
SDL_DestroyWindow(window);
|
||||
SDL_Quit();
|
||||
}
|
||||
};
|
||||
class Renderer final : public RenderInterface_GL3 {
|
||||
class Renderer final : public bmh::rml::Renderer {
|
||||
public:
|
||||
Session &session;
|
||||
std::map<std::string, std::pair<std::string, std::string>> memory;
|
||||
std::map<std::string, std::string> logical;
|
||||
std::map<std::string, std::string> asset_tokens;
|
||||
uint64_t serial = 0;
|
||||
explicit Renderer(Session &s) : session(s) {}
|
||||
Renderer(Session &s, bmh::rml::Video &video) : bmh::rml::Renderer(video), session(s) {}
|
||||
std::string asset(const std::string &key) {
|
||||
if (auto found = asset_tokens.find(key); found != asset_tokens.end())
|
||||
return found->second;
|
||||
auto token = "world-image-" + std::to_string(serial++) + ".png";
|
||||
logical[token] = key;
|
||||
asset_tokens[key] = token;
|
||||
return token;
|
||||
}
|
||||
std::string bytes(std::string data, const std::string &extension) {
|
||||
@@ -93,15 +53,28 @@ class Renderer final : public RenderInterface_GL3 {
|
||||
memory[token] = {std::move(data), extension};
|
||||
return token;
|
||||
}
|
||||
static constexpr const char *view_source = "readonly-image-preview.png";
|
||||
void release_view() {
|
||||
for (const auto &source : Rml::GetTextureSourceList())
|
||||
if (utf8(path(source).filename()) == view_source)
|
||||
Rml::ReleaseTexture(source, this);
|
||||
memory.erase(view_source);
|
||||
}
|
||||
std::string view(std::string data) {
|
||||
release_view();
|
||||
memory[view_source] = {std::move(data), ".png"};
|
||||
return view_source;
|
||||
}
|
||||
void clear() {
|
||||
Rml::ReleaseTextures(this);
|
||||
logical.clear();
|
||||
asset_tokens.clear();
|
||||
memory.clear();
|
||||
}
|
||||
Rml::TextureHandle LoadTexture(Rml::Vector2i &dimensions, const Rml::String &source) override {
|
||||
const auto token = utf8(path(source).filename());
|
||||
if (!memory.contains(token) && !logical.contains(token))
|
||||
return RenderInterface_GL3::LoadTexture(dimensions, source);
|
||||
return bmh::rml::Renderer::LoadTexture(dimensions, source);
|
||||
try {
|
||||
auto value = memory.contains(token) ? memory.at(token) : session.asset_bytes(logical.at(token));
|
||||
auto raster = images::decode(value.first, value.second, token.starts_with("icon-") ? 64 : 512);
|
||||
@@ -129,7 +102,7 @@ class EditorUi final : public Rml::EventListener {
|
||||
Options &options_;
|
||||
McpServer &server_;
|
||||
UiConfig config_;
|
||||
Video video_;
|
||||
bmh::rml::Video video_{"OpenBMH Editor", 1440, 900, 1080, 720};
|
||||
bmh::rml::AssetFiles files_;
|
||||
SystemInterface_SDL system_{video_.window};
|
||||
Renderer renderer_;
|
||||
@@ -137,8 +110,9 @@ class EditorUi final : public Rml::EventListener {
|
||||
Rml::Context *context_ = nullptr;
|
||||
Rml::ElementDocument *doc_ = nullptr;
|
||||
bool initialized_ = false, closed_ = false, busy_ = false, modal_ = false;
|
||||
bool roster24_ = false, show_source_ = false, needs_refresh_ = true;
|
||||
bool roster24_ = false, show_source_ = false, needs_refresh_ = true, redraw_ = true;
|
||||
uint64_t revision_ = uint64_t(-1);
|
||||
uint64_t world_generation_ = uint64_t(-1);
|
||||
Json info_, selected_ = Json::object(), listed_ = Json::array();
|
||||
std::map<std::string, Json> lookup_;
|
||||
std::string page_ = "overview", selected_id_, search_, nation_, league_, team_, sort_ = "name", remembered_;
|
||||
@@ -151,6 +125,27 @@ class EditorUi final : public Rml::EventListener {
|
||||
std::string regulation_id_, game_rule_id_;
|
||||
int offset_ = 0;
|
||||
size_t total_ = 0;
|
||||
struct Location {
|
||||
std::string page, selected, search, nation, league, team, sort;
|
||||
bool descending, roster24, show_source;
|
||||
int offset;
|
||||
std::string comparison_table, comparison_set, comparison_sort;
|
||||
bool comparison_descending, regulations_game, regulations_source;
|
||||
std::string regulation_id, game_rule_id;
|
||||
bool operator==(const Location &) const = default;
|
||||
};
|
||||
struct ScrollPosition {
|
||||
std::string selector;
|
||||
float left, top;
|
||||
};
|
||||
struct Visit {
|
||||
Location location;
|
||||
std::vector<ScrollPosition> scroll;
|
||||
};
|
||||
std::vector<Visit> navigation_;
|
||||
size_t navigation_index_ = 0;
|
||||
std::optional<std::vector<ScrollPosition>> restore_scroll_;
|
||||
bool history_menu_open_ = false;
|
||||
struct Field {
|
||||
std::string id, pointer, kind, initial;
|
||||
Json original;
|
||||
@@ -163,7 +158,7 @@ class EditorUi final : public Rml::EventListener {
|
||||
std::string image_bytes_, image_extension_, image_file_, image_key_, image_source_key_;
|
||||
Json image_target_, image_recipe_;
|
||||
double drag_x_ = 0, drag_y_ = 0;
|
||||
bool dragging_ = false;
|
||||
bool dragging_ = false, image_view_open_ = false;
|
||||
std::chrono::steady_clock::time_point start_ = std::chrono::steady_clock::now();
|
||||
std::string t(const std::string &key) const { return tr(options_.language, key); }
|
||||
Rml::Element *el(const std::string &id) const {
|
||||
@@ -172,7 +167,20 @@ class EditorUi final : public Rml::EventListener {
|
||||
throw std::runtime_error("Missing editor element: " + id);
|
||||
return value;
|
||||
}
|
||||
void html(const std::string &id, const std::string &value) { el(id)->SetInnerRML(value); }
|
||||
void html(const std::string &id, const std::string &value) {
|
||||
auto *container = el(id);
|
||||
container->SetInnerRML(value);
|
||||
Rml::ElementList controls;
|
||||
container->QuerySelectorAll(controls, "select");
|
||||
for (auto *element : controls)
|
||||
if (auto *select = dynamic_cast<Rml::ElementFormControlSelect *>(element))
|
||||
for (int i = 0; i < select->GetNumOptions(); ++i) {
|
||||
auto *option = select->GetOption(i);
|
||||
option->SetInnerRML("<span class=\"option-check\"></span><span class=\"option-label\">" +
|
||||
option->GetInnerRML() + "</span>");
|
||||
}
|
||||
redraw_ = true;
|
||||
}
|
||||
void label(const std::string &id, const std::string &value) { html(id, escaped(value)); }
|
||||
std::string value(const std::string &id) const {
|
||||
auto *field = dynamic_cast<Rml::ElementFormControl *>(el(id));
|
||||
@@ -183,6 +191,136 @@ class EditorUi final : public Rml::EventListener {
|
||||
field->SetValue(value);
|
||||
}
|
||||
std::string table() const { return page_ == "roster" ? "players" : page_; }
|
||||
Location location() const {
|
||||
return {page_,
|
||||
selected_id_,
|
||||
search_,
|
||||
nation_,
|
||||
league_,
|
||||
team_,
|
||||
sort_,
|
||||
descending_,
|
||||
roster24_,
|
||||
show_source_,
|
||||
offset_,
|
||||
comparison_table_,
|
||||
comparison_set_,
|
||||
comparison_sort_,
|
||||
comparison_descending_,
|
||||
regulations_game_,
|
||||
regulations_source_,
|
||||
regulation_id_,
|
||||
game_rule_id_};
|
||||
}
|
||||
std::vector<ScrollPosition> scroll_positions() const {
|
||||
std::vector<ScrollPosition> result;
|
||||
for (const auto *selector :
|
||||
{"#table-scroll", ".inspector-scroll", "#comparison-x", ".regulation-list .table-scroll",
|
||||
".regulation-scroll", ".dashboard", "#navigation"})
|
||||
if (auto *element = doc_->QuerySelector(selector))
|
||||
result.push_back({selector, element->GetScrollLeft(), element->GetScrollTop()});
|
||||
return result;
|
||||
}
|
||||
void remember_location() {
|
||||
if (!navigation_.empty())
|
||||
navigation_[navigation_index_] = {location(), scroll_positions()};
|
||||
}
|
||||
void visit(std::function<void()> next) {
|
||||
leave_fields([this, next] {
|
||||
remember_location();
|
||||
const auto previous = location();
|
||||
next();
|
||||
if (location() == previous)
|
||||
return;
|
||||
navigation_.resize(navigation_index_ + 1);
|
||||
navigation_.push_back({location(), {}});
|
||||
navigation_index_ = navigation_.size() - 1;
|
||||
// Bound memory use during long editing sessions.
|
||||
if (navigation_.size() > 200) {
|
||||
navigation_.erase(navigation_.begin());
|
||||
--navigation_index_;
|
||||
}
|
||||
});
|
||||
}
|
||||
bool can_navigate(int direction) const {
|
||||
return !busy_ && !modal_ && !navigation_.empty() &&
|
||||
(direction < 0 ? navigation_index_ > 0 : navigation_index_ + 1 < navigation_.size());
|
||||
}
|
||||
void navigate_history(int direction) {
|
||||
if (!can_navigate(direction))
|
||||
return;
|
||||
leave_fields([this, direction] {
|
||||
remember_location();
|
||||
navigation_index_ = direction < 0 ? navigation_index_ - 1 : navigation_index_ + 1;
|
||||
const auto &destination = navigation_[navigation_index_];
|
||||
const auto &l = destination.location;
|
||||
page_ = l.page;
|
||||
selected_id_ = l.selected;
|
||||
search_ = l.search;
|
||||
nation_ = l.nation;
|
||||
league_ = l.league;
|
||||
team_ = l.team;
|
||||
sort_ = l.sort;
|
||||
descending_ = l.descending;
|
||||
roster24_ = l.roster24;
|
||||
show_source_ = l.show_source;
|
||||
offset_ = l.offset;
|
||||
comparison_table_ = l.comparison_table;
|
||||
comparison_set_ = l.comparison_set;
|
||||
comparison_sort_ = l.comparison_sort;
|
||||
comparison_descending_ = l.comparison_descending;
|
||||
regulations_game_ = l.regulations_game;
|
||||
regulations_source_ = l.regulations_source;
|
||||
regulation_id_ = l.regulation_id;
|
||||
game_rule_id_ = l.game_rule_id;
|
||||
restore_scroll_ = destination.scroll;
|
||||
fields_.clear();
|
||||
needs_refresh_ = true;
|
||||
});
|
||||
}
|
||||
void close_history_menu() {
|
||||
if (!history_menu_open_)
|
||||
return;
|
||||
el("history-overlay")->SetProperty("display", "none");
|
||||
history_menu_open_ = false;
|
||||
redraw_ = true;
|
||||
}
|
||||
void history_menu(int x, int y) {
|
||||
Rml::ElementList controls;
|
||||
doc_->QuerySelectorAll(controls, "select");
|
||||
for (auto *element : controls)
|
||||
if (auto *select = dynamic_cast<Rml::ElementFormControlSelect *>(element))
|
||||
select->HideSelectBox();
|
||||
std::string items;
|
||||
for (const int direction : {-1, 1}) {
|
||||
const auto action = direction < 0 ? "history-back" : "history-forward";
|
||||
items += "<button id=\"" + std::string(action) + "\" data-action=\"" + action + "\" " +
|
||||
(can_navigate(direction) ? "" : "disabled") + "><span class=\"history-arrow\">" +
|
||||
icon(direction < 0 ? "back" : "forward") + "</span><span>" +
|
||||
escaped(t(direction < 0 ? "navigation_back" : "navigation_forward")) +
|
||||
"</span><small>Alt + " + t(direction < 0 ? "navigation_left" : "navigation_right") +
|
||||
"</small></button>";
|
||||
}
|
||||
html("history-menu", items);
|
||||
el("history-overlay")->SetProperty("display", "block");
|
||||
history_menu_open_ = true;
|
||||
context_->Update();
|
||||
const auto dimensions = context_->GetDimensions();
|
||||
auto *menu = el("history-menu");
|
||||
const float margin = 6 * context_->GetDensityIndependentPixelRatio();
|
||||
menu->SetProperty(
|
||||
"left", number(std::clamp(float(x), margin,
|
||||
std::max(margin, dimensions.x - menu->GetOffsetWidth() - margin))) +
|
||||
"px");
|
||||
menu->SetProperty(
|
||||
"top", number(std::clamp(float(y), margin,
|
||||
std::max(margin, dimensions.y - menu->GetOffsetHeight() - margin))) +
|
||||
"px");
|
||||
if (can_navigate(-1))
|
||||
el("history-back")->Focus();
|
||||
else if (can_navigate(1))
|
||||
el("history-forward")->Focus();
|
||||
}
|
||||
static std::string identity(const Json &row, const std::string &table) {
|
||||
return str(row, table == "assets" ? "key" : "id");
|
||||
}
|
||||
@@ -201,10 +339,13 @@ class EditorUi final : public Rml::EventListener {
|
||||
return found == lookup_.end() ? id : title(found->second);
|
||||
}
|
||||
std::string img(const std::string &key, const std::string &css) {
|
||||
return "<img class=\"" + css + "\" src=\"" + renderer_.asset(key) + "\"/>";
|
||||
return "<img class=\"" + css + "\" src=\"" + renderer_.asset(key) +
|
||||
"\" data-action=\"image-view\" data-value=\"" + escaped(key) + "\"/>";
|
||||
}
|
||||
std::string icon(const std::string &name) {
|
||||
static const std::map<std::string, std::string> paths{
|
||||
{"back", "M19 12H5M12 5l-7 7 7 7"},
|
||||
{"forward", "M5 12h14M12 5l7 7-7 7"},
|
||||
{"overview", "M3 3h7v7H3zM14 3h7v7h-7zM3 14h7v7H3zM14 14h7v7h-7z"},
|
||||
{"nations", "M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0M3 12h18M12 3c-5 5-5 "
|
||||
"13 0 18M12 3c5 5 5 13 0 18"},
|
||||
@@ -297,9 +438,11 @@ class EditorUi final : public Rml::EventListener {
|
||||
return result;
|
||||
}
|
||||
void resize() {
|
||||
close_history_menu();
|
||||
redraw_ = true;
|
||||
int w, h, pw, ph;
|
||||
SDL_GetWindowSize(video_.window, &w, &h);
|
||||
SDL_GL_GetDrawableSize(video_.window, &pw, &ph);
|
||||
video_.drawable_size(pw, ph);
|
||||
if (!w || !h)
|
||||
return;
|
||||
renderer_.SetViewport(pw, ph);
|
||||
@@ -308,12 +451,21 @@ class EditorUi final : public Rml::EventListener {
|
||||
std::clamp(std::min(w / 1440.f, h / 900.f), .78f, 1.8f));
|
||||
}
|
||||
void close_modal() {
|
||||
redraw_ = true;
|
||||
el("overlay")->SetProperty("display", "none");
|
||||
if (image_view_open_) {
|
||||
html("modal-content", "");
|
||||
renderer_.release_view();
|
||||
image_view_open_ = false;
|
||||
}
|
||||
modal_ = dragging_ = false;
|
||||
modal_accept_ = {};
|
||||
}
|
||||
void modal(const std::string &title, const std::string &body, const std::string &accept,
|
||||
std::function<void()> callback, bool cancel = true, bool wide = false) {
|
||||
close_history_menu();
|
||||
if (image_view_open_)
|
||||
close_modal();
|
||||
label("modal-title", title);
|
||||
html("modal-content", body);
|
||||
label("modal-error", "");
|
||||
@@ -420,6 +572,8 @@ class EditorUi final : public Rml::EventListener {
|
||||
label("page-subtitle", page_ == "roster" ? t("roster_hint")
|
||||
: page_ == "review" ? t("review_hint")
|
||||
: t("subtitle_" + page_));
|
||||
if (page_ == "nations" || page_ == "competitions" || page_ == "clubs")
|
||||
label("page-subtitle", t("subtitle_" + page_) + " · " + t("drill_" + page_));
|
||||
label("state", info_.value("dirty", false) ? "* " + t("unsaved") : t("saved"));
|
||||
html("bottom-actions",
|
||||
button("undo", t("undo"), "quiet", info_.value("can_undo", false) ? "" : "disabled") +
|
||||
@@ -477,7 +631,8 @@ class EditorUi final : public Rml::EventListener {
|
||||
if (selected_["name"].contains("first") || selected_["name"].contains("last")) {
|
||||
field(body, "/name/first", t("first"));
|
||||
field(body, "/name/last", t("last"));
|
||||
field(body, "/name/known_as", t("known_as"));
|
||||
if (selected_["name"].contains("known_as"))
|
||||
field(body, "/name/known_as", t("known_as"));
|
||||
} else
|
||||
field(body, "/name/default", t("name"));
|
||||
} else
|
||||
@@ -486,9 +641,10 @@ class EditorUi final : public Rml::EventListener {
|
||||
std::string inspector() {
|
||||
fields_.clear();
|
||||
if (selected_.empty())
|
||||
return "<div class=\"inspector\"><div class=\"empty\">" + escaped(t("select_record")) + "</div></div>";
|
||||
std::string body = "<div class=\"inspector\"><div class=\"inspector-head\">";
|
||||
if (table() == "players" || table() == "clubs" || table() == "competitions" || table() == "assets")
|
||||
return "<div class=\"empty\">" + escaped(t("select_record")) + "</div>";
|
||||
std::string body = "<div class=\"inspector-head\">";
|
||||
if (table() == "players" || table() == "clubs" || table() == "competitions" || table() == "assets" ||
|
||||
table() == "staff")
|
||||
body += img(table() == "players" && selected_.contains("appearance") ? "portrait:" + selected_id_
|
||||
: image_key(selected_),
|
||||
"hero-image");
|
||||
@@ -595,7 +751,53 @@ class EditorUi final : public Rml::EventListener {
|
||||
if (page_ != "review")
|
||||
body += "<div class=\"inspector-actions\">" + button("delete", t("delete"), "danger") +
|
||||
button("apply", t("apply"), "primary") + "</div>";
|
||||
return body + "</div>";
|
||||
return body;
|
||||
}
|
||||
void initialize_fields() {
|
||||
// Native values also preserve JSON textarea contents without escaping.
|
||||
for (auto &f : fields_) {
|
||||
set_value(f.id, f.kind == "bool" && f.initial.empty() ? "false" : f.initial);
|
||||
f.initial = value(f.id);
|
||||
}
|
||||
}
|
||||
void select_record(const std::string &id) {
|
||||
if (id == selected_id_)
|
||||
return;
|
||||
auto record = session_.execute("get", {{"table", table()}, {"id", id}})["record"];
|
||||
selected_id_ = id;
|
||||
selected_ = std::move(record);
|
||||
Rml::ElementList rows;
|
||||
el("table-scroll")->QuerySelectorAll(rows, ".record");
|
||||
for (auto *row : rows)
|
||||
row->SetClass("selected", row->GetAttribute<Rml::String>("data-value", "") == id);
|
||||
// Keep list elements alive between clicks. Replacing them here would
|
||||
// cancel RmlUI's native double-click detection on a different row.
|
||||
html("record-inspector", inspector());
|
||||
initialize_fields();
|
||||
}
|
||||
void browse_related(const std::string &source, const std::string &id) {
|
||||
if (source != table())
|
||||
return;
|
||||
const auto record = session_.execute("get", {{"table", source}, {"id", id}})["record"];
|
||||
if (source == "competitions" && str(record, "type") != "league")
|
||||
return;
|
||||
visit([this, source, id] {
|
||||
// Apply/discard decisions may have updated the source record.
|
||||
const auto row = session_.execute("get", {{"table", source}, {"id", id}})["record"];
|
||||
if (source == "competitions" && str(row, "type") != "league")
|
||||
return;
|
||||
page_ = source == "nations" ? "competitions" : source == "competitions" ? "clubs" : "players";
|
||||
nation_ = source == "nations" ? id : str(row, "nation");
|
||||
league_ = source == "competitions" ? id : source == "clubs" ? str(row, "competition") : "";
|
||||
team_ = source == "clubs" ? id : "";
|
||||
fields_.clear();
|
||||
selected_id_.clear();
|
||||
search_.clear();
|
||||
offset_ = 0;
|
||||
sort_ = "name";
|
||||
descending_ = false;
|
||||
needs_refresh_ = true;
|
||||
});
|
||||
}
|
||||
void records() {
|
||||
if (!info_.value("loaded", false)) {
|
||||
@@ -617,7 +819,8 @@ class EditorUi final : public Rml::EventListener {
|
||||
toolbar += "<select id=\"filter-league\">" + choices("competitions", league_, t("all_leagues"), nation_) +
|
||||
"</select>";
|
||||
if (table() == "players")
|
||||
toolbar += "<select id=\"filter-team\">" + choices("clubs", team_, t("all_clubs"), nation_) + "</select>";
|
||||
toolbar += "<select id=\"filter-team\">" +
|
||||
choices("clubs", team_, t("all_clubs"), nation_, league_) + "</select>";
|
||||
if (page_ == "roster")
|
||||
toolbar += button("view24", "24", roster24_ ? "primary" : "");
|
||||
html("toolbar", toolbar);
|
||||
@@ -682,13 +885,11 @@ class EditorUi final : public Rml::EventListener {
|
||||
html("page-content", "<div class=\"split\"><div class=\"list-panel\"><div "
|
||||
"class=\"table-header\">" +
|
||||
columns + "</div><div class=\"table-scroll\" id=\"table-scroll\">" + rows +
|
||||
"</div></div>" + inspector() + "</div>");
|
||||
"</div></div><div class=\"inspector\" id=\"record-inspector\">" +
|
||||
inspector() + "</div></div>");
|
||||
// RmlUI's textarea parser retains its raw body rather than decoding
|
||||
// HTML entities. Assign native values after constructing the controls.
|
||||
for (auto &f : fields_) {
|
||||
set_value(f.id, f.kind == "bool" && f.initial.empty() ? "false" : f.initial);
|
||||
f.initial = value(f.id);
|
||||
}
|
||||
initialize_fields();
|
||||
html("pagination",
|
||||
"<span>" + std::to_string(total_) + " " + escaped(t("records")) +
|
||||
(roster24_ ? " · " + escaped(t("compatibility24")) : "") + "</span><div class=\"button-row\">" +
|
||||
@@ -1204,6 +1405,31 @@ class EditorUi final : public Rml::EventListener {
|
||||
if (auto *input = dynamic_cast<Rml::ElementFormControlInput *>(context_->GetFocusElement()))
|
||||
input->GetSelection(&selection_start, &selection_end, nullptr);
|
||||
info_ = session_.execute("info");
|
||||
const auto generation = info_.value("world_generation", uint64_t(0));
|
||||
if (generation != world_generation_) {
|
||||
// An MCP client can also open a different world, even with the
|
||||
// same filename and identifiers. Never replay an old view/draft.
|
||||
world_generation_ = generation;
|
||||
navigation_.clear();
|
||||
navigation_index_ = 0;
|
||||
restore_scroll_.reset();
|
||||
selected_id_.clear();
|
||||
fields_.clear();
|
||||
search_.clear();
|
||||
nation_.clear();
|
||||
league_.clear();
|
||||
team_.clear();
|
||||
remembered_.clear();
|
||||
comparison_set_.clear();
|
||||
comparison_columns_.clear();
|
||||
regulation_id_.clear();
|
||||
game_rule_id_.clear();
|
||||
offset_ = 0;
|
||||
close_history_menu();
|
||||
if (modal_)
|
||||
close_modal();
|
||||
discard_continuation_ = {};
|
||||
}
|
||||
auto rev = info_.value("revision", uint64_t(0));
|
||||
renderer_.clear();
|
||||
if (revision_ != rev) {
|
||||
@@ -1230,6 +1456,17 @@ class EditorUi final : public Rml::EventListener {
|
||||
input->Focus();
|
||||
input->SetSelectionRange(selection_start, selection_end);
|
||||
}
|
||||
if (restore_scroll_) {
|
||||
context_->Update();
|
||||
for (const auto &position : *restore_scroll_)
|
||||
if (auto *element = doc_->QuerySelector(position.selector)) {
|
||||
element->SetScrollLeft(position.left);
|
||||
element->SetScrollTop(position.top);
|
||||
}
|
||||
restore_scroll_.reset();
|
||||
}
|
||||
if (navigation_.empty())
|
||||
navigation_.push_back({location(), {}});
|
||||
needs_refresh_ = false;
|
||||
}
|
||||
bool has_draft() const {
|
||||
@@ -1304,7 +1541,8 @@ class EditorUi final : public Rml::EventListener {
|
||||
body += "<p class=\"form-help\">" + t("mcp_local") + " · " + t(server_.running() ? "online" : "offline") +
|
||||
(server_.running() ? "<br/>http://127.0.0.1:" + std::to_string(server_.port()) + "/mcp" : "") + "</p>";
|
||||
if (server_.running())
|
||||
body += button("copy-connection", t("copy_connection"));
|
||||
body += "<div class=\"connection-actions\">" + button("copy-connection", t("copy_connection")) +
|
||||
"</div>";
|
||||
modal(t("options"), body, t("apply"), [this] {
|
||||
auto next = options_;
|
||||
next.apply({{"language", value("option-language")},
|
||||
@@ -1353,6 +1591,42 @@ class EditorUi final : public Rml::EventListener {
|
||||
el("crop-canvas")->SetProperty("height", std::to_string(h) + "dp");
|
||||
crop_box();
|
||||
}
|
||||
void view_image(const std::string &key) {
|
||||
if (image_view_open_)
|
||||
close_modal();
|
||||
std::string asset_key = key;
|
||||
if (key.starts_with("portrait:")) {
|
||||
const auto player =
|
||||
session_.execute("get", {{"table", "players"}, {"id", key.substr(9)}})["record"];
|
||||
asset_key = str(player, "photo");
|
||||
}
|
||||
std::string caption;
|
||||
if (!asset_key.empty()) {
|
||||
try {
|
||||
const auto asset =
|
||||
session_.execute("get", {{"table", "assets"}, {"id", asset_key}})["record"];
|
||||
caption = title(asset);
|
||||
} catch (const Error &error) {
|
||||
if (error.code != "record_missing")
|
||||
throw;
|
||||
asset_key.clear();
|
||||
}
|
||||
}
|
||||
const auto source = session_.asset_bytes(key);
|
||||
const auto raster = images::preview(source.first, source.second, Json::object(), 1536);
|
||||
const double scale = std::min(810.0 / raster.width, 500.0 / raster.height);
|
||||
const auto token = renderer_.view(images::encode_png(raster));
|
||||
const std::string body = "<div class=\"image-stage readonly-stage\"><img src=\"" + token +
|
||||
"\" style=\"width:" + number(raster.width * scale) +
|
||||
"dp;height:" + number(raster.height * scale) +
|
||||
"dp;\"/></div><p class=\"form-help image-caption\">" + escaped(caption) +
|
||||
"</p>";
|
||||
modal(t("image_view"), body, t("close"), [this] { close_modal(); }, false, true);
|
||||
image_view_open_ = true;
|
||||
html("modal-buttons", button("image-view-asset", t(asset_key.empty() ? "assets" : "view_asset"), "",
|
||||
"data-value=\"" + escaped(asset_key) + "\"") +
|
||||
button("accept-modal", t("close"), "primary"));
|
||||
}
|
||||
void edit_image(bool existing, bool fresh = false) {
|
||||
image_file_.clear();
|
||||
image_key_ = fresh ? "" : image_key(selected_);
|
||||
@@ -1481,20 +1755,24 @@ class EditorUi final : public Rml::EventListener {
|
||||
});
|
||||
}
|
||||
void dispatch(const std::string &action, const std::string &arg) {
|
||||
if (action == "history-close" || action == "history-back" || action == "history-forward") {
|
||||
close_history_menu();
|
||||
if (action != "history-close")
|
||||
navigate_history(action == "history-back" ? -1 : 1);
|
||||
return;
|
||||
}
|
||||
if (busy_)
|
||||
return;
|
||||
if (action == "navigate")
|
||||
leave_fields([this, arg] {
|
||||
visit([this, arg] {
|
||||
page_ = arg;
|
||||
fields_.clear();
|
||||
selected_id_.clear();
|
||||
offset_ = 0;
|
||||
search_.clear();
|
||||
if (arg == "comparison" || arg == "regulations") {
|
||||
nation_.clear();
|
||||
league_.clear();
|
||||
team_.clear();
|
||||
}
|
||||
nation_.clear();
|
||||
league_.clear();
|
||||
team_.clear();
|
||||
needs_refresh_ = true;
|
||||
});
|
||||
else if (action == "regulations-tab") {
|
||||
@@ -1509,7 +1787,7 @@ class EditorUi final : public Rml::EventListener {
|
||||
regulations_source_ = !regulations_source_;
|
||||
needs_refresh_ = true;
|
||||
} else if (action == "compare-open" || action == "compare-scope")
|
||||
leave_fields([this, action, arg] {
|
||||
visit([this, action, arg] {
|
||||
comparison_table_ =
|
||||
action == "compare-open" ? (table() == "competitions" ? "leagues" : table()) : arg;
|
||||
page_ = "comparison";
|
||||
@@ -1546,19 +1824,22 @@ class EditorUi final : public Rml::EventListener {
|
||||
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] {
|
||||
} else if (action == "compare-edit")
|
||||
visit([this, arg] {
|
||||
page_ = comparison_table_ == "leagues" ? "competitions" : comparison_table_;
|
||||
selected_id_ = arg;
|
||||
sort_ = "name";
|
||||
offset_ = 0;
|
||||
search_.clear();
|
||||
needs_refresh_ = true;
|
||||
});
|
||||
else if (action == "cancel-modal")
|
||||
else if (action.starts_with("browse:"))
|
||||
browse_related(action.substr(7), arg);
|
||||
else if (action.starts_with("select:")) {
|
||||
// The click following a double click still belongs to its old list.
|
||||
if (action.substr(7) == table() && arg != selected_id_)
|
||||
leave_fields([this, arg] { select_record(arg); });
|
||||
} else if (action == "cancel-modal")
|
||||
close_modal();
|
||||
else if (action == "accept-modal") {
|
||||
if (modal_accept_) {
|
||||
@@ -1704,6 +1985,22 @@ class EditorUi final : public Rml::EventListener {
|
||||
{"choice", std::stoi(value("review-choice"))},
|
||||
{"expected_revision", revision_}});
|
||||
needs_refresh_ = true;
|
||||
} else if (action == "image-view")
|
||||
view_image(arg);
|
||||
else if (action == "image-view-asset") {
|
||||
close_modal();
|
||||
visit([this, arg] {
|
||||
page_ = "assets";
|
||||
selected_id_ = search_ = arg;
|
||||
offset_ = 0;
|
||||
sort_ = "name";
|
||||
descending_ = false;
|
||||
nation_.clear();
|
||||
league_.clear();
|
||||
team_.clear();
|
||||
fields_.clear();
|
||||
needs_refresh_ = true;
|
||||
});
|
||||
} else if (action == "image-import" || action == "image-edit") {
|
||||
if (has_draft()) {
|
||||
apply_fields();
|
||||
@@ -1775,23 +2072,16 @@ class EditorUi final : public Rml::EventListener {
|
||||
if (config_.screenshot.empty())
|
||||
return;
|
||||
int w, h;
|
||||
SDL_GL_GetDrawableSize(video_.window, &w, &h);
|
||||
images::Raster raster{w, h, std::vector<uint8_t>(size_t(w) * h * 4)};
|
||||
using ReadPixels = void (*)(int, int, int, int, unsigned, unsigned, void *);
|
||||
auto read = reinterpret_cast<ReadPixels>(SDL_GL_GetProcAddress("glReadPixels"));
|
||||
if (!read)
|
||||
throw Error("video_failed");
|
||||
read(0, 0, w, h, 0x1908 /* RGBA */, 0x1401 /* UNSIGNED_BYTE */, raster.pixels.data());
|
||||
for (int y = 0; y < h / 2; ++y)
|
||||
for (int x = 0; x < w * 4; ++x)
|
||||
std::swap(raster.pixels[size_t(y) * w * 4 + x], raster.pixels[size_t(h - y - 1) * w * 4 + x]);
|
||||
auto pixels = video_.capture(w, h);
|
||||
images::Raster raster{w, h, std::move(pixels)};
|
||||
write_atomic(config_.screenshot, images::encode_png(raster));
|
||||
config_.screenshot.clear();
|
||||
}
|
||||
|
||||
public:
|
||||
EditorUi(Session &s, Options &o, McpServer &server, UiConfig config)
|
||||
: session_(s), options_(o), server_(server), config_(std::move(config)), renderer_(s) {
|
||||
: session_(s), options_(o), server_(server), config_(std::move(config)), renderer_(s, video_) {
|
||||
SDL_StartTextInput();
|
||||
page_ = config_.page;
|
||||
Rml::SetSystemInterface(&system_);
|
||||
Rml::SetFileInterface(&files_);
|
||||
@@ -1801,13 +2091,14 @@ class EditorUi final : public Rml::EventListener {
|
||||
if (!initialized_)
|
||||
throw Error("video_failed");
|
||||
for (auto weight : {"Regular", "Bold"})
|
||||
if (!Rml::LoadFontFace(utf8(config_.assets / (std::string("LatoLatin-") + weight + ".ttf"))))
|
||||
if (!Rml::LoadFontFace(
|
||||
bmh::rml::asset_path(config_.assets / (std::string("LatoLatin-") + weight + ".ttf"))))
|
||||
throw Error("ui_assets_missing");
|
||||
context_ = Rml::CreateContext("editor", {1440, 900});
|
||||
doc_ = context_->LoadDocument(utf8(config_.assets / "editor.rml"));
|
||||
doc_ = context_->LoadDocument(bmh::rml::asset_path(config_.assets / "editor.rml"));
|
||||
if (!doc_)
|
||||
throw Error("ui_assets_missing");
|
||||
for (auto event : {"click", "change", "mousedown", "mouseup", "mousemove"})
|
||||
for (auto event : {"click", "dblclick", "change", "mousedown", "mouseup", "mousemove"})
|
||||
doc_->AddEventListener(event, this);
|
||||
resize();
|
||||
refresh();
|
||||
@@ -1823,7 +2114,8 @@ class EditorUi final : public Rml::EventListener {
|
||||
void ProcessEvent(Rml::Event &event) override {
|
||||
auto *target = event.GetTargetElement();
|
||||
const auto type = event.GetType();
|
||||
if (type == "mousedown" && modal_ && doc_->GetElementById("crop-canvas")) {
|
||||
if (type == "mousedown" && event.GetParameter<int>("button", 0) == 0 && modal_ &&
|
||||
doc_->GetElementById("crop-canvas")) {
|
||||
for (auto *node = target; node; node = node->GetParentNode())
|
||||
if (node->GetId() == "crop-canvas") {
|
||||
crop_drag(event.GetParameter<float>("mouse_x", 0), event.GetParameter<float>("mouse_y", 0), true);
|
||||
@@ -1850,20 +2142,49 @@ class EditorUi final : public Rml::EventListener {
|
||||
pending_.emplace_back("image-preview", "");
|
||||
return;
|
||||
}
|
||||
if (type != "click")
|
||||
if (type != "click" && type != "dblclick")
|
||||
return;
|
||||
for (auto *node = target; node; node = node->GetParentNode())
|
||||
if (node->HasAttribute("data-action") && !node->HasAttribute("disabled")) {
|
||||
pending_.emplace_back(node->GetAttribute<Rml::String>("data-action", ""),
|
||||
node->GetAttribute<Rml::String>("data-value", ""));
|
||||
auto action = node->GetAttribute<Rml::String>("data-action", "");
|
||||
if (type == "dblclick") {
|
||||
if (action != "select" ||
|
||||
(table() != "nations" && table() != "competitions" && table() != "clubs"))
|
||||
return;
|
||||
action = "browse:" + table();
|
||||
} else if (action == "select")
|
||||
action = "select:" + table();
|
||||
pending_.emplace_back(action, node->GetAttribute<Rml::String>("data-value", ""));
|
||||
return;
|
||||
}
|
||||
}
|
||||
int run() {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
using namespace std::chrono_literals;
|
||||
auto last_poll = start_;
|
||||
auto next_update = start_;
|
||||
auto observed_revision = revision_;
|
||||
while (!closed_) {
|
||||
const auto before_wait = Clock::now();
|
||||
const bool drawable =
|
||||
!(SDL_GetWindowFlags(video_.window) & (SDL_WINDOW_MINIMIZED | SDL_WINDOW_HIDDEN));
|
||||
auto wake = busy_ ? before_wait + 50ms : last_poll + 400ms;
|
||||
if (drawable) {
|
||||
wake = std::min(wake, next_update);
|
||||
if (!busy_ && !config_.screenshot.empty())
|
||||
wake = std::min(wake, start_ + 1200ms);
|
||||
}
|
||||
if (config_.quit_after_ms > 0)
|
||||
wake = std::min(wake, start_ + std::chrono::milliseconds(config_.quit_after_ms));
|
||||
const auto timeout =
|
||||
!pending_.empty() || (drawable && (redraw_ || (needs_refresh_ && !busy_)))
|
||||
? 0
|
||||
: int(std::clamp(std::chrono::ceil<std::chrono::milliseconds>(wake - before_wait).count(),
|
||||
int64_t(0), int64_t(400)));
|
||||
SDL_Event event;
|
||||
while (SDL_PollEvent(&event)) {
|
||||
int have_event = timeout > 0 ? SDL_WaitEventTimeout(&event, timeout) : SDL_PollEvent(&event);
|
||||
for (; have_event; have_event = SDL_PollEvent(&event)) {
|
||||
redraw_ = true;
|
||||
if (event.type == SDL_QUIT) {
|
||||
try {
|
||||
leaving([this] { closed_ = true; });
|
||||
@@ -1892,6 +2213,27 @@ class EditorUi final : public Rml::EventListener {
|
||||
pending_.emplace_back("open", "");
|
||||
continue;
|
||||
}
|
||||
if ((event.key.keysym.mod & KMOD_ALT) &&
|
||||
(event.key.keysym.sym == SDLK_LEFT || event.key.keysym.sym == SDLK_RIGHT)) {
|
||||
pending_.emplace_back(
|
||||
event.key.keysym.sym == SDLK_LEFT ? "history-back" : "history-forward", "");
|
||||
continue;
|
||||
}
|
||||
if (event.key.keysym.sym == SDLK_ESCAPE && history_menu_open_) {
|
||||
close_history_menu();
|
||||
continue;
|
||||
}
|
||||
if (event.key.keysym.sym == SDLK_ESCAPE) {
|
||||
auto *owner = focused;
|
||||
while (owner && owner->GetTagName() != "select")
|
||||
owner = owner->GetParentNode();
|
||||
if (auto *select = dynamic_cast<Rml::ElementFormControlSelect *>(owner);
|
||||
select && select->IsSelectBoxVisible()) {
|
||||
select->CancelSelectBox();
|
||||
select->Focus();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (event.key.keysym.sym == SDLK_ESCAPE && modal_) {
|
||||
close_modal();
|
||||
continue;
|
||||
@@ -1915,7 +2257,7 @@ class EditorUi final : public Rml::EventListener {
|
||||
ime_.HandleEdit(event.edit);
|
||||
int w, h, pw, ph;
|
||||
SDL_GetWindowSize(video_.window, &w, &h);
|
||||
SDL_GL_GetDrawableSize(video_.window, &pw, &ph);
|
||||
video_.drawable_size(pw, ph);
|
||||
if (w && h) {
|
||||
if (event.type == SDL_MOUSEMOTION) {
|
||||
event.motion.x = int(double(event.motion.x) * pw / w);
|
||||
@@ -1927,12 +2269,27 @@ class EditorUi final : public Rml::EventListener {
|
||||
context_->ProcessMouseMove(event.button.x, event.button.y, RmlSDL::GetKeyModifierState());
|
||||
}
|
||||
}
|
||||
if (event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP) {
|
||||
if (event.button.button == SDL_BUTTON_RIGHT) {
|
||||
if (event.type == SDL_MOUSEBUTTONUP)
|
||||
history_menu(event.button.x, event.button.y);
|
||||
continue;
|
||||
}
|
||||
if (event.button.button == SDL_BUTTON_X1 || event.button.button == SDL_BUTTON_X2) {
|
||||
if (event.type == SDL_MOUSEBUTTONUP)
|
||||
pending_.emplace_back(
|
||||
event.button.button == SDL_BUTTON_X1 ? "history-back" : "history-forward",
|
||||
"");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
RmlSDL::InputEventHandler(context_, video_.window, event);
|
||||
}
|
||||
}
|
||||
while (!pending_.empty()) {
|
||||
auto [action, arg] = pending_.front();
|
||||
pending_.pop_front();
|
||||
redraw_ = true;
|
||||
try {
|
||||
dispatch(action, arg);
|
||||
} catch (const std::exception &e) {
|
||||
@@ -1951,15 +2308,19 @@ class EditorUi final : public Rml::EventListener {
|
||||
}
|
||||
completed_ = {};
|
||||
}
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (!busy_ && now - last_poll > std::chrono::milliseconds(400)) {
|
||||
const auto now = Clock::now();
|
||||
if (!busy_ && now - last_poll >= 400ms) {
|
||||
auto info = session_.execute("info");
|
||||
if (info.value("revision", uint64_t(0)) != revision_) {
|
||||
if (!has_draft() && !modal_)
|
||||
const auto revision = info.value("revision", uint64_t(0));
|
||||
if (info.value("world_generation", uint64_t(0)) != world_generation_)
|
||||
needs_refresh_ = true;
|
||||
else if (info != info_) {
|
||||
if (!has_draft() && !modal_ && !history_menu_open_)
|
||||
needs_refresh_ = true;
|
||||
else
|
||||
else if (revision != revision_ && revision != observed_revision)
|
||||
label("status-message", t("stale_revision"));
|
||||
}
|
||||
observed_revision = revision;
|
||||
last_poll = now;
|
||||
}
|
||||
if (needs_refresh_ && !busy_) {
|
||||
@@ -1970,16 +2331,30 @@ class EditorUi final : public Rml::EventListener {
|
||||
error(e);
|
||||
}
|
||||
}
|
||||
context_->Update();
|
||||
renderer_.BeginFrame();
|
||||
renderer_.Clear();
|
||||
context_->Render();
|
||||
renderer_.EndFrame();
|
||||
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start_).count();
|
||||
if (!busy_ && elapsed > 1200 && !config_.screenshot.empty())
|
||||
screenshot();
|
||||
SDL_GL_SwapWindow(video_.window);
|
||||
SDL_Delay(10);
|
||||
const bool capture = !busy_ && elapsed >= 1200 && !config_.screenshot.empty();
|
||||
if (drawable && (redraw_ || now >= next_update || capture)) {
|
||||
const auto updated = Clock::now();
|
||||
context_->Update();
|
||||
// BeginFrame configures transparent clears for offscreen
|
||||
// layers (popup shadows). Clear the output before that setup.
|
||||
renderer_.Clear();
|
||||
renderer_.BeginFrame();
|
||||
context_->Render();
|
||||
renderer_.EndFrame();
|
||||
if (capture)
|
||||
screenshot();
|
||||
video_.present();
|
||||
redraw_ = false;
|
||||
const double delay = context_->GetNextUpdateDelay();
|
||||
// RmlUI requests timed updates for caret blink, animations and
|
||||
// smooth scrolling. A static view needs no frames at all.
|
||||
next_update =
|
||||
std::isfinite(delay)
|
||||
? updated + std::chrono::duration_cast<Clock::duration>(
|
||||
std::chrono::duration<double>(std::clamp(delay, .016, 3600.0)))
|
||||
: Clock::time_point::max();
|
||||
}
|
||||
if (config_.quit_after_ms > 0 && elapsed >= config_.quit_after_ms)
|
||||
closed_ = true;
|
||||
}
|
||||
|
||||
@@ -33,6 +33,9 @@ target_link_libraries(bmh_launcher PUBLIC bmh_content)
|
||||
include(../launch/rmlui.cmake)
|
||||
target_sources(bmh_launcher PRIVATE ../launch/launcher_rmlui.cpp)
|
||||
target_link_libraries(bmh_launcher PRIVATE bmh_rmlui nfd)
|
||||
add_executable(launcher_gui_smoke ../../tests/launcher_gui_smoke.cpp)
|
||||
target_link_libraries(launcher_gui_smoke PRIVATE bmh_launcher bmh_rmlui)
|
||||
set_target_properties(launcher_gui_smoke PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}")
|
||||
add_executable(launcher_document_tests ../../tests/launcher_document_tests.cpp)
|
||||
target_include_directories(launcher_document_tests PRIVATE ..)
|
||||
target_link_libraries(launcher_document_tests PRIVATE RmlUi::Core)
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "launch/launcher_ui.hpp"
|
||||
#include "launch/rml_path.hpp"
|
||||
#include "launch/archive.hpp"
|
||||
#include "launch/launcher_ui.hpp"
|
||||
#include "launch/process.hpp"
|
||||
#include "launch/rml_path.hpp"
|
||||
#include "launch/rml_video.hpp"
|
||||
#include "version.hpp"
|
||||
#include <RmlUi/Core.h>
|
||||
#include <RmlUi/Core/Elements/ElementFormControl.h>
|
||||
#include <RmlUi/Core/Elements/ElementFormControlInput.h>
|
||||
#include <RmlUi_Platform_SDL.h>
|
||||
#include <RmlUi_Renderer_GL3.h>
|
||||
#include <nfd.hpp>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <nfd.hpp>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace bmh::launch {
|
||||
@@ -41,9 +41,6 @@ std::string escape(std::string_view value) {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
[[noreturn]] void sdl_error(const char *operation) {
|
||||
throw std::runtime_error(std::string(operation) + ": " + SDL_GetError());
|
||||
}
|
||||
int modifiers(Uint16 state) {
|
||||
int result = 0;
|
||||
if (state & KMOD_CTRL)
|
||||
@@ -65,62 +62,11 @@ int modifiers(Uint16 state) {
|
||||
result |= Rml::Input::KM_NUMLOCK;
|
||||
return result;
|
||||
}
|
||||
struct Video {
|
||||
SDL_Window *window = nullptr;
|
||||
SDL_GLContext gl = nullptr;
|
||||
bool loader = false;
|
||||
Video() {
|
||||
try {
|
||||
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER) != 0)
|
||||
sdl_error("Launcher video initialization");
|
||||
SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
|
||||
#ifdef __APPLE__
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
|
||||
#else
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
|
||||
#endif
|
||||
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
|
||||
window = SDL_CreateWindow("OpenBMH", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1100, 688,
|
||||
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI |
|
||||
SDL_WINDOW_HIDDEN);
|
||||
if (!window)
|
||||
sdl_error("Launcher window");
|
||||
SDL_SetWindowMinimumSize(window, 800, 540);
|
||||
gl = SDL_GL_CreateContext(window);
|
||||
if (!gl)
|
||||
sdl_error("Launcher requires OpenGL 3.3 (macOS: 4.1)");
|
||||
SDL_GL_MakeCurrent(window, gl);
|
||||
SDL_GL_SetSwapInterval(1);
|
||||
std::string error;
|
||||
if (!RmlGL3::Initialize(&error))
|
||||
throw std::runtime_error("Launcher graphics initialization: " + error);
|
||||
loader = true;
|
||||
SDL_StopTextInput();
|
||||
} catch (...) {
|
||||
close();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
void close() {
|
||||
if (loader)
|
||||
RmlGL3::Shutdown();
|
||||
if (gl)
|
||||
SDL_GL_DeleteContext(gl);
|
||||
if (window)
|
||||
SDL_DestroyWindow(window);
|
||||
SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER);
|
||||
}
|
||||
~Video() { close(); }
|
||||
};
|
||||
class RmlLauncher final : public LauncherUI, public Rml::EventListener {
|
||||
Video video_;
|
||||
rml::Video video_{"OpenBMH", 1100, 688, 800, 540};
|
||||
rml::AssetFiles files_;
|
||||
SystemInterface_SDL system_{video_.window};
|
||||
RenderInterface_GL3 renderer_;
|
||||
rml::Renderer renderer_{video_};
|
||||
TextInputMethodEditor_SDL ime_;
|
||||
Rml::Context *context_ = nullptr;
|
||||
Rml::ElementDocument *document_ = nullptr;
|
||||
@@ -165,7 +111,7 @@ class RmlLauncher final : public LauncherUI, public Rml::EventListener {
|
||||
void resize() {
|
||||
int w = 0, h = 0, pixels_w = 0, pixels_h = 0;
|
||||
SDL_GetWindowSize(video_.window, &w, &h);
|
||||
SDL_GL_GetDrawableSize(video_.window, &pixels_w, &pixels_h);
|
||||
video_.drawable_size(pixels_w, pixels_h);
|
||||
if (w <= 0 || h <= 0 || pixels_w <= 0 || pixels_h <= 0)
|
||||
return;
|
||||
renderer_.SetViewport(pixels_w, pixels_h);
|
||||
@@ -350,7 +296,7 @@ class RmlLauncher final : public LauncherUI, public Rml::EventListener {
|
||||
// SDL2 reports mouse coordinates in window units on Retina/HiDPI.
|
||||
int w = 0, h = 0, pw = 0, ph = 0;
|
||||
SDL_GetWindowSize(video_.window, &w, &h);
|
||||
SDL_GL_GetDrawableSize(video_.window, &pw, &ph);
|
||||
video_.drawable_size(pw, ph);
|
||||
if (w > 0 && h > 0) {
|
||||
if (event.type == SDL_MOUSEMOTION) {
|
||||
event.motion.x = int(double(event.motion.x) * pw / w);
|
||||
@@ -377,7 +323,7 @@ class RmlLauncher final : public LauncherUI, public Rml::EventListener {
|
||||
renderer_.Clear();
|
||||
context_->Render();
|
||||
renderer_.EndFrame();
|
||||
SDL_GL_SwapWindow(video_.window);
|
||||
video_.present();
|
||||
dirty_ = false;
|
||||
}
|
||||
}
|
||||
@@ -390,8 +336,9 @@ class RmlLauncher final : public LauncherUI, public Rml::EventListener {
|
||||
|
||||
public:
|
||||
RmlLauncher() {
|
||||
SDL_StopTextInput();
|
||||
if (!renderer_)
|
||||
throw std::runtime_error("RmlUI could not create the OpenGL renderer");
|
||||
throw std::runtime_error("RmlUI could not create the graphics renderer");
|
||||
try {
|
||||
Rml::SetSystemInterface(&system_);
|
||||
Rml::SetFileInterface(&files_);
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "launch/rml_video.hpp"
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
#include <string_view>
|
||||
#ifdef _WIN32
|
||||
#include <SDL_syswm.h>
|
||||
#endif
|
||||
|
||||
namespace bmh::rml {
|
||||
namespace {
|
||||
[[noreturn]] void sdl_error(const char *operation) {
|
||||
throw std::runtime_error(std::string(operation) + ": " + SDL_GetError());
|
||||
}
|
||||
#ifdef _WIN32
|
||||
void check(HRESULT result, const char *operation) {
|
||||
if (FAILED(result)) {
|
||||
char code[24];
|
||||
std::snprintf(code, sizeof(code), "0x%08lX", static_cast<unsigned long>(result));
|
||||
throw std::runtime_error(std::string(operation) + ": " + code);
|
||||
}
|
||||
}
|
||||
std::wstring wide(const std::string &text) {
|
||||
const int length = MultiByteToWideChar(CP_UTF8, 0, text.data(), int(text.size()), nullptr, 0);
|
||||
std::wstring result(size_t(length), L' ');
|
||||
MultiByteToWideChar(CP_UTF8, 0, text.data(), int(text.size()), result.data(), length);
|
||||
return result;
|
||||
}
|
||||
#endif
|
||||
} // namespace
|
||||
|
||||
Video::Video(const char *title, int width, int height, int minimum_width, int minimum_height) {
|
||||
try {
|
||||
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER) != 0)
|
||||
sdl_error("Video initialization");
|
||||
SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
|
||||
Uint32 flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_HIDDEN;
|
||||
#ifndef _WIN32
|
||||
flags |= SDL_WINDOW_OPENGL;
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
|
||||
#ifdef __APPLE__
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
|
||||
#else
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
|
||||
#endif
|
||||
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
|
||||
#endif
|
||||
window =
|
||||
SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, flags);
|
||||
if (!window)
|
||||
sdl_error("Window creation");
|
||||
SDL_SetWindowMinimumSize(window, minimum_width, minimum_height);
|
||||
#ifdef _WIN32
|
||||
SDL_SysWMinfo info{};
|
||||
SDL_VERSION(&info.version);
|
||||
if (!SDL_GetWindowWMInfo(window, &info))
|
||||
sdl_error("Native window handle");
|
||||
DXGI_SWAP_CHAIN_DESC desc{};
|
||||
desc.BufferCount = 2;
|
||||
desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
|
||||
desc.OutputWindow = info.info.win.window;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Windowed = TRUE;
|
||||
desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
|
||||
const D3D_FEATURE_LEVEL levels[] = {D3D_FEATURE_LEVEL_11_0};
|
||||
auto create = [&](D3D_DRIVER_TYPE driver) {
|
||||
return D3D11CreateDeviceAndSwapChain(nullptr, driver, nullptr, 0, levels, 1, D3D11_SDK_VERSION,
|
||||
&desc, swapchain_.ReleaseAndGetAddressOf(),
|
||||
device_.ReleaseAndGetAddressOf(), nullptr,
|
||||
context_.ReleaseAndGetAddressOf());
|
||||
};
|
||||
const auto mode = std::getenv("OPENBMH_RML_DRIVER");
|
||||
const bool force_warp = mode && std::string_view(mode) == "warp";
|
||||
HRESULT result = force_warp ? E_FAIL : create(D3D_DRIVER_TYPE_HARDWARE);
|
||||
bool software = false;
|
||||
if (FAILED(result)) {
|
||||
result = create(D3D_DRIVER_TYPE_WARP);
|
||||
software = true;
|
||||
}
|
||||
check(result, "Direct3D 11 initialization (hardware and WARP)");
|
||||
// Upstream's full-featured renderer requires the 11.1 runtime interfaces.
|
||||
Microsoft::WRL::ComPtr<ID3D11Device1> device1;
|
||||
Microsoft::WRL::ComPtr<ID3D11DeviceContext1> context1;
|
||||
check(device_.As(&device1), "Direct3D 11.1 device");
|
||||
check(context_.As(&context1), "Direct3D 11.1 context");
|
||||
std::fprintf(stderr, "RmlUI renderer: Direct3D 11 (%s)\n", software ? "WARP software" : "hardware");
|
||||
int pw, ph;
|
||||
drawable_size(pw, ph);
|
||||
resize(pw, ph);
|
||||
#else
|
||||
gl_ = SDL_GL_CreateContext(window);
|
||||
if (!gl_)
|
||||
sdl_error("OpenGL 3.3 initialization (macOS: 4.1)");
|
||||
if (SDL_GL_MakeCurrent(window, gl_) != 0)
|
||||
sdl_error("OpenGL context activation");
|
||||
SDL_GL_SetSwapInterval(1);
|
||||
std::string error;
|
||||
if (!RmlGL3::Initialize(&error))
|
||||
throw std::runtime_error("OpenGL renderer initialization: " + error);
|
||||
loader_ = true;
|
||||
#endif
|
||||
} catch (...) {
|
||||
close();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
Video::~Video() { close(); }
|
||||
void Video::close() noexcept {
|
||||
#ifdef _WIN32
|
||||
if (context_)
|
||||
context_->ClearState();
|
||||
target_.Reset();
|
||||
swapchain_.Reset();
|
||||
context_.Reset();
|
||||
device_.Reset();
|
||||
#else
|
||||
if (loader_)
|
||||
RmlGL3::Shutdown();
|
||||
if (gl_)
|
||||
SDL_GL_DeleteContext(gl_);
|
||||
#endif
|
||||
if (window)
|
||||
SDL_DestroyWindow(window);
|
||||
SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER);
|
||||
}
|
||||
void Video::drawable_size(int &width, int &height) const {
|
||||
#ifdef _WIN32
|
||||
SDL_GetWindowSizeInPixels(window, &width, &height);
|
||||
#else
|
||||
SDL_GL_GetDrawableSize(window, &width, &height);
|
||||
#endif
|
||||
}
|
||||
#ifdef _WIN32
|
||||
void Video::resize(int width, int height) {
|
||||
if (width < 1 || height < 1 || (width == width_ && height == height_ && target_))
|
||||
return;
|
||||
context_->OMSetRenderTargets(0, nullptr, nullptr);
|
||||
target_.Reset();
|
||||
check(swapchain_->ResizeBuffers(0, UINT(width), UINT(height), DXGI_FORMAT_UNKNOWN, 0),
|
||||
"Swapchain resize");
|
||||
Microsoft::WRL::ComPtr<ID3D11Texture2D> buffer;
|
||||
check(swapchain_->GetBuffer(0, IID_PPV_ARGS(&buffer)), "Swapchain buffer");
|
||||
check(device_->CreateRenderTargetView(buffer.Get(), nullptr, &target_), "Render target");
|
||||
width_ = width;
|
||||
height_ = height;
|
||||
}
|
||||
#endif
|
||||
void Video::present() {
|
||||
#ifdef _WIN32
|
||||
check(swapchain_->Present(1, 0), "Direct3D presentation");
|
||||
#else
|
||||
SDL_GL_SwapWindow(window);
|
||||
#endif
|
||||
}
|
||||
std::vector<uint8_t> Video::capture(int &width, int &height) {
|
||||
#ifdef _WIN32
|
||||
Microsoft::WRL::ComPtr<ID3D11Texture2D> buffer, staging;
|
||||
check(swapchain_->GetBuffer(0, IID_PPV_ARGS(&buffer)), "Screenshot buffer");
|
||||
D3D11_TEXTURE2D_DESC desc{};
|
||||
buffer->GetDesc(&desc);
|
||||
width = static_cast<int>(desc.Width);
|
||||
height = static_cast<int>(desc.Height);
|
||||
std::vector<uint8_t> pixels(size_t(width) * size_t(height) * 4);
|
||||
desc.Usage = D3D11_USAGE_STAGING;
|
||||
desc.BindFlags = 0;
|
||||
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
|
||||
desc.MiscFlags = 0;
|
||||
check(device_->CreateTexture2D(&desc, nullptr, &staging), "Screenshot staging texture");
|
||||
context_->CopyResource(staging.Get(), buffer.Get());
|
||||
D3D11_MAPPED_SUBRESOURCE data{};
|
||||
check(context_->Map(staging.Get(), 0, D3D11_MAP_READ, 0, &data), "Screenshot readback");
|
||||
for (int row = 0; row < height; ++row)
|
||||
std::memcpy(pixels.data() + size_t(row) * width * 4,
|
||||
static_cast<const uint8_t *>(data.pData) + size_t(row) * data.RowPitch,
|
||||
size_t(width) * 4);
|
||||
context_->Unmap(staging.Get(), 0);
|
||||
#else
|
||||
drawable_size(width, height);
|
||||
std::vector<uint8_t> pixels(size_t(width) * size_t(height) * 4);
|
||||
using ReadPixels = void (*)(int, int, int, int, unsigned, unsigned, void *);
|
||||
auto read = reinterpret_cast<ReadPixels>(SDL_GL_GetProcAddress("glReadPixels"));
|
||||
if (!read)
|
||||
sdl_error("Screenshot readback");
|
||||
read(0, 0, width, height, 0x1908, 0x1401, pixels.data());
|
||||
for (int row = 0; row < height / 2; ++row)
|
||||
for (int col = 0; col < width * 4; ++col)
|
||||
std::swap(pixels[size_t(row) * width * 4 + col],
|
||||
pixels[size_t(height - row - 1) * width * 4 + col]);
|
||||
#endif
|
||||
return pixels;
|
||||
}
|
||||
void report_start_error(const char *product, const std::string &message, bool dialog) noexcept {
|
||||
std::fprintf(stderr, "%s: %s\n", product, message.c_str());
|
||||
#ifdef _WIN32
|
||||
try {
|
||||
wchar_t directory[32768]{};
|
||||
const auto length = GetEnvironmentVariableW(L"LOCALAPPDATA", directory, 32768);
|
||||
auto root = (length > 0 && length < 32768 ? std::filesystem::path(directory)
|
||||
: std::filesystem::temp_directory_path()) /
|
||||
L"OpenBMH";
|
||||
std::filesystem::create_directories(root);
|
||||
std::ofstream log(root / (std::string(product) + "-startup.log"), std::ios::app);
|
||||
log << message << '\n';
|
||||
if (dialog && !std::getenv("OPENBMH_NO_ERROR_DIALOG"))
|
||||
MessageBoxW(nullptr, wide(message).c_str(), wide(product).c_str(), MB_OK | MB_ICONERROR);
|
||||
} catch (...) {
|
||||
if (dialog && !std::getenv("OPENBMH_NO_ERROR_DIALOG"))
|
||||
MessageBoxW(nullptr, L"The application could not start.", L"OpenBMH", MB_OK | MB_ICONERROR);
|
||||
}
|
||||
#else
|
||||
if (dialog && !std::getenv("OPENBMH_NO_ERROR_DIALOG"))
|
||||
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, product, message.c_str(), nullptr);
|
||||
#endif
|
||||
}
|
||||
void attach_parent_console() noexcept {
|
||||
#ifdef _WIN32
|
||||
const bool out_free = _fileno(stdout) < 0, err_free = _fileno(stderr) < 0;
|
||||
if ((out_free || err_free) && AttachConsole(ATTACH_PARENT_PROCESS)) {
|
||||
FILE *stream = nullptr;
|
||||
if (out_free)
|
||||
freopen_s(&stream, "CONOUT$", "w", stdout);
|
||||
if (err_free)
|
||||
freopen_s(&stream, "CONOUT$", "w", stderr);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
} // namespace bmh::rml
|
||||
@@ -0,0 +1,71 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include "launch/startup_error.hpp"
|
||||
#include <SDL.h>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#ifdef _WIN32
|
||||
#ifndef NOMINMAX
|
||||
#define NOMINMAX
|
||||
#endif
|
||||
#include <RmlUi_Renderer_DX11.h>
|
||||
#include <wrl/client.h>
|
||||
#else
|
||||
#include <RmlUi_Renderer_GL3.h>
|
||||
#endif
|
||||
|
||||
namespace bmh::rml {
|
||||
// The native Windows renderer needs no OpenGL ICD in a Remote Desktop session.
|
||||
// The device falls back to Microsoft's built-in WARP when hardware is absent.
|
||||
class Video {
|
||||
public:
|
||||
SDL_Window *window = nullptr;
|
||||
Video(const char *title, int width, int height, int minimum_width, int minimum_height);
|
||||
~Video();
|
||||
Video(const Video &) = delete;
|
||||
Video &operator=(const Video &) = delete;
|
||||
void drawable_size(int &width, int &height) const;
|
||||
void present();
|
||||
// RGBA rows in top-to-bottom order, independent of the graphics API.
|
||||
std::vector<uint8_t> capture(int &width, int &height);
|
||||
#ifdef _WIN32
|
||||
ID3D11Device *device() const { return device_.Get(); }
|
||||
ID3D11RenderTargetView *target() const { return target_.Get(); }
|
||||
void resize(int width, int height);
|
||||
#endif
|
||||
private:
|
||||
void close() noexcept;
|
||||
#ifdef _WIN32
|
||||
Microsoft::WRL::ComPtr<ID3D11Device> device_;
|
||||
Microsoft::WRL::ComPtr<ID3D11DeviceContext> context_;
|
||||
Microsoft::WRL::ComPtr<IDXGISwapChain> swapchain_;
|
||||
Microsoft::WRL::ComPtr<ID3D11RenderTargetView> target_;
|
||||
int width_ = 0, height_ = 0;
|
||||
#else
|
||||
SDL_GLContext gl_ = nullptr;
|
||||
bool loader_ = false;
|
||||
#endif
|
||||
};
|
||||
|
||||
#ifdef _WIN32
|
||||
class Renderer : public RenderInterface_DX11 {
|
||||
Video &video_;
|
||||
|
||||
public:
|
||||
explicit Renderer(Video &video) : RenderInterface_DX11(video.device()), video_(video) {}
|
||||
void SetViewport(int width, int height) {
|
||||
video_.resize(width, height);
|
||||
RenderInterface_DX11::SetViewport(width, height);
|
||||
}
|
||||
void Clear() { RenderInterface_DX11::Clear(video_.target()); }
|
||||
void EndFrame() { RenderInterface_DX11::EndFrame(video_.target()); }
|
||||
explicit operator bool() const { return video_.device() != nullptr; }
|
||||
};
|
||||
#else
|
||||
class Renderer : public RenderInterface_GL3 {
|
||||
public:
|
||||
explicit Renderer(Video &) {}
|
||||
};
|
||||
#endif
|
||||
} // namespace bmh::rml
|
||||
@@ -22,8 +22,16 @@ FetchContent_Declare(rmlui
|
||||
FetchContent_MakeAvailable(rmlui)
|
||||
add_library(bmh_rmlui STATIC
|
||||
${rmlui_SOURCE_DIR}/Backends/RmlUi_Platform_SDL.cpp
|
||||
${rmlui_SOURCE_DIR}/Backends/RmlUi_Renderer_GL3.cpp)
|
||||
target_include_directories(bmh_rmlui PUBLIC ${rmlui_SOURCE_DIR}/Backends)
|
||||
${CMAKE_SOURCE_DIR}/src/launch/rml_video.cpp)
|
||||
if(WIN32)
|
||||
target_sources(bmh_rmlui PRIVATE ${rmlui_SOURCE_DIR}/Backends/RmlUi_Renderer_DX11.cpp)
|
||||
target_link_libraries(bmh_rmlui PUBLIC d3d11 dxgi d3dcompiler)
|
||||
# Upstream resolves its multisampled UI layer into the swapchain every frame.
|
||||
target_compile_definitions(bmh_rmlui PUBLIC NUM_MSAA_SAMPLES=2 NOMINMAX)
|
||||
else()
|
||||
target_sources(bmh_rmlui PRIVATE ${rmlui_SOURCE_DIR}/Backends/RmlUi_Renderer_GL3.cpp)
|
||||
endif()
|
||||
target_include_directories(bmh_rmlui PUBLIC ${rmlui_SOURCE_DIR}/Backends ${CMAKE_SOURCE_DIR}/src)
|
||||
target_compile_definitions(bmh_rmlui PUBLIC RMLUI_SDL_VERSION_MAJOR=2 RMLUI_NUM_MSAA_SAMPLES=0)
|
||||
target_link_libraries(bmh_rmlui PUBLIC RmlUi::Core ${BMH_SDL_TARGET} PRIVATE ${CMAKE_DL_LIBS})
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include <string>
|
||||
|
||||
namespace bmh::rml {
|
||||
// Safe before video initialization, including when no graphics driver is available.
|
||||
// No preferences or authentication tokens are logged.
|
||||
void report_start_error(const char *product, const std::string &message, bool dialog = true) noexcept;
|
||||
void attach_parent_console() noexcept;
|
||||
} // namespace bmh::rml
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "editor/mcp.hpp"
|
||||
#include "editor/session.hpp"
|
||||
#include <httplib.h>
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
#ifdef _WIN32
|
||||
@@ -47,6 +48,7 @@ int main() {
|
||||
try {
|
||||
Session s;
|
||||
s.execute("demo");
|
||||
const auto generation = s.execute("info")["world_generation"];
|
||||
check(s.execute("list", {{"table", "players"}})["total"] == 52, "all squads retained");
|
||||
check(s.execute("list", {{"table", "players"}, {"team", "club:north"}, {"limit", 24}})["items"].size() == 24,
|
||||
"24 view");
|
||||
@@ -62,6 +64,8 @@ int main() {
|
||||
s.execute("undo");
|
||||
check(row(s, "players", "player:demo-0") == initial, "undo complete row");
|
||||
check(s.execute("info")["revision"] > revision, "revision monotonic across undo");
|
||||
check(s.execute("info")["world_generation"] == generation,
|
||||
"edits and undo keep navigation world identity");
|
||||
s.execute("redo");
|
||||
check(row(s, "players", "player:demo-0")["attributes"]["strength"] == 99, "redo");
|
||||
rejects("validation_failed",
|
||||
@@ -108,6 +112,25 @@ int main() {
|
||||
const auto png = images::encode_png(image);
|
||||
write_atomic(root / "input.png", png);
|
||||
check(images::decode(png, ".png").pixels == image.pixels, "PNG lossless RGBA");
|
||||
// Authored synthetic pixels: a solid teal 17x19 VP8 image and the
|
||||
// same four RGBA pixels as above encoded as VP8L, including alpha.
|
||||
const std::string webp_lossy(
|
||||
"\x52\x49\x46\x46\x4a\x00\x00\x00\x57\x45\x42\x50\x56\x50\x38\x20"
|
||||
"\x3e\x00\x00\x00\x90\x03\x00\x9d\x01\x2a\x11\x00\x13\x00\x3e\x31"
|
||||
"\x18\x8a\x43\xa2\x21\xa1\x14\x04\x00\x20\x03\x04\xb2\x80\x3b\x00"
|
||||
"\x7e\x00\x7e\x00\x00\x49\x95\x7c\x00\x00\xfe\xe8\x38\xbf\xff\xf6"
|
||||
"\x96\x42\x15\xd7\xfc\x95\x7f\xff\xee\x9e\x90\x81\xa3\xfe\x4a\x00\x00\x00", 82);
|
||||
const std::string webp_lossless(
|
||||
"\x52\x49\x46\x46\x30\x00\x00\x00\x57\x45\x42\x50\x56\x50\x38\x4c"
|
||||
"\x23\x00\x00\x00\x2f\x01\x40\x00\x10\x1f\x20\x10\x48\xde\x1f\x3a"
|
||||
"\x8d\xf9\x17\x10\x14\xfc\x1f\x9d\x80\xa0\xe8\xba\xe5\x22\x66\x0f"
|
||||
"\xc2\x0d\x18\x22\xfa\x1f\x02\x00", 56);
|
||||
const auto webp = images::decode(webp_lossy, ".webp");
|
||||
check(webp.width == 17 && webp.height == 19 && webp.pixels.size() == 17 * 19 * 4 &&
|
||||
std::abs(int(webp.pixels[0]) - 40) <= 4 && std::abs(int(webp.pixels[1]) - 140) <= 4 &&
|
||||
std::abs(int(webp.pixels[2]) - 200) <= 4 && webp.pixels[3] == 255,
|
||||
"WebP lossy colour and dimensions");
|
||||
check(images::decode(webp_lossless, ".webp").pixels == image.pixels, "WebP lossless RGBA");
|
||||
check(images::transform(png, ".png", Json::object()).bytes == png, "identity preserves exact bytes");
|
||||
auto flip = images::decode(images::transform(png, ".png", {{"flip_x", true}}).bytes, ".png");
|
||||
check(flip.pixels[1] == 255 && flip.pixels[4] == 255, "horizontal mirror pixels");
|
||||
@@ -213,6 +236,17 @@ int main() {
|
||||
}
|
||||
#endif
|
||||
check(tr("de", "clubs") != tr("en", "clubs"), "bilingual labels");
|
||||
{
|
||||
Session reopened;
|
||||
reopened.execute("demo");
|
||||
const auto identity = reopened.execute("info")["world_generation"];
|
||||
reopened.execute("save", {{"path", utf8(root / "navigation-world.obw")}});
|
||||
check(reopened.execute("info")["world_generation"] == identity,
|
||||
"saving keeps navigation world identity");
|
||||
reopened.execute("open", {{"path", utf8(root / "navigation-world.obw")}});
|
||||
check(reopened.execute("info")["world_generation"] > identity,
|
||||
"reopening identical IDs resets navigation identity");
|
||||
}
|
||||
McpServer mcp(s);
|
||||
mcp.start(options);
|
||||
httplib::Client client("127.0.0.1", mcp.port());
|
||||
|
||||
@@ -137,7 +137,172 @@ def main():
|
||||
assert rules['read_only'] is True and len(rules['items']) == 1
|
||||
assert rules['items'][0]['movement_defined'] is False
|
||||
assert tool('editor_info') == before_rules
|
||||
print('Native edit, search, undo/save, sorted comparisons and read-only regulations passed.')
|
||||
# Two distinct leagues ensure drilling filters rows rather than
|
||||
# merely opening the first club/player from the whole world.
|
||||
tool('editor_apply', {'changes': [
|
||||
{'op': 'create', 'table': 'competitions', 'id': 'comp:second',
|
||||
'name': 'Zweite Demo-Liga', 'data': {'nation': 'nation:de', 'tier': 2}},
|
||||
{'op': 'create', 'table': 'competitions', 'id': 'comp:cup',
|
||||
'name': 'Zzz-Testpokal', 'data': {'nation': 'nation:de', 'type': 'cup'}},
|
||||
{'op': 'update', 'table': 'clubs', 'id': 'club:south',
|
||||
'set': {'/competition': 'comp:second'}}]})
|
||||
tool('editor_save', {'path': str(root / 'world.obw')})
|
||||
time.sleep(.6)
|
||||
def double_click(a, b):
|
||||
before = tool('editor_info')
|
||||
x('mousemove', '--window', window, a, b, 'click', '--repeat', 2, '--delay', 120, 1)
|
||||
time.sleep(.4)
|
||||
assert tool('editor_info') == before, 'Navigation must not mutate the world'
|
||||
def edit_selected(table, identifier, expected, first=False):
|
||||
click(1150, 443); x('key', 'ctrl+a'); x('type', '--clearmodifiers', expected)
|
||||
click(1300, 741)
|
||||
for _ in range(40):
|
||||
name = tool('editor_get', {'table': table, 'id': identifier})['record']['name']
|
||||
if name['first' if first else 'default'] == expected:
|
||||
break
|
||||
time.sleep(.05)
|
||||
else:
|
||||
raise AssertionError('Double click did not filter the expected destination: ' + identifier)
|
||||
tool('editor_undo'); time.sleep(.5)
|
||||
south_player = tool('editor_list', {'table': 'players', 'team': 'club:south',
|
||||
'sort': 'name', 'limit': 1})['items'][0]['id']
|
||||
click(100, 264) # Leagues, then the unselected second row.
|
||||
double_click(350, 385)
|
||||
edit_selected('clubs', 'club:south', 'Filtered South')
|
||||
double_click(350, 335) # That club's players, all nationalities.
|
||||
edit_selected('players', south_player, 'Filtered Player', True)
|
||||
click(100, 264) # Root navigation clears hidden team filters.
|
||||
double_click(350, 335)
|
||||
edit_selected('clubs', 'club:north', 'Filtered North')
|
||||
click(100, 313) # Double click a club that was not already selected.
|
||||
double_click(350, 385)
|
||||
edit_selected('players', south_player, 'Second Club', True)
|
||||
click(100, 313)
|
||||
click(1150, 443); x('key', 'ctrl+a'); x('type', '--clearmodifiers', 'Keep Draft')
|
||||
double_click(350, 385)
|
||||
x('key', 'Escape'); time.sleep(.2)
|
||||
click(1300, 741); wait_name('Keep Draft')
|
||||
tool('editor_undo'); time.sleep(.5)
|
||||
click(100, 215); double_click(350, 335) # Country -> its competitions.
|
||||
double_click(350, 434) # A cup keeps its own inspector.
|
||||
edit_selected('competitions', 'comp:cup', 'Cup Inspector')
|
||||
# Viewing a linked image is read only and must preserve a
|
||||
# pending property draft until the user chooses to apply it.
|
||||
click(100, 313)
|
||||
before_view = tool('editor_info')
|
||||
click(1150, 443); x('key', 'ctrl+a'); x('type', '--clearmodifiers', 'Preview Draft')
|
||||
click(1100, 326)
|
||||
assert tool('editor_info') == before_view
|
||||
click(985, 757) # A jump with a pending draft asks before leaving.
|
||||
assert tool('editor_info') == before_view
|
||||
x('key', 'Escape'); time.sleep(.2)
|
||||
click(1300, 741); wait_name('Preview Draft')
|
||||
tool('editor_undo'); time.sleep(.5)
|
||||
click(1100, 326); click(985, 757) # Exact linked asset, not the first world row.
|
||||
edit_selected('assets', 'asset:demo/north', 'Preview Asset')
|
||||
# A thumbnail on an unselected row previews that row's image.
|
||||
click(100, 313); click(280, 385); click(985, 757)
|
||||
edit_selected('assets', 'asset:demo/south', 'Second Preview Asset')
|
||||
# Missing/composed portraits still open, with a library link
|
||||
# instead of inventing a single backing asset.
|
||||
click(100, 361)
|
||||
before_view = tool('editor_info')
|
||||
click(1100, 326); x('key', 'Escape'); time.sleep(.2)
|
||||
assert tool('editor_info') == before_view
|
||||
# Browser navigation restores the selected league and its
|
||||
# filters without editing data or advancing the undo cursor.
|
||||
def history(direction):
|
||||
before = tool('editor_info')
|
||||
x('mousemove', '--window', window, 760, 300, 'click', 3)
|
||||
time.sleep(.15)
|
||||
click(850, 330 if direction == 'back' else 375)
|
||||
time.sleep(.2)
|
||||
assert tool('editor_info') == before, 'History must be read only'
|
||||
click(100, 264); double_click(350, 385)
|
||||
double_click(350, 335)
|
||||
history('back')
|
||||
edit_selected('clubs', 'club:south', 'History Team')
|
||||
history('back')
|
||||
edit_selected('competitions', 'comp:second', 'History League')
|
||||
history('forward')
|
||||
edit_selected('clubs', 'club:south', 'History Forward Team')
|
||||
history('forward')
|
||||
edit_selected('players', south_player, 'History Forward Player', True)
|
||||
# Cancelling a pending property edit must keep the history
|
||||
# cursor in place, so the next Back still visits the team.
|
||||
click(1150, 443); x('key', 'ctrl+a'); x('type', '--clearmodifiers', 'History Draft')
|
||||
history('back'); x('key', 'Escape'); time.sleep(.2)
|
||||
click(1300, 741)
|
||||
assert tool('editor_get', {'table': 'players', 'id': south_player})['record']['name']['first'] == 'History Draft'
|
||||
tool('editor_undo'); time.sleep(.5)
|
||||
history('back')
|
||||
edit_selected('clubs', 'club:south', 'History After Cancel')
|
||||
# A different destination after Back removes the forward
|
||||
# branch. Alt+arrows and mouse side buttons share this history.
|
||||
click(100, 313)
|
||||
x('key', 'alt+Right'); time.sleep(.2)
|
||||
edit_selected('clubs', 'club:north', 'History New Branch')
|
||||
x('click', 8); time.sleep(.3)
|
||||
edit_selected('clubs', 'club:south', 'History Side Back')
|
||||
x('click', 9); time.sleep(.3)
|
||||
edit_selected('clubs', 'club:north', 'History Side Forward')
|
||||
# Preview -> exact asset is also a visit, not a data undo.
|
||||
click(280, 385); click(985, 757)
|
||||
history('back')
|
||||
edit_selected('clubs', 'club:north', 'History Preview Back')
|
||||
history('forward')
|
||||
edit_selected('assets', 'asset:demo/south', 'History Preview Forward')
|
||||
# External MCP opens invalidate navigation, including when the
|
||||
# filename and all record IDs are unchanged.
|
||||
click(100, 361); click(100, 313)
|
||||
generation = tool('editor_info')['world_generation']
|
||||
tool('editor_open', {'path': str(root / 'world.obw'), 'discard': True})
|
||||
time.sleep(.6)
|
||||
assert tool('editor_info')['world_generation'] > generation
|
||||
x('key', 'alt+Left'); time.sleep(.2)
|
||||
edit_selected('clubs', 'club:north', 'History New World')
|
||||
# Modern dropdowns retain native values and keyboard input.
|
||||
# Escape cancels just the open list, keeping Options open and
|
||||
# restoring its prior value. Nothing applies before Apply.
|
||||
before_options = tool('editor_info')
|
||||
click(1370, 44)
|
||||
click(690, 258); x('key', 'Down'); x('key', 'Escape')
|
||||
time.sleep(.15)
|
||||
assert json.loads(settings.read_text())['language'] == 'de'
|
||||
click(690, 343); x('key', 'Down'); x('key', 'Return')
|
||||
assert json.loads(settings.read_text())['theme'] == 'midnight'
|
||||
click(950, 725)
|
||||
assert json.loads(settings.read_text())['theme'] == 'silver'
|
||||
assert json.loads(settings.read_text())['language'] == 'de'
|
||||
click(1370, 44)
|
||||
click(690, 258); x('key', 'Down'); x('key', 'Return')
|
||||
click(690, 343); x('key', 'Down'); x('key', 'Return')
|
||||
click(950, 725)
|
||||
assert json.loads(settings.read_text())['theme'] == 'matchday'
|
||||
assert json.loads(settings.read_text())['language'] == 'en'
|
||||
click(1370, 44)
|
||||
click(690, 258); x('key', 'Up'); x('key', 'Return')
|
||||
click(690, 343); x('key', 'Up'); x('key', 'Up'); x('key', 'Return')
|
||||
click(950, 725)
|
||||
assert json.loads(settings.read_text())['theme'] == 'midnight'
|
||||
assert json.loads(settings.read_text())['language'] == 'de'
|
||||
assert tool('editor_info') == before_options
|
||||
# An idle, unfocused form must not continuously render. The
|
||||
# generous one-core CPU budget catches a software-render loop
|
||||
# while allowing timer/MCP polling and slow CI machines.
|
||||
click(700, 153); time.sleep(.5)
|
||||
def cpu_seconds():
|
||||
fields = Path(f'/proc/{app.pid}/stat').read_text().rsplit(')', 1)[1].split()
|
||||
return (int(fields[11]) + int(fields[12])) / os.sysconf('SC_CLK_TCK')
|
||||
before_idle = tool('editor_info')
|
||||
cpu_start, wall_start = cpu_seconds(), time.monotonic()
|
||||
time.sleep(3)
|
||||
cpu_used, wall_used = cpu_seconds() - cpu_start, time.monotonic() - wall_start
|
||||
assert cpu_used < .20 * wall_used, f'Idle CPU exceeded 20% of one core: {cpu_used / wall_used:.1%}'
|
||||
assert tool('editor_info') == before_idle
|
||||
assert 'Syntax error parsing property' not in (root / 'app.log').read_text()
|
||||
print(f'Idle CPU: {cpu_used / wall_used:.1%} of one core.')
|
||||
print('Native edits, comparisons, rules, drill-down, image previews, browser history and idle CPU passed.')
|
||||
except Exception:
|
||||
log.flush()
|
||||
print((root / 'app.log').read_text())
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-only
|
||||
"""Native graphics startup, including Windows Server/WARP and missing assets.
|
||||
|
||||
Use an actual display (Xvfb on Linux). Never reads a user profile or game data.
|
||||
Optionally opens the actual launcher UI too. Windows CI runs on Server 2022.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('editor', type=Path)
|
||||
parser.add_argument('--launcher', type=Path)
|
||||
args = parser.parse_args()
|
||||
# Non-ASCII + spaces exercise UTF-8 native loading and RmlUI URL paths.
|
||||
with tempfile.TemporaryDirectory(prefix='OpenBMH Pr\u00fcfung ') as temporary:
|
||||
root = Path(temporary)
|
||||
executable = args.editor.resolve()
|
||||
env = {**os.environ, 'OPENBMH_RML_DRIVER': 'warp', 'OPENBMH_NO_ERROR_DIALOG': '1',
|
||||
'LIBGL_ALWAYS_SOFTWARE': '1', 'SDL_AUDIODRIVER': 'dummy'}
|
||||
if os.name == 'nt':
|
||||
env['SDL_VIDEODRIVER'] = 'windows'
|
||||
# Copy the GUI and its own assets, rather than finding files via cwd.
|
||||
installed = root / 'Programme'; installed.mkdir()
|
||||
exe = installed / executable.name
|
||||
shutil.copy2(executable, exe)
|
||||
shutil.copytree(executable.parent / 'assets/editor', installed / 'assets/editor')
|
||||
for dll in executable.parent.glob('*.dll'):
|
||||
shutil.copy2(dll, installed / dll.name)
|
||||
settings = root / 'settings.json'
|
||||
settings.write_text(json.dumps({'language': 'de', 'theme': 'midnight', 'mcp_enabled': False}))
|
||||
for name, options in [('first-start', []), ('demo', ['--demo', '--page', 'regulations'])]:
|
||||
screenshot = root / (name + '.png')
|
||||
result = subprocess.run([str(exe), '--settings', str(settings), '--quit-after-ms', '1800',
|
||||
'--screenshot', str(screenshot), *options],
|
||||
cwd=root, env=env, capture_output=True, timeout=35)
|
||||
assert result.returncode == 0, (name, result.returncode, result.stderr.decode(errors='replace'))
|
||||
image = screenshot.read_bytes()
|
||||
assert image[:8] == b'\x89PNG\r\n\x1a\n' and len(image) > 15000, name
|
||||
width, height = struct.unpack_from('>II', image, 16)
|
||||
assert width >= 1080 and height >= 720, (width, height)
|
||||
if os.name == 'nt':
|
||||
assert b'Direct3D 11 (WARP software)' in result.stderr, result.stderr
|
||||
result = subprocess.run([str(exe), '--settings', str(settings), '--assets', str(root / 'missing-assets')],
|
||||
cwd=root, env=env, capture_output=True, timeout=20)
|
||||
assert result.returncode == 1 and b'ui_assets_missing' in result.stderr, result.stderr
|
||||
# Also render and close the real launcher, without needing installed mods.
|
||||
if args.launcher:
|
||||
original = args.launcher.resolve()
|
||||
launcher = installed / original.name
|
||||
shutil.copy2(original, launcher)
|
||||
shutil.copytree(original.parent / 'assets/launcher', installed / 'assets/launcher')
|
||||
for dll in original.parent.glob('*.dll'):
|
||||
shutil.copy2(dll, installed / dll.name)
|
||||
result = subprocess.run([str(launcher)], cwd=root, env=env, capture_output=True, timeout=25)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert b'Native launcher rendered' in result.stdout, result.stdout
|
||||
if os.name == 'nt':
|
||||
assert b'Direct3D 11 (WARP software)' in result.stderr, result.stderr
|
||||
print('Native first start, demo, Unicode asset paths, failure reporting and launcher startup passed')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -36,7 +36,8 @@ struct Renderer : Rml::RenderInterface {
|
||||
unsigned char header[18]{};
|
||||
const auto read = files->Read(header, sizeof(header), input);
|
||||
files->Close(input);
|
||||
if (read != sizeof(header) || header[2] != 2 || header[16] != 24)
|
||||
// The pinned DX11 loader requires bottom-origin rows for 24-bit input.
|
||||
if (read != sizeof(header) || header[2] != 2 || header[16] != 24 || (header[17] & 32))
|
||||
throw std::runtime_error("Invalid stadium asset: " + name);
|
||||
dimensions = {header[12] + 256 * header[13], header[14] + 256 * header[15]};
|
||||
return 1;
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "launch/launcher_ui.hpp"
|
||||
#include <SDL.h>
|
||||
#include <cstdio>
|
||||
#include <stdexcept>
|
||||
|
||||
// Run explicitly on a real display (Windows CI also forces the WARP device),
|
||||
// outside the dummy-video CTest suite. This constructs the actual launcher UI.
|
||||
int main(int, char **) {
|
||||
try {
|
||||
auto ui = bmh::launch::make_launcher_ui();
|
||||
const auto timer = SDL_AddTimer(
|
||||
1600,
|
||||
[](Uint32, void *) -> Uint32 {
|
||||
SDL_Event event{};
|
||||
event.type = SDL_QUIT;
|
||||
SDL_PushEvent(&event);
|
||||
return 0;
|
||||
},
|
||||
nullptr);
|
||||
if (!timer)
|
||||
throw std::runtime_error(SDL_GetError());
|
||||
const auto result = ui->next({});
|
||||
SDL_RemoveTimer(timer);
|
||||
if (result.action != bmh::launch::LauncherAction::end)
|
||||
return 1;
|
||||
std::puts("Native launcher rendered and exited successfully");
|
||||
return 0;
|
||||
} catch (const std::exception &error) {
|
||||
std::fprintf(stderr, "%s\n", error.what());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,39 @@ 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-navigation/before-options-0.5.3.png": {
|
||||
"493984e53b85c516a3a541ae879fdd18fdc7ec54a4d6478c571865bee15a9b44",
|
||||
},
|
||||
"docs/qa/editor-navigation/dropdown-matchday-de.png": {
|
||||
"594bdce386a91e2ef24fbab72d4910eed0899d8c108087b1cf00f9750e949b58",
|
||||
},
|
||||
"docs/qa/editor-navigation/dropdown-midnight-de.png": {
|
||||
"42cc11138163ce0a030c85fc5cb5c1204dbb7c05cfd7f8ef16cff8f6f6eeb422",
|
||||
},
|
||||
"docs/qa/editor-navigation/dropdown-silver-en.png": {
|
||||
"4ec9bf9a7af979c1c72f5cc6cd1b8a969f579a9680d8afc00837fff71da87a22",
|
||||
},
|
||||
"docs/qa/editor-navigation/history-midnight-de.png": {
|
||||
"7f141a6283ee946e17caa5d82a37503776133090fe86f82f0f9b2180b6444706",
|
||||
},
|
||||
"docs/qa/editor-navigation/options-midnight-de.png": {
|
||||
"3facf3da00290e5d39f0eeb210f657ae1040fce54f3e48e81529875e5d6f3fc9",
|
||||
},
|
||||
'docs/qa/editor-images/before-club-image.png': {
|
||||
'ac57bbbce2b8b7f71dad1d9e94d7b7baf182cb337d3800b5aac7a7f65db456bc',
|
||||
},
|
||||
'docs/qa/editor-images/linked-asset.png': {
|
||||
'76717df021e0c6db9a4afcab283923a20c2bf47d43f7e111303dca66041d3bf8',
|
||||
},
|
||||
'docs/qa/editor-images/preview-matchday-de.png': {
|
||||
'b7c0fad929fb28d25ef9e104e4ee90e62ab1d6e5ff8746bd0e8805bc2204d410',
|
||||
},
|
||||
'docs/qa/editor-images/preview-midnight-de.png': {
|
||||
'cc0ba1b7a1e4ea21f06fa9eb254a8b523da79bfa495a5068e345651619ab0407',
|
||||
},
|
||||
'docs/qa/editor-images/preview-silver-en.png': {
|
||||
'8704055293f58796b92057bc8a0c111b4db8bcaca297e45b7cb8d4bcacdd9a92',
|
||||
},
|
||||
"docs/qa/editor-regulations/before-competitions-0.5.1.png": {
|
||||
"cffa594e4d5ee942e086ab24fe7744a53dab4d5083dc1659f5e4b3ebdaee1f0b",
|
||||
},
|
||||
@@ -109,6 +142,7 @@ PROJECT_ARTWORK = {
|
||||
"assets/launcher/stadium.tga": {
|
||||
"08f82783a357d5b0722f3737de54844150bc14d98036845f1aaee3211608e1c8",
|
||||
"fb8e5f1f86afe60de87b70a2f533690d1ef470241fa24ee4384ff000149edaab",
|
||||
"8bd89b7db8dbd0e92707240c5367cb92f8f32c2903e08157d0f278ac2599d6cf",
|
||||
},
|
||||
"docs/qa/editor-poc/clubs-silver-de.png": {
|
||||
"3e557f68bf8d0e8186dc237f9e92f6b9c7743d7df79fd29c3a5838ba01c116f2",
|
||||
|
||||