Build 0.2 native launcher and portable Classic runtime (by Codex)
This commit is contained in:
1 parent
3a021fc160
commit
2552528176
84 files changed
+5004
-197
No files matched your search
@@ -3,7 +3,7 @@ name: Build without game data
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
branches: [main, assist/codex-0.2-launcher]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
workflow_call:
|
||||
|
||||
+12
-7
@@ -1,6 +1,6 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-only
|
||||
cmake_minimum_required(VERSION 3.24)
|
||||
project(OpenBMH VERSION 0.1.2 LANGUAGES CXX C)
|
||||
project(OpenBMH VERSION 0.2.0 LANGUAGES CXX C)
|
||||
# the one place of the version: --version of both programs and the window title (src/version.hpp)
|
||||
add_compile_definitions(OPENBMH_VERSION="${PROJECT_VERSION}")
|
||||
|
||||
@@ -196,6 +196,10 @@ bmh_add_data_test(NAME highscore_tests REQUIRED_OPTIONS BMH_TEST_HIGHSCORE_TESTS
|
||||
# Engine core: file formats and game logic, no platform dependencies
|
||||
add_library(bmhcore STATIC
|
||||
src/formats/binary.cpp
|
||||
src/formats/content.cpp
|
||||
src/formats/native_state.cpp
|
||||
src/formats/native_file.cpp
|
||||
src/cli/json.cpp
|
||||
src/formats/palette.cpp
|
||||
src/formats/vga.cpp
|
||||
src/formats/font.cpp
|
||||
@@ -264,10 +268,10 @@ else()
|
||||
target_compile_options(bmhcore PRIVATE -Wall -Wextra)
|
||||
endif()
|
||||
|
||||
add_executable(openbmh src/main.cpp)
|
||||
target_link_libraries(openbmh PRIVATE bmhcore ${BMH_SDL_TARGET})
|
||||
add_executable(openbmh_inspect src/main.cpp)
|
||||
target_link_libraries(openbmh_inspect PRIVATE bmhcore ${BMH_SDL_TARGET})
|
||||
if(MSVC)
|
||||
target_compile_options(openbmh PRIVATE /utf-8)
|
||||
target_compile_options(openbmh_inspect PRIVATE /utf-8)
|
||||
endif()
|
||||
|
||||
# --- Game data launcher (src/launch): find, unpack and check the original game data ---------
|
||||
@@ -317,6 +321,7 @@ endif()
|
||||
|
||||
add_subdirectory(src/ui)
|
||||
add_subdirectory(src/import)
|
||||
target_link_libraries(bmhui PUBLIC bmh_content)
|
||||
add_executable(driver_barrier_tests tests/driver_barrier_tests.cpp)
|
||||
target_link_libraries(driver_barrier_tests PRIVATE bmhcore)
|
||||
add_test(NAME driver_barrier_tests COMMAND driver_barrier_tests)
|
||||
@@ -439,10 +444,10 @@ add_executable(openbmh_play
|
||||
src/app/main.cpp
|
||||
${BMH_APP_CONTROLLER_SOURCE}
|
||||
${BMH_APP_SESSION_SDL_SOURCE})
|
||||
target_link_libraries(openbmh_play PRIVATE bmhui bmhlaunch_dialog openbmh_audio ${BMH_SDL_TARGET})
|
||||
target_link_libraries(openbmh_play PRIVATE bmhui bmh_launcher bmhlaunch_dialog openbmh_audio ${BMH_SDL_TARGET})
|
||||
# a game without a console window on double-click (SDL2main provides WinMain); started from a
|
||||
# console it attaches to that one for --version, --help and start errors (src/app/main.cpp)
|
||||
set_target_properties(openbmh_play PROPERTIES WIN32_EXECUTABLE TRUE)
|
||||
set_target_properties(openbmh_play PROPERTIES WIN32_EXECUTABLE TRUE OUTPUT_NAME OpenBMH)
|
||||
if(MSVC)
|
||||
target_compile_options(openbmh_play PRIVATE /utf-8)
|
||||
# App sources also compile in headless tests/helpers without target /utf-8.
|
||||
@@ -622,7 +627,7 @@ add_executable(openbmh_cli
|
||||
src/cli/seat_hub.cpp
|
||||
src/cli/json.cpp
|
||||
${BMH_APP_SESSION_SOURCE})
|
||||
target_link_libraries(openbmh_cli PRIVATE bmhui bmhlaunch)
|
||||
target_link_libraries(openbmh_cli PRIVATE bmh_launcher bmhui bmhlaunch)
|
||||
if(WIN32)
|
||||
target_link_libraries(openbmh_cli PRIVATE ws2_32) # --listen (Winsock)
|
||||
endif()
|
||||
|
||||
@@ -4,7 +4,7 @@ A modern and faithful open source rebuild of the *Bundesliga Manager Hattrick* e
|
||||
|
||||
OpenBMH is a standalone C++20 engine with an SDL2 interface for *Bundesliga Manager Hattrick* (1994/95) and its English edition, *Football Limited*. The project develops a playable reconstruction alongside a platform for new rules, content and interfaces. Keeping the familiar game enjoyable and making it easier to extend are equally important goals.
|
||||
|
||||
The engine reads a game installation supplied by the player. Game data, artwork, music, manuals and the original executable are not distributed with OpenBMH. Its aim is recognisable behaviour and plausible results; documented compatibility decisions and safety fixes take precedence over reproducing every original fault.
|
||||
The 0.2 development branch imports a game installation supplied by the player into a portable Classic mod. The running game reads the converted OBW content. Game data, artwork, music, manuals and the original executable are not distributed with OpenBMH. Its aim is recognisable behaviour and plausible results; documented compatibility decisions and safety fixes take precedence over reproducing every original fault.
|
||||
|
||||
This is an independent community project, with no affiliation with or endorsement by the original rights holders, the DFL or the Bundesliga. It is an engine implementation, not an official source release or a remaster.
|
||||
|
||||
@@ -12,18 +12,26 @@ 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.
|
||||
|
||||
1. Have your own supported game installation available.
|
||||
2. Extract the OpenBMH package into a separate directory, or alongside the game files.
|
||||
3. Start `openbmh_play` (`openbmh_play.exe` on Windows). Select the game directory or executable when prompted. A ZIP or 7z containing one game installation can also be selected.
|
||||
These instructions describe the **0.2 development branch**, not the published 0.1.2 package.
|
||||
|
||||
From a terminal:
|
||||
1. Extract OpenBMH into a writable directory.
|
||||
2. Start `OpenBMH.exe` on Windows, or `OpenBMH` on Linux/macOS. Its native launcher initially has an empty **Name | Art** list.
|
||||
3. Choose **Add**, select your own BMH or Football Limited installation, and enter a unique mod name and starting display year. The default names are `BMH-classic` and `FTDL-classic` (the English format identifier is `FLTD-classic`).
|
||||
4. Optionally transfer saved games and settings from the installation or another folder. The import reports files it could not migrate.
|
||||
5. Select the resulting Classic mod and choose **Start**. After import, its original installation is no longer needed for play.
|
||||
|
||||
Converted contents live in `mods/<name>/content.obw` next to the program. Saves (`.obs`), settings (`.obsettings`), desktop layouts (`.oblayout`) and high scores (`.obscore`) live separately in `userdata/<content-id>/`. **Delete** asks before removing a mod and retains personal data; importing identical contents reconnects them. **Rename** renames the mod directory. Externally modified Classic packages are rejected; import the installation again to repair them. Keep backups of the portable directory.
|
||||
|
||||
For direct startup or the console:
|
||||
|
||||
```sh
|
||||
openbmh_play --data "path/to/game" --save-directory "path/to/saves"
|
||||
openbmh_cli --console --data "path/to/game" --saves "path/to/saves"
|
||||
./OpenBMH --mod "mods/BMH-classic/content.obw"
|
||||
./openbmh_cli --console --mod "mods/BMH-classic/content.obw"
|
||||
```
|
||||
|
||||
Use a writable save directory and keep backups of existing games. German editions are the primary compatibility target. **Football Limited / English data support is experimental**; original V2.20 save import and some edition-specific behaviour remain limited. See the [0.1 release notes](docs/release/0.1/RELEASE_NOTES.md).
|
||||
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.
|
||||
|
||||
See the [0.2 migration contract](docs/formats/obw/runtime-0.2.md) for compatibility and validation limits. Native Windows and macOS behaviour must be checked on their target platforms before a 0.2 release.
|
||||
|
||||
## Features and direction
|
||||
|
||||
@@ -31,11 +39,11 @@ The graphical client and console share career management, matches, transfers, co
|
||||
|
||||
Version 0.1 establishes the playable engine and development interfaces. Later milestones introduce an open data format and typed model, configurable rules, a scalable interface and independently distributable content. These are goals rather than delivery dates; the [roadmap](docs/ROADMAP.md) describes their dependencies.
|
||||
|
||||
The standalone [`openbmh_import` tool](docs/formats/obw/import.md) converts BMH and Football Limited installations into **BMH-classic** / **FLTD-classic** OBW worlds, including media and frozen player portrait recipes. The content targets the versioned Classic adapter planned for 0.2; the 0.1 game does not load OBW. Savegame conversion is separate future work. The importer is built from current source and included in subsequent CI packages; it is absent from the already published 0.1.2 packages.
|
||||
The standalone [`openbmh_import` tool](docs/formats/obw/import.md) produces the same complete Classic content packages, including media and frozen player portrait recipes. A mod directory contains its sealed `content.obw`; legacy save migration is performed through the launcher.
|
||||
|
||||
## Build from source
|
||||
|
||||
The following recipes target v0.1.2. They require Git, CMake 3.24 or newer and a C++20 compiler. The first configure fetches pinned open-source dependencies. Native build and package results are documented for each release; these instructions do not claim an untested platform result.
|
||||
The following recipes target this 0.2 development branch. They require Git, CMake 3.24 or newer and a C++20 compiler. The first configure fetches pinned open-source dependencies. Native build and package results are documented for each release; these instructions do not claim an untested platform result.
|
||||
|
||||
Clone the public repository, then run the commands for your system:
|
||||
|
||||
@@ -52,7 +60,7 @@ Install Visual Studio 2022 or its Build Tools with **Desktop development with C+
|
||||
cmake -S . -B build-windows -G "Visual Studio 17 2022" -A x64
|
||||
cmake --build build-windows --config Release
|
||||
ctest --test-dir build-windows -C Release --output-on-failure
|
||||
.\build-windows\Release\openbmh_play.exe --data "path/to/game" --save-directory "path/to/saves"
|
||||
.\build-windows\Release\OpenBMH.exe
|
||||
```
|
||||
|
||||
### Linux
|
||||
@@ -64,7 +72,7 @@ sudo apt install build-essential git cmake ninja-build pkg-config libgtk-3-dev l
|
||||
cmake -S . -B build-linux -G Ninja -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build-linux
|
||||
ctest --test-dir build-linux --output-on-failure
|
||||
./build-linux/openbmh_play --data "path/to/game" --save-directory "path/to/saves"
|
||||
./build-linux/OpenBMH
|
||||
```
|
||||
|
||||
Use a newer CMake if your distribution ships a version older than 3.24. A Linux binary can still require system libraries such as GTK3; a ZIP is not a guarantee of portability across distributions.
|
||||
@@ -79,7 +87,7 @@ brew install cmake ninja
|
||||
cmake -S . -B build-macos -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_OSX_ARCHITECTURES=arm64
|
||||
cmake --build build-macos
|
||||
ctest --test-dir build-macos --output-on-failure
|
||||
./build-macos/openbmh_play --data "path/to/game" --save-directory "path/to/saves"
|
||||
./build-macos/OpenBMH
|
||||
```
|
||||
|
||||
On Intel Macs omit the arm64 setting or select `x86_64`. These commands build terminal executables; they do not create a signed application bundle.
|
||||
@@ -105,6 +113,6 @@ The implementation grew from study of file formats and behaviour of a legally ob
|
||||
|
||||
OpenBMH's own code and documentation are licensed under **GNU GPL version 3 only**, SPDX **GPL-3.0-only**. [LICENSE](LICENSE) contains the unchanged GPLv3 text; the example wording in its appendix does not change this project's version choice. Game content has separate ownership and is not covered by this license.
|
||||
|
||||
Release source is identified by the matching version tag: [v0.1.2](https://github.com/Weyoune/openbmh/tree/v0.1.2) for this version. Binary releases must accompany or offer the corresponding source and build/relinking materials required by the applicable licenses. The tag identifies application source; it does not replace required materials for linked third-party components.
|
||||
Release source is identified by the matching version tag: [v0.1.2](https://github.com/Weyoune/openbmh/tree/v0.1.2) for the published 0.1.2 version. This branch develops 0.2; it is not a published release. Binary releases must accompany or offer the corresponding source and build/relinking materials required by the applicable licenses. The tag identifies application source; it does not replace required materials for linked third-party components.
|
||||
|
||||
Bundled components retain their own licenses, including Nuked OPL3 under LGPL-2.1-or-later. See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) and [ACKNOWLEDGEMENTS.md](ACKNOWLEDGEMENTS.md).
|
||||
+7
-5
@@ -10,7 +10,7 @@ ctest --test-dir build --output-on-failure
|
||||
|
||||
The public checkout does not include game data. Tests that require a game installation are conditional; configure with `-DBMH_DATA="path/to/game"` to make locally available data eligible. Private saved-game fixtures are not supplied by the project. Read the test output to distinguish executed and skipped checks.
|
||||
|
||||
Main programs are `openbmh_play` (graphical game) and `openbmh_cli` (console and protocol). Single-configuration generators put them in the build directory; multi-configuration generators normally add a configuration directory. On Windows they have the `.exe` suffix.
|
||||
Main programs are `OpenBMH` (native launcher and graphical game) and `openbmh_cli` (console and protocol). Single-configuration generators put them in the build directory; multi-configuration generators normally add a configuration directory. On Windows they have the `.exe` suffix.
|
||||
|
||||
## Windows
|
||||
|
||||
@@ -26,7 +26,7 @@ With a Visual Studio generator, choose one actually provided by your installed C
|
||||
|
||||
## Linux
|
||||
|
||||
Install a C++20 compiler, Git, CMake, Ninja, pkg-config and the development packages required by SDL2 and the dialog backend. The default Linux dialog backend uses GTK3. For example, Debian-family development packages include `build-essential`, `cmake`, `ninja-build`, `git`, `pkg-config` and `libgtk-3-dev`; SDL2's selected video/audio backends may need additional development libraries.
|
||||
Install a C++20 compiler, Git, CMake, Ninja, pkg-config and the development packages required by SDL2 and the dialog backend. The native Linux launcher uses GTK3. For example, Debian-family development packages include `build-essential`, `cmake`, `ninja-build`, `git`, `pkg-config` and `libgtk-3-dev`; SDL2's selected video/audio backends may need additional development libraries.
|
||||
|
||||
The common commands above build the bundled SDL2. To use an installed SDL2 CMake package instead, configure with `-DBMH_USE_SYSTEM_SDL2=ON`. Its version and backend configuration then come from the installed package.
|
||||
|
||||
@@ -42,11 +42,13 @@ ctest --test-dir build-macos --output-on-failure
|
||||
|
||||
Use native toolchain/dependency architectures consistently. A terminal executable and a Finder-launchable, signed `.app` package are different deliverables. The commands describe the build procedure, not a claim that a particular Windows or macOS binary has passed native acceptance.
|
||||
|
||||
## Run with your data
|
||||
## Import and run your data
|
||||
|
||||
Start the native launcher, choose **Add**, and select your original installation. Content and personal files are portable beside the executable. The original installation is needed only for import. See the [0.2 contract](formats/obw/runtime-0.2.md).
|
||||
|
||||
```sh
|
||||
build/openbmh_play --data "path/to/game" --save-directory "path/to/saves"
|
||||
build/openbmh_cli --console --data "path/to/game" --saves "path/to/saves" --seed 1
|
||||
build/OpenBMH
|
||||
build/openbmh_cli --console --mod "build/mods/BMH-classic/content.obw" --seed 1
|
||||
```
|
||||
|
||||
For redistribution, include [LICENSE](../LICENSE), [THIRD_PARTY_NOTICES.md](../THIRD_PARTY_NOTICES.md), the full texts in [licenses/](licenses/README.md), and the corresponding source and build information required by the applicable licenses. Inspect the actual libraries in each platform package; static SDL2 alone does not establish that every dependency is static.
|
||||
@@ -46,3 +46,20 @@ instead of an added fixed pause. A9 and the existing scene delays can be adjuste
|
||||
in Settings; loaded saves and EIN files retain their chosen speeds. VGA retrace
|
||||
animations use a 70-Hz reference instead of the host monitor's refresh rate.
|
||||
`--live-frame-ms` and `BMH_LIVE_FRAME_MS` remain explicit diagnostic overrides.
|
||||
|
||||
## Native data and saves in 0.2
|
||||
|
||||
Classic imports preserve the supported BMH and Football Limited structures in sealed OBW
|
||||
packages. The normal runtime no longer reads the original installation. Package integrity
|
||||
failures require reimport; Classic overlays and manual content editing are unsupported.
|
||||
|
||||
Native saving and autosaving consume no random numbers. The FBM writer previously drew
|
||||
four Watcom values for its encryption envelope, so future results after a legacy save
|
||||
operation can differ. A native save/load pair preserves both generators and their draw
|
||||
counts exactly. Original saves lack the clock-seeded Watcom state; migration derives its
|
||||
initial value reproducibly from the source file and records the full state thereafter.
|
||||
|
||||
The launcher start year affects displayed years only. Classic weekdays and season timing
|
||||
retain their existing cycle. Imported careers keep the valid year in their own save header.
|
||||
The launcher exits without confirmation; the running game's existing exit confirmation
|
||||
remains in effect and returns control to the launcher after a confirmed exit.
|
||||
@@ -4,12 +4,12 @@ The console is a local control interface for one running career. Human clients,
|
||||
|
||||
## Choose a transport
|
||||
|
||||
For a single process, start `openbmh_cli --console --data "path/to/game" --saves "path/to/saves"`. Send command lines on stdin and finish each block with `go.`. `--json` provides structured output records.
|
||||
For a single process, start `openbmh_cli --console --mod "mods/BMH-classic/content.obw" --saves "path/to/saves"`. Send command lines on stdin and finish each block with `go.`. `--json` provides structured output records.
|
||||
|
||||
For separate manager processes, start a local mailbox server:
|
||||
|
||||
```sh
|
||||
openbmh_cli --console --data "path/to/game" --saves "path/to/saves" --serve mailbox --seats 4 --seed 1
|
||||
openbmh_cli --console --mod "mods/BMH-classic/content.obw" --saves "path/to/saves" --serve mailbox --seats 4 --seed 1
|
||||
```
|
||||
|
||||
A client sends one block on stdin to:
|
||||
|
||||
@@ -6,6 +6,7 @@ See [Compatibility decisions](COMPATIBILITY.md) for the overall policy. These en
|
||||
describe deliberate changes; they are not a list of every known compatibility limit.
|
||||
|
||||
- [src/app/career_session.cpp](../src/app/career_session.cpp): supports designated set-piece record initialization and validation.
|
||||
- [src/app/career_session.cpp](../src/app/career_session.cpp): native saves do not consume gameplay randomness for encryption.
|
||||
- [src/app/quit_confirmation.hpp](../src/app/quit_confirmation.hpp): confirms application exit with a localized native dialog, with cancellation selected by default.
|
||||
- [src/formats/le.hpp](../src/formats/le.hpp): applies a shared supported rule profile when loading editions with different rule-table values.
|
||||
- [src/formats/rule_base.cpp](../src/formats/rule_base.cpp): normalizes live-scene defaults, league strength ranges, option defaults, stadium prices and capacities, betting limits, and the foreign-player limit across supported editions.
|
||||
|
||||
+17
-2
@@ -12,8 +12,9 @@ OpenBMH is a C++20 engine with graphical and console frontends. The implementati
|
||||
| `src/ui` | View projections, rendering and input interpretation for game screens |
|
||||
| `src/cli` | Command language, structured protocol, console windows and multi-client seat routing |
|
||||
| `src/audio` | Bank decoding, synthesis, playback and cues, without authority to change gameplay |
|
||||
| `src/launch` | Locating user data, archive extraction, edition normalisation and file selection |
|
||||
| `src/import` | Standalone legacy-to-OBW conversion; no game-state ownership or OBW engine integration |
|
||||
| `src/launch` | Native launcher, portable mod library, child processes and legacy installation discovery |
|
||||
| `src/content` | Sealed OBW content, native career containers and personal preferences |
|
||||
| `src/import` | Legacy installation and save-layout conversion; original readers are used here |
|
||||
|
||||
`bmhcore` contains the format and game layers. `bmhui`, `openbmh_audio` and the application session provide reusable pieces above it. Frontends should translate actions and display results; they should not introduce independent transfer, calendar or financial rules.
|
||||
|
||||
@@ -38,3 +39,17 @@ Legacy saves serialize blocks in a fixed order and store name pools separately.
|
||||
The [console reference](CLI_CONCEPT/README.md) documents window commands. [protocol.md](protocol.md) describes structured requests, and [CONSOLE_CLIENTS.md](CONSOLE_CLIENTS.md) explains safe client ownership and batching. Prefer shared projections/actions when adding another frontend.
|
||||
|
||||
Use synthetic data for public tests and locally supplied installations only for data-dependent checks. Renderer tests, simulation tests and target-platform runtime checks answer different questions; document what each validates. See [CONTRIBUTING.md](../CONTRIBUTING.md).
|
||||
|
||||
## 0.2 content boundary
|
||||
|
||||
Normal GUI and console entrypoints accept sealed Classic OBW packages. `content::Mount`
|
||||
owns a shared immutable decoded store; existing path-shaped UI aliases identify resources
|
||||
inside it, without creating VGA/FNT/EXE files or falling back to an installation on disk.
|
||||
The only mutable mount setting is the presentation year of the selected career. Native
|
||||
`.obs` checkpoints serialize named fields, compatibility memory blocks, both random
|
||||
streams, Reality residues and the manager-desk driver. No host object, pointer or callback
|
||||
is dumped. The session reconstructs content pointers and callbacks when loading.
|
||||
|
||||
The native launcher remains the parent process. Each game starts in a fresh child process
|
||||
of `OpenBMH`, keeping edition-specific process globals isolated. Portable mod content and
|
||||
personal files have independent lifetimes. See [runtime-0.2](formats/obw/runtime-0.2.md).
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# OBW: OpenBMH world, save and pack format (concept, format version 1.0)
|
||||
|
||||
Status: **format concept with a complete Classic installation-content converter** for roadmap 0.2, with preparation for 0.4. `openbmh_import` produces `BMH-classic` and `FLTD-classic` worlds under the guarded [`runtime:classic-v1` contract](obw/classic-v1.md), including all startup inputs and media. The [import guide](obw/import.md) distinguishes this from the explicitly partial `legacy-database-v1` development export. The 0.1 engine still reads legacy installations; OBW runtime integration and savegame conversion are separate work.
|
||||
Status: **format concept with a complete Classic installation-content converter** for roadmap 0.2, with preparation for 0.4. `openbmh_import` produces `BMH-classic` and `FLTD-classic` worlds under the guarded [`runtime:classic-v1` contract](obw/classic-v1.md), including all startup inputs and media. The [import guide](obw/import.md) distinguishes this from the explicitly partial `legacy-database-v1` development export. The 0.2 development branch adds a sealed Classic runtime, portable launcher and native career checkpoints; see [the runtime contract](obw/runtime-0.2.md). The released 0.1 engine still reads legacy installations.
|
||||
|
||||
## 1. Goals and non-goals
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
<!-- SPDX-License-Identifier: GPL-3.0-only -->
|
||||
# Classic runtime and portable launcher (0.2 development)
|
||||
|
||||
This contract is for the 0.2 development branch. It is not a release validation claim.
|
||||
|
||||
## Portable layout and lifecycle
|
||||
|
||||
`OpenBMH.exe` (Windows) / `OpenBMH` (Linux and macOS) starts the operating system's
|
||||
native launcher: one selected row, **Name | Art**, and **Start, Add, Delete, Rename, End**.
|
||||
No installation is auto-selected on first launch. Add converts an externally owned
|
||||
installation; original assets never belong in a distribution.
|
||||
|
||||
```
|
||||
OpenBMH[.exe]
|
||||
mods/<name>/content.obw
|
||||
userdata/<content-id>/*.obs
|
||||
userdata/<content-id>/*.obsettings
|
||||
userdata/<content-id>/*.oblayout
|
||||
userdata/<content-id>/highscore-<signature>.obscore
|
||||
```
|
||||
|
||||
The directory name is the launcher name, separate from `manifest.mod` (`BMH-classic`
|
||||
or `FLTD-classic`). `FTDL-classic` is the requested English directory-name default.
|
||||
Names must be portable single path components; duplicates are case-insensitive.
|
||||
Classic files are sealed, not editable world overlays. Modern gameplay is not implemented.
|
||||
|
||||
Rename changes the directory only. Delete removes mod content after confirmation and
|
||||
retains user data. Reimporting the same content and start year reconnects it. The content
|
||||
identity excludes display title, generator version and the CRC inventory, but includes
|
||||
runtime content and the starting-year configuration. It deliberately changes when content
|
||||
actually changes. User data cannot be silently associated with a different database.
|
||||
|
||||
The launcher starts a child process of the same binary, with `--run-mod` and a separate
|
||||
save directory, and remains available after the child exits. `--mod <content.obw>` bypasses
|
||||
the launcher. A normal GUI/console invocation cannot fall back to original game files.
|
||||
|
||||
## Integrity and content access
|
||||
|
||||
The existing `classic-installation-v1` payload is complemented by
|
||||
`x-classic/seal.json` (`classic-seal@1.0`): SHA-256 for every other archive entry plus
|
||||
`content_id`. The earlier CRC inventory excludes the seal to avoid a circular digest.
|
||||
A missing seal, changed entry or unexpected file in a Classic mod directory prevents start.
|
||||
SHA-256 detects ordinary manual changes/corruption; it is not a signature or a promise
|
||||
against a local owner modifying the validator.
|
||||
|
||||
The runtime decodes indexed images, fonts and palettes into an immutable store. Existing
|
||||
UI aliases such as `KB/29.VGA` select the already decoded object; they are not files.
|
||||
Embedded image palettes are imported separately, preserving the Sportschau/title colours.
|
||||
Original single-byte readme content is preserved in the local package where available.
|
||||
No original executable is reconstructed or executed.
|
||||
|
||||
## Native careers and personal files
|
||||
|
||||
A `.obs` ZIP contains the complete sealed starting world, with its original manifest at
|
||||
`state/world-manifest.json`. The top manifest has `kind: save`,
|
||||
`save_profile: classic-career-v1` and the content identity.
|
||||
|
||||
| Entry | Native contract |
|
||||
|---|---|
|
||||
| `state/career.json` | `classic-state@1.0`: named typed arrays/scalars, name bytes and explicitly addressed compatibility blocks |
|
||||
| `state/rng.json` | `classic-rng@1.0`: both seeds and decimal-string draw counters |
|
||||
| `state/session.json` | `classic-session@1.0`: runtime option bytes, stable desk arguments and manager mappings |
|
||||
| `state/driver.json` | `classic-driver@1.0`: desk stage/order, match groups, referees, event counter and previous results |
|
||||
| `state/information.json` | `classic-bytes@1.0`: Classic browser information fields |
|
||||
| `state/integrity.json` | `save-integrity@1.0`: SHA-256 of every other state entry |
|
||||
|
||||
Only existing manager-desk save boundaries are supported. Runtime callbacks and host
|
||||
pointers are reconstructed. Native saving is RNG-neutral; unlike the old FBM envelope it
|
||||
needs no random encryption fields. Both generator seeds and draw counters resume exactly.
|
||||
Names and compatibility bytes use hexadecimal encoding to retain single-byte values
|
||||
without pretending they are UTF-8. Integer fields have explicit bounds.
|
||||
|
||||
`.obsettings`, `.oblayout` and `.obscore` are JSON documents with kind-specific schema
|
||||
names (`classic-settings@1.0`, `classic-layout@1.0`, `classic-highscore@1.0`) and a
|
||||
`classic-bytes@1.0` payload. They preserve existing availability bits, layout chains and
|
||||
high-score fields. The existing application validators still govern settings and layouts.
|
||||
Writes publish a complete temporary file atomically; overwrites require the existing
|
||||
application confirmation.
|
||||
|
||||
## Legacy migration and Classic dates
|
||||
|
||||
Add defaults to transferring games/settings, with a separately selectable source directory.
|
||||
The source is read-only. Existing personal files are retained rather than overwritten.
|
||||
Individual failures appear in the import report.
|
||||
|
||||
German/OpenBMH V2.24 files use their documented block contract. Original Football Limited
|
||||
V2.20 has its own block translator, including FA Cup, League Cup and additional-cup memory.
|
||||
It is never accepted by merely changing a version string. Like the V2.20 loader, migration
|
||||
rebuilds its unsaved current match groups without replaying daily finances or shuffling
|
||||
saved manager order. Unknown/damaged versions fail explicitly.
|
||||
|
||||
Original FBM files do not contain the clock-seeded Watcom random state. Migration therefore
|
||||
seeds that stream reproducibly from SHA-256 of the source file. A converted career cannot
|
||||
promise the original machine's unknown random future; subsequent native checkpoints retain
|
||||
both streams in full.
|
||||
|
||||
The selected start year changes only displayed years for new careers. Weekdays and the
|
||||
original four-year calendar remain unchanged. Imported careers retain the year from their
|
||||
saved information header when it is valid. This cosmetic origin is independent of the
|
||||
immutable world's start configuration and is carried in the native career.
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://raw.githubusercontent.com/Weyoune/openbmh/main/docs/formats/obw/schema/1.0/classic-bytes.json",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": "classic-bytes@1.0"
|
||||
},
|
||||
"hex": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"hex"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://raw.githubusercontent.com/Weyoune/openbmh/main/docs/formats/obw/schema/1.0/classic-driver.json",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": "classic-driver@1.0"
|
||||
},
|
||||
"stage": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 2
|
||||
},
|
||||
"calendar_entry": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 65535
|
||||
},
|
||||
"manager_position": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4
|
||||
},
|
||||
"next_event_id": {
|
||||
"type": "string",
|
||||
"pattern": "^(0|[1-9][0-9]*)$",
|
||||
"maxLength": 20
|
||||
},
|
||||
"loaded_matchday_resume": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"suppress_remaining_pre_match_offers": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"national_nomination_desk": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"enable_national_nomination_desks": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"groups": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"desc": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 255
|
||||
},
|
||||
"minItems": 192,
|
||||
"maxItems": 208
|
||||
},
|
||||
"fixtures": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": -1,
|
||||
"maximum": 4095
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 64
|
||||
},
|
||||
"results": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 255
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 32
|
||||
},
|
||||
"cup_results": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 65535
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 32
|
||||
},
|
||||
"cup_other_leg": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 65535
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 32
|
||||
},
|
||||
"records": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 255
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 576
|
||||
},
|
||||
"end_minute": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 255
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 32
|
||||
},
|
||||
"spectators": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 32
|
||||
},
|
||||
"log": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 65535
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 1000000
|
||||
},
|
||||
"cup_addresses": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"minItems": 2,
|
||||
"maxItems": 2
|
||||
},
|
||||
"phase": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"ended": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"kickoff_void_mask": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"desc",
|
||||
"fixtures",
|
||||
"results",
|
||||
"cup_results",
|
||||
"cup_other_leg",
|
||||
"records",
|
||||
"end_minute",
|
||||
"spectators",
|
||||
"log",
|
||||
"cup_addresses",
|
||||
"phase",
|
||||
"ended",
|
||||
"kickoff_void_mask"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 6
|
||||
},
|
||||
"referee_source": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 255
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 255
|
||||
},
|
||||
"referees": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 255
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 255
|
||||
},
|
||||
"last_results": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"valid": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"date": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"calendar_entry": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 65535
|
||||
},
|
||||
"matchday": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 65535
|
||||
},
|
||||
"groups": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"desc": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 255
|
||||
},
|
||||
"minItems": 192,
|
||||
"maxItems": 208
|
||||
},
|
||||
"fixtures": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": -1,
|
||||
"maximum": 4095
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 64
|
||||
},
|
||||
"results": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 255
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 32
|
||||
},
|
||||
"cup_results": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 65535
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 32
|
||||
},
|
||||
"cup_other_leg": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 65535
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 32
|
||||
},
|
||||
"records": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 255
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 576
|
||||
},
|
||||
"end_minute": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 255
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 32
|
||||
},
|
||||
"spectators": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 32
|
||||
},
|
||||
"log": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 65535
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 1000000
|
||||
},
|
||||
"cup_addresses": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"minItems": 2,
|
||||
"maxItems": 2
|
||||
},
|
||||
"phase": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"ended": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"kickoff_void_mask": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"desc",
|
||||
"fixtures",
|
||||
"results",
|
||||
"cup_results",
|
||||
"cup_other_leg",
|
||||
"records",
|
||||
"end_minute",
|
||||
"spectators",
|
||||
"log",
|
||||
"cup_addresses",
|
||||
"phase",
|
||||
"ended",
|
||||
"kickoff_void_mask"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 6
|
||||
},
|
||||
"tournament_name": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 255
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 1000000
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"valid",
|
||||
"date",
|
||||
"calendar_entry",
|
||||
"matchday",
|
||||
"groups",
|
||||
"tournament_name"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"stage",
|
||||
"calendar_entry",
|
||||
"manager_position",
|
||||
"next_event_id",
|
||||
"loaded_matchday_resume",
|
||||
"suppress_remaining_pre_match_offers",
|
||||
"national_nomination_desk",
|
||||
"enable_national_nomination_desks",
|
||||
"groups",
|
||||
"referee_source",
|
||||
"referees",
|
||||
"last_results"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://raw.githubusercontent.com/Weyoune/openbmh/main/docs/formats/obw/schema/1.0/classic-highscore.json",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": "classic-highscore@1.0"
|
||||
},
|
||||
"payload": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": "classic-bytes@1.0"
|
||||
},
|
||||
"hex": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 720,
|
||||
"minLength": 720
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"hex"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"payload"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://raw.githubusercontent.com/Weyoune/openbmh/main/docs/formats/obw/schema/1.0/classic-layout.json",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": "classic-layout@1.0"
|
||||
},
|
||||
"payload": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": "classic-bytes@1.0"
|
||||
},
|
||||
"hex": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 1728,
|
||||
"minLength": 1728
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"hex"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"payload"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://raw.githubusercontent.com/Weyoune/openbmh/main/docs/formats/obw/schema/1.0/classic-rng.json",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": "classic-rng@1.0"
|
||||
},
|
||||
"watcom": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"seed": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"calls": {
|
||||
"type": "string",
|
||||
"pattern": "^(0|[1-9][0-9]*)$",
|
||||
"maxLength": 20
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"seed",
|
||||
"calls"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"game": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"seed": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"calls": {
|
||||
"type": "string",
|
||||
"pattern": "^(0|[1-9][0-9]*)$",
|
||||
"maxLength": 20
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"seed",
|
||||
"calls"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"watcom",
|
||||
"game"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://raw.githubusercontent.com/Weyoune/openbmh/main/docs/formats/obw/schema/1.0/classic-seal.json",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": "classic-seal@1.0"
|
||||
},
|
||||
"content_id": {
|
||||
"type": "string",
|
||||
"pattern": "^[0-9a-f]{64}$"
|
||||
},
|
||||
"entries": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string",
|
||||
"pattern": "^[0-9a-f]{64}$"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"content_id",
|
||||
"entries"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://raw.githubusercontent.com/Weyoune/openbmh/main/docs/formats/obw/schema/1.0/classic-session.json",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": "classic-session@1.0"
|
||||
},
|
||||
"runtime": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"address": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"value": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 255
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"address",
|
||||
"value"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 8192
|
||||
},
|
||||
"desk_callargs": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"minItems": 2,
|
||||
"maxItems": 2
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 4
|
||||
},
|
||||
"managers": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"minItems": 3,
|
||||
"maxItems": 3
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 4
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"runtime",
|
||||
"desk_callargs",
|
||||
"managers"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://raw.githubusercontent.com/Weyoune/openbmh/main/docs/formats/obw/schema/1.0/classic-settings.json",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": "classic-settings@1.0"
|
||||
},
|
||||
"payload": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": "classic-bytes@1.0"
|
||||
},
|
||||
"hex": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 360,
|
||||
"minLength": 360
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"hex"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"payload"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -0,0 +1,542 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://raw.githubusercontent.com/Weyoune/openbmh/main/docs/formats/obw/schema/1.0/classic-state.json",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": "classic-state@1.0"
|
||||
},
|
||||
"indoor": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"level": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"chance_rain": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"chance_temperature": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"last_shooter": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"last_pick_quality": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"live_scene": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"sportschau_selection_available": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"sportschau_club_threshold": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"list_toggle": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"lineups_frozen": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"offer_answer": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"transfer_notice_suppressed": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"pools_open": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"autosave_months": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"autosave_month": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"display_start_year": {
|
||||
"type": "integer",
|
||||
"minimum": 1900,
|
||||
"maximum": 9998
|
||||
},
|
||||
"date": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 3000000
|
||||
},
|
||||
"season_start": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 3000000
|
||||
},
|
||||
"development_balance": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"trend_rotation": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"season": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"team_morale": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"player_bonus": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"formations": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"manager_records": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"tactics": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"manager_options": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"club_table": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"club_heap_bc": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"club_heap_78": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"club_heap_b8": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"master_database_metadata": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"referee_names": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"stadium_names": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"tournament_name": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"manager_results": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"manager_ratings": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"position_history": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"league_rounds": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"results": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"stocks": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"foreign_strength": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"mailbox": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"club_names": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"player_names": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"squad_slots": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 65535
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 1000000
|
||||
},
|
||||
"team_flags": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 65535
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 1000000
|
||||
},
|
||||
"manager_teams": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": -1,
|
||||
"maximum": 4095
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 4
|
||||
},
|
||||
"live_matches": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 1000000
|
||||
},
|
||||
"sportschau_homes": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 65535
|
||||
},
|
||||
"minItems": 10,
|
||||
"maxItems": 10
|
||||
},
|
||||
"sportschau_priorities": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 255
|
||||
},
|
||||
"minItems": 10,
|
||||
"maxItems": 10
|
||||
},
|
||||
"club_ids": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 65535
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 1000000
|
||||
},
|
||||
"player_cards": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 65535
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 1000000
|
||||
},
|
||||
"player_name_offsets": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 65535
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 1000000
|
||||
},
|
||||
"players": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name_hex": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
},
|
||||
"form": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"skills": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"identity": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name_hex",
|
||||
"form",
|
||||
"skills",
|
||||
"identity"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 4095
|
||||
},
|
||||
"memory": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"address": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 4294967295
|
||||
},
|
||||
"hex": {
|
||||
"type": "string",
|
||||
"pattern": "^(?:[0-9a-f]{2})*$",
|
||||
"maxLength": 33554432
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"address",
|
||||
"hex"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"minItems": 0,
|
||||
"maxItems": 8192
|
||||
},
|
||||
"reality": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"initialized": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"deflected": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"card_kind": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 255
|
||||
},
|
||||
"distance": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"actors": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 255
|
||||
},
|
||||
"minItems": 5,
|
||||
"maxItems": 5
|
||||
},
|
||||
"grid": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"planes": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 255
|
||||
},
|
||||
"minItems": 1144,
|
||||
"maxItems": 1144
|
||||
},
|
||||
"minItems": 2,
|
||||
"maxItems": 2
|
||||
},
|
||||
"positions": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"minItems": 2,
|
||||
"maxItems": 2
|
||||
},
|
||||
"minItems": 24,
|
||||
"maxItems": 24
|
||||
},
|
||||
"ball": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"minItems": 2,
|
||||
"maxItems": 2
|
||||
},
|
||||
"previous_ball": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"minimum": -2147483648,
|
||||
"maximum": 2147483647
|
||||
},
|
||||
"minItems": 2,
|
||||
"maxItems": 2
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"planes",
|
||||
"positions",
|
||||
"ball",
|
||||
"previous_ball"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"initialized",
|
||||
"deflected",
|
||||
"card_kind",
|
||||
"distance",
|
||||
"actors",
|
||||
"grid"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"indoor",
|
||||
"level",
|
||||
"chance_rain",
|
||||
"chance_temperature",
|
||||
"last_shooter",
|
||||
"last_pick_quality",
|
||||
"live_scene",
|
||||
"sportschau_selection_available",
|
||||
"sportschau_club_threshold",
|
||||
"list_toggle",
|
||||
"lineups_frozen",
|
||||
"offer_answer",
|
||||
"transfer_notice_suppressed",
|
||||
"pools_open",
|
||||
"autosave_months",
|
||||
"autosave_month",
|
||||
"display_start_year",
|
||||
"date",
|
||||
"season_start",
|
||||
"development_balance",
|
||||
"trend_rotation",
|
||||
"season",
|
||||
"team_morale",
|
||||
"player_bonus",
|
||||
"formations",
|
||||
"manager_records",
|
||||
"tactics",
|
||||
"manager_options",
|
||||
"club_table",
|
||||
"club_heap_bc",
|
||||
"club_heap_78",
|
||||
"club_heap_b8",
|
||||
"master_database_metadata",
|
||||
"referee_names",
|
||||
"stadium_names",
|
||||
"tournament_name",
|
||||
"manager_results",
|
||||
"manager_ratings",
|
||||
"position_history",
|
||||
"league_rounds",
|
||||
"results",
|
||||
"stocks",
|
||||
"foreign_strength",
|
||||
"mailbox",
|
||||
"club_names",
|
||||
"player_names",
|
||||
"squad_slots",
|
||||
"team_flags",
|
||||
"manager_teams",
|
||||
"live_matches",
|
||||
"sportschau_homes",
|
||||
"sportschau_priorities",
|
||||
"club_ids",
|
||||
"player_cards",
|
||||
"player_name_offsets",
|
||||
"players",
|
||||
"memory",
|
||||
"reality"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://raw.githubusercontent.com/Weyoune/openbmh/main/docs/formats/obw/schema/1.0/save-integrity.json",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"const": "save-integrity@1.0"
|
||||
},
|
||||
"entries": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "string",
|
||||
"pattern": "^[0-9a-f]{64}$"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"entries"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://raw.githubusercontent.com/Weyoune/openbmh/main/docs/formats/obw/schema/1.0/save-manifest.json",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"format",
|
||||
"format_version",
|
||||
"kind",
|
||||
"save_profile",
|
||||
"content_id"
|
||||
],
|
||||
"properties": {
|
||||
"format": {
|
||||
"const": "openbmh-world"
|
||||
},
|
||||
"format_version": {
|
||||
"const": "1.0"
|
||||
},
|
||||
"kind": {
|
||||
"const": "save"
|
||||
},
|
||||
"save_profile": {
|
||||
"const": "classic-career-v1"
|
||||
},
|
||||
"content_id": {
|
||||
"type": "string",
|
||||
"pattern": "^[0-9a-f]{64}$"
|
||||
}
|
||||
},
|
||||
"additionalProperties": true
|
||||
}
|
||||
+227
-19
@@ -1,6 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/executable_layout.hpp"
|
||||
#include "app/career_session.hpp"
|
||||
#include "content/save.hpp"
|
||||
#include "import/save.hpp"
|
||||
|
||||
#include <stdexcept>
|
||||
#include <system_error>
|
||||
@@ -560,6 +562,11 @@ CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_
|
||||
session_id_ = next_session_id.fetch_add(1, std::memory_order_relaxed);
|
||||
initialize_club_modal_runtime();
|
||||
g_ = startup_state(exe_, db_, read_file(data / "M3.MEN"), read_file(data / "M3.DAT"));
|
||||
if (const auto resource = content::find(data)) {
|
||||
g_.display_start_year = resource->content->start_year;
|
||||
content::set_display_start_year(data, g_.display_start_year);
|
||||
exe_.set_display_start_year(g_.display_start_year);
|
||||
}
|
||||
g_.texts = &texts_;
|
||||
g_.currency_suffix = exe_.cstring(::bmh::layout::CurrencySuffixText); // CurrencySuffixText
|
||||
configure_training_camp_data(g_, exe_);
|
||||
@@ -567,14 +574,18 @@ CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_
|
||||
g_.credit_divisor = std::bit_cast<double>(uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField)) | uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField2)) << 32);
|
||||
g_.credit_rate_table_available = true;
|
||||
install_default_hooks();
|
||||
if (content::find(data))
|
||||
turn_driver_.desk_autosave = [this](const GameState &state, WatcomRandom &random) {
|
||||
write_desk_autosave(state, random);
|
||||
};
|
||||
startup_players(g_, game_, rand_); // CareerFirstSteps2
|
||||
MinuteReport report;
|
||||
if (!new_career_before_dialog(g_, game_, rand_, report)) // InitializeCareer up to the dialog
|
||||
throw std::runtime_error("career start: " + report.reason);
|
||||
}
|
||||
|
||||
CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_seed,
|
||||
const std::filesystem::path& save_path)
|
||||
CareerSession::CareerSession(const std::filesystem::path &data, uint32_t watcom_seed,
|
||||
const std::filesystem::path &save_path, bool importing_legacy)
|
||||
: data_directory_(data), exe_(load_le(data / "BMH.exe")), db_(load_database(data / "M3D.MAN")),
|
||||
texts_(load_textd(data / "TEXTD.BLK")), rand_(watcom_seed) {
|
||||
install_league_sizes(exe_);
|
||||
@@ -584,15 +595,48 @@ CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_
|
||||
? TransferAllocatorContext::zero : TransferAllocatorContext::blocked;
|
||||
session_id_ = next_session_id.fetch_add(1, std::memory_order_relaxed);
|
||||
initialize_club_modal_runtime();
|
||||
const Savegame file = load_savegame(save_path);
|
||||
if (!file.checksum_ok || file.version != "V2.24") throw std::runtime_error("savegame: unsupported or damaged FBM");
|
||||
const DbCounts counts{exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField), exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField3), exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField2), exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField4)};
|
||||
const SaveState save(file.stream, counts);
|
||||
g_ = GameState::from_save(save, counts);
|
||||
bool original_english_save = false;
|
||||
std::optional<content::SavedCareer> native;
|
||||
if (const auto resource = content::find(data); resource && !importing_legacy) {
|
||||
if (content::key(save_path.extension()) != ".obs")
|
||||
throw FormatError("0.2 loads native OBS saves; use Add to migrate legacy games");
|
||||
native = content::load_career(save_path, *resource->content);
|
||||
g_ = std::move(native->state);
|
||||
rand_ = native->random;
|
||||
game_ = native->game;
|
||||
} else {
|
||||
const Savegame file = load_savegame(save_path);
|
||||
original_english_save = file.version == "V2.20";
|
||||
if (!file.checksum_ok ||
|
||||
(file.version != "V2.24" && !(importing_legacy && kEnglishCompetitions && original_english_save)))
|
||||
throw FormatError("savegame: unsupported or damaged FBM");
|
||||
const DbCounts counts{exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField),
|
||||
exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField3),
|
||||
exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField2),
|
||||
exe_.u32(::bmh::layout::CareerSession_DataDirectory_RuntimeField4)};
|
||||
const auto stream = original_english_save ? obw::normalize_english_save(file, counts) : file.stream;
|
||||
const SaveState save(stream, counts);
|
||||
g_ = GameState::from_save(save, counts);
|
||||
if (importing_legacy && file.plain_header.size() >= 11) {
|
||||
const std::string year(file.plain_header.begin() + 7, file.plain_header.begin() + 11);
|
||||
if (std::all_of(year.begin(), year.end(), [](unsigned char c) { return std::isdigit(c); })) {
|
||||
const int elapsed = ui::desk_date(g_.date, exe_).year - exe_.display_start_year();
|
||||
const int origin = std::stoi(year) - elapsed;
|
||||
if (origin >= 1900 && origin <= 9998)
|
||||
g_.display_start_year = origin;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (content::find(data)) {
|
||||
content::set_display_start_year(data, g_.display_start_year);
|
||||
exe_.set_display_start_year(g_.display_start_year);
|
||||
}
|
||||
// CompetitionPointers2, after DeskDate2: these are process statics, not FBM fields.
|
||||
// Resuming within this month must not count it as a newly elapsed month.
|
||||
g_.autosave_months = 0;
|
||||
g_.autosave_month = month_code(g_.date);
|
||||
if (!native) {
|
||||
g_.autosave_months = 0;
|
||||
g_.autosave_month = month_code(g_.date);
|
||||
}
|
||||
// Original CompetitionPointers2 calls CompetitionPointers after loading the stream. This
|
||||
// rebinds pointer fields in the saved competition table before any resume
|
||||
// path dereferences them (the serialized values may point into the old process).
|
||||
@@ -604,10 +648,55 @@ CareerSession::CareerSession(const std::filesystem::path& data, uint32_t watcom_
|
||||
g_.credit_divisor = std::bit_cast<double>(uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField)) | uint64_t(exe_.u32(::bmh::layout::BankCredit_BankCreditContext_RuntimeField2)) << 32);
|
||||
g_.credit_rate_table_available = true;
|
||||
install_default_hooks();
|
||||
national_coach_after_load(g_); // (NationalCoachAfterLoad: a Bundestrainer takes the national team over again)
|
||||
if (g_.memory.has(::bmh::layout::CareerSession_Save_RuntimeField)) game_.set_seed(int32_t(g_.memory.u32(::bmh::layout::CareerSession_Save_RuntimeField)));
|
||||
restore_saved_turn_cursor(turn_driver_, g_, db_, session_id_, 1, saved_turn_error_);
|
||||
capture_source_desk_callargs();
|
||||
if (content::find(data))
|
||||
turn_driver_.desk_autosave = [this](const GameState &state, WatcomRandom &random) {
|
||||
write_desk_autosave(state, random);
|
||||
};
|
||||
if (!native)
|
||||
national_coach_after_load(
|
||||
g_); // (NationalCoachAfterLoad: a Bundestrainer takes the national team over again)
|
||||
if (!native && g_.memory.has(::bmh::layout::CareerSession_Save_RuntimeField))
|
||||
game_.set_seed(int32_t(g_.memory.u32(::bmh::layout::CareerSession_Save_RuntimeField)));
|
||||
if (native) {
|
||||
content::restore_driver(turn_driver_, native->driver);
|
||||
restore_native_session_context(native->session);
|
||||
turn_driver_.session_id = session_id_;
|
||||
turn_driver_.revision = 1;
|
||||
exe_.set_display_start_year(g_.display_start_year);
|
||||
} else if (original_english_save &&
|
||||
!g_.memory.u8(::bmh::layout::CareerSession_RuntimeError_RuntimeField4)) {
|
||||
// V2.20 never stored transient match descriptors. Like its original loader,
|
||||
// rebuild the current groups without replaying daily/financial progression
|
||||
// or shuffling the saved manager order.
|
||||
const int day = g_.season_day();
|
||||
if (day < 0 || day >= 365)
|
||||
throw FormatError("V2.20 calendar day is invalid");
|
||||
const auto entry = g_.memory.u16(::bmh::layout::CompetitionCalendar + uint32_t(day) * 2);
|
||||
const auto competitions = g_.memory.u32(::bmh::layout::SavedCompetition);
|
||||
std::vector<uint8_t> referees = db_.raw_referee_properties;
|
||||
for (auto &referee : referees)
|
||||
referee &= 0x7f;
|
||||
MatchdayContext context;
|
||||
context.month = month_code(g_.date);
|
||||
context.season_day = day;
|
||||
context.weekday = ui::desk_date(g_.date, exe_).weekday;
|
||||
context.referees = &referees;
|
||||
MinuteReport report;
|
||||
auto groups = setup_matchday(g_, competitions, context, game_, rand_, report);
|
||||
if (report.unsupported)
|
||||
throw FormatError("V2.20 continuation: " + report.reason);
|
||||
std::string error;
|
||||
if (!begin_turn_driver(turn_driver_, g_, std::move(groups), entry, db_.raw_referee_properties,
|
||||
session_id_, 1, error))
|
||||
throw FormatError(error);
|
||||
turn_driver_.referees = std::move(referees);
|
||||
turn_driver_.loaded_matchday_resume = true;
|
||||
} else
|
||||
restore_saved_turn_cursor(turn_driver_, g_, db_, session_id_, 1, saved_turn_error_);
|
||||
if (importing_legacy && !saved_turn_error_.empty())
|
||||
throw FormatError(saved_turn_error_);
|
||||
if (!native)
|
||||
capture_source_desk_callargs();
|
||||
}
|
||||
|
||||
int CareerSession::runtime_club(int master) const { return runtime_club(g_, master); }
|
||||
@@ -4129,6 +4218,7 @@ bool CareerSession::finish(ui::CareerInitializationResult& result, std::string&
|
||||
for (size_t m = 0; m < managers_.size(); ++m)
|
||||
managers_[m].runtime_club = g_.manager_teams.at(m);
|
||||
result.managers = managers_;
|
||||
flush_native_autosave();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -4335,6 +4425,7 @@ TurnAdvanceResult CareerSession::dispatch_kickoff(const ui::DeskRequest& request
|
||||
return id < names.size() ? names[id] : std::string();
|
||||
}, exe_, g_);
|
||||
}
|
||||
flush_native_autosave();
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -4800,7 +4891,10 @@ bool CareerSession::apply_settings_file(const ui::SaveLoadRequest& request,int m
|
||||
std::string extension=request.path.extension().string();
|
||||
std::transform(extension.begin(),extension.end(),extension.begin(),
|
||||
[](unsigned char c){return char(std::tolower(c));});
|
||||
if(extension!=".ein") {error="invalid_settings_file_extension";return false;}
|
||||
if (extension != (content::find(data_directory_) ? ".obsettings" : ".ein")) {
|
||||
error = "invalid_settings_file_extension";
|
||||
return false;
|
||||
}
|
||||
const uint32_t base=::bmh::layout::LeaguePresentationOptions;
|
||||
if(!staged.memory.has(base+uint32_t(kBytes-1))) {error="settings_file_memory_unavailable";return false;}
|
||||
std::error_code ec;
|
||||
@@ -4808,7 +4902,14 @@ bool CareerSession::apply_settings_file(const ui::SaveLoadRequest& request,int m
|
||||
if(!ec&&std::filesystem::is_symlink(status)) {error="settings_file_target_is_symlink";return false;}
|
||||
if(request.action==ui::SaveLoadAction::load) {
|
||||
Bytes bytes;
|
||||
try {bytes=read_file(request.path);}catch(const std::exception&) {error="settings_file_read_failed";return false;}
|
||||
try {
|
||||
bytes = content::find(data_directory_)
|
||||
? content::load_preferences(request.path, "settings", kBytes)
|
||||
: read_file(request.path);
|
||||
} catch (const std::exception &) {
|
||||
error = "settings_file_read_failed";
|
||||
return false;
|
||||
}
|
||||
if(bytes.size()!=kBytes) {error="settings_file_wrong_size";return false;}
|
||||
for(size_t i=0;i<kBytes;++i)staged.memory.set8(base+uint32_t(i),bytes[i]);
|
||||
std::array<uint8_t,kBytes> raw{};
|
||||
@@ -4831,6 +4932,11 @@ bool CareerSession::apply_settings_file(const ui::SaveLoadRequest& request,int m
|
||||
Bytes bytes(kBytes);
|
||||
for(size_t i=0;i<kBytes;++i)bytes[i]=staged.memory.u8(base+uint32_t(i));
|
||||
try {
|
||||
if (content::find(data_directory_)) {
|
||||
content::save_preferences(request.path, "settings", bytes, request.overwrite);
|
||||
error.clear();
|
||||
return true;
|
||||
}
|
||||
std::ofstream file(request.path,std::ios::binary|std::ios::trunc);
|
||||
if(!file) {error="settings_file_write_failed";return false;}
|
||||
file.write(reinterpret_cast<const char*>(bytes.data()),std::streamsize(bytes.size()));file.flush();
|
||||
@@ -7522,6 +7628,11 @@ std::string CareerSession::take_autosave_error() {
|
||||
}
|
||||
|
||||
void CareerSession::write_desk_autosave(const GameState& state, WatcomRandom& random) {
|
||||
// OpenBMH deviates from the original: native saves do not consume gameplay randomness for encryption.
|
||||
if (content::find(data_directory_)) {
|
||||
native_autosave_pending_ = bool(autosave_directory_);
|
||||
return;
|
||||
}
|
||||
std::filesystem::path temporary;
|
||||
try {
|
||||
if (!autosave_directory_ || !std::filesystem::is_directory(*autosave_directory_))
|
||||
@@ -7556,6 +7667,83 @@ void CareerSession::write_desk_autosave(const GameState& state, WatcomRandom& ra
|
||||
}
|
||||
}
|
||||
|
||||
cli::Json CareerSession::native_session_context() const {
|
||||
cli::Json::Array runtime, callargs, managers;
|
||||
for (const auto &[address, value] : club_modal_runtime_)
|
||||
runtime.emplace_back(cli::Json::Object{{"address", int64_t(address)}, {"value", int(value)}});
|
||||
for (const auto &args : source_desk_callargs_)
|
||||
callargs.emplace_back(cli::Json::Array{args.competition, args.opponent});
|
||||
for (const auto &manager : managers_)
|
||||
managers.emplace_back(cli::Json::Array{manager.slot, manager.master_club, manager.runtime_club});
|
||||
return cli::Json::Object{{"schema", "classic-session@1.0"},
|
||||
{"runtime", std::move(runtime)},
|
||||
{"desk_callargs", std::move(callargs)},
|
||||
{"managers", std::move(managers)}};
|
||||
}
|
||||
void CareerSession::restore_native_session_context(const cli::Json &root) {
|
||||
const auto field = [&](const char *name) -> const cli::Json & {
|
||||
if (!root.object() || !root.object()->contains(name))
|
||||
throw FormatError("Native session field missing");
|
||||
return root.object()->at(name);
|
||||
};
|
||||
if (!field("schema").string() || *field("schema").string() != "classic-session@1.0")
|
||||
throw FormatError("Unsupported native session");
|
||||
const auto array = [](const cli::Json &j, size_t maximum) -> const cli::Json::Array & {
|
||||
if (!j.array() || j.array()->size() > maximum)
|
||||
throw FormatError("Invalid native session array");
|
||||
return *j.array();
|
||||
};
|
||||
const auto integer = [](const cli::Json &j, int64_t low, int64_t high) -> int64_t {
|
||||
if (!j.integer() || *j.integer() < low || *j.integer() > high)
|
||||
throw FormatError("Invalid native session integer");
|
||||
return *j.integer();
|
||||
};
|
||||
std::map<uint32_t, uint8_t> runtime;
|
||||
for (const auto &row : array(field("runtime"), 8192)) {
|
||||
if (!row.object() || !row.object()->contains("address") || !row.object()->contains("value"))
|
||||
throw FormatError("Invalid runtime byte");
|
||||
const auto at = uint32_t(integer(row.object()->at("address"), 0, UINT32_MAX));
|
||||
if (!club_modal_runtime_.contains(at) ||
|
||||
!runtime.emplace(at, uint8_t(integer(row.object()->at("value"), 0, 255))).second)
|
||||
throw FormatError("Unknown or duplicated runtime byte");
|
||||
}
|
||||
if (runtime.size() != club_modal_runtime_.size())
|
||||
throw FormatError("Incomplete native runtime bytes");
|
||||
std::vector<ui::DeskMatchCallargs> callargs;
|
||||
for (const auto &row : array(field("desk_callargs"), 4)) {
|
||||
const auto &fields = array(row, 2);
|
||||
if (fields.size() != 2)
|
||||
throw FormatError("Invalid desk arguments");
|
||||
callargs.push_back({int(integer(fields[0], -1, 255)), int(integer(fields[1], -1, 4095))});
|
||||
}
|
||||
std::vector<ui::InitializedManager> managers;
|
||||
for (const auto &row : array(field("managers"), 4)) {
|
||||
const auto &fields = array(row, 3);
|
||||
if (fields.size() != 3)
|
||||
throw FormatError("Invalid manager mapping");
|
||||
managers.push_back({int(integer(fields[0], 0, 3)), int(integer(fields[1], 0, 4095)),
|
||||
int(integer(fields[2], 0, 4095))});
|
||||
}
|
||||
club_modal_runtime_ = std::move(runtime);
|
||||
source_desk_callargs_ = std::move(callargs);
|
||||
managers_ = std::move(managers);
|
||||
}
|
||||
void CareerSession::flush_native_autosave() {
|
||||
if (!std::exchange(native_autosave_pending_, false))
|
||||
return;
|
||||
try {
|
||||
if (!autosave_directory_ || !std::filesystem::is_directory(*autosave_directory_))
|
||||
throw FormatError("Autosave directory unavailable");
|
||||
const auto resource = content::find(data_directory_);
|
||||
if (!resource)
|
||||
throw FormatError("Native content unavailable");
|
||||
content::save_career(*autosave_directory_ / "AUTOSAVE.obs", *resource->content, g_, rand_, game_,
|
||||
turn_driver_, true, native_session_context());
|
||||
} catch (const std::exception &e) {
|
||||
autosave_error_ = e.what();
|
||||
}
|
||||
}
|
||||
|
||||
bool CareerSession::save_game(const std::filesystem::path& path, int manager_slot, bool overwrite, std::string& error) {
|
||||
if (advertising_renewal_dispatch_active_) { error="save_blocked_during_advertising_renewal"; return false; }
|
||||
if(balance_draft_||balance_dispatch_active_||strengths_owner_||strengths_dispatch_active_||
|
||||
@@ -7569,7 +7757,7 @@ bool CareerSession::save_game(const std::filesystem::path& path, int manager_slo
|
||||
std::string extension = path.extension().string();
|
||||
std::transform(extension.begin(), extension.end(), extension.begin(), [](unsigned char c) { return char(std::tolower(c)); });
|
||||
if (manager_slot != active || manager_slot < 0 || size_t(manager_slot) >= g_.manager_teams.size() ||
|
||||
extension != ".fbm" || path.filename().empty()) {
|
||||
extension != (content::find(data_directory_) ? ".obs" : ".fbm") || path.filename().empty()) {
|
||||
error = "invalid_save_request"; return false;
|
||||
}
|
||||
std::error_code ec;
|
||||
@@ -7582,6 +7770,11 @@ bool CareerSession::save_game(const std::filesystem::path& path, int manager_slo
|
||||
const bool exists = std::filesystem::exists(path, ec);
|
||||
if (ec || (exists && !overwrite)) { error = exists ? "overwrite_confirmation_required" : "save_target_unavailable"; return false; }
|
||||
try {
|
||||
if (const auto resource = content::find(data_directory_)) {
|
||||
content::save_career(path, *resource->content, g_, rand_, game_, turn_driver_, overwrite,
|
||||
native_session_context());
|
||||
return true;
|
||||
}
|
||||
WatcomRandom staged_rand = rand_;
|
||||
const Savegame save = make_savegame(g_, staged_rand);
|
||||
write_savegame(path, save);
|
||||
@@ -7623,7 +7816,10 @@ bool CareerSession::dispatch_menu_layout(const ui::SaveLoadRequest& request, uin
|
||||
std::string extension = request.path.extension().string();
|
||||
std::transform(extension.begin(), extension.end(), extension.begin(),
|
||||
[](unsigned char c) { return char(std::tolower(c)); });
|
||||
if (extension != ".men") { error = "invalid_menu_layout_extension"; return false; }
|
||||
if (extension != (content::find(data_directory_) ? ".oblayout" : ".men")) {
|
||||
error = "invalid_menu_layout_extension";
|
||||
return false;
|
||||
}
|
||||
const size_t active_base = size_t(request.manager_slot) * 0xb0c;
|
||||
if (active_base + 0xb0c > g_.manager_records.size() ||
|
||||
size_t(request.manager_slot) >= g_.manager_teams.size() ||
|
||||
@@ -7668,8 +7864,14 @@ bool CareerSession::dispatch_menu_layout(const ui::SaveLoadRequest& request, uin
|
||||
|
||||
if (request.action == ui::SaveLoadAction::load) {
|
||||
Bytes payload;
|
||||
try { payload = read_file(request.path); }
|
||||
catch (const std::exception&) { error = "menu_layout_read_failed"; return false; }
|
||||
try {
|
||||
payload = content::find(data_directory_)
|
||||
? content::load_preferences(request.path, "layout", kLayoutBytes)
|
||||
: read_file(request.path);
|
||||
} catch (const std::exception &) {
|
||||
error = "menu_layout_read_failed";
|
||||
return false;
|
||||
}
|
||||
if (!validate_payload(payload)) return false;
|
||||
GameState staged = g_;
|
||||
for (size_t i = 0; i < kLayoutBytes; ++i)
|
||||
@@ -7704,6 +7906,12 @@ bool CareerSession::dispatch_menu_layout(const ui::SaveLoadRequest& request, uin
|
||||
for (size_t i = 0; i < kLayoutBytes; ++i) payload[i] = g_.memory.u8(base + uint32_t(i));
|
||||
if (!validate_payload(payload)) return false;
|
||||
try {
|
||||
if (content::find(data_directory_)) {
|
||||
content::save_preferences(request.path, "layout", payload, request.overwrite);
|
||||
++revision;
|
||||
error.clear();
|
||||
return true;
|
||||
}
|
||||
std::ofstream file(request.path, std::ios::binary | std::ios::trunc);
|
||||
if (!file) { error = "menu_layout_write_failed"; return false; }
|
||||
file.write(reinterpret_cast<const char*>(payload.data()), std::streamsize(payload.size()));
|
||||
|
||||
@@ -808,7 +808,8 @@ public:
|
||||
bool dispatch_menu_layout(const ui::SaveLoadRequest&, uint64_t& revision, std::string& error);
|
||||
|
||||
// Load an existing V2.24 save without applying new-career options or startup RNG.
|
||||
CareerSession(const std::filesystem::path& data, uint32_t watcom_seed, const std::filesystem::path& save_path);
|
||||
CareerSession(const std::filesystem::path &data, uint32_t watcom_seed,
|
||||
const std::filesystem::path &save_path, bool importing_legacy = false);
|
||||
|
||||
const GameState& state() const { return g_; }
|
||||
GameState& state() { return g_; }
|
||||
@@ -883,6 +884,10 @@ private:
|
||||
std::optional<std::filesystem::path> autosave_directory_;
|
||||
std::string autosave_error_;
|
||||
void write_desk_autosave(const GameState&, WatcomRandom&);
|
||||
bool native_autosave_pending_ = false;
|
||||
void flush_native_autosave();
|
||||
cli::Json native_session_context() const;
|
||||
void restore_native_session_context(const cli::Json &);
|
||||
bool live_source_identity(const ui::StrengthsIdentity&) const;
|
||||
bool validate_desk_setting_owner(const DeskSettingIdentity&, uint64_t revision, std::string& error,
|
||||
bool require_desk_phase = true) const;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/content.hpp"
|
||||
#include "formats/executable_layout.hpp"
|
||||
#include "app/controller.hpp"
|
||||
#include "app/window_actions.hpp"
|
||||
@@ -979,7 +980,8 @@ std::string serve_flow_request(ui::StartupFlow& flow, const ui::FlowResult& resu
|
||||
page.highscore.rows={};
|
||||
if(page.highscore.ranked) {
|
||||
auto texts=load_textd(ui::asset_path(data,"TEXTD.BLK"));
|
||||
const auto file=highscore_file(save_directory,page.highscore.signature,texts.strings.at(889));
|
||||
const auto file = highscore_file(save_directory, page.highscore.signature,
|
||||
texts.strings.at(889), bool(content::find(data)));
|
||||
HighscoreTable rows{};
|
||||
if(fs::exists(file))rows=load_highscore_table(file);
|
||||
page.highscore=make_highscore_projection(game,std::move(rows),HighscoreContext::ActiveManager);
|
||||
|
||||
+57
-35
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/content.hpp"
|
||||
#include "formats/executable_layout.hpp"
|
||||
#include "ui/live_timing.hpp"
|
||||
// openbmh_play - the UI of src/ui connected to the engine: options, manager dialogs, a new
|
||||
@@ -29,6 +30,8 @@
|
||||
#include "launch/archive.hpp"
|
||||
#include "launch/file_dialog.hpp"
|
||||
#include "launch/game_data.hpp"
|
||||
#include "launch/launcher.hpp"
|
||||
#include "content/package.hpp"
|
||||
#include "version.hpp"
|
||||
#include "app/live_matchday_events.hpp"
|
||||
#include "audio/playback.hpp"
|
||||
@@ -131,7 +134,7 @@ int main(int argc, char** argv) {
|
||||
} else if (is("--live-frame-ms") && value) {
|
||||
live_frame_ms = std::clamp(std::atoi(args[++i].c_str()), 0, 1000);
|
||||
live_frame_ms_explicit = true;
|
||||
} else if (is("--data") && value) {
|
||||
} else if ((is("--run-mod") || is("--mod") || is("--data")) && value) {
|
||||
data = launch::path_from_utf8(args[++i]);
|
||||
} else if (is("--seed") && value) {
|
||||
seed = uint32_t(std::strtoul(args[++i].c_str(), nullptr, 0));
|
||||
@@ -143,51 +146,69 @@ int main(int argc, char** argv) {
|
||||
std::printf("OpenBMH %s\n", bmh::kOpenBmhVersion);
|
||||
return 0;
|
||||
} else if (is("--help") || is("-h")) {
|
||||
std::printf("usage: openbmh_play [<game directory | BMH.EXE | game.zip | game.7z>] [--seed <Watcom seed>] "
|
||||
"[--save-directory <directory>] [--mute] [--volume <0..1>] [--no-music] [--live-frame-ms <0..1000>]\n");
|
||||
std::printf("usage: OpenBMH [--mod <mods/name/content.obw>] [--seed <Watcom seed>] "
|
||||
"[--save-directory <directory>] [--mute] [--volume <0..1>] [--no-music] "
|
||||
"[--live-frame-ms <0..1000>]\n");
|
||||
return 0;
|
||||
} else if (args[i].rfind("--", 0) != 0 && data.empty()) {
|
||||
data = launch::path_from_utf8(args[i]);
|
||||
} else {
|
||||
show_start_error("Unknown option or missing argument: " + args[i]);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
// the game: as given (directory, EXE or archive); else the directory OpenBMH itself lies in,
|
||||
// when it holds a playable game (the simplest install: openbmh next to BMH.EXE); else
|
||||
// chosen in the file dialog
|
||||
if (data.empty()) {
|
||||
if (char* base = SDL_GetBasePath()) {
|
||||
const fs::path here = launch::path_from_utf8(base);
|
||||
SDL_free(base);
|
||||
try {
|
||||
const launch::ResolvedGame game = launch::resolve_game(here, launch::default_cache_directory());
|
||||
if (game.error.empty() && game.check.playable) data = here;
|
||||
} catch (const std::exception&) {
|
||||
// (not a game directory: fall through to the file dialog)
|
||||
}
|
||||
}
|
||||
}
|
||||
std::filesystem::path executable;
|
||||
if (char *base = SDL_GetBasePath()) {
|
||||
executable = launch::path_from_utf8(base);
|
||||
SDL_free(base);
|
||||
#ifdef _WIN32
|
||||
executable /= "OpenBMH.exe";
|
||||
#else
|
||||
executable /= "OpenBMH";
|
||||
#endif
|
||||
} else
|
||||
executable = fs::absolute(launch::path_from_utf8(args.front()));
|
||||
if (data.empty()) {
|
||||
try {
|
||||
const auto chosen = launch::choose_game_file("OpenBMH");
|
||||
if (!chosen) return 0; // cancelled
|
||||
data = *chosen;
|
||||
} catch (const std::exception& e) {
|
||||
show_start_error(std::string(e.what()) +
|
||||
"\nStart OpenBMH with the game as argument: openbmh_play <game directory | BMH.EXE | game.zip>");
|
||||
return launch::run_launcher(executable, [](const fs::path &package, const fs::path &source,
|
||||
const fs::path &destination) {
|
||||
const auto content = content::open(package);
|
||||
content::Mount mount(package, content);
|
||||
const auto source_bytes = read_file(source);
|
||||
const auto digest = content::sha256(std::string(source_bytes.begin(), source_bytes.end()));
|
||||
const auto seed = uint32_t(std::stoul(digest.substr(0, 8), nullptr, 16));
|
||||
app::CareerSession migrated(mount.root(), seed, source, true);
|
||||
std::string error;
|
||||
if (!migrated.save_game(destination, migrated.state().memory.u8(::bmh::layout::ActiveManager),
|
||||
false, error))
|
||||
throw FormatError("Spielstand konnte nicht übernommen werden: " + error);
|
||||
});
|
||||
} catch (const std::exception &e) {
|
||||
show_start_error(e.what());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
bool english_game = false; // (the window title marks the English version as experimental)
|
||||
{
|
||||
const launch::ResolvedGame game = launch::resolve_game(data, launch::default_cache_directory());
|
||||
if (!game.error.empty() || !game.check.playable) {
|
||||
show_start_error("The game cannot be started:\n" + launch::describe(game));
|
||||
return 1;
|
||||
std::shared_ptr<const content::Classic> contents;
|
||||
std::unique_ptr<content::Mount> mount;
|
||||
bool english_game = false;
|
||||
try {
|
||||
if (fs::is_directory(data))
|
||||
data /= "content.obw";
|
||||
contents = content::open(data);
|
||||
mount = std::make_unique<content::Mount>(data, contents);
|
||||
data = mount->root();
|
||||
english_game = contents->english;
|
||||
if (save_directory.empty()) {
|
||||
const auto root = executable.parent_path();
|
||||
launch::ModLibrary library(root);
|
||||
launch::ModEntry mod;
|
||||
mod.content_id = contents->content_id;
|
||||
save_directory = library.user_directory(mod);
|
||||
}
|
||||
english_game = game.check.family == launch::GameFamily::english;
|
||||
// (from an archive: its unpacked copy in the cache, which then also keeps the saves)
|
||||
data = game.check.directory;
|
||||
} catch (const std::exception &e) {
|
||||
show_start_error(e.what());
|
||||
return 1;
|
||||
}
|
||||
if (save_directory.empty()) save_directory = data;
|
||||
try {
|
||||
const Palette palette = load_palette(ui::asset_path(data, "M3PC.COL"));
|
||||
ui::StartupFlow flow(data, save_directory);
|
||||
@@ -1676,7 +1697,8 @@ int main(int argc, char** argv) {
|
||||
wait_season_ack();
|
||||
}
|
||||
} else {
|
||||
const auto file = highscore_file(save_directory, signature, season_texts[889]);
|
||||
const auto file =
|
||||
highscore_file(save_directory, signature, season_texts[889], bool(content::find(data)));
|
||||
auto scores = make_highscore_projection(state, load_highscore_table(file), HighscoreContext::SeasonBoundary);
|
||||
// The Original stores this table outside the native FBM. Use the
|
||||
// configured writable save base rather than a working-directory path.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/content.hpp"
|
||||
#include "formats/executable_layout.hpp"
|
||||
// Information windows of docs/CLI_CONCEPT/05-information.md that the engine can already
|
||||
// project: TeamInfo (club information, from LeagueTable / Fixtures), HighScore (menu 26) and
|
||||
@@ -186,7 +187,8 @@ void Console::register_info_commands() {
|
||||
const uint16_t signature = g.memory.has(::bmh::layout::CareerSession_FormatError_RuntimeField7) ? g.memory.u16(::bmh::layout::CareerSession_FormatError_RuntimeField7) : 0;
|
||||
if (signature != 0) {
|
||||
// the ranked list of this game's level, stored next to the saved games
|
||||
const auto file = highscore_file(save_directory(), signature, texts_.strings.at(kHighscorePrefix));
|
||||
const auto file = highscore_file(save_directory(), signature, texts_.strings.at(kHighscorePrefix),
|
||||
bool(content::find(options_.data)));
|
||||
HighscoreTable rows{};
|
||||
std::error_code ec;
|
||||
if (std::filesystem::exists(file, ec)) rows = load_highscore_table(file);
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "formats/content.hpp"
|
||||
#include "cli/console/console.hpp"
|
||||
#include "cli/console/detail.hpp"
|
||||
#include "ui/cup_draw.hpp"
|
||||
@@ -396,7 +397,8 @@ std::filesystem::path Console::browser_file(const std::string& name) const {
|
||||
if (name == "." || name == ".." || name.find_first_of("/\\:") != std::string::npos)
|
||||
fail("E_BAD_ARGUMENT", "not a file name: " + name + " (no directories; use ChangeDirectory)");
|
||||
std::filesystem::path path = browse_directory_ / name;
|
||||
if (!path.has_extension()) path += ".FBM";
|
||||
if (!path.has_extension())
|
||||
path += content::find(options_.data) ? ".obs" : ".FBM";
|
||||
return path;
|
||||
}
|
||||
|
||||
@@ -410,7 +412,8 @@ void Console::register_file_commands() {
|
||||
std::error_code ec;
|
||||
for (const auto& entry : std::filesystem::directory_iterator(browse_directory_, ec)) {
|
||||
if (entry.is_directory(ec)) dirs.push_back({entry.path().filename().string(), "dir"});
|
||||
else if (entry.is_regular_file(ec) && lower(entry.path().extension().string()) == ".fbm")
|
||||
else if (entry.is_regular_file(ec) && lower(entry.path().extension().string()) ==
|
||||
(content::find(options_.data) ? ".obs" : ".fbm"))
|
||||
files.push_back({entry.path().stem().string(), "file"});
|
||||
}
|
||||
if (ec) fail("E_IO", "cannot read the directory " + shown_directory());
|
||||
@@ -463,7 +466,8 @@ void Console::register_file_commands() {
|
||||
|
||||
void Console::load_game(const std::filesystem::path& requested) {
|
||||
std::filesystem::path path = requested;
|
||||
if (!path.has_extension()) path += ".FBM";
|
||||
if (!path.has_extension())
|
||||
path += content::find(options_.data) ? ".obs" : ".FBM";
|
||||
std::error_code ec;
|
||||
if (!std::filesystem::is_regular_file(path, ec)) fail("E_IO", "file not found: " + path.filename().string());
|
||||
std::unique_ptr<app::CareerSession> loaded;
|
||||
|
||||
+21
-8
@@ -32,6 +32,8 @@
|
||||
|
||||
#include "launch/archive.hpp"
|
||||
#include "launch/game_data.hpp"
|
||||
#include "content/package.hpp"
|
||||
#include "launch/mods.hpp"
|
||||
#include "version.hpp"
|
||||
|
||||
namespace {
|
||||
@@ -83,7 +85,8 @@ Arguments parse_args(int argc, char** argv) {
|
||||
std::exit(0);
|
||||
}
|
||||
if (arg == "--help" || arg == "-h") args.help = true;
|
||||
else if (arg == "--data") args.data = bmh::launch::path_from_utf8(next(arg));
|
||||
else if (arg == "--data" || arg == "--mod")
|
||||
args.data = bmh::launch::path_from_utf8(next(arg));
|
||||
else if (arg == "--seed") { args.seed = parse_seed(next(arg)); args.seed_set = true; }
|
||||
else if (arg == "--text") args.json = false;
|
||||
else if (arg == "--json") args.json = true;
|
||||
@@ -710,14 +713,24 @@ int main(int argc, char** argv) {
|
||||
Arguments args = parse_args(argc, argv);
|
||||
if (args.help) { print_usage(); return 0; }
|
||||
if (!args.send.empty()) return run_send(args);
|
||||
// --data may also name BMH.EXE or a ZIP/7z archive with one game (src/launch); an
|
||||
// archive is unpacked into the per-user cache and its copy is used
|
||||
std::shared_ptr<const bmh::content::Classic> contents;
|
||||
std::unique_ptr<bmh::content::Mount> mount;
|
||||
if (!args.data.empty()) {
|
||||
const auto game = bmh::launch::resolve_game(args.data, bmh::launch::default_cache_directory());
|
||||
if (!game.error.empty() || !game.check.playable)
|
||||
throw std::runtime_error("the game cannot be used:\n" + bmh::launch::describe(game));
|
||||
args.data = game.check.directory;
|
||||
}
|
||||
if (std::filesystem::is_directory(args.data))
|
||||
args.data /= "content.obw";
|
||||
contents = bmh::content::open(args.data);
|
||||
mount = std::make_unique<bmh::content::Mount>(args.data, contents);
|
||||
args.data = mount->root();
|
||||
if (args.saves.empty()) {
|
||||
bmh::launch::ModLibrary library(
|
||||
std::filesystem::absolute(bmh::launch::path_from_utf8(argv[0])).parent_path());
|
||||
bmh::launch::ModEntry mod;
|
||||
mod.content_id = contents->content_id;
|
||||
args.saves = library.user_directory(mod);
|
||||
}
|
||||
} else
|
||||
throw std::runtime_error(
|
||||
"0.2 requires --mod <content.obw>; import installations in OpenBMH first");
|
||||
if (args.console) {
|
||||
if (!args.log.empty() && !args.replay.empty()) throw std::runtime_error("--log and --replay cannot be combined");
|
||||
if (args.listen_port) return run_console_listen(args);
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "content/digest.hpp"
|
||||
#include <array>
|
||||
#include <bit>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
namespace bmh::content {
|
||||
std::string sha256(std::string_view input) {
|
||||
constexpr std::array<uint32_t, 64> k{
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
|
||||
std::array<uint32_t, 8> h{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
|
||||
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
|
||||
std::vector<uint8_t> data(input.begin(), input.end());
|
||||
const uint64_t bits = uint64_t(data.size()) * 8;
|
||||
data.push_back(0x80);
|
||||
while (data.size() % 64 != 56)
|
||||
data.push_back(0);
|
||||
for (int i = 7; i >= 0; --i)
|
||||
data.push_back(uint8_t(bits >> (8 * i)));
|
||||
for (size_t offset = 0; offset < data.size(); offset += 64) {
|
||||
std::array<uint32_t, 64> w{};
|
||||
for (size_t i = 0; i < 16; ++i)
|
||||
for (size_t j = 0; j < 4; ++j)
|
||||
w[i] = (w[i] << 8) | data[offset + 4 * i + j];
|
||||
for (size_t i = 16; i < 64; ++i) {
|
||||
const auto a = w[i - 15], b = w[i - 2];
|
||||
w[i] = w[i - 16] + (std::rotr(a, 7) ^ std::rotr(a, 18) ^ (a >> 3)) + w[i - 7] +
|
||||
(std::rotr(b, 17) ^ std::rotr(b, 19) ^ (b >> 10));
|
||||
}
|
||||
auto [a, b, c, d, e, f, g, v] = h;
|
||||
for (size_t i = 0; i < 64; ++i) {
|
||||
const auto t = v + (std::rotr(e, 6) ^ std::rotr(e, 11) ^ std::rotr(e, 25)) +
|
||||
((e & f) ^ (~e & g)) + k[i] + w[i];
|
||||
const auto u =
|
||||
(std::rotr(a, 2) ^ std::rotr(a, 13) ^ std::rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c));
|
||||
v = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = d + t;
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = t + u;
|
||||
}
|
||||
const std::array<uint32_t, 8> work{a, b, c, d, e, f, g, v};
|
||||
for (size_t i = 0; i < 8; ++i)
|
||||
h[i] += work[i];
|
||||
}
|
||||
constexpr char digits[] = "0123456789abcdef";
|
||||
std::string result;
|
||||
for (auto word : h)
|
||||
for (int i = 7; i >= 0; --i)
|
||||
result += digits[(word >> (4 * i)) & 15];
|
||||
return result;
|
||||
}
|
||||
} // namespace bmh::content
|
||||
@@ -0,0 +1,7 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
namespace bmh::content {
|
||||
std::string sha256(std::string_view data);
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "content/package.hpp"
|
||||
#include "import/detail.hpp"
|
||||
#include <chrono>
|
||||
#include <fstream>
|
||||
namespace bmh::content {
|
||||
namespace fs = std::filesystem;
|
||||
using namespace obw::detail;
|
||||
namespace {
|
||||
constexpr const char *inventory = "x-classic/seal.json";
|
||||
O hashes(const Documents &docs) {
|
||||
O result;
|
||||
for (const auto &[name, value] : docs)
|
||||
if (name != inventory) {
|
||||
if (!safe_path(name))
|
||||
fail("invalid content entry");
|
||||
result[name] = sha256(value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
std::string identity(const Documents &docs) {
|
||||
auto entries = hashes(docs);
|
||||
entries.erase("x-classic/inventory.json");
|
||||
auto manifest = parse(docs, "manifest.json");
|
||||
manifest.object()->erase("generator");
|
||||
manifest.object()->erase("title");
|
||||
entries["manifest.json"] = sha256(cli::dump_json(manifest));
|
||||
return sha256(cli::dump_json(entries));
|
||||
}
|
||||
} // namespace
|
||||
Documents read_archive(const fs::path &file) {
|
||||
if (fs::is_symlink(fs::symlink_status(file)) || !fs::is_regular_file(file) ||
|
||||
fs::file_size(file) > 128ull * 1024 * 1024)
|
||||
fail("invalid native archive");
|
||||
const auto input = read_file(file);
|
||||
mz_zip_archive zip{};
|
||||
if (!mz_zip_reader_init_mem(&zip, input.data(), input.size(), 0))
|
||||
fail("invalid ZIP archive");
|
||||
struct End {
|
||||
mz_zip_archive *zip;
|
||||
~End() { mz_zip_reader_end(zip); }
|
||||
} end{&zip};
|
||||
Documents out;
|
||||
uint64_t total = 0;
|
||||
const auto count = mz_zip_reader_get_num_files(&zip);
|
||||
if (count > 8192)
|
||||
fail("too many archive entries");
|
||||
for (mz_uint i = 0; i < count; ++i) {
|
||||
mz_zip_archive_file_stat stat{};
|
||||
if (!mz_zip_reader_file_stat(&zip, i, &stat))
|
||||
fail("cannot read entry metadata");
|
||||
if (stat.m_is_directory)
|
||||
continue;
|
||||
const std::string name = stat.m_filename;
|
||||
if (!safe_path(name) || stat.m_uncomp_size > 32ull * 1024 * 1024 ||
|
||||
(total += stat.m_uncomp_size) > 128ull * 1024 * 1024)
|
||||
fail("unsafe or oversized archive entry");
|
||||
std::string value(size_t(stat.m_uncomp_size), '\0');
|
||||
if (!mz_zip_reader_extract_to_mem(&zip, i, value.data(), value.size(), 0))
|
||||
fail("damaged ZIP entry");
|
||||
if (!out.emplace(name, std::move(value)).second)
|
||||
fail("duplicate archive entry");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
void write_archive(const Documents &out, const fs::path &file, bool overwrite) {
|
||||
mz_zip_archive zip{};
|
||||
if (!mz_zip_writer_init_heap(&zip, 0, 0))
|
||||
fail("cannot initialize ZIP writer");
|
||||
struct End {
|
||||
mz_zip_archive *zip;
|
||||
~End() { mz_zip_writer_end(zip); }
|
||||
} end{&zip};
|
||||
uint64_t total = 0;
|
||||
if (out.size() > 8192)
|
||||
fail("too many archive entries");
|
||||
for (const auto &[name, data] : out) {
|
||||
if (!safe_path(name) || data.size() > 32ull * 1024 * 1024 ||
|
||||
(total += data.size()) > 128ull * 1024 * 1024)
|
||||
fail("invalid archive size or path");
|
||||
if (!mz_zip_writer_add_mem(&zip, name.c_str(), data.data(), data.size(), MZ_BEST_SPEED))
|
||||
fail("cannot add ZIP entry");
|
||||
}
|
||||
void *buffer = nullptr;
|
||||
size_t size = 0;
|
||||
if (!mz_zip_writer_finalize_heap_archive(&zip, &buffer, &size))
|
||||
fail("cannot finalize ZIP archive");
|
||||
struct Free {
|
||||
void *data;
|
||||
~Free() { mz_free(data); }
|
||||
} free{buffer};
|
||||
write_atomic(file, std::string_view(static_cast<const char *>(buffer), size), overwrite);
|
||||
}
|
||||
std::string seal(Documents &docs) {
|
||||
obw::validate(docs);
|
||||
auto entries = hashes(docs);
|
||||
const auto id = identity(docs);
|
||||
put(docs, inventory,
|
||||
O{{"schema", "classic-seal@1.0"}, {"content_id", id}, {"entries", std::move(entries)}});
|
||||
return id;
|
||||
}
|
||||
std::string verify(const Documents &docs) {
|
||||
const auto stored = parse(docs, inventory);
|
||||
if (str(get(stored, "schema")) != "classic-seal@1.0")
|
||||
fail("unsupported Classic seal");
|
||||
const auto actual = hashes(docs);
|
||||
const auto encoded = cli::dump_json(actual);
|
||||
if (cli::dump_json(get(stored, "entries")) != encoded || str(get(stored, "content_id")) != identity(docs))
|
||||
fail("Classic contents were changed; import the installation again");
|
||||
return identity(docs);
|
||||
}
|
||||
std::shared_ptr<const Classic> open(const fs::path &path) {
|
||||
auto docs = read_archive(path);
|
||||
const auto id = verify(docs);
|
||||
auto value = std::make_shared<Classic>(obw::load_classic(docs));
|
||||
value->content_id = id;
|
||||
const auto manifest = parse(docs, "manifest.json");
|
||||
value->start_year = std::stoi(str(get(manifest, "start_date")).substr(0, 4));
|
||||
value->executable.set_display_start_year(value->start_year);
|
||||
value->documents = std::move(docs);
|
||||
return value;
|
||||
}
|
||||
} // namespace bmh::content
|
||||
@@ -0,0 +1,15 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include "import/classic.hpp"
|
||||
#include "content/digest.hpp"
|
||||
#include "formats/native_file.hpp"
|
||||
namespace bmh::content {
|
||||
using Documents = obw::Documents;
|
||||
// Generic bounded ZIP documents; format-specific validation belongs to its reader.
|
||||
Documents read_archive(const std::filesystem::path &file);
|
||||
void write_archive(const Documents &, const std::filesystem::path &, bool overwrite = false);
|
||||
// Sealed Classic contents: hashes cover every entry, including the original importer inventory.
|
||||
std::string seal(Documents &);
|
||||
std::string verify(const Documents &);
|
||||
std::shared_ptr<const Classic> open(const std::filesystem::path &);
|
||||
} // namespace bmh::content
|
||||
@@ -0,0 +1,262 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "content/save.hpp"
|
||||
#include "import/detail.hpp"
|
||||
#include "game/save.hpp"
|
||||
#include <limits>
|
||||
#include <algorithm>
|
||||
#include <bit>
|
||||
namespace bmh::content {
|
||||
using namespace obw::detail;
|
||||
namespace {
|
||||
J rng(uint32_t seed, uint64_t calls) { return O{{"seed", int64_t(seed)}, {"calls", std::to_string(calls)}}; }
|
||||
uint64_t calls(const J &value) {
|
||||
const auto s = str(get(value, "calls"));
|
||||
size_t end = 0;
|
||||
uint64_t n;
|
||||
try {
|
||||
n = std::stoull(s, &end);
|
||||
} catch (...) {
|
||||
fail("invalid random draw counter");
|
||||
}
|
||||
if (end != s.size() || s.empty() ||
|
||||
!std::all_of(s.begin(), s.end(), [](unsigned char c) { return c >= '0' && c <= '9'; }))
|
||||
fail("invalid random draw counter");
|
||||
return n;
|
||||
}
|
||||
uint32_t seed(const J &value) {
|
||||
const auto n = num(get(value, "seed"));
|
||||
if (n < 0 || n > UINT32_MAX)
|
||||
fail("invalid random seed");
|
||||
return uint32_t(n);
|
||||
}
|
||||
Documents world_of(const Documents &docs) {
|
||||
Documents world;
|
||||
for (const auto &[name, value] : docs)
|
||||
if (!name.starts_with("state/"))
|
||||
world[name] = value;
|
||||
world["manifest.json"] = docs.at("state/world-manifest.json");
|
||||
return world;
|
||||
}
|
||||
} // namespace
|
||||
namespace {
|
||||
template <class T> J vector_json(const std::vector<T> &values) {
|
||||
A rows;
|
||||
for (auto value : values)
|
||||
rows.emplace_back(int64_t(value));
|
||||
return rows;
|
||||
}
|
||||
template <class T> void vector_json(const J &j, std::vector<T> &out) {
|
||||
if (!j.array() || j.array()->size() > 1000000)
|
||||
fail("invalid checkpoint array");
|
||||
for (const auto &row : *j.array()) {
|
||||
const auto n = num(row);
|
||||
if (n < int64_t(std::numeric_limits<T>::min()) || n > int64_t(std::numeric_limits<T>::max()))
|
||||
fail("checkpoint array value out of range");
|
||||
out.push_back(T(n));
|
||||
}
|
||||
}
|
||||
J group_json(const MatchGroup &g) {
|
||||
O out;
|
||||
#define FIELD(name) out[#name] = vector_json(g.name);
|
||||
FIELD(desc)
|
||||
FIELD(fixtures) FIELD(results) FIELD(cup_results) FIELD(cup_other_leg) FIELD(records) FIELD(end_minute)
|
||||
FIELD(spectators) FIELD(log)
|
||||
#undef FIELD
|
||||
out["cup_addresses"] = A{int64_t(g.cup_result_address[0]), int64_t(g.cup_result_address[1])};
|
||||
out["phase"] = g.phase;
|
||||
out["ended"] = int64_t(g.ended);
|
||||
out["kickoff_void_mask"] = int64_t(g.kickoff_void_mask);
|
||||
return out;
|
||||
}
|
||||
MatchGroup group_json(const J &in) {
|
||||
MatchGroup g;
|
||||
#define FIELD(name) vector_json(get(in, #name), g.name);
|
||||
FIELD(desc)
|
||||
FIELD(fixtures) FIELD(results) FIELD(cup_results) FIELD(cup_other_leg) FIELD(records) FIELD(end_minute)
|
||||
FIELD(spectators) FIELD(log)
|
||||
#undef FIELD
|
||||
const auto &at = arr(get(in, "cup_addresses"));
|
||||
if (at.size() != 2)
|
||||
fail("invalid cup addresses");
|
||||
for (size_t i = 0; i < 2; ++i) {
|
||||
const auto n = num(at[i]);
|
||||
if (n < 0 || n > UINT32_MAX)
|
||||
fail("invalid cup address");
|
||||
g.cup_result_address[i] = uint32_t(n);
|
||||
}
|
||||
const auto phase = num(get(in, "phase")), ended = num(get(in, "ended")),
|
||||
mask = num(get(in, "kickoff_void_mask"));
|
||||
if (phase < 0 || phase > 1 || ended < 0 || ended > UINT32_MAX || mask < 0 || mask > UINT32_MAX)
|
||||
fail("invalid match checkpoint");
|
||||
g.phase = int(phase);
|
||||
g.ended = uint32_t(ended);
|
||||
g.kickoff_void_mask = uint32_t(mask);
|
||||
if ((g.desc.size() != 0xc0 && g.desc.size() != 0xd0) || g.fixtures.size() % 2 || g.matches() > 32 ||
|
||||
g.records.size() != size_t(g.matches()) * 18 || g.end_minute.size() != size_t(g.matches()) ||
|
||||
g.spectators.size() != size_t(g.matches()))
|
||||
fail("invalid match dimensions");
|
||||
return g;
|
||||
}
|
||||
J groups_json(const std::vector<MatchGroup> &groups) {
|
||||
A rows;
|
||||
for (const auto &group : groups)
|
||||
rows.push_back(group_json(group));
|
||||
return rows;
|
||||
}
|
||||
std::vector<MatchGroup> groups_json(const J &j) {
|
||||
std::vector<MatchGroup> groups;
|
||||
const auto &rows = arr(j);
|
||||
if (rows.size() > 6)
|
||||
fail("too many match groups");
|
||||
for (const auto &row : rows)
|
||||
groups.push_back(group_json(row));
|
||||
return groups;
|
||||
}
|
||||
} // namespace
|
||||
J driver_checkpoint(const TurnDriver &d) {
|
||||
return O{{"schema", "classic-driver@1.0"},
|
||||
{"stage", int(d.stage)},
|
||||
{"calendar_entry", d.calendar_entry},
|
||||
{"manager_position", d.manager_position},
|
||||
{"next_event_id", std::to_string(d.next_event_id)},
|
||||
{"loaded_matchday_resume", d.loaded_matchday_resume},
|
||||
{"suppress_remaining_pre_match_offers", d.suppress_remaining_pre_match_offers},
|
||||
{"national_nomination_desk", d.national_nomination_desk},
|
||||
{"enable_national_nomination_desks", d.enable_national_nomination_desks},
|
||||
{"groups", groups_json(d.groups)},
|
||||
{"referee_source", vector_json(d.referee_source)},
|
||||
{"referees", vector_json(d.referees)},
|
||||
{"last_results", O{{"valid", d.last_results.valid},
|
||||
{"date", int64_t(d.last_results.date)},
|
||||
{"calendar_entry", d.last_results.calendar_entry},
|
||||
{"matchday", d.last_results.matchday},
|
||||
{"groups", groups_json(d.last_results.groups)},
|
||||
{"tournament_name", vector_json(d.last_results.tournament_name)}}}};
|
||||
}
|
||||
void restore_driver(TurnDriver &d, const J &j) {
|
||||
if (str(get(j, "schema")) != "classic-driver@1.0")
|
||||
fail("unsupported driver checkpoint");
|
||||
const auto stage = num(get(j, "stage"));
|
||||
const auto position = num(get(j, "manager_position"));
|
||||
const auto entry = num(get(j, "calendar_entry"));
|
||||
if (stage < 0 || stage > 2 || position < 0 || position > 4 || entry < 0 || entry > UINT16_MAX)
|
||||
fail("invalid saved desk cursor");
|
||||
d.stage = TurnDriver::Stage(stage);
|
||||
d.manager_position = int(position);
|
||||
d.calendar_entry = uint16_t(entry);
|
||||
const auto flag = [](const J &value, const char *name) {
|
||||
const auto &b = get(value, name);
|
||||
if (!b.boolean())
|
||||
fail("invalid driver flag");
|
||||
return *b.boolean();
|
||||
};
|
||||
d.loaded_matchday_resume = flag(j, "loaded_matchday_resume");
|
||||
d.suppress_remaining_pre_match_offers = flag(j, "suppress_remaining_pre_match_offers");
|
||||
d.national_nomination_desk = flag(j, "national_nomination_desk");
|
||||
d.enable_national_nomination_desks = flag(j, "enable_national_nomination_desks");
|
||||
J counter = O{{"calls", get(j, "next_event_id")}};
|
||||
d.next_event_id = calls(counter);
|
||||
d.groups = groups_json(get(j, "groups"));
|
||||
d.referee_source.clear();
|
||||
d.referees.clear();
|
||||
vector_json(get(j, "referee_source"), d.referee_source);
|
||||
vector_json(get(j, "referees"), d.referees);
|
||||
const auto &last = get(j, "last_results");
|
||||
d.last_results.valid = flag(last, "valid");
|
||||
const auto date = num(get(last, "date")), calendar = num(get(last, "calendar_entry")),
|
||||
matchday = num(get(last, "matchday"));
|
||||
if (date < 0 || date > UINT32_MAX || calendar < 0 || calendar > UINT16_MAX || matchday < 0 ||
|
||||
matchday > UINT16_MAX)
|
||||
fail("invalid result snapshot");
|
||||
d.last_results.date = uint32_t(date);
|
||||
d.last_results.calendar_entry = uint16_t(calendar);
|
||||
d.last_results.matchday = uint16_t(matchday);
|
||||
d.last_results.groups = groups_json(get(last, "groups"));
|
||||
d.last_results.tournament_name.clear();
|
||||
vector_json(get(last, "tournament_name"), d.last_results.tournament_name);
|
||||
}
|
||||
void save_career(const std::filesystem::path &path, const Classic &content, const GameState &state,
|
||||
const WatcomRandom &random, const GameRandom &game, const TurnDriver &driver, bool overwrite,
|
||||
const J &session) {
|
||||
if (driver.stage != TurnDriver::Stage::Empty && driver.stage != TurnDriver::Stage::MatchdayDesks &&
|
||||
driver.stage != TurnDriver::Stage::SeasonEndDesk)
|
||||
fail("save unavailable outside a manager desk");
|
||||
Documents docs = content.documents;
|
||||
if (verify(docs) != content.content_id)
|
||||
fail("invalid content identity");
|
||||
docs["state/world-manifest.json"] = docs.at("manifest.json");
|
||||
auto manifest = parse(docs, "manifest.json");
|
||||
(*manifest.object())["kind"] = "save";
|
||||
(*manifest.object())["save_profile"] = "classic-career-v1";
|
||||
(*manifest.object())["content_id"] = content.content_id;
|
||||
put(docs, "manifest.json", std::move(manifest));
|
||||
put(docs, "state/career.json", encode_native_state(state));
|
||||
put(docs, "state/rng.json",
|
||||
O{{"schema", "classic-rng@1.0"},
|
||||
{"watcom", rng(random.seed(), random.calls())},
|
||||
{"game", rng(uint32_t(game.seed()), game.calls())}});
|
||||
put(docs, "state/session.json", session);
|
||||
put(docs, "state/driver.json", driver_checkpoint(driver));
|
||||
put(docs, "state/information.json", encode_native_bytes(save_header(state)));
|
||||
O checks;
|
||||
for (const auto &[name, value] : docs)
|
||||
if (name.starts_with("state/"))
|
||||
checks[name] = sha256(value);
|
||||
put(docs, "state/integrity.json", O{{"schema", "save-integrity@1.0"}, {"entries", std::move(checks)}});
|
||||
write_archive(docs, path, overwrite);
|
||||
}
|
||||
SavedCareer load_career(const std::filesystem::path &path, const Classic &content) {
|
||||
const auto docs = read_archive(path);
|
||||
const auto manifest = parse(docs, "manifest.json");
|
||||
if (str(get(manifest, "kind")) != "save" || str(get(manifest, "save_profile")) != "classic-career-v1" ||
|
||||
str(get(manifest, "content_id")) != content.content_id)
|
||||
fail("save belongs to another mod or format");
|
||||
const auto integrity = parse(docs, "state/integrity.json");
|
||||
if (str(get(integrity, "schema")) != "save-integrity@1.0")
|
||||
fail("unsupported save integrity");
|
||||
O checks;
|
||||
for (const auto &[name, value] : docs)
|
||||
if (name.starts_with("state/") && name != "state/integrity.json")
|
||||
checks[name] = sha256(value);
|
||||
if (cli::dump_json(get(integrity, "entries")) != cli::dump_json(checks))
|
||||
fail("damaged native save");
|
||||
const auto world = world_of(docs);
|
||||
if (verify(world) != content.content_id)
|
||||
fail("save world contents changed");
|
||||
SavedCareer out;
|
||||
out.state = decode_native_state(parse(docs, "state/career.json"));
|
||||
if (out.state.players.size() != content.database.players.size() ||
|
||||
out.state.club_ids.size() != content.database.club_names.size() ||
|
||||
out.state.manager_records.size() != 5 * 0xb0c)
|
||||
fail("native state does not match Classic dimensions");
|
||||
const auto generators = parse(docs, "state/rng.json");
|
||||
if (str(get(generators, "schema")) != "classic-rng@1.0")
|
||||
fail("unsupported RNG checkpoint");
|
||||
const auto &w = get(generators, "watcom");
|
||||
const auto &g = get(generators, "game");
|
||||
out.random.restore(seed(w), calls(w));
|
||||
out.game.restore(std::bit_cast<int32_t>(seed(g)), calls(g));
|
||||
out.session = parse(docs, "state/session.json");
|
||||
out.driver = parse(docs, "state/driver.json");
|
||||
out.header = decode_native_bytes(parse(docs, "state/information.json"), 172);
|
||||
return out;
|
||||
}
|
||||
Bytes save_information(const std::filesystem::path &path) {
|
||||
const auto docs = read_archive(path);
|
||||
return decode_native_bytes(parse(docs, "state/information.json"), 172);
|
||||
}
|
||||
Bytes load_preferences(const std::filesystem::path &path, const char *kind, size_t size) {
|
||||
const auto b = read_file(path);
|
||||
const auto root = cli::parse_json(std::string(b.begin(), b.end()));
|
||||
if (str(get(root, "schema")) != std::string("classic-") + kind + "@1.0")
|
||||
fail("unsupported preferences");
|
||||
return decode_native_bytes(get(root, "payload"), size);
|
||||
}
|
||||
void save_preferences(const std::filesystem::path &path, const char *kind, const Bytes &b, bool overwrite) {
|
||||
write_atomic(path,
|
||||
cli::dump_json(O{{"schema", std::string("classic-") + kind + "@1.0"},
|
||||
{"payload", encode_native_bytes(b)}}) +
|
||||
"\n",
|
||||
overwrite);
|
||||
}
|
||||
} // namespace bmh::content
|
||||
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include "content/package.hpp"
|
||||
#include "formats/native_state.hpp"
|
||||
#include "game/turn_driver.hpp"
|
||||
namespace bmh::content {
|
||||
struct SavedCareer {
|
||||
GameState state;
|
||||
WatcomRandom random;
|
||||
GameRandom game;
|
||||
cli::Json driver, session;
|
||||
Bytes header;
|
||||
};
|
||||
void save_career(const std::filesystem::path &, const Classic &, const GameState &, const WatcomRandom &,
|
||||
const GameRandom &, const TurnDriver &, bool overwrite, const cli::Json &session = {});
|
||||
SavedCareer load_career(const std::filesystem::path &, const Classic &);
|
||||
Bytes save_information(const std::filesystem::path &);
|
||||
cli::Json driver_checkpoint(const TurnDriver &);
|
||||
void restore_driver(TurnDriver &, const cli::Json &);
|
||||
// Native settings/layout files retain the validated Classic bytes with a typed envelope.
|
||||
Bytes load_preferences(const std::filesystem::path &, const char *kind, size_t size);
|
||||
void save_preferences(const std::filesystem::path &, const char *kind, const Bytes &, bool overwrite);
|
||||
} // namespace bmh::content
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/content.hpp"
|
||||
#include "formats/binary.hpp"
|
||||
|
||||
#include <fstream>
|
||||
@@ -7,6 +8,8 @@
|
||||
namespace bmh {
|
||||
|
||||
Bytes read_file(const std::filesystem::path& path) {
|
||||
if (const auto r = content::find(path))
|
||||
return content::bytes(*r);
|
||||
std::ifstream in(path, std::ios::binary);
|
||||
if (!in) throw FormatError("cannot open " + path.string());
|
||||
return Bytes(std::istreambuf_iterator<char>(in), {});
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/content.hpp"
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
namespace bmh::content {
|
||||
namespace {
|
||||
std::mutex mutex;
|
||||
struct Binding {
|
||||
std::shared_ptr<const Classic> content;
|
||||
int year;
|
||||
};
|
||||
std::map<std::filesystem::path, Binding> mounts;
|
||||
auto normalized(const std::filesystem::path &p) { return std::filesystem::absolute(p).lexically_normal(); }
|
||||
} // namespace
|
||||
std::string key(const std::filesystem::path &p) {
|
||||
auto result = p.generic_string();
|
||||
std::transform(result.begin(), result.end(), result.begin(),
|
||||
[](unsigned char c) { return char(std::tolower(c)); });
|
||||
return result;
|
||||
}
|
||||
Mount::Mount(std::filesystem::path root, std::shared_ptr<const Classic> value) : root_(normalized(root)) {
|
||||
if (!value)
|
||||
throw FormatError("content: empty mount");
|
||||
std::lock_guard lock(mutex);
|
||||
const auto year = value->start_year;
|
||||
if (!mounts.emplace(root_, Binding{std::move(value), year}).second)
|
||||
throw FormatError("content: already mounted");
|
||||
}
|
||||
Mount::~Mount() {
|
||||
std::lock_guard lock(mutex);
|
||||
mounts.erase(root_);
|
||||
}
|
||||
std::optional<Resource> find(const std::filesystem::path &p) {
|
||||
const auto full = normalized(p);
|
||||
std::lock_guard lock(mutex);
|
||||
for (const auto &[root, data] : mounts) {
|
||||
const auto relative = full.lexically_relative(root);
|
||||
if (relative.empty() || *relative.begin() == "..")
|
||||
continue;
|
||||
return Resource{data.content, key(relative), data.year};
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
void set_display_start_year(const std::filesystem::path &root, int year) {
|
||||
if (year < 1900 || year > 9998)
|
||||
throw FormatError("Invalid Classic display origin");
|
||||
std::lock_guard lock(mutex);
|
||||
const auto it = mounts.find(normalized(root));
|
||||
if (it == mounts.end())
|
||||
throw FormatError("Content is not mounted");
|
||||
it->second.year = year;
|
||||
}
|
||||
Bytes bytes(const Resource &r) {
|
||||
if (r.key == "m3.men")
|
||||
return r.content->desktops;
|
||||
if (r.key == "m3.dat")
|
||||
return r.content->formations;
|
||||
if (r.key == "textd.blk.header")
|
||||
return r.content->text_header;
|
||||
if (r.key.starts_with("s/")) {
|
||||
const auto it = r.content->audio.find(r.key.substr(2));
|
||||
if (it != r.content->audio.end())
|
||||
return it->second;
|
||||
}
|
||||
if (const auto it = r.content->supplemental.find(r.key); it != r.content->supplemental.end())
|
||||
return it->second;
|
||||
throw FormatError("content: no byte resource: " + r.key);
|
||||
}
|
||||
} // namespace bmh::content
|
||||
@@ -0,0 +1,54 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include "formats/font.hpp"
|
||||
#include "formats/palette.hpp"
|
||||
#include "formats/le.hpp"
|
||||
#include "formats/m3d.hpp"
|
||||
#include "formats/textd.hpp"
|
||||
|
||||
namespace bmh::content {
|
||||
// Immutable decoded Classic content. Logical aliases keep the existing UI geometry
|
||||
// independent of both storage layout and the legacy binary codecs.
|
||||
struct Classic {
|
||||
bool english = false;
|
||||
Database database;
|
||||
TextDb texts;
|
||||
LeImage executable, source_tables;
|
||||
Bytes desktops, formations, text_header;
|
||||
Palette palette;
|
||||
std::map<std::string, Image> images;
|
||||
std::map<std::string, Font> fonts;
|
||||
std::map<std::string, Palette> image_palettes;
|
||||
std::map<std::string, Bytes> audio;
|
||||
std::map<std::string, Bytes> supplemental;
|
||||
std::map<std::string, std::string> documents;
|
||||
std::string content_id;
|
||||
int start_year = 2026;
|
||||
};
|
||||
struct Resource {
|
||||
std::shared_ptr<const Classic> content;
|
||||
std::string key;
|
||||
int display_start_year = 2026;
|
||||
};
|
||||
// The mount owns a shared content reference; callers never reconstruct legacy files.
|
||||
// One game runs per process. Multiple mounts are supported by tools and tests.
|
||||
class Mount {
|
||||
public:
|
||||
Mount(std::filesystem::path root, std::shared_ptr<const Classic> content);
|
||||
~Mount();
|
||||
Mount(const Mount &) = delete;
|
||||
Mount &operator=(const Mount &) = delete;
|
||||
const std::filesystem::path &root() const { return root_; }
|
||||
|
||||
private:
|
||||
std::filesystem::path root_;
|
||||
};
|
||||
std::optional<Resource> find(const std::filesystem::path &locator);
|
||||
void set_display_start_year(const std::filesystem::path &root, int year);
|
||||
Bytes bytes(const Resource &resource);
|
||||
std::string key(const std::filesystem::path &relative);
|
||||
} // namespace bmh::content
|
||||
@@ -1,9 +1,16 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/content.hpp"
|
||||
#include "formats/font.hpp"
|
||||
|
||||
namespace bmh {
|
||||
|
||||
Font load_font(const std::filesystem::path& path) {
|
||||
if (const auto r = content::find(path)) {
|
||||
const auto found = r->content->fonts.find(std::filesystem::path(r->key).filename().string());
|
||||
if (found == r->content->fonts.end())
|
||||
throw FormatError("content: missing font: " + r->key);
|
||||
return found->second;
|
||||
}
|
||||
Bytes d = read_file(path);
|
||||
if (d.size() < 28) throw FormatError("FNT: file too short");
|
||||
Font f;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/content.hpp"
|
||||
#include "formats/le.hpp"
|
||||
#include "formats/rule_base.hpp"
|
||||
|
||||
@@ -37,6 +38,13 @@ void save_image(const LeImage& image, const std::filesystem::path& path) {
|
||||
}
|
||||
|
||||
LeImage load_le(const std::filesystem::path& path, bool apply_supported_rules) {
|
||||
if (const auto r = content::find(path)) {
|
||||
if (r->key != "bmh.exe")
|
||||
throw FormatError("content: unknown Classic table set");
|
||||
auto tables = apply_supported_rules ? r->content->executable : r->content->source_tables;
|
||||
tables.set_display_start_year(r->display_start_year);
|
||||
return tables;
|
||||
}
|
||||
const Bytes raw = read_file(path);
|
||||
if (raw.size() >= sizeof kImageMagic + 8 && std::equal(kImageMagic, kImageMagic + sizeof kImageMagic, raw.begin())) {
|
||||
const auto word = [&](size_t at) { return uint32_t(raw[at] | raw[at + 1] << 8 | raw[at + 2] << 16) | uint32_t(raw[at + 3]) << 24; };
|
||||
|
||||
+20
-16
@@ -18,20 +18,23 @@ namespace bmh {
|
||||
|
||||
class LeImage {
|
||||
public:
|
||||
uint32_t base() const { return base_; }
|
||||
uint32_t size() const { return uint32_t(bytes_.size()); }
|
||||
bool contains(uint32_t address) const { return address >= base_ && address - base_ < bytes_.size(); }
|
||||
uint8_t u8(uint32_t address) const { return bytes_.at(address - base_); }
|
||||
uint16_t u16(uint32_t address) const { return uint16_t(u8(address) | u8(address + 1) << 8); }
|
||||
uint32_t u32(uint32_t address) const { return uint32_t(u16(address)) | uint32_t(u16(address + 2)) << 16; }
|
||||
// A NUL terminated string at `address` (ISO 646-DE bytes, see textd.hpp).
|
||||
std::string cstring(uint32_t address) const;
|
||||
// The string a pointer variable at `address` points to (e.g. Weekly_AdvertisingOffers_TextPointer).
|
||||
std::string string_at_pointer(uint32_t address) const { return cstring(u32(address)); }
|
||||
const uint8_t* data(uint32_t address) const { return bytes_.data() + (address - base_); }
|
||||
// Overwrites bytes inside the image (the rule base, formats/rule_base.hpp).
|
||||
void patch(uint32_t address, const uint8_t* bytes, size_t count) {
|
||||
for (size_t i = 0; i < count; ++i) bytes_.at(address - base_ + i) = bytes[i];
|
||||
int display_start_year() const { return display_start_year_; }
|
||||
void set_display_start_year(int year) { display_start_year_ = year; }
|
||||
uint32_t base() const { return base_; }
|
||||
uint32_t size() const { return uint32_t(bytes_.size()); }
|
||||
bool contains(uint32_t address) const { return address >= base_ && address - base_ < bytes_.size(); }
|
||||
uint8_t u8(uint32_t address) const { return bytes_.at(address - base_); }
|
||||
uint16_t u16(uint32_t address) const { return uint16_t(u8(address) | u8(address + 1) << 8); }
|
||||
uint32_t u32(uint32_t address) const { return uint32_t(u16(address)) | uint32_t(u16(address + 2)) << 16; }
|
||||
// A NUL terminated string at `address` (ISO 646-DE bytes, see textd.hpp).
|
||||
std::string cstring(uint32_t address) const;
|
||||
// The string a pointer variable at `address` points to (e.g. Weekly_AdvertisingOffers_TextPointer).
|
||||
std::string string_at_pointer(uint32_t address) const { return cstring(u32(address)); }
|
||||
const uint8_t *data(uint32_t address) const { return bytes_.data() + (address - base_); }
|
||||
// Overwrites bytes inside the image (the rule base, formats/rule_base.hpp).
|
||||
void patch(uint32_t address, const uint8_t *bytes, size_t count) {
|
||||
for (size_t i = 0; i < count; ++i)
|
||||
bytes_.at(address - base_ + i) = bytes[i];
|
||||
}
|
||||
|
||||
// An image built by OpenBMH itself (the English FLTD.EXE translated into the German
|
||||
@@ -47,8 +50,9 @@ public:
|
||||
friend LeImage load_le(const std::filesystem::path& path, bool apply_supported_rules);
|
||||
|
||||
private:
|
||||
uint32_t base_ = 0;
|
||||
Bytes bytes_;
|
||||
int display_start_year_ = 2026;
|
||||
uint32_t base_ = 0;
|
||||
Bytes bytes_;
|
||||
};
|
||||
|
||||
// OpenBMH deviates from the original: applies a shared supported rule profile when loading editions with different rule-table values.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/content.hpp"
|
||||
#include "formats/m3d.hpp"
|
||||
|
||||
#include <cstring>
|
||||
@@ -35,6 +36,11 @@ std::string pool_string(const Bytes& pool, size_t offset) {
|
||||
} // namespace
|
||||
|
||||
Database load_database(const std::filesystem::path& path, const DbCounts& c) {
|
||||
if (const auto r = content::find(path)) {
|
||||
if (r->key != "m3d.man")
|
||||
throw FormatError("content: unknown database");
|
||||
return r->content->database;
|
||||
}
|
||||
return decode_database(read_file(path), c);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/native_file.hpp"
|
||||
#include "formats/binary.hpp"
|
||||
#include <chrono>
|
||||
#include <fstream>
|
||||
#ifdef _WIN32
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#endif
|
||||
namespace bmh::content {
|
||||
namespace fs = std::filesystem;
|
||||
namespace {
|
||||
[[noreturn]] void fail(const std::string &error) { throw FormatError(error); }
|
||||
} // namespace
|
||||
void write_atomic(const fs::path &file, std::string_view data, bool overwrite) {
|
||||
const auto parent = file.has_parent_path() ? file.parent_path() : fs::path(".");
|
||||
if (!fs::is_directory(parent))
|
||||
fail("destination directory unavailable");
|
||||
const auto status = fs::symlink_status(file);
|
||||
if (fs::is_symlink(status) || fs::is_directory(status) || (!overwrite && fs::exists(status)))
|
||||
fail("destination already exists or is unsafe");
|
||||
fs::path staging;
|
||||
for (int i = 0; i < 100; ++i) {
|
||||
auto candidate =
|
||||
parent /
|
||||
(".openbmh-write-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) +
|
||||
"-" + std::to_string(i));
|
||||
if (fs::create_directory(candidate)) {
|
||||
staging = std::move(candidate);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (staging.empty())
|
||||
fail("cannot reserve staging directory");
|
||||
struct Cleanup {
|
||||
fs::path path;
|
||||
~Cleanup() {
|
||||
std::error_code ec;
|
||||
fs::remove_all(path, ec);
|
||||
}
|
||||
} cleanup{staging};
|
||||
const auto temp = staging / "payload";
|
||||
std::ofstream stream(temp, std::ios::binary);
|
||||
stream.write(data.data(), std::streamsize(data.size()));
|
||||
stream.close();
|
||||
if (!stream)
|
||||
fail("cannot write temporary file");
|
||||
const auto current = fs::symlink_status(file);
|
||||
if (fs::is_symlink(current) || fs::is_directory(current) || (!overwrite && fs::exists(current)))
|
||||
fail("destination changed while writing");
|
||||
#ifdef _WIN32
|
||||
if (!MoveFileExW(temp.c_str(), file.c_str(),
|
||||
MOVEFILE_WRITE_THROUGH | (overwrite ? MOVEFILE_REPLACE_EXISTING : 0)))
|
||||
fail("cannot publish file");
|
||||
#else
|
||||
if (overwrite)
|
||||
fs::rename(temp, file);
|
||||
else {
|
||||
fs::create_hard_link(temp, file);
|
||||
fs::remove(temp);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
} // namespace bmh::content
|
||||
@@ -0,0 +1,7 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include <filesystem>
|
||||
#include <string_view>
|
||||
namespace bmh::content {
|
||||
void write_atomic(const std::filesystem::path &, std::string_view, bool overwrite = false);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/native_state.hpp"
|
||||
#include <limits>
|
||||
#include <type_traits>
|
||||
namespace bmh {
|
||||
namespace {
|
||||
using J = cli::Json;
|
||||
using O = J::Object;
|
||||
using A = J::Array;
|
||||
[[noreturn]] void invalid() { throw FormatError("native state: invalid or missing field"); }
|
||||
const J &field(const J &obj, const char *name) {
|
||||
if (!obj.object())
|
||||
invalid();
|
||||
const auto it = obj.object()->find(name);
|
||||
if (it == obj.object()->end())
|
||||
invalid();
|
||||
return it->second;
|
||||
}
|
||||
template <class T> J number(T v) { return J(int64_t(v)); }
|
||||
template <class T> void number(const J &j, T &v) {
|
||||
if (!j.integer())
|
||||
invalid();
|
||||
const auto n = *j.integer();
|
||||
if constexpr (std::is_unsigned_v<T>) {
|
||||
if (n < 0 || uint64_t(n) > uint64_t(std::numeric_limits<T>::max()))
|
||||
invalid();
|
||||
} else if (n < std::numeric_limits<T>::min() || n > std::numeric_limits<T>::max())
|
||||
invalid();
|
||||
v = T(n);
|
||||
}
|
||||
J scalar(bool b) { return b; }
|
||||
void scalar(const J &j, bool &b) {
|
||||
if (!j.boolean())
|
||||
invalid();
|
||||
b = *j.boolean();
|
||||
}
|
||||
template <class T> J scalar(T n) { return number(n); }
|
||||
template <class T> void scalar(const J &j, T &n) { number(j, n); }
|
||||
template <class Range> J sequence(const Range &values) {
|
||||
A out;
|
||||
for (const auto v : values)
|
||||
out.push_back(number(v));
|
||||
return out;
|
||||
}
|
||||
template <class T> void sequence(const J &j, std::vector<T> &values) {
|
||||
if (!j.array() || j.array()->size() > 1000000)
|
||||
invalid();
|
||||
values.resize(j.array()->size());
|
||||
for (size_t i = 0; i < values.size(); ++i)
|
||||
number((*j.array())[i], values[i]);
|
||||
}
|
||||
template <class T, size_t N> void sequence(const J &j, std::array<T, N> &values) {
|
||||
if (!j.array() || j.array()->size() != N)
|
||||
invalid();
|
||||
for (size_t i = 0; i < N; ++i)
|
||||
number((*j.array())[i], values[i]);
|
||||
}
|
||||
std::string hex(const Bytes &data) {
|
||||
constexpr char d[] = "0123456789abcdef";
|
||||
std::string out;
|
||||
out.reserve(data.size() * 2);
|
||||
for (auto c : data) {
|
||||
out += d[c >> 4];
|
||||
out += d[c & 15];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
Bytes unhex(const J &value) {
|
||||
if (!value.string() || value.string()->size() % 2 || value.string()->size() > 32 * 1024 * 1024)
|
||||
invalid();
|
||||
const auto &s = *value.string();
|
||||
Bytes b;
|
||||
b.reserve(s.size() / 2);
|
||||
const auto digit = [](char c) -> int {
|
||||
if (c >= '0' && c <= '9')
|
||||
return c - '0';
|
||||
if (c >= 'a' && c <= 'f')
|
||||
return c - 'a' + 10;
|
||||
invalid();
|
||||
};
|
||||
for (size_t i = 0; i < s.size(); i += 2)
|
||||
b.push_back(uint8_t(digit(s[i]) * 16 + digit(s[i + 1])));
|
||||
return b;
|
||||
}
|
||||
} // namespace
|
||||
cli::Json encode_native_bytes(const Bytes &bytes) {
|
||||
return O{{"schema", "classic-bytes@1.0"}, {"hex", hex(bytes)}};
|
||||
}
|
||||
Bytes decode_native_bytes(const J &value, size_t expected) {
|
||||
if (!field(value, "schema").string() || *field(value, "schema").string() != "classic-bytes@1.0")
|
||||
invalid();
|
||||
auto b = unhex(field(value, "hex"));
|
||||
if (b.size() != expected)
|
||||
invalid();
|
||||
return b;
|
||||
}
|
||||
#define STATE_SCALARS(X) \
|
||||
X(indoor) \
|
||||
X(level) X(chance_rain) X(chance_temperature) X(last_shooter) X(last_pick_quality) X(live_scene) \
|
||||
X(sportschau_selection_available) X(sportschau_club_threshold) X(list_toggle) X(lineups_frozen) \
|
||||
X(offer_answer) X(transfer_notice_suppressed) X(pools_open) X(autosave_months) X(autosave_month) \
|
||||
X(display_start_year) X(date) X(season_start) X(development_balance) X(trend_rotation) \
|
||||
X(season)
|
||||
#define STATE_BYTES(X) \
|
||||
X(team_morale) \
|
||||
X(player_bonus) X(formations) X(manager_records) X(tactics) X(manager_options) X(club_table) \
|
||||
X(club_heap_bc) X(club_heap_78) X(club_heap_b8) X(master_database_metadata) X(referee_names) \
|
||||
X(stadium_names) X(tournament_name) X(manager_results) X(manager_ratings) X(position_history) \
|
||||
X(league_rounds) X(results) X(stocks) X(foreign_strength) X(mailbox) X(club_names) \
|
||||
X(player_names)
|
||||
#define STATE_NUMBERS(X) \
|
||||
X(squad_slots) \
|
||||
X(team_flags) X(manager_teams) X(live_matches) X(sportschau_homes) X(sportschau_priorities) X(club_ids) \
|
||||
X(player_cards) X(player_name_offsets)
|
||||
J encode_native_state(const GameState &g) {
|
||||
O out{{"schema", "classic-state@1.0"}};
|
||||
#define PUT_SCALAR(name) out[#name] = scalar(g.name);
|
||||
STATE_SCALARS(PUT_SCALAR)
|
||||
#undef PUT_SCALAR
|
||||
#define PUT_BYTES(name) out[#name] = hex(g.name);
|
||||
STATE_BYTES(PUT_BYTES)
|
||||
#undef PUT_BYTES
|
||||
#define PUT_NUMBERS(name) out[#name] = sequence(g.name);
|
||||
STATE_NUMBERS(PUT_NUMBERS)
|
||||
#undef PUT_NUMBERS
|
||||
A players;
|
||||
for (const auto &p : g.players)
|
||||
players.push_back(O{{"name_hex", hex(Bytes(p.name.begin(), p.name.end()))},
|
||||
{"form", number(p.w35c)},
|
||||
{"skills", number(p.w368)},
|
||||
{"identity", number(p.w364)}});
|
||||
out["players"] = std::move(players);
|
||||
A blocks;
|
||||
for (const auto &[at, bytes] : g.memory.blocks())
|
||||
blocks.push_back(O{{"address", number(at)}, {"hex", hex(bytes)}});
|
||||
out["memory"] = std::move(blocks);
|
||||
// Reality scene residues influence later matches and must survive a checkpoint.
|
||||
out["reality"] = O{{"initialized", g.reality.initialized}, {"deflected", g.reality.deflected},
|
||||
{"card_kind", number(g.reality.card_kind)}, {"distance", g.reality.distance},
|
||||
{"actors", sequence(g.reality.cue_actors)}, {"grid", g.reality.grid.checkpoint()}};
|
||||
return out;
|
||||
}
|
||||
GameState decode_native_state(const J &in) {
|
||||
if (!field(in, "schema").string() || *field(in, "schema").string() != "classic-state@1.0")
|
||||
invalid();
|
||||
GameState g;
|
||||
#define GET_SCALAR(name) scalar(field(in, #name), g.name);
|
||||
STATE_SCALARS(GET_SCALAR)
|
||||
#undef GET_SCALAR
|
||||
#define GET_BYTES(name) g.name = unhex(field(in, #name));
|
||||
STATE_BYTES(GET_BYTES)
|
||||
#undef GET_BYTES
|
||||
#define GET_NUMBERS(name) sequence(field(in, #name), g.name);
|
||||
STATE_NUMBERS(GET_NUMBERS)
|
||||
#undef GET_NUMBERS
|
||||
const auto &players = field(in, "players");
|
||||
if (!players.array() || players.array()->size() > 4095)
|
||||
invalid();
|
||||
for (const auto &row : *players.array()) {
|
||||
Player p;
|
||||
auto bytes = unhex(field(row, "name_hex"));
|
||||
p.name.assign(bytes.begin(), bytes.end());
|
||||
number(field(row, "form"), p.w35c);
|
||||
number(field(row, "skills"), p.w368);
|
||||
number(field(row, "identity"), p.w364);
|
||||
g.players.push_back(std::move(p));
|
||||
}
|
||||
const auto &memory = field(in, "memory");
|
||||
if (!memory.array() || memory.array()->size() > 8192)
|
||||
invalid();
|
||||
std::map<uint32_t, Bytes> blocks;
|
||||
for (const auto &row : *memory.array()) {
|
||||
uint32_t at;
|
||||
number(field(row, "address"), at);
|
||||
auto b = unhex(field(row, "hex"));
|
||||
if (uint64_t(at) + b.size() > UINT32_MAX || !blocks.emplace(at, std::move(b)).second)
|
||||
invalid();
|
||||
}
|
||||
g.memory = StaticMemory::from_blocks(std::move(blocks));
|
||||
const auto &reality = field(in, "reality");
|
||||
scalar(field(reality, "initialized"), g.reality.initialized);
|
||||
scalar(field(reality, "deflected"), g.reality.deflected);
|
||||
number(field(reality, "card_kind"), g.reality.card_kind);
|
||||
number(field(reality, "distance"), g.reality.distance);
|
||||
sequence(field(reality, "actors"), g.reality.cue_actors);
|
||||
g.reality.grid.restore_checkpoint(field(reality, "grid"));
|
||||
if (g.display_start_year < 1900 || g.display_start_year > 9998 || g.manager_teams.size() > 4 ||
|
||||
g.level < 0 || g.level > 9 || g.date < g.season_start || g.date > 3000000)
|
||||
invalid();
|
||||
return g;
|
||||
}
|
||||
#undef STATE_SCALARS
|
||||
#undef STATE_BYTES
|
||||
#undef STATE_NUMBERS
|
||||
} // namespace bmh
|
||||
@@ -0,0 +1,11 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include "cli/json.hpp"
|
||||
#include "game/state.hpp"
|
||||
namespace bmh {
|
||||
// Explicit, platform-independent checkpoint. No object dumps, pointers or callbacks.
|
||||
cli::Json encode_native_state(const GameState &);
|
||||
GameState decode_native_state(const cli::Json &);
|
||||
cli::Json encode_native_bytes(const Bytes &);
|
||||
Bytes decode_native_bytes(const cli::Json &, size_t expected);
|
||||
} // namespace bmh
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/content.hpp"
|
||||
#include "formats/palette.hpp"
|
||||
|
||||
#include "formats/binary.hpp"
|
||||
@@ -6,6 +7,11 @@
|
||||
namespace bmh {
|
||||
|
||||
Palette load_palette(const std::filesystem::path& path) {
|
||||
if (const auto r = content::find(path)) {
|
||||
if (r->key != "m3pc.col")
|
||||
throw FormatError("content: unknown palette");
|
||||
return r->content->palette;
|
||||
}
|
||||
Bytes b = read_file(path);
|
||||
if (b.size() < 768) throw FormatError("palette too short: " + path.string());
|
||||
Palette p;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/content.hpp"
|
||||
#include "formats/textd.hpp"
|
||||
|
||||
#include "formats/binary.hpp"
|
||||
@@ -6,6 +7,11 @@
|
||||
namespace bmh {
|
||||
|
||||
TextDb load_textd(const std::filesystem::path& path) {
|
||||
if (const auto r = content::find(path)) {
|
||||
if (r->key != "textd.blk")
|
||||
throw FormatError("content: unknown text set");
|
||||
return r->content->texts;
|
||||
}
|
||||
Bytes d = read_file(path);
|
||||
if (d.size() < 7) throw FormatError("TEXTD: file too short");
|
||||
// header: u8 id, u16 buffer size, u32 unknown; the buffer may be larger than the file rest
|
||||
|
||||
+12
-1
@@ -1,5 +1,6 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/vga.hpp"
|
||||
#include "formats/content.hpp"
|
||||
|
||||
namespace bmh {
|
||||
|
||||
@@ -40,6 +41,16 @@ Image decode_vga(const Bytes& d) {
|
||||
return img;
|
||||
}
|
||||
|
||||
Image load_vga(const std::filesystem::path& path) { return decode_vga(read_file(path)); }
|
||||
Image load_vga(const std::filesystem::path &path) {
|
||||
if (const auto r = content::find(path)) {
|
||||
auto name = std::filesystem::path(r->key);
|
||||
name.replace_extension();
|
||||
const auto found = r->content->images.find(name.generic_string());
|
||||
if (found == r->content->images.end())
|
||||
throw FormatError("content: missing image: " + r->key);
|
||||
return found->second;
|
||||
}
|
||||
return decode_vga(read_file(path));
|
||||
}
|
||||
|
||||
} // namespace bmh
|
||||
+29
-1
@@ -1,6 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/executable_layout.hpp"
|
||||
#include "game/highscore.hpp"
|
||||
#include "formats/native_state.hpp"
|
||||
#include "formats/native_file.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <bit>
|
||||
@@ -186,11 +188,25 @@ HighscoreTable decode_highscore_table(const HighscoreBytes& bytes) {
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
std::filesystem::path highscore_file(const std::filesystem::path& base, uint16_t signature, const std::string& prefix) {
|
||||
std::filesystem::path highscore_file(const std::filesystem::path &base, uint16_t signature,
|
||||
const std::string &prefix, bool native) {
|
||||
if (!signature) throw std::invalid_argument("highscore: signature0 has no ranked file");
|
||||
if (native)
|
||||
return base / ("highscore-" + std::to_string(signature) + ".obscore");
|
||||
return base / (prefix + std::to_string(signature));
|
||||
}
|
||||
HighscoreTable load_highscore_table(const std::filesystem::path& file) {
|
||||
if (file.extension() == ".obscore") {
|
||||
const auto data = read_file(file);
|
||||
const auto j = cli::parse_json(std::string(data.begin(), data.end()));
|
||||
if (!j.object() || !j.object()->contains("schema") || !j.object()->at("schema").string() ||
|
||||
*j.object()->at("schema").string() != "classic-highscore@1.0" || !j.object()->contains("payload"))
|
||||
throw FormatError("Invalid native highscore");
|
||||
const auto raw = decode_native_bytes(j.object()->at("payload"), 360);
|
||||
HighscoreBytes bytes;
|
||||
std::copy(raw.begin(), raw.end(), bytes.begin());
|
||||
return decode_highscore_table(bytes);
|
||||
}
|
||||
std::ifstream in(file, std::ios::binary);
|
||||
if (!in) {
|
||||
HighscoreTable empty{};
|
||||
@@ -203,6 +219,18 @@ HighscoreTable load_highscore_table(const std::filesystem::path& file) {
|
||||
}
|
||||
bool save_highscore_table(const std::filesystem::path& file, const HighscoreTable& rows) {
|
||||
const auto bytes = encode_highscore_table(rows);
|
||||
if (file.extension() == ".obscore") {
|
||||
try {
|
||||
content::write_atomic(file,
|
||||
cli::dump_json(cli::Json::Object{
|
||||
{"schema", "classic-highscore@1.0"},
|
||||
{"payload", encode_native_bytes(Bytes(bytes.begin(), bytes.end()))}}),
|
||||
true);
|
||||
return true;
|
||||
} catch (const std::exception &) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
std::ofstream out(file, std::ios::binary | std::ios::trunc);
|
||||
if (!out) return false;
|
||||
out.write(reinterpret_cast<const char*>(bytes.data()), bytes.size());
|
||||
|
||||
@@ -53,8 +53,8 @@ HighscoreProjection make_highscore_projection(const GameState& g, HighscoreTable
|
||||
HighscoreBytes encode_highscore_table(const HighscoreTable& rows);
|
||||
HighscoreTable decode_highscore_table(const HighscoreBytes& bytes);
|
||||
// The caller supplies the configured installation base and Original TEXTD889 prefix.
|
||||
std::filesystem::path highscore_file(const std::filesystem::path& base,
|
||||
uint16_t signature, const std::string& prefix = "high/h.");
|
||||
std::filesystem::path highscore_file(const std::filesystem::path &base, uint16_t signature,
|
||||
const std::string &prefix = "high/h.", bool native = false);
|
||||
HighscoreTable load_highscore_table(const std::filesystem::path& file);
|
||||
bool save_highscore_table(const std::filesystem::path& file, const HighscoreTable& rows);
|
||||
|
||||
|
||||
@@ -70,6 +70,13 @@ public:
|
||||
}
|
||||
void set_pointer(uint32_t a, uint32_t address) { set32(a, address == 0 ? 0 : address + kGuestDataBase); }
|
||||
|
||||
const std::map<uint32_t, Bytes> &blocks() const { return blocks_; }
|
||||
static StaticMemory from_blocks(std::map<uint32_t, Bytes> blocks) {
|
||||
StaticMemory memory;
|
||||
memory.blocks_ = std::move(blocks);
|
||||
return memory;
|
||||
}
|
||||
|
||||
private:
|
||||
static std::string hex(uint32_t v) {
|
||||
char b[16];
|
||||
|
||||
@@ -20,6 +20,10 @@ public:
|
||||
void srand(uint32_t seed) { seed_ = seed; }
|
||||
uint32_t seed() const { return seed_; }
|
||||
uint64_t calls() const { return calls_; }
|
||||
void restore(uint32_t seed, uint64_t calls) {
|
||||
seed_ = seed;
|
||||
calls_ = calls;
|
||||
}
|
||||
int rand() {
|
||||
calls_++;
|
||||
if (draw_hook) draw_hook(1);
|
||||
@@ -47,6 +51,10 @@ public:
|
||||
int32_t seed() const { return seed_; }
|
||||
void set_seed(int32_t seed) { seed_ = seed; }
|
||||
uint64_t calls() const { return calls_; }
|
||||
void restore(int32_t seed, uint64_t calls) {
|
||||
seed_ = seed;
|
||||
calls_ = calls;
|
||||
}
|
||||
int32_t range(int32_t lo, int32_t hi) {
|
||||
calls_++;
|
||||
if (draw_hook) draw_hook(0);
|
||||
|
||||
@@ -166,3 +166,60 @@ std::pair<int,int> RealityGrid::position(int figure) const {
|
||||
}
|
||||
|
||||
} // namespace bmh
|
||||
|
||||
namespace bmh {
|
||||
cli::Json RealityGrid::checkpoint() const {
|
||||
cli::Json::Array planes, positions;
|
||||
for (const auto &plane : occupied_) {
|
||||
cli::Json::Array cells;
|
||||
for (auto b : plane)
|
||||
cells.emplace_back(int(b));
|
||||
planes.emplace_back(std::move(cells));
|
||||
}
|
||||
for (const auto &[x, y] : positions_)
|
||||
positions.emplace_back(cli::Json::Array{x, y});
|
||||
return cli::Json::Object{
|
||||
{"planes", std::move(planes)},
|
||||
{"positions", std::move(positions)},
|
||||
{"ball", cli::Json::Array{ball_.first, ball_.second}},
|
||||
{"previous_ball", cli::Json::Array{previous_ball_.first, previous_ball_.second}}};
|
||||
}
|
||||
void RealityGrid::restore_checkpoint(const cli::Json &value) {
|
||||
const auto field = [&](const char *name) -> const cli::Json & {
|
||||
if (!value.object() || !value.object()->contains(name))
|
||||
throw FormatError("native Reality grid field missing");
|
||||
return value.object()->at(name);
|
||||
};
|
||||
const auto array = [](const cli::Json &j, size_t size) -> const cli::Json::Array & {
|
||||
if (!j.array() || j.array()->size() != size)
|
||||
throw FormatError("invalid native Reality grid dimensions");
|
||||
return *j.array();
|
||||
};
|
||||
const auto integer = [](const cli::Json &j) -> int {
|
||||
if (!j.integer() || *j.integer() < INT32_MIN || *j.integer() > INT32_MAX)
|
||||
throw FormatError("invalid native Reality coordinate");
|
||||
return int(*j.integer());
|
||||
};
|
||||
RealityGrid restored;
|
||||
const auto &planes = array(field("planes"), 2);
|
||||
for (size_t p = 0; p < 2; ++p) {
|
||||
const auto &cells = array(planes[p], 0x478);
|
||||
for (size_t i = 0; i < cells.size(); ++i) {
|
||||
const int n = integer(cells[i]);
|
||||
if (n < 0 || n > 255)
|
||||
throw FormatError("invalid native Reality cell");
|
||||
restored.occupied_[p][i] = uint8_t(n);
|
||||
}
|
||||
}
|
||||
const auto pair = [&](const cli::Json &j) {
|
||||
const auto &xy = array(j, 2);
|
||||
return std::pair<int, int>{integer(xy[0]), integer(xy[1])};
|
||||
};
|
||||
const auto &positions = array(field("positions"), 24);
|
||||
for (size_t i = 0; i < 24; ++i)
|
||||
restored.positions_[i] = pair(positions[i]);
|
||||
restored.ball_ = pair(field("ball"));
|
||||
restored.previous_ball_ = pair(field("previous_ball"));
|
||||
*this = std::move(restored);
|
||||
}
|
||||
} // namespace bmh
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <utility>
|
||||
|
||||
#include "formats/le.hpp"
|
||||
#include "cli/json.hpp"
|
||||
|
||||
namespace bmh {
|
||||
|
||||
@@ -59,15 +60,17 @@ RealityPath reality_goal_path(int x, int y, int goal_x);
|
||||
// either player plane. This is runtime scene state, not a Native save extension.
|
||||
class RealityGrid {
|
||||
public:
|
||||
bool place(int figure, int x, int y, int side);
|
||||
void clear(int x, int y, int side); // caller clears old occupancy before a move
|
||||
void reset_occupancy(); // Source initialization preserves old figure/ball data
|
||||
bool operator==(const RealityGrid&) const = default;
|
||||
void stage_position(int figure, int x, int y); // afb0c/afb23 before occupancy is committed
|
||||
uint8_t occupant(int x, int y, int side) const;
|
||||
std::pair<int, int> position(int figure) const;
|
||||
std::pair<int, int> ball() const { return ball_; }
|
||||
std::pair<int, int> previous_ball() const { return previous_ball_; }
|
||||
cli::Json checkpoint() const;
|
||||
void restore_checkpoint(const cli::Json &);
|
||||
bool place(int figure, int x, int y, int side);
|
||||
void clear(int x, int y, int side); // caller clears old occupancy before a move
|
||||
void reset_occupancy(); // Source initialization preserves old figure/ball data
|
||||
bool operator==(const RealityGrid &) const = default;
|
||||
void stage_position(int figure, int x, int y); // afb0c/afb23 before occupancy is committed
|
||||
uint8_t occupant(int x, int y, int side) const;
|
||||
std::pair<int, int> position(int figure) const;
|
||||
std::pair<int, int> ball() const { return ball_; }
|
||||
std::pair<int, int> previous_ball() const { return previous_ball_; }
|
||||
private:
|
||||
std::array<std::array<uint8_t, 0x478>, 2> occupied_{};
|
||||
std::array<std::pair<int, int>, 24> positions_{};
|
||||
|
||||
+3
-3
@@ -27,7 +27,7 @@ void put32(Bytes& d, size_t at, uint32_t x) {
|
||||
|
||||
// DeskDate2(date, buffer, 0): "TT.MM.JJJJ" of a day counter (day 0 = 1 July 2026; a
|
||||
// four-year leap cycle that starts with the third year).
|
||||
std::string date_text(uint32_t counter) {
|
||||
std::string date_text(uint32_t counter, int start_year) {
|
||||
static const int kDays[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
|
||||
int cycle = 3, years = 0, month = 7;
|
||||
while (counter > uint32_t(364 + (cycle == 4))) {
|
||||
@@ -45,7 +45,7 @@ std::string date_text(uint32_t counter) {
|
||||
if (++month == 13) month = 1, ++years;
|
||||
}
|
||||
char buf[16];
|
||||
std::snprintf(buf, sizeof buf, "%02d.%02d.%04d", day, month, 2026 + years);
|
||||
std::snprintf(buf, sizeof buf, "%02d.%02d.%04d", day, month, start_year + years);
|
||||
return buf;
|
||||
}
|
||||
|
||||
@@ -133,7 +133,7 @@ Bytes save_header(const GameState& g) {
|
||||
const int managers = g.memory.u8(::bmh::layout::ManagerCount);
|
||||
Bytes h;
|
||||
h.push_back(uint8_t(managers));
|
||||
const std::string date = date_text(g.date);
|
||||
const std::string date = date_text(g.date, g.display_start_year);
|
||||
for (size_t i = 0; i < 11; i++) h.push_back(i < date.size() ? uint8_t(date[i]) : 0);
|
||||
Bytes list(0xa0, 0);
|
||||
for (int m = 0; m < managers && m < 4; m++) {
|
||||
|
||||
@@ -174,6 +174,7 @@ struct GameState {
|
||||
// 3 (stadiums, *ba360): not used by the engine, kept for writing savegames.
|
||||
std::vector<uint8_t> master_database_metadata, referee_names, stadium_names;
|
||||
std::vector<uint16_t> player_cards; // *PlayerCards, per player: card counters per competition
|
||||
int display_start_year = 2026; // Cosmetic Classic origin; does not alter scheduling.
|
||||
uint32_t date = 0; // CalendarDay: day counter
|
||||
// DaysIntoSeason (day of the season, the calendar index) moves with the day counter within
|
||||
// a season: season_day() = date - season_start.
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-only
|
||||
add_library(bmh_obw STATIC obw.cpp classic.cpp assets.cpp ../cli/json.cpp ../audio/container.cpp)
|
||||
add_library(bmh_obw STATIC obw.cpp classic.cpp assets.cpp save.cpp ../audio/container.cpp)
|
||||
target_include_directories(bmh_obw PUBLIC ..)
|
||||
target_link_libraries(bmh_obw PUBLIC bmhlaunch PRIVATE bmh_miniz)
|
||||
add_executable(openbmh_import main.cpp)
|
||||
target_link_libraries(openbmh_import PRIVATE bmh_obw)
|
||||
target_link_libraries(openbmh_import PRIVATE bmh_content)
|
||||
set_target_properties(openbmh_import PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}")
|
||||
add_executable(obw_import_tests ../../tests/obw_import_tests.cpp)
|
||||
target_link_libraries(obw_import_tests PRIVATE bmh_obw bmh_miniz)
|
||||
target_link_libraries(obw_import_tests PRIVATE bmh_content bmh_miniz)
|
||||
if(MSVC)
|
||||
target_compile_options(bmh_obw PRIVATE /W4 /utf-8)
|
||||
target_compile_options(openbmh_import PRIVATE /W4 /utf-8)
|
||||
@@ -22,3 +22,39 @@ if(MSVC)
|
||||
endif()
|
||||
bmh_add_data_test(NAME obw_classic_installation_tests COMMAND obw_classic_installation_tests "${BMH_DATA}")
|
||||
install(TARGETS openbmh_import RUNTIME DESTINATION . COMPONENT Runtime)
|
||||
|
||||
add_library(bmh_content STATIC ../content/digest.cpp ../content/package.cpp ../content/save.cpp)
|
||||
target_include_directories(bmh_content PUBLIC ..)
|
||||
target_link_libraries(bmh_content PUBLIC bmh_obw PRIVATE bmh_miniz)
|
||||
|
||||
add_library(bmh_launcher STATIC ../launch/mods.cpp ../launch/process.cpp ../launch/launcher.cpp)
|
||||
target_include_directories(bmh_launcher PUBLIC ..)
|
||||
target_link_libraries(bmh_launcher PUBLIC bmh_content)
|
||||
if(WIN32)
|
||||
target_sources(bmh_launcher PRIVATE ../launch/launcher_win32.cpp)
|
||||
target_link_libraries(bmh_launcher PRIVATE comctl32 ole32 shell32 uuid)
|
||||
elseif(APPLE)
|
||||
enable_language(OBJCXX)
|
||||
set_property(TARGET bmh_launcher PROPERTY OBJCXX_STANDARD 20)
|
||||
target_sources(bmh_launcher PRIVATE ../launch/launcher_cocoa.mm)
|
||||
set_source_files_properties(../launch/launcher_cocoa.mm PROPERTIES COMPILE_OPTIONS "-fobjc-arc")
|
||||
target_link_libraries(bmh_launcher PRIVATE "-framework AppKit")
|
||||
else()
|
||||
find_package(PkgConfig REQUIRED)
|
||||
pkg_check_modules(BMH_GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
|
||||
target_sources(bmh_launcher PRIVATE ../launch/launcher_gtk.cpp)
|
||||
target_link_libraries(bmh_launcher PRIVATE PkgConfig::BMH_GTK)
|
||||
endif()
|
||||
add_executable(native_content_tests ../../tests/native_content_tests.cpp)
|
||||
target_link_libraries(native_content_tests PRIVATE bmh_launcher)
|
||||
add_test(NAME native_content_tests COMMAND native_content_tests)
|
||||
add_executable(native_runtime_tests ../../tests/native_runtime_tests.cpp ${BMH_APP_SESSION_SOURCE})
|
||||
target_link_libraries(native_runtime_tests PRIVATE bmhui bmh_launcher)
|
||||
bmh_add_data_test(NAME native_runtime_tests COMMAND native_runtime_tests "${BMH_DATA}")
|
||||
|
||||
if(MSVC)
|
||||
target_compile_options(bmh_content PRIVATE /W4 /utf-8)
|
||||
target_compile_options(bmh_launcher PRIVATE /W4 /utf-8)
|
||||
target_compile_options(native_content_tests PRIVATE /utf-8)
|
||||
target_compile_options(native_runtime_tests PRIVATE /utf-8)
|
||||
endif()
|
||||
+60
-4
@@ -109,7 +109,7 @@ cli::Json portrait_recipe(const std::string& legacy_name, const LeImage& exe) {
|
||||
void import_assets(Documents& out, const std::filesystem::path& root, const Database& db, const LeImage& exe) {
|
||||
using namespace detail;
|
||||
const auto palette = load_palette(required(root, "M3PC.COL"));
|
||||
A colors, index, images, fonts, audio, animations;
|
||||
A colors, index, images, fonts, audio, animations, palettes, supplemental;
|
||||
for (const auto color : palette.argb) colors.emplace_back(int64_t(color));
|
||||
put(out, "assets/classic/palette.json", O{{"schema", "classic-palette@1.0"}, {"argb", std::move(colors)}});
|
||||
std::map<std::string, Image> atlases;
|
||||
@@ -129,7 +129,21 @@ void import_assets(Documents& out, const std::filesystem::path& root, const Data
|
||||
const auto name = lower(group) + '/' + launch::path_to_utf8(path.stem());
|
||||
if (atlases.contains(name)) fail("duplicate image resource: " + name);
|
||||
auto image = decode_vga(bytes);
|
||||
image_entry(out, images, index, "asset:classic/" + name, name, image, palette);
|
||||
const size_t end = 8 + size_t(le32(bytes, 4));
|
||||
if (end > bytes.size())
|
||||
fail("invalid indexed image stream length");
|
||||
Palette effective = palette;
|
||||
if (bytes.size() - end >= 768) {
|
||||
A entries;
|
||||
for (size_t i = 0; i < 256; ++i) {
|
||||
auto channel = [&](size_t c) { return uint32_t(vga_dac_rgb8(bytes[end + i * 3 + c])); };
|
||||
effective.argb[i] = 0xff000000u | channel(0) << 16 | channel(1) << 8 | channel(2);
|
||||
entries.emplace_back(int64_t(effective.argb[i]));
|
||||
}
|
||||
palettes.emplace_back(O{{"name", name}, {"argb", std::move(entries)}});
|
||||
} else if (end != bytes.size())
|
||||
fail("truncated embedded palette");
|
||||
image_entry(out, images, index, "asset:classic/" + name, name, image, effective);
|
||||
atlases.emplace(name, std::move(image));
|
||||
}
|
||||
}
|
||||
@@ -225,8 +239,29 @@ void import_assets(Documents& out, const std::filesystem::path& root, const Data
|
||||
animations.emplace_back(O{{"name", name}, {"path", path}});
|
||||
index.emplace_back(asset("asset:classic/optional/" + name, path, name, "legacy-artwork"));
|
||||
}
|
||||
put(out, "assets/classic/resources.json", O{{"schema", "classic-resources@1.0"},
|
||||
{"images", std::move(images)}, {"fonts", std::move(fonts)}, {"audio", std::move(audio)}, {"optional", std::move(animations)}});
|
||||
// The in-game readme is content too; preserve its original byte encoding locally.
|
||||
const bool english = str(get(parse(out, "manifest.json"), "provenance")) == "import:fltd";
|
||||
const auto texts = load_textd(required(root, english ? "TEXTE.BLK" : "TEXTD.BLK"));
|
||||
if (texts.strings.size() > 839) {
|
||||
const auto name = texts[839];
|
||||
if (!name.empty() && fs::path(name) == fs::path(name).filename()) {
|
||||
if (const auto source = launch::find_file(root, name); source && fs::is_regular_file(*source)) {
|
||||
if (fs::is_symlink(fs::symlink_status(*source)) || fs::file_size(*source) > 1024 * 1024)
|
||||
fail("unsafe readme input");
|
||||
const auto path = "assets/classic/documents/readme.bytes";
|
||||
out[path] = binary(read_file(*source));
|
||||
supplemental.emplace_back(O{{"name", lower(name)}, {"path", path}});
|
||||
}
|
||||
}
|
||||
}
|
||||
put(out, "assets/classic/resources.json",
|
||||
O{{"schema", "classic-resources@1.0"},
|
||||
{"images", std::move(images)},
|
||||
{"fonts", std::move(fonts)},
|
||||
{"audio", std::move(audio)},
|
||||
{"optional", std::move(animations)},
|
||||
{"palettes", std::move(palettes)},
|
||||
{"supplemental", std::move(supplemental)}});
|
||||
put(out, "assets/index.json", O{{"schema", "asset-index@1.0"}, {"items", std::move(index)}});
|
||||
}
|
||||
|
||||
@@ -274,6 +309,27 @@ void load_assets(const Documents& out, ClassicData& data) {
|
||||
if (!openbmh::audio::parse_container(bank, parsed, error)) fail("invalid audio container: " + error);
|
||||
if (!data.audio.emplace(str(get(row, "name")), std::move(bank)).second) fail("duplicate audio bank");
|
||||
}
|
||||
if (resources.object()->contains("palettes"))
|
||||
for (const auto &row : arr(get(resources, "palettes"))) {
|
||||
const auto &colors = arr(get(row, "argb"));
|
||||
if (colors.size() != 256)
|
||||
fail("invalid embedded palette");
|
||||
Palette palette;
|
||||
for (size_t i = 0; i < 256; ++i) {
|
||||
const auto n = num(colors[i]);
|
||||
if (n < 0 || n > UINT32_MAX)
|
||||
fail("invalid color");
|
||||
palette.argb[i] = uint32_t(n);
|
||||
}
|
||||
if (!data.image_palettes.emplace(str(get(row, "name")), palette).second)
|
||||
fail("duplicate embedded palette");
|
||||
}
|
||||
if (resources.object()->contains("supplemental"))
|
||||
for (const auto &row : arr(get(resources, "supplemental"))) {
|
||||
if (!data.supplemental.emplace(str(get(row, "name")), bytes(out.at(str(get(row, "path")))))
|
||||
.second)
|
||||
fail("duplicate supplemental content");
|
||||
}
|
||||
if (!data.images.contains("kb/29") || data.fonts.size() != 2 || data.audio.size() != 4) fail("incomplete classic media");
|
||||
}
|
||||
} // namespace bmh::obw
|
||||
+108
-23
@@ -275,7 +275,7 @@ void refresh_classic_inventory(Documents& out) {
|
||||
using namespace detail;
|
||||
A inventory;
|
||||
for (const auto& [path, contents] : out)
|
||||
if (path != "x-classic/inventory.json")
|
||||
if (path != "x-classic/inventory.json" && path != "x-classic/seal.json")
|
||||
inventory.emplace_back(O{{"path", path}, {"bytes", int64_t(contents.size())}, {"crc32", int64_t(crc(contents))}});
|
||||
put(out, "x-classic/inventory.json", O{{"schema", "classic-inventory@1.0"}, {"entries", std::move(inventory)}});
|
||||
}
|
||||
@@ -286,52 +286,136 @@ static ClassicData decode_classic(const Documents& out) {
|
||||
if (str(get(startup, "schema")) != "classic-startup@1.0" || str(get(startup, "layout")) != layout_id)
|
||||
fail("unsupported classic startup/layout version");
|
||||
ClassicData data;
|
||||
const auto* en = get(startup, "english").boolean();
|
||||
if (!en) fail("invalid edition flag");
|
||||
const auto *en = get(startup, "english").boolean();
|
||||
if (!en)
|
||||
fail("invalid edition flag");
|
||||
data.english = *en;
|
||||
data.executable = load_regions(out, get(startup, "data_regions"), get(startup, "embedded_literals"), data.english);
|
||||
data.source_tables = load_regions(out, get(startup, "source_regions"), get(startup, "source_literals"), data.english);
|
||||
const auto database = parse(out, "x-legacy/source-database.json");
|
||||
data.database = decode_database(unhex(str(get(database, "bytes"))));
|
||||
data.executable =
|
||||
load_regions(out, get(startup, "data_regions"), get(startup, "embedded_literals"), data.english);
|
||||
data.source_tables =
|
||||
load_regions(out, get(startup, "source_regions"), get(startup, "source_literals"), data.english);
|
||||
// Reconstruct the native Classic database fields directly. The original M3D
|
||||
// byte stream is retained as import provenance only, never parsed at runtime.
|
||||
const auto database = parse(out, "x-legacy/database.json");
|
||||
const auto &counts = get(database, "counts");
|
||||
if (num(get(counts, "clubs")) != 419 || num(get(counts, "players")) != 2574 ||
|
||||
num(get(counts, "n42")) != 168 || num(get(counts, "n66")) != 3096)
|
||||
fail("unsupported Classic database dimensions");
|
||||
auto &db = data.database;
|
||||
const auto &pools = arr(get(database, "pools"));
|
||||
if (pools.size() != 4)
|
||||
fail("invalid native name pools");
|
||||
for (size_t i = 0; i < 4; ++i)
|
||||
db.pools[i] = unhex(str(pools[i]));
|
||||
const auto &tables = get(database, "tables");
|
||||
const auto table = [&](const char *name, Bytes &target, size_t expected) {
|
||||
target = unhex(str(get(tables, name)));
|
||||
if (target.size() != expected)
|
||||
fail(std::string("invalid Classic table size: ") + name);
|
||||
};
|
||||
table("player_bonus_values", db.raw_player_bonus_values, 3096 + 0x32);
|
||||
table("database_metadata", db.raw_database_metadata, 100);
|
||||
table("club_auxiliary_words", db.raw_club_auxiliary_words, 168 * 2);
|
||||
table("club_badge_selectors", db.raw_club_badge_selectors, 419 * 2);
|
||||
table("foreign_club_strength", db.raw_foreign_club_strength, 0xfb);
|
||||
table("league_auxiliary_bytes", db.raw_league_auxiliary_bytes, 0xbd);
|
||||
table("referee_properties", db.raw_referee_properties, 50);
|
||||
table("club_kit_selectors", db.raw_club_kit_selectors, 419);
|
||||
table("club_short_name_offsets", db.raw_club_short_name_offsets, 168);
|
||||
table("club_name_offsets", db.raw_club_name_offsets, 419 * 2);
|
||||
table("player_name_offsets", db.raw_player_name_offsets, 2574 * 2);
|
||||
table("squad_list", db.squad_list, (3096 - 4) * 2 + 0x6c);
|
||||
const auto name = [&](size_t pool, size_t offset) {
|
||||
const auto &bytes = db.pools[pool];
|
||||
if (offset >= bytes.size())
|
||||
fail("native name offset outside pool");
|
||||
const auto end = std::find(bytes.begin() + offset, bytes.end(), 0);
|
||||
if (end == bytes.end())
|
||||
fail("unterminated native name");
|
||||
return std::string(bytes.begin() + offset, end);
|
||||
};
|
||||
for (size_t i = 0; i < 419; ++i)
|
||||
db.club_names.push_back(name(0, le16(db.raw_club_name_offsets, i * 2)));
|
||||
db.players.resize(2574);
|
||||
std::set<size_t> player_ids;
|
||||
for (const auto &player : items(out, "players")) {
|
||||
const auto &raw = get(player, "x-legacy");
|
||||
const auto id = num(get(raw, "player_index"));
|
||||
if (id < 0 || id >= 2574 || !player_ids.insert(size_t(id)).second)
|
||||
fail("invalid native player identity");
|
||||
auto &value = db.players[size_t(id)];
|
||||
value.name = name(1, le16(db.raw_player_name_offsets, size_t(id) * 2));
|
||||
const auto word = [&](const char *key) {
|
||||
const auto n = num(get(raw, key));
|
||||
if (n < 0 || n > UINT32_MAX)
|
||||
fail("invalid native player word");
|
||||
return uint32_t(n);
|
||||
};
|
||||
value.w35c = word("condition_technique_form_word");
|
||||
value.w368 = word("skill_word");
|
||||
value.w364 = word("identity_word");
|
||||
}
|
||||
if (player_ids.size() != 2574)
|
||||
fail("incomplete native player records");
|
||||
const auto split = [&](size_t pool, std::vector<std::string> &values) {
|
||||
size_t at = 0;
|
||||
while (at < db.pools[pool].size()) {
|
||||
auto value = name(pool, at);
|
||||
at += value.size() + 1;
|
||||
values.push_back(std::move(value));
|
||||
}
|
||||
};
|
||||
split(2, db.referees);
|
||||
split(3, db.stadiums);
|
||||
data.desktops = bytes(out.at(str(get(startup, "desktop_seed"))));
|
||||
data.formations = bytes(out.at(str(get(startup, "formation_seed"))));
|
||||
if (data.desktops.size() != 864 || data.formations.size() != 1408) fail("invalid startup seed sizes");
|
||||
if (data.desktops.size() != 864 || data.formations.size() != 1408)
|
||||
fail("invalid startup seed sizes");
|
||||
data.texts.blob = bytes(out.at(str(get(startup, "text_blob"))));
|
||||
const auto& header = arr(get(startup, "text_header"));
|
||||
if (header.size() != 7) fail("invalid source text header");
|
||||
for (const auto& byte : header) {
|
||||
if (num(byte) < 0 || num(byte) > 255) fail("invalid source text header byte");
|
||||
const auto &header = arr(get(startup, "text_header"));
|
||||
if (header.size() != 7)
|
||||
fail("invalid source text header");
|
||||
for (const auto &byte : header) {
|
||||
if (num(byte) < 0 || num(byte) > 255)
|
||||
fail("invalid source text header byte");
|
||||
data.text_header.push_back(uint8_t(num(byte)));
|
||||
}
|
||||
size_t position = 0;
|
||||
while (data.texts.strings.size() < TEXT_COUNT && position < data.texts.blob.size()) {
|
||||
const auto begin = position;
|
||||
while (position < data.texts.blob.size() && data.texts.blob[position]) ++position;
|
||||
if (position == data.texts.blob.size()) fail("unterminated classic text");
|
||||
while (position < data.texts.blob.size() && data.texts.blob[position])
|
||||
++position;
|
||||
if (position == data.texts.blob.size())
|
||||
fail("unterminated classic text");
|
||||
data.texts.offsets.push_back(begin);
|
||||
data.texts.strings.emplace_back(data.texts.blob.begin() + begin, data.texts.blob.begin() + position);
|
||||
++position;
|
||||
}
|
||||
if (data.texts.strings.size() != TEXT_COUNT) fail("incomplete classic texts");
|
||||
if (data.texts.strings.size() != TEXT_COUNT)
|
||||
fail("incomplete classic texts");
|
||||
load_assets(out, data);
|
||||
return data;
|
||||
}
|
||||
|
||||
void validate_classic(const Documents& out) {
|
||||
void validate_classic(const Documents &out) {
|
||||
using namespace detail;
|
||||
const auto manifest = parse(out, "manifest.json");
|
||||
const auto& imported = get(manifest, "x-import");
|
||||
const auto &imported = get(manifest, "x-import");
|
||||
if (str(get(imported, "profile")) != profile || !get(imported, "content_complete").boolean() ||
|
||||
!*get(imported, "content_complete").boolean()) fail("incomplete classic profile");
|
||||
const auto& required_features = arr(get(manifest, "requires"));
|
||||
if (required_features.size() != 1 || str(required_features[0]) != feature) fail("missing classic runtime requirement");
|
||||
!*get(imported, "content_complete").boolean())
|
||||
fail("incomplete classic profile");
|
||||
const auto &required_features = arr(get(manifest, "requires"));
|
||||
if (required_features.size() != 1 || str(required_features[0]) != feature)
|
||||
fail("missing classic runtime requirement");
|
||||
const auto startup = parse(out, "x-classic/startup.json");
|
||||
const auto expected = str(get(manifest, "provenance")) == "import:fltd" ? "FLTD-classic" : "BMH-classic";
|
||||
if (str(get(manifest, "mod")) != expected || str(get(startup, "mod")) != expected) fail("mod/edition mismatch");
|
||||
if (str(get(manifest, "mod")) != expected || str(get(startup, "mod")) != expected)
|
||||
fail("mod/edition mismatch");
|
||||
if (str(get(imported, "rule_profile")) != "openbmh-supported@1" ||
|
||||
str(get(startup, "rule_profile")) != "openbmh-supported@1" ||
|
||||
cli::dump_json(get(startup, "initializers")) != cli::dump_json(initializers) ||
|
||||
cli::dump_json(get(startup, "runtime_inputs")) != cli::dump_json(runtime_inputs)) fail("unsupported classic initialization contract");
|
||||
cli::dump_json(get(startup, "runtime_inputs")) != cli::dump_json(runtime_inputs))
|
||||
fail("unsupported classic initialization contract");
|
||||
std::set<std::string> seen;
|
||||
const auto inventory = parse(out, "x-classic/inventory.json");
|
||||
for (const auto& entry : arr(get(inventory, "entries"))) {
|
||||
@@ -344,7 +428,8 @@ void validate_classic(const Documents& out) {
|
||||
for (char& ch : suffix) ch = char(std::tolower(static_cast<unsigned char>(ch)));
|
||||
if (suffix == ".exe" || suffix == ".fbm" || suffix == ".obs" || suffix == ".ein" || suffix == ".cfg") fail("non-content file in classic world");
|
||||
}
|
||||
if (seen.size() + 1 != out.size()) fail("unlisted archive entries");
|
||||
if (seen.size() + 1 + size_t(out.contains("x-classic/seal.json")) != out.size())
|
||||
fail("unlisted archive entries");
|
||||
auto data = decode_classic(out);
|
||||
if (data.english != (std::string(expected) == "FLTD-classic")) fail("startup edition mismatch");
|
||||
// Every fixture pointer must remain readable from the exported DATA view.
|
||||
|
||||
+2
-13
@@ -1,23 +1,12 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include "import/obw.hpp"
|
||||
#include "formats/font.hpp"
|
||||
#include "formats/content.hpp"
|
||||
#include "formats/palette.hpp"
|
||||
|
||||
namespace bmh::obw {
|
||||
// Installation content only. No manager choices, career RNG or save state.
|
||||
struct ClassicData {
|
||||
bool english = false;
|
||||
Database database;
|
||||
TextDb texts;
|
||||
LeImage executable; // DATA regions and four bounded literals; no instructions
|
||||
LeImage source_tables;
|
||||
Bytes desktops, formations, text_header;
|
||||
Palette palette;
|
||||
std::map<std::string, Image> images;
|
||||
std::map<std::string, Font> fonts;
|
||||
std::map<std::string, Bytes> audio;
|
||||
};
|
||||
using ClassicData = content::Classic;
|
||||
|
||||
void complete_classic(Documents& out, const std::filesystem::path& root,
|
||||
const Database& database, const LeImage& executable,
|
||||
|
||||
+11
-3
@@ -1,5 +1,6 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "import/obw.hpp"
|
||||
#include "content/package.hpp"
|
||||
#include "launch/archive.hpp"
|
||||
#include "version.hpp"
|
||||
|
||||
@@ -53,6 +54,8 @@ int main(int argc, char** argv) {
|
||||
if (!source.empty() || !destination.empty() || !options.start_date.empty() || !options.mod.empty() || directory || options.database_only)
|
||||
throw std::runtime_error("--validate cannot be combined with conversion options");
|
||||
const auto documents = bmh::obw::read(validate_path);
|
||||
if (documents.contains("x-classic/seal.json"))
|
||||
bmh::content::verify(documents);
|
||||
std::cout << "Valid OBW content: " << documents.size() << " entries; no engine runtime test implied.\n";
|
||||
return 0;
|
||||
}
|
||||
@@ -60,13 +63,18 @@ int main(int argc, char** argv) {
|
||||
throw std::runtime_error("--data, --output and --start-date are required; see --help");
|
||||
if (!directory && destination.extension() != ".obw")
|
||||
throw std::runtime_error("archive output must use the .obw extension");
|
||||
const auto documents = bmh::obw::import_installation(source, options);
|
||||
auto documents = bmh::obw::import_installation(source, options);
|
||||
if (!options.database_only)
|
||||
bmh::content::seal(documents);
|
||||
bmh::obw::write(documents, destination, directory);
|
||||
std::cout << "Converted " << documents.size() << " documents to "
|
||||
<< bmh::launch::path_to_utf8(destination) << "\n"
|
||||
<< "Profile: " << (options.database_only ? "legacy-database-v1 (partial)" : "classic-installation-v1 (complete Classic content)")
|
||||
<< "Profile: "
|
||||
<< (options.database_only ? "legacy-database-v1 (partial)"
|
||||
: "classic-installation-v1 (complete Classic content)")
|
||||
<< "; content_license: local-import-only.\n"
|
||||
<< "See manifest.json and x-legacy/import-report.json. 0.2 runtime integration is separate.\n";
|
||||
<< "See manifest.json and x-legacy/import-report.json. Classic packages can be added to "
|
||||
"the 0.2 portable mods directory.\n";
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << "openbmh_import: " << error.what() << '\n';
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "import/save.hpp"
|
||||
#include "formats/executable_layout.hpp"
|
||||
#include "game/career.hpp"
|
||||
#include <algorithm>
|
||||
#include <map>
|
||||
namespace bmh::obw {
|
||||
namespace {
|
||||
struct Record {
|
||||
int target;
|
||||
uint32_t native_address;
|
||||
size_t size;
|
||||
};
|
||||
} // namespace
|
||||
Bytes normalize_english_save(const Savegame &source, const DbCounts &counts) {
|
||||
if (source.version != "V2.20" || !source.checksum_ok)
|
||||
throw FormatError("Invalid Football Limited V2.20 save");
|
||||
const auto layout = save_layout(counts, true);
|
||||
const Record records[] = {
|
||||
{0, 0, 0}, // Cup_AdvanceCup_RuntimeField3
|
||||
{1, 0, 0}, // LiveMatchday_FormatError_RuntimeField14
|
||||
{2, 0, 0}, // ManagerRecords
|
||||
{3, 0, 0}, // Loans
|
||||
{4, 0, 0}, // ManagerMatchHistory
|
||||
{6, 0, 0}, // ManagerAutomation
|
||||
{7, 0, 0}, // Desktops
|
||||
{8, 0, 0}, // CareerSession_DispatchToto_RuntimeField
|
||||
{10, 0, 0}, // CalendarState_FormatError_RuntimeField3
|
||||
{11, 0, 0}, // ActiveManager
|
||||
{12, 0, 0}, // CareerSession_RuntimeError_RuntimeField4
|
||||
{13, 0, 0}, // LeaguePresentationOptions
|
||||
{14, 0, 0}, // FriendlyTeams
|
||||
{15, 0, 0}, // FriendlyDays
|
||||
{16, 0, 0}, // Cup_AdvanceCup_ExecutableField
|
||||
{17, 0, 0}, // MatchdaySetup_IndoorTournamentDraw_RuntimeField
|
||||
{18, 0, 0}, // Placements
|
||||
{19, 0, 0}, // ActiveSelectors
|
||||
{20, 0, 0}, // Career_CareerAddManager_RuntimeField2
|
||||
{21, 0, 0}, // DeskActions_SubmitPoolsCoupon_RuntimeField
|
||||
{22, 0, 0}, // NextDeskManager
|
||||
{23, 0, 0}, // Savestate_Layout_ExecutableField8
|
||||
{24, 0, 0}, // DeskPosition
|
||||
{25, 0, 0}, // DeskRecords_Teams_RuntimeField
|
||||
{26, 0, 0}, // CareerSession_FormatError_RuntimeField7
|
||||
{27, 0, 0}, // Cup_AdvanceCup_RuntimeField6
|
||||
{28, 0, 0}, // CurrentMatchday
|
||||
{29, 0, 0}, // ClubPlayerDetail_InvalidArgument_RuntimeField3
|
||||
{30, 0, 0}, // CoachActive
|
||||
{31, 0, 0}, // OriginalManagerCount
|
||||
{32, 0, 0}, // CareerSession_Invalid_RuntimeField2
|
||||
{33, 0, 0}, // CareerDuration
|
||||
{34, 0, 0}, // GameMode
|
||||
{35, 0, 0}, // CompetitionSelection
|
||||
{36, 0, 0}, // ManagerCount
|
||||
{37, 0, 0}, // SavedCompetition
|
||||
{38, 0, 0}, // Difficulty
|
||||
{39, 0, 0}, // StockExchange
|
||||
{40, 0, 0}, // FundBlock
|
||||
{41, 0, 0}, // Coupon
|
||||
{42, 0, 0}, // Savestate_Layout_ExecutableField2
|
||||
{43, 0, 0}, // Savestate_Layout_ExecutableField
|
||||
{44, 0, 0}, // AdGroupId
|
||||
{45, 0, 0}, // OfferSlots
|
||||
{46, 0, 0}, // ForeignClubStrength
|
||||
{47, 0, 0}, // Career_Put_ExecutableField3
|
||||
{48, 0, 0}, // ClubShortNameOffsets
|
||||
{49, 0, 0}, // ClubKitSelectors
|
||||
{50, 0, 0}, // Savestate_Layout_ExecutableField7
|
||||
{51, 0, 0}, // ClubInfo_FormatError_RuntimeField
|
||||
{52, 0, 0}, // Career_CareerManagersEnd_RuntimeField
|
||||
{53, 0, 0}, // ClubInfo_FormatError_RuntimeField2
|
||||
{54, 0, 0}, // DeskActions_Unsupported_RuntimeField
|
||||
{55, 0, 0}, // Career_RemoveJoinLoans_RuntimeField
|
||||
{56, 0, 0}, // ClubPlayerDetail_InvalidArgument_RuntimeField
|
||||
{57, 0, 0}, // ManagerRatings
|
||||
{58, 0, 0}, // DaysIntoSeason
|
||||
{-1, ::bmh::layout::EnglishFaCupResults, 0x86}, // fa_results
|
||||
{-1, ::bmh::layout::EnglishLeagueCupFirstRoundResults, 0x56}, // league_results
|
||||
{-1, ::bmh::layout::EnglishLeagueCupQuarterFinalOtherLegResults, 0x3c}, // league_return
|
||||
{-1, ::bmh::layout::EnglishLeagueCupField, 0xa4}, // league_field
|
||||
{-1, ::bmh::layout::EnglishFaCupField, 0x134}, // fa_field
|
||||
{61, 0, 0}, // CalendarDay
|
||||
{62, 0, 0}, // SeasonIndex
|
||||
{63, 0, 0}, // Savestate_Layout_ExecutableField5
|
||||
{64, 0, 0}, // CompetitionCalendar
|
||||
{65, 0, 0}, // Postponed
|
||||
{66, 0, 0}, // LeagueTableDisplayModes
|
||||
{67, 0, 0}, // CareerSession_FormatError_ExecutableField
|
||||
{68, 0, 0}, // ManagerSettings
|
||||
{69, 0, 0}, // CareerSession_DispatchOtherGames_RuntimeField
|
||||
{70, 0, 0}, // CareerSession_AnyOf_ExecutableField
|
||||
{71, 0, 0}, // Career_NewCareerMarketsAndMoods_RuntimeField2
|
||||
{72, 0, 0}, // ManagerMailbox
|
||||
{73, 0, 0}, // CareerSession_CloseLeagueFamily_ExecutableField
|
||||
{74, 0, 0}, // Savestate_Layout_ExecutableField3
|
||||
{75, 0, 0}, // Flags
|
||||
{76, 0, 0}, // Formations
|
||||
{77, 0, 0}, // PlayerDevelopmentBalance
|
||||
{78, 0, 0}, // PlayerBonuses
|
||||
{79, 0, 0}, // EditorList
|
||||
{80, 0, 0}, // Field0
|
||||
{81, 0, 0}, // Career_CompetitionPointersEnglish_RuntimeField13
|
||||
{82, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField25
|
||||
{83, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField22
|
||||
{84, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField23
|
||||
{85, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField19
|
||||
{86, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField26
|
||||
{87, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField21
|
||||
{88, 0, 0}, // Career_CompetitionPointersEnglish_RuntimeField14
|
||||
{89, 0, 0}, // Career_CompetitionPointersEnglish_RuntimeField17
|
||||
{90, 0, 0}, // Savestate_Layout_ExecutableField4
|
||||
{91, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField28
|
||||
{92, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField31
|
||||
{93, 0, 0}, // Teams
|
||||
{94, 0, 0}, // MatchdayGroupWorkspace
|
||||
{95, 0, 0}, // Savestate_Layout_ExecutableField6
|
||||
{96, 0, 0}, // EventPasses
|
||||
{97, 0, 0}, // LeagueResults
|
||||
{98, 0, 0}, // LeagueRoundCounters
|
||||
{99, 0, 0}, // TeamMorale
|
||||
{100, 0, 0}, // ClubBadgeSelectors
|
||||
{101, 0, 0}, // TeamFlags
|
||||
{102, 0, 0}, // ClubIdentities
|
||||
{103, 0, 0}, // PlayerNameOffsets
|
||||
{104, 0, 0}, // MasterDatabaseMetadata
|
||||
{105, 0, 0}, // ClubAuxiliaryWords
|
||||
{106, 0, 0}, // LeagueRankHistory
|
||||
{107, 0, 0}, // Titles
|
||||
{108, 0, 0}, // Cup_AdvanceCup_RuntimeField6
|
||||
{109, 0, 0}, // ClubAuxiliaryBytes
|
||||
{110, 0, 0}, // CupTable
|
||||
{111, 0, 0}, // SquadSlots
|
||||
{112, 0, 0}, // PlayerConditionTechniqueForm
|
||||
{113, 0, 0}, // PlayerCards
|
||||
{114, 0, 0}, // PlayerSkillWords
|
||||
{115, 0, 0}, // PlayerIdentityWords
|
||||
{116, 0, 0}, // TacticsBoards
|
||||
{117, 0, 0}, // TournamentName
|
||||
{118, 0, 0}, // Career_EuropeanClub_ExecutableField
|
||||
{119, 0, 0}, // Career_EuropeanClub_ExecutableField2
|
||||
{120, 0, 0}, // Career_EuropeanClub_ExecutableField3
|
||||
{121, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField24
|
||||
{122, 0, 0}, // Career_CompetitionPointersEnglish_ExecutableField29
|
||||
{123, 0, 0}, // ClubSeasonRecords
|
||||
{124, 0, 0}, // ClubSeasonRecords
|
||||
};
|
||||
std::map<int, Bytes> decoded;
|
||||
std::map<uint32_t, Bytes> native;
|
||||
for (const auto &[address, size] : kEnglishCompetitionBlocks)
|
||||
native[address] = Bytes(size, 0);
|
||||
size_t offset = 0;
|
||||
bool club_records = false;
|
||||
for (const auto &record : records) {
|
||||
if (record.target == 124 && !club_records)
|
||||
continue;
|
||||
const size_t size = record.target < 0 ? record.size : layout.at(size_t(record.target)).size;
|
||||
if (offset + size > source.stream.size())
|
||||
throw FormatError("V2.20 state is truncated");
|
||||
Bytes bytes(source.stream.begin() + offset, source.stream.begin() + offset + size);
|
||||
offset += size;
|
||||
if (record.target == 123) {
|
||||
if (size != 4)
|
||||
throw FormatError("Invalid club record pointer");
|
||||
club_records = le32(bytes, 0) != 0;
|
||||
}
|
||||
if (record.target >= 0)
|
||||
decoded[record.target] = bytes;
|
||||
uint32_t target = record.native_address;
|
||||
if (record.target == 93)
|
||||
target = ::bmh::layout::EnglishAdditionalCupField;
|
||||
if (record.target == 94)
|
||||
target = ::bmh::layout::EnglishAdditionalCupResults;
|
||||
if (target)
|
||||
for (auto &[at, block] : native)
|
||||
if (target >= at && uint64_t(target) + bytes.size() <= uint64_t(at) + block.size())
|
||||
std::copy(bytes.begin(), bytes.end(), block.begin() + (target - at));
|
||||
}
|
||||
Bytes normalized;
|
||||
for (size_t i = 0; i < layout.size(); ++i) {
|
||||
if (i == 124 && !club_records)
|
||||
continue;
|
||||
if (const auto it = decoded.find(int(i)); it != decoded.end())
|
||||
normalized.insert(normalized.end(), it->second.begin(), it->second.end());
|
||||
else
|
||||
normalized.insert(normalized.end(), layout[i].size, 0);
|
||||
}
|
||||
// Four length-prefixed name pools, shared by both original editions.
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
if (offset + 2 > source.stream.size())
|
||||
throw FormatError("V2.20 name pool missing");
|
||||
const size_t size = le16(source.stream, offset) + 2;
|
||||
if (offset + size > source.stream.size())
|
||||
throw FormatError("V2.20 name pool is truncated");
|
||||
normalized.insert(normalized.end(), source.stream.begin() + offset,
|
||||
source.stream.begin() + offset + size);
|
||||
offset += size;
|
||||
}
|
||||
if (offset != source.stream.size())
|
||||
throw FormatError("V2.20 state has unexpected trailing bytes");
|
||||
std::vector<SaveState::ExtensionBlock> extension;
|
||||
for (auto &[at, bytes] : native)
|
||||
extension.push_back({at, std::move(bytes)});
|
||||
append_save_extension(normalized, extension);
|
||||
(void)SaveState(normalized, counts);
|
||||
return normalized;
|
||||
}
|
||||
} // namespace bmh::obw
|
||||
@@ -0,0 +1,9 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include "formats/fbm.hpp"
|
||||
#include "formats/savestate.hpp"
|
||||
namespace bmh::obw {
|
||||
// Translate the V2.20 state-block contract, including its native cup regions,
|
||||
// to the existing in-memory Classic layout. No executable or FBM file is emitted.
|
||||
Bytes normalize_english_save(const Savegame &, const DbCounts &counts = {});
|
||||
} // namespace bmh::obw
|
||||
@@ -0,0 +1,90 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "launch/launcher.hpp"
|
||||
#include "launch/launcher_ui.hpp"
|
||||
#include "launch/process.hpp"
|
||||
#include "launch/game_data.hpp"
|
||||
#include "launch/archive.hpp"
|
||||
#include <atomic>
|
||||
#include <future>
|
||||
#include <mutex>
|
||||
namespace bmh::launch {
|
||||
int run_launcher(const std::filesystem::path &executable, const SaveMigrator &migrate) {
|
||||
auto ui = make_launcher_ui();
|
||||
ModLibrary library(executable.parent_path());
|
||||
for (;;)
|
||||
try {
|
||||
const auto mods = library.list();
|
||||
const auto action = ui->next(mods);
|
||||
if (action.action == LauncherAction::end)
|
||||
return 0;
|
||||
if (action.action == LauncherAction::add) {
|
||||
const auto source = ui->choose_folder("BMH-/Football-Limited-Installation wählen");
|
||||
if (!source)
|
||||
continue;
|
||||
const auto check = check_game_directory(*source);
|
||||
if (!check.playable)
|
||||
throw FormatError("Installation wird nicht unterstützt: " + check.unsupported);
|
||||
AddMod initial;
|
||||
initial.source = check.directory;
|
||||
initial.saves = check.directory;
|
||||
initial.name = check.family == GameFamily::english ? "FTDL-classic" : "BMH-classic";
|
||||
const auto request = ui->configure_add(initial);
|
||||
if (!request)
|
||||
continue;
|
||||
std::mutex mutex;
|
||||
std::string text = "Import wird vorbereitet …";
|
||||
std::atomic_bool cancelled = false;
|
||||
ui->progress(text, true);
|
||||
auto job = std::async(std::launch::async, [&] {
|
||||
return library.add(*request, migrate, [&](const std::string &s) {
|
||||
if (cancelled.load())
|
||||
throw FormatError("Import abgebrochen");
|
||||
std::lock_guard lock(mutex);
|
||||
text = s;
|
||||
});
|
||||
});
|
||||
while (job.wait_for(std::chrono::milliseconds(20)) != std::future_status::ready) {
|
||||
if (ui->pump())
|
||||
cancelled = true;
|
||||
std::lock_guard lock(mutex);
|
||||
ui->progress(text, true);
|
||||
}
|
||||
ui->finish_progress();
|
||||
const auto report = job.get();
|
||||
std::string summary =
|
||||
"Mod importiert: " + report.mod.name +
|
||||
"\nÜbernommene Spielstände/Einstellungen: " + std::to_string(report.migrated);
|
||||
for (const auto &error : report.errors)
|
||||
summary += "\n" + error;
|
||||
ui->message(summary, false);
|
||||
continue;
|
||||
}
|
||||
if (action.selection < 0 || size_t(action.selection) >= mods.size())
|
||||
continue;
|
||||
const auto &mod = mods[size_t(action.selection)];
|
||||
if (action.action == LauncherAction::remove) {
|
||||
if (ui->confirm_delete(mod.name))
|
||||
library.remove(mod);
|
||||
} else if (action.action == LauncherAction::rename) {
|
||||
if (const auto name = ui->rename(mod.name))
|
||||
library.rename(mod, *name);
|
||||
} else if (action.action == LauncherAction::start) {
|
||||
if (!mod.error.empty())
|
||||
throw FormatError(mod.error);
|
||||
(void)content::open(mod.directory / "content.obw");
|
||||
const auto userdata = library.user_directory(mod);
|
||||
ui->progress("Spiel läuft: " + mod.name, false);
|
||||
const int code = run_child(executable,
|
||||
{"--run-mod", path_to_utf8(mod.directory / "content.obw"),
|
||||
"--save-directory", path_to_utf8(userdata)},
|
||||
[&] { ui->pump(); });
|
||||
ui->finish_progress();
|
||||
if (code)
|
||||
ui->message("Das Spiel wurde mit Fehlercode " + std::to_string(code) + " beendet.", true);
|
||||
}
|
||||
} catch (const std::exception &e) {
|
||||
ui->finish_progress();
|
||||
ui->message(e.what(), true);
|
||||
}
|
||||
}
|
||||
} // namespace bmh::launch
|
||||
@@ -0,0 +1,6 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include "launch/mods.hpp"
|
||||
namespace bmh::launch {
|
||||
int run_launcher(const std::filesystem::path &executable, const SaveMigrator &);
|
||||
} // namespace bmh::launch
|
||||
@@ -0,0 +1,300 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#import <AppKit/AppKit.h>
|
||||
#include "launch/launcher_ui.hpp"
|
||||
#include "launch/archive.hpp"
|
||||
#include <functional>
|
||||
|
||||
@interface OBMLauncherBridge : NSObject <NSTableViewDataSource, NSTableViewDelegate, NSWindowDelegate> {
|
||||
@public
|
||||
std::function<void(NSInteger)> action;
|
||||
std::function<void()> selection;
|
||||
}
|
||||
@property(strong) NSArray<NSDictionary *> *rows;
|
||||
- (void)activate:(id)sender;
|
||||
@end
|
||||
@implementation OBMLauncherBridge
|
||||
- (NSInteger)numberOfRowsInTableView:(NSTableView *)table {
|
||||
(void)table;
|
||||
return self.rows.count;
|
||||
}
|
||||
- (id)tableView:(NSTableView *)table objectValueForTableColumn:(NSTableColumn *)column row:(NSInteger)row {
|
||||
(void)table;
|
||||
return self.rows[row][column.identifier];
|
||||
}
|
||||
- (void)tableViewSelectionDidChange:(NSNotification *)note {
|
||||
(void)note;
|
||||
if (selection)
|
||||
selection();
|
||||
}
|
||||
- (void)activate:(id)sender {
|
||||
if (action)
|
||||
action([sender tag]);
|
||||
}
|
||||
- (BOOL)windowShouldClose:(NSWindow *)window {
|
||||
(void)window;
|
||||
if (action)
|
||||
action(0);
|
||||
return NO;
|
||||
}
|
||||
@end
|
||||
|
||||
namespace bmh::launch {
|
||||
namespace {
|
||||
NSString *string(const std::string &s) {
|
||||
auto value = [[NSString alloc] initWithBytes:s.data() length:s.size() encoding:NSUTF8StringEncoding];
|
||||
if (!value)
|
||||
throw std::runtime_error("Invalid UTF-8 launcher text");
|
||||
return value;
|
||||
}
|
||||
std::string utf8(NSString *s) { return std::string(s.UTF8String ?: ""); }
|
||||
NSTextField *label(NSString *text, NSRect frame) {
|
||||
auto *field = [NSTextField labelWithString:text];
|
||||
field.frame = frame;
|
||||
return field;
|
||||
}
|
||||
NSTextField *input(NSString *text, NSRect frame) {
|
||||
auto *field = [[NSTextField alloc] initWithFrame:frame];
|
||||
field.stringValue = text;
|
||||
return field;
|
||||
}
|
||||
class CocoaLauncher final : public LauncherUI {
|
||||
NSWindow *window_;
|
||||
NSTableView *table_;
|
||||
OBMLauncherBridge *bridge_;
|
||||
NSMutableArray<NSButton *> *buttons_;
|
||||
NSWindow *progress_ = nil;
|
||||
NSTextField *progress_label_ = nil;
|
||||
OBMLauncherBridge *progress_bridge_ = nil;
|
||||
bool cancelled_ = false;
|
||||
|
||||
public:
|
||||
CocoaLauncher() {
|
||||
[NSApplication sharedApplication];
|
||||
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
|
||||
[NSApp finishLaunching];
|
||||
window_ = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 660, 340)
|
||||
styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
|
||||
NSWindowStyleMaskMiniaturizable
|
||||
backing:NSBackingStoreBuffered
|
||||
defer:NO];
|
||||
window_.title = @"OpenBMH";
|
||||
[window_ center];
|
||||
window_.releasedWhenClosed = NO;
|
||||
bridge_ = [OBMLauncherBridge new];
|
||||
bridge_.rows = @[];
|
||||
window_.delegate = bridge_;
|
||||
auto *scroll = [[NSScrollView alloc] initWithFrame:NSMakeRect(16, 16, 490, 308)];
|
||||
scroll.hasVerticalScroller = YES;
|
||||
scroll.borderType = NSBezelBorder;
|
||||
table_ = [[NSTableView alloc] initWithFrame:scroll.bounds];
|
||||
table_.allowsMultipleSelection = NO;
|
||||
table_.dataSource = bridge_;
|
||||
table_.delegate = bridge_;
|
||||
for (NSString *identifier in @[ @"Name", @"Art" ]) {
|
||||
auto *column = [[NSTableColumn alloc] initWithIdentifier:identifier];
|
||||
column.title = identifier;
|
||||
column.width = [identifier isEqualToString:@"Name"] ? 350 : 110;
|
||||
[table_ addTableColumn:column];
|
||||
}
|
||||
table_.target = bridge_;
|
||||
table_.doubleAction = @selector(activate:);
|
||||
table_.tag = 1;
|
||||
scroll.documentView = table_;
|
||||
[window_.contentView addSubview:scroll];
|
||||
buttons_ = [NSMutableArray new];
|
||||
NSArray *titles = @[ @"Start", @"Add", @"Delete", @"Rename", @"End" ];
|
||||
for (NSInteger i = 0; i < 5; ++i) {
|
||||
auto *button = [NSButton buttonWithTitle:titles[i] target:bridge_ action:@selector(activate:)];
|
||||
button.tag = i + 1;
|
||||
button.frame = NSMakeRect(522, 282 - i * 50, 120, 34);
|
||||
[window_.contentView addSubview:button];
|
||||
[buttons_ addObject:button];
|
||||
}
|
||||
bridge_->action = [this](NSInteger code) {
|
||||
if ((code == 1 || code == 3 || code == 4) && table_.selectedRow < 0)
|
||||
return;
|
||||
[NSApp stopModalWithCode:code];
|
||||
};
|
||||
bridge_->selection = [this] {
|
||||
for (NSInteger i : {0, 2, 3})
|
||||
buttons_[i].enabled = table_.selectedRow >= 0;
|
||||
};
|
||||
bridge_->selection();
|
||||
[window_ makeKeyAndOrderFront:nil];
|
||||
[NSApp activateIgnoringOtherApps:YES];
|
||||
}
|
||||
~CocoaLauncher() override {
|
||||
bridge_->action = {};
|
||||
bridge_->selection = {};
|
||||
finish_progress();
|
||||
window_.delegate = nil;
|
||||
[window_ orderOut:nil];
|
||||
[window_ close];
|
||||
}
|
||||
LauncherChoice next(const std::vector<ModEntry> &mods) override {
|
||||
const NSInteger old = table_.selectedRow;
|
||||
auto *rows = [NSMutableArray new];
|
||||
for (const auto &mod : mods)
|
||||
[rows addObject:@{
|
||||
@"Name" : string(mod.name + (mod.error.empty() ? "" : " ⚠")),
|
||||
@"Art" : string(mod.type)
|
||||
}];
|
||||
bridge_.rows = rows;
|
||||
[table_ reloadData];
|
||||
if (old >= 0 && size_t(old) < mods.size())
|
||||
[table_ selectRowIndexes:[NSIndexSet indexSetWithIndex:old] byExtendingSelection:NO];
|
||||
bridge_->selection();
|
||||
[window_ makeKeyAndOrderFront:nil];
|
||||
const NSInteger response = [NSApp runModalForWindow:window_];
|
||||
return {response == 1 ? LauncherAction::start
|
||||
: response == 2 ? LauncherAction::add
|
||||
: response == 3 ? LauncherAction::remove
|
||||
: response == 4 ? LauncherAction::rename
|
||||
: LauncherAction::end,
|
||||
int(table_.selectedRow)};
|
||||
}
|
||||
std::optional<std::filesystem::path> choose_folder(const std::string &title,
|
||||
const std::filesystem::path &initial) override {
|
||||
auto *panel = [NSOpenPanel openPanel];
|
||||
panel.title = string(title);
|
||||
panel.canChooseFiles = NO;
|
||||
panel.canChooseDirectories = YES;
|
||||
panel.allowsMultipleSelection = NO;
|
||||
if (!initial.empty())
|
||||
panel.directoryURL = [NSURL fileURLWithPath:string(path_to_utf8(initial)) isDirectory:YES];
|
||||
if ([panel runModal] != NSModalResponseOK)
|
||||
return {};
|
||||
return path_from_utf8(utf8(panel.URL.path));
|
||||
}
|
||||
std::optional<AddMod> configure_add(AddMod initial) override {
|
||||
auto *alert = [NSAlert new];
|
||||
alert.messageText = @"Classic-Mod hinzufügen";
|
||||
[alert addButtonWithTitle:@"Importieren"];
|
||||
[alert addButtonWithTitle:@"Abbrechen"];
|
||||
auto *view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 540, 180)];
|
||||
[view addSubview:label(@"Bezeichnung", NSMakeRect(0, 146, 160, 24))];
|
||||
auto *name = input(string(initial.name), NSMakeRect(170, 146, 370, 24));
|
||||
[view addSubview:name];
|
||||
[view addSubview:label(@"Startjahr (nur Anzeige)", NSMakeRect(0, 106, 165, 24))];
|
||||
auto *year = input(string(std::to_string(initial.start_year)), NSMakeRect(170, 106, 110, 24));
|
||||
[view addSubview:year];
|
||||
auto *migrate = [NSButton checkboxWithTitle:@"Spielstände/Einstellungen übernehmen"
|
||||
target:nil
|
||||
action:nil];
|
||||
migrate.frame = NSMakeRect(0, 68, 540, 24);
|
||||
migrate.state = initial.migrate ? NSControlStateValueOn : NSControlStateValueOff;
|
||||
[view addSubview:migrate];
|
||||
[view addSubview:label(@"Spielstandsordner", NSMakeRect(0, 25, 160, 24))];
|
||||
auto *saves = input(string(path_to_utf8(initial.saves)), NSMakeRect(170, 25, 245, 24));
|
||||
[view addSubview:saves];
|
||||
auto *browse_bridge = [OBMLauncherBridge new];
|
||||
browse_bridge->action = [this, saves](NSInteger) {
|
||||
if (auto p = choose_folder("Spielstandsordner wählen", path_from_utf8(utf8(saves.stringValue))))
|
||||
saves.stringValue = string(path_to_utf8(*p));
|
||||
};
|
||||
auto *browse = [NSButton buttonWithTitle:@"Auswählen …"
|
||||
target:browse_bridge
|
||||
action:@selector(activate:)];
|
||||
browse.frame = NSMakeRect(420, 22, 120, 30);
|
||||
[view addSubview:browse];
|
||||
alert.accessoryView = view;
|
||||
while ([alert runModal] == NSAlertFirstButtonReturn)
|
||||
try {
|
||||
initial.name = utf8(name.stringValue);
|
||||
ModLibrary::validate_name(initial.name);
|
||||
const auto value = utf8(year.stringValue);
|
||||
size_t end = 0;
|
||||
initial.start_year = std::stoi(value, &end);
|
||||
if (end != value.size() || initial.start_year < 1900 || initial.start_year > 9998)
|
||||
throw std::runtime_error("Startjahr muss zwischen 1900 und 9998 liegen");
|
||||
initial.saves = path_from_utf8(utf8(saves.stringValue));
|
||||
initial.migrate = migrate.state == NSControlStateValueOn;
|
||||
return initial;
|
||||
} catch (const std::exception &e) {
|
||||
message(e.what(), true);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
std::optional<std::string> rename(const std::string &old) override {
|
||||
auto *alert = [NSAlert new];
|
||||
alert.messageText = @"Mod umbenennen";
|
||||
[alert addButtonWithTitle:@"Umbenennen"];
|
||||
[alert addButtonWithTitle:@"Abbrechen"];
|
||||
auto *field = input(string(old), NSMakeRect(0, 0, 380, 26));
|
||||
alert.accessoryView = field;
|
||||
if ([alert runModal] != NSAlertFirstButtonReturn)
|
||||
return {};
|
||||
return utf8(field.stringValue);
|
||||
}
|
||||
bool confirm_delete(const std::string &name) override {
|
||||
auto *alert = [NSAlert new];
|
||||
alert.messageText = string("Mod „" + name + "“ löschen?");
|
||||
alert.informativeText = @"Spielstände und persönliche Einstellungen bleiben erhalten.";
|
||||
[alert addButtonWithTitle:@"Abbrechen"];
|
||||
[alert addButtonWithTitle:@"Löschen"];
|
||||
return [alert runModal] == NSAlertSecondButtonReturn;
|
||||
}
|
||||
void message(const std::string &value, bool error) override {
|
||||
auto *alert = [NSAlert new];
|
||||
alert.messageText = @"OpenBMH";
|
||||
alert.informativeText = string(value);
|
||||
alert.alertStyle = error ? NSAlertStyleWarning : NSAlertStyleInformational;
|
||||
[alert runModal];
|
||||
}
|
||||
void progress(const std::string &value, bool cancellable) override {
|
||||
if (!progress_) {
|
||||
cancelled_ = false;
|
||||
for (NSButton *b in buttons_)
|
||||
b.enabled = NO;
|
||||
progress_ = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 580, 125)
|
||||
styleMask:NSWindowStyleMaskTitled
|
||||
backing:NSBackingStoreBuffered
|
||||
defer:NO];
|
||||
progress_.title = @"OpenBMH";
|
||||
progress_.releasedWhenClosed = NO;
|
||||
progress_label_ = label(string(value), NSMakeRect(16, 65, 548, 40));
|
||||
[progress_.contentView addSubview:progress_label_];
|
||||
progress_bridge_ = [OBMLauncherBridge new];
|
||||
progress_bridge_->action = [this](NSInteger) { cancelled_ = true; };
|
||||
progress_.delegate = progress_bridge_;
|
||||
if (cancellable) {
|
||||
auto *button = [NSButton buttonWithTitle:@"Abbrechen"
|
||||
target:progress_bridge_
|
||||
action:@selector(activate:)];
|
||||
button.frame = NSMakeRect(440, 15, 120, 30);
|
||||
[progress_.contentView addSubview:button];
|
||||
}
|
||||
[window_ beginSheet:progress_ completionHandler:nil];
|
||||
}
|
||||
progress_label_.stringValue = string(value);
|
||||
}
|
||||
bool pump() override {
|
||||
@autoreleasepool {
|
||||
NSEvent *event;
|
||||
while ((event = [NSApp nextEventMatchingMask:NSEventMaskAny
|
||||
untilDate:[NSDate distantPast]
|
||||
inMode:NSDefaultRunLoopMode
|
||||
dequeue:YES]))
|
||||
[NSApp sendEvent:event];
|
||||
[NSApp updateWindows];
|
||||
}
|
||||
return cancelled_;
|
||||
}
|
||||
void finish_progress() override {
|
||||
if (progress_) {
|
||||
progress_bridge_->action = {};
|
||||
[window_ endSheet:progress_];
|
||||
[progress_ orderOut:nil];
|
||||
[progress_ close];
|
||||
progress_ = nil;
|
||||
progress_label_ = nil;
|
||||
progress_bridge_ = nil;
|
||||
for (NSButton *b in buttons_)
|
||||
b.enabled = YES;
|
||||
bridge_->selection();
|
||||
}
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
std::unique_ptr<LauncherUI> make_launcher_ui() { return std::make_unique<CocoaLauncher>(); }
|
||||
} // namespace bmh::launch
|
||||
@@ -0,0 +1,269 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "launch/launcher_ui.hpp"
|
||||
#include "launch/archive.hpp"
|
||||
#include <gtk/gtk.h>
|
||||
#include <array>
|
||||
namespace bmh::launch {
|
||||
namespace {
|
||||
class GtkLauncher final : public LauncherUI {
|
||||
GtkWidget *window_ = nullptr, *tree_ = nullptr, *progress_ = nullptr, *progress_label_ = nullptr;
|
||||
GtkListStore *model_ = nullptr;
|
||||
std::array<GtkWidget *, 5> buttons_{};
|
||||
bool cancelled_ = false;
|
||||
std::string selection_;
|
||||
enum { Start = 1, Add, Delete, Rename, End };
|
||||
static void selection_changed(GtkTreeSelection *selection, gpointer data) {
|
||||
auto &self = *static_cast<GtkLauncher *>(data);
|
||||
GtkTreeIter it;
|
||||
GtkTreeModel *model;
|
||||
const bool selected = gtk_tree_selection_get_selected(selection, &model, &it);
|
||||
for (int id : {Start, Delete, Rename})
|
||||
gtk_widget_set_sensitive(self.buttons_[size_t(id - 1)], selected);
|
||||
}
|
||||
GtkWidget *entry(GtkWidget *grid, int row, const char *label, const std::string &initial) {
|
||||
auto *title = gtk_label_new(label);
|
||||
gtk_widget_set_halign(title, GTK_ALIGN_START);
|
||||
gtk_grid_attach(GTK_GRID(grid), title, 0, row, 1, 1);
|
||||
auto *input = gtk_entry_new();
|
||||
gtk_entry_set_text(GTK_ENTRY(input), initial.c_str());
|
||||
gtk_widget_set_hexpand(input, TRUE);
|
||||
gtk_grid_attach(GTK_GRID(grid), input, 1, row, 1, 1);
|
||||
return input;
|
||||
}
|
||||
|
||||
public:
|
||||
GtkLauncher() {
|
||||
if (!gtk_init_check(nullptr, nullptr))
|
||||
throw std::runtime_error("Kein Desktop für den nativen Launcher verfügbar");
|
||||
window_ = gtk_dialog_new();
|
||||
gtk_window_set_title(GTK_WINDOW(window_), "OpenBMH");
|
||||
gtk_window_set_default_size(GTK_WINDOW(window_), 620, 340);
|
||||
auto *body = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 16);
|
||||
gtk_container_set_border_width(GTK_CONTAINER(body), 16);
|
||||
gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(window_))), body, TRUE, TRUE, 0);
|
||||
model_ = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING);
|
||||
tree_ = gtk_tree_view_new_with_model(GTK_TREE_MODEL(model_));
|
||||
auto *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree_));
|
||||
gtk_tree_selection_set_mode(selection, GTK_SELECTION_SINGLE);
|
||||
g_signal_connect(selection, "changed", G_CALLBACK(selection_changed), this);
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
auto *renderer = gtk_cell_renderer_text_new();
|
||||
auto *column =
|
||||
gtk_tree_view_column_new_with_attributes(i ? "Art" : "Name", renderer, "text", i, nullptr);
|
||||
gtk_tree_view_column_set_expand(column, i == 0);
|
||||
gtk_tree_view_append_column(GTK_TREE_VIEW(tree_), column);
|
||||
}
|
||||
gtk_tree_view_set_tooltip_column(GTK_TREE_VIEW(tree_), 2);
|
||||
auto *scroller = gtk_scrolled_window_new(nullptr, nullptr);
|
||||
gtk_widget_set_hexpand(scroller, TRUE);
|
||||
gtk_widget_set_vexpand(scroller, TRUE);
|
||||
gtk_container_add(GTK_CONTAINER(scroller), tree_);
|
||||
gtk_box_pack_start(GTK_BOX(body), scroller, TRUE, TRUE, 0);
|
||||
auto *buttons = gtk_box_new(GTK_ORIENTATION_VERTICAL, 8);
|
||||
gtk_box_pack_start(GTK_BOX(body), buttons, FALSE, FALSE, 0);
|
||||
const char *labels[] = {"Start", "Add", "Delete", "Rename", "End"};
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
auto *button = gtk_button_new_with_label(labels[i]);
|
||||
buttons_[size_t(i)] = button;
|
||||
gtk_box_pack_start(GTK_BOX(buttons), button, FALSE, FALSE, 0);
|
||||
g_object_set_data(G_OBJECT(button), "response-id", GINT_TO_POINTER(i + 1));
|
||||
g_signal_connect(button, "clicked", G_CALLBACK(+[](GtkButton *button, gpointer self) {
|
||||
auto *window = static_cast<GtkLauncher *>(self)->window_;
|
||||
gtk_dialog_response(
|
||||
GTK_DIALOG(window),
|
||||
GPOINTER_TO_INT(g_object_get_data(G_OBJECT(button), "response-id")));
|
||||
}),
|
||||
this);
|
||||
}
|
||||
g_signal_connect(tree_, "row-activated",
|
||||
G_CALLBACK(+[](GtkTreeView *, GtkTreePath *, GtkTreeViewColumn *, gpointer data) {
|
||||
gtk_dialog_response(GTK_DIALOG(static_cast<GtkLauncher *>(data)->window_),
|
||||
Start);
|
||||
}),
|
||||
this);
|
||||
gtk_widget_show_all(window_);
|
||||
}
|
||||
~GtkLauncher() override {
|
||||
finish_progress();
|
||||
gtk_widget_destroy(window_);
|
||||
g_object_unref(model_);
|
||||
}
|
||||
LauncherChoice next(const std::vector<ModEntry> &mods) override {
|
||||
gtk_list_store_clear(model_);
|
||||
int selected = -1;
|
||||
for (size_t i = 0; i < mods.size(); ++i) {
|
||||
GtkTreeIter it;
|
||||
gtk_list_store_append(model_, &it);
|
||||
const auto &mod = mods[i];
|
||||
const auto shown = mod.error.empty() ? mod.name : mod.name + " ⚠";
|
||||
gtk_list_store_set(model_, &it, 0, shown.c_str(), 1, mod.type.c_str(), 2, mod.error.c_str(), -1);
|
||||
if (mod.name == selection_) {
|
||||
auto *path = gtk_tree_path_new_from_indices(int(i), -1);
|
||||
gtk_tree_view_set_cursor(GTK_TREE_VIEW(tree_), path, nullptr, FALSE);
|
||||
gtk_tree_path_free(path);
|
||||
}
|
||||
}
|
||||
selection_changed(gtk_tree_view_get_selection(GTK_TREE_VIEW(tree_)), this);
|
||||
const int response = gtk_dialog_run(GTK_DIALOG(window_));
|
||||
GtkTreeIter it;
|
||||
GtkTreeModel *model;
|
||||
if (gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(tree_)), &model, &it)) {
|
||||
auto *path = gtk_tree_model_get_path(model, &it);
|
||||
selected = gtk_tree_path_get_indices(path)[0];
|
||||
gtk_tree_path_free(path);
|
||||
if (selected >= 0 && size_t(selected) < mods.size())
|
||||
selection_ = mods[size_t(selected)].name;
|
||||
}
|
||||
return {response == Start ? LauncherAction::start
|
||||
: response == Add ? LauncherAction::add
|
||||
: response == Delete ? LauncherAction::remove
|
||||
: response == Rename ? LauncherAction::rename
|
||||
: LauncherAction::end,
|
||||
selected};
|
||||
}
|
||||
std::optional<std::filesystem::path> choose_folder(const std::string &title,
|
||||
const std::filesystem::path &initial) override {
|
||||
auto *dialog = gtk_file_chooser_dialog_new(
|
||||
title.c_str(), GTK_WINDOW(window_), GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, "Abbrechen",
|
||||
GTK_RESPONSE_CANCEL, "Auswählen", GTK_RESPONSE_ACCEPT, nullptr);
|
||||
if (!initial.empty())
|
||||
gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog), path_to_utf8(initial).c_str());
|
||||
std::optional<std::filesystem::path> result;
|
||||
if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
|
||||
char *file = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
|
||||
if (file) {
|
||||
result = path_from_utf8(file);
|
||||
g_free(file);
|
||||
}
|
||||
}
|
||||
gtk_widget_destroy(dialog);
|
||||
return result;
|
||||
}
|
||||
std::optional<AddMod> configure_add(AddMod initial) override {
|
||||
auto *dialog = gtk_dialog_new_with_buttons("Classic-Mod hinzufügen", GTK_WINDOW(window_),
|
||||
GTK_DIALOG_MODAL, "Abbrechen", GTK_RESPONSE_CANCEL,
|
||||
"Importieren", GTK_RESPONSE_ACCEPT, nullptr);
|
||||
gtk_window_set_default_size(GTK_WINDOW(dialog), 540, -1);
|
||||
auto *grid = gtk_grid_new();
|
||||
gtk_grid_set_row_spacing(GTK_GRID(grid), 12);
|
||||
gtk_grid_set_column_spacing(GTK_GRID(grid), 12);
|
||||
gtk_container_set_border_width(GTK_CONTAINER(grid), 16);
|
||||
gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), grid, TRUE, TRUE, 0);
|
||||
auto *name = entry(grid, 0, "Bezeichnung", initial.name);
|
||||
auto *year = entry(grid, 1, "Startjahr (nur Anzeige)", std::to_string(initial.start_year));
|
||||
auto *migrate = gtk_check_button_new_with_label("Spielstände/Einstellungen übernehmen");
|
||||
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(migrate), initial.migrate);
|
||||
gtk_grid_attach(GTK_GRID(grid), migrate, 0, 2, 3, 1);
|
||||
auto *saves = entry(grid, 3, "Spielstandsordner", path_to_utf8(initial.saves));
|
||||
auto *browse = gtk_button_new_with_label("Auswählen …");
|
||||
gtk_grid_attach(GTK_GRID(grid), browse, 2, 3, 1, 1);
|
||||
struct Browse {
|
||||
GtkLauncher *self;
|
||||
GtkWidget *input;
|
||||
};
|
||||
Browse context{this, saves};
|
||||
g_signal_connect(
|
||||
browse, "clicked", G_CALLBACK(+[](GtkButton *, gpointer p) {
|
||||
auto &c = *static_cast<Browse *>(p);
|
||||
if (auto path = c.self->choose_folder("Spielstandsordner wählen",
|
||||
path_from_utf8(gtk_entry_get_text(GTK_ENTRY(c.input)))))
|
||||
gtk_entry_set_text(GTK_ENTRY(c.input), path_to_utf8(*path).c_str());
|
||||
}),
|
||||
&context);
|
||||
gtk_widget_show_all(dialog);
|
||||
std::optional<AddMod> result;
|
||||
while (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT)
|
||||
try {
|
||||
initial.name = gtk_entry_get_text(GTK_ENTRY(name));
|
||||
ModLibrary::validate_name(initial.name);
|
||||
std::string value = gtk_entry_get_text(GTK_ENTRY(year));
|
||||
size_t end = 0;
|
||||
initial.start_year = std::stoi(value, &end);
|
||||
if (end != value.size() || initial.start_year < 1900 || initial.start_year > 9998)
|
||||
throw std::runtime_error("Startjahr muss zwischen 1900 und 9998 liegen");
|
||||
initial.saves = path_from_utf8(gtk_entry_get_text(GTK_ENTRY(saves)));
|
||||
initial.migrate = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(migrate));
|
||||
result = initial;
|
||||
break;
|
||||
} catch (const std::exception &e) {
|
||||
message(e.what(), true);
|
||||
}
|
||||
gtk_widget_destroy(dialog);
|
||||
return result;
|
||||
}
|
||||
std::optional<std::string> rename(const std::string &old) override {
|
||||
auto *dialog =
|
||||
gtk_dialog_new_with_buttons("Mod umbenennen", GTK_WINDOW(window_), GTK_DIALOG_MODAL, "Abbrechen",
|
||||
GTK_RESPONSE_CANCEL, "Umbenennen", GTK_RESPONSE_ACCEPT, nullptr);
|
||||
auto *input = gtk_entry_new();
|
||||
gtk_entry_set_text(GTK_ENTRY(input), old.c_str());
|
||||
gtk_container_set_border_width(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), 16);
|
||||
gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), input, TRUE, TRUE, 0);
|
||||
gtk_widget_show_all(dialog);
|
||||
std::optional<std::string> result;
|
||||
if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT)
|
||||
result = gtk_entry_get_text(GTK_ENTRY(input));
|
||||
gtk_widget_destroy(dialog);
|
||||
return result;
|
||||
}
|
||||
bool confirm_delete(const std::string &name) override {
|
||||
auto *dialog = gtk_message_dialog_new(GTK_WINDOW(window_), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION,
|
||||
GTK_BUTTONS_YES_NO, "Mod „%s“ löschen?", name.c_str());
|
||||
gtk_message_dialog_format_secondary_text(
|
||||
GTK_MESSAGE_DIALOG(dialog), "Spielstände und persönliche Einstellungen bleiben erhalten.");
|
||||
const bool yes = gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_YES;
|
||||
gtk_widget_destroy(dialog);
|
||||
return yes;
|
||||
}
|
||||
void message(const std::string &text, bool error) override {
|
||||
auto *dialog = gtk_message_dialog_new(GTK_WINDOW(window_), GTK_DIALOG_MODAL,
|
||||
error ? GTK_MESSAGE_ERROR : GTK_MESSAGE_INFO, GTK_BUTTONS_OK,
|
||||
"%s", text.c_str());
|
||||
gtk_dialog_run(GTK_DIALOG(dialog));
|
||||
gtk_widget_destroy(dialog);
|
||||
}
|
||||
void progress(const std::string &text, bool cancellable) override {
|
||||
if (!progress_) {
|
||||
cancelled_ = false;
|
||||
progress_ = gtk_dialog_new();
|
||||
gtk_window_set_title(GTK_WINDOW(progress_), "OpenBMH");
|
||||
gtk_window_set_transient_for(GTK_WINDOW(progress_), GTK_WINDOW(window_));
|
||||
gtk_window_set_modal(GTK_WINDOW(progress_), TRUE);
|
||||
gtk_container_set_border_width(GTK_CONTAINER(progress_), 20);
|
||||
progress_label_ = gtk_label_new(text.c_str());
|
||||
gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(progress_))), progress_label_,
|
||||
TRUE, TRUE, 0);
|
||||
if (cancellable)
|
||||
gtk_dialog_add_button(GTK_DIALOG(progress_), "Abbrechen", GTK_RESPONSE_CANCEL);
|
||||
g_signal_connect(progress_, "response", G_CALLBACK(+[](GtkDialog *, int, gpointer data) {
|
||||
static_cast<GtkLauncher *>(data)->cancelled_ = true;
|
||||
}),
|
||||
this);
|
||||
g_signal_connect(progress_, "delete-event",
|
||||
G_CALLBACK(+[](GtkWidget *, GdkEvent *, gpointer data) -> gboolean {
|
||||
static_cast<GtkLauncher *>(data)->cancelled_ = true;
|
||||
return TRUE;
|
||||
}),
|
||||
this);
|
||||
gtk_widget_set_sensitive(window_, FALSE);
|
||||
gtk_widget_show_all(progress_);
|
||||
}
|
||||
gtk_label_set_text(GTK_LABEL(progress_label_), text.c_str());
|
||||
}
|
||||
bool pump() override {
|
||||
while (gtk_events_pending())
|
||||
gtk_main_iteration();
|
||||
return cancelled_;
|
||||
}
|
||||
void finish_progress() override {
|
||||
if (progress_) {
|
||||
gtk_widget_destroy(progress_);
|
||||
progress_ = progress_label_ = nullptr;
|
||||
gtk_widget_set_sensitive(window_, TRUE);
|
||||
gtk_window_present(GTK_WINDOW(window_));
|
||||
}
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
std::unique_ptr<LauncherUI> make_launcher_ui() { return std::make_unique<GtkLauncher>(); }
|
||||
} // namespace bmh::launch
|
||||
@@ -0,0 +1,27 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include "launch/mods.hpp"
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
namespace bmh::launch {
|
||||
enum class LauncherAction { start, add, remove, rename, end };
|
||||
struct LauncherChoice {
|
||||
LauncherAction action = LauncherAction::end;
|
||||
int selection = -1;
|
||||
};
|
||||
class LauncherUI {
|
||||
public:
|
||||
virtual ~LauncherUI() = default;
|
||||
virtual LauncherChoice next(const std::vector<ModEntry> &) = 0;
|
||||
virtual std::optional<std::filesystem::path> choose_folder(const std::string &title,
|
||||
const std::filesystem::path &initial = {}) = 0;
|
||||
virtual std::optional<AddMod> configure_add(AddMod defaults) = 0;
|
||||
virtual std::optional<std::string> rename(const std::string &) = 0;
|
||||
virtual bool confirm_delete(const std::string &) = 0;
|
||||
virtual void message(const std::string &, bool error) = 0;
|
||||
virtual void progress(const std::string &, bool cancellable) = 0;
|
||||
virtual bool pump() = 0; // cancellation requested
|
||||
virtual void finish_progress() = 0;
|
||||
};
|
||||
std::unique_ptr<LauncherUI> make_launcher_ui();
|
||||
} // namespace bmh::launch
|
||||
@@ -0,0 +1,317 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#ifndef UNICODE
|
||||
#define UNICODE
|
||||
#endif
|
||||
#ifndef _UNICODE
|
||||
#define _UNICODE
|
||||
#endif
|
||||
#define NOMINMAX
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#include <commctrl.h>
|
||||
#include <shobjidl.h>
|
||||
#include "launch/launcher_ui.hpp"
|
||||
#include "launch/archive.hpp"
|
||||
#include <functional>
|
||||
namespace bmh::launch {
|
||||
namespace {
|
||||
std::wstring wide(const std::string &s) { return path_from_utf8(s).wstring(); }
|
||||
std::string text(HWND window) {
|
||||
int n = GetWindowTextLengthW(window);
|
||||
std::wstring s(size_t(n) + 1, L'\0');
|
||||
GetWindowTextW(window, s.data(), n + 1);
|
||||
s.resize(size_t(n));
|
||||
return path_to_utf8(std::filesystem::path(s));
|
||||
}
|
||||
struct Form {
|
||||
HWND window = nullptr;
|
||||
bool done = false;
|
||||
int response = 0;
|
||||
bool prevent_close = false;
|
||||
std::function<void(int)> command;
|
||||
static LRESULT CALLBACK procedure(HWND h, UINT msg, WPARAM w, LPARAM l) {
|
||||
auto *form = reinterpret_cast<Form *>(GetWindowLongPtrW(h, GWLP_USERDATA));
|
||||
if (msg == WM_NCCREATE) {
|
||||
form = static_cast<Form *>(reinterpret_cast<CREATESTRUCTW *>(l)->lpCreateParams);
|
||||
SetWindowLongPtrW(h, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(form));
|
||||
form->window = h;
|
||||
}
|
||||
if (form) {
|
||||
if (msg == WM_COMMAND && form->command) {
|
||||
try {
|
||||
form->command(LOWORD(w));
|
||||
} catch (const std::exception &e) {
|
||||
MessageBoxW(h, wide(e.what()).c_str(), L"OpenBMH", MB_OK | MB_ICONERROR);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (msg == WM_NOTIFY && reinterpret_cast<NMHDR *>(l)->code == LVN_ITEMCHANGED) {
|
||||
const bool selected =
|
||||
ListView_GetNextItem(reinterpret_cast<NMHDR *>(l)->hwndFrom, -1, LVNI_SELECTED) >= 0;
|
||||
for (int id : {1, 3, 4})
|
||||
EnableWindow(GetDlgItem(h, id), selected);
|
||||
return 0;
|
||||
}
|
||||
if (msg == WM_CLOSE) {
|
||||
form->response = 0;
|
||||
form->done = true;
|
||||
if (!form->prevent_close)
|
||||
ShowWindow(h, SW_HIDE);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return DefWindowProcW(h, msg, w, l);
|
||||
}
|
||||
Form(const wchar_t *title, int width, int height, HWND owner = nullptr) {
|
||||
static const bool registered = [] {
|
||||
WNDCLASSW c{};
|
||||
c.lpfnWndProc = procedure;
|
||||
c.hInstance = GetModuleHandleW(nullptr);
|
||||
c.lpszClassName = L"OpenBMHLauncher";
|
||||
c.hCursor = LoadCursorW(nullptr, IDC_ARROW);
|
||||
c.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BTNFACE + 1);
|
||||
return RegisterClassW(&c) != 0;
|
||||
}();
|
||||
if (!registered)
|
||||
throw std::runtime_error("Cannot register native launcher window");
|
||||
window =
|
||||
CreateWindowExW(WS_EX_DLGMODALFRAME, L"OpenBMHLauncher", title,
|
||||
WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, CW_USEDEFAULT,
|
||||
CW_USEDEFAULT, width, height, owner, nullptr, GetModuleHandleW(nullptr), this);
|
||||
if (!window)
|
||||
throw std::runtime_error("Cannot create native launcher window");
|
||||
command = [this](int id) {
|
||||
response = id;
|
||||
done = true;
|
||||
};
|
||||
}
|
||||
~Form() {
|
||||
if (window)
|
||||
DestroyWindow(window);
|
||||
}
|
||||
HWND control(const wchar_t *cls, const std::wstring &label, int x, int y, int w, int h, int id,
|
||||
DWORD style = 0) {
|
||||
auto window =
|
||||
CreateWindowExW(cls == std::wstring(L"EDIT") ? WS_EX_CLIENTEDGE : 0, cls, label.c_str(),
|
||||
WS_CHILD | WS_VISIBLE | WS_TABSTOP | style, x, y, w, h, this->window,
|
||||
reinterpret_cast<HMENU>(INT_PTR(id)), GetModuleHandleW(nullptr), nullptr);
|
||||
SendMessageW(window, WM_SETFONT, reinterpret_cast<WPARAM>(GetStockObject(DEFAULT_GUI_FONT)), TRUE);
|
||||
return window;
|
||||
}
|
||||
int run() {
|
||||
done = false;
|
||||
response = 0;
|
||||
ShowWindow(window, SW_SHOW);
|
||||
SetForegroundWindow(window);
|
||||
MSG msg;
|
||||
while (!done && GetMessageW(&msg, nullptr, 0, 0) > 0)
|
||||
if (!IsDialogMessageW(window, &msg)) {
|
||||
TranslateMessage(&msg);
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
};
|
||||
class WinLauncher final : public LauncherUI {
|
||||
Form main_{L"OpenBMH", 660, 370};
|
||||
HWND list_ = nullptr;
|
||||
std::unique_ptr<Form> progress_;
|
||||
HWND progress_label_ = nullptr;
|
||||
bool com_ = false;
|
||||
|
||||
public:
|
||||
WinLauncher() {
|
||||
const auto result = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
|
||||
com_ = SUCCEEDED(result);
|
||||
if (FAILED(result) && result != RPC_E_CHANGED_MODE)
|
||||
throw std::runtime_error("Cannot initialize native folder dialog");
|
||||
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES};
|
||||
InitCommonControlsEx(&controls);
|
||||
list_ = main_.control(WC_LISTVIEWW, L"", 16, 16, 480, 290, 100,
|
||||
LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | WS_BORDER);
|
||||
ListView_SetExtendedListViewStyle(list_, LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER);
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
LVCOLUMNW c{};
|
||||
c.mask = LVCF_TEXT | LVCF_WIDTH;
|
||||
c.cx = i ? 110 : 340;
|
||||
c.pszText = const_cast<wchar_t *>(i ? L"Art" : L"Name");
|
||||
ListView_InsertColumn(list_, i, &c);
|
||||
}
|
||||
const wchar_t *labels[] = {L"Start", L"Add", L"Delete", L"Rename", L"End"};
|
||||
for (int i = 0; i < 5; ++i)
|
||||
main_.control(L"BUTTON", labels[i], 514, 16 + i * 48, 110, 34, i + 1, BS_PUSHBUTTON);
|
||||
main_.command = [this](int id) {
|
||||
if (id < 1 || id > 5)
|
||||
return;
|
||||
const int selected = ListView_GetNextItem(list_, -1, LVNI_SELECTED);
|
||||
if (id != 2 && id != 5 && selected < 0)
|
||||
return;
|
||||
main_.response = id;
|
||||
main_.done = true;
|
||||
};
|
||||
}
|
||||
~WinLauncher() override {
|
||||
if (com_)
|
||||
CoUninitialize();
|
||||
}
|
||||
LauncherChoice next(const std::vector<ModEntry> &mods) override {
|
||||
const int old = ListView_GetNextItem(list_, -1, LVNI_SELECTED);
|
||||
ListView_DeleteAllItems(list_);
|
||||
for (size_t i = 0; i < mods.size(); ++i) {
|
||||
auto name = wide(mods[i].name + (mods[i].error.empty() ? "" : " [!]"));
|
||||
LVITEMW row{};
|
||||
row.mask = LVIF_TEXT;
|
||||
row.iItem = int(i);
|
||||
row.pszText = name.data();
|
||||
ListView_InsertItem(list_, &row);
|
||||
auto type = wide(mods[i].type);
|
||||
ListView_SetItemText(list_, int(i), 1, type.data());
|
||||
}
|
||||
if (old >= 0 && size_t(old) < mods.size())
|
||||
ListView_SetItemState(list_, old, LVIS_SELECTED, LVIS_SELECTED);
|
||||
const bool selected = ListView_GetNextItem(list_, -1, LVNI_SELECTED) >= 0;
|
||||
for (int id : {1, 3, 4})
|
||||
EnableWindow(GetDlgItem(main_.window, id), selected);
|
||||
const int response = main_.run();
|
||||
return {response == 1 ? LauncherAction::start
|
||||
: response == 2 ? LauncherAction::add
|
||||
: response == 3 ? LauncherAction::remove
|
||||
: response == 4 ? LauncherAction::rename
|
||||
: LauncherAction::end,
|
||||
ListView_GetNextItem(list_, -1, LVNI_SELECTED)};
|
||||
}
|
||||
std::optional<std::filesystem::path> choose_folder(const std::string &title,
|
||||
const std::filesystem::path &initial) override {
|
||||
IFileOpenDialog *dialog = nullptr;
|
||||
if (FAILED(
|
||||
CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&dialog))))
|
||||
throw std::runtime_error("Cannot create folder dialog");
|
||||
struct Release {
|
||||
IFileOpenDialog *p;
|
||||
~Release() { p->Release(); }
|
||||
} release{dialog};
|
||||
DWORD options = 0;
|
||||
dialog->GetOptions(&options);
|
||||
dialog->SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM);
|
||||
dialog->SetTitle(wide(title).c_str());
|
||||
if (!initial.empty()) {
|
||||
IShellItem *folder = nullptr;
|
||||
if (SUCCEEDED(SHCreateItemFromParsingName(initial.c_str(), nullptr, IID_PPV_ARGS(&folder)))) {
|
||||
dialog->SetFolder(folder);
|
||||
folder->Release();
|
||||
}
|
||||
}
|
||||
const auto status = dialog->Show(main_.window);
|
||||
if (status == HRESULT_FROM_WIN32(ERROR_CANCELLED))
|
||||
return {};
|
||||
if (FAILED(status))
|
||||
throw std::runtime_error("Folder dialog failed");
|
||||
IShellItem *item = nullptr;
|
||||
if (FAILED(dialog->GetResult(&item)))
|
||||
throw std::runtime_error("No folder selected");
|
||||
PWSTR name = nullptr;
|
||||
const auto result = item->GetDisplayName(SIGDN_FILESYSPATH, &name);
|
||||
item->Release();
|
||||
if (FAILED(result))
|
||||
throw std::runtime_error("Invalid folder selection");
|
||||
std::filesystem::path path(name);
|
||||
CoTaskMemFree(name);
|
||||
return path;
|
||||
}
|
||||
std::optional<AddMod> configure_add(AddMod initial) override {
|
||||
Form form(L"Classic-Mod hinzufügen", 650, 295, main_.window);
|
||||
form.control(L"STATIC", L"Bezeichnung", 16, 20, 160, 22, 100);
|
||||
auto name = form.control(L"EDIT", wide(initial.name), 182, 16, 425, 26, 101, ES_AUTOHSCROLL);
|
||||
form.control(L"STATIC", L"Startjahr (nur Anzeige)", 16, 62, 164, 22, 102);
|
||||
auto year =
|
||||
form.control(L"EDIT", wide(std::to_string(initial.start_year)), 182, 58, 110, 26, 103, ES_NUMBER);
|
||||
auto migrate = form.control(L"BUTTON", L"Spielstände/Einstellungen übernehmen", 16, 100, 550, 26, 104,
|
||||
BS_AUTOCHECKBOX);
|
||||
SendMessageW(migrate, BM_SETCHECK, initial.migrate ? BST_CHECKED : BST_UNCHECKED, 0);
|
||||
form.control(L"STATIC", L"Spielstandsordner", 16, 146, 160, 22, 105);
|
||||
auto saves = form.control(L"EDIT", initial.saves.wstring(), 182, 140, 310, 26, 106, ES_AUTOHSCROLL);
|
||||
form.control(L"BUTTON", L"Auswählen …", 502, 140, 106, 26, 107);
|
||||
form.control(L"BUTTON", L"Importieren", 365, 204, 116, 32, 1);
|
||||
form.control(L"BUTTON", L"Abbrechen", 493, 204, 116, 32, 2);
|
||||
form.command = [&](int id) {
|
||||
if (id == 107) {
|
||||
if (auto path = choose_folder("Spielstandsordner wählen", path_from_utf8(text(saves))))
|
||||
SetWindowTextW(saves, path->c_str());
|
||||
} else if (id == 1 || id == 2) {
|
||||
form.response = id;
|
||||
form.done = true;
|
||||
}
|
||||
};
|
||||
EnableWindow(main_.window, FALSE);
|
||||
std::optional<AddMod> out;
|
||||
while (form.run() == 1)
|
||||
try {
|
||||
initial.name = text(name);
|
||||
ModLibrary::validate_name(initial.name);
|
||||
auto value = text(year);
|
||||
size_t end = 0;
|
||||
initial.start_year = std::stoi(value, &end);
|
||||
if (end != value.size() || initial.start_year < 1900 || initial.start_year > 9998)
|
||||
throw std::runtime_error("Startjahr muss zwischen 1900 und 9998 liegen");
|
||||
initial.saves = path_from_utf8(text(saves));
|
||||
initial.migrate = SendMessageW(migrate, BM_GETCHECK, 0, 0) == BST_CHECKED;
|
||||
out = initial;
|
||||
break;
|
||||
} catch (const std::exception &e) {
|
||||
message(e.what(), true);
|
||||
}
|
||||
EnableWindow(main_.window, TRUE);
|
||||
return out;
|
||||
}
|
||||
std::optional<std::string> rename(const std::string &old) override {
|
||||
Form form(L"Mod umbenennen", 480, 165, main_.window);
|
||||
auto input = form.control(L"EDIT", wide(old), 16, 16, 430, 26, 100, ES_AUTOHSCROLL);
|
||||
form.control(L"BUTTON", L"Umbenennen", 190, 65, 120, 32, 1);
|
||||
form.control(L"BUTTON", L"Abbrechen", 322, 65, 124, 32, 2);
|
||||
EnableWindow(main_.window, FALSE);
|
||||
const auto response = form.run();
|
||||
EnableWindow(main_.window, TRUE);
|
||||
return response == 1 ? std::optional<std::string>(text(input)) : std::nullopt;
|
||||
}
|
||||
bool confirm_delete(const std::string &name) override {
|
||||
return MessageBoxW(main_.window,
|
||||
wide("Mod „" + name +
|
||||
"“ löschen?\nSpielstände und persönliche Einstellungen bleiben erhalten.")
|
||||
.c_str(),
|
||||
L"OpenBMH", MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2) == IDYES;
|
||||
}
|
||||
void message(const std::string &value, bool error) override {
|
||||
MessageBoxW(main_.window, wide(value).c_str(), L"OpenBMH",
|
||||
MB_OK | (error ? MB_ICONERROR : MB_ICONINFORMATION));
|
||||
}
|
||||
void progress(const std::string &value, bool cancellable) override {
|
||||
if (!progress_) {
|
||||
EnableWindow(main_.window, FALSE);
|
||||
progress_ = std::make_unique<Form>(L"OpenBMH", 600, 150, main_.window);
|
||||
progress_->prevent_close = true;
|
||||
progress_label_ = progress_->control(L"STATIC", L"", 16, 18, 550, 40, 100);
|
||||
if (cancellable)
|
||||
progress_->control(L"BUTTON", L"Abbrechen", 440, 65, 115, 28, 1);
|
||||
ShowWindow(progress_->window, SW_SHOW);
|
||||
}
|
||||
SetWindowTextW(progress_label_, wide(value).c_str());
|
||||
}
|
||||
bool pump() override {
|
||||
MSG msg;
|
||||
while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) {
|
||||
TranslateMessage(&msg);
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
return progress_ && progress_->done;
|
||||
}
|
||||
void finish_progress() override {
|
||||
if (progress_) {
|
||||
progress_.reset();
|
||||
EnableWindow(main_.window, TRUE);
|
||||
SetForegroundWindow(main_.window);
|
||||
}
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
std::unique_ptr<LauncherUI> make_launcher_ui() { return std::make_unique<WinLauncher>(); }
|
||||
} // namespace bmh::launch
|
||||
@@ -0,0 +1,190 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "launch/mods.hpp"
|
||||
#include "content/save.hpp"
|
||||
#include "launch/archive.hpp"
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <chrono>
|
||||
#include <set>
|
||||
namespace bmh::launch {
|
||||
namespace fs = std::filesystem;
|
||||
namespace {
|
||||
std::string fold(std::string s) {
|
||||
for (auto &c : s)
|
||||
c = char(std::tolower(static_cast<unsigned char>(c)));
|
||||
return s;
|
||||
}
|
||||
std::string filename(const fs::path &p) { return path_to_utf8(p.filename()); }
|
||||
void safe_directory(const fs::path &path) {
|
||||
const auto status = fs::symlink_status(path);
|
||||
if (fs::is_symlink(status) || (fs::exists(status) && !fs::is_directory(status)))
|
||||
throw FormatError("Unsafe portable directory: " + path_to_utf8(path));
|
||||
fs::create_directories(path);
|
||||
}
|
||||
} // namespace
|
||||
ModLibrary::ModLibrary(fs::path root) : root_(fs::absolute(std::move(root)).lexically_normal()) {}
|
||||
void ModLibrary::validate_name(const std::string &name) {
|
||||
if (name.empty() || name.size() > 100 || name == "." || name == ".." || name.front() == '.' ||
|
||||
name.back() == '.' || name.back() == ' ')
|
||||
throw FormatError("Invalid mod name");
|
||||
for (unsigned char c : name)
|
||||
if (c < 32 || c == 127 || std::string("/\\:*?\"<>|").find(char(c)) != std::string::npos)
|
||||
throw FormatError("Invalid character in mod name");
|
||||
auto base = fold(name.substr(0, name.find('.')));
|
||||
const std::set<std::string> reserved{"con", "prn", "aux", "nul", "com1", "com2", "com3", "com4",
|
||||
"com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
|
||||
"lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9"};
|
||||
if (reserved.contains(base))
|
||||
throw FormatError("Reserved mod name");
|
||||
}
|
||||
std::vector<ModEntry> ModLibrary::list() const {
|
||||
std::vector<ModEntry> out;
|
||||
const auto folder = root_ / "mods";
|
||||
if (!fs::exists(fs::symlink_status(folder)))
|
||||
return out;
|
||||
if (fs::is_symlink(fs::symlink_status(folder)) || !fs::is_directory(folder))
|
||||
throw FormatError("Unsafe mods directory");
|
||||
for (const auto &entry : fs::directory_iterator(folder)) {
|
||||
const auto name = filename(entry.path());
|
||||
if (name.starts_with('.'))
|
||||
continue;
|
||||
if (!entry.is_directory() && !entry.is_symlink())
|
||||
continue;
|
||||
ModEntry mod;
|
||||
mod.name = name;
|
||||
mod.directory = entry.path();
|
||||
try {
|
||||
validate_name(name);
|
||||
if (entry.is_symlink())
|
||||
throw FormatError("Linked mod directories are not supported");
|
||||
for (const auto &child : fs::directory_iterator(entry.path()))
|
||||
if (child.path().filename() != "content.obw")
|
||||
throw FormatError("Unexpected files in sealed Classic mod");
|
||||
const auto content = content::open(entry.path() / "content.obw");
|
||||
mod.content_id = content->content_id;
|
||||
} catch (const std::exception &e) {
|
||||
mod.error = e.what();
|
||||
}
|
||||
out.push_back(std::move(mod));
|
||||
}
|
||||
std::sort(out.begin(), out.end(),
|
||||
[](const auto &a, const auto &b) { return fold(a.name) < fold(b.name); });
|
||||
return out;
|
||||
}
|
||||
void ModLibrary::available(const std::string &name) const {
|
||||
validate_name(name);
|
||||
const auto folder = root_ / "mods";
|
||||
if (fs::exists(fs::symlink_status(folder))) {
|
||||
if (fs::is_symlink(fs::symlink_status(folder)) || !fs::is_directory(folder))
|
||||
throw FormatError("Unsafe mods directory");
|
||||
for (const auto &entry : fs::directory_iterator(folder))
|
||||
if (fold(filename(entry.path())) == fold(name))
|
||||
throw FormatError("A mod with this name already exists");
|
||||
}
|
||||
}
|
||||
void ModLibrary::owned(const ModEntry &mod) const {
|
||||
if (mod.directory.parent_path() != root_ / "mods" || filename(mod.directory) != mod.name ||
|
||||
fs::is_symlink(fs::symlink_status(mod.directory)))
|
||||
throw FormatError("Mod path is not owned by this library");
|
||||
}
|
||||
fs::path ModLibrary::user_directory(const ModEntry &mod) const {
|
||||
if (mod.content_id.size() != 64 ||
|
||||
mod.content_id.find_first_not_of("0123456789abcdef") != std::string::npos)
|
||||
throw FormatError("Invalid mod identity");
|
||||
safe_directory(root_ / "userdata");
|
||||
const auto directory = root_ / "userdata" / mod.content_id;
|
||||
safe_directory(directory);
|
||||
return directory;
|
||||
}
|
||||
ImportReport ModLibrary::add(const AddMod &request, const SaveMigrator &migrate,
|
||||
const ImportProgress &progress) {
|
||||
available(request.name);
|
||||
if (request.start_year < 1900 || request.start_year > 9998)
|
||||
throw FormatError("Start year must be 1900–9998");
|
||||
safe_directory(root_ / "mods");
|
||||
const auto update = [&](const std::string &s) {
|
||||
if (progress)
|
||||
progress(s);
|
||||
};
|
||||
update("Installation wird konvertiert …");
|
||||
obw::Options options;
|
||||
options.start_date = std::to_string(request.start_year) + "-07-01";
|
||||
options.title = "Classic installation";
|
||||
auto docs = obw::import_installation(request.source, options);
|
||||
const auto identity = content::seal(docs);
|
||||
update("Konvertierte Inhalte werden geprüft …");
|
||||
const auto staging =
|
||||
root_ / "mods" /
|
||||
(".import-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
|
||||
if (!fs::create_directory(staging))
|
||||
throw FormatError("Cannot reserve mod staging directory");
|
||||
struct Cleanup {
|
||||
fs::path p;
|
||||
~Cleanup() {
|
||||
std::error_code ec;
|
||||
fs::remove_all(p, ec);
|
||||
}
|
||||
} cleanup{staging};
|
||||
content::write_archive(docs, staging / "content.obw");
|
||||
(void)content::open(staging / "content.obw");
|
||||
ImportReport report;
|
||||
report.mod = {request.name, "Classic", identity, {}, root_ / "mods" / path_from_utf8(request.name)};
|
||||
const auto userdata = user_directory(report.mod);
|
||||
// User data is retained separately, and never overwrites a previous migration.
|
||||
if (request.migrate) {
|
||||
const auto source = request.saves.empty() ? request.source : request.saves;
|
||||
if (!fs::is_directory(source))
|
||||
report.errors.push_back("Spielstandsordner ist nicht verfügbar");
|
||||
else {
|
||||
std::vector<fs::path> files;
|
||||
for (const auto &entry : fs::directory_iterator(source))
|
||||
if (entry.is_regular_file() && !entry.is_symlink())
|
||||
files.push_back(entry.path());
|
||||
std::sort(files.begin(), files.end());
|
||||
for (const auto &input : files) {
|
||||
const auto ext = fold(path_to_utf8(input.extension()));
|
||||
if (ext != ".fbm" && ext != ".ein" && ext != ".men")
|
||||
continue;
|
||||
update("Übernahme: " + filename(input));
|
||||
try {
|
||||
auto destination = userdata / input.stem();
|
||||
destination += ext == ".fbm" ? ".obs" : ext == ".ein" ? ".obsettings" : ".oblayout";
|
||||
if (fs::exists(fs::symlink_status(destination)))
|
||||
throw FormatError("Destination already exists; retained existing file");
|
||||
if (ext == ".fbm") {
|
||||
if (!migrate)
|
||||
throw FormatError("Save migrator unavailable");
|
||||
migrate(staging / "content.obw", input, destination);
|
||||
} else {
|
||||
auto bytes = read_file(input);
|
||||
if (ext == ".ein" && bytes.size() != 180)
|
||||
throw FormatError("Invalid settings length");
|
||||
if (ext == ".men" && bytes.size() != 0x360)
|
||||
throw FormatError("Invalid desktop layout length");
|
||||
content::save_preferences(destination, ext == ".ein" ? "settings" : "layout", bytes,
|
||||
false);
|
||||
}
|
||||
++report.migrated;
|
||||
} catch (const std::exception &e) {
|
||||
report.errors.push_back(filename(input) + ": " + e.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
update("Mod wird eingetragen …");
|
||||
available(request.name);
|
||||
fs::rename(staging, report.mod.directory);
|
||||
return report;
|
||||
}
|
||||
void ModLibrary::rename(const ModEntry &mod, const std::string &name) {
|
||||
owned(mod);
|
||||
if (name == mod.name)
|
||||
return;
|
||||
available(name);
|
||||
fs::rename(mod.directory, root_ / "mods" / path_from_utf8(name));
|
||||
}
|
||||
void ModLibrary::remove(const ModEntry &mod) {
|
||||
owned(mod);
|
||||
fs::remove_all(mod.directory);
|
||||
}
|
||||
} // namespace bmh::launch
|
||||
@@ -0,0 +1,41 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include "content/package.hpp"
|
||||
#include <functional>
|
||||
namespace bmh::launch {
|
||||
struct ModEntry {
|
||||
std::string name, type = "Classic", content_id, error;
|
||||
std::filesystem::path directory;
|
||||
};
|
||||
struct AddMod {
|
||||
std::filesystem::path source, saves;
|
||||
std::string name;
|
||||
int start_year = 2026;
|
||||
bool migrate = true;
|
||||
};
|
||||
using SaveMigrator =
|
||||
std::function<void(const std::filesystem::path &content, const std::filesystem::path &source,
|
||||
const std::filesystem::path &destination)>;
|
||||
using ImportProgress = std::function<void(const std::string &)>;
|
||||
struct ImportReport {
|
||||
ModEntry mod;
|
||||
size_t migrated = 0;
|
||||
std::vector<std::string> errors;
|
||||
};
|
||||
class ModLibrary {
|
||||
public:
|
||||
explicit ModLibrary(std::filesystem::path portable_root);
|
||||
std::vector<ModEntry> list() const;
|
||||
ImportReport add(const AddMod &, const SaveMigrator &, const ImportProgress &progress = {});
|
||||
void rename(const ModEntry &, const std::string &name);
|
||||
void remove(const ModEntry &);
|
||||
std::filesystem::path user_directory(const ModEntry &) const;
|
||||
const std::filesystem::path &root() const { return root_; }
|
||||
static void validate_name(const std::string &);
|
||||
|
||||
private:
|
||||
std::filesystem::path root_;
|
||||
void available(const std::string &) const;
|
||||
void owned(const ModEntry &) const;
|
||||
};
|
||||
} // namespace bmh::launch
|
||||
@@ -0,0 +1,84 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "launch/process.hpp"
|
||||
#include "launch/archive.hpp"
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
#include <stdexcept>
|
||||
#ifdef _WIN32
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <spawn.h>
|
||||
#include <sys/wait.h>
|
||||
#include <cerrno>
|
||||
extern char **environ;
|
||||
#endif
|
||||
namespace bmh::launch {
|
||||
int run_child(const std::filesystem::path &executable, const std::vector<std::string> &args,
|
||||
const std::function<void()> &pump) {
|
||||
#ifdef _WIN32
|
||||
const auto quote = [](const std::wstring &value) {
|
||||
std::wstring out = L"\"";
|
||||
size_t slashes = 0;
|
||||
for (wchar_t c : value) {
|
||||
if (c == L'\\') {
|
||||
++slashes;
|
||||
continue;
|
||||
}
|
||||
if (c == L'\"')
|
||||
out.append(slashes * 2 + 1, L'\\');
|
||||
else
|
||||
out.append(slashes, L'\\');
|
||||
out += c;
|
||||
slashes = 0;
|
||||
}
|
||||
out.append(slashes * 2, L'\\');
|
||||
out += L'\"';
|
||||
return out;
|
||||
};
|
||||
auto command = quote(executable.wstring());
|
||||
for (const auto &a : args) {
|
||||
command += L' ';
|
||||
command += quote(path_from_utf8(a).wstring());
|
||||
}
|
||||
STARTUPINFOW start{};
|
||||
start.cb = sizeof(start);
|
||||
PROCESS_INFORMATION process{};
|
||||
if (!CreateProcessW(executable.c_str(), command.data(), nullptr, nullptr, FALSE, 0, nullptr,
|
||||
executable.parent_path().c_str(), &start, &process))
|
||||
throw std::runtime_error("Cannot start OpenBMH game process");
|
||||
CloseHandle(process.hThread);
|
||||
while (WaitForSingleObject(process.hProcess, 20) == WAIT_TIMEOUT)
|
||||
if (pump)
|
||||
pump();
|
||||
DWORD code = 1;
|
||||
GetExitCodeProcess(process.hProcess, &code);
|
||||
CloseHandle(process.hProcess);
|
||||
return int(code);
|
||||
#else
|
||||
const auto binary = path_to_utf8(executable);
|
||||
std::vector<std::string> storage{binary};
|
||||
storage.insert(storage.end(), args.begin(), args.end());
|
||||
std::vector<char *> argv;
|
||||
for (auto &s : storage)
|
||||
argv.push_back(s.data());
|
||||
argv.push_back(nullptr);
|
||||
pid_t pid;
|
||||
const int error = posix_spawn(&pid, binary.c_str(), nullptr, nullptr, argv.data(), environ);
|
||||
if (error)
|
||||
throw std::runtime_error("Cannot start OpenBMH game process (" + std::to_string(error) + ")");
|
||||
int status = 0;
|
||||
for (;;) {
|
||||
const auto result = waitpid(pid, &status, WNOHANG);
|
||||
if (result == pid)
|
||||
break;
|
||||
if (result < 0 && errno != EINTR)
|
||||
throw std::runtime_error("Cannot wait for game process");
|
||||
if (pump)
|
||||
pump();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
||||
}
|
||||
return WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
|
||||
#endif
|
||||
}
|
||||
} // namespace bmh::launch
|
||||
@@ -0,0 +1,10 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
namespace bmh::launch {
|
||||
int run_child(const std::filesystem::path &, const std::vector<std::string> &,
|
||||
const std::function<void()> &pump);
|
||||
} // namespace bmh::launch
|
||||
@@ -478,7 +478,7 @@ DeskDate desk_date(uint32_t counter, const LeImage& exe) {
|
||||
d.day -= month_days();
|
||||
if (++d.month == 13) { d.month = 1; ++years; }
|
||||
}
|
||||
d.year = 2026 + years;
|
||||
d.year = exe.display_start_year() + years;
|
||||
return d;
|
||||
}
|
||||
|
||||
@@ -518,6 +518,7 @@ DeskState desk_from_game(const GameState& g, const LeImage& exe, uint64_t revisi
|
||||
// runtime (0x165) suppresses this consumer while manual mailbox access remains valid.
|
||||
if (d.runtime_club != kNoTeam && d.manager_slot >= 0 && d.manager_slot < 32 && g.memory.has(::bmh::layout::MailboxRecipientMask))
|
||||
d.mailbox_notification_pending = (g.memory.u32(::bmh::layout::MailboxRecipientMask) & (uint32_t(1) << d.manager_slot)) != 0;
|
||||
d.date.year += g.display_start_year - exe.display_start_year();
|
||||
project_table_position(d, g);
|
||||
if (!current_groups && g.date == 0 && g.season == 0 && g.season_day() == 0 && g.texts) {
|
||||
const size_t title = (::bmh::layout::DeskState_DeskFromGame_TextPointer - ::bmh::layout::TextPointerTable) / 4 + 33;
|
||||
|
||||
+22
-5
@@ -11,6 +11,7 @@
|
||||
#include "ui/host_path.hpp"
|
||||
#include "ui/setup.hpp"
|
||||
#include "formats/fbm.hpp"
|
||||
#include "content/save.hpp"
|
||||
|
||||
namespace bmh::ui {
|
||||
namespace {
|
||||
@@ -38,13 +39,21 @@ void rect(Image& image, int x, int y, int w, int h, uint8_t color) {
|
||||
for (int yy = std::max(0, y); yy < std::min(image.height, y + h); ++yy)
|
||||
for (int xx = std::max(0, x); xx < std::min(image.width, x + w); ++xx) image.at(xx, yy) = color;
|
||||
}
|
||||
bool has_file_kind_extension(const std::filesystem::path& path, SaveLoadFileKind kind) {
|
||||
bool has_file_kind_extension(const std::filesystem::path &path, SaveLoadFileKind kind, bool native) {
|
||||
std::string ext = path_to_utf8(path.extension());
|
||||
std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return char(std::tolower(c)); });
|
||||
if (native)
|
||||
return ext == (kind == SaveLoadFileKind::menu_layout ? ".oblayout"
|
||||
: kind == SaveLoadFileKind::settings ? ".obsettings"
|
||||
: ".obs");
|
||||
return ext == (kind == SaveLoadFileKind::menu_layout ? ".men" :
|
||||
kind == SaveLoadFileKind::settings ? ".ein" : ".fbm");
|
||||
}
|
||||
std::string_view file_kind_extension(SaveLoadFileKind kind) {
|
||||
std::string_view file_kind_extension(SaveLoadFileKind kind, bool native) {
|
||||
if (native)
|
||||
return kind == SaveLoadFileKind::menu_layout ? ".oblayout"
|
||||
: kind == SaveLoadFileKind::settings ? ".obsettings"
|
||||
: ".obs";
|
||||
return kind == SaveLoadFileKind::menu_layout ? ".MEN" :
|
||||
kind == SaveLoadFileKind::settings ? ".EIN" : ".FBM";
|
||||
}
|
||||
@@ -85,13 +94,14 @@ SaveLoadScreen::SaveLoadScreen(const std::filesystem::path& data, std::filesyste
|
||||
throw FormatError("save/load: unsupported state");
|
||||
if (widgets_.width != 77 || widgets_.height != 112 || font_.height != 8 || footer_font_.height != 6)
|
||||
throw FormatError("save/load: unsupported Original font or widget atlas");
|
||||
native_ = bool(content::find(data));
|
||||
std::error_code ec;
|
||||
if (std::filesystem::is_directory(directory_, ec)) {
|
||||
for (std::filesystem::directory_iterator it(directory_, ec), end; !ec && it != end; it.increment(ec)) {
|
||||
std::error_code file_error;
|
||||
const auto status = it->symlink_status(file_error);
|
||||
if (!file_error && std::filesystem::is_regular_file(status) &&
|
||||
has_file_kind_extension(it->path(), file_kind_))
|
||||
has_file_kind_extension(it->path(), file_kind_, native_))
|
||||
entries_.push_back({it->path()});
|
||||
}
|
||||
std::sort(entries_.begin(), entries_.end(), [](const auto& a, const auto& b) {
|
||||
@@ -183,7 +193,13 @@ bool SaveLoadScreen::info_press(int x, int y) {
|
||||
if (file_kind_ != SaveLoadFileKind::game || pending_ || info_ || x <= 52 || x >= 200 || y <= 40 ||
|
||||
y >= 192 || !select_row(y)) return false;
|
||||
try {
|
||||
const auto saved = load_savegame(entries_.at(size_t(selected_)).path);
|
||||
Savegame saved;
|
||||
if (native_) {
|
||||
saved.plain_header = content::save_information(entries_.at(size_t(selected_)).path);
|
||||
saved.version = "V2.24";
|
||||
saved.checksum_ok = true;
|
||||
} else
|
||||
saved = load_savegame(entries_.at(size_t(selected_)).path);
|
||||
const auto& h = saved.plain_header;
|
||||
if (!saved.checksum_ok || saved.version != "V2.24" || h.size() < 172 || h[0] < 1 || h[0] > 4)
|
||||
throw FormatError("save/load: invalid native information header");
|
||||
@@ -306,7 +322,8 @@ void SaveLoadScreen::request_action() {
|
||||
if (!valid_filename(filename_)) {
|
||||
feedback_ = "UNGUELTIGER DATEINAME"; return;
|
||||
}
|
||||
auto path = directory_ / path_from_utf8(filename_ + std::string(file_kind_extension(file_kind_)));
|
||||
auto path =
|
||||
directory_ / path_from_utf8(filename_ + std::string(file_kind_extension(file_kind_, native_)));
|
||||
// Selecting an existing mixed-case extension must overwrite that same file.
|
||||
if (selected_ >= 0 && size_t(selected_) < entries_.size() &&
|
||||
path_to_utf8(entries_[size_t(selected_)].path.stem()) == filename_)
|
||||
|
||||
@@ -67,6 +67,7 @@ private:
|
||||
TextDb texts_;
|
||||
SpriteFont sprite_font_;
|
||||
Font footer_font_;
|
||||
bool native_ = false;
|
||||
bool gradient_text_ = true;
|
||||
std::vector<SaveLoadEntry> entries_;
|
||||
int selected_ = 0, scroll_ = 0;
|
||||
|
||||
+21
-11
@@ -1,6 +1,7 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/executable_layout.hpp"
|
||||
#include "ui/settings.hpp"
|
||||
#include "formats/content.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
@@ -304,18 +305,27 @@ SettingsReadmeScreen::SettingsReadmeScreen(const std::filesystem::path& data,
|
||||
// DOS resolves it case-insensitively; also try its uppercase spelling on
|
||||
// case-sensitive host filesystems.
|
||||
const std::filesystem::path source_name(texts_[839]);
|
||||
std::ifstream file(data / source_name, std::ios::binary);
|
||||
if (!file) {
|
||||
auto uppercase_name = source_name.string();
|
||||
std::transform(uppercase_name.begin(), uppercase_name.end(), uppercase_name.begin(),
|
||||
[](unsigned char c) { return char(std::toupper(c)); });
|
||||
file.open(data / uppercase_name, std::ios::binary);
|
||||
if (const auto resource = content::find(data / source_name)) {
|
||||
const auto it = resource->content->supplemental.find(resource->key);
|
||||
if (it == resource->content->supplemental.end())
|
||||
return;
|
||||
file_available_ = true;
|
||||
content_.assign(it->second.begin(), it->second.begin() + std::min(size_t(20000), it->second.size()));
|
||||
} else {
|
||||
std::ifstream file(data / source_name, std::ios::binary);
|
||||
if (!file) {
|
||||
auto uppercase_name = source_name.string();
|
||||
std::transform(uppercase_name.begin(), uppercase_name.end(), uppercase_name.begin(),
|
||||
[](unsigned char c) { return char(std::toupper(c)); });
|
||||
file.open(data / uppercase_name, std::ios::binary);
|
||||
}
|
||||
if (!file)
|
||||
return;
|
||||
file_available_ = true;
|
||||
std::array<char, 20000> bytes{};
|
||||
file.read(bytes.data(), std::streamsize(bytes.size()));
|
||||
content_.assign(bytes.data(), size_t(file.gcount()));
|
||||
}
|
||||
if (!file) return;
|
||||
file_available_ = true;
|
||||
std::array<char, 20000> bytes{};
|
||||
file.read(bytes.data(), std::streamsize(bytes.size()));
|
||||
content_.assign(bytes.data(), size_t(file.gcount()));
|
||||
pages_.emplace_back();
|
||||
int x = 0, baseline = 19;
|
||||
bool emphasized = false, new_page_before_next_byte = false;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/executable_layout.hpp"
|
||||
#include "ui/setup.hpp"
|
||||
#include "formats/content.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
@@ -30,6 +31,8 @@ void copy_rect(Image& dst, const Image& src, int sx, int sy, int dx, int dy,
|
||||
} // namespace
|
||||
|
||||
std::filesystem::path asset_path(const std::filesystem::path& directory, const std::string& name) {
|
||||
if (content::find(directory / name))
|
||||
return directory / name;
|
||||
std::filesystem::path found;
|
||||
for (const auto& e : std::filesystem::directory_iterator(directory)) {
|
||||
if (e.is_regular_file() && folded(e.path().filename().string()) == folded(name)) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/executable_layout.hpp"
|
||||
#include "ui/sportschau.hpp"
|
||||
#include "formats/content.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
@@ -89,6 +90,14 @@ Image load_kb(const std::filesystem::path& data_directory, const char* file) {
|
||||
}
|
||||
|
||||
std::optional<Palette> load_optional_embedded_palette(const std::filesystem::path& path) {
|
||||
if (const auto resource = content::find(path)) {
|
||||
auto name = std::filesystem::path(resource->key);
|
||||
name.replace_extension();
|
||||
const auto it = resource->content->image_palettes.find(name.generic_string());
|
||||
if (it == resource->content->image_palettes.end())
|
||||
return std::nullopt;
|
||||
return it->second;
|
||||
}
|
||||
const Bytes bytes = read_file(path);
|
||||
if (bytes.size() < 8) throw FormatError("sportschau: VGA palette source is truncated");
|
||||
const size_t rle_end = 8 + size_t(le32(bytes, 4));
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "content/package.hpp"
|
||||
#include "content/save.hpp"
|
||||
#include "launch/mods.hpp"
|
||||
#include "formats/content.hpp"
|
||||
#include "formats/native_state.hpp"
|
||||
#include "formats/vga.hpp"
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
using namespace bmh;
|
||||
namespace fs = std::filesystem;
|
||||
void check(bool value, const char *message) {
|
||||
if (!value)
|
||||
throw std::runtime_error(message);
|
||||
}
|
||||
template <class F> void rejects(F f, const char *message) {
|
||||
bool failed = false;
|
||||
try {
|
||||
f();
|
||||
} catch (const std::exception &) {
|
||||
failed = true;
|
||||
}
|
||||
check(failed, message);
|
||||
}
|
||||
int main() try {
|
||||
check(content::sha256("") == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"SHA256 empty vector");
|
||||
check(content::sha256("abc") == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
|
||||
"SHA256 short vector");
|
||||
check(content::sha256(std::string(1000000, 'a')) ==
|
||||
"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0",
|
||||
"SHA256 multi-block vector");
|
||||
const auto root = fs::temp_directory_path() /
|
||||
("openbmh-native-test-" +
|
||||
std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
|
||||
fs::create_directories(root);
|
||||
struct Cleanup {
|
||||
fs::path p;
|
||||
~Cleanup() {
|
||||
std::error_code ec;
|
||||
fs::remove_all(p, ec);
|
||||
}
|
||||
} cleanup{root};
|
||||
auto classic = std::make_shared<content::Classic>();
|
||||
classic->images.emplace("kb/7", Image(2, 2, 19));
|
||||
classic->audio["2000"] = {1, 2, 3};
|
||||
classic->desktops = {4, 5};
|
||||
classic->palette.argb[9] = 0xffabcdef;
|
||||
{
|
||||
content::Mount mount(root / "content.obw", classic);
|
||||
check(!fs::exists(mount.root()), "mounted contents need no materialized legacy files");
|
||||
check(load_vga(mount.root() / "KB/7.VGA").pixels == Bytes(4, 19),
|
||||
"indexed OBW image reaches existing renderer");
|
||||
check(read_file(mount.root() / "S/2000") == Bytes({1, 2, 3}),
|
||||
"audio bank comes from immutable store");
|
||||
check(read_file(mount.root() / "M3.MEN") == Bytes({4, 5}),
|
||||
"startup input comes from immutable store");
|
||||
check(load_palette(mount.root() / "M3PC.COL").argb[9] == 0xffabcdef,
|
||||
"palette keeps exact imported RGB8");
|
||||
rejects([&] { load_vga(mount.root() / "KB/999.VGA"); },
|
||||
"missing content must not fall through to disk");
|
||||
rejects([&] { content::Mount duplicate(mount.root(), classic); },
|
||||
"duplicate mounts must not replace live contents");
|
||||
}
|
||||
check(!content::find(root / "content.obw/KB/7.VGA"), "mount lifetime is bounded");
|
||||
GameState state;
|
||||
state.date = 99;
|
||||
state.season_start = 12;
|
||||
state.display_start_year = 1994;
|
||||
state.squad_slots = {0x8fff, 42};
|
||||
state.manager_teams = {-1, 12};
|
||||
state.manager_records = {1, 2, 3};
|
||||
state.player_names = {0, 0xff};
|
||||
state.memory.add_block(0x1000, 4);
|
||||
state.memory.set32(0x1000, 0xff123456);
|
||||
state.players.push_back({std::string("A\xff", 2), 0xdeadbeef, 0x12345678, 0xffffffff});
|
||||
state.autosave_month = 4;
|
||||
state.list_toggle = 1;
|
||||
state.sportschau_homes[9] = 41;
|
||||
state.reality.initialized = true;
|
||||
state.reality.grid.place(0, 5, 7, 0);
|
||||
state.reality.cue_actors[3] = 19;
|
||||
const auto encoded = encode_native_state(state);
|
||||
const auto restored = decode_native_state(cli::parse_json(cli::dump_json(encoded)));
|
||||
check(cli::dump_json(encoded) == cli::dump_json(encode_native_state(restored)),
|
||||
"all native fields round-trip without host padding/pointers");
|
||||
check(restored.reality == state.reality, "Reality residues survive exactly");
|
||||
auto damaged = encoded;
|
||||
damaged.object()->at("schema") = "classic-state@99.0";
|
||||
rejects([&] { decode_native_state(damaged); }, "unsupported checkpoint schema rejected");
|
||||
TurnDriver driver;
|
||||
driver.referees = {1, 0x81};
|
||||
driver.next_event_id = UINT64_MAX;
|
||||
TurnDriver copy;
|
||||
content::restore_driver(copy, content::driver_checkpoint(driver));
|
||||
check(copy.next_event_id == UINT64_MAX && copy.referees == driver.referees,
|
||||
"driver counters and referees round-trip");
|
||||
WatcomRandom random(7);
|
||||
random.rand();
|
||||
WatcomRandom continued;
|
||||
continued.restore(random.seed(), random.calls());
|
||||
check(continued.rand() == random.rand() && continued.calls() == random.calls(),
|
||||
"Watcom stream resumes including counter");
|
||||
content::Documents docs{{"manifest.json", "{}"}, {"assets/test.pixels", std::string("a\0b", 3)}};
|
||||
const auto archive = root / "sample.obs";
|
||||
content::write_archive(docs, archive);
|
||||
check(content::read_archive(archive) == docs, "binary native archive round-trip");
|
||||
rejects([&] { content::write_archive({{"../outside", "x"}}, root / "unsafe.obs"); },
|
||||
"archive traversal rejected");
|
||||
rejects([&] { content::write_archive({}, archive); }, "existing saves require explicit overwrite");
|
||||
check(content::read_archive(archive) == docs, "rejected overwrite retains existing save");
|
||||
content::write_archive({{"new", "value"}}, archive, true);
|
||||
check(content::read_archive(archive).contains("new"), "atomic replacement publishes complete archive");
|
||||
content::save_preferences(root / "test.obsettings", "settings", Bytes(180, 0x82), false);
|
||||
check(content::load_preferences(root / "test.obsettings", "settings", 180) == Bytes(180, 0x82),
|
||||
"native settings retain availability bits");
|
||||
rejects([&] { content::load_preferences(root / "test.obsettings", "layout", 180); },
|
||||
"preferences kinds cannot be confused");
|
||||
launch::ModLibrary library(root);
|
||||
check(library.list().empty(), "first launch has no implicit installation");
|
||||
for (const char *name : {"../escape", "CON", "lpt1.txt", "trailing.", "bad/name", ""})
|
||||
rejects([&] { launch::ModLibrary::validate_name(name); }, "portable mod name validation");
|
||||
fs::create_directories(root / "mods/BMH-classic");
|
||||
auto entries = library.list();
|
||||
check(entries.size() == 1 && !entries[0].error.empty(), "damaged mods remain visible with error");
|
||||
rejects([&] { library.rename(entries[0], "bmh-CLASSIC"); }, "case-insensitive duplicate name rejected");
|
||||
library.rename(entries[0], "Renamed");
|
||||
entries = library.list();
|
||||
check(entries[0].name == "Renamed", "rename changes directory name");
|
||||
entries[0].content_id = std::string(64, 'a');
|
||||
const auto personal = library.user_directory(entries[0]);
|
||||
content::write_atomic(personal / "keep.obs", "saved", false);
|
||||
library.remove(entries[0]);
|
||||
check(library.list().empty() && fs::exists(personal / "keep.obs"), "delete retains personal saves");
|
||||
std::cout << "native content, checkpoints and portable mod lifecycle passed\n";
|
||||
return 0;
|
||||
} catch (const std::exception &e) {
|
||||
std::cerr << e.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "app/career_session.hpp"
|
||||
#include "content/save.hpp"
|
||||
#include "launch/mods.hpp"
|
||||
#include "launch/game_data.hpp"
|
||||
#include "ui/setup.hpp"
|
||||
#include "ui/sportschau.hpp"
|
||||
#include "game/save.hpp"
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
using namespace bmh;
|
||||
namespace fs = std::filesystem;
|
||||
void check(bool value, const std::string &text) {
|
||||
if (!value)
|
||||
throw std::runtime_error(text);
|
||||
}
|
||||
int main(int argc, char **argv) try {
|
||||
if (argc < 2)
|
||||
return 77;
|
||||
const auto root = fs::temp_directory_path() /
|
||||
("openbmh-native-career-" +
|
||||
std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
|
||||
fs::create_directories(root);
|
||||
struct Cleanup {
|
||||
fs::path p;
|
||||
~Cleanup() {
|
||||
std::error_code ec;
|
||||
fs::remove_all(p, ec);
|
||||
}
|
||||
} cleanup{root};
|
||||
launch::ModLibrary library(root);
|
||||
launch::AddMod request;
|
||||
request.source = argv[1];
|
||||
request.name = "Test Classic";
|
||||
request.migrate = false;
|
||||
const auto result = library.add(request, {});
|
||||
const auto package = result.mod.directory / "content.obw";
|
||||
auto content = content::open(package);
|
||||
content::Mount mount(package, content);
|
||||
// Exercise renderers through aliases while the mod contains only content.obw.
|
||||
check(ui::SetupScreen(mount.root()).render().pixels.size() == 320 * 240, "OBW-only setup renderer");
|
||||
(void)ui::SportschauIntro(mount.root()).render_frame(0);
|
||||
const auto resolved = launch::resolve_game(request.source, root / "legacy-test-cache");
|
||||
check(resolved.error.empty(), resolved.error);
|
||||
app::CareerSession old(resolved.check.directory, 12345);
|
||||
app::CareerSession session(mount.root(), 12345);
|
||||
check(save_stream(old.state()) == save_stream(session.state()) &&
|
||||
old.rand().seed() == session.rand().seed() && old.game().seed() == session.game().seed(),
|
||||
"OBW bootstrap matches legacy state and RNG");
|
||||
ui::SetupOptions options;
|
||||
options.managers = 1;
|
||||
ui::ManagerChoice manager;
|
||||
manager.slot = 0;
|
||||
manager.master_club = 0;
|
||||
manager.start_league = 0;
|
||||
manager.strength = 1;
|
||||
manager.portrait = 0;
|
||||
manager.name = "Native QA";
|
||||
std::string error;
|
||||
check(session.confirm_manager(options, manager, error), error);
|
||||
const auto personal = library.user_directory(result.mod);
|
||||
session.configure_autosave_directory(personal);
|
||||
session.state().memory.set8(layout::Desk_EnterDesk_RuntimeField, 1);
|
||||
ui::CareerInitializationResult initial;
|
||||
check(session.finish(initial, error), error);
|
||||
const auto before = cli::dump_json(encode_native_state(session.state()));
|
||||
const auto random = session.rand();
|
||||
const auto game = session.game();
|
||||
const auto save = library.user_directory(result.mod) / "QA.obs";
|
||||
check(session.save_game(save, 0, false, error), error);
|
||||
check(session.rand().seed() == random.seed() && session.rand().calls() == random.calls() &&
|
||||
session.game().seed() == game.seed() && session.game().calls() == game.calls(),
|
||||
"native saving is RNG-neutral");
|
||||
app::CareerSession loaded(mount.root(), 999, save);
|
||||
check(cli::dump_json(encode_native_state(loaded.state())) == before, "native career state round-trip");
|
||||
check(loaded.rand().seed() == random.seed() && loaded.rand().calls() == random.calls() &&
|
||||
loaded.game().seed() == game.seed() && loaded.game().calls() == game.calls(),
|
||||
"both RNG states and counters restored");
|
||||
check(cli::dump_json(content::driver_checkpoint(session.manager_join_checkpoint().driver)) ==
|
||||
cli::dump_json(content::driver_checkpoint(loaded.manager_join_checkpoint().driver)),
|
||||
"native turn cursor round-trip");
|
||||
session.state().memory.set8(layout::Desk_EnterDesk_RuntimeField, 1);
|
||||
loaded.state().memory.set8(layout::Desk_EnterDesk_RuntimeField, 1);
|
||||
session.state().autosave_month = 0;
|
||||
loaded.state().autosave_month = 0;
|
||||
uint64_t first_revision = 1, second_revision = 1;
|
||||
for (int step = 0; step < 8; ++step) {
|
||||
const auto first_desk = session.desktop_projection(first_revision),
|
||||
second_desk = loaded.desktop_projection(second_revision);
|
||||
ui::DeskRequest first_request;
|
||||
first_request.kind = ui::DeskRequestKind::advance_turn;
|
||||
first_request.manager_slot = first_desk.manager_slot;
|
||||
first_request.revision = first_revision;
|
||||
auto second_request = first_request;
|
||||
second_request.manager_slot = second_desk.manager_slot;
|
||||
second_request.revision = second_revision;
|
||||
std::string first_error, second_error;
|
||||
const auto first = session.dispatch_kickoff(first_request, first_revision, first_error);
|
||||
const auto second = loaded.dispatch_kickoff(second_request, second_revision, second_error);
|
||||
check(first.kind == second.kind && first_error == second_error,
|
||||
"native continuation has identical outcome");
|
||||
check(cli::dump_json(encode_native_state(session.state())) ==
|
||||
cli::dump_json(encode_native_state(loaded.state())),
|
||||
"native continuation preserves every game-state field");
|
||||
check(session.rand().seed() == loaded.rand().seed() &&
|
||||
session.rand().calls() == loaded.rand().calls() &&
|
||||
session.game().seed() == loaded.game().seed() &&
|
||||
session.game().calls() == loaded.game().calls(),
|
||||
"native continuation preserves both random streams");
|
||||
if (first.kind == TurnDeskKind::Failed || first.kind == TurnDeskKind::WaitingAtDesk)
|
||||
break;
|
||||
if (step == 0) {
|
||||
const auto autosave_error = session.take_autosave_error();
|
||||
check(fs::exists(personal / "AUTOSAVE.obs"), "native autosave at stable desk: " + autosave_error);
|
||||
app::CareerSession autosaved(mount.root(), 0, personal / "AUTOSAVE.obs");
|
||||
check(cli::dump_json(encode_native_state(autosaved.state())) ==
|
||||
cli::dump_json(encode_native_state(session.state())),
|
||||
"autosave matches completed desk, including runtime flags");
|
||||
}
|
||||
check(session.save_game(save, first.manager_slot, true, error), error);
|
||||
auto fresh = std::make_unique<app::CareerSession>(mount.root(), 0, save);
|
||||
check(cli::dump_json(content::driver_checkpoint(session.manager_join_checkpoint().driver)) ==
|
||||
cli::dump_json(content::driver_checkpoint(fresh->manager_join_checkpoint().driver)),
|
||||
"prepared match groups and previous results survive saving");
|
||||
}
|
||||
// Original save migration must not require the original installation afterwards.
|
||||
auto old_save = make_savegame(session.state(), session.rand());
|
||||
write_savegame(root / "legacy.FBM", old_save);
|
||||
app::CareerSession migrated(mount.root(), 4321, root / "legacy.FBM", true);
|
||||
check(migrated.save_game(root / "migrated.obs", 0, false, error), error);
|
||||
app::CareerSession continued(mount.root(), 1, root / "migrated.obs");
|
||||
check(continued.state().players.size() == session.state().players.size(),
|
||||
"legacy save migrates to native continuation");
|
||||
if (argc > 2) {
|
||||
app::CareerSession original(mount.root(), 0x12345678, argv[2], true);
|
||||
check(original.save_game(root / "original-import.obs",
|
||||
original.state().memory.u8(layout::ActiveManager), false, error),
|
||||
error);
|
||||
app::CareerSession resumed(mount.root(), 0, root / "original-import.obs");
|
||||
check(cli::dump_json(encode_native_state(original.state())) ==
|
||||
cli::dump_json(encode_native_state(resumed.state())),
|
||||
"original edition save migration round-trip");
|
||||
}
|
||||
auto changed = content->documents;
|
||||
changed["assets/classic/images/kb/29.pixels"][0] ^= 1;
|
||||
bool rejected = false;
|
||||
try {
|
||||
content::verify(changed);
|
||||
} catch (const std::exception &) {
|
||||
rejected = true;
|
||||
}
|
||||
check(rejected, "modified Classic assets rejected");
|
||||
std::cout << "OBW-only GUI/bootstrap, career/RNG round-trip and migration passed\n";
|
||||
return 0;
|
||||
} catch (const std::exception &e) {
|
||||
std::cerr << e.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "import/obw.hpp"
|
||||
#include "import/classic.hpp"
|
||||
#include "content/package.hpp"
|
||||
#include "import/assets.hpp"
|
||||
#include "formats/executable_layout.hpp"
|
||||
#include "launch/archive.hpp"
|
||||
@@ -283,6 +284,23 @@ int main() {
|
||||
const auto classic_zip = root / "classic.obw";
|
||||
obw::write(classic, classic_zip, false);
|
||||
check(obw::read(classic_zip) == classic, "binary Classic ZIP round trip");
|
||||
auto sealed=classic;
|
||||
const auto identity=content::seal(sealed);
|
||||
const auto runtime_zip=root/"runtime.obw";
|
||||
content::write_archive(sealed,runtime_zip);
|
||||
const auto runtime=content::open(runtime_zip);
|
||||
check(runtime->content_id==identity&&runtime->database.squad_list==db.squad_list,
|
||||
"sealed native runtime reconstructs typed database without the source codec");
|
||||
auto changed_title=sealed;
|
||||
auto changed_manifest=cli::parse_json(changed_title.at("manifest.json"));
|
||||
(*changed_manifest.object())["generator"]="new importer version";
|
||||
(*changed_manifest.object())["title"]=J::Object{{"default","Renamed title"}};
|
||||
changed_title["manifest.json"]=cli::dump_json(changed_manifest)+"\n";
|
||||
obw::refresh_classic_inventory(changed_title);
|
||||
check(content::seal(changed_title)==identity,"reimport identity ignores presentation title and generator version");
|
||||
auto edited=sealed;edited.at("x-classic/desktop-seed.bin")[0]^=1;
|
||||
obw::refresh_classic_inventory(edited);
|
||||
rejects([&]{content::verify(edited);},"refreshing old CRC inventory cannot bypass the Classic seal");
|
||||
auto damaged = classic;
|
||||
damaged.at("x-classic/desktop-seed.bin")[0] ^= 1;
|
||||
rejects([&] { obw::validate(damaged); }, "inventory catches binary corruption");
|
||||
|
||||
@@ -22,7 +22,7 @@ class PackageAllowlistTests(unittest.TestCase):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
# Empty authored placeholders test names/structure, not executable behavior.
|
||||
for name in ['openbmh_play', 'openbmh_cli', 'openbmh_import', 'README.md', 'LICENSE',
|
||||
for name in ['OpenBMH', 'openbmh_cli', 'openbmh_import', 'README.md', 'LICENSE',
|
||||
'THIRD_PARTY_NOTICES.md', 'ACKNOWLEDGEMENTS.md', 'CONTRIBUTING.md']:
|
||||
(root / name).write_text('synthetic')
|
||||
notes = root / 'docs/release/0.1/RELEASE_NOTES.md'
|
||||
|
||||
@@ -10,7 +10,7 @@ import zipfile
|
||||
|
||||
|
||||
def validate(directory, windows):
|
||||
products = {name + ('.exe' if windows else '') for name in ('openbmh_play', 'openbmh_cli', 'openbmh_import')}
|
||||
products = {name + ('.exe' if windows else '') for name in ('OpenBMH', 'openbmh_cli', 'openbmh_import')}
|
||||
documents = {'README.md', 'LICENSE', 'THIRD_PARTY_NOTICES.md', 'ACKNOWLEDGEMENTS.md', 'CONTRIBUTING.md'}
|
||||
licenses = {'README.md', 'LGPL-2.1.txt', 'Nuked-OPL3-notices.txt', 'LZMA-SDK.txt', 'SDL2-HIDAPI-BSD.txt',
|
||||
'SDL2-HIDAPI-options.txt', 'SDL2-HIDAPI-original.txt', 'SDL2-yuv2rgb.txt',
|
||||
|
||||
Reference in new issue
Block a user